Annotation of loncom/lond, revision 1.532

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

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