Annotation of loncom/lond, revision 1.578

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.578   ! raeburn     5: # $Id: lond,v 1.577 2023/05/22 21:10:56 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.578   ! raeburn    68: my $VERSION='$Revision: 1.577 $'; #' stupid emacs
1.121     albertel   69: my $remoteVERSION;
1.214     foxr       70: my $currenthostid="default";
1.115     albertel   71: my $currentdomainid;
1.134     albertel   72: 
                     73: my $client;
1.200     matthew    74: my $clientip;			# IP address of client.
                     75: my $clientname;			# LonCAPA name of client.
1.448     raeburn    76: my $clientversion;              # LonCAPA version running on client.
                     77: my $clienthomedom;              # LonCAPA domain of homeID for client. 
1.525     raeburn    78: my $clientintdom;               # LonCAPA "internet domain" for client.
1.532     raeburn    79: my $clientsamedom;              # LonCAPA domain same for this host 
                     80:                                 # and client.
1.525     raeburn    81: my $clientsameinst;             # LonCAPA "internet domain" same for 
                     82:                                 # this host and client.
1.556     raeburn    83: my $clientremoteok;             # Current domain permits hosting on client
                     84:                                 # (not set if host and client share "internet domain").
                     85:                                 # Values are 0 or 1; 1 if allowed.
                     86: my %clientprohibited;           # Commands from client prohibited for domain's
                     87:                                 # users.
                     88: 
1.134     albertel   89: my $server;
1.200     matthew    90: 
                     91: my $keymode;
1.198     foxr       92: 
1.207     foxr       93: my $cipher;			# Cipher key negotiated with client
                     94: my $tmpsnum = 0;		# Id of tmpputs.
                     95: 
1.178     foxr       96: # 
                     97: #   Connection type is:
                     98: #      client                   - All client actions are allowed
                     99: #      manager                  - only management functions allowed.
                    100: #      both                     - Both management and client actions are allowed
                    101: #
1.161     foxr      102: 
1.178     foxr      103: my $ConnectionType;
1.161     foxr      104: 
1.178     foxr      105: my %managers;			# Ip -> manager names
1.161     foxr      106: 
1.178     foxr      107: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel  108: 
1.532     raeburn   109: my %secureconf;                 # Will have requirements for security 
                    110:                                 # of lond connections
                    111: 
1.545     raeburn   112: my %crlchecked;                 # Will contain clients for which the client's SSL
                    113:                                 # has been checked against the cluster's Certificate
                    114:                                 # Revocation List.
                    115: 
1.480     raeburn   116: my $dist;
                    117: 
1.178     foxr      118: #
1.207     foxr      119: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                    120: #    Each element of the hash contains a reference to an array that contains:
                    121: #          A reference to a sub that executes the request corresponding to the keyword.
                    122: #          A flag that is true if the request must be encoded to be acceptable.
                    123: #          A mask with bits as follows:
                    124: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    125: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    126: #
                    127: my $CLIENT_OK  = 1;
                    128: my $MANAGER_OK = 2;
                    129: my %Dispatcher;
                    130: 
                    131: 
                    132: #
1.178     foxr      133: #  The array below are password error strings."
                    134: #
                    135: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    136: my @passwderrors = ("ok",
1.287     foxr      137: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
                    138: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
                    139: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
                    140: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
                    141: 		   "pwchange_failure - lcpasswd User does not exist.",
                    142: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
                    143: 		   "pwchange_failure - lcpasswd Unable to su to root.",
                    144: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
                    145: 		   "pwchange_failure - lcpasswd Username has invalid characters",
                    146: 		   "pwchange_failure - lcpasswd Invalid characters in password",
                    147: 		   "pwchange_failure - lcpasswd User already exists", 
                    148:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
                    149: 		   "pwchange_failure - lcpasswd Password mismatch",
                    150: 		   "pwchange_failure - lcpasswd Error filename is invalid");
1.97      foxr      151: 
                    152: 
1.412     foxr      153: # This array are the errors from lcinstallfile:
                    154: 
                    155: my @installerrors = ("ok",
                    156: 		     "Initial user id of client not that of www",
                    157: 		     "Usage error, not enough command line arguments",
1.500     bisitz    158: 		     "Source filename does not exist",
                    159: 		     "Destination filename does not exist",
1.412     foxr      160: 		     "Some file operation failed",
                    161: 		     "Invalid table filename."
                    162: 		     );
1.207     foxr      163: 
                    164: #
1.525     raeburn   165: # The %trust hash classifies commands according to type of trust 
                    166: # required for execution of the command.
                    167: #
                    168: # When clients from a different institution request execution of a
                    169: # particular command, the trust settings for that institution set
                    170: # for this domain (or default domain for a multi-domain server) will
                    171: # be checked to see if running the command is allowed.
                    172: #
                    173: # Trust types which depend on the "Trust" domain configuration
                    174: # for the machine's default domain are:
                    175: #
                    176: # content   ("Access to this domain's content by others")
                    177: # shared    ("Access to other domain's content by this domain")
                    178: # enroll    ("Enrollment in this domain's courses by others")
                    179: # coaurem   ("Co-author roles for this domain's users elsewhere")
1.552     raeburn   180: # othcoau   ("Co-author roles in this domain for others")
1.525     raeburn   181: # domroles  ("Domain roles in this domain assignable to others")
                    182: # catalog   ("Course Catalog for this domain displayed elsewhere")
                    183: # reqcrs    ("Requests for creation of courses in this domain by others")
                    184: # msg       ("Users in other domains can send messages to this domain")
                    185: # 
                    186: # Trust type which depends on the User Session Hosting (remote) 
                    187: # domain configuration for machine's default domain is: "remote".
                    188: #
                    189: # Trust types which depend on contents of manager.tab in 
                    190: # /home/httpd/lonTabs is: "manageronly".
                    191: # 
                    192: # Trust type which requires client to share the same LON-CAPA
                    193: # "internet domain" (i.e., same institution as this server) is:
                    194: # "institutiononly".
                    195: #
                    196: 
                    197: my %trust = (
                    198:                auth => {remote => 1},
                    199:                autocreatepassword => {remote => 1},
                    200:                autocrsreqchecks => {remote => 1, reqcrs => 1},
                    201:                autocrsrequpdate => {remote => 1},
                    202:                autocrsreqvalidation => {remote => 1},
                    203:                autogetsections => {remote => 1},
                    204:                autoinstcodedefaults => {remote => 1, catalog => 1},
                    205:                autoinstcodeformat => {remote => 1, catalog => 1},
                    206:                autonewcourse => {remote => 1, reqcrs => 1},
                    207:                autophotocheck => {remote => 1, enroll => 1},
                    208:                autophotochoice => {remote => 1},
                    209:                autophotopermission => {remote => 1, enroll => 1},
                    210:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
                    211:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
                    212:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
                    213:                autovalidateclass_sec => {catalog => 1},
                    214:                autovalidatecourse => {remote => 1, enroll => 1},
                    215:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
1.566     raeburn   216:                autovalidateinstcrosslist => {remote => 1, enroll => 1},
1.567     raeburn   217:                autoinstsecreformat => {remote => 1, enroll => 1},
1.525     raeburn   218:                changeuserauth => {remote => 1, domroles => 1},
                    219:                chatretr => {remote => 1, enroll => 1},
                    220:                chatsend => {remote => 1, enroll => 1},
                    221:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
                    222:                courseidput => {remote => 1, domroles => 1, enroll => 1},
                    223:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
                    224:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
1.561     raeburn   225:                coursesessions => {institutiononly => 1},
1.525     raeburn   226:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    227:                currentdump => {remote => 1, enroll => 1},
                    228:                currentversion => {remote=> 1, content => 1},
                    229:                dcmaildump => {remote => 1, domroles => 1},
                    230:                dcmailput => {remote => 1, domroles => 1},
                    231:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
1.551     raeburn   232:                delbalcookie => {institutiononly => 1},
1.560     raeburn   233:                delusersession => {institutiononly => 1},
1.525     raeburn   234:                deldom => {remote => 1, domroles => 1}, # not currently used
                    235:                devalidatecache => {institutiononly => 1},
                    236:                domroleput => {remote => 1, enroll => 1},
                    237:                domrolesdump => {remote => 1, catalog => 1},
                    238:                du => {remote => 1, enroll => 1},
                    239:                du2 => {remote => 1, enroll => 1},
                    240:                dump => {remote => 1, enroll => 1, domroles => 1},
                    241:                edit => {institutiononly => 1},  #not used currently
1.568     raeburn   242:                edump => {remote => 1, enroll => 1, domroles => 1},
1.525     raeburn   243:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536     raeburn   244:                egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.553     raeburn   245:                ekey => {anywhere => 1},
1.525     raeburn   246:                exit => {anywhere => 1},
                    247:                fetchuserfile => {remote => 1, enroll => 1},
                    248:                get => {remote => 1, domroles => 1, enroll => 1},
                    249:                getdom => {anywhere => 1},
                    250:                home => {anywhere => 1},
                    251:                iddel => {remote => 1, enroll => 1},
                    252:                idget => {remote => 1, enroll => 1},
                    253:                idput => {remote => 1, domroles => 1, enroll => 1},
                    254:                inc => {remote => 1, enroll => 1},
                    255:                init => {anywhere => 1},
                    256:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    257:                instemailrules => {remote => 1, domroles => 1},
                    258:                instidrulecheck => {remote => 1, domroles => 1,},
                    259:                instidrules => {remote => 1, domroles => 1,},
                    260:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    261:                instselfcreatecheck => {institutiononly => 1},
1.575     raeburn   262:                instunamemapcheck => {remote => 1,},  
1.525     raeburn   263:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    264:                keys => {remote => 1,},
                    265:                load => {anywhere => 1},
                    266:                log => {anywhere => 1},
                    267:                ls => {remote => 1, enroll => 1, content => 1,},
                    268:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    269:                ls3 => {remote => 1, enroll => 1, content => 1,},
1.572     raeburn   270:                lti => {institutiononly => 1},
1.525     raeburn   271:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    272:                mkdiruserfile => {remote => 1, enroll => 1,},
                    273:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    274:                passwd => {remote => 1},
                    275:                ping => {anywhere => 1},
                    276:                pong => {anywhere => 1},
                    277:                pushfile => {manageronly => 1},
                    278:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    279:                putdom => {remote => 1, domroles => 1,},
                    280:                putstore => {remote => 1, enroll => 1},
                    281:                queryreply => {anywhere => 1},
                    282:                querysend => {anywhere => 1},
1.535     raeburn   283:                querysend_activitylog => {remote => 1},
                    284:                querysend_allusers => {remote => 1, domroles => 1},
                    285:                querysend_courselog => {remote => 1},
                    286:                querysend_fetchenrollment => {remote => 1},
                    287:                querysend_getinstuser => {remote => 1},
                    288:                querysend_getmultinstusers => {remote => 1},
                    289:                querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
                    290:                querysend_institutionalphotos => {remote => 1},
                    291:                querysend_portfolio_metadata => {remote => 1, content => 1},
                    292:                querysend_userlog => {remote => 1, domroles => 1},
                    293:                querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525     raeburn   294:                quit => {anywhere => 1},
                    295:                readlonnetglobal => {institutiononly => 1},
                    296:                reinit => {manageronly => 1}, #not used currently
                    297:                removeuserfile => {remote => 1, enroll => 1},
                    298:                renameuserfile => {remote => 1,},
                    299:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    300:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    301:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527     raeburn   302:                servercerts => {institutiononly => 1},
1.528     raeburn   303:                serverdistarch => {anywhere => 1},
1.525     raeburn   304:                serverhomeID => {anywhere => 1},
                    305:                serverloncaparev => {anywhere => 1},
                    306:                servertimezone => {remote => 1, enroll => 1},
                    307:                setannounce => {remote => 1, domroles => 1},
                    308:                sethost => {anywhere => 1},
1.577     raeburn   309:                signlti => {remote => 1},
1.525     raeburn   310:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    311:                studentphoto => {remote => 1, enroll => 1},
                    312:                sub => {content => 1,},
1.552     raeburn   313:                tmpdel => {institutiononly => 1},
                    314:                tmpget => {institutiononly => 1},
                    315:                tmpput => {remote => 1, othcoau => 1},
1.525     raeburn   316:                tokenauthuserfile => {anywhere => 1},
1.575     raeburn   317:                unamemaprules => {remote => 1,},
1.525     raeburn   318:                unsub => {content => 1,},
                    319:                update => {shared => 1},
1.564     raeburn   320:                updatebalcookie => {institutiononly => 1},
1.525     raeburn   321:                updateclickers => {remote => 1},
                    322:                userhassession => {anywhere => 1},
                    323:                userload => {anywhere => 1},
                    324:                version => {anywhere => 1}, #not used
                    325:             );
                    326: 
                    327: #
1.207     foxr      328: #   Statistics that are maintained and dislayed in the status line.
                    329: #
1.212     foxr      330: my $Transactions = 0;		# Number of attempted transactions.
                    331: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      332: 
                    333: #   ResetStatistics: 
                    334: #      Resets the statistics counters:
                    335: #
                    336: sub ResetStatistics {
                    337:     $Transactions = 0;
                    338:     $Failures     = 0;
                    339: }
                    340: 
1.200     matthew   341: #------------------------------------------------------------------------
                    342: #
                    343: #   LocalConnection
                    344: #     Completes the formation of a locally authenticated connection.
                    345: #     This function will ensure that the 'remote' client is really the
                    346: #     local host.  If not, the connection is closed, and the function fails.
                    347: #     If so, initcmd is parsed for the name of a file containing the
                    348: #     IDEA session key.  The fie is opened, read, deleted and the session
                    349: #     key returned to the caller.
                    350: #
                    351: # Parameters:
                    352: #   $Socket      - Socket open on client.
                    353: #   $initcmd     - The full text of the init command.
                    354: #
                    355: # Returns:
                    356: #     IDEA session key on success.
                    357: #     undef on failure.
                    358: #
                    359: sub LocalConnection {
                    360:     my ($Socket, $initcmd) = @_;
1.373     albertel  361:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  362:     if($clientip ne "127.0.0.1") {
1.200     matthew   363: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  364: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   365: 	close $Socket;
                    366: 	return undef;
1.224     foxr      367:     }  else {
1.200     matthew   368: 	chomp($initcmd);	# Get rid of \n in filename.
                    369: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    370: 	Debug(" Init command: $init $type $name ");
                    371: 
                    372: 	# Require that $init = init, and $type = local:  Otherwise
                    373: 	# the caller is insane:
                    374: 
                    375: 	if(($init ne "init") && ($type ne "local")) {
                    376: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    377: 		     ."init = $init, and type = $type </font>");
                    378: 	    close($Socket);;
                    379: 	    return undef;
                    380: 		
                    381: 	}
                    382: 	#  Now get the key filename:
                    383: 
                    384: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    385: 	return $IDEAKey;
                    386:     }
                    387: }
                    388: #------------------------------------------------------------------------------
                    389: #
                    390: #  SSLConnection
                    391: #   Completes the formation of an ssh authenticated connection. The
                    392: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    393: #   certificate exchange are successful, the IDEA key is generated and sent
                    394: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    395: #   the caller after the SSL tunnel is torn down.
                    396: #
                    397: # Parameters:
                    398: #   Name              Type             Purpose
                    399: #   $Socket          IO::Socket::INET  Plaintext socket.
                    400: #
                    401: # Returns:
                    402: #    IDEA key on success.
                    403: #    undef on failure.
                    404: #
                    405: sub SSLConnection {
                    406:     my $Socket   = shift;
                    407: 
                    408:     Debug("SSLConnection: ");
                    409:     my $KeyFile         = lonssl::KeyFile();
                    410:     if(!$KeyFile) {
                    411: 	my $err = lonssl::LastError();
                    412: 	&logthis("<font color=\"red\"> CRITICAL"
                    413: 		 ."Can't get key file $err </font>");
                    414: 	return undef;
                    415:     }
                    416:     my ($CACertificate,
                    417: 	$Certificate) = lonssl::CertificateFile();
                    418: 
                    419: 
                    420:     # If any of the key, certificate or certificate authority 
                    421:     # certificate filenames are not defined, this can't work.
                    422: 
                    423:     if((!$Certificate) || (!$CACertificate)) {
                    424: 	my $err = lonssl::LastError();
                    425: 	&logthis("<font color=\"red\"> CRITICAL"
                    426: 		 ."Can't get certificates: $err </font>");
                    427: 
                    428: 	return undef;
                    429:     }
                    430:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    431: 
                    432:     # Indicate to our peer that we can procede with
                    433:     # a transition to ssl authentication:
                    434: 
                    435:     print $Socket "ok:ssl\n";
                    436: 
                    437:     Debug("Approving promotion -> ssl");
                    438:     #  And do so:
                    439: 
1.545     raeburn   440:     my $CRLFile;
                    441:     unless ($crlchecked{$clientname}) {
                    442:         $CRLFile = lonssl::CRLFile();
                    443:         $crlchecked{$clientname} = 1;
                    444:     }
                    445: 
1.200     matthew   446:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    447: 						$CACertificate,
                    448: 						$Certificate,
1.544     raeburn   449: 						$KeyFile,
1.545     raeburn   450: 						$clientname,
1.546     raeburn   451:                                                 $CRLFile,
                    452:                                                 $clientversion);
1.200     matthew   453:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    454: 	my $err = lonssl::LastError();
                    455: 	&logthis("<font color=\"red\"> CRITICAL "
                    456: 		 ."SSL Socket promotion failed: $err </font>");
                    457: 	return undef;
                    458:     }
                    459:     Debug("SSL Promotion successful");
                    460: 
                    461:     # 
                    462:     #  The only thing we'll use the socket for is to send the IDEA key
                    463:     #  to the peer:
                    464: 
                    465:     my $Key = lonlocal::CreateCipherKey();
                    466:     print $SSLSocket "$Key\n";
                    467: 
                    468:     lonssl::Close($SSLSocket); 
                    469: 
                    470:     Debug("Key exchange complete: $Key");
                    471: 
                    472:     return $Key;
                    473: }
                    474: #
                    475: #     InsecureConnection: 
                    476: #        If insecure connections are allowd,
                    477: #        exchange a challenge with the client to 'validate' the
                    478: #        client (not really, but that's the protocol):
                    479: #        We produce a challenge string that's sent to the client.
                    480: #        The client must then echo the challenge verbatim to us.
                    481: #
                    482: #  Parameter:
                    483: #      Socket      - Socket open on the client.
                    484: #  Returns:
                    485: #      1           - success.
                    486: #      0           - failure (e.g.mismatch or insecure not allowed).
                    487: #
                    488: sub InsecureConnection {
                    489:     my $Socket  =  shift;
                    490: 
                    491:     #   Don't even start if insecure connections are not allowed.
1.532     raeburn   492:     #   return 0 if Insecure connections not allowed.
                    493:     #
                    494:     if (ref($secureconf{'connfrom'}) eq 'HASH') {
                    495:         if ($clientsamedom) {
                    496:             if ($secureconf{'connfrom'}{'dom'} eq 'req') {
                    497:                 return 0;
                    498:             } 
                    499:         } elsif ($clientsameinst) {
                    500:             if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
                    501:                 return 0;
                    502:             }
                    503:         } else {
                    504:             if ($secureconf{'connfrom'}{'other'} eq 'req') {
                    505:                 return 0;
                    506:             }
                    507:         }
                    508:     } elsif (!$perlvar{londAllowInsecure}) {
1.200     matthew   509: 	return 0;
                    510:     }
                    511: 
                    512:     #   Fabricate a challenge string and send it..
                    513: 
                    514:     my $challenge = "$$".time;	# pid + time.
                    515:     print $Socket "$challenge\n";
                    516:     &status("Waiting for challenge reply");
                    517: 
                    518:     my $answer = <$Socket>;
                    519:     $answer    =~s/\W//g;
                    520:     if($challenge eq $answer) {
                    521: 	return 1;
1.224     foxr      522:     } else {
1.200     matthew   523: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    524: 	&status("No challenge reqply");
                    525: 	return 0;
                    526:     }
                    527:     
                    528: 
                    529: }
1.251     foxr      530: #
                    531: #   Safely execute a command (as long as it's not a shel command and doesn
                    532: #   not require/rely on shell escapes.   The function operates by doing a
                    533: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    534: #
                    535: # Formal Parameters:
                    536: #     $line                    - A line of text to be executed as a command.
                    537: # Returns:
                    538: #     The output from that command.  If the output is multiline the caller
                    539: #     must know how to split up the output.
                    540: #
                    541: #
                    542: sub execute_command {
                    543:     my ($line)    = @_;
                    544:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    545:     my $output    = "";
                    546: 
                    547:     my $pid = open(CHILD, "-|");
                    548:     
                    549:     if($pid) {			# Parent process
                    550: 	Debug("In parent process for execute_command");
                    551: 	my @data = <CHILD>;	# Read the child's outupt...
                    552: 	close CHILD;
                    553: 	foreach my $output_line (@data) {
                    554: 	    Debug("Adding $output_line");
                    555: 	    $output .= $output_line; # Presumably has a \n on it.
                    556: 	}
                    557: 
                    558:     } else {			# Child process
                    559: 	close (STDERR);
                    560: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    561: 	exec(@words);		# won't return.
                    562:     }
                    563:     return $output;
                    564: }
                    565: 
1.200     matthew   566: 
1.140     foxr      567: #   GetCertificate: Given a transaction that requires a certificate,
                    568: #   this function will extract the certificate from the transaction
                    569: #   request.  Note that at this point, the only concept of a certificate
                    570: #   is the hostname to which we are connected.
                    571: #
                    572: #   Parameter:
                    573: #      request   - The request sent by our client (this parameterization may
                    574: #                  need to change when we really use a certificate granting
                    575: #                  authority.
                    576: #
                    577: sub GetCertificate {
                    578:     my $request = shift;
                    579: 
                    580:     return $clientip;
                    581: }
1.161     foxr      582: 
1.178     foxr      583: #
                    584: #   Return true if client is a manager.
                    585: #
                    586: sub isManager {
                    587:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    588: }
                    589: #
                    590: #   Return tru if client can do client functions
                    591: #
                    592: sub isClient {
                    593:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    594: }
1.161     foxr      595: 
                    596: 
1.156     foxr      597: #
                    598: #   ReadManagerTable: Reads in the current manager table. For now this is
                    599: #                     done on each manager authentication because:
                    600: #                     - These authentications are not frequent
                    601: #                     - This allows dynamic changes to the manager table
                    602: #                       without the need to signal to the lond.
                    603: #
                    604: sub ReadManagerTable {
                    605: 
1.412     foxr      606:     &Debug("Reading manager table");
1.156     foxr      607:     #   Clean out the old table first..
                    608: 
1.166     foxr      609:    foreach my $key (keys %managers) {
                    610:       delete $managers{$key};
                    611:    }
                    612: 
                    613:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    614:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   615:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    616:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   617:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    618:        }
                    619:        return;
1.166     foxr      620:    }
                    621:    while(my $host = <MANAGERS>) {
                    622:       chomp($host);
                    623:       if ($host =~ "^#") {                  # Comment line.
                    624:          next;
                    625:       }
1.368     albertel  626:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      627: 	    #  The entry is of the form:
                    628: 	    #    cluname:hostname
                    629: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    630: 	    #            the host key.
                    631: 	    #  hostname- The dns name of the host.
                    632: 	    #
1.166     foxr      633:           my($cluname, $dnsname) = split(/:/, $host);
                    634:           
                    635:           my $ip = gethostbyname($dnsname);
                    636:           if(defined($ip)) {                 # bad names don't deserve entry.
                    637:             my $hostip = inet_ntoa($ip);
                    638:             $managers{$hostip} = $cluname;
                    639:             logthis('<font color="green"> registering manager '.
                    640:                     "$dnsname as $cluname with $hostip </font>\n");
                    641:          }
                    642:       } else {
                    643:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   644:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      645:       }
                    646:    }
1.156     foxr      647: }
1.140     foxr      648: 
                    649: #
                    650: #  ValidManager: Determines if a given certificate represents a valid manager.
                    651: #                in this primitive implementation, the 'certificate' is
                    652: #                just the connecting loncapa client name.  This is checked
                    653: #                against a valid client list in the configuration.
                    654: #
                    655: #                  
                    656: sub ValidManager {
                    657:     my $certificate = shift; 
                    658: 
1.163     foxr      659:     return isManager;
1.140     foxr      660: }
                    661: #
1.143     foxr      662: #  CopyFile:  Called as part of the process of installing a 
                    663: #             new configuration file.  This function copies an existing
                    664: #             file to a backup file.
                    665: # Parameters:
                    666: #     oldfile  - Name of the file to backup.
                    667: #     newfile  - Name of the backup file.
                    668: # Return:
                    669: #     0   - Failure (errno has failure reason).
                    670: #     1   - Success.
                    671: #
                    672: sub CopyFile {
1.192     foxr      673: 
                    674:     my ($oldfile, $newfile) = @_;
1.143     foxr      675: 
1.281     matthew   676:     if (! copy($oldfile,$newfile)) {
                    677:         return 0;
1.143     foxr      678:     }
1.281     matthew   679:     chmod(0660, $newfile);
                    680:     return 1;
1.143     foxr      681: }
1.157     foxr      682: #
                    683: #  Host files are passed out with externally visible host IPs.
                    684: #  If, for example, we are behind a fire-wall or NAT host, our 
                    685: #  internally visible IP may be different than the externally
                    686: #  visible IP.  Therefore, we always adjust the contents of the
                    687: #  host file so that the entry for ME is the IP that we believe
                    688: #  we have.  At present, this is defined as the entry that
                    689: #  DNS has for us.  If by some chance we are not able to get a
                    690: #  DNS translation for us, then we assume that the host.tab file
                    691: #  is correct.  
                    692: #    BUGBUGBUG - in the future, we really should see if we can
                    693: #       easily query the interface(s) instead.
                    694: # Parameter(s):
                    695: #     contents    - The contents of the host.tab to check.
                    696: # Returns:
                    697: #     newcontents - The adjusted contents.
                    698: #
                    699: #
                    700: sub AdjustHostContents {
                    701:     my $contents  = shift;
                    702:     my $adjusted;
                    703:     my $me        = $perlvar{'lonHostID'};
                    704: 
1.354     albertel  705:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   706: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    707:              ($line =~ /^\s*\^/))) {
1.157     foxr      708: 	    chomp($line);
                    709: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    710: 	    if ($id eq $me) {
1.354     albertel  711: 		my $ip = gethostbyname($name);
                    712: 		my $ipnew = inet_ntoa($ip);
                    713: 		$ip = $ipnew;
1.157     foxr      714: 		#  Reconstruct the host line and append to adjusted:
                    715: 		
1.354     albertel  716: 		my $newline = "$id:$domain:$role:$name:$ip";
                    717: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    718: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    719: 		}
                    720: 		$adjusted .= $newline."\n";
1.157     foxr      721: 		
1.354     albertel  722: 	    } else {		# Not me, pass unmodified.
                    723: 		$adjusted .= $line."\n";
                    724: 	    }
1.157     foxr      725: 	} else {                  # Blank or comment never re-written.
                    726: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    727: 	}
1.354     albertel  728:     }
                    729:     return $adjusted;
1.157     foxr      730: }
1.143     foxr      731: #
                    732: #   InstallFile: Called to install an administrative file:
1.412     foxr      733: #       - The file is created int a temp directory called <name>.tmp
                    734: #       - lcinstall file is called to install the file.
                    735: #         since the web app has no direct write access to the table directory
1.143     foxr      736: #
                    737: #  Parameters:
                    738: #       Name of the file
                    739: #       File Contents.
                    740: #  Return:
                    741: #      nonzero - success.
                    742: #      0       - failure and $! has an errno.
1.412     foxr      743: # Assumptions:
                    744: #    File installtion is a relatively infrequent
1.143     foxr      745: #
                    746: sub InstallFile {
1.192     foxr      747: 
                    748:     my ($Filename, $Contents) = @_;
1.412     foxr      749: #     my $TempFile = $Filename.".tmp";
                    750:     my $exedir = $perlvar{'lonDaemons'};
                    751:     my $tmpdir = $exedir.'/tmp/';
                    752:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      753: 
                    754:     #  Open the file for write:
                    755: 
                    756:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    757:     if(!(defined $fh)) {
                    758: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    759: 	return 0;
                    760:     }
                    761:     #  write the contents of the file:
                    762: 
                    763:     print $fh ($Contents); 
                    764:     $fh->close;			# In case we ever have a filesystem w. locking
                    765: 
1.412     foxr      766:     chmod(0664, $TempFile);	# Everyone can write it.
                    767: 
                    768:     # Use lcinstall file to put the file in the table directory...
                    769: 
                    770:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    771:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    772:     close $pf;
                    773:     my $err = $?;
                    774:     &Debug("Status is $err");
                    775:     if ($err != 0) {
                    776: 	my $msg = $err;
                    777: 	if ($err < @installerrors) {
                    778: 	    $msg = $installerrors[$err];
                    779: 	}
                    780: 	&logthis("Install failed for table file $Filename : $msg");
                    781: 	return 0;
                    782:     }
                    783: 
                    784:     # Remove the temp file:
1.143     foxr      785: 
1.412     foxr      786:     unlink($TempFile);
1.143     foxr      787: 
                    788:     return 1;
                    789: }
1.200     matthew   790: 
                    791: 
1.169     foxr      792: #
                    793: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      794: #                 into a configuration file pathname.
1.472     raeburn   795: #                 Supports the following file selectors: 
                    796: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      797: #
1.169     foxr      798: #
                    799: #  Parameters:
                    800: #      selector  - Configuration file selector.
                    801: #  Returns:
                    802: #      Full path to the file or undef if the selector is invalid.
                    803: #
                    804: sub ConfigFileFromSelector {
                    805:     my $selector   = shift;
                    806:     my $tablefile;
                    807: 
1.549     raeburn   808:     if ($selector eq 'loncapaCAcrl') {
                    809:         my $tabledir = $perlvar{'lonCertificateDirectory'};
                    810:         if (-d $tabledir) {
                    811:             $tablefile =  $tabledir.'/'.$selector.'.pem';
                    812:         }
                    813:     } else {
                    814:         my $tabledir = $perlvar{'lonTabDir'}.'/';
                    815:         if (($selector eq "hosts") || ($selector eq "domain") || 
                    816:             ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
                    817: 	    $tablefile =  $tabledir.$selector.'.tab';
                    818:         }
1.169     foxr      819:     }
                    820:     return $tablefile;
                    821: }
1.143     foxr      822: #
1.141     foxr      823: #   PushFile:  Called to do an administrative push of a file.
                    824: #              - Ensure the file being pushed is one we support.
                    825: #              - Backup the old file to <filename.saved>
                    826: #              - Separate the contents of the new file out from the
                    827: #                rest of the request.
                    828: #              - Write the new file.
                    829: #  Parameter:
                    830: #     Request - The entire user request.  This consists of a : separated
                    831: #               string pushfile:tablename:contents.
                    832: #     NOTE:  The contents may have :'s in it as well making things a bit
                    833: #            more interesting... but not much.
                    834: #  Returns:
                    835: #     String to send to client ("ok" or "refused" if bad file).
                    836: #
                    837: sub PushFile {
1.510     raeburn   838:     my $request = shift;
1.141     foxr      839:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      840:     &Debug("PushFile");
1.141     foxr      841:     
1.549     raeburn   842:     #  At this point in time, pushes for only the following tables and
                    843:     #  CRL file are supported:
1.141     foxr      844:     #   hosts.tab  ($filename eq host).
                    845:     #   domain.tab ($filename eq domain).
1.472     raeburn   846:     #   dns_hosts.tab ($filename eq dns_host).
1.554     raeburn   847:     #   dns_domain.tab ($filename eq dns_domain).
                    848:     #   loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141     foxr      849:     # Construct the destination filename or reject the request.
                    850:     #
                    851:     # lonManage is supposed to ensure this, however this session could be
                    852:     # part of some elaborate spoof that managed somehow to authenticate.
                    853:     #
                    854: 
1.169     foxr      855: 
                    856:     my $tablefile = ConfigFileFromSelector($filename);
                    857:     if(! (defined $tablefile)) {
1.141     foxr      858: 	return "refused";
                    859:     }
1.412     foxr      860: 
1.157     foxr      861:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    862:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    863:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    864:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    865:     #  that possibilty.
                    866: 
                    867:     if($filename eq "host") {
                    868: 	$contents = AdjustHostContents($contents);
1.576     raeburn   869:     } elsif (($filename eq 'dns_hosts') || ($filename eq 'dns_domain') ||
1.549     raeburn   870:              ($filename eq 'loncapaCAcrl')) {
1.510     raeburn   871:         if ($contents eq '') {
                    872:             &logthis('<font color="red"> Pushfile: unable to install '
                    873:                     .$tablefile." - no data received from push. </font>");
                    874:             return 'error: push had no data';
                    875:         }
                    876:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    877:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    878:             if ($managers{$clientip} eq $clientname) {
                    879:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    880:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549     raeburn   881:                 my $url;
                    882:                 if ($filename eq 'loncapaCAcrl') {
                    883:                     $url = '/adm/dns/loncapaCRL';
                    884:                 } else {
                    885:                     $url = '/adm/'.$filename;
                    886:                     $url =~ s{_}{/};
                    887:                 }
1.510     raeburn   888:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   889:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   890:                 if ($response->is_error()) {
                    891:                     &logthis('<font color="red"> Pushfile: unable to install '
                    892:                             .$tablefile." - error attempting to pull data. </font>");
                    893:                     return 'error: pull failed';
                    894:                 } else {
                    895:                     my $result = $response->content;
                    896:                     chomp($result);
                    897:                     unless ($result eq $contents) {
                    898:                         &logthis('<font color="red"> Pushfile: unable to install '
                    899:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    900:                         my $pushleng = length($contents);
                    901:                         my $pullleng = length($result);
                    902:                         if ($pushleng != $pullleng) {
                    903:                             return "error: $pushleng vs $pullleng bytes";
                    904:                         } else {
                    905:                             return "error: mismatch push and pull";
                    906:                         }
                    907:                     }
                    908:                 }
                    909:             }
                    910:         }
1.157     foxr      911:     }
                    912: 
1.141     foxr      913:     #  Install the new file:
                    914: 
1.412     foxr      915:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      916:     if(!InstallFile($tablefile, $contents)) {
                    917: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      918: 	 .$tablefile." $! </font>");
1.143     foxr      919: 	return "error:$!";
1.224     foxr      920:     } else {
1.143     foxr      921: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   922: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   923:         my $adminmail = $perlvar{'lonAdmEMail'};
                    924:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    925:         if ($admindom ne '') {
                    926:             my %domconfig =
                    927:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    928:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    929:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    930:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    931:                 }
                    932:             }
                    933:         }
                    934:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    935:             my $msg = new Mail::Send;
                    936:             $msg->to($adminmail);
                    937:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    938:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    939:             if (my $fh = $msg->open()) {
                    940:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   941:                           "$clientname ($clientip)\n";
1.472     raeburn   942:                 $fh->close;
                    943:             }
                    944:         }
1.143     foxr      945:     }
                    946: 
1.141     foxr      947:     #  Indicate success:
                    948:  
                    949:     return "ok";
                    950: 
                    951: }
1.145     foxr      952: 
                    953: #
                    954: #  Called to re-init either lonc or lond.
                    955: #
                    956: #  Parameters:
                    957: #    request   - The full request by the client.  This is of the form
                    958: #                reinit:<process>  
                    959: #                where <process> is allowed to be either of 
                    960: #                lonc or lond
                    961: #
                    962: #  Returns:
                    963: #     The string to be sent back to the client either:
                    964: #   ok         - Everything worked just fine.
                    965: #   error:why  - There was a failure and why describes the reason.
                    966: #
                    967: #
                    968: sub ReinitProcess {
                    969:     my $request = shift;
                    970: 
1.146     foxr      971: 
                    972:     # separate the request (reinit) from the process identifier and
                    973:     # validate it producing the name of the .pid file for the process.
                    974:     #
                    975:     #
                    976:     my ($junk, $process) = split(":", $request);
1.147     foxr      977:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      978:     if($process eq 'lonc') {
                    979: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      980: 	if (!open(PIDFILE, "< $processpidfile")) {
                    981: 	    return "error:Open failed for $processpidfile";
                    982: 	}
                    983: 	my $loncpid = <PIDFILE>;
                    984: 	close(PIDFILE);
                    985: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    986: 		."</font>");
                    987: 	kill("USR2", $loncpid);
1.146     foxr      988:     } elsif ($process eq 'lond') {
1.147     foxr      989: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    990: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      991:     } else {
                    992: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    993: 		 ."</font>");
                    994: 	return "error:Invalid process identifier $process";
                    995:     }
1.145     foxr      996:     return 'ok';
                    997: }
1.168     foxr      998: #   Validate a line in a configuration file edit script:
                    999: #   Validation includes:
                   1000: #     - Ensuring the command is valid.
                   1001: #     - Ensuring the command has sufficient parameters
                   1002: #   Parameters:
                   1003: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr     1004: #
1.168     foxr     1005: #   Return:
                   1006: #      0     - Invalid scriptline.
                   1007: #      1     - Valid scriptline
                   1008: #  NOTE:
                   1009: #     Only the command syntax is checked, not the executability of the
                   1010: #     command.
                   1011: #
                   1012: sub isValidEditCommand {
                   1013:     my $scriptline = shift;
                   1014: 
                   1015:     #   Line elements are pipe separated:
                   1016: 
                   1017:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                   1018:     &logthis('<font color="green"> isValideditCommand checking: '.
                   1019: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                   1020:     
                   1021:     if ($command eq "delete") {
                   1022: 	#
                   1023: 	#   key with no newline.
                   1024: 	#
                   1025: 	if( ($key eq "") || ($newline ne "")) {
                   1026: 	    return 0;		# Must have key but no newline.
                   1027: 	} else {
                   1028: 	    return 1;		# Valid syntax.
                   1029: 	}
1.169     foxr     1030:     } elsif ($command eq "replace") {
1.168     foxr     1031: 	#
                   1032: 	#   key and newline:
                   1033: 	#
                   1034: 	if (($key eq "") || ($newline eq "")) {
                   1035: 	    return 0;
                   1036: 	} else {
                   1037: 	    return 1;
                   1038: 	}
1.169     foxr     1039:     } elsif ($command eq "append") {
                   1040: 	if (($key ne "") && ($newline eq "")) {
                   1041: 	    return 1;
                   1042: 	} else {
                   1043: 	    return 0;
                   1044: 	}
1.168     foxr     1045:     } else {
                   1046: 	return 0;		# Invalid command.
                   1047:     }
                   1048:     return 0;			# Should not get here!!!
                   1049: }
1.169     foxr     1050: #
                   1051: #   ApplyEdit - Applies an edit command to a line in a configuration 
                   1052: #               file.  It is the caller's responsiblity to validate the
                   1053: #               edit line.
                   1054: #   Parameters:
                   1055: #      $directive - A single edit directive to apply.  
                   1056: #                   Edit directives are of the form:
                   1057: #                  append|newline      - Appends a new line to the file.
                   1058: #                  replace|key|newline - Replaces the line with key value 'key'
                   1059: #                  delete|key          - Deletes the line with key value 'key'.
                   1060: #      $editor   - A config file editor object that contains the
                   1061: #                  file being edited.
                   1062: #
                   1063: sub ApplyEdit {
1.192     foxr     1064: 
                   1065:     my ($directive, $editor) = @_;
1.169     foxr     1066: 
                   1067:     # Break the directive down into its command and its parameters
                   1068:     # (at most two at this point.  The meaning of the parameters, if in fact
                   1069:     #  they exist depends on the command).
                   1070: 
                   1071:     my ($command, $p1, $p2) = split(/\|/, $directive);
                   1072: 
                   1073:     if($command eq "append") {
                   1074: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1075:     } elsif ($command eq "replace") {
                   1076: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1077:     } elsif ($command eq "delete") {
                   1078: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1079:     } else {			          # Should not get here!!!
                   1080: 	die "Invalid command given to ApplyEdit $command"
                   1081:     }
                   1082: }
                   1083: #
                   1084: # AdjustOurHost:
                   1085: #           Adjusts a host file stored in a configuration file editor object
                   1086: #           for the true IP address of this host. This is necessary for hosts
                   1087: #           that live behind a firewall.
                   1088: #           Those hosts have a publicly distributed IP of the firewall, but
                   1089: #           internally must use their actual IP.  We assume that a given
                   1090: #           host only has a single IP interface for now.
                   1091: # Formal Parameters:
                   1092: #     editor   - The configuration file editor to adjust.  This
                   1093: #                editor is assumed to contain a hosts.tab file.
                   1094: # Strategy:
                   1095: #    - Figure out our hostname.
                   1096: #    - Lookup the entry for this host.
                   1097: #    - Modify the line to contain our IP
                   1098: #    - Do a replace for this host.
                   1099: sub AdjustOurHost {
                   1100:     my $editor        = shift;
                   1101: 
                   1102:     # figure out who I am.
                   1103: 
                   1104:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1105: 
                   1106:     #  Get my host file entry.
                   1107: 
                   1108:     my $ConfigLine    = $editor->Find($myHostName);
                   1109:     if(! (defined $ConfigLine)) {
                   1110: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1111:     }
                   1112:     # figure out my IP:
                   1113:     #   Use the config line to get my hostname.
                   1114:     #   Use gethostbyname to translate that into an IP address.
                   1115:     #
1.338     albertel 1116:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1117:     #
                   1118:     #  Reassemble the config line from the elements in the list.
                   1119:     #  Note that if the loncnew items were not present before, they will
                   1120:     #  be now even if they would be empty
                   1121:     #
                   1122:     my $newConfigLine = $id;
1.338     albertel 1123:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1124: 	$newConfigLine .= ":".$item;
                   1125:     }
                   1126:     #  Replace the line:
                   1127: 
                   1128:     $editor->ReplaceLine($id, $newConfigLine);
                   1129:     
                   1130: }
                   1131: #
                   1132: #   ReplaceConfigFile:
                   1133: #              Replaces a configuration file with the contents of a
                   1134: #              configuration file editor object.
                   1135: #              This is done by:
                   1136: #              - Copying the target file to <filename>.old
                   1137: #              - Writing the new file to <filename>.tmp
                   1138: #              - Moving <filename.tmp>  -> <filename>
                   1139: #              This laborious process ensures that the system is never without
                   1140: #              a configuration file that's at least valid (even if the contents
                   1141: #              may be dated).
                   1142: #   Parameters:
                   1143: #        filename   - Name of the file to modify... this is a full path.
                   1144: #        editor     - Editor containing the file.
                   1145: #
                   1146: sub ReplaceConfigFile {
1.192     foxr     1147:     
                   1148:     my ($filename, $editor) = @_;
1.168     foxr     1149: 
1.169     foxr     1150:     CopyFile ($filename, $filename.".old");
                   1151: 
                   1152:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1153: 
                   1154:     InstallFile($filename, $contents);
                   1155: }
1.168     foxr     1156: #   
                   1157: #
                   1158: #   Called to edit a configuration table  file
1.167     foxr     1159: #   Parameters:
                   1160: #      request           - The entire command/request sent by lonc or lonManage
                   1161: #   Return:
                   1162: #      The reply to send to the client.
1.168     foxr     1163: #
1.167     foxr     1164: sub EditFile {
                   1165:     my $request = shift;
                   1166: 
                   1167:     #  Split the command into it's pieces:  edit:filetype:script
                   1168: 
1.339     albertel 1169:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1170: 
                   1171:     #  Check the pre-coditions for success:
                   1172: 
1.339     albertel 1173:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1174: 	return "error:edit request detected, but request != 'edit'\n";
                   1175:     }
                   1176:     if( ($filetype ne "hosts")  &&
                   1177: 	($filetype ne "domain")) {
                   1178: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1179:     }
                   1180: 
                   1181:     #   Split the edit script and check it's validity.
1.168     foxr     1182: 
                   1183:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1184:     my $linecount   = scalar(@scriptlines);
                   1185:     for(my $i = 0; $i < $linecount; $i++) {
                   1186: 	chomp($scriptlines[$i]);
                   1187: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1188: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1189: 	}
                   1190:     }
1.145     foxr     1191: 
1.167     foxr     1192:     #   Execute the edit operation.
1.169     foxr     1193:     #   - Create a config file editor for the appropriate file and 
                   1194:     #   - execute each command in the script:
                   1195:     #
                   1196:     my $configfile = ConfigFileFromSelector($filetype);
                   1197:     if (!(defined $configfile)) {
                   1198: 	return "refused\n";
                   1199:     }
                   1200:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1201: 
1.169     foxr     1202:     for (my $i = 0; $i < $linecount; $i++) {
                   1203: 	ApplyEdit($scriptlines[$i], $editor);
                   1204:     }
                   1205:     # If the file is the host file, ensure that our host is
                   1206:     # adjusted to have our ip:
                   1207:     #
                   1208:     if($filetype eq "host") {
                   1209: 	AdjustOurHost($editor);
                   1210:     }
                   1211:     #  Finally replace the current file with our file.
                   1212:     #
                   1213:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1214: 
                   1215:     return "ok\n";
                   1216: }
1.207     foxr     1217: 
1.255     foxr     1218: #   read_profile
                   1219: #
                   1220: #   Returns a set of specific entries from a user's profile file.
                   1221: #   this is a utility function that is used by both get_profile_entry and
                   1222: #   get_profile_entry_encrypted.
                   1223: #
                   1224: # Parameters:
                   1225: #    udom       - Domain in which the user exists.
                   1226: #    uname      - User's account name (loncapa account)
                   1227: #    namespace  - The profile namespace to open.
                   1228: #    what       - A set of & separated queries.
                   1229: # Returns:
                   1230: #    If all ok: - The string that needs to be shipped back to the user.
                   1231: #    If failure - A string that starts with error: followed by the failure
                   1232: #                 reason.. note that this probabyl gets shipped back to the
                   1233: #                 user as well.
                   1234: #
                   1235: sub read_profile {
                   1236:     my ($udom, $uname, $namespace, $what) = @_;
                   1237:     
                   1238:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1239: 				 &GDBM_READER());
                   1240:     if ($hashref) {
                   1241:         my @queries=split(/\&/,$what);
1.440     raeburn  1242:         if ($namespace eq 'roles') {
                   1243:             @queries = map { &unescape($_); } @queries; 
                   1244:         }
1.255     foxr     1245:         my $qresult='';
                   1246: 	
                   1247: 	for (my $i=0;$i<=$#queries;$i++) {
                   1248: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1249: 	}
                   1250: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1251: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1252: 	    return $qresult;
                   1253: 	} else {
                   1254: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1255: 	}
                   1256:     } else {
                   1257: 	if ($!+0 == 2) {
                   1258: 	    return "error:No such file or GDBM reported bad block error";
                   1259: 	} else {
                   1260: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1261: 	}
                   1262:     }
                   1263: 
                   1264: }
1.214     foxr     1265: #--------------------- Request Handlers --------------------------------------------
                   1266: #
1.215     foxr     1267: #   By convention each request handler registers itself prior to the sub 
                   1268: #   declaration:
1.214     foxr     1269: #
                   1270: 
1.216     foxr     1271: #++
                   1272: #
1.214     foxr     1273: #  Handles ping requests.
                   1274: #  Parameters:
                   1275: #      $cmd    - the actual keyword that invoked us.
                   1276: #      $tail   - the tail of the request that invoked us.
                   1277: #      $replyfd- File descriptor connected to the client
                   1278: #  Implicit Inputs:
                   1279: #      $currenthostid - Global variable that carries the name of the host we are
                   1280: #                       known as.
                   1281: #  Returns:
                   1282: #      1       - Ok to continue processing.
                   1283: #      0       - Program should exit.
                   1284: #  Side effects:
                   1285: #      Reply information is sent to the client.
                   1286: sub ping_handler {
                   1287:     my ($cmd, $tail, $client) = @_;
                   1288:     Debug("$cmd $tail $client .. $currenthostid:");
                   1289:    
1.387     albertel 1290:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1291:    
                   1292:     return 1;
                   1293: }
                   1294: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1295: 
1.216     foxr     1296: #++
1.215     foxr     1297: #
                   1298: # Handles pong requests.  Pong replies with our current host id, and
                   1299: #                         the results of a ping sent to us via our lonc.
                   1300: #
                   1301: # Parameters:
                   1302: #      $cmd    - the actual keyword that invoked us.
                   1303: #      $tail   - the tail of the request that invoked us.
                   1304: #      $replyfd- File descriptor connected to the client
                   1305: #  Implicit Inputs:
                   1306: #      $currenthostid - Global variable that carries the name of the host we are
                   1307: #                       connected to.
                   1308: #  Returns:
                   1309: #      1       - Ok to continue processing.
                   1310: #      0       - Program should exit.
                   1311: #  Side effects:
                   1312: #      Reply information is sent to the client.
                   1313: sub pong_handler {
                   1314:     my ($cmd, $tail, $replyfd) = @_;
                   1315: 
1.365     albertel 1316:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1317:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1318:     return 1;
                   1319: }
                   1320: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1321: 
1.216     foxr     1322: #++
                   1323: #      Called to establish an encrypted session key with the remote client.
                   1324: #      Note that with secure lond, in most cases this function is never
                   1325: #      invoked.  Instead, the secure session key is established either
                   1326: #      via a local file that's locked down tight and only lives for a short
                   1327: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1328: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1329: #      by this sub.  This sub is only used in the old-style insecure
                   1330: #      key negotiation.
                   1331: # Parameters:
                   1332: #      $cmd    - the actual keyword that invoked us.
                   1333: #      $tail   - the tail of the request that invoked us.
                   1334: #      $replyfd- File descriptor connected to the client
                   1335: #  Implicit Inputs:
                   1336: #      $currenthostid - Global variable that carries the name of the host
                   1337: #                       known as.
1.448     raeburn  1338: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1339: #  Returns:
                   1340: #      1       - Ok to continue processing.
                   1341: #      0       - Program should exit.
                   1342: #  Implicit Outputs:
                   1343: #      Reply information is sent to the client.
                   1344: #      $cipher is set with a reference to a new IDEA encryption object.
                   1345: #
                   1346: sub establish_key_handler {
                   1347:     my ($cmd, $tail, $replyfd) = @_;
                   1348: 
                   1349:     my $buildkey=time.$$.int(rand 100000);
                   1350:     $buildkey=~tr/1-6/A-F/;
                   1351:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1352:     my $key=$currenthostid.$clientname;
                   1353:     $key=~tr/a-z/A-Z/;
                   1354:     $key=~tr/G-P/0-9/;
                   1355:     $key=~tr/Q-Z/0-9/;
                   1356:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1357:     $key=substr($key,0,32);
                   1358:     my $cipherkey=pack("H32",$key);
                   1359:     $cipher=new IDEA $cipherkey;
1.387     albertel 1360:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1361:    
                   1362:     return 1;
                   1363: 
                   1364: }
                   1365: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1366: 
1.217     foxr     1367: #     Handler for the load command.  Returns the current system load average
                   1368: #     to the requestor.
                   1369: #
                   1370: # Parameters:
                   1371: #      $cmd    - the actual keyword that invoked us.
                   1372: #      $tail   - the tail of the request that invoked us.
                   1373: #      $replyfd- File descriptor connected to the client
                   1374: #  Implicit Inputs:
                   1375: #      $currenthostid - Global variable that carries the name of the host
                   1376: #                       known as.
1.448     raeburn  1377: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1378: #  Returns:
                   1379: #      1       - Ok to continue processing.
                   1380: #      0       - Program should exit.
                   1381: #  Side effects:
                   1382: #      Reply information is sent to the client.
                   1383: sub load_handler {
                   1384:     my ($cmd, $tail, $replyfd) = @_;
                   1385: 
1.463     foxr     1386: 
                   1387: 
1.217     foxr     1388:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1389:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1390: 
                   1391:     my $loadavg;
                   1392:     my $loadfile=IO::File->new('/proc/loadavg');
                   1393:    
                   1394:     $loadavg=<$loadfile>;
                   1395:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1396:    
                   1397:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1398: 
1.387     albertel 1399:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1400:    
                   1401:     return 1;
                   1402: }
1.263     albertel 1403: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1404: 
                   1405: #
                   1406: #   Process the userload request.  This sub returns to the client the current
                   1407: #  user load average.  It can be invoked either by clients or managers.
                   1408: #
                   1409: # Parameters:
                   1410: #      $cmd    - the actual keyword that invoked us.
                   1411: #      $tail   - the tail of the request that invoked us.
                   1412: #      $replyfd- File descriptor connected to the client
                   1413: #  Implicit Inputs:
                   1414: #      $currenthostid - Global variable that carries the name of the host
                   1415: #                       known as.
1.448     raeburn  1416: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1417: #  Returns:
                   1418: #      1       - Ok to continue processing.
                   1419: #      0       - Program should exit
                   1420: # Implicit inputs:
                   1421: #     whatever the userload() function requires.
                   1422: #  Implicit outputs:
                   1423: #     the reply is written to the client.
                   1424: #
                   1425: sub user_load_handler {
                   1426:     my ($cmd, $tail, $replyfd) = @_;
                   1427: 
1.365     albertel 1428:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1429:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1430:     
                   1431:     return 1;
                   1432: }
1.263     albertel 1433: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1434: 
1.218     foxr     1435: #   Process a request for the authorization type of a user:
                   1436: #   (userauth).
                   1437: #
                   1438: # Parameters:
                   1439: #      $cmd    - the actual keyword that invoked us.
                   1440: #      $tail   - the tail of the request that invoked us.
                   1441: #      $replyfd- File descriptor connected to the client
                   1442: #  Returns:
                   1443: #      1       - Ok to continue processing.
                   1444: #      0       - Program should exit
                   1445: # Implicit outputs:
                   1446: #    The user authorization type is written to the client.
                   1447: #
                   1448: sub user_authorization_type {
                   1449:     my ($cmd, $tail, $replyfd) = @_;
                   1450:    
                   1451:     my $userinput = "$cmd:$tail";
                   1452:    
                   1453:     #  Pull the domain and username out of the command tail.
1.222     foxr     1454:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1455:    
                   1456:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1457:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1458:     if($result eq "nouser") {
                   1459: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1460:     } else {
                   1461: 	#
1.222     foxr     1462: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1463: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1464: 	# password for internals e.g.
                   1465: 	#
                   1466: 	my ($type,$otherinfo) = split(/:/,$result);
                   1467: 	if($type =~ /^krb/) {
                   1468: 	    $type = $result;
1.269     raeburn  1469: 	} else {
                   1470:             $type .= ':';
                   1471:         }
1.387     albertel 1472: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1473:     }
                   1474:   
                   1475:     return 1;
                   1476: }
                   1477: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1478: 
                   1479: #   Process a request by a manager to push a hosts or domain table 
                   1480: #   to us.  We pick apart the command and pass it on to the subs
                   1481: #   that already exist to do this.
                   1482: #
                   1483: # Parameters:
                   1484: #      $cmd    - the actual keyword that invoked us.
                   1485: #      $tail   - the tail of the request that invoked us.
                   1486: #      $client - File descriptor connected to the client
                   1487: #  Returns:
                   1488: #      1       - Ok to continue processing.
                   1489: #      0       - Program should exit
                   1490: # Implicit Output:
                   1491: #    a reply is written to the client.
                   1492: sub push_file_handler {
                   1493:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1494:     &Debug("In push file handler");
1.218     foxr     1495:     my $userinput = "$cmd:$tail";
                   1496: 
                   1497:     # At this time we only know that the IP of our partner is a valid manager
                   1498:     # the code below is a hook to do further authentication (e.g. to resolve
                   1499:     # spoofing).
                   1500: 
                   1501:     my $cert = &GetCertificate($userinput);
1.412     foxr     1502:     if(&ValidManager($cert)) {
                   1503: 	&Debug("Valid manager: $client");
1.218     foxr     1504: 
                   1505: 	# Now presumably we have the bona fides of both the peer host and the
                   1506: 	# process making the request.
                   1507:       
                   1508: 	my $reply = &PushFile($userinput);
1.387     albertel 1509: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1510: 
                   1511:     } else {
1.412     foxr     1512: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1513: 	&Failure( $client, "refused\n", $userinput);
                   1514:     } 
1.219     foxr     1515:     return 1;
1.218     foxr     1516: }
                   1517: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1518: 
1.399     raeburn  1519: # The du_handler routine should be considered obsolete and is retained
                   1520: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1521: #
1.399     raeburn  1522: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1523: #    
                   1524: #   note: stolen code from the ls file handler
                   1525: #   under construction by Rick Banghart 
                   1526: #    .
                   1527: # Parameters:
                   1528: #    $cmd        - The command that dispatched us (du).
                   1529: #    $ududir     - The directory path to list... I'm not sure what this
                   1530: #                  is relative as things like ls:. return e.g.
                   1531: #                  no_such_dir.
                   1532: #    $client     - Socket open on the client.
                   1533: # Returns:
                   1534: #     1 - indicating that the daemon should not disconnect.
                   1535: # Side Effects:
                   1536: #   The reply is written to  $client.
                   1537: #
                   1538: sub du_handler {
                   1539:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1540:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1541:     my $userinput = "$cmd:$ududir";
                   1542: 
1.245     albertel 1543:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1544: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1545: 	return 1;
                   1546:     }
1.249     foxr     1547:     #  Since $ududir could have some nasties in it,
                   1548:     #  we will require that ududir is a valid
                   1549:     #  directory.  Just in case someone tries to
                   1550:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1551:     #  etc.
                   1552:     #
                   1553:     if (-d $ududir) {
1.292     albertel 1554: 	my $total_size=0;
                   1555: 	my $code=sub { 
                   1556: 	    if ($_=~/\.\d+\./) { return;} 
                   1557: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1558: 	    if (-d $_)         { return;}
1.292     albertel 1559: 	    $total_size+=(stat($_))[7];
                   1560: 	};
1.295     raeburn  1561: 	chdir($ududir);
1.292     albertel 1562: 	find($code,$ududir);
                   1563: 	$total_size=int($total_size/1024);
1.387     albertel 1564: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1565:     } else {
1.251     foxr     1566: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1567:     }
1.243     banghart 1568:     return 1;
                   1569: }
                   1570: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1571: 
1.399     raeburn  1572: # Please also see the du_handler, which is obsoleted by du2. 
                   1573: # du2_handler differs from du_handler in that required path to directory
                   1574: # provided by &propath() is prepended in the handler instead of on the 
                   1575: # client side.
1.239     foxr     1576: #
1.399     raeburn  1577: #   du2  - list the disk usage of a directory recursively.
                   1578: #
                   1579: # Parameters:
                   1580: #    $cmd        - The command that dispatched us (du).
                   1581: #    $tail       - The tail of the request that invoked us.
                   1582: #                  $tail is a : separated list of the following:
                   1583: #                   - $ududir - directory path to list (before prepending)
                   1584: #                   - $getpropath = 1 if &propath() should prepend
                   1585: #                   - $uname - username to use for &propath or user dir
                   1586: #                   - $udom - domain to use for &propath or user dir
                   1587: #                   All are escaped.
                   1588: #    $client     - Socket open on the client.
                   1589: # Returns:
                   1590: #     1 - indicating that the daemon should not disconnect.
                   1591: # Side Effects:
                   1592: #   The reply is written to $client.
                   1593: #
                   1594: 
                   1595: sub du2_handler {
                   1596:     my ($cmd, $tail, $client) = @_;
                   1597:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1598:     my $userinput = "$cmd:$tail";
                   1599:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1600:         &Failure($client,"refused\n","$cmd:$tail");
                   1601:         return 1;
                   1602:     }
                   1603:     if ($getpropath) {
                   1604:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1605:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1606:         } else {
                   1607:             &Failure($client,"refused\n","$cmd:$tail");
                   1608:             return 1;
                   1609:         }
                   1610:     }
                   1611:     #  Since $ududir could have some nasties in it,
                   1612:     #  we will require that ududir is a valid
                   1613:     #  directory.  Just in case someone tries to
                   1614:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1615:     #  etc.
                   1616:     #
                   1617:     if (-d $ududir) {
                   1618:         my $total_size=0;
                   1619:         my $code=sub {
                   1620:             if ($_=~/\.\d+\./) { return;}
                   1621:             if ($_=~/\.meta$/) { return;}
                   1622:             if (-d $_)         { return;}
                   1623:             $total_size+=(stat($_))[7];
                   1624:         };
                   1625:         chdir($ududir);
                   1626:         find($code,$ududir);
                   1627:         $total_size=int($total_size/1024);
                   1628:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1629:     } else {
                   1630:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1631:     }
                   1632:     return 1;
                   1633: }
                   1634: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1635: 
                   1636: #
                   1637: # The ls_handler routine should be considered obsolete and is retained
                   1638: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1639: #
1.239     foxr     1640: #   ls  - list the contents of a directory.  For each file in the
                   1641: #    selected directory the filename followed by the full output of
                   1642: #    the stat function is returned.  The returned info for each
                   1643: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1644: #
                   1645: #    If the requested path contains /../ or is:
                   1646: #
                   1647: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1648: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1649: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1650: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1651: #    or is:
                   1652: #
1.538     raeburn  1653: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1654: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1655: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1656: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1657: #
                   1658: #    the response will be "refused".
                   1659: #
1.239     foxr     1660: # Parameters:
                   1661: #    $cmd        - The command that dispatched us (ls).
                   1662: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1663: #                  is relative as things like ls:. return e.g.
                   1664: #                  no_such_dir.
                   1665: #    $client     - Socket open on the client.
                   1666: # Returns:
                   1667: #     1 - indicating that the daemon should not disconnect.
                   1668: # Side Effects:
                   1669: #   The reply is written to  $client.
                   1670: #
                   1671: sub ls_handler {
1.280     matthew  1672:     # obsoleted by ls2_handler
1.239     foxr     1673:     my ($cmd, $ulsdir, $client) = @_;
                   1674: 
                   1675:     my $userinput = "$cmd:$ulsdir";
                   1676: 
                   1677:     my $obs;
                   1678:     my $rights;
                   1679:     my $ulsout='';
                   1680:     my $ulsfn;
1.529     raeburn  1681:     if ($ulsdir =~m{/\.\./}) {
                   1682:         &Failure($client,"refused\n",$userinput);
                   1683:         return 1;
                   1684:     }
1.239     foxr     1685:     if (-e $ulsdir) {
                   1686: 	if(-d $ulsdir) {
1.539     raeburn  1687:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1688:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1689:                 &Failure($client,"refused\n",$userinput);
                   1690:                 return 1;
                   1691:             }
1.239     foxr     1692: 	    if (opendir(LSDIR,$ulsdir)) {
                   1693: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1694: 		    undef($obs);
                   1695: 		    undef($rights); 
1.239     foxr     1696: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1697: 		    #We do some obsolete checking here
                   1698: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1699: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1700: 			my @obsolete=<FILE>;
                   1701: 			foreach my $obsolete (@obsolete) {
1.301     www      1702: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1703: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1704: 			}
                   1705: 		    }
                   1706: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1707: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1708: 		    else { $ulsout.="&0"; }
                   1709: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1710: 		    else { $ulsout.="&0:"; }
                   1711: 		}
                   1712: 		closedir(LSDIR);
                   1713: 	    }
                   1714: 	} else {
1.539     raeburn  1715:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1716:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1717:                 &Failure($client,"refused\n",$userinput);
                   1718:                 return 1;
                   1719:             }
1.239     foxr     1720: 	    my @ulsstats=stat($ulsdir);
                   1721: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1722: 	}
                   1723:     } else {
                   1724: 	$ulsout='no_such_dir';
                   1725:     }
                   1726:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1727:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1728:     
                   1729:     return 1;
                   1730: 
                   1731: }
                   1732: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1733: 
1.399     raeburn  1734: # The ls2_handler routine should be considered obsolete and is retained
                   1735: # for communication with legacy servers.  Please see the ls3_handler.
                   1736: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1737: # ls2_handler differs from ls_handler in that it escapes its return 
                   1738: # values before concatenating them together with ':'s.
                   1739: #
                   1740: #   ls2  - list the contents of a directory.  For each file in the
                   1741: #    selected directory the filename followed by the full output of
                   1742: #    the stat function is returned.  The returned info for each
                   1743: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1744: #
                   1745: #    If the requested path contains /../ or is:
                   1746: #
                   1747: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1748: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1749: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1750: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
                   1751: #    or is:
                   1752: #
1.538     raeburn  1753: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1754: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1755: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1756: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529     raeburn  1757: #
                   1758: #    the response will be "refused".
                   1759: #
1.280     matthew  1760: # Parameters:
                   1761: #    $cmd        - The command that dispatched us (ls).
                   1762: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1763: #                  is relative as things like ls:. return e.g.
                   1764: #                  no_such_dir.
                   1765: #    $client     - Socket open on the client.
                   1766: # Returns:
                   1767: #     1 - indicating that the daemon should not disconnect.
                   1768: # Side Effects:
                   1769: #   The reply is written to  $client.
                   1770: #
                   1771: sub ls2_handler {
                   1772:     my ($cmd, $ulsdir, $client) = @_;
                   1773: 
                   1774:     my $userinput = "$cmd:$ulsdir";
                   1775: 
                   1776:     my $obs;
                   1777:     my $rights;
                   1778:     my $ulsout='';
                   1779:     my $ulsfn;
1.529     raeburn  1780:     if ($ulsdir =~m{/\.\./}) {
                   1781:         &Failure($client,"refused\n",$userinput);
                   1782:         return 1;
                   1783:     }
1.280     matthew  1784:     if (-e $ulsdir) {
                   1785:         if(-d $ulsdir) {
1.539     raeburn  1786:             unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1787:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529     raeburn  1788:                 &Failure($client,"refused\n","$userinput");
                   1789:                 return 1;
                   1790:             }
1.280     matthew  1791:             if (opendir(LSDIR,$ulsdir)) {
                   1792:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1793:                     undef($obs);
                   1794: 		    undef($rights); 
1.280     matthew  1795:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1796:                     #We do some obsolete checking here
                   1797:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1798:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1799:                         my @obsolete=<FILE>;
                   1800:                         foreach my $obsolete (@obsolete) {
1.301     www      1801:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1802:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1803:                                 $rights = 1;
                   1804:                             }
                   1805:                         }
                   1806:                     }
                   1807:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1808:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1809:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1810:                     $ulsout.= &escape($tmp).':';
                   1811:                 }
                   1812:                 closedir(LSDIR);
                   1813:             }
                   1814:         } else {
1.539     raeburn  1815:             unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1816:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529     raeburn  1817:                 &Failure($client,"refused\n",$userinput);
                   1818:                 return 1;
                   1819:             }
1.280     matthew  1820:             my @ulsstats=stat($ulsdir);
                   1821:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1822:         }
                   1823:     } else {
                   1824:         $ulsout='no_such_dir';
                   1825:    }
                   1826:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1827:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1828:    return 1;
                   1829: }
                   1830: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1831: #
                   1832: #   ls3  - list the contents of a directory.  For each file in the
                   1833: #    selected directory the filename followed by the full output of
                   1834: #    the stat function is returned.  The returned info for each
                   1835: #    file are separated by ':'.  The stat fields are separated by &'s.
1.529     raeburn  1836: #
                   1837: #    If the requested path (after prepending) contains /../ or is:
                   1838: #
                   1839: #    1. for a directory, and the path does not begin with one of:
1.530     raeburn  1840: #        (a) /home/httpd/html/res/<domain>
1.539     raeburn  1841: #        (b) /home/httpd/html/userfiles/
1.529     raeburn  1842: #        (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539     raeburn  1843: #        (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529     raeburn  1844: #
1.530     raeburn  1845: #    or is:
1.529     raeburn  1846: #
1.538     raeburn  1847: #    2. for a file, and the path (after prepending) does not begin with one of:
1.539     raeburn  1848: #        (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
                   1849: #        (b) /home/httpd/html/res/<domain>/<username>/
                   1850: #        (c) /home/httpd/html/userfiles/<domain>/<username>/
                   1851: #        (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529     raeburn  1852: #
                   1853: #    the response will be "refused".
                   1854: #
1.399     raeburn  1855: # Parameters:
                   1856: #    $cmd        - The command that dispatched us (ls).
                   1857: #    $tail       - The tail of the request that invoked us.
                   1858: #                  $tail is a : separated list of the following:
                   1859: #                   - $ulsdir - directory path to list (before prepending)
                   1860: #                   - $getpropath = 1 if &propath() should prepend
                   1861: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1862: #                                     prepend
                   1863: #                   - $alternate_root - path to prepend
                   1864: #                   - $uname - username to use for &propath or user dir
                   1865: #                   - $udom - domain to use for &propath or user dir
                   1866: #            All of these except $getpropath and &getuserdir are escaped.    
                   1867: #                  no_such_dir.
                   1868: #    $client     - Socket open on the client.
                   1869: # Returns:
                   1870: #     1 - indicating that the daemon should not disconnect.
                   1871: # Side Effects:
                   1872: #   The reply is written to $client.
                   1873: #
                   1874: 
                   1875: sub ls3_handler {
                   1876:     my ($cmd, $tail, $client) = @_;
                   1877:     my $userinput = "$cmd:$tail";
                   1878:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1879:         split(/:/,$tail);
                   1880:     if (defined($ulsdir)) {
                   1881:         $ulsdir = &unescape($ulsdir);
                   1882:     }
                   1883:     if (defined($alternate_root)) {
                   1884:         $alternate_root = &unescape($alternate_root);
                   1885:     }
                   1886:     if (defined($uname)) {
                   1887:         $uname = &unescape($uname);
                   1888:     }
                   1889:     if (defined($udom)) {
                   1890:         $udom = &unescape($udom);
                   1891:     }
                   1892: 
                   1893:     my $dir_root = $perlvar{'lonDocRoot'};
1.529     raeburn  1894:     if (($getpropath) || ($getuserdir)) {
1.399     raeburn  1895:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1896:             $dir_root = &propath($udom,$uname);
                   1897:             $dir_root =~ s/\/$//;
                   1898:         } else {
1.529     raeburn  1899:             &Failure($client,"refused\n",$userinput);
1.399     raeburn  1900:             return 1;
                   1901:         }
1.400     raeburn  1902:     } elsif ($alternate_root ne '') {
1.399     raeburn  1903:         $dir_root = $alternate_root;
                   1904:     }
1.408     raeburn  1905:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1906:         if ($ulsdir =~ /^\//) {
                   1907:             $ulsdir = $dir_root.$ulsdir;
                   1908:         } else {
                   1909:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1910:         }
1.399     raeburn  1911:     }
1.529     raeburn  1912:     if ($ulsdir =~m{/\.\./}) {
                   1913:         &Failure($client,"refused\n",$userinput);
                   1914:         return 1;
                   1915:     }
                   1916:     my $islocal;
                   1917:     my @machine_ids = &Apache::lonnet::current_machine_ids();
                   1918:     if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   1919:         $islocal = 1;
                   1920:     }
1.399     raeburn  1921:     my $obs;
                   1922:     my $rights;
                   1923:     my $ulsout='';
                   1924:     my $ulsfn;
1.547     raeburn  1925: 
                   1926:     my ($crscheck,$toplevel,$currdom,$currnum,$skip);
                   1927:     unless ($islocal) {
                   1928:         my ($major,$minor) = split(/\./,$clientversion);
                   1929:         if (($major < 2) || ($major == 2 && $minor < 12)) {
                   1930:             $crscheck = 1;
                   1931:         }
                   1932:     }
1.399     raeburn  1933:     if (-e $ulsdir) {
                   1934:         if(-d $ulsdir) {
1.529     raeburn  1935:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1936:                     ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
                   1937:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
                   1938:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1.529     raeburn  1939:                 &Failure($client,"refused\n",$userinput);
                   1940:                 return 1;
                   1941:             }
1.547     raeburn  1942:             if (($crscheck) &&
                   1943:                 ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
                   1944:                 ($currdom,my $posscnum) = ($1,$2);
                   1945:                 if (($posscnum eq '') || ($posscnum eq '/')) {
                   1946:                     $toplevel = 1;
                   1947:                 } else {
                   1948:                     $posscnum =~ s{^/+}{};
                   1949:                     if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
                   1950:                         $skip = 1;
                   1951:                     }
                   1952:                 }
                   1953:             }
                   1954:             if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399     raeburn  1955:                 while ($ulsfn=readdir(LSDIR)) {
1.547     raeburn  1956:                     if (($crscheck) && ($toplevel) && ($currdom ne '') &&
                   1957:                         ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
                   1958:                         if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
                   1959:                             next;
                   1960:                         }
                   1961:                     }
1.399     raeburn  1962:                     undef($obs);
                   1963:                     undef($rights);
                   1964:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1965:                     #We do some obsolete checking here
                   1966:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1967:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1968:                         my @obsolete=<FILE>;
                   1969:                         foreach my $obsolete (@obsolete) {
                   1970:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1971:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1972:                                 $rights = 1;
                   1973:                             }
                   1974:                         }
                   1975:                     }
                   1976:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1977:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1978:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1979:                     $ulsout.= &escape($tmp).':';
                   1980:                 }
                   1981:                 closedir(LSDIR);
                   1982:             }
                   1983:         } else {
1.529     raeburn  1984:             unless (($getpropath) || ($getuserdir) ||
1.539     raeburn  1985:                     ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
                   1986:                     ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
                   1987:                     (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529     raeburn  1988:                 &Failure($client,"refused\n",$userinput);
                   1989:                 return 1;
                   1990:             }
1.399     raeburn  1991:             my @ulsstats=stat($ulsdir);
                   1992:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1993:         }
                   1994:     } else {
                   1995:         $ulsout='no_such_dir';
1.400     raeburn  1996:     }
                   1997:     if ($ulsout eq '') { $ulsout='empty'; }
                   1998:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1999:     return 1;
1.399     raeburn  2000: }
                   2001: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  2002: 
1.477     raeburn  2003: sub read_lonnet_global {
                   2004:     my ($cmd,$tail,$client) = @_;
                   2005:     my $userinput = "$cmd:$tail";
                   2006:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   2007:     my $result;
1.480     raeburn  2008:     my %packagevars = (
                   2009:                         spareid => \%Apache::lonnet::spareid,
                   2010:                         perlvar => \%Apache::lonnet::perlvar,
                   2011:                       );
                   2012:     my %limit_to = (
                   2013:                     perlvar => {
1.531     raeburn  2014:                                  lonOtherAuthen  => 1,
                   2015:                                  lonBalancer     => 1,
                   2016:                                  lonVersion      => 1,
                   2017:                                  lonAdmEMail     => 1,
                   2018:                                  lonSupportEMail => 1,  
                   2019:                                  lonSysEMail     => 1,
                   2020:                                  lonHostID       => 1,
                   2021:                                  lonRole         => 1,
                   2022:                                  lonDefDomain    => 1,
                   2023:                                  lonLoadLim      => 1,
                   2024:                                  lonUserLoadLim  => 1,
1.480     raeburn  2025:                                }
                   2026:                   );
1.477     raeburn  2027:     if (ref($requested) eq 'HASH') {
                   2028:         foreach my $what (keys(%{$requested})) {
                   2029:             my $response;
1.480     raeburn  2030:             my $items = {};
                   2031:             if (exists($packagevars{$what})) {
                   2032:                 if (ref($limit_to{$what}) eq 'HASH') {
                   2033:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   2034:                         if ($limit_to{$what}{$varname}) {
                   2035:                             $items->{$varname} = $packagevars{$what}{$varname};
                   2036:                         }
                   2037:                     }
                   2038:                 } else {
                   2039:                     $items = $packagevars{$what};
1.477     raeburn  2040:                 }
1.480     raeburn  2041:                 if ($what eq 'perlvar') {
                   2042:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
1.570     raeburn  2043:                         if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
1.480     raeburn  2044:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   2045:                             if (ref($othervarref) eq 'HASH') {
                   2046:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   2047:                             }
                   2048:                         }
                   2049:                     }
1.477     raeburn  2050:                 }
1.480     raeburn  2051:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  2052:             }
1.478     raeburn  2053:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  2054:         }
                   2055:     }
                   2056:     $result =~ s/\&$//;
                   2057:     &Reply($client,\$result,$userinput);
                   2058:     return 1;
                   2059: }
                   2060: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   2061: 
1.479     raeburn  2062: sub server_devalidatecache_handler {
                   2063:     my ($cmd,$tail,$client) = @_;
                   2064:     my $userinput = "$cmd:$tail";
1.503     raeburn  2065:     my $items = &unescape($tail);
                   2066:     my @cached = split(/\&/,$items);
                   2067:     foreach my $key (@cached) {
                   2068:         if ($key =~ /:/) {
                   2069:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   2070:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   2071:         }
                   2072:     }
1.479     raeburn  2073:     my $result = 'ok';
                   2074:     &Reply($client,\$result,$userinput);
                   2075:     return 1;
                   2076: }
1.481     raeburn  2077: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  2078: 
1.410     raeburn  2079: sub server_timezone_handler {
                   2080:     my ($cmd,$tail,$client) = @_;
                   2081:     my $userinput = "$cmd:$tail";
                   2082:     my $timezone;
                   2083:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   2084:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   2085:     if (-e $clockfile) {
                   2086:         if (open(my $fh,"<$clockfile")) {
                   2087:             while (<$fh>) {
                   2088:                 next if (/^[\#\s]/);
                   2089:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   2090:                     $timezone = $1;
                   2091:                     last;
                   2092:                 }
                   2093:             }
                   2094:             close($fh);
                   2095:         }
                   2096:     } elsif (-e $tzfile) {
                   2097:         if (open(my $fh,"<$tzfile")) {
                   2098:             $timezone = <$fh>;
                   2099:             close($fh);
                   2100:             chomp($timezone);
                   2101:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   2102:                 $timezone = $1;
                   2103:             }
                   2104:         }
                   2105:     }
                   2106:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   2107:     return 1;
                   2108: }
                   2109: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   2110: 
1.413     raeburn  2111: sub server_loncaparev_handler {
                   2112:     my ($cmd,$tail,$client) = @_;
                   2113:     my $userinput = "$cmd:$tail";
                   2114:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   2115:     return 1;
                   2116: }
                   2117: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   2118: 
1.448     raeburn  2119: sub server_homeID_handler {
                   2120:     my ($cmd,$tail,$client) = @_;
                   2121:     my $userinput = "$cmd:$tail";
                   2122:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   2123:     return 1;
                   2124: }
                   2125: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   2126: 
1.471     raeburn  2127: sub server_distarch_handler {
                   2128:     my ($cmd,$tail,$client) = @_;
                   2129:     my $userinput = "$cmd:$tail";
                   2130:     my $reply = &distro_and_arch();
                   2131:     &Reply($client,\$reply,$userinput);
                   2132:     return 1;
                   2133: }
                   2134: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   2135: 
1.523     raeburn  2136: sub server_certs_handler {
                   2137:     my ($cmd,$tail,$client) = @_;
                   2138:     my $userinput = "$cmd:$tail";
1.548     raeburn  2139:     my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                   2140:     my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523     raeburn  2141:     &Reply($client,\$result,$userinput);
                   2142:     return;
                   2143: }
                   2144: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   2145: 
1.218     foxr     2146: #   Process a reinit request.  Reinit requests that either
                   2147: #   lonc or lond be reinitialized so that an updated 
                   2148: #   host.tab or domain.tab can be processed.
                   2149: #
                   2150: # Parameters:
                   2151: #      $cmd    - the actual keyword that invoked us.
                   2152: #      $tail   - the tail of the request that invoked us.
                   2153: #      $client - File descriptor connected to the client
                   2154: #  Returns:
                   2155: #      1       - Ok to continue processing.
                   2156: #      0       - Program should exit
                   2157: #  Implicit output:
                   2158: #     a reply is sent to the client.
                   2159: #
                   2160: sub reinit_process_handler {
                   2161:     my ($cmd, $tail, $client) = @_;
                   2162:    
                   2163:     my $userinput = "$cmd:$tail";
                   2164:    
                   2165:     my $cert = &GetCertificate($userinput);
                   2166:     if(&ValidManager($cert)) {
                   2167: 	chomp($userinput);
                   2168: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 2169: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     2170:     } else {
                   2171: 	&Failure( $client, "refused\n", $userinput);
                   2172:     }
                   2173:     return 1;
                   2174: }
                   2175: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   2176: 
                   2177: #  Process the editing script for a table edit operation.
                   2178: #  the editing operation must be encrypted and requested by
                   2179: #  a manager host.
                   2180: #
                   2181: # Parameters:
                   2182: #      $cmd    - the actual keyword that invoked us.
                   2183: #      $tail   - the tail of the request that invoked us.
                   2184: #      $client - File descriptor connected to the client
                   2185: #  Returns:
                   2186: #      1       - Ok to continue processing.
                   2187: #      0       - Program should exit
                   2188: #  Implicit output:
                   2189: #     a reply is sent to the client.
                   2190: #
                   2191: sub edit_table_handler {
                   2192:     my ($command, $tail, $client) = @_;
                   2193:    
                   2194:     my $userinput = "$command:$tail";
                   2195: 
                   2196:     my $cert = &GetCertificate($userinput);
                   2197:     if(&ValidManager($cert)) {
                   2198: 	my($filetype, $script) = split(/:/, $tail);
                   2199: 	if (($filetype eq "hosts") || 
                   2200: 	    ($filetype eq "domain")) {
                   2201: 	    if($script ne "") {
                   2202: 		&Reply($client,              # BUGBUG - EditFile
                   2203: 		      &EditFile($userinput), #   could fail.
                   2204: 		      $userinput);
                   2205: 	    } else {
                   2206: 		&Failure($client,"refused\n",$userinput);
                   2207: 	    }
                   2208: 	} else {
                   2209: 	    &Failure($client,"refused\n",$userinput);
                   2210: 	}
                   2211:     } else {
                   2212: 	&Failure($client,"refused\n",$userinput);
                   2213:     }
                   2214:     return 1;
                   2215: }
1.263     albertel 2216: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2217: 
1.220     foxr     2218: #
                   2219: #   Authenticate a user against the LonCAPA authentication
                   2220: #   database.  Note that there are several authentication
                   2221: #   possibilities:
                   2222: #   - unix     - The user can be authenticated against the unix
                   2223: #                password file.
                   2224: #   - internal - The user can be authenticated against a purely 
                   2225: #                internal per user password file.
                   2226: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2227: #                ticket granting authority.
                   2228: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2229: #                mechanism that is per system.
                   2230: #
                   2231: # Parameters:
                   2232: #    $cmd      - The command that got us here.
                   2233: #    $tail     - Tail of the command (remaining parameters).
                   2234: #    $client   - File descriptor connected to client.
                   2235: # Returns
                   2236: #     0        - Requested to exit, caller should shut down.
                   2237: #     1        - Continue processing.
                   2238: # Implicit inputs:
                   2239: #    The authentication systems describe above have their own forms of implicit
                   2240: #    input into the authentication process that are described above.
                   2241: #
                   2242: sub authenticate_handler {
                   2243:     my ($cmd, $tail, $client) = @_;
                   2244: 
                   2245:     
                   2246:     #  Regenerate the full input line 
                   2247:     
                   2248:     my $userinput  = $cmd.":".$tail;
                   2249:     
                   2250:     #  udom    - User's domain.
                   2251:     #  uname   - Username.
                   2252:     #  upass   - User's password.
1.396     raeburn  2253:     #  checkdefauth - Pass to validate_user() to try authentication
                   2254:     #                 with default auth type(s) if no user account.
1.447     raeburn  2255:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2256:     #                       to check if session can be hosted.
1.220     foxr     2257:     
1.447     raeburn  2258:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2259:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2260:     chomp($upass);
                   2261:     $upass=&unescape($upass);
                   2262: 
1.396     raeburn  2263:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2264:     if($pwdcorrect) {
1.447     raeburn  2265:         my $canhost = 1;
                   2266:         unless ($clientcancheckhost) {
1.448     raeburn  2267:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2268:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2269:             my @intdoms;
                   2270:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2271:             if (ref($internet_names) eq 'ARRAY') {
                   2272:                 @intdoms = @{$internet_names};
                   2273:             }
1.448     raeburn  2274:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2275:                 my ($remote,$hosted);
                   2276:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2277:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2278:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2279:                 }
1.448     raeburn  2280:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2281:                 if (ref($hostedsession) eq 'HASH') {
                   2282:                     $hosted = $hostedsession->{'hosted'};
                   2283:                 }
1.448     raeburn  2284:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2285:                                                              $clientversion,
1.447     raeburn  2286:                                                              $remote,$hosted);
                   2287:             }
                   2288:         }
                   2289:         if ($canhost) {               
                   2290:             &Reply( $client, "authorized\n", $userinput);
                   2291:         } else {
                   2292:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2293:         }
1.220     foxr     2294: 	#
                   2295: 	#  Bad credentials: Failed to authorize
                   2296: 	#
                   2297:     } else {
                   2298: 	&Failure( $client, "non_authorized\n", $userinput);
                   2299:     }
                   2300: 
                   2301:     return 1;
                   2302: }
1.263     albertel 2303: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2304: 
1.222     foxr     2305: #
                   2306: #   Change a user's password.  Note that this function is complicated by
                   2307: #   the fact that a user may be authenticated in more than one way:
                   2308: #   At present, we are not able to change the password for all types of
                   2309: #   authentication methods.  Only for:
                   2310: #      unix    - unix password or shadow passoword style authentication.
                   2311: #      local   - Locally written authentication mechanism.
                   2312: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2313: #   in an error.
                   2314: # FUTURE WORK:
                   2315: #    Support kerberos passwd changes?
                   2316: # Parameters:
                   2317: #    $cmd      - The command that got us here.
                   2318: #    $tail     - Tail of the command (remaining parameters).
                   2319: #    $client   - File descriptor connected to client.
                   2320: # Returns
                   2321: #     0        - Requested to exit, caller should shut down.
                   2322: #     1        - Continue processing.
                   2323: # Implicit inputs:
                   2324: #    The authentication systems describe above have their own forms of implicit
                   2325: #    input into the authentication process that are described above.
                   2326: sub change_password_handler {
                   2327:     my ($cmd, $tail, $client) = @_;
                   2328: 
                   2329:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2330: 
                   2331:     #
                   2332:     #  udom  - user's domain.
                   2333:     #  uname - Username.
                   2334:     #  upass - Current password.
                   2335:     #  npass - New password.
1.346     raeburn  2336:     #  context - Context in which this was called 
                   2337:     #            (preferences or reset_by_email).
1.428     raeburn  2338:     #  lonhost - HostID of server where request originated 
1.222     foxr     2339:    
1.428     raeburn  2340:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2341: 
                   2342:     $upass=&unescape($upass);
                   2343:     $npass=&unescape($npass);
                   2344:     &Debug("Trying to change password for $uname");
                   2345: 
                   2346:     # First require that the user can be authenticated with their
1.346     raeburn  2347:     # old password unless context was 'reset_by_email':
                   2348:     
1.428     raeburn  2349:     my ($validated,$failure);
1.346     raeburn  2350:     if ($context eq 'reset_by_email') {
1.428     raeburn  2351:         if ($lonhost eq '') {
                   2352:             $failure = 'invalid_client';
                   2353:         } else {
                   2354:             $validated = 1;
                   2355:         }
1.346     raeburn  2356:     } else {
                   2357:         $validated = &validate_user($udom, $uname, $upass);
                   2358:     }
1.222     foxr     2359:     if($validated) {
                   2360: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2361: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558     raeburn  2362:         my $notunique;
1.222     foxr     2363: 	if ($howpwd eq 'internal') {
                   2364: 	    &Debug("internal auth");
1.518     raeburn  2365:             my $ncpass = &hash_passwd($udom,$npass);
1.558     raeburn  2366:             my (undef,$method,@rest) = split(/!/,$contentpwd);
                   2367:             if ($method eq 'bcrypt') {
                   2368:                 my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
                   2369:                 if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
                   2370:                     my @oldpasswds;
                   2371:                     my $userpath = &propath($udom,$uname);
                   2372:                     my $fullpath = $userpath.'/oldpasswds';
                   2373:                     if (-d $userpath) {
                   2374:                         my @oldfiles;
                   2375:                         if (-e $fullpath) {
                   2376:                             if (opendir(my $dir,$fullpath)) {
                   2377:                                 (@oldfiles) = grep(/^\d+$/,readdir($dir));
                   2378:                                 closedir($dir);
                   2379:                             }
                   2380:                             if (@oldfiles) {
                   2381:                                 @oldfiles = sort { $b <=> $a } (@oldfiles);
                   2382:                                 my $numremoved = 0;
                   2383:                                 for (my $i=0; $i<@oldfiles; $i++) {
                   2384:                                     if ($i>=$passwdconf{'numsaved'}) {
                   2385:                                         if (-f "$fullpath/$oldfiles[$i]") {
                   2386:                                             if (unlink("$fullpath/$oldfiles[$i]")) {
                   2387:                                                 $numremoved ++;
                   2388:                                             }
                   2389:                                         }
                   2390:                                     } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
                   2391:                                         while (my $line = <$fh>) {
                   2392:                                             push(@oldpasswds,$line);
                   2393:                                         }
                   2394:                                         close($fh);
                   2395:                                     }
                   2396:                                 }
                   2397:                                 if ($numremoved) {
                   2398:                                     &logthis("unlinked $numremoved old password files for $uname:$udom");
                   2399:                                 }
                   2400:                             }
                   2401:                         }
                   2402:                         push(@oldpasswds,$contentpwd);
                   2403:                         foreach my $item (@oldpasswds) {
                   2404:                             my (undef,$method,@rest) = split(/!/,$item);
                   2405:                             if ($method eq 'bcrypt') {
                   2406:                                 my $result = &hash_passwd($udom,$npass,@rest);
                   2407:                                 if ($result eq $item) {
                   2408:                                     $notunique = 1;
                   2409:                                     last;
                   2410:                                 }
                   2411:                             }
                   2412:                         }
                   2413:                         unless ($notunique) {
                   2414:                             unless (-e $fullpath) {
                   2415:                                 if (&mkpath("$fullpath/")) {
                   2416:                                     chmod(0700,$fullpath);
                   2417:                                 }
                   2418:                             }
                   2419:                             if (-d $fullpath) {
                   2420:                                 my $now = time;
                   2421:                                 if (open(my $fh,'>',"$fullpath/$now")) {
                   2422:                                     print $fh $contentpwd;
                   2423:                                     close($fh);
                   2424:                                     chmod(0400,"$fullpath/$now");
                   2425:                                 }
                   2426:                             }
                   2427:                         }
                   2428:                     }
                   2429:                 }
                   2430:             }
                   2431:             if ($notunique) {
                   2432:                 my $msg="Result of password change for $uname:$udom - password matches one used before";
                   2433:                 if ($lonhost) {
                   2434:                     $msg .= " - request originated from: $lonhost";
                   2435:                 }
                   2436:                 &logthis($msg);
                   2437:                 &Reply($client, "prioruse\n", $userinput);
                   2438: 	    } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2439: 		my $msg="Result of password change for $uname: pwchange_success";
                   2440:                 if ($lonhost) {
                   2441:                     $msg .= " - request originated from: $lonhost";
                   2442:                 }
                   2443:                 &logthis($msg);
1.518     raeburn  2444:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2445: 		&Reply($client, "ok\n", $userinput);
                   2446: 	    } else {
                   2447: 		&logthis("Unable to open $uname passwd "               
                   2448: 			 ."to change password");
                   2449: 		&Failure( $client, "non_authorized\n",$userinput);
                   2450: 	    }
1.346     raeburn  2451: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2452: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2453:             if ($result eq 'ok') {
                   2454:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.561     raeburn  2455:             }
1.222     foxr     2456: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2457: 		     $result);
1.387     albertel 2458: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2459: 	} else {
                   2460: 	    # this just means that the current password mode is not
                   2461: 	    # one we know how to change (e.g the kerberos auth modes or
                   2462: 	    # locally written auth handler).
                   2463: 	    #
                   2464: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2465: 	}  
1.224     foxr     2466:     } else {
1.428     raeburn  2467: 	if ($failure eq '') {
                   2468: 	    $failure = 'non_authorized';
                   2469: 	}
                   2470: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2471:     }
                   2472: 
                   2473:     return 1;
                   2474: }
1.263     albertel 2475: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2476: 
1.518     raeburn  2477: sub hash_passwd {
                   2478:     my ($domain,$plainpass,@rest) = @_;
                   2479:     my ($salt,$cost);
                   2480:     if (@rest) {
                   2481:         $cost = $rest[0];
                   2482:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2483:         my $plainsalt = substr($rest[1],0,22);
                   2484:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2485:     } else {
1.533     raeburn  2486:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2487:         my $defaultcost = $domdefaults{'intauth_cost'};
1.518     raeburn  2488:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2489:             $cost = 10;
                   2490:         } else {
                   2491:             $cost = $defaultcost;
                   2492:         }
                   2493:         # Generate random 16-octet base64 salt
                   2494:         $salt = "";
                   2495:         $salt .= pack("C", int rand(256)) for 1..16;
                   2496:     }
                   2497:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2498:         key_nul => 1,
                   2499:         cost    => $cost,
                   2500:         salt    => $salt,
                   2501:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2502: 
                   2503:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2504:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2505:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2506:     return $result;
                   2507: }
                   2508: 
1.225     foxr     2509: #
                   2510: #   Create a new user.  User in this case means a lon-capa user.
                   2511: #   The user must either already exist in some authentication realm
                   2512: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2513: #   this loncapa system is created.
                   2514: #
                   2515: # Parameters:
                   2516: #    $cmd      - The command that got us here.
                   2517: #    $tail     - Tail of the command (remaining parameters).
                   2518: #    $client   - File descriptor connected to client.
                   2519: # Returns
                   2520: #     0        - Requested to exit, caller should shut down.
                   2521: #     1        - Continue processing.
                   2522: # Implicit inputs:
                   2523: #    The authentication systems describe above have their own forms of implicit
                   2524: #    input into the authentication process that are described above.
                   2525: sub add_user_handler {
                   2526: 
                   2527:     my ($cmd, $tail, $client) = @_;
                   2528: 
                   2529: 
                   2530:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2531:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2532: 
                   2533:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2534: 
                   2535: 
                   2536:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2537: 	
                   2538: 	my $oldumask=umask(0077);
                   2539: 	chomp($npass);
                   2540: 	$npass=&unescape($npass);
                   2541: 	my $passfilename  = &password_path($udom, $uname);
                   2542: 	&Debug("Password file created will be:".$passfilename);
                   2543: 	if (-e $passfilename) {
                   2544: 	    &Failure( $client, "already_exists\n", $userinput);
                   2545: 	} else {
                   2546: 	    my $fperror='';
1.264     albertel 2547: 	    if (!&mkpath($passfilename)) {
                   2548: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2549: 		    ."makeuser";
1.225     foxr     2550: 	    }
                   2551: 	    unless ($fperror) {
1.518     raeburn  2552: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2553:                                              $passfilename,'makeuser');
1.390     raeburn  2554: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2555: 	    } else {
1.387     albertel 2556: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2557: 	    }
                   2558: 	}
                   2559: 	umask($oldumask);
                   2560:     }  else {
                   2561: 	&Failure($client, "not_right_domain\n",
                   2562: 		$userinput);	# Even if we are multihomed.
                   2563:     
                   2564:     }
                   2565:     return 1;
                   2566: 
                   2567: }
                   2568: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2569: 
                   2570: #
                   2571: #   Change the authentication method of a user.  Note that this may
                   2572: #   also implicitly change the user's password if, for example, the user is
                   2573: #   joining an existing authentication realm.  Known authentication realms at
                   2574: #   this time are:
                   2575: #    internal   - Purely internal password file (only loncapa knows this user)
                   2576: #    local      - Institutionally written authentication module.
                   2577: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2578: #    kerb4      - kerberos version 4
                   2579: #    kerb5      - kerberos version 5
                   2580: #
                   2581: # Parameters:
                   2582: #    $cmd      - The command that got us here.
                   2583: #    $tail     - Tail of the command (remaining parameters).
                   2584: #    $client   - File descriptor connected to client.
                   2585: # Returns
                   2586: #     0        - Requested to exit, caller should shut down.
                   2587: #     1        - Continue processing.
                   2588: # Implicit inputs:
                   2589: #    The authentication systems describe above have their own forms of implicit
                   2590: #    input into the authentication process that are described above.
1.287     foxr     2591: # NOTE:
                   2592: #   This is also used to change the authentication credential values (e.g. passwd).
                   2593: #   
1.225     foxr     2594: #
                   2595: sub change_authentication_handler {
                   2596: 
                   2597:     my ($cmd, $tail, $client) = @_;
                   2598:    
                   2599:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2600: 
                   2601:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2602:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2603:     if ($udom ne $currentdomainid) {
                   2604: 	&Failure( $client, "not_right_domain\n", $client);
                   2605:     } else {
                   2606: 	
                   2607: 	chomp($npass);
                   2608: 	
                   2609: 	$npass=&unescape($npass);
1.261     foxr     2610: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2611: 	my $passfilename = &password_path($udom, $uname);
                   2612: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2613: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2614: 	    # passwd since otherwise make_passwd_file will fail as 
                   2615: 	    # creation of unix authenticated users is no longer supported
                   2616:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2617: 
                   2618: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2619: 		my $result = &change_unix_password($uname, $npass);
                   2620: 		&logthis("Result of password change for $uname: ".$result);
                   2621: 		if ($result eq "ok") {
1.518     raeburn  2622:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2623: 		    &Reply($client, \$result);
1.288     albertel 2624: 		} else {
1.387     albertel 2625: 		    &Failure($client, \$result);
1.287     foxr     2626: 		}
1.288     albertel 2627: 	    } else {
1.518     raeburn  2628: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2629:                                              $passfilename,'changeuserauth');
1.287     foxr     2630: 		#
                   2631: 		#  If the current auth mode is internal, and the old auth mode was
                   2632: 		#  unix, or krb*,  and the user is an author for this domain,
                   2633: 		#  re-run manage_permissions for that role in order to be able
                   2634: 		#  to take ownership of the construction space back to www:www
                   2635: 		#
1.502     raeburn  2636: 
                   2637: 
1.387     albertel 2638: 		&Reply($client, \$result, $userinput);
1.261     foxr     2639: 	    }
                   2640: 	       
                   2641: 
1.225     foxr     2642: 	} else {	       
1.251     foxr     2643: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2644: 	}
                   2645:     }
                   2646:     return 1;
                   2647: }
                   2648: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2649: 
1.518     raeburn  2650: sub update_passwd_history {
                   2651:     my ($uname,$udom,$umode,$context) = @_;
                   2652:     my $proname=&propath($udom,$uname);
                   2653:     my $now = time;
                   2654:     if (open(my $fh,">>$proname/passwd.log")) {
                   2655:         print $fh "$now:$umode:$context\n";
                   2656:         close($fh);
                   2657:     }
                   2658:     return;
                   2659: }
                   2660: 
1.575     raeburn  2661: sub inst_unamemap_check {
                   2662:     my ($cmd, $tail, $client)   = @_;
                   2663:     my $userinput               = "$cmd:$tail";
                   2664:     my %rulecheck;
                   2665:     my $outcome;
                   2666:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   2667:     $udom = &unescape($udom);
                   2668:     $uname = &unescape($uname);
                   2669:     @rules = map {&unescape($_);} (@rules);
                   2670:     eval {
                   2671:         local($SIG{__DIE__})='DEFAULT';
                   2672:         $outcome = &localenroll::unamemap_check($udom,$uname,\@rules,\%rulecheck);
                   2673:     };
                   2674:     if (!$@) {
                   2675:         if ($outcome eq 'ok') {
                   2676:             my $result='';
                   2677:             foreach my $key (keys(%rulecheck)) {
                   2678:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   2679:             }
                   2680:             &Reply($client,\$result,$userinput);
                   2681:         } else {
                   2682:             &Reply($client,"error\n", $userinput);
                   2683:         }
                   2684:     } else {
                   2685:         &Failure($client,"unknown_cmd\n",$userinput);
                   2686:     }
                   2687: }
                   2688: &register_handler("instunamemapcheck",\&inst_unamemap_check,0,1,0);
                   2689: 
                   2690: 
1.225     foxr     2691: #
                   2692: #   Determines if this is the home server for a user.  The home server
                   2693: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2694: #   to do is determine if this file exists.
                   2695: #
                   2696: # Parameters:
                   2697: #    $cmd      - The command that got us here.
                   2698: #    $tail     - Tail of the command (remaining parameters).
                   2699: #    $client   - File descriptor connected to client.
                   2700: # Returns
                   2701: #     0        - Requested to exit, caller should shut down.
                   2702: #     1        - Continue processing.
                   2703: # Implicit inputs:
                   2704: #    The authentication systems describe above have their own forms of implicit
                   2705: #    input into the authentication process that are described above.
                   2706: #
                   2707: sub is_home_handler {
                   2708:     my ($cmd, $tail, $client) = @_;
                   2709:    
                   2710:     my $userinput  = "$cmd:$tail";
                   2711:    
                   2712:     my ($udom,$uname)=split(/:/,$tail);
                   2713:     chomp($uname);
                   2714:     my $passfile = &password_filename($udom, $uname);
                   2715:     if($passfile) {
                   2716: 	&Reply( $client, "found\n", $userinput);
                   2717:     } else {
                   2718: 	&Failure($client, "not_found\n", $userinput);
                   2719:     }
                   2720:     return 1;
                   2721: }
                   2722: &register_handler("home", \&is_home_handler, 0,1,0);
                   2723: 
                   2724: #
1.434     www      2725: #   Process an update request for a resource.
                   2726: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2727: #   If the resource is not local, then we must update, or at least invalidate our
                   2728: #   cached copy of the resource. 
                   2729: # Parameters:
                   2730: #    $cmd      - The command that got us here.
                   2731: #    $tail     - Tail of the command (remaining parameters).
                   2732: #    $client   - File descriptor connected to client.
                   2733: # Returns
                   2734: #     0        - Requested to exit, caller should shut down.
                   2735: #     1        - Continue processing.
                   2736: # Implicit inputs:
                   2737: #    The authentication systems describe above have their own forms of implicit
                   2738: #    input into the authentication process that are described above.
                   2739: #
                   2740: sub update_resource_handler {
                   2741: 
                   2742:     my ($cmd, $tail, $client) = @_;
                   2743:    
                   2744:     my $userinput = "$cmd:$tail";
                   2745:    
                   2746:     my $fname= $tail;		# This allows interactive testing
                   2747: 
                   2748: 
                   2749:     my $ownership=ishome($fname);
                   2750:     if ($ownership eq 'not_owner') {
                   2751: 	if (-e $fname) {
1.434     www      2752:             # Delete preview file, if exists
                   2753:             unlink("$fname.tmp");
                   2754:             # Get usage stats
1.225     foxr     2755: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2756: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2757: 	    my $now=time;
                   2758: 	    my $since=$now-$atime;
1.434     www      2759:             # If the file has not been used within lonExpire seconds,
                   2760:             # unsubscribe from it and delete local copy
1.225     foxr     2761: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2762: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2763: 		&devalidate_meta_cache($fname);
1.225     foxr     2764: 		unlink("$fname");
1.334     albertel 2765: 		unlink("$fname.meta");
1.225     foxr     2766: 	    } else {
1.434     www      2767:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2768:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2769: 		my $transname="$fname.in.transfer";
1.365     albertel 2770: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2771: 		my $response;
1.537     raeburn  2772: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
                   2773: # for LWP request.
                   2774: 		my $request=new HTTP::Request('GET',"$remoteurl");
                   2775:                 $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2776: 		if ($response->is_error()) {
1.541     raeburn  2777:                     my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
                   2778:                     &devalidate_meta_cache($fname);
                   2779:                     if (-e $transname) {
                   2780:                         unlink($transname);
                   2781:                     }
                   2782:                     unlink($fname);
1.225     foxr     2783: 		    my $message=$response->status_line;
                   2784: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2785: 		} else {
                   2786: 		    if ($remoteurl!~/\.meta$/) {
1.537     raeburn  2787: 			my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2788:                         my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
                   2789: 			if ($mresponse->is_error()) {
                   2790: 			    unlink($fname.'.meta');
1.225     foxr     2791: 			}
                   2792: 		    }
1.434     www      2793:                     # we successfully transfered, copy file over to real name
1.225     foxr     2794: 		    rename($transname,$fname);
1.308     albertel 2795: 		    &devalidate_meta_cache($fname);
1.225     foxr     2796: 		}
                   2797: 	    }
                   2798: 	    &Reply( $client, "ok\n", $userinput);
                   2799: 	} else {
                   2800: 	    &Failure($client, "not_found\n", $userinput);
                   2801: 	}
                   2802:     } else {
                   2803: 	&Failure($client, "rejected\n", $userinput);
                   2804:     }
                   2805:     return 1;
                   2806: }
                   2807: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2808: 
1.308     albertel 2809: sub devalidate_meta_cache {
                   2810:     my ($url) = @_;
                   2811:     use Cache::Memcached;
                   2812:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2813:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2814:     $url =~ s-\.meta$--;
                   2815:     my $id = &escape('meta:'.$url);
                   2816:     $memcache->delete($id);
                   2817: }
                   2818: 
1.225     foxr     2819: #
1.226     foxr     2820: #   Fetch a user file from a remote server to the user's home directory
                   2821: #   userfiles subdir.
1.225     foxr     2822: # Parameters:
                   2823: #    $cmd      - The command that got us here.
                   2824: #    $tail     - Tail of the command (remaining parameters).
                   2825: #    $client   - File descriptor connected to client.
                   2826: # Returns
                   2827: #     0        - Requested to exit, caller should shut down.
                   2828: #     1        - Continue processing.
                   2829: #
                   2830: sub fetch_user_file_handler {
                   2831: 
                   2832:     my ($cmd, $tail, $client) = @_;
                   2833: 
                   2834:     my $userinput = "$cmd:$tail";
                   2835:     my $fname           = $tail;
1.232     foxr     2836:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2837:     my $udir=&propath($udom,$uname).'/userfiles';
                   2838:     unless (-e $udir) {
                   2839: 	mkdir($udir,0770); 
                   2840:     }
1.232     foxr     2841:     Debug("fetch user file for $fname");
1.225     foxr     2842:     if (-e $udir) {
                   2843: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2844: 
                   2845: 	# IF necessary, create the path right down to the file.
                   2846: 	# Note that any regular files in the way of this path are
                   2847: 	# wiped out to deal with some earlier folly of mine.
                   2848: 
1.267     raeburn  2849: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2850: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2851: 	}
                   2852: 
1.225     foxr     2853: 	my $destname=$udir.'/'.$ufile;
                   2854: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2855:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2856:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2857: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2858: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2859: 	my $response;
1.232     foxr     2860: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537     raeburn  2861: 	my $request=new HTTP::Request('GET',"$remoteurl");
                   2862:         my $verifycert = 1;
                   2863:         my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2864:         if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2865:             $verifycert = 0;
                   2866:         }
                   2867:         $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2868: 	if ($response->is_error()) {
                   2869: 	    unlink($transname);
                   2870: 	    my $message=$response->status_line;
                   2871: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2872: 	    &Failure($client, "failed\n", $userinput);
                   2873: 	} else {
1.232     foxr     2874: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2875: 	    if (!rename($transname,$destname)) {
                   2876: 		&logthis("Unable to move $transname to $destname");
                   2877: 		unlink($transname);
                   2878: 		&Failure($client, "failed\n", $userinput);
                   2879: 	    } else {
1.495     raeburn  2880:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2881:                     my ($major,$minor) = split(/\./,$clientversion);
                   2882:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2883:                         my $now = time;
                   2884:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2885:                         my $key = &escape('internal.contentchange');
                   2886:                         my $what = "$key=$now";
                   2887:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2888:                                                      &GDBM_WRCREAT(),"P",$what);
                   2889:                         if ($hashref) {
                   2890:                             $hashref->{$key}=$now;
                   2891:                             if (!&untie_user_hash($hashref)) {
                   2892:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2893:                                          "when updating internal.contentchange");
                   2894:                             }
                   2895:                         }
                   2896:                     }
                   2897:                 }
1.225     foxr     2898: 		&Reply($client, "ok\n", $userinput);
                   2899: 	    }
                   2900: 	}   
                   2901:     } else {
                   2902: 	&Failure($client, "not_home\n", $userinput);
                   2903:     }
                   2904:     return 1;
                   2905: }
                   2906: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2907: 
1.226     foxr     2908: #
                   2909: #   Remove a file from a user's home directory userfiles subdirectory.
                   2910: # Parameters:
                   2911: #    cmd   - the Lond request keyword that got us here.
                   2912: #    tail  - the part of the command past the keyword.
                   2913: #    client- File descriptor connected with the client.
                   2914: #
                   2915: # Returns:
                   2916: #    1    - Continue processing.
                   2917: sub remove_user_file_handler {
                   2918:     my ($cmd, $tail, $client) = @_;
                   2919: 
                   2920:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2921: 
                   2922:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2923:     if ($ufile =~m|/\.\./|) {
                   2924: 	# any files paths with /../ in them refuse 
                   2925: 	# to deal with
                   2926: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2927:     } else {
                   2928: 	my $udir = &propath($udom,$uname);
                   2929: 	if (-e $udir) {
                   2930: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2931: 	    if (-e $file) {
1.253     foxr     2932: 		#
                   2933: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2934: 		#   However it's possible the client wants a dir 
                   2935: 		#   removed, in which case rmdir is more appropriate.
                   2936: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2937: 		#
1.240     banghart 2938: 	        if (-f $file){
1.241     albertel 2939: 		    unlink($file);
1.520     raeburn  2940:                     # for html files remove the associated .bak file 
                   2941:                     # which may have been created by the editor.
                   2942:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2943:                         my $path = $1;
                   2944:                         if (-e $file.'.bak') {
                   2945:                             unlink($file.'.bak');
                   2946:                         }
                   2947:                     }
1.241     albertel 2948: 		} elsif(-d $file) {
                   2949: 		    rmdir($file);
1.240     banghart 2950: 		}
1.226     foxr     2951: 		if (-e $file) {
1.253     foxr     2952: 		    #  File is still there after we deleted it ?!?
                   2953: 
1.226     foxr     2954: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2955: 		} else {
                   2956: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2957: 		}
                   2958: 	    } else {
                   2959: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2960: 	    }
                   2961: 	} else {
                   2962: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2963: 	}
                   2964:     }
                   2965:     return 1;
                   2966: }
                   2967: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2968: 
1.236     albertel 2969: #
                   2970: #   make a directory in a user's home directory userfiles subdirectory.
                   2971: # Parameters:
                   2972: #    cmd   - the Lond request keyword that got us here.
                   2973: #    tail  - the part of the command past the keyword.
                   2974: #    client- File descriptor connected with the client.
                   2975: #
                   2976: # Returns:
                   2977: #    1    - Continue processing.
                   2978: sub mkdir_user_file_handler {
                   2979:     my ($cmd, $tail, $client) = @_;
                   2980: 
                   2981:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2982:     $dir=&unescape($dir);
                   2983:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2984:     if ($ufile =~m|/\.\./|) {
                   2985: 	# any files paths with /../ in them refuse 
                   2986: 	# to deal with
                   2987: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2988:     } else {
                   2989: 	my $udir = &propath($udom,$uname);
                   2990: 	if (-e $udir) {
1.264     albertel 2991: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2992: 	    if (!&mkpath($newdir)) {
                   2993: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2994: 	    }
1.264     albertel 2995: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2996: 	} else {
                   2997: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2998: 	}
                   2999:     }
                   3000:     return 1;
                   3001: }
                   3002: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   3003: 
1.237     albertel 3004: #
                   3005: #   rename a file in a user's home directory userfiles subdirectory.
                   3006: # Parameters:
                   3007: #    cmd   - the Lond request keyword that got us here.
                   3008: #    tail  - the part of the command past the keyword.
                   3009: #    client- File descriptor connected with the client.
                   3010: #
                   3011: # Returns:
                   3012: #    1    - Continue processing.
                   3013: sub rename_user_file_handler {
                   3014:     my ($cmd, $tail, $client) = @_;
                   3015: 
                   3016:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   3017:     $old=&unescape($old);
                   3018:     $new=&unescape($new);
                   3019:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   3020: 	# any files paths with /../ in them refuse to deal with
                   3021: 	&Failure($client, "refused\n", "$cmd:$tail");
                   3022:     } else {
                   3023: 	my $udir = &propath($udom,$uname);
                   3024: 	if (-e $udir) {
                   3025: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   3026: 	    my $newfile=$udir.'/userfiles/'.$new;
                   3027: 	    if (-e $newfile) {
                   3028: 		&Failure($client, "exists\n", "$cmd:$tail");
                   3029: 	    } elsif (! -e $oldfile) {
                   3030: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   3031: 	    } else {
                   3032: 		if (!rename($oldfile,$newfile)) {
                   3033: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   3034: 		} else {
                   3035: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   3036: 		}
                   3037: 	    }
                   3038: 	} else {
                   3039: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   3040: 	}
                   3041:     }
                   3042:     return 1;
                   3043: }
                   3044: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   3045: 
1.227     foxr     3046: #
1.382     albertel 3047: #  Checks if the specified user has an active session on the server
                   3048: #  return ok if so, not_found if not
                   3049: #
                   3050: # Parameters:
                   3051: #   cmd      - The request keyword that dispatched to tus.
                   3052: #   tail     - The tail of the request (colon separated parameters).
                   3053: #   client   - Filehandle open on the client.
                   3054: # Return:
                   3055: #    1.
                   3056: sub user_has_session_handler {
                   3057:     my ($cmd, $tail, $client) = @_;
                   3058: 
                   3059:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3060:     
                   3061:     opendir(DIR,$perlvar{'lonIDsDir'});
                   3062:     my $filename;
                   3063:     while ($filename=readdir(DIR)) {
                   3064: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   3065:     }
                   3066:     if ($filename) {
                   3067: 	&Reply($client, "ok\n", "$cmd:$tail");
                   3068:     } else {
                   3069: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   3070:     }
                   3071:     return 1;
                   3072: 
                   3073: }
                   3074: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   3075: 
1.560     raeburn  3076: sub del_usersession_handler {
                   3077:     my ($cmd, $tail, $client) = @_;
                   3078: 
                   3079:     my $result;
                   3080:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   3081:     if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
                   3082:         my $lonidsdir = $perlvar{'lonIDsDir'};
                   3083:         if (-d $lonidsdir) {
                   3084:             if (opendir(DIR,$lonidsdir)) {
                   3085:                 my $filename;
                   3086:                 while ($filename=readdir(DIR)) {
                   3087:                     if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
                   3088:                         if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
                   3089:                                 &GDBM_READER(),0640)) {
                   3090:                             my $linkedfile;
                   3091:                             if (exists($oldenv{'user.linkedenv'})) {
                   3092:                                 $linkedfile = $oldenv{'user.linkedenv'};
                   3093:                             }
                   3094:                             untie(%oldenv);
                   3095:                             $result = unlink("$lonidsdir/$filename");
                   3096:                             if ($result) {
                   3097:                                 if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
                   3098:                                     if (-l "$lonidsdir/$linkedfile.id") {
                   3099:                                         unlink("$lonidsdir/$linkedfile.id");
                   3100:                                     }
                   3101:                                 }
                   3102:                             }
                   3103:                         } else {
                   3104:                             $result = unlink("$lonidsdir/$filename");
                   3105:                         }
                   3106:                         last;
                   3107:                     }
                   3108:                 }
                   3109:             }
                   3110:         }
                   3111:         if ($result == 1) {
                   3112:             &Reply($client, "$result\n", "$cmd:$tail");
                   3113:         } else {
                   3114:             &Reply($client, "not_found\n", "$cmd:$tail");
                   3115:         }
                   3116:     } else {
                   3117:         &Failure($client, "invalid_user\n", "$cmd:$tail");
                   3118:     }
                   3119:     return 1;
                   3120: }
                   3121: 
                   3122: &register_handler("delusersession", \&del_usersession_handler, 0,1,0);
                   3123: 
1.382     albertel 3124: #
1.263     albertel 3125: #  Authenticate access to a user file by checking that the token the user's 
                   3126: #  passed also exists in their session file
1.227     foxr     3127: #
                   3128: # Parameters:
                   3129: #   cmd      - The request keyword that dispatched to tus.
                   3130: #   tail     - The tail of the request (colon separated parameters).
                   3131: #   client   - Filehandle open on the client.
                   3132: # Return:
                   3133: #    1.
                   3134: sub token_auth_user_file_handler {
                   3135:     my ($cmd, $tail, $client) = @_;
                   3136: 
                   3137:     my ($fname, $session) = split(/:/, $tail);
                   3138:     
                   3139:     chomp($session);
1.393     raeburn  3140:     my $reply="non_auth";
1.343     albertel 3141:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   3142:     if (open(ENVIN,"$file")) {
1.332     albertel 3143: 	flock(ENVIN,LOCK_SH);
1.343     albertel 3144: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   3145: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  3146: 	    $reply="ok";
1.343     albertel 3147: 	} else {
                   3148: 	    foreach my $envname (keys(%disk_env)) {
                   3149: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  3150: 		    $reply="ok";
1.343     albertel 3151: 		    last;
                   3152: 		}
                   3153: 	    }
1.227     foxr     3154: 	}
1.343     albertel 3155: 	untie(%disk_env);
1.227     foxr     3156: 	close(ENVIN);
1.387     albertel 3157: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     3158:     } else {
                   3159: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   3160:     }
                   3161:     return 1;
                   3162: 
                   3163: }
                   3164: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     3165: 
                   3166: #
                   3167: #   Unsubscribe from a resource.
                   3168: #
                   3169: # Parameters:
                   3170: #    $cmd      - The command that got us here.
                   3171: #    $tail     - Tail of the command (remaining parameters).
                   3172: #    $client   - File descriptor connected to client.
                   3173: # Returns
                   3174: #     0        - Requested to exit, caller should shut down.
                   3175: #     1        - Continue processing.
                   3176: #
                   3177: sub unsubscribe_handler {
                   3178:     my ($cmd, $tail, $client) = @_;
                   3179: 
                   3180:     my $userinput= "$cmd:$tail";
                   3181:     
                   3182:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   3183: 
                   3184:     &Debug("Unsubscribing $fname");
                   3185:     if (-e $fname) {
                   3186: 	&Debug("Exists");
                   3187: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   3188:     } else {
                   3189: 	&Failure($client, "not_found\n", $userinput);
                   3190:     }
                   3191:     return 1;
                   3192: }
                   3193: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 3194: 
1.230     foxr     3195: #   Subscribe to a resource
                   3196: #
                   3197: # Parameters:
                   3198: #    $cmd      - The command that got us here.
                   3199: #    $tail     - Tail of the command (remaining parameters).
                   3200: #    $client   - File descriptor connected to client.
                   3201: # Returns
                   3202: #     0        - Requested to exit, caller should shut down.
                   3203: #     1        - Continue processing.
                   3204: #
                   3205: sub subscribe_handler {
                   3206:     my ($cmd, $tail, $client)= @_;
                   3207: 
                   3208:     my $userinput  = "$cmd:$tail";
                   3209: 
                   3210:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   3211: 
                   3212:     return 1;
                   3213: }
                   3214: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   3215: 
                   3216: #
1.379     albertel 3217: #   Determine the latest version of a resource (it looks for the highest
                   3218: #   past version and then returns that +1)
1.230     foxr     3219: #
                   3220: # Parameters:
                   3221: #    $cmd      - The command that got us here.
                   3222: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 3223: #                 (Should consist of an absolute path to a file)
1.230     foxr     3224: #    $client   - File descriptor connected to client.
                   3225: # Returns
                   3226: #     0        - Requested to exit, caller should shut down.
                   3227: #     1        - Continue processing.
                   3228: #
                   3229: sub current_version_handler {
                   3230:     my ($cmd, $tail, $client) = @_;
                   3231: 
                   3232:     my $userinput= "$cmd:$tail";
                   3233:    
                   3234:     my $fname   = $tail;
                   3235:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   3236:     return 1;
                   3237: 
                   3238: }
                   3239: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   3240: 
                   3241: #  Make an entry in a user's activity log.
                   3242: #
                   3243: # Parameters:
                   3244: #    $cmd      - The command that got us here.
                   3245: #    $tail     - Tail of the command (remaining parameters).
                   3246: #    $client   - File descriptor connected to client.
                   3247: # Returns
                   3248: #     0        - Requested to exit, caller should shut down.
                   3249: #     1        - Continue processing.
                   3250: #
                   3251: sub activity_log_handler {
                   3252:     my ($cmd, $tail, $client) = @_;
                   3253: 
                   3254: 
                   3255:     my $userinput= "$cmd:$tail";
                   3256: 
                   3257:     my ($udom,$uname,$what)=split(/:/,$tail);
                   3258:     chomp($what);
                   3259:     my $proname=&propath($udom,$uname);
                   3260:     my $now=time;
                   3261:     my $hfh;
                   3262:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   3263: 	print $hfh "$now:$clientname:$what\n";
                   3264: 	&Reply( $client, "ok\n", $userinput); 
                   3265:     } else {
                   3266: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   3267: 		 ."while attempting log\n", 
                   3268: 		 $userinput);
                   3269:     }
                   3270: 
                   3271:     return 1;
                   3272: }
1.263     albertel 3273: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     3274: 
                   3275: #
                   3276: #   Put a namespace entry in a user profile hash.
                   3277: #   My druthers would be for this to be an encrypted interaction too.
                   3278: #   anything that might be an inadvertent covert channel about either
                   3279: #   user authentication or user personal information....
                   3280: #
                   3281: # Parameters:
                   3282: #    $cmd      - The command that got us here.
                   3283: #    $tail     - Tail of the command (remaining parameters).
                   3284: #    $client   - File descriptor connected to client.
                   3285: # Returns
                   3286: #     0        - Requested to exit, caller should shut down.
                   3287: #     1        - Continue processing.
                   3288: #
                   3289: sub put_user_profile_entry {
                   3290:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     3291: 
1.230     foxr     3292:     my $userinput = "$cmd:$tail";
                   3293:     
1.242     raeburn  3294:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     3295:     if ($namespace ne 'roles') {
                   3296: 	chomp($what);
                   3297: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3298: 				  &GDBM_WRCREAT(),"P",$what);
                   3299: 	if($hashref) {
                   3300: 	    my @pairs=split(/\&/,$what);
                   3301: 	    foreach my $pair (@pairs) {
                   3302: 		my ($key,$value)=split(/=/,$pair);
                   3303: 		$hashref->{$key}=$value;
                   3304: 	    }
1.311     albertel 3305: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3306: 		&Reply( $client, "ok\n", $userinput);
                   3307: 	    } else {
                   3308: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3309: 			"while attempting put\n", 
                   3310: 			$userinput);
                   3311: 	    }
                   3312: 	} else {
1.316     albertel 3313: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     3314: 		     "while attempting put\n", $userinput);
                   3315: 	}
                   3316:     } else {
                   3317:         &Failure( $client, "refused\n", $userinput);
                   3318:     }
                   3319:     
                   3320:     return 1;
                   3321: }
                   3322: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   3323: 
1.283     albertel 3324: #   Put a piece of new data in hash, returns error if entry already exists
                   3325: # Parameters:
                   3326: #    $cmd      - The command that got us here.
                   3327: #    $tail     - Tail of the command (remaining parameters).
                   3328: #    $client   - File descriptor connected to client.
                   3329: # Returns
                   3330: #     0        - Requested to exit, caller should shut down.
                   3331: #     1        - Continue processing.
                   3332: #
                   3333: sub newput_user_profile_entry {
                   3334:     my ($cmd, $tail, $client)  = @_;
                   3335: 
                   3336:     my $userinput = "$cmd:$tail";
                   3337: 
                   3338:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3339:     if ($namespace eq 'roles') {
                   3340:         &Failure( $client, "refused\n", $userinput);
                   3341: 	return 1;
                   3342:     }
                   3343: 
                   3344:     chomp($what);
                   3345: 
                   3346:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3347: 				 &GDBM_WRCREAT(),"N",$what);
                   3348:     if(!$hashref) {
1.316     albertel 3349: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3350: 		  "while attempting put\n", $userinput);
                   3351: 	return 1;
                   3352:     }
                   3353: 
                   3354:     my @pairs=split(/\&/,$what);
                   3355:     foreach my $pair (@pairs) {
                   3356: 	my ($key,$value)=split(/=/,$pair);
                   3357: 	if (exists($hashref->{$key})) {
1.513     raeburn  3358:             if (!&untie_user_hash($hashref)) {
                   3359:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3360:                          "while attempting newput - early out as key exists");
                   3361:             }
                   3362:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3363:             return 1;
1.283     albertel 3364: 	}
                   3365:     }
                   3366: 
                   3367:     foreach my $pair (@pairs) {
                   3368: 	my ($key,$value)=split(/=/,$pair);
                   3369: 	$hashref->{$key}=$value;
                   3370:     }
                   3371: 
1.311     albertel 3372:     if (&untie_user_hash($hashref)) {
1.283     albertel 3373: 	&Reply( $client, "ok\n", $userinput);
                   3374:     } else {
                   3375: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3376: 		 "while attempting put\n", 
                   3377: 		 $userinput);
                   3378:     }
                   3379:     return 1;
                   3380: }
                   3381: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3382: 
1.230     foxr     3383: # 
                   3384: #   Increment a profile entry in the user history file.
                   3385: #   The history contains keyword value pairs.  In this case,
                   3386: #   The value itself is a pair of numbers.  The first, the current value
                   3387: #   the second an increment that this function applies to the current
                   3388: #   value.
                   3389: #
                   3390: # Parameters:
                   3391: #    $cmd      - The command that got us here.
                   3392: #    $tail     - Tail of the command (remaining parameters).
                   3393: #    $client   - File descriptor connected to client.
                   3394: # Returns
                   3395: #     0        - Requested to exit, caller should shut down.
                   3396: #     1        - Continue processing.
                   3397: #
                   3398: sub increment_user_value_handler {
                   3399:     my ($cmd, $tail, $client) = @_;
                   3400:     
                   3401:     my $userinput   = "$cmd:$tail";
                   3402:     
                   3403:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3404:     if ($namespace ne 'roles') {
                   3405:         chomp($what);
                   3406: 	my $hashref = &tie_user_hash($udom, $uname,
                   3407: 				     $namespace, &GDBM_WRCREAT(),
                   3408: 				     "P",$what);
                   3409: 	if ($hashref) {
                   3410: 	    my @pairs=split(/\&/,$what);
                   3411: 	    foreach my $pair (@pairs) {
                   3412: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3413:                 $value = &unescape($value);
1.230     foxr     3414: 		# We could check that we have a number...
                   3415: 		if (! defined($value) || $value eq '') {
                   3416: 		    $value = 1;
                   3417: 		}
                   3418: 		$hashref->{$key}+=$value;
1.284     raeburn  3419:                 if ($namespace eq 'nohist_resourcetracker') {
                   3420:                     if ($hashref->{$key} < 0) {
                   3421:                         $hashref->{$key} = 0;
                   3422:                     }
                   3423:                 }
1.230     foxr     3424: 	    }
1.311     albertel 3425: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3426: 		&Reply( $client, "ok\n", $userinput);
                   3427: 	    } else {
                   3428: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3429: 			 "while attempting inc\n", $userinput);
                   3430: 	    }
                   3431: 	} else {
                   3432: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3433: 		     "while attempting inc\n", $userinput);
                   3434: 	}
                   3435:     } else {
                   3436: 	&Failure($client, "refused\n", $userinput);
                   3437:     }
                   3438:     
                   3439:     return 1;
                   3440: }
                   3441: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3442: 
                   3443: #
                   3444: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3445: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3446: #   for a person grants the permissions packaged with that role
                   3447: #   to that user when the role is selected.
                   3448: #
                   3449: # Parameters:
                   3450: #    $cmd       - The command string (rolesput).
                   3451: #    $tail      - The remainder of the request line.  For rolesput this
                   3452: #                 consists of a colon separated list that contains:
                   3453: #                 The domain and user that is granting the role (logged).
                   3454: #                 The domain and user that is getting the role.
                   3455: #                 The roles being granted as a set of & separated pairs.
                   3456: #                 each pair a key value pair.
                   3457: #    $client    - File descriptor connected to the client.
                   3458: # Returns:
                   3459: #     0         - If the daemon should exit
                   3460: #     1         - To continue processing.
                   3461: #
                   3462: #
                   3463: sub roles_put_handler {
                   3464:     my ($cmd, $tail, $client) = @_;
                   3465: 
                   3466:     my $userinput  = "$cmd:$tail";
                   3467: 
                   3468:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3469:     
                   3470: 
                   3471:     my $namespace='roles';
                   3472:     chomp($what);
                   3473:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3474: 				 &GDBM_WRCREAT(), "P",
                   3475: 				 "$exedom:$exeuser:$what");
                   3476:     #
                   3477:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3478:     #  handle is open for the minimal amount of time.  Since the flush
                   3479:     #  is done on close this improves the chances the log will be an un-
                   3480:     #  corrupted ordered thing.
                   3481:     if ($hashref) {
1.261     foxr     3482: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3483: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3484: 	$auth_type = $auth_type.":";
1.230     foxr     3485: 	my @pairs=split(/\&/,$what);
                   3486: 	foreach my $pair (@pairs) {
                   3487: 	    my ($key,$value)=split(/=/,$pair);
                   3488: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3489: 			       $auth_type);
1.230     foxr     3490: 	    $hashref->{$key}=$value;
                   3491: 	}
1.311     albertel 3492: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3493: 	    &Reply($client, "ok\n", $userinput);
                   3494: 	} else {
                   3495: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3496: 		     "while attempting rolesput\n", $userinput);
                   3497: 	}
                   3498:     } else {
                   3499: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3500: 		 "while attempting rolesput\n", $userinput);
                   3501:     }
                   3502:     return 1;
                   3503: }
                   3504: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3505: 
                   3506: #
1.231     foxr     3507: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3508: #  a permissions package associated with the role from the user's profile.
                   3509: #
                   3510: # Parameters:
                   3511: #     $cmd                 - The command (rolesdel)
                   3512: #     $tail                - The remainder of the request line. This consists
                   3513: #                             of:
                   3514: #                             The domain and user requesting the change (logged)
                   3515: #                             The domain and user being changed.
                   3516: #                             The roles being revoked.  These are shipped to us
                   3517: #                             as a bunch of & separated role name keywords.
                   3518: #     $client              - The file handle open on the client.
                   3519: # Returns:
                   3520: #     1                    - Continue processing
                   3521: #     0                    - Exit.
                   3522: #
                   3523: sub roles_delete_handler {
                   3524:     my ($cmd, $tail, $client)  = @_;
                   3525: 
                   3526:     my $userinput    = "$cmd:$tail";
                   3527:    
                   3528:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3529:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3530: 	   "what = ".$what);
                   3531:     my $namespace='roles';
                   3532:     chomp($what);
                   3533:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3534: 				 &GDBM_WRCREAT(), "D",
                   3535: 				 "$exedom:$exeuser:$what");
                   3536:     
                   3537:     if ($hashref) {
                   3538: 	my @rolekeys=split(/\&/,$what);
                   3539: 	
                   3540: 	foreach my $key (@rolekeys) {
                   3541: 	    delete $hashref->{$key};
                   3542: 	}
1.315     albertel 3543: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3544: 	    &Reply($client, "ok\n", $userinput);
                   3545: 	} else {
                   3546: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3547: 		     "while attempting rolesdel\n", $userinput);
                   3548: 	}
                   3549:     } else {
                   3550:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3551: 		 "while attempting rolesdel\n", $userinput);
                   3552:     }
                   3553:     
                   3554:     return 1;
                   3555: }
                   3556: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3557: 
                   3558: # Unencrypted get from a user's profile database.  See 
                   3559: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3560: # This function retrieves a keyed item from a specific named database in the
                   3561: # user's directory.
                   3562: #
                   3563: # Parameters:
                   3564: #   $cmd             - Command request keyword (get).
                   3565: #   $tail            - Tail of the command.  This is a colon separated list
                   3566: #                      consisting of the domain and username that uniquely
                   3567: #                      identifies the profile,
                   3568: #                      The 'namespace' which selects the gdbm file to 
                   3569: #                      do the lookup in, 
                   3570: #                      & separated list of keys to lookup.  Note that
                   3571: #                      the values are returned as an & separated list too.
                   3572: #   $client          - File descriptor open on the client.
                   3573: # Returns:
                   3574: #   1       - Continue processing.
                   3575: #   0       - Exit.
                   3576: #
                   3577: sub get_profile_entry {
                   3578:     my ($cmd, $tail, $client) = @_;
                   3579: 
                   3580:     my $userinput= "$cmd:$tail";
                   3581:    
                   3582:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3583:     chomp($what);
1.255     foxr     3584: 
1.390     raeburn  3585: 
1.255     foxr     3586:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3587:     my ($first) = split(/:/,$replystring);
                   3588:     if($first ne "error") {
1.387     albertel 3589: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3590:     } else {
1.255     foxr     3591: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3592:     }
                   3593:     return 1;
1.255     foxr     3594: 
                   3595: 
1.231     foxr     3596: }
                   3597: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3598: 
                   3599: #
                   3600: #  Process the encrypted get request.  Note that the request is sent
                   3601: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3602: #  information about the sensitive keys is given to the snooper.  Just not
                   3603: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3604: #  know these I'd snoop for the egets. Get the profile item names from them
                   3605: #  and then issue a get for them since there's no enforcement of the
                   3606: #  requirement of an encrypted get for particular profile items.  If I
                   3607: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3608: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3609: #  that would prevent any covert channel snooping.
                   3610: #
                   3611: #  Parameters:
                   3612: #     $cmd               - Command keyword of request (eget).
1.536     raeburn  3613: #     $tail              - Tail of the command.  See GetProfileEntry
                   3614: #                          for more information about this.
1.231     foxr     3615: #     $client            - File open on the client.
                   3616: #  Returns:
                   3617: #     1      - Continue processing
                   3618: #     0      - server should exit.
                   3619: sub get_profile_entry_encrypted {
                   3620:     my ($cmd, $tail, $client) = @_;
                   3621: 
                   3622:     my $userinput = "$cmd:$tail";
                   3623:    
1.339     albertel 3624:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3625:     chomp($what);
1.255     foxr     3626:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3627:     my ($first) = split(/:/, $qresult);
                   3628:     if($first ne "error") {
                   3629: 	
                   3630: 	if ($cipher) {
                   3631: 	    my $cmdlength=length($qresult);
                   3632: 	    $qresult.="         ";
                   3633: 	    my $encqresult='';
                   3634: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3635: 		$encqresult.= unpack("H16", 
                   3636: 				     $cipher->encrypt(substr($qresult,
                   3637: 							     $encidx,
                   3638: 							     8)));
                   3639: 	    }
                   3640: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3641: 	} else {
1.231     foxr     3642: 		&Failure( $client, "error:no_key\n", $userinput);
                   3643: 	    }
                   3644:     } else {
1.255     foxr     3645: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3646: 
1.231     foxr     3647:     }
                   3648:     
                   3649:     return 1;
                   3650: }
1.255     foxr     3651: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3652: 
1.231     foxr     3653: #
                   3654: #   Deletes a key in a user profile database.
                   3655: #   
                   3656: #   Parameters:
                   3657: #       $cmd                  - Command keyword (del).
                   3658: #       $tail                 - Command tail.  IN this case a colon
                   3659: #                               separated list containing:
                   3660: #                               The domain and user that identifies uniquely
                   3661: #                               the identity of the user.
                   3662: #                               The profile namespace (name of the profile
                   3663: #                               database file).
                   3664: #                               & separated list of keywords to delete.
                   3665: #       $client              - File open on client socket.
                   3666: # Returns:
                   3667: #     1   - Continue processing
                   3668: #     0   - Exit server.
                   3669: #
                   3670: #
                   3671: sub delete_profile_entry {
                   3672:     my ($cmd, $tail, $client) = @_;
                   3673: 
                   3674:     my $userinput = "cmd:$tail";
                   3675: 
                   3676:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3677:     chomp($what);
                   3678:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3679: 				 &GDBM_WRCREAT(),
                   3680: 				 "D",$what);
                   3681:     if ($hashref) {
                   3682:         my @keys=split(/\&/,$what);
                   3683: 	foreach my $key (@keys) {
                   3684: 	    delete($hashref->{$key});
                   3685: 	}
1.315     albertel 3686: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3687: 	    &Reply($client, "ok\n", $userinput);
                   3688: 	} else {
                   3689: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3690: 		    "while attempting del\n", $userinput);
                   3691: 	}
                   3692:     } else {
                   3693: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3694: 		 "while attempting del\n", $userinput);
                   3695:     }
                   3696:     return 1;
                   3697: }
                   3698: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3699: 
1.231     foxr     3700: #
                   3701: #  List the set of keys that are defined in a profile database file.
                   3702: #  A successful reply from this will contain an & separated list of
                   3703: #  the keys. 
                   3704: # Parameters:
                   3705: #     $cmd              - Command request (keys).
                   3706: #     $tail             - Remainder of the request, a colon separated
                   3707: #                         list containing domain/user that identifies the
                   3708: #                         user being queried, and the database namespace
                   3709: #                         (database filename essentially).
                   3710: #     $client           - File open on the client.
                   3711: #  Returns:
                   3712: #    1    - Continue processing.
                   3713: #    0    - Exit the server.
                   3714: #
                   3715: sub get_profile_keys {
                   3716:     my ($cmd, $tail, $client) = @_;
                   3717: 
                   3718:     my $userinput = "$cmd:$tail";
                   3719: 
                   3720:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3721:     my $qresult='';
                   3722:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3723: 				  &GDBM_READER());
                   3724:     if ($hashref) {
                   3725: 	foreach my $key (keys %$hashref) {
                   3726: 	    $qresult.="$key&";
                   3727: 	}
1.315     albertel 3728: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3729: 	    $qresult=~s/\&$//;
1.387     albertel 3730: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3731: 	} else {
                   3732: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3733: 		    "while attempting keys\n", $userinput);
                   3734: 	}
                   3735:     } else {
                   3736: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3737: 		 "while attempting keys\n", $userinput);
                   3738:     }
                   3739:    
                   3740:     return 1;
                   3741: }
                   3742: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3743: 
                   3744: #
                   3745: #   Dump the contents of a user profile database.
                   3746: #   Note that this constitutes a very large covert channel too since
                   3747: #   the dump will return sensitive information that is not encrypted.
                   3748: #   The naive security assumption is that the session negotiation ensures
                   3749: #   our client is trusted and I don't believe that's assured at present.
                   3750: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3751: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3752: # 
                   3753: #  Parameters:
                   3754: #     $cmd           - The command request keyword (currentdump).
                   3755: #     $tail          - Remainder of the request, consisting of a colon
                   3756: #                      separated list that has the domain/username and
                   3757: #                      the namespace to dump (database file).
                   3758: #     $client        - file open on the remote client.
                   3759: # Returns:
                   3760: #     1    - Continue processing.
                   3761: #     0    - Exit the server.
                   3762: #
                   3763: sub dump_profile_database {
                   3764:     my ($cmd, $tail, $client) = @_;
                   3765: 
1.494     droeschl 3766:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3767: 
                   3768:     if ($res =~ /^error:/) {
                   3769:         Failure($client, \$res, "$cmd:$tail");
                   3770:     } else {
                   3771:         Reply($client, \$res, "$cmd:$tail");
                   3772:     }
                   3773: 
                   3774:     return 1;  
                   3775: 
                   3776:     #TODO remove 
1.231     foxr     3777:     my $userinput = "$cmd:$tail";
                   3778:    
                   3779:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3780:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3781: 				 &GDBM_READER());
                   3782:     if ($hashref) {
                   3783: 	# Structure of %data:
                   3784: 	# $data{$symb}->{$parameter}=$value;
                   3785: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3786: 	# since $parameter will be unescaped, we do not
                   3787:  	# have to worry about silly parameter names...
                   3788: 	
                   3789:         my $qresult='';
                   3790: 	my %data = ();                     # A hash of anonymous hashes..
                   3791: 	while (my ($key,$value) = each(%$hashref)) {
                   3792: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3793: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3794: 	    next if (exists($data{$symb}) && 
                   3795: 		     exists($data{$symb}->{$param}) &&
                   3796: 		     $data{$symb}->{'v.'.$param} > $v);
                   3797: 	    $data{$symb}->{$param}=$value;
                   3798: 	    $data{$symb}->{'v.'.$param}=$v;
                   3799: 	}
1.311     albertel 3800: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3801: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3802: 		while(my ($param,$value) = each (%$param_hash)){
                   3803: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3804: 		    #
                   3805: 		    #   Just dump the symb=value pairs separated by &
                   3806: 		    #
                   3807: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3808: 		}
                   3809: 	    }
                   3810: 	    chop($qresult);
1.387     albertel 3811: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3812: 	} else {
                   3813: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3814: 		     "while attempting currentdump\n", $userinput);
                   3815: 	}
                   3816:     } else {
                   3817: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3818: 		"while attempting currentdump\n", $userinput);
                   3819:     }
                   3820: 
                   3821:     return 1;
                   3822: }
                   3823: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3824: 
                   3825: #
                   3826: #   Dump a profile database with an optional regular expression
                   3827: #   to match against the keys.  In this dump, no effort is made
                   3828: #   to separate symb from version information. Presumably the
                   3829: #   databases that are dumped by this command are of a different
                   3830: #   structure.  Need to look at this and improve the documentation of
                   3831: #   both this and the currentdump handler.
                   3832: # Parameters:
                   3833: #    $cmd                     - The command keyword.
                   3834: #    $tail                    - All of the characters after the $cmd:
                   3835: #                               These are expected to be a colon
                   3836: #                               separated list containing:
                   3837: #                               domain/user - identifying the user.
                   3838: #                               namespace   - identifying the database.
                   3839: #                               regexp      - optional regular expression
                   3840: #                                             that is matched against
                   3841: #                                             database keywords to do
                   3842: #                                             selective dumps.
1.488     raeburn  3843: #                               range       - optional range of entries
                   3844: #                                             e.g., 10-20 would return the
                   3845: #                                             10th to 19th items, etc.  
1.231     foxr     3846: #   $client                   - Channel open on the client.
                   3847: # Returns:
                   3848: #    1    - Continue processing.
                   3849: # Side effects:
                   3850: #    response is written to $client.
                   3851: #
                   3852: sub dump_with_regexp {
                   3853:     my ($cmd, $tail, $client) = @_;
                   3854: 
1.494     droeschl 3855:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3856:     
                   3857:     if ($res =~ /^error:/) {
                   3858:         Failure($client, \$res, "$cmd:$tail");
                   3859:     } else {
                   3860:         Reply($client, \$res, "$cmd:$tail");
                   3861:     }
1.231     foxr     3862: 
                   3863:     return 1;
                   3864: }
                   3865: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3866: 
1.568     raeburn  3867: #
                   3868: #  Process the encrypted dump request. Original call should
                   3869: #  be from lonnet::dump() with seventh arg ($encrypt) set to
                   3870: #  1, to ensure that both request and response are encrypted.
                   3871: #
                   3872: #  Parameters:
                   3873: #     $cmd               - Command keyword of request (edump).
                   3874: #     $tail              - Tail of the command.
                   3875: #                          See &dump_with_regexp for more
                   3876: #                          information about this.
                   3877: #     $client            - File open on the client.
                   3878: #  Returns:
                   3879: #     1      - Continue processing
                   3880: #     0      - server should exit.
                   3881: #
                   3882: 
                   3883: sub encrypted_dump_with_regexp {
                   3884:     my ($cmd, $tail, $client) = @_;
                   3885:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
                   3886: 
                   3887:     if ($res =~ /^error:/) {
                   3888:         Failure($client, \$res, "$cmd:$tail");
                   3889:     } else {
                   3890:         if ($cipher) {
                   3891:             my $cmdlength=length($res);
                   3892:             $res.="         ";
                   3893:             my $encres='';
                   3894:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3895:                 $encres.= unpack("H16",
                   3896:                                  $cipher->encrypt(substr($res,
                   3897:                                                          $encidx,
                   3898:                                                          8)));
                   3899:             }
                   3900:             &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
                   3901:         } else {
                   3902:             &Failure( $client, "error:no_key\n","$cmd:$tail");
                   3903:         }
                   3904:     }
                   3905: }
                   3906: &register_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
                   3907: 
1.231     foxr     3908: #  Store a set of key=value pairs associated with a versioned name.
                   3909: #
                   3910: #  Parameters:
                   3911: #    $cmd                - Request command keyword.
                   3912: #    $tail               - Tail of the request.  This is a colon
                   3913: #                          separated list containing:
                   3914: #                          domain/user - User and authentication domain.
                   3915: #                          namespace   - Name of the database being modified
                   3916: #                          rid         - Resource keyword to modify.
                   3917: #                          what        - new value associated with rid.
1.512     raeburn  3918: #                          laststore   - (optional) version=timestamp
                   3919: #                                        for most recent transaction for rid
                   3920: #                                        in namespace, when cstore was called
1.231     foxr     3921: #
                   3922: #    $client             - Socket open on the client.
                   3923: #
                   3924: #
                   3925: #  Returns:
                   3926: #      1 (keep on processing).
                   3927: #  Side-Effects:
                   3928: #    Writes to the client
1.512     raeburn  3929: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3930: #    in the tail of the request, and the version number for the last transaction
                   3931: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3932: #    is the number of store evevnts recorded for rid in namespace since
                   3933: #    lonnet::store() was called by the client.
                   3934: #
1.231     foxr     3935: sub store_handler {
                   3936:     my ($cmd, $tail, $client) = @_;
                   3937:  
                   3938:     my $userinput = "$cmd:$tail";
1.512     raeburn  3939:     chomp($tail);
                   3940:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3941:     if ($namespace ne 'roles') {
                   3942: 
                   3943: 	my @pairs=split(/\&/,$what);
                   3944: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3945: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3946: 				       "$rid:$what");
                   3947: 	if ($hashref) {
                   3948: 	    my $now = time;
1.512     raeburn  3949:             my $numtrans;
                   3950:             if ($laststore) {
                   3951:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3952:                 my ($lastversion,$lasttime) = (0,0);
                   3953:                 $lastversion = $hashref->{"version:$rid"};
                   3954:                 if ($lastversion) {
                   3955:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3956:                 }
                   3957:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3958:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3959:                         $numtrans = $lastversion - $previousversion;
                   3960:                     }
                   3961:                 } elsif ($lastversion) {
                   3962:                     $numtrans = $lastversion;
                   3963:                 }
                   3964:                 if ($numtrans) {
                   3965:                     $numtrans =~ s/D//g;
                   3966:                 }
                   3967:             }
1.231     foxr     3968: 	    $hashref->{"version:$rid"}++;
                   3969: 	    my $version=$hashref->{"version:$rid"};
                   3970: 	    my $allkeys=''; 
                   3971: 	    foreach my $pair (@pairs) {
                   3972: 		my ($key,$value)=split(/=/,$pair);
                   3973: 		$allkeys.=$key.':';
                   3974: 		$hashref->{"$version:$rid:$key"}=$value;
                   3975: 	    }
                   3976: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3977: 	    $allkeys.='timestamp';
                   3978: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3979: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3980:                 my $msg = 'ok';
                   3981:                 if ($numtrans) {
                   3982:                     $msg = 'delay:'.$numtrans;
                   3983:                 }
                   3984: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3985: 	    } else {
                   3986: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3987: 			"while attempting store\n", $userinput);
                   3988: 	    }
                   3989: 	} else {
                   3990: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3991: 		     "while attempting store\n", $userinput);
                   3992: 	}
                   3993:     } else {
                   3994: 	&Failure($client, "refused\n", $userinput);
                   3995:     }
                   3996: 
                   3997:     return 1;
                   3998: }
                   3999: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 4000: 
1.323     albertel 4001: #  Modify a set of key=value pairs associated with a versioned name.
                   4002: #
                   4003: #  Parameters:
                   4004: #    $cmd                - Request command keyword.
                   4005: #    $tail               - Tail of the request.  This is a colon
                   4006: #                          separated list containing:
                   4007: #                          domain/user - User and authentication domain.
                   4008: #                          namespace   - Name of the database being modified
                   4009: #                          rid         - Resource keyword to modify.
                   4010: #                          v           - Version item to modify
                   4011: #                          what        - new value associated with rid.
                   4012: #
                   4013: #    $client             - Socket open on the client.
                   4014: #
                   4015: #
                   4016: #  Returns:
                   4017: #      1 (keep on processing).
                   4018: #  Side-Effects:
                   4019: #    Writes to the client
                   4020: sub putstore_handler {
                   4021:     my ($cmd, $tail, $client) = @_;
                   4022:  
                   4023:     my $userinput = "$cmd:$tail";
                   4024: 
                   4025:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   4026:     if ($namespace ne 'roles') {
                   4027: 
                   4028: 	chomp($what);
                   4029: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   4030: 				       &GDBM_WRCREAT(), "M",
                   4031: 				       "$rid:$v:$what");
                   4032: 	if ($hashref) {
                   4033: 	    my $now = time;
                   4034: 	    my %data = &hash_extract($what);
                   4035: 	    my @allkeys;
                   4036: 	    while (my($key,$value) = each(%data)) {
                   4037: 		push(@allkeys,$key);
                   4038: 		$hashref->{"$v:$rid:$key"} = $value;
                   4039: 	    }
                   4040: 	    my $allkeys = join(':',@allkeys);
                   4041: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   4042: 
                   4043: 	    if (&untie_user_hash($hashref)) {
                   4044: 		&Reply($client, "ok\n", $userinput);
                   4045: 	    } else {
                   4046: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4047: 			"while attempting store\n", $userinput);
                   4048: 	    }
                   4049: 	} else {
                   4050: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4051: 		     "while attempting store\n", $userinput);
                   4052: 	}
                   4053:     } else {
                   4054: 	&Failure($client, "refused\n", $userinput);
                   4055:     }
                   4056: 
                   4057:     return 1;
                   4058: }
                   4059: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   4060: 
                   4061: sub hash_extract {
                   4062:     my ($str)=@_;
                   4063:     my %hash;
                   4064:     foreach my $pair (split(/\&/,$str)) {
                   4065: 	my ($key,$value)=split(/=/,$pair);
                   4066: 	$hash{$key}=$value;
                   4067:     }
                   4068:     return (%hash);
                   4069: }
                   4070: sub hash_to_str {
                   4071:     my ($hash_ref)=@_;
                   4072:     my $str;
                   4073:     foreach my $key (keys(%$hash_ref)) {
                   4074: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   4075:     }
                   4076:     $str=~s/\&$//;
                   4077:     return $str;
                   4078: }
                   4079: 
1.231     foxr     4080: #
                   4081: #  Dump out all versions of a resource that has key=value pairs associated
                   4082: # with it for each version.  These resources are built up via the store
                   4083: # command.
                   4084: #
                   4085: #  Parameters:
                   4086: #     $cmd               - Command keyword.
                   4087: #     $tail              - Remainder of the request which consists of:
                   4088: #                          domain/user   - User and auth. domain.
                   4089: #                          namespace     - name of resource database.
                   4090: #                          rid           - Resource id.
                   4091: #    $client             - socket open on the client.
                   4092: #
                   4093: # Returns:
                   4094: #      1  indicating the caller should not yet exit.
                   4095: # Side-effects:
                   4096: #   Writes a reply to the client.
                   4097: #   The reply is a string of the following shape:
                   4098: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   4099: #    Where the 1 above represents version 1.
                   4100: #    this continues for all pairs of keys in all versions.
                   4101: #
                   4102: #
                   4103: #    
                   4104: #
                   4105: sub restore_handler {
                   4106:     my ($cmd, $tail, $client) = @_;
                   4107: 
                   4108:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 4109:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 4110:     $namespace=~s/\//\_/g;
1.350     albertel 4111:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 4112: 
1.231     foxr     4113:     chomp($rid);
                   4114:     my $qresult='';
1.309     albertel 4115:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   4116:     if ($hashref) {
                   4117: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     4118: 	$qresult.="version=$version&";
                   4119: 	my $scope;
                   4120: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 4121: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     4122: 	    my @keys=split(/:/,$vkeys);
                   4123: 	    my $key;
                   4124: 	    $qresult.="$scope:keys=$vkeys&";
                   4125: 	    foreach $key (@keys) {
1.309     albertel 4126: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     4127: 	    }                                  
                   4128: 	}
1.311     albertel 4129: 	if (&untie_user_hash($hashref)) {
1.231     foxr     4130: 	    $qresult=~s/\&$//;
1.387     albertel 4131: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     4132: 	} else {
                   4133: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4134: 		    "while attempting restore\n", $userinput);
                   4135: 	}
                   4136:     } else {
                   4137: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4138: 		"while attempting restore\n", $userinput);
                   4139:     }
                   4140:   
                   4141:     return 1;
                   4142: 
                   4143: 
                   4144: }
                   4145: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     4146: 
                   4147: #
1.324     raeburn  4148: #   Add a chat message to a synchronous discussion board.
1.234     foxr     4149: #
                   4150: # Parameters:
                   4151: #    $cmd                - Request keyword.
                   4152: #    $tail               - Tail of the command. A colon separated list
                   4153: #                          containing:
                   4154: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  4155: #                          cnum    - Course containing the chat board.
                   4156: #                          newpost - Body of the posting.
                   4157: #                          group   - Optional group, if chat board is only 
                   4158: #                                    accessible in a group within the course 
1.234     foxr     4159: #   $client              - Socket open on the client.
                   4160: # Returns:
                   4161: #   1    - Indicating caller should keep on processing.
                   4162: #
                   4163: # Side-effects:
                   4164: #   writes a reply to the client.
                   4165: #
                   4166: #
                   4167: sub send_chat_handler {
                   4168:     my ($cmd, $tail, $client) = @_;
                   4169: 
                   4170:     
                   4171:     my $userinput = "$cmd:$tail";
                   4172: 
1.324     raeburn  4173:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   4174:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     4175:     &Reply($client, "ok\n", $userinput);
                   4176: 
                   4177:     return 1;
                   4178: }
                   4179: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 4180: 
1.234     foxr     4181: #
1.324     raeburn  4182: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     4183: #
                   4184: #  Parameters:
                   4185: #    $cmd             - Command keyword that initiated the request.
                   4186: #    $tail            - Remainder of the request after the command
                   4187: #                       keyword.  In this case a colon separated list of
                   4188: #                       chat domain    - Which discussion board.
                   4189: #                       chat id        - Discussion thread(?)
                   4190: #                       domain/user    - Authentication domain and username
                   4191: #                                        of the requesting person.
1.324     raeburn  4192: #                       group          - Optional course group containing
                   4193: #                                        the board.      
1.234     foxr     4194: #   $client           - Socket open on the client program.
                   4195: # Returns:
                   4196: #    1     - continue processing
                   4197: # Side effects:
                   4198: #    Response is written to the client.
                   4199: #
                   4200: sub retrieve_chat_handler {
                   4201:     my ($cmd, $tail, $client) = @_;
                   4202: 
                   4203: 
                   4204:     my $userinput = "$cmd:$tail";
                   4205: 
1.324     raeburn  4206:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     4207:     my $reply='';
1.324     raeburn  4208:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     4209: 	$reply.=&escape($_).':';
                   4210:     }
                   4211:     $reply=~s/\:$//;
1.387     albertel 4212:     &Reply($client, \$reply, $userinput);
1.234     foxr     4213: 
                   4214: 
                   4215:     return 1;
                   4216: }
                   4217: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   4218: 
                   4219: #
                   4220: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   4221: #  a file for later retrieval.  This prevents sql query results from
                   4222: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   4223: #  less of an issue since multiple outstanding requests can be concurrently
                   4224: #  serviced.
                   4225: #
                   4226: #  Parameters:
1.535     raeburn  4227: #     $cmd       - Command keyword that initiated the request.
1.234     foxr     4228: #     $tail      - Remainder of the command after the keyword.
                   4229: #                  For this function, this consists of a query and
                   4230: #                  3 arguments that are self-documentingly labelled
                   4231: #                  in the original arg1, arg2, arg3.
                   4232: #     $client    - Socket open on the client.
                   4233: # Return:
                   4234: #    1   - Indicating processing should continue.
                   4235: # Side-effects:
                   4236: #    a reply is written to $client.
                   4237: #
                   4238: sub send_query_handler {
                   4239:     my ($cmd, $tail, $client) = @_;
                   4240: 
                   4241:     my $userinput = "$cmd:$tail";
                   4242: 
                   4243:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   4244:     $query=~s/\n*$//g;
1.534     raeburn  4245:     if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
                   4246:         my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
                   4247:         my $earlyout;
                   4248:         if (ref($usersearchconf) eq 'HASH') {
                   4249:             if ($currentdomainid eq $clienthomedom) {
                   4250:                 if ($query eq 'usersearch') {
                   4251:                     if ($usersearchconf->{'lcavailable'} eq '0') {
                   4252:                         $earlyout = 1;
                   4253:                     }
                   4254:                 } else {
                   4255:                     if ($usersearchconf->{'available'} eq '0') {
                   4256:                         $earlyout = 1;
                   4257:                     }
                   4258:                 }
                   4259:             } else {
                   4260:                 if ($query eq 'usersearch') {
                   4261:                     if ($usersearchconf->{'lclocalonly'}) {
                   4262:                         $earlyout = 1;
                   4263:                     }
                   4264:                 } else {
                   4265:                     if ($usersearchconf->{'localonly'}) {
                   4266:                         $earlyout = 1;
                   4267:                     }
                   4268:                 }
                   4269:             }
                   4270:         }
                   4271:         if ($earlyout) {
                   4272:             &Reply($client, "query_not_authorized\n");
                   4273:             return 1;
                   4274:         }
                   4275:     }
1.234     foxr     4276:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   4277: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   4278: 	  $userinput);
                   4279:     
                   4280:     return 1;
                   4281: }
                   4282: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   4283: 
                   4284: #
                   4285: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   4286: #   The query is submitted via a "querysend" transaction.
                   4287: #   There it is passed on to the lonsql daemon, queued and issued to
                   4288: #   mysql.
                   4289: #     This transaction is invoked when the sql transaction is complete
                   4290: #   it stores the query results in flie and indicates query completion.
                   4291: #   presumably local software then fetches this response... I'm guessing
                   4292: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   4293: #   lonsql on completion of the query interacts with the lond of our
                   4294: #   client to do a query reply storing two files:
                   4295: #    - id     - The results of the query.
                   4296: #    - id.end - Indicating the transaction completed. 
                   4297: #    NOTE: id is a unique id assigned to the query and querysend time.
                   4298: # Parameters:
                   4299: #    $cmd        - Command keyword that initiated this request.
                   4300: #    $tail       - Remainder of the tail.  In this case that's a colon
                   4301: #                  separated list containing the query Id and the 
                   4302: #                  results of the query.
                   4303: #    $client     - Socket open on the client.
                   4304: # Return:
                   4305: #    1           - Indicating that we should continue processing.
                   4306: # Side effects:
                   4307: #    ok written to the client.
                   4308: #
                   4309: sub reply_query_handler {
                   4310:     my ($cmd, $tail, $client) = @_;
                   4311: 
                   4312: 
                   4313:     my $userinput = "$cmd:$tail";
                   4314: 
1.339     albertel 4315:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     4316:     my $store;
                   4317:     my $execdir=$perlvar{'lonDaemons'};
                   4318:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   4319: 	$reply=~s/\&/\n/g;
                   4320: 	print $store $reply;
                   4321: 	close $store;
                   4322: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   4323: 	print $store2 "done\n";
                   4324: 	close $store2;
                   4325: 	&Reply($client, "ok\n", $userinput);
                   4326:     } else {
                   4327: 	&Failure($client, "error: ".($!+0)
                   4328: 		." IO::File->new Failed ".
                   4329: 		"while attempting queryreply\n", $userinput);
                   4330:     }
                   4331:  
                   4332: 
                   4333:     return 1;
                   4334: }
                   4335: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   4336: 
                   4337: #
                   4338: #  Process the courseidput request.  Not quite sure what this means
                   4339: #  at the system level sense.  It appears a gdbm file in the 
                   4340: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   4341: #  a set of entries made in that database.
                   4342: #
                   4343: # Parameters:
                   4344: #   $cmd      - The command keyword that initiated this request.
                   4345: #   $tail     - Tail of the command.  In this case consists of a colon
                   4346: #               separated list contaning the domain to apply this to and
                   4347: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  4348: #               Each value is a colon separated list that includes:  
                   4349: #               description, institutional code and course owner.
                   4350: #               For backward compatibility with versions included
                   4351: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   4352: #               code and/or course owner are preserved from the existing 
                   4353: #               record when writing a new record in response to 1.1 or 
                   4354: #               1.2 implementations of lonnet::flushcourselogs().   
                   4355: #                      
1.234     foxr     4356: #   $client   - Socket open on the client.
                   4357: # Returns:
                   4358: #   1    - indicating that processing should continue
                   4359: #
                   4360: # Side effects:
                   4361: #   reply is written to the client.
                   4362: #
                   4363: sub put_course_id_handler {
                   4364:     my ($cmd, $tail, $client) = @_;
                   4365: 
                   4366: 
                   4367:     my $userinput = "$cmd:$tail";
                   4368: 
1.266     raeburn  4369:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     4370:     chomp($what);
                   4371:     my $now=time;
                   4372:     my @pairs=split(/\&/,$what);
                   4373: 
                   4374:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4375:     if ($hashref) {
                   4376: 	foreach my $pair (@pairs) {
1.271     raeburn  4377:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   4378:             $courseinfo =~ s/=/:/g;
1.384     raeburn  4379:             if (defined($hashref->{$key})) {
                   4380:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   4381:                 if (ref($value) eq 'HASH') {
                   4382:                     my @items = ('description','inst_code','owner','type');
                   4383:                     my @new_items = split(/:/,$courseinfo,-1);
                   4384:                     my %storehash; 
                   4385:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  4386:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  4387:                     }
                   4388:                     $hashref->{$key} = 
                   4389:                         &Apache::lonnet::freeze_escape(\%storehash);
                   4390:                     my $unesc_key = &unescape($key);
                   4391:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4392:                     next;
1.383     raeburn  4393:                 }
1.384     raeburn  4394:             }
                   4395:             my @current_items = split(/:/,$hashref->{$key},-1);
                   4396:             shift(@current_items); # remove description
                   4397:             pop(@current_items);   # remove last access
                   4398:             my $numcurrent = scalar(@current_items);
                   4399:             if ($numcurrent > 3) {
                   4400:                 $numcurrent = 3;
                   4401:             }
                   4402:             my @new_items = split(/:/,$courseinfo,-1);
                   4403:             my $numnew = scalar(@new_items);
                   4404:             if ($numcurrent > 0) {
                   4405:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4406:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4407:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4408:                     }
1.272     raeburn  4409:                 }
                   4410:             }
1.384     raeburn  4411:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4412: 	}
1.311     albertel 4413: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4414: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4415: 	} else {
1.253     foxr     4416: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4417: 		     ." untie(GDBM) Failed ".
                   4418: 		     "while attempting courseidput\n", $userinput);
                   4419: 	}
                   4420:     } else {
1.253     foxr     4421: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4422: 		 ." tie(GDBM) Failed ".
                   4423: 		 "while attempting courseidput\n", $userinput);
                   4424:     }
                   4425: 
                   4426:     return 1;
                   4427: }
                   4428: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4429: 
1.383     raeburn  4430: sub put_course_id_hash_handler {
                   4431:     my ($cmd, $tail, $client) = @_;
                   4432:     my $userinput = "$cmd:$tail";
1.384     raeburn  4433:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4434:     chomp($what);
                   4435:     my $now=time;
                   4436:     my @pairs=split(/\&/,$what);
1.384     raeburn  4437:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4438:     if ($hashref) {
                   4439:         foreach my $pair (@pairs) {
                   4440:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4441:             my $unesc_key = &unescape($key);
                   4442:             if ($mode ne 'timeonly') {
                   4443:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4444:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4445:                     if (ref($curritems) ne 'HASH') {
                   4446:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4447:                         my $lasttime = pop(@current_items);
                   4448:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4449:                     } else {
                   4450:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4451:                     }
                   4452:                 } 
                   4453:                 $hashref->{$key} = $value;
                   4454:             }
                   4455:             if ($mode ne 'notime') {
                   4456:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4457:             }
1.383     raeburn  4458:         }
                   4459:         if (&untie_domain_hash($hashref)) {
                   4460:             &Reply($client, "ok\n", $userinput);
                   4461:         } else {
                   4462:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4463:                      "while attempting courseidputhash\n", $userinput);
                   4464:         }
                   4465:     } else {
                   4466:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4467:                   "while attempting courseidputhash\n", $userinput);
                   4468:     }
                   4469:     return 1;
                   4470: }
                   4471: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4472: 
1.234     foxr     4473: #  Retrieves the value of a course id resource keyword pattern
                   4474: #  defined since a starting date.  Both the starting date and the
                   4475: #  keyword pattern are optional.  If the starting date is not supplied it
                   4476: #  is treated as the beginning of time.  If the pattern is not found,
                   4477: #  it is treatred as "." matching everything.
                   4478: #
                   4479: #  Parameters:
                   4480: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4481: #     $tail    - The remainder of the command that, in this case, consists
                   4482: #                of a colon separated list of:
                   4483: #                 domain   - The domain in which the course database is 
                   4484: #                            defined.
                   4485: #                 since    - Optional parameter describing the minimum
                   4486: #                            time of definition(?) of the resources that
                   4487: #                            will match the dump.
                   4488: #                 description - regular expression that is used to filter
                   4489: #                            the dump.  Only keywords matching this regexp
                   4490: #                            will be used.
1.272     raeburn  4491: #                 institutional code - optional supplied code to filter 
                   4492: #                            the dump. Only courses with an institutional code 
                   4493: #                            that match the supplied code will be returned.
1.336     raeburn  4494: #                 owner    - optional supplied username and domain of owner to
                   4495: #                            filter the dump.  Only courses for which the course
                   4496: #                            owner matches the supplied username and/or domain
                   4497: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4498: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4499: #                 type     - optional parameter for selection 
1.418     raeburn  4500: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4501: #                            filter to behave as a regular expression:
                   4502: #	                      1 will not exclude the course if the instcode matches the RE 
                   4503: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4504: #                 rtn_as_hash - whether to return the information available for
                   4505: #                            each matched item as a frozen hash of all 
                   4506: #                            key, value pairs in the item's hash, or as a 
                   4507: #                            colon-separated list of (in order) description,
                   4508: #                            institutional code, and course owner.
1.404     raeburn  4509: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4510: #                                  now or in the future (selfenrollonly = 1).
                   4511: #                 catfilter - filter by course category, assigned to a course 
                   4512: #                             using manually defined categories (i.e., not
1.407     raeburn  4513: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4514: #                 showhidden - include course in results even if course  
1.407     raeburn  4515: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4516: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4517: #                           from course catalog will be excluded from results (unless
                   4518: #                           overridden by "showhidden".
1.427     raeburn  4519: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4520: #                          clone).
                   4521: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4522: #                                 course cloner has active CC role (and so can clone
                   4523: #                                 automatically).
1.427     raeburn  4524: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4525: #                 createdbefore - include courses for which creation date preceeded this date.
                   4526: #                 createdafter - include courses for which creation date followed this date.
                   4527: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4528: #
1.445     raeburn  4529: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4530: #                             If so, ability to clone course is automatic.
                   4531: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4532: #                                 been set.
1.445     raeburn  4533: #
1.234     foxr     4534: #     $client  - The socket open on the client.
                   4535: # Returns:
                   4536: #    1     - Continue processing.
                   4537: # Side Effects:
                   4538: #   a reply is written to $client.
                   4539: sub dump_course_id_handler {
                   4540:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4541: 
                   4542:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4543:     if ($res =~ /^error:/) {
                   4544:         Failure($client, \$res, "$cmd:$tail");
                   4545:     } else {
                   4546:         Reply($client, \$res, "$cmd:$tail");
                   4547:     }
                   4548: 
                   4549:     return 1;  
                   4550: 
                   4551:     #TODO remove
1.234     foxr     4552:     my $userinput = "$cmd:$tail";
                   4553: 
1.333     raeburn  4554:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4555:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4556:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4557:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4558:     my $now = time;
1.419     raeburn  4559:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4560:     if (defined($description)) {
                   4561: 	$description=&unescape($description);
                   4562:     } else {
                   4563: 	$description='.';
                   4564:     }
1.266     raeburn  4565:     if (defined($instcodefilter)) {
                   4566:         $instcodefilter=&unescape($instcodefilter);
                   4567:     } else {
                   4568:         $instcodefilter='.';
                   4569:     }
1.336     raeburn  4570:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4571:     if (defined($ownerfilter)) {
                   4572:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4573:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4574:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4575:                  $ownerunamefilter = $1;
                   4576:                  $ownerdomfilter = $2;
                   4577:             } else {
                   4578:                 $ownerunamefilter = $ownerfilter;
                   4579:                 $ownerdomfilter = '';
                   4580:             }
                   4581:         }
1.266     raeburn  4582:     } else {
                   4583:         $ownerfilter='.';
                   4584:     }
1.336     raeburn  4585: 
1.282     raeburn  4586:     if (defined($coursefilter)) {
                   4587:         $coursefilter=&unescape($coursefilter);
                   4588:     } else {
                   4589:         $coursefilter='.';
                   4590:     }
1.333     raeburn  4591:     if (defined($typefilter)) {
                   4592:         $typefilter=&unescape($typefilter);
                   4593:     } else {
                   4594:         $typefilter='.';
                   4595:     }
1.344     raeburn  4596:     if (defined($regexp_ok)) {
                   4597:         $regexp_ok=&unescape($regexp_ok);
                   4598:     }
1.401     raeburn  4599:     if (defined($catfilter)) {
                   4600:         $catfilter=&unescape($catfilter);
                   4601:     }
1.419     raeburn  4602:     if (defined($cloner)) {
                   4603:         $cloner = &unescape($cloner);
                   4604:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4605:     }
                   4606:     if (defined($cc_clone_list)) {
                   4607:         $cc_clone_list = &unescape($cc_clone_list);
                   4608:         my @cc_cloners = split('&',$cc_clone_list);
                   4609:         foreach my $cid (@cc_cloners) {
                   4610:             my ($clonedom,$clonenum) = split(':',$cid);
                   4611:             next if ($clonedom ne $udom); 
                   4612:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4613:         } 
                   4614:     }
1.431     raeburn  4615:     if ($createdbefore ne '') {
1.427     raeburn  4616:         $createdbefore = &unescape($createdbefore);
                   4617:     } else {
                   4618:        $createdbefore = 0;
                   4619:     }
1.431     raeburn  4620:     if ($createdafter ne '') {
1.427     raeburn  4621:         $createdafter = &unescape($createdafter);
                   4622:     } else {
                   4623:         $createdafter = 0;
                   4624:     }
1.431     raeburn  4625:     if ($creationcontext ne '') {
1.427     raeburn  4626:         $creationcontext = &unescape($creationcontext);
                   4627:     } else {
                   4628:         $creationcontext = '.';
                   4629:     }
1.505     raeburn  4630:     unless ($hasuniquecode) {
                   4631:         $hasuniquecode = '.';
                   4632:     }
1.384     raeburn  4633:     my $unpack = 1;
1.485     raeburn  4634:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4635:         $typefilter eq '.') {
                   4636:         $unpack = 0;
                   4637:     }
                   4638:     if (!defined($since)) { $since=0; }
1.234     foxr     4639:     my $qresult='';
                   4640:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4641:     if ($hashref) {
1.384     raeburn  4642: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4643:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4644:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4645:                 $context);
1.384     raeburn  4646:             $unesc_key = &unescape($key);
                   4647:             if ($unesc_key =~ /^lasttime:/) {
                   4648:                 next;
                   4649:             } else {
                   4650:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4651:             }
                   4652:             if ($hashref->{$lasttime_key} ne '') {
                   4653:                 $lasttime = $hashref->{$lasttime_key};
                   4654:                 next if ($lasttime<$since);
                   4655:             }
1.419     raeburn  4656:             my ($canclone,$valchange);
1.384     raeburn  4657:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4658:             if (ref($items) eq 'HASH') {
1.429     raeburn  4659:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4660:                     next if ($since > 1);
1.429     raeburn  4661:                 }
1.384     raeburn  4662:                 $is_hash =  1;
1.445     raeburn  4663:                 if ($domcloner) {
                   4664:                     $canclone = 1;
                   4665:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4666:                     if ($items->{'cloners'}) {
                   4667:                         my @cloneable = split(',',$items->{'cloners'});
                   4668:                         if (@cloneable) {
                   4669:                             if (grep(/^\*$/,@cloneable))  {
                   4670:                                 $canclone = 1;
                   4671:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4672:                                 $canclone = 1;
                   4673:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4674:                                 $canclone = 1;
                   4675:                             }
                   4676:                         }
                   4677:                         unless ($canclone) {
                   4678:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4679:                                 if ($cc_clone{$unesc_key}) {
                   4680:                                     $canclone = 1;
                   4681:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4682:                                                            $clonerudom;
                   4683:                                     $valchange = 1;
                   4684:                                 }
                   4685:                             }
                   4686:                         }
                   4687:                     } elsif (defined($cloneruname)) {
                   4688:                         if ($cc_clone{$unesc_key}) {
                   4689:                             $canclone = 1;
                   4690:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4691:                             $valchange = 1;
                   4692:                         }
1.437     raeburn  4693:                         unless ($canclone) {
                   4694:                             if ($items->{'owner'} =~ /:/) {
                   4695:                                 if ($items->{'owner'} eq $cloner) {
                   4696:                                     $canclone = 1;
                   4697:                                 }
1.444     raeburn  4698:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4699:                                 $canclone = 1;
                   4700:                             }
                   4701:                             if ($canclone) {
                   4702:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4703:                                 $valchange = 1;
                   4704:                             }
                   4705:                         }
1.419     raeburn  4706:                     }
                   4707:                 }
1.384     raeburn  4708:                 if ($unpack || !$rtn_as_hash) {
                   4709:                     $unesc_val{'descr'} = $items->{'description'};
                   4710:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4711:                     $unesc_val{'owner'} = $items->{'owner'};
                   4712:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4713:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4714:                     $unesc_val{'created'} = $items->{'created'};
                   4715:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4716:                 }
                   4717:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4718:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4719:                 $created = $items->{'created'};
                   4720:                 $context = $items->{'context'};
1.505     raeburn  4721:                 if ($hasuniquecode ne '.') {
                   4722:                     next unless ($items->{'uniquecode'});
                   4723:                 }
1.404     raeburn  4724:                 if ($selfenrollonly) {
                   4725:                     next if (!$selfenroll_types);
                   4726:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4727:                         next;
1.397     raeburn  4728:                     }
1.404     raeburn  4729:                 }
1.427     raeburn  4730:                 if ($creationcontext ne '.') {
                   4731:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4732:                 }
                   4733:                 if ($createdbefore > 0) {
                   4734:                     next if (($created eq '') || ($created > $createdbefore));   
                   4735:                 }
                   4736:                 if ($createdafter > 0) {
                   4737:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4738:                 }
1.404     raeburn  4739:                 if ($catfilter ne '') {
1.406     raeburn  4740:                     next if ($items->{'categories'} eq '');
                   4741:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4742:                     next if (@categories == 0);
                   4743:                     my @subcats = split('&',$catfilter);
                   4744:                     my $matchcat = 0;
                   4745:                     foreach my $cat (@categories) {
                   4746:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4747:                             $matchcat = 1;
                   4748:                             last;
                   4749:                         }
                   4750:                     }
                   4751:                     next if (!$matchcat);
1.404     raeburn  4752:                 }
                   4753:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4754:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4755:                         next if !$showhidden;
1.401     raeburn  4756:                     }
1.384     raeburn  4757:                 }
1.383     raeburn  4758:             } else {
1.401     raeburn  4759:                 next if ($catfilter ne '');
1.419     raeburn  4760:                 next if ($selfenrollonly);
1.427     raeburn  4761:                 next if ($createdbefore || $createdafter);
                   4762:                 next if ($creationcontext ne '.');
1.419     raeburn  4763:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4764:                     if ($cc_clone{$unesc_key}) {
                   4765:                         $canclone = 1;
                   4766:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4767:                     }
                   4768:                 }
1.384     raeburn  4769:                 $is_hash =  0;
1.388     raeburn  4770:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4771:                 $lasttime = pop(@courseitems);
1.402     raeburn  4772:                 if ($hashref->{$lasttime_key} eq '') {
                   4773:                     next if ($lasttime<$since);
                   4774:                 }
1.384     raeburn  4775: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4776:             }
1.419     raeburn  4777:             if ($cloneonly) {
                   4778:                next unless ($canclone);
                   4779:             }
1.266     raeburn  4780:             my $match = 1;
1.384     raeburn  4781: 	    if ($description ne '.') {
                   4782:                 if (!$is_hash) {
                   4783:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4784:                 }
                   4785:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4786:                     $match = 0;
1.384     raeburn  4787:                 }
1.266     raeburn  4788:             }
1.384     raeburn  4789:             if ($instcodefilter ne '.') {
                   4790:                 if (!$is_hash) {
                   4791:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4792:                 }
1.418     raeburn  4793:                 if ($regexp_ok == 1) {
1.384     raeburn  4794:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4795:                         $match = 0;
                   4796:                     }
1.418     raeburn  4797:                 } elsif ($regexp_ok == -1) {
                   4798:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4799:                         $match = 0;
                   4800:                     }
1.344     raeburn  4801:                 } else {
1.384     raeburn  4802:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4803:                         $match = 0;
                   4804:                     }
1.266     raeburn  4805:                 }
1.234     foxr     4806: 	    }
1.384     raeburn  4807:             if ($ownerfilter ne '.') {
                   4808:                 if (!$is_hash) {
                   4809:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4810:                 }
1.336     raeburn  4811:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4812:                     if ($unesc_val{'owner'} =~ /:/) {
                   4813:                         if (eval{$unesc_val{'owner'} !~ 
                   4814:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4815:                             $match = 0;
                   4816:                         } 
                   4817:                     } else {
1.384     raeburn  4818:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4819:                             $match = 0;
                   4820:                         }
                   4821:                     }
                   4822:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4823:                     if ($unesc_val{'owner'} =~ /:/) {
                   4824:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4825:                              $match = 0;
                   4826:                         }
                   4827:                     } else {
1.384     raeburn  4828:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4829:                             $match = 0;
                   4830:                         }
                   4831:                     }
                   4832:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4833:                     if ($unesc_val{'owner'} =~ /:/) {
                   4834:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4835:                              $match = 0;
                   4836:                         }
                   4837:                     } else {
                   4838:                         if ($ownerdomfilter ne $udom) {
                   4839:                             $match = 0;
                   4840:                         }
                   4841:                     }
1.266     raeburn  4842:                 }
                   4843:             }
1.384     raeburn  4844:             if ($coursefilter ne '.') {
                   4845:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4846:                     $match = 0;
                   4847:                 }
                   4848:             }
1.384     raeburn  4849:             if ($typefilter ne '.') {
                   4850:                 if (!$is_hash) {
                   4851:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4852:                 }
                   4853:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4854:                     if ($typefilter ne 'Course') {
                   4855:                         $match = 0;
                   4856:                     }
1.383     raeburn  4857:                 } else {
1.384     raeburn  4858:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4859:                         $match = 0;
                   4860:                     }
                   4861:                 }
                   4862:             }
1.266     raeburn  4863:             if ($match == 1) {
1.384     raeburn  4864:                 if ($rtn_as_hash) {
                   4865:                     if ($is_hash) {
1.419     raeburn  4866:                         if ($valchange) {
                   4867:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4868:                             $qresult.=$key.'='.$newvalue.'&';
                   4869:                         } else {
                   4870:                             $qresult.=$key.'='.$value.'&';
                   4871:                         }
1.384     raeburn  4872:                     } else {
1.388     raeburn  4873:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4874:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4875:                                         'owner'     => &unescape($val{'owner'}),
                   4876:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4877:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4878:                                       );
                   4879:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4880:                         $qresult.=$key.'='.$items.'&';
                   4881:                     }
1.383     raeburn  4882:                 } else {
1.384     raeburn  4883:                     if ($is_hash) {
                   4884:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4885:                                     &escape($unesc_val{'inst_code'}).':'.
                   4886:                                     &escape($unesc_val{'owner'}).'&';
                   4887:                     } else {
                   4888:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4889:                                     ':'.$val{'owner'}.'&';
                   4890:                     }
1.383     raeburn  4891:                 }
1.266     raeburn  4892:             }
1.234     foxr     4893: 	}
1.311     albertel 4894: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4895: 	    chop($qresult);
1.387     albertel 4896: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4897: 	} else {
                   4898: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4899: 		    "while attempting courseiddump\n", $userinput);
                   4900: 	}
                   4901:     } else {
                   4902: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4903: 		"while attempting courseiddump\n", $userinput);
                   4904:     }
                   4905:     return 1;
                   4906: }
                   4907: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4908: 
1.438     raeburn  4909: sub course_lastaccess_handler {
                   4910:     my ($cmd, $tail, $client) = @_;
                   4911:     my $userinput = "$cmd:$tail";
                   4912:     my ($cdom,$cnum) = split(':',$tail); 
                   4913:     my (%lastaccess,$qresult);
                   4914:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4915:     if ($hashref) {
                   4916:         while (my ($key,$value) = each(%$hashref)) {
                   4917:             my ($unesc_key,$lasttime);
                   4918:             $unesc_key = &unescape($key);
                   4919:             if ($cnum) {
                   4920:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4921:             }
                   4922:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4923:                 $lastaccess{$1} = $value;
                   4924:             } else {
                   4925:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4926:                 if (ref($items) eq 'HASH') {
                   4927:                     unless ($lastaccess{$unesc_key}) {
                   4928:                         $lastaccess{$unesc_key} = '';
                   4929:                     }
                   4930:                 } else {
                   4931:                     my @courseitems = split(':',$value);
                   4932:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4933:                 }
                   4934:             }
                   4935:         }
                   4936:         foreach my $cid (sort(keys(%lastaccess))) {
                   4937:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4938:         }
                   4939:         if (&untie_domain_hash($hashref)) {
                   4940:             if ($qresult) {
                   4941:                 chop($qresult);
                   4942:             }
                   4943:             &Reply($client, \$qresult, $userinput);
                   4944:         } else {
                   4945:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4946:                     "while attempting lastacourseaccess\n", $userinput);
                   4947:         }
                   4948:     } else {
                   4949:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4950:                 "while attempting lastcourseaccess\n", $userinput);
                   4951:     }
                   4952:     return 1;
                   4953: }
                   4954: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4955: 
1.561     raeburn  4956: sub course_sessions_handler {
                   4957:     my ($cmd, $tail, $client) = @_;
                   4958:     my $userinput = "$cmd:$tail";
                   4959:     my ($cdom,$cnum,$lastactivity) = split(':',$tail);
                   4960:     my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
                   4961:     my (%sessions,$qresult);
                   4962:     my $now=time;
                   4963:     if (opendir(DIR,$perlvar{'lonIDsDir'})) {
                   4964:         my $filename;
                   4965:         while ($filename=readdir(DIR)) {
                   4966:             next if ($filename=~/^\./);
                   4967:             next if ($filename=~/^publicuser_/);
                   4968:             next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.562     raeburn  4969:             if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.561     raeburn  4970:                 my ($uname,$udom) = ($1,$2);
1.562     raeburn  4971:                 next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.561     raeburn  4972:                 my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
                   4973:                 if ($lastactivity < 0) {
1.563     raeburn  4974:                     next if ($mtime-$now > $lastactivity);
1.561     raeburn  4975:                 } else {
1.563     raeburn  4976:                     next if ($now-$mtime > $lastactivity);
1.561     raeburn  4977:                 }
                   4978:                 $sessions{$uname.':'.$udom} = $mtime;
                   4979:             }
                   4980:         }
                   4981:         closedir(DIR); 
                   4982:     }
                   4983:     foreach my $user (keys(%sessions)) {
                   4984:         $qresult.=&escape($user).'='.$sessions{$user}.'&';
                   4985:     }
                   4986:     if ($qresult) {
                   4987:         chop($qresult);
                   4988:     }
                   4989:     &Reply($client, \$qresult, $userinput);
                   4990:     return 1;
                   4991: }
                   4992: &register_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
                   4993: 
1.238     foxr     4994: #
1.348     raeburn  4995: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4996: #
                   4997: # Parameters:
                   4998: #    $cmd      - The command that got us here.
                   4999: #    $tail     - Tail of the command (remaining parameters).
                   5000: #    $client   - File descriptor connected to client.
                   5001: # Returns
                   5002: #     0        - Requested to exit, caller should shut down.
                   5003: #     1        - Continue processing.
                   5004: #  Side effects:
                   5005: #     reply is written to $client.
                   5006: #
                   5007: sub put_domain_handler {
                   5008:     my ($cmd,$tail,$client) = @_;
                   5009: 
                   5010:     my $userinput = "$cmd:$tail";
                   5011: 
                   5012:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   5013:     chomp($what);
                   5014:     my @pairs=split(/\&/,$what);
                   5015:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   5016:                                    "P", $what);
                   5017:     if ($hashref) {
                   5018:         foreach my $pair (@pairs) {
                   5019:             my ($key,$value)=split(/=/,$pair);
                   5020:             $hashref->{$key}=$value;
                   5021:         }
                   5022:         if (&untie_domain_hash($hashref)) {
                   5023:             &Reply($client, "ok\n", $userinput);
                   5024:         } else {
                   5025:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5026:                      "while attempting putdom\n", $userinput);
                   5027:         }
                   5028:     } else {
                   5029:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5030:                   "while attempting putdom\n", $userinput);
                   5031:     }
                   5032: 
                   5033:     return 1;
                   5034: }
                   5035: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   5036: 
1.517     raeburn  5037: # Updates one or more entries in clickers.db file at the domain level
                   5038: #
                   5039: # Parameters:
                   5040: #    $cmd      - The command that got us here.
                   5041: #    $tail     - Tail of the command (remaining parameters).
                   5042: #                In this case a colon separated list containing:
                   5043: #                (a) the domain for which we are updating the entries,
                   5044: #                (b) the action required -- add or del -- and
                   5045: #                (c) a &-separated list of entries to add or delete.
                   5046: #    $client   - File descriptor connected to client.
                   5047: # Returns
                   5048: #     1        - Continue processing.
                   5049: #     0        - Requested to exit, caller should shut down.
                   5050: #  Side effects:
                   5051: #     reply is written to $client.
                   5052: #
                   5053: 
                   5054: 
                   5055: sub update_clickers {
                   5056:     my ($cmd, $tail, $client)  = @_;
                   5057: 
                   5058:     my $userinput = "$cmd:$tail";
                   5059:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   5060:     chomp($what);
                   5061: 
                   5062:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   5063:                                  "U","$action:$what");
                   5064: 
                   5065:     if (!$hashref) {
                   5066:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5067:                   "while attempting updateclickers\n", $userinput);
                   5068:         return 1;
                   5069:     }
                   5070: 
                   5071:     my @pairs=split(/\&/,$what);
                   5072:     foreach my $pair (@pairs) {
                   5073:         my ($key,$value)=split(/=/,$pair);
                   5074:         if ($action eq 'add') {
                   5075:             if (exists($hashref->{$key})) {
                   5076:                 my @newvals = split(/,/,&unescape($value));
                   5077:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   5078:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   5079:                 $hashref->{$key}=&escape(join(',',@merged));
                   5080:             } else {
                   5081:                 $hashref->{$key}=$value;
                   5082:             }
                   5083:         } elsif ($action eq 'del') {
                   5084:             if (exists($hashref->{$key})) {
                   5085:                 my %current;
                   5086:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   5087:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   5088:                 if (keys(%current)) {
                   5089:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   5090:                 } else {
                   5091:                     delete($hashref->{$key});
                   5092:                 }
                   5093:             }
                   5094:         }
                   5095:     }
                   5096:     if (&untie_user_hash($hashref)) {
                   5097:         &Reply( $client, "ok\n", $userinput);
                   5098:     } else {
                   5099:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   5100:                  "while attempting put\n",
                   5101:                  $userinput);
                   5102:     }
                   5103:     return 1;
                   5104: }
                   5105: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   5106: 
                   5107: 
                   5108: # Deletes one or more entries in a namespace db file at the domain level
                   5109: #
                   5110: # Parameters:
                   5111: #    $cmd      - The command that got us here.
                   5112: #    $tail     - Tail of the command (remaining parameters).
                   5113: #                In this case a colon separated list containing:
                   5114: #                (a) the domain for which we are deleting the entries,
                   5115: #                (b) &-separated list of keys to delete.  
                   5116: #    $client   - File descriptor connected to client.
                   5117: # Returns
                   5118: #     1        - Continue processing.
                   5119: #     0        - Requested to exit, caller should shut down.
                   5120: #  Side effects:
                   5121: #     reply is written to $client.
                   5122: #
                   5123: 
                   5124: sub del_domain_handler {
                   5125:     my ($cmd,$tail,$client) = @_;
                   5126: 
                   5127:     my $userinput = "$cmd:$tail";
                   5128: 
                   5129:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   5130:     chomp($what);
                   5131:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   5132:                                    "D", $what);
                   5133:     if ($hashref) {
                   5134:         my @keys=split(/\&/,$what);
                   5135:         foreach my $key (@keys) {
                   5136:             delete($hashref->{$key});
                   5137:         }
                   5138:         if (&untie_user_hash($hashref)) {
                   5139:             &Reply($client, "ok\n", $userinput);
                   5140:         } else {
                   5141:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5142:                     "while attempting deldom\n", $userinput);
                   5143:         }
                   5144:     } else {
                   5145:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5146:                  "while attempting deldom\n", $userinput);
                   5147:     }
                   5148:     return 1;
                   5149: }
                   5150: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   5151: 
                   5152: 
1.348     raeburn  5153: # Unencrypted get from the namespace database file at the domain level.
                   5154: # This function retrieves a keyed item from a specific named database in the
                   5155: # domain directory.
                   5156: #
                   5157: # Parameters:
1.565     raeburn  5158: #   $cmd             - Command request keyword (getdom).
1.348     raeburn  5159: #   $tail            - Tail of the command.  This is a colon separated list
                   5160: #                      consisting of the domain and the 'namespace' 
                   5161: #                      which selects the gdbm file to do the lookup in,
                   5162: #                      & separated list of keys to lookup.  Note that
                   5163: #                      the values are returned as an & separated list too.
                   5164: #   $client          - File descriptor open on the client.
                   5165: # Returns:
                   5166: #   1       - Continue processing.
                   5167: #   0       - Exit.
                   5168: #  Side effects:
                   5169: #     reply is written to $client.
                   5170: #
                   5171: 
                   5172: sub get_domain_handler {
                   5173:     my ($cmd, $tail, $client) = @_;
                   5174: 
1.536     raeburn  5175:     my $userinput = "$cmd:$tail";
                   5176: 
                   5177:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
1.573     raeburn  5178:     if (($namespace =~ /^enc/) || ($namespace eq 'private')) {
1.536     raeburn  5179:         &Failure( $client, "refused\n", $userinput);
                   5180:     } else {
1.565     raeburn  5181:         my $res = LONCAPA::Lond::get_dom($userinput);
                   5182:         if ($res =~ /^error:/) {
                   5183:             &Failure($client, \$res, $userinput);
1.536     raeburn  5184:         } else {
1.565     raeburn  5185:             &Reply($client, \$res, $userinput);
1.536     raeburn  5186:         }
                   5187:     }
                   5188: 
                   5189:     return 1;
                   5190: }
                   5191: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
                   5192: 
1.572     raeburn  5193: #
                   5194: # Encrypted get from the namespace database file at the domain level.
                   5195: # This function retrieves a keyed item from a specific named database in the
                   5196: # domain directory.
                   5197: #
                   5198: # Parameters:
                   5199: #   $cmd             - Command request keyword (egetdom).
                   5200: #   $tail            - Tail of the command.  This is a colon separated list
                   5201: #                      consisting of the domain and the 'namespace'
                   5202: #                      which selects the gdbm file to do the lookup in,
                   5203: #                      & separated list of keys to lookup.  Note that
                   5204: #                      the values are returned as an & separated list too.
                   5205: #   $client          - File descriptor open on the client.
                   5206: # Returns:
                   5207: #   1       - Continue processing.
                   5208: #   0       - Exit.
                   5209: #  Side effects:
                   5210: #     reply is encrypted before being written to $client.
                   5211: #
1.536     raeburn  5212: sub encrypted_get_domain_handler {
                   5213:     my ($cmd, $tail, $client) = @_;
                   5214: 
                   5215:     my $userinput = "$cmd:$tail";
1.348     raeburn  5216: 
1.573     raeburn  5217:     my ($udom,$namespace,$what) = split(/:/,$tail,3);
                   5218:     if ($namespace eq 'private') {
                   5219:         &Failure( $client, "refused\n", $userinput);
1.565     raeburn  5220:     } else {
1.573     raeburn  5221:         my $res = LONCAPA::Lond::get_dom($userinput);
                   5222:         if ($res =~ /^error:/) {
                   5223:             &Failure($client, \$res, $userinput);
                   5224:         } else {
                   5225:             if ($cipher) {
                   5226:                 my $cmdlength=length($res);
                   5227:                 $res.="         ";
                   5228:                 my $encres='';
                   5229:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5230:                     $encres.= unpack("H16",
                   5231:                                      $cipher->encrypt(substr($res,
                   5232:                                                              $encidx,
                   5233:                                                              8)));
                   5234:                 }
                   5235:                 &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5236:             } else {
                   5237:                 &Failure( $client, "error:no_key\n",$userinput);
1.536     raeburn  5238:             }
1.348     raeburn  5239:         }
                   5240:     }
                   5241:     return 1;
                   5242: }
1.536     raeburn  5243: &register_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348     raeburn  5244: 
1.420     raeburn  5245: #
1.572     raeburn  5246: # Encrypted get from the namespace database file at the domain level.
                   5247: # This function retrieves a keyed item from a specific named database in the
                   5248: # domain directory.
                   5249: #
                   5250: # Parameters:
                   5251: #   $cmd             - Command request keyword (lti).
                   5252: #   $tail            - Tail of the command.  This is a colon-separated list
                   5253: #                      consisting of the domain, coursenum, if for LTI-
                   5254: #                      enabled deep-linking to course content using
                   5255: #                      link protection configured within a course,
                   5256: #                      context (=deeplink) if for LTI-enabled deep-linking
                   5257: #                      to course content using LTI Provider settings
                   5258: #                      configured within a course's domain, the (escaped)
                   5259: #                      launch URL, the (escaped) method (typically POST),
                   5260: #                      and a frozen hash of the LTI launch parameters
                   5261: #                      from the LTI payload.
                   5262: #   $client          - File descriptor open on the client.
                   5263: # Returns:
                   5264: #   1       - Continue processing.
                   5265: #   0       - Exit.
                   5266: #  Side effects:
                   5267: #     The reply will contain an LTI itemID, if the signed LTI payload
                   5268: #     could be verified using the consumer key and the shared secret 
                   5269: #     available for that key (for the itemID) for either the course or domain, 
                   5270: #     depending on values for cnum and context. The reply is encrypted before 
                   5271: #     being written to $client.
                   5272: #
                   5273: sub lti_handler {
                   5274:     my ($cmd, $tail, $client) = @_;
                   5275: 
                   5276:     my $userinput = "$cmd:$tail";
                   5277: 
                   5278:     my ($cdom,$cnum,$context,$escurl,$escmethod,$items) = split(/:/,$tail);
                   5279:     my $url = &unescape($escurl);
                   5280:     my $method = &unescape($escmethod);
                   5281:     my $params = &Apache::lonnet::thaw_unescape($items);
                   5282:     my $res;
                   5283:     if ($cnum ne '') {
                   5284:         $res = &LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   5285:     } else {
                   5286:         $res = &LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   5287:     }
                   5288:     if ($res =~ /^error:/) {
                   5289:         &Failure($client, \$res, $userinput);
                   5290:     } else {
                   5291:         if ($cipher) {
                   5292:             my $cmdlength=length($res);
                   5293:             $res.="         ";
                   5294:             my $encres='';
                   5295:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5296:                 $encres.= unpack("H16",
                   5297:                                  $cipher->encrypt(substr($res,
                   5298:                                                          $encidx,
                   5299:                                                          8)));
                   5300:             }
                   5301:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5302:         } else {
                   5303:             &Failure( $client, "error:no_key\n",$userinput);
                   5304:         }
                   5305:     }
                   5306:     return 1;
                   5307: }
                   5308: &register_handler("lti", \&lti_handler, 1, 1, 0);
                   5309: 
                   5310: #
1.577     raeburn  5311: # LTI data for launch payload (received encrypted) are unencrypted and
                   5312: # then signed with the appropriate key and secret, before re-encrypting
                   5313: # for sending as the signed payload to the client (caller lonnet::sign_lti()).
                   5314: #
                   5315: # Parameters:
                   5316: #   $cmd             - Command request keyword (signlti).
                   5317: #   $tail            - Tail of the command.  This is a colon-separated list
                   5318: #                      consisting of the domain, coursenum (if for an External
1.578   ! raeburn  5319: #                      Tool defined in a course), crsdef (true if defined in
        !          5320: #                      a course), context (launch, roster, logout, or grade),
        !          5321: #                      escaped launch URL, numeric ID of external tool,
1.577     raeburn  5322: #                      version number for encryption key (if tool's LTI secret was
1.578   ! raeburn  5323: #                      encrypted before storing), a frozen hash of LTI launch 
        !          5324: #                      parameters, and a frozen hash of LTI information,
        !          5325: #                      (e.g., method => 'HMAC-SHA1',
        !          5326: #                             respfmt => 'to_authorization_header').
1.577     raeburn  5327: #   $client          - File descriptor open on the client.
                   5328: # Returns:
                   5329: #   1       - Continue processing.
                   5330: #   0       - Exit.
                   5331: #  Side effects:
                   5332: #     The reply will contain the LTI payload, as & separated key=value pairs,
                   5333: #     where value is itself a frozen hash, if the required key and secret
                   5334: #     for the apecific tool ID are available. The payload data are retrived from
1.578   ! raeburn  5335: #     a call to Lond::sign_lti_payload(), and the reply is encrypted before being
1.577     raeburn  5336: #     written to $client.
                   5337: #
                   5338: sub sign_lti_handler {
                   5339:     my ($cmd, $tail, $client) = @_;
                   5340: 
                   5341:     my $userinput = "$cmd:$tail";
                   5342: 
1.578   ! raeburn  5343:     my ($cdom,$cnum,$crsdef,$context,$escurl,$ltinum,$keynum,$paramsref,$inforef) = split(/:/,$tail);
1.577     raeburn  5344:     my $url = &unescape($escurl);
                   5345:     my $params = &Apache::lonnet::thaw_unescape($paramsref);
                   5346:     my $info = &Apache::lonnet::thaw_unescape($inforef);
                   5347:     my $res =
1.578   ! raeburn  5348:         &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$context,$url,$ltinum,$keynum,
        !          5349:                                          $perlvar{'lonVersion'},$params,$info);
1.577     raeburn  5350:     my $result;
                   5351:     if (ref($res) eq 'HASH') {
                   5352:         foreach my $key (keys(%{$res})) {
                   5353:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($res->{$key}).'&';
                   5354:         }
                   5355:         $result =~ s/\&$//;
                   5356:     } else {
                   5357:         $result = $res;
                   5358:     }
                   5359:     if ($result =~ /^error:/) {
                   5360:         &Failure($client, \$result, $userinput);
                   5361:     } else {
                   5362:         if ($cipher) {
                   5363:             my $cmdlength=length($result);
                   5364:             $result.="         ";
                   5365:             my $encres='';
                   5366:             for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5367:                 $encres.= unpack("H16",
                   5368:                                  $cipher->encrypt(substr($result,
                   5369:                                                          $encidx,
                   5370:                                                          8)));
                   5371:             }
                   5372:             &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
                   5373:         } else {
                   5374:             &Failure( $client, "error:no_key\n",$userinput);
                   5375:         }
                   5376:     }
                   5377:     return 1;
                   5378: }
                   5379: &register_handler("signlti", \&sign_lti_handler, 1, 1, 0);
                   5380: 
                   5381: #
1.238     foxr     5382: #  Puts an id to a domains id database. 
                   5383: #
                   5384: #  Parameters:
                   5385: #   $cmd     - The command that triggered us.
                   5386: #   $tail    - Remainder of the request other than the command. This is a 
                   5387: #              colon separated list containing:
                   5388: #              $domain  - The domain for which we are writing the id.
                   5389: #              $pairs  - The id info to write... this is and & separated list
                   5390: #                        of keyword=value.
                   5391: #   $client  - Socket open on the client.
                   5392: #  Returns:
                   5393: #    1   - Continue processing.
                   5394: #  Side effects:
                   5395: #     reply is written to $client.
                   5396: #
                   5397: sub put_id_handler {
                   5398:     my ($cmd,$tail,$client) = @_;
                   5399: 
                   5400: 
                   5401:     my $userinput = "$cmd:$tail";
                   5402: 
                   5403:     my ($udom,$what)=split(/:/,$tail);
                   5404:     chomp($what);
                   5405:     my @pairs=split(/\&/,$what);
                   5406:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5407: 				   "P", $what);
                   5408:     if ($hashref) {
                   5409: 	foreach my $pair (@pairs) {
                   5410: 	    my ($key,$value)=split(/=/,$pair);
                   5411: 	    $hashref->{$key}=$value;
                   5412: 	}
1.311     albertel 5413: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5414: 	    &Reply($client, "ok\n", $userinput);
                   5415: 	} else {
                   5416: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5417: 		     "while attempting idput\n", $userinput);
                   5418: 	}
                   5419:     } else {
                   5420: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5421: 		  "while attempting idput\n", $userinput);
                   5422:     }
                   5423: 
                   5424:     return 1;
                   5425: }
1.263     albertel 5426: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     5427: 
                   5428: #
                   5429: #  Retrieves a set of id values from the id database.
                   5430: #  Returns an & separated list of results, one for each requested id to the
                   5431: #  client.
                   5432: #
                   5433: # Parameters:
                   5434: #   $cmd       - Command keyword that caused us to be dispatched.
                   5435: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5436: #               domain - the domain whose id table we dump
                   5437: #               ids      Consists of an & separated list of
                   5438: #                        id keywords whose values will be fetched.
                   5439: #                        nonexisting keywords will have an empty value.
                   5440: #   $client    - Socket open on the client.
                   5441: #
                   5442: # Returns:
                   5443: #    1 - indicating processing should continue.
                   5444: # Side effects:
                   5445: #   An & separated list of results is written to $client.
                   5446: #
                   5447: sub get_id_handler {
                   5448:     my ($cmd, $tail, $client) = @_;
                   5449: 
                   5450:     
                   5451:     my $userinput = "$client:$tail";
                   5452:     
                   5453:     my ($udom,$what)=split(/:/,$tail);
                   5454:     chomp($what);
                   5455:     my @queries=split(/\&/,$what);
                   5456:     my $qresult='';
                   5457:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   5458:     if ($hashref) {
                   5459: 	for (my $i=0;$i<=$#queries;$i++) {
                   5460: 	    $qresult.="$hashref->{$queries[$i]}&";
                   5461: 	}
1.311     albertel 5462: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     5463: 	    $qresult=~s/\&$//;
1.387     albertel 5464: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     5465: 	} else {
                   5466: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5467: 		      "while attempting idget\n",$userinput);
                   5468: 	}
                   5469:     } else {
                   5470: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5471: 		 "while attempting idget\n",$userinput);
                   5472:     }
                   5473:     
                   5474:     return 1;
                   5475: }
1.263     albertel 5476: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     5477: 
1.501     raeburn  5478: #   Deletes one or more ids in a domain's id database.
                   5479: #
                   5480: #   Parameters:
                   5481: #       $cmd                  - Command keyword (iddel).
                   5482: #       $tail                 - Command tail.  In this case a colon
                   5483: #                               separated list containing:
                   5484: #                               The domain for which we are deleting the id(s).
                   5485: #                               &-separated list of id(s) to delete.
                   5486: #       $client               - File open on client socket.
                   5487: # Returns:
                   5488: #     1   - Continue processing
                   5489: #     0   - Exit server.
                   5490: #     
                   5491: #
                   5492: 
                   5493: sub del_id_handler {
                   5494:     my ($cmd,$tail,$client) = @_;
                   5495: 
                   5496:     my $userinput = "$cmd:$tail";
                   5497: 
                   5498:     my ($udom,$what)=split(/:/,$tail);
                   5499:     chomp($what);
                   5500:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   5501:                                    "D", $what);
                   5502:     if ($hashref) {
                   5503:         my @keys=split(/\&/,$what);
                   5504:         foreach my $key (@keys) {
                   5505:             delete($hashref->{$key});
                   5506:         }
                   5507:         if (&untie_user_hash($hashref)) {
                   5508:             &Reply($client, "ok\n", $userinput);
                   5509:         } else {
                   5510:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5511:                     "while attempting iddel\n", $userinput);
                   5512:         }
                   5513:     } else {
                   5514:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5515:                  "while attempting iddel\n", $userinput);
                   5516:     }
                   5517:     return 1;
                   5518: }
                   5519: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   5520: 
1.238     foxr     5521: #
1.299     raeburn  5522: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   5523: #
                   5524: # Parameters
                   5525: #   $cmd       - Command keyword that caused us to be dispatched.
                   5526: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5527: #               domain - the domain whose dcmail we are recording
                   5528: #               email    Consists of key=value pair 
                   5529: #                        where key is unique msgid
                   5530: #                        and value is message (in XML)
                   5531: #   $client    - Socket open on the client.
                   5532: #
                   5533: # Returns:
                   5534: #    1 - indicating processing should continue.
                   5535: # Side effects
                   5536: #     reply is written to $client.
                   5537: #
                   5538: sub put_dcmail_handler {
                   5539:     my ($cmd,$tail,$client) = @_;
                   5540:     my $userinput = "$cmd:$tail";
1.463     foxr     5541: 
                   5542: 
1.299     raeburn  5543:     my ($udom,$what)=split(/:/,$tail);
                   5544:     chomp($what);
                   5545:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5546:     if ($hashref) {
                   5547:         my ($key,$value)=split(/=/,$what);
                   5548:         $hashref->{$key}=$value;
                   5549:     }
1.311     albertel 5550:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  5551:         &Reply($client, "ok\n", $userinput);
                   5552:     } else {
                   5553:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5554:                  "while attempting dcmailput\n", $userinput);
                   5555:     }
                   5556:     return 1;
                   5557: }
                   5558: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   5559: 
                   5560: #
                   5561: # Retrieves broadcast e-mail from nohist_dcmail database
                   5562: # Returns to client an & separated list of key=value pairs,
                   5563: # where key is msgid and value is message information.
                   5564: #
                   5565: # Parameters
                   5566: #   $cmd       - Command keyword that caused us to be dispatched.
                   5567: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5568: #               domain - the domain whose dcmail table we dump
                   5569: #               startfilter - beginning of time window 
                   5570: #               endfilter - end of time window
                   5571: #               sendersfilter - & separated list of username:domain 
                   5572: #                 for senders to search for.
                   5573: #   $client    - Socket open on the client.
                   5574: #
                   5575: # Returns:
                   5576: #    1 - indicating processing should continue.
                   5577: # Side effects
                   5578: #     reply (& separated list of msgid=messageinfo pairs) is 
                   5579: #     written to $client.
                   5580: #
                   5581: sub dump_dcmail_handler {
                   5582:     my ($cmd, $tail, $client) = @_;
                   5583:                                                                                 
                   5584:     my $userinput = "$cmd:$tail";
                   5585:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   5586:     chomp($sendersfilter);
                   5587:     my @senders = ();
                   5588:     if (defined($startfilter)) {
                   5589:         $startfilter=&unescape($startfilter);
                   5590:     } else {
                   5591:         $startfilter='.';
                   5592:     }
                   5593:     if (defined($endfilter)) {
                   5594:         $endfilter=&unescape($endfilter);
                   5595:     } else {
                   5596:         $endfilter='.';
                   5597:     }
                   5598:     if (defined($sendersfilter)) {
                   5599:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 5600: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  5601:     }
                   5602: 
                   5603:     my $qresult='';
                   5604:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   5605:     if ($hashref) {
                   5606:         while (my ($key,$value) = each(%$hashref)) {
                   5607:             my $match = 1;
1.303     albertel 5608:             my ($timestamp,$subj,$uname,$udom) = 
                   5609: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  5610:             $subj = &unescape($subj);
                   5611:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   5612:                 if ($timestamp < $startfilter) {
                   5613:                     $match = 0;
                   5614:                 }
                   5615:             }
                   5616:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5617:                 if ($timestamp > $endfilter) {
                   5618:                     $match = 0;
                   5619:                 }
                   5620:             }
                   5621:             unless (@senders < 1) {
                   5622:                 unless (grep/^$uname:$udom$/,@senders) {
                   5623:                     $match = 0;
                   5624:                 }
                   5625:             }
                   5626:             if ($match == 1) {
                   5627:                 $qresult.=$key.'='.$value.'&';
                   5628:             }
                   5629:         }
1.311     albertel 5630:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5631:             chop($qresult);
1.387     albertel 5632:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5633:         } else {
                   5634:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5635:                     "while attempting dcmaildump\n", $userinput);
                   5636:         }
                   5637:     } else {
                   5638:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5639:                 "while attempting dcmaildump\n", $userinput);
                   5640:     }
                   5641:     return 1;
                   5642: }
                   5643: 
                   5644: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5645: 
                   5646: #
                   5647: # Puts domain roles in nohist_domainroles database
                   5648: #
                   5649: # Parameters
                   5650: #   $cmd       - Command keyword that caused us to be dispatched.
                   5651: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5652: #               domain - the domain whose roles we are recording  
                   5653: #               role -   Consists of key=value pair
                   5654: #                        where key is unique role
                   5655: #                        and value is start/end date information
                   5656: #   $client    - Socket open on the client.
                   5657: #
                   5658: # Returns:
                   5659: #    1 - indicating processing should continue.
                   5660: # Side effects
                   5661: #     reply is written to $client.
                   5662: #
                   5663: 
                   5664: sub put_domainroles_handler {
                   5665:     my ($cmd,$tail,$client) = @_;
                   5666: 
                   5667:     my $userinput = "$cmd:$tail";
                   5668:     my ($udom,$what)=split(/:/,$tail);
                   5669:     chomp($what);
                   5670:     my @pairs=split(/\&/,$what);
                   5671:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5672:     if ($hashref) {
                   5673:         foreach my $pair (@pairs) {
                   5674:             my ($key,$value)=split(/=/,$pair);
                   5675:             $hashref->{$key}=$value;
                   5676:         }
1.311     albertel 5677:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5678:             &Reply($client, "ok\n", $userinput);
                   5679:         } else {
                   5680:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5681:                      "while attempting domroleput\n", $userinput);
                   5682:         }
                   5683:     } else {
                   5684:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5685:                   "while attempting domroleput\n", $userinput);
                   5686:     }
                   5687:                                                                                   
                   5688:     return 1;
                   5689: }
                   5690: 
                   5691: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5692: 
                   5693: #
                   5694: # Retrieves domain roles from nohist_domainroles database
                   5695: # Returns to client an & separated list of key=value pairs,
                   5696: # where key is role and value is start and end date information.
                   5697: #
                   5698: # Parameters
                   5699: #   $cmd       - Command keyword that caused us to be dispatched.
                   5700: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5701: #               domain - the domain whose domain roles table we dump
                   5702: #   $client    - Socket open on the client.
                   5703: #
                   5704: # Returns:
                   5705: #    1 - indicating processing should continue.
                   5706: # Side effects
                   5707: #     reply (& separated list of role=start/end info pairs) is
                   5708: #     written to $client.
                   5709: #
                   5710: sub dump_domainroles_handler {
                   5711:     my ($cmd, $tail, $client) = @_;
                   5712:                                                                                            
                   5713:     my $userinput = "$cmd:$tail";
                   5714:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5715:     chomp($rolesfilter);
                   5716:     my @roles = ();
                   5717:     if (defined($startfilter)) {
                   5718:         $startfilter=&unescape($startfilter);
                   5719:     } else {
                   5720:         $startfilter='.';
                   5721:     }
                   5722:     if (defined($endfilter)) {
                   5723:         $endfilter=&unescape($endfilter);
                   5724:     } else {
                   5725:         $endfilter='.';
                   5726:     }
                   5727:     if (defined($rolesfilter)) {
                   5728:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5729: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5730:     }
1.421     raeburn  5731: 
1.299     raeburn  5732:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5733:     if ($hashref) {
                   5734:         my $qresult = '';
                   5735:         while (my ($key,$value) = each(%$hashref)) {
                   5736:             my $match = 1;
1.421     raeburn  5737:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5738:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5739:             unless (@roles < 1) {
                   5740:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5741:                     $match = 0;
                   5742:                     next;
                   5743:                 }
                   5744:             }
1.299     raeburn  5745:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5746:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5747:                     $match = 0;
1.421     raeburn  5748:                     next;
1.299     raeburn  5749:                 }
                   5750:             }
                   5751:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5752:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5753:                     $match = 0;
1.421     raeburn  5754:                     next;
1.299     raeburn  5755:                 }
                   5756:             }
                   5757:             if ($match == 1) {
                   5758:                 $qresult.=$key.'='.$value.'&';
                   5759:             }
                   5760:         }
1.311     albertel 5761:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5762:             chop($qresult);
1.387     albertel 5763:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5764:         } else {
                   5765:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5766:                     "while attempting domrolesdump\n", $userinput);
                   5767:         }
                   5768:     } else {
                   5769:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5770:                 "while attempting domrolesdump\n", $userinput);
                   5771:     }
                   5772:     return 1;
                   5773: }
                   5774: 
                   5775: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5776: 
                   5777: 
1.238     foxr     5778: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5779: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5780: # where Id is the client's ip concatenated with a sequence number.
                   5781: # The file will contain some value that is passed in.  Is this e.g.
                   5782: # a login token?
                   5783: #
                   5784: # Parameters:
                   5785: #    $cmd     - The command that got us dispatched.
                   5786: #    $tail    - The remainder of the request following $cmd:
                   5787: #               In this case this will be the contents of the file.
                   5788: #    $client  - Socket connected to the client.
                   5789: # Returns:
                   5790: #    1 indicating processing can continue.
                   5791: # Side effects:
                   5792: #   A file is created in the local filesystem.
                   5793: #   A reply is sent to the client.
                   5794: sub tmp_put_handler {
                   5795:     my ($cmd, $what, $client) = @_;
                   5796: 
                   5797:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5798: 
1.347     raeburn  5799:     my ($record,$context) = split(/:/,$what);
                   5800:     if ($context ne '') {
                   5801:         chomp($context);
                   5802:         $context = &unescape($context);
                   5803:     }
                   5804:     my ($id,$store);
1.238     foxr     5805:     $tmpsnum++;
1.569     raeburn  5806:     my $numtries = 0;
                   5807:     my $execdir=$perlvar{'lonDaemons'};
                   5808:     if (($context eq 'resetpw') || ($context eq 'createaccount') ||
                   5809:         ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
                   5810:         $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5811:         while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
                   5812:             undef($id);
                   5813:             $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
                   5814:             $numtries ++;
                   5815:         }
1.347     raeburn  5816:     } else {
                   5817:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5818:     }
1.238     foxr     5819:     $id=~s/\W/\_/g;
1.347     raeburn  5820:     $record=~s/\n//g;
1.569     raeburn  5821:     if (($id ne '') &&
                   5822:         ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
1.347     raeburn  5823: 	print $store $record;
1.238     foxr     5824: 	close $store;
1.387     albertel 5825: 	&Reply($client, \$id, $userinput);
1.238     foxr     5826:     } else {
                   5827: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5828: 		  "while attempting tmpput\n", $userinput);
                   5829:     }
                   5830:     return 1;
                   5831:   
                   5832: }
                   5833: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5834: 
1.238     foxr     5835: #   Processes the tmpget command.  This command returns the contents
                   5836: #  of a temporary resource file(?) created via tmpput.
                   5837: #
                   5838: # Paramters:
                   5839: #    $cmd      - Command that got us dispatched.
                   5840: #    $id       - Tail of the command, contain the id of the resource
                   5841: #                we want to fetch.
                   5842: #    $client   - socket open on the client.
                   5843: # Return:
                   5844: #    1         - Inidcating processing can continue.
                   5845: # Side effects:
                   5846: #   A reply is sent to the client.
                   5847: #
                   5848: sub tmp_get_handler {
                   5849:     my ($cmd, $id, $client) = @_;
                   5850: 
                   5851:     my $userinput = "$cmd:$id"; 
                   5852:     
                   5853: 
                   5854:     $id=~s/\W/\_/g;
                   5855:     my $store;
                   5856:     my $execdir=$perlvar{'lonDaemons'};
                   5857:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5858: 	my $reply=<$store>;
1.387     albertel 5859: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5860: 	close $store;
                   5861:     } else {
                   5862: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5863: 		  "while attempting tmpget\n", $userinput);
                   5864:     }
                   5865: 
                   5866:     return 1;
                   5867: }
                   5868: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5869: 
1.238     foxr     5870: #
                   5871: #  Process the tmpdel command.  This command deletes a temp resource
                   5872: #  created by the tmpput command.
                   5873: #
                   5874: # Parameters:
                   5875: #   $cmd      - Command that got us here.
                   5876: #   $id       - Id of the temporary resource created.
                   5877: #   $client   - socket open on the client process.
                   5878: #
                   5879: # Returns:
                   5880: #   1     - Indicating processing should continue.
                   5881: # Side Effects:
                   5882: #   A file is deleted
                   5883: #   A reply is sent to the client.
                   5884: sub tmp_del_handler {
                   5885:     my ($cmd, $id, $client) = @_;
                   5886:     
                   5887:     my $userinput= "$cmd:$id";
                   5888:     
                   5889:     chomp($id);
                   5890:     $id=~s/\W/\_/g;
                   5891:     my $execdir=$perlvar{'lonDaemons'};
                   5892:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5893: 	&Reply($client, "ok\n", $userinput);
                   5894:     } else {
                   5895: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5896: 		  "while attempting tmpdel\n", $userinput);
                   5897:     }
                   5898:     
                   5899:     return 1;
                   5900: 
                   5901: }
                   5902: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5903: 
1.238     foxr     5904: #
1.564     raeburn  5905: #  Process the updatebalcookie command.  This command updates a
                   5906: #  cookie in the lonBalancedir directory on a load balancer node.
                   5907: #
                   5908: # Parameters:
                   5909: #   $cmd      - Command that got us here.
                   5910: #   $tail     - Tail of the request (escaped cookie: escaped current entry)
                   5911: #
                   5912: #   $client   - socket open on the client process.
                   5913: #
                   5914: # Returns:
                   5915: #   1     - Indicating processing should continue.
                   5916: # Side Effects:
                   5917: #   A cookie file is updated from the lonBalancedir directory
                   5918: #   A reply is sent to the client.
                   5919: #
                   5920: sub update_balcookie_handler {
                   5921:     my ($cmd, $tail, $client) = @_;
                   5922: 
                   5923:     my $userinput= "$cmd:$tail";
                   5924:     chomp($tail);
                   5925:     my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
                   5926: 
                   5927:     my $updatedone;
                   5928:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5929:         my $execdir=$perlvar{'lonBalanceDir'};
                   5930:         if (-e "$execdir/$cookie.id") {
                   5931:             my $doupdate;
                   5932:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5933:                 while (my $line = <$fh>) {
                   5934:                     chomp($line);
                   5935:                     if ($line eq $lastentry) {
                   5936:                         $doupdate = 1;
                   5937:                         last;
                   5938:                     }
                   5939:                 }
                   5940:                 close($fh);
                   5941:             }
                   5942:             if ($doupdate) {
                   5943:                 if (open(my $fh,'>',"$execdir/$cookie.id")) {
                   5944:                     print $fh $clientname;
                   5945:                     close($fh);
                   5946:                     $updatedone = 1;
                   5947:                 }
                   5948:             }
                   5949:         }
                   5950:     }
                   5951:     if ($updatedone) {
                   5952:         &Reply($client, "ok\n", $userinput);
                   5953:     } else {
                   5954:         &Failure( $client, "error: ".($!+0)."file update failed ".
                   5955:                   "while attempting updatebalcookie\n", $userinput);
                   5956:     }
                   5957:     return 1;
                   5958: }
                   5959: &register_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
                   5960: 
                   5961: #
1.551     raeburn  5962: #  Process the delbalcookie command. This command deletes a balancer
1.564     raeburn  5963: #  cookie in the lonBalancedir directory on a load balancer node.
1.551     raeburn  5964: #
                   5965: # Parameters:
                   5966: #   $cmd      - Command that got us here.
                   5967: #   $cookie   - Cookie to be deleted.
                   5968: #   $client   - socket open on the client process.
                   5969: #
                   5970: # Returns:
                   5971: #   1     - Indicating processing should continue.
                   5972: # Side Effects:
                   5973: #   A cookie file is deleted from the lonBalancedir directory
                   5974: #   A reply is sent to the client.
                   5975: sub del_balcookie_handler {
                   5976:     my ($cmd, $cookie, $client) = @_;
                   5977: 
                   5978:     my $userinput= "$cmd:$cookie";
                   5979: 
                   5980:     chomp($cookie);
1.564     raeburn  5981:     $cookie = &unescape($cookie);
1.551     raeburn  5982:     my $deleted = '';
                   5983:     if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
                   5984:         my $execdir=$perlvar{'lonBalanceDir'};
                   5985:         if (-e "$execdir/$cookie.id") {
                   5986:             if (open(my $fh,'<',"$execdir/$cookie.id")) {
                   5987:                 my $dodelete;
                   5988:                 while (my $line = <$fh>) {
                   5989:                     chomp($line);
                   5990:                     if ($line eq $clientname) {
                   5991:                         $dodelete = 1;
1.554     raeburn  5992:                         last;
1.551     raeburn  5993:                     }
                   5994:                 }
1.554     raeburn  5995:                 close($fh);
1.551     raeburn  5996:                 if ($dodelete) {
                   5997:                     if (unlink("$execdir/$cookie.id")) {
                   5998:                         $deleted = 1;
                   5999:                     }
                   6000:                 }
                   6001:             }
                   6002:         }
                   6003:     }
                   6004:     if ($deleted) {
                   6005:         &Reply($client, "ok\n", $userinput);
                   6006:     } else {
                   6007:         &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
                   6008:                   "while attempting delbalcookie\n", $userinput);
                   6009:     }
                   6010:     return 1;
                   6011: }
                   6012: &register_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
                   6013: 
                   6014: #
1.246     foxr     6015: #   Processes the setannounce command.  This command
                   6016: #   creates a file named announce.txt in the top directory of
                   6017: #   the documentn root and sets its contents.  The announce.txt file is
                   6018: #   printed in its entirety at the LonCAPA login page.  Note:
                   6019: #   once the announcement.txt fileis created it cannot be deleted.
                   6020: #   However, setting the contents of the file to empty removes the
                   6021: #   announcement from the login page of loncapa so who cares.
                   6022: #
                   6023: # Parameters:
                   6024: #    $cmd          - The command that got us dispatched.
                   6025: #    $announcement - The text of the announcement.
                   6026: #    $client       - Socket open on the client process.
                   6027: # Retunrns:
                   6028: #   1             - Indicating request processing should continue
                   6029: # Side Effects:
                   6030: #   The file {DocRoot}/announcement.txt is created.
                   6031: #   A reply is sent to $client.
                   6032: #
                   6033: sub set_announce_handler {
                   6034:     my ($cmd, $announcement, $client) = @_;
                   6035:   
                   6036:     my $userinput    = "$cmd:$announcement";
                   6037: 
                   6038:     chomp($announcement);
                   6039:     $announcement=&unescape($announcement);
                   6040:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   6041: 				'/announcement.txt')) {
                   6042: 	print $store $announcement;
                   6043: 	close $store;
                   6044: 	&Reply($client, "ok\n", $userinput);
                   6045:     } else {
                   6046: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   6047:     }
                   6048: 
                   6049:     return 1;
                   6050: }
                   6051: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 6052: 
1.246     foxr     6053: #
                   6054: #  Return the version of the daemon.  This can be used to determine
                   6055: #  the compatibility of cross version installations or, alternatively to
                   6056: #  simply know who's out of date and who isn't.  Note that the version
                   6057: #  is returned concatenated with the tail.
                   6058: # Parameters:
                   6059: #   $cmd        - the request that dispatched to us.
                   6060: #   $tail       - Tail of the request (client's version?).
                   6061: #   $client     - Socket open on the client.
                   6062: #Returns:
                   6063: #   1 - continue processing requests.
                   6064: # Side Effects:
                   6065: #   Replies with version to $client.
                   6066: sub get_version_handler {
                   6067:     my ($cmd, $tail, $client) = @_;
                   6068: 
                   6069:     my $userinput  = $cmd.$tail;
                   6070:     
                   6071:     &Reply($client, &version($userinput)."\n", $userinput);
                   6072: 
                   6073: 
                   6074:     return 1;
                   6075: }
                   6076: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 6077: 
1.246     foxr     6078: #  Set the current host and domain.  This is used to support
                   6079: #  multihomed systems.  Each IP of the system, or even separate daemons
                   6080: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   6081: #  machine.  This command selects the virtual lonCAPA.  The client always
                   6082: #  knows the right one since it is lonc and it is selecting the domain/system
                   6083: #  from the hosts.tab file.
                   6084: # Parameters:
                   6085: #    $cmd      - Command that dispatched us.
                   6086: #    $tail     - Tail of the command (domain/host requested).
                   6087: #    $socket   - Socket open on the client.
                   6088: #
                   6089: # Returns:
                   6090: #     1   - Indicates the program should continue to process requests.
                   6091: # Side-effects:
                   6092: #     The default domain/system context is modified for this daemon.
                   6093: #     a reply is sent to the client.
                   6094: #
                   6095: sub set_virtual_host_handler {
                   6096:     my ($cmd, $tail, $socket) = @_;
                   6097:   
                   6098:     my $userinput  ="$cmd:$tail";
                   6099: 
                   6100:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   6101: 
                   6102: 
                   6103:     return 1;
                   6104: }
1.247     albertel 6105: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     6106: 
                   6107: #  Process a request to exit:
                   6108: #   - "bye" is sent to the client.
                   6109: #   - The client socket is shutdown and closed.
                   6110: #   - We indicate to the caller that we should exit.
                   6111: # Formal Parameters:
                   6112: #   $cmd                - The command that got us here.
                   6113: #   $tail               - Tail of the command (empty).
                   6114: #   $client             - Socket open on the tail.
                   6115: # Returns:
                   6116: #   0      - Indicating the program should exit!!
                   6117: #
                   6118: sub exit_handler {
                   6119:     my ($cmd, $tail, $client) = @_;
                   6120: 
                   6121:     my $userinput = "$cmd:$tail";
                   6122: 
                   6123:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   6124:     &Reply($client, "bye\n", $userinput);
                   6125:     $client->shutdown(2);        # shutdown the socket forcibly.
                   6126:     $client->close();
                   6127: 
                   6128:     return 0;
                   6129: }
1.248     foxr     6130: &register_handler("exit", \&exit_handler, 0,1,1);
                   6131: &register_handler("init", \&exit_handler, 0,1,1);
                   6132: &register_handler("quit", \&exit_handler, 0,1,1);
                   6133: 
                   6134: #  Determine if auto-enrollment is enabled.
                   6135: #  Note that the original had what I believe to be a defect.
                   6136: #  The original returned 0 if the requestor was not a registerd client.
                   6137: #  It should return "refused".
                   6138: # Formal Parameters:
                   6139: #   $cmd       - The command that invoked us.
                   6140: #   $tail      - The tail of the command (Extra command parameters.
                   6141: #   $client    - The socket open on the client that issued the request.
                   6142: # Returns:
                   6143: #    1         - Indicating processing should continue.
                   6144: #
                   6145: sub enrollment_enabled_handler {
                   6146:     my ($cmd, $tail, $client) = @_;
                   6147:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   6148: 
                   6149:     
1.337     albertel 6150:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   6151: 
1.248     foxr     6152:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 6153:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6154: 
                   6155:     return 1;
                   6156: }
                   6157: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   6158: 
1.417     raeburn  6159: #
1.423     raeburn  6160: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  6161: #
                   6162: # Formal Parameters:
                   6163: #   $cmd          - The command request that got us dispatched.
                   6164: #   $tail         - The tail of the command.  In this case,
                   6165: #                   this is a colon separated set of words that will be split
                   6166: #                   into:
1.424     raeburn  6167: #                        $dom      - The domain for which the check of 
                   6168: #                                    institutional course code will occur.
                   6169: #
                   6170: #                        $instcode - The institutional code for the course
                   6171: #                                    being requested, or validated for rights
                   6172: #                                    to request.
                   6173: #
                   6174: #                        $owner    - The course requestor (who will be the
                   6175: #                                    course owner, in the form username:domain
                   6176: #
1.417     raeburn  6177: #   $client       - Socket open on the client.
                   6178: # Returns:
                   6179: #    1           - Indicating processing should continue.
                   6180: #
                   6181: sub validate_instcode_handler {
                   6182:     my ($cmd, $tail, $client) = @_;
                   6183:     my $userinput = "$cmd:$tail";
1.423     raeburn  6184:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  6185:     $instcode = &unescape($instcode);
                   6186:     $owner = &unescape($owner);
1.498     raeburn  6187:     my ($outcome,$description,$credits) = 
1.426     raeburn  6188:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  6189:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   6190:                  &escape($credits);
1.426     raeburn  6191:     &Reply($client, \$result, $userinput);
1.417     raeburn  6192: 
                   6193:     return 1;
                   6194: }
                   6195: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   6196: 
1.566     raeburn  6197: #
                   6198: #  Validate co-owner for cross-listed institutional code and
                   6199: #  institutional course code itself used for a LON-CAPA course.
                   6200: #
                   6201: # Formal Parameters:
                   6202: #   $cmd          - The command request that got us dispatched.
                   6203: #   $tail         - The tail of the command.  In this case,
                   6204: #                   this is a colon separated string containing:
                   6205: #      $dom            - Course's LON-CAPA domain
                   6206: #      $instcode       - Institutional course code for the course
                   6207: #      $inst_xlist     - Institutional course Id for the crosslisting
                   6208: #      $coowner        - Username of co-owner
                   6209: #      (values for all but $dom have been escaped). 
                   6210: #
                   6211: #   $client       - Socket open on the client.
                   6212: # Returns:
                   6213: #    1           - Indicating processing should continue.
                   6214: #
                   6215: sub validate_instcrosslist_handler  {
                   6216:     my ($cmd, $tail, $client) = @_;
                   6217:     my $userinput = "$cmd:$tail";
                   6218:     my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
                   6219:     $instcode = &unescape($instcode);
                   6220:     $inst_xlist = &unescape($inst_xlist);
                   6221:     $coowner = &unescape($coowner);
                   6222:     my $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
                   6223:                                                           $inst_xlist,$coowner);
                   6224:     &Reply($client, \$outcome, $userinput);
                   6225: 
                   6226:     return 1;
                   6227: }
                   6228: &register_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
                   6229: 
1.248     foxr     6230: #   Get the official sections for which auto-enrollment is possible.
                   6231: #   Since the admin people won't know about 'unofficial sections' 
                   6232: #   we cannot auto-enroll on them.
                   6233: # Formal Parameters:
                   6234: #    $cmd     - The command request that got us dispatched here.
                   6235: #    $tail    - The remainder of the request.  In our case this
                   6236: #               will be split into:
                   6237: #               $coursecode   - The course name from the admin point of view.
                   6238: #               $cdom         - The course's domain(?).
                   6239: #    $client  - Socket open on the client.
                   6240: # Returns:
                   6241: #    1    - Indiciting processing should continue.
                   6242: #
                   6243: sub get_sections_handler {
                   6244:     my ($cmd, $tail, $client) = @_;
                   6245:     my $userinput = "$cmd:$tail";
                   6246: 
                   6247:     my ($coursecode, $cdom) = split(/:/, $tail);
                   6248:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   6249:     my $seclist = &escape(join(':',@secs));
                   6250: 
1.387     albertel 6251:     &Reply($client, \$seclist, $userinput);
1.248     foxr     6252:     
                   6253: 
                   6254:     return 1;
                   6255: }
                   6256: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   6257: 
                   6258: #   Validate the owner of a new course section.  
                   6259: #
                   6260: # Formal Parameters:
                   6261: #   $cmd      - Command that got us dispatched.
                   6262: #   $tail     - the remainder of the command.  For us this consists of a
                   6263: #               colon separated string containing:
                   6264: #                  $inst    - Course Id from the institutions point of view.
                   6265: #                  $owner   - Proposed owner of the course.
                   6266: #                  $cdom    - Domain of the course (from the institutions
                   6267: #                             point of view?)..
                   6268: #   $client   - Socket open on the client.
                   6269: #
                   6270: # Returns:
                   6271: #   1        - Processing should continue.
                   6272: #
                   6273: sub validate_course_owner_handler {
                   6274:     my ($cmd, $tail, $client)  = @_;
                   6275:     my $userinput = "$cmd:$tail";
1.470     raeburn  6276:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   6277:     
1.336     raeburn  6278:     $owner = &unescape($owner);
1.470     raeburn  6279:     $coowners = &unescape($coowners);
                   6280:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 6281:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6282: 
                   6283: 
                   6284: 
                   6285:     return 1;
                   6286: }
                   6287: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 6288: 
1.248     foxr     6289: #
                   6290: #   Validate a course section in the official schedule of classes
                   6291: #   from the institutions point of view (part of autoenrollment).
                   6292: #
                   6293: # Formal Parameters:
                   6294: #   $cmd          - The command request that got us dispatched.
                   6295: #   $tail         - The tail of the command.  In this case,
                   6296: #                   this is a colon separated set of words that will be split
                   6297: #                   into:
                   6298: #                        $inst_course_id - The course/section id from the
                   6299: #                                          institutions point of view.
                   6300: #                        $cdom           - The domain from the institutions
                   6301: #                                          point of view.
                   6302: #   $client       - Socket open on the client.
                   6303: # Returns:
                   6304: #    1           - Indicating processing should continue.
                   6305: #
                   6306: sub validate_course_section_handler {
                   6307:     my ($cmd, $tail, $client) = @_;
                   6308:     my $userinput = "$cmd:$tail";
                   6309:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   6310: 
                   6311:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 6312:     &Reply($client, \$outcome, $userinput);
1.248     foxr     6313: 
                   6314: 
                   6315:     return 1;
                   6316: }
                   6317: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   6318: 
                   6319: #
1.340     raeburn  6320: #   Validate course owner's access to enrollment data for specific class section. 
                   6321: #   
                   6322: #
                   6323: # Formal Parameters:
                   6324: #    $cmd     - The command request that got us dispatched.
                   6325: #    $tail    - The tail of the command.   In this case this is a colon separated
1.542     raeburn  6326: #               set of values that will be split into:
1.340     raeburn  6327: #               $inst_class  - Institutional code for the specific class section   
1.542     raeburn  6328: #               $ownerlist   - An escaped comma-separated list of username:domain 
                   6329: #                              of the course owner, and co-owner(s).
1.340     raeburn  6330: #               $cdom        - The domain of the course from the institution's
                   6331: #                              point of view.
                   6332: #    $client  - The socket open on the client.
                   6333: # Returns:
                   6334: #    1 - continue processing.
                   6335: #
                   6336: 
                   6337: sub validate_class_access_handler {
                   6338:     my ($cmd, $tail, $client) = @_;
                   6339:     my $userinput = "$cmd:$tail";
1.383     raeburn  6340:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  6341:     my $owners = &unescape($ownerlist);
1.341     albertel 6342:     my $outcome;
                   6343:     eval {
                   6344: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  6345: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 6346:     };
1.387     albertel 6347:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  6348: 
                   6349:     return 1;
                   6350: }
                   6351: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   6352: 
                   6353: #
1.567     raeburn  6354: #    Modify institutional sections (using customized &instsec_reformat()
                   6355: #    routine in localenroll.pm), to either clutter or declutter, for  
                   6356: #    purposes of ensuring an institutional course section (string) can
                   6357: #    be unambiguously separated into institutional course and section.
                   6358: #
                   6359: # Formal Parameters:
                   6360: #    $cmd     - The command request that got us dispatched.
                   6361: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6362: #               set of values that will be split into:
                   6363: #               $cdom        - The LON-CAPA domain of the course.
                   6364: #               $action      - Either: clutter or declutter
                   6365: #                              clutter adds character(s) to eliminate ambiguity
                   6366: #                              declutter removes the added characters (e.g., for
                   6367: #                              display of the institutional course section string.
                   6368: #               $info        - A frozen hash in which keys are: 
                   6369: #                              LON-CAPA course number:Institutional course code
                   6370: #                              and values are a reference to an array of the
                   6371: #                              items to modify -- either institutional sections,
                   6372: #                              or institutional course sections (for crosslistings). 
                   6373: #    $client  - The socket open on the client.
                   6374: # Returns:
                   6375: #    1 - continue processing.
                   6376: #   
                   6377: 
                   6378: sub instsec_reformat_handler {
                   6379:     my ($cmd, $tail, $client) = @_;
                   6380:     my $userinput = "$cmd:$tail";
                   6381:     my ($cdom,$action,$info) = split(/:/,$tail);
                   6382:     my $instsecref = &Apache::lonnet::thaw_unescape($info);
                   6383:     my ($outcome,$result);
                   6384:     eval {
                   6385:         local($SIG{__DIE__})='DEFAULT';
                   6386:         $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
                   6387:         if ($outcome eq 'ok') {
                   6388:             if (ref($instsecref) eq 'HASH') {
                   6389:                 foreach my $key (keys(%{$instsecref})) {
                   6390:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
                   6391:                 }
                   6392:                 $result =~ s/\&$//;
                   6393:             }
                   6394:         }
                   6395:     };
                   6396:     if (!$@) {
                   6397:         if ($outcome eq 'ok') {
                   6398:             &Reply( $client, \$result, $userinput);
                   6399:         } else {
                   6400:             &Reply($client,\$outcome, $userinput);
                   6401:         }
                   6402:     } else {
                   6403:         &Failure($client,"unknown_cmd\n",$userinput);
                   6404:     }
                   6405:     return 1;
                   6406: }
                   6407: &register_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
                   6408: 
                   6409: #
1.542     raeburn  6410: #   Validate course owner or co-owners(s) access to enrollment data for all sections
                   6411: #   and crosslistings for a particular course.
                   6412: #
                   6413: #
                   6414: # Formal Parameters:
                   6415: #    $cmd     - The command request that got us dispatched.
                   6416: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6417: #               set of values that will be split into:
                   6418: #               $ownerlist   - An escaped comma-separated list of username:domain
                   6419: #                              of the course owner, and co-owner(s).
                   6420: #               $cdom        - The domain of the course from the institution's
                   6421: #                              point of view.
                   6422: #               $classes     - Frozen hash of institutional course sections and
                   6423: #                              crosslistings.
                   6424: #    $client  - The socket open on the client.
                   6425: # Returns:
                   6426: #    1 - continue processing.
                   6427: #
                   6428: 
                   6429: sub validate_classes_handler {
                   6430:     my ($cmd, $tail, $client) = @_;
                   6431:     my $userinput = "$cmd:$tail";
                   6432:     my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
                   6433:     my $classesref = &Apache::lonnet::thaw_unescape($classes);
                   6434:     my $owners = &unescape($ownerlist);
                   6435:     my $result;
                   6436:     eval {
                   6437:         local($SIG{__DIE__})='DEFAULT';
                   6438:         my %validations;
                   6439:         my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
                   6440:                                                        \%validations);
                   6441:         if ($response eq 'ok') {
                   6442:             foreach my $key (keys(%validations)) {
                   6443:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6444:             }
                   6445:             $result =~ s/\&$//;
                   6446:         } else {
                   6447:             $result = 'error';
                   6448:         }
                   6449:     };
                   6450:     if (!$@) {
                   6451:         &Reply($client, \$result, $userinput);
                   6452:     } else {
                   6453:         &Failure($client,"unknown_cmd\n",$userinput);
                   6454:     }
                   6455:     return 1;
                   6456: }
                   6457: &register_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
                   6458: 
                   6459: #
1.340     raeburn  6460: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   6461: #   Only used for case where authentication method for new user is localauth
1.248     foxr     6462: #
                   6463: # Formal Parameters:
                   6464: #    $cmd     - The command request that got us dispatched.
                   6465: #    $tail    - The tail of the command.   In this case this is a colon separated
                   6466: #               set of words that will be split into:
1.340     raeburn  6467: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     6468: #               $cdom      - The domain of the course from the institution's
                   6469: #                            point of view.
                   6470: #    $client  - The socket open on the client.
                   6471: # Returns:
                   6472: #    1 - continue processing.
                   6473: #
                   6474: sub create_auto_enroll_password_handler {
                   6475:     my ($cmd, $tail, $client) = @_;
                   6476:     my $userinput = "$cmd:$tail";
                   6477: 
                   6478:     my ($authparam, $cdom) = split(/:/, $userinput);
                   6479: 
                   6480:     my ($create_passwd,$authchk);
                   6481:     ($authparam,
                   6482:      $create_passwd,
                   6483:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   6484: 
                   6485:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   6486: 	   $userinput);
                   6487: 
                   6488: 
                   6489:     return 1;
                   6490: }
                   6491: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   6492: 		  0, 1, 0);
                   6493: 
1.522     raeburn  6494: sub auto_export_grades_handler {
                   6495:     my ($cmd, $tail, $client) = @_;
                   6496:     my $userinput = "$cmd:$tail";
                   6497:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   6498:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   6499:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   6500:     my ($outcome,$result);;
                   6501:     eval {
                   6502:         local($SIG{__DIE__})='DEFAULT';
                   6503:         my %rtnhash;
                   6504:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   6505:         if ($outcome eq 'ok') {
                   6506:             foreach my $key (keys(%rtnhash)) {
                   6507:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6508:             }
                   6509:             $result =~ s/\&$//;
                   6510:         }
                   6511:     };
                   6512:     if (!$@) {
                   6513:         if ($outcome eq 'ok') {
                   6514:             if ($cipher) {
                   6515:                 my $cmdlength=length($result);
                   6516:                 $result.="         ";
                   6517:                 my $encresult='';
                   6518:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   6519:                     $encresult.= unpack("H16",
                   6520:                                         $cipher->encrypt(substr($result,
                   6521:                                                                 $encidx,
                   6522:                                                                 8)));
                   6523:                 }
                   6524:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   6525:             } else {
                   6526:                 &Failure( $client, "error:no_key\n", $userinput);
                   6527:             }
                   6528:         } else {
                   6529:             &Reply($client, "$outcome\n", $userinput);
                   6530:         }
                   6531:     } else {
                   6532:         &Failure($client,"export_error\n",$userinput);
                   6533:     }
                   6534:     return 1;
                   6535: }
                   6536: &register_handler("autoexportgrades", \&auto_export_grades_handler,
1.536     raeburn  6537:                   1, 1, 0);
1.522     raeburn  6538: 
1.248     foxr     6539: #   Retrieve and remove temporary files created by/during autoenrollment.
                   6540: #
                   6541: # Formal Parameters:
                   6542: #    $cmd      - The command that got us dispatched.
                   6543: #    $tail     - The tail of the command.  In our case this is a colon 
                   6544: #                separated list that will be split into:
1.526     raeburn  6545: #                $filename - The name of the file to retrieve.
1.248     foxr     6546: #                            The filename is given as a path relative to
                   6547: #                            the LonCAPA temp file directory.
                   6548: #    $client   - Socket open on the client.
                   6549: #
                   6550: # Returns:
                   6551: #   1     - Continue processing.
                   6552: sub retrieve_auto_file_handler {
                   6553:     my ($cmd, $tail, $client)    = @_;
                   6554:     my $userinput                = "cmd:$tail";
                   6555: 
                   6556:     my ($filename)   = split(/:/, $tail);
                   6557: 
                   6558:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  6559: 
                   6560:     if ($filename =~m{/\.\./}) {
                   6561:         &Failure($client, "refused\n", $userinput);
1.526     raeburn  6562:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
                   6563:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  6564:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     6565: 	my $reply = '';
                   6566: 	if (open(my $fh,$source)) {
                   6567: 	    while (<$fh>) {
                   6568: 		chomp($_);
                   6569: 		$_ =~ s/^\s+//g;
                   6570: 		$_ =~ s/\s+$//g;
                   6571: 		$reply .= $_;
                   6572: 	    }
                   6573: 	    close($fh);
                   6574: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   6575: 
                   6576: #   Does this have to be uncommented??!?  (RF).
                   6577: #
                   6578: #                                unlink($source);
                   6579: 	} else {
                   6580: 	    &Failure($client, "error\n", $userinput);
                   6581: 	}
                   6582:     } else {
                   6583: 	&Failure($client, "error\n", $userinput);
                   6584:     }
                   6585:     
                   6586: 
                   6587:     return 1;
                   6588: }
                   6589: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   6590: 
1.423     raeburn  6591: sub crsreq_checks_handler {
                   6592:     my ($cmd, $tail, $client) = @_;
                   6593:     my $userinput = "$cmd:$tail";
                   6594:     my $dom = $tail;
                   6595:     my $result;
1.519     raeburn  6596:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  6597:     eval {
                   6598:         local($SIG{__DIE__})='DEFAULT';
                   6599:         my %validations;
1.424     raeburn  6600:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   6601:                                                    \%validations);
1.423     raeburn  6602:         if ($response eq 'ok') { 
                   6603:             foreach my $key (keys(%validations)) {
                   6604:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   6605:             }
                   6606:             $result =~ s/\&$//;
                   6607:         } else {
                   6608:             $result = 'error';
                   6609:         }
                   6610:     };
                   6611:     if (!$@) {
                   6612:         &Reply($client, \$result, $userinput);
                   6613:     } else {
                   6614:         &Failure($client,"unknown_cmd\n",$userinput);
                   6615:     }
                   6616:     return 1;
                   6617: }
                   6618: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   6619: 
                   6620: sub validate_crsreq_handler {
                   6621:     my ($cmd, $tail, $client) = @_;
                   6622:     my $userinput = "$cmd:$tail";
1.508     raeburn  6623:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  6624:     $instcode = &unescape($instcode);
                   6625:     $owner = &unescape($owner);
                   6626:     $crstype = &unescape($crstype);
                   6627:     $inststatuslist = &unescape($inststatuslist);
                   6628:     $instcode = &unescape($instcode);
                   6629:     $instseclist = &unescape($instseclist);
1.508     raeburn  6630:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  6631:     my $outcome;
                   6632:     eval {
                   6633:         local($SIG{__DIE__})='DEFAULT';
                   6634:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   6635:                                                  $inststatuslist,$instcode,
1.508     raeburn  6636:                                                  $instseclist,$custominfo);
1.423     raeburn  6637:     };
                   6638:     if (!$@) {
                   6639:         &Reply($client, \$outcome, $userinput);
                   6640:     } else {
                   6641:         &Failure($client,"unknown_cmd\n",$userinput);
                   6642:     }
                   6643:     return 1;
                   6644: }
                   6645: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   6646: 
1.506     raeburn  6647: sub crsreq_update_handler {
                   6648:     my ($cmd, $tail, $client) = @_;
                   6649:     my $userinput = "$cmd:$tail";
1.509     raeburn  6650:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   6651:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  6652:         split(/:/, $tail);
                   6653:     $crstype = &unescape($crstype);
                   6654:     $action = &unescape($action);
                   6655:     $ownername = &unescape($ownername);
                   6656:     $ownerdomain = &unescape($ownerdomain);
                   6657:     $fullname = &unescape($fullname);
                   6658:     $title = &unescape($title);
                   6659:     $code = &unescape($code);
1.509     raeburn  6660:     $accessstart = &unescape($accessstart);
                   6661:     $accessend = &unescape($accessend);
1.506     raeburn  6662:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   6663:     my ($result,$outcome);
                   6664:     eval {
                   6665:         local($SIG{__DIE__})='DEFAULT';
                   6666:         my %rtnhash;
                   6667:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   6668:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  6669:                                                 $title,$code,$accessstart,$accessend,
                   6670:                                                 $incoming,\%rtnhash);
1.506     raeburn  6671:         if ($outcome eq 'ok') {
1.515     raeburn  6672:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  6673:             foreach my $key (keys(%rtnhash)) {
                   6674:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   6675:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   6676:                 }
                   6677:             }
                   6678:             $result =~ s/\&$//;
                   6679:         }
                   6680:     };
                   6681:     if (!$@) {
                   6682:         if ($outcome eq 'ok') {
                   6683:             &Reply($client, \$result, $userinput);
                   6684:         } else {
                   6685:             &Reply($client, "format_error\n", $userinput);
                   6686:         }
                   6687:     } else {
                   6688:         &Failure($client,"unknown_cmd\n",$userinput);
                   6689:     }
                   6690:     return 1;
                   6691: }
                   6692: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   6693: 
1.248     foxr     6694: #
                   6695: #   Read and retrieve institutional code format (for support form).
                   6696: # Formal Parameters:
                   6697: #    $cmd        - Command that dispatched us.
                   6698: #    $tail       - Tail of the command.  In this case it conatins 
                   6699: #                  the course domain and the coursename.
                   6700: #    $client     - Socket open on the client.
                   6701: # Returns:
                   6702: #    1     - Continue processing.
                   6703: #
                   6704: sub get_institutional_code_format_handler {
                   6705:     my ($cmd, $tail, $client)   = @_;
                   6706:     my $userinput               = "$cmd:$tail";
                   6707: 
                   6708:     my $reply;
                   6709:     my($cdom,$course) = split(/:/,$tail);
                   6710:     my @pairs = split/\&/,$course;
                   6711:     my %instcodes = ();
                   6712:     my %codes = ();
                   6713:     my @codetitles = ();
                   6714:     my %cat_titles = ();
                   6715:     my %cat_order = ();
                   6716:     foreach (@pairs) {
                   6717: 	my ($key,$value) = split/=/,$_;
                   6718: 	$instcodes{&unescape($key)} = &unescape($value);
                   6719:     }
                   6720:     my $formatreply = &localenroll::instcode_format($cdom,
                   6721: 						    \%instcodes,
                   6722: 						    \%codes,
                   6723: 						    \@codetitles,
                   6724: 						    \%cat_titles,
                   6725: 						    \%cat_order);
                   6726:     if ($formatreply eq 'ok') {
1.365     albertel 6727: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   6728: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   6729: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   6730: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     6731: 	&Reply($client,
                   6732: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   6733: 	       .$cat_order_str."\n",
                   6734: 	       $userinput);
                   6735:     } else {
                   6736: 	# this else branch added by RF since if not ok, lonc will
                   6737: 	# hang waiting on reply until timeout.
                   6738: 	#
                   6739: 	&Reply($client, "format_error\n", $userinput);
                   6740:     }
                   6741:     
                   6742:     return 1;
                   6743: }
1.265     albertel 6744: &register_handler("autoinstcodeformat",
                   6745: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     6746: 
1.345     raeburn  6747: sub get_institutional_defaults_handler {
                   6748:     my ($cmd, $tail, $client)   = @_;
                   6749:     my $userinput               = "$cmd:$tail";
                   6750: 
                   6751:     my $dom = $tail;
                   6752:     my %defaults_hash;
                   6753:     my @code_order;
                   6754:     my $outcome;
                   6755:     eval {
                   6756:         local($SIG{__DIE__})='DEFAULT';
                   6757:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   6758:                                                    \@code_order);
                   6759:     };
                   6760:     if (!$@) {
                   6761:         if ($outcome eq 'ok') {
                   6762:             my $result='';
                   6763:             while (my ($key,$value) = each(%defaults_hash)) {
                   6764:                 $result.=&escape($key).'='.&escape($value).'&';
                   6765:             }
                   6766:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 6767:             &Reply($client,\$result,$userinput);
1.345     raeburn  6768:         } else {
                   6769:             &Reply($client,"error\n", $userinput);
                   6770:         }
                   6771:     } else {
                   6772:         &Failure($client,"unknown_cmd\n",$userinput);
                   6773:     }
                   6774: }
                   6775: &register_handler("autoinstcodedefaults",
                   6776:                   \&get_institutional_defaults_handler,0,1,0);
                   6777: 
1.416     raeburn  6778: sub get_possible_instcodes_handler {
                   6779:     my ($cmd, $tail, $client)   = @_;
                   6780:     my $userinput               = "$cmd:$tail";
                   6781: 
                   6782:     my $reply;
                   6783:     my $cdom = $tail;
1.417     raeburn  6784:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  6785:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   6786:                                                        \@codetitles,
                   6787:                                                        \%cat_titles,
1.417     raeburn  6788:                                                        \%cat_order,
                   6789:                                                        \@code_order);
1.416     raeburn  6790:     if ($formatreply eq 'ok') {
                   6791:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  6792:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  6793:         foreach my $key (keys(%cat_titles)) {
                   6794:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   6795:         }
                   6796:         $result =~ s/\&$//;
                   6797:         $result .= ':';
                   6798:         foreach my $key (keys(%cat_order)) {
                   6799:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   6800:         }
                   6801:         $result =~ s/\&$//;
                   6802:         &Reply($client,\$result,$userinput);
                   6803:     } else {
                   6804:         &Reply($client, "format_error\n", $userinput);
                   6805:     }
                   6806:     return 1;
                   6807: }
                   6808: &register_handler("autopossibleinstcodes",
                   6809:                   \&get_possible_instcodes_handler,0,1,0);
                   6810: 
1.381     raeburn  6811: sub get_institutional_user_rules {
                   6812:     my ($cmd, $tail, $client)   = @_;
                   6813:     my $userinput               = "$cmd:$tail";
                   6814:     my $dom = &unescape($tail);
                   6815:     my (%rules_hash,@rules_order);
                   6816:     my $outcome;
                   6817:     eval {
                   6818:         local($SIG{__DIE__})='DEFAULT';
                   6819:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   6820:     };
                   6821:     if (!$@) {
                   6822:         if ($outcome eq 'ok') {
                   6823:             my $result;
                   6824:             foreach my $key (keys(%rules_hash)) {
                   6825:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6826:             }
                   6827:             $result =~ s/\&$//;
                   6828:             $result .= ':';
                   6829:             if (@rules_order > 0) {
                   6830:                 foreach my $item (@rules_order) {
                   6831:                     $result .= &escape($item).'&';
                   6832:                 }
                   6833:             }
                   6834:             $result =~ s/\&$//;
1.387     albertel 6835:             &Reply($client,\$result,$userinput);
1.381     raeburn  6836:         } else {
                   6837:             &Reply($client,"error\n", $userinput);
                   6838:         }
                   6839:     } else {
                   6840:         &Failure($client,"unknown_cmd\n",$userinput);
                   6841:     }
                   6842: }
                   6843: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   6844: 
1.389     raeburn  6845: sub get_institutional_id_rules {
                   6846:     my ($cmd, $tail, $client)   = @_;
                   6847:     my $userinput               = "$cmd:$tail";
                   6848:     my $dom = &unescape($tail);
                   6849:     my (%rules_hash,@rules_order);
                   6850:     my $outcome;
                   6851:     eval {
                   6852:         local($SIG{__DIE__})='DEFAULT';
                   6853:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   6854:     };
                   6855:     if (!$@) {
                   6856:         if ($outcome eq 'ok') {
                   6857:             my $result;
                   6858:             foreach my $key (keys(%rules_hash)) {
                   6859:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6860:             }
                   6861:             $result =~ s/\&$//;
                   6862:             $result .= ':';
                   6863:             if (@rules_order > 0) {
                   6864:                 foreach my $item (@rules_order) {
                   6865:                     $result .= &escape($item).'&';
                   6866:                 }
                   6867:             }
                   6868:             $result =~ s/\&$//;
                   6869:             &Reply($client,\$result,$userinput);
                   6870:         } else {
                   6871:             &Reply($client,"error\n", $userinput);
                   6872:         }
                   6873:     } else {
                   6874:         &Failure($client,"unknown_cmd\n",$userinput);
                   6875:     }
                   6876: }
                   6877: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6878: 
1.397     raeburn  6879: sub get_institutional_selfcreate_rules {
1.396     raeburn  6880:     my ($cmd, $tail, $client)   = @_;
                   6881:     my $userinput               = "$cmd:$tail";
                   6882:     my $dom = &unescape($tail);
                   6883:     my (%rules_hash,@rules_order);
                   6884:     my $outcome;
                   6885:     eval {
                   6886:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6887:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6888:     };
                   6889:     if (!$@) {
                   6890:         if ($outcome eq 'ok') {
                   6891:             my $result;
                   6892:             foreach my $key (keys(%rules_hash)) {
                   6893:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6894:             }
                   6895:             $result =~ s/\&$//;
                   6896:             $result .= ':';
                   6897:             if (@rules_order > 0) {
                   6898:                 foreach my $item (@rules_order) {
                   6899:                     $result .= &escape($item).'&';
                   6900:                 }
                   6901:             }
                   6902:             $result =~ s/\&$//;
                   6903:             &Reply($client,\$result,$userinput);
                   6904:         } else {
                   6905:             &Reply($client,"error\n", $userinput);
                   6906:         }
                   6907:     } else {
                   6908:         &Failure($client,"unknown_cmd\n",$userinput);
                   6909:     }
                   6910: }
1.397     raeburn  6911: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6912: 
1.575     raeburn  6913: sub get_unamemap_rules {
                   6914:     my ($cmd, $tail, $client)   = @_;
                   6915:     my $userinput               = "$cmd:$tail";
                   6916:     my $dom = &unescape($tail);
                   6917:     my (%rules_hash,@rules_order);
                   6918:     my $outcome;
                   6919:     eval {
                   6920:         local($SIG{__DIE__})='DEFAULT';
                   6921:         $outcome = &localenroll::unamemap_rules($dom,\%rules_hash,\@rules_order);
                   6922:     };
                   6923:     if (!$@) {
                   6924:         if ($outcome eq 'ok') {
                   6925:             my $result;
                   6926:             foreach my $key (keys(%rules_hash)) {
                   6927:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6928:             }
                   6929:             $result =~ s/\&$//;
                   6930:             $result .= ':';
                   6931:             if (@rules_order > 0) {
                   6932:                 foreach my $item (@rules_order) {
                   6933:                     $result .= &escape($item).'&';
                   6934:                 }
                   6935:             }
                   6936:             $result =~ s/\&$//;
                   6937:             &Reply($client,\$result,$userinput);
                   6938:         } else {
                   6939:             &Reply($client,"error\n", $userinput);
                   6940:         }
                   6941:     } else {
                   6942:         &Failure($client,"unknown_cmd\n",$userinput);
                   6943:     }
                   6944: }
                   6945: &register_handler("unamemaprules",\&get_unamemap_rules,0,1,0);
1.381     raeburn  6946: 
                   6947: sub institutional_username_check {
                   6948:     my ($cmd, $tail, $client)   = @_;
                   6949:     my $userinput               = "$cmd:$tail";
                   6950:     my %rulecheck;
                   6951:     my $outcome;
                   6952:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6953:     $udom = &unescape($udom);
                   6954:     $uname = &unescape($uname);
                   6955:     @rules = map {&unescape($_);} (@rules);
                   6956:     eval {
                   6957:         local($SIG{__DIE__})='DEFAULT';
                   6958:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6959:     };
                   6960:     if (!$@) {
                   6961:         if ($outcome eq 'ok') {
                   6962:             my $result='';
                   6963:             foreach my $key (keys(%rulecheck)) {
                   6964:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6965:             }
1.387     albertel 6966:             &Reply($client,\$result,$userinput);
1.381     raeburn  6967:         } else {
                   6968:             &Reply($client,"error\n", $userinput);
                   6969:         }
                   6970:     } else {
                   6971:         &Failure($client,"unknown_cmd\n",$userinput);
                   6972:     }
                   6973: }
                   6974: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6975: 
1.389     raeburn  6976: sub institutional_id_check {
                   6977:     my ($cmd, $tail, $client)   = @_;
                   6978:     my $userinput               = "$cmd:$tail";
                   6979:     my %rulecheck;
                   6980:     my $outcome;
                   6981:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6982:     $udom = &unescape($udom);
                   6983:     $id = &unescape($id);
                   6984:     @rules = map {&unescape($_);} (@rules);
                   6985:     eval {
                   6986:         local($SIG{__DIE__})='DEFAULT';
                   6987:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6988:     };
                   6989:     if (!$@) {
                   6990:         if ($outcome eq 'ok') {
                   6991:             my $result='';
                   6992:             foreach my $key (keys(%rulecheck)) {
                   6993:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6994:             }
                   6995:             &Reply($client,\$result,$userinput);
                   6996:         } else {
                   6997:             &Reply($client,"error\n", $userinput);
                   6998:         }
                   6999:     } else {
                   7000:         &Failure($client,"unknown_cmd\n",$userinput);
                   7001:     }
                   7002: }
                   7003: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  7004: 
1.397     raeburn  7005: sub institutional_selfcreate_check {
1.396     raeburn  7006:     my ($cmd, $tail, $client)   = @_;
                   7007:     my $userinput               = "$cmd:$tail";
                   7008:     my %rulecheck;
                   7009:     my $outcome;
                   7010:     my ($udom,$email,@rules) = split(/:/,$tail);
                   7011:     $udom = &unescape($udom);
                   7012:     $email = &unescape($email);
                   7013:     @rules = map {&unescape($_);} (@rules);
                   7014:     eval {
                   7015:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  7016:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  7017:     };
                   7018:     if (!$@) {
                   7019:         if ($outcome eq 'ok') {
                   7020:             my $result='';
                   7021:             foreach my $key (keys(%rulecheck)) {
                   7022:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   7023:             }
                   7024:             &Reply($client,\$result,$userinput);
                   7025:         } else {
                   7026:             &Reply($client,"error\n", $userinput);
                   7027:         }
                   7028:     } else {
                   7029:         &Failure($client,"unknown_cmd\n",$userinput);
                   7030:     }
                   7031: }
1.397     raeburn  7032: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  7033: 
1.317     raeburn  7034: # Get domain specific conditions for import of student photographs to a course
                   7035: #
                   7036: # Retrieves information from photo_permission subroutine in localenroll.
                   7037: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   7038: # required to accept conditions of use (yes/no).
                   7039: #
                   7040: #    
                   7041: sub photo_permission_handler {
                   7042:     my ($cmd, $tail, $client)   = @_;
                   7043:     my $userinput               = "$cmd:$tail";
                   7044:     my $cdom = $tail;
                   7045:     my ($perm_reqd,$conditions);
1.320     albertel 7046:     my $outcome;
                   7047:     eval {
                   7048: 	local($SIG{__DIE__})='DEFAULT';
                   7049: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   7050: 						  \$conditions);
                   7051:     };
                   7052:     if (!$@) {
                   7053: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   7054: 	       $userinput);
                   7055:     } else {
                   7056: 	&Failure($client,"unknown_cmd\n",$userinput);
                   7057:     }
                   7058:     return 1;
1.317     raeburn  7059: }
                   7060: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   7061: 
                   7062: #
                   7063: # Checks if student photo is available for a user in the domain, in the user's
                   7064: # directory (in /userfiles/internal/studentphoto.jpg).
                   7065: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   7066: # the student's photo.   
                   7067: 
                   7068: sub photo_check_handler {
                   7069:     my ($cmd, $tail, $client)   = @_;
                   7070:     my $userinput               = "$cmd:$tail";
                   7071:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   7072:     $udom = &unescape($udom);
                   7073:     $uname = &unescape($uname);
                   7074:     $pid = &unescape($pid);
                   7075:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   7076:     if (!-e $path) {
                   7077:         &mkpath($path);
                   7078:     }
                   7079:     my $response;
                   7080:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   7081:     $result .= ':'.$response;
                   7082:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 7083:     return 1;
1.317     raeburn  7084: }
                   7085: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   7086: 
                   7087: #
                   7088: # Retrieve information from localenroll about whether to provide a button     
                   7089: # for users who have enbled import of student photos to initiate an 
                   7090: # update of photo files for registered students. Also include 
                   7091: # comment to display alongside button.  
                   7092: 
                   7093: sub photo_choice_handler {
                   7094:     my ($cmd, $tail, $client) = @_;
                   7095:     my $userinput             = "$cmd:$tail";
                   7096:     my $cdom                  = &unescape($tail);
1.320     albertel 7097:     my ($update,$comment);
                   7098:     eval {
                   7099: 	local($SIG{__DIE__})='DEFAULT';
                   7100: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   7101:     };
                   7102:     if (!$@) {
                   7103: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   7104:     } else {
                   7105: 	&Failure($client,"unknown_cmd\n",$userinput);
                   7106:     }
                   7107:     return 1;
1.317     raeburn  7108: }
                   7109: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   7110: 
1.265     albertel 7111: #
                   7112: # Gets a student's photo to exist (in the correct image type) in the user's 
                   7113: # directory.
                   7114: # Formal Parameters:
                   7115: #    $cmd     - The command request that got us dispatched.
                   7116: #    $tail    - A colon separated set of words that will be split into:
                   7117: #               $domain - student's domain
                   7118: #               $uname  - student username
                   7119: #               $type   - image type desired
                   7120: #    $client  - The socket open on the client.
                   7121: # Returns:
                   7122: #    1 - continue processing.
1.317     raeburn  7123: 
1.265     albertel 7124: sub student_photo_handler {
                   7125:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  7126:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 7127: 
1.317     raeburn  7128:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   7129:     my $filename = 'studentphoto.'.$ext;
                   7130:     if ($type eq 'thumbnail') {
                   7131:         $filename = 'studentphoto_tn.'.$ext;
                   7132:     }
                   7133:     if (-e $path.$filename) {
1.265     albertel 7134: 	&Reply($client,"ok\n","$cmd:$tail");
                   7135: 	return 1;
                   7136:     }
                   7137:     &mkpath($path);
1.317     raeburn  7138:     my $file;
                   7139:     if ($type eq 'thumbnail') {
1.320     albertel 7140: 	eval {
                   7141: 	    local($SIG{__DIE__})='DEFAULT';
                   7142: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   7143: 	};
1.317     raeburn  7144:     } else {
                   7145:         $file=&localstudentphoto::fetch($domain,$uname);
                   7146:     }
1.265     albertel 7147:     if (!$file) {
                   7148: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   7149: 	return 1;
                   7150:     }
1.317     raeburn  7151:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   7152:     if (-e $path.$filename) {
1.265     albertel 7153: 	&Reply($client,"ok\n","$cmd:$tail");
                   7154: 	return 1;
                   7155:     }
                   7156:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   7157:     return 1;
                   7158: }
                   7159: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     7160: 
1.361     raeburn  7161: sub inst_usertypes_handler {
                   7162:     my ($cmd, $domain, $client) = @_;
                   7163:     my $res;
                   7164:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 7165:     my (%typeshash,@order,$result);
                   7166:     eval {
                   7167: 	local($SIG{__DIE__})='DEFAULT';
                   7168: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   7169:     };
                   7170:     if ($result eq 'ok') {
1.361     raeburn  7171:         if (keys(%typeshash) > 0) {
                   7172:             foreach my $key (keys(%typeshash)) {
                   7173:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   7174:             }
                   7175:         }
                   7176:         $res=~s/\&$//;
                   7177:         $res .= ':';
                   7178:         if (@order > 0) {
                   7179:             foreach my $item (@order) {
                   7180:                 $res .= &escape($item).'&';
                   7181:             }
                   7182:         }
                   7183:         $res=~s/\&$//;
                   7184:     }
1.387     albertel 7185:     &Reply($client, \$res, $userinput);
1.361     raeburn  7186:     return 1;
                   7187: }
                   7188: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   7189: 
1.264     albertel 7190: # mkpath makes all directories for a file, expects an absolute path with a
                   7191: # file or a trailing / if just a dir is passed
                   7192: # returns 1 on success 0 on failure
                   7193: sub mkpath {
                   7194:     my ($file)=@_;
                   7195:     my @parts=split(/\//,$file,-1);
                   7196:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   7197:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 7198: 	$now.='/'.$parts[$i]; 
1.264     albertel 7199: 	if (!-e $now) {
                   7200: 	    if  (!mkdir($now,0770)) { return 0; }
                   7201: 	}
                   7202:     }
                   7203:     return 1;
                   7204: }
                   7205: 
1.207     foxr     7206: #---------------------------------------------------------------
                   7207: #
                   7208: #   Getting, decoding and dispatching requests:
                   7209: #
                   7210: #
                   7211: #   Get a Request:
                   7212: #   Gets a Request message from the client.  The transaction
                   7213: #   is defined as a 'line' of text.  We remove the new line
                   7214: #   from the text line.  
1.226     foxr     7215: #
1.211     albertel 7216: sub get_request {
1.207     foxr     7217:     my $input = <$client>;
                   7218:     chomp($input);
1.226     foxr     7219: 
1.234     foxr     7220:     &Debug("get_request: Request = $input\n");
1.207     foxr     7221: 
                   7222:     &status('Processing '.$clientname.':'.$input);
                   7223: 
                   7224:     return $input;
                   7225: }
1.212     foxr     7226: #---------------------------------------------------------------
                   7227: #
                   7228: #  Process a request.  This sub should shrink as each action
                   7229: #  gets farmed out into a separat sub that is registered 
                   7230: #  with the dispatch hash.  
                   7231: #
                   7232: # Parameters:
                   7233: #    user_input   - The request received from the client (lonc).
1.525     raeburn  7234: #
1.212     foxr     7235: # Returns:
                   7236: #    true to keep processing, false if caller should exit.
                   7237: #
                   7238: sub process_request {
1.525     raeburn  7239:     my ($userinput) = @_; # Easier for now to break style than to
                   7240:                           # fix all the userinput -> user_input.
1.212     foxr     7241:     my $wasenc    = 0;		# True if request was encrypted.
                   7242: # ------------------------------------------------------------ See if encrypted
1.322     albertel 7243:     # for command
                   7244:     # sethost:<server>
                   7245:     # <command>:<args>
                   7246:     #   we just send it to the processor
                   7247:     # for
                   7248:     # sethost:<server>:<command>:<args>
                   7249:     #  we do the implict set host and then do the command
                   7250:     if ($userinput =~ /^sethost:/) {
                   7251: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   7252: 	if (defined($userinput)) {
                   7253: 	    &sethost("$cmd:$newid");
                   7254: 	} else {
                   7255: 	    $userinput = "$cmd:$newid";
                   7256: 	}
                   7257:     }
                   7258: 
1.212     foxr     7259:     if ($userinput =~ /^enc/) {
                   7260: 	$userinput = decipher($userinput);
                   7261: 	$wasenc=1;
                   7262: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     7263: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     7264: 	    return 0;
                   7265: 	}
                   7266:     }
                   7267:     Debug("process_request: $userinput\n");
                   7268:     
1.213     foxr     7269:     #  
                   7270:     #   The 'correct way' to add a command to lond is now to
                   7271:     #   write a sub to execute it and Add it to the command dispatch
                   7272:     #   hash via a call to register_handler..  The comments to that
                   7273:     #   sub should give you enough to go on to show how to do this
                   7274:     #   along with the examples that are building up as this code
                   7275:     #   is getting refactored.   Until all branches of the
                   7276:     #   if/elseif monster below have been factored out into
                   7277:     #   separate procesor subs, if the dispatch hash is missing
                   7278:     #   the command keyword, we will fall through to the remainder
                   7279:     #   of the if/else chain below in order to keep this thing in 
                   7280:     #   working order throughout the transmogrification.
                   7281: 
                   7282:     my ($command, $tail) = split(/:/, $userinput, 2);
                   7283:     chomp($command);
                   7284:     chomp($tail);
                   7285:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     7286:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   7287:     if(!$tail) {
                   7288: 	$tail ="";		# defined but blank.
                   7289:     }
1.213     foxr     7290: 
                   7291:     &Debug("Command received: $command, encoded = $wasenc");
                   7292: 
                   7293:     if(defined $Dispatcher{$command}) {
                   7294: 
                   7295: 	my $dispatch_info = $Dispatcher{$command};
                   7296: 	my $handler       = $$dispatch_info[0];
                   7297: 	my $need_encode   = $$dispatch_info[1];
                   7298: 	my $client_types  = $$dispatch_info[2];
                   7299: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   7300: 	      ."ClientType $client_types");
                   7301:       
                   7302: 	#  Validate the request:
                   7303:       
                   7304: 	my $ok = 1;
                   7305: 	my $requesterprivs = 0;
                   7306: 	if(&isClient()) {
                   7307: 	    $requesterprivs |= $CLIENT_OK;
                   7308: 	}
                   7309: 	if(&isManager()) {
                   7310: 	    $requesterprivs |= $MANAGER_OK;
                   7311: 	}
                   7312: 	if($need_encode && (!$wasenc)) {
                   7313: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   7314: 	    $ok = 0;
                   7315: 	}
                   7316: 	if(($client_types & $requesterprivs) == 0) {
                   7317: 	    Debug("Client not privileged to do this operation");
                   7318: 	    $ok = 0;
                   7319: 	}
1.525     raeburn  7320:         if ($ok) {
1.535     raeburn  7321:             my $realcommand = $command;
                   7322:             if ($command eq 'querysend') {
                   7323:                 my ($query,$rest)=split(/\:/,$tail,2);
                   7324:                 $query=~s/\n*$//g;
                   7325:                 my @possqueries = 
                   7326:                     qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
                   7327:                 if (grep(/^\Q$query\E$/,@possqueries)) {
                   7328:                     $command .= '_'.$query;
                   7329:                 } elsif ($query eq 'prepare activity log') {
                   7330:                     $command .= '_activitylog';
                   7331:                 }
                   7332:             }
1.525     raeburn  7333:             if (ref($trust{$command}) eq 'HASH') {
                   7334:                 my $donechecks;
                   7335:                 if ($trust{$command}{'anywhere'}) {
                   7336:                    $donechecks = 1;
                   7337:                 } elsif ($trust{$command}{'manageronly'}) {
                   7338:                     unless (&isManager()) {
                   7339:                         $ok = 0;
                   7340:                     }
                   7341:                     $donechecks = 1;
                   7342:                 } elsif ($trust{$command}{'institutiononly'}) {
                   7343:                     unless ($clientsameinst) {
                   7344:                         $ok = 0;
                   7345:                     }
                   7346:                     $donechecks = 1;
                   7347:                 } elsif ($clientsameinst) {
                   7348:                     $donechecks = 1;
                   7349:                 }
                   7350:                 unless ($donechecks) {
                   7351:                     foreach my $rule (keys(%{$trust{$command}})) {
                   7352:                         next if ($rule eq 'remote');
                   7353:                         if ($trust{$command}{$rule}) {
                   7354:                             if ($clientprohibited{$rule}) {
                   7355:                                 $ok = 0;
                   7356:                             } else {
                   7357:                                 $ok = 1;
                   7358:                                 $donechecks = 1;
                   7359:                                 last;
                   7360:                             }
                   7361:                         }
                   7362:                     }
                   7363:                 }
                   7364:                 unless ($donechecks) {
                   7365:                     if ($trust{$command}{'remote'}) {
                   7366:                         if ($clientremoteok) {
                   7367:                             $ok = 1;
                   7368:                         } else {
                   7369:                             $ok = 0;
                   7370:                         } 
                   7371:                     }
                   7372:                 }
                   7373:             }
1.535     raeburn  7374:             $command = $realcommand;
1.525     raeburn  7375:         }
1.213     foxr     7376: 
                   7377: 	if($ok) {
                   7378: 	    Debug("Dispatching to handler $command $tail");
                   7379: 	    my $keep_going = &$handler($command, $tail, $client);
                   7380: 	    return $keep_going;
                   7381: 	} else {
                   7382: 	    Debug("Refusing to dispatch because client did not match requirements");
                   7383: 	    Failure($client, "refused\n", $userinput);
                   7384: 	    return 1;
                   7385: 	}
1.525     raeburn  7386:     }
1.213     foxr     7387: 
1.262     foxr     7388:     print $client "unknown_cmd\n";
1.212     foxr     7389: # -------------------------------------------------------------------- complete
                   7390:     Debug("process_request - returning 1");
                   7391:     return 1;
                   7392: }
1.207     foxr     7393: #
                   7394: #   Decipher encoded traffic
                   7395: #  Parameters:
                   7396: #     input      - Encoded data.
                   7397: #  Returns:
                   7398: #     Decoded data or undef if encryption key was not yet negotiated.
                   7399: #  Implicit input:
                   7400: #     cipher  - This global holds the negotiated encryption key.
                   7401: #
1.211     albertel 7402: sub decipher {
1.207     foxr     7403:     my ($input)  = @_;
                   7404:     my $output = '';
1.212     foxr     7405:     
                   7406:     
1.207     foxr     7407:     if($cipher) {
                   7408: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   7409: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   7410: 	    $output .= 
                   7411: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   7412: 	}
                   7413: 	return substr($output, 0, $enclength);
                   7414:     } else {
                   7415: 	return undef;
                   7416:     }
                   7417: }
                   7418: 
                   7419: #
                   7420: #   Register a command processor.  This function is invoked to register a sub
                   7421: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   7422: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   7423: #   as well:
                   7424: #    - Is the keyword recognized.
                   7425: #    - Is the proper client type attempting the request.
                   7426: #    - Is the request encrypted if it has to be.
                   7427: #   Parameters:
                   7428: #    $request_name         - Name of the request being registered.
                   7429: #                           This is the command request that will match
                   7430: #                           against the hash keywords to lookup the information
                   7431: #                           associated with the dispatch information.
                   7432: #    $procedure           - Reference to a sub to call to process the request.
                   7433: #                           All subs get called as follows:
                   7434: #                             Procedure($cmd, $tail, $replyfd, $key)
                   7435: #                             $cmd    - the actual keyword that invoked us.
                   7436: #                             $tail   - the tail of the request that invoked us.
                   7437: #                             $replyfd- File descriptor connected to the client
                   7438: #    $must_encode          - True if the request must be encoded to be good.
                   7439: #    $client_ok            - True if it's ok for a client to request this.
                   7440: #    $manager_ok           - True if it's ok for a manager to request this.
                   7441: # Side effects:
                   7442: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   7443: #      - On failure, the program will die as it's a bad internal bug to try to 
                   7444: #        register a duplicate command handler.
                   7445: #
1.211     albertel 7446: sub register_handler {
1.212     foxr     7447:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     7448: 
                   7449:     #  Don't allow duplication#
                   7450:    
                   7451:     if (defined $Dispatcher{$request_name}) {
                   7452: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   7453:     }
                   7454:     #   Build the client type mask:
                   7455:     
                   7456:     my $client_type_mask = 0;
                   7457:     if($client_ok) {
                   7458: 	$client_type_mask  |= $CLIENT_OK;
                   7459:     }
                   7460:     if($manager_ok) {
                   7461: 	$client_type_mask  |= $MANAGER_OK;
                   7462:     }
                   7463:    
                   7464:     #  Enter the hash:
                   7465:       
                   7466:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   7467:    
                   7468:     $Dispatcher{$request_name} = \@entry;
                   7469:    
                   7470: }
                   7471: 
                   7472: 
                   7473: #------------------------------------------------------------------
                   7474: 
                   7475: 
                   7476: 
                   7477: 
1.141     foxr     7478: #
1.96      foxr     7479: #  Convert an error return code from lcpasswd to a string value.
                   7480: #
                   7481: sub lcpasswdstrerror {
                   7482:     my $ErrorCode = shift;
1.97      foxr     7483:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     7484: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   7485:     } else {
1.98      foxr     7486: 	return $passwderrors[$ErrorCode];
1.96      foxr     7487:     }
                   7488: }
                   7489: 
1.23      harris41 7490: # grabs exception and records it to log before exiting
                   7491: sub catchexception {
1.27      albertel 7492:     my ($error)=@_;
1.25      www      7493:     $SIG{'QUIT'}='DEFAULT';
                   7494:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 7495:     &status("Catching exception");
1.190     albertel 7496:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 7497:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 7498:      ."a crash with this error msg->[$error]</font>");
1.57      www      7499:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 7500:     if ($client) { print $client "error: $error\n"; }
1.59      www      7501:     $server->close();
1.27      albertel 7502:     die($error);
1.23      harris41 7503: }
1.63      www      7504: sub timeout {
1.165     albertel 7505:     &status("Handling Timeout");
1.190     albertel 7506:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      7507:     &catchexception('Timeout');
                   7508: }
1.22      harris41 7509: # -------------------------------- Set signal handlers to record abnormal exits
                   7510: 
1.226     foxr     7511: 
1.22      harris41 7512: $SIG{'QUIT'}=\&catchexception;
                   7513: $SIG{__DIE__}=\&catchexception;
                   7514: 
1.81      matthew  7515: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 7516: &status("Read loncapa.conf and loncapa_apache.conf");
                   7517: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     7518: %perlvar=%{$perlvarref};
1.80      harris41 7519: undef $perlvarref;
1.19      www      7520: 
1.35      harris41 7521: # ----------------------------- Make sure this process is running from user=www
                   7522: my $wwwid=getpwnam('www');
                   7523: if ($wwwid!=$<) {
1.134     albertel 7524:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7525:    my $subj="LON: $currenthostid User ID mismatch";
1.550     raeburn  7526:    system("echo 'User ID mismatch.  lond must be run as user www.' |".
                   7527:           " mail -s '$subj' $emailto > /dev/null");
1.35      harris41 7528:    exit 1;
                   7529: }
                   7530: 
1.19      www      7531: # --------------------------------------------- Check if other instance running
                   7532: 
                   7533: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   7534: 
                   7535: if (-e $pidfile) {
                   7536:    my $lfh=IO::File->new("$pidfile");
                   7537:    my $pide=<$lfh>;
                   7538:    chomp($pide);
1.29      harris41 7539:    if (kill 0 => $pide) { die "already running"; }
1.19      www      7540: }
1.1       albertel 7541: 
                   7542: # ------------------------------------------------------------- Read hosts file
                   7543: 
                   7544: 
                   7545: 
                   7546: # establish SERVER socket, bind and listen.
                   7547: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   7548:                                 Type      => SOCK_STREAM,
                   7549:                                 Proto     => 'tcp',
1.469     foxr     7550:                                 ReuseAddr     => 1,
1.1       albertel 7551:                                 Listen    => 10 )
1.29      harris41 7552:   or die "making socket: $@\n";
1.1       albertel 7553: 
                   7554: # --------------------------------------------------------- Do global variables
                   7555: 
                   7556: # global variables
                   7557: 
1.134     albertel 7558: my %children               = ();       # keys are current child process IDs
1.1       albertel 7559: 
                   7560: sub REAPER {                        # takes care of dead children
                   7561:     $SIG{CHLD} = \&REAPER;
1.165     albertel 7562:     &status("Handling child death");
1.178     foxr     7563:     my $pid;
                   7564:     do {
                   7565: 	$pid = waitpid(-1,&WNOHANG());
                   7566: 	if (defined($children{$pid})) {
                   7567: 	    &logthis("Child $pid died");
                   7568: 	    delete($children{$pid});
1.183     albertel 7569: 	} elsif ($pid > 0) {
1.178     foxr     7570: 	    &logthis("Unknown Child $pid died");
                   7571: 	}
                   7572:     } while ( $pid > 0 );
                   7573:     foreach my $child (keys(%children)) {
                   7574: 	$pid = waitpid($child,&WNOHANG());
                   7575: 	if ($pid > 0) {
                   7576: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   7577: 	    delete($children{$pid});
                   7578: 	}
1.176     albertel 7579:     }
1.165     albertel 7580:     &status("Finished Handling child death");
1.1       albertel 7581: }
                   7582: 
                   7583: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 7584:     &status("Killing children (INT)");
1.1       albertel 7585:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   7586:     kill 'INT' => keys %children;
1.59      www      7587:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 7588:     my $execdir=$perlvar{'lonDaemons'};
                   7589:     unlink("$execdir/logs/lond.pid");
1.190     albertel 7590:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 7591:     &status("Done killing children");
1.1       albertel 7592:     exit;                           # clean up with dignity
                   7593: }
                   7594: 
                   7595: sub HUPSMAN {                      # signal handler for SIGHUP
                   7596:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 7597:     &status("Killing children for restart (HUP)");
1.1       albertel 7598:     kill 'INT' => keys %children;
1.59      www      7599:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 7600:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 7601:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 7602:     unlink("$execdir/logs/lond.pid");
1.165     albertel 7603:     &status("Restarting self (HUP)");
1.1       albertel 7604:     exec("$execdir/lond");         # here we go again
                   7605: }
                   7606: 
1.144     foxr     7607: #
1.148     foxr     7608: #  Reload the Apache daemon's state.
1.150     foxr     7609: #  This is done by invoking /home/httpd/perl/apachereload
                   7610: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     7611: #
                   7612: sub ReloadApache {
1.473     raeburn  7613: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  7614:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   7615:         my $execdir = $perlvar{'lonDaemons'};
                   7616:         my $script  = $execdir."/apachereload";
                   7617:         system($script);
                   7618:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   7619:     }
1.148     foxr     7620: }
                   7621: 
                   7622: #
1.144     foxr     7623: #   Called in response to a USR2 signal.
                   7624: #   - Reread hosts.tab
                   7625: #   - All children connected to hosts that were removed from hosts.tab
                   7626: #     are killed via SIGINT
                   7627: #   - All children connected to previously existing hosts are sent SIGUSR1
                   7628: #   - Our internal hosts hash is updated to reflect the new contents of
                   7629: #     hosts.tab causing connections from hosts added to hosts.tab to
                   7630: #     now be honored.
                   7631: #
                   7632: sub UpdateHosts {
1.165     albertel 7633:     &status("Reload hosts.tab");
1.147     foxr     7634:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     7635:     #
                   7636:     #  The %children hash has the set of IP's we currently have children
                   7637:     #  on.  These need to be matched against records in the hosts.tab
                   7638:     #  Any ip's no longer in the table get killed off they correspond to
                   7639:     #  either dropped or changed hosts.  Note that the re-read of the table
                   7640:     #  will take care of new and changed hosts as connections come into being.
                   7641: 
1.371     albertel 7642:     &Apache::lonnet::reset_hosts_info();
1.532     raeburn  7643:     my %active;
1.148     foxr     7644: 
1.368     albertel 7645:     foreach my $child (keys(%children)) {
1.148     foxr     7646: 	my $childip = $children{$child};
1.374     albertel 7647: 	if ($childip ne '127.0.0.1'
                   7648: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     7649: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   7650: 		    ." $child for ip $childip </font>");
1.148     foxr     7651: 	    kill('INT', $child);
1.149     foxr     7652: 	} else {
1.532     raeburn  7653:             $active{$child} = $childip;
1.149     foxr     7654: 	    logthis('<font color="green"> keeping child for ip '
                   7655: 		    ." $childip (pid=$child) </font>");
1.148     foxr     7656: 	}
                   7657:     }
1.532     raeburn  7658: 
                   7659:     my %oldconf = %secureconf;
                   7660:     my %connchange;
1.555     raeburn  7661:     if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545     raeburn  7662:         logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532     raeburn  7663:     } else {
1.545     raeburn  7664:         logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532     raeburn  7665:     }
                   7666:     if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
                   7667:         foreach my $type ('dom','intdom','other') {
                   7668:             if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
                   7669:                 (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
                   7670:                 $connchange{$type} = 1;
                   7671:             }
                   7672:         }
                   7673:     }
                   7674:     if (keys(%connchange)) {
                   7675:         foreach my $child (keys(%active)) {
                   7676:             my $childip = $active{$child};
                   7677:             if ($childip ne '127.0.0.1') {
                   7678:                 my $childhostname  = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
                   7679:                 if ($childhostname ne '') {
                   7680:                     my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
                   7681:                     my ($samedom,$sameinst) = &set_client_info($childlonhost);
                   7682:                     if ($samedom) {
                   7683:                         if ($connchange{'dom'}) {
                   7684:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7685:                                    ." $child for ip $childip </font>");
                   7686:                             kill('INT', $child);
                   7687:                         }
                   7688:                     } elsif ($sameinst) {
                   7689:                         if ($connchange{'intdom'}) {
                   7690:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7691:                                    ." $child for ip $childip </font>");
                   7692:                            kill('INT', $child);
                   7693:                         }
                   7694:                     } else {
                   7695:                         if ($connchange{'other'}) {
                   7696:                             logthis('<font color="blue"> UpdateHosts killing child '
                   7697:                                    ." $child for ip $childip </font>");
                   7698:                             kill('INT', $child);
                   7699:                         }
                   7700:                     }
                   7701:                 }
                   7702:             }
                   7703:         }
                   7704:     }
1.148     foxr     7705:     ReloadApache;
1.165     albertel 7706:     &status("Finished reloading hosts.tab");
1.144     foxr     7707: }
                   7708: 
1.57      www      7709: sub checkchildren {
1.165     albertel 7710:     &status("Checking on the children (sending signals)");
1.57      www      7711:     &initnewstatus();
                   7712:     &logstatus();
                   7713:     &logthis('Going to check on the children');
1.134     albertel 7714:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 7715:     foreach (sort keys %children) {
1.221     albertel 7716: 	#sleep 1;
1.57      www      7717:         unless (kill 'USR1' => $_) {
                   7718: 	    &logthis ('Child '.$_.' is dead');
                   7719:             &logstatus($$.' is dead');
1.221     albertel 7720: 	    delete($children{$_});
1.57      www      7721:         } 
1.61      harris41 7722:     }
1.63      www      7723:     sleep 5;
1.212     foxr     7724:     $SIG{ALRM} = sub { Debug("timeout"); 
                   7725: 		       die "timeout";  };
1.113     albertel 7726:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 7727:     &status("Checking on the children (waiting for reports)");
1.63      www      7728:     foreach (sort keys %children) {
                   7729:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 7730:           eval {
                   7731:             alarm(300);
1.63      www      7732: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 7733: 	    kill 9 => $_;
1.131     albertel 7734: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   7735: 	    #$subj="LON: $currenthostid killed lond process $_";
                   7736: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   7737: 	    #$execdir=$perlvar{'lonDaemons'};
                   7738: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 7739: 	    delete($children{$_});
1.113     albertel 7740: 	    alarm(0);
                   7741: 	  }
1.63      www      7742:         }
                   7743:     }
1.113     albertel 7744:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 7745:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 7746:     &status("Finished checking children");
1.221     albertel 7747:     &logthis('Finished Checking children');
1.57      www      7748: }
                   7749: 
1.1       albertel 7750: # --------------------------------------------------------------------- Logging
                   7751: 
                   7752: sub logthis {
                   7753:     my $message=shift;
                   7754:     my $execdir=$perlvar{'lonDaemons'};
                   7755:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   7756:     my $now=time;
                   7757:     my $local=localtime($now);
1.58      www      7758:     $lastlog=$local.': '.$message;
1.1       albertel 7759:     print $fh "$local ($$): $message\n";
                   7760: }
                   7761: 
1.77      foxr     7762: # ------------------------- Conditional log if $DEBUG true.
                   7763: sub Debug {
                   7764:     my $message = shift;
                   7765:     if($DEBUG) {
                   7766: 	&logthis($message);
                   7767:     }
                   7768: }
1.161     foxr     7769: 
                   7770: #
                   7771: #   Sub to do replies to client.. this gives a hook for some
                   7772: #   debug tracing too:
                   7773: #  Parameters:
                   7774: #     fd      - File open on client.
                   7775: #     reply   - Text to send to client.
                   7776: #     request - Original request from client.
                   7777: #
1.490     droeschl 7778: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   7779: #this is done automatically ($$reply must not contain any \n in this case). 
                   7780: #If $reply is a string the caller has to ensure this.
1.161     foxr     7781: sub Reply {
1.192     foxr     7782:     my ($fd, $reply, $request) = @_;
1.387     albertel 7783:     if (ref($reply)) {
                   7784: 	print $fd $$reply;
                   7785: 	print $fd "\n";
                   7786: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   7787:     } else {
                   7788: 	print $fd $reply;
                   7789: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   7790:     }
1.212     foxr     7791:     $Transactions++;
                   7792: }
                   7793: 
                   7794: 
                   7795: #
                   7796: #    Sub to report a failure.
                   7797: #    This function:
                   7798: #     -   Increments the failure statistic counters.
                   7799: #     -   Invokes Reply to send the error message to the client.
                   7800: # Parameters:
                   7801: #    fd       - File descriptor open on the client
                   7802: #    reply    - Reply text to emit.
                   7803: #    request  - The original request message (used by Reply
                   7804: #               to debug if that's enabled.
                   7805: # Implicit outputs:
                   7806: #    $Failures- The number of failures is incremented.
                   7807: #    Reply (invoked here) sends a message to the 
                   7808: #    client:
                   7809: #
                   7810: sub Failure {
                   7811:     my $fd      = shift;
                   7812:     my $reply   = shift;
                   7813:     my $request = shift;
                   7814:    
                   7815:     $Failures++;
                   7816:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     7817: }
1.57      www      7818: # ------------------------------------------------------------------ Log status
                   7819: 
                   7820: sub logstatus {
1.178     foxr     7821:     &status("Doing logging");
                   7822:     my $docdir=$perlvar{'lonDocRoot'};
                   7823:     {
                   7824: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  7825:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     7826:         $fh->close();
                   7827:     }
1.221     albertel 7828:     &status("Finished $$.txt");
                   7829:     {
                   7830: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   7831: 	flock(LOG,LOCK_EX);
                   7832: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   7833: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 7834: 	flock(LOG,LOCK_UN);
1.221     albertel 7835: 	close(LOG);
                   7836:     }
1.178     foxr     7837:     &status("Finished logging");
1.57      www      7838: }
                   7839: 
                   7840: sub initnewstatus {
                   7841:     my $docdir=$perlvar{'lonDocRoot'};
                   7842:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     7843:     my $now=time();
1.57      www      7844:     my $local=localtime($now);
                   7845:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      7846:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 7847:     while (my $filename=readdir(DIR)) {
1.64      www      7848:         unlink("$docdir/lon-status/londchld/$filename");
                   7849:     }
                   7850:     closedir(DIR);
1.57      www      7851: }
                   7852: 
                   7853: # -------------------------------------------------------------- Status setting
                   7854: 
                   7855: sub status {
                   7856:     my $what=shift;
                   7857:     my $now=time;
                   7858:     my $local=localtime($now);
1.178     foxr     7859:     $status=$local.': '.$what;
                   7860:     $0='lond: '.$what.' '.$local;
1.57      www      7861: }
1.11      www      7862: 
1.13      www      7863: # -------------------------------------------------------------- Talk to lonsql
                   7864: 
1.234     foxr     7865: sub sql_reply {
1.12      harris41 7866:     my ($cmd)=@_;
1.234     foxr     7867:     my $answer=&sub_sql_reply($cmd);
                   7868:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 7869:     return $answer;
                   7870: }
                   7871: 
1.234     foxr     7872: sub sub_sql_reply {
1.12      harris41 7873:     my ($cmd)=@_;
                   7874:     my $unixsock="mysqlsock";
                   7875:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   7876:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   7877:                                       Type    => SOCK_STREAM,
                   7878:                                       Timeout => 10)
                   7879:        or return "con_lost";
1.319     www      7880:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 7881:     my $answer=<$sclient>;
                   7882:     chomp($answer);
                   7883:     if (!$answer) { $answer="con_lost"; }
                   7884:     return $answer;
                   7885: }
                   7886: 
1.1       albertel 7887: # --------------------------------------- Is this the home server of an author?
1.11      www      7888: 
1.1       albertel 7889: sub ishome {
                   7890:     my $author=shift;
                   7891:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   7892:     my ($udom,$uname)=split(/\//,$author);
                   7893:     my $proname=propath($udom,$uname);
                   7894:     if (-e $proname) {
                   7895: 	return 'owner';
                   7896:     } else {
                   7897:         return 'not_owner';
                   7898:     }
                   7899: }
                   7900: 
                   7901: # ======================================================= Continue main program
                   7902: # ---------------------------------------------------- Fork once and dissociate
                   7903: 
1.134     albertel 7904: my $fpid=fork;
1.1       albertel 7905: exit if $fpid;
1.29      harris41 7906: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 7907: 
1.29      harris41 7908: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 7909: 
                   7910: # ------------------------------------------------------- Write our PID on disk
                   7911: 
1.134     albertel 7912: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 7913: open (PIDSAVE,">$execdir/logs/lond.pid");
                   7914: print PIDSAVE "$$\n";
                   7915: close(PIDSAVE);
1.190     albertel 7916: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      7917: &status('Starting');
1.1       albertel 7918: 
1.106     foxr     7919: 
1.1       albertel 7920: 
                   7921: # ----------------------------------------------------- Install signal handlers
                   7922: 
1.57      www      7923: 
1.1       albertel 7924: $SIG{CHLD} = \&REAPER;
                   7925: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   7926: $SIG{HUP}  = \&HUPSMAN;
1.57      www      7927: $SIG{USR1} = \&checkchildren;
1.144     foxr     7928: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     7929: 
1.148     foxr     7930: #  Read the host hashes:
1.368     albertel 7931: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  7932: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     7933: 
1.480     raeburn  7934: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 7935: 
1.471     raeburn  7936: my $arch = `uname -i`;
1.475     raeburn  7937: chomp($arch);
1.471     raeburn  7938: if ($arch eq 'unknown') {
                   7939:     $arch = `uname -m`;
1.475     raeburn  7940:     chomp($arch);
1.471     raeburn  7941: }
                   7942: 
1.555     raeburn  7943: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532     raeburn  7944:     &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
                   7945: }
                   7946: 
1.106     foxr     7947: # --------------------------------------------------------------
                   7948: #   Accept connections.  When a connection comes in, it is validated
                   7949: #   and if good, a child process is created to process transactions
                   7950: #   along the connection.
                   7951: 
1.1       albertel 7952: while (1) {
1.165     albertel 7953:     &status('Starting accept');
1.106     foxr     7954:     $client = $server->accept() or next;
1.165     albertel 7955:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 7956:     make_new_child($client);
1.165     albertel 7957:     &status('Finished spawning');
1.1       albertel 7958: }
                   7959: 
1.212     foxr     7960: sub make_new_child {
                   7961:     my $pid;
                   7962: #    my $cipher;     # Now global
                   7963:     my $sigset;
1.178     foxr     7964: 
1.212     foxr     7965:     $client = shift;
                   7966:     &status('Starting new child '.$client);
                   7967:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   7968: 	     ")</font>");    
                   7969:     # block signal for fork
                   7970:     $sigset = POSIX::SigSet->new(SIGINT);
                   7971:     sigprocmask(SIG_BLOCK, $sigset)
                   7972:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7973: 
1.212     foxr     7974:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7975: 
1.212     foxr     7976:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7977: 	                               # connection liveness.
1.178     foxr     7978: 
1.212     foxr     7979:     #
                   7980:     #  Figure out who we're talking to so we can record the peer in 
                   7981:     #  the pid hash.
                   7982:     #
                   7983:     my $caller = getpeername($client);
                   7984:     my ($port,$iaddr);
                   7985:     if (defined($caller) && length($caller) > 0) {
                   7986: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7987:     } else {
                   7988: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7989:     }
                   7990:     if (defined($iaddr)) {
                   7991: 	$clientip  = inet_ntoa($iaddr);
                   7992: 	Debug("Connected with $clientip");
                   7993:     } else {
                   7994: 	&logthis("Unable to determine clientip");
                   7995: 	$clientip='Unavailable';
                   7996:     }
                   7997:     
                   7998:     if ($pid) {
                   7999:         # Parent records the child's birth and returns.
                   8000:         sigprocmask(SIG_UNBLOCK, $sigset)
                   8001:             or die "Can't unblock SIGINT for fork: $!\n";
                   8002:         $children{$pid} = $clientip;
                   8003:         &status('Started child '.$pid);
1.462     foxr     8004: 	close($client);
1.212     foxr     8005:         return;
                   8006:     } else {
                   8007:         # Child can *not* return from this subroutine.
                   8008:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   8009:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   8010:                                 #don't get intercepted
                   8011:         $SIG{USR1}= \&logstatus;
                   8012:         $SIG{ALRM}= \&timeout;
1.468     foxr     8013: 	#
                   8014: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   8015: 	# deal with that as a read faiure instead.
                   8016: 	#
                   8017: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   8018: 	sigprocmask(SIG_BLOCK, $blockset);
                   8019: 
1.212     foxr     8020:         $lastlog='Forked ';
                   8021:         $status='Forked';
1.178     foxr     8022: 
1.212     foxr     8023:         # unblock signals
                   8024:         sigprocmask(SIG_UNBLOCK, $sigset)
                   8025:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     8026: 
1.212     foxr     8027: #        my $tmpsnum=0;            # Now global
                   8028: #---------------------------------------------------- kerberos 5 initialization
                   8029:         &Authen::Krb5::init_context();
1.511     raeburn  8030: 
                   8031:         my $no_ets;
1.571     raeburn  8032:         if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
1.511     raeburn  8033:             if ($1 >= 7) {
                   8034:                 $no_ets = 1;
                   8035:             }
                   8036:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   8037:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   8038:                 $no_ets = 1; 
                   8039:             }
1.514     raeburn  8040:         } elsif ($dist =~ /^sles(\d+)$/) {
                   8041:             if ($1 > 11) {
                   8042:                 $no_ets = 1;
                   8043:             }
1.511     raeburn  8044:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   8045:             if ($1 < 7) {
                   8046:                 $no_ets = 1;
                   8047:             }
                   8048:         }
                   8049:         unless ($no_ets) {
1.286     albertel 8050: 	    &Authen::Krb5::init_ets();
                   8051: 	}
1.209     albertel 8052: 
1.212     foxr     8053: 	&status('Accepted connection');
                   8054: # =============================================================================
                   8055:             # do something with the connection
                   8056: # -----------------------------------------------------------------------------
                   8057: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     8058: 
1.278     albertel 8059: 	my $outsideip=$clientip;
                   8060: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 8061: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 8062: 	}
1.412     foxr     8063: 	&ReadManagerTable();
1.368     albertel 8064: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 8065: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  8066: 	$clientname  = "[unknown]";
1.212     foxr     8067: 	if($clientrec) {	# Establish client type.
                   8068: 	    $ConnectionType = "client";
1.368     albertel 8069: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     8070: 	    if($ismanager) {
                   8071: 		$ConnectionType = "both";
                   8072: 	    }
                   8073: 	} else {
                   8074: 	    $ConnectionType = "manager";
1.278     albertel 8075: 	    $clientname = $managers{$outsideip};
1.212     foxr     8076: 	}
1.556     raeburn  8077: 	my $clientok;
1.178     foxr     8078: 
1.212     foxr     8079: 	if ($clientrec || $ismanager) {
                   8080: 	    &status("Waiting for init from $clientip $clientname");
                   8081: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   8082: 		     $clientip.
                   8083: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   8084: 	    &status("Connecting $clientip  ($clientname))"); 
                   8085: 	    my $remotereq=<$client>;
                   8086: 	    chomp($remotereq);
                   8087: 	    Debug("Got init: $remotereq");
1.337     albertel 8088: 
1.212     foxr     8089: 	    if ($remotereq =~ /^init/) {
                   8090: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   8091: 		#
                   8092: 		#  If the remote is attempting a local init... give that a try:
                   8093: 		#
1.432     raeburn  8094: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 8095:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   8096:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   8097:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 8098:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   8099:         # it's overridden below in this case
1.492     droeschl 8100:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 8101: 
1.212     foxr     8102: 		# If the connection type is ssl, but I didn't get my
                   8103: 		# certificate files yet, then I'll drop  back to 
                   8104: 		# insecure (if allowed).
1.532     raeburn  8105: 
                   8106:                 if ($inittype eq "ssl") {
                   8107:                     my $context;
                   8108:                     if ($clientsamedom) {
                   8109:                         $context = 'dom';
                   8110:                         if ($secureconf{'connfrom'}{'dom'} eq 'no') {
                   8111:                             $inittype = "";
                   8112:                         }
                   8113:                     } elsif ($clientsameinst) {
                   8114:                         $context = 'intdom';
                   8115:                         if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
                   8116:                             $inittype = "";
                   8117:                         }
                   8118:                     } else {
                   8119:                         $context = 'other';
                   8120:                         if ($secureconf{'connfrom'}{'other'} eq 'no') {
                   8121:                             $inittype = "";
                   8122:                         }
                   8123:                     }
                   8124:                     if ($inittype eq '') {
                   8125:                         &logthis("<font color=\"blue\"> Domain config set "
                   8126:                                 ."to no ssl for $clientname (context: $context)"
                   8127:                                 ." -- trying insecure auth</font>");
                   8128:                     }
                   8129:                 }
                   8130: 
1.212     foxr     8131: 		if($inittype eq "ssl") {
                   8132: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   8133: 		    my $kfile       = lonssl::KeyFile;
                   8134: 		    if((!$ca)   || 
                   8135: 		       (!$cert) || 
                   8136: 		       (!$kfile)) {
                   8137: 			$inittype = ""; # This forces insecure attempt.
                   8138: 			&logthis("<font color=\"blue\"> Certificates not "
                   8139: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     8140: 		    } else {	# SSL certificates are in place so
1.212     foxr     8141: 		    }		# Leave the inittype alone.
                   8142: 		}
                   8143: 
                   8144: 		if($inittype eq "local") {
1.432     raeburn  8145:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     8146: 		    my $key = LocalConnection($client, $remotereq);
                   8147: 		    if($key) {
                   8148: 			Debug("Got local key $key");
                   8149: 			$clientok     = 1;
                   8150: 			my $cipherkey = pack("H32", $key);
                   8151: 			$cipher       = new IDEA($cipherkey);
                   8152: 			print $client "ok:local\n";
1.442     www      8153: 			&logthis('<font color="green">'
1.212     foxr     8154: 				 . "Successful local authentication </font>");
                   8155: 			$keymode = "local"
1.178     foxr     8156: 		    } else {
1.212     foxr     8157: 			Debug("Failed to get local key");
                   8158: 			$clientok = 0;
                   8159: 			shutdown($client, 3);
                   8160: 			close $client;
1.178     foxr     8161: 		    }
1.212     foxr     8162: 		} elsif ($inittype eq "ssl") {
1.532     raeburn  8163: 		    my $key = SSLConnection($client,$clientname);
1.212     foxr     8164: 		    if ($key) {
                   8165: 			$clientok = 1;
                   8166: 			my $cipherkey = pack("H32", $key);
                   8167: 			$cipher       = new IDEA($cipherkey);
                   8168: 			&logthis('<font color="green">'
                   8169: 				 ."Successfull ssl authentication with $clientname </font>");
                   8170: 			$keymode = "ssl";
                   8171: 	     
1.178     foxr     8172: 		    } else {
1.212     foxr     8173: 			$clientok = 0;
                   8174: 			close $client;
1.178     foxr     8175: 		    }
1.212     foxr     8176: 	   
                   8177: 		} else {
                   8178: 		    my $ok = InsecureConnection($client);
                   8179: 		    if($ok) {
                   8180: 			$clientok = 1;
                   8181: 			&logthis('<font color="green">'
                   8182: 				 ."Successful insecure authentication with $clientname </font>");
                   8183: 			print $client "ok\n";
                   8184: 			$keymode = "insecure";
1.178     foxr     8185: 		    } else {
1.212     foxr     8186: 			&logthis('<font color="yellow">'
                   8187: 				  ."Attempted insecure connection disallowed </font>");
                   8188: 			close $client;
                   8189: 			$clientok = 0;
1.178     foxr     8190: 		    }
                   8191: 		}
1.212     foxr     8192: 	    } else {
                   8193: 		&logthis(
                   8194: 			 "<font color='blue'>WARNING: "
                   8195: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   8196: 		&status('No init '.$clientip);
                   8197: 	    }
                   8198: 	} else {
                   8199: 	    &logthis(
                   8200: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   8201: 	    &status('Hung up on '.$clientip);
                   8202: 	}
                   8203:  
                   8204: 	if ($clientok) {
                   8205: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 8206: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 8207: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 8208: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     8209: 	    }
                   8210: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   8211: 	    &status('Will listen to '.$clientname);
                   8212: # ------------------------------------------------------------ Process requests
                   8213: 	    my $keep_going = 1;
                   8214: 	    my $user_input;
1.556     raeburn  8215: 
1.212     foxr     8216: 	    while(($user_input = get_request) && $keep_going) {
                   8217: 		alarm(120);
                   8218: 		Debug("Main: Got $user_input\n");
                   8219: 		$keep_going = &process_request($user_input);
1.178     foxr     8220: 		alarm(0);
1.569     raeburn  8221: 		&status('Listening to '.$clientname." ($keymode)");
1.161     foxr     8222: 	    }
1.212     foxr     8223: 
1.59      www      8224: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     8225: 	}  else {
1.161     foxr     8226: 	    print $client "refused\n";
                   8227: 	    $client->close();
1.190     albertel 8228: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     8229: 		     ."Rejected client $clientip, closing connection</font>");
                   8230: 	}
1.525     raeburn  8231:     }
1.161     foxr     8232:     
1.1       albertel 8233: # =============================================================================
1.161     foxr     8234:     
1.190     albertel 8235:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     8236: 	     ."Disconnect from $clientip ($clientname)</font>");    
1.569     raeburn  8237: 
                   8238: 
1.161     foxr     8239:     # this exit is VERY important, otherwise the child will become
                   8240:     # a producer of more and more children, forking yourself into
                   8241:     # process death.
                   8242:     exit;
1.106     foxr     8243:     
1.78      foxr     8244: }
1.532     raeburn  8245: 
                   8246: #
                   8247: #  Used to determine if a particular client is from the same domain
1.556     raeburn  8248: #  as the current server, or from the same internet domain, and
                   8249: #  also if the client can host sessions for the domain's users.
                   8250: #  A hash is populated with keys set to commands sent by the client
                   8251: #  which may not be executed for this domain.
1.532     raeburn  8252: #
                   8253: #  Optional input -- the client to check for domain and internet domain.
                   8254: #  If not specified, defaults to the package variable: $clientname
                   8255: #
                   8256: #  If called in array context will not set package variables, but will
                   8257: #  instead return an array of two values - (a) true if client is in the
1.556     raeburn  8258: #  same domain as the server, and (b) true if client is in the same 
                   8259: #  internet domain.
1.532     raeburn  8260: #
                   8261: #  If called in scalar context, sets package variables for current client:
                   8262: #
1.556     raeburn  8263: #  $clienthomedom    - LonCAPA domain of homeID for client.
                   8264: #  $clientsamedom    - LonCAPA domain same for this host and client.
                   8265: #  $clientintdom     - LonCAPA "internet domain" for client.
                   8266: #  $clientsameinst   - LonCAPA "internet domain" same for this host & client.
                   8267: #  $clientremoteok   - If current domain permits hosting on this client: 1
                   8268: #  %clientprohibited - Commands prohibited for domain's users for this client.
                   8269: #
                   8270: #  if the host and client have the same "internet domain", then the value
                   8271: #  of $clientremoteok is not used, and no commands are prohibited.
1.532     raeburn  8272: #
                   8273: #  returns 1 to indicate package variables have been set for current client.
                   8274: #
                   8275: 
                   8276: sub set_client_info {
                   8277:     my ($lonhost) = @_;
                   8278:     $lonhost ||= $clientname;
                   8279:     my $clienthost = &Apache::lonnet::hostname($lonhost);
                   8280:     my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   8281:     my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
                   8282:     my $samedom = 0;
1.557     raeburn  8283:     if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532     raeburn  8284:         $samedom = 1;
                   8285:     }
                   8286:     my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   8287:     my $sameinst = 0;
                   8288:     if ($intdom ne '') {
                   8289:         my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   8290:         if (ref($internet_names) eq 'ARRAY') {
                   8291:             if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
                   8292:                 $sameinst = 1;
                   8293:             }
                   8294:         }
                   8295:     }
                   8296:     if (wantarray) {
                   8297:         return ($samedom,$sameinst);
                   8298:     } else {
                   8299:         $clienthomedom = $homedom;
                   8300:         $clientsamedom = $samedom;
                   8301:         $clientintdom = $intdom;
                   8302:         $clientsameinst = $sameinst;
1.556     raeburn  8303:         if ($clientsameinst) {
                   8304:             undef($clientremoteok);
                   8305:             undef(%clientprohibited);
                   8306:         } else {
                   8307:             $clientremoteok = &get_remote_hostable($currentdomainid);
                   8308:             %clientprohibited = &get_prohibited($currentdomainid);
                   8309:         }
1.532     raeburn  8310:         return 1;
                   8311:     }
                   8312: }
                   8313: 
1.261     foxr     8314: #
                   8315: #   Determine if a user is an author for the indicated domain.
                   8316: #
                   8317: # Parameters:
                   8318: #    domain          - domain to check in .
                   8319: #    user            - Name of user to check.
                   8320: #
                   8321: # Return:
                   8322: #     1             - User is an author for domain.
                   8323: #     0             - User is not an author for domain.
                   8324: sub is_author {
                   8325:     my ($domain, $user) = @_;
                   8326: 
                   8327:     &Debug("is_author: $user @ $domain");
                   8328: 
                   8329:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   8330: 				 &GDBM_READER());
                   8331: 
                   8332:     #  Author role should show up as a key /domain/_au
1.78      foxr     8333: 
1.321     albertel 8334:     my $value;
1.487     foxr     8335:     if ($hashref) {
1.78      foxr     8336: 
1.487     foxr     8337: 	my $key    = "/$domain/_au";
                   8338: 	if (defined($hashref)) {
                   8339: 	    $value = $hashref->{$key};
                   8340: 	    if(!untie_user_hash($hashref)) {
                   8341: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   8342: 	    }
                   8343: 	}
                   8344: 	
                   8345: 	if(defined($value)) {
                   8346: 	    &Debug("$user @ $domain is an author");
                   8347: 	}
                   8348:     } else {
                   8349: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     8350:     }
                   8351: 
                   8352:     return defined($value);
                   8353: }
1.78      foxr     8354: #
                   8355: #   Checks to see if the input roleput request was to set
1.482     www      8356: # an author role.  If so, creates construction space 
1.78      foxr     8357: # Parameters:
                   8358: #    request   - The request sent to the rolesput subchunk.
                   8359: #                We're looking for  /domain/_au
                   8360: #    domain    - The domain in which the user is having roles doctored.
                   8361: #    user      - Name of the user for which the role is being put.
                   8362: #    authtype  - The authentication type associated with the user.
                   8363: #
1.289     albertel 8364: sub manage_permissions {
1.192     foxr     8365:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     8366:     # See if the request is of the form /$domain/_au
1.289     albertel 8367:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  8368:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      8369:         unless (-e $path) {        
                   8370:            mkdir($path);
                   8371:         }
                   8372:         unless (-e $path.'/'.$user) {
                   8373:            mkdir($path.'/'.$user);
                   8374:         }
1.78      foxr     8375:     }
                   8376: }
1.222     foxr     8377: 
                   8378: 
                   8379: #
                   8380: #  Return the full path of a user password file, whether it exists or not.
                   8381: # Parameters:
                   8382: #   domain     - Domain in which the password file lives.
                   8383: #   user       - name of the user.
                   8384: # Returns:
                   8385: #    Full passwd path:
                   8386: #
                   8387: sub password_path {
                   8388:     my ($domain, $user) = @_;
1.264     albertel 8389:     return &propath($domain, $user).'/passwd';
1.222     foxr     8390: }
                   8391: 
                   8392: #   Password Filename
                   8393: #   Returns the path to a passwd file given domain and user... only if
                   8394: #  it exists.
                   8395: # Parameters:
                   8396: #   domain    - Domain in which to search.
                   8397: #   user      - username.
                   8398: # Returns:
                   8399: #   - If the password file exists returns its path.
                   8400: #   - If the password file does not exist, returns undefined.
                   8401: #
                   8402: sub password_filename {
                   8403:     my ($domain, $user) = @_;
                   8404: 
                   8405:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   8406: 
                   8407:     my $path  = &password_path($domain, $user);
                   8408:     Debug("PasswordFilename got path: $path");
                   8409:     if(-e $path) {
                   8410: 	return $path;
                   8411:     } else {
                   8412: 	return undef;
                   8413:     }
                   8414: }
                   8415: 
                   8416: #
                   8417: #   Rewrite the contents of the user's passwd file.
                   8418: #  Parameters:
                   8419: #    domain    - domain of the user.
                   8420: #    name      - User's name.
                   8421: #    contents  - New contents of the file.
1.533     raeburn  8422: #    saveold   - (optional). If true save old file in a passwd.bak file.
1.222     foxr     8423: # Returns:
                   8424: #   0    - Failed.
                   8425: #   1    - Success.
                   8426: #
                   8427: sub rewrite_password_file {
1.533     raeburn  8428:     my ($domain, $user, $contents, $saveold) = @_;
1.222     foxr     8429: 
                   8430:     my $file = &password_filename($domain, $user);
                   8431:     if (defined $file) {
1.533     raeburn  8432:         if ($saveold) {
                   8433:             my $bakfile = $file.'.bak';
                   8434:             if (CopyFile($file,$bakfile)) {
                   8435:                 chmod(0400,$bakfile);
                   8436:                 &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
                   8437:             } else {
                   8438:                 &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
                   8439:             }
                   8440:         }
1.222     foxr     8441: 	my $pf = IO::File->new(">$file");
                   8442: 	if($pf) {
                   8443: 	    print $pf "$contents\n";
                   8444: 	    return 1;
                   8445: 	} else {
                   8446: 	    return 0;
                   8447: 	}
                   8448:     } else {
                   8449: 	return 0;
                   8450:     }
                   8451: 
                   8452: }
                   8453: 
1.78      foxr     8454: #
1.222     foxr     8455: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     8456: 
                   8457: #     Returns the authorization type or nouser if there is no such user.
                   8458: #
1.436     raeburn  8459: sub get_auth_type {
1.192     foxr     8460:     my ($domain, $user)  = @_;
1.78      foxr     8461: 
1.222     foxr     8462:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     8463:     my $proname    = &propath($domain, $user); 
                   8464:     my $passwdfile = "$proname/passwd";
                   8465:     if( -e $passwdfile ) {
                   8466: 	my $pf = IO::File->new($passwdfile);
                   8467: 	my $realpassword = <$pf>;
                   8468: 	chomp($realpassword);
1.79      foxr     8469: 	Debug("Password info = $realpassword\n");
1.78      foxr     8470: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     8471: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  8472: 	return "$authtype:$contentpwd";     
1.224     foxr     8473:     } else {
1.79      foxr     8474: 	Debug("Returning nouser");
1.78      foxr     8475: 	return "nouser";
                   8476:     }
1.1       albertel 8477: }
                   8478: 
1.220     foxr     8479: #
                   8480: #  Validate a user given their domain, name and password.  This utility
                   8481: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   8482: #  to validate the login credentials of a user.
                   8483: # Parameters:
                   8484: #    $domain    - The domain being logged into (this is required due to
                   8485: #                 the capability for multihomed systems.
                   8486: #    $user      - The name of the user being validated.
                   8487: #    $password  - The user's propoposed password.
                   8488: #
                   8489: # Returns:
                   8490: #     1        - The domain,user,pasword triplet corresponds to a valid
                   8491: #                user.
                   8492: #     0        - The domain,user,password triplet is not a valid user.
                   8493: #
                   8494: sub validate_user {
1.396     raeburn  8495:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     8496: 
                   8497:     # Why negative ~pi you may well ask?  Well this function is about
                   8498:     # authentication, and therefore very important to get right.
                   8499:     # I've initialized the flag that determines whether or not I've 
                   8500:     # validated correctly to a value it's not supposed to get.
                   8501:     # At the end of this function. I'll ensure that it's not still that
                   8502:     # value so we don't just wind up returning some accidental value
                   8503:     # as a result of executing an unforseen code path that
1.249     foxr     8504:     # did not set $validated.  At the end of valid execution paths,
                   8505:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     8506: 
                   8507:     my $validated = -3.14159;
                   8508: 
                   8509:     #  How we authenticate is determined by the type of authentication
                   8510:     #  the user has been assigned.  If the authentication type is
                   8511:     #  "nouser", the user does not exist so we will return 0.
                   8512: 
1.222     foxr     8513:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     8514:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   8515: 
                   8516:     my $null = pack("C",0);	# Used by kerberos auth types.
                   8517: 
1.395     raeburn  8518:     if ($howpwd eq 'nouser') {
1.396     raeburn  8519:         if ($checkdefauth) {
                   8520:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8521:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   8522:                 $howpwd = $domdefaults{'auth_def'};
                   8523:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   8524:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   8525:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   8526:                      ($domdefaults{'auth_arg_def'} ne '')) {
1.574     raeburn  8527:                 #
                   8528:                 # Don't attempt authentication for username and password supplied
                   8529:                 # for user without an account if uername contains @ to avoid
1.575     raeburn  8530:                 # call to &Authen::Krb5::parse_name() which will result in con_lost
1.574     raeburn  8531:                 #
                   8532:                 unless ($user =~ /\@/) {
                   8533:                     $howpwd = $domdefaults{'auth_def'};
                   8534:                     $contentpwd = $domdefaults{'auth_arg_def'};
                   8535:                 }
1.396     raeburn  8536:             }
1.395     raeburn  8537:         }
1.533     raeburn  8538:     }
1.220     foxr     8539:     if ($howpwd ne 'nouser') {
                   8540: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  8541:             if (length($contentpwd) == 13) {
                   8542:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   8543:                 if ($validated) {
1.533     raeburn  8544:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8545:                     if ($domdefaults{'intauth_switch'}) {
                   8546:                         my $ncpass = &hash_passwd($domain,$password);
                   8547:                         my $saveold;
                   8548:                         if ($domdefaults{'intauth_switch'} == 2) {
                   8549:                             $saveold = 1;
                   8550:                         }
                   8551:                         if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
                   8552:                             &update_passwd_history($user,$domain,$howpwd,'conversion');
                   8553:                             &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8554:                         }
1.518     raeburn  8555:                     }
                   8556:                 }
                   8557:             } else {
1.533     raeburn  8558:                 $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518     raeburn  8559:             }
1.220     foxr     8560: 	}
                   8561: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   8562: 	    $contentpwd = (getpwnam($user))[1];
                   8563: 	    if($contentpwd) {
                   8564: 		if($contentpwd eq 'x') { # Shadow password file...
                   8565: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   8566: 		    open PWAUTH,  "|$pwauth_path" or
                   8567: 			die "Cannot invoke authentication";
                   8568: 		    print PWAUTH "$user\n$password\n";
                   8569: 		    close PWAUTH;
                   8570: 		    $validated = ! $?;
                   8571: 
                   8572: 		} else { 	         # Passwords in /etc/passwd. 
                   8573: 		    $validated = (crypt($password,
                   8574: 					$contentpwd) eq $contentpwd);
                   8575: 		}
                   8576: 	    } else {
                   8577: 		$validated = 0;
                   8578: 	    }
1.439     raeburn  8579: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   8580:             my $checkwithkrb5 = 0;
                   8581:             if ($dist =~/^fedora(\d+)$/) {
                   8582:                 if ($1 > 11) {
                   8583:                     $checkwithkrb5 = 1;
                   8584:                 }
                   8585:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   8586:                 if ($1 > 11.1) {
                   8587:                     $checkwithkrb5 = 1; 
                   8588:                 }
                   8589:             }
                   8590:             if ($checkwithkrb5) {
                   8591:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   8592:             } else {
                   8593:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   8594:             }
1.224     foxr     8595: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  8596:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     8597: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     8598: 	    #  Authenticate via installation specific authentcation method:
                   8599: 	    $validated = &localauth::localauth($user, 
                   8600: 					       $password, 
1.353     albertel 8601: 					       $contentpwd,
                   8602: 					       $domain);
1.358     albertel 8603: 	    if ($validated < 0) {
1.357     albertel 8604: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   8605: 		$validated = 0;
                   8606: 	    }
1.224     foxr     8607: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     8608: 	    $validated = 0;
                   8609: 	}
                   8610:     } else {
                   8611: 	$validated = 0;
                   8612:     }
                   8613:     #
                   8614:     #  $validated has the correct stat of the authentication:
                   8615:     #
                   8616: 
                   8617:     unless ($validated != -3.14159) {
1.249     foxr     8618: 	#  I >really really< want to know if this happens.
                   8619: 	#  since it indicates that user authentication is badly
                   8620: 	#  broken in some code path.
                   8621:         #
                   8622: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     8623:     }
                   8624:     return $validated;
                   8625: }
                   8626: 
1.518     raeburn  8627: sub check_internal_passwd {
1.533     raeburn  8628:     my ($plainpass,$stored,$domain,$user) = @_;
1.518     raeburn  8629:     my (undef,$method,@rest) = split(/!/,$stored);
1.533     raeburn  8630:     if ($method eq 'bcrypt') {
1.518     raeburn  8631:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   8632:         if ($result ne $stored) {
                   8633:             return 0;
                   8634:         }
1.533     raeburn  8635:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   8636:         if ($domdefaults{'intauth_check'}) {
                   8637:             # Upgrade to a larger number of rounds if necessary
                   8638:             my $defaultcost = $domdefaults{'intauth_cost'};
                   8639:             if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   8640:                 $defaultcost = 10;
                   8641:             }
                   8642:             if (int($rest[0])<int($defaultcost)) {
                   8643:                 if ($domdefaults{'intauth_check'} == 1) { 
                   8644:                     my $ncpass = &hash_passwd($domain,$plainpass);
                   8645:                     if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
                   8646:                         &update_passwd_history($user,$domain,'internal','update cost');
                   8647:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   8648:                     }
                   8649:                     return 1;
                   8650:                 } elsif ($domdefaults{'intauth_check'} == 2) {
                   8651:                     return 0;
                   8652:                 }
                   8653:             }
                   8654:         } else {
                   8655:             return 1;
1.518     raeburn  8656:         }
                   8657:     }
                   8658:     return 0;
                   8659: }
                   8660: 
                   8661: sub get_last_authchg {
                   8662:     my ($domain,$user) = @_;
                   8663:     my $lastmod;
                   8664:     my $logname = &propath($domain,$user).'/passwd.log';
                   8665:     if (-e "$logname") {
                   8666:         $lastmod = (stat("$logname"))[9];
                   8667:     }
                   8668:     return $lastmod;
                   8669: }
                   8670: 
1.439     raeburn  8671: sub krb4_authen {
                   8672:     my ($password,$null,$user,$contentpwd) = @_;
                   8673:     my $validated = 0;
                   8674:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   8675:         eval {
                   8676:             require Authen::Krb4;
                   8677:         };
                   8678:         if (!$@) {
                   8679:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   8680:                                                        "",
                   8681:                                                        $contentpwd,,
                   8682:                                                        'krbtgt',
                   8683:                                                        $contentpwd,
                   8684:                                                        1,
                   8685:                                                        $password);
                   8686:             if(!$k4error) {
                   8687:                 $validated = 1;
                   8688:             } else {
                   8689:                 $validated = 0;
                   8690:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   8691:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   8692:             }
                   8693:         } else {
                   8694:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   8695:         }
                   8696:     }
                   8697:     return $validated;
                   8698: }
                   8699: 
                   8700: sub krb5_authen {
                   8701:     my ($password,$null,$user,$contentpwd) = @_;
                   8702:     my $validated = 0;
                   8703:     if(!($password =~ /$null/)) { # Null password not allowed.
                   8704:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   8705:                                                   .$contentpwd);
                   8706:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   8707:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   8708:         my $credentials= &Authen::Krb5::cc_default();
                   8709:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   8710:                                                             .$contentpwd));
                   8711:         my $krbreturn;
                   8712:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   8713:             $krbreturn =
                   8714:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   8715:                                                           $krbservice);
                   8716:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   8717:         } else {
                   8718:             $krbreturn  =
                   8719:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   8720:                                                          $password,$credentials);
                   8721:             $validated = ($krbreturn == 1);
                   8722:         }
                   8723:         if (!$validated) {
                   8724:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   8725:                      &Authen::Krb5::error());
                   8726:         }
                   8727:     }
                   8728:     return $validated;
                   8729: }
1.220     foxr     8730: 
1.84      albertel 8731: sub addline {
                   8732:     my ($fname,$hostid,$ip,$newline)=@_;
                   8733:     my $contents;
                   8734:     my $found=0;
1.355     albertel 8735:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 8736:     my $sh;
1.84      albertel 8737:     if ($sh=IO::File->new("$fname.subscription")) {
                   8738: 	while (my $subline=<$sh>) {
                   8739: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   8740: 	}
                   8741: 	$sh->close();
                   8742:     }
                   8743:     $sh=IO::File->new(">$fname.subscription");
                   8744:     if ($contents) { print $sh $contents; }
                   8745:     if ($newline) { print $sh $newline; }
                   8746:     $sh->close();
                   8747:     return $found;
1.86      www      8748: }
                   8749: 
1.234     foxr     8750: sub get_chat {
1.324     raeburn  8751:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 8752: 
1.87      www      8753:     my @entries=();
1.324     raeburn  8754:     my $namespace = 'nohist_chatroom';
                   8755:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 8756:     if ($group ne '') {
1.324     raeburn  8757:         $namespace .= '_'.$group;
                   8758:         $namespace_inroom .= '_'.$group;
                   8759:     }
                   8760:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8761: 				 &GDBM_READER());
                   8762:     if ($hashref) {
                   8763: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 8764: 	&untie_user_hash($hashref);
1.123     www      8765:     }
1.124     www      8766:     my @participants=();
1.134     albertel 8767:     my $cutoff=time-60;
1.324     raeburn  8768:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 8769: 			      &GDBM_WRCREAT());
                   8770:     if ($hashref) {
                   8771:         $hashref->{$uname.':'.$udom}=time;
                   8772:         foreach my $user (sort(keys(%$hashref))) {
                   8773: 	    if ($hashref->{$user}>$cutoff) {
                   8774: 		push(@participants, 'active_participant:'.$user);
1.123     www      8775:             }
                   8776:         }
1.311     albertel 8777:         &untie_user_hash($hashref);
1.86      www      8778:     }
1.124     www      8779:     return (@participants,@entries);
1.86      www      8780: }
                   8781: 
1.234     foxr     8782: sub chat_add {
1.324     raeburn  8783:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 8784:     my @entries=();
1.142     www      8785:     my $time=time;
1.324     raeburn  8786:     my $namespace = 'nohist_chatroom';
                   8787:     my $logfile = 'chatroom.log';
1.335     albertel 8788:     if ($group ne '') {
1.324     raeburn  8789:         $namespace .= '_'.$group;
                   8790:         $logfile = 'chatroom_'.$group.'.log';
                   8791:     }
                   8792:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 8793: 				 &GDBM_WRCREAT());
                   8794:     if ($hashref) {
                   8795: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 8796: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   8797: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   8798: 	my $newid=$time.'_000000';
                   8799: 	if ($thentime==$time) {
                   8800: 	    $idnum=~s/^0+//;
                   8801: 	    $idnum++;
                   8802: 	    $idnum=substr('000000'.$idnum,-6,6);
                   8803: 	    $newid=$time.'_'.$idnum;
                   8804: 	}
1.310     albertel 8805: 	$hashref->{$newid}=$newchat;
1.88      albertel 8806: 	my $expired=$time-3600;
1.310     albertel 8807: 	foreach my $comment (keys(%$hashref)) {
                   8808: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 8809: 	    if ($thistime<$expired) {
1.310     albertel 8810: 		delete $hashref->{$comment};
1.88      albertel 8811: 	    }
                   8812: 	}
1.310     albertel 8813: 	{
                   8814: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  8815: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 8816: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   8817: 	    }
                   8818: 	    close(CHATLOG);
1.142     www      8819: 	}
1.311     albertel 8820: 	&untie_user_hash($hashref);
1.86      www      8821:     }
1.84      albertel 8822: }
                   8823: 
                   8824: sub unsub {
                   8825:     my ($fname,$clientip)=@_;
                   8826:     my $result;
1.188     foxr     8827:     my $unsubs = 0;		# Number of successful unsubscribes:
                   8828: 
                   8829: 
                   8830:     # An old way subscriptions were handled was to have a 
                   8831:     # subscription marker file:
                   8832: 
                   8833:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     8834:     if (unlink("$fname.$clientname")) {
1.188     foxr     8835: 	$unsubs++;		# Successful unsub via marker file.
                   8836:     } 
                   8837: 
                   8838:     # The more modern way to do it is to have a subscription list
                   8839:     # file:
                   8840: 
1.84      albertel 8841:     if (-e "$fname.subscription") {
1.161     foxr     8842: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     8843: 	if ($found) { 
                   8844: 	    $unsubs++;
                   8845: 	}
                   8846:     } 
                   8847: 
                   8848:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   8849:     #  resource we can return ok:
                   8850: 
                   8851:     if($unsubs) {
                   8852: 	$result = "ok\n";
1.84      albertel 8853:     } else {
1.188     foxr     8854: 	$result = "not_subscribed\n";
1.84      albertel 8855:     }
1.188     foxr     8856: 
1.84      albertel 8857:     return $result;
                   8858: }
                   8859: 
1.101     www      8860: sub currentversion {
                   8861:     my $fname=shift;
                   8862:     my $version=-1;
                   8863:     my $ulsdir='';
                   8864:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   8865:        $ulsdir=$1;
                   8866:     }
1.114     albertel 8867:     my ($fnamere1,$fnamere2);
                   8868:     # remove version if already specified
1.101     www      8869:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 8870:     # get the bits that go before and after the version number
                   8871:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   8872: 	$fnamere1=$1;
                   8873: 	$fnamere2='.'.$2;
                   8874:     }
1.101     www      8875:     if (-e $fname) { $version=1; }
                   8876:     if (-e $ulsdir) {
1.134     albertel 8877: 	if(-d $ulsdir) {
                   8878: 	    if (opendir(LSDIR,$ulsdir)) {
                   8879: 		my $ulsfn;
                   8880: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      8881: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 8882: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   8883: 		    unless (-l $thisfile) {
1.160     www      8884: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 8885: 			    if ($1>$version) { $version=$1; }
                   8886: 			}
                   8887: 		    }
                   8888: 		}
                   8889: 		closedir(LSDIR);
                   8890: 		$version++;
                   8891: 	    }
                   8892: 	}
                   8893:     }
                   8894:     return $version;
1.101     www      8895: }
                   8896: 
                   8897: sub thisversion {
                   8898:     my $fname=shift;
                   8899:     my $version=-1;
                   8900:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   8901: 	$version=$1;
                   8902:     }
                   8903:     return $version;
                   8904: }
                   8905: 
1.84      albertel 8906: sub subscribe {
                   8907:     my ($userinput,$clientip)=@_;
                   8908:     my $result;
1.293     albertel 8909:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 8910:     my $ownership=&ishome($fname);
                   8911:     if ($ownership eq 'owner') {
1.101     www      8912: # explitly asking for the current version?
                   8913:         unless (-e $fname) {
                   8914:             my $currentversion=&currentversion($fname);
                   8915: 	    if (&thisversion($fname)==$currentversion) {
                   8916:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   8917: 		    my $root=$1;
                   8918:                     my $extension=$2;
                   8919:                     symlink($root.'.'.$extension,
                   8920:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      8921:                     unless ($extension=~/\.meta$/) {
                   8922:                        symlink($root.'.'.$extension.'.meta',
                   8923:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   8924: 		    }
1.101     www      8925:                 }
                   8926:             }
                   8927:         }
1.84      albertel 8928: 	if (-e $fname) {
                   8929: 	    if (-d $fname) {
                   8930: 		$result="directory\n";
                   8931: 	    } else {
1.161     foxr     8932: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 8933: 		my $now=time;
1.161     foxr     8934: 		my $found=&addline($fname,$clientname,$clientip,
                   8935: 				   "$clientname:$clientip:$now\n");
1.84      albertel 8936: 		if ($found) { $result="$fname\n"; }
                   8937: 		# if they were subscribed to only meta data, delete that
                   8938:                 # subscription, when you subscribe to a file you also get
                   8939:                 # the metadata
                   8940: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   8941: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  8942:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   8943:                 $protocol = 'http' if ($protocol ne 'https');
                   8944: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 8945: 		$result="$fname\n";
                   8946: 	    }
                   8947: 	} else {
                   8948: 	    $result="not_found\n";
                   8949: 	}
                   8950:     } else {
                   8951: 	$result="rejected\n";
                   8952:     }
                   8953:     return $result;
                   8954: }
1.287     foxr     8955: #  Change the passwd of a unix user.  The caller must have
                   8956: #  first verified that the user is a loncapa user.
                   8957: #
                   8958: # Parameters:
                   8959: #    user      - Unix user name to change.
                   8960: #    pass      - New password for the user.
                   8961: # Returns:
                   8962: #    ok    - if success
                   8963: #    other - Some meaningfule error message string.
                   8964: # NOTE:
                   8965: #    invokes a setuid script to change the passwd.
                   8966: sub change_unix_password {
                   8967:     my ($user, $pass) = @_;
                   8968: 
                   8969:     &Debug("change_unix_password");
                   8970:     my $execdir=$perlvar{'lonDaemons'};
                   8971:     &Debug("Opening lcpasswd pipeline");
                   8972:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   8973: 			   ."$perlvar{'lonDaemons'}"
                   8974: 			   ."/logs/lcpasswd.log");
                   8975:     print $pf "$user\n$pass\n$pass\n";
                   8976:     close $pf;
                   8977:     my $err = $?;
                   8978:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   8979: 	"pwchange_falure - unknown error";
                   8980: 
                   8981:     
                   8982: }
                   8983: 
1.91      albertel 8984: 
                   8985: sub make_passwd_file {
1.518     raeburn  8986:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  8987:     my $result="ok";
1.91      albertel 8988:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   8989: 	{
                   8990: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     8991: 	    if ($pf) {
                   8992: 		print $pf "$umode:$npass\n";
1.518     raeburn  8993:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     8994: 	    } else {
                   8995: 		$result = "pass_file_failed_error";
                   8996: 	    }
1.91      albertel 8997: 	}
                   8998:     } elsif ($umode eq 'internal') {
1.518     raeburn  8999:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 9000: 	{
                   9001: 	    &Debug("Creating internal auth");
                   9002: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     9003: 	    if($pf) {
1.518     raeburn  9004: 		print $pf "internal:$ncpass\n";
                   9005:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     9006: 	    } else {
                   9007: 		$result = "pass_file_failed_error";
                   9008: 	    }
1.91      albertel 9009: 	}
                   9010:     } elsif ($umode eq 'localauth') {
                   9011: 	{
                   9012: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     9013: 	    if($pf) {
                   9014: 		print $pf "localauth:$npass\n";
1.524     raeburn  9015:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     9016: 	    } else {
                   9017: 		$result = "pass_file_failed_error";
                   9018: 	    }
1.91      albertel 9019: 	}
                   9020:     } elsif ($umode eq 'unix') {
1.502     raeburn  9021: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   9022: 	$result="no_new_unix_accounts";
1.91      albertel 9023:     } elsif ($umode eq 'none') {
                   9024: 	{
1.223     foxr     9025: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     9026: 	    if($pf) {
                   9027: 		print $pf "none:\n";
                   9028: 	    } else {
                   9029: 		$result = "pass_file_failed_error";
                   9030: 	    }
1.91      albertel 9031: 	}
1.543     raeburn  9032:     } elsif ($umode eq 'lti') {
                   9033:         my $pf = IO::File->new(">$passfilename");
                   9034:         if($pf) {
                   9035:             print $pf "lti:\n";
                   9036:             &update_passwd_history($uname,$udom,$umode,$action);
                   9037:         } else {
                   9038:             $result = "pass_file_failed_error";
                   9039:         }
1.91      albertel 9040:     } else {
1.390     raeburn  9041: 	$result="auth_mode_error";
1.91      albertel 9042:     }
                   9043:     return $result;
1.121     albertel 9044: }
                   9045: 
1.265     albertel 9046: sub convert_photo {
                   9047:     my ($start,$dest)=@_;
                   9048:     system("convert $start $dest");
                   9049: }
                   9050: 
1.121     albertel 9051: sub sethost {
                   9052:     my ($remotereq) = @_;
                   9053:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 9054:     # ignore sethost if we are already correct
                   9055:     if ($hostid eq $currenthostid) {
                   9056: 	return 'ok';
                   9057:     }
                   9058: 
1.121     albertel 9059:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 9060:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   9061: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  9062: 	$currenthostid  =$hostid;
1.369     albertel 9063: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556     raeburn  9064:         &set_client_info();
1.443     www      9065: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 9066:     } else {
                   9067: 	&logthis("Requested host id $hostid not an alias of ".
                   9068: 		 $perlvar{'lonHostID'}." refusing connection");
                   9069: 	return 'unable_to_set';
                   9070:     }
                   9071:     return 'ok';
                   9072: }
                   9073: 
                   9074: sub version {
                   9075:     my ($userinput)=@_;
                   9076:     $remoteVERSION=(split(/:/,$userinput))[1];
                   9077:     return "version:$VERSION";
1.127     albertel 9078: }
1.178     foxr     9079: 
1.447     raeburn  9080: sub get_usersession_config {
                   9081:     my ($dom,$name) = @_;
                   9082:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9083:     if (defined($cached)) {
                   9084:         return $usersessionconf;
                   9085:     } else {
                   9086:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  9087:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   9088:         return $domconfig{'usersessions'};
1.447     raeburn  9089:     }
                   9090:     return;
                   9091: }
1.200     matthew  9092: 
1.534     raeburn  9093: sub get_usersearch_config {
                   9094:     my ($dom,$name) = @_;
                   9095:     my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9096:     if (defined($cached)) {
                   9097:         return $usersearchconf;
                   9098:     } else {
                   9099:         my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
                   9100:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
                   9101:         return $domconfig{'directorysrch'};
                   9102:     }
                   9103:     return;
                   9104: }
                   9105: 
1.525     raeburn  9106: sub get_prohibited {
                   9107:     my ($dom) = @_;
                   9108:     my $name = 'trust';
                   9109:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   9110:     unless (defined($cached)) {
                   9111:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   9112:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   9113:         $trustconfig = $domconfig{'trust'};
                   9114:     }
                   9115:     my %prohibited;
                   9116:     if (ref($trustconfig)) {
                   9117:         foreach my $prefix (keys(%{$trustconfig})) {
                   9118:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   9119:                 my $reject;
                   9120:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   9121:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   9122:                         $reject = 1;
                   9123:                     }
                   9124:                 }
                   9125:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   9126:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   9127:                         $reject = 0;
                   9128:                     } else {
                   9129:                         $reject = 1;
                   9130:                     }
                   9131:                 }
                   9132:                 if ($reject) {
                   9133:                     $prohibited{$prefix} = 1;
                   9134:                 }
                   9135:             }
                   9136:         }
                   9137:     }
                   9138:     return %prohibited;
                   9139: }
1.450     raeburn  9140: 
1.556     raeburn  9141: sub get_remote_hostable {
                   9142:     my ($dom) = @_;
                   9143:     my $result;
                   9144:     if ($clientintdom) {
                   9145:         $result = 1;
                   9146:         my $remsessconf = &get_usersession_config($dom,'remotesession');
                   9147:         if (ref($remsessconf) eq 'HASH') {
                   9148:             if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   9149:                 if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   9150:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   9151:                         $result = 0;
                   9152:                     }
                   9153:                 }
                   9154:                 if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   9155:                     if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   9156:                         $result = 1;
                   9157:                     } else {
                   9158:                         $result = 0;
                   9159:                     }
                   9160:                 }
                   9161:             }
                   9162:         }
                   9163:     }
                   9164:     return $result;
                   9165: }
                   9166: 
1.471     raeburn  9167: sub distro_and_arch {
                   9168:     return $dist.':'.$arch;
                   9169: }
                   9170: 
1.61      harris41 9171: # ----------------------------------- POD (plain old documentation, CPAN style)
                   9172: 
                   9173: =head1 NAME
                   9174: 
                   9175: lond - "LON Daemon" Server (port "LOND" 5663)
                   9176: 
                   9177: =head1 SYNOPSIS
                   9178: 
1.74      harris41 9179: Usage: B<lond>
                   9180: 
                   9181: Should only be run as user=www.  This is a command-line script which
                   9182: is invoked by B<loncron>.  There is no expectation that a typical user
                   9183: will manually start B<lond> from the command-line.  (In other words,
                   9184: DO NOT START B<lond> YOURSELF.)
1.61      harris41 9185: 
                   9186: =head1 DESCRIPTION
                   9187: 
1.74      harris41 9188: There are two characteristics associated with the running of B<lond>,
                   9189: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   9190: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   9191: subscriptions, etc).  These are described in two large
                   9192: sections below.
                   9193: 
                   9194: B<PROCESS MANAGEMENT>
                   9195: 
1.61      harris41 9196: Preforker - server who forks first. Runs as a daemon. HUPs.
                   9197: Uses IDEA encryption
                   9198: 
1.74      harris41 9199: B<lond> forks off children processes that correspond to the other servers
                   9200: in the network.  Management of these processes can be done at the
                   9201: parent process level or the child process level.
                   9202: 
                   9203: B<logs/lond.log> is the location of log messages.
                   9204: 
                   9205: The process management is now explained in terms of linux shell commands,
                   9206: subroutines internal to this code, and signal assignments:
                   9207: 
                   9208: =over 4
                   9209: 
                   9210: =item *
                   9211: 
                   9212: PID is stored in B<logs/lond.pid>
                   9213: 
                   9214: This is the process id number of the parent B<lond> process.
                   9215: 
                   9216: =item *
                   9217: 
                   9218: SIGTERM and SIGINT
                   9219: 
                   9220: Parent signal assignment:
                   9221:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   9222: 
                   9223: Child signal assignment:
                   9224:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   9225: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   9226:  to restart a new child.)
                   9227: 
                   9228: Command-line invocations:
                   9229:  B<kill> B<-s> SIGTERM I<PID>
                   9230:  B<kill> B<-s> SIGINT I<PID>
                   9231: 
                   9232: Subroutine B<HUNTSMAN>:
                   9233:  This is only invoked for the B<lond> parent I<PID>.
                   9234: This kills all the children, and then the parent.
                   9235: The B<lonc.pid> file is cleared.
                   9236: 
                   9237: =item *
                   9238: 
                   9239: SIGHUP
                   9240: 
                   9241: Current bug:
                   9242:  This signal can only be processed the first time
                   9243: on the parent process.  Subsequent SIGHUP signals
                   9244: have no effect.
                   9245: 
                   9246: Parent signal assignment:
                   9247:  $SIG{HUP}  = \&HUPSMAN;
                   9248: 
                   9249: Child signal assignment:
                   9250:  none (nothing happens)
                   9251: 
                   9252: Command-line invocations:
                   9253:  B<kill> B<-s> SIGHUP I<PID>
                   9254: 
                   9255: Subroutine B<HUPSMAN>:
                   9256:  This is only invoked for the B<lond> parent I<PID>,
                   9257: This kills all the children, and then the parent.
                   9258: The B<lond.pid> file is cleared.
                   9259: 
                   9260: =item *
                   9261: 
                   9262: SIGUSR1
                   9263: 
                   9264: Parent signal assignment:
                   9265:  $SIG{USR1} = \&USRMAN;
                   9266: 
                   9267: Child signal assignment:
                   9268:  $SIG{USR1}= \&logstatus;
                   9269: 
                   9270: Command-line invocations:
                   9271:  B<kill> B<-s> SIGUSR1 I<PID>
                   9272: 
                   9273: Subroutine B<USRMAN>:
                   9274:  When invoked for the B<lond> parent I<PID>,
                   9275: SIGUSR1 is sent to all the children, and the status of
                   9276: each connection is logged.
1.144     foxr     9277: 
                   9278: =item *
                   9279: 
                   9280: SIGUSR2
                   9281: 
                   9282: Parent Signal assignment:
                   9283:     $SIG{USR2} = \&UpdateHosts
                   9284: 
                   9285: Child signal assignment:
                   9286:     NONE
                   9287: 
1.74      harris41 9288: 
                   9289: =item *
                   9290: 
                   9291: SIGCHLD
                   9292: 
                   9293: Parent signal assignment:
                   9294:  $SIG{CHLD} = \&REAPER;
                   9295: 
                   9296: Child signal assignment:
                   9297:  none
                   9298: 
                   9299: Command-line invocations:
                   9300:  B<kill> B<-s> SIGCHLD I<PID>
                   9301: 
                   9302: Subroutine B<REAPER>:
                   9303:  This is only invoked for the B<lond> parent I<PID>.
                   9304: Information pertaining to the child is removed.
                   9305: The socket port is cleaned up.
                   9306: 
                   9307: =back
                   9308: 
                   9309: B<SERVER-SIDE ACTIVITIES>
                   9310: 
                   9311: Server-side information can be accepted in an encrypted or non-encrypted
                   9312: method.
                   9313: 
                   9314: =over 4
                   9315: 
                   9316: =item ping
                   9317: 
                   9318: Query a client in the hosts.tab table; "Are you there?"
                   9319: 
                   9320: =item pong
                   9321: 
                   9322: Respond to a ping query.
                   9323: 
                   9324: =item ekey
                   9325: 
                   9326: Read in encrypted key, make cipher.  Respond with a buildkey.
                   9327: 
                   9328: =item load
                   9329: 
                   9330: Respond with CPU load based on a computation upon /proc/loadavg.
                   9331: 
                   9332: =item currentauth
                   9333: 
                   9334: Reply with current authentication information (only over an
                   9335: encrypted channel).
                   9336: 
                   9337: =item auth
                   9338: 
                   9339: Only over an encrypted channel, reply as to whether a user's
                   9340: authentication information can be validated.
                   9341: 
                   9342: =item passwd
                   9343: 
                   9344: Allow for a password to be set.
                   9345: 
                   9346: =item makeuser
                   9347: 
                   9348: Make a user.
                   9349: 
1.517     raeburn  9350: =item changeuserauth
1.74      harris41 9351: 
                   9352: Allow for authentication mechanism and password to be changed.
                   9353: 
                   9354: =item home
1.61      harris41 9355: 
1.74      harris41 9356: Respond to a question "are you the home for a given user?"
                   9357: 
                   9358: =item update
                   9359: 
                   9360: Update contents of a subscribed resource.
                   9361: 
                   9362: =item unsubscribe
                   9363: 
                   9364: The server is unsubscribing from a resource.
                   9365: 
                   9366: =item subscribe
                   9367: 
                   9368: The server is subscribing to a resource.
                   9369: 
                   9370: =item log
                   9371: 
                   9372: Place in B<logs/lond.log>
                   9373: 
                   9374: =item put
                   9375: 
                   9376: stores hash in namespace
                   9377: 
1.496     raeburn  9378: =item rolesput
1.74      harris41 9379: 
                   9380: put a role into a user's environment
                   9381: 
                   9382: =item get
                   9383: 
                   9384: returns hash with keys from array
                   9385: reference filled in from namespace
                   9386: 
                   9387: =item eget
                   9388: 
                   9389: returns hash with keys from array
                   9390: reference filled in from namesp (encrypts the return communication)
                   9391: 
                   9392: =item rolesget
                   9393: 
                   9394: get a role from a user's environment
                   9395: 
                   9396: =item del
                   9397: 
                   9398: deletes keys out of array from namespace
                   9399: 
                   9400: =item keys
                   9401: 
                   9402: returns namespace keys
                   9403: 
                   9404: =item dump
                   9405: 
                   9406: dumps the complete (or key matching regexp) namespace into a hash
                   9407: 
                   9408: =item store
                   9409: 
                   9410: stores hash permanently
                   9411: for this url; hashref needs to be given and should be a \%hashname; the
                   9412: remaining args aren't required and if they aren't passed or are '' they will
                   9413: be derived from the ENV
                   9414: 
                   9415: =item restore
                   9416: 
                   9417: returns a hash for a given url
                   9418: 
                   9419: =item querysend
                   9420: 
                   9421: Tells client about the lonsql process that has been launched in response
                   9422: to a sent query.
                   9423: 
                   9424: =item queryreply
                   9425: 
                   9426: Accept information from lonsql and make appropriate storage in temporary
                   9427: file space.
                   9428: 
                   9429: =item idput
                   9430: 
                   9431: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   9432: for each student, defined perhaps by the institutional Registrar.)
                   9433: 
                   9434: =item idget
                   9435: 
                   9436: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   9437: for each student, defined perhaps by the institutional Registrar.)
                   9438: 
1.517     raeburn  9439: =item iddel
                   9440: 
                   9441: Deletes one or more ids in a domain's id database.
                   9442: 
1.74      harris41 9443: =item tmpput
                   9444: 
                   9445: Accept and store information in temporary space.
                   9446: 
                   9447: =item tmpget
                   9448: 
                   9449: Send along temporarily stored information.
                   9450: 
                   9451: =item ls
                   9452: 
                   9453: List part of a user's directory.
                   9454: 
1.135     foxr     9455: =item pushtable
                   9456: 
                   9457: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   9458: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   9459: must be restored manually in case of a problem with the new table file.
                   9460: pushtable requires that the request be encrypted and validated via
                   9461: ValidateManager.  The form of the command is:
                   9462: enc:pushtable tablename <tablecontents> \n
                   9463: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   9464: cleartext newline.
                   9465: 
1.74      harris41 9466: =item Hanging up (exit or init)
                   9467: 
                   9468: What to do when a client tells the server that they (the client)
                   9469: are leaving the network.
                   9470: 
                   9471: =item unknown command
                   9472: 
                   9473: If B<lond> is sent an unknown command (not in the list above),
                   9474: it replys to the client "unknown_cmd".
1.135     foxr     9475: 
1.74      harris41 9476: 
                   9477: =item UNKNOWN CLIENT
                   9478: 
                   9479: If the anti-spoofing algorithm cannot verify the client,
                   9480: the client is rejected (with a "refused" message sent
                   9481: to the client, and the connection is closed.
                   9482: 
                   9483: =back
1.61      harris41 9484: 
                   9485: =head1 PREREQUISITES
                   9486: 
                   9487: IO::Socket
                   9488: IO::File
                   9489: Apache::File
                   9490: POSIX
                   9491: Crypt::IDEA
                   9492: GDBM_File
                   9493: Authen::Krb4
1.91      albertel 9494: Authen::Krb5
1.61      harris41 9495: 
                   9496: =head1 COREQUISITES
                   9497: 
1.490     droeschl 9498: none
                   9499: 
1.61      harris41 9500: =head1 OSNAMES
                   9501: 
                   9502: linux
                   9503: 
                   9504: =head1 SCRIPT CATEGORIES
                   9505: 
                   9506: Server/Process
                   9507: 
                   9508: =cut
1.409     foxr     9509: 
                   9510: 
                   9511: =pod
                   9512: 
                   9513: =head1 LOG MESSAGES
                   9514: 
                   9515: The messages below can be emitted in the lond log.  This log is located
                   9516: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   9517: to provide coloring if examined from inside a web page. Some do not.
                   9518: Where color is used, the colors are; Red for sometihhng to get excited
                   9519: about and to follow up on. Yellow for something to keep an eye on to
                   9520: be sure it does not get worse, Green,and Blue for informational items.
                   9521: 
                   9522: In the discussions below, sometimes reference is made to ~httpd
                   9523: when describing file locations.  There isn't really an httpd 
                   9524: user, however there is an httpd directory that gets installed in the
                   9525: place that user home directories go.  On linux, this is usually
                   9526: (always?) /home/httpd.
                   9527: 
                   9528: 
                   9529: Some messages are colorless.  These are usually (not always)
                   9530: Green/Blue color level messages.
                   9531: 
                   9532: =over 2
                   9533: 
                   9534: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   9535: 
                   9536: A local connection negotiation was attempted by
                   9537: a host whose IP address was not 127.0.0.1.
                   9538: The socket is closed and the child will exit.
                   9539: lond has three ways to establish an encyrption
                   9540: key with a client:
                   9541: 
                   9542: =over 2
                   9543: 
                   9544: =item local 
                   9545: 
                   9546: The key is written and read from a file.
                   9547: This is only valid for connections from localhost.
                   9548: 
                   9549: =item insecure 
                   9550: 
                   9551: The key is generated by the server and
                   9552: transmitted to the client.
                   9553: 
                   9554: =item  ssl (secure)
                   9555: 
                   9556: An ssl connection is negotiated with the client,
                   9557: the key is generated by the server and sent to the 
                   9558: client across this ssl connection before the
                   9559: ssl connectionis terminated and clear text
                   9560: transmission resumes.
                   9561: 
                   9562: =back
                   9563: 
                   9564: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   9565: 
                   9566: The client is local but has not sent an initialization
                   9567: string that is the literal "init:local"  The connection
                   9568: is closed and the child exits.
                   9569: 
                   9570: =item Red CRITICAL Can't get key file <error>        
                   9571: 
                   9572: SSL key negotiation is being attempted but the call to
1.549     raeburn  9573: lonssl::KeyFile failed.  This usually means that the
1.409     foxr     9574: configuration file is not correctly defining or protecting
                   9575: the directories/files lonCertificateDirectory or
                   9576: lonnetPrivateKey
                   9577: <error> is a string that describes the reason that
                   9578: the key file could not be located.
                   9579: 
                   9580: =item (Red) CRITICAL  Can't get certificates <error>  
                   9581: 
                   9582: SSL key negotiation failed because we were not able to retrives our certificate
                   9583: or the CA's certificate in the call to lonssl::CertificateFile
                   9584: <error> is the textual reason this failed.  Usual reasons:
                   9585: 
                   9586: =over 2
1.490     droeschl 9587: 
1.409     foxr     9588: =item Apache config file for loncapa  incorrect:
1.490     droeschl 9589: 
1.409     foxr     9590: one of the variables 
                   9591: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   9592: undefined or incorrect
                   9593: 
                   9594: =item Permission error:
                   9595: 
                   9596: The directory pointed to by lonCertificateDirectory is not readable by lond
                   9597: 
                   9598: =item Permission error:
                   9599: 
                   9600: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   9601: 
                   9602: =item Installation error:                         
                   9603: 
                   9604: Either the certificate authority file or the certificate have not
                   9605: been installed in lonCertificateDirectory.
                   9606: 
                   9607: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   9608: 
                   9609: The promotion of the connection from plaintext to SSL failed
                   9610: <err> is the reason for the failure.  There are two
                   9611: system calls involved in the promotion (one of which failed), 
                   9612: a dup to produce
                   9613: a second fd on the raw socket over which the encrypted data
                   9614: will flow and IO::SOcket::SSL->new_from_fd which creates
                   9615: the SSL connection on the duped fd.
                   9616: 
                   9617: =item (Blue)   WARNING client did not respond to challenge 
                   9618: 
                   9619: This occurs on an insecure (non SSL) connection negotiation request.
                   9620: lond generates some number from the time, the PID and sends it to
                   9621: the client.  The client must respond by echoing this information back.
                   9622: If the client does not do so, that's a violation of the challenge
                   9623: protocols and the connection will be failed.
                   9624: 
                   9625: =item (Red) No manager table. Nobody can manage!!    
                   9626: 
                   9627: lond has the concept of privileged hosts that
                   9628: can perform remote management function such
                   9629: as update the hosts.tab.   The manager hosts
                   9630: are described in the 
                   9631: ~httpd/lonTabs/managers.tab file.
                   9632: this message is logged if this file is missing.
                   9633: 
                   9634: 
                   9635: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   9636: 
                   9637: Reports the successful parse and registration
                   9638: of a specific manager. 
                   9639: 
                   9640: =item Green existing host <clustername:dnsname>  
                   9641: 
                   9642: The manager host is already defined in the hosts.tab
                   9643: the information in that table, rather than the info in the
                   9644: manager table will be used to determine the manager's ip.
                   9645: 
                   9646: =item (Red) Unable to craete <filename>                 
                   9647: 
                   9648: lond has been asked to create new versions of an administrative
                   9649: file (by a manager).  When this is done, the new file is created
                   9650: in a temp file and then renamed into place so that there are always
                   9651: usable administrative files, even if the update fails.  This failure
                   9652: message means that the temp file could not be created.
                   9653: The update is abandoned, and the old file is available for use.
                   9654: 
                   9655: =item (Green) CopyFile from <oldname> to <newname> failed
                   9656: 
                   9657: In an update of administrative files, the copy of the existing file to a
                   9658: backup file failed.  The installation of the new file may still succeed,
                   9659: but there will not be a back up file to rever to (this should probably
                   9660: be yellow).
                   9661: 
                   9662: =item (Green) Pushfile: backed up <oldname> to <newname>
                   9663: 
                   9664: See above, the backup of the old administrative file succeeded.
                   9665: 
                   9666: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   9667: 
                   9668: The new administrative file could not be installed.  In this case,
                   9669: the old administrative file is still in use.
                   9670: 
                   9671: =item (Green) Installed new < filename>.                      
                   9672: 
                   9673: The new administrative file was successfullly installed.                                               
                   9674: 
                   9675: =item (Red) Reinitializing lond pid=<pid>                    
                   9676: 
                   9677: The lonc child process <pid> will be sent a USR2 
                   9678: signal.
                   9679: 
                   9680: =item (Red) Reinitializing self                                    
                   9681: 
                   9682: We've been asked to re-read our administrative files,and
                   9683: are doing so.
                   9684: 
                   9685: =item (Yellow) error:Invalid process identifier <ident>  
                   9686: 
                   9687: A reinit command was received, but the target part of the 
                   9688: command was not valid.  It must be either
                   9689: 'lond' or 'lonc' but was <ident>
                   9690: 
                   9691: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   9692: 
                   9693: Checking to see if lond has been handed a valid edit
                   9694: command.  It is possible the edit command is not valid
                   9695: in that case there are no log messages to indicate that.
                   9696: 
                   9697: =item Result of password change for  <username> pwchange_success
                   9698: 
                   9699: The password for <username> was
                   9700: successfully changed.
                   9701: 
                   9702: =item Unable to open <user> passwd to change password
                   9703: 
                   9704: Could not rewrite the 
                   9705: internal password file for a user
                   9706: 
                   9707: =item Result of password change for <user> : <result>
1.490     droeschl 9708: 
1.409     foxr     9709: A unix password change for <user> was attempted 
                   9710: and the pipe returned <result>  
                   9711: 
                   9712: =item LWP GET: <message> for <fname> (<remoteurl>)
                   9713: 
                   9714: The lightweight process fetch for a resource failed
                   9715: with <message> the local filename that should
                   9716: have existed/been created was  <fname> the
                   9717: corresponding URI: <remoteurl>  This is emitted in several
                   9718: places.
                   9719: 
                   9720: =item Unable to move <transname> to <destname>     
                   9721: 
                   9722: From fetch_user_file_handler - the user file was replicated but could not
                   9723: be mv'd to its final location.
                   9724: 
                   9725: =item Looking for <domain> <username>              
                   9726: 
                   9727: From user_has_session_handler - This should be a Debug call instead
                   9728: it indicates lond is about to check whether the specified user has a 
                   9729: session active on the specified domain on the local host.
                   9730: 
                   9731: =item Client <ip> (<name>) hanging up: <input>     
                   9732: 
                   9733: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   9734: client systemand <input> is the full exit command sent to the server.
                   9735: 
                   9736: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 9737: 
1.409     foxr     9738: A lond child terminated.  NOte that this termination can also occur when the
                   9739: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   9740: <hostname> the host lond is working for, and <message> the reason the child died
                   9741: to the best of our ability to get it (I would guess that any numeric value
                   9742: represents and errno value).  This is immediately followed by
                   9743: 
                   9744: =item  Famous last words: Catching exception - <log> 
                   9745: 
                   9746: Where log is some recent information about the state of the child.
                   9747: 
                   9748: =item Red CRITICAL: TIME OUT <pid>                     
                   9749: 
                   9750: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   9751: doing an HTTP::GET.
                   9752: 
                   9753: =item child <pid> died                              
                   9754: 
                   9755: The reaper caught a SIGCHILD for the lond child process <pid>
                   9756: This should be modified to also display the IP of the dying child
                   9757: $children{$pid}
                   9758: 
                   9759: =item Unknown child 0 died                           
                   9760: A child died but the wait for it returned a pid of zero which really should not
                   9761: ever happen. 
                   9762: 
                   9763: =item Child <which> - <pid> looks like we missed it's death 
                   9764: 
                   9765: When a sigchild is received, the reaper process checks all children to see if they are
                   9766: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   9767: that a signal hearalds the death of more than one child.  If so this message indicates
                   9768: which other one died. <which> is the ip of a dead child
                   9769: 
                   9770: =item Free socket: <shutdownretval>                
                   9771: 
                   9772: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   9773: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   9774: to return anything. This is followed by: 
                   9775: 
                   9776: =item Red CRITICAL: Shutting down                       
                   9777: 
                   9778: Just prior to exit.
                   9779: 
                   9780: =item Free socket: <shutdownretval>                 
                   9781: 
                   9782: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   9783: This is followed by:
                   9784: 
                   9785: =item (Red) CRITICAL: Restarting                         
                   9786: 
                   9787: lond is about to exec itself to restart.
                   9788: 
                   9789: =item (Blue) Updating connections                        
                   9790: 
                   9791: (In response to a USR2).  All the children (except the one for localhost)
                   9792: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   9793: 
                   9794: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   9795: 
                   9796: Due to USR2 as above.
                   9797: 
                   9798: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   9799: 
                   9800: In response to USR2 as above, the child indicated is not being restarted because
                   9801: it's assumed that we'll always need a child for the localhost.
                   9802: 
                   9803: 
                   9804: =item Going to check on the children                
                   9805: 
                   9806: Parent is about to check on the health of the child processes.
                   9807: Note that this is in response to a USR1 sent to the parent lond.
                   9808: there may be one or more of the next two messages:
                   9809: 
                   9810: =item <pid> is dead                                 
                   9811: 
                   9812: A child that we have in our child hash as alive has evidently died.
                   9813: 
                   9814: =item  Child <pid> did not respond                   
                   9815: 
                   9816: In the health check the child <pid> did not update/produce a pid_.txt
                   9817: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   9818: assumed to be hung in some un-fixable way.
                   9819: 
                   9820: =item Finished checking children                   
1.490     droeschl 9821: 
1.409     foxr     9822: Master processs's USR1 processing is cojmplete.
                   9823: 
                   9824: =item (Red) CRITICAL: ------- Starting ------            
                   9825: 
                   9826: (There are more '-'s on either side).  Lond has forked itself off to 
                   9827: form a new session and is about to start actual initialization.
                   9828: 
                   9829: =item (Green) Attempting to start child (<client>)       
                   9830: 
                   9831: Started a new child process for <client>.  Client is IO::Socket object
                   9832: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   9833: 
                   9834: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 9835: 
1.409     foxr     9836: In child process initialization.  either getpeername returned undef or
                   9837: a zero sized object was returned.  Processing continues, but in my opinion,
                   9838: this should be cause for the child to exit.
                   9839: 
                   9840: =item Unable to determine clientip                  
                   9841: 
                   9842: In child process initialization.  The peer address from getpeername was not defined.
                   9843: The client address is stored as "Unavailable" and processing continues.
                   9844: 
                   9845: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 9846: 
1.409     foxr     9847: In child initialization.  A good connectionw as received from <ip>.
                   9848: 
                   9849: =over 2
                   9850: 
                   9851: =item <name> 
                   9852: 
                   9853: is the name of the client from hosts.tab.
                   9854: 
                   9855: =item <type> 
                   9856: 
                   9857: Is the connection type which is either 
                   9858: 
                   9859: =over 2
                   9860: 
                   9861: =item manager 
                   9862: 
                   9863: The connection is from a manager node, not in hosts.tab
                   9864: 
                   9865: =item client  
                   9866: 
                   9867: the connection is from a non-manager in the hosts.tab
                   9868: 
                   9869: =item both
                   9870: 
                   9871: The connection is from a manager in the hosts.tab.
                   9872: 
                   9873: =back
                   9874: 
                   9875: =back
                   9876: 
                   9877: =item (Blue) Certificates not installed -- trying insecure auth
                   9878: 
                   9879: One of the certificate file, key file or
                   9880: certificate authority file could not be found for a client attempting
                   9881: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   9882: (this would be a system with an up to date lond that has not gotten a 
                   9883: certificate from us).
                   9884: 
                   9885: =item (Green)  Successful local authentication            
                   9886: 
                   9887: A local connection successfully negotiated the encryption key. 
                   9888: In this case the IDEA key is in a file (that is hopefully well protected).
                   9889: 
                   9890: =item (Green) Successful ssl authentication with <client>  
                   9891: 
                   9892: The client (<client> is the peer's name in hosts.tab), has successfully
                   9893: negotiated an SSL connection with this child process.
                   9894: 
                   9895: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 9896: 
1.409     foxr     9897: 
                   9898: The client has successfully negotiated an  insecure connection withthe child process.
                   9899: 
                   9900: =item (Yellow) Attempted insecure connection disallowed    
                   9901: 
                   9902: The client attempted and failed to successfully negotiate a successful insecure
                   9903: connection.  This can happen either because the variable londAllowInsecure is false
                   9904: or undefined, or becuse the child did not successfully echo back the challenge
                   9905: string.
                   9906: 
                   9907: 
                   9908: =back
                   9909: 
1.441     raeburn  9910: =back
                   9911: 
1.409     foxr     9912: 
                   9913: =cut

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