Annotation of loncom/lond, revision 1.528

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

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