Annotation of loncom/lond, revision 1.526

1.1       albertel    1: #!/usr/bin/perl
                      2: # The LearningOnline Network
                      3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60      www         4: #
1.526   ! raeburn     5: # $Id: lond,v 1.525 2016/09/12 20:20:44 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.1       albertel   38: use IO::Socket;
                     39: use IO::File;
1.126     albertel   40: #use Apache::File;
1.1       albertel   41: use POSIX;
                     42: use Crypt::IDEA;
1.523     raeburn    43: use HTTP::Request;
1.347     raeburn    44: use Digest::MD5 qw(md5_hex);
1.3       www        45: use GDBM_File;
1.91      albertel   46: use Authen::Krb5;
1.49      albertel   47: use localauth;
1.193     raeburn    48: use localenroll;
1.265     albertel   49: use localstudentphoto;
1.143     foxr       50: use File::Copy;
1.292     albertel   51: use File::Find;
1.200     matthew    52: use LONCAPA::lonlocal;
                     53: use LONCAPA::lonssl;
1.221     albertel   54: use Fcntl qw(:flock);
1.383     raeburn    55: use Apache::lonnet;
1.472     raeburn    56: use Mail::Send;
1.518     raeburn    57: use Crypt::Eksblowfish::Bcrypt;
                     58: use Digest::SHA;
                     59: use Encode;
1.523     raeburn    60: use LONCAPA::LWPReq;
1.1       albertel   61: 
1.463     foxr       62: my $DEBUG = 0;		       # Non zero to enable debug log entries.
1.77      foxr       63: 
1.57      www        64: my $status='';
                     65: my $lastlog='';
                     66: 
1.526   ! raeburn    67: my $VERSION='$Revision: 1.525 $'; #' stupid emacs
1.121     albertel   68: my $remoteVERSION;
1.214     foxr       69: my $currenthostid="default";
1.115     albertel   70: my $currentdomainid;
1.134     albertel   71: 
                     72: my $client;
1.200     matthew    73: my $clientip;			# IP address of client.
                     74: my $clientname;			# LonCAPA name of client.
1.448     raeburn    75: my $clientversion;              # LonCAPA version running on client.
                     76: my $clienthomedom;              # LonCAPA domain of homeID for client. 
1.525     raeburn    77: my $clientintdom;               # LonCAPA "internet domain" for client.
                     78: my $clientsameinst;             # LonCAPA "internet domain" same for 
                     79:                                 # this host and client.
                     80: my $clientremoteok;             # Client allowed to host domain's users.
                     81:                                 # (version constraints ignored), not set
                     82:                                 # if this host and client share "internet domain". 
                     83: my %clientprohibited;           # Actions prohibited on client;
                     84:  
1.134     albertel   85: my $server;
1.200     matthew    86: 
                     87: my $keymode;
1.198     foxr       88: 
1.207     foxr       89: my $cipher;			# Cipher key negotiated with client
                     90: my $tmpsnum = 0;		# Id of tmpputs.
                     91: 
1.178     foxr       92: # 
                     93: #   Connection type is:
                     94: #      client                   - All client actions are allowed
                     95: #      manager                  - only management functions allowed.
                     96: #      both                     - Both management and client actions are allowed
                     97: #
1.161     foxr       98: 
1.178     foxr       99: my $ConnectionType;
1.161     foxr      100: 
1.178     foxr      101: my %managers;			# Ip -> manager names
1.161     foxr      102: 
1.178     foxr      103: my %perlvar;			# Will have the apache conf defined perl vars.
1.134     albertel  104: 
1.480     raeburn   105: my $dist;
                    106: 
1.178     foxr      107: #
1.207     foxr      108: #   The hash below is used for command dispatching, and is therefore keyed on the request keyword.
                    109: #    Each element of the hash contains a reference to an array that contains:
                    110: #          A reference to a sub that executes the request corresponding to the keyword.
                    111: #          A flag that is true if the request must be encoded to be acceptable.
                    112: #          A mask with bits as follows:
                    113: #                      CLIENT_OK    - Set when the function is allowed by ordinary clients
                    114: #                      MANAGER_OK   - Set when the function is allowed to manager clients.
                    115: #
                    116: my $CLIENT_OK  = 1;
                    117: my $MANAGER_OK = 2;
                    118: my %Dispatcher;
                    119: 
                    120: 
                    121: #
1.178     foxr      122: #  The array below are password error strings."
                    123: #
                    124: my $lastpwderror    = 13;		# Largest error number from lcpasswd.
                    125: my @passwderrors = ("ok",
1.287     foxr      126: 		   "pwchange_failure - lcpasswd must be run as user 'www'",
                    127: 		   "pwchange_failure - lcpasswd got incorrect number of arguments",
                    128: 		   "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
                    129: 		   "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
                    130: 		   "pwchange_failure - lcpasswd User does not exist.",
                    131: 		   "pwchange_failure - lcpasswd Incorrect current passwd",
                    132: 		   "pwchange_failure - lcpasswd Unable to su to root.",
                    133: 		   "pwchange_failure - lcpasswd Cannot set new passwd.",
                    134: 		   "pwchange_failure - lcpasswd Username has invalid characters",
                    135: 		   "pwchange_failure - lcpasswd Invalid characters in password",
                    136: 		   "pwchange_failure - lcpasswd User already exists", 
                    137:                    "pwchange_failure - lcpasswd Something went wrong with user addition.",
                    138: 		   "pwchange_failure - lcpasswd Password mismatch",
                    139: 		   "pwchange_failure - lcpasswd Error filename is invalid");
1.97      foxr      140: 
                    141: 
1.412     foxr      142: # This array are the errors from lcinstallfile:
                    143: 
                    144: my @installerrors = ("ok",
                    145: 		     "Initial user id of client not that of www",
                    146: 		     "Usage error, not enough command line arguments",
1.500     bisitz    147: 		     "Source filename does not exist",
                    148: 		     "Destination filename does not exist",
1.412     foxr      149: 		     "Some file operation failed",
                    150: 		     "Invalid table filename."
                    151: 		     );
1.207     foxr      152: 
                    153: #
1.525     raeburn   154: # The %trust hash classifies commands according to type of trust 
                    155: # required for execution of the command.
                    156: #
                    157: # When clients from a different institution request execution of a
                    158: # particular command, the trust settings for that institution set
                    159: # for this domain (or default domain for a multi-domain server) will
                    160: # be checked to see if running the command is allowed.
                    161: #
                    162: # Trust types which depend on the "Trust" domain configuration
                    163: # for the machine's default domain are:
                    164: #
                    165: # content   ("Access to this domain's content by others")
                    166: # shared    ("Access to other domain's content by this domain")
                    167: # enroll    ("Enrollment in this domain's courses by others")
                    168: # coaurem   ("Co-author roles for this domain's users elsewhere")
                    169: # domroles  ("Domain roles in this domain assignable to others")
                    170: # catalog   ("Course Catalog for this domain displayed elsewhere")
                    171: # reqcrs    ("Requests for creation of courses in this domain by others")
                    172: # msg       ("Users in other domains can send messages to this domain")
                    173: # 
                    174: # Trust type which depends on the User Session Hosting (remote) 
                    175: # domain configuration for machine's default domain is: "remote".
                    176: #
                    177: # Trust types which depend on contents of manager.tab in 
                    178: # /home/httpd/lonTabs is: "manageronly".
                    179: # 
                    180: # Trust type which requires client to share the same LON-CAPA
                    181: # "internet domain" (i.e., same institution as this server) is:
                    182: # "institutiononly".
                    183: #
                    184: 
                    185: my %trust = (
                    186:                auth => {remote => 1},
                    187:                autocreatepassword => {remote => 1},
                    188:                autocrsreqchecks => {remote => 1, reqcrs => 1},
                    189:                autocrsrequpdate => {remote => 1},
                    190:                autocrsreqvalidation => {remote => 1},
                    191:                autogetsections => {remote => 1},
                    192:                autoinstcodedefaults => {remote => 1, catalog => 1},
                    193:                autoinstcodeformat => {remote => 1, catalog => 1},
                    194:                autonewcourse => {remote => 1, reqcrs => 1},
                    195:                autophotocheck => {remote => 1, enroll => 1},
                    196:                autophotochoice => {remote => 1},
                    197:                autophotopermission => {remote => 1, enroll => 1},
                    198:                autopossibleinstcodes => {remote => 1, reqcrs => 1},
                    199:                autoretrieve => {remote => 1, enroll => 1, catalog => 1},
                    200:                autorun => {remote => 1, enroll => 1, reqcrs => 1},
                    201:                autovalidateclass_sec => {catalog => 1},
                    202:                autovalidatecourse => {remote => 1, enroll => 1},
                    203:                autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
                    204:                changeuserauth => {remote => 1, domroles => 1},
                    205:                chatretr => {remote => 1, enroll => 1},
                    206:                chatsend => {remote => 1, enroll => 1},
                    207:                courseiddump => {remote => 1, domroles => 1, enroll => 1},
                    208:                courseidput => {remote => 1, domroles => 1, enroll => 1},
                    209:                courseidputhash => {remote => 1, domroles => 1, enroll => 1},
                    210:                courselastaccess => {remote => 1, domroles => 1, enroll => 1},
                    211:                currentauth => {remote => 1, domroles => 1, enroll => 1},
                    212:                currentdump => {remote => 1, enroll => 1},
                    213:                currentversion => {remote=> 1, content => 1},
                    214:                dcmaildump => {remote => 1, domroles => 1},
                    215:                dcmailput => {remote => 1, domroles => 1},
                    216:                del => {remote => 1, domroles => 1, enroll => 1, content => 1},
                    217:                deldom => {remote => 1, domroles => 1}, # not currently used
                    218:                devalidatecache => {institutiononly => 1},
                    219:                domroleput => {remote => 1, enroll => 1},
                    220:                domrolesdump => {remote => 1, catalog => 1},
                    221:                du => {remote => 1, enroll => 1},
                    222:                du2 => {remote => 1, enroll => 1},
                    223:                dump => {remote => 1, enroll => 1, domroles => 1},
                    224:                edit => {institutiononly => 1},  #not used currently
                    225:                eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
                    226:                ekey => {}, #not used currently
                    227:                exit => {anywhere => 1},
                    228:                fetchuserfile => {remote => 1, enroll => 1},
                    229:                get => {remote => 1, domroles => 1, enroll => 1},
                    230:                getdom => {anywhere => 1},
                    231:                home => {anywhere => 1},
                    232:                iddel => {remote => 1, enroll => 1},
                    233:                idget => {remote => 1, enroll => 1},
                    234:                idput => {remote => 1, domroles => 1, enroll => 1},
                    235:                inc => {remote => 1, enroll => 1},
                    236:                init => {anywhere => 1},
                    237:                inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
                    238:                instemailrules => {remote => 1, domroles => 1},
                    239:                instidrulecheck => {remote => 1, domroles => 1,},
                    240:                instidrules => {remote => 1, domroles => 1,},
                    241:                instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    242:                instselfcreatecheck => {institutiononly => 1},
                    243:                instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
                    244:                keys => {remote => 1,},
                    245:                load => {anywhere => 1},
                    246:                log => {anywhere => 1},
                    247:                ls => {remote => 1, enroll => 1, content => 1,},
                    248:                ls2 => {remote => 1, enroll => 1, content => 1,},
                    249:                ls3 => {remote => 1, enroll => 1, content => 1,},
                    250:                makeuser => {remote => 1, enroll => 1, domroles => 1,},
                    251:                mkdiruserfile => {remote => 1, enroll => 1,},
                    252:                newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
                    253:                passwd => {remote => 1},
                    254:                ping => {anywhere => 1},
                    255:                pong => {anywhere => 1},
                    256:                pushfile => {manageronly => 1},
                    257:                put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
                    258:                putdom => {remote => 1, domroles => 1,},
                    259:                putstore => {remote => 1, enroll => 1},
                    260:                queryreply => {anywhere => 1},
                    261:                querysend => {anywhere => 1},
                    262:                quit => {anywhere => 1},
                    263:                readlonnetglobal => {institutiononly => 1},
                    264:                reinit => {manageronly => 1}, #not used currently
                    265:                removeuserfile => {remote => 1, enroll => 1},
                    266:                renameuserfile => {remote => 1,},
                    267:                restore => {remote => 1, enroll => 1, reqcrs => 1,},
                    268:                rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    269:                rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
                    270:                serverdistarch => {manageronly => 1},
                    271:                serverhomeID => {anywhere => 1},
                    272:                serverloncaparev => {anywhere => 1},
                    273:                servertimezone => {remote => 1, enroll => 1},
                    274:                setannounce => {remote => 1, domroles => 1},
                    275:                sethost => {anywhere => 1},
                    276:                store => {remote => 1, enroll => 1, reqcrs => 1,},
                    277:                studentphoto => {remote => 1, enroll => 1},
                    278:                sub => {content => 1,},
                    279:                tmpdel => {anywhere => 1},
                    280:                tmpget => {anywhere => 1},
                    281:                tmpput => {anywhere => 1},
                    282:                tokenauthuserfile => {anywhere => 1},
                    283:                unsub => {content => 1,},
                    284:                update => {shared => 1},
                    285:                updateclickers => {remote => 1},
                    286:                userhassession => {anywhere => 1},
                    287:                userload => {anywhere => 1},
                    288:                version => {anywhere => 1}, #not used
                    289:             );
                    290: 
                    291: #
1.207     foxr      292: #   Statistics that are maintained and dislayed in the status line.
                    293: #
1.212     foxr      294: my $Transactions = 0;		# Number of attempted transactions.
                    295: my $Failures     = 0;		# Number of transcations failed.
1.207     foxr      296: 
                    297: #   ResetStatistics: 
                    298: #      Resets the statistics counters:
                    299: #
                    300: sub ResetStatistics {
                    301:     $Transactions = 0;
                    302:     $Failures     = 0;
                    303: }
                    304: 
1.200     matthew   305: #------------------------------------------------------------------------
                    306: #
                    307: #   LocalConnection
                    308: #     Completes the formation of a locally authenticated connection.
                    309: #     This function will ensure that the 'remote' client is really the
                    310: #     local host.  If not, the connection is closed, and the function fails.
                    311: #     If so, initcmd is parsed for the name of a file containing the
                    312: #     IDEA session key.  The fie is opened, read, deleted and the session
                    313: #     key returned to the caller.
                    314: #
                    315: # Parameters:
                    316: #   $Socket      - Socket open on client.
                    317: #   $initcmd     - The full text of the init command.
                    318: #
                    319: # Returns:
                    320: #     IDEA session key on success.
                    321: #     undef on failure.
                    322: #
                    323: sub LocalConnection {
                    324:     my ($Socket, $initcmd) = @_;
1.373     albertel  325:     Debug("Attempting local connection: $initcmd client: $clientip");
1.277     albertel  326:     if($clientip ne "127.0.0.1") {
1.200     matthew   327: 	&logthis('<font color="red"> LocalConnection rejecting non local: '
1.373     albertel  328: 		 ."$clientip ne 127.0.0.1 </font>");
1.200     matthew   329: 	close $Socket;
                    330: 	return undef;
1.224     foxr      331:     }  else {
1.200     matthew   332: 	chomp($initcmd);	# Get rid of \n in filename.
                    333: 	my ($init, $type, $name) = split(/:/, $initcmd);
                    334: 	Debug(" Init command: $init $type $name ");
                    335: 
                    336: 	# Require that $init = init, and $type = local:  Otherwise
                    337: 	# the caller is insane:
                    338: 
                    339: 	if(($init ne "init") && ($type ne "local")) {
                    340: 	    &logthis('<font color = "red"> LocalConnection: caller is insane! '
                    341: 		     ."init = $init, and type = $type </font>");
                    342: 	    close($Socket);;
                    343: 	    return undef;
                    344: 		
                    345: 	}
                    346: 	#  Now get the key filename:
                    347: 
                    348: 	my $IDEAKey = lonlocal::ReadKeyFile($name);
                    349: 	return $IDEAKey;
                    350:     }
                    351: }
                    352: #------------------------------------------------------------------------------
                    353: #
                    354: #  SSLConnection
                    355: #   Completes the formation of an ssh authenticated connection. The
                    356: #   socket is promoted to an ssl socket.  If this promotion and the associated
                    357: #   certificate exchange are successful, the IDEA key is generated and sent
                    358: #   to the remote peer via the SSL tunnel. The IDEA key is also returned to
                    359: #   the caller after the SSL tunnel is torn down.
                    360: #
                    361: # Parameters:
                    362: #   Name              Type             Purpose
                    363: #   $Socket          IO::Socket::INET  Plaintext socket.
                    364: #
                    365: # Returns:
                    366: #    IDEA key on success.
                    367: #    undef on failure.
                    368: #
                    369: sub SSLConnection {
                    370:     my $Socket   = shift;
                    371: 
                    372:     Debug("SSLConnection: ");
                    373:     my $KeyFile         = lonssl::KeyFile();
                    374:     if(!$KeyFile) {
                    375: 	my $err = lonssl::LastError();
                    376: 	&logthis("<font color=\"red\"> CRITICAL"
                    377: 		 ."Can't get key file $err </font>");
                    378: 	return undef;
                    379:     }
                    380:     my ($CACertificate,
                    381: 	$Certificate) = lonssl::CertificateFile();
                    382: 
                    383: 
                    384:     # If any of the key, certificate or certificate authority 
                    385:     # certificate filenames are not defined, this can't work.
                    386: 
                    387:     if((!$Certificate) || (!$CACertificate)) {
                    388: 	my $err = lonssl::LastError();
                    389: 	&logthis("<font color=\"red\"> CRITICAL"
                    390: 		 ."Can't get certificates: $err </font>");
                    391: 
                    392: 	return undef;
                    393:     }
                    394:     Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
                    395: 
                    396:     # Indicate to our peer that we can procede with
                    397:     # a transition to ssl authentication:
                    398: 
                    399:     print $Socket "ok:ssl\n";
                    400: 
                    401:     Debug("Approving promotion -> ssl");
                    402:     #  And do so:
                    403: 
                    404:     my $SSLSocket = lonssl::PromoteServerSocket($Socket,
                    405: 						$CACertificate,
                    406: 						$Certificate,
                    407: 						$KeyFile);
                    408:     if(! ($SSLSocket) ) {	# SSL socket promotion failed.
                    409: 	my $err = lonssl::LastError();
                    410: 	&logthis("<font color=\"red\"> CRITICAL "
                    411: 		 ."SSL Socket promotion failed: $err </font>");
                    412: 	return undef;
                    413:     }
                    414:     Debug("SSL Promotion successful");
                    415: 
                    416:     # 
                    417:     #  The only thing we'll use the socket for is to send the IDEA key
                    418:     #  to the peer:
                    419: 
                    420:     my $Key = lonlocal::CreateCipherKey();
                    421:     print $SSLSocket "$Key\n";
                    422: 
                    423:     lonssl::Close($SSLSocket); 
                    424: 
                    425:     Debug("Key exchange complete: $Key");
                    426: 
                    427:     return $Key;
                    428: }
                    429: #
                    430: #     InsecureConnection: 
                    431: #        If insecure connections are allowd,
                    432: #        exchange a challenge with the client to 'validate' the
                    433: #        client (not really, but that's the protocol):
                    434: #        We produce a challenge string that's sent to the client.
                    435: #        The client must then echo the challenge verbatim to us.
                    436: #
                    437: #  Parameter:
                    438: #      Socket      - Socket open on the client.
                    439: #  Returns:
                    440: #      1           - success.
                    441: #      0           - failure (e.g.mismatch or insecure not allowed).
                    442: #
                    443: sub InsecureConnection {
                    444:     my $Socket  =  shift;
                    445: 
                    446:     #   Don't even start if insecure connections are not allowed.
                    447: 
                    448:     if(! $perlvar{londAllowInsecure}) {	# Insecure connections not allowed.
                    449: 	return 0;
                    450:     }
                    451: 
                    452:     #   Fabricate a challenge string and send it..
                    453: 
                    454:     my $challenge = "$$".time;	# pid + time.
                    455:     print $Socket "$challenge\n";
                    456:     &status("Waiting for challenge reply");
                    457: 
                    458:     my $answer = <$Socket>;
                    459:     $answer    =~s/\W//g;
                    460:     if($challenge eq $answer) {
                    461: 	return 1;
1.224     foxr      462:     } else {
1.200     matthew   463: 	logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
                    464: 	&status("No challenge reqply");
                    465: 	return 0;
                    466:     }
                    467:     
                    468: 
                    469: }
1.251     foxr      470: #
                    471: #   Safely execute a command (as long as it's not a shel command and doesn
                    472: #   not require/rely on shell escapes.   The function operates by doing a
                    473: #   a pipe based fork and capturing stdout and stderr  from the pipe.
                    474: #
                    475: # Formal Parameters:
                    476: #     $line                    - A line of text to be executed as a command.
                    477: # Returns:
                    478: #     The output from that command.  If the output is multiline the caller
                    479: #     must know how to split up the output.
                    480: #
                    481: #
                    482: sub execute_command {
                    483:     my ($line)    = @_;
                    484:     my @words     = split(/\s/, $line);	# Bust the command up into words.
                    485:     my $output    = "";
                    486: 
                    487:     my $pid = open(CHILD, "-|");
                    488:     
                    489:     if($pid) {			# Parent process
                    490: 	Debug("In parent process for execute_command");
                    491: 	my @data = <CHILD>;	# Read the child's outupt...
                    492: 	close CHILD;
                    493: 	foreach my $output_line (@data) {
                    494: 	    Debug("Adding $output_line");
                    495: 	    $output .= $output_line; # Presumably has a \n on it.
                    496: 	}
                    497: 
                    498:     } else {			# Child process
                    499: 	close (STDERR);
                    500: 	open  (STDERR, ">&STDOUT");# Combine stderr, and stdout...
                    501: 	exec(@words);		# won't return.
                    502:     }
                    503:     return $output;
                    504: }
                    505: 
1.200     matthew   506: 
1.140     foxr      507: #   GetCertificate: Given a transaction that requires a certificate,
                    508: #   this function will extract the certificate from the transaction
                    509: #   request.  Note that at this point, the only concept of a certificate
                    510: #   is the hostname to which we are connected.
                    511: #
                    512: #   Parameter:
                    513: #      request   - The request sent by our client (this parameterization may
                    514: #                  need to change when we really use a certificate granting
                    515: #                  authority.
                    516: #
                    517: sub GetCertificate {
                    518:     my $request = shift;
                    519: 
                    520:     return $clientip;
                    521: }
1.161     foxr      522: 
1.178     foxr      523: #
                    524: #   Return true if client is a manager.
                    525: #
                    526: sub isManager {
                    527:     return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
                    528: }
                    529: #
                    530: #   Return tru if client can do client functions
                    531: #
                    532: sub isClient {
                    533:     return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
                    534: }
1.161     foxr      535: 
                    536: 
1.156     foxr      537: #
                    538: #   ReadManagerTable: Reads in the current manager table. For now this is
                    539: #                     done on each manager authentication because:
                    540: #                     - These authentications are not frequent
                    541: #                     - This allows dynamic changes to the manager table
                    542: #                       without the need to signal to the lond.
                    543: #
                    544: sub ReadManagerTable {
                    545: 
1.412     foxr      546:     &Debug("Reading manager table");
1.156     foxr      547:     #   Clean out the old table first..
                    548: 
1.166     foxr      549:    foreach my $key (keys %managers) {
                    550:       delete $managers{$key};
                    551:    }
                    552: 
                    553:    my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
                    554:    if (!open (MANAGERS, $tablename)) {
1.473     raeburn   555:        my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
                    556:        if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472     raeburn   557:            &logthis('<font color="red">No manager table.  Nobody can manage!!</font>');
                    558:        }
                    559:        return;
1.166     foxr      560:    }
                    561:    while(my $host = <MANAGERS>) {
                    562:       chomp($host);
                    563:       if ($host =~ "^#") {                  # Comment line.
                    564:          next;
                    565:       }
1.368     albertel  566:       if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161     foxr      567: 	    #  The entry is of the form:
                    568: 	    #    cluname:hostname
                    569: 	    #  cluname - A 'cluster hostname' is needed in order to negotiate
                    570: 	    #            the host key.
                    571: 	    #  hostname- The dns name of the host.
                    572: 	    #
1.166     foxr      573:           my($cluname, $dnsname) = split(/:/, $host);
                    574:           
                    575:           my $ip = gethostbyname($dnsname);
                    576:           if(defined($ip)) {                 # bad names don't deserve entry.
                    577:             my $hostip = inet_ntoa($ip);
                    578:             $managers{$hostip} = $cluname;
                    579:             logthis('<font color="green"> registering manager '.
                    580:                     "$dnsname as $cluname with $hostip </font>\n");
                    581:          }
                    582:       } else {
                    583:          logthis('<font color="green"> existing host'." $host</font>\n");
1.472     raeburn   584:          $managers{&Apache::lonnet::get_host_ip($host)} = $host;  # Use info from cluster tab if cluster memeber
1.166     foxr      585:       }
                    586:    }
1.156     foxr      587: }
1.140     foxr      588: 
                    589: #
                    590: #  ValidManager: Determines if a given certificate represents a valid manager.
                    591: #                in this primitive implementation, the 'certificate' is
                    592: #                just the connecting loncapa client name.  This is checked
                    593: #                against a valid client list in the configuration.
                    594: #
                    595: #                  
                    596: sub ValidManager {
                    597:     my $certificate = shift; 
                    598: 
1.163     foxr      599:     return isManager;
1.140     foxr      600: }
                    601: #
1.143     foxr      602: #  CopyFile:  Called as part of the process of installing a 
                    603: #             new configuration file.  This function copies an existing
                    604: #             file to a backup file.
                    605: # Parameters:
                    606: #     oldfile  - Name of the file to backup.
                    607: #     newfile  - Name of the backup file.
                    608: # Return:
                    609: #     0   - Failure (errno has failure reason).
                    610: #     1   - Success.
                    611: #
                    612: sub CopyFile {
1.192     foxr      613: 
                    614:     my ($oldfile, $newfile) = @_;
1.143     foxr      615: 
1.281     matthew   616:     if (! copy($oldfile,$newfile)) {
                    617:         return 0;
1.143     foxr      618:     }
1.281     matthew   619:     chmod(0660, $newfile);
                    620:     return 1;
1.143     foxr      621: }
1.157     foxr      622: #
                    623: #  Host files are passed out with externally visible host IPs.
                    624: #  If, for example, we are behind a fire-wall or NAT host, our 
                    625: #  internally visible IP may be different than the externally
                    626: #  visible IP.  Therefore, we always adjust the contents of the
                    627: #  host file so that the entry for ME is the IP that we believe
                    628: #  we have.  At present, this is defined as the entry that
                    629: #  DNS has for us.  If by some chance we are not able to get a
                    630: #  DNS translation for us, then we assume that the host.tab file
                    631: #  is correct.  
                    632: #    BUGBUGBUG - in the future, we really should see if we can
                    633: #       easily query the interface(s) instead.
                    634: # Parameter(s):
                    635: #     contents    - The contents of the host.tab to check.
                    636: # Returns:
                    637: #     newcontents - The adjusted contents.
                    638: #
                    639: #
                    640: sub AdjustHostContents {
                    641:     my $contents  = shift;
                    642:     my $adjusted;
                    643:     my $me        = $perlvar{'lonHostID'};
                    644: 
1.354     albertel  645:     foreach my $line (split(/\n/,$contents)) {
1.472     raeburn   646: 	if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
                    647:              ($line =~ /^\s*\^/))) {
1.157     foxr      648: 	    chomp($line);
                    649: 	    my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
                    650: 	    if ($id eq $me) {
1.354     albertel  651: 		my $ip = gethostbyname($name);
                    652: 		my $ipnew = inet_ntoa($ip);
                    653: 		$ip = $ipnew;
1.157     foxr      654: 		#  Reconstruct the host line and append to adjusted:
                    655: 		
1.354     albertel  656: 		my $newline = "$id:$domain:$role:$name:$ip";
                    657: 		if($maxcon ne "") { # Not all hosts have loncnew tuning params
                    658: 		    $newline .= ":$maxcon:$idleto:$mincon";
                    659: 		}
                    660: 		$adjusted .= $newline."\n";
1.157     foxr      661: 		
1.354     albertel  662: 	    } else {		# Not me, pass unmodified.
                    663: 		$adjusted .= $line."\n";
                    664: 	    }
1.157     foxr      665: 	} else {                  # Blank or comment never re-written.
                    666: 	    $adjusted .= $line."\n";	# Pass blanks and comments as is.
                    667: 	}
1.354     albertel  668:     }
                    669:     return $adjusted;
1.157     foxr      670: }
1.143     foxr      671: #
                    672: #   InstallFile: Called to install an administrative file:
1.412     foxr      673: #       - The file is created int a temp directory called <name>.tmp
                    674: #       - lcinstall file is called to install the file.
                    675: #         since the web app has no direct write access to the table directory
1.143     foxr      676: #
                    677: #  Parameters:
                    678: #       Name of the file
                    679: #       File Contents.
                    680: #  Return:
                    681: #      nonzero - success.
                    682: #      0       - failure and $! has an errno.
1.412     foxr      683: # Assumptions:
                    684: #    File installtion is a relatively infrequent
1.143     foxr      685: #
                    686: sub InstallFile {
1.192     foxr      687: 
                    688:     my ($Filename, $Contents) = @_;
1.412     foxr      689: #     my $TempFile = $Filename.".tmp";
                    690:     my $exedir = $perlvar{'lonDaemons'};
                    691:     my $tmpdir = $exedir.'/tmp/';
                    692:     my $TempFile = $tmpdir."TempTableFile.tmp";
1.143     foxr      693: 
                    694:     #  Open the file for write:
                    695: 
                    696:     my $fh = IO::File->new("> $TempFile"); # Write to temp.
                    697:     if(!(defined $fh)) {
                    698: 	&logthis('<font color="red"> Unable to create '.$TempFile."</font>");
                    699: 	return 0;
                    700:     }
                    701:     #  write the contents of the file:
                    702: 
                    703:     print $fh ($Contents); 
                    704:     $fh->close;			# In case we ever have a filesystem w. locking
                    705: 
1.412     foxr      706:     chmod(0664, $TempFile);	# Everyone can write it.
                    707: 
                    708:     # Use lcinstall file to put the file in the table directory...
                    709: 
                    710:     &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
                    711:     my $pf = IO::File->new("| $exedir/lcinstallfile   $TempFile $Filename > $exedir/logs/lcinstallfile.log");
                    712:     close $pf;
                    713:     my $err = $?;
                    714:     &Debug("Status is $err");
                    715:     if ($err != 0) {
                    716: 	my $msg = $err;
                    717: 	if ($err < @installerrors) {
                    718: 	    $msg = $installerrors[$err];
                    719: 	}
                    720: 	&logthis("Install failed for table file $Filename : $msg");
                    721: 	return 0;
                    722:     }
                    723: 
                    724:     # Remove the temp file:
1.143     foxr      725: 
1.412     foxr      726:     unlink($TempFile);
1.143     foxr      727: 
                    728:     return 1;
                    729: }
1.200     matthew   730: 
                    731: 
1.169     foxr      732: #
                    733: #   ConfigFileFromSelector: converts a configuration file selector
1.411     foxr      734: #                 into a configuration file pathname.
1.472     raeburn   735: #                 Supports the following file selectors: 
                    736: #                 hosts, domain, dns_hosts, dns_domain  
1.411     foxr      737: #
1.169     foxr      738: #
                    739: #  Parameters:
                    740: #      selector  - Configuration file selector.
                    741: #  Returns:
                    742: #      Full path to the file or undef if the selector is invalid.
                    743: #
                    744: sub ConfigFileFromSelector {
                    745:     my $selector   = shift;
                    746:     my $tablefile;
                    747: 
                    748:     my $tabledir = $perlvar{'lonTabDir'}.'/';
1.472     raeburn   749:     if (($selector eq "hosts") || ($selector eq "domain") || 
                    750:         ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
1.411     foxr      751: 	$tablefile =  $tabledir.$selector.'.tab';
1.169     foxr      752:     }
                    753:     return $tablefile;
                    754: }
1.143     foxr      755: #
1.141     foxr      756: #   PushFile:  Called to do an administrative push of a file.
                    757: #              - Ensure the file being pushed is one we support.
                    758: #              - Backup the old file to <filename.saved>
                    759: #              - Separate the contents of the new file out from the
                    760: #                rest of the request.
                    761: #              - Write the new file.
                    762: #  Parameter:
                    763: #     Request - The entire user request.  This consists of a : separated
                    764: #               string pushfile:tablename:contents.
                    765: #     NOTE:  The contents may have :'s in it as well making things a bit
                    766: #            more interesting... but not much.
                    767: #  Returns:
                    768: #     String to send to client ("ok" or "refused" if bad file).
                    769: #
                    770: sub PushFile {
1.510     raeburn   771:     my $request = shift;
1.141     foxr      772:     my ($command, $filename, $contents) = split(":", $request, 3);
1.412     foxr      773:     &Debug("PushFile");
1.141     foxr      774:     
                    775:     #  At this point in time, pushes for only the following tables are
                    776:     #  supported:
                    777:     #   hosts.tab  ($filename eq host).
                    778:     #   domain.tab ($filename eq domain).
1.472     raeburn   779:     #   dns_hosts.tab ($filename eq dns_host).
                    780:     #   dns_domain.tab ($filename eq dns_domain). 
1.141     foxr      781:     # Construct the destination filename or reject the request.
                    782:     #
                    783:     # lonManage is supposed to ensure this, however this session could be
                    784:     # part of some elaborate spoof that managed somehow to authenticate.
                    785:     #
                    786: 
1.169     foxr      787: 
                    788:     my $tablefile = ConfigFileFromSelector($filename);
                    789:     if(! (defined $tablefile)) {
1.141     foxr      790: 	return "refused";
                    791:     }
1.412     foxr      792: 
1.157     foxr      793:     #  If the file being pushed is the host file, we adjust the entry for ourself so that the
                    794:     #  IP will be our current IP as looked up in dns.  Note this is only 99% good as it's possible
                    795:     #  to conceive of conditions where we don't have a DNS entry locally.  This is possible in a 
                    796:     #  network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
                    797:     #  that possibilty.
                    798: 
                    799:     if($filename eq "host") {
                    800: 	$contents = AdjustHostContents($contents);
1.510     raeburn   801:     } elsif ($filename eq 'dns_host' || $filename eq 'dns_domain') {
                    802:         if ($contents eq '') {
                    803:             &logthis('<font color="red"> Pushfile: unable to install '
                    804:                     .$tablefile." - no data received from push. </font>");
                    805:             return 'error: push had no data';
                    806:         }
                    807:         if (&Apache::lonnet::get_host_ip($clientname)) {
                    808:             my $clienthost = &Apache::lonnet::hostname($clientname);
                    809:             if ($managers{$clientip} eq $clientname) {
                    810:                 my $clientprotocol = $Apache::lonnet::protocol{$clientname};
                    811:                 $clientprotocol = 'http' if ($clientprotocol ne 'https');
                    812:                 my $url = '/adm/'.$filename;
                    813:                 $url =~ s{_}{/};
                    814:                 my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523     raeburn   815:                 my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510     raeburn   816:                 if ($response->is_error()) {
                    817:                     &logthis('<font color="red"> Pushfile: unable to install '
                    818:                             .$tablefile." - error attempting to pull data. </font>");
                    819:                     return 'error: pull failed';
                    820:                 } else {
                    821:                     my $result = $response->content;
                    822:                     chomp($result);
                    823:                     unless ($result eq $contents) {
                    824:                         &logthis('<font color="red"> Pushfile: unable to install '
                    825:                                 .$tablefile." - pushed data and pulled data differ. </font>");
                    826:                         my $pushleng = length($contents);
                    827:                         my $pullleng = length($result);
                    828:                         if ($pushleng != $pullleng) {
                    829:                             return "error: $pushleng vs $pullleng bytes";
                    830:                         } else {
                    831:                             return "error: mismatch push and pull";
                    832:                         }
                    833:                     }
                    834:                 }
                    835:             }
                    836:         }
1.157     foxr      837:     }
                    838: 
1.141     foxr      839:     #  Install the new file:
                    840: 
1.412     foxr      841:     &logthis("Installing new $tablefile contents:\n$contents");
1.143     foxr      842:     if(!InstallFile($tablefile, $contents)) {
                    843: 	&logthis('<font color="red"> Pushfile: unable to install '
1.145     foxr      844: 	 .$tablefile." $! </font>");
1.143     foxr      845: 	return "error:$!";
1.224     foxr      846:     } else {
1.143     foxr      847: 	&logthis('<font color="green"> Installed new '.$tablefile
1.473     raeburn   848: 		 ." - transaction by: $clientname ($clientip)</font>");
1.472     raeburn   849:         my $adminmail = $perlvar{'lonAdmEMail'};
                    850:         my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                    851:         if ($admindom ne '') {
                    852:             my %domconfig =
                    853:                 &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
                    854:             if (ref($domconfig{'contacts'}) eq 'HASH') {
                    855:                 if ($domconfig{'contacts'}{'adminemail'} ne '') {
                    856:                     $adminmail = $domconfig{'contacts'}{'adminemail'};
                    857:                 }
                    858:             }
                    859:         }
                    860:         if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
                    861:             my $msg = new Mail::Send;
                    862:             $msg->to($adminmail);
                    863:             $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
                    864:             $msg->add('Content-type','text/plain; charset=UTF-8');
                    865:             if (my $fh = $msg->open()) {
                    866:                 print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473     raeburn   867:                           "$clientname ($clientip)\n";
1.472     raeburn   868:                 $fh->close;
                    869:             }
                    870:         }
1.143     foxr      871:     }
                    872: 
1.141     foxr      873:     #  Indicate success:
                    874:  
                    875:     return "ok";
                    876: 
                    877: }
1.145     foxr      878: 
                    879: #
                    880: #  Called to re-init either lonc or lond.
                    881: #
                    882: #  Parameters:
                    883: #    request   - The full request by the client.  This is of the form
                    884: #                reinit:<process>  
                    885: #                where <process> is allowed to be either of 
                    886: #                lonc or lond
                    887: #
                    888: #  Returns:
                    889: #     The string to be sent back to the client either:
                    890: #   ok         - Everything worked just fine.
                    891: #   error:why  - There was a failure and why describes the reason.
                    892: #
                    893: #
                    894: sub ReinitProcess {
                    895:     my $request = shift;
                    896: 
1.146     foxr      897: 
                    898:     # separate the request (reinit) from the process identifier and
                    899:     # validate it producing the name of the .pid file for the process.
                    900:     #
                    901:     #
                    902:     my ($junk, $process) = split(":", $request);
1.147     foxr      903:     my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146     foxr      904:     if($process eq 'lonc') {
                    905: 	$processpidfile = $processpidfile."lonc.pid";
1.147     foxr      906: 	if (!open(PIDFILE, "< $processpidfile")) {
                    907: 	    return "error:Open failed for $processpidfile";
                    908: 	}
                    909: 	my $loncpid = <PIDFILE>;
                    910: 	close(PIDFILE);
                    911: 	logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
                    912: 		."</font>");
                    913: 	kill("USR2", $loncpid);
1.146     foxr      914:     } elsif ($process eq 'lond') {
1.147     foxr      915: 	logthis('<font color="red"> Reinitializing self (lond) </font>');
                    916: 	&UpdateHosts;			# Lond is us!!
1.146     foxr      917:     } else {
                    918: 	&logthis('<font color="yellow" Invalid reinit request for '.$process
                    919: 		 ."</font>");
                    920: 	return "error:Invalid process identifier $process";
                    921:     }
1.145     foxr      922:     return 'ok';
                    923: }
1.168     foxr      924: #   Validate a line in a configuration file edit script:
                    925: #   Validation includes:
                    926: #     - Ensuring the command is valid.
                    927: #     - Ensuring the command has sufficient parameters
                    928: #   Parameters:
                    929: #     scriptline - A line to validate (\n has been stripped for what it's worth).
1.167     foxr      930: #
1.168     foxr      931: #   Return:
                    932: #      0     - Invalid scriptline.
                    933: #      1     - Valid scriptline
                    934: #  NOTE:
                    935: #     Only the command syntax is checked, not the executability of the
                    936: #     command.
                    937: #
                    938: sub isValidEditCommand {
                    939:     my $scriptline = shift;
                    940: 
                    941:     #   Line elements are pipe separated:
                    942: 
                    943:     my ($command, $key, $newline)  = split(/\|/, $scriptline);
                    944:     &logthis('<font color="green"> isValideditCommand checking: '.
                    945: 	     "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
                    946:     
                    947:     if ($command eq "delete") {
                    948: 	#
                    949: 	#   key with no newline.
                    950: 	#
                    951: 	if( ($key eq "") || ($newline ne "")) {
                    952: 	    return 0;		# Must have key but no newline.
                    953: 	} else {
                    954: 	    return 1;		# Valid syntax.
                    955: 	}
1.169     foxr      956:     } elsif ($command eq "replace") {
1.168     foxr      957: 	#
                    958: 	#   key and newline:
                    959: 	#
                    960: 	if (($key eq "") || ($newline eq "")) {
                    961: 	    return 0;
                    962: 	} else {
                    963: 	    return 1;
                    964: 	}
1.169     foxr      965:     } elsif ($command eq "append") {
                    966: 	if (($key ne "") && ($newline eq "")) {
                    967: 	    return 1;
                    968: 	} else {
                    969: 	    return 0;
                    970: 	}
1.168     foxr      971:     } else {
                    972: 	return 0;		# Invalid command.
                    973:     }
                    974:     return 0;			# Should not get here!!!
                    975: }
1.169     foxr      976: #
                    977: #   ApplyEdit - Applies an edit command to a line in a configuration 
                    978: #               file.  It is the caller's responsiblity to validate the
                    979: #               edit line.
                    980: #   Parameters:
                    981: #      $directive - A single edit directive to apply.  
                    982: #                   Edit directives are of the form:
                    983: #                  append|newline      - Appends a new line to the file.
                    984: #                  replace|key|newline - Replaces the line with key value 'key'
                    985: #                  delete|key          - Deletes the line with key value 'key'.
                    986: #      $editor   - A config file editor object that contains the
                    987: #                  file being edited.
                    988: #
                    989: sub ApplyEdit {
1.192     foxr      990: 
                    991:     my ($directive, $editor) = @_;
1.169     foxr      992: 
                    993:     # Break the directive down into its command and its parameters
                    994:     # (at most two at this point.  The meaning of the parameters, if in fact
                    995:     #  they exist depends on the command).
                    996: 
                    997:     my ($command, $p1, $p2) = split(/\|/, $directive);
                    998: 
                    999:     if($command eq "append") {
                   1000: 	$editor->Append($p1);	          # p1 - key p2 null.
                   1001:     } elsif ($command eq "replace") {
                   1002: 	$editor->ReplaceLine($p1, $p2);   # p1 - key p2 = newline.
                   1003:     } elsif ($command eq "delete") {
                   1004: 	$editor->DeleteLine($p1);         # p1 - key p2 null.
                   1005:     } else {			          # Should not get here!!!
                   1006: 	die "Invalid command given to ApplyEdit $command"
                   1007:     }
                   1008: }
                   1009: #
                   1010: # AdjustOurHost:
                   1011: #           Adjusts a host file stored in a configuration file editor object
                   1012: #           for the true IP address of this host. This is necessary for hosts
                   1013: #           that live behind a firewall.
                   1014: #           Those hosts have a publicly distributed IP of the firewall, but
                   1015: #           internally must use their actual IP.  We assume that a given
                   1016: #           host only has a single IP interface for now.
                   1017: # Formal Parameters:
                   1018: #     editor   - The configuration file editor to adjust.  This
                   1019: #                editor is assumed to contain a hosts.tab file.
                   1020: # Strategy:
                   1021: #    - Figure out our hostname.
                   1022: #    - Lookup the entry for this host.
                   1023: #    - Modify the line to contain our IP
                   1024: #    - Do a replace for this host.
                   1025: sub AdjustOurHost {
                   1026:     my $editor        = shift;
                   1027: 
                   1028:     # figure out who I am.
                   1029: 
                   1030:     my $myHostName    = $perlvar{'lonHostID'}; # LonCAPA hostname.
                   1031: 
                   1032:     #  Get my host file entry.
                   1033: 
                   1034:     my $ConfigLine    = $editor->Find($myHostName);
                   1035:     if(! (defined $ConfigLine)) {
                   1036: 	die "AdjustOurHost - no entry for me in hosts file $myHostName";
                   1037:     }
                   1038:     # figure out my IP:
                   1039:     #   Use the config line to get my hostname.
                   1040:     #   Use gethostbyname to translate that into an IP address.
                   1041:     #
1.338     albertel 1042:     my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169     foxr     1043:     #
                   1044:     #  Reassemble the config line from the elements in the list.
                   1045:     #  Note that if the loncnew items were not present before, they will
                   1046:     #  be now even if they would be empty
                   1047:     #
                   1048:     my $newConfigLine = $id;
1.338     albertel 1049:     foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169     foxr     1050: 	$newConfigLine .= ":".$item;
                   1051:     }
                   1052:     #  Replace the line:
                   1053: 
                   1054:     $editor->ReplaceLine($id, $newConfigLine);
                   1055:     
                   1056: }
                   1057: #
                   1058: #   ReplaceConfigFile:
                   1059: #              Replaces a configuration file with the contents of a
                   1060: #              configuration file editor object.
                   1061: #              This is done by:
                   1062: #              - Copying the target file to <filename>.old
                   1063: #              - Writing the new file to <filename>.tmp
                   1064: #              - Moving <filename.tmp>  -> <filename>
                   1065: #              This laborious process ensures that the system is never without
                   1066: #              a configuration file that's at least valid (even if the contents
                   1067: #              may be dated).
                   1068: #   Parameters:
                   1069: #        filename   - Name of the file to modify... this is a full path.
                   1070: #        editor     - Editor containing the file.
                   1071: #
                   1072: sub ReplaceConfigFile {
1.192     foxr     1073:     
                   1074:     my ($filename, $editor) = @_;
1.168     foxr     1075: 
1.169     foxr     1076:     CopyFile ($filename, $filename.".old");
                   1077: 
                   1078:     my $contents  = $editor->Get(); # Get the contents of the file.
                   1079: 
                   1080:     InstallFile($filename, $contents);
                   1081: }
1.168     foxr     1082: #   
                   1083: #
                   1084: #   Called to edit a configuration table  file
1.167     foxr     1085: #   Parameters:
                   1086: #      request           - The entire command/request sent by lonc or lonManage
                   1087: #   Return:
                   1088: #      The reply to send to the client.
1.168     foxr     1089: #
1.167     foxr     1090: sub EditFile {
                   1091:     my $request = shift;
                   1092: 
                   1093:     #  Split the command into it's pieces:  edit:filetype:script
                   1094: 
1.339     albertel 1095:     my ($cmd, $filetype, $script) = split(/:/, $request,3);	# : in script
1.167     foxr     1096: 
                   1097:     #  Check the pre-coditions for success:
                   1098: 
1.339     albertel 1099:     if($cmd != "edit") {	# Something is amiss afoot alack.
1.167     foxr     1100: 	return "error:edit request detected, but request != 'edit'\n";
                   1101:     }
                   1102:     if( ($filetype ne "hosts")  &&
                   1103: 	($filetype ne "domain")) {
                   1104: 	return "error:edit requested with invalid file specifier: $filetype \n";
                   1105:     }
                   1106: 
                   1107:     #   Split the edit script and check it's validity.
1.168     foxr     1108: 
                   1109:     my @scriptlines = split(/\n/, $script);  # one line per element.
                   1110:     my $linecount   = scalar(@scriptlines);
                   1111:     for(my $i = 0; $i < $linecount; $i++) {
                   1112: 	chomp($scriptlines[$i]);
                   1113: 	if(!isValidEditCommand($scriptlines[$i])) {
                   1114: 	    return "error:edit with bad script line: '$scriptlines[$i]' \n";
                   1115: 	}
                   1116:     }
1.145     foxr     1117: 
1.167     foxr     1118:     #   Execute the edit operation.
1.169     foxr     1119:     #   - Create a config file editor for the appropriate file and 
                   1120:     #   - execute each command in the script:
                   1121:     #
                   1122:     my $configfile = ConfigFileFromSelector($filetype);
                   1123:     if (!(defined $configfile)) {
                   1124: 	return "refused\n";
                   1125:     }
                   1126:     my $editor = ConfigFileEdit->new($configfile);
1.167     foxr     1127: 
1.169     foxr     1128:     for (my $i = 0; $i < $linecount; $i++) {
                   1129: 	ApplyEdit($scriptlines[$i], $editor);
                   1130:     }
                   1131:     # If the file is the host file, ensure that our host is
                   1132:     # adjusted to have our ip:
                   1133:     #
                   1134:     if($filetype eq "host") {
                   1135: 	AdjustOurHost($editor);
                   1136:     }
                   1137:     #  Finally replace the current file with our file.
                   1138:     #
                   1139:     ReplaceConfigFile($configfile, $editor);
1.167     foxr     1140: 
                   1141:     return "ok\n";
                   1142: }
1.207     foxr     1143: 
1.255     foxr     1144: #   read_profile
                   1145: #
                   1146: #   Returns a set of specific entries from a user's profile file.
                   1147: #   this is a utility function that is used by both get_profile_entry and
                   1148: #   get_profile_entry_encrypted.
                   1149: #
                   1150: # Parameters:
                   1151: #    udom       - Domain in which the user exists.
                   1152: #    uname      - User's account name (loncapa account)
                   1153: #    namespace  - The profile namespace to open.
                   1154: #    what       - A set of & separated queries.
                   1155: # Returns:
                   1156: #    If all ok: - The string that needs to be shipped back to the user.
                   1157: #    If failure - A string that starts with error: followed by the failure
                   1158: #                 reason.. note that this probabyl gets shipped back to the
                   1159: #                 user as well.
                   1160: #
                   1161: sub read_profile {
                   1162:     my ($udom, $uname, $namespace, $what) = @_;
                   1163:     
                   1164:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   1165: 				 &GDBM_READER());
                   1166:     if ($hashref) {
                   1167:         my @queries=split(/\&/,$what);
1.440     raeburn  1168:         if ($namespace eq 'roles') {
                   1169:             @queries = map { &unescape($_); } @queries; 
                   1170:         }
1.255     foxr     1171:         my $qresult='';
                   1172: 	
                   1173: 	for (my $i=0;$i<=$#queries;$i++) {
                   1174: 	    $qresult.="$hashref->{$queries[$i]}&";    # Presumably failure gives empty string.
                   1175: 	}
                   1176: 	$qresult=~s/\&$//;              # Remove trailing & from last lookup.
1.311     albertel 1177: 	if (&untie_user_hash($hashref)) {
1.255     foxr     1178: 	    return $qresult;
                   1179: 	} else {
                   1180: 	    return "error: ".($!+0)." untie (GDBM) Failed";
                   1181: 	}
                   1182:     } else {
                   1183: 	if ($!+0 == 2) {
                   1184: 	    return "error:No such file or GDBM reported bad block error";
                   1185: 	} else {
                   1186: 	    return "error: ".($!+0)." tie (GDBM) Failed";
                   1187: 	}
                   1188:     }
                   1189: 
                   1190: }
1.214     foxr     1191: #--------------------- Request Handlers --------------------------------------------
                   1192: #
1.215     foxr     1193: #   By convention each request handler registers itself prior to the sub 
                   1194: #   declaration:
1.214     foxr     1195: #
                   1196: 
1.216     foxr     1197: #++
                   1198: #
1.214     foxr     1199: #  Handles ping requests.
                   1200: #  Parameters:
                   1201: #      $cmd    - the actual keyword that invoked us.
                   1202: #      $tail   - the tail of the request that invoked us.
                   1203: #      $replyfd- File descriptor connected to the client
                   1204: #  Implicit Inputs:
                   1205: #      $currenthostid - Global variable that carries the name of the host we are
                   1206: #                       known as.
                   1207: #  Returns:
                   1208: #      1       - Ok to continue processing.
                   1209: #      0       - Program should exit.
                   1210: #  Side effects:
                   1211: #      Reply information is sent to the client.
                   1212: sub ping_handler {
                   1213:     my ($cmd, $tail, $client) = @_;
                   1214:     Debug("$cmd $tail $client .. $currenthostid:");
                   1215:    
1.387     albertel 1216:     Reply( $client,\$currenthostid,"$cmd:$tail");
1.214     foxr     1217:    
                   1218:     return 1;
                   1219: }
                   1220: &register_handler("ping", \&ping_handler, 0, 1, 1);       # Ping unencoded, client or manager.
                   1221: 
1.216     foxr     1222: #++
1.215     foxr     1223: #
                   1224: # Handles pong requests.  Pong replies with our current host id, and
                   1225: #                         the results of a ping sent to us via our lonc.
                   1226: #
                   1227: # Parameters:
                   1228: #      $cmd    - the actual keyword that invoked us.
                   1229: #      $tail   - the tail of the request that invoked us.
                   1230: #      $replyfd- File descriptor connected to the client
                   1231: #  Implicit Inputs:
                   1232: #      $currenthostid - Global variable that carries the name of the host we are
                   1233: #                       connected to.
                   1234: #  Returns:
                   1235: #      1       - Ok to continue processing.
                   1236: #      0       - Program should exit.
                   1237: #  Side effects:
                   1238: #      Reply information is sent to the client.
                   1239: sub pong_handler {
                   1240:     my ($cmd, $tail, $replyfd) = @_;
                   1241: 
1.365     albertel 1242:     my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215     foxr     1243:     &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail"); 
                   1244:     return 1;
                   1245: }
                   1246: &register_handler("pong", \&pong_handler, 0, 1, 1);       # Pong unencoded, client or manager
                   1247: 
1.216     foxr     1248: #++
                   1249: #      Called to establish an encrypted session key with the remote client.
                   1250: #      Note that with secure lond, in most cases this function is never
                   1251: #      invoked.  Instead, the secure session key is established either
                   1252: #      via a local file that's locked down tight and only lives for a short
                   1253: #      time, or via an ssl tunnel...and is generated from a bunch-o-random
                   1254: #      bits from /dev/urandom, rather than the predictable pattern used by
                   1255: #      by this sub.  This sub is only used in the old-style insecure
                   1256: #      key negotiation.
                   1257: # Parameters:
                   1258: #      $cmd    - the actual keyword that invoked us.
                   1259: #      $tail   - the tail of the request that invoked us.
                   1260: #      $replyfd- File descriptor connected to the client
                   1261: #  Implicit Inputs:
                   1262: #      $currenthostid - Global variable that carries the name of the host
                   1263: #                       known as.
1.448     raeburn  1264: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.216     foxr     1265: #  Returns:
                   1266: #      1       - Ok to continue processing.
                   1267: #      0       - Program should exit.
                   1268: #  Implicit Outputs:
                   1269: #      Reply information is sent to the client.
                   1270: #      $cipher is set with a reference to a new IDEA encryption object.
                   1271: #
                   1272: sub establish_key_handler {
                   1273:     my ($cmd, $tail, $replyfd) = @_;
                   1274: 
                   1275:     my $buildkey=time.$$.int(rand 100000);
                   1276:     $buildkey=~tr/1-6/A-F/;
                   1277:     $buildkey=int(rand 100000).$buildkey.int(rand 100000);
                   1278:     my $key=$currenthostid.$clientname;
                   1279:     $key=~tr/a-z/A-Z/;
                   1280:     $key=~tr/G-P/0-9/;
                   1281:     $key=~tr/Q-Z/0-9/;
                   1282:     $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
                   1283:     $key=substr($key,0,32);
                   1284:     my $cipherkey=pack("H32",$key);
                   1285:     $cipher=new IDEA $cipherkey;
1.387     albertel 1286:     &Reply($replyfd, \$buildkey, "$cmd:$tail"); 
1.216     foxr     1287:    
                   1288:     return 1;
                   1289: 
                   1290: }
                   1291: &register_handler("ekey", \&establish_key_handler, 0, 1,1);
                   1292: 
1.217     foxr     1293: #     Handler for the load command.  Returns the current system load average
                   1294: #     to the requestor.
                   1295: #
                   1296: # Parameters:
                   1297: #      $cmd    - the actual keyword that invoked us.
                   1298: #      $tail   - the tail of the request that invoked us.
                   1299: #      $replyfd- File descriptor connected to the client
                   1300: #  Implicit Inputs:
                   1301: #      $currenthostid - Global variable that carries the name of the host
                   1302: #                       known as.
1.448     raeburn  1303: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1304: #  Returns:
                   1305: #      1       - Ok to continue processing.
                   1306: #      0       - Program should exit.
                   1307: #  Side effects:
                   1308: #      Reply information is sent to the client.
                   1309: sub load_handler {
                   1310:     my ($cmd, $tail, $replyfd) = @_;
                   1311: 
1.463     foxr     1312: 
                   1313: 
1.217     foxr     1314:    # Get the load average from /proc/loadavg and calculate it as a percentage of
                   1315:    # the allowed load limit as set by the perl global variable lonLoadLim
                   1316: 
                   1317:     my $loadavg;
                   1318:     my $loadfile=IO::File->new('/proc/loadavg');
                   1319:    
                   1320:     $loadavg=<$loadfile>;
                   1321:     $loadavg =~ s/\s.*//g;                      # Extract the first field only.
                   1322:    
                   1323:     my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
                   1324: 
1.387     albertel 1325:     &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217     foxr     1326:    
                   1327:     return 1;
                   1328: }
1.263     albertel 1329: &register_handler("load", \&load_handler, 0, 1, 0);
1.217     foxr     1330: 
                   1331: #
                   1332: #   Process the userload request.  This sub returns to the client the current
                   1333: #  user load average.  It can be invoked either by clients or managers.
                   1334: #
                   1335: # Parameters:
                   1336: #      $cmd    - the actual keyword that invoked us.
                   1337: #      $tail   - the tail of the request that invoked us.
                   1338: #      $replyfd- File descriptor connected to the client
                   1339: #  Implicit Inputs:
                   1340: #      $currenthostid - Global variable that carries the name of the host
                   1341: #                       known as.
1.448     raeburn  1342: #      $clientname    - Global variable that carries the name of the host we're connected to.
1.217     foxr     1343: #  Returns:
                   1344: #      1       - Ok to continue processing.
                   1345: #      0       - Program should exit
                   1346: # Implicit inputs:
                   1347: #     whatever the userload() function requires.
                   1348: #  Implicit outputs:
                   1349: #     the reply is written to the client.
                   1350: #
                   1351: sub user_load_handler {
                   1352:     my ($cmd, $tail, $replyfd) = @_;
                   1353: 
1.365     albertel 1354:     my $userloadpercent=&Apache::lonnet::userload();
1.387     albertel 1355:     &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217     foxr     1356:     
                   1357:     return 1;
                   1358: }
1.263     albertel 1359: &register_handler("userload", \&user_load_handler, 0, 1, 0);
1.217     foxr     1360: 
1.218     foxr     1361: #   Process a request for the authorization type of a user:
                   1362: #   (userauth).
                   1363: #
                   1364: # Parameters:
                   1365: #      $cmd    - the actual keyword that invoked us.
                   1366: #      $tail   - the tail of the request that invoked us.
                   1367: #      $replyfd- File descriptor connected to the client
                   1368: #  Returns:
                   1369: #      1       - Ok to continue processing.
                   1370: #      0       - Program should exit
                   1371: # Implicit outputs:
                   1372: #    The user authorization type is written to the client.
                   1373: #
                   1374: sub user_authorization_type {
                   1375:     my ($cmd, $tail, $replyfd) = @_;
                   1376:    
                   1377:     my $userinput = "$cmd:$tail";
                   1378:    
                   1379:     #  Pull the domain and username out of the command tail.
1.222     foxr     1380:     # and call get_auth_type to determine the authentication type.
1.218     foxr     1381:    
                   1382:     my ($udom,$uname)=split(/:/,$tail);
1.222     foxr     1383:     my $result = &get_auth_type($udom, $uname);
1.218     foxr     1384:     if($result eq "nouser") {
                   1385: 	&Failure( $replyfd, "unknown_user\n", $userinput);
                   1386:     } else {
                   1387: 	#
1.222     foxr     1388: 	# We only want to pass the second field from get_auth_type
1.218     foxr     1389: 	# for ^krb.. otherwise we'll be handing out the encrypted
                   1390: 	# password for internals e.g.
                   1391: 	#
                   1392: 	my ($type,$otherinfo) = split(/:/,$result);
                   1393: 	if($type =~ /^krb/) {
                   1394: 	    $type = $result;
1.269     raeburn  1395: 	} else {
                   1396:             $type .= ':';
                   1397:         }
1.387     albertel 1398: 	&Reply( $replyfd, \$type, $userinput);
1.218     foxr     1399:     }
                   1400:   
                   1401:     return 1;
                   1402: }
                   1403: &register_handler("currentauth", \&user_authorization_type, 1, 1, 0);
                   1404: 
                   1405: #   Process a request by a manager to push a hosts or domain table 
                   1406: #   to us.  We pick apart the command and pass it on to the subs
                   1407: #   that already exist to do this.
                   1408: #
                   1409: # Parameters:
                   1410: #      $cmd    - the actual keyword that invoked us.
                   1411: #      $tail   - the tail of the request that invoked us.
                   1412: #      $client - File descriptor connected to the client
                   1413: #  Returns:
                   1414: #      1       - Ok to continue processing.
                   1415: #      0       - Program should exit
                   1416: # Implicit Output:
                   1417: #    a reply is written to the client.
                   1418: sub push_file_handler {
                   1419:     my ($cmd, $tail, $client) = @_;
1.412     foxr     1420:     &Debug("In push file handler");
1.218     foxr     1421:     my $userinput = "$cmd:$tail";
                   1422: 
                   1423:     # At this time we only know that the IP of our partner is a valid manager
                   1424:     # the code below is a hook to do further authentication (e.g. to resolve
                   1425:     # spoofing).
                   1426: 
                   1427:     my $cert = &GetCertificate($userinput);
1.412     foxr     1428:     if(&ValidManager($cert)) {
                   1429: 	&Debug("Valid manager: $client");
1.218     foxr     1430: 
                   1431: 	# Now presumably we have the bona fides of both the peer host and the
                   1432: 	# process making the request.
                   1433:       
                   1434: 	my $reply = &PushFile($userinput);
1.387     albertel 1435: 	&Reply($client, \$reply, $userinput);
1.218     foxr     1436: 
                   1437:     } else {
1.412     foxr     1438: 	&logthis("push_file_handler $client is not valid");
1.218     foxr     1439: 	&Failure( $client, "refused\n", $userinput);
                   1440:     } 
1.219     foxr     1441:     return 1;
1.218     foxr     1442: }
                   1443: &register_handler("pushfile", \&push_file_handler, 1, 0, 1);
                   1444: 
1.399     raeburn  1445: # The du_handler routine should be considered obsolete and is retained
                   1446: # for communication with legacy servers.  Please see the du2_handler.
1.243     banghart 1447: #
1.399     raeburn  1448: #   du  - list the disk usage of a directory recursively. 
1.243     banghart 1449: #    
                   1450: #   note: stolen code from the ls file handler
                   1451: #   under construction by Rick Banghart 
                   1452: #    .
                   1453: # Parameters:
                   1454: #    $cmd        - The command that dispatched us (du).
                   1455: #    $ududir     - The directory path to list... I'm not sure what this
                   1456: #                  is relative as things like ls:. return e.g.
                   1457: #                  no_such_dir.
                   1458: #    $client     - Socket open on the client.
                   1459: # Returns:
                   1460: #     1 - indicating that the daemon should not disconnect.
                   1461: # Side Effects:
                   1462: #   The reply is written to  $client.
                   1463: #
                   1464: sub du_handler {
                   1465:     my ($cmd, $ududir, $client) = @_;
1.339     albertel 1466:     ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251     foxr     1467:     my $userinput = "$cmd:$ududir";
                   1468: 
1.245     albertel 1469:     if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
                   1470: 	&Failure($client,"refused\n","$cmd:$ududir");
                   1471: 	return 1;
                   1472:     }
1.249     foxr     1473:     #  Since $ududir could have some nasties in it,
                   1474:     #  we will require that ududir is a valid
                   1475:     #  directory.  Just in case someone tries to
                   1476:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1477:     #  etc.
                   1478:     #
                   1479:     if (-d $ududir) {
1.292     albertel 1480: 	my $total_size=0;
                   1481: 	my $code=sub { 
                   1482: 	    if ($_=~/\.\d+\./) { return;} 
                   1483: 	    if ($_=~/\.meta$/) { return;}
1.362     albertel 1484: 	    if (-d $_)         { return;}
1.292     albertel 1485: 	    $total_size+=(stat($_))[7];
                   1486: 	};
1.295     raeburn  1487: 	chdir($ududir);
1.292     albertel 1488: 	find($code,$ududir);
                   1489: 	$total_size=int($total_size/1024);
1.387     albertel 1490: 	&Reply($client,\$total_size,"$cmd:$ududir");
1.249     foxr     1491:     } else {
1.251     foxr     1492: 	&Failure($client, "bad_directory:$ududir\n","$cmd:$ududir"); 
1.249     foxr     1493:     }
1.243     banghart 1494:     return 1;
                   1495: }
                   1496: &register_handler("du", \&du_handler, 0, 1, 0);
1.218     foxr     1497: 
1.399     raeburn  1498: # Please also see the du_handler, which is obsoleted by du2. 
                   1499: # du2_handler differs from du_handler in that required path to directory
                   1500: # provided by &propath() is prepended in the handler instead of on the 
                   1501: # client side.
1.239     foxr     1502: #
1.399     raeburn  1503: #   du2  - list the disk usage of a directory recursively.
                   1504: #
                   1505: # Parameters:
                   1506: #    $cmd        - The command that dispatched us (du).
                   1507: #    $tail       - The tail of the request that invoked us.
                   1508: #                  $tail is a : separated list of the following:
                   1509: #                   - $ududir - directory path to list (before prepending)
                   1510: #                   - $getpropath = 1 if &propath() should prepend
                   1511: #                   - $uname - username to use for &propath or user dir
                   1512: #                   - $udom - domain to use for &propath or user dir
                   1513: #                   All are escaped.
                   1514: #    $client     - Socket open on the client.
                   1515: # Returns:
                   1516: #     1 - indicating that the daemon should not disconnect.
                   1517: # Side Effects:
                   1518: #   The reply is written to $client.
                   1519: #
                   1520: 
                   1521: sub du2_handler {
                   1522:     my ($cmd, $tail, $client) = @_;
                   1523:     my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
                   1524:     my $userinput = "$cmd:$tail";
                   1525:     if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
                   1526:         &Failure($client,"refused\n","$cmd:$tail");
                   1527:         return 1;
                   1528:     }
                   1529:     if ($getpropath) {
                   1530:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1531:             $ududir = &propath($udom,$uname).'/'.$ududir;
                   1532:         } else {
                   1533:             &Failure($client,"refused\n","$cmd:$tail");
                   1534:             return 1;
                   1535:         }
                   1536:     }
                   1537:     #  Since $ududir could have some nasties in it,
                   1538:     #  we will require that ududir is a valid
                   1539:     #  directory.  Just in case someone tries to
                   1540:     #  slip us a  line like .;(cd /home/httpd rm -rf*)
                   1541:     #  etc.
                   1542:     #
                   1543:     if (-d $ududir) {
                   1544:         my $total_size=0;
                   1545:         my $code=sub {
                   1546:             if ($_=~/\.\d+\./) { return;}
                   1547:             if ($_=~/\.meta$/) { return;}
                   1548:             if (-d $_)         { return;}
                   1549:             $total_size+=(stat($_))[7];
                   1550:         };
                   1551:         chdir($ududir);
                   1552:         find($code,$ududir);
                   1553:         $total_size=int($total_size/1024);
                   1554:         &Reply($client,\$total_size,"$cmd:$ududir");
                   1555:     } else {
                   1556:         &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
                   1557:     }
                   1558:     return 1;
                   1559: }
                   1560: &register_handler("du2", \&du2_handler, 0, 1, 0);
                   1561: 
                   1562: #
                   1563: # The ls_handler routine should be considered obsolete and is retained
                   1564: # for communication with legacy servers.  Please see the ls3_handler.
1.280     matthew  1565: #
1.239     foxr     1566: #   ls  - list the contents of a directory.  For each file in the
                   1567: #    selected directory the filename followed by the full output of
                   1568: #    the stat function is returned.  The returned info for each
                   1569: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1570: # Parameters:
                   1571: #    $cmd        - The command that dispatched us (ls).
                   1572: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1573: #                  is relative as things like ls:. return e.g.
                   1574: #                  no_such_dir.
                   1575: #    $client     - Socket open on the client.
                   1576: # Returns:
                   1577: #     1 - indicating that the daemon should not disconnect.
                   1578: # Side Effects:
                   1579: #   The reply is written to  $client.
                   1580: #
                   1581: sub ls_handler {
1.280     matthew  1582:     # obsoleted by ls2_handler
1.239     foxr     1583:     my ($cmd, $ulsdir, $client) = @_;
                   1584: 
                   1585:     my $userinput = "$cmd:$ulsdir";
                   1586: 
                   1587:     my $obs;
                   1588:     my $rights;
                   1589:     my $ulsout='';
                   1590:     my $ulsfn;
                   1591:     if (-e $ulsdir) {
                   1592: 	if(-d $ulsdir) {
                   1593: 	    if (opendir(LSDIR,$ulsdir)) {
                   1594: 		while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1595: 		    undef($obs);
                   1596: 		    undef($rights); 
1.239     foxr     1597: 		    my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1598: 		    #We do some obsolete checking here
                   1599: 		    if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1600: 			open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1601: 			my @obsolete=<FILE>;
                   1602: 			foreach my $obsolete (@obsolete) {
1.301     www      1603: 			    if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.239     foxr     1604: 			    if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
                   1605: 			}
                   1606: 		    }
                   1607: 		    $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
                   1608: 		    if($obs eq '1') { $ulsout.="&1"; }
                   1609: 		    else { $ulsout.="&0"; }
                   1610: 		    if($rights eq '1') { $ulsout.="&1:"; }
                   1611: 		    else { $ulsout.="&0:"; }
                   1612: 		}
                   1613: 		closedir(LSDIR);
                   1614: 	    }
                   1615: 	} else {
                   1616: 	    my @ulsstats=stat($ulsdir);
                   1617: 	    $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1618: 	}
                   1619:     } else {
                   1620: 	$ulsout='no_such_dir';
                   1621:     }
                   1622:     if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1623:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239     foxr     1624:     
                   1625:     return 1;
                   1626: 
                   1627: }
                   1628: &register_handler("ls", \&ls_handler, 0, 1, 0);
                   1629: 
1.399     raeburn  1630: # The ls2_handler routine should be considered obsolete and is retained
                   1631: # for communication with legacy servers.  Please see the ls3_handler.
                   1632: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280     matthew  1633: # ls2_handler differs from ls_handler in that it escapes its return 
                   1634: # values before concatenating them together with ':'s.
                   1635: #
                   1636: #   ls2  - list the contents of a directory.  For each file in the
                   1637: #    selected directory the filename followed by the full output of
                   1638: #    the stat function is returned.  The returned info for each
                   1639: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1640: # Parameters:
                   1641: #    $cmd        - The command that dispatched us (ls).
                   1642: #    $ulsdir     - The directory path to list... I'm not sure what this
                   1643: #                  is relative as things like ls:. return e.g.
                   1644: #                  no_such_dir.
                   1645: #    $client     - Socket open on the client.
                   1646: # Returns:
                   1647: #     1 - indicating that the daemon should not disconnect.
                   1648: # Side Effects:
                   1649: #   The reply is written to  $client.
                   1650: #
                   1651: sub ls2_handler {
                   1652:     my ($cmd, $ulsdir, $client) = @_;
                   1653: 
                   1654:     my $userinput = "$cmd:$ulsdir";
                   1655: 
                   1656:     my $obs;
                   1657:     my $rights;
                   1658:     my $ulsout='';
                   1659:     my $ulsfn;
                   1660:     if (-e $ulsdir) {
                   1661:         if(-d $ulsdir) {
                   1662:             if (opendir(LSDIR,$ulsdir)) {
                   1663:                 while ($ulsfn=readdir(LSDIR)) {
1.291     albertel 1664:                     undef($obs);
                   1665: 		    undef($rights); 
1.280     matthew  1666:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1667:                     #We do some obsolete checking here
                   1668:                     if(-e $ulsdir.'/'.$ulsfn.".meta") { 
                   1669:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1670:                         my @obsolete=<FILE>;
                   1671:                         foreach my $obsolete (@obsolete) {
1.301     www      1672:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; } 
1.280     matthew  1673:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1674:                                 $rights = 1;
                   1675:                             }
                   1676:                         }
                   1677:                     }
                   1678:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1679:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1680:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1681:                     $ulsout.= &escape($tmp).':';
                   1682:                 }
                   1683:                 closedir(LSDIR);
                   1684:             }
                   1685:         } else {
                   1686:             my @ulsstats=stat($ulsdir);
                   1687:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1688:         }
                   1689:     } else {
                   1690:         $ulsout='no_such_dir';
                   1691:    }
                   1692:    if ($ulsout eq '') { $ulsout='empty'; }
1.387     albertel 1693:    &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280     matthew  1694:    return 1;
                   1695: }
                   1696: &register_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399     raeburn  1697: #
                   1698: #   ls3  - list the contents of a directory.  For each file in the
                   1699: #    selected directory the filename followed by the full output of
                   1700: #    the stat function is returned.  The returned info for each
                   1701: #    file are separated by ':'.  The stat fields are separated by &'s.
                   1702: # Parameters:
                   1703: #    $cmd        - The command that dispatched us (ls).
                   1704: #    $tail       - The tail of the request that invoked us.
                   1705: #                  $tail is a : separated list of the following:
                   1706: #                   - $ulsdir - directory path to list (before prepending)
                   1707: #                   - $getpropath = 1 if &propath() should prepend
                   1708: #                   - $getuserdir = 1 if path to user dir in lonUsers should
                   1709: #                                     prepend
                   1710: #                   - $alternate_root - path to prepend
                   1711: #                   - $uname - username to use for &propath or user dir
                   1712: #                   - $udom - domain to use for &propath or user dir
                   1713: #            All of these except $getpropath and &getuserdir are escaped.    
                   1714: #                  no_such_dir.
                   1715: #    $client     - Socket open on the client.
                   1716: # Returns:
                   1717: #     1 - indicating that the daemon should not disconnect.
                   1718: # Side Effects:
                   1719: #   The reply is written to $client.
                   1720: #
                   1721: 
                   1722: sub ls3_handler {
                   1723:     my ($cmd, $tail, $client) = @_;
                   1724:     my $userinput = "$cmd:$tail";
                   1725:     my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
                   1726:         split(/:/,$tail);
                   1727:     if (defined($ulsdir)) {
                   1728:         $ulsdir = &unescape($ulsdir);
                   1729:     }
                   1730:     if (defined($alternate_root)) {
                   1731:         $alternate_root = &unescape($alternate_root);
                   1732:     }
                   1733:     if (defined($uname)) {
                   1734:         $uname = &unescape($uname);
                   1735:     }
                   1736:     if (defined($udom)) {
                   1737:         $udom = &unescape($udom);
                   1738:     }
                   1739: 
                   1740:     my $dir_root = $perlvar{'lonDocRoot'};
                   1741:     if ($getpropath) {
                   1742:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1743:             $dir_root = &propath($udom,$uname);
                   1744:             $dir_root =~ s/\/$//;
                   1745:         } else {
                   1746:             &Failure($client,"refused\n","$cmd:$tail");
                   1747:             return 1;
                   1748:         }
                   1749:     } elsif ($getuserdir) {
                   1750:         if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
                   1751:             my $subdir=$uname.'__';
                   1752:             $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   1753:             $dir_root = $Apache::lonnet::perlvar{'lonUsersDir'}
                   1754:                        ."/$udom/$subdir/$uname";
                   1755:         } else {
                   1756:             &Failure($client,"refused\n","$cmd:$tail");
                   1757:             return 1;
                   1758:         }
1.400     raeburn  1759:     } elsif ($alternate_root ne '') {
1.399     raeburn  1760:         $dir_root = $alternate_root;
                   1761:     }
1.408     raeburn  1762:     if (($dir_root ne '') && ($dir_root ne '/')) {
1.400     raeburn  1763:         if ($ulsdir =~ /^\//) {
                   1764:             $ulsdir = $dir_root.$ulsdir;
                   1765:         } else {
                   1766:             $ulsdir = $dir_root.'/'.$ulsdir;
                   1767:         }
1.399     raeburn  1768:     }
                   1769:     my $obs;
                   1770:     my $rights;
                   1771:     my $ulsout='';
                   1772:     my $ulsfn;
                   1773:     if (-e $ulsdir) {
                   1774:         if(-d $ulsdir) {
                   1775:             if (opendir(LSDIR,$ulsdir)) {
                   1776:                 while ($ulsfn=readdir(LSDIR)) {
                   1777:                     undef($obs);
                   1778:                     undef($rights);
                   1779:                     my @ulsstats=stat($ulsdir.'/'.$ulsfn);
                   1780:                     #We do some obsolete checking here
                   1781:                     if(-e $ulsdir.'/'.$ulsfn.".meta") {
                   1782:                         open(FILE, $ulsdir.'/'.$ulsfn.".meta");
                   1783:                         my @obsolete=<FILE>;
                   1784:                         foreach my $obsolete (@obsolete) {
                   1785:                             if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
                   1786:                             if($obsolete =~ m|(<copyright>)(default)|) {
                   1787:                                 $rights = 1;
                   1788:                             }
                   1789:                         }
                   1790:                     }
                   1791:                     my $tmp = $ulsfn.'&'.join('&',@ulsstats);
                   1792:                     if ($obs    eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1793:                     if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
                   1794:                     $ulsout.= &escape($tmp).':';
                   1795:                 }
                   1796:                 closedir(LSDIR);
                   1797:             }
                   1798:         } else {
                   1799:             my @ulsstats=stat($ulsdir);
                   1800:             $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
                   1801:         }
                   1802:     } else {
                   1803:         $ulsout='no_such_dir';
1.400     raeburn  1804:     }
                   1805:     if ($ulsout eq '') { $ulsout='empty'; }
                   1806:     &Reply($client, \$ulsout, $userinput); # This supports debug logging.
                   1807:     return 1;
1.399     raeburn  1808: }
                   1809: &register_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280     matthew  1810: 
1.477     raeburn  1811: sub read_lonnet_global {
                   1812:     my ($cmd,$tail,$client) = @_;
                   1813:     my $userinput = "$cmd:$tail";
                   1814:     my $requested = &Apache::lonnet::thaw_unescape($tail);
                   1815:     my $result;
1.480     raeburn  1816:     my %packagevars = (
                   1817:                         spareid => \%Apache::lonnet::spareid,
                   1818:                         perlvar => \%Apache::lonnet::perlvar,
                   1819:                       );
                   1820:     my %limit_to = (
                   1821:                     perlvar => {
                   1822:                                  lonOtherAuthen => 1,
                   1823:                                  lonBalancer    => 1,
                   1824:                                  lonVersion     => 1,
                   1825:                                  lonSysEMail    => 1,
                   1826:                                  lonHostID      => 1,
                   1827:                                  lonRole        => 1,
                   1828:                                  lonDefDomain   => 1,
                   1829:                                  lonLoadLim     => 1,
                   1830:                                  lonUserLoadLim => 1,
                   1831:                                }
                   1832:                   );
1.477     raeburn  1833:     if (ref($requested) eq 'HASH') {
                   1834:         foreach my $what (keys(%{$requested})) {
                   1835:             my $response;
1.480     raeburn  1836:             my $items = {};
                   1837:             if (exists($packagevars{$what})) {
                   1838:                 if (ref($limit_to{$what}) eq 'HASH') {
                   1839:                     foreach my $varname (keys(%{$packagevars{$what}})) {
                   1840:                         if ($limit_to{$what}{$varname}) {
                   1841:                             $items->{$varname} = $packagevars{$what}{$varname};
                   1842:                         }
                   1843:                     }
                   1844:                 } else {
                   1845:                     $items = $packagevars{$what};
1.477     raeburn  1846:                 }
1.480     raeburn  1847:                 if ($what eq 'perlvar') {
                   1848:                     if (!exists($packagevars{$what}{'lonBalancer'})) {
                   1849:                         if ($dist =~ /^(centos|rhes|fedora|scientific)/) {
                   1850:                             my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
                   1851:                             if (ref($othervarref) eq 'HASH') {
                   1852:                                 $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
                   1853:                             }
                   1854:                         }
                   1855:                     }
1.477     raeburn  1856:                 }
1.480     raeburn  1857:                 $response = &Apache::lonnet::freeze_escape($items);
1.477     raeburn  1858:             }
1.478     raeburn  1859:             $result .= &escape($what).'='.$response.'&';
1.477     raeburn  1860:         }
                   1861:     }
                   1862:     $result =~ s/\&$//;
                   1863:     &Reply($client,\$result,$userinput);
                   1864:     return 1;
                   1865: }
                   1866: &register_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
                   1867: 
1.479     raeburn  1868: sub server_devalidatecache_handler {
                   1869:     my ($cmd,$tail,$client) = @_;
                   1870:     my $userinput = "$cmd:$tail";
1.503     raeburn  1871:     my $items = &unescape($tail);
                   1872:     my @cached = split(/\&/,$items);
                   1873:     foreach my $key (@cached) {
                   1874:         if ($key =~ /:/) {
                   1875:             my ($name,$id) = map { &unescape($_); } split(/:/,$key);
                   1876:             &Apache::lonnet::devalidate_cache_new($name,$id);
                   1877:         }
                   1878:     }
1.479     raeburn  1879:     my $result = 'ok';
                   1880:     &Reply($client,\$result,$userinput);
                   1881:     return 1;
                   1882: }
1.481     raeburn  1883: &register_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479     raeburn  1884: 
1.410     raeburn  1885: sub server_timezone_handler {
                   1886:     my ($cmd,$tail,$client) = @_;
                   1887:     my $userinput = "$cmd:$tail";
                   1888:     my $timezone;
                   1889:     my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
                   1890:     my $tzfile = '/etc/timezone'; # Debian/Ubuntu
                   1891:     if (-e $clockfile) {
                   1892:         if (open(my $fh,"<$clockfile")) {
                   1893:             while (<$fh>) {
                   1894:                 next if (/^[\#\s]/);
                   1895:                 if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
                   1896:                     $timezone = $1;
                   1897:                     last;
                   1898:                 }
                   1899:             }
                   1900:             close($fh);
                   1901:         }
                   1902:     } elsif (-e $tzfile) {
                   1903:         if (open(my $fh,"<$tzfile")) {
                   1904:             $timezone = <$fh>;
                   1905:             close($fh);
                   1906:             chomp($timezone);
                   1907:             if ($timezone =~ m{^Etc/(\w+)$}) {
                   1908:                 $timezone = $1;
                   1909:             }
                   1910:         }
                   1911:     }
                   1912:     &Reply($client,\$timezone,$userinput); # This supports debug logging.
                   1913:     return 1;
                   1914: }
                   1915: &register_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
                   1916: 
1.413     raeburn  1917: sub server_loncaparev_handler {
                   1918:     my ($cmd,$tail,$client) = @_;
                   1919:     my $userinput = "$cmd:$tail";
                   1920:     &Reply($client,\$perlvar{'lonVersion'},$userinput);
                   1921:     return 1;
                   1922: }
                   1923: &register_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
                   1924: 
1.448     raeburn  1925: sub server_homeID_handler {
                   1926:     my ($cmd,$tail,$client) = @_;
                   1927:     my $userinput = "$cmd:$tail";
                   1928:     &Reply($client,\$perlvar{'lonHostID'},$userinput);
                   1929:     return 1;
                   1930: }
                   1931: &register_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
                   1932: 
1.471     raeburn  1933: sub server_distarch_handler {
                   1934:     my ($cmd,$tail,$client) = @_;
                   1935:     my $userinput = "$cmd:$tail";
                   1936:     my $reply = &distro_and_arch();
                   1937:     &Reply($client,\$reply,$userinput);
                   1938:     return 1;
                   1939: }
                   1940: &register_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
                   1941: 
1.523     raeburn  1942: sub server_certs_handler {
                   1943:     my ($cmd,$tail,$client) = @_;
                   1944:     my $userinput = "$cmd:$tail";
                   1945:     my $result;
                   1946:     my $result = &LONCAPA::Lond::server_certs(\%perlvar);
                   1947:     &Reply($client,\$result,$userinput);
                   1948:     return;
                   1949: }
                   1950: &register_handler("servercerts", \&server_certs_handler, 0, 1, 0);
                   1951: 
1.218     foxr     1952: #   Process a reinit request.  Reinit requests that either
                   1953: #   lonc or lond be reinitialized so that an updated 
                   1954: #   host.tab or domain.tab can be processed.
                   1955: #
                   1956: # Parameters:
                   1957: #      $cmd    - the actual keyword that invoked us.
                   1958: #      $tail   - the tail of the request that invoked us.
                   1959: #      $client - File descriptor connected to the client
                   1960: #  Returns:
                   1961: #      1       - Ok to continue processing.
                   1962: #      0       - Program should exit
                   1963: #  Implicit output:
                   1964: #     a reply is sent to the client.
                   1965: #
                   1966: sub reinit_process_handler {
                   1967:     my ($cmd, $tail, $client) = @_;
                   1968:    
                   1969:     my $userinput = "$cmd:$tail";
                   1970:    
                   1971:     my $cert = &GetCertificate($userinput);
                   1972:     if(&ValidManager($cert)) {
                   1973: 	chomp($userinput);
                   1974: 	my $reply = &ReinitProcess($userinput);
1.387     albertel 1975: 	&Reply( $client,  \$reply, $userinput);
1.218     foxr     1976:     } else {
                   1977: 	&Failure( $client, "refused\n", $userinput);
                   1978:     }
                   1979:     return 1;
                   1980: }
                   1981: &register_handler("reinit", \&reinit_process_handler, 1, 0, 1);
                   1982: 
                   1983: #  Process the editing script for a table edit operation.
                   1984: #  the editing operation must be encrypted and requested by
                   1985: #  a manager host.
                   1986: #
                   1987: # Parameters:
                   1988: #      $cmd    - the actual keyword that invoked us.
                   1989: #      $tail   - the tail of the request that invoked us.
                   1990: #      $client - File descriptor connected to the client
                   1991: #  Returns:
                   1992: #      1       - Ok to continue processing.
                   1993: #      0       - Program should exit
                   1994: #  Implicit output:
                   1995: #     a reply is sent to the client.
                   1996: #
                   1997: sub edit_table_handler {
                   1998:     my ($command, $tail, $client) = @_;
                   1999:    
                   2000:     my $userinput = "$command:$tail";
                   2001: 
                   2002:     my $cert = &GetCertificate($userinput);
                   2003:     if(&ValidManager($cert)) {
                   2004: 	my($filetype, $script) = split(/:/, $tail);
                   2005: 	if (($filetype eq "hosts") || 
                   2006: 	    ($filetype eq "domain")) {
                   2007: 	    if($script ne "") {
                   2008: 		&Reply($client,              # BUGBUG - EditFile
                   2009: 		      &EditFile($userinput), #   could fail.
                   2010: 		      $userinput);
                   2011: 	    } else {
                   2012: 		&Failure($client,"refused\n",$userinput);
                   2013: 	    }
                   2014: 	} else {
                   2015: 	    &Failure($client,"refused\n",$userinput);
                   2016: 	}
                   2017:     } else {
                   2018: 	&Failure($client,"refused\n",$userinput);
                   2019:     }
                   2020:     return 1;
                   2021: }
1.263     albertel 2022: &register_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218     foxr     2023: 
1.220     foxr     2024: #
                   2025: #   Authenticate a user against the LonCAPA authentication
                   2026: #   database.  Note that there are several authentication
                   2027: #   possibilities:
                   2028: #   - unix     - The user can be authenticated against the unix
                   2029: #                password file.
                   2030: #   - internal - The user can be authenticated against a purely 
                   2031: #                internal per user password file.
                   2032: #   - kerberos - The user can be authenticated against either a kerb4 or kerb5
                   2033: #                ticket granting authority.
                   2034: #   - user     - The person tailoring LonCAPA can supply a user authentication
                   2035: #                mechanism that is per system.
                   2036: #
                   2037: # Parameters:
                   2038: #    $cmd      - The command that got us here.
                   2039: #    $tail     - Tail of the command (remaining parameters).
                   2040: #    $client   - File descriptor connected to client.
                   2041: # Returns
                   2042: #     0        - Requested to exit, caller should shut down.
                   2043: #     1        - Continue processing.
                   2044: # Implicit inputs:
                   2045: #    The authentication systems describe above have their own forms of implicit
                   2046: #    input into the authentication process that are described above.
                   2047: #
                   2048: sub authenticate_handler {
                   2049:     my ($cmd, $tail, $client) = @_;
                   2050: 
                   2051:     
                   2052:     #  Regenerate the full input line 
                   2053:     
                   2054:     my $userinput  = $cmd.":".$tail;
                   2055:     
                   2056:     #  udom    - User's domain.
                   2057:     #  uname   - Username.
                   2058:     #  upass   - User's password.
1.396     raeburn  2059:     #  checkdefauth - Pass to validate_user() to try authentication
                   2060:     #                 with default auth type(s) if no user account.
1.447     raeburn  2061:     #  clientcancheckhost - Passed by clients with functionality in lonauth.pm
                   2062:     #                       to check if session can be hosted.
1.220     foxr     2063:     
1.447     raeburn  2064:     my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399     raeburn  2065:     &Debug(" Authenticate domain = $udom, user = $uname, password = $upass,  checkdefauth = $checkdefauth");
1.220     foxr     2066:     chomp($upass);
                   2067:     $upass=&unescape($upass);
                   2068: 
1.396     raeburn  2069:     my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220     foxr     2070:     if($pwdcorrect) {
1.447     raeburn  2071:         my $canhost = 1;
                   2072:         unless ($clientcancheckhost) {
1.448     raeburn  2073:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   2074:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452     raeburn  2075:             my @intdoms;
                   2076:             my $internet_names = &Apache::lonnet::get_internet_names($clientname);
                   2077:             if (ref($internet_names) eq 'ARRAY') {
                   2078:                 @intdoms = @{$internet_names};
                   2079:             }
1.448     raeburn  2080:             unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447     raeburn  2081:                 my ($remote,$hosted);
                   2082:                 my $remotesession = &get_usersession_config($udom,'remotesession');
                   2083:                 if (ref($remotesession) eq 'HASH') {
1.525     raeburn  2084:                     $remote = $remotesession->{'remote'};
1.447     raeburn  2085:                 }
1.448     raeburn  2086:                 my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447     raeburn  2087:                 if (ref($hostedsession) eq 'HASH') {
                   2088:                     $hosted = $hostedsession->{'hosted'};
                   2089:                 }
1.448     raeburn  2090:                 $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492     droeschl 2091:                                                              $clientversion,
1.447     raeburn  2092:                                                              $remote,$hosted);
                   2093:             }
                   2094:         }
                   2095:         if ($canhost) {               
                   2096:             &Reply( $client, "authorized\n", $userinput);
                   2097:         } else {
                   2098:             &Reply( $client, "not_allowed_to_host\n", $userinput);
                   2099:         }
1.220     foxr     2100: 	#
                   2101: 	#  Bad credentials: Failed to authorize
                   2102: 	#
                   2103:     } else {
                   2104: 	&Failure( $client, "non_authorized\n", $userinput);
                   2105:     }
                   2106: 
                   2107:     return 1;
                   2108: }
1.263     albertel 2109: &register_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214     foxr     2110: 
1.222     foxr     2111: #
                   2112: #   Change a user's password.  Note that this function is complicated by
                   2113: #   the fact that a user may be authenticated in more than one way:
                   2114: #   At present, we are not able to change the password for all types of
                   2115: #   authentication methods.  Only for:
                   2116: #      unix    - unix password or shadow passoword style authentication.
                   2117: #      local   - Locally written authentication mechanism.
                   2118: #   For now, kerb4 and kerb5 password changes are not supported and result
                   2119: #   in an error.
                   2120: # FUTURE WORK:
                   2121: #    Support kerberos passwd changes?
                   2122: # Parameters:
                   2123: #    $cmd      - The command that got us here.
                   2124: #    $tail     - Tail of the command (remaining parameters).
                   2125: #    $client   - File descriptor connected to client.
                   2126: # Returns
                   2127: #     0        - Requested to exit, caller should shut down.
                   2128: #     1        - Continue processing.
                   2129: # Implicit inputs:
                   2130: #    The authentication systems describe above have their own forms of implicit
                   2131: #    input into the authentication process that are described above.
                   2132: sub change_password_handler {
                   2133:     my ($cmd, $tail, $client) = @_;
                   2134: 
                   2135:     my $userinput = $cmd.":".$tail;           # Reconstruct client's string.
                   2136: 
                   2137:     #
                   2138:     #  udom  - user's domain.
                   2139:     #  uname - Username.
                   2140:     #  upass - Current password.
                   2141:     #  npass - New password.
1.346     raeburn  2142:     #  context - Context in which this was called 
                   2143:     #            (preferences or reset_by_email).
1.428     raeburn  2144:     #  lonhost - HostID of server where request originated 
1.222     foxr     2145:    
1.428     raeburn  2146:     my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222     foxr     2147: 
                   2148:     $upass=&unescape($upass);
                   2149:     $npass=&unescape($npass);
                   2150:     &Debug("Trying to change password for $uname");
                   2151: 
                   2152:     # First require that the user can be authenticated with their
1.346     raeburn  2153:     # old password unless context was 'reset_by_email':
                   2154:     
1.428     raeburn  2155:     my ($validated,$failure);
1.346     raeburn  2156:     if ($context eq 'reset_by_email') {
1.428     raeburn  2157:         if ($lonhost eq '') {
                   2158:             $failure = 'invalid_client';
                   2159:         } else {
                   2160:             $validated = 1;
                   2161:         }
1.346     raeburn  2162:     } else {
                   2163:         $validated = &validate_user($udom, $uname, $upass);
                   2164:     }
1.222     foxr     2165:     if($validated) {
                   2166: 	my $realpasswd  = &get_auth_type($udom, $uname); # Defined since authd.
                   2167: 	
                   2168: 	my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
                   2169: 	if ($howpwd eq 'internal') {
                   2170: 	    &Debug("internal auth");
1.518     raeburn  2171:             my $ncpass = &hash_passwd($udom,$npass);
1.222     foxr     2172: 	    if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428     raeburn  2173: 		my $msg="Result of password change for $uname: pwchange_success";
                   2174:                 if ($lonhost) {
                   2175:                     $msg .= " - request originated from: $lonhost";
                   2176:                 }
                   2177:                 &logthis($msg);
1.518     raeburn  2178:                 &update_passwd_history($uname,$udom,$howpwd,$context);
1.222     foxr     2179: 		&Reply($client, "ok\n", $userinput);
                   2180: 	    } else {
                   2181: 		&logthis("Unable to open $uname passwd "               
                   2182: 			 ."to change password");
                   2183: 		&Failure( $client, "non_authorized\n",$userinput);
                   2184: 	    }
1.346     raeburn  2185: 	} elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287     foxr     2186: 	    my $result = &change_unix_password($uname, $npass);
1.518     raeburn  2187:             if ($result eq 'ok') {
                   2188:                 &update_passwd_history($uname,$udom,$howpwd,$context);
                   2189:              }
1.222     foxr     2190: 	    &logthis("Result of password change for $uname: ".
1.287     foxr     2191: 		     $result);
1.387     albertel 2192: 	    &Reply($client, \$result, $userinput);
1.222     foxr     2193: 	} else {
                   2194: 	    # this just means that the current password mode is not
                   2195: 	    # one we know how to change (e.g the kerberos auth modes or
                   2196: 	    # locally written auth handler).
                   2197: 	    #
                   2198: 	    &Failure( $client, "auth_mode_error\n", $userinput);
                   2199: 	}  
                   2200: 	
1.224     foxr     2201:     } else {
1.428     raeburn  2202: 	if ($failure eq '') {
                   2203: 	    $failure = 'non_authorized';
                   2204: 	}
                   2205: 	&Failure( $client, "$failure\n", $userinput);
1.222     foxr     2206:     }
                   2207: 
                   2208:     return 1;
                   2209: }
1.263     albertel 2210: &register_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222     foxr     2211: 
1.518     raeburn  2212: sub hash_passwd {
                   2213:     my ($domain,$plainpass,@rest) = @_;
                   2214:     my ($salt,$cost);
                   2215:     if (@rest) {
                   2216:         $cost = $rest[0];
                   2217:         # salt is first 22 characters, base-64 encoded by bcrypt
                   2218:         my $plainsalt = substr($rest[1],0,22);
                   2219:         $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
                   2220:     } else {
                   2221:         my $defaultcost;
                   2222:         my %domconfig =
                   2223:             &Apache::lonnet::get_dom('configuration',['password'],$domain);
                   2224:         if (ref($domconfig{'password'}) eq 'HASH') {
                   2225:             $defaultcost = $domconfig{'password'}{'cost'};
                   2226:         }
                   2227:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   2228:             $cost = 10;
                   2229:         } else {
                   2230:             $cost = $defaultcost;
                   2231:         }
                   2232:         # Generate random 16-octet base64 salt
                   2233:         $salt = "";
                   2234:         $salt .= pack("C", int rand(256)) for 1..16;
                   2235:     }
                   2236:     my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
                   2237:         key_nul => 1,
                   2238:         cost    => $cost,
                   2239:         salt    => $salt,
                   2240:     }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
                   2241: 
                   2242:     my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
                   2243:                 &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
                   2244:                 &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
                   2245:     return $result;
                   2246: }
                   2247: 
1.225     foxr     2248: #
                   2249: #   Create a new user.  User in this case means a lon-capa user.
                   2250: #   The user must either already exist in some authentication realm
                   2251: #   like kerberos or the /etc/passwd.  If not, a user completely local to
                   2252: #   this loncapa system is created.
                   2253: #
                   2254: # Parameters:
                   2255: #    $cmd      - The command that got us here.
                   2256: #    $tail     - Tail of the command (remaining parameters).
                   2257: #    $client   - File descriptor connected to client.
                   2258: # Returns
                   2259: #     0        - Requested to exit, caller should shut down.
                   2260: #     1        - Continue processing.
                   2261: # Implicit inputs:
                   2262: #    The authentication systems describe above have their own forms of implicit
                   2263: #    input into the authentication process that are described above.
                   2264: sub add_user_handler {
                   2265: 
                   2266:     my ($cmd, $tail, $client) = @_;
                   2267: 
                   2268: 
                   2269:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2270:     my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
                   2271: 
                   2272:     &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
                   2273: 
                   2274: 
                   2275:     if($udom eq $currentdomainid) { # Reject new users for other domains...
                   2276: 	
                   2277: 	my $oldumask=umask(0077);
                   2278: 	chomp($npass);
                   2279: 	$npass=&unescape($npass);
                   2280: 	my $passfilename  = &password_path($udom, $uname);
                   2281: 	&Debug("Password file created will be:".$passfilename);
                   2282: 	if (-e $passfilename) {
                   2283: 	    &Failure( $client, "already_exists\n", $userinput);
                   2284: 	} else {
                   2285: 	    my $fperror='';
1.264     albertel 2286: 	    if (!&mkpath($passfilename)) {
                   2287: 		$fperror="error: ".($!+0)." mkdir failed while attempting "
                   2288: 		    ."makeuser";
1.225     foxr     2289: 	    }
                   2290: 	    unless ($fperror) {
1.518     raeburn  2291: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2292:                                              $passfilename,'makeuser');
1.390     raeburn  2293: 		&Reply($client,\$result, $userinput);     #BUGBUG - could be fail
1.225     foxr     2294: 	    } else {
1.387     albertel 2295: 		&Failure($client, \$fperror, $userinput);
1.225     foxr     2296: 	    }
                   2297: 	}
                   2298: 	umask($oldumask);
                   2299:     }  else {
                   2300: 	&Failure($client, "not_right_domain\n",
                   2301: 		$userinput);	# Even if we are multihomed.
                   2302:     
                   2303:     }
                   2304:     return 1;
                   2305: 
                   2306: }
                   2307: &register_handler("makeuser", \&add_user_handler, 1, 1, 0);
                   2308: 
                   2309: #
                   2310: #   Change the authentication method of a user.  Note that this may
                   2311: #   also implicitly change the user's password if, for example, the user is
                   2312: #   joining an existing authentication realm.  Known authentication realms at
                   2313: #   this time are:
                   2314: #    internal   - Purely internal password file (only loncapa knows this user)
                   2315: #    local      - Institutionally written authentication module.
                   2316: #    unix       - Unix user (/etc/passwd with or without /etc/shadow).
                   2317: #    kerb4      - kerberos version 4
                   2318: #    kerb5      - kerberos version 5
                   2319: #
                   2320: # Parameters:
                   2321: #    $cmd      - The command that got us here.
                   2322: #    $tail     - Tail of the command (remaining parameters).
                   2323: #    $client   - File descriptor connected to client.
                   2324: # Returns
                   2325: #     0        - Requested to exit, caller should shut down.
                   2326: #     1        - Continue processing.
                   2327: # Implicit inputs:
                   2328: #    The authentication systems describe above have their own forms of implicit
                   2329: #    input into the authentication process that are described above.
1.287     foxr     2330: # NOTE:
                   2331: #   This is also used to change the authentication credential values (e.g. passwd).
                   2332: #   
1.225     foxr     2333: #
                   2334: sub change_authentication_handler {
                   2335: 
                   2336:     my ($cmd, $tail, $client) = @_;
                   2337:    
                   2338:     my $userinput  = "$cmd:$tail";              # Reconstruct user input.
                   2339: 
                   2340:     my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
                   2341:     &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
                   2342:     if ($udom ne $currentdomainid) {
                   2343: 	&Failure( $client, "not_right_domain\n", $client);
                   2344:     } else {
                   2345: 	
                   2346: 	chomp($npass);
                   2347: 	
                   2348: 	$npass=&unescape($npass);
1.261     foxr     2349: 	my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225     foxr     2350: 	my $passfilename = &password_path($udom, $uname);
                   2351: 	if ($passfilename) {	# Not allowed to create a new user!!
1.287     foxr     2352: 	    # If just changing the unix passwd. need to arrange to run
1.502     raeburn  2353: 	    # passwd since otherwise make_passwd_file will fail as 
                   2354: 	    # creation of unix authenticated users is no longer supported
                   2355:             # except from the command line, when running make_domain_coordinator.pl
1.287     foxr     2356: 
                   2357: 	    if(($oldauth =~/^unix/) && ($umode eq "unix")) {
                   2358: 		my $result = &change_unix_password($uname, $npass);
                   2359: 		&logthis("Result of password change for $uname: ".$result);
                   2360: 		if ($result eq "ok") {
1.518     raeburn  2361:                     &update_passwd_history($uname,$udom,$umode,'changeuserauth'); 
1.390     raeburn  2362: 		    &Reply($client, \$result);
1.288     albertel 2363: 		} else {
1.387     albertel 2364: 		    &Failure($client, \$result);
1.287     foxr     2365: 		}
1.288     albertel 2366: 	    } else {
1.518     raeburn  2367: 		my $result=&make_passwd_file($uname,$udom,$umode,$npass,
                   2368:                                              $passfilename,'changeuserauth');
1.287     foxr     2369: 		#
                   2370: 		#  If the current auth mode is internal, and the old auth mode was
                   2371: 		#  unix, or krb*,  and the user is an author for this domain,
                   2372: 		#  re-run manage_permissions for that role in order to be able
                   2373: 		#  to take ownership of the construction space back to www:www
                   2374: 		#
1.502     raeburn  2375: 
                   2376: 
1.387     albertel 2377: 		&Reply($client, \$result, $userinput);
1.261     foxr     2378: 	    }
                   2379: 	       
                   2380: 
1.225     foxr     2381: 	} else {	       
1.251     foxr     2382: 	    &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225     foxr     2383: 	}
                   2384:     }
                   2385:     return 1;
                   2386: }
                   2387: &register_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
                   2388: 
1.518     raeburn  2389: sub update_passwd_history {
                   2390:     my ($uname,$udom,$umode,$context) = @_;
                   2391:     my $proname=&propath($udom,$uname);
                   2392:     my $now = time;
                   2393:     if (open(my $fh,">>$proname/passwd.log")) {
                   2394:         print $fh "$now:$umode:$context\n";
                   2395:         close($fh);
                   2396:     }
                   2397:     return;
                   2398: }
                   2399: 
1.225     foxr     2400: #
                   2401: #   Determines if this is the home server for a user.  The home server
                   2402: #   for a user will have his/her lon-capa passwd file.  Therefore all we need
                   2403: #   to do is determine if this file exists.
                   2404: #
                   2405: # Parameters:
                   2406: #    $cmd      - The command that got us here.
                   2407: #    $tail     - Tail of the command (remaining parameters).
                   2408: #    $client   - File descriptor connected to client.
                   2409: # Returns
                   2410: #     0        - Requested to exit, caller should shut down.
                   2411: #     1        - Continue processing.
                   2412: # Implicit inputs:
                   2413: #    The authentication systems describe above have their own forms of implicit
                   2414: #    input into the authentication process that are described above.
                   2415: #
                   2416: sub is_home_handler {
                   2417:     my ($cmd, $tail, $client) = @_;
                   2418:    
                   2419:     my $userinput  = "$cmd:$tail";
                   2420:    
                   2421:     my ($udom,$uname)=split(/:/,$tail);
                   2422:     chomp($uname);
                   2423:     my $passfile = &password_filename($udom, $uname);
                   2424:     if($passfile) {
                   2425: 	&Reply( $client, "found\n", $userinput);
                   2426:     } else {
                   2427: 	&Failure($client, "not_found\n", $userinput);
                   2428:     }
                   2429:     return 1;
                   2430: }
                   2431: &register_handler("home", \&is_home_handler, 0,1,0);
                   2432: 
                   2433: #
1.434     www      2434: #   Process an update request for a resource.
                   2435: #   A resource has been modified that we hold a subscription to.
1.225     foxr     2436: #   If the resource is not local, then we must update, or at least invalidate our
                   2437: #   cached copy of the resource. 
                   2438: # Parameters:
                   2439: #    $cmd      - The command that got us here.
                   2440: #    $tail     - Tail of the command (remaining parameters).
                   2441: #    $client   - File descriptor connected to client.
                   2442: # Returns
                   2443: #     0        - Requested to exit, caller should shut down.
                   2444: #     1        - Continue processing.
                   2445: # Implicit inputs:
                   2446: #    The authentication systems describe above have their own forms of implicit
                   2447: #    input into the authentication process that are described above.
                   2448: #
                   2449: sub update_resource_handler {
                   2450: 
                   2451:     my ($cmd, $tail, $client) = @_;
                   2452:    
                   2453:     my $userinput = "$cmd:$tail";
                   2454:    
                   2455:     my $fname= $tail;		# This allows interactive testing
                   2456: 
                   2457: 
                   2458:     my $ownership=ishome($fname);
                   2459:     if ($ownership eq 'not_owner') {
                   2460: 	if (-e $fname) {
1.434     www      2461:             # Delete preview file, if exists
                   2462:             unlink("$fname.tmp");
                   2463:             # Get usage stats
1.225     foxr     2464: 	    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
                   2465: 		$atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
                   2466: 	    my $now=time;
                   2467: 	    my $since=$now-$atime;
1.434     www      2468:             # If the file has not been used within lonExpire seconds,
                   2469:             # unsubscribe from it and delete local copy
1.225     foxr     2470: 	    if ($since>$perlvar{'lonExpire'}) {
1.365     albertel 2471: 		my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308     albertel 2472: 		&devalidate_meta_cache($fname);
1.225     foxr     2473: 		unlink("$fname");
1.334     albertel 2474: 		unlink("$fname.meta");
1.225     foxr     2475: 	    } else {
1.434     www      2476:             # Yes, this is in active use. Get a fresh copy. Since it might be in
                   2477:             # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225     foxr     2478: 		my $transname="$fname.in.transfer";
1.365     albertel 2479: 		my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225     foxr     2480: 		my $response;
1.455     www      2481: # FIXME: cannot replicate files that take more than two minutes to transfer?
                   2482: #		alarm(120);
                   2483: # FIXME: this should use the LWP mechanism, not internal alarms.
                   2484:                 alarm(1200);
1.225     foxr     2485: 		{
                   2486: 		    my $request=new HTTP::Request('GET',"$remoteurl");
1.523     raeburn  2487:                     $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225     foxr     2488: 		}
                   2489: 		alarm(0);
                   2490: 		if ($response->is_error()) {
1.455     www      2491: # FIXME: we should probably clean up here instead of just whine
1.225     foxr     2492: 		    unlink($transname);
                   2493: 		    my $message=$response->status_line;
                   2494: 		    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2495: 		} else {
                   2496: 		    if ($remoteurl!~/\.meta$/) {
1.455     www      2497: # FIXME: isn't there an internal LWP mechanism for this?
1.225     foxr     2498: 			alarm(120);
                   2499: 			{
                   2500: 			    my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.523     raeburn  2501:                             my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
1.225     foxr     2502: 			    if ($mresponse->is_error()) {
                   2503: 				unlink($fname.'.meta');
                   2504: 			    }
                   2505: 			}
                   2506: 			alarm(0);
                   2507: 		    }
1.434     www      2508:                     # we successfully transfered, copy file over to real name
1.225     foxr     2509: 		    rename($transname,$fname);
1.308     albertel 2510: 		    &devalidate_meta_cache($fname);
1.225     foxr     2511: 		}
                   2512: 	    }
                   2513: 	    &Reply( $client, "ok\n", $userinput);
                   2514: 	} else {
                   2515: 	    &Failure($client, "not_found\n", $userinput);
                   2516: 	}
                   2517:     } else {
                   2518: 	&Failure($client, "rejected\n", $userinput);
                   2519:     }
                   2520:     return 1;
                   2521: }
                   2522: &register_handler("update", \&update_resource_handler, 0 ,1, 0);
                   2523: 
1.308     albertel 2524: sub devalidate_meta_cache {
                   2525:     my ($url) = @_;
                   2526:     use Cache::Memcached;
                   2527:     my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365     albertel 2528:     $url = &Apache::lonnet::declutter($url);
1.308     albertel 2529:     $url =~ s-\.meta$--;
                   2530:     my $id = &escape('meta:'.$url);
                   2531:     $memcache->delete($id);
                   2532: }
                   2533: 
1.225     foxr     2534: #
1.226     foxr     2535: #   Fetch a user file from a remote server to the user's home directory
                   2536: #   userfiles subdir.
1.225     foxr     2537: # Parameters:
                   2538: #    $cmd      - The command that got us here.
                   2539: #    $tail     - Tail of the command (remaining parameters).
                   2540: #    $client   - File descriptor connected to client.
                   2541: # Returns
                   2542: #     0        - Requested to exit, caller should shut down.
                   2543: #     1        - Continue processing.
                   2544: #
                   2545: sub fetch_user_file_handler {
                   2546: 
                   2547:     my ($cmd, $tail, $client) = @_;
                   2548: 
                   2549:     my $userinput = "$cmd:$tail";
                   2550:     my $fname           = $tail;
1.232     foxr     2551:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225     foxr     2552:     my $udir=&propath($udom,$uname).'/userfiles';
                   2553:     unless (-e $udir) {
                   2554: 	mkdir($udir,0770); 
                   2555:     }
1.232     foxr     2556:     Debug("fetch user file for $fname");
1.225     foxr     2557:     if (-e $udir) {
                   2558: 	$ufile=~s/^[\.\~]+//;
1.232     foxr     2559: 
                   2560: 	# IF necessary, create the path right down to the file.
                   2561: 	# Note that any regular files in the way of this path are
                   2562: 	# wiped out to deal with some earlier folly of mine.
                   2563: 
1.267     raeburn  2564: 	if (!&mkpath($udir.'/'.$ufile)) {
1.264     albertel 2565: 	    &Failure($client, "unable_to_create\n", $userinput);	    
1.232     foxr     2566: 	}
                   2567: 
1.225     foxr     2568: 	my $destname=$udir.'/'.$ufile;
                   2569: 	my $transname=$udir.'/'.$ufile.'.in.transit';
1.476     raeburn  2570:         my $clientprotocol=$Apache::lonnet::protocol{$clientname};
                   2571:         $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486     raeburn  2572: 	my $clienthost = &Apache::lonnet::hostname($clientname);
                   2573: 	my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225     foxr     2574: 	my $response;
1.232     foxr     2575: 	Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.523     raeburn  2576: 	alarm(1200);
1.225     foxr     2577: 	{
                   2578: 	    my $request=new HTTP::Request('GET',"$remoteurl");
1.523     raeburn  2579:             my $verifycert = 1;
                   2580:             my @machine_ids = &Apache::lonnet::current_machine_ids();
                   2581:             if (grep(/^\Q$clientname\E$/,@machine_ids)) {
                   2582:                 $verifycert = 0;
                   2583:             }
                   2584:             $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225     foxr     2585: 	}
                   2586: 	alarm(0);
                   2587: 	if ($response->is_error()) {
                   2588: 	    unlink($transname);
                   2589: 	    my $message=$response->status_line;
                   2590: 	    &logthis("LWP GET: $message for $fname ($remoteurl)");
                   2591: 	    &Failure($client, "failed\n", $userinput);
                   2592: 	} else {
1.232     foxr     2593: 	    Debug("Renaming $transname to $destname");
1.225     foxr     2594: 	    if (!rename($transname,$destname)) {
                   2595: 		&logthis("Unable to move $transname to $destname");
                   2596: 		unlink($transname);
                   2597: 		&Failure($client, "failed\n", $userinput);
                   2598: 	    } else {
1.495     raeburn  2599:                 if ($fname =~ /^default.+\.(page|sequence)$/) {
                   2600:                     my ($major,$minor) = split(/\./,$clientversion);
                   2601:                     if (($major < 2) || ($major == 2 && $minor < 11)) {
                   2602:                         my $now = time;
                   2603:                         &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
                   2604:                         my $key = &escape('internal.contentchange');
                   2605:                         my $what = "$key=$now";
                   2606:                         my $hashref = &tie_user_hash($udom,$uname,'environment',
                   2607:                                                      &GDBM_WRCREAT(),"P",$what);
                   2608:                         if ($hashref) {
                   2609:                             $hashref->{$key}=$now;
                   2610:                             if (!&untie_user_hash($hashref)) {
                   2611:                                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   2612:                                          "when updating internal.contentchange");
                   2613:                             }
                   2614:                         }
                   2615:                     }
                   2616:                 }
1.225     foxr     2617: 		&Reply($client, "ok\n", $userinput);
                   2618: 	    }
                   2619: 	}   
                   2620:     } else {
                   2621: 	&Failure($client, "not_home\n", $userinput);
                   2622:     }
                   2623:     return 1;
                   2624: }
                   2625: &register_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
                   2626: 
1.226     foxr     2627: #
                   2628: #   Remove a file from a user's home directory userfiles subdirectory.
                   2629: # Parameters:
                   2630: #    cmd   - the Lond request keyword that got us here.
                   2631: #    tail  - the part of the command past the keyword.
                   2632: #    client- File descriptor connected with the client.
                   2633: #
                   2634: # Returns:
                   2635: #    1    - Continue processing.
                   2636: sub remove_user_file_handler {
                   2637:     my ($cmd, $tail, $client) = @_;
                   2638: 
                   2639:     my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2640: 
                   2641:     my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2642:     if ($ufile =~m|/\.\./|) {
                   2643: 	# any files paths with /../ in them refuse 
                   2644: 	# to deal with
                   2645: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2646:     } else {
                   2647: 	my $udir = &propath($udom,$uname);
                   2648: 	if (-e $udir) {
                   2649: 	    my $file=$udir.'/userfiles/'.$ufile;
                   2650: 	    if (-e $file) {
1.253     foxr     2651: 		#
                   2652: 		#   If the file is a regular file unlink is fine...
1.520     raeburn  2653: 		#   However it's possible the client wants a dir 
                   2654: 		#   removed, in which case rmdir is more appropriate.
                   2655: 		#   Note: rmdir will only remove an empty directory.
1.253     foxr     2656: 		#
1.240     banghart 2657: 	        if (-f $file){
1.241     albertel 2658: 		    unlink($file);
1.520     raeburn  2659:                     # for html files remove the associated .bak file 
                   2660:                     # which may have been created by the editor.
                   2661:                     if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
                   2662:                         my $path = $1;
                   2663:                         if (-e $file.'.bak') {
                   2664:                             unlink($file.'.bak');
                   2665:                         }
                   2666:                     }
1.241     albertel 2667: 		} elsif(-d $file) {
                   2668: 		    rmdir($file);
1.240     banghart 2669: 		}
1.226     foxr     2670: 		if (-e $file) {
1.253     foxr     2671: 		    #  File is still there after we deleted it ?!?
                   2672: 
1.226     foxr     2673: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2674: 		} else {
                   2675: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2676: 		}
                   2677: 	    } else {
                   2678: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2679: 	    }
                   2680: 	} else {
                   2681: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2682: 	}
                   2683:     }
                   2684:     return 1;
                   2685: }
                   2686: &register_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
                   2687: 
1.236     albertel 2688: #
                   2689: #   make a directory in a user's home directory userfiles subdirectory.
                   2690: # Parameters:
                   2691: #    cmd   - the Lond request keyword that got us here.
                   2692: #    tail  - the part of the command past the keyword.
                   2693: #    client- File descriptor connected with the client.
                   2694: #
                   2695: # Returns:
                   2696: #    1    - Continue processing.
                   2697: sub mkdir_user_file_handler {
                   2698:     my ($cmd, $tail, $client) = @_;
                   2699: 
                   2700:     my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
                   2701:     $dir=&unescape($dir);
                   2702:     my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
                   2703:     if ($ufile =~m|/\.\./|) {
                   2704: 	# any files paths with /../ in them refuse 
                   2705: 	# to deal with
                   2706: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2707:     } else {
                   2708: 	my $udir = &propath($udom,$uname);
                   2709: 	if (-e $udir) {
1.264     albertel 2710: 	    my $newdir=$udir.'/userfiles/'.$ufile.'/';
                   2711: 	    if (!&mkpath($newdir)) {
                   2712: 		&Failure($client, "failed\n", "$cmd:$tail");
1.236     albertel 2713: 	    }
1.264     albertel 2714: 	    &Reply($client, "ok\n", "$cmd:$tail");
1.236     albertel 2715: 	} else {
                   2716: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2717: 	}
                   2718:     }
                   2719:     return 1;
                   2720: }
                   2721: &register_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
                   2722: 
1.237     albertel 2723: #
                   2724: #   rename a file in a user's home directory userfiles subdirectory.
                   2725: # Parameters:
                   2726: #    cmd   - the Lond request keyword that got us here.
                   2727: #    tail  - the part of the command past the keyword.
                   2728: #    client- File descriptor connected with the client.
                   2729: #
                   2730: # Returns:
                   2731: #    1    - Continue processing.
                   2732: sub rename_user_file_handler {
                   2733:     my ($cmd, $tail, $client) = @_;
                   2734: 
                   2735:     my ($udom,$uname,$old,$new) = split(/:/, $tail);
                   2736:     $old=&unescape($old);
                   2737:     $new=&unescape($new);
                   2738:     if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
                   2739: 	# any files paths with /../ in them refuse to deal with
                   2740: 	&Failure($client, "refused\n", "$cmd:$tail");
                   2741:     } else {
                   2742: 	my $udir = &propath($udom,$uname);
                   2743: 	if (-e $udir) {
                   2744: 	    my $oldfile=$udir.'/userfiles/'.$old;
                   2745: 	    my $newfile=$udir.'/userfiles/'.$new;
                   2746: 	    if (-e $newfile) {
                   2747: 		&Failure($client, "exists\n", "$cmd:$tail");
                   2748: 	    } elsif (! -e $oldfile) {
                   2749: 		&Failure($client, "not_found\n", "$cmd:$tail");
                   2750: 	    } else {
                   2751: 		if (!rename($oldfile,$newfile)) {
                   2752: 		    &Failure($client, "failed\n", "$cmd:$tail");
                   2753: 		} else {
                   2754: 		    &Reply($client, "ok\n", "$cmd:$tail");
                   2755: 		}
                   2756: 	    }
                   2757: 	} else {
                   2758: 	    &Failure($client, "not_home\n", "$cmd:$tail");
                   2759: 	}
                   2760:     }
                   2761:     return 1;
                   2762: }
                   2763: &register_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
                   2764: 
1.227     foxr     2765: #
1.382     albertel 2766: #  Checks if the specified user has an active session on the server
                   2767: #  return ok if so, not_found if not
                   2768: #
                   2769: # Parameters:
                   2770: #   cmd      - The request keyword that dispatched to tus.
                   2771: #   tail     - The tail of the request (colon separated parameters).
                   2772: #   client   - Filehandle open on the client.
                   2773: # Return:
                   2774: #    1.
                   2775: sub user_has_session_handler {
                   2776:     my ($cmd, $tail, $client) = @_;
                   2777: 
                   2778:     my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
                   2779:     
                   2780:     opendir(DIR,$perlvar{'lonIDsDir'});
                   2781:     my $filename;
                   2782:     while ($filename=readdir(DIR)) {
                   2783: 	last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
                   2784:     }
                   2785:     if ($filename) {
                   2786: 	&Reply($client, "ok\n", "$cmd:$tail");
                   2787:     } else {
                   2788: 	&Failure($client, "not_found\n", "$cmd:$tail");
                   2789:     }
                   2790:     return 1;
                   2791: 
                   2792: }
                   2793: &register_handler("userhassession", \&user_has_session_handler, 0,1,0);
                   2794: 
                   2795: #
1.263     albertel 2796: #  Authenticate access to a user file by checking that the token the user's 
                   2797: #  passed also exists in their session file
1.227     foxr     2798: #
                   2799: # Parameters:
                   2800: #   cmd      - The request keyword that dispatched to tus.
                   2801: #   tail     - The tail of the request (colon separated parameters).
                   2802: #   client   - Filehandle open on the client.
                   2803: # Return:
                   2804: #    1.
                   2805: sub token_auth_user_file_handler {
                   2806:     my ($cmd, $tail, $client) = @_;
                   2807: 
                   2808:     my ($fname, $session) = split(/:/, $tail);
                   2809:     
                   2810:     chomp($session);
1.393     raeburn  2811:     my $reply="non_auth";
1.343     albertel 2812:     my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
                   2813:     if (open(ENVIN,"$file")) {
1.332     albertel 2814: 	flock(ENVIN,LOCK_SH);
1.343     albertel 2815: 	tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
                   2816: 	if (exists($disk_env{"userfile.$fname"})) {
1.393     raeburn  2817: 	    $reply="ok";
1.343     albertel 2818: 	} else {
                   2819: 	    foreach my $envname (keys(%disk_env)) {
                   2820: 		if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393     raeburn  2821: 		    $reply="ok";
1.343     albertel 2822: 		    last;
                   2823: 		}
                   2824: 	    }
1.227     foxr     2825: 	}
1.343     albertel 2826: 	untie(%disk_env);
1.227     foxr     2827: 	close(ENVIN);
1.387     albertel 2828: 	&Reply($client, \$reply, "$cmd:$tail");
1.227     foxr     2829:     } else {
                   2830: 	&Failure($client, "invalid_token\n", "$cmd:$tail");
                   2831:     }
                   2832:     return 1;
                   2833: 
                   2834: }
                   2835: &register_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229     foxr     2836: 
                   2837: #
                   2838: #   Unsubscribe from a resource.
                   2839: #
                   2840: # Parameters:
                   2841: #    $cmd      - The command that got us here.
                   2842: #    $tail     - Tail of the command (remaining parameters).
                   2843: #    $client   - File descriptor connected to client.
                   2844: # Returns
                   2845: #     0        - Requested to exit, caller should shut down.
                   2846: #     1        - Continue processing.
                   2847: #
                   2848: sub unsubscribe_handler {
                   2849:     my ($cmd, $tail, $client) = @_;
                   2850: 
                   2851:     my $userinput= "$cmd:$tail";
                   2852:     
                   2853:     my ($fname) = split(/:/,$tail); # Split in case there's extrs.
                   2854: 
                   2855:     &Debug("Unsubscribing $fname");
                   2856:     if (-e $fname) {
                   2857: 	&Debug("Exists");
                   2858: 	&Reply($client, &unsub($fname,$clientip), $userinput);
                   2859:     } else {
                   2860: 	&Failure($client, "not_found\n", $userinput);
                   2861:     }
                   2862:     return 1;
                   2863: }
                   2864: &register_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263     albertel 2865: 
1.230     foxr     2866: #   Subscribe to a resource
                   2867: #
                   2868: # Parameters:
                   2869: #    $cmd      - The command that got us here.
                   2870: #    $tail     - Tail of the command (remaining parameters).
                   2871: #    $client   - File descriptor connected to client.
                   2872: # Returns
                   2873: #     0        - Requested to exit, caller should shut down.
                   2874: #     1        - Continue processing.
                   2875: #
                   2876: sub subscribe_handler {
                   2877:     my ($cmd, $tail, $client)= @_;
                   2878: 
                   2879:     my $userinput  = "$cmd:$tail";
                   2880: 
                   2881:     &Reply( $client, &subscribe($userinput,$clientip), $userinput);
                   2882: 
                   2883:     return 1;
                   2884: }
                   2885: &register_handler("sub", \&subscribe_handler, 0, 1, 0);
                   2886: 
                   2887: #
1.379     albertel 2888: #   Determine the latest version of a resource (it looks for the highest
                   2889: #   past version and then returns that +1)
1.230     foxr     2890: #
                   2891: # Parameters:
                   2892: #    $cmd      - The command that got us here.
                   2893: #    $tail     - Tail of the command (remaining parameters).
1.379     albertel 2894: #                 (Should consist of an absolute path to a file)
1.230     foxr     2895: #    $client   - File descriptor connected to client.
                   2896: # Returns
                   2897: #     0        - Requested to exit, caller should shut down.
                   2898: #     1        - Continue processing.
                   2899: #
                   2900: sub current_version_handler {
                   2901:     my ($cmd, $tail, $client) = @_;
                   2902: 
                   2903:     my $userinput= "$cmd:$tail";
                   2904:    
                   2905:     my $fname   = $tail;
                   2906:     &Reply( $client, &currentversion($fname)."\n", $userinput);
                   2907:     return 1;
                   2908: 
                   2909: }
                   2910: &register_handler("currentversion", \&current_version_handler, 0, 1, 0);
                   2911: 
                   2912: #  Make an entry in a user's activity log.
                   2913: #
                   2914: # Parameters:
                   2915: #    $cmd      - The command that got us here.
                   2916: #    $tail     - Tail of the command (remaining parameters).
                   2917: #    $client   - File descriptor connected to client.
                   2918: # Returns
                   2919: #     0        - Requested to exit, caller should shut down.
                   2920: #     1        - Continue processing.
                   2921: #
                   2922: sub activity_log_handler {
                   2923:     my ($cmd, $tail, $client) = @_;
                   2924: 
                   2925: 
                   2926:     my $userinput= "$cmd:$tail";
                   2927: 
                   2928:     my ($udom,$uname,$what)=split(/:/,$tail);
                   2929:     chomp($what);
                   2930:     my $proname=&propath($udom,$uname);
                   2931:     my $now=time;
                   2932:     my $hfh;
                   2933:     if ($hfh=IO::File->new(">>$proname/activity.log")) { 
                   2934: 	print $hfh "$now:$clientname:$what\n";
                   2935: 	&Reply( $client, "ok\n", $userinput); 
                   2936:     } else {
                   2937: 	&Failure($client, "error: ".($!+0)." IO::File->new Failed "
                   2938: 		 ."while attempting log\n", 
                   2939: 		 $userinput);
                   2940:     }
                   2941: 
                   2942:     return 1;
                   2943: }
1.263     albertel 2944: &register_handler("log", \&activity_log_handler, 0, 1, 0);
1.230     foxr     2945: 
                   2946: #
                   2947: #   Put a namespace entry in a user profile hash.
                   2948: #   My druthers would be for this to be an encrypted interaction too.
                   2949: #   anything that might be an inadvertent covert channel about either
                   2950: #   user authentication or user personal information....
                   2951: #
                   2952: # Parameters:
                   2953: #    $cmd      - The command that got us here.
                   2954: #    $tail     - Tail of the command (remaining parameters).
                   2955: #    $client   - File descriptor connected to client.
                   2956: # Returns
                   2957: #     0        - Requested to exit, caller should shut down.
                   2958: #     1        - Continue processing.
                   2959: #
                   2960: sub put_user_profile_entry {
                   2961:     my ($cmd, $tail, $client)  = @_;
1.229     foxr     2962: 
1.230     foxr     2963:     my $userinput = "$cmd:$tail";
                   2964:     
1.242     raeburn  2965:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230     foxr     2966:     if ($namespace ne 'roles') {
                   2967: 	chomp($what);
                   2968: 	my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   2969: 				  &GDBM_WRCREAT(),"P",$what);
                   2970: 	if($hashref) {
                   2971: 	    my @pairs=split(/\&/,$what);
                   2972: 	    foreach my $pair (@pairs) {
                   2973: 		my ($key,$value)=split(/=/,$pair);
                   2974: 		$hashref->{$key}=$value;
                   2975: 	    }
1.311     albertel 2976: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     2977: 		&Reply( $client, "ok\n", $userinput);
                   2978: 	    } else {
                   2979: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   2980: 			"while attempting put\n", 
                   2981: 			$userinput);
                   2982: 	    }
                   2983: 	} else {
1.316     albertel 2984: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230     foxr     2985: 		     "while attempting put\n", $userinput);
                   2986: 	}
                   2987:     } else {
                   2988:         &Failure( $client, "refused\n", $userinput);
                   2989:     }
                   2990:     
                   2991:     return 1;
                   2992: }
                   2993: &register_handler("put", \&put_user_profile_entry, 0, 1, 0);
                   2994: 
1.283     albertel 2995: #   Put a piece of new data in hash, returns error if entry already exists
                   2996: # Parameters:
                   2997: #    $cmd      - The command that got us here.
                   2998: #    $tail     - Tail of the command (remaining parameters).
                   2999: #    $client   - File descriptor connected to client.
                   3000: # Returns
                   3001: #     0        - Requested to exit, caller should shut down.
                   3002: #     1        - Continue processing.
                   3003: #
                   3004: sub newput_user_profile_entry {
                   3005:     my ($cmd, $tail, $client)  = @_;
                   3006: 
                   3007:     my $userinput = "$cmd:$tail";
                   3008: 
                   3009:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
                   3010:     if ($namespace eq 'roles') {
                   3011:         &Failure( $client, "refused\n", $userinput);
                   3012: 	return 1;
                   3013:     }
                   3014: 
                   3015:     chomp($what);
                   3016: 
                   3017:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3018: 				 &GDBM_WRCREAT(),"N",$what);
                   3019:     if(!$hashref) {
1.316     albertel 3020: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283     albertel 3021: 		  "while attempting put\n", $userinput);
                   3022: 	return 1;
                   3023:     }
                   3024: 
                   3025:     my @pairs=split(/\&/,$what);
                   3026:     foreach my $pair (@pairs) {
                   3027: 	my ($key,$value)=split(/=/,$pair);
                   3028: 	if (exists($hashref->{$key})) {
1.513     raeburn  3029:             if (!&untie_user_hash($hashref)) {
                   3030:                 &logthis("error: ".($!+0)." untie (GDBM) failed ".
                   3031:                          "while attempting newput - early out as key exists");
                   3032:             }
                   3033:             &Failure($client, "key_exists: ".$key."\n",$userinput);
                   3034:             return 1;
1.283     albertel 3035: 	}
                   3036:     }
                   3037: 
                   3038:     foreach my $pair (@pairs) {
                   3039: 	my ($key,$value)=split(/=/,$pair);
                   3040: 	$hashref->{$key}=$value;
                   3041:     }
                   3042: 
1.311     albertel 3043:     if (&untie_user_hash($hashref)) {
1.283     albertel 3044: 	&Reply( $client, "ok\n", $userinput);
                   3045:     } else {
                   3046: 	&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3047: 		 "while attempting put\n", 
                   3048: 		 $userinput);
                   3049:     }
                   3050:     return 1;
                   3051: }
                   3052: &register_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
                   3053: 
1.230     foxr     3054: # 
                   3055: #   Increment a profile entry in the user history file.
                   3056: #   The history contains keyword value pairs.  In this case,
                   3057: #   The value itself is a pair of numbers.  The first, the current value
                   3058: #   the second an increment that this function applies to the current
                   3059: #   value.
                   3060: #
                   3061: # Parameters:
                   3062: #    $cmd      - The command that got us here.
                   3063: #    $tail     - Tail of the command (remaining parameters).
                   3064: #    $client   - File descriptor connected to client.
                   3065: # Returns
                   3066: #     0        - Requested to exit, caller should shut down.
                   3067: #     1        - Continue processing.
                   3068: #
                   3069: sub increment_user_value_handler {
                   3070:     my ($cmd, $tail, $client) = @_;
                   3071:     
                   3072:     my $userinput   = "$cmd:$tail";
                   3073:     
                   3074:     my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
                   3075:     if ($namespace ne 'roles') {
                   3076:         chomp($what);
                   3077: 	my $hashref = &tie_user_hash($udom, $uname,
                   3078: 				     $namespace, &GDBM_WRCREAT(),
                   3079: 				     "P",$what);
                   3080: 	if ($hashref) {
                   3081: 	    my @pairs=split(/\&/,$what);
                   3082: 	    foreach my $pair (@pairs) {
                   3083: 		my ($key,$value)=split(/=/,$pair);
1.284     raeburn  3084:                 $value = &unescape($value);
1.230     foxr     3085: 		# We could check that we have a number...
                   3086: 		if (! defined($value) || $value eq '') {
                   3087: 		    $value = 1;
                   3088: 		}
                   3089: 		$hashref->{$key}+=$value;
1.284     raeburn  3090:                 if ($namespace eq 'nohist_resourcetracker') {
                   3091:                     if ($hashref->{$key} < 0) {
                   3092:                         $hashref->{$key} = 0;
                   3093:                     }
                   3094:                 }
1.230     foxr     3095: 	    }
1.311     albertel 3096: 	    if (&untie_user_hash($hashref)) {
1.230     foxr     3097: 		&Reply( $client, "ok\n", $userinput);
                   3098: 	    } else {
                   3099: 		&Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   3100: 			 "while attempting inc\n", $userinput);
                   3101: 	    }
                   3102: 	} else {
                   3103: 	    &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3104: 		     "while attempting inc\n", $userinput);
                   3105: 	}
                   3106:     } else {
                   3107: 	&Failure($client, "refused\n", $userinput);
                   3108:     }
                   3109:     
                   3110:     return 1;
                   3111: }
                   3112: &register_handler("inc", \&increment_user_value_handler, 0, 1, 0);
                   3113: 
                   3114: #
                   3115: #   Put a new role for a user.  Roles are LonCAPA's packaging of permissions.
                   3116: #   Each 'role' a user has implies a set of permissions.  Adding a new role
                   3117: #   for a person grants the permissions packaged with that role
                   3118: #   to that user when the role is selected.
                   3119: #
                   3120: # Parameters:
                   3121: #    $cmd       - The command string (rolesput).
                   3122: #    $tail      - The remainder of the request line.  For rolesput this
                   3123: #                 consists of a colon separated list that contains:
                   3124: #                 The domain and user that is granting the role (logged).
                   3125: #                 The domain and user that is getting the role.
                   3126: #                 The roles being granted as a set of & separated pairs.
                   3127: #                 each pair a key value pair.
                   3128: #    $client    - File descriptor connected to the client.
                   3129: # Returns:
                   3130: #     0         - If the daemon should exit
                   3131: #     1         - To continue processing.
                   3132: #
                   3133: #
                   3134: sub roles_put_handler {
                   3135:     my ($cmd, $tail, $client) = @_;
                   3136: 
                   3137:     my $userinput  = "$cmd:$tail";
                   3138: 
                   3139:     my ( $exedom, $exeuser, $udom, $uname,  $what) = split(/:/,$tail);
                   3140:     
                   3141: 
                   3142:     my $namespace='roles';
                   3143:     chomp($what);
                   3144:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3145: 				 &GDBM_WRCREAT(), "P",
                   3146: 				 "$exedom:$exeuser:$what");
                   3147:     #
                   3148:     #  Log the attempt to set a role.  The {}'s here ensure that the file 
                   3149:     #  handle is open for the minimal amount of time.  Since the flush
                   3150:     #  is done on close this improves the chances the log will be an un-
                   3151:     #  corrupted ordered thing.
                   3152:     if ($hashref) {
1.261     foxr     3153: 	my $pass_entry = &get_auth_type($udom, $uname);
                   3154: 	my ($auth_type,$pwd)  = split(/:/, $pass_entry);
                   3155: 	$auth_type = $auth_type.":";
1.230     foxr     3156: 	my @pairs=split(/\&/,$what);
                   3157: 	foreach my $pair (@pairs) {
                   3158: 	    my ($key,$value)=split(/=/,$pair);
                   3159: 	    &manage_permissions($key, $udom, $uname,
1.260     foxr     3160: 			       $auth_type);
1.230     foxr     3161: 	    $hashref->{$key}=$value;
                   3162: 	}
1.311     albertel 3163: 	if (&untie_user_hash($hashref)) {
1.230     foxr     3164: 	    &Reply($client, "ok\n", $userinput);
                   3165: 	} else {
                   3166: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3167: 		     "while attempting rolesput\n", $userinput);
                   3168: 	}
                   3169:     } else {
                   3170: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3171: 		 "while attempting rolesput\n", $userinput);
                   3172:     }
                   3173:     return 1;
                   3174: }
                   3175: &register_handler("rolesput", \&roles_put_handler, 1,1,0);  # Encoded client only.
                   3176: 
                   3177: #
1.231     foxr     3178: #   Deletes (removes) a role for a user.   This is equivalent to removing
                   3179: #  a permissions package associated with the role from the user's profile.
                   3180: #
                   3181: # Parameters:
                   3182: #     $cmd                 - The command (rolesdel)
                   3183: #     $tail                - The remainder of the request line. This consists
                   3184: #                             of:
                   3185: #                             The domain and user requesting the change (logged)
                   3186: #                             The domain and user being changed.
                   3187: #                             The roles being revoked.  These are shipped to us
                   3188: #                             as a bunch of & separated role name keywords.
                   3189: #     $client              - The file handle open on the client.
                   3190: # Returns:
                   3191: #     1                    - Continue processing
                   3192: #     0                    - Exit.
                   3193: #
                   3194: sub roles_delete_handler {
                   3195:     my ($cmd, $tail, $client)  = @_;
                   3196: 
                   3197:     my $userinput    = "$cmd:$tail";
                   3198:    
                   3199:     my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
                   3200:     &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
                   3201: 	   "what = ".$what);
                   3202:     my $namespace='roles';
                   3203:     chomp($what);
                   3204:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3205: 				 &GDBM_WRCREAT(), "D",
                   3206: 				 "$exedom:$exeuser:$what");
                   3207:     
                   3208:     if ($hashref) {
                   3209: 	my @rolekeys=split(/\&/,$what);
                   3210: 	
                   3211: 	foreach my $key (@rolekeys) {
                   3212: 	    delete $hashref->{$key};
                   3213: 	}
1.315     albertel 3214: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3215: 	    &Reply($client, "ok\n", $userinput);
                   3216: 	} else {
                   3217: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3218: 		     "while attempting rolesdel\n", $userinput);
                   3219: 	}
                   3220:     } else {
                   3221:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3222: 		 "while attempting rolesdel\n", $userinput);
                   3223:     }
                   3224:     
                   3225:     return 1;
                   3226: }
                   3227: &register_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
                   3228: 
                   3229: # Unencrypted get from a user's profile database.  See 
                   3230: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
                   3231: # This function retrieves a keyed item from a specific named database in the
                   3232: # user's directory.
                   3233: #
                   3234: # Parameters:
                   3235: #   $cmd             - Command request keyword (get).
                   3236: #   $tail            - Tail of the command.  This is a colon separated list
                   3237: #                      consisting of the domain and username that uniquely
                   3238: #                      identifies the profile,
                   3239: #                      The 'namespace' which selects the gdbm file to 
                   3240: #                      do the lookup in, 
                   3241: #                      & separated list of keys to lookup.  Note that
                   3242: #                      the values are returned as an & separated list too.
                   3243: #   $client          - File descriptor open on the client.
                   3244: # Returns:
                   3245: #   1       - Continue processing.
                   3246: #   0       - Exit.
                   3247: #
                   3248: sub get_profile_entry {
                   3249:     my ($cmd, $tail, $client) = @_;
                   3250: 
                   3251:     my $userinput= "$cmd:$tail";
                   3252:    
                   3253:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3254:     chomp($what);
1.255     foxr     3255: 
1.390     raeburn  3256: 
1.255     foxr     3257:     my $replystring = read_profile($udom, $uname, $namespace, $what);
                   3258:     my ($first) = split(/:/,$replystring);
                   3259:     if($first ne "error") {
1.387     albertel 3260: 	&Reply($client, \$replystring, $userinput);
1.231     foxr     3261:     } else {
1.255     foxr     3262: 	&Failure($client, $replystring." while attempting get\n", $userinput);
1.231     foxr     3263:     }
                   3264:     return 1;
1.255     foxr     3265: 
                   3266: 
1.231     foxr     3267: }
                   3268: &register_handler("get", \&get_profile_entry, 0,1,0);
                   3269: 
                   3270: #
                   3271: #  Process the encrypted get request.  Note that the request is sent
                   3272: #  in clear, but the reply is encrypted.  This is a small covert channel:
                   3273: #  information about the sensitive keys is given to the snooper.  Just not
                   3274: #  information about the values of the sensitive key.  Hmm if I wanted to
                   3275: #  know these I'd snoop for the egets. Get the profile item names from them
                   3276: #  and then issue a get for them since there's no enforcement of the
                   3277: #  requirement of an encrypted get for particular profile items.  If I
                   3278: #  were re-doing this, I'd force the request to be encrypted as well as the
                   3279: #  reply.  I'd also just enforce encrypted transactions for all gets since
                   3280: #  that would prevent any covert channel snooping.
                   3281: #
                   3282: #  Parameters:
                   3283: #     $cmd               - Command keyword of request (eget).
                   3284: #     $tail              - Tail of the command.  See GetProfileEntry
#                          for more information about this.
                   3285: #     $client            - File open on the client.
                   3286: #  Returns:
                   3287: #     1      - Continue processing
                   3288: #     0      - server should exit.
                   3289: sub get_profile_entry_encrypted {
                   3290:     my ($cmd, $tail, $client) = @_;
                   3291: 
                   3292:     my $userinput = "$cmd:$tail";
                   3293:    
1.339     albertel 3294:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231     foxr     3295:     chomp($what);
1.255     foxr     3296:     my $qresult = read_profile($udom, $uname, $namespace, $what);
                   3297:     my ($first) = split(/:/, $qresult);
                   3298:     if($first ne "error") {
                   3299: 	
                   3300: 	if ($cipher) {
                   3301: 	    my $cmdlength=length($qresult);
                   3302: 	    $qresult.="         ";
                   3303: 	    my $encqresult='';
                   3304: 	    for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   3305: 		$encqresult.= unpack("H16", 
                   3306: 				     $cipher->encrypt(substr($qresult,
                   3307: 							     $encidx,
                   3308: 							     8)));
                   3309: 	    }
                   3310: 	    &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
                   3311: 	} else {
1.231     foxr     3312: 		&Failure( $client, "error:no_key\n", $userinput);
                   3313: 	    }
                   3314:     } else {
1.255     foxr     3315: 	&Failure($client, "$qresult while attempting eget\n", $userinput);
                   3316: 
1.231     foxr     3317:     }
                   3318:     
                   3319:     return 1;
                   3320: }
1.255     foxr     3321: &register_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263     albertel 3322: 
1.231     foxr     3323: #
                   3324: #   Deletes a key in a user profile database.
                   3325: #   
                   3326: #   Parameters:
                   3327: #       $cmd                  - Command keyword (del).
                   3328: #       $tail                 - Command tail.  IN this case a colon
                   3329: #                               separated list containing:
                   3330: #                               The domain and user that identifies uniquely
                   3331: #                               the identity of the user.
                   3332: #                               The profile namespace (name of the profile
                   3333: #                               database file).
                   3334: #                               & separated list of keywords to delete.
                   3335: #       $client              - File open on client socket.
                   3336: # Returns:
                   3337: #     1   - Continue processing
                   3338: #     0   - Exit server.
                   3339: #
                   3340: #
                   3341: sub delete_profile_entry {
                   3342:     my ($cmd, $tail, $client) = @_;
                   3343: 
                   3344:     my $userinput = "cmd:$tail";
                   3345: 
                   3346:     my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
                   3347:     chomp($what);
                   3348:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3349: 				 &GDBM_WRCREAT(),
                   3350: 				 "D",$what);
                   3351:     if ($hashref) {
                   3352:         my @keys=split(/\&/,$what);
                   3353: 	foreach my $key (@keys) {
                   3354: 	    delete($hashref->{$key});
                   3355: 	}
1.315     albertel 3356: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3357: 	    &Reply($client, "ok\n", $userinput);
                   3358: 	} else {
                   3359: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3360: 		    "while attempting del\n", $userinput);
                   3361: 	}
                   3362:     } else {
                   3363: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3364: 		 "while attempting del\n", $userinput);
                   3365:     }
                   3366:     return 1;
                   3367: }
                   3368: &register_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263     albertel 3369: 
1.231     foxr     3370: #
                   3371: #  List the set of keys that are defined in a profile database file.
                   3372: #  A successful reply from this will contain an & separated list of
                   3373: #  the keys. 
                   3374: # Parameters:
                   3375: #     $cmd              - Command request (keys).
                   3376: #     $tail             - Remainder of the request, a colon separated
                   3377: #                         list containing domain/user that identifies the
                   3378: #                         user being queried, and the database namespace
                   3379: #                         (database filename essentially).
                   3380: #     $client           - File open on the client.
                   3381: #  Returns:
                   3382: #    1    - Continue processing.
                   3383: #    0    - Exit the server.
                   3384: #
                   3385: sub get_profile_keys {
                   3386:     my ($cmd, $tail, $client) = @_;
                   3387: 
                   3388:     my $userinput = "$cmd:$tail";
                   3389: 
                   3390:     my ($udom,$uname,$namespace)=split(/:/,$tail);
                   3391:     my $qresult='';
                   3392:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3393: 				  &GDBM_READER());
                   3394:     if ($hashref) {
                   3395: 	foreach my $key (keys %$hashref) {
                   3396: 	    $qresult.="$key&";
                   3397: 	}
1.315     albertel 3398: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3399: 	    $qresult=~s/\&$//;
1.387     albertel 3400: 	    &Reply($client, \$qresult, $userinput);
1.231     foxr     3401: 	} else {
                   3402: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3403: 		    "while attempting keys\n", $userinput);
                   3404: 	}
                   3405:     } else {
                   3406: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3407: 		 "while attempting keys\n", $userinput);
                   3408:     }
                   3409:    
                   3410:     return 1;
                   3411: }
                   3412: &register_handler("keys", \&get_profile_keys, 0, 1, 0);
                   3413: 
                   3414: #
                   3415: #   Dump the contents of a user profile database.
                   3416: #   Note that this constitutes a very large covert channel too since
                   3417: #   the dump will return sensitive information that is not encrypted.
                   3418: #   The naive security assumption is that the session negotiation ensures
                   3419: #   our client is trusted and I don't believe that's assured at present.
                   3420: #   Sure want badly to go to ssl or tls.  Of course if my peer isn't really
                   3421: #   a LonCAPA node they could have negotiated an encryption key too so >sigh<.
                   3422: # 
                   3423: #  Parameters:
                   3424: #     $cmd           - The command request keyword (currentdump).
                   3425: #     $tail          - Remainder of the request, consisting of a colon
                   3426: #                      separated list that has the domain/username and
                   3427: #                      the namespace to dump (database file).
                   3428: #     $client        - file open on the remote client.
                   3429: # Returns:
                   3430: #     1    - Continue processing.
                   3431: #     0    - Exit the server.
                   3432: #
                   3433: sub dump_profile_database {
                   3434:     my ($cmd, $tail, $client) = @_;
                   3435: 
1.494     droeschl 3436:     my $res = LONCAPA::Lond::dump_profile_database($tail);
                   3437: 
                   3438:     if ($res =~ /^error:/) {
                   3439:         Failure($client, \$res, "$cmd:$tail");
                   3440:     } else {
                   3441:         Reply($client, \$res, "$cmd:$tail");
                   3442:     }
                   3443: 
                   3444:     return 1;  
                   3445: 
                   3446:     #TODO remove 
1.231     foxr     3447:     my $userinput = "$cmd:$tail";
                   3448:    
                   3449:     my ($udom,$uname,$namespace) = split(/:/,$tail);
                   3450:     my $hashref = &tie_user_hash($udom, $uname, $namespace,
                   3451: 				 &GDBM_READER());
                   3452:     if ($hashref) {
                   3453: 	# Structure of %data:
                   3454: 	# $data{$symb}->{$parameter}=$value;
                   3455: 	# $data{$symb}->{'v.'.$parameter}=$version;
                   3456: 	# since $parameter will be unescaped, we do not
                   3457:  	# have to worry about silly parameter names...
                   3458: 	
                   3459:         my $qresult='';
                   3460: 	my %data = ();                     # A hash of anonymous hashes..
                   3461: 	while (my ($key,$value) = each(%$hashref)) {
                   3462: 	    my ($v,$symb,$param) = split(/:/,$key);
                   3463: 	    next if ($v eq 'version' || $symb eq 'keys');
                   3464: 	    next if (exists($data{$symb}) && 
                   3465: 		     exists($data{$symb}->{$param}) &&
                   3466: 		     $data{$symb}->{'v.'.$param} > $v);
                   3467: 	    $data{$symb}->{$param}=$value;
                   3468: 	    $data{$symb}->{'v.'.$param}=$v;
                   3469: 	}
1.311     albertel 3470: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3471: 	    while (my ($symb,$param_hash) = each(%data)) {
                   3472: 		while(my ($param,$value) = each (%$param_hash)){
                   3473: 		    next if ($param =~ /^v\./);       # Ignore versions...
                   3474: 		    #
                   3475: 		    #   Just dump the symb=value pairs separated by &
                   3476: 		    #
                   3477: 		    $qresult.=$symb.':'.$param.'='.$value.'&';
                   3478: 		}
                   3479: 	    }
                   3480: 	    chop($qresult);
1.387     albertel 3481: 	    &Reply($client , \$qresult, $userinput);
1.231     foxr     3482: 	} else {
                   3483: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3484: 		     "while attempting currentdump\n", $userinput);
                   3485: 	}
                   3486:     } else {
                   3487: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3488: 		"while attempting currentdump\n", $userinput);
                   3489:     }
                   3490: 
                   3491:     return 1;
                   3492: }
                   3493: &register_handler("currentdump", \&dump_profile_database, 0, 1, 0);
                   3494: 
                   3495: #
                   3496: #   Dump a profile database with an optional regular expression
                   3497: #   to match against the keys.  In this dump, no effort is made
                   3498: #   to separate symb from version information. Presumably the
                   3499: #   databases that are dumped by this command are of a different
                   3500: #   structure.  Need to look at this and improve the documentation of
                   3501: #   both this and the currentdump handler.
                   3502: # Parameters:
                   3503: #    $cmd                     - The command keyword.
                   3504: #    $tail                    - All of the characters after the $cmd:
                   3505: #                               These are expected to be a colon
                   3506: #                               separated list containing:
                   3507: #                               domain/user - identifying the user.
                   3508: #                               namespace   - identifying the database.
                   3509: #                               regexp      - optional regular expression
                   3510: #                                             that is matched against
                   3511: #                                             database keywords to do
                   3512: #                                             selective dumps.
1.488     raeburn  3513: #                               range       - optional range of entries
                   3514: #                                             e.g., 10-20 would return the
                   3515: #                                             10th to 19th items, etc.  
1.231     foxr     3516: #   $client                   - Channel open on the client.
                   3517: # Returns:
                   3518: #    1    - Continue processing.
                   3519: # Side effects:
                   3520: #    response is written to $client.
                   3521: #
                   3522: sub dump_with_regexp {
                   3523:     my ($cmd, $tail, $client) = @_;
                   3524: 
1.494     droeschl 3525:     my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490     droeschl 3526:     
                   3527:     if ($res =~ /^error:/) {
                   3528:         Failure($client, \$res, "$cmd:$tail");
                   3529:     } else {
                   3530:         Reply($client, \$res, "$cmd:$tail");
                   3531:     }
1.231     foxr     3532: 
                   3533:     return 1;
                   3534: }
                   3535: &register_handler("dump", \&dump_with_regexp, 0, 1, 0);
                   3536: 
                   3537: #  Store a set of key=value pairs associated with a versioned name.
                   3538: #
                   3539: #  Parameters:
                   3540: #    $cmd                - Request command keyword.
                   3541: #    $tail               - Tail of the request.  This is a colon
                   3542: #                          separated list containing:
                   3543: #                          domain/user - User and authentication domain.
                   3544: #                          namespace   - Name of the database being modified
                   3545: #                          rid         - Resource keyword to modify.
                   3546: #                          what        - new value associated with rid.
1.512     raeburn  3547: #                          laststore   - (optional) version=timestamp
                   3548: #                                        for most recent transaction for rid
                   3549: #                                        in namespace, when cstore was called
1.231     foxr     3550: #
                   3551: #    $client             - Socket open on the client.
                   3552: #
                   3553: #
                   3554: #  Returns:
                   3555: #      1 (keep on processing).
                   3556: #  Side-Effects:
                   3557: #    Writes to the client
1.512     raeburn  3558: #    Successful storage will cause either 'ok', or, if $laststore was included
                   3559: #    in the tail of the request, and the version number for the last transaction
                   3560: #    is larger than the version in $laststore, delay:$numtrans , where $numtrans
                   3561: #    is the number of store evevnts recorded for rid in namespace since
                   3562: #    lonnet::store() was called by the client.
                   3563: #
1.231     foxr     3564: sub store_handler {
                   3565:     my ($cmd, $tail, $client) = @_;
                   3566:  
                   3567:     my $userinput = "$cmd:$tail";
1.512     raeburn  3568:     chomp($tail);
                   3569:     my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231     foxr     3570:     if ($namespace ne 'roles') {
                   3571: 
                   3572: 	my @pairs=split(/\&/,$what);
                   3573: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
1.268     albertel 3574: 				       &GDBM_WRCREAT(), "S",
1.231     foxr     3575: 				       "$rid:$what");
                   3576: 	if ($hashref) {
                   3577: 	    my $now = time;
1.512     raeburn  3578:             my $numtrans;
                   3579:             if ($laststore) {
                   3580:                 my ($previousversion,$previoustime) = split(/\=/,$laststore);
                   3581:                 my ($lastversion,$lasttime) = (0,0);
                   3582:                 $lastversion = $hashref->{"version:$rid"};
                   3583:                 if ($lastversion) {
                   3584:                     $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
                   3585:                 }
                   3586:                 if (($previousversion) && ($previousversion !~ /\D/)) {
                   3587:                     if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
                   3588:                         $numtrans = $lastversion - $previousversion;
                   3589:                     }
                   3590:                 } elsif ($lastversion) {
                   3591:                     $numtrans = $lastversion;
                   3592:                 }
                   3593:                 if ($numtrans) {
                   3594:                     $numtrans =~ s/D//g;
                   3595:                 }
                   3596:             }
1.231     foxr     3597: 	    $hashref->{"version:$rid"}++;
                   3598: 	    my $version=$hashref->{"version:$rid"};
                   3599: 	    my $allkeys=''; 
                   3600: 	    foreach my $pair (@pairs) {
                   3601: 		my ($key,$value)=split(/=/,$pair);
                   3602: 		$allkeys.=$key.':';
                   3603: 		$hashref->{"$version:$rid:$key"}=$value;
                   3604: 	    }
                   3605: 	    $hashref->{"$version:$rid:timestamp"}=$now;
                   3606: 	    $allkeys.='timestamp';
                   3607: 	    $hashref->{"$version:keys:$rid"}=$allkeys;
1.311     albertel 3608: 	    if (&untie_user_hash($hashref)) {
1.512     raeburn  3609:                 my $msg = 'ok';
                   3610:                 if ($numtrans) {
                   3611:                     $msg = 'delay:'.$numtrans;
                   3612:                 }
                   3613: 		&Reply($client, "$msg\n", $userinput);
1.231     foxr     3614: 	    } else {
                   3615: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3616: 			"while attempting store\n", $userinput);
                   3617: 	    }
                   3618: 	} else {
                   3619: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3620: 		     "while attempting store\n", $userinput);
                   3621: 	}
                   3622:     } else {
                   3623: 	&Failure($client, "refused\n", $userinput);
                   3624:     }
                   3625: 
                   3626:     return 1;
                   3627: }
                   3628: &register_handler("store", \&store_handler, 0, 1, 0);
1.263     albertel 3629: 
1.323     albertel 3630: #  Modify a set of key=value pairs associated with a versioned name.
                   3631: #
                   3632: #  Parameters:
                   3633: #    $cmd                - Request command keyword.
                   3634: #    $tail               - Tail of the request.  This is a colon
                   3635: #                          separated list containing:
                   3636: #                          domain/user - User and authentication domain.
                   3637: #                          namespace   - Name of the database being modified
                   3638: #                          rid         - Resource keyword to modify.
                   3639: #                          v           - Version item to modify
                   3640: #                          what        - new value associated with rid.
                   3641: #
                   3642: #    $client             - Socket open on the client.
                   3643: #
                   3644: #
                   3645: #  Returns:
                   3646: #      1 (keep on processing).
                   3647: #  Side-Effects:
                   3648: #    Writes to the client
                   3649: sub putstore_handler {
                   3650:     my ($cmd, $tail, $client) = @_;
                   3651:  
                   3652:     my $userinput = "$cmd:$tail";
                   3653: 
                   3654:     my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
                   3655:     if ($namespace ne 'roles') {
                   3656: 
                   3657: 	chomp($what);
                   3658: 	my $hashref  = &tie_user_hash($udom, $uname, $namespace,
                   3659: 				       &GDBM_WRCREAT(), "M",
                   3660: 				       "$rid:$v:$what");
                   3661: 	if ($hashref) {
                   3662: 	    my $now = time;
                   3663: 	    my %data = &hash_extract($what);
                   3664: 	    my @allkeys;
                   3665: 	    while (my($key,$value) = each(%data)) {
                   3666: 		push(@allkeys,$key);
                   3667: 		$hashref->{"$v:$rid:$key"} = $value;
                   3668: 	    }
                   3669: 	    my $allkeys = join(':',@allkeys);
                   3670: 	    $hashref->{"$v:keys:$rid"}=$allkeys;
                   3671: 
                   3672: 	    if (&untie_user_hash($hashref)) {
                   3673: 		&Reply($client, "ok\n", $userinput);
                   3674: 	    } else {
                   3675: 		&Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3676: 			"while attempting store\n", $userinput);
                   3677: 	    }
                   3678: 	} else {
                   3679: 	    &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3680: 		     "while attempting store\n", $userinput);
                   3681: 	}
                   3682:     } else {
                   3683: 	&Failure($client, "refused\n", $userinput);
                   3684:     }
                   3685: 
                   3686:     return 1;
                   3687: }
                   3688: &register_handler("putstore", \&putstore_handler, 0, 1, 0);
                   3689: 
                   3690: sub hash_extract {
                   3691:     my ($str)=@_;
                   3692:     my %hash;
                   3693:     foreach my $pair (split(/\&/,$str)) {
                   3694: 	my ($key,$value)=split(/=/,$pair);
                   3695: 	$hash{$key}=$value;
                   3696:     }
                   3697:     return (%hash);
                   3698: }
                   3699: sub hash_to_str {
                   3700:     my ($hash_ref)=@_;
                   3701:     my $str;
                   3702:     foreach my $key (keys(%$hash_ref)) {
                   3703: 	$str.=$key.'='.$hash_ref->{$key}.'&';
                   3704:     }
                   3705:     $str=~s/\&$//;
                   3706:     return $str;
                   3707: }
                   3708: 
1.231     foxr     3709: #
                   3710: #  Dump out all versions of a resource that has key=value pairs associated
                   3711: # with it for each version.  These resources are built up via the store
                   3712: # command.
                   3713: #
                   3714: #  Parameters:
                   3715: #     $cmd               - Command keyword.
                   3716: #     $tail              - Remainder of the request which consists of:
                   3717: #                          domain/user   - User and auth. domain.
                   3718: #                          namespace     - name of resource database.
                   3719: #                          rid           - Resource id.
                   3720: #    $client             - socket open on the client.
                   3721: #
                   3722: # Returns:
                   3723: #      1  indicating the caller should not yet exit.
                   3724: # Side-effects:
                   3725: #   Writes a reply to the client.
                   3726: #   The reply is a string of the following shape:
                   3727: #   version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
                   3728: #    Where the 1 above represents version 1.
                   3729: #    this continues for all pairs of keys in all versions.
                   3730: #
                   3731: #
                   3732: #    
                   3733: #
                   3734: sub restore_handler {
                   3735:     my ($cmd, $tail, $client) = @_;
                   3736: 
                   3737:     my $userinput = "$cmd:$tail";	# Only used for logging purposes.
1.351     banghart 3738:     my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352     albertel 3739:     $namespace=~s/\//\_/g;
1.350     albertel 3740:     $namespace = &LONCAPA::clean_username($namespace);
1.349     albertel 3741: 
1.231     foxr     3742:     chomp($rid);
                   3743:     my $qresult='';
1.309     albertel 3744:     my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
                   3745:     if ($hashref) {
                   3746: 	my $version=$hashref->{"version:$rid"};
1.231     foxr     3747: 	$qresult.="version=$version&";
                   3748: 	my $scope;
                   3749: 	for ($scope=1;$scope<=$version;$scope++) {
1.309     albertel 3750: 	    my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231     foxr     3751: 	    my @keys=split(/:/,$vkeys);
                   3752: 	    my $key;
                   3753: 	    $qresult.="$scope:keys=$vkeys&";
                   3754: 	    foreach $key (@keys) {
1.309     albertel 3755: 		$qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231     foxr     3756: 	    }                                  
                   3757: 	}
1.311     albertel 3758: 	if (&untie_user_hash($hashref)) {
1.231     foxr     3759: 	    $qresult=~s/\&$//;
1.387     albertel 3760: 	    &Reply( $client, \$qresult, $userinput);
1.231     foxr     3761: 	} else {
                   3762: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   3763: 		    "while attempting restore\n", $userinput);
                   3764: 	}
                   3765:     } else {
                   3766: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   3767: 		"while attempting restore\n", $userinput);
                   3768:     }
                   3769:   
                   3770:     return 1;
                   3771: 
                   3772: 
                   3773: }
                   3774: &register_handler("restore", \&restore_handler, 0,1,0);
1.234     foxr     3775: 
                   3776: #
1.324     raeburn  3777: #   Add a chat message to a synchronous discussion board.
1.234     foxr     3778: #
                   3779: # Parameters:
                   3780: #    $cmd                - Request keyword.
                   3781: #    $tail               - Tail of the command. A colon separated list
                   3782: #                          containing:
                   3783: #                          cdom    - Domain on which the chat board lives
1.324     raeburn  3784: #                          cnum    - Course containing the chat board.
                   3785: #                          newpost - Body of the posting.
                   3786: #                          group   - Optional group, if chat board is only 
                   3787: #                                    accessible in a group within the course 
1.234     foxr     3788: #   $client              - Socket open on the client.
                   3789: # Returns:
                   3790: #   1    - Indicating caller should keep on processing.
                   3791: #
                   3792: # Side-effects:
                   3793: #   writes a reply to the client.
                   3794: #
                   3795: #
                   3796: sub send_chat_handler {
                   3797:     my ($cmd, $tail, $client) = @_;
                   3798: 
                   3799:     
                   3800:     my $userinput = "$cmd:$tail";
                   3801: 
1.324     raeburn  3802:     my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
                   3803:     &chat_add($cdom,$cnum,$newpost,$group);
1.234     foxr     3804:     &Reply($client, "ok\n", $userinput);
                   3805: 
                   3806:     return 1;
                   3807: }
                   3808: &register_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263     albertel 3809: 
1.234     foxr     3810: #
1.324     raeburn  3811: #   Retrieve the set of chat messages from a discussion board.
1.234     foxr     3812: #
                   3813: #  Parameters:
                   3814: #    $cmd             - Command keyword that initiated the request.
                   3815: #    $tail            - Remainder of the request after the command
                   3816: #                       keyword.  In this case a colon separated list of
                   3817: #                       chat domain    - Which discussion board.
                   3818: #                       chat id        - Discussion thread(?)
                   3819: #                       domain/user    - Authentication domain and username
                   3820: #                                        of the requesting person.
1.324     raeburn  3821: #                       group          - Optional course group containing
                   3822: #                                        the board.      
1.234     foxr     3823: #   $client           - Socket open on the client program.
                   3824: # Returns:
                   3825: #    1     - continue processing
                   3826: # Side effects:
                   3827: #    Response is written to the client.
                   3828: #
                   3829: sub retrieve_chat_handler {
                   3830:     my ($cmd, $tail, $client) = @_;
                   3831: 
                   3832: 
                   3833:     my $userinput = "$cmd:$tail";
                   3834: 
1.324     raeburn  3835:     my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234     foxr     3836:     my $reply='';
1.324     raeburn  3837:     foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234     foxr     3838: 	$reply.=&escape($_).':';
                   3839:     }
                   3840:     $reply=~s/\:$//;
1.387     albertel 3841:     &Reply($client, \$reply, $userinput);
1.234     foxr     3842: 
                   3843: 
                   3844:     return 1;
                   3845: }
                   3846: &register_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
                   3847: 
                   3848: #
                   3849: #  Initiate a query of an sql database.  SQL query repsonses get put in
                   3850: #  a file for later retrieval.  This prevents sql query results from
                   3851: #  bottlenecking the system.  Note that with loncnew, perhaps this is
                   3852: #  less of an issue since multiple outstanding requests can be concurrently
                   3853: #  serviced.
                   3854: #
                   3855: #  Parameters:
                   3856: #     $cmd       - COmmand keyword that initiated the request.
                   3857: #     $tail      - Remainder of the command after the keyword.
                   3858: #                  For this function, this consists of a query and
                   3859: #                  3 arguments that are self-documentingly labelled
                   3860: #                  in the original arg1, arg2, arg3.
                   3861: #     $client    - Socket open on the client.
                   3862: # Return:
                   3863: #    1   - Indicating processing should continue.
                   3864: # Side-effects:
                   3865: #    a reply is written to $client.
                   3866: #
                   3867: sub send_query_handler {
                   3868:     my ($cmd, $tail, $client) = @_;
                   3869: 
                   3870: 
                   3871:     my $userinput = "$cmd:$tail";
                   3872: 
                   3873:     my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
                   3874:     $query=~s/\n*$//g;
                   3875:     &Reply($client, "". &sql_reply("$clientname\&$query".
                   3876: 				"\&$arg1"."\&$arg2"."\&$arg3")."\n",
                   3877: 	  $userinput);
                   3878:     
                   3879:     return 1;
                   3880: }
                   3881: &register_handler("querysend", \&send_query_handler, 0, 1, 0);
                   3882: 
                   3883: #
                   3884: #   Add a reply to an sql query.  SQL queries are done asyncrhonously.
                   3885: #   The query is submitted via a "querysend" transaction.
                   3886: #   There it is passed on to the lonsql daemon, queued and issued to
                   3887: #   mysql.
                   3888: #     This transaction is invoked when the sql transaction is complete
                   3889: #   it stores the query results in flie and indicates query completion.
                   3890: #   presumably local software then fetches this response... I'm guessing
                   3891: #   the sequence is: lonc does a querysend, we ask lonsql to do it.
                   3892: #   lonsql on completion of the query interacts with the lond of our
                   3893: #   client to do a query reply storing two files:
                   3894: #    - id     - The results of the query.
                   3895: #    - id.end - Indicating the transaction completed. 
                   3896: #    NOTE: id is a unique id assigned to the query and querysend time.
                   3897: # Parameters:
                   3898: #    $cmd        - Command keyword that initiated this request.
                   3899: #    $tail       - Remainder of the tail.  In this case that's a colon
                   3900: #                  separated list containing the query Id and the 
                   3901: #                  results of the query.
                   3902: #    $client     - Socket open on the client.
                   3903: # Return:
                   3904: #    1           - Indicating that we should continue processing.
                   3905: # Side effects:
                   3906: #    ok written to the client.
                   3907: #
                   3908: sub reply_query_handler {
                   3909:     my ($cmd, $tail, $client) = @_;
                   3910: 
                   3911: 
                   3912:     my $userinput = "$cmd:$tail";
                   3913: 
1.339     albertel 3914:     my ($id,$reply)=split(/:/,$tail); 
1.234     foxr     3915:     my $store;
                   3916:     my $execdir=$perlvar{'lonDaemons'};
                   3917:     if ($store=IO::File->new(">$execdir/tmp/$id")) {
                   3918: 	$reply=~s/\&/\n/g;
                   3919: 	print $store $reply;
                   3920: 	close $store;
                   3921: 	my $store2=IO::File->new(">$execdir/tmp/$id.end");
                   3922: 	print $store2 "done\n";
                   3923: 	close $store2;
                   3924: 	&Reply($client, "ok\n", $userinput);
                   3925:     } else {
                   3926: 	&Failure($client, "error: ".($!+0)
                   3927: 		." IO::File->new Failed ".
                   3928: 		"while attempting queryreply\n", $userinput);
                   3929:     }
                   3930:  
                   3931: 
                   3932:     return 1;
                   3933: }
                   3934: &register_handler("queryreply", \&reply_query_handler, 0, 1, 0);
                   3935: 
                   3936: #
                   3937: #  Process the courseidput request.  Not quite sure what this means
                   3938: #  at the system level sense.  It appears a gdbm file in the 
                   3939: #  /home/httpd/lonUsers/$domain/nohist_courseids is tied and
                   3940: #  a set of entries made in that database.
                   3941: #
                   3942: # Parameters:
                   3943: #   $cmd      - The command keyword that initiated this request.
                   3944: #   $tail     - Tail of the command.  In this case consists of a colon
                   3945: #               separated list contaning the domain to apply this to and
                   3946: #               an ampersand separated list of keyword=value pairs.
1.272     raeburn  3947: #               Each value is a colon separated list that includes:  
                   3948: #               description, institutional code and course owner.
                   3949: #               For backward compatibility with versions included
                   3950: #               in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
                   3951: #               code and/or course owner are preserved from the existing 
                   3952: #               record when writing a new record in response to 1.1 or 
                   3953: #               1.2 implementations of lonnet::flushcourselogs().   
                   3954: #                      
1.234     foxr     3955: #   $client   - Socket open on the client.
                   3956: # Returns:
                   3957: #   1    - indicating that processing should continue
                   3958: #
                   3959: # Side effects:
                   3960: #   reply is written to the client.
                   3961: #
                   3962: sub put_course_id_handler {
                   3963:     my ($cmd, $tail, $client) = @_;
                   3964: 
                   3965: 
                   3966:     my $userinput = "$cmd:$tail";
                   3967: 
1.266     raeburn  3968:     my ($udom, $what) = split(/:/, $tail,2);
1.234     foxr     3969:     chomp($what);
                   3970:     my $now=time;
                   3971:     my @pairs=split(/\&/,$what);
                   3972: 
                   3973:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   3974:     if ($hashref) {
                   3975: 	foreach my $pair (@pairs) {
1.271     raeburn  3976:             my ($key,$courseinfo) = split(/=/,$pair,2);
                   3977:             $courseinfo =~ s/=/:/g;
1.384     raeburn  3978:             if (defined($hashref->{$key})) {
                   3979:                 my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
                   3980:                 if (ref($value) eq 'HASH') {
                   3981:                     my @items = ('description','inst_code','owner','type');
                   3982:                     my @new_items = split(/:/,$courseinfo,-1);
                   3983:                     my %storehash; 
                   3984:                     for (my $i=0; $i<@new_items; $i++) {
1.391     raeburn  3985:                         $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384     raeburn  3986:                     }
                   3987:                     $hashref->{$key} = 
                   3988:                         &Apache::lonnet::freeze_escape(\%storehash);
                   3989:                     my $unesc_key = &unescape($key);
                   3990:                     $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   3991:                     next;
1.383     raeburn  3992:                 }
1.384     raeburn  3993:             }
                   3994:             my @current_items = split(/:/,$hashref->{$key},-1);
                   3995:             shift(@current_items); # remove description
                   3996:             pop(@current_items);   # remove last access
                   3997:             my $numcurrent = scalar(@current_items);
                   3998:             if ($numcurrent > 3) {
                   3999:                 $numcurrent = 3;
                   4000:             }
                   4001:             my @new_items = split(/:/,$courseinfo,-1);
                   4002:             my $numnew = scalar(@new_items);
                   4003:             if ($numcurrent > 0) {
                   4004:                 if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2 
                   4005:                     for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
                   4006:                         $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333     raeburn  4007:                     }
1.272     raeburn  4008:                 }
                   4009:             }
1.384     raeburn  4010:             $hashref->{$key}=$courseinfo.':'.$now;
1.234     foxr     4011: 	}
1.311     albertel 4012: 	if (&untie_domain_hash($hashref)) {
1.253     foxr     4013: 	    &Reply( $client, "ok\n", $userinput);
1.234     foxr     4014: 	} else {
1.253     foxr     4015: 	    &Failure($client, "error: ".($!+0)
1.234     foxr     4016: 		     ." untie(GDBM) Failed ".
                   4017: 		     "while attempting courseidput\n", $userinput);
                   4018: 	}
                   4019:     } else {
1.253     foxr     4020: 	&Failure($client, "error: ".($!+0)
1.234     foxr     4021: 		 ." tie(GDBM) Failed ".
                   4022: 		 "while attempting courseidput\n", $userinput);
                   4023:     }
                   4024: 
                   4025:     return 1;
                   4026: }
                   4027: &register_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
                   4028: 
1.383     raeburn  4029: sub put_course_id_hash_handler {
                   4030:     my ($cmd, $tail, $client) = @_;
                   4031:     my $userinput = "$cmd:$tail";
1.384     raeburn  4032:     my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383     raeburn  4033:     chomp($what);
                   4034:     my $now=time;
                   4035:     my @pairs=split(/\&/,$what);
1.384     raeburn  4036:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383     raeburn  4037:     if ($hashref) {
                   4038:         foreach my $pair (@pairs) {
                   4039:             my ($key,$value)=split(/=/,$pair);
1.384     raeburn  4040:             my $unesc_key = &unescape($key);
                   4041:             if ($mode ne 'timeonly') {
                   4042:                 if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
                   4043:                     my $curritems = &Apache::lonnet::thaw_unescape($key); 
                   4044:                     if (ref($curritems) ne 'HASH') {
                   4045:                         my @current_items = split(/:/,$hashref->{$key},-1);
                   4046:                         my $lasttime = pop(@current_items);
                   4047:                         $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
                   4048:                     } else {
                   4049:                         $hashref->{&escape('lasttime:'.$unesc_key)} = '';
                   4050:                     }
                   4051:                 } 
                   4052:                 $hashref->{$key} = $value;
                   4053:             }
                   4054:             if ($mode ne 'notime') {
                   4055:                 $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
                   4056:             }
1.383     raeburn  4057:         }
                   4058:         if (&untie_domain_hash($hashref)) {
                   4059:             &Reply($client, "ok\n", $userinput);
                   4060:         } else {
                   4061:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4062:                      "while attempting courseidputhash\n", $userinput);
                   4063:         }
                   4064:     } else {
                   4065:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4066:                   "while attempting courseidputhash\n", $userinput);
                   4067:     }
                   4068:     return 1;
                   4069: }
                   4070: &register_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
                   4071: 
1.234     foxr     4072: #  Retrieves the value of a course id resource keyword pattern
                   4073: #  defined since a starting date.  Both the starting date and the
                   4074: #  keyword pattern are optional.  If the starting date is not supplied it
                   4075: #  is treated as the beginning of time.  If the pattern is not found,
                   4076: #  it is treatred as "." matching everything.
                   4077: #
                   4078: #  Parameters:
                   4079: #     $cmd     - Command keyword that resulted in us being dispatched.
                   4080: #     $tail    - The remainder of the command that, in this case, consists
                   4081: #                of a colon separated list of:
                   4082: #                 domain   - The domain in which the course database is 
                   4083: #                            defined.
                   4084: #                 since    - Optional parameter describing the minimum
                   4085: #                            time of definition(?) of the resources that
                   4086: #                            will match the dump.
                   4087: #                 description - regular expression that is used to filter
                   4088: #                            the dump.  Only keywords matching this regexp
                   4089: #                            will be used.
1.272     raeburn  4090: #                 institutional code - optional supplied code to filter 
                   4091: #                            the dump. Only courses with an institutional code 
                   4092: #                            that match the supplied code will be returned.
1.336     raeburn  4093: #                 owner    - optional supplied username and domain of owner to
                   4094: #                            filter the dump.  Only courses for which the course
                   4095: #                            owner matches the supplied username and/or domain
                   4096: #                            will be returned. Pre-2.2.0 legacy entries from 
                   4097: #                            nohist_courseiddump will only contain usernames.
1.384     raeburn  4098: #                 type     - optional parameter for selection 
1.418     raeburn  4099: #                 regexp_ok - if 1 or -1 allow the supplied institutional code
                   4100: #                            filter to behave as a regular expression:
                   4101: #	                      1 will not exclude the course if the instcode matches the RE 
                   4102: #                            -1 will exclude the course if the instcode matches the RE
1.384     raeburn  4103: #                 rtn_as_hash - whether to return the information available for
                   4104: #                            each matched item as a frozen hash of all 
                   4105: #                            key, value pairs in the item's hash, or as a 
                   4106: #                            colon-separated list of (in order) description,
                   4107: #                            institutional code, and course owner.
1.404     raeburn  4108: #                 selfenrollonly - filter by courses allowing self-enrollment  
                   4109: #                                  now or in the future (selfenrollonly = 1).
                   4110: #                 catfilter - filter by course category, assigned to a course 
                   4111: #                             using manually defined categories (i.e., not
1.407     raeburn  4112: #                             self-cataloging based on on institutional code).   
1.404     raeburn  4113: #                 showhidden - include course in results even if course  
1.407     raeburn  4114: #                              was set to be excluded from course catalog (DC only).
1.404     raeburn  4115: #                 caller -  if set to 'coursecatalog', courses set to be hidden
                   4116: #                           from course catalog will be excluded from results (unless
                   4117: #                           overridden by "showhidden".
1.427     raeburn  4118: #                 cloner - escaped username:domain of course cloner (if picking course to
1.419     raeburn  4119: #                          clone).
                   4120: #                 cc_clone_list - escaped comma separated list of courses for which 
                   4121: #                                 course cloner has active CC role (and so can clone
                   4122: #                                 automatically).
1.427     raeburn  4123: #                 cloneonly - filter by courses for which cloner has rights to clone.
                   4124: #                 createdbefore - include courses for which creation date preceeded this date.
                   4125: #                 createdafter - include courses for which creation date followed this date.
                   4126: #                 creationcontext - include courses created in specified context 
1.404     raeburn  4127: #
1.445     raeburn  4128: #                 domcloner - flag to indicate if user can create CCs in course's domain.
1.505     raeburn  4129: #                             If so, ability to clone course is automatic.
                   4130: #                 hasuniquecode - filter by courses for which a six character unique code has 
                   4131: #                                 been set.
1.445     raeburn  4132: #
1.234     foxr     4133: #     $client  - The socket open on the client.
                   4134: # Returns:
                   4135: #    1     - Continue processing.
                   4136: # Side Effects:
                   4137: #   a reply is written to $client.
                   4138: sub dump_course_id_handler {
                   4139:     my ($cmd, $tail, $client) = @_;
1.494     droeschl 4140: 
                   4141:     my $res = LONCAPA::Lond::dump_course_id_handler($tail);
                   4142:     if ($res =~ /^error:/) {
                   4143:         Failure($client, \$res, "$cmd:$tail");
                   4144:     } else {
                   4145:         Reply($client, \$res, "$cmd:$tail");
                   4146:     }
                   4147: 
                   4148:     return 1;  
                   4149: 
                   4150:     #TODO remove
1.234     foxr     4151:     my $userinput = "$cmd:$tail";
                   4152: 
1.333     raeburn  4153:     my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404     raeburn  4154:         $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427     raeburn  4155:         $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505     raeburn  4156:         $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397     raeburn  4157:     my $now = time;
1.419     raeburn  4158:     my ($cloneruname,$clonerudom,%cc_clone);
1.234     foxr     4159:     if (defined($description)) {
                   4160: 	$description=&unescape($description);
                   4161:     } else {
                   4162: 	$description='.';
                   4163:     }
1.266     raeburn  4164:     if (defined($instcodefilter)) {
                   4165:         $instcodefilter=&unescape($instcodefilter);
                   4166:     } else {
                   4167:         $instcodefilter='.';
                   4168:     }
1.336     raeburn  4169:     my ($ownerunamefilter,$ownerdomfilter);
1.266     raeburn  4170:     if (defined($ownerfilter)) {
                   4171:         $ownerfilter=&unescape($ownerfilter);
1.336     raeburn  4172:         if ($ownerfilter ne '.' && defined($ownerfilter)) {
                   4173:             if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
                   4174:                  $ownerunamefilter = $1;
                   4175:                  $ownerdomfilter = $2;
                   4176:             } else {
                   4177:                 $ownerunamefilter = $ownerfilter;
                   4178:                 $ownerdomfilter = '';
                   4179:             }
                   4180:         }
1.266     raeburn  4181:     } else {
                   4182:         $ownerfilter='.';
                   4183:     }
1.336     raeburn  4184: 
1.282     raeburn  4185:     if (defined($coursefilter)) {
                   4186:         $coursefilter=&unescape($coursefilter);
                   4187:     } else {
                   4188:         $coursefilter='.';
                   4189:     }
1.333     raeburn  4190:     if (defined($typefilter)) {
                   4191:         $typefilter=&unescape($typefilter);
                   4192:     } else {
                   4193:         $typefilter='.';
                   4194:     }
1.344     raeburn  4195:     if (defined($regexp_ok)) {
                   4196:         $regexp_ok=&unescape($regexp_ok);
                   4197:     }
1.401     raeburn  4198:     if (defined($catfilter)) {
                   4199:         $catfilter=&unescape($catfilter);
                   4200:     }
1.419     raeburn  4201:     if (defined($cloner)) {
                   4202:         $cloner = &unescape($cloner);
                   4203:         ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/); 
                   4204:     }
                   4205:     if (defined($cc_clone_list)) {
                   4206:         $cc_clone_list = &unescape($cc_clone_list);
                   4207:         my @cc_cloners = split('&',$cc_clone_list);
                   4208:         foreach my $cid (@cc_cloners) {
                   4209:             my ($clonedom,$clonenum) = split(':',$cid);
                   4210:             next if ($clonedom ne $udom); 
                   4211:             $cc_clone{$clonedom.'_'.$clonenum} = 1;
                   4212:         } 
                   4213:     }
1.431     raeburn  4214:     if ($createdbefore ne '') {
1.427     raeburn  4215:         $createdbefore = &unescape($createdbefore);
                   4216:     } else {
                   4217:        $createdbefore = 0;
                   4218:     }
1.431     raeburn  4219:     if ($createdafter ne '') {
1.427     raeburn  4220:         $createdafter = &unescape($createdafter);
                   4221:     } else {
                   4222:         $createdafter = 0;
                   4223:     }
1.431     raeburn  4224:     if ($creationcontext ne '') {
1.427     raeburn  4225:         $creationcontext = &unescape($creationcontext);
                   4226:     } else {
                   4227:         $creationcontext = '.';
                   4228:     }
1.505     raeburn  4229:     unless ($hasuniquecode) {
                   4230:         $hasuniquecode = '.';
                   4231:     }
1.384     raeburn  4232:     my $unpack = 1;
1.485     raeburn  4233:     if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' && 
1.384     raeburn  4234:         $typefilter eq '.') {
                   4235:         $unpack = 0;
                   4236:     }
                   4237:     if (!defined($since)) { $since=0; }
1.234     foxr     4238:     my $qresult='';
                   4239:     my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
                   4240:     if ($hashref) {
1.384     raeburn  4241: 	while (my ($key,$value) = each(%$hashref)) {
1.397     raeburn  4242:             my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427     raeburn  4243:                 %unesc_val,$selfenroll_end,$selfenroll_types,$created,
                   4244:                 $context);
1.384     raeburn  4245:             $unesc_key = &unescape($key);
                   4246:             if ($unesc_key =~ /^lasttime:/) {
                   4247:                 next;
                   4248:             } else {
                   4249:                 $lasttime_key = &escape('lasttime:'.$unesc_key);
                   4250:             }
                   4251:             if ($hashref->{$lasttime_key} ne '') {
                   4252:                 $lasttime = $hashref->{$lasttime_key};
                   4253:                 next if ($lasttime<$since);
                   4254:             }
1.419     raeburn  4255:             my ($canclone,$valchange);
1.384     raeburn  4256:             my $items = &Apache::lonnet::thaw_unescape($value);
                   4257:             if (ref($items) eq 'HASH') {
1.429     raeburn  4258:                 if ($hashref->{$lasttime_key} eq '') {
1.430     raeburn  4259:                     next if ($since > 1);
1.429     raeburn  4260:                 }
1.384     raeburn  4261:                 $is_hash =  1;
1.445     raeburn  4262:                 if ($domcloner) {
                   4263:                     $canclone = 1;
                   4264:                 } elsif (defined($clonerudom)) {
1.419     raeburn  4265:                     if ($items->{'cloners'}) {
                   4266:                         my @cloneable = split(',',$items->{'cloners'});
                   4267:                         if (@cloneable) {
                   4268:                             if (grep(/^\*$/,@cloneable))  {
                   4269:                                 $canclone = 1;
                   4270:                             } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
                   4271:                                 $canclone = 1;
                   4272:                             } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
                   4273:                                 $canclone = 1;
                   4274:                             }
                   4275:                         }
                   4276:                         unless ($canclone) {
                   4277:                             if ($cloneruname ne '' && $clonerudom ne '') {
                   4278:                                 if ($cc_clone{$unesc_key}) {
                   4279:                                     $canclone = 1;
                   4280:                                     $items->{'cloners'} .= ','.$cloneruname.':'.
                   4281:                                                            $clonerudom;
                   4282:                                     $valchange = 1;
                   4283:                                 }
                   4284:                             }
                   4285:                         }
                   4286:                     } elsif (defined($cloneruname)) {
                   4287:                         if ($cc_clone{$unesc_key}) {
                   4288:                             $canclone = 1;
                   4289:                             $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4290:                             $valchange = 1;
                   4291:                         }
1.437     raeburn  4292:                         unless ($canclone) {
                   4293:                             if ($items->{'owner'} =~ /:/) {
                   4294:                                 if ($items->{'owner'} eq $cloner) {
                   4295:                                     $canclone = 1;
                   4296:                                 }
1.444     raeburn  4297:                             } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437     raeburn  4298:                                 $canclone = 1;
                   4299:                             }
                   4300:                             if ($canclone) {
                   4301:                                 $items->{'cloners'} = $cloneruname.':'.$clonerudom;
                   4302:                                 $valchange = 1;
                   4303:                             }
                   4304:                         }
1.419     raeburn  4305:                     }
                   4306:                 }
1.384     raeburn  4307:                 if ($unpack || !$rtn_as_hash) {
                   4308:                     $unesc_val{'descr'} = $items->{'description'};
                   4309:                     $unesc_val{'inst_code'} = $items->{'inst_code'};
                   4310:                     $unesc_val{'owner'} = $items->{'owner'};
                   4311:                     $unesc_val{'type'} = $items->{'type'};
1.419     raeburn  4312:                     $unesc_val{'cloners'} = $items->{'cloners'};
1.427     raeburn  4313:                     $unesc_val{'created'} = $items->{'created'};
                   4314:                     $unesc_val{'context'} = $items->{'context'};
1.404     raeburn  4315:                 }
                   4316:                 $selfenroll_types = $items->{'selfenroll_types'};
                   4317:                 $selfenroll_end = $items->{'selfenroll_end_date'};
1.427     raeburn  4318:                 $created = $items->{'created'};
                   4319:                 $context = $items->{'context'};
1.505     raeburn  4320:                 if ($hasuniquecode ne '.') {
                   4321:                     next unless ($items->{'uniquecode'});
                   4322:                 }
1.404     raeburn  4323:                 if ($selfenrollonly) {
                   4324:                     next if (!$selfenroll_types);
                   4325:                     if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
                   4326:                         next;
1.397     raeburn  4327:                     }
1.404     raeburn  4328:                 }
1.427     raeburn  4329:                 if ($creationcontext ne '.') {
                   4330:                     next if (($context ne '') && ($context ne $creationcontext));  
                   4331:                 }
                   4332:                 if ($createdbefore > 0) {
                   4333:                     next if (($created eq '') || ($created > $createdbefore));   
                   4334:                 }
                   4335:                 if ($createdafter > 0) {
                   4336:                     next if (($created eq '') || ($created <= $createdafter)); 
                   4337:                 }
1.404     raeburn  4338:                 if ($catfilter ne '') {
1.406     raeburn  4339:                     next if ($items->{'categories'} eq '');
                   4340:                     my @categories = split('&',$items->{'categories'}); 
1.407     raeburn  4341:                     next if (@categories == 0);
                   4342:                     my @subcats = split('&',$catfilter);
                   4343:                     my $matchcat = 0;
                   4344:                     foreach my $cat (@categories) {
                   4345:                         if (grep(/^\Q$cat\E$/,@subcats)) {
                   4346:                             $matchcat = 1;
                   4347:                             last;
                   4348:                         }
                   4349:                     }
                   4350:                     next if (!$matchcat);
1.404     raeburn  4351:                 }
                   4352:                 if ($caller eq 'coursecatalog') {
1.405     raeburn  4353:                     if ($items->{'hidefromcat'} eq 'yes') {
                   4354:                         next if !$showhidden;
1.401     raeburn  4355:                     }
1.384     raeburn  4356:                 }
1.383     raeburn  4357:             } else {
1.401     raeburn  4358:                 next if ($catfilter ne '');
1.419     raeburn  4359:                 next if ($selfenrollonly);
1.427     raeburn  4360:                 next if ($createdbefore || $createdafter);
                   4361:                 next if ($creationcontext ne '.');
1.419     raeburn  4362:                 if ((defined($clonerudom)) && (defined($cloneruname)))  {
                   4363:                     if ($cc_clone{$unesc_key}) {
                   4364:                         $canclone = 1;
                   4365:                         $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
                   4366:                     }
                   4367:                 }
1.384     raeburn  4368:                 $is_hash =  0;
1.388     raeburn  4369:                 my @courseitems = split(/:/,$value);
1.403     raeburn  4370:                 $lasttime = pop(@courseitems);
1.402     raeburn  4371:                 if ($hashref->{$lasttime_key} eq '') {
                   4372:                     next if ($lasttime<$since);
                   4373:                 }
1.384     raeburn  4374: 	        ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383     raeburn  4375:             }
1.419     raeburn  4376:             if ($cloneonly) {
                   4377:                next unless ($canclone);
                   4378:             }
1.266     raeburn  4379:             my $match = 1;
1.384     raeburn  4380: 	    if ($description ne '.') {
                   4381:                 if (!$is_hash) {
                   4382:                     $unesc_val{'descr'} = &unescape($val{'descr'});
                   4383:                 }
                   4384:                 if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266     raeburn  4385:                     $match = 0;
1.384     raeburn  4386:                 }
1.266     raeburn  4387:             }
1.384     raeburn  4388:             if ($instcodefilter ne '.') {
                   4389:                 if (!$is_hash) {
                   4390:                     $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
                   4391:                 }
1.418     raeburn  4392:                 if ($regexp_ok == 1) {
1.384     raeburn  4393:                     if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344     raeburn  4394:                         $match = 0;
                   4395:                     }
1.418     raeburn  4396:                 } elsif ($regexp_ok == -1) {
                   4397:                     if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
                   4398:                         $match = 0;
                   4399:                     }
1.344     raeburn  4400:                 } else {
1.384     raeburn  4401:                     if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344     raeburn  4402:                         $match = 0;
                   4403:                     }
1.266     raeburn  4404:                 }
1.234     foxr     4405: 	    }
1.384     raeburn  4406:             if ($ownerfilter ne '.') {
                   4407:                 if (!$is_hash) {
                   4408:                     $unesc_val{'owner'} = &unescape($val{'owner'});
                   4409:                 }
1.336     raeburn  4410:                 if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384     raeburn  4411:                     if ($unesc_val{'owner'} =~ /:/) {
                   4412:                         if (eval{$unesc_val{'owner'} !~ 
                   4413:                              /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336     raeburn  4414:                             $match = 0;
                   4415:                         } 
                   4416:                     } else {
1.384     raeburn  4417:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4418:                             $match = 0;
                   4419:                         }
                   4420:                     }
                   4421:                 } elsif ($ownerunamefilter ne '') {
1.384     raeburn  4422:                     if ($unesc_val{'owner'} =~ /:/) {
                   4423:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336     raeburn  4424:                              $match = 0;
                   4425:                         }
                   4426:                     } else {
1.384     raeburn  4427:                         if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336     raeburn  4428:                             $match = 0;
                   4429:                         }
                   4430:                     }
                   4431:                 } elsif ($ownerdomfilter ne '') {
1.384     raeburn  4432:                     if ($unesc_val{'owner'} =~ /:/) {
                   4433:                         if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336     raeburn  4434:                              $match = 0;
                   4435:                         }
                   4436:                     } else {
                   4437:                         if ($ownerdomfilter ne $udom) {
                   4438:                             $match = 0;
                   4439:                         }
                   4440:                     }
1.266     raeburn  4441:                 }
                   4442:             }
1.384     raeburn  4443:             if ($coursefilter ne '.') {
                   4444:                 if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282     raeburn  4445:                     $match = 0;
                   4446:                 }
                   4447:             }
1.384     raeburn  4448:             if ($typefilter ne '.') {
                   4449:                 if (!$is_hash) {
                   4450:                     $unesc_val{'type'} = &unescape($val{'type'});
                   4451:                 }
                   4452:                 if ($unesc_val{'type'} eq '') {
1.333     raeburn  4453:                     if ($typefilter ne 'Course') {
                   4454:                         $match = 0;
                   4455:                     }
1.383     raeburn  4456:                 } else {
1.384     raeburn  4457:                     if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333     raeburn  4458:                         $match = 0;
                   4459:                     }
                   4460:                 }
                   4461:             }
1.266     raeburn  4462:             if ($match == 1) {
1.384     raeburn  4463:                 if ($rtn_as_hash) {
                   4464:                     if ($is_hash) {
1.419     raeburn  4465:                         if ($valchange) {
                   4466:                             my $newvalue = &Apache::lonnet::freeze_escape($items);
                   4467:                             $qresult.=$key.'='.$newvalue.'&';
                   4468:                         } else {
                   4469:                             $qresult.=$key.'='.$value.'&';
                   4470:                         }
1.384     raeburn  4471:                     } else {
1.388     raeburn  4472:                         my %rtnhash = ( 'description' => &unescape($val{'descr'}),
                   4473:                                         'inst_code' => &unescape($val{'inst_code'}),
                   4474:                                         'owner'     => &unescape($val{'owner'}),
                   4475:                                         'type'      => &unescape($val{'type'}),
1.419     raeburn  4476:                                         'cloners'   => &unescape($val{'cloners'}),
1.384     raeburn  4477:                                       );
                   4478:                         my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
                   4479:                         $qresult.=$key.'='.$items.'&';
                   4480:                     }
1.383     raeburn  4481:                 } else {
1.384     raeburn  4482:                     if ($is_hash) {
                   4483:                         $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
                   4484:                                     &escape($unesc_val{'inst_code'}).':'.
                   4485:                                     &escape($unesc_val{'owner'}).'&';
                   4486:                     } else {
                   4487:                         $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
                   4488:                                     ':'.$val{'owner'}.'&';
                   4489:                     }
1.383     raeburn  4490:                 }
1.266     raeburn  4491:             }
1.234     foxr     4492: 	}
1.311     albertel 4493: 	if (&untie_domain_hash($hashref)) {
1.234     foxr     4494: 	    chop($qresult);
1.387     albertel 4495: 	    &Reply($client, \$qresult, $userinput);
1.234     foxr     4496: 	} else {
                   4497: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4498: 		    "while attempting courseiddump\n", $userinput);
                   4499: 	}
                   4500:     } else {
                   4501: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4502: 		"while attempting courseiddump\n", $userinput);
                   4503:     }
                   4504:     return 1;
                   4505: }
                   4506: &register_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238     foxr     4507: 
1.438     raeburn  4508: sub course_lastaccess_handler {
                   4509:     my ($cmd, $tail, $client) = @_;
                   4510:     my $userinput = "$cmd:$tail";
                   4511:     my ($cdom,$cnum) = split(':',$tail); 
                   4512:     my (%lastaccess,$qresult);
                   4513:     my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
                   4514:     if ($hashref) {
                   4515:         while (my ($key,$value) = each(%$hashref)) {
                   4516:             my ($unesc_key,$lasttime);
                   4517:             $unesc_key = &unescape($key);
                   4518:             if ($cnum) {
                   4519:                 next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
                   4520:             }
                   4521:             if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
                   4522:                 $lastaccess{$1} = $value;
                   4523:             } else {
                   4524:                 my $items = &Apache::lonnet::thaw_unescape($value);
                   4525:                 if (ref($items) eq 'HASH') {
                   4526:                     unless ($lastaccess{$unesc_key}) {
                   4527:                         $lastaccess{$unesc_key} = '';
                   4528:                     }
                   4529:                 } else {
                   4530:                     my @courseitems = split(':',$value);
                   4531:                     $lastaccess{$unesc_key} = pop(@courseitems);
                   4532:                 }
                   4533:             }
                   4534:         }
                   4535:         foreach my $cid (sort(keys(%lastaccess))) {
                   4536:             $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&'; 
                   4537:         }
                   4538:         if (&untie_domain_hash($hashref)) {
                   4539:             if ($qresult) {
                   4540:                 chop($qresult);
                   4541:             }
                   4542:             &Reply($client, \$qresult, $userinput);
                   4543:         } else {
                   4544:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4545:                     "while attempting lastacourseaccess\n", $userinput);
                   4546:         }
                   4547:     } else {
                   4548:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4549:                 "while attempting lastcourseaccess\n", $userinput);
                   4550:     }
                   4551:     return 1;
                   4552: }
                   4553: &register_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
                   4554: 
1.238     foxr     4555: #
1.348     raeburn  4556: # Puts an unencrypted entry in a namespace db file at the domain level 
                   4557: #
                   4558: # Parameters:
                   4559: #    $cmd      - The command that got us here.
                   4560: #    $tail     - Tail of the command (remaining parameters).
                   4561: #    $client   - File descriptor connected to client.
                   4562: # Returns
                   4563: #     0        - Requested to exit, caller should shut down.
                   4564: #     1        - Continue processing.
                   4565: #  Side effects:
                   4566: #     reply is written to $client.
                   4567: #
                   4568: sub put_domain_handler {
                   4569:     my ($cmd,$tail,$client) = @_;
                   4570: 
                   4571:     my $userinput = "$cmd:$tail";
                   4572: 
                   4573:     my ($udom,$namespace,$what) =split(/:/,$tail,3);
                   4574:     chomp($what);
                   4575:     my @pairs=split(/\&/,$what);
                   4576:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
                   4577:                                    "P", $what);
                   4578:     if ($hashref) {
                   4579:         foreach my $pair (@pairs) {
                   4580:             my ($key,$value)=split(/=/,$pair);
                   4581:             $hashref->{$key}=$value;
                   4582:         }
                   4583:         if (&untie_domain_hash($hashref)) {
                   4584:             &Reply($client, "ok\n", $userinput);
                   4585:         } else {
                   4586:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4587:                      "while attempting putdom\n", $userinput);
                   4588:         }
                   4589:     } else {
                   4590:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4591:                   "while attempting putdom\n", $userinput);
                   4592:     }
                   4593: 
                   4594:     return 1;
                   4595: }
                   4596: &register_handler("putdom", \&put_domain_handler, 0, 1, 0);
                   4597: 
1.517     raeburn  4598: # Updates one or more entries in clickers.db file at the domain level
                   4599: #
                   4600: # Parameters:
                   4601: #    $cmd      - The command that got us here.
                   4602: #    $tail     - Tail of the command (remaining parameters).
                   4603: #                In this case a colon separated list containing:
                   4604: #                (a) the domain for which we are updating the entries,
                   4605: #                (b) the action required -- add or del -- and
                   4606: #                (c) a &-separated list of entries to add or delete.
                   4607: #    $client   - File descriptor connected to client.
                   4608: # Returns
                   4609: #     1        - Continue processing.
                   4610: #     0        - Requested to exit, caller should shut down.
                   4611: #  Side effects:
                   4612: #     reply is written to $client.
                   4613: #
                   4614: 
                   4615: 
                   4616: sub update_clickers {
                   4617:     my ($cmd, $tail, $client)  = @_;
                   4618: 
                   4619:     my $userinput = "$cmd:$tail";
                   4620:     my ($udom,$action,$what) =split(/:/,$tail,3);
                   4621:     chomp($what);
                   4622: 
                   4623:     my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
                   4624:                                  "U","$action:$what");
                   4625: 
                   4626:     if (!$hashref) {
                   4627:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4628:                   "while attempting updateclickers\n", $userinput);
                   4629:         return 1;
                   4630:     }
                   4631: 
                   4632:     my @pairs=split(/\&/,$what);
                   4633:     foreach my $pair (@pairs) {
                   4634:         my ($key,$value)=split(/=/,$pair);
                   4635:         if ($action eq 'add') {
                   4636:             if (exists($hashref->{$key})) {
                   4637:                 my @newvals = split(/,/,&unescape($value));
                   4638:                 my @currvals = split(/,/,&unescape($hashref->{$key}));
                   4639:                 my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
                   4640:                 $hashref->{$key}=&escape(join(',',@merged));
                   4641:             } else {
                   4642:                 $hashref->{$key}=$value;
                   4643:             }
                   4644:         } elsif ($action eq 'del') {
                   4645:             if (exists($hashref->{$key})) {
                   4646:                 my %current;
                   4647:                 map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
                   4648:                 map { delete($current{$_}); } split(/,/,&unescape($value));
                   4649:                 if (keys(%current)) {
                   4650:                     $hashref->{$key}=&escape(join(',',sort(keys(%current))));
                   4651:                 } else {
                   4652:                     delete($hashref->{$key});
                   4653:                 }
                   4654:             }
                   4655:         }
                   4656:     }
                   4657:     if (&untie_user_hash($hashref)) {
                   4658:         &Reply( $client, "ok\n", $userinput);
                   4659:     } else {
                   4660:         &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
                   4661:                  "while attempting put\n",
                   4662:                  $userinput);
                   4663:     }
                   4664:     return 1;
                   4665: }
                   4666: &register_handler("updateclickers", \&update_clickers, 0, 1, 0);
                   4667: 
                   4668: 
                   4669: # Deletes one or more entries in a namespace db file at the domain level
                   4670: #
                   4671: # Parameters:
                   4672: #    $cmd      - The command that got us here.
                   4673: #    $tail     - Tail of the command (remaining parameters).
                   4674: #                In this case a colon separated list containing:
                   4675: #                (a) the domain for which we are deleting the entries,
                   4676: #                (b) &-separated list of keys to delete.  
                   4677: #    $client   - File descriptor connected to client.
                   4678: # Returns
                   4679: #     1        - Continue processing.
                   4680: #     0        - Requested to exit, caller should shut down.
                   4681: #  Side effects:
                   4682: #     reply is written to $client.
                   4683: #
                   4684: 
                   4685: sub del_domain_handler {
                   4686:     my ($cmd,$tail,$client) = @_;
                   4687: 
                   4688:     my $userinput = "$cmd:$tail";
                   4689: 
                   4690:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4691:     chomp($what);
                   4692:     my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
                   4693:                                    "D", $what);
                   4694:     if ($hashref) {
                   4695:         my @keys=split(/\&/,$what);
                   4696:         foreach my $key (@keys) {
                   4697:             delete($hashref->{$key});
                   4698:         }
                   4699:         if (&untie_user_hash($hashref)) {
                   4700:             &Reply($client, "ok\n", $userinput);
                   4701:         } else {
                   4702:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4703:                     "while attempting deldom\n", $userinput);
                   4704:         }
                   4705:     } else {
                   4706:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4707:                  "while attempting deldom\n", $userinput);
                   4708:     }
                   4709:     return 1;
                   4710: }
                   4711: &register_handler("deldom", \&del_domain_handler, 0, 1, 0);
                   4712: 
                   4713: 
1.348     raeburn  4714: # Unencrypted get from the namespace database file at the domain level.
                   4715: # This function retrieves a keyed item from a specific named database in the
                   4716: # domain directory.
                   4717: #
                   4718: # Parameters:
                   4719: #   $cmd             - Command request keyword (get).
                   4720: #   $tail            - Tail of the command.  This is a colon separated list
                   4721: #                      consisting of the domain and the 'namespace' 
                   4722: #                      which selects the gdbm file to do the lookup in,
                   4723: #                      & separated list of keys to lookup.  Note that
                   4724: #                      the values are returned as an & separated list too.
                   4725: #   $client          - File descriptor open on the client.
                   4726: # Returns:
                   4727: #   1       - Continue processing.
                   4728: #   0       - Exit.
                   4729: #  Side effects:
                   4730: #     reply is written to $client.
                   4731: #
                   4732: 
                   4733: sub get_domain_handler {
                   4734:     my ($cmd, $tail, $client) = @_;
                   4735: 
1.461     foxr     4736: 
1.348     raeburn  4737:     my $userinput = "$client:$tail";
                   4738: 
                   4739:     my ($udom,$namespace,$what)=split(/:/,$tail,3);
                   4740:     chomp($what);
                   4741:     my @queries=split(/\&/,$what);
                   4742:     my $qresult='';
                   4743:     my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
                   4744:     if ($hashref) {
                   4745:         for (my $i=0;$i<=$#queries;$i++) {
                   4746:             $qresult.="$hashref->{$queries[$i]}&";
                   4747:         }
                   4748:         if (&untie_domain_hash($hashref)) {
                   4749:             $qresult=~s/\&$//;
1.387     albertel 4750:             &Reply($client, \$qresult, $userinput);
1.348     raeburn  4751:         } else {
                   4752:             &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4753:                       "while attempting getdom\n",$userinput);
                   4754:         }
                   4755:     } else {
                   4756:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4757:                  "while attempting getdom\n",$userinput);
                   4758:     }
                   4759: 
                   4760:     return 1;
                   4761: }
1.360     raeburn  4762: &register_handler("getdom", \&get_domain_handler, 0, 1, 0);
1.348     raeburn  4763: 
1.420     raeburn  4764: #
1.238     foxr     4765: #  Puts an id to a domains id database. 
                   4766: #
                   4767: #  Parameters:
                   4768: #   $cmd     - The command that triggered us.
                   4769: #   $tail    - Remainder of the request other than the command. This is a 
                   4770: #              colon separated list containing:
                   4771: #              $domain  - The domain for which we are writing the id.
                   4772: #              $pairs  - The id info to write... this is and & separated list
                   4773: #                        of keyword=value.
                   4774: #   $client  - Socket open on the client.
                   4775: #  Returns:
                   4776: #    1   - Continue processing.
                   4777: #  Side effects:
                   4778: #     reply is written to $client.
                   4779: #
                   4780: sub put_id_handler {
                   4781:     my ($cmd,$tail,$client) = @_;
                   4782: 
                   4783: 
                   4784:     my $userinput = "$cmd:$tail";
                   4785: 
                   4786:     my ($udom,$what)=split(/:/,$tail);
                   4787:     chomp($what);
                   4788:     my @pairs=split(/\&/,$what);
                   4789:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   4790: 				   "P", $what);
                   4791:     if ($hashref) {
                   4792: 	foreach my $pair (@pairs) {
                   4793: 	    my ($key,$value)=split(/=/,$pair);
                   4794: 	    $hashref->{$key}=$value;
                   4795: 	}
1.311     albertel 4796: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     4797: 	    &Reply($client, "ok\n", $userinput);
                   4798: 	} else {
                   4799: 	    &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4800: 		     "while attempting idput\n", $userinput);
                   4801: 	}
                   4802:     } else {
                   4803: 	&Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4804: 		  "while attempting idput\n", $userinput);
                   4805:     }
                   4806: 
                   4807:     return 1;
                   4808: }
1.263     albertel 4809: &register_handler("idput", \&put_id_handler, 0, 1, 0);
1.238     foxr     4810: 
                   4811: #
                   4812: #  Retrieves a set of id values from the id database.
                   4813: #  Returns an & separated list of results, one for each requested id to the
                   4814: #  client.
                   4815: #
                   4816: # Parameters:
                   4817: #   $cmd       - Command keyword that caused us to be dispatched.
                   4818: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4819: #               domain - the domain whose id table we dump
                   4820: #               ids      Consists of an & separated list of
                   4821: #                        id keywords whose values will be fetched.
                   4822: #                        nonexisting keywords will have an empty value.
                   4823: #   $client    - Socket open on the client.
                   4824: #
                   4825: # Returns:
                   4826: #    1 - indicating processing should continue.
                   4827: # Side effects:
                   4828: #   An & separated list of results is written to $client.
                   4829: #
                   4830: sub get_id_handler {
                   4831:     my ($cmd, $tail, $client) = @_;
                   4832: 
                   4833:     
                   4834:     my $userinput = "$client:$tail";
                   4835:     
                   4836:     my ($udom,$what)=split(/:/,$tail);
                   4837:     chomp($what);
                   4838:     my @queries=split(/\&/,$what);
                   4839:     my $qresult='';
                   4840:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
                   4841:     if ($hashref) {
                   4842: 	for (my $i=0;$i<=$#queries;$i++) {
                   4843: 	    $qresult.="$hashref->{$queries[$i]}&";
                   4844: 	}
1.311     albertel 4845: 	if (&untie_domain_hash($hashref)) {
1.238     foxr     4846: 	    $qresult=~s/\&$//;
1.387     albertel 4847: 	    &Reply($client, \$qresult, $userinput);
1.238     foxr     4848: 	} else {
                   4849: 	    &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4850: 		      "while attempting idget\n",$userinput);
                   4851: 	}
                   4852:     } else {
                   4853: 	&Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4854: 		 "while attempting idget\n",$userinput);
                   4855:     }
                   4856:     
                   4857:     return 1;
                   4858: }
1.263     albertel 4859: &register_handler("idget", \&get_id_handler, 0, 1, 0);
1.238     foxr     4860: 
1.501     raeburn  4861: #   Deletes one or more ids in a domain's id database.
                   4862: #
                   4863: #   Parameters:
                   4864: #       $cmd                  - Command keyword (iddel).
                   4865: #       $tail                 - Command tail.  In this case a colon
                   4866: #                               separated list containing:
                   4867: #                               The domain for which we are deleting the id(s).
                   4868: #                               &-separated list of id(s) to delete.
                   4869: #       $client               - File open on client socket.
                   4870: # Returns:
                   4871: #     1   - Continue processing
                   4872: #     0   - Exit server.
                   4873: #     
                   4874: #
                   4875: 
                   4876: sub del_id_handler {
                   4877:     my ($cmd,$tail,$client) = @_;
                   4878: 
                   4879:     my $userinput = "$cmd:$tail";
                   4880: 
                   4881:     my ($udom,$what)=split(/:/,$tail);
                   4882:     chomp($what);
                   4883:     my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
                   4884:                                    "D", $what);
                   4885:     if ($hashref) {
                   4886:         my @keys=split(/\&/,$what);
                   4887:         foreach my $key (@keys) {
                   4888:             delete($hashref->{$key});
                   4889:         }
                   4890:         if (&untie_user_hash($hashref)) {
                   4891:             &Reply($client, "ok\n", $userinput);
                   4892:         } else {
                   4893:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4894:                     "while attempting iddel\n", $userinput);
                   4895:         }
                   4896:     } else {
                   4897:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   4898:                  "while attempting iddel\n", $userinput);
                   4899:     }
                   4900:     return 1;
                   4901: }
                   4902: &register_handler("iddel", \&del_id_handler, 0, 1, 0);
                   4903: 
1.238     foxr     4904: #
1.299     raeburn  4905: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database 
                   4906: #
                   4907: # Parameters
                   4908: #   $cmd       - Command keyword that caused us to be dispatched.
                   4909: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4910: #               domain - the domain whose dcmail we are recording
                   4911: #               email    Consists of key=value pair 
                   4912: #                        where key is unique msgid
                   4913: #                        and value is message (in XML)
                   4914: #   $client    - Socket open on the client.
                   4915: #
                   4916: # Returns:
                   4917: #    1 - indicating processing should continue.
                   4918: # Side effects
                   4919: #     reply is written to $client.
                   4920: #
                   4921: sub put_dcmail_handler {
                   4922:     my ($cmd,$tail,$client) = @_;
                   4923:     my $userinput = "$cmd:$tail";
1.463     foxr     4924: 
                   4925: 
1.299     raeburn  4926:     my ($udom,$what)=split(/:/,$tail);
                   4927:     chomp($what);
                   4928:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   4929:     if ($hashref) {
                   4930:         my ($key,$value)=split(/=/,$what);
                   4931:         $hashref->{$key}=$value;
                   4932:     }
1.311     albertel 4933:     if (&untie_domain_hash($hashref)) {
1.299     raeburn  4934:         &Reply($client, "ok\n", $userinput);
                   4935:     } else {
                   4936:         &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   4937:                  "while attempting dcmailput\n", $userinput);
                   4938:     }
                   4939:     return 1;
                   4940: }
                   4941: &register_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
                   4942: 
                   4943: #
                   4944: # Retrieves broadcast e-mail from nohist_dcmail database
                   4945: # Returns to client an & separated list of key=value pairs,
                   4946: # where key is msgid and value is message information.
                   4947: #
                   4948: # Parameters
                   4949: #   $cmd       - Command keyword that caused us to be dispatched.
                   4950: #   $tail      - Tail of the command.  Consists of a colon separated:
                   4951: #               domain - the domain whose dcmail table we dump
                   4952: #               startfilter - beginning of time window 
                   4953: #               endfilter - end of time window
                   4954: #               sendersfilter - & separated list of username:domain 
                   4955: #                 for senders to search for.
                   4956: #   $client    - Socket open on the client.
                   4957: #
                   4958: # Returns:
                   4959: #    1 - indicating processing should continue.
                   4960: # Side effects
                   4961: #     reply (& separated list of msgid=messageinfo pairs) is 
                   4962: #     written to $client.
                   4963: #
                   4964: sub dump_dcmail_handler {
                   4965:     my ($cmd, $tail, $client) = @_;
                   4966:                                                                                 
                   4967:     my $userinput = "$cmd:$tail";
                   4968:     my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
                   4969:     chomp($sendersfilter);
                   4970:     my @senders = ();
                   4971:     if (defined($startfilter)) {
                   4972:         $startfilter=&unescape($startfilter);
                   4973:     } else {
                   4974:         $startfilter='.';
                   4975:     }
                   4976:     if (defined($endfilter)) {
                   4977:         $endfilter=&unescape($endfilter);
                   4978:     } else {
                   4979:         $endfilter='.';
                   4980:     }
                   4981:     if (defined($sendersfilter)) {
                   4982:         $sendersfilter=&unescape($sendersfilter);
1.300     albertel 4983: 	@senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299     raeburn  4984:     }
                   4985: 
                   4986:     my $qresult='';
                   4987:     my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
                   4988:     if ($hashref) {
                   4989:         while (my ($key,$value) = each(%$hashref)) {
                   4990:             my $match = 1;
1.303     albertel 4991:             my ($timestamp,$subj,$uname,$udom) = 
                   4992: 		split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299     raeburn  4993:             $subj = &unescape($subj);
                   4994:             unless ($startfilter eq '.' || !defined($startfilter)) {
                   4995:                 if ($timestamp < $startfilter) {
                   4996:                     $match = 0;
                   4997:                 }
                   4998:             }
                   4999:             unless ($endfilter eq '.' || !defined($endfilter)) {
                   5000:                 if ($timestamp > $endfilter) {
                   5001:                     $match = 0;
                   5002:                 }
                   5003:             }
                   5004:             unless (@senders < 1) {
                   5005:                 unless (grep/^$uname:$udom$/,@senders) {
                   5006:                     $match = 0;
                   5007:                 }
                   5008:             }
                   5009:             if ($match == 1) {
                   5010:                 $qresult.=$key.'='.$value.'&';
                   5011:             }
                   5012:         }
1.311     albertel 5013:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5014:             chop($qresult);
1.387     albertel 5015:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5016:         } else {
                   5017:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5018:                     "while attempting dcmaildump\n", $userinput);
                   5019:         }
                   5020:     } else {
                   5021:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5022:                 "while attempting dcmaildump\n", $userinput);
                   5023:     }
                   5024:     return 1;
                   5025: }
                   5026: 
                   5027: &register_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
                   5028: 
                   5029: #
                   5030: # Puts domain roles in nohist_domainroles database
                   5031: #
                   5032: # Parameters
                   5033: #   $cmd       - Command keyword that caused us to be dispatched.
                   5034: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5035: #               domain - the domain whose roles we are recording  
                   5036: #               role -   Consists of key=value pair
                   5037: #                        where key is unique role
                   5038: #                        and value is start/end date information
                   5039: #   $client    - Socket open on the client.
                   5040: #
                   5041: # Returns:
                   5042: #    1 - indicating processing should continue.
                   5043: # Side effects
                   5044: #     reply is written to $client.
                   5045: #
                   5046: 
                   5047: sub put_domainroles_handler {
                   5048:     my ($cmd,$tail,$client) = @_;
                   5049: 
                   5050:     my $userinput = "$cmd:$tail";
                   5051:     my ($udom,$what)=split(/:/,$tail);
                   5052:     chomp($what);
                   5053:     my @pairs=split(/\&/,$what);
                   5054:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5055:     if ($hashref) {
                   5056:         foreach my $pair (@pairs) {
                   5057:             my ($key,$value)=split(/=/,$pair);
                   5058:             $hashref->{$key}=$value;
                   5059:         }
1.311     albertel 5060:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5061:             &Reply($client, "ok\n", $userinput);
                   5062:         } else {
                   5063:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5064:                      "while attempting domroleput\n", $userinput);
                   5065:         }
                   5066:     } else {
                   5067:         &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5068:                   "while attempting domroleput\n", $userinput);
                   5069:     }
                   5070:                                                                                   
                   5071:     return 1;
                   5072: }
                   5073: 
                   5074: &register_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
                   5075: 
                   5076: #
                   5077: # Retrieves domain roles from nohist_domainroles database
                   5078: # Returns to client an & separated list of key=value pairs,
                   5079: # where key is role and value is start and end date information.
                   5080: #
                   5081: # Parameters
                   5082: #   $cmd       - Command keyword that caused us to be dispatched.
                   5083: #   $tail      - Tail of the command.  Consists of a colon separated:
                   5084: #               domain - the domain whose domain roles table we dump
                   5085: #   $client    - Socket open on the client.
                   5086: #
                   5087: # Returns:
                   5088: #    1 - indicating processing should continue.
                   5089: # Side effects
                   5090: #     reply (& separated list of role=start/end info pairs) is
                   5091: #     written to $client.
                   5092: #
                   5093: sub dump_domainroles_handler {
                   5094:     my ($cmd, $tail, $client) = @_;
                   5095:                                                                                            
                   5096:     my $userinput = "$cmd:$tail";
                   5097:     my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
                   5098:     chomp($rolesfilter);
                   5099:     my @roles = ();
                   5100:     if (defined($startfilter)) {
                   5101:         $startfilter=&unescape($startfilter);
                   5102:     } else {
                   5103:         $startfilter='.';
                   5104:     }
                   5105:     if (defined($endfilter)) {
                   5106:         $endfilter=&unescape($endfilter);
                   5107:     } else {
                   5108:         $endfilter='.';
                   5109:     }
                   5110:     if (defined($rolesfilter)) {
                   5111:         $rolesfilter=&unescape($rolesfilter);
1.300     albertel 5112: 	@roles = split(/\&/,$rolesfilter);
1.299     raeburn  5113:     }
1.421     raeburn  5114: 
1.299     raeburn  5115:     my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
                   5116:     if ($hashref) {
                   5117:         my $qresult = '';
                   5118:         while (my ($key,$value) = each(%$hashref)) {
                   5119:             my $match = 1;
1.421     raeburn  5120:             my ($end,$start) = split(/:/,&unescape($value));
1.299     raeburn  5121:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421     raeburn  5122:             unless (@roles < 1) {
                   5123:                 unless (grep/^\Q$trole\E$/,@roles) {
                   5124:                     $match = 0;
                   5125:                     next;
                   5126:                 }
                   5127:             }
1.299     raeburn  5128:             unless ($startfilter eq '.' || !defined($startfilter)) {
1.415     raeburn  5129:                 if ((defined($start)) && ($start >= $startfilter)) {
1.299     raeburn  5130:                     $match = 0;
1.421     raeburn  5131:                     next;
1.299     raeburn  5132:                 }
                   5133:             }
                   5134:             unless ($endfilter eq '.' || !defined($endfilter)) {
1.421     raeburn  5135:                 if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299     raeburn  5136:                     $match = 0;
1.421     raeburn  5137:                     next;
1.299     raeburn  5138:                 }
                   5139:             }
                   5140:             if ($match == 1) {
                   5141:                 $qresult.=$key.'='.$value.'&';
                   5142:             }
                   5143:         }
1.311     albertel 5144:         if (&untie_domain_hash($hashref)) {
1.299     raeburn  5145:             chop($qresult);
1.387     albertel 5146:             &Reply($client, \$qresult, $userinput);
1.299     raeburn  5147:         } else {
                   5148:             &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
                   5149:                     "while attempting domrolesdump\n", $userinput);
                   5150:         }
                   5151:     } else {
                   5152:         &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
                   5153:                 "while attempting domrolesdump\n", $userinput);
                   5154:     }
                   5155:     return 1;
                   5156: }
                   5157: 
                   5158: &register_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
                   5159: 
                   5160: 
1.238     foxr     5161: #  Process the tmpput command I'm not sure what this does.. Seems to
                   5162: #  create a file in the lonDaemons/tmp directory of the form $id.tmp
                   5163: # where Id is the client's ip concatenated with a sequence number.
                   5164: # The file will contain some value that is passed in.  Is this e.g.
                   5165: # a login token?
                   5166: #
                   5167: # Parameters:
                   5168: #    $cmd     - The command that got us dispatched.
                   5169: #    $tail    - The remainder of the request following $cmd:
                   5170: #               In this case this will be the contents of the file.
                   5171: #    $client  - Socket connected to the client.
                   5172: # Returns:
                   5173: #    1 indicating processing can continue.
                   5174: # Side effects:
                   5175: #   A file is created in the local filesystem.
                   5176: #   A reply is sent to the client.
                   5177: sub tmp_put_handler {
                   5178:     my ($cmd, $what, $client) = @_;
                   5179: 
                   5180:     my $userinput = "$cmd:$what";	# Reconstruct for logging.
                   5181: 
1.347     raeburn  5182:     my ($record,$context) = split(/:/,$what);
                   5183:     if ($context ne '') {
                   5184:         chomp($context);
                   5185:         $context = &unescape($context);
                   5186:     }
                   5187:     my ($id,$store);
1.238     foxr     5188:     $tmpsnum++;
1.454     raeburn  5189:     if (($context eq 'resetpw') || ($context eq 'createaccount')) {
1.347     raeburn  5190:         $id = &md5_hex(&md5_hex(time.{}.rand().$$));
                   5191:     } else {
                   5192:         $id = $$.'_'.$clientip.'_'.$tmpsnum;
                   5193:     }
1.238     foxr     5194:     $id=~s/\W/\_/g;
1.347     raeburn  5195:     $record=~s/\n//g;
1.238     foxr     5196:     my $execdir=$perlvar{'lonDaemons'};
                   5197:     if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
1.347     raeburn  5198: 	print $store $record;
1.238     foxr     5199: 	close $store;
1.387     albertel 5200: 	&Reply($client, \$id, $userinput);
1.238     foxr     5201:     } else {
                   5202: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5203: 		  "while attempting tmpput\n", $userinput);
                   5204:     }
                   5205:     return 1;
                   5206:   
                   5207: }
                   5208: &register_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263     albertel 5209: 
1.238     foxr     5210: #   Processes the tmpget command.  This command returns the contents
                   5211: #  of a temporary resource file(?) created via tmpput.
                   5212: #
                   5213: # Paramters:
                   5214: #    $cmd      - Command that got us dispatched.
                   5215: #    $id       - Tail of the command, contain the id of the resource
                   5216: #                we want to fetch.
                   5217: #    $client   - socket open on the client.
                   5218: # Return:
                   5219: #    1         - Inidcating processing can continue.
                   5220: # Side effects:
                   5221: #   A reply is sent to the client.
                   5222: #
                   5223: sub tmp_get_handler {
                   5224:     my ($cmd, $id, $client) = @_;
                   5225: 
                   5226:     my $userinput = "$cmd:$id"; 
                   5227:     
                   5228: 
                   5229:     $id=~s/\W/\_/g;
                   5230:     my $store;
                   5231:     my $execdir=$perlvar{'lonDaemons'};
                   5232:     if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
                   5233: 	my $reply=<$store>;
1.387     albertel 5234: 	&Reply( $client, \$reply, $userinput);
1.238     foxr     5235: 	close $store;
                   5236:     } else {
                   5237: 	&Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
                   5238: 		  "while attempting tmpget\n", $userinput);
                   5239:     }
                   5240: 
                   5241:     return 1;
                   5242: }
                   5243: &register_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263     albertel 5244: 
1.238     foxr     5245: #
                   5246: #  Process the tmpdel command.  This command deletes a temp resource
                   5247: #  created by the tmpput command.
                   5248: #
                   5249: # Parameters:
                   5250: #   $cmd      - Command that got us here.
                   5251: #   $id       - Id of the temporary resource created.
                   5252: #   $client   - socket open on the client process.
                   5253: #
                   5254: # Returns:
                   5255: #   1     - Indicating processing should continue.
                   5256: # Side Effects:
                   5257: #   A file is deleted
                   5258: #   A reply is sent to the client.
                   5259: sub tmp_del_handler {
                   5260:     my ($cmd, $id, $client) = @_;
                   5261:     
                   5262:     my $userinput= "$cmd:$id";
                   5263:     
                   5264:     chomp($id);
                   5265:     $id=~s/\W/\_/g;
                   5266:     my $execdir=$perlvar{'lonDaemons'};
                   5267:     if (unlink("$execdir/tmp/$id.tmp")) {
                   5268: 	&Reply($client, "ok\n", $userinput);
                   5269:     } else {
                   5270: 	&Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
                   5271: 		  "while attempting tmpdel\n", $userinput);
                   5272:     }
                   5273:     
                   5274:     return 1;
                   5275: 
                   5276: }
                   5277: &register_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263     albertel 5278: 
1.238     foxr     5279: #
1.246     foxr     5280: #   Processes the setannounce command.  This command
                   5281: #   creates a file named announce.txt in the top directory of
                   5282: #   the documentn root and sets its contents.  The announce.txt file is
                   5283: #   printed in its entirety at the LonCAPA login page.  Note:
                   5284: #   once the announcement.txt fileis created it cannot be deleted.
                   5285: #   However, setting the contents of the file to empty removes the
                   5286: #   announcement from the login page of loncapa so who cares.
                   5287: #
                   5288: # Parameters:
                   5289: #    $cmd          - The command that got us dispatched.
                   5290: #    $announcement - The text of the announcement.
                   5291: #    $client       - Socket open on the client process.
                   5292: # Retunrns:
                   5293: #   1             - Indicating request processing should continue
                   5294: # Side Effects:
                   5295: #   The file {DocRoot}/announcement.txt is created.
                   5296: #   A reply is sent to $client.
                   5297: #
                   5298: sub set_announce_handler {
                   5299:     my ($cmd, $announcement, $client) = @_;
                   5300:   
                   5301:     my $userinput    = "$cmd:$announcement";
                   5302: 
                   5303:     chomp($announcement);
                   5304:     $announcement=&unescape($announcement);
                   5305:     if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
                   5306: 				'/announcement.txt')) {
                   5307: 	print $store $announcement;
                   5308: 	close $store;
                   5309: 	&Reply($client, "ok\n", $userinput);
                   5310:     } else {
                   5311: 	&Failure($client, "error: ".($!+0)."\n", $userinput);
                   5312:     }
                   5313: 
                   5314:     return 1;
                   5315: }
                   5316: &register_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263     albertel 5317: 
1.246     foxr     5318: #
                   5319: #  Return the version of the daemon.  This can be used to determine
                   5320: #  the compatibility of cross version installations or, alternatively to
                   5321: #  simply know who's out of date and who isn't.  Note that the version
                   5322: #  is returned concatenated with the tail.
                   5323: # Parameters:
                   5324: #   $cmd        - the request that dispatched to us.
                   5325: #   $tail       - Tail of the request (client's version?).
                   5326: #   $client     - Socket open on the client.
                   5327: #Returns:
                   5328: #   1 - continue processing requests.
                   5329: # Side Effects:
                   5330: #   Replies with version to $client.
                   5331: sub get_version_handler {
                   5332:     my ($cmd, $tail, $client) = @_;
                   5333: 
                   5334:     my $userinput  = $cmd.$tail;
                   5335:     
                   5336:     &Reply($client, &version($userinput)."\n", $userinput);
                   5337: 
                   5338: 
                   5339:     return 1;
                   5340: }
                   5341: &register_handler("version", \&get_version_handler, 0, 1, 0);
1.263     albertel 5342: 
1.246     foxr     5343: #  Set the current host and domain.  This is used to support
                   5344: #  multihomed systems.  Each IP of the system, or even separate daemons
                   5345: #  on the same IP can be treated as handling a separate lonCAPA virtual
                   5346: #  machine.  This command selects the virtual lonCAPA.  The client always
                   5347: #  knows the right one since it is lonc and it is selecting the domain/system
                   5348: #  from the hosts.tab file.
                   5349: # Parameters:
                   5350: #    $cmd      - Command that dispatched us.
                   5351: #    $tail     - Tail of the command (domain/host requested).
                   5352: #    $socket   - Socket open on the client.
                   5353: #
                   5354: # Returns:
                   5355: #     1   - Indicates the program should continue to process requests.
                   5356: # Side-effects:
                   5357: #     The default domain/system context is modified for this daemon.
                   5358: #     a reply is sent to the client.
                   5359: #
                   5360: sub set_virtual_host_handler {
                   5361:     my ($cmd, $tail, $socket) = @_;
                   5362:   
                   5363:     my $userinput  ="$cmd:$tail";
                   5364: 
                   5365:     &Reply($client, &sethost($userinput)."\n", $userinput);
                   5366: 
                   5367: 
                   5368:     return 1;
                   5369: }
1.247     albertel 5370: &register_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246     foxr     5371: 
                   5372: #  Process a request to exit:
                   5373: #   - "bye" is sent to the client.
                   5374: #   - The client socket is shutdown and closed.
                   5375: #   - We indicate to the caller that we should exit.
                   5376: # Formal Parameters:
                   5377: #   $cmd                - The command that got us here.
                   5378: #   $tail               - Tail of the command (empty).
                   5379: #   $client             - Socket open on the tail.
                   5380: # Returns:
                   5381: #   0      - Indicating the program should exit!!
                   5382: #
                   5383: sub exit_handler {
                   5384:     my ($cmd, $tail, $client) = @_;
                   5385: 
                   5386:     my $userinput = "$cmd:$tail";
                   5387: 
                   5388:     &logthis("Client $clientip ($clientname) hanging up: $userinput");
                   5389:     &Reply($client, "bye\n", $userinput);
                   5390:     $client->shutdown(2);        # shutdown the socket forcibly.
                   5391:     $client->close();
                   5392: 
                   5393:     return 0;
                   5394: }
1.248     foxr     5395: &register_handler("exit", \&exit_handler, 0,1,1);
                   5396: &register_handler("init", \&exit_handler, 0,1,1);
                   5397: &register_handler("quit", \&exit_handler, 0,1,1);
                   5398: 
                   5399: #  Determine if auto-enrollment is enabled.
                   5400: #  Note that the original had what I believe to be a defect.
                   5401: #  The original returned 0 if the requestor was not a registerd client.
                   5402: #  It should return "refused".
                   5403: # Formal Parameters:
                   5404: #   $cmd       - The command that invoked us.
                   5405: #   $tail      - The tail of the command (Extra command parameters.
                   5406: #   $client    - The socket open on the client that issued the request.
                   5407: # Returns:
                   5408: #    1         - Indicating processing should continue.
                   5409: #
                   5410: sub enrollment_enabled_handler {
                   5411:     my ($cmd, $tail, $client) = @_;
                   5412:     my $userinput = $cmd.":".$tail; # For logging purposes.
                   5413: 
                   5414:     
1.337     albertel 5415:     my ($cdom) = split(/:/, $tail, 2);   # Domain we're asking about.
                   5416: 
1.248     foxr     5417:     my $outcome  = &localenroll::run($cdom);
1.387     albertel 5418:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5419: 
                   5420:     return 1;
                   5421: }
                   5422: &register_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
                   5423: 
1.417     raeburn  5424: #
1.423     raeburn  5425: #   Validate an institutional code used for a LON-CAPA course.          
1.417     raeburn  5426: #
                   5427: # Formal Parameters:
                   5428: #   $cmd          - The command request that got us dispatched.
                   5429: #   $tail         - The tail of the command.  In this case,
                   5430: #                   this is a colon separated set of words that will be split
                   5431: #                   into:
1.424     raeburn  5432: #                        $dom      - The domain for which the check of 
                   5433: #                                    institutional course code will occur.
                   5434: #
                   5435: #                        $instcode - The institutional code for the course
                   5436: #                                    being requested, or validated for rights
                   5437: #                                    to request.
                   5438: #
                   5439: #                        $owner    - The course requestor (who will be the
                   5440: #                                    course owner, in the form username:domain
                   5441: #
1.417     raeburn  5442: #   $client       - Socket open on the client.
                   5443: # Returns:
                   5444: #    1           - Indicating processing should continue.
                   5445: #
                   5446: sub validate_instcode_handler {
                   5447:     my ($cmd, $tail, $client) = @_;
                   5448:     my $userinput = "$cmd:$tail";
1.423     raeburn  5449:     my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422     raeburn  5450:     $instcode = &unescape($instcode);
                   5451:     $owner = &unescape($owner);
1.498     raeburn  5452:     my ($outcome,$description,$credits) = 
1.426     raeburn  5453:         &localenroll::validate_instcode($dom,$instcode,$owner);
1.498     raeburn  5454:     my $result = &escape($outcome).'&'.&escape($description).'&'.
                   5455:                  &escape($credits);
1.426     raeburn  5456:     &Reply($client, \$result, $userinput);
1.417     raeburn  5457: 
                   5458:     return 1;
                   5459: }
                   5460: &register_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
                   5461: 
1.248     foxr     5462: #   Get the official sections for which auto-enrollment is possible.
                   5463: #   Since the admin people won't know about 'unofficial sections' 
                   5464: #   we cannot auto-enroll on them.
                   5465: # Formal Parameters:
                   5466: #    $cmd     - The command request that got us dispatched here.
                   5467: #    $tail    - The remainder of the request.  In our case this
                   5468: #               will be split into:
                   5469: #               $coursecode   - The course name from the admin point of view.
                   5470: #               $cdom         - The course's domain(?).
                   5471: #    $client  - Socket open on the client.
                   5472: # Returns:
                   5473: #    1    - Indiciting processing should continue.
                   5474: #
                   5475: sub get_sections_handler {
                   5476:     my ($cmd, $tail, $client) = @_;
                   5477:     my $userinput = "$cmd:$tail";
                   5478: 
                   5479:     my ($coursecode, $cdom) = split(/:/, $tail);
                   5480:     my @secs = &localenroll::get_sections($coursecode,$cdom);
                   5481:     my $seclist = &escape(join(':',@secs));
                   5482: 
1.387     albertel 5483:     &Reply($client, \$seclist, $userinput);
1.248     foxr     5484:     
                   5485: 
                   5486:     return 1;
                   5487: }
                   5488: &register_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
                   5489: 
                   5490: #   Validate the owner of a new course section.  
                   5491: #
                   5492: # Formal Parameters:
                   5493: #   $cmd      - Command that got us dispatched.
                   5494: #   $tail     - the remainder of the command.  For us this consists of a
                   5495: #               colon separated string containing:
                   5496: #                  $inst    - Course Id from the institutions point of view.
                   5497: #                  $owner   - Proposed owner of the course.
                   5498: #                  $cdom    - Domain of the course (from the institutions
                   5499: #                             point of view?)..
                   5500: #   $client   - Socket open on the client.
                   5501: #
                   5502: # Returns:
                   5503: #   1        - Processing should continue.
                   5504: #
                   5505: sub validate_course_owner_handler {
                   5506:     my ($cmd, $tail, $client)  = @_;
                   5507:     my $userinput = "$cmd:$tail";
1.470     raeburn  5508:     my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
                   5509:     
1.336     raeburn  5510:     $owner = &unescape($owner);
1.470     raeburn  5511:     $coowners = &unescape($coowners);
                   5512:     my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387     albertel 5513:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5514: 
                   5515: 
                   5516: 
                   5517:     return 1;
                   5518: }
                   5519: &register_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263     albertel 5520: 
1.248     foxr     5521: #
                   5522: #   Validate a course section in the official schedule of classes
                   5523: #   from the institutions point of view (part of autoenrollment).
                   5524: #
                   5525: # Formal Parameters:
                   5526: #   $cmd          - The command request that got us dispatched.
                   5527: #   $tail         - The tail of the command.  In this case,
                   5528: #                   this is a colon separated set of words that will be split
                   5529: #                   into:
                   5530: #                        $inst_course_id - The course/section id from the
                   5531: #                                          institutions point of view.
                   5532: #                        $cdom           - The domain from the institutions
                   5533: #                                          point of view.
                   5534: #   $client       - Socket open on the client.
                   5535: # Returns:
                   5536: #    1           - Indicating processing should continue.
                   5537: #
                   5538: sub validate_course_section_handler {
                   5539:     my ($cmd, $tail, $client) = @_;
                   5540:     my $userinput = "$cmd:$tail";
                   5541:     my ($inst_course_id, $cdom) = split(/:/, $tail);
                   5542: 
                   5543:     my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387     albertel 5544:     &Reply($client, \$outcome, $userinput);
1.248     foxr     5545: 
                   5546: 
                   5547:     return 1;
                   5548: }
                   5549: &register_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
                   5550: 
                   5551: #
1.340     raeburn  5552: #   Validate course owner's access to enrollment data for specific class section. 
                   5553: #   
                   5554: #
                   5555: # Formal Parameters:
                   5556: #    $cmd     - The command request that got us dispatched.
                   5557: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5558: #               set of words that will be split into:
                   5559: #               $inst_class  - Institutional code for the specific class section   
                   5560: #               $courseowner - The escaped username:domain of the course owner 
                   5561: #               $cdom        - The domain of the course from the institution's
                   5562: #                              point of view.
                   5563: #    $client  - The socket open on the client.
                   5564: # Returns:
                   5565: #    1 - continue processing.
                   5566: #
                   5567: 
                   5568: sub validate_class_access_handler {
                   5569:     my ($cmd, $tail, $client) = @_;
                   5570:     my $userinput = "$cmd:$tail";
1.383     raeburn  5571:     my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392     raeburn  5572:     my $owners = &unescape($ownerlist);
1.341     albertel 5573:     my $outcome;
                   5574:     eval {
                   5575: 	local($SIG{__DIE__})='DEFAULT';
1.392     raeburn  5576: 	$outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341     albertel 5577:     };
1.387     albertel 5578:     &Reply($client,\$outcome, $userinput);
1.340     raeburn  5579: 
                   5580:     return 1;
                   5581: }
                   5582: &register_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
                   5583: 
                   5584: #
                   5585: #   Create a password for a new LON-CAPA user added by auto-enrollment.
                   5586: #   Only used for case where authentication method for new user is localauth
1.248     foxr     5587: #
                   5588: # Formal Parameters:
                   5589: #    $cmd     - The command request that got us dispatched.
                   5590: #    $tail    - The tail of the command.   In this case this is a colon separated
                   5591: #               set of words that will be split into:
1.340     raeburn  5592: #               $authparam - An authentication parameter (localauth parameter).
1.248     foxr     5593: #               $cdom      - The domain of the course from the institution's
                   5594: #                            point of view.
                   5595: #    $client  - The socket open on the client.
                   5596: # Returns:
                   5597: #    1 - continue processing.
                   5598: #
                   5599: sub create_auto_enroll_password_handler {
                   5600:     my ($cmd, $tail, $client) = @_;
                   5601:     my $userinput = "$cmd:$tail";
                   5602: 
                   5603:     my ($authparam, $cdom) = split(/:/, $userinput);
                   5604: 
                   5605:     my ($create_passwd,$authchk);
                   5606:     ($authparam,
                   5607:      $create_passwd,
                   5608:      $authchk) = &localenroll::create_password($authparam,$cdom);
                   5609: 
                   5610:     &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
                   5611: 	   $userinput);
                   5612: 
                   5613: 
                   5614:     return 1;
                   5615: }
                   5616: &register_handler("autocreatepassword", \&create_auto_enroll_password_handler, 
                   5617: 		  0, 1, 0);
                   5618: 
1.522     raeburn  5619: sub auto_export_grades_handler {
                   5620:     my ($cmd, $tail, $client) = @_;
                   5621:     my $userinput = "$cmd:$tail";
                   5622:     my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
                   5623:     my $inforef = &Apache::lonnet::thaw_unescape($info);
                   5624:     my $dataref = &Apache::lonnet::thaw_unescape($data);
                   5625:     my ($outcome,$result);;
                   5626:     eval {
                   5627:         local($SIG{__DIE__})='DEFAULT';
                   5628:         my %rtnhash;
                   5629:         $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
                   5630:         if ($outcome eq 'ok') {
                   5631:             foreach my $key (keys(%rtnhash)) {
                   5632:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   5633:             }
                   5634:             $result =~ s/\&$//;
                   5635:         }
                   5636:     };
                   5637:     if (!$@) {
                   5638:         if ($outcome eq 'ok') {
                   5639:             if ($cipher) {
                   5640:                 my $cmdlength=length($result);
                   5641:                 $result.="         ";
                   5642:                 my $encresult='';
                   5643:                 for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
                   5644:                     $encresult.= unpack("H16",
                   5645:                                         $cipher->encrypt(substr($result,
                   5646:                                                                 $encidx,
                   5647:                                                                 8)));
                   5648:                 }
                   5649:                 &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
                   5650:             } else {
                   5651:                 &Failure( $client, "error:no_key\n", $userinput);
                   5652:             }
                   5653:         } else {
                   5654:             &Reply($client, "$outcome\n", $userinput);
                   5655:         }
                   5656:     } else {
                   5657:         &Failure($client,"export_error\n",$userinput);
                   5658:     }
                   5659:     return 1;
                   5660: }
                   5661: &register_handler("autoexportgrades", \&auto_export_grades_handler,
                   5662:                   0, 1, 0);
                   5663: 
1.248     foxr     5664: #   Retrieve and remove temporary files created by/during autoenrollment.
                   5665: #
                   5666: # Formal Parameters:
                   5667: #    $cmd      - The command that got us dispatched.
                   5668: #    $tail     - The tail of the command.  In our case this is a colon 
                   5669: #                separated list that will be split into:
1.526   ! raeburn  5670: #                $filename - The name of the file to retrieve.
1.248     foxr     5671: #                            The filename is given as a path relative to
                   5672: #                            the LonCAPA temp file directory.
                   5673: #    $client   - Socket open on the client.
                   5674: #
                   5675: # Returns:
                   5676: #   1     - Continue processing.
                   5677: sub retrieve_auto_file_handler {
                   5678:     my ($cmd, $tail, $client)    = @_;
                   5679:     my $userinput                = "cmd:$tail";
                   5680: 
                   5681:     my ($filename)   = split(/:/, $tail);
                   5682: 
                   5683:     my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521     raeburn  5684: 
                   5685:     if ($filename =~m{/\.\./}) {
                   5686:         &Failure($client, "refused\n", $userinput);
1.526   ! raeburn  5687:     } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
        !          5688:         &Failure($client, "refused\n", $userinput);
1.521     raeburn  5689:     } elsif ( (-e $source) && ($filename ne '') ) {
1.248     foxr     5690: 	my $reply = '';
                   5691: 	if (open(my $fh,$source)) {
                   5692: 	    while (<$fh>) {
                   5693: 		chomp($_);
                   5694: 		$_ =~ s/^\s+//g;
                   5695: 		$_ =~ s/\s+$//g;
                   5696: 		$reply .= $_;
                   5697: 	    }
                   5698: 	    close($fh);
                   5699: 	    &Reply($client, &escape($reply)."\n", $userinput);
                   5700: 
                   5701: #   Does this have to be uncommented??!?  (RF).
                   5702: #
                   5703: #                                unlink($source);
                   5704: 	} else {
                   5705: 	    &Failure($client, "error\n", $userinput);
                   5706: 	}
                   5707:     } else {
                   5708: 	&Failure($client, "error\n", $userinput);
                   5709:     }
                   5710:     
                   5711: 
                   5712:     return 1;
                   5713: }
                   5714: &register_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
                   5715: 
1.423     raeburn  5716: sub crsreq_checks_handler {
                   5717:     my ($cmd, $tail, $client) = @_;
                   5718:     my $userinput = "$cmd:$tail";
                   5719:     my $dom = $tail;
                   5720:     my $result;
1.519     raeburn  5721:     my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423     raeburn  5722:     eval {
                   5723:         local($SIG{__DIE__})='DEFAULT';
                   5724:         my %validations;
1.424     raeburn  5725:         my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
                   5726:                                                    \%validations);
1.423     raeburn  5727:         if ($response eq 'ok') { 
                   5728:             foreach my $key (keys(%validations)) {
                   5729:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
                   5730:             }
                   5731:             $result =~ s/\&$//;
                   5732:         } else {
                   5733:             $result = 'error';
                   5734:         }
                   5735:     };
                   5736:     if (!$@) {
                   5737:         &Reply($client, \$result, $userinput);
                   5738:     } else {
                   5739:         &Failure($client,"unknown_cmd\n",$userinput);
                   5740:     }
                   5741:     return 1;
                   5742: }
                   5743: &register_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
                   5744: 
                   5745: sub validate_crsreq_handler {
                   5746:     my ($cmd, $tail, $client) = @_;
                   5747:     my $userinput = "$cmd:$tail";
1.508     raeburn  5748:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423     raeburn  5749:     $instcode = &unescape($instcode);
                   5750:     $owner = &unescape($owner);
                   5751:     $crstype = &unescape($crstype);
                   5752:     $inststatuslist = &unescape($inststatuslist);
                   5753:     $instcode = &unescape($instcode);
                   5754:     $instseclist = &unescape($instseclist);
1.508     raeburn  5755:     my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423     raeburn  5756:     my $outcome;
                   5757:     eval {
                   5758:         local($SIG{__DIE__})='DEFAULT';
                   5759:         $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
                   5760:                                                  $inststatuslist,$instcode,
1.508     raeburn  5761:                                                  $instseclist,$custominfo);
1.423     raeburn  5762:     };
                   5763:     if (!$@) {
                   5764:         &Reply($client, \$outcome, $userinput);
                   5765:     } else {
                   5766:         &Failure($client,"unknown_cmd\n",$userinput);
                   5767:     }
                   5768:     return 1;
                   5769: }
                   5770: &register_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
                   5771: 
1.506     raeburn  5772: sub crsreq_update_handler {
                   5773:     my ($cmd, $tail, $client) = @_;
                   5774:     my $userinput = "$cmd:$tail";
1.509     raeburn  5775:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
                   5776:         $accessstart,$accessend,$infohashref) =
1.506     raeburn  5777:         split(/:/, $tail);
                   5778:     $crstype = &unescape($crstype);
                   5779:     $action = &unescape($action);
                   5780:     $ownername = &unescape($ownername);
                   5781:     $ownerdomain = &unescape($ownerdomain);
                   5782:     $fullname = &unescape($fullname);
                   5783:     $title = &unescape($title);
                   5784:     $code = &unescape($code);
1.509     raeburn  5785:     $accessstart = &unescape($accessstart);
                   5786:     $accessend = &unescape($accessend);
1.506     raeburn  5787:     my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
                   5788:     my ($result,$outcome);
                   5789:     eval {
                   5790:         local($SIG{__DIE__})='DEFAULT';
                   5791:         my %rtnhash;
                   5792:         $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
                   5793:                                                 $ownername,$ownerdomain,$fullname,
1.509     raeburn  5794:                                                 $title,$code,$accessstart,$accessend,
                   5795:                                                 $incoming,\%rtnhash);
1.506     raeburn  5796:         if ($outcome eq 'ok') {
1.515     raeburn  5797:             my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506     raeburn  5798:             foreach my $key (keys(%rtnhash)) {
                   5799:                 if (grep(/^\Q$key\E/,@posskeys)) {
                   5800:                     $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
                   5801:                 }
                   5802:             }
                   5803:             $result =~ s/\&$//;
                   5804:         }
                   5805:     };
                   5806:     if (!$@) {
                   5807:         if ($outcome eq 'ok') {
                   5808:             &Reply($client, \$result, $userinput);
                   5809:         } else {
                   5810:             &Reply($client, "format_error\n", $userinput);
                   5811:         }
                   5812:     } else {
                   5813:         &Failure($client,"unknown_cmd\n",$userinput);
                   5814:     }
                   5815:     return 1;
                   5816: }
                   5817: &register_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
                   5818: 
1.248     foxr     5819: #
                   5820: #   Read and retrieve institutional code format (for support form).
                   5821: # Formal Parameters:
                   5822: #    $cmd        - Command that dispatched us.
                   5823: #    $tail       - Tail of the command.  In this case it conatins 
                   5824: #                  the course domain and the coursename.
                   5825: #    $client     - Socket open on the client.
                   5826: # Returns:
                   5827: #    1     - Continue processing.
                   5828: #
                   5829: sub get_institutional_code_format_handler {
                   5830:     my ($cmd, $tail, $client)   = @_;
                   5831:     my $userinput               = "$cmd:$tail";
                   5832: 
                   5833:     my $reply;
                   5834:     my($cdom,$course) = split(/:/,$tail);
                   5835:     my @pairs = split/\&/,$course;
                   5836:     my %instcodes = ();
                   5837:     my %codes = ();
                   5838:     my @codetitles = ();
                   5839:     my %cat_titles = ();
                   5840:     my %cat_order = ();
                   5841:     foreach (@pairs) {
                   5842: 	my ($key,$value) = split/=/,$_;
                   5843: 	$instcodes{&unescape($key)} = &unescape($value);
                   5844:     }
                   5845:     my $formatreply = &localenroll::instcode_format($cdom,
                   5846: 						    \%instcodes,
                   5847: 						    \%codes,
                   5848: 						    \@codetitles,
                   5849: 						    \%cat_titles,
                   5850: 						    \%cat_order);
                   5851:     if ($formatreply eq 'ok') {
1.365     albertel 5852: 	my $codes_str = &Apache::lonnet::hash2str(%codes);
                   5853: 	my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
                   5854: 	my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
                   5855: 	my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248     foxr     5856: 	&Reply($client,
                   5857: 	       $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
                   5858: 	       .$cat_order_str."\n",
                   5859: 	       $userinput);
                   5860:     } else {
                   5861: 	# this else branch added by RF since if not ok, lonc will
                   5862: 	# hang waiting on reply until timeout.
                   5863: 	#
                   5864: 	&Reply($client, "format_error\n", $userinput);
                   5865:     }
                   5866:     
                   5867:     return 1;
                   5868: }
1.265     albertel 5869: &register_handler("autoinstcodeformat",
                   5870: 		  \&get_institutional_code_format_handler,0,1,0);
1.246     foxr     5871: 
1.345     raeburn  5872: sub get_institutional_defaults_handler {
                   5873:     my ($cmd, $tail, $client)   = @_;
                   5874:     my $userinput               = "$cmd:$tail";
                   5875: 
                   5876:     my $dom = $tail;
                   5877:     my %defaults_hash;
                   5878:     my @code_order;
                   5879:     my $outcome;
                   5880:     eval {
                   5881:         local($SIG{__DIE__})='DEFAULT';
                   5882:         $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
                   5883:                                                    \@code_order);
                   5884:     };
                   5885:     if (!$@) {
                   5886:         if ($outcome eq 'ok') {
                   5887:             my $result='';
                   5888:             while (my ($key,$value) = each(%defaults_hash)) {
                   5889:                 $result.=&escape($key).'='.&escape($value).'&';
                   5890:             }
                   5891:             $result .= 'code_order='.&escape(join('&',@code_order));
1.387     albertel 5892:             &Reply($client,\$result,$userinput);
1.345     raeburn  5893:         } else {
                   5894:             &Reply($client,"error\n", $userinput);
                   5895:         }
                   5896:     } else {
                   5897:         &Failure($client,"unknown_cmd\n",$userinput);
                   5898:     }
                   5899: }
                   5900: &register_handler("autoinstcodedefaults",
                   5901:                   \&get_institutional_defaults_handler,0,1,0);
                   5902: 
1.416     raeburn  5903: sub get_possible_instcodes_handler {
                   5904:     my ($cmd, $tail, $client)   = @_;
                   5905:     my $userinput               = "$cmd:$tail";
                   5906: 
                   5907:     my $reply;
                   5908:     my $cdom = $tail;
1.417     raeburn  5909:     my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416     raeburn  5910:     my $formatreply = &localenroll::possible_instcodes($cdom,
                   5911:                                                        \@codetitles,
                   5912:                                                        \%cat_titles,
1.417     raeburn  5913:                                                        \%cat_order,
                   5914:                                                        \@code_order);
1.416     raeburn  5915:     if ($formatreply eq 'ok') {
                   5916:         my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417     raeburn  5917:         $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416     raeburn  5918:         foreach my $key (keys(%cat_titles)) {
                   5919:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
                   5920:         }
                   5921:         $result =~ s/\&$//;
                   5922:         $result .= ':';
                   5923:         foreach my $key (keys(%cat_order)) {
                   5924:             $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
                   5925:         }
                   5926:         $result =~ s/\&$//;
                   5927:         &Reply($client,\$result,$userinput);
                   5928:     } else {
                   5929:         &Reply($client, "format_error\n", $userinput);
                   5930:     }
                   5931:     return 1;
                   5932: }
                   5933: &register_handler("autopossibleinstcodes",
                   5934:                   \&get_possible_instcodes_handler,0,1,0);
                   5935: 
1.381     raeburn  5936: sub get_institutional_user_rules {
                   5937:     my ($cmd, $tail, $client)   = @_;
                   5938:     my $userinput               = "$cmd:$tail";
                   5939:     my $dom = &unescape($tail);
                   5940:     my (%rules_hash,@rules_order);
                   5941:     my $outcome;
                   5942:     eval {
                   5943:         local($SIG{__DIE__})='DEFAULT';
                   5944:         $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
                   5945:     };
                   5946:     if (!$@) {
                   5947:         if ($outcome eq 'ok') {
                   5948:             my $result;
                   5949:             foreach my $key (keys(%rules_hash)) {
                   5950:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   5951:             }
                   5952:             $result =~ s/\&$//;
                   5953:             $result .= ':';
                   5954:             if (@rules_order > 0) {
                   5955:                 foreach my $item (@rules_order) {
                   5956:                     $result .= &escape($item).'&';
                   5957:                 }
                   5958:             }
                   5959:             $result =~ s/\&$//;
1.387     albertel 5960:             &Reply($client,\$result,$userinput);
1.381     raeburn  5961:         } else {
                   5962:             &Reply($client,"error\n", $userinput);
                   5963:         }
                   5964:     } else {
                   5965:         &Failure($client,"unknown_cmd\n",$userinput);
                   5966:     }
                   5967: }
                   5968: &register_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
                   5969: 
1.389     raeburn  5970: sub get_institutional_id_rules {
                   5971:     my ($cmd, $tail, $client)   = @_;
                   5972:     my $userinput               = "$cmd:$tail";
                   5973:     my $dom = &unescape($tail);
                   5974:     my (%rules_hash,@rules_order);
                   5975:     my $outcome;
                   5976:     eval {
                   5977:         local($SIG{__DIE__})='DEFAULT';
                   5978:         $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
                   5979:     };
                   5980:     if (!$@) {
                   5981:         if ($outcome eq 'ok') {
                   5982:             my $result;
                   5983:             foreach my $key (keys(%rules_hash)) {
                   5984:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   5985:             }
                   5986:             $result =~ s/\&$//;
                   5987:             $result .= ':';
                   5988:             if (@rules_order > 0) {
                   5989:                 foreach my $item (@rules_order) {
                   5990:                     $result .= &escape($item).'&';
                   5991:                 }
                   5992:             }
                   5993:             $result =~ s/\&$//;
                   5994:             &Reply($client,\$result,$userinput);
                   5995:         } else {
                   5996:             &Reply($client,"error\n", $userinput);
                   5997:         }
                   5998:     } else {
                   5999:         &Failure($client,"unknown_cmd\n",$userinput);
                   6000:     }
                   6001: }
                   6002: &register_handler("instidrules",\&get_institutional_id_rules,0,1,0);
                   6003: 
1.397     raeburn  6004: sub get_institutional_selfcreate_rules {
1.396     raeburn  6005:     my ($cmd, $tail, $client)   = @_;
                   6006:     my $userinput               = "$cmd:$tail";
                   6007:     my $dom = &unescape($tail);
                   6008:     my (%rules_hash,@rules_order);
                   6009:     my $outcome;
                   6010:     eval {
                   6011:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6012:         $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396     raeburn  6013:     };
                   6014:     if (!$@) {
                   6015:         if ($outcome eq 'ok') {
                   6016:             my $result;
                   6017:             foreach my $key (keys(%rules_hash)) {
                   6018:                 $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
                   6019:             }
                   6020:             $result =~ s/\&$//;
                   6021:             $result .= ':';
                   6022:             if (@rules_order > 0) {
                   6023:                 foreach my $item (@rules_order) {
                   6024:                     $result .= &escape($item).'&';
                   6025:                 }
                   6026:             }
                   6027:             $result =~ s/\&$//;
                   6028:             &Reply($client,\$result,$userinput);
                   6029:         } else {
                   6030:             &Reply($client,"error\n", $userinput);
                   6031:         }
                   6032:     } else {
                   6033:         &Failure($client,"unknown_cmd\n",$userinput);
                   6034:     }
                   6035: }
1.397     raeburn  6036: &register_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396     raeburn  6037: 
1.381     raeburn  6038: 
                   6039: sub institutional_username_check {
                   6040:     my ($cmd, $tail, $client)   = @_;
                   6041:     my $userinput               = "$cmd:$tail";
                   6042:     my %rulecheck;
                   6043:     my $outcome;
                   6044:     my ($udom,$uname,@rules) = split(/:/,$tail);
                   6045:     $udom = &unescape($udom);
                   6046:     $uname = &unescape($uname);
                   6047:     @rules = map {&unescape($_);} (@rules);
                   6048:     eval {
                   6049:         local($SIG{__DIE__})='DEFAULT';
                   6050:         $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
                   6051:     };
                   6052:     if (!$@) {
                   6053:         if ($outcome eq 'ok') {
                   6054:             my $result='';
                   6055:             foreach my $key (keys(%rulecheck)) {
                   6056:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6057:             }
1.387     albertel 6058:             &Reply($client,\$result,$userinput);
1.381     raeburn  6059:         } else {
                   6060:             &Reply($client,"error\n", $userinput);
                   6061:         }
                   6062:     } else {
                   6063:         &Failure($client,"unknown_cmd\n",$userinput);
                   6064:     }
                   6065: }
                   6066: &register_handler("instrulecheck",\&institutional_username_check,0,1,0);
                   6067: 
1.389     raeburn  6068: sub institutional_id_check {
                   6069:     my ($cmd, $tail, $client)   = @_;
                   6070:     my $userinput               = "$cmd:$tail";
                   6071:     my %rulecheck;
                   6072:     my $outcome;
                   6073:     my ($udom,$id,@rules) = split(/:/,$tail);
                   6074:     $udom = &unescape($udom);
                   6075:     $id = &unescape($id);
                   6076:     @rules = map {&unescape($_);} (@rules);
                   6077:     eval {
                   6078:         local($SIG{__DIE__})='DEFAULT';
                   6079:         $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
                   6080:     };
                   6081:     if (!$@) {
                   6082:         if ($outcome eq 'ok') {
                   6083:             my $result='';
                   6084:             foreach my $key (keys(%rulecheck)) {
                   6085:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6086:             }
                   6087:             &Reply($client,\$result,$userinput);
                   6088:         } else {
                   6089:             &Reply($client,"error\n", $userinput);
                   6090:         }
                   6091:     } else {
                   6092:         &Failure($client,"unknown_cmd\n",$userinput);
                   6093:     }
                   6094: }
                   6095: &register_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345     raeburn  6096: 
1.397     raeburn  6097: sub institutional_selfcreate_check {
1.396     raeburn  6098:     my ($cmd, $tail, $client)   = @_;
                   6099:     my $userinput               = "$cmd:$tail";
                   6100:     my %rulecheck;
                   6101:     my $outcome;
                   6102:     my ($udom,$email,@rules) = split(/:/,$tail);
                   6103:     $udom = &unescape($udom);
                   6104:     $email = &unescape($email);
                   6105:     @rules = map {&unescape($_);} (@rules);
                   6106:     eval {
                   6107:         local($SIG{__DIE__})='DEFAULT';
1.397     raeburn  6108:         $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396     raeburn  6109:     };
                   6110:     if (!$@) {
                   6111:         if ($outcome eq 'ok') {
                   6112:             my $result='';
                   6113:             foreach my $key (keys(%rulecheck)) {
                   6114:                 $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
                   6115:             }
                   6116:             &Reply($client,\$result,$userinput);
                   6117:         } else {
                   6118:             &Reply($client,"error\n", $userinput);
                   6119:         }
                   6120:     } else {
                   6121:         &Failure($client,"unknown_cmd\n",$userinput);
                   6122:     }
                   6123: }
1.397     raeburn  6124: &register_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396     raeburn  6125: 
1.317     raeburn  6126: # Get domain specific conditions for import of student photographs to a course
                   6127: #
                   6128: # Retrieves information from photo_permission subroutine in localenroll.
                   6129: # Returns outcome (ok) if no processing errors, and whether course owner is 
                   6130: # required to accept conditions of use (yes/no).
                   6131: #
                   6132: #    
                   6133: sub photo_permission_handler {
                   6134:     my ($cmd, $tail, $client)   = @_;
                   6135:     my $userinput               = "$cmd:$tail";
                   6136:     my $cdom = $tail;
                   6137:     my ($perm_reqd,$conditions);
1.320     albertel 6138:     my $outcome;
                   6139:     eval {
                   6140: 	local($SIG{__DIE__})='DEFAULT';
                   6141: 	$outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
                   6142: 						  \$conditions);
                   6143:     };
                   6144:     if (!$@) {
                   6145: 	&Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
                   6146: 	       $userinput);
                   6147:     } else {
                   6148: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6149:     }
                   6150:     return 1;
1.317     raeburn  6151: }
                   6152: &register_handler("autophotopermission",\&photo_permission_handler,0,1,0);
                   6153: 
                   6154: #
                   6155: # Checks if student photo is available for a user in the domain, in the user's
                   6156: # directory (in /userfiles/internal/studentphoto.jpg).
                   6157: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
                   6158: # the student's photo.   
                   6159: 
                   6160: sub photo_check_handler {
                   6161:     my ($cmd, $tail, $client)   = @_;
                   6162:     my $userinput               = "$cmd:$tail";
                   6163:     my ($udom,$uname,$pid) = split(/:/,$tail);
                   6164:     $udom = &unescape($udom);
                   6165:     $uname = &unescape($uname);
                   6166:     $pid = &unescape($pid);
                   6167:     my $path=&propath($udom,$uname).'/userfiles/internal/';
                   6168:     if (!-e $path) {
                   6169:         &mkpath($path);
                   6170:     }
                   6171:     my $response;
                   6172:     my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
                   6173:     $result .= ':'.$response;
                   6174:     &Reply($client, &escape($result)."\n",$userinput);
1.320     albertel 6175:     return 1;
1.317     raeburn  6176: }
                   6177: &register_handler("autophotocheck",\&photo_check_handler,0,1,0);
                   6178: 
                   6179: #
                   6180: # Retrieve information from localenroll about whether to provide a button     
                   6181: # for users who have enbled import of student photos to initiate an 
                   6182: # update of photo files for registered students. Also include 
                   6183: # comment to display alongside button.  
                   6184: 
                   6185: sub photo_choice_handler {
                   6186:     my ($cmd, $tail, $client) = @_;
                   6187:     my $userinput             = "$cmd:$tail";
                   6188:     my $cdom                  = &unescape($tail);
1.320     albertel 6189:     my ($update,$comment);
                   6190:     eval {
                   6191: 	local($SIG{__DIE__})='DEFAULT';
                   6192: 	($update,$comment)    = &localenroll::manager_photo_update($cdom);
                   6193:     };
                   6194:     if (!$@) {
                   6195: 	&Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
                   6196:     } else {
                   6197: 	&Failure($client,"unknown_cmd\n",$userinput);
                   6198:     }
                   6199:     return 1;
1.317     raeburn  6200: }
                   6201: &register_handler("autophotochoice",\&photo_choice_handler,0,1,0);
                   6202: 
1.265     albertel 6203: #
                   6204: # Gets a student's photo to exist (in the correct image type) in the user's 
                   6205: # directory.
                   6206: # Formal Parameters:
                   6207: #    $cmd     - The command request that got us dispatched.
                   6208: #    $tail    - A colon separated set of words that will be split into:
                   6209: #               $domain - student's domain
                   6210: #               $uname  - student username
                   6211: #               $type   - image type desired
                   6212: #    $client  - The socket open on the client.
                   6213: # Returns:
                   6214: #    1 - continue processing.
1.317     raeburn  6215: 
1.265     albertel 6216: sub student_photo_handler {
                   6217:     my ($cmd, $tail, $client) = @_;
1.317     raeburn  6218:     my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265     albertel 6219: 
1.317     raeburn  6220:     my $path=&propath($domain,$uname). '/userfiles/internal/';
                   6221:     my $filename = 'studentphoto.'.$ext;
                   6222:     if ($type eq 'thumbnail') {
                   6223:         $filename = 'studentphoto_tn.'.$ext;
                   6224:     }
                   6225:     if (-e $path.$filename) {
1.265     albertel 6226: 	&Reply($client,"ok\n","$cmd:$tail");
                   6227: 	return 1;
                   6228:     }
                   6229:     &mkpath($path);
1.317     raeburn  6230:     my $file;
                   6231:     if ($type eq 'thumbnail') {
1.320     albertel 6232: 	eval {
                   6233: 	    local($SIG{__DIE__})='DEFAULT';
                   6234: 	    $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
                   6235: 	};
1.317     raeburn  6236:     } else {
                   6237:         $file=&localstudentphoto::fetch($domain,$uname);
                   6238:     }
1.265     albertel 6239:     if (!$file) {
                   6240: 	&Failure($client,"unavailable\n","$cmd:$tail");
                   6241: 	return 1;
                   6242:     }
1.317     raeburn  6243:     if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
                   6244:     if (-e $path.$filename) {
1.265     albertel 6245: 	&Reply($client,"ok\n","$cmd:$tail");
                   6246: 	return 1;
                   6247:     }
                   6248:     &Failure($client,"unable_to_convert\n","$cmd:$tail");
                   6249:     return 1;
                   6250: }
                   6251: &register_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246     foxr     6252: 
1.361     raeburn  6253: sub inst_usertypes_handler {
                   6254:     my ($cmd, $domain, $client) = @_;
                   6255:     my $res;
                   6256:     my $userinput = $cmd.":".$domain; # For logging purposes.
1.370     albertel 6257:     my (%typeshash,@order,$result);
                   6258:     eval {
                   6259: 	local($SIG{__DIE__})='DEFAULT';
                   6260: 	$result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
                   6261:     };
                   6262:     if ($result eq 'ok') {
1.361     raeburn  6263:         if (keys(%typeshash) > 0) {
                   6264:             foreach my $key (keys(%typeshash)) {
                   6265:                 $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
                   6266:             }
                   6267:         }
                   6268:         $res=~s/\&$//;
                   6269:         $res .= ':';
                   6270:         if (@order > 0) {
                   6271:             foreach my $item (@order) {
                   6272:                 $res .= &escape($item).'&';
                   6273:             }
                   6274:         }
                   6275:         $res=~s/\&$//;
                   6276:     }
1.387     albertel 6277:     &Reply($client, \$res, $userinput);
1.361     raeburn  6278:     return 1;
                   6279: }
                   6280: &register_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
                   6281: 
1.264     albertel 6282: # mkpath makes all directories for a file, expects an absolute path with a
                   6283: # file or a trailing / if just a dir is passed
                   6284: # returns 1 on success 0 on failure
                   6285: sub mkpath {
                   6286:     my ($file)=@_;
                   6287:     my @parts=split(/\//,$file,-1);
                   6288:     my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
                   6289:     for (my $i=3;$i<= ($#parts-1);$i++) {
1.265     albertel 6290: 	$now.='/'.$parts[$i]; 
1.264     albertel 6291: 	if (!-e $now) {
                   6292: 	    if  (!mkdir($now,0770)) { return 0; }
                   6293: 	}
                   6294:     }
                   6295:     return 1;
                   6296: }
                   6297: 
1.207     foxr     6298: #---------------------------------------------------------------
                   6299: #
                   6300: #   Getting, decoding and dispatching requests:
                   6301: #
                   6302: #
                   6303: #   Get a Request:
                   6304: #   Gets a Request message from the client.  The transaction
                   6305: #   is defined as a 'line' of text.  We remove the new line
                   6306: #   from the text line.  
1.226     foxr     6307: #
1.211     albertel 6308: sub get_request {
1.207     foxr     6309:     my $input = <$client>;
                   6310:     chomp($input);
1.226     foxr     6311: 
1.234     foxr     6312:     &Debug("get_request: Request = $input\n");
1.207     foxr     6313: 
                   6314:     &status('Processing '.$clientname.':'.$input);
                   6315: 
                   6316:     return $input;
                   6317: }
1.212     foxr     6318: #---------------------------------------------------------------
                   6319: #
                   6320: #  Process a request.  This sub should shrink as each action
                   6321: #  gets farmed out into a separat sub that is registered 
                   6322: #  with the dispatch hash.  
                   6323: #
                   6324: # Parameters:
                   6325: #    user_input   - The request received from the client (lonc).
1.525     raeburn  6326: #
1.212     foxr     6327: # Returns:
                   6328: #    true to keep processing, false if caller should exit.
                   6329: #
                   6330: sub process_request {
1.525     raeburn  6331:     my ($userinput) = @_; # Easier for now to break style than to
                   6332:                           # fix all the userinput -> user_input.
1.212     foxr     6333:     my $wasenc    = 0;		# True if request was encrypted.
                   6334: # ------------------------------------------------------------ See if encrypted
1.322     albertel 6335:     # for command
                   6336:     # sethost:<server>
                   6337:     # <command>:<args>
                   6338:     #   we just send it to the processor
                   6339:     # for
                   6340:     # sethost:<server>:<command>:<args>
                   6341:     #  we do the implict set host and then do the command
                   6342:     if ($userinput =~ /^sethost:/) {
                   6343: 	(my $cmd,my $newid,$userinput) = split(':',$userinput,3);
                   6344: 	if (defined($userinput)) {
                   6345: 	    &sethost("$cmd:$newid");
                   6346: 	} else {
                   6347: 	    $userinput = "$cmd:$newid";
                   6348: 	}
                   6349:     }
                   6350: 
1.212     foxr     6351:     if ($userinput =~ /^enc/) {
                   6352: 	$userinput = decipher($userinput);
                   6353: 	$wasenc=1;
                   6354: 	if(!$userinput) {	# Cipher not defined.
1.251     foxr     6355: 	    &Failure($client, "error: Encrypted data without negotated key\n");
1.212     foxr     6356: 	    return 0;
                   6357: 	}
                   6358:     }
                   6359:     Debug("process_request: $userinput\n");
                   6360:     
1.213     foxr     6361:     #  
                   6362:     #   The 'correct way' to add a command to lond is now to
                   6363:     #   write a sub to execute it and Add it to the command dispatch
                   6364:     #   hash via a call to register_handler..  The comments to that
                   6365:     #   sub should give you enough to go on to show how to do this
                   6366:     #   along with the examples that are building up as this code
                   6367:     #   is getting refactored.   Until all branches of the
                   6368:     #   if/elseif monster below have been factored out into
                   6369:     #   separate procesor subs, if the dispatch hash is missing
                   6370:     #   the command keyword, we will fall through to the remainder
                   6371:     #   of the if/else chain below in order to keep this thing in 
                   6372:     #   working order throughout the transmogrification.
                   6373: 
                   6374:     my ($command, $tail) = split(/:/, $userinput, 2);
                   6375:     chomp($command);
                   6376:     chomp($tail);
                   6377:     $tail =~ s/(\r)//;		# This helps people debugging with e.g. telnet.
1.214     foxr     6378:     $command =~ s/(\r)//;	# And this too for parameterless commands.
                   6379:     if(!$tail) {
                   6380: 	$tail ="";		# defined but blank.
                   6381:     }
1.213     foxr     6382: 
                   6383:     &Debug("Command received: $command, encoded = $wasenc");
                   6384: 
                   6385:     if(defined $Dispatcher{$command}) {
                   6386: 
                   6387: 	my $dispatch_info = $Dispatcher{$command};
                   6388: 	my $handler       = $$dispatch_info[0];
                   6389: 	my $need_encode   = $$dispatch_info[1];
                   6390: 	my $client_types  = $$dispatch_info[2];
                   6391: 	Debug("Matched dispatch hash: mustencode: $need_encode "
                   6392: 	      ."ClientType $client_types");
                   6393:       
                   6394: 	#  Validate the request:
                   6395:       
                   6396: 	my $ok = 1;
                   6397: 	my $requesterprivs = 0;
                   6398: 	if(&isClient()) {
                   6399: 	    $requesterprivs |= $CLIENT_OK;
                   6400: 	}
                   6401: 	if(&isManager()) {
                   6402: 	    $requesterprivs |= $MANAGER_OK;
                   6403: 	}
                   6404: 	if($need_encode && (!$wasenc)) {
                   6405: 	    Debug("Must encode but wasn't: $need_encode $wasenc");
                   6406: 	    $ok = 0;
                   6407: 	}
                   6408: 	if(($client_types & $requesterprivs) == 0) {
                   6409: 	    Debug("Client not privileged to do this operation");
                   6410: 	    $ok = 0;
                   6411: 	}
1.525     raeburn  6412:         if ($ok) {
                   6413:             if (ref($trust{$command}) eq 'HASH') {
                   6414:                 my $donechecks;
                   6415:                 if ($trust{$command}{'anywhere'}) {
                   6416:                    $donechecks = 1;
                   6417:                 } elsif ($trust{$command}{'manageronly'}) {
                   6418:                     unless (&isManager()) {
                   6419:                         $ok = 0;
                   6420:                     }
                   6421:                     $donechecks = 1;
                   6422:                 } elsif ($trust{$command}{'institutiononly'}) {
                   6423:                     unless ($clientsameinst) {
                   6424:                         $ok = 0;
                   6425:                     }
                   6426:                     $donechecks = 1;
                   6427:                 } elsif ($clientsameinst) {
                   6428:                     $donechecks = 1;
                   6429:                 }
                   6430:                 unless ($donechecks) {
                   6431:                     foreach my $rule (keys(%{$trust{$command}})) {
                   6432:                         next if ($rule eq 'remote');
                   6433:                         if ($trust{$command}{$rule}) {
                   6434:                             if ($clientprohibited{$rule}) {
                   6435:                                 $ok = 0;
                   6436:                             } else {
                   6437:                                 $ok = 1;
                   6438:                                 $donechecks = 1;
                   6439:                                 last;
                   6440:                             }
                   6441:                         }
                   6442:                     }
                   6443:                 }
                   6444:                 unless ($donechecks) {
                   6445:                     if ($trust{$command}{'remote'}) {
                   6446:                         if ($clientremoteok) {
                   6447:                             $ok = 1;
                   6448:                         } else {
                   6449:                             $ok = 0;
                   6450:                         } 
                   6451:                     }
                   6452:                 }
                   6453:             }
                   6454:         }
1.213     foxr     6455: 
                   6456: 	if($ok) {
                   6457: 	    Debug("Dispatching to handler $command $tail");
                   6458: 	    my $keep_going = &$handler($command, $tail, $client);
                   6459: 	    return $keep_going;
                   6460: 	} else {
                   6461: 	    Debug("Refusing to dispatch because client did not match requirements");
                   6462: 	    Failure($client, "refused\n", $userinput);
                   6463: 	    return 1;
                   6464: 	}
1.525     raeburn  6465:     }
1.213     foxr     6466: 
1.262     foxr     6467:     print $client "unknown_cmd\n";
1.212     foxr     6468: # -------------------------------------------------------------------- complete
                   6469:     Debug("process_request - returning 1");
                   6470:     return 1;
                   6471: }
1.207     foxr     6472: #
                   6473: #   Decipher encoded traffic
                   6474: #  Parameters:
                   6475: #     input      - Encoded data.
                   6476: #  Returns:
                   6477: #     Decoded data or undef if encryption key was not yet negotiated.
                   6478: #  Implicit input:
                   6479: #     cipher  - This global holds the negotiated encryption key.
                   6480: #
1.211     albertel 6481: sub decipher {
1.207     foxr     6482:     my ($input)  = @_;
                   6483:     my $output = '';
1.212     foxr     6484:     
                   6485:     
1.207     foxr     6486:     if($cipher) {
                   6487: 	my($enc, $enclength, $encinput) = split(/:/, $input);
                   6488: 	for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
                   6489: 	    $output .= 
                   6490: 		$cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
                   6491: 	}
                   6492: 	return substr($output, 0, $enclength);
                   6493:     } else {
                   6494: 	return undef;
                   6495:     }
                   6496: }
                   6497: 
                   6498: #
                   6499: #   Register a command processor.  This function is invoked to register a sub
                   6500: #   to process a request.  Once registered, the ProcessRequest sub can automatically
                   6501: #   dispatch requests to an appropriate sub, and do the top level validity checking
                   6502: #   as well:
                   6503: #    - Is the keyword recognized.
                   6504: #    - Is the proper client type attempting the request.
                   6505: #    - Is the request encrypted if it has to be.
                   6506: #   Parameters:
                   6507: #    $request_name         - Name of the request being registered.
                   6508: #                           This is the command request that will match
                   6509: #                           against the hash keywords to lookup the information
                   6510: #                           associated with the dispatch information.
                   6511: #    $procedure           - Reference to a sub to call to process the request.
                   6512: #                           All subs get called as follows:
                   6513: #                             Procedure($cmd, $tail, $replyfd, $key)
                   6514: #                             $cmd    - the actual keyword that invoked us.
                   6515: #                             $tail   - the tail of the request that invoked us.
                   6516: #                             $replyfd- File descriptor connected to the client
                   6517: #    $must_encode          - True if the request must be encoded to be good.
                   6518: #    $client_ok            - True if it's ok for a client to request this.
                   6519: #    $manager_ok           - True if it's ok for a manager to request this.
                   6520: # Side effects:
                   6521: #      - On success, the Dispatcher hash has an entry added for the key $RequestName
                   6522: #      - On failure, the program will die as it's a bad internal bug to try to 
                   6523: #        register a duplicate command handler.
                   6524: #
1.211     albertel 6525: sub register_handler {
1.212     foxr     6526:     my ($request_name,$procedure,$must_encode,	$client_ok,$manager_ok)   = @_;
1.207     foxr     6527: 
                   6528:     #  Don't allow duplication#
                   6529:    
                   6530:     if (defined $Dispatcher{$request_name}) {
                   6531: 	die "Attempting to define a duplicate request handler for $request_name\n";
                   6532:     }
                   6533:     #   Build the client type mask:
                   6534:     
                   6535:     my $client_type_mask = 0;
                   6536:     if($client_ok) {
                   6537: 	$client_type_mask  |= $CLIENT_OK;
                   6538:     }
                   6539:     if($manager_ok) {
                   6540: 	$client_type_mask  |= $MANAGER_OK;
                   6541:     }
                   6542:    
                   6543:     #  Enter the hash:
                   6544:       
                   6545:     my @entry = ($procedure, $must_encode, $client_type_mask);
                   6546:    
                   6547:     $Dispatcher{$request_name} = \@entry;
                   6548:    
                   6549: }
                   6550: 
                   6551: 
                   6552: #------------------------------------------------------------------
                   6553: 
                   6554: 
                   6555: 
                   6556: 
1.141     foxr     6557: #
1.96      foxr     6558: #  Convert an error return code from lcpasswd to a string value.
                   6559: #
                   6560: sub lcpasswdstrerror {
                   6561:     my $ErrorCode = shift;
1.97      foxr     6562:     if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96      foxr     6563: 	return "lcpasswd Unrecognized error return value ".$ErrorCode;
                   6564:     } else {
1.98      foxr     6565: 	return $passwderrors[$ErrorCode];
1.96      foxr     6566:     }
                   6567: }
                   6568: 
1.23      harris41 6569: # grabs exception and records it to log before exiting
                   6570: sub catchexception {
1.27      albertel 6571:     my ($error)=@_;
1.25      www      6572:     $SIG{'QUIT'}='DEFAULT';
                   6573:     $SIG{__DIE__}='DEFAULT';
1.165     albertel 6574:     &status("Catching exception");
1.190     albertel 6575:     &logthis("<font color='red'>CRITICAL: "
1.373     albertel 6576:      ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27      albertel 6577:      ."a crash with this error msg->[$error]</font>");
1.57      www      6578:     &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27      albertel 6579:     if ($client) { print $client "error: $error\n"; }
1.59      www      6580:     $server->close();
1.27      albertel 6581:     die($error);
1.23      harris41 6582: }
1.63      www      6583: sub timeout {
1.165     albertel 6584:     &status("Handling Timeout");
1.190     albertel 6585:     &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63      www      6586:     &catchexception('Timeout');
                   6587: }
1.22      harris41 6588: # -------------------------------- Set signal handlers to record abnormal exits
                   6589: 
1.226     foxr     6590: 
1.22      harris41 6591: $SIG{'QUIT'}=\&catchexception;
                   6592: $SIG{__DIE__}=\&catchexception;
                   6593: 
1.81      matthew  6594: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95      harris41 6595: &status("Read loncapa.conf and loncapa_apache.conf");
                   6596: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141     foxr     6597: %perlvar=%{$perlvarref};
1.80      harris41 6598: undef $perlvarref;
1.19      www      6599: 
1.35      harris41 6600: # ----------------------------- Make sure this process is running from user=www
                   6601: my $wwwid=getpwnam('www');
                   6602: if ($wwwid!=$<) {
1.134     albertel 6603:    my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   6604:    my $subj="LON: $currenthostid User ID mismatch";
1.37      harris41 6605:    system("echo 'User ID mismatch.  lond must be run as user www.' |\
1.35      harris41 6606:  mailto $emailto -s '$subj' > /dev/null");
                   6607:    exit 1;
                   6608: }
                   6609: 
1.19      www      6610: # --------------------------------------------- Check if other instance running
                   6611: 
                   6612: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
                   6613: 
                   6614: if (-e $pidfile) {
                   6615:    my $lfh=IO::File->new("$pidfile");
                   6616:    my $pide=<$lfh>;
                   6617:    chomp($pide);
1.29      harris41 6618:    if (kill 0 => $pide) { die "already running"; }
1.19      www      6619: }
1.1       albertel 6620: 
                   6621: # ------------------------------------------------------------- Read hosts file
                   6622: 
                   6623: 
                   6624: 
                   6625: # establish SERVER socket, bind and listen.
                   6626: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
                   6627:                                 Type      => SOCK_STREAM,
                   6628:                                 Proto     => 'tcp',
1.469     foxr     6629:                                 ReuseAddr     => 1,
1.1       albertel 6630:                                 Listen    => 10 )
1.29      harris41 6631:   or die "making socket: $@\n";
1.1       albertel 6632: 
                   6633: # --------------------------------------------------------- Do global variables
                   6634: 
                   6635: # global variables
                   6636: 
1.134     albertel 6637: my %children               = ();       # keys are current child process IDs
1.1       albertel 6638: 
                   6639: sub REAPER {                        # takes care of dead children
                   6640:     $SIG{CHLD} = \&REAPER;
1.165     albertel 6641:     &status("Handling child death");
1.178     foxr     6642:     my $pid;
                   6643:     do {
                   6644: 	$pid = waitpid(-1,&WNOHANG());
                   6645: 	if (defined($children{$pid})) {
                   6646: 	    &logthis("Child $pid died");
                   6647: 	    delete($children{$pid});
1.183     albertel 6648: 	} elsif ($pid > 0) {
1.178     foxr     6649: 	    &logthis("Unknown Child $pid died");
                   6650: 	}
                   6651:     } while ( $pid > 0 );
                   6652:     foreach my $child (keys(%children)) {
                   6653: 	$pid = waitpid($child,&WNOHANG());
                   6654: 	if ($pid > 0) {
                   6655: 	    &logthis("Child $child - $pid looks like we missed it's death");
                   6656: 	    delete($children{$pid});
                   6657: 	}
1.176     albertel 6658:     }
1.165     albertel 6659:     &status("Finished Handling child death");
1.1       albertel 6660: }
                   6661: 
                   6662: sub HUNTSMAN {                      # signal handler for SIGINT
1.165     albertel 6663:     &status("Killing children (INT)");
1.1       albertel 6664:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
                   6665:     kill 'INT' => keys %children;
1.59      www      6666:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1       albertel 6667:     my $execdir=$perlvar{'lonDaemons'};
                   6668:     unlink("$execdir/logs/lond.pid");
1.190     albertel 6669:     &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165     albertel 6670:     &status("Done killing children");
1.1       albertel 6671:     exit;                           # clean up with dignity
                   6672: }
                   6673: 
                   6674: sub HUPSMAN {                      # signal handler for SIGHUP
                   6675:     local($SIG{CHLD}) = 'IGNORE';  # we're going to kill our children
1.165     albertel 6676:     &status("Killing children for restart (HUP)");
1.1       albertel 6677:     kill 'INT' => keys %children;
1.59      www      6678:     &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190     albertel 6679:     &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134     albertel 6680:     my $execdir=$perlvar{'lonDaemons'};
1.30      harris41 6681:     unlink("$execdir/logs/lond.pid");
1.165     albertel 6682:     &status("Restarting self (HUP)");
1.1       albertel 6683:     exec("$execdir/lond");         # here we go again
                   6684: }
                   6685: 
1.144     foxr     6686: #
1.148     foxr     6687: #  Reload the Apache daemon's state.
1.150     foxr     6688: #  This is done by invoking /home/httpd/perl/apachereload
                   6689: #  a setuid perl script that can be root for us to do this job.
1.148     foxr     6690: #
                   6691: sub ReloadApache {
1.473     raeburn  6692: # --------------------------- Handle case of another apachereload process (locking)
1.474     raeburn  6693:     if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
                   6694:         my $execdir = $perlvar{'lonDaemons'};
                   6695:         my $script  = $execdir."/apachereload";
                   6696:         system($script);
                   6697:         unlink('/tmp/lock_apachereload'); #  Remove the lock file.
                   6698:     }
1.148     foxr     6699: }
                   6700: 
                   6701: #
1.144     foxr     6702: #   Called in response to a USR2 signal.
                   6703: #   - Reread hosts.tab
                   6704: #   - All children connected to hosts that were removed from hosts.tab
                   6705: #     are killed via SIGINT
                   6706: #   - All children connected to previously existing hosts are sent SIGUSR1
                   6707: #   - Our internal hosts hash is updated to reflect the new contents of
                   6708: #     hosts.tab causing connections from hosts added to hosts.tab to
                   6709: #     now be honored.
                   6710: #
                   6711: sub UpdateHosts {
1.165     albertel 6712:     &status("Reload hosts.tab");
1.147     foxr     6713:     logthis('<font color="blue"> Updating connections </font>');
1.148     foxr     6714:     #
                   6715:     #  The %children hash has the set of IP's we currently have children
                   6716:     #  on.  These need to be matched against records in the hosts.tab
                   6717:     #  Any ip's no longer in the table get killed off they correspond to
                   6718:     #  either dropped or changed hosts.  Note that the re-read of the table
                   6719:     #  will take care of new and changed hosts as connections come into being.
                   6720: 
1.371     albertel 6721:     &Apache::lonnet::reset_hosts_info();
1.148     foxr     6722: 
1.368     albertel 6723:     foreach my $child (keys(%children)) {
1.148     foxr     6724: 	my $childip = $children{$child};
1.374     albertel 6725: 	if ($childip ne '127.0.0.1'
                   6726: 	    && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149     foxr     6727: 	    logthis('<font color="blue"> UpdateHosts killing child '
                   6728: 		    ." $child for ip $childip </font>");
1.148     foxr     6729: 	    kill('INT', $child);
1.149     foxr     6730: 	} else {
                   6731: 	    logthis('<font color="green"> keeping child for ip '
                   6732: 		    ." $childip (pid=$child) </font>");
1.148     foxr     6733: 	}
                   6734:     }
                   6735:     ReloadApache;
1.165     albertel 6736:     &status("Finished reloading hosts.tab");
1.144     foxr     6737: }
                   6738: 
1.148     foxr     6739: 
1.57      www      6740: sub checkchildren {
1.165     albertel 6741:     &status("Checking on the children (sending signals)");
1.57      www      6742:     &initnewstatus();
                   6743:     &logstatus();
                   6744:     &logthis('Going to check on the children');
1.134     albertel 6745:     my $docdir=$perlvar{'lonDocRoot'};
1.61      harris41 6746:     foreach (sort keys %children) {
1.221     albertel 6747: 	#sleep 1;
1.57      www      6748:         unless (kill 'USR1' => $_) {
                   6749: 	    &logthis ('Child '.$_.' is dead');
                   6750:             &logstatus($$.' is dead');
1.221     albertel 6751: 	    delete($children{$_});
1.57      www      6752:         } 
1.61      harris41 6753:     }
1.63      www      6754:     sleep 5;
1.212     foxr     6755:     $SIG{ALRM} = sub { Debug("timeout"); 
                   6756: 		       die "timeout";  };
1.113     albertel 6757:     $SIG{__DIE__} = 'DEFAULT';
1.165     albertel 6758:     &status("Checking on the children (waiting for reports)");
1.63      www      6759:     foreach (sort keys %children) {
                   6760:         unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113     albertel 6761:           eval {
                   6762:             alarm(300);
1.63      www      6763: 	    &logthis('Child '.$_.' did not respond');
1.67      albertel 6764: 	    kill 9 => $_;
1.131     albertel 6765: 	    #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
                   6766: 	    #$subj="LON: $currenthostid killed lond process $_";
                   6767: 	    #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
                   6768: 	    #$execdir=$perlvar{'lonDaemons'};
                   6769: 	    #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221     albertel 6770: 	    delete($children{$_});
1.113     albertel 6771: 	    alarm(0);
                   6772: 	  }
1.63      www      6773:         }
                   6774:     }
1.113     albertel 6775:     $SIG{ALRM} = 'DEFAULT';
1.155     albertel 6776:     $SIG{__DIE__} = \&catchexception;
1.165     albertel 6777:     &status("Finished checking children");
1.221     albertel 6778:     &logthis('Finished Checking children');
1.57      www      6779: }
                   6780: 
1.1       albertel 6781: # --------------------------------------------------------------------- Logging
                   6782: 
                   6783: sub logthis {
                   6784:     my $message=shift;
                   6785:     my $execdir=$perlvar{'lonDaemons'};
                   6786:     my $fh=IO::File->new(">>$execdir/logs/lond.log");
                   6787:     my $now=time;
                   6788:     my $local=localtime($now);
1.58      www      6789:     $lastlog=$local.': '.$message;
1.1       albertel 6790:     print $fh "$local ($$): $message\n";
                   6791: }
                   6792: 
1.77      foxr     6793: # ------------------------- Conditional log if $DEBUG true.
                   6794: sub Debug {
                   6795:     my $message = shift;
                   6796:     if($DEBUG) {
                   6797: 	&logthis($message);
                   6798:     }
                   6799: }
1.161     foxr     6800: 
                   6801: #
                   6802: #   Sub to do replies to client.. this gives a hook for some
                   6803: #   debug tracing too:
                   6804: #  Parameters:
                   6805: #     fd      - File open on client.
                   6806: #     reply   - Text to send to client.
                   6807: #     request - Original request from client.
                   6808: #
1.490     droeschl 6809: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
                   6810: #this is done automatically ($$reply must not contain any \n in this case). 
                   6811: #If $reply is a string the caller has to ensure this.
1.161     foxr     6812: sub Reply {
1.192     foxr     6813:     my ($fd, $reply, $request) = @_;
1.387     albertel 6814:     if (ref($reply)) {
                   6815: 	print $fd $$reply;
                   6816: 	print $fd "\n";
                   6817: 	if ($DEBUG) { Debug("Request was $request  Reply was $$reply"); }
                   6818:     } else {
                   6819: 	print $fd $reply;
                   6820: 	if ($DEBUG) { Debug("Request was $request  Reply was $reply"); }
                   6821:     }
1.212     foxr     6822:     $Transactions++;
                   6823: }
                   6824: 
                   6825: 
                   6826: #
                   6827: #    Sub to report a failure.
                   6828: #    This function:
                   6829: #     -   Increments the failure statistic counters.
                   6830: #     -   Invokes Reply to send the error message to the client.
                   6831: # Parameters:
                   6832: #    fd       - File descriptor open on the client
                   6833: #    reply    - Reply text to emit.
                   6834: #    request  - The original request message (used by Reply
                   6835: #               to debug if that's enabled.
                   6836: # Implicit outputs:
                   6837: #    $Failures- The number of failures is incremented.
                   6838: #    Reply (invoked here) sends a message to the 
                   6839: #    client:
                   6840: #
                   6841: sub Failure {
                   6842:     my $fd      = shift;
                   6843:     my $reply   = shift;
                   6844:     my $request = shift;
                   6845:    
                   6846:     $Failures++;
                   6847:     Reply($fd, $reply, $request);      # That's simple eh?
1.161     foxr     6848: }
1.57      www      6849: # ------------------------------------------------------------------ Log status
                   6850: 
                   6851: sub logstatus {
1.178     foxr     6852:     &status("Doing logging");
                   6853:     my $docdir=$perlvar{'lonDocRoot'};
                   6854:     {
                   6855: 	my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200     matthew  6856:         print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178     foxr     6857:         $fh->close();
                   6858:     }
1.221     albertel 6859:     &status("Finished $$.txt");
                   6860:     {
                   6861: 	open(LOG,">>$docdir/lon-status/londstatus.txt");
                   6862: 	flock(LOG,LOCK_EX);
                   6863: 	print LOG $$."\t".$clientname."\t".$currenthostid."\t"
                   6864: 	    .$status."\t".$lastlog."\t $keymode\n";
1.275     albertel 6865: 	flock(LOG,LOCK_UN);
1.221     albertel 6866: 	close(LOG);
                   6867:     }
1.178     foxr     6868:     &status("Finished logging");
1.57      www      6869: }
                   6870: 
                   6871: sub initnewstatus {
                   6872:     my $docdir=$perlvar{'lonDocRoot'};
                   6873:     my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460     foxr     6874:     my $now=time();
1.57      www      6875:     my $local=localtime($now);
                   6876:     print $fh "LOND status $local - parent $$\n\n";
1.64      www      6877:     opendir(DIR,"$docdir/lon-status/londchld");
1.134     albertel 6878:     while (my $filename=readdir(DIR)) {
1.64      www      6879:         unlink("$docdir/lon-status/londchld/$filename");
                   6880:     }
                   6881:     closedir(DIR);
1.57      www      6882: }
                   6883: 
                   6884: # -------------------------------------------------------------- Status setting
                   6885: 
                   6886: sub status {
                   6887:     my $what=shift;
                   6888:     my $now=time;
                   6889:     my $local=localtime($now);
1.178     foxr     6890:     $status=$local.': '.$what;
                   6891:     $0='lond: '.$what.' '.$local;
1.57      www      6892: }
1.11      www      6893: 
1.13      www      6894: # -------------------------------------------------------------- Talk to lonsql
                   6895: 
1.234     foxr     6896: sub sql_reply {
1.12      harris41 6897:     my ($cmd)=@_;
1.234     foxr     6898:     my $answer=&sub_sql_reply($cmd);
                   6899:     if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12      harris41 6900:     return $answer;
                   6901: }
                   6902: 
1.234     foxr     6903: sub sub_sql_reply {
1.12      harris41 6904:     my ($cmd)=@_;
                   6905:     my $unixsock="mysqlsock";
                   6906:     my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
                   6907:     my $sclient=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                   6908:                                       Type    => SOCK_STREAM,
                   6909:                                       Timeout => 10)
                   6910:        or return "con_lost";
1.319     www      6911:     print $sclient "$cmd:$currentdomainid\n";
1.12      harris41 6912:     my $answer=<$sclient>;
                   6913:     chomp($answer);
                   6914:     if (!$answer) { $answer="con_lost"; }
                   6915:     return $answer;
                   6916: }
                   6917: 
1.1       albertel 6918: # --------------------------------------- Is this the home server of an author?
1.11      www      6919: 
1.1       albertel 6920: sub ishome {
                   6921:     my $author=shift;
                   6922:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   6923:     my ($udom,$uname)=split(/\//,$author);
                   6924:     my $proname=propath($udom,$uname);
                   6925:     if (-e $proname) {
                   6926: 	return 'owner';
                   6927:     } else {
                   6928:         return 'not_owner';
                   6929:     }
                   6930: }
                   6931: 
                   6932: # ======================================================= Continue main program
                   6933: # ---------------------------------------------------- Fork once and dissociate
                   6934: 
1.134     albertel 6935: my $fpid=fork;
1.1       albertel 6936: exit if $fpid;
1.29      harris41 6937: die "Couldn't fork: $!" unless defined ($fpid);
1.1       albertel 6938: 
1.29      harris41 6939: POSIX::setsid() or die "Can't start new session: $!";
1.1       albertel 6940: 
                   6941: # ------------------------------------------------------- Write our PID on disk
                   6942: 
1.134     albertel 6943: my $execdir=$perlvar{'lonDaemons'};
1.1       albertel 6944: open (PIDSAVE,">$execdir/logs/lond.pid");
                   6945: print PIDSAVE "$$\n";
                   6946: close(PIDSAVE);
1.190     albertel 6947: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57      www      6948: &status('Starting');
1.1       albertel 6949: 
1.106     foxr     6950: 
1.1       albertel 6951: 
                   6952: # ----------------------------------------------------- Install signal handlers
                   6953: 
1.57      www      6954: 
1.1       albertel 6955: $SIG{CHLD} = \&REAPER;
                   6956: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   6957: $SIG{HUP}  = \&HUPSMAN;
1.57      www      6958: $SIG{USR1} = \&checkchildren;
1.144     foxr     6959: $SIG{USR2} = \&UpdateHosts;
1.106     foxr     6960: 
1.148     foxr     6961: #  Read the host hashes:
1.368     albertel 6962: &Apache::lonnet::load_hosts_tab();
1.447     raeburn  6963: my %iphost = &Apache::lonnet::get_iphost(1);
1.106     foxr     6964: 
1.480     raeburn  6965: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286     albertel 6966: 
1.471     raeburn  6967: my $arch = `uname -i`;
1.475     raeburn  6968: chomp($arch);
1.471     raeburn  6969: if ($arch eq 'unknown') {
                   6970:     $arch = `uname -m`;
1.475     raeburn  6971:     chomp($arch);
1.471     raeburn  6972: }
                   6973: 
1.106     foxr     6974: # --------------------------------------------------------------
                   6975: #   Accept connections.  When a connection comes in, it is validated
                   6976: #   and if good, a child process is created to process transactions
                   6977: #   along the connection.
                   6978: 
1.1       albertel 6979: while (1) {
1.165     albertel 6980:     &status('Starting accept');
1.106     foxr     6981:     $client = $server->accept() or next;
1.165     albertel 6982:     &status('Accepted '.$client.' off to spawn');
1.386     albertel 6983:     make_new_child($client);
1.165     albertel 6984:     &status('Finished spawning');
1.1       albertel 6985: }
                   6986: 
1.212     foxr     6987: sub make_new_child {
                   6988:     my $pid;
                   6989: #    my $cipher;     # Now global
                   6990:     my $sigset;
1.178     foxr     6991: 
1.212     foxr     6992:     $client = shift;
                   6993:     &status('Starting new child '.$client);
                   6994:     &logthis('<font color="green"> Attempting to start child ('.$client.
                   6995: 	     ")</font>");    
                   6996:     # block signal for fork
                   6997:     $sigset = POSIX::SigSet->new(SIGINT);
                   6998:     sigprocmask(SIG_BLOCK, $sigset)
                   6999:         or die "Can't block SIGINT for fork: $!\n";
1.178     foxr     7000: 
1.212     foxr     7001:     die "fork: $!" unless defined ($pid = fork);
1.178     foxr     7002: 
1.212     foxr     7003:     $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
                   7004: 	                               # connection liveness.
1.178     foxr     7005: 
1.212     foxr     7006:     #
                   7007:     #  Figure out who we're talking to so we can record the peer in 
                   7008:     #  the pid hash.
                   7009:     #
                   7010:     my $caller = getpeername($client);
                   7011:     my ($port,$iaddr);
                   7012:     if (defined($caller) && length($caller) > 0) {
                   7013: 	($port,$iaddr)=unpack_sockaddr_in($caller);
                   7014:     } else {
                   7015: 	&logthis("Unable to determine who caller was, getpeername returned nothing");
                   7016:     }
                   7017:     if (defined($iaddr)) {
                   7018: 	$clientip  = inet_ntoa($iaddr);
                   7019: 	Debug("Connected with $clientip");
                   7020:     } else {
                   7021: 	&logthis("Unable to determine clientip");
                   7022: 	$clientip='Unavailable';
                   7023:     }
                   7024:     
                   7025:     if ($pid) {
                   7026:         # Parent records the child's birth and returns.
                   7027:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7028:             or die "Can't unblock SIGINT for fork: $!\n";
                   7029:         $children{$pid} = $clientip;
                   7030:         &status('Started child '.$pid);
1.462     foxr     7031: 	close($client);
1.212     foxr     7032:         return;
                   7033:     } else {
                   7034:         # Child can *not* return from this subroutine.
                   7035:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
                   7036:         $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns 
                   7037:                                 #don't get intercepted
                   7038:         $SIG{USR1}= \&logstatus;
                   7039:         $SIG{ALRM}= \&timeout;
1.468     foxr     7040: 	#
                   7041: 	# Block sigpipe as it gets thrownon socket disconnect and we want to 
                   7042: 	# deal with that as a read faiure instead.
                   7043: 	#
                   7044: 	my $blockset = POSIX::SigSet->new(SIGPIPE);
                   7045: 	sigprocmask(SIG_BLOCK, $blockset);
                   7046: 
1.212     foxr     7047:         $lastlog='Forked ';
                   7048:         $status='Forked';
1.178     foxr     7049: 
1.212     foxr     7050:         # unblock signals
                   7051:         sigprocmask(SIG_UNBLOCK, $sigset)
                   7052:             or die "Can't unblock SIGINT for fork: $!\n";
1.178     foxr     7053: 
1.212     foxr     7054: #        my $tmpsnum=0;            # Now global
                   7055: #---------------------------------------------------- kerberos 5 initialization
                   7056:         &Authen::Krb5::init_context();
1.511     raeburn  7057: 
                   7058:         my $no_ets;
1.514     raeburn  7059:         if ($dist =~ /^(?:centos|rhes|scientific)(\d+)$/) {
1.511     raeburn  7060:             if ($1 >= 7) {
                   7061:                 $no_ets = 1;
                   7062:             }
                   7063:         } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
                   7064:             if (($1 eq '9.3') || ($1 >= 12.2)) {
                   7065:                 $no_ets = 1; 
                   7066:             }
1.514     raeburn  7067:         } elsif ($dist =~ /^sles(\d+)$/) {
                   7068:             if ($1 > 11) {
                   7069:                 $no_ets = 1;
                   7070:             }
1.511     raeburn  7071:         } elsif ($dist =~ /^fedora(\d+)$/) {
                   7072:             if ($1 < 7) {
                   7073:                 $no_ets = 1;
                   7074:             }
                   7075:         }
                   7076:         unless ($no_ets) {
1.286     albertel 7077: 	    &Authen::Krb5::init_ets();
                   7078: 	}
1.209     albertel 7079: 
1.212     foxr     7080: 	&status('Accepted connection');
                   7081: # =============================================================================
                   7082:             # do something with the connection
                   7083: # -----------------------------------------------------------------------------
                   7084: 	# see if we know client and 'check' for spoof IP by ineffective challenge
1.178     foxr     7085: 
1.278     albertel 7086: 	my $outsideip=$clientip;
                   7087: 	if ($clientip eq '127.0.0.1') {
1.368     albertel 7088: 	    $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278     albertel 7089: 	}
1.412     foxr     7090: 	&ReadManagerTable();
1.368     albertel 7091: 	my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278     albertel 7092: 	my $ismanager=($managers{$outsideip}    ne undef);
1.432     raeburn  7093: 	$clientname  = "[unknown]";
1.212     foxr     7094: 	if($clientrec) {	# Establish client type.
                   7095: 	    $ConnectionType = "client";
1.368     albertel 7096: 	    $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212     foxr     7097: 	    if($ismanager) {
                   7098: 		$ConnectionType = "both";
                   7099: 	    }
                   7100: 	} else {
                   7101: 	    $ConnectionType = "manager";
1.278     albertel 7102: 	    $clientname = $managers{$outsideip};
1.212     foxr     7103: 	}
                   7104: 	my $clientok;
1.178     foxr     7105: 
1.212     foxr     7106: 	if ($clientrec || $ismanager) {
                   7107: 	    &status("Waiting for init from $clientip $clientname");
                   7108: 	    &logthis('<font color="yellow">INFO: Connection, '.
                   7109: 		     $clientip.
                   7110: 		  " ($clientname) connection type = $ConnectionType </font>" );
                   7111: 	    &status("Connecting $clientip  ($clientname))"); 
                   7112: 	    my $remotereq=<$client>;
                   7113: 	    chomp($remotereq);
                   7114: 	    Debug("Got init: $remotereq");
1.337     albertel 7115: 
1.212     foxr     7116: 	    if ($remotereq =~ /^init/) {
                   7117: 		&sethost("sethost:$perlvar{'lonHostID'}");
                   7118: 		#
                   7119: 		#  If the remote is attempting a local init... give that a try:
                   7120: 		#
1.432     raeburn  7121: 		(my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492     droeschl 7122:         # For LON-CAPA 2.9, the  client session will have sent its LON-CAPA
                   7123:         # version when initiating the connection. For LON-CAPA 2.8 and older,
                   7124:         # the version is retrieved from the global %loncaparevs in lonnet.pm.            
1.494     droeschl 7125:         # $clientversion contains path to keyfile if $inittype eq 'local'
                   7126:         # it's overridden below in this case
1.492     droeschl 7127:         $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209     albertel 7128: 
1.212     foxr     7129: 		# If the connection type is ssl, but I didn't get my
                   7130: 		# certificate files yet, then I'll drop  back to 
                   7131: 		# insecure (if allowed).
                   7132: 		
                   7133: 		if($inittype eq "ssl") {
                   7134: 		    my ($ca, $cert) = lonssl::CertificateFile;
                   7135: 		    my $kfile       = lonssl::KeyFile;
                   7136: 		    if((!$ca)   || 
                   7137: 		       (!$cert) || 
                   7138: 		       (!$kfile)) {
                   7139: 			$inittype = ""; # This forces insecure attempt.
                   7140: 			&logthis("<font color=\"blue\"> Certificates not "
                   7141: 				 ."installed -- trying insecure auth</font>");
1.224     foxr     7142: 		    } else {	# SSL certificates are in place so
1.212     foxr     7143: 		    }		# Leave the inittype alone.
                   7144: 		}
                   7145: 
                   7146: 		if($inittype eq "local") {
1.432     raeburn  7147:                     $clientversion = $perlvar{'lonVersion'};
1.212     foxr     7148: 		    my $key = LocalConnection($client, $remotereq);
                   7149: 		    if($key) {
                   7150: 			Debug("Got local key $key");
                   7151: 			$clientok     = 1;
                   7152: 			my $cipherkey = pack("H32", $key);
                   7153: 			$cipher       = new IDEA($cipherkey);
                   7154: 			print $client "ok:local\n";
1.442     www      7155: 			&logthis('<font color="green">'
1.212     foxr     7156: 				 . "Successful local authentication </font>");
                   7157: 			$keymode = "local"
1.178     foxr     7158: 		    } else {
1.212     foxr     7159: 			Debug("Failed to get local key");
                   7160: 			$clientok = 0;
                   7161: 			shutdown($client, 3);
                   7162: 			close $client;
1.178     foxr     7163: 		    }
1.212     foxr     7164: 		} elsif ($inittype eq "ssl") {
                   7165: 		    my $key = SSLConnection($client);
                   7166: 		    if ($key) {
                   7167: 			$clientok = 1;
                   7168: 			my $cipherkey = pack("H32", $key);
                   7169: 			$cipher       = new IDEA($cipherkey);
                   7170: 			&logthis('<font color="green">'
                   7171: 				 ."Successfull ssl authentication with $clientname </font>");
                   7172: 			$keymode = "ssl";
                   7173: 	     
1.178     foxr     7174: 		    } else {
1.212     foxr     7175: 			$clientok = 0;
                   7176: 			close $client;
1.178     foxr     7177: 		    }
1.212     foxr     7178: 	   
                   7179: 		} else {
                   7180: 		    my $ok = InsecureConnection($client);
                   7181: 		    if($ok) {
                   7182: 			$clientok = 1;
                   7183: 			&logthis('<font color="green">'
                   7184: 				 ."Successful insecure authentication with $clientname </font>");
                   7185: 			print $client "ok\n";
                   7186: 			$keymode = "insecure";
1.178     foxr     7187: 		    } else {
1.212     foxr     7188: 			&logthis('<font color="yellow">'
                   7189: 				  ."Attempted insecure connection disallowed </font>");
                   7190: 			close $client;
                   7191: 			$clientok = 0;
1.178     foxr     7192: 			
                   7193: 		    }
                   7194: 		}
1.212     foxr     7195: 	    } else {
                   7196: 		&logthis(
                   7197: 			 "<font color='blue'>WARNING: "
                   7198: 			 ."$clientip failed to initialize: >$remotereq< </font>");
                   7199: 		&status('No init '.$clientip);
                   7200: 	    }
                   7201: 	    
                   7202: 	} else {
                   7203: 	    &logthis(
                   7204: 		     "<font color='blue'>WARNING: Unknown client $clientip</font>");
                   7205: 	    &status('Hung up on '.$clientip);
                   7206: 	}
                   7207:  
                   7208: 	if ($clientok) {
                   7209: # ---------------- New known client connecting, could mean machine online again
1.368     albertel 7210: 	    if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip 
1.367     albertel 7211: 		&& $clientip ne '127.0.0.1') {
1.375     albertel 7212: 		&Apache::lonnet::reconlonc($clientname);
1.212     foxr     7213: 	    }
                   7214: 	    &logthis("<font color='green'>Established connection: $clientname</font>");
                   7215: 	    &status('Will listen to '.$clientname);
                   7216: # ------------------------------------------------------------ Process requests
                   7217: 	    my $keep_going = 1;
                   7218: 	    my $user_input;
1.448     raeburn  7219:             my $clienthost = &Apache::lonnet::hostname($clientname);
                   7220:             my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
                   7221:             $clienthomedom = &Apache::lonnet::host_domain($clientserverhomeID);
1.525     raeburn  7222:             $clientintdom = &Apache::lonnet::internet_dom($clientserverhomeID);
                   7223:             $clientsameinst = 0;
                   7224:             if ($clientintdom ne '') {
                   7225:                 my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
                   7226:                 if (ref($internet_names) eq 'ARRAY') {
                   7227:                     if (grep(/^\Q$clientintdom\E$/,@{$internet_names})) {
                   7228:                         $clientsameinst = 1;
                   7229:                     }
                   7230:                 }
                   7231:             }
                   7232:             $clientremoteok = 0;
                   7233:             unless ($clientsameinst) {
                   7234:                 $clientremoteok = 1;
                   7235:                 my $defdom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
                   7236:                 %clientprohibited = &get_prohibited($defdom);
                   7237:                 if ($clientintdom) {
                   7238:                     my $remsessconf = &get_usersession_config($defdom,'remotesession');
                   7239:                     if (ref($remsessconf) eq 'HASH') {
                   7240:                         if (ref($remsessconf->{'remote'}) eq 'HASH') {
                   7241:                             if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
                   7242:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
                   7243:                                     $clientremoteok = 0;
                   7244:                                 }
                   7245:                             }
                   7246:                             if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
                   7247:                                 if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
                   7248:                                     $clientremoteok = 1;
                   7249:                                 } else {
                   7250:                                     $clientremoteok = 0;
                   7251:                                 }
                   7252:                             }
                   7253:                         }
                   7254:                     }
                   7255:                 }
                   7256:             }
1.212     foxr     7257: 	    while(($user_input = get_request) && $keep_going) {
                   7258: 		alarm(120);
                   7259: 		Debug("Main: Got $user_input\n");
                   7260: 		$keep_going = &process_request($user_input);
1.178     foxr     7261: 		alarm(0);
1.212     foxr     7262: 		&status('Listening to '.$clientname." ($keymode)");	   
1.161     foxr     7263: 	    }
1.212     foxr     7264: 
1.59      www      7265: # --------------------------------------------- client unknown or fishy, refuse
1.212     foxr     7266: 	}  else {
1.161     foxr     7267: 	    print $client "refused\n";
                   7268: 	    $client->close();
1.190     albertel 7269: 	    &logthis("<font color='blue'>WARNING: "
1.161     foxr     7270: 		     ."Rejected client $clientip, closing connection</font>");
                   7271: 	}
1.525     raeburn  7272:     }
1.161     foxr     7273:     
1.1       albertel 7274: # =============================================================================
1.161     foxr     7275:     
1.190     albertel 7276:     &logthis("<font color='red'>CRITICAL: "
1.161     foxr     7277: 	     ."Disconnect from $clientip ($clientname)</font>");    
                   7278:     
                   7279:     
                   7280:     # this exit is VERY important, otherwise the child will become
                   7281:     # a producer of more and more children, forking yourself into
                   7282:     # process death.
                   7283:     exit;
1.106     foxr     7284:     
1.78      foxr     7285: }
1.261     foxr     7286: #
                   7287: #   Determine if a user is an author for the indicated domain.
                   7288: #
                   7289: # Parameters:
                   7290: #    domain          - domain to check in .
                   7291: #    user            - Name of user to check.
                   7292: #
                   7293: # Return:
                   7294: #     1             - User is an author for domain.
                   7295: #     0             - User is not an author for domain.
                   7296: sub is_author {
                   7297:     my ($domain, $user) = @_;
                   7298: 
                   7299:     &Debug("is_author: $user @ $domain");
                   7300: 
                   7301:     my $hashref = &tie_user_hash($domain, $user, "roles",
                   7302: 				 &GDBM_READER());
                   7303: 
                   7304:     #  Author role should show up as a key /domain/_au
1.78      foxr     7305: 
1.321     albertel 7306:     my $value;
1.487     foxr     7307:     if ($hashref) {
1.78      foxr     7308: 
1.487     foxr     7309: 	my $key    = "/$domain/_au";
                   7310: 	if (defined($hashref)) {
                   7311: 	    $value = $hashref->{$key};
                   7312: 	    if(!untie_user_hash($hashref)) {
                   7313: 		return 'error: ' .  ($!+0)." untie (GDBM) Failed";
                   7314: 	    }
                   7315: 	}
                   7316: 	
                   7317: 	if(defined($value)) {
                   7318: 	    &Debug("$user @ $domain is an author");
                   7319: 	}
                   7320:     } else {
                   7321: 	return 'error: '.($!+0)." tie (GDBM) Failed";
1.261     foxr     7322:     }
                   7323: 
                   7324:     return defined($value);
                   7325: }
1.78      foxr     7326: #
                   7327: #   Checks to see if the input roleput request was to set
1.482     www      7328: # an author role.  If so, creates construction space 
1.78      foxr     7329: # Parameters:
                   7330: #    request   - The request sent to the rolesput subchunk.
                   7331: #                We're looking for  /domain/_au
                   7332: #    domain    - The domain in which the user is having roles doctored.
                   7333: #    user      - Name of the user for which the role is being put.
                   7334: #    authtype  - The authentication type associated with the user.
                   7335: #
1.289     albertel 7336: sub manage_permissions {
1.192     foxr     7337:     my ($request, $domain, $user, $authtype) = @_;
1.78      foxr     7338:     # See if the request is of the form /$domain/_au
1.289     albertel 7339:     if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484     raeburn  7340:         my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482     www      7341:         unless (-e $path) {        
                   7342:            mkdir($path);
                   7343:         }
                   7344:         unless (-e $path.'/'.$user) {
                   7345:            mkdir($path.'/'.$user);
                   7346:         }
1.78      foxr     7347:     }
                   7348: }
1.222     foxr     7349: 
                   7350: 
                   7351: #
                   7352: #  Return the full path of a user password file, whether it exists or not.
                   7353: # Parameters:
                   7354: #   domain     - Domain in which the password file lives.
                   7355: #   user       - name of the user.
                   7356: # Returns:
                   7357: #    Full passwd path:
                   7358: #
                   7359: sub password_path {
                   7360:     my ($domain, $user) = @_;
1.264     albertel 7361:     return &propath($domain, $user).'/passwd';
1.222     foxr     7362: }
                   7363: 
                   7364: #   Password Filename
                   7365: #   Returns the path to a passwd file given domain and user... only if
                   7366: #  it exists.
                   7367: # Parameters:
                   7368: #   domain    - Domain in which to search.
                   7369: #   user      - username.
                   7370: # Returns:
                   7371: #   - If the password file exists returns its path.
                   7372: #   - If the password file does not exist, returns undefined.
                   7373: #
                   7374: sub password_filename {
                   7375:     my ($domain, $user) = @_;
                   7376: 
                   7377:     Debug ("PasswordFilename called: dom = $domain user = $user");
                   7378: 
                   7379:     my $path  = &password_path($domain, $user);
                   7380:     Debug("PasswordFilename got path: $path");
                   7381:     if(-e $path) {
                   7382: 	return $path;
                   7383:     } else {
                   7384: 	return undef;
                   7385:     }
                   7386: }
                   7387: 
                   7388: #
                   7389: #   Rewrite the contents of the user's passwd file.
                   7390: #  Parameters:
                   7391: #    domain    - domain of the user.
                   7392: #    name      - User's name.
                   7393: #    contents  - New contents of the file.
                   7394: # Returns:
                   7395: #   0    - Failed.
                   7396: #   1    - Success.
                   7397: #
                   7398: sub rewrite_password_file {
                   7399:     my ($domain, $user, $contents) = @_;
                   7400: 
                   7401:     my $file = &password_filename($domain, $user);
                   7402:     if (defined $file) {
                   7403: 	my $pf = IO::File->new(">$file");
                   7404: 	if($pf) {
                   7405: 	    print $pf "$contents\n";
                   7406: 	    return 1;
                   7407: 	} else {
                   7408: 	    return 0;
                   7409: 	}
                   7410:     } else {
                   7411: 	return 0;
                   7412:     }
                   7413: 
                   7414: }
                   7415: 
1.78      foxr     7416: #
1.222     foxr     7417: #   get_auth_type - Determines the authorization type of a user in a domain.
1.78      foxr     7418: 
                   7419: #     Returns the authorization type or nouser if there is no such user.
                   7420: #
1.436     raeburn  7421: sub get_auth_type {
1.192     foxr     7422:     my ($domain, $user)  = @_;
1.78      foxr     7423: 
1.222     foxr     7424:     Debug("get_auth_type( $domain, $user ) \n");
1.78      foxr     7425:     my $proname    = &propath($domain, $user); 
                   7426:     my $passwdfile = "$proname/passwd";
                   7427:     if( -e $passwdfile ) {
                   7428: 	my $pf = IO::File->new($passwdfile);
                   7429: 	my $realpassword = <$pf>;
                   7430: 	chomp($realpassword);
1.79      foxr     7431: 	Debug("Password info = $realpassword\n");
1.78      foxr     7432: 	my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79      foxr     7433: 	Debug("Authtype = $authtype, content = $contentpwd\n");
1.259     raeburn  7434: 	return "$authtype:$contentpwd";     
1.224     foxr     7435:     } else {
1.79      foxr     7436: 	Debug("Returning nouser");
1.78      foxr     7437: 	return "nouser";
                   7438:     }
1.1       albertel 7439: }
                   7440: 
1.220     foxr     7441: #
                   7442: #  Validate a user given their domain, name and password.  This utility
                   7443: #  function is used by both  AuthenticateHandler and ChangePasswordHandler
                   7444: #  to validate the login credentials of a user.
                   7445: # Parameters:
                   7446: #    $domain    - The domain being logged into (this is required due to
                   7447: #                 the capability for multihomed systems.
                   7448: #    $user      - The name of the user being validated.
                   7449: #    $password  - The user's propoposed password.
                   7450: #
                   7451: # Returns:
                   7452: #     1        - The domain,user,pasword triplet corresponds to a valid
                   7453: #                user.
                   7454: #     0        - The domain,user,password triplet is not a valid user.
                   7455: #
                   7456: sub validate_user {
1.396     raeburn  7457:     my ($domain, $user, $password, $checkdefauth) = @_;
1.220     foxr     7458: 
                   7459:     # Why negative ~pi you may well ask?  Well this function is about
                   7460:     # authentication, and therefore very important to get right.
                   7461:     # I've initialized the flag that determines whether or not I've 
                   7462:     # validated correctly to a value it's not supposed to get.
                   7463:     # At the end of this function. I'll ensure that it's not still that
                   7464:     # value so we don't just wind up returning some accidental value
                   7465:     # as a result of executing an unforseen code path that
1.249     foxr     7466:     # did not set $validated.  At the end of valid execution paths,
                   7467:     # validated shoule be 1 for success or 0 for failuer.
1.220     foxr     7468: 
                   7469:     my $validated = -3.14159;
                   7470: 
                   7471:     #  How we authenticate is determined by the type of authentication
                   7472:     #  the user has been assigned.  If the authentication type is
                   7473:     #  "nouser", the user does not exist so we will return 0.
                   7474: 
1.222     foxr     7475:     my $contents = &get_auth_type($domain, $user);
1.220     foxr     7476:     my ($howpwd, $contentpwd) = split(/:/, $contents);
                   7477: 
                   7478:     my $null = pack("C",0);	# Used by kerberos auth types.
                   7479: 
1.395     raeburn  7480:     if ($howpwd eq 'nouser') {
1.396     raeburn  7481:         if ($checkdefauth) {
                   7482:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   7483:             if ($domdefaults{'auth_def'} eq 'localauth') {
                   7484:                 $howpwd = $domdefaults{'auth_def'};
                   7485:                 $contentpwd = $domdefaults{'auth_arg_def'};
                   7486:             } elsif ((($domdefaults{'auth_def'} eq 'krb4') || 
                   7487:                       ($domdefaults{'auth_def'} eq 'krb5')) &&
                   7488:                      ($domdefaults{'auth_arg_def'} ne '')) {
                   7489:                 $howpwd = $domdefaults{'auth_def'};
                   7490:                 $contentpwd = $domdefaults{'auth_arg_def'}; 
                   7491:             }
1.395     raeburn  7492:         }
                   7493:     } 
1.220     foxr     7494:     if ($howpwd ne 'nouser') {
                   7495: 	if($howpwd eq "internal") { # Encrypted is in local password file.
1.518     raeburn  7496:             if (length($contentpwd) == 13) {
                   7497:                 $validated = (crypt($password,$contentpwd) eq $contentpwd);
                   7498:                 if ($validated) {
                   7499:                     my $ncpass = &hash_passwd($domain,$password);
                   7500:                     if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass")) {
                   7501:                         &update_passwd_history($user,$domain,$howpwd,'conversion');
                   7502:                         &logthis("Validated password hashed with bcrypt for $user:$domain");
                   7503:                     }
                   7504:                 }
                   7505:             } else {
                   7506:                 $validated = &check_internal_passwd($password,$contentpwd,$domain);
                   7507:             }
1.220     foxr     7508: 	}
                   7509: 	elsif ($howpwd eq "unix") { # User is a normal unix user.
                   7510: 	    $contentpwd = (getpwnam($user))[1];
                   7511: 	    if($contentpwd) {
                   7512: 		if($contentpwd eq 'x') { # Shadow password file...
                   7513: 		    my $pwauth_path = "/usr/local/sbin/pwauth";
                   7514: 		    open PWAUTH,  "|$pwauth_path" or
                   7515: 			die "Cannot invoke authentication";
                   7516: 		    print PWAUTH "$user\n$password\n";
                   7517: 		    close PWAUTH;
                   7518: 		    $validated = ! $?;
                   7519: 
                   7520: 		} else { 	         # Passwords in /etc/passwd. 
                   7521: 		    $validated = (crypt($password,
                   7522: 					$contentpwd) eq $contentpwd);
                   7523: 		}
                   7524: 	    } else {
                   7525: 		$validated = 0;
                   7526: 	    }
1.439     raeburn  7527: 	} elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
                   7528:             my $checkwithkrb5 = 0;
                   7529:             if ($dist =~/^fedora(\d+)$/) {
                   7530:                 if ($1 > 11) {
                   7531:                     $checkwithkrb5 = 1;
                   7532:                 }
                   7533:             } elsif ($dist =~ /^suse([\d.]+)$/) {
                   7534:                 if ($1 > 11.1) {
                   7535:                     $checkwithkrb5 = 1; 
                   7536:                 }
                   7537:             }
                   7538:             if ($checkwithkrb5) {
                   7539:                 $validated = &krb5_authen($password,$null,$user,$contentpwd);
                   7540:             } else {
                   7541:                 $validated = &krb4_authen($password,$null,$user,$contentpwd);
                   7542:             }
1.224     foxr     7543: 	} elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439     raeburn  7544:             $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224     foxr     7545: 	} elsif ($howpwd eq "localauth") { 
1.220     foxr     7546: 	    #  Authenticate via installation specific authentcation method:
                   7547: 	    $validated = &localauth::localauth($user, 
                   7548: 					       $password, 
1.353     albertel 7549: 					       $contentpwd,
                   7550: 					       $domain);
1.358     albertel 7551: 	    if ($validated < 0) {
1.357     albertel 7552: 		&logthis("localauth for $contentpwd $user:$domain returned a $validated");
                   7553: 		$validated = 0;
                   7554: 	    }
1.224     foxr     7555: 	} else {			# Unrecognized auth is also bad.
1.220     foxr     7556: 	    $validated = 0;
                   7557: 	}
                   7558:     } else {
                   7559: 	$validated = 0;
                   7560:     }
                   7561:     #
                   7562:     #  $validated has the correct stat of the authentication:
                   7563:     #
                   7564: 
                   7565:     unless ($validated != -3.14159) {
1.249     foxr     7566: 	#  I >really really< want to know if this happens.
                   7567: 	#  since it indicates that user authentication is badly
                   7568: 	#  broken in some code path.
                   7569:         #
                   7570: 	die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220     foxr     7571:     }
                   7572:     return $validated;
                   7573: }
                   7574: 
1.518     raeburn  7575: sub check_internal_passwd {
                   7576:     my ($plainpass,$stored,$domain) = @_;
                   7577:     my (undef,$method,@rest) = split(/!/,$stored);
                   7578:     if ($method eq "bcrypt") {
                   7579:         my $result = &hash_passwd($domain,$plainpass,@rest);
                   7580:         if ($result ne $stored) {
                   7581:             return 0;
                   7582:         }
                   7583:         # Upgrade to a larger number of rounds if necessary
                   7584:         my $defaultcost;
                   7585:         my %domconfig =
                   7586:             &Apache::lonnet::get_dom('configuration',['password'],$domain);
                   7587:         if (ref($domconfig{'password'}) eq 'HASH') {
                   7588:             $defaultcost = $domconfig{'password'}{'cost'};
                   7589:         }
                   7590:         if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
                   7591:             $defaultcost = 10;
                   7592:         }
                   7593:         return 1 unless($rest[0]<$defaultcost);
                   7594:     }
                   7595:     return 0;
                   7596: }
                   7597: 
                   7598: sub get_last_authchg {
                   7599:     my ($domain,$user) = @_;
                   7600:     my $lastmod;
                   7601:     my $logname = &propath($domain,$user).'/passwd.log';
                   7602:     if (-e "$logname") {
                   7603:         $lastmod = (stat("$logname"))[9];
                   7604:     }
                   7605:     return $lastmod;
                   7606: }
                   7607: 
1.439     raeburn  7608: sub krb4_authen {
                   7609:     my ($password,$null,$user,$contentpwd) = @_;
                   7610:     my $validated = 0;
                   7611:     if (!($password =~ /$null/) ) {  # Null password not allowed.
                   7612:         eval {
                   7613:             require Authen::Krb4;
                   7614:         };
                   7615:         if (!$@) {
                   7616:             my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
                   7617:                                                        "",
                   7618:                                                        $contentpwd,,
                   7619:                                                        'krbtgt',
                   7620:                                                        $contentpwd,
                   7621:                                                        1,
                   7622:                                                        $password);
                   7623:             if(!$k4error) {
                   7624:                 $validated = 1;
                   7625:             } else {
                   7626:                 $validated = 0;
                   7627:                 &logthis('krb4: '.$user.', '.$contentpwd.', '.
                   7628:                           &Authen::Krb4::get_err_txt($Authen::Krb4::error));
                   7629:             }
                   7630:         } else {
                   7631:             $validated = krb5_authen($password,$null,$user,$contentpwd);
                   7632:         }
                   7633:     }
                   7634:     return $validated;
                   7635: }
                   7636: 
                   7637: sub krb5_authen {
                   7638:     my ($password,$null,$user,$contentpwd) = @_;
                   7639:     my $validated = 0;
                   7640:     if(!($password =~ /$null/)) { # Null password not allowed.
                   7641:         my $krbclient = &Authen::Krb5::parse_name($user.'@'
                   7642:                                                   .$contentpwd);
                   7643:         my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
                   7644:         my $krbserver  = &Authen::Krb5::parse_name($krbservice);
                   7645:         my $credentials= &Authen::Krb5::cc_default();
                   7646:         $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
                   7647:                                                             .$contentpwd));
                   7648:         my $krbreturn;
                   7649:         if (exists(&Authen::Krb5::get_init_creds_password)) {
                   7650:             $krbreturn =
                   7651:                 &Authen::Krb5::get_init_creds_password($krbclient,$password,
                   7652:                                                           $krbservice);
                   7653:             $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
                   7654:         } else {
                   7655:             $krbreturn  =
                   7656:                 &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
                   7657:                                                          $password,$credentials);
                   7658:             $validated = ($krbreturn == 1);
                   7659:         }
                   7660:         if (!$validated) {
                   7661:             &logthis('krb5: '.$user.', '.$contentpwd.', '.
                   7662:                      &Authen::Krb5::error());
                   7663:         }
                   7664:     }
                   7665:     return $validated;
                   7666: }
1.220     foxr     7667: 
1.84      albertel 7668: sub addline {
                   7669:     my ($fname,$hostid,$ip,$newline)=@_;
                   7670:     my $contents;
                   7671:     my $found=0;
1.355     albertel 7672:     my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134     albertel 7673:     my $sh;
1.84      albertel 7674:     if ($sh=IO::File->new("$fname.subscription")) {
                   7675: 	while (my $subline=<$sh>) {
                   7676: 	    if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
                   7677: 	}
                   7678: 	$sh->close();
                   7679:     }
                   7680:     $sh=IO::File->new(">$fname.subscription");
                   7681:     if ($contents) { print $sh $contents; }
                   7682:     if ($newline) { print $sh $newline; }
                   7683:     $sh->close();
                   7684:     return $found;
1.86      www      7685: }
                   7686: 
1.234     foxr     7687: sub get_chat {
1.324     raeburn  7688:     my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310     albertel 7689: 
1.87      www      7690:     my @entries=();
1.324     raeburn  7691:     my $namespace = 'nohist_chatroom';
                   7692:     my $namespace_inroom = 'nohist_inchatroom';
1.335     albertel 7693:     if ($group ne '') {
1.324     raeburn  7694:         $namespace .= '_'.$group;
                   7695:         $namespace_inroom .= '_'.$group;
                   7696:     }
                   7697:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 7698: 				 &GDBM_READER());
                   7699:     if ($hashref) {
                   7700: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311     albertel 7701: 	&untie_user_hash($hashref);
1.123     www      7702:     }
1.124     www      7703:     my @participants=();
1.134     albertel 7704:     my $cutoff=time-60;
1.324     raeburn  7705:     $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310     albertel 7706: 			      &GDBM_WRCREAT());
                   7707:     if ($hashref) {
                   7708:         $hashref->{$uname.':'.$udom}=time;
                   7709:         foreach my $user (sort(keys(%$hashref))) {
                   7710: 	    if ($hashref->{$user}>$cutoff) {
                   7711: 		push(@participants, 'active_participant:'.$user);
1.123     www      7712:             }
                   7713:         }
1.311     albertel 7714:         &untie_user_hash($hashref);
1.86      www      7715:     }
1.124     www      7716:     return (@participants,@entries);
1.86      www      7717: }
                   7718: 
1.234     foxr     7719: sub chat_add {
1.324     raeburn  7720:     my ($cdom,$cname,$newchat,$group)=@_;
1.88      albertel 7721:     my @entries=();
1.142     www      7722:     my $time=time;
1.324     raeburn  7723:     my $namespace = 'nohist_chatroom';
                   7724:     my $logfile = 'chatroom.log';
1.335     albertel 7725:     if ($group ne '') {
1.324     raeburn  7726:         $namespace .= '_'.$group;
                   7727:         $logfile = 'chatroom_'.$group.'.log';
                   7728:     }
                   7729:     my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310     albertel 7730: 				 &GDBM_WRCREAT());
                   7731:     if ($hashref) {
                   7732: 	@entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88      albertel 7733: 	my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
                   7734: 	my ($thentime,$idnum)=split(/\_/,$lastid);
                   7735: 	my $newid=$time.'_000000';
                   7736: 	if ($thentime==$time) {
                   7737: 	    $idnum=~s/^0+//;
                   7738: 	    $idnum++;
                   7739: 	    $idnum=substr('000000'.$idnum,-6,6);
                   7740: 	    $newid=$time.'_'.$idnum;
                   7741: 	}
1.310     albertel 7742: 	$hashref->{$newid}=$newchat;
1.88      albertel 7743: 	my $expired=$time-3600;
1.310     albertel 7744: 	foreach my $comment (keys(%$hashref)) {
                   7745: 	    my ($thistime) = ($comment=~/(\d+)\_/);
1.88      albertel 7746: 	    if ($thistime<$expired) {
1.310     albertel 7747: 		delete $hashref->{$comment};
1.88      albertel 7748: 	    }
                   7749: 	}
1.310     albertel 7750: 	{
                   7751: 	    my $proname=&propath($cdom,$cname);
1.324     raeburn  7752: 	    if (open(CHATLOG,">>$proname/$logfile")) { 
1.310     albertel 7753: 		print CHATLOG ("$time:".&unescape($newchat)."\n");
                   7754: 	    }
                   7755: 	    close(CHATLOG);
1.142     www      7756: 	}
1.311     albertel 7757: 	&untie_user_hash($hashref);
1.86      www      7758:     }
1.84      albertel 7759: }
                   7760: 
                   7761: sub unsub {
                   7762:     my ($fname,$clientip)=@_;
                   7763:     my $result;
1.188     foxr     7764:     my $unsubs = 0;		# Number of successful unsubscribes:
                   7765: 
                   7766: 
                   7767:     # An old way subscriptions were handled was to have a 
                   7768:     # subscription marker file:
                   7769: 
                   7770:     Debug("Attempting unlink of $fname.$clientname");
1.161     foxr     7771:     if (unlink("$fname.$clientname")) {
1.188     foxr     7772: 	$unsubs++;		# Successful unsub via marker file.
                   7773:     } 
                   7774: 
                   7775:     # The more modern way to do it is to have a subscription list
                   7776:     # file:
                   7777: 
1.84      albertel 7778:     if (-e "$fname.subscription") {
1.161     foxr     7779: 	my $found=&addline($fname,$clientname,$clientip,'');
1.188     foxr     7780: 	if ($found) { 
                   7781: 	    $unsubs++;
                   7782: 	}
                   7783:     } 
                   7784: 
                   7785:     #  If either or both of these mechanisms succeeded in unsubscribing a 
                   7786:     #  resource we can return ok:
                   7787: 
                   7788:     if($unsubs) {
                   7789: 	$result = "ok\n";
1.84      albertel 7790:     } else {
1.188     foxr     7791: 	$result = "not_subscribed\n";
1.84      albertel 7792:     }
1.188     foxr     7793: 
1.84      albertel 7794:     return $result;
                   7795: }
                   7796: 
1.101     www      7797: sub currentversion {
                   7798:     my $fname=shift;
                   7799:     my $version=-1;
                   7800:     my $ulsdir='';
                   7801:     if ($fname=~/^(.+)\/[^\/]+$/) {
                   7802:        $ulsdir=$1;
                   7803:     }
1.114     albertel 7804:     my ($fnamere1,$fnamere2);
                   7805:     # remove version if already specified
1.101     www      7806:     $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114     albertel 7807:     # get the bits that go before and after the version number
                   7808:     if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
                   7809: 	$fnamere1=$1;
                   7810: 	$fnamere2='.'.$2;
                   7811:     }
1.101     www      7812:     if (-e $fname) { $version=1; }
                   7813:     if (-e $ulsdir) {
1.134     albertel 7814: 	if(-d $ulsdir) {
                   7815: 	    if (opendir(LSDIR,$ulsdir)) {
                   7816: 		my $ulsfn;
                   7817: 		while ($ulsfn=readdir(LSDIR)) {
1.101     www      7818: # see if this is a regular file (ignore links produced earlier)
1.134     albertel 7819: 		    my $thisfile=$ulsdir.'/'.$ulsfn;
                   7820: 		    unless (-l $thisfile) {
1.160     www      7821: 			if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134     albertel 7822: 			    if ($1>$version) { $version=$1; }
                   7823: 			}
                   7824: 		    }
                   7825: 		}
                   7826: 		closedir(LSDIR);
                   7827: 		$version++;
                   7828: 	    }
                   7829: 	}
                   7830:     }
                   7831:     return $version;
1.101     www      7832: }
                   7833: 
                   7834: sub thisversion {
                   7835:     my $fname=shift;
                   7836:     my $version=-1;
                   7837:     if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
                   7838: 	$version=$1;
                   7839:     }
                   7840:     return $version;
                   7841: }
                   7842: 
1.84      albertel 7843: sub subscribe {
                   7844:     my ($userinput,$clientip)=@_;
                   7845:     my $result;
1.293     albertel 7846:     my ($cmd,$fname)=split(/:/,$userinput,2);
1.84      albertel 7847:     my $ownership=&ishome($fname);
                   7848:     if ($ownership eq 'owner') {
1.101     www      7849: # explitly asking for the current version?
                   7850:         unless (-e $fname) {
                   7851:             my $currentversion=&currentversion($fname);
                   7852: 	    if (&thisversion($fname)==$currentversion) {
                   7853:                 if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
                   7854: 		    my $root=$1;
                   7855:                     my $extension=$2;
                   7856:                     symlink($root.'.'.$extension,
                   7857:                             $root.'.'.$currentversion.'.'.$extension);
1.102     www      7858:                     unless ($extension=~/\.meta$/) {
                   7859:                        symlink($root.'.'.$extension.'.meta',
                   7860:                             $root.'.'.$currentversion.'.'.$extension.'.meta');
                   7861: 		    }
1.101     www      7862:                 }
                   7863:             }
                   7864:         }
1.84      albertel 7865: 	if (-e $fname) {
                   7866: 	    if (-d $fname) {
                   7867: 		$result="directory\n";
                   7868: 	    } else {
1.161     foxr     7869: 		if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134     albertel 7870: 		my $now=time;
1.161     foxr     7871: 		my $found=&addline($fname,$clientname,$clientip,
                   7872: 				   "$clientname:$clientip:$now\n");
1.84      albertel 7873: 		if ($found) { $result="$fname\n"; }
                   7874: 		# if they were subscribed to only meta data, delete that
                   7875:                 # subscription, when you subscribe to a file you also get
                   7876:                 # the metadata
                   7877: 		unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
                   7878: 		$fname=~s/\/home\/httpd\/html\/res/raw/;
1.476     raeburn  7879:                 my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
                   7880:                 $protocol = 'http' if ($protocol ne 'https');
                   7881: 		$fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84      albertel 7882: 		$result="$fname\n";
                   7883: 	    }
                   7884: 	} else {
                   7885: 	    $result="not_found\n";
                   7886: 	}
                   7887:     } else {
                   7888: 	$result="rejected\n";
                   7889:     }
                   7890:     return $result;
                   7891: }
1.287     foxr     7892: #  Change the passwd of a unix user.  The caller must have
                   7893: #  first verified that the user is a loncapa user.
                   7894: #
                   7895: # Parameters:
                   7896: #    user      - Unix user name to change.
                   7897: #    pass      - New password for the user.
                   7898: # Returns:
                   7899: #    ok    - if success
                   7900: #    other - Some meaningfule error message string.
                   7901: # NOTE:
                   7902: #    invokes a setuid script to change the passwd.
                   7903: sub change_unix_password {
                   7904:     my ($user, $pass) = @_;
                   7905: 
                   7906:     &Debug("change_unix_password");
                   7907:     my $execdir=$perlvar{'lonDaemons'};
                   7908:     &Debug("Opening lcpasswd pipeline");
                   7909:     my $pf = IO::File->new("|$execdir/lcpasswd > "
                   7910: 			   ."$perlvar{'lonDaemons'}"
                   7911: 			   ."/logs/lcpasswd.log");
                   7912:     print $pf "$user\n$pass\n$pass\n";
                   7913:     close $pf;
                   7914:     my $err = $?;
                   7915:     return ($err < @passwderrors) ? $passwderrors[$err] : 
                   7916: 	"pwchange_falure - unknown error";
                   7917: 
                   7918:     
                   7919: }
                   7920: 
1.91      albertel 7921: 
                   7922: sub make_passwd_file {
1.518     raeburn  7923:     my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390     raeburn  7924:     my $result="ok";
1.91      albertel 7925:     if ($umode eq 'krb4' or $umode eq 'krb5') {
                   7926: 	{
                   7927: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     7928: 	    if ($pf) {
                   7929: 		print $pf "$umode:$npass\n";
1.518     raeburn  7930:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     7931: 	    } else {
                   7932: 		$result = "pass_file_failed_error";
                   7933: 	    }
1.91      albertel 7934: 	}
                   7935:     } elsif ($umode eq 'internal') {
1.518     raeburn  7936:         my $ncpass = &hash_passwd($udom,$npass);
1.91      albertel 7937: 	{
                   7938: 	    &Debug("Creating internal auth");
                   7939: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     7940: 	    if($pf) {
1.518     raeburn  7941: 		print $pf "internal:$ncpass\n";
                   7942:                 &update_passwd_history($uname,$udom,$umode,$action); 
1.261     foxr     7943: 	    } else {
                   7944: 		$result = "pass_file_failed_error";
                   7945: 	    }
1.91      albertel 7946: 	}
                   7947:     } elsif ($umode eq 'localauth') {
                   7948: 	{
                   7949: 	    my $pf = IO::File->new(">$passfilename");
1.261     foxr     7950: 	    if($pf) {
                   7951: 		print $pf "localauth:$npass\n";
1.524     raeburn  7952:                 &update_passwd_history($uname,$udom,$umode,$action);
1.261     foxr     7953: 	    } else {
                   7954: 		$result = "pass_file_failed_error";
                   7955: 	    }
1.91      albertel 7956: 	}
                   7957:     } elsif ($umode eq 'unix') {
1.502     raeburn  7958: 	&logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
                   7959: 	$result="no_new_unix_accounts";
1.91      albertel 7960:     } elsif ($umode eq 'none') {
                   7961: 	{
1.223     foxr     7962: 	    my $pf = IO::File->new("> $passfilename");
1.261     foxr     7963: 	    if($pf) {
                   7964: 		print $pf "none:\n";
                   7965: 	    } else {
                   7966: 		$result = "pass_file_failed_error";
                   7967: 	    }
1.91      albertel 7968: 	}
                   7969:     } else {
1.390     raeburn  7970: 	$result="auth_mode_error";
1.91      albertel 7971:     }
                   7972:     return $result;
1.121     albertel 7973: }
                   7974: 
1.265     albertel 7975: sub convert_photo {
                   7976:     my ($start,$dest)=@_;
                   7977:     system("convert $start $dest");
                   7978: }
                   7979: 
1.121     albertel 7980: sub sethost {
                   7981:     my ($remotereq) = @_;
                   7982:     my (undef,$hostid)=split(/:/,$remotereq);
1.322     albertel 7983:     # ignore sethost if we are already correct
                   7984:     if ($hostid eq $currenthostid) {
                   7985: 	return 'ok';
                   7986:     }
                   7987: 
1.121     albertel 7988:     if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368     albertel 7989:     if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'}) 
                   7990: 	eq &Apache::lonnet::get_host_ip($hostid)) {
1.200     matthew  7991: 	$currenthostid  =$hostid;
1.369     albertel 7992: 	$currentdomainid=&Apache::lonnet::host_domain($hostid);
1.443     www      7993: #	&logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121     albertel 7994:     } else {
                   7995: 	&logthis("Requested host id $hostid not an alias of ".
                   7996: 		 $perlvar{'lonHostID'}." refusing connection");
                   7997: 	return 'unable_to_set';
                   7998:     }
                   7999:     return 'ok';
                   8000: }
                   8001: 
                   8002: sub version {
                   8003:     my ($userinput)=@_;
                   8004:     $remoteVERSION=(split(/:/,$userinput))[1];
                   8005:     return "version:$VERSION";
1.127     albertel 8006: }
1.178     foxr     8007: 
1.447     raeburn  8008: sub get_usersession_config {
                   8009:     my ($dom,$name) = @_;
                   8010:     my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8011:     if (defined($cached)) {
                   8012:         return $usersessionconf;
                   8013:     } else {
                   8014:         my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525     raeburn  8015:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
                   8016:         return $domconfig{'usersessions'};
1.447     raeburn  8017:     }
                   8018:     return;
                   8019: }
1.200     matthew  8020: 
1.525     raeburn  8021: sub get_prohibited {
                   8022:     my ($dom) = @_;
                   8023:     my $name = 'trust';
                   8024:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
                   8025:     unless (defined($cached)) {
                   8026:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
                   8027:         &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
                   8028:         $trustconfig = $domconfig{'trust'};
                   8029:     }
                   8030:     my %prohibited;
                   8031:     if (ref($trustconfig)) {
                   8032:         foreach my $prefix (keys(%{$trustconfig})) {
                   8033:             if (ref($trustconfig->{$prefix}) eq 'HASH') {
                   8034:                 my $reject;
                   8035:                 if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
                   8036:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
                   8037:                         $reject = 1;
                   8038:                     }
                   8039:                 }
                   8040:                 if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
                   8041:                     if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
                   8042:                         $reject = 0;
                   8043:                     } else {
                   8044:                         $reject = 1;
                   8045:                     }
                   8046:                 }
                   8047:                 if ($reject) {
                   8048:                     $prohibited{$prefix} = 1;
                   8049:                 }
                   8050:             }
                   8051:         }
                   8052:     }
                   8053:     return %prohibited;
                   8054: }
1.450     raeburn  8055: 
1.471     raeburn  8056: sub distro_and_arch {
                   8057:     return $dist.':'.$arch;
                   8058: }
                   8059: 
1.61      harris41 8060: # ----------------------------------- POD (plain old documentation, CPAN style)
                   8061: 
                   8062: =head1 NAME
                   8063: 
                   8064: lond - "LON Daemon" Server (port "LOND" 5663)
                   8065: 
                   8066: =head1 SYNOPSIS
                   8067: 
1.74      harris41 8068: Usage: B<lond>
                   8069: 
                   8070: Should only be run as user=www.  This is a command-line script which
                   8071: is invoked by B<loncron>.  There is no expectation that a typical user
                   8072: will manually start B<lond> from the command-line.  (In other words,
                   8073: DO NOT START B<lond> YOURSELF.)
1.61      harris41 8074: 
                   8075: =head1 DESCRIPTION
                   8076: 
1.74      harris41 8077: There are two characteristics associated with the running of B<lond>,
                   8078: PROCESS MANAGEMENT (starting, stopping, handling child processes)
                   8079: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
                   8080: subscriptions, etc).  These are described in two large
                   8081: sections below.
                   8082: 
                   8083: B<PROCESS MANAGEMENT>
                   8084: 
1.61      harris41 8085: Preforker - server who forks first. Runs as a daemon. HUPs.
                   8086: Uses IDEA encryption
                   8087: 
1.74      harris41 8088: B<lond> forks off children processes that correspond to the other servers
                   8089: in the network.  Management of these processes can be done at the
                   8090: parent process level or the child process level.
                   8091: 
                   8092: B<logs/lond.log> is the location of log messages.
                   8093: 
                   8094: The process management is now explained in terms of linux shell commands,
                   8095: subroutines internal to this code, and signal assignments:
                   8096: 
                   8097: =over 4
                   8098: 
                   8099: =item *
                   8100: 
                   8101: PID is stored in B<logs/lond.pid>
                   8102: 
                   8103: This is the process id number of the parent B<lond> process.
                   8104: 
                   8105: =item *
                   8106: 
                   8107: SIGTERM and SIGINT
                   8108: 
                   8109: Parent signal assignment:
                   8110:  $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
                   8111: 
                   8112: Child signal assignment:
                   8113:  $SIG{INT}  = 'DEFAULT'; (and SIGTERM is DEFAULT also)
                   8114: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
                   8115:  to restart a new child.)
                   8116: 
                   8117: Command-line invocations:
                   8118:  B<kill> B<-s> SIGTERM I<PID>
                   8119:  B<kill> B<-s> SIGINT I<PID>
                   8120: 
                   8121: Subroutine B<HUNTSMAN>:
                   8122:  This is only invoked for the B<lond> parent I<PID>.
                   8123: This kills all the children, and then the parent.
                   8124: The B<lonc.pid> file is cleared.
                   8125: 
                   8126: =item *
                   8127: 
                   8128: SIGHUP
                   8129: 
                   8130: Current bug:
                   8131:  This signal can only be processed the first time
                   8132: on the parent process.  Subsequent SIGHUP signals
                   8133: have no effect.
                   8134: 
                   8135: Parent signal assignment:
                   8136:  $SIG{HUP}  = \&HUPSMAN;
                   8137: 
                   8138: Child signal assignment:
                   8139:  none (nothing happens)
                   8140: 
                   8141: Command-line invocations:
                   8142:  B<kill> B<-s> SIGHUP I<PID>
                   8143: 
                   8144: Subroutine B<HUPSMAN>:
                   8145:  This is only invoked for the B<lond> parent I<PID>,
                   8146: This kills all the children, and then the parent.
                   8147: The B<lond.pid> file is cleared.
                   8148: 
                   8149: =item *
                   8150: 
                   8151: SIGUSR1
                   8152: 
                   8153: Parent signal assignment:
                   8154:  $SIG{USR1} = \&USRMAN;
                   8155: 
                   8156: Child signal assignment:
                   8157:  $SIG{USR1}= \&logstatus;
                   8158: 
                   8159: Command-line invocations:
                   8160:  B<kill> B<-s> SIGUSR1 I<PID>
                   8161: 
                   8162: Subroutine B<USRMAN>:
                   8163:  When invoked for the B<lond> parent I<PID>,
                   8164: SIGUSR1 is sent to all the children, and the status of
                   8165: each connection is logged.
1.144     foxr     8166: 
                   8167: =item *
                   8168: 
                   8169: SIGUSR2
                   8170: 
                   8171: Parent Signal assignment:
                   8172:     $SIG{USR2} = \&UpdateHosts
                   8173: 
                   8174: Child signal assignment:
                   8175:     NONE
                   8176: 
1.74      harris41 8177: 
                   8178: =item *
                   8179: 
                   8180: SIGCHLD
                   8181: 
                   8182: Parent signal assignment:
                   8183:  $SIG{CHLD} = \&REAPER;
                   8184: 
                   8185: Child signal assignment:
                   8186:  none
                   8187: 
                   8188: Command-line invocations:
                   8189:  B<kill> B<-s> SIGCHLD I<PID>
                   8190: 
                   8191: Subroutine B<REAPER>:
                   8192:  This is only invoked for the B<lond> parent I<PID>.
                   8193: Information pertaining to the child is removed.
                   8194: The socket port is cleaned up.
                   8195: 
                   8196: =back
                   8197: 
                   8198: B<SERVER-SIDE ACTIVITIES>
                   8199: 
                   8200: Server-side information can be accepted in an encrypted or non-encrypted
                   8201: method.
                   8202: 
                   8203: =over 4
                   8204: 
                   8205: =item ping
                   8206: 
                   8207: Query a client in the hosts.tab table; "Are you there?"
                   8208: 
                   8209: =item pong
                   8210: 
                   8211: Respond to a ping query.
                   8212: 
                   8213: =item ekey
                   8214: 
                   8215: Read in encrypted key, make cipher.  Respond with a buildkey.
                   8216: 
                   8217: =item load
                   8218: 
                   8219: Respond with CPU load based on a computation upon /proc/loadavg.
                   8220: 
                   8221: =item currentauth
                   8222: 
                   8223: Reply with current authentication information (only over an
                   8224: encrypted channel).
                   8225: 
                   8226: =item auth
                   8227: 
                   8228: Only over an encrypted channel, reply as to whether a user's
                   8229: authentication information can be validated.
                   8230: 
                   8231: =item passwd
                   8232: 
                   8233: Allow for a password to be set.
                   8234: 
                   8235: =item makeuser
                   8236: 
                   8237: Make a user.
                   8238: 
1.517     raeburn  8239: =item changeuserauth
1.74      harris41 8240: 
                   8241: Allow for authentication mechanism and password to be changed.
                   8242: 
                   8243: =item home
1.61      harris41 8244: 
1.74      harris41 8245: Respond to a question "are you the home for a given user?"
                   8246: 
                   8247: =item update
                   8248: 
                   8249: Update contents of a subscribed resource.
                   8250: 
                   8251: =item unsubscribe
                   8252: 
                   8253: The server is unsubscribing from a resource.
                   8254: 
                   8255: =item subscribe
                   8256: 
                   8257: The server is subscribing to a resource.
                   8258: 
                   8259: =item log
                   8260: 
                   8261: Place in B<logs/lond.log>
                   8262: 
                   8263: =item put
                   8264: 
                   8265: stores hash in namespace
                   8266: 
1.496     raeburn  8267: =item rolesput
1.74      harris41 8268: 
                   8269: put a role into a user's environment
                   8270: 
                   8271: =item get
                   8272: 
                   8273: returns hash with keys from array
                   8274: reference filled in from namespace
                   8275: 
                   8276: =item eget
                   8277: 
                   8278: returns hash with keys from array
                   8279: reference filled in from namesp (encrypts the return communication)
                   8280: 
                   8281: =item rolesget
                   8282: 
                   8283: get a role from a user's environment
                   8284: 
                   8285: =item del
                   8286: 
                   8287: deletes keys out of array from namespace
                   8288: 
                   8289: =item keys
                   8290: 
                   8291: returns namespace keys
                   8292: 
                   8293: =item dump
                   8294: 
                   8295: dumps the complete (or key matching regexp) namespace into a hash
                   8296: 
                   8297: =item store
                   8298: 
                   8299: stores hash permanently
                   8300: for this url; hashref needs to be given and should be a \%hashname; the
                   8301: remaining args aren't required and if they aren't passed or are '' they will
                   8302: be derived from the ENV
                   8303: 
                   8304: =item restore
                   8305: 
                   8306: returns a hash for a given url
                   8307: 
                   8308: =item querysend
                   8309: 
                   8310: Tells client about the lonsql process that has been launched in response
                   8311: to a sent query.
                   8312: 
                   8313: =item queryreply
                   8314: 
                   8315: Accept information from lonsql and make appropriate storage in temporary
                   8316: file space.
                   8317: 
                   8318: =item idput
                   8319: 
                   8320: Defines usernames as corresponding to IDs.  (These "IDs" are unique identifiers
                   8321: for each student, defined perhaps by the institutional Registrar.)
                   8322: 
                   8323: =item idget
                   8324: 
                   8325: Returns usernames corresponding to IDs.  (These "IDs" are unique identifiers
                   8326: for each student, defined perhaps by the institutional Registrar.)
                   8327: 
1.517     raeburn  8328: =item iddel
                   8329: 
                   8330: Deletes one or more ids in a domain's id database.
                   8331: 
1.74      harris41 8332: =item tmpput
                   8333: 
                   8334: Accept and store information in temporary space.
                   8335: 
                   8336: =item tmpget
                   8337: 
                   8338: Send along temporarily stored information.
                   8339: 
                   8340: =item ls
                   8341: 
                   8342: List part of a user's directory.
                   8343: 
1.135     foxr     8344: =item pushtable
                   8345: 
                   8346: Pushes a file in /home/httpd/lonTab directory.  Currently limited to:
                   8347: hosts.tab and domain.tab. The old file is copied to  *.tab.backup but
                   8348: must be restored manually in case of a problem with the new table file.
                   8349: pushtable requires that the request be encrypted and validated via
                   8350: ValidateManager.  The form of the command is:
                   8351: enc:pushtable tablename <tablecontents> \n
                   8352: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a 
                   8353: cleartext newline.
                   8354: 
1.74      harris41 8355: =item Hanging up (exit or init)
                   8356: 
                   8357: What to do when a client tells the server that they (the client)
                   8358: are leaving the network.
                   8359: 
                   8360: =item unknown command
                   8361: 
                   8362: If B<lond> is sent an unknown command (not in the list above),
                   8363: it replys to the client "unknown_cmd".
1.135     foxr     8364: 
1.74      harris41 8365: 
                   8366: =item UNKNOWN CLIENT
                   8367: 
                   8368: If the anti-spoofing algorithm cannot verify the client,
                   8369: the client is rejected (with a "refused" message sent
                   8370: to the client, and the connection is closed.
                   8371: 
                   8372: =back
1.61      harris41 8373: 
                   8374: =head1 PREREQUISITES
                   8375: 
                   8376: IO::Socket
                   8377: IO::File
                   8378: Apache::File
                   8379: POSIX
                   8380: Crypt::IDEA
                   8381: LWP::UserAgent()
                   8382: GDBM_File
                   8383: Authen::Krb4
1.91      albertel 8384: Authen::Krb5
1.61      harris41 8385: 
                   8386: =head1 COREQUISITES
                   8387: 
1.490     droeschl 8388: none
                   8389: 
1.61      harris41 8390: =head1 OSNAMES
                   8391: 
                   8392: linux
                   8393: 
                   8394: =head1 SCRIPT CATEGORIES
                   8395: 
                   8396: Server/Process
                   8397: 
                   8398: =cut
1.409     foxr     8399: 
                   8400: 
                   8401: =pod
                   8402: 
                   8403: =head1 LOG MESSAGES
                   8404: 
                   8405: The messages below can be emitted in the lond log.  This log is located
                   8406: in ~httpd/perl/logs/lond.log  Many log messages have HTML encapsulation
                   8407: to provide coloring if examined from inside a web page. Some do not.
                   8408: Where color is used, the colors are; Red for sometihhng to get excited
                   8409: about and to follow up on. Yellow for something to keep an eye on to
                   8410: be sure it does not get worse, Green,and Blue for informational items.
                   8411: 
                   8412: In the discussions below, sometimes reference is made to ~httpd
                   8413: when describing file locations.  There isn't really an httpd 
                   8414: user, however there is an httpd directory that gets installed in the
                   8415: place that user home directories go.  On linux, this is usually
                   8416: (always?) /home/httpd.
                   8417: 
                   8418: 
                   8419: Some messages are colorless.  These are usually (not always)
                   8420: Green/Blue color level messages.
                   8421: 
                   8422: =over 2
                   8423: 
                   8424: =item (Red)  LocalConnection rejecting non local: <ip> ne 127.0.0.1
                   8425: 
                   8426: A local connection negotiation was attempted by
                   8427: a host whose IP address was not 127.0.0.1.
                   8428: The socket is closed and the child will exit.
                   8429: lond has three ways to establish an encyrption
                   8430: key with a client:
                   8431: 
                   8432: =over 2
                   8433: 
                   8434: =item local 
                   8435: 
                   8436: The key is written and read from a file.
                   8437: This is only valid for connections from localhost.
                   8438: 
                   8439: =item insecure 
                   8440: 
                   8441: The key is generated by the server and
                   8442: transmitted to the client.
                   8443: 
                   8444: =item  ssl (secure)
                   8445: 
                   8446: An ssl connection is negotiated with the client,
                   8447: the key is generated by the server and sent to the 
                   8448: client across this ssl connection before the
                   8449: ssl connectionis terminated and clear text
                   8450: transmission resumes.
                   8451: 
                   8452: =back
                   8453: 
                   8454: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
                   8455: 
                   8456: The client is local but has not sent an initialization
                   8457: string that is the literal "init:local"  The connection
                   8458: is closed and the child exits.
                   8459: 
                   8460: =item Red CRITICAL Can't get key file <error>        
                   8461: 
                   8462: SSL key negotiation is being attempted but the call to
                   8463: lonssl::KeyFile  failed.  This usually means that the
                   8464: configuration file is not correctly defining or protecting
                   8465: the directories/files lonCertificateDirectory or
                   8466: lonnetPrivateKey
                   8467: <error> is a string that describes the reason that
                   8468: the key file could not be located.
                   8469: 
                   8470: =item (Red) CRITICAL  Can't get certificates <error>  
                   8471: 
                   8472: SSL key negotiation failed because we were not able to retrives our certificate
                   8473: or the CA's certificate in the call to lonssl::CertificateFile
                   8474: <error> is the textual reason this failed.  Usual reasons:
                   8475: 
                   8476: =over 2
1.490     droeschl 8477: 
1.409     foxr     8478: =item Apache config file for loncapa  incorrect:
1.490     droeschl 8479: 
1.409     foxr     8480: one of the variables 
                   8481: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
                   8482: undefined or incorrect
                   8483: 
                   8484: =item Permission error:
                   8485: 
                   8486: The directory pointed to by lonCertificateDirectory is not readable by lond
                   8487: 
                   8488: =item Permission error:
                   8489: 
                   8490: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
                   8491: 
                   8492: =item Installation error:                         
                   8493: 
                   8494: Either the certificate authority file or the certificate have not
                   8495: been installed in lonCertificateDirectory.
                   8496: 
                   8497: =item (Red) CRITICAL SSL Socket promotion failed:  <err> 
                   8498: 
                   8499: The promotion of the connection from plaintext to SSL failed
                   8500: <err> is the reason for the failure.  There are two
                   8501: system calls involved in the promotion (one of which failed), 
                   8502: a dup to produce
                   8503: a second fd on the raw socket over which the encrypted data
                   8504: will flow and IO::SOcket::SSL->new_from_fd which creates
                   8505: the SSL connection on the duped fd.
                   8506: 
                   8507: =item (Blue)   WARNING client did not respond to challenge 
                   8508: 
                   8509: This occurs on an insecure (non SSL) connection negotiation request.
                   8510: lond generates some number from the time, the PID and sends it to
                   8511: the client.  The client must respond by echoing this information back.
                   8512: If the client does not do so, that's a violation of the challenge
                   8513: protocols and the connection will be failed.
                   8514: 
                   8515: =item (Red) No manager table. Nobody can manage!!    
                   8516: 
                   8517: lond has the concept of privileged hosts that
                   8518: can perform remote management function such
                   8519: as update the hosts.tab.   The manager hosts
                   8520: are described in the 
                   8521: ~httpd/lonTabs/managers.tab file.
                   8522: this message is logged if this file is missing.
                   8523: 
                   8524: 
                   8525: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
                   8526: 
                   8527: Reports the successful parse and registration
                   8528: of a specific manager. 
                   8529: 
                   8530: =item Green existing host <clustername:dnsname>  
                   8531: 
                   8532: The manager host is already defined in the hosts.tab
                   8533: the information in that table, rather than the info in the
                   8534: manager table will be used to determine the manager's ip.
                   8535: 
                   8536: =item (Red) Unable to craete <filename>                 
                   8537: 
                   8538: lond has been asked to create new versions of an administrative
                   8539: file (by a manager).  When this is done, the new file is created
                   8540: in a temp file and then renamed into place so that there are always
                   8541: usable administrative files, even if the update fails.  This failure
                   8542: message means that the temp file could not be created.
                   8543: The update is abandoned, and the old file is available for use.
                   8544: 
                   8545: =item (Green) CopyFile from <oldname> to <newname> failed
                   8546: 
                   8547: In an update of administrative files, the copy of the existing file to a
                   8548: backup file failed.  The installation of the new file may still succeed,
                   8549: but there will not be a back up file to rever to (this should probably
                   8550: be yellow).
                   8551: 
                   8552: =item (Green) Pushfile: backed up <oldname> to <newname>
                   8553: 
                   8554: See above, the backup of the old administrative file succeeded.
                   8555: 
                   8556: =item (Red)  Pushfile: Unable to install <filename> <reason>
                   8557: 
                   8558: The new administrative file could not be installed.  In this case,
                   8559: the old administrative file is still in use.
                   8560: 
                   8561: =item (Green) Installed new < filename>.                      
                   8562: 
                   8563: The new administrative file was successfullly installed.                                               
                   8564: 
                   8565: =item (Red) Reinitializing lond pid=<pid>                    
                   8566: 
                   8567: The lonc child process <pid> will be sent a USR2 
                   8568: signal.
                   8569: 
                   8570: =item (Red) Reinitializing self                                    
                   8571: 
                   8572: We've been asked to re-read our administrative files,and
                   8573: are doing so.
                   8574: 
                   8575: =item (Yellow) error:Invalid process identifier <ident>  
                   8576: 
                   8577: A reinit command was received, but the target part of the 
                   8578: command was not valid.  It must be either
                   8579: 'lond' or 'lonc' but was <ident>
                   8580: 
                   8581: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
                   8582: 
                   8583: Checking to see if lond has been handed a valid edit
                   8584: command.  It is possible the edit command is not valid
                   8585: in that case there are no log messages to indicate that.
                   8586: 
                   8587: =item Result of password change for  <username> pwchange_success
                   8588: 
                   8589: The password for <username> was
                   8590: successfully changed.
                   8591: 
                   8592: =item Unable to open <user> passwd to change password
                   8593: 
                   8594: Could not rewrite the 
                   8595: internal password file for a user
                   8596: 
                   8597: =item Result of password change for <user> : <result>
1.490     droeschl 8598: 
1.409     foxr     8599: A unix password change for <user> was attempted 
                   8600: and the pipe returned <result>  
                   8601: 
                   8602: =item LWP GET: <message> for <fname> (<remoteurl>)
                   8603: 
                   8604: The lightweight process fetch for a resource failed
                   8605: with <message> the local filename that should
                   8606: have existed/been created was  <fname> the
                   8607: corresponding URI: <remoteurl>  This is emitted in several
                   8608: places.
                   8609: 
                   8610: =item Unable to move <transname> to <destname>     
                   8611: 
                   8612: From fetch_user_file_handler - the user file was replicated but could not
                   8613: be mv'd to its final location.
                   8614: 
                   8615: =item Looking for <domain> <username>              
                   8616: 
                   8617: From user_has_session_handler - This should be a Debug call instead
                   8618: it indicates lond is about to check whether the specified user has a 
                   8619: session active on the specified domain on the local host.
                   8620: 
                   8621: =item Client <ip> (<name>) hanging up: <input>     
                   8622: 
                   8623: lond has been asked to exit by its client.  The <ip> and <name> identify the
                   8624: client systemand <input> is the full exit command sent to the server.
                   8625: 
                   8626: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490     droeschl 8627: 
1.409     foxr     8628: A lond child terminated.  NOte that this termination can also occur when the
                   8629: child receives the QUIT or DIE signals.  <pid> is the process id of the child,
                   8630: <hostname> the host lond is working for, and <message> the reason the child died
                   8631: to the best of our ability to get it (I would guess that any numeric value
                   8632: represents and errno value).  This is immediately followed by
                   8633: 
                   8634: =item  Famous last words: Catching exception - <log> 
                   8635: 
                   8636: Where log is some recent information about the state of the child.
                   8637: 
                   8638: =item Red CRITICAL: TIME OUT <pid>                     
                   8639: 
                   8640: Some timeout occured for server <pid>.  THis is normally a timeout on an LWP
                   8641: doing an HTTP::GET.
                   8642: 
                   8643: =item child <pid> died                              
                   8644: 
                   8645: The reaper caught a SIGCHILD for the lond child process <pid>
                   8646: This should be modified to also display the IP of the dying child
                   8647: $children{$pid}
                   8648: 
                   8649: =item Unknown child 0 died                           
                   8650: A child died but the wait for it returned a pid of zero which really should not
                   8651: ever happen. 
                   8652: 
                   8653: =item Child <which> - <pid> looks like we missed it's death 
                   8654: 
                   8655: When a sigchild is received, the reaper process checks all children to see if they are
                   8656: alive.  If children are dying quite quickly, the lack of signal queuing can mean
                   8657: that a signal hearalds the death of more than one child.  If so this message indicates
                   8658: which other one died. <which> is the ip of a dead child
                   8659: 
                   8660: =item Free socket: <shutdownretval>                
                   8661: 
                   8662: The HUNTSMAN sub was called due to a SIGINT in a child process.  The socket is being shutdown.
                   8663: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
                   8664: to return anything. This is followed by: 
                   8665: 
                   8666: =item Red CRITICAL: Shutting down                       
                   8667: 
                   8668: Just prior to exit.
                   8669: 
                   8670: =item Free socket: <shutdownretval>                 
                   8671: 
                   8672: The HUPSMAN sub was called due to a SIGHUP.  all children get killsed, and lond execs itself.
                   8673: This is followed by:
                   8674: 
                   8675: =item (Red) CRITICAL: Restarting                         
                   8676: 
                   8677: lond is about to exec itself to restart.
                   8678: 
                   8679: =item (Blue) Updating connections                        
                   8680: 
                   8681: (In response to a USR2).  All the children (except the one for localhost)
                   8682: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
                   8683: 
                   8684: =item (Blue) UpdateHosts killing child <pid> for ip <ip>   
                   8685: 
                   8686: Due to USR2 as above.
                   8687: 
                   8688: =item (Green) keeping child for ip <ip> (pid = <pid>)    
                   8689: 
                   8690: In response to USR2 as above, the child indicated is not being restarted because
                   8691: it's assumed that we'll always need a child for the localhost.
                   8692: 
                   8693: 
                   8694: =item Going to check on the children                
                   8695: 
                   8696: Parent is about to check on the health of the child processes.
                   8697: Note that this is in response to a USR1 sent to the parent lond.
                   8698: there may be one or more of the next two messages:
                   8699: 
                   8700: =item <pid> is dead                                 
                   8701: 
                   8702: A child that we have in our child hash as alive has evidently died.
                   8703: 
                   8704: =item  Child <pid> did not respond                   
                   8705: 
                   8706: In the health check the child <pid> did not update/produce a pid_.txt
                   8707: file when sent it's USR1 signal.  That process is killed with a 9 signal, as it's
                   8708: assumed to be hung in some un-fixable way.
                   8709: 
                   8710: =item Finished checking children                   
1.490     droeschl 8711: 
1.409     foxr     8712: Master processs's USR1 processing is cojmplete.
                   8713: 
                   8714: =item (Red) CRITICAL: ------- Starting ------            
                   8715: 
                   8716: (There are more '-'s on either side).  Lond has forked itself off to 
                   8717: form a new session and is about to start actual initialization.
                   8718: 
                   8719: =item (Green) Attempting to start child (<client>)       
                   8720: 
                   8721: Started a new child process for <client>.  Client is IO::Socket object
                   8722: connected to the child.  This was as a result of a TCP/IP connection from a client.
                   8723: 
                   8724: =item Unable to determine who caller was, getpeername returned nothing
1.490     droeschl 8725: 
1.409     foxr     8726: In child process initialization.  either getpeername returned undef or
                   8727: a zero sized object was returned.  Processing continues, but in my opinion,
                   8728: this should be cause for the child to exit.
                   8729: 
                   8730: =item Unable to determine clientip                  
                   8731: 
                   8732: In child process initialization.  The peer address from getpeername was not defined.
                   8733: The client address is stored as "Unavailable" and processing continues.
                   8734: 
                   8735: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490     droeschl 8736: 
1.409     foxr     8737: In child initialization.  A good connectionw as received from <ip>.
                   8738: 
                   8739: =over 2
                   8740: 
                   8741: =item <name> 
                   8742: 
                   8743: is the name of the client from hosts.tab.
                   8744: 
                   8745: =item <type> 
                   8746: 
                   8747: Is the connection type which is either 
                   8748: 
                   8749: =over 2
                   8750: 
                   8751: =item manager 
                   8752: 
                   8753: The connection is from a manager node, not in hosts.tab
                   8754: 
                   8755: =item client  
                   8756: 
                   8757: the connection is from a non-manager in the hosts.tab
                   8758: 
                   8759: =item both
                   8760: 
                   8761: The connection is from a manager in the hosts.tab.
                   8762: 
                   8763: =back
                   8764: 
                   8765: =back
                   8766: 
                   8767: =item (Blue) Certificates not installed -- trying insecure auth
                   8768: 
                   8769: One of the certificate file, key file or
                   8770: certificate authority file could not be found for a client attempting
                   8771: SSL connection intiation.  COnnection will be attemptied in in-secure mode.
                   8772: (this would be a system with an up to date lond that has not gotten a 
                   8773: certificate from us).
                   8774: 
                   8775: =item (Green)  Successful local authentication            
                   8776: 
                   8777: A local connection successfully negotiated the encryption key. 
                   8778: In this case the IDEA key is in a file (that is hopefully well protected).
                   8779: 
                   8780: =item (Green) Successful ssl authentication with <client>  
                   8781: 
                   8782: The client (<client> is the peer's name in hosts.tab), has successfully
                   8783: negotiated an SSL connection with this child process.
                   8784: 
                   8785: =item (Green) Successful insecure authentication with <client>
1.490     droeschl 8786: 
1.409     foxr     8787: 
                   8788: The client has successfully negotiated an  insecure connection withthe child process.
                   8789: 
                   8790: =item (Yellow) Attempted insecure connection disallowed    
                   8791: 
                   8792: The client attempted and failed to successfully negotiate a successful insecure
                   8793: connection.  This can happen either because the variable londAllowInsecure is false
                   8794: or undefined, or becuse the child did not successfully echo back the challenge
                   8795: string.
                   8796: 
                   8797: 
                   8798: =back
                   8799: 
1.441     raeburn  8800: =back
                   8801: 
1.409     foxr     8802: 
                   8803: =cut

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