Annotation of loncom/lond, revision 1.583
1.1 albertel 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60 www 4: #
1.583 ! raeburn 5: # $Id: lond,v 1.582 2024/12/27 01:04:00 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.583 ! raeburn 68: my $VERSION='$Revision: 1.582 $'; #' stupid emacs
1.121 albertel 69: my $remoteVERSION;
1.214 foxr 70: my $currenthostid="default";
1.115 albertel 71: my $currentdomainid;
1.134 albertel 72:
73: my $client;
1.200 matthew 74: my $clientip; # IP address of client.
75: my $clientname; # LonCAPA name of client.
1.448 raeburn 76: my $clientversion; # LonCAPA version running on client.
77: my $clienthomedom; # LonCAPA domain of homeID for client.
1.525 raeburn 78: my $clientintdom; # LonCAPA "internet domain" for client.
1.532 raeburn 79: my $clientsamedom; # LonCAPA domain same for this host
80: # and client.
1.525 raeburn 81: my $clientsameinst; # LonCAPA "internet domain" same for
82: # this host and client.
1.556 raeburn 83: my $clientremoteok; # Current domain permits hosting on client
84: # (not set if host and client share "internet domain").
85: # Values are 0 or 1; 1 if allowed.
86: my %clientprohibited; # Commands from client prohibited for domain's
87: # users.
88:
1.134 albertel 89: my $server;
1.200 matthew 90:
91: my $keymode;
1.198 foxr 92:
1.207 foxr 93: my $cipher; # Cipher key negotiated with client
94: my $tmpsnum = 0; # Id of tmpputs.
95:
1.178 foxr 96: #
97: # Connection type is:
98: # client - All client actions are allowed
99: # manager - only management functions allowed.
100: # both - Both management and client actions are allowed
101: #
1.161 foxr 102:
1.178 foxr 103: my $ConnectionType;
1.161 foxr 104:
1.178 foxr 105: my %managers; # Ip -> manager names
1.161 foxr 106:
1.178 foxr 107: my %perlvar; # Will have the apache conf defined perl vars.
1.134 albertel 108:
1.532 raeburn 109: my %secureconf; # Will have requirements for security
110: # of lond connections
111:
1.545 raeburn 112: my %crlchecked; # Will contain clients for which the client's SSL
113: # has been checked against the cluster's Certificate
114: # Revocation List.
115:
1.480 raeburn 116: my $dist;
117:
1.178 foxr 118: #
1.207 foxr 119: # The hash below is used for command dispatching, and is therefore keyed on the request keyword.
120: # Each element of the hash contains a reference to an array that contains:
121: # A reference to a sub that executes the request corresponding to the keyword.
122: # A flag that is true if the request must be encoded to be acceptable.
123: # A mask with bits as follows:
124: # CLIENT_OK - Set when the function is allowed by ordinary clients
125: # MANAGER_OK - Set when the function is allowed to manager clients.
126: #
127: my $CLIENT_OK = 1;
128: my $MANAGER_OK = 2;
129: my %Dispatcher;
130:
131:
132: #
1.178 foxr 133: # The array below are password error strings."
134: #
135: my $lastpwderror = 13; # Largest error number from lcpasswd.
136: my @passwderrors = ("ok",
1.287 foxr 137: "pwchange_failure - lcpasswd must be run as user 'www'",
138: "pwchange_failure - lcpasswd got incorrect number of arguments",
139: "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
140: "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
141: "pwchange_failure - lcpasswd User does not exist.",
142: "pwchange_failure - lcpasswd Incorrect current passwd",
143: "pwchange_failure - lcpasswd Unable to su to root.",
144: "pwchange_failure - lcpasswd Cannot set new passwd.",
145: "pwchange_failure - lcpasswd Username has invalid characters",
146: "pwchange_failure - lcpasswd Invalid characters in password",
147: "pwchange_failure - lcpasswd User already exists",
148: "pwchange_failure - lcpasswd Something went wrong with user addition.",
149: "pwchange_failure - lcpasswd Password mismatch",
150: "pwchange_failure - lcpasswd Error filename is invalid");
1.97 foxr 151:
152:
1.412 foxr 153: # This array are the errors from lcinstallfile:
154:
155: my @installerrors = ("ok",
156: "Initial user id of client not that of www",
157: "Usage error, not enough command line arguments",
1.500 bisitz 158: "Source filename does not exist",
159: "Destination filename does not exist",
1.412 foxr 160: "Some file operation failed",
161: "Invalid table filename."
162: );
1.207 foxr 163:
164: #
1.525 raeburn 165: # The %trust hash classifies commands according to type of trust
166: # required for execution of the command.
167: #
168: # When clients from a different institution request execution of a
169: # particular command, the trust settings for that institution set
170: # for this domain (or default domain for a multi-domain server) will
171: # be checked to see if running the command is allowed.
172: #
173: # Trust types which depend on the "Trust" domain configuration
174: # for the machine's default domain are:
175: #
176: # content ("Access to this domain's content by others")
177: # shared ("Access to other domain's content by this domain")
178: # enroll ("Enrollment in this domain's courses by others")
179: # coaurem ("Co-author roles for this domain's users elsewhere")
1.552 raeburn 180: # othcoau ("Co-author roles in this domain for others")
1.525 raeburn 181: # domroles ("Domain roles in this domain assignable to others")
182: # catalog ("Course Catalog for this domain displayed elsewhere")
183: # reqcrs ("Requests for creation of courses in this domain by others")
184: # msg ("Users in other domains can send messages to this domain")
185: #
186: # Trust type which depends on the User Session Hosting (remote)
187: # domain configuration for machine's default domain is: "remote".
188: #
189: # Trust types which depend on contents of manager.tab in
190: # /home/httpd/lonTabs is: "manageronly".
191: #
192: # Trust type which requires client to share the same LON-CAPA
193: # "internet domain" (i.e., same institution as this server) is:
194: # "institutiononly".
195: #
196:
197: my %trust = (
198: auth => {remote => 1},
199: autocreatepassword => {remote => 1},
200: autocrsreqchecks => {remote => 1, reqcrs => 1},
201: autocrsrequpdate => {remote => 1},
202: autocrsreqvalidation => {remote => 1},
203: autogetsections => {remote => 1},
204: autoinstcodedefaults => {remote => 1, catalog => 1},
205: autoinstcodeformat => {remote => 1, catalog => 1},
206: autonewcourse => {remote => 1, reqcrs => 1},
207: autophotocheck => {remote => 1, enroll => 1},
208: autophotochoice => {remote => 1},
209: autophotopermission => {remote => 1, enroll => 1},
210: autopossibleinstcodes => {remote => 1, reqcrs => 1},
211: autoretrieve => {remote => 1, enroll => 1, catalog => 1},
212: autorun => {remote => 1, enroll => 1, reqcrs => 1},
213: autovalidateclass_sec => {catalog => 1},
214: autovalidatecourse => {remote => 1, enroll => 1},
215: autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
1.566 raeburn 216: autovalidateinstcrosslist => {remote => 1, enroll => 1},
1.567 raeburn 217: autoinstsecreformat => {remote => 1, enroll => 1},
1.525 raeburn 218: changeuserauth => {remote => 1, domroles => 1},
219: chatretr => {remote => 1, enroll => 1},
220: chatsend => {remote => 1, enroll => 1},
221: courseiddump => {remote => 1, domroles => 1, enroll => 1},
222: courseidput => {remote => 1, domroles => 1, enroll => 1},
223: courseidputhash => {remote => 1, domroles => 1, enroll => 1},
224: courselastaccess => {remote => 1, domroles => 1, enroll => 1},
1.561 raeburn 225: coursesessions => {institutiononly => 1},
1.583 ! raeburn 226: crsfilefrompriv => {remote => 1, enroll => 1},
1.525 raeburn 227: currentauth => {remote => 1, domroles => 1, enroll => 1},
228: currentdump => {remote => 1, enroll => 1},
229: currentversion => {remote=> 1, content => 1},
230: dcmaildump => {remote => 1, domroles => 1},
231: dcmailput => {remote => 1, domroles => 1},
232: del => {remote => 1, domroles => 1, enroll => 1, content => 1},
1.551 raeburn 233: delbalcookie => {institutiononly => 1},
1.560 raeburn 234: delusersession => {institutiononly => 1},
1.525 raeburn 235: deldom => {remote => 1, domroles => 1}, # not currently used
236: devalidatecache => {institutiononly => 1},
237: domroleput => {remote => 1, enroll => 1},
238: domrolesdump => {remote => 1, catalog => 1},
239: du => {remote => 1, enroll => 1},
240: du2 => {remote => 1, enroll => 1},
241: dump => {remote => 1, enroll => 1, domroles => 1},
242: edit => {institutiononly => 1}, #not used currently
1.568 raeburn 243: edump => {remote => 1, enroll => 1, domroles => 1},
1.525 raeburn 244: eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
1.536 raeburn 245: egetdom => {remote => 1, domroles => 1, enroll => 1, },
1.553 raeburn 246: ekey => {anywhere => 1},
1.525 raeburn 247: exit => {anywhere => 1},
248: fetchuserfile => {remote => 1, enroll => 1},
249: get => {remote => 1, domroles => 1, enroll => 1},
250: getdom => {anywhere => 1},
251: home => {anywhere => 1},
252: iddel => {remote => 1, enroll => 1},
253: idget => {remote => 1, enroll => 1},
254: idput => {remote => 1, domroles => 1, enroll => 1},
255: inc => {remote => 1, enroll => 1},
256: init => {anywhere => 1},
257: inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
258: instemailrules => {remote => 1, domroles => 1},
259: instidrulecheck => {remote => 1, domroles => 1,},
260: instidrules => {remote => 1, domroles => 1,},
261: instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
262: instselfcreatecheck => {institutiononly => 1},
1.575 raeburn 263: instunamemapcheck => {remote => 1,},
1.525 raeburn 264: instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
265: keys => {remote => 1,},
266: load => {anywhere => 1},
267: log => {anywhere => 1},
268: ls => {remote => 1, enroll => 1, content => 1,},
269: ls2 => {remote => 1, enroll => 1, content => 1,},
270: ls3 => {remote => 1, enroll => 1, content => 1,},
1.572 raeburn 271: lti => {institutiononly => 1},
1.525 raeburn 272: makeuser => {remote => 1, enroll => 1, domroles => 1,},
273: mkdiruserfile => {remote => 1, enroll => 1,},
274: newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
275: passwd => {remote => 1},
276: ping => {anywhere => 1},
277: pong => {anywhere => 1},
278: pushfile => {manageronly => 1},
279: put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
280: putdom => {remote => 1, domroles => 1,},
281: putstore => {remote => 1, enroll => 1},
282: queryreply => {anywhere => 1},
283: querysend => {anywhere => 1},
1.535 raeburn 284: querysend_activitylog => {remote => 1},
285: querysend_allusers => {remote => 1, domroles => 1},
286: querysend_courselog => {remote => 1},
287: querysend_fetchenrollment => {remote => 1},
288: querysend_getinstuser => {remote => 1},
289: querysend_getmultinstusers => {remote => 1},
290: querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
291: querysend_institutionalphotos => {remote => 1},
292: querysend_portfolio_metadata => {remote => 1, content => 1},
293: querysend_userlog => {remote => 1, domroles => 1},
294: querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
1.525 raeburn 295: quit => {anywhere => 1},
296: readlonnetglobal => {institutiononly => 1},
297: reinit => {manageronly => 1}, #not used currently
298: removeuserfile => {remote => 1, enroll => 1},
299: renameuserfile => {remote => 1,},
300: restore => {remote => 1, enroll => 1, reqcrs => 1,},
301: rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
302: rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
1.527 raeburn 303: servercerts => {institutiononly => 1},
1.528 raeburn 304: serverdistarch => {anywhere => 1},
1.525 raeburn 305: serverhomeID => {anywhere => 1},
306: serverloncaparev => {anywhere => 1},
307: servertimezone => {remote => 1, enroll => 1},
308: setannounce => {remote => 1, domroles => 1},
309: sethost => {anywhere => 1},
1.577 raeburn 310: signlti => {remote => 1},
1.525 raeburn 311: store => {remote => 1, enroll => 1, reqcrs => 1,},
312: studentphoto => {remote => 1, enroll => 1},
313: sub => {content => 1,},
1.552 raeburn 314: tmpdel => {institutiononly => 1},
315: tmpget => {institutiononly => 1},
316: tmpput => {remote => 1, othcoau => 1},
1.525 raeburn 317: tokenauthuserfile => {anywhere => 1},
1.575 raeburn 318: unamemaprules => {remote => 1,},
1.525 raeburn 319: unsub => {content => 1,},
320: update => {shared => 1},
1.564 raeburn 321: updatebalcookie => {institutiononly => 1},
1.525 raeburn 322: updateclickers => {remote => 1},
323: userhassession => {anywhere => 1},
324: userload => {anywhere => 1},
325: version => {anywhere => 1}, #not used
326: );
327:
328: #
1.207 foxr 329: # Statistics that are maintained and dislayed in the status line.
330: #
1.212 foxr 331: my $Transactions = 0; # Number of attempted transactions.
332: my $Failures = 0; # Number of transcations failed.
1.207 foxr 333:
334: # ResetStatistics:
335: # Resets the statistics counters:
336: #
337: sub ResetStatistics {
338: $Transactions = 0;
339: $Failures = 0;
340: }
341:
1.200 matthew 342: #------------------------------------------------------------------------
343: #
344: # LocalConnection
345: # Completes the formation of a locally authenticated connection.
346: # This function will ensure that the 'remote' client is really the
347: # local host. If not, the connection is closed, and the function fails.
348: # If so, initcmd is parsed for the name of a file containing the
349: # IDEA session key. The fie is opened, read, deleted and the session
350: # key returned to the caller.
351: #
352: # Parameters:
353: # $Socket - Socket open on client.
354: # $initcmd - The full text of the init command.
355: #
356: # Returns:
357: # IDEA session key on success.
358: # undef on failure.
359: #
360: sub LocalConnection {
361: my ($Socket, $initcmd) = @_;
1.373 albertel 362: Debug("Attempting local connection: $initcmd client: $clientip");
1.277 albertel 363: if($clientip ne "127.0.0.1") {
1.200 matthew 364: &logthis('<font color="red"> LocalConnection rejecting non local: '
1.373 albertel 365: ."$clientip ne 127.0.0.1 </font>");
1.200 matthew 366: close $Socket;
367: return undef;
1.224 foxr 368: } else {
1.200 matthew 369: chomp($initcmd); # Get rid of \n in filename.
370: my ($init, $type, $name) = split(/:/, $initcmd);
371: Debug(" Init command: $init $type $name ");
372:
373: # Require that $init = init, and $type = local: Otherwise
374: # the caller is insane:
375:
376: if(($init ne "init") && ($type ne "local")) {
377: &logthis('<font color = "red"> LocalConnection: caller is insane! '
378: ."init = $init, and type = $type </font>");
379: close($Socket);;
380: return undef;
381:
382: }
383: # Now get the key filename:
384:
385: my $IDEAKey = lonlocal::ReadKeyFile($name);
386: return $IDEAKey;
387: }
388: }
389: #------------------------------------------------------------------------------
390: #
391: # SSLConnection
392: # Completes the formation of an ssh authenticated connection. The
393: # socket is promoted to an ssl socket. If this promotion and the associated
394: # certificate exchange are successful, the IDEA key is generated and sent
395: # to the remote peer via the SSL tunnel. The IDEA key is also returned to
396: # the caller after the SSL tunnel is torn down.
397: #
398: # Parameters:
399: # Name Type Purpose
400: # $Socket IO::Socket::INET Plaintext socket.
401: #
402: # Returns:
403: # IDEA key on success.
404: # undef on failure.
405: #
406: sub SSLConnection {
407: my $Socket = shift;
408:
409: Debug("SSLConnection: ");
410: my $KeyFile = lonssl::KeyFile();
411: if(!$KeyFile) {
412: my $err = lonssl::LastError();
413: &logthis("<font color=\"red\"> CRITICAL"
414: ."Can't get key file $err </font>");
415: return undef;
416: }
417: my ($CACertificate,
418: $Certificate) = lonssl::CertificateFile();
419:
420:
421: # If any of the key, certificate or certificate authority
422: # certificate filenames are not defined, this can't work.
423:
424: if((!$Certificate) || (!$CACertificate)) {
425: my $err = lonssl::LastError();
426: &logthis("<font color=\"red\"> CRITICAL"
427: ."Can't get certificates: $err </font>");
428:
429: return undef;
430: }
431: Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
432:
433: # Indicate to our peer that we can procede with
434: # a transition to ssl authentication:
435:
436: print $Socket "ok:ssl\n";
437:
438: Debug("Approving promotion -> ssl");
439: # And do so:
440:
1.545 raeburn 441: my $CRLFile;
442: unless ($crlchecked{$clientname}) {
443: $CRLFile = lonssl::CRLFile();
444: $crlchecked{$clientname} = 1;
445: }
446:
1.200 matthew 447: my $SSLSocket = lonssl::PromoteServerSocket($Socket,
448: $CACertificate,
449: $Certificate,
1.544 raeburn 450: $KeyFile,
1.545 raeburn 451: $clientname,
1.546 raeburn 452: $CRLFile,
453: $clientversion);
1.200 matthew 454: if(! ($SSLSocket) ) { # SSL socket promotion failed.
455: my $err = lonssl::LastError();
456: &logthis("<font color=\"red\"> CRITICAL "
457: ."SSL Socket promotion failed: $err </font>");
458: return undef;
459: }
460: Debug("SSL Promotion successful");
461:
462: #
463: # The only thing we'll use the socket for is to send the IDEA key
464: # to the peer:
465:
466: my $Key = lonlocal::CreateCipherKey();
467: print $SSLSocket "$Key\n";
468:
469: lonssl::Close($SSLSocket);
470:
471: Debug("Key exchange complete: $Key");
472:
473: return $Key;
474: }
475: #
476: # InsecureConnection:
477: # If insecure connections are allowd,
478: # exchange a challenge with the client to 'validate' the
479: # client (not really, but that's the protocol):
480: # We produce a challenge string that's sent to the client.
481: # The client must then echo the challenge verbatim to us.
482: #
483: # Parameter:
484: # Socket - Socket open on the client.
485: # Returns:
486: # 1 - success.
487: # 0 - failure (e.g.mismatch or insecure not allowed).
488: #
489: sub InsecureConnection {
490: my $Socket = shift;
491:
492: # Don't even start if insecure connections are not allowed.
1.532 raeburn 493: # return 0 if Insecure connections not allowed.
494: #
495: if (ref($secureconf{'connfrom'}) eq 'HASH') {
496: if ($clientsamedom) {
497: if ($secureconf{'connfrom'}{'dom'} eq 'req') {
498: return 0;
499: }
500: } elsif ($clientsameinst) {
501: if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
502: return 0;
503: }
504: } else {
505: if ($secureconf{'connfrom'}{'other'} eq 'req') {
506: return 0;
507: }
508: }
509: } elsif (!$perlvar{londAllowInsecure}) {
1.200 matthew 510: return 0;
511: }
512:
513: # Fabricate a challenge string and send it..
514:
515: my $challenge = "$$".time; # pid + time.
516: print $Socket "$challenge\n";
517: &status("Waiting for challenge reply");
518:
519: my $answer = <$Socket>;
520: $answer =~s/\W//g;
521: if($challenge eq $answer) {
522: return 1;
1.224 foxr 523: } else {
1.200 matthew 524: logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
525: &status("No challenge reqply");
526: return 0;
527: }
528:
529:
530: }
1.251 foxr 531: #
532: # Safely execute a command (as long as it's not a shel command and doesn
533: # not require/rely on shell escapes. The function operates by doing a
534: # a pipe based fork and capturing stdout and stderr from the pipe.
535: #
536: # Formal Parameters:
537: # $line - A line of text to be executed as a command.
538: # Returns:
539: # The output from that command. If the output is multiline the caller
540: # must know how to split up the output.
541: #
542: #
543: sub execute_command {
544: my ($line) = @_;
545: my @words = split(/\s/, $line); # Bust the command up into words.
546: my $output = "";
547:
548: my $pid = open(CHILD, "-|");
549:
550: if($pid) { # Parent process
551: Debug("In parent process for execute_command");
552: my @data = <CHILD>; # Read the child's outupt...
553: close CHILD;
554: foreach my $output_line (@data) {
555: Debug("Adding $output_line");
556: $output .= $output_line; # Presumably has a \n on it.
557: }
558:
559: } else { # Child process
560: close (STDERR);
561: open (STDERR, ">&STDOUT");# Combine stderr, and stdout...
562: exec(@words); # won't return.
563: }
564: return $output;
565: }
566:
1.200 matthew 567:
1.140 foxr 568: # GetCertificate: Given a transaction that requires a certificate,
569: # this function will extract the certificate from the transaction
570: # request. Note that at this point, the only concept of a certificate
571: # is the hostname to which we are connected.
572: #
573: # Parameter:
574: # request - The request sent by our client (this parameterization may
575: # need to change when we really use a certificate granting
576: # authority.
577: #
578: sub GetCertificate {
579: my $request = shift;
580:
581: return $clientip;
582: }
1.161 foxr 583:
1.178 foxr 584: #
585: # Return true if client is a manager.
586: #
587: sub isManager {
588: return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
589: }
590: #
591: # Return tru if client can do client functions
592: #
593: sub isClient {
594: return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
595: }
1.161 foxr 596:
597:
1.156 foxr 598: #
599: # ReadManagerTable: Reads in the current manager table. For now this is
600: # done on each manager authentication because:
601: # - These authentications are not frequent
602: # - This allows dynamic changes to the manager table
603: # without the need to signal to the lond.
604: #
605: sub ReadManagerTable {
606:
1.412 foxr 607: &Debug("Reading manager table");
1.156 foxr 608: # Clean out the old table first..
609:
1.166 foxr 610: foreach my $key (keys %managers) {
611: delete $managers{$key};
612: }
613:
614: my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
615: if (!open (MANAGERS, $tablename)) {
1.473 raeburn 616: my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
617: if (&Apache::lonnet::is_LC_dns($hostname)) {
1.472 raeburn 618: &logthis('<font color="red">No manager table. Nobody can manage!!</font>');
619: }
620: return;
1.166 foxr 621: }
622: while(my $host = <MANAGERS>) {
623: chomp($host);
624: if ($host =~ "^#") { # Comment line.
625: next;
626: }
1.368 albertel 627: if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
1.161 foxr 628: # The entry is of the form:
629: # cluname:hostname
630: # cluname - A 'cluster hostname' is needed in order to negotiate
631: # the host key.
632: # hostname- The dns name of the host.
633: #
1.166 foxr 634: my($cluname, $dnsname) = split(/:/, $host);
635:
636: my $ip = gethostbyname($dnsname);
637: if(defined($ip)) { # bad names don't deserve entry.
638: my $hostip = inet_ntoa($ip);
639: $managers{$hostip} = $cluname;
640: logthis('<font color="green"> registering manager '.
641: "$dnsname as $cluname with $hostip </font>\n");
642: }
643: } else {
644: logthis('<font color="green"> existing host'." $host</font>\n");
1.472 raeburn 645: $managers{&Apache::lonnet::get_host_ip($host)} = $host; # Use info from cluster tab if cluster memeber
1.166 foxr 646: }
647: }
1.156 foxr 648: }
1.140 foxr 649:
650: #
651: # ValidManager: Determines if a given certificate represents a valid manager.
652: # in this primitive implementation, the 'certificate' is
653: # just the connecting loncapa client name. This is checked
654: # against a valid client list in the configuration.
655: #
656: #
657: sub ValidManager {
658: my $certificate = shift;
659:
1.163 foxr 660: return isManager;
1.140 foxr 661: }
662: #
1.143 foxr 663: # CopyFile: Called as part of the process of installing a
664: # new configuration file. This function copies an existing
665: # file to a backup file.
666: # Parameters:
667: # oldfile - Name of the file to backup.
668: # newfile - Name of the backup file.
669: # Return:
670: # 0 - Failure (errno has failure reason).
671: # 1 - Success.
672: #
673: sub CopyFile {
1.192 foxr 674:
675: my ($oldfile, $newfile) = @_;
1.143 foxr 676:
1.281 matthew 677: if (! copy($oldfile,$newfile)) {
678: return 0;
1.143 foxr 679: }
1.281 matthew 680: chmod(0660, $newfile);
681: return 1;
1.143 foxr 682: }
1.157 foxr 683: #
684: # Host files are passed out with externally visible host IPs.
685: # If, for example, we are behind a fire-wall or NAT host, our
686: # internally visible IP may be different than the externally
687: # visible IP. Therefore, we always adjust the contents of the
688: # host file so that the entry for ME is the IP that we believe
689: # we have. At present, this is defined as the entry that
690: # DNS has for us. If by some chance we are not able to get a
691: # DNS translation for us, then we assume that the host.tab file
692: # is correct.
693: # BUGBUGBUG - in the future, we really should see if we can
694: # easily query the interface(s) instead.
695: # Parameter(s):
696: # contents - The contents of the host.tab to check.
697: # Returns:
698: # newcontents - The adjusted contents.
699: #
700: #
701: sub AdjustHostContents {
702: my $contents = shift;
703: my $adjusted;
704: my $me = $perlvar{'lonHostID'};
705:
1.354 albertel 706: foreach my $line (split(/\n/,$contents)) {
1.472 raeburn 707: if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
708: ($line =~ /^\s*\^/))) {
1.157 foxr 709: chomp($line);
710: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
711: if ($id eq $me) {
1.354 albertel 712: my $ip = gethostbyname($name);
713: my $ipnew = inet_ntoa($ip);
714: $ip = $ipnew;
1.157 foxr 715: # Reconstruct the host line and append to adjusted:
716:
1.354 albertel 717: my $newline = "$id:$domain:$role:$name:$ip";
718: if($maxcon ne "") { # Not all hosts have loncnew tuning params
719: $newline .= ":$maxcon:$idleto:$mincon";
720: }
721: $adjusted .= $newline."\n";
1.157 foxr 722:
1.354 albertel 723: } else { # Not me, pass unmodified.
724: $adjusted .= $line."\n";
725: }
1.157 foxr 726: } else { # Blank or comment never re-written.
727: $adjusted .= $line."\n"; # Pass blanks and comments as is.
728: }
1.354 albertel 729: }
730: return $adjusted;
1.157 foxr 731: }
1.143 foxr 732: #
733: # InstallFile: Called to install an administrative file:
1.412 foxr 734: # - The file is created int a temp directory called <name>.tmp
735: # - lcinstall file is called to install the file.
736: # since the web app has no direct write access to the table directory
1.143 foxr 737: #
738: # Parameters:
739: # Name of the file
740: # File Contents.
741: # Return:
742: # nonzero - success.
743: # 0 - failure and $! has an errno.
1.412 foxr 744: # Assumptions:
745: # File installtion is a relatively infrequent
1.143 foxr 746: #
747: sub InstallFile {
1.192 foxr 748:
749: my ($Filename, $Contents) = @_;
1.412 foxr 750: # my $TempFile = $Filename.".tmp";
751: my $exedir = $perlvar{'lonDaemons'};
752: my $tmpdir = $exedir.'/tmp/';
753: my $TempFile = $tmpdir."TempTableFile.tmp";
1.143 foxr 754:
755: # Open the file for write:
756:
757: my $fh = IO::File->new("> $TempFile"); # Write to temp.
758: if(!(defined $fh)) {
759: &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
760: return 0;
761: }
762: # write the contents of the file:
763:
764: print $fh ($Contents);
765: $fh->close; # In case we ever have a filesystem w. locking
766:
1.412 foxr 767: chmod(0664, $TempFile); # Everyone can write it.
768:
769: # Use lcinstall file to put the file in the table directory...
770:
771: &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
772: my $pf = IO::File->new("| $exedir/lcinstallfile $TempFile $Filename > $exedir/logs/lcinstallfile.log");
773: close $pf;
774: my $err = $?;
775: &Debug("Status is $err");
776: if ($err != 0) {
777: my $msg = $err;
778: if ($err < @installerrors) {
779: $msg = $installerrors[$err];
780: }
781: &logthis("Install failed for table file $Filename : $msg");
782: return 0;
783: }
784:
785: # Remove the temp file:
1.143 foxr 786:
1.412 foxr 787: unlink($TempFile);
1.143 foxr 788:
789: return 1;
790: }
1.200 matthew 791:
792:
1.169 foxr 793: #
794: # ConfigFileFromSelector: converts a configuration file selector
1.411 foxr 795: # into a configuration file pathname.
1.472 raeburn 796: # Supports the following file selectors:
797: # hosts, domain, dns_hosts, dns_domain
1.411 foxr 798: #
1.169 foxr 799: #
800: # Parameters:
801: # selector - Configuration file selector.
802: # Returns:
803: # Full path to the file or undef if the selector is invalid.
804: #
805: sub ConfigFileFromSelector {
806: my $selector = shift;
807: my $tablefile;
808:
1.549 raeburn 809: if ($selector eq 'loncapaCAcrl') {
810: my $tabledir = $perlvar{'lonCertificateDirectory'};
811: if (-d $tabledir) {
812: $tablefile = $tabledir.'/'.$selector.'.pem';
813: }
814: } else {
815: my $tabledir = $perlvar{'lonTabDir'}.'/';
816: if (($selector eq "hosts") || ($selector eq "domain") ||
817: ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
818: $tablefile = $tabledir.$selector.'.tab';
819: }
1.169 foxr 820: }
821: return $tablefile;
822: }
1.143 foxr 823: #
1.141 foxr 824: # PushFile: Called to do an administrative push of a file.
825: # - Ensure the file being pushed is one we support.
826: # - Backup the old file to <filename.saved>
827: # - Separate the contents of the new file out from the
828: # rest of the request.
829: # - Write the new file.
830: # Parameter:
831: # Request - The entire user request. This consists of a : separated
832: # string pushfile:tablename:contents.
833: # NOTE: The contents may have :'s in it as well making things a bit
834: # more interesting... but not much.
835: # Returns:
836: # String to send to client ("ok" or "refused" if bad file).
837: #
838: sub PushFile {
1.510 raeburn 839: my $request = shift;
1.141 foxr 840: my ($command, $filename, $contents) = split(":", $request, 3);
1.412 foxr 841: &Debug("PushFile");
1.141 foxr 842:
1.549 raeburn 843: # At this point in time, pushes for only the following tables and
844: # CRL file are supported:
1.141 foxr 845: # hosts.tab ($filename eq host).
846: # domain.tab ($filename eq domain).
1.472 raeburn 847: # dns_hosts.tab ($filename eq dns_host).
1.554 raeburn 848: # dns_domain.tab ($filename eq dns_domain).
849: # loncapaCAcrl.pem ($filename eq loncapaCAcrl).
1.141 foxr 850: # Construct the destination filename or reject the request.
851: #
852: # lonManage is supposed to ensure this, however this session could be
853: # part of some elaborate spoof that managed somehow to authenticate.
854: #
855:
1.169 foxr 856:
857: my $tablefile = ConfigFileFromSelector($filename);
858: if(! (defined $tablefile)) {
1.141 foxr 859: return "refused";
860: }
1.412 foxr 861:
1.157 foxr 862: # If the file being pushed is the host file, we adjust the entry for ourself so that the
863: # IP will be our current IP as looked up in dns. Note this is only 99% good as it's possible
864: # to conceive of conditions where we don't have a DNS entry locally. This is possible in a
865: # network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
866: # that possibilty.
867:
868: if($filename eq "host") {
869: $contents = AdjustHostContents($contents);
1.576 raeburn 870: } elsif (($filename eq 'dns_hosts') || ($filename eq 'dns_domain') ||
1.549 raeburn 871: ($filename eq 'loncapaCAcrl')) {
1.510 raeburn 872: if ($contents eq '') {
873: &logthis('<font color="red"> Pushfile: unable to install '
874: .$tablefile." - no data received from push. </font>");
875: return 'error: push had no data';
876: }
877: if (&Apache::lonnet::get_host_ip($clientname)) {
878: my $clienthost = &Apache::lonnet::hostname($clientname);
879: if ($managers{$clientip} eq $clientname) {
880: my $clientprotocol = $Apache::lonnet::protocol{$clientname};
881: $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.549 raeburn 882: my $url;
883: if ($filename eq 'loncapaCAcrl') {
884: $url = '/adm/dns/loncapaCRL';
885: } else {
886: $url = '/adm/'.$filename;
887: $url =~ s{_}{/};
888: }
1.510 raeburn 889: my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
1.523 raeburn 890: my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
1.510 raeburn 891: if ($response->is_error()) {
892: &logthis('<font color="red"> Pushfile: unable to install '
893: .$tablefile." - error attempting to pull data. </font>");
894: return 'error: pull failed';
895: } else {
896: my $result = $response->content;
897: chomp($result);
898: unless ($result eq $contents) {
899: &logthis('<font color="red"> Pushfile: unable to install '
900: .$tablefile." - pushed data and pulled data differ. </font>");
901: my $pushleng = length($contents);
902: my $pullleng = length($result);
903: if ($pushleng != $pullleng) {
904: return "error: $pushleng vs $pullleng bytes";
905: } else {
906: return "error: mismatch push and pull";
907: }
908: }
909: }
910: }
911: }
1.157 foxr 912: }
913:
1.141 foxr 914: # Install the new file:
915:
1.412 foxr 916: &logthis("Installing new $tablefile contents:\n$contents");
1.143 foxr 917: if(!InstallFile($tablefile, $contents)) {
918: &logthis('<font color="red"> Pushfile: unable to install '
1.145 foxr 919: .$tablefile." $! </font>");
1.143 foxr 920: return "error:$!";
1.224 foxr 921: } else {
1.143 foxr 922: &logthis('<font color="green"> Installed new '.$tablefile
1.473 raeburn 923: ." - transaction by: $clientname ($clientip)</font>");
1.472 raeburn 924: my $adminmail = $perlvar{'lonAdmEMail'};
925: my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
926: if ($admindom ne '') {
927: my %domconfig =
928: &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
929: if (ref($domconfig{'contacts'}) eq 'HASH') {
930: if ($domconfig{'contacts'}{'adminemail'} ne '') {
931: $adminmail = $domconfig{'contacts'}{'adminemail'};
932: }
933: }
934: }
935: if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
936: my $msg = new Mail::Send;
937: $msg->to($adminmail);
938: $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
939: $msg->add('Content-type','text/plain; charset=UTF-8');
940: if (my $fh = $msg->open()) {
941: print $fh 'Update to '.$tablefile.' from Cluster Manager '.
1.473 raeburn 942: "$clientname ($clientip)\n";
1.472 raeburn 943: $fh->close;
944: }
945: }
1.143 foxr 946: }
947:
1.141 foxr 948: # Indicate success:
949:
950: return "ok";
951:
952: }
1.145 foxr 953:
954: #
955: # Called to re-init either lonc or lond.
956: #
957: # Parameters:
958: # request - The full request by the client. This is of the form
959: # reinit:<process>
960: # where <process> is allowed to be either of
961: # lonc or lond
962: #
963: # Returns:
964: # The string to be sent back to the client either:
965: # ok - Everything worked just fine.
966: # error:why - There was a failure and why describes the reason.
967: #
968: #
969: sub ReinitProcess {
970: my $request = shift;
971:
1.146 foxr 972:
973: # separate the request (reinit) from the process identifier and
974: # validate it producing the name of the .pid file for the process.
975: #
976: #
977: my ($junk, $process) = split(":", $request);
1.147 foxr 978: my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146 foxr 979: if($process eq 'lonc') {
980: $processpidfile = $processpidfile."lonc.pid";
1.147 foxr 981: if (!open(PIDFILE, "< $processpidfile")) {
982: return "error:Open failed for $processpidfile";
983: }
984: my $loncpid = <PIDFILE>;
985: close(PIDFILE);
986: logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
987: ."</font>");
988: kill("USR2", $loncpid);
1.146 foxr 989: } elsif ($process eq 'lond') {
1.147 foxr 990: logthis('<font color="red"> Reinitializing self (lond) </font>');
991: &UpdateHosts; # Lond is us!!
1.146 foxr 992: } else {
993: &logthis('<font color="yellow" Invalid reinit request for '.$process
994: ."</font>");
995: return "error:Invalid process identifier $process";
996: }
1.145 foxr 997: return 'ok';
998: }
1.168 foxr 999: # Validate a line in a configuration file edit script:
1000: # Validation includes:
1001: # - Ensuring the command is valid.
1002: # - Ensuring the command has sufficient parameters
1003: # Parameters:
1004: # scriptline - A line to validate (\n has been stripped for what it's worth).
1.167 foxr 1005: #
1.168 foxr 1006: # Return:
1007: # 0 - Invalid scriptline.
1008: # 1 - Valid scriptline
1009: # NOTE:
1010: # Only the command syntax is checked, not the executability of the
1011: # command.
1012: #
1013: sub isValidEditCommand {
1014: my $scriptline = shift;
1015:
1016: # Line elements are pipe separated:
1017:
1018: my ($command, $key, $newline) = split(/\|/, $scriptline);
1019: &logthis('<font color="green"> isValideditCommand checking: '.
1020: "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
1021:
1022: if ($command eq "delete") {
1023: #
1024: # key with no newline.
1025: #
1026: if( ($key eq "") || ($newline ne "")) {
1027: return 0; # Must have key but no newline.
1028: } else {
1029: return 1; # Valid syntax.
1030: }
1.169 foxr 1031: } elsif ($command eq "replace") {
1.168 foxr 1032: #
1033: # key and newline:
1034: #
1035: if (($key eq "") || ($newline eq "")) {
1036: return 0;
1037: } else {
1038: return 1;
1039: }
1.169 foxr 1040: } elsif ($command eq "append") {
1041: if (($key ne "") && ($newline eq "")) {
1042: return 1;
1043: } else {
1044: return 0;
1045: }
1.168 foxr 1046: } else {
1047: return 0; # Invalid command.
1048: }
1049: return 0; # Should not get here!!!
1050: }
1.169 foxr 1051: #
1052: # ApplyEdit - Applies an edit command to a line in a configuration
1053: # file. It is the caller's responsiblity to validate the
1054: # edit line.
1055: # Parameters:
1056: # $directive - A single edit directive to apply.
1057: # Edit directives are of the form:
1058: # append|newline - Appends a new line to the file.
1059: # replace|key|newline - Replaces the line with key value 'key'
1060: # delete|key - Deletes the line with key value 'key'.
1061: # $editor - A config file editor object that contains the
1062: # file being edited.
1063: #
1064: sub ApplyEdit {
1.192 foxr 1065:
1066: my ($directive, $editor) = @_;
1.169 foxr 1067:
1068: # Break the directive down into its command and its parameters
1069: # (at most two at this point. The meaning of the parameters, if in fact
1070: # they exist depends on the command).
1071:
1072: my ($command, $p1, $p2) = split(/\|/, $directive);
1073:
1074: if($command eq "append") {
1075: $editor->Append($p1); # p1 - key p2 null.
1076: } elsif ($command eq "replace") {
1077: $editor->ReplaceLine($p1, $p2); # p1 - key p2 = newline.
1078: } elsif ($command eq "delete") {
1079: $editor->DeleteLine($p1); # p1 - key p2 null.
1080: } else { # Should not get here!!!
1081: die "Invalid command given to ApplyEdit $command"
1082: }
1083: }
1084: #
1085: # AdjustOurHost:
1086: # Adjusts a host file stored in a configuration file editor object
1087: # for the true IP address of this host. This is necessary for hosts
1088: # that live behind a firewall.
1089: # Those hosts have a publicly distributed IP of the firewall, but
1090: # internally must use their actual IP. We assume that a given
1091: # host only has a single IP interface for now.
1092: # Formal Parameters:
1093: # editor - The configuration file editor to adjust. This
1094: # editor is assumed to contain a hosts.tab file.
1095: # Strategy:
1096: # - Figure out our hostname.
1097: # - Lookup the entry for this host.
1098: # - Modify the line to contain our IP
1099: # - Do a replace for this host.
1100: sub AdjustOurHost {
1101: my $editor = shift;
1102:
1103: # figure out who I am.
1104:
1105: my $myHostName = $perlvar{'lonHostID'}; # LonCAPA hostname.
1106:
1107: # Get my host file entry.
1108:
1109: my $ConfigLine = $editor->Find($myHostName);
1110: if(! (defined $ConfigLine)) {
1111: die "AdjustOurHost - no entry for me in hosts file $myHostName";
1112: }
1113: # figure out my IP:
1114: # Use the config line to get my hostname.
1115: # Use gethostbyname to translate that into an IP address.
1116: #
1.338 albertel 1117: my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1.169 foxr 1118: #
1119: # Reassemble the config line from the elements in the list.
1120: # Note that if the loncnew items were not present before, they will
1121: # be now even if they would be empty
1122: #
1123: my $newConfigLine = $id;
1.338 albertel 1124: foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1.169 foxr 1125: $newConfigLine .= ":".$item;
1126: }
1127: # Replace the line:
1128:
1129: $editor->ReplaceLine($id, $newConfigLine);
1130:
1131: }
1132: #
1133: # ReplaceConfigFile:
1134: # Replaces a configuration file with the contents of a
1135: # configuration file editor object.
1136: # This is done by:
1137: # - Copying the target file to <filename>.old
1138: # - Writing the new file to <filename>.tmp
1139: # - Moving <filename.tmp> -> <filename>
1140: # This laborious process ensures that the system is never without
1141: # a configuration file that's at least valid (even if the contents
1142: # may be dated).
1143: # Parameters:
1144: # filename - Name of the file to modify... this is a full path.
1145: # editor - Editor containing the file.
1146: #
1147: sub ReplaceConfigFile {
1.192 foxr 1148:
1149: my ($filename, $editor) = @_;
1.168 foxr 1150:
1.169 foxr 1151: CopyFile ($filename, $filename.".old");
1152:
1153: my $contents = $editor->Get(); # Get the contents of the file.
1154:
1155: InstallFile($filename, $contents);
1156: }
1.168 foxr 1157: #
1158: #
1159: # Called to edit a configuration table file
1.167 foxr 1160: # Parameters:
1161: # request - The entire command/request sent by lonc or lonManage
1162: # Return:
1163: # The reply to send to the client.
1.168 foxr 1164: #
1.167 foxr 1165: sub EditFile {
1166: my $request = shift;
1167:
1168: # Split the command into it's pieces: edit:filetype:script
1169:
1.339 albertel 1170: my ($cmd, $filetype, $script) = split(/:/, $request,3); # : in script
1.167 foxr 1171:
1172: # Check the pre-coditions for success:
1173:
1.339 albertel 1174: if($cmd != "edit") { # Something is amiss afoot alack.
1.167 foxr 1175: return "error:edit request detected, but request != 'edit'\n";
1176: }
1177: if( ($filetype ne "hosts") &&
1178: ($filetype ne "domain")) {
1179: return "error:edit requested with invalid file specifier: $filetype \n";
1180: }
1181:
1182: # Split the edit script and check it's validity.
1.168 foxr 1183:
1184: my @scriptlines = split(/\n/, $script); # one line per element.
1185: my $linecount = scalar(@scriptlines);
1186: for(my $i = 0; $i < $linecount; $i++) {
1187: chomp($scriptlines[$i]);
1188: if(!isValidEditCommand($scriptlines[$i])) {
1189: return "error:edit with bad script line: '$scriptlines[$i]' \n";
1190: }
1191: }
1.145 foxr 1192:
1.167 foxr 1193: # Execute the edit operation.
1.169 foxr 1194: # - Create a config file editor for the appropriate file and
1195: # - execute each command in the script:
1196: #
1197: my $configfile = ConfigFileFromSelector($filetype);
1198: if (!(defined $configfile)) {
1199: return "refused\n";
1200: }
1201: my $editor = ConfigFileEdit->new($configfile);
1.167 foxr 1202:
1.169 foxr 1203: for (my $i = 0; $i < $linecount; $i++) {
1204: ApplyEdit($scriptlines[$i], $editor);
1205: }
1206: # If the file is the host file, ensure that our host is
1207: # adjusted to have our ip:
1208: #
1209: if($filetype eq "host") {
1210: AdjustOurHost($editor);
1211: }
1212: # Finally replace the current file with our file.
1213: #
1214: ReplaceConfigFile($configfile, $editor);
1.167 foxr 1215:
1216: return "ok\n";
1217: }
1.207 foxr 1218:
1.255 foxr 1219: # read_profile
1220: #
1221: # Returns a set of specific entries from a user's profile file.
1222: # this is a utility function that is used by both get_profile_entry and
1223: # get_profile_entry_encrypted.
1224: #
1225: # Parameters:
1226: # udom - Domain in which the user exists.
1227: # uname - User's account name (loncapa account)
1228: # namespace - The profile namespace to open.
1229: # what - A set of & separated queries.
1230: # Returns:
1231: # If all ok: - The string that needs to be shipped back to the user.
1232: # If failure - A string that starts with error: followed by the failure
1233: # reason.. note that this probabyl gets shipped back to the
1234: # user as well.
1235: #
1236: sub read_profile {
1237: my ($udom, $uname, $namespace, $what) = @_;
1238:
1239: my $hashref = &tie_user_hash($udom, $uname, $namespace,
1240: &GDBM_READER());
1241: if ($hashref) {
1242: my @queries=split(/\&/,$what);
1.440 raeburn 1243: if ($namespace eq 'roles') {
1244: @queries = map { &unescape($_); } @queries;
1245: }
1.255 foxr 1246: my $qresult='';
1247:
1248: for (my $i=0;$i<=$#queries;$i++) {
1249: $qresult.="$hashref->{$queries[$i]}&"; # Presumably failure gives empty string.
1250: }
1251: $qresult=~s/\&$//; # Remove trailing & from last lookup.
1.311 albertel 1252: if (&untie_user_hash($hashref)) {
1.255 foxr 1253: return $qresult;
1254: } else {
1255: return "error: ".($!+0)." untie (GDBM) Failed";
1256: }
1257: } else {
1258: if ($!+0 == 2) {
1259: return "error:No such file or GDBM reported bad block error";
1260: } else {
1261: return "error: ".($!+0)." tie (GDBM) Failed";
1262: }
1263: }
1264:
1265: }
1.214 foxr 1266: #--------------------- Request Handlers --------------------------------------------
1267: #
1.215 foxr 1268: # By convention each request handler registers itself prior to the sub
1269: # declaration:
1.214 foxr 1270: #
1271:
1.216 foxr 1272: #++
1273: #
1.214 foxr 1274: # Handles ping requests.
1275: # Parameters:
1276: # $cmd - the actual keyword that invoked us.
1277: # $tail - the tail of the request that invoked us.
1278: # $replyfd- File descriptor connected to the client
1279: # Implicit Inputs:
1280: # $currenthostid - Global variable that carries the name of the host we are
1281: # known as.
1282: # Returns:
1283: # 1 - Ok to continue processing.
1284: # 0 - Program should exit.
1285: # Side effects:
1286: # Reply information is sent to the client.
1287: sub ping_handler {
1288: my ($cmd, $tail, $client) = @_;
1289: Debug("$cmd $tail $client .. $currenthostid:");
1290:
1.387 albertel 1291: Reply( $client,\$currenthostid,"$cmd:$tail");
1.214 foxr 1292:
1293: return 1;
1294: }
1295: ®ister_handler("ping", \&ping_handler, 0, 1, 1); # Ping unencoded, client or manager.
1296:
1.216 foxr 1297: #++
1.215 foxr 1298: #
1299: # Handles pong requests. Pong replies with our current host id, and
1300: # the results of a ping sent to us via our lonc.
1301: #
1302: # Parameters:
1303: # $cmd - the actual keyword that invoked us.
1304: # $tail - the tail of the request that invoked us.
1305: # $replyfd- File descriptor connected to the client
1306: # Implicit Inputs:
1307: # $currenthostid - Global variable that carries the name of the host we are
1308: # connected to.
1309: # Returns:
1310: # 1 - Ok to continue processing.
1311: # 0 - Program should exit.
1312: # Side effects:
1313: # Reply information is sent to the client.
1314: sub pong_handler {
1315: my ($cmd, $tail, $replyfd) = @_;
1316:
1.365 albertel 1317: my $reply=&Apache::lonnet::reply("ping",$clientname);
1.215 foxr 1318: &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail");
1319: return 1;
1320: }
1321: ®ister_handler("pong", \&pong_handler, 0, 1, 1); # Pong unencoded, client or manager
1322:
1.216 foxr 1323: #++
1324: # Called to establish an encrypted session key with the remote client.
1325: # Note that with secure lond, in most cases this function is never
1326: # invoked. Instead, the secure session key is established either
1327: # via a local file that's locked down tight and only lives for a short
1328: # time, or via an ssl tunnel...and is generated from a bunch-o-random
1329: # bits from /dev/urandom, rather than the predictable pattern used by
1330: # by this sub. This sub is only used in the old-style insecure
1331: # key negotiation.
1332: # Parameters:
1333: # $cmd - the actual keyword that invoked us.
1334: # $tail - the tail of the request that invoked us.
1335: # $replyfd- File descriptor connected to the client
1336: # Implicit Inputs:
1337: # $currenthostid - Global variable that carries the name of the host
1338: # known as.
1.448 raeburn 1339: # $clientname - Global variable that carries the name of the host we're connected to.
1.216 foxr 1340: # Returns:
1341: # 1 - Ok to continue processing.
1342: # 0 - Program should exit.
1343: # Implicit Outputs:
1344: # Reply information is sent to the client.
1345: # $cipher is set with a reference to a new IDEA encryption object.
1346: #
1347: sub establish_key_handler {
1348: my ($cmd, $tail, $replyfd) = @_;
1349:
1350: my $buildkey=time.$$.int(rand 100000);
1351: $buildkey=~tr/1-6/A-F/;
1352: $buildkey=int(rand 100000).$buildkey.int(rand 100000);
1353: my $key=$currenthostid.$clientname;
1354: $key=~tr/a-z/A-Z/;
1355: $key=~tr/G-P/0-9/;
1356: $key=~tr/Q-Z/0-9/;
1357: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
1358: $key=substr($key,0,32);
1359: my $cipherkey=pack("H32",$key);
1360: $cipher=new IDEA $cipherkey;
1.387 albertel 1361: &Reply($replyfd, \$buildkey, "$cmd:$tail");
1.216 foxr 1362:
1363: return 1;
1364:
1365: }
1366: ®ister_handler("ekey", \&establish_key_handler, 0, 1,1);
1367:
1.217 foxr 1368: # Handler for the load command. Returns the current system load average
1369: # to the requestor.
1370: #
1371: # Parameters:
1372: # $cmd - the actual keyword that invoked us.
1373: # $tail - the tail of the request that invoked us.
1374: # $replyfd- File descriptor connected to the client
1375: # Implicit Inputs:
1376: # $currenthostid - Global variable that carries the name of the host
1377: # known as.
1.448 raeburn 1378: # $clientname - Global variable that carries the name of the host we're connected to.
1.217 foxr 1379: # Returns:
1380: # 1 - Ok to continue processing.
1381: # 0 - Program should exit.
1382: # Side effects:
1383: # Reply information is sent to the client.
1384: sub load_handler {
1385: my ($cmd, $tail, $replyfd) = @_;
1386:
1.463 foxr 1387:
1388:
1.217 foxr 1389: # Get the load average from /proc/loadavg and calculate it as a percentage of
1390: # the allowed load limit as set by the perl global variable lonLoadLim
1391:
1392: my $loadavg;
1393: my $loadfile=IO::File->new('/proc/loadavg');
1394:
1395: $loadavg=<$loadfile>;
1396: $loadavg =~ s/\s.*//g; # Extract the first field only.
1397:
1398: my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
1399:
1.387 albertel 1400: &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1.217 foxr 1401:
1402: return 1;
1403: }
1.263 albertel 1404: ®ister_handler("load", \&load_handler, 0, 1, 0);
1.217 foxr 1405:
1406: #
1407: # Process the userload request. This sub returns to the client the current
1408: # user load average. It can be invoked either by clients or managers.
1409: #
1410: # Parameters:
1411: # $cmd - the actual keyword that invoked us.
1412: # $tail - the tail of the request that invoked us.
1413: # $replyfd- File descriptor connected to the client
1414: # Implicit Inputs:
1415: # $currenthostid - Global variable that carries the name of the host
1416: # known as.
1.448 raeburn 1417: # $clientname - Global variable that carries the name of the host we're connected to.
1.217 foxr 1418: # Returns:
1419: # 1 - Ok to continue processing.
1420: # 0 - Program should exit
1421: # Implicit inputs:
1422: # whatever the userload() function requires.
1423: # Implicit outputs:
1424: # the reply is written to the client.
1425: #
1426: sub user_load_handler {
1427: my ($cmd, $tail, $replyfd) = @_;
1428:
1.365 albertel 1429: my $userloadpercent=&Apache::lonnet::userload();
1.387 albertel 1430: &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1.217 foxr 1431:
1432: return 1;
1433: }
1.263 albertel 1434: ®ister_handler("userload", \&user_load_handler, 0, 1, 0);
1.217 foxr 1435:
1.218 foxr 1436: # Process a request for the authorization type of a user:
1437: # (userauth).
1438: #
1439: # Parameters:
1440: # $cmd - the actual keyword that invoked us.
1441: # $tail - the tail of the request that invoked us.
1442: # $replyfd- File descriptor connected to the client
1443: # Returns:
1444: # 1 - Ok to continue processing.
1445: # 0 - Program should exit
1446: # Implicit outputs:
1447: # The user authorization type is written to the client.
1448: #
1449: sub user_authorization_type {
1450: my ($cmd, $tail, $replyfd) = @_;
1451:
1452: my $userinput = "$cmd:$tail";
1453:
1454: # Pull the domain and username out of the command tail.
1.222 foxr 1455: # and call get_auth_type to determine the authentication type.
1.218 foxr 1456:
1457: my ($udom,$uname)=split(/:/,$tail);
1.222 foxr 1458: my $result = &get_auth_type($udom, $uname);
1.218 foxr 1459: if($result eq "nouser") {
1460: &Failure( $replyfd, "unknown_user\n", $userinput);
1461: } else {
1462: #
1.222 foxr 1463: # We only want to pass the second field from get_auth_type
1.218 foxr 1464: # for ^krb.. otherwise we'll be handing out the encrypted
1465: # password for internals e.g.
1466: #
1467: my ($type,$otherinfo) = split(/:/,$result);
1468: if($type =~ /^krb/) {
1469: $type = $result;
1.269 raeburn 1470: } else {
1471: $type .= ':';
1472: }
1.387 albertel 1473: &Reply( $replyfd, \$type, $userinput);
1.218 foxr 1474: }
1475:
1476: return 1;
1477: }
1478: ®ister_handler("currentauth", \&user_authorization_type, 1, 1, 0);
1479:
1480: # Process a request by a manager to push a hosts or domain table
1481: # to us. We pick apart the command and pass it on to the subs
1482: # that already exist to do this.
1483: #
1484: # Parameters:
1485: # $cmd - the actual keyword that invoked us.
1486: # $tail - the tail of the request that invoked us.
1487: # $client - File descriptor connected to the client
1488: # Returns:
1489: # 1 - Ok to continue processing.
1490: # 0 - Program should exit
1491: # Implicit Output:
1492: # a reply is written to the client.
1493: sub push_file_handler {
1494: my ($cmd, $tail, $client) = @_;
1.412 foxr 1495: &Debug("In push file handler");
1.218 foxr 1496: my $userinput = "$cmd:$tail";
1497:
1498: # At this time we only know that the IP of our partner is a valid manager
1499: # the code below is a hook to do further authentication (e.g. to resolve
1500: # spoofing).
1501:
1502: my $cert = &GetCertificate($userinput);
1.412 foxr 1503: if(&ValidManager($cert)) {
1504: &Debug("Valid manager: $client");
1.218 foxr 1505:
1506: # Now presumably we have the bona fides of both the peer host and the
1507: # process making the request.
1508:
1509: my $reply = &PushFile($userinput);
1.387 albertel 1510: &Reply($client, \$reply, $userinput);
1.218 foxr 1511:
1512: } else {
1.412 foxr 1513: &logthis("push_file_handler $client is not valid");
1.218 foxr 1514: &Failure( $client, "refused\n", $userinput);
1515: }
1.219 foxr 1516: return 1;
1.218 foxr 1517: }
1518: ®ister_handler("pushfile", \&push_file_handler, 1, 0, 1);
1519:
1.399 raeburn 1520: # The du_handler routine should be considered obsolete and is retained
1521: # for communication with legacy servers. Please see the du2_handler.
1.243 banghart 1522: #
1.399 raeburn 1523: # du - list the disk usage of a directory recursively.
1.243 banghart 1524: #
1525: # note: stolen code from the ls file handler
1526: # under construction by Rick Banghart
1527: # .
1528: # Parameters:
1529: # $cmd - The command that dispatched us (du).
1530: # $ududir - The directory path to list... I'm not sure what this
1531: # is relative as things like ls:. return e.g.
1532: # no_such_dir.
1533: # $client - Socket open on the client.
1534: # Returns:
1535: # 1 - indicating that the daemon should not disconnect.
1536: # Side Effects:
1537: # The reply is written to $client.
1538: #
1539: sub du_handler {
1540: my ($cmd, $ududir, $client) = @_;
1.339 albertel 1541: ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1.251 foxr 1542: my $userinput = "$cmd:$ududir";
1543:
1.245 albertel 1544: if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
1545: &Failure($client,"refused\n","$cmd:$ududir");
1546: return 1;
1547: }
1.249 foxr 1548: # Since $ududir could have some nasties in it,
1549: # we will require that ududir is a valid
1550: # directory. Just in case someone tries to
1551: # slip us a line like .;(cd /home/httpd rm -rf*)
1552: # etc.
1553: #
1554: if (-d $ududir) {
1.292 albertel 1555: my $total_size=0;
1556: my $code=sub {
1557: if ($_=~/\.\d+\./) { return;}
1558: if ($_=~/\.meta$/) { return;}
1.362 albertel 1559: if (-d $_) { return;}
1.292 albertel 1560: $total_size+=(stat($_))[7];
1561: };
1.295 raeburn 1562: chdir($ududir);
1.292 albertel 1563: find($code,$ududir);
1564: $total_size=int($total_size/1024);
1.387 albertel 1565: &Reply($client,\$total_size,"$cmd:$ududir");
1.249 foxr 1566: } else {
1.251 foxr 1567: &Failure($client, "bad_directory:$ududir\n","$cmd:$ududir");
1.249 foxr 1568: }
1.243 banghart 1569: return 1;
1570: }
1571: ®ister_handler("du", \&du_handler, 0, 1, 0);
1.218 foxr 1572:
1.399 raeburn 1573: # Please also see the du_handler, which is obsoleted by du2.
1574: # du2_handler differs from du_handler in that required path to directory
1575: # provided by &propath() is prepended in the handler instead of on the
1576: # client side.
1.239 foxr 1577: #
1.399 raeburn 1578: # du2 - list the disk usage of a directory recursively.
1579: #
1580: # Parameters:
1581: # $cmd - The command that dispatched us (du).
1582: # $tail - The tail of the request that invoked us.
1583: # $tail is a : separated list of the following:
1584: # - $ududir - directory path to list (before prepending)
1585: # - $getpropath = 1 if &propath() should prepend
1586: # - $uname - username to use for &propath or user dir
1587: # - $udom - domain to use for &propath or user dir
1588: # All are escaped.
1589: # $client - Socket open on the client.
1590: # Returns:
1591: # 1 - indicating that the daemon should not disconnect.
1592: # Side Effects:
1593: # The reply is written to $client.
1594: #
1595:
1596: sub du2_handler {
1597: my ($cmd, $tail, $client) = @_;
1598: my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
1599: my $userinput = "$cmd:$tail";
1600: if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
1601: &Failure($client,"refused\n","$cmd:$tail");
1602: return 1;
1603: }
1604: if ($getpropath) {
1605: if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
1606: $ududir = &propath($udom,$uname).'/'.$ududir;
1607: } else {
1608: &Failure($client,"refused\n","$cmd:$tail");
1609: return 1;
1610: }
1611: }
1612: # Since $ududir could have some nasties in it,
1613: # we will require that ududir is a valid
1614: # directory. Just in case someone tries to
1615: # slip us a line like .;(cd /home/httpd rm -rf*)
1616: # etc.
1617: #
1618: if (-d $ududir) {
1619: my $total_size=0;
1620: my $code=sub {
1621: if ($_=~/\.\d+\./) { return;}
1622: if ($_=~/\.meta$/) { return;}
1623: if (-d $_) { return;}
1624: $total_size+=(stat($_))[7];
1625: };
1626: chdir($ududir);
1627: find($code,$ududir);
1628: $total_size=int($total_size/1024);
1629: &Reply($client,\$total_size,"$cmd:$ududir");
1630: } else {
1631: &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
1632: }
1633: return 1;
1634: }
1635: ®ister_handler("du2", \&du2_handler, 0, 1, 0);
1636:
1637: #
1638: # The ls_handler routine should be considered obsolete and is retained
1639: # for communication with legacy servers. Please see the ls3_handler.
1.280 matthew 1640: #
1.239 foxr 1641: # ls - list the contents of a directory. For each file in the
1642: # selected directory the filename followed by the full output of
1643: # the stat function is returned. The returned info for each
1644: # file are separated by ':'. The stat fields are separated by &'s.
1.529 raeburn 1645: #
1646: # If the requested path contains /../ or is:
1647: #
1648: # 1. for a directory, and the path does not begin with one of:
1.530 raeburn 1649: # (a) /home/httpd/html/res/<domain>
1.539 raeburn 1650: # (b) /home/httpd/html/userfiles/
1.529 raeburn 1651: # (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1652: # or is:
1653: #
1.538 raeburn 1654: # 2. for a file, and the path (after prepending) does not begin with one of:
1.539 raeburn 1655: # (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
1656: # (b) /home/httpd/html/res/<domain>/<username>/
1657: # (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529 raeburn 1658: #
1659: # the response will be "refused".
1660: #
1.239 foxr 1661: # Parameters:
1662: # $cmd - The command that dispatched us (ls).
1663: # $ulsdir - The directory path to list... I'm not sure what this
1664: # is relative as things like ls:. return e.g.
1665: # no_such_dir.
1666: # $client - Socket open on the client.
1667: # Returns:
1668: # 1 - indicating that the daemon should not disconnect.
1669: # Side Effects:
1670: # The reply is written to $client.
1671: #
1672: sub ls_handler {
1.280 matthew 1673: # obsoleted by ls2_handler
1.239 foxr 1674: my ($cmd, $ulsdir, $client) = @_;
1675:
1676: my $userinput = "$cmd:$ulsdir";
1677:
1678: my $obs;
1679: my $rights;
1680: my $ulsout='';
1681: my $ulsfn;
1.529 raeburn 1682: if ($ulsdir =~m{/\.\./}) {
1683: &Failure($client,"refused\n",$userinput);
1684: return 1;
1685: }
1.239 foxr 1686: if (-e $ulsdir) {
1687: if(-d $ulsdir) {
1.539 raeburn 1688: unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
1689: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529 raeburn 1690: &Failure($client,"refused\n",$userinput);
1691: return 1;
1692: }
1.239 foxr 1693: if (opendir(LSDIR,$ulsdir)) {
1694: while ($ulsfn=readdir(LSDIR)) {
1.291 albertel 1695: undef($obs);
1696: undef($rights);
1.239 foxr 1697: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1698: #We do some obsolete checking here
1699: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1700: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1701: my @obsolete=<FILE>;
1702: foreach my $obsolete (@obsolete) {
1.301 www 1703: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1.239 foxr 1704: if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
1705: }
1706: }
1707: $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
1708: if($obs eq '1') { $ulsout.="&1"; }
1709: else { $ulsout.="&0"; }
1710: if($rights eq '1') { $ulsout.="&1:"; }
1711: else { $ulsout.="&0:"; }
1712: }
1713: closedir(LSDIR);
1714: }
1715: } else {
1.539 raeburn 1716: unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
1717: ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529 raeburn 1718: &Failure($client,"refused\n",$userinput);
1719: return 1;
1720: }
1.239 foxr 1721: my @ulsstats=stat($ulsdir);
1722: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1723: }
1724: } else {
1725: $ulsout='no_such_dir';
1726: }
1727: if ($ulsout eq '') { $ulsout='empty'; }
1.387 albertel 1728: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.239 foxr 1729:
1730: return 1;
1731:
1732: }
1733: ®ister_handler("ls", \&ls_handler, 0, 1, 0);
1734:
1.399 raeburn 1735: # The ls2_handler routine should be considered obsolete and is retained
1736: # for communication with legacy servers. Please see the ls3_handler.
1737: # Please also see the ls_handler, which was itself obsoleted by ls2.
1.280 matthew 1738: # ls2_handler differs from ls_handler in that it escapes its return
1739: # values before concatenating them together with ':'s.
1740: #
1741: # ls2 - list the contents of a directory. For each file in the
1742: # selected directory the filename followed by the full output of
1743: # the stat function is returned. The returned info for each
1744: # file are separated by ':'. The stat fields are separated by &'s.
1.529 raeburn 1745: #
1746: # If the requested path contains /../ or is:
1747: #
1748: # 1. for a directory, and the path does not begin with one of:
1.530 raeburn 1749: # (a) /home/httpd/html/res/<domain>
1.539 raeburn 1750: # (b) /home/httpd/html/userfiles/
1.529 raeburn 1751: # (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1752: # or is:
1753: #
1.538 raeburn 1754: # 2. for a file, and the path (after prepending) does not begin with one of:
1.539 raeburn 1755: # (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
1756: # (b) /home/httpd/html/res/<domain>/<username>/
1757: # (c) /home/httpd/html/userfiles/<domain>/<username>/
1.529 raeburn 1758: #
1759: # the response will be "refused".
1760: #
1.280 matthew 1761: # Parameters:
1762: # $cmd - The command that dispatched us (ls).
1763: # $ulsdir - The directory path to list... I'm not sure what this
1764: # is relative as things like ls:. return e.g.
1765: # no_such_dir.
1766: # $client - Socket open on the client.
1767: # Returns:
1768: # 1 - indicating that the daemon should not disconnect.
1769: # Side Effects:
1770: # The reply is written to $client.
1771: #
1772: sub ls2_handler {
1773: my ($cmd, $ulsdir, $client) = @_;
1774:
1775: my $userinput = "$cmd:$ulsdir";
1776:
1777: my $obs;
1778: my $rights;
1779: my $ulsout='';
1780: my $ulsfn;
1.529 raeburn 1781: if ($ulsdir =~m{/\.\./}) {
1782: &Failure($client,"refused\n",$userinput);
1783: return 1;
1784: }
1.280 matthew 1785: if (-e $ulsdir) {
1786: if(-d $ulsdir) {
1.539 raeburn 1787: unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
1788: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1.529 raeburn 1789: &Failure($client,"refused\n","$userinput");
1790: return 1;
1791: }
1.280 matthew 1792: if (opendir(LSDIR,$ulsdir)) {
1793: while ($ulsfn=readdir(LSDIR)) {
1.291 albertel 1794: undef($obs);
1795: undef($rights);
1.280 matthew 1796: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1797: #We do some obsolete checking here
1798: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1799: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1800: my @obsolete=<FILE>;
1801: foreach my $obsolete (@obsolete) {
1.301 www 1802: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1.280 matthew 1803: if($obsolete =~ m|(<copyright>)(default)|) {
1804: $rights = 1;
1805: }
1806: }
1807: }
1808: my $tmp = $ulsfn.'&'.join('&',@ulsstats);
1809: if ($obs eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1810: if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1811: $ulsout.= &escape($tmp).':';
1812: }
1813: closedir(LSDIR);
1814: }
1815: } else {
1.539 raeburn 1816: unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
1817: ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1.529 raeburn 1818: &Failure($client,"refused\n",$userinput);
1819: return 1;
1820: }
1.280 matthew 1821: my @ulsstats=stat($ulsdir);
1822: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1823: }
1824: } else {
1825: $ulsout='no_such_dir';
1826: }
1827: if ($ulsout eq '') { $ulsout='empty'; }
1.387 albertel 1828: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1.280 matthew 1829: return 1;
1830: }
1831: ®ister_handler("ls2", \&ls2_handler, 0, 1, 0);
1.399 raeburn 1832: #
1833: # ls3 - list the contents of a directory. For each file in the
1834: # selected directory the filename followed by the full output of
1835: # the stat function is returned. The returned info for each
1836: # file are separated by ':'. The stat fields are separated by &'s.
1.529 raeburn 1837: #
1838: # If the requested path (after prepending) contains /../ or is:
1839: #
1840: # 1. for a directory, and the path does not begin with one of:
1.530 raeburn 1841: # (a) /home/httpd/html/res/<domain>
1.539 raeburn 1842: # (b) /home/httpd/html/userfiles/
1.529 raeburn 1843: # (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1.539 raeburn 1844: # (d) /home/httpd/html/priv/<domain> and client is the homeserver
1.529 raeburn 1845: #
1.530 raeburn 1846: # or is:
1.529 raeburn 1847: #
1.538 raeburn 1848: # 2. for a file, and the path (after prepending) does not begin with one of:
1.539 raeburn 1849: # (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
1850: # (b) /home/httpd/html/res/<domain>/<username>/
1851: # (c) /home/httpd/html/userfiles/<domain>/<username>/
1852: # (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1.529 raeburn 1853: #
1854: # the response will be "refused".
1855: #
1.399 raeburn 1856: # Parameters:
1857: # $cmd - The command that dispatched us (ls).
1858: # $tail - The tail of the request that invoked us.
1859: # $tail is a : separated list of the following:
1860: # - $ulsdir - directory path to list (before prepending)
1861: # - $getpropath = 1 if &propath() should prepend
1862: # - $getuserdir = 1 if path to user dir in lonUsers should
1863: # prepend
1864: # - $alternate_root - path to prepend
1865: # - $uname - username to use for &propath or user dir
1866: # - $udom - domain to use for &propath or user dir
1867: # All of these except $getpropath and &getuserdir are escaped.
1868: # no_such_dir.
1869: # $client - Socket open on the client.
1870: # Returns:
1871: # 1 - indicating that the daemon should not disconnect.
1872: # Side Effects:
1873: # The reply is written to $client.
1874: #
1875:
1876: sub ls3_handler {
1877: my ($cmd, $tail, $client) = @_;
1878: my $userinput = "$cmd:$tail";
1879: my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
1880: split(/:/,$tail);
1881: if (defined($ulsdir)) {
1882: $ulsdir = &unescape($ulsdir);
1883: }
1884: if (defined($alternate_root)) {
1885: $alternate_root = &unescape($alternate_root);
1886: }
1887: if (defined($uname)) {
1888: $uname = &unescape($uname);
1889: }
1890: if (defined($udom)) {
1891: $udom = &unescape($udom);
1892: }
1893:
1894: my $dir_root = $perlvar{'lonDocRoot'};
1.529 raeburn 1895: if (($getpropath) || ($getuserdir)) {
1.399 raeburn 1896: if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
1897: $dir_root = &propath($udom,$uname);
1898: $dir_root =~ s/\/$//;
1899: } else {
1.529 raeburn 1900: &Failure($client,"refused\n",$userinput);
1.399 raeburn 1901: return 1;
1902: }
1.400 raeburn 1903: } elsif ($alternate_root ne '') {
1.399 raeburn 1904: $dir_root = $alternate_root;
1905: }
1.408 raeburn 1906: if (($dir_root ne '') && ($dir_root ne '/')) {
1.400 raeburn 1907: if ($ulsdir =~ /^\//) {
1908: $ulsdir = $dir_root.$ulsdir;
1909: } else {
1910: $ulsdir = $dir_root.'/'.$ulsdir;
1911: }
1.399 raeburn 1912: }
1.529 raeburn 1913: if ($ulsdir =~m{/\.\./}) {
1914: &Failure($client,"refused\n",$userinput);
1915: return 1;
1916: }
1917: my $islocal;
1918: my @machine_ids = &Apache::lonnet::current_machine_ids();
1919: if (grep(/^\Q$clientname\E$/,@machine_ids)) {
1920: $islocal = 1;
1921: }
1.399 raeburn 1922: my $obs;
1923: my $rights;
1924: my $ulsout='';
1925: my $ulsfn;
1.547 raeburn 1926:
1.583 ! raeburn 1927: my ($crscheck,$toplevel,$currdom,$currnum,$skip,$privdir_for_course);
1.547 raeburn 1928: unless ($islocal) {
1929: my ($major,$minor) = split(/\./,$clientversion);
1930: if (($major < 2) || ($major == 2 && $minor < 12)) {
1931: $crscheck = 1;
1932: }
1.583 ! raeburn 1933: if ($ulsdir =~ m{^/home/httpd/html/priv/($LONCAPA::match_domain)/($LONCAPA::match_courseid)}) {
! 1934: my ($currdom,$currnum) = ($1,$2);
! 1935: if (&LONCAPA::Lond::is_course($currdom,$currnum)) {
! 1936: $privdir_for_course = 1;
! 1937: }
! 1938: }
1.547 raeburn 1939: }
1.399 raeburn 1940: if (-e $ulsdir) {
1941: if(-d $ulsdir) {
1.529 raeburn 1942: unless (($getpropath) || ($getuserdir) ||
1.539 raeburn 1943: ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
1944: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
1.583 ! raeburn 1945: (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal)) ||
! 1946: ($privdir_for_course)) {
1.529 raeburn 1947: &Failure($client,"refused\n",$userinput);
1948: return 1;
1949: }
1.547 raeburn 1950: if (($crscheck) &&
1951: ($ulsdir =~ m{^/home/httpd/html/res/($LONCAPA::match_domain)(/?$|/$LONCAPA::match_courseid)})) {
1952: ($currdom,my $posscnum) = ($1,$2);
1953: if (($posscnum eq '') || ($posscnum eq '/')) {
1954: $toplevel = 1;
1955: } else {
1956: $posscnum =~ s{^/+}{};
1957: if (&LONCAPA::Lond::is_course($currdom,$posscnum)) {
1958: $skip = 1;
1959: }
1960: }
1961: }
1962: if ((!$skip) && (opendir(LSDIR,$ulsdir))) {
1.399 raeburn 1963: while ($ulsfn=readdir(LSDIR)) {
1.547 raeburn 1964: if (($crscheck) && ($toplevel) && ($currdom ne '') &&
1965: ($ulsfn =~ /^$LONCAPA::match_courseid$/) && (-d "$ulsdir/$ulsfn")) {
1966: if (&LONCAPA::Lond::is_course($currdom,$ulsfn)) {
1967: next;
1968: }
1969: }
1.399 raeburn 1970: undef($obs);
1971: undef($rights);
1972: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1973: #We do some obsolete checking here
1974: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1975: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1976: my @obsolete=<FILE>;
1977: foreach my $obsolete (@obsolete) {
1978: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1979: if($obsolete =~ m|(<copyright>)(default)|) {
1980: $rights = 1;
1981: }
1982: }
1983: }
1984: my $tmp = $ulsfn.'&'.join('&',@ulsstats);
1985: if ($obs eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1986: if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1987: $ulsout.= &escape($tmp).':';
1988: }
1989: closedir(LSDIR);
1990: }
1991: } else {
1.529 raeburn 1992: unless (($getpropath) || ($getuserdir) ||
1.539 raeburn 1993: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
1994: ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
1995: (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1.529 raeburn 1996: &Failure($client,"refused\n",$userinput);
1997: return 1;
1998: }
1.399 raeburn 1999: my @ulsstats=stat($ulsdir);
2000: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
2001: }
2002: } else {
2003: $ulsout='no_such_dir';
1.400 raeburn 2004: }
2005: if ($ulsout eq '') { $ulsout='empty'; }
2006: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
2007: return 1;
1.399 raeburn 2008: }
2009: ®ister_handler("ls3", \&ls3_handler, 0, 1, 0);
1.280 matthew 2010:
1.477 raeburn 2011: sub read_lonnet_global {
2012: my ($cmd,$tail,$client) = @_;
2013: my $userinput = "$cmd:$tail";
2014: my $requested = &Apache::lonnet::thaw_unescape($tail);
2015: my $result;
1.480 raeburn 2016: my %packagevars = (
2017: spareid => \%Apache::lonnet::spareid,
2018: perlvar => \%Apache::lonnet::perlvar,
2019: );
2020: my %limit_to = (
2021: perlvar => {
1.531 raeburn 2022: lonOtherAuthen => 1,
2023: lonBalancer => 1,
2024: lonVersion => 1,
2025: lonAdmEMail => 1,
2026: lonSupportEMail => 1,
2027: lonSysEMail => 1,
2028: lonHostID => 1,
2029: lonRole => 1,
2030: lonDefDomain => 1,
2031: lonLoadLim => 1,
2032: lonUserLoadLim => 1,
1.480 raeburn 2033: }
2034: );
1.477 raeburn 2035: if (ref($requested) eq 'HASH') {
2036: foreach my $what (keys(%{$requested})) {
2037: my $response;
1.480 raeburn 2038: my $items = {};
2039: if (exists($packagevars{$what})) {
2040: if (ref($limit_to{$what}) eq 'HASH') {
2041: foreach my $varname (keys(%{$packagevars{$what}})) {
2042: if ($limit_to{$what}{$varname}) {
2043: $items->{$varname} = $packagevars{$what}{$varname};
2044: }
2045: }
2046: } else {
2047: $items = $packagevars{$what};
1.477 raeburn 2048: }
1.480 raeburn 2049: if ($what eq 'perlvar') {
2050: if (!exists($packagevars{$what}{'lonBalancer'})) {
1.570 raeburn 2051: if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
1.480 raeburn 2052: my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
2053: if (ref($othervarref) eq 'HASH') {
2054: $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
2055: }
2056: }
2057: }
1.477 raeburn 2058: }
1.480 raeburn 2059: $response = &Apache::lonnet::freeze_escape($items);
1.477 raeburn 2060: }
1.478 raeburn 2061: $result .= &escape($what).'='.$response.'&';
1.477 raeburn 2062: }
2063: }
2064: $result =~ s/\&$//;
2065: &Reply($client,\$result,$userinput);
2066: return 1;
2067: }
2068: ®ister_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
2069:
1.479 raeburn 2070: sub server_devalidatecache_handler {
2071: my ($cmd,$tail,$client) = @_;
2072: my $userinput = "$cmd:$tail";
1.503 raeburn 2073: my $items = &unescape($tail);
2074: my @cached = split(/\&/,$items);
2075: foreach my $key (@cached) {
2076: if ($key =~ /:/) {
2077: my ($name,$id) = map { &unescape($_); } split(/:/,$key);
2078: &Apache::lonnet::devalidate_cache_new($name,$id);
2079: }
2080: }
1.479 raeburn 2081: my $result = 'ok';
2082: &Reply($client,\$result,$userinput);
2083: return 1;
2084: }
1.481 raeburn 2085: ®ister_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
1.479 raeburn 2086:
1.410 raeburn 2087: sub server_timezone_handler {
2088: my ($cmd,$tail,$client) = @_;
2089: my $userinput = "$cmd:$tail";
2090: my $timezone;
2091: my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
2092: my $tzfile = '/etc/timezone'; # Debian/Ubuntu
2093: if (-e $clockfile) {
2094: if (open(my $fh,"<$clockfile")) {
2095: while (<$fh>) {
2096: next if (/^[\#\s]/);
2097: if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
2098: $timezone = $1;
2099: last;
2100: }
2101: }
2102: close($fh);
2103: }
2104: } elsif (-e $tzfile) {
2105: if (open(my $fh,"<$tzfile")) {
2106: $timezone = <$fh>;
2107: close($fh);
2108: chomp($timezone);
2109: if ($timezone =~ m{^Etc/(\w+)$}) {
2110: $timezone = $1;
2111: }
2112: }
2113: }
2114: &Reply($client,\$timezone,$userinput); # This supports debug logging.
2115: return 1;
2116: }
2117: ®ister_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
2118:
1.413 raeburn 2119: sub server_loncaparev_handler {
2120: my ($cmd,$tail,$client) = @_;
2121: my $userinput = "$cmd:$tail";
2122: &Reply($client,\$perlvar{'lonVersion'},$userinput);
2123: return 1;
2124: }
2125: ®ister_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
2126:
1.448 raeburn 2127: sub server_homeID_handler {
2128: my ($cmd,$tail,$client) = @_;
2129: my $userinput = "$cmd:$tail";
2130: &Reply($client,\$perlvar{'lonHostID'},$userinput);
2131: return 1;
2132: }
2133: ®ister_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
2134:
1.471 raeburn 2135: sub server_distarch_handler {
2136: my ($cmd,$tail,$client) = @_;
2137: my $userinput = "$cmd:$tail";
2138: my $reply = &distro_and_arch();
2139: &Reply($client,\$reply,$userinput);
2140: return 1;
2141: }
2142: ®ister_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
2143:
1.523 raeburn 2144: sub server_certs_handler {
2145: my ($cmd,$tail,$client) = @_;
2146: my $userinput = "$cmd:$tail";
1.548 raeburn 2147: my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
2148: my $result = &LONCAPA::Lond::server_certs(\%perlvar,$perlvar{'lonHostID'},$hostname);
1.523 raeburn 2149: &Reply($client,\$result,$userinput);
2150: return;
2151: }
2152: ®ister_handler("servercerts", \&server_certs_handler, 0, 1, 0);
2153:
1.218 foxr 2154: # Process a reinit request. Reinit requests that either
2155: # lonc or lond be reinitialized so that an updated
2156: # host.tab or domain.tab can be processed.
2157: #
2158: # Parameters:
2159: # $cmd - the actual keyword that invoked us.
2160: # $tail - the tail of the request that invoked us.
2161: # $client - File descriptor connected to the client
2162: # Returns:
2163: # 1 - Ok to continue processing.
2164: # 0 - Program should exit
2165: # Implicit output:
2166: # a reply is sent to the client.
2167: #
2168: sub reinit_process_handler {
2169: my ($cmd, $tail, $client) = @_;
2170:
2171: my $userinput = "$cmd:$tail";
2172:
2173: my $cert = &GetCertificate($userinput);
2174: if(&ValidManager($cert)) {
2175: chomp($userinput);
2176: my $reply = &ReinitProcess($userinput);
1.387 albertel 2177: &Reply( $client, \$reply, $userinput);
1.218 foxr 2178: } else {
2179: &Failure( $client, "refused\n", $userinput);
2180: }
2181: return 1;
2182: }
2183: ®ister_handler("reinit", \&reinit_process_handler, 1, 0, 1);
2184:
2185: # Process the editing script for a table edit operation.
2186: # the editing operation must be encrypted and requested by
2187: # a manager host.
2188: #
2189: # Parameters:
2190: # $cmd - the actual keyword that invoked us.
2191: # $tail - the tail of the request that invoked us.
2192: # $client - File descriptor connected to the client
2193: # Returns:
2194: # 1 - Ok to continue processing.
2195: # 0 - Program should exit
2196: # Implicit output:
2197: # a reply is sent to the client.
2198: #
2199: sub edit_table_handler {
2200: my ($command, $tail, $client) = @_;
2201:
2202: my $userinput = "$command:$tail";
2203:
2204: my $cert = &GetCertificate($userinput);
2205: if(&ValidManager($cert)) {
2206: my($filetype, $script) = split(/:/, $tail);
2207: if (($filetype eq "hosts") ||
2208: ($filetype eq "domain")) {
2209: if($script ne "") {
2210: &Reply($client, # BUGBUG - EditFile
2211: &EditFile($userinput), # could fail.
2212: $userinput);
2213: } else {
2214: &Failure($client,"refused\n",$userinput);
2215: }
2216: } else {
2217: &Failure($client,"refused\n",$userinput);
2218: }
2219: } else {
2220: &Failure($client,"refused\n",$userinput);
2221: }
2222: return 1;
2223: }
1.263 albertel 2224: ®ister_handler("edit", \&edit_table_handler, 1, 0, 1);
1.218 foxr 2225:
1.220 foxr 2226: #
2227: # Authenticate a user against the LonCAPA authentication
2228: # database. Note that there are several authentication
2229: # possibilities:
2230: # - unix - The user can be authenticated against the unix
2231: # password file.
2232: # - internal - The user can be authenticated against a purely
2233: # internal per user password file.
2234: # - kerberos - The user can be authenticated against either a kerb4 or kerb5
2235: # ticket granting authority.
2236: # - user - The person tailoring LonCAPA can supply a user authentication
2237: # mechanism that is per system.
2238: #
2239: # Parameters:
2240: # $cmd - The command that got us here.
2241: # $tail - Tail of the command (remaining parameters).
2242: # $client - File descriptor connected to client.
2243: # Returns
2244: # 0 - Requested to exit, caller should shut down.
2245: # 1 - Continue processing.
2246: # Implicit inputs:
2247: # The authentication systems describe above have their own forms of implicit
2248: # input into the authentication process that are described above.
2249: #
2250: sub authenticate_handler {
2251: my ($cmd, $tail, $client) = @_;
2252:
2253:
2254: # Regenerate the full input line
2255:
2256: my $userinput = $cmd.":".$tail;
2257:
2258: # udom - User's domain.
2259: # uname - Username.
2260: # upass - User's password.
1.396 raeburn 2261: # checkdefauth - Pass to validate_user() to try authentication
2262: # with default auth type(s) if no user account.
1.447 raeburn 2263: # clientcancheckhost - Passed by clients with functionality in lonauth.pm
2264: # to check if session can be hosted.
1.220 foxr 2265:
1.447 raeburn 2266: my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
1.399 raeburn 2267: &Debug(" Authenticate domain = $udom, user = $uname, password = $upass, checkdefauth = $checkdefauth");
1.220 foxr 2268: chomp($upass);
2269: $upass=&unescape($upass);
2270:
1.396 raeburn 2271: my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
1.220 foxr 2272: if($pwdcorrect) {
1.447 raeburn 2273: my $canhost = 1;
2274: unless ($clientcancheckhost) {
1.448 raeburn 2275: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
2276: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.452 raeburn 2277: my @intdoms;
2278: my $internet_names = &Apache::lonnet::get_internet_names($clientname);
2279: if (ref($internet_names) eq 'ARRAY') {
2280: @intdoms = @{$internet_names};
2281: }
1.448 raeburn 2282: unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
1.447 raeburn 2283: my ($remote,$hosted);
2284: my $remotesession = &get_usersession_config($udom,'remotesession');
2285: if (ref($remotesession) eq 'HASH') {
1.525 raeburn 2286: $remote = $remotesession->{'remote'};
1.447 raeburn 2287: }
1.448 raeburn 2288: my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
1.447 raeburn 2289: if (ref($hostedsession) eq 'HASH') {
2290: $hosted = $hostedsession->{'hosted'};
2291: }
1.448 raeburn 2292: $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
1.492 droeschl 2293: $clientversion,
1.447 raeburn 2294: $remote,$hosted);
2295: }
2296: }
2297: if ($canhost) {
2298: &Reply( $client, "authorized\n", $userinput);
2299: } else {
2300: &Reply( $client, "not_allowed_to_host\n", $userinput);
2301: }
1.220 foxr 2302: #
2303: # Bad credentials: Failed to authorize
2304: #
2305: } else {
2306: &Failure( $client, "non_authorized\n", $userinput);
2307: }
2308:
2309: return 1;
2310: }
1.263 albertel 2311: ®ister_handler("auth", \&authenticate_handler, 1, 1, 0);
1.214 foxr 2312:
1.222 foxr 2313: #
2314: # Change a user's password. Note that this function is complicated by
2315: # the fact that a user may be authenticated in more than one way:
2316: # At present, we are not able to change the password for all types of
2317: # authentication methods. Only for:
2318: # unix - unix password or shadow passoword style authentication.
2319: # local - Locally written authentication mechanism.
2320: # For now, kerb4 and kerb5 password changes are not supported and result
2321: # in an error.
2322: # FUTURE WORK:
2323: # Support kerberos passwd changes?
2324: # Parameters:
2325: # $cmd - The command that got us here.
2326: # $tail - Tail of the command (remaining parameters).
2327: # $client - File descriptor connected to client.
2328: # Returns
2329: # 0 - Requested to exit, caller should shut down.
2330: # 1 - Continue processing.
2331: # Implicit inputs:
2332: # The authentication systems describe above have their own forms of implicit
2333: # input into the authentication process that are described above.
2334: sub change_password_handler {
2335: my ($cmd, $tail, $client) = @_;
2336:
2337: my $userinput = $cmd.":".$tail; # Reconstruct client's string.
2338:
2339: #
2340: # udom - user's domain.
2341: # uname - Username.
2342: # upass - Current password.
2343: # npass - New password.
1.346 raeburn 2344: # context - Context in which this was called
2345: # (preferences or reset_by_email).
1.428 raeburn 2346: # lonhost - HostID of server where request originated
1.222 foxr 2347:
1.428 raeburn 2348: my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
1.222 foxr 2349:
2350: $upass=&unescape($upass);
2351: $npass=&unescape($npass);
2352: &Debug("Trying to change password for $uname");
2353:
2354: # First require that the user can be authenticated with their
1.346 raeburn 2355: # old password unless context was 'reset_by_email':
2356:
1.428 raeburn 2357: my ($validated,$failure);
1.346 raeburn 2358: if ($context eq 'reset_by_email') {
1.428 raeburn 2359: if ($lonhost eq '') {
2360: $failure = 'invalid_client';
2361: } else {
2362: $validated = 1;
2363: }
1.346 raeburn 2364: } else {
2365: $validated = &validate_user($udom, $uname, $upass);
2366: }
1.222 foxr 2367: if($validated) {
2368: my $realpasswd = &get_auth_type($udom, $uname); # Defined since authd.
2369: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.558 raeburn 2370: my $notunique;
1.222 foxr 2371: if ($howpwd eq 'internal') {
2372: &Debug("internal auth");
1.518 raeburn 2373: my $ncpass = &hash_passwd($udom,$npass);
1.558 raeburn 2374: my (undef,$method,@rest) = split(/!/,$contentpwd);
2375: if ($method eq 'bcrypt') {
2376: my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
2377: if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
2378: my @oldpasswds;
2379: my $userpath = &propath($udom,$uname);
2380: my $fullpath = $userpath.'/oldpasswds';
2381: if (-d $userpath) {
2382: my @oldfiles;
2383: if (-e $fullpath) {
2384: if (opendir(my $dir,$fullpath)) {
2385: (@oldfiles) = grep(/^\d+$/,readdir($dir));
2386: closedir($dir);
2387: }
2388: if (@oldfiles) {
2389: @oldfiles = sort { $b <=> $a } (@oldfiles);
2390: my $numremoved = 0;
2391: for (my $i=0; $i<@oldfiles; $i++) {
2392: if ($i>=$passwdconf{'numsaved'}) {
2393: if (-f "$fullpath/$oldfiles[$i]") {
2394: if (unlink("$fullpath/$oldfiles[$i]")) {
2395: $numremoved ++;
2396: }
2397: }
2398: } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
2399: while (my $line = <$fh>) {
2400: push(@oldpasswds,$line);
2401: }
2402: close($fh);
2403: }
2404: }
2405: if ($numremoved) {
2406: &logthis("unlinked $numremoved old password files for $uname:$udom");
2407: }
2408: }
2409: }
2410: push(@oldpasswds,$contentpwd);
2411: foreach my $item (@oldpasswds) {
2412: my (undef,$method,@rest) = split(/!/,$item);
2413: if ($method eq 'bcrypt') {
2414: my $result = &hash_passwd($udom,$npass,@rest);
2415: if ($result eq $item) {
2416: $notunique = 1;
2417: last;
2418: }
2419: }
2420: }
2421: unless ($notunique) {
2422: unless (-e $fullpath) {
2423: if (&mkpath("$fullpath/")) {
2424: chmod(0700,$fullpath);
2425: }
2426: }
2427: if (-d $fullpath) {
2428: my $now = time;
2429: if (open(my $fh,'>',"$fullpath/$now")) {
2430: print $fh $contentpwd;
2431: close($fh);
2432: chmod(0400,"$fullpath/$now");
2433: }
2434: }
2435: }
2436: }
2437: }
2438: }
2439: if ($notunique) {
2440: my $msg="Result of password change for $uname:$udom - password matches one used before";
2441: if ($lonhost) {
2442: $msg .= " - request originated from: $lonhost";
2443: }
2444: &logthis($msg);
2445: &Reply($client, "prioruse\n", $userinput);
2446: } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428 raeburn 2447: my $msg="Result of password change for $uname: pwchange_success";
2448: if ($lonhost) {
2449: $msg .= " - request originated from: $lonhost";
2450: }
2451: &logthis($msg);
1.518 raeburn 2452: &update_passwd_history($uname,$udom,$howpwd,$context);
1.222 foxr 2453: &Reply($client, "ok\n", $userinput);
2454: } else {
2455: &logthis("Unable to open $uname passwd "
2456: ."to change password");
2457: &Failure( $client, "non_authorized\n",$userinput);
2458: }
1.346 raeburn 2459: } elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287 foxr 2460: my $result = &change_unix_password($uname, $npass);
1.518 raeburn 2461: if ($result eq 'ok') {
2462: &update_passwd_history($uname,$udom,$howpwd,$context);
1.561 raeburn 2463: }
1.222 foxr 2464: &logthis("Result of password change for $uname: ".
1.287 foxr 2465: $result);
1.387 albertel 2466: &Reply($client, \$result, $userinput);
1.222 foxr 2467: } else {
2468: # this just means that the current password mode is not
2469: # one we know how to change (e.g the kerberos auth modes or
2470: # locally written auth handler).
2471: #
2472: &Failure( $client, "auth_mode_error\n", $userinput);
2473: }
1.224 foxr 2474: } else {
1.428 raeburn 2475: if ($failure eq '') {
2476: $failure = 'non_authorized';
2477: }
2478: &Failure( $client, "$failure\n", $userinput);
1.222 foxr 2479: }
2480:
2481: return 1;
2482: }
1.263 albertel 2483: ®ister_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222 foxr 2484:
1.518 raeburn 2485: sub hash_passwd {
2486: my ($domain,$plainpass,@rest) = @_;
2487: my ($salt,$cost);
2488: if (@rest) {
2489: $cost = $rest[0];
2490: # salt is first 22 characters, base-64 encoded by bcrypt
2491: my $plainsalt = substr($rest[1],0,22);
2492: $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
2493: } else {
1.533 raeburn 2494: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2495: my $defaultcost = $domdefaults{'intauth_cost'};
1.518 raeburn 2496: if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
2497: $cost = 10;
2498: } else {
2499: $cost = $defaultcost;
2500: }
2501: # Generate random 16-octet base64 salt
2502: $salt = "";
2503: $salt .= pack("C", int rand(256)) for 1..16;
2504: }
2505: my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
2506: key_nul => 1,
2507: cost => $cost,
2508: salt => $salt,
2509: }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
2510:
2511: my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
2512: &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
2513: &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
2514: return $result;
2515: }
2516:
1.225 foxr 2517: #
2518: # Create a new user. User in this case means a lon-capa user.
2519: # The user must either already exist in some authentication realm
2520: # like kerberos or the /etc/passwd. If not, a user completely local to
2521: # this loncapa system is created.
2522: #
2523: # Parameters:
2524: # $cmd - The command that got us here.
2525: # $tail - Tail of the command (remaining parameters).
2526: # $client - File descriptor connected to client.
2527: # Returns
2528: # 0 - Requested to exit, caller should shut down.
2529: # 1 - Continue processing.
2530: # Implicit inputs:
2531: # The authentication systems describe above have their own forms of implicit
2532: # input into the authentication process that are described above.
2533: sub add_user_handler {
2534:
2535: my ($cmd, $tail, $client) = @_;
2536:
2537:
2538: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
2539: my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
2540:
2541: &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
2542:
2543:
2544: if($udom eq $currentdomainid) { # Reject new users for other domains...
2545:
2546: my $oldumask=umask(0077);
2547: chomp($npass);
2548: $npass=&unescape($npass);
2549: my $passfilename = &password_path($udom, $uname);
2550: &Debug("Password file created will be:".$passfilename);
2551: if (-e $passfilename) {
2552: &Failure( $client, "already_exists\n", $userinput);
2553: } else {
2554: my $fperror='';
1.264 albertel 2555: if (!&mkpath($passfilename)) {
2556: $fperror="error: ".($!+0)." mkdir failed while attempting "
2557: ."makeuser";
1.225 foxr 2558: }
2559: unless ($fperror) {
1.518 raeburn 2560: my $result=&make_passwd_file($uname,$udom,$umode,$npass,
2561: $passfilename,'makeuser');
1.390 raeburn 2562: &Reply($client,\$result, $userinput); #BUGBUG - could be fail
1.225 foxr 2563: } else {
1.387 albertel 2564: &Failure($client, \$fperror, $userinput);
1.225 foxr 2565: }
2566: }
2567: umask($oldumask);
2568: } else {
2569: &Failure($client, "not_right_domain\n",
2570: $userinput); # Even if we are multihomed.
2571:
2572: }
2573: return 1;
2574:
2575: }
2576: ®ister_handler("makeuser", \&add_user_handler, 1, 1, 0);
2577:
2578: #
2579: # Change the authentication method of a user. Note that this may
2580: # also implicitly change the user's password if, for example, the user is
2581: # joining an existing authentication realm. Known authentication realms at
2582: # this time are:
2583: # internal - Purely internal password file (only loncapa knows this user)
2584: # local - Institutionally written authentication module.
2585: # unix - Unix user (/etc/passwd with or without /etc/shadow).
2586: # kerb4 - kerberos version 4
2587: # kerb5 - kerberos version 5
2588: #
2589: # Parameters:
2590: # $cmd - The command that got us here.
2591: # $tail - Tail of the command (remaining parameters).
2592: # $client - File descriptor connected to client.
2593: # Returns
2594: # 0 - Requested to exit, caller should shut down.
2595: # 1 - Continue processing.
2596: # Implicit inputs:
2597: # The authentication systems describe above have their own forms of implicit
2598: # input into the authentication process that are described above.
1.287 foxr 2599: # NOTE:
2600: # This is also used to change the authentication credential values (e.g. passwd).
2601: #
1.225 foxr 2602: #
2603: sub change_authentication_handler {
2604:
2605: my ($cmd, $tail, $client) = @_;
2606:
2607: my $userinput = "$cmd:$tail"; # Reconstruct user input.
2608:
2609: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
2610: &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
2611: if ($udom ne $currentdomainid) {
2612: &Failure( $client, "not_right_domain\n", $client);
2613: } else {
2614:
2615: chomp($npass);
2616:
2617: $npass=&unescape($npass);
1.261 foxr 2618: my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225 foxr 2619: my $passfilename = &password_path($udom, $uname);
2620: if ($passfilename) { # Not allowed to create a new user!!
1.287 foxr 2621: # If just changing the unix passwd. need to arrange to run
1.502 raeburn 2622: # passwd since otherwise make_passwd_file will fail as
2623: # creation of unix authenticated users is no longer supported
2624: # except from the command line, when running make_domain_coordinator.pl
1.287 foxr 2625:
2626: if(($oldauth =~/^unix/) && ($umode eq "unix")) {
2627: my $result = &change_unix_password($uname, $npass);
2628: &logthis("Result of password change for $uname: ".$result);
2629: if ($result eq "ok") {
1.518 raeburn 2630: &update_passwd_history($uname,$udom,$umode,'changeuserauth');
1.390 raeburn 2631: &Reply($client, \$result);
1.288 albertel 2632: } else {
1.387 albertel 2633: &Failure($client, \$result);
1.287 foxr 2634: }
1.288 albertel 2635: } else {
1.518 raeburn 2636: my $result=&make_passwd_file($uname,$udom,$umode,$npass,
2637: $passfilename,'changeuserauth');
1.287 foxr 2638: #
2639: # If the current auth mode is internal, and the old auth mode was
2640: # unix, or krb*, and the user is an author for this domain,
2641: # re-run manage_permissions for that role in order to be able
2642: # to take ownership of the construction space back to www:www
2643: #
1.502 raeburn 2644:
2645:
1.387 albertel 2646: &Reply($client, \$result, $userinput);
1.261 foxr 2647: }
2648:
2649:
1.225 foxr 2650: } else {
1.251 foxr 2651: &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225 foxr 2652: }
2653: }
2654: return 1;
2655: }
2656: ®ister_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
2657:
1.518 raeburn 2658: sub update_passwd_history {
2659: my ($uname,$udom,$umode,$context) = @_;
2660: my $proname=&propath($udom,$uname);
2661: my $now = time;
2662: if (open(my $fh,">>$proname/passwd.log")) {
2663: print $fh "$now:$umode:$context\n";
2664: close($fh);
2665: }
2666: return;
2667: }
2668:
1.575 raeburn 2669: sub inst_unamemap_check {
2670: my ($cmd, $tail, $client) = @_;
2671: my $userinput = "$cmd:$tail";
2672: my %rulecheck;
2673: my $outcome;
2674: my ($udom,$uname,@rules) = split(/:/,$tail);
2675: $udom = &unescape($udom);
2676: $uname = &unescape($uname);
2677: @rules = map {&unescape($_);} (@rules);
2678: eval {
2679: local($SIG{__DIE__})='DEFAULT';
2680: $outcome = &localenroll::unamemap_check($udom,$uname,\@rules,\%rulecheck);
2681: };
2682: if (!$@) {
2683: if ($outcome eq 'ok') {
2684: my $result='';
2685: foreach my $key (keys(%rulecheck)) {
2686: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
2687: }
2688: &Reply($client,\$result,$userinput);
2689: } else {
2690: &Reply($client,"error\n", $userinput);
2691: }
2692: } else {
2693: &Failure($client,"unknown_cmd\n",$userinput);
2694: }
2695: }
2696: ®ister_handler("instunamemapcheck",\&inst_unamemap_check,0,1,0);
2697:
2698:
1.225 foxr 2699: #
2700: # Determines if this is the home server for a user. The home server
2701: # for a user will have his/her lon-capa passwd file. Therefore all we need
2702: # to do is determine if this file exists.
2703: #
2704: # Parameters:
2705: # $cmd - The command that got us here.
2706: # $tail - Tail of the command (remaining parameters).
2707: # $client - File descriptor connected to client.
2708: # Returns
2709: # 0 - Requested to exit, caller should shut down.
2710: # 1 - Continue processing.
2711: # Implicit inputs:
2712: # The authentication systems describe above have their own forms of implicit
2713: # input into the authentication process that are described above.
2714: #
2715: sub is_home_handler {
2716: my ($cmd, $tail, $client) = @_;
2717:
2718: my $userinput = "$cmd:$tail";
2719:
2720: my ($udom,$uname)=split(/:/,$tail);
2721: chomp($uname);
2722: my $passfile = &password_filename($udom, $uname);
2723: if($passfile) {
2724: &Reply( $client, "found\n", $userinput);
2725: } else {
2726: &Failure($client, "not_found\n", $userinput);
2727: }
2728: return 1;
2729: }
2730: ®ister_handler("home", \&is_home_handler, 0,1,0);
2731:
2732: #
1.434 www 2733: # Process an update request for a resource.
2734: # A resource has been modified that we hold a subscription to.
1.225 foxr 2735: # If the resource is not local, then we must update, or at least invalidate our
2736: # cached copy of the resource.
2737: # Parameters:
2738: # $cmd - The command that got us here.
2739: # $tail - Tail of the command (remaining parameters).
2740: # $client - File descriptor connected to client.
2741: # Returns
2742: # 0 - Requested to exit, caller should shut down.
2743: # 1 - Continue processing.
2744: # Implicit inputs:
2745: # The authentication systems describe above have their own forms of implicit
2746: # input into the authentication process that are described above.
2747: #
2748: sub update_resource_handler {
2749:
2750: my ($cmd, $tail, $client) = @_;
2751:
2752: my $userinput = "$cmd:$tail";
2753:
2754: my $fname= $tail; # This allows interactive testing
2755:
2756:
2757: my $ownership=ishome($fname);
2758: if ($ownership eq 'not_owner') {
2759: if (-e $fname) {
1.434 www 2760: # Delete preview file, if exists
2761: unlink("$fname.tmp");
2762: # Get usage stats
1.225 foxr 2763: my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
2764: $atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
2765: my $now=time;
2766: my $since=$now-$atime;
1.434 www 2767: # If the file has not been used within lonExpire seconds,
2768: # unsubscribe from it and delete local copy
1.225 foxr 2769: if ($since>$perlvar{'lonExpire'}) {
1.365 albertel 2770: my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308 albertel 2771: &devalidate_meta_cache($fname);
1.225 foxr 2772: unlink("$fname");
1.334 albertel 2773: unlink("$fname.meta");
1.225 foxr 2774: } else {
1.434 www 2775: # Yes, this is in active use. Get a fresh copy. Since it might be in
2776: # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225 foxr 2777: my $transname="$fname.in.transfer";
1.365 albertel 2778: my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225 foxr 2779: my $response;
1.537 raeburn 2780: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
2781: # for LWP request.
2782: my $request=new HTTP::Request('GET',"$remoteurl");
2783: $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
1.225 foxr 2784: if ($response->is_error()) {
1.541 raeburn 2785: my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
2786: &devalidate_meta_cache($fname);
2787: if (-e $transname) {
2788: unlink($transname);
2789: }
2790: unlink($fname);
1.225 foxr 2791: my $message=$response->status_line;
2792: &logthis("LWP GET: $message for $fname ($remoteurl)");
2793: } else {
2794: if ($remoteurl!~/\.meta$/) {
1.537 raeburn 2795: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2796: my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
2797: if ($mresponse->is_error()) {
2798: unlink($fname.'.meta');
1.225 foxr 2799: }
2800: }
1.434 www 2801: # we successfully transfered, copy file over to real name
1.225 foxr 2802: rename($transname,$fname);
1.308 albertel 2803: &devalidate_meta_cache($fname);
1.225 foxr 2804: }
2805: }
2806: &Reply( $client, "ok\n", $userinput);
2807: } else {
2808: &Failure($client, "not_found\n", $userinput);
2809: }
2810: } else {
2811: &Failure($client, "rejected\n", $userinput);
2812: }
2813: return 1;
2814: }
2815: ®ister_handler("update", \&update_resource_handler, 0 ,1, 0);
2816:
1.308 albertel 2817: sub devalidate_meta_cache {
2818: my ($url) = @_;
2819: use Cache::Memcached;
2820: my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365 albertel 2821: $url = &Apache::lonnet::declutter($url);
1.308 albertel 2822: $url =~ s-\.meta$--;
2823: my $id = &escape('meta:'.$url);
2824: $memcache->delete($id);
2825: }
2826:
1.225 foxr 2827: #
1.583 ! raeburn 2828: # Copy a file from /home/httpd/html/priv/domain/coursenum/
! 2829: # to /home/httpd/html/userfiles/domain/coursenum/priv
! 2830: #
! 2831: # Parameters:
! 2832: # $cmd - The command that got us here.
! 2833: # $tail - Tail of the command
! 2834: # : separated list of escaped values for
! 2835: # (a) relative path to a file in /priv/domain/coursenum
! 2836: # (b) coursenum
! 2837: # (c) domain
! 2838: # $client - File descriptor connected to client.
! 2839: # Returns
! 2840: # 0 - Requested to exit, caller should shut down.
! 2841: # 1 - Continue processing.
! 2842: #
! 2843:
! 2844: sub crs_filefrompriv_handler {
! 2845: my ($cmd, $tail, $client) = @_;
! 2846: my $userinput = "$cmd:$tail";
! 2847: my ($path,$cnum,$cdom) = map { &unescape($_); } split(/:/,$tail);
! 2848: $path =~ s/\.{2,}//g;
! 2849: if (($path eq '') || ($path eq '.')) {
! 2850: &Failure($client, "not_found\n", "$cmd:$tail");
! 2851: } else {
! 2852: $cdom = &LONCAPA::clean_domain($cdom);
! 2853: $cnum = &LONCAPA::clean_courseid($cnum);
! 2854: if (&LONCAPA::Lond::is_course($cdom,$cnum)) {
! 2855: my $toplevel = "/userfiles/$cdom/$cnum/priv";
! 2856: my $toppath = $perlvar{'lonDocRoot'}.$toplevel;
! 2857: my $dest = $toppath.'/'.$path;
! 2858: my $desturl = $toplevel.'/'.$path;
! 2859: my $src = $perlvar{'lonDocRoot'}.'/priv/'.$cdom.'/'.$cnum.'/'.$path;
! 2860: my ($dest_mtime, $src_mtime);
! 2861: if (-e $dest) {
! 2862: ($dest_mtime) = (stat($dest))[9];
! 2863: }
! 2864: if (-e $src) {
! 2865: my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
! 2866: $protocol = 'http' if ($protocol ne 'https');
! 2867: my $url = $protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'}).$desturl;
! 2868: ($src_mtime) = (stat($src))[9];
! 2869: if ((-e $dest) && ($dest_mtime >= $src_mtime)) {
! 2870: my $result = &escape($url);
! 2871: &Reply($client,\$result,$userinput);
! 2872: } else {
! 2873: my $reldir = $toplevel;
! 2874: my ($subdir,$fname) = ($path =~ m{^(.+)/([^/]+)$});
! 2875: if ($subdir eq '') {
! 2876: $fname = $path;
! 2877: } else {
! 2878: $reldir .= '/'.$subdir;
! 2879: }
! 2880: my $targetdir = $perlvar{'lonDocRoot'};
! 2881: my $dirfail;
! 2882: foreach my $part (split(/\//,$reldir)) {
! 2883: $targetdir .= '/'.$part;
! 2884: if ((-e $targetdir)!=1) {
! 2885: unless (mkdir($targetdir,0755)) {
! 2886: $dirfail = 1;
! 2887: last;
! 2888: }
! 2889: }
! 2890: }
! 2891: if ($dirfail) {
! 2892: &Failure($client,"error: mkdir_failed\n", $userinput);
! 2893: } else {
! 2894: if (File::Copy::copy($src,$dest)) {
! 2895: my $result = &escape($url);
! 2896: &Reply($client,\$result,$userinput);
! 2897: } else {
! 2898: &Failure($client,"error: copy_failed\n", $userinput);
! 2899: }
! 2900: }
! 2901: }
! 2902: } else {
! 2903: &Failure($client,"error: not_found\n", $userinput);
! 2904: }
! 2905: } else {
! 2906: &Failure($client, "error: not_course\n", $userinput);
! 2907: }
! 2908: }
! 2909: return 1;
! 2910: }
! 2911: ®ister_handler("crsfilefrompriv", \&crs_filefrompriv_handler, 0, 1, 0);
! 2912:
! 2913: #
1.226 foxr 2914: # Fetch a user file from a remote server to the user's home directory
2915: # userfiles subdir.
1.225 foxr 2916: # Parameters:
2917: # $cmd - The command that got us here.
2918: # $tail - Tail of the command (remaining parameters).
2919: # $client - File descriptor connected to client.
2920: # Returns
2921: # 0 - Requested to exit, caller should shut down.
2922: # 1 - Continue processing.
2923: #
2924: sub fetch_user_file_handler {
2925:
2926: my ($cmd, $tail, $client) = @_;
2927:
2928: my $userinput = "$cmd:$tail";
2929: my $fname = $tail;
1.232 foxr 2930: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225 foxr 2931: my $udir=&propath($udom,$uname).'/userfiles';
2932: unless (-e $udir) {
2933: mkdir($udir,0770);
2934: }
1.232 foxr 2935: Debug("fetch user file for $fname");
1.225 foxr 2936: if (-e $udir) {
2937: $ufile=~s/^[\.\~]+//;
1.232 foxr 2938:
2939: # IF necessary, create the path right down to the file.
2940: # Note that any regular files in the way of this path are
2941: # wiped out to deal with some earlier folly of mine.
2942:
1.267 raeburn 2943: if (!&mkpath($udir.'/'.$ufile)) {
1.264 albertel 2944: &Failure($client, "unable_to_create\n", $userinput);
1.232 foxr 2945: }
2946:
1.225 foxr 2947: my $destname=$udir.'/'.$ufile;
2948: my $transname=$udir.'/'.$ufile.'.in.transit';
1.476 raeburn 2949: my $clientprotocol=$Apache::lonnet::protocol{$clientname};
2950: $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486 raeburn 2951: my $clienthost = &Apache::lonnet::hostname($clientname);
2952: my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225 foxr 2953: my $response;
1.232 foxr 2954: Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.537 raeburn 2955: my $request=new HTTP::Request('GET',"$remoteurl");
2956: my $verifycert = 1;
2957: my @machine_ids = &Apache::lonnet::current_machine_ids();
2958: if (grep(/^\Q$clientname\E$/,@machine_ids)) {
2959: $verifycert = 0;
2960: }
2961: $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
1.225 foxr 2962: if ($response->is_error()) {
2963: unlink($transname);
2964: my $message=$response->status_line;
2965: &logthis("LWP GET: $message for $fname ($remoteurl)");
2966: &Failure($client, "failed\n", $userinput);
2967: } else {
1.232 foxr 2968: Debug("Renaming $transname to $destname");
1.225 foxr 2969: if (!rename($transname,$destname)) {
2970: &logthis("Unable to move $transname to $destname");
2971: unlink($transname);
2972: &Failure($client, "failed\n", $userinput);
2973: } else {
1.495 raeburn 2974: if ($fname =~ /^default.+\.(page|sequence)$/) {
2975: my ($major,$minor) = split(/\./,$clientversion);
2976: if (($major < 2) || ($major == 2 && $minor < 11)) {
2977: my $now = time;
2978: &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
2979: my $key = &escape('internal.contentchange');
2980: my $what = "$key=$now";
2981: my $hashref = &tie_user_hash($udom,$uname,'environment',
2982: &GDBM_WRCREAT(),"P",$what);
2983: if ($hashref) {
2984: $hashref->{$key}=$now;
2985: if (!&untie_user_hash($hashref)) {
2986: &logthis("error: ".($!+0)." untie (GDBM) failed ".
2987: "when updating internal.contentchange");
2988: }
2989: }
2990: }
2991: }
1.225 foxr 2992: &Reply($client, "ok\n", $userinput);
2993: }
2994: }
2995: } else {
2996: &Failure($client, "not_home\n", $userinput);
2997: }
2998: return 1;
2999: }
3000: ®ister_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
3001:
1.226 foxr 3002: #
3003: # Remove a file from a user's home directory userfiles subdirectory.
3004: # Parameters:
3005: # cmd - the Lond request keyword that got us here.
3006: # tail - the part of the command past the keyword.
3007: # client- File descriptor connected with the client.
3008: #
3009: # Returns:
3010: # 1 - Continue processing.
3011: sub remove_user_file_handler {
3012: my ($cmd, $tail, $client) = @_;
3013:
3014: my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
3015:
3016: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
3017: if ($ufile =~m|/\.\./|) {
3018: # any files paths with /../ in them refuse
3019: # to deal with
3020: &Failure($client, "refused\n", "$cmd:$tail");
3021: } else {
3022: my $udir = &propath($udom,$uname);
3023: if (-e $udir) {
3024: my $file=$udir.'/userfiles/'.$ufile;
3025: if (-e $file) {
1.253 foxr 3026: #
3027: # If the file is a regular file unlink is fine...
1.520 raeburn 3028: # However it's possible the client wants a dir
3029: # removed, in which case rmdir is more appropriate.
3030: # Note: rmdir will only remove an empty directory.
1.253 foxr 3031: #
1.240 banghart 3032: if (-f $file){
1.241 albertel 3033: unlink($file);
1.520 raeburn 3034: # for html files remove the associated .bak file
3035: # which may have been created by the editor.
3036: if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
3037: my $path = $1;
3038: if (-e $file.'.bak') {
3039: unlink($file.'.bak');
3040: }
3041: }
1.241 albertel 3042: } elsif(-d $file) {
3043: rmdir($file);
1.240 banghart 3044: }
1.226 foxr 3045: if (-e $file) {
1.253 foxr 3046: # File is still there after we deleted it ?!?
3047:
1.226 foxr 3048: &Failure($client, "failed\n", "$cmd:$tail");
3049: } else {
3050: &Reply($client, "ok\n", "$cmd:$tail");
3051: }
3052: } else {
3053: &Failure($client, "not_found\n", "$cmd:$tail");
3054: }
3055: } else {
3056: &Failure($client, "not_home\n", "$cmd:$tail");
3057: }
3058: }
3059: return 1;
3060: }
3061: ®ister_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
3062:
1.236 albertel 3063: #
3064: # make a directory in a user's home directory userfiles subdirectory.
3065: # Parameters:
3066: # cmd - the Lond request keyword that got us here.
3067: # tail - the part of the command past the keyword.
3068: # client- File descriptor connected with the client.
3069: #
3070: # Returns:
3071: # 1 - Continue processing.
3072: sub mkdir_user_file_handler {
3073: my ($cmd, $tail, $client) = @_;
3074:
3075: my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
3076: $dir=&unescape($dir);
3077: my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
3078: if ($ufile =~m|/\.\./|) {
3079: # any files paths with /../ in them refuse
3080: # to deal with
3081: &Failure($client, "refused\n", "$cmd:$tail");
3082: } else {
3083: my $udir = &propath($udom,$uname);
3084: if (-e $udir) {
1.264 albertel 3085: my $newdir=$udir.'/userfiles/'.$ufile.'/';
3086: if (!&mkpath($newdir)) {
3087: &Failure($client, "failed\n", "$cmd:$tail");
1.236 albertel 3088: }
1.264 albertel 3089: &Reply($client, "ok\n", "$cmd:$tail");
1.236 albertel 3090: } else {
3091: &Failure($client, "not_home\n", "$cmd:$tail");
3092: }
3093: }
3094: return 1;
3095: }
3096: ®ister_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
3097:
1.237 albertel 3098: #
3099: # rename a file in a user's home directory userfiles subdirectory.
3100: # Parameters:
3101: # cmd - the Lond request keyword that got us here.
3102: # tail - the part of the command past the keyword.
3103: # client- File descriptor connected with the client.
3104: #
3105: # Returns:
3106: # 1 - Continue processing.
3107: sub rename_user_file_handler {
3108: my ($cmd, $tail, $client) = @_;
3109:
3110: my ($udom,$uname,$old,$new) = split(/:/, $tail);
3111: $old=&unescape($old);
3112: $new=&unescape($new);
3113: if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
3114: # any files paths with /../ in them refuse to deal with
3115: &Failure($client, "refused\n", "$cmd:$tail");
3116: } else {
3117: my $udir = &propath($udom,$uname);
3118: if (-e $udir) {
3119: my $oldfile=$udir.'/userfiles/'.$old;
3120: my $newfile=$udir.'/userfiles/'.$new;
3121: if (-e $newfile) {
3122: &Failure($client, "exists\n", "$cmd:$tail");
3123: } elsif (! -e $oldfile) {
3124: &Failure($client, "not_found\n", "$cmd:$tail");
3125: } else {
3126: if (!rename($oldfile,$newfile)) {
3127: &Failure($client, "failed\n", "$cmd:$tail");
3128: } else {
3129: &Reply($client, "ok\n", "$cmd:$tail");
3130: }
3131: }
3132: } else {
3133: &Failure($client, "not_home\n", "$cmd:$tail");
3134: }
3135: }
3136: return 1;
3137: }
3138: ®ister_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
3139:
1.227 foxr 3140: #
1.382 albertel 3141: # Checks if the specified user has an active session on the server
3142: # return ok if so, not_found if not
3143: #
3144: # Parameters:
3145: # cmd - The request keyword that dispatched to tus.
3146: # tail - The tail of the request (colon separated parameters).
3147: # client - Filehandle open on the client.
3148: # Return:
3149: # 1.
3150: sub user_has_session_handler {
3151: my ($cmd, $tail, $client) = @_;
3152:
3153: my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
3154:
3155: opendir(DIR,$perlvar{'lonIDsDir'});
3156: my $filename;
3157: while ($filename=readdir(DIR)) {
3158: last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
3159: }
3160: if ($filename) {
3161: &Reply($client, "ok\n", "$cmd:$tail");
3162: } else {
3163: &Failure($client, "not_found\n", "$cmd:$tail");
3164: }
3165: return 1;
3166:
3167: }
3168: ®ister_handler("userhassession", \&user_has_session_handler, 0,1,0);
3169:
1.560 raeburn 3170: sub del_usersession_handler {
3171: my ($cmd, $tail, $client) = @_;
3172:
3173: my $result;
3174: my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
3175: if (($udom =~ /^$LONCAPA::match_domain$/) && ($uname =~ /^$LONCAPA::match_username$/)) {
3176: my $lonidsdir = $perlvar{'lonIDsDir'};
3177: if (-d $lonidsdir) {
3178: if (opendir(DIR,$lonidsdir)) {
3179: my $filename;
3180: while ($filename=readdir(DIR)) {
3181: if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/) {
3182: if (tie(my %oldenv,'GDBM_File',"$lonidsdir/$filename",
3183: &GDBM_READER(),0640)) {
3184: my $linkedfile;
3185: if (exists($oldenv{'user.linkedenv'})) {
3186: $linkedfile = $oldenv{'user.linkedenv'};
3187: }
3188: untie(%oldenv);
3189: $result = unlink("$lonidsdir/$filename");
3190: if ($result) {
3191: if ($linkedfile =~ /^[a-f0-9]+_linked$/) {
3192: if (-l "$lonidsdir/$linkedfile.id") {
3193: unlink("$lonidsdir/$linkedfile.id");
3194: }
3195: }
3196: }
3197: } else {
3198: $result = unlink("$lonidsdir/$filename");
3199: }
3200: last;
3201: }
3202: }
3203: }
3204: }
3205: if ($result == 1) {
3206: &Reply($client, "$result\n", "$cmd:$tail");
3207: } else {
3208: &Reply($client, "not_found\n", "$cmd:$tail");
3209: }
3210: } else {
3211: &Failure($client, "invalid_user\n", "$cmd:$tail");
3212: }
3213: return 1;
3214: }
3215:
3216: ®ister_handler("delusersession", \&del_usersession_handler, 0,1,0);
3217:
1.382 albertel 3218: #
1.263 albertel 3219: # Authenticate access to a user file by checking that the token the user's
3220: # passed also exists in their session file
1.227 foxr 3221: #
3222: # Parameters:
3223: # cmd - The request keyword that dispatched to tus.
3224: # tail - The tail of the request (colon separated parameters).
3225: # client - Filehandle open on the client.
3226: # Return:
3227: # 1.
3228: sub token_auth_user_file_handler {
3229: my ($cmd, $tail, $client) = @_;
3230:
3231: my ($fname, $session) = split(/:/, $tail);
3232:
3233: chomp($session);
1.393 raeburn 3234: my $reply="non_auth";
1.343 albertel 3235: my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
3236: if (open(ENVIN,"$file")) {
1.332 albertel 3237: flock(ENVIN,LOCK_SH);
1.343 albertel 3238: tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
3239: if (exists($disk_env{"userfile.$fname"})) {
1.393 raeburn 3240: $reply="ok";
1.343 albertel 3241: } else {
3242: foreach my $envname (keys(%disk_env)) {
3243: if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393 raeburn 3244: $reply="ok";
1.343 albertel 3245: last;
3246: }
3247: }
1.227 foxr 3248: }
1.343 albertel 3249: untie(%disk_env);
1.227 foxr 3250: close(ENVIN);
1.387 albertel 3251: &Reply($client, \$reply, "$cmd:$tail");
1.227 foxr 3252: } else {
3253: &Failure($client, "invalid_token\n", "$cmd:$tail");
3254: }
3255: return 1;
3256:
3257: }
3258: ®ister_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229 foxr 3259:
3260: #
3261: # Unsubscribe from a resource.
3262: #
3263: # Parameters:
3264: # $cmd - The command that got us here.
3265: # $tail - Tail of the command (remaining parameters).
3266: # $client - File descriptor connected to client.
3267: # Returns
3268: # 0 - Requested to exit, caller should shut down.
3269: # 1 - Continue processing.
3270: #
3271: sub unsubscribe_handler {
3272: my ($cmd, $tail, $client) = @_;
3273:
3274: my $userinput= "$cmd:$tail";
3275:
3276: my ($fname) = split(/:/,$tail); # Split in case there's extrs.
3277:
3278: &Debug("Unsubscribing $fname");
3279: if (-e $fname) {
3280: &Debug("Exists");
3281: &Reply($client, &unsub($fname,$clientip), $userinput);
3282: } else {
3283: &Failure($client, "not_found\n", $userinput);
3284: }
3285: return 1;
3286: }
3287: ®ister_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263 albertel 3288:
1.230 foxr 3289: # Subscribe to a resource
3290: #
3291: # Parameters:
3292: # $cmd - The command that got us here.
3293: # $tail - Tail of the command (remaining parameters).
3294: # $client - File descriptor connected to client.
3295: # Returns
3296: # 0 - Requested to exit, caller should shut down.
3297: # 1 - Continue processing.
3298: #
3299: sub subscribe_handler {
3300: my ($cmd, $tail, $client)= @_;
3301:
3302: my $userinput = "$cmd:$tail";
3303:
3304: &Reply( $client, &subscribe($userinput,$clientip), $userinput);
3305:
3306: return 1;
3307: }
3308: ®ister_handler("sub", \&subscribe_handler, 0, 1, 0);
3309:
3310: #
1.379 albertel 3311: # Determine the latest version of a resource (it looks for the highest
3312: # past version and then returns that +1)
1.230 foxr 3313: #
3314: # Parameters:
3315: # $cmd - The command that got us here.
3316: # $tail - Tail of the command (remaining parameters).
1.379 albertel 3317: # (Should consist of an absolute path to a file)
1.230 foxr 3318: # $client - File descriptor connected to client.
3319: # Returns
3320: # 0 - Requested to exit, caller should shut down.
3321: # 1 - Continue processing.
3322: #
3323: sub current_version_handler {
3324: my ($cmd, $tail, $client) = @_;
3325:
3326: my $userinput= "$cmd:$tail";
3327:
3328: my $fname = $tail;
3329: &Reply( $client, ¤tversion($fname)."\n", $userinput);
3330: return 1;
3331:
3332: }
3333: ®ister_handler("currentversion", \¤t_version_handler, 0, 1, 0);
3334:
3335: # Make an entry in a user's activity log.
3336: #
3337: # Parameters:
3338: # $cmd - The command that got us here.
3339: # $tail - Tail of the command (remaining parameters).
3340: # $client - File descriptor connected to client.
3341: # Returns
3342: # 0 - Requested to exit, caller should shut down.
3343: # 1 - Continue processing.
3344: #
3345: sub activity_log_handler {
3346: my ($cmd, $tail, $client) = @_;
3347:
3348:
3349: my $userinput= "$cmd:$tail";
3350:
3351: my ($udom,$uname,$what)=split(/:/,$tail);
3352: chomp($what);
3353: my $proname=&propath($udom,$uname);
3354: my $now=time;
3355: my $hfh;
3356: if ($hfh=IO::File->new(">>$proname/activity.log")) {
3357: print $hfh "$now:$clientname:$what\n";
3358: &Reply( $client, "ok\n", $userinput);
3359: } else {
3360: &Failure($client, "error: ".($!+0)." IO::File->new Failed "
3361: ."while attempting log\n",
3362: $userinput);
3363: }
3364:
3365: return 1;
3366: }
1.263 albertel 3367: ®ister_handler("log", \&activity_log_handler, 0, 1, 0);
1.230 foxr 3368:
3369: #
3370: # Put a namespace entry in a user profile hash.
3371: # My druthers would be for this to be an encrypted interaction too.
3372: # anything that might be an inadvertent covert channel about either
3373: # user authentication or user personal information....
3374: #
3375: # Parameters:
3376: # $cmd - The command that got us here.
3377: # $tail - Tail of the command (remaining parameters).
3378: # $client - File descriptor connected to client.
3379: # Returns
3380: # 0 - Requested to exit, caller should shut down.
3381: # 1 - Continue processing.
3382: #
3383: sub put_user_profile_entry {
3384: my ($cmd, $tail, $client) = @_;
1.229 foxr 3385:
1.230 foxr 3386: my $userinput = "$cmd:$tail";
3387:
1.242 raeburn 3388: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230 foxr 3389: if ($namespace ne 'roles') {
3390: chomp($what);
3391: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3392: &GDBM_WRCREAT(),"P",$what);
3393: if($hashref) {
3394: my @pairs=split(/\&/,$what);
3395: foreach my $pair (@pairs) {
3396: my ($key,$value)=split(/=/,$pair);
3397: $hashref->{$key}=$value;
3398: }
1.311 albertel 3399: if (&untie_user_hash($hashref)) {
1.230 foxr 3400: &Reply( $client, "ok\n", $userinput);
3401: } else {
3402: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3403: "while attempting put\n",
3404: $userinput);
3405: }
3406: } else {
1.316 albertel 3407: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230 foxr 3408: "while attempting put\n", $userinput);
3409: }
3410: } else {
3411: &Failure( $client, "refused\n", $userinput);
3412: }
3413:
3414: return 1;
3415: }
3416: ®ister_handler("put", \&put_user_profile_entry, 0, 1, 0);
3417:
1.283 albertel 3418: # Put a piece of new data in hash, returns error if entry already exists
3419: # Parameters:
3420: # $cmd - The command that got us here.
3421: # $tail - Tail of the command (remaining parameters).
3422: # $client - File descriptor connected to client.
3423: # Returns
3424: # 0 - Requested to exit, caller should shut down.
3425: # 1 - Continue processing.
3426: #
3427: sub newput_user_profile_entry {
3428: my ($cmd, $tail, $client) = @_;
3429:
3430: my $userinput = "$cmd:$tail";
3431:
3432: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
3433: if ($namespace eq 'roles') {
3434: &Failure( $client, "refused\n", $userinput);
3435: return 1;
3436: }
3437:
3438: chomp($what);
3439:
3440: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3441: &GDBM_WRCREAT(),"N",$what);
3442: if(!$hashref) {
1.316 albertel 3443: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283 albertel 3444: "while attempting put\n", $userinput);
3445: return 1;
3446: }
3447:
3448: my @pairs=split(/\&/,$what);
3449: foreach my $pair (@pairs) {
3450: my ($key,$value)=split(/=/,$pair);
3451: if (exists($hashref->{$key})) {
1.513 raeburn 3452: if (!&untie_user_hash($hashref)) {
3453: &logthis("error: ".($!+0)." untie (GDBM) failed ".
3454: "while attempting newput - early out as key exists");
3455: }
3456: &Failure($client, "key_exists: ".$key."\n",$userinput);
3457: return 1;
1.283 albertel 3458: }
3459: }
3460:
3461: foreach my $pair (@pairs) {
3462: my ($key,$value)=split(/=/,$pair);
3463: $hashref->{$key}=$value;
3464: }
3465:
1.311 albertel 3466: if (&untie_user_hash($hashref)) {
1.283 albertel 3467: &Reply( $client, "ok\n", $userinput);
3468: } else {
3469: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3470: "while attempting put\n",
3471: $userinput);
3472: }
3473: return 1;
3474: }
3475: ®ister_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
3476:
1.230 foxr 3477: #
3478: # Increment a profile entry in the user history file.
3479: # The history contains keyword value pairs. In this case,
3480: # The value itself is a pair of numbers. The first, the current value
3481: # the second an increment that this function applies to the current
3482: # value.
3483: #
3484: # Parameters:
3485: # $cmd - The command that got us here.
3486: # $tail - Tail of the command (remaining parameters).
3487: # $client - File descriptor connected to client.
3488: # Returns
3489: # 0 - Requested to exit, caller should shut down.
3490: # 1 - Continue processing.
3491: #
3492: sub increment_user_value_handler {
3493: my ($cmd, $tail, $client) = @_;
3494:
3495: my $userinput = "$cmd:$tail";
3496:
3497: my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
3498: if ($namespace ne 'roles') {
3499: chomp($what);
3500: my $hashref = &tie_user_hash($udom, $uname,
3501: $namespace, &GDBM_WRCREAT(),
3502: "P",$what);
3503: if ($hashref) {
3504: my @pairs=split(/\&/,$what);
3505: foreach my $pair (@pairs) {
3506: my ($key,$value)=split(/=/,$pair);
1.284 raeburn 3507: $value = &unescape($value);
1.230 foxr 3508: # We could check that we have a number...
3509: if (! defined($value) || $value eq '') {
3510: $value = 1;
3511: }
3512: $hashref->{$key}+=$value;
1.284 raeburn 3513: if ($namespace eq 'nohist_resourcetracker') {
3514: if ($hashref->{$key} < 0) {
3515: $hashref->{$key} = 0;
3516: }
3517: }
1.230 foxr 3518: }
1.311 albertel 3519: if (&untie_user_hash($hashref)) {
1.230 foxr 3520: &Reply( $client, "ok\n", $userinput);
3521: } else {
3522: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3523: "while attempting inc\n", $userinput);
3524: }
3525: } else {
3526: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3527: "while attempting inc\n", $userinput);
3528: }
3529: } else {
3530: &Failure($client, "refused\n", $userinput);
3531: }
3532:
3533: return 1;
3534: }
3535: ®ister_handler("inc", \&increment_user_value_handler, 0, 1, 0);
3536:
3537: #
3538: # Put a new role for a user. Roles are LonCAPA's packaging of permissions.
3539: # Each 'role' a user has implies a set of permissions. Adding a new role
3540: # for a person grants the permissions packaged with that role
3541: # to that user when the role is selected.
3542: #
3543: # Parameters:
3544: # $cmd - The command string (rolesput).
3545: # $tail - The remainder of the request line. For rolesput this
3546: # consists of a colon separated list that contains:
3547: # The domain and user that is granting the role (logged).
3548: # The domain and user that is getting the role.
3549: # The roles being granted as a set of & separated pairs.
3550: # each pair a key value pair.
3551: # $client - File descriptor connected to the client.
3552: # Returns:
3553: # 0 - If the daemon should exit
3554: # 1 - To continue processing.
3555: #
3556: #
3557: sub roles_put_handler {
3558: my ($cmd, $tail, $client) = @_;
3559:
3560: my $userinput = "$cmd:$tail";
3561:
3562: my ( $exedom, $exeuser, $udom, $uname, $what) = split(/:/,$tail);
3563:
3564:
3565: my $namespace='roles';
3566: chomp($what);
3567: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3568: &GDBM_WRCREAT(), "P",
3569: "$exedom:$exeuser:$what");
3570: #
3571: # Log the attempt to set a role. The {}'s here ensure that the file
3572: # handle is open for the minimal amount of time. Since the flush
3573: # is done on close this improves the chances the log will be an un-
3574: # corrupted ordered thing.
3575: if ($hashref) {
1.261 foxr 3576: my $pass_entry = &get_auth_type($udom, $uname);
3577: my ($auth_type,$pwd) = split(/:/, $pass_entry);
3578: $auth_type = $auth_type.":";
1.230 foxr 3579: my @pairs=split(/\&/,$what);
3580: foreach my $pair (@pairs) {
3581: my ($key,$value)=split(/=/,$pair);
3582: &manage_permissions($key, $udom, $uname,
1.260 foxr 3583: $auth_type);
1.230 foxr 3584: $hashref->{$key}=$value;
3585: }
1.311 albertel 3586: if (&untie_user_hash($hashref)) {
1.230 foxr 3587: &Reply($client, "ok\n", $userinput);
3588: } else {
3589: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3590: "while attempting rolesput\n", $userinput);
3591: }
3592: } else {
3593: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3594: "while attempting rolesput\n", $userinput);
3595: }
3596: return 1;
3597: }
3598: ®ister_handler("rolesput", \&roles_put_handler, 1,1,0); # Encoded client only.
3599:
3600: #
1.231 foxr 3601: # Deletes (removes) a role for a user. This is equivalent to removing
3602: # a permissions package associated with the role from the user's profile.
3603: #
3604: # Parameters:
3605: # $cmd - The command (rolesdel)
3606: # $tail - The remainder of the request line. This consists
3607: # of:
3608: # The domain and user requesting the change (logged)
3609: # The domain and user being changed.
3610: # The roles being revoked. These are shipped to us
3611: # as a bunch of & separated role name keywords.
3612: # $client - The file handle open on the client.
3613: # Returns:
3614: # 1 - Continue processing
3615: # 0 - Exit.
3616: #
3617: sub roles_delete_handler {
3618: my ($cmd, $tail, $client) = @_;
3619:
3620: my $userinput = "$cmd:$tail";
3621:
3622: my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
3623: &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
3624: "what = ".$what);
3625: my $namespace='roles';
3626: chomp($what);
3627: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3628: &GDBM_WRCREAT(), "D",
3629: "$exedom:$exeuser:$what");
3630:
3631: if ($hashref) {
3632: my @rolekeys=split(/\&/,$what);
3633:
3634: foreach my $key (@rolekeys) {
3635: delete $hashref->{$key};
3636: }
1.315 albertel 3637: if (&untie_user_hash($hashref)) {
1.231 foxr 3638: &Reply($client, "ok\n", $userinput);
3639: } else {
3640: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3641: "while attempting rolesdel\n", $userinput);
3642: }
3643: } else {
3644: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3645: "while attempting rolesdel\n", $userinput);
3646: }
3647:
3648: return 1;
3649: }
3650: ®ister_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
3651:
3652: # Unencrypted get from a user's profile database. See
3653: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
3654: # This function retrieves a keyed item from a specific named database in the
3655: # user's directory.
3656: #
3657: # Parameters:
3658: # $cmd - Command request keyword (get).
3659: # $tail - Tail of the command. This is a colon separated list
3660: # consisting of the domain and username that uniquely
3661: # identifies the profile,
3662: # The 'namespace' which selects the gdbm file to
3663: # do the lookup in,
3664: # & separated list of keys to lookup. Note that
3665: # the values are returned as an & separated list too.
3666: # $client - File descriptor open on the client.
3667: # Returns:
3668: # 1 - Continue processing.
3669: # 0 - Exit.
3670: #
3671: sub get_profile_entry {
3672: my ($cmd, $tail, $client) = @_;
3673:
3674: my $userinput= "$cmd:$tail";
3675:
3676: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
3677: chomp($what);
1.255 foxr 3678:
1.390 raeburn 3679:
1.255 foxr 3680: my $replystring = read_profile($udom, $uname, $namespace, $what);
3681: my ($first) = split(/:/,$replystring);
3682: if($first ne "error") {
1.387 albertel 3683: &Reply($client, \$replystring, $userinput);
1.231 foxr 3684: } else {
1.255 foxr 3685: &Failure($client, $replystring." while attempting get\n", $userinput);
1.231 foxr 3686: }
3687: return 1;
1.255 foxr 3688:
3689:
1.231 foxr 3690: }
3691: ®ister_handler("get", \&get_profile_entry, 0,1,0);
3692:
3693: #
3694: # Process the encrypted get request. Note that the request is sent
3695: # in clear, but the reply is encrypted. This is a small covert channel:
3696: # information about the sensitive keys is given to the snooper. Just not
3697: # information about the values of the sensitive key. Hmm if I wanted to
3698: # know these I'd snoop for the egets. Get the profile item names from them
3699: # and then issue a get for them since there's no enforcement of the
3700: # requirement of an encrypted get for particular profile items. If I
3701: # were re-doing this, I'd force the request to be encrypted as well as the
3702: # reply. I'd also just enforce encrypted transactions for all gets since
3703: # that would prevent any covert channel snooping.
3704: #
3705: # Parameters:
3706: # $cmd - Command keyword of request (eget).
1.536 raeburn 3707: # $tail - Tail of the command. See GetProfileEntry
3708: # for more information about this.
1.231 foxr 3709: # $client - File open on the client.
3710: # Returns:
3711: # 1 - Continue processing
3712: # 0 - server should exit.
3713: sub get_profile_entry_encrypted {
3714: my ($cmd, $tail, $client) = @_;
3715:
3716: my $userinput = "$cmd:$tail";
3717:
1.339 albertel 3718: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231 foxr 3719: chomp($what);
1.255 foxr 3720: my $qresult = read_profile($udom, $uname, $namespace, $what);
3721: my ($first) = split(/:/, $qresult);
3722: if($first ne "error") {
3723:
3724: if ($cipher) {
3725: my $cmdlength=length($qresult);
3726: $qresult.=" ";
3727: my $encqresult='';
3728: for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
3729: $encqresult.= unpack("H16",
3730: $cipher->encrypt(substr($qresult,
3731: $encidx,
3732: 8)));
3733: }
3734: &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
3735: } else {
1.231 foxr 3736: &Failure( $client, "error:no_key\n", $userinput);
3737: }
3738: } else {
1.255 foxr 3739: &Failure($client, "$qresult while attempting eget\n", $userinput);
3740:
1.231 foxr 3741: }
3742:
3743: return 1;
3744: }
1.255 foxr 3745: ®ister_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263 albertel 3746:
1.231 foxr 3747: #
3748: # Deletes a key in a user profile database.
3749: #
3750: # Parameters:
3751: # $cmd - Command keyword (del).
3752: # $tail - Command tail. IN this case a colon
3753: # separated list containing:
3754: # The domain and user that identifies uniquely
3755: # the identity of the user.
3756: # The profile namespace (name of the profile
3757: # database file).
3758: # & separated list of keywords to delete.
3759: # $client - File open on client socket.
3760: # Returns:
3761: # 1 - Continue processing
3762: # 0 - Exit server.
3763: #
3764: #
3765: sub delete_profile_entry {
3766: my ($cmd, $tail, $client) = @_;
3767:
3768: my $userinput = "cmd:$tail";
3769:
3770: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
3771: chomp($what);
3772: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3773: &GDBM_WRCREAT(),
3774: "D",$what);
3775: if ($hashref) {
3776: my @keys=split(/\&/,$what);
3777: foreach my $key (@keys) {
3778: delete($hashref->{$key});
3779: }
1.315 albertel 3780: if (&untie_user_hash($hashref)) {
1.231 foxr 3781: &Reply($client, "ok\n", $userinput);
3782: } else {
3783: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3784: "while attempting del\n", $userinput);
3785: }
3786: } else {
3787: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3788: "while attempting del\n", $userinput);
3789: }
3790: return 1;
3791: }
3792: ®ister_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263 albertel 3793:
1.231 foxr 3794: #
3795: # List the set of keys that are defined in a profile database file.
3796: # A successful reply from this will contain an & separated list of
3797: # the keys.
3798: # Parameters:
3799: # $cmd - Command request (keys).
3800: # $tail - Remainder of the request, a colon separated
3801: # list containing domain/user that identifies the
3802: # user being queried, and the database namespace
3803: # (database filename essentially).
3804: # $client - File open on the client.
3805: # Returns:
3806: # 1 - Continue processing.
3807: # 0 - Exit the server.
3808: #
3809: sub get_profile_keys {
3810: my ($cmd, $tail, $client) = @_;
3811:
3812: my $userinput = "$cmd:$tail";
3813:
3814: my ($udom,$uname,$namespace)=split(/:/,$tail);
3815: my $qresult='';
3816: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3817: &GDBM_READER());
3818: if ($hashref) {
3819: foreach my $key (keys %$hashref) {
3820: $qresult.="$key&";
3821: }
1.315 albertel 3822: if (&untie_user_hash($hashref)) {
1.231 foxr 3823: $qresult=~s/\&$//;
1.387 albertel 3824: &Reply($client, \$qresult, $userinput);
1.231 foxr 3825: } else {
3826: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3827: "while attempting keys\n", $userinput);
3828: }
3829: } else {
3830: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3831: "while attempting keys\n", $userinput);
3832: }
3833:
3834: return 1;
3835: }
3836: ®ister_handler("keys", \&get_profile_keys, 0, 1, 0);
3837:
3838: #
3839: # Dump the contents of a user profile database.
3840: # Note that this constitutes a very large covert channel too since
3841: # the dump will return sensitive information that is not encrypted.
3842: # The naive security assumption is that the session negotiation ensures
3843: # our client is trusted and I don't believe that's assured at present.
3844: # Sure want badly to go to ssl or tls. Of course if my peer isn't really
3845: # a LonCAPA node they could have negotiated an encryption key too so >sigh<.
3846: #
3847: # Parameters:
3848: # $cmd - The command request keyword (currentdump).
3849: # $tail - Remainder of the request, consisting of a colon
3850: # separated list that has the domain/username and
3851: # the namespace to dump (database file).
3852: # $client - file open on the remote client.
3853: # Returns:
3854: # 1 - Continue processing.
3855: # 0 - Exit the server.
3856: #
3857: sub dump_profile_database {
3858: my ($cmd, $tail, $client) = @_;
3859:
1.494 droeschl 3860: my $res = LONCAPA::Lond::dump_profile_database($tail);
3861:
3862: if ($res =~ /^error:/) {
3863: Failure($client, \$res, "$cmd:$tail");
3864: } else {
3865: Reply($client, \$res, "$cmd:$tail");
3866: }
3867:
3868: return 1;
3869:
3870: #TODO remove
1.231 foxr 3871: my $userinput = "$cmd:$tail";
3872:
3873: my ($udom,$uname,$namespace) = split(/:/,$tail);
3874: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3875: &GDBM_READER());
3876: if ($hashref) {
3877: # Structure of %data:
3878: # $data{$symb}->{$parameter}=$value;
3879: # $data{$symb}->{'v.'.$parameter}=$version;
3880: # since $parameter will be unescaped, we do not
3881: # have to worry about silly parameter names...
3882:
3883: my $qresult='';
3884: my %data = (); # A hash of anonymous hashes..
3885: while (my ($key,$value) = each(%$hashref)) {
3886: my ($v,$symb,$param) = split(/:/,$key);
3887: next if ($v eq 'version' || $symb eq 'keys');
3888: next if (exists($data{$symb}) &&
3889: exists($data{$symb}->{$param}) &&
3890: $data{$symb}->{'v.'.$param} > $v);
3891: $data{$symb}->{$param}=$value;
3892: $data{$symb}->{'v.'.$param}=$v;
3893: }
1.311 albertel 3894: if (&untie_user_hash($hashref)) {
1.231 foxr 3895: while (my ($symb,$param_hash) = each(%data)) {
3896: while(my ($param,$value) = each (%$param_hash)){
3897: next if ($param =~ /^v\./); # Ignore versions...
3898: #
3899: # Just dump the symb=value pairs separated by &
3900: #
3901: $qresult.=$symb.':'.$param.'='.$value.'&';
3902: }
3903: }
3904: chop($qresult);
1.387 albertel 3905: &Reply($client , \$qresult, $userinput);
1.231 foxr 3906: } else {
3907: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3908: "while attempting currentdump\n", $userinput);
3909: }
3910: } else {
3911: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3912: "while attempting currentdump\n", $userinput);
3913: }
3914:
3915: return 1;
3916: }
3917: ®ister_handler("currentdump", \&dump_profile_database, 0, 1, 0);
3918:
3919: #
3920: # Dump a profile database with an optional regular expression
3921: # to match against the keys. In this dump, no effort is made
3922: # to separate symb from version information. Presumably the
3923: # databases that are dumped by this command are of a different
3924: # structure. Need to look at this and improve the documentation of
3925: # both this and the currentdump handler.
3926: # Parameters:
3927: # $cmd - The command keyword.
3928: # $tail - All of the characters after the $cmd:
3929: # These are expected to be a colon
3930: # separated list containing:
3931: # domain/user - identifying the user.
3932: # namespace - identifying the database.
3933: # regexp - optional regular expression
3934: # that is matched against
3935: # database keywords to do
3936: # selective dumps.
1.488 raeburn 3937: # range - optional range of entries
3938: # e.g., 10-20 would return the
3939: # 10th to 19th items, etc.
1.231 foxr 3940: # $client - Channel open on the client.
3941: # Returns:
3942: # 1 - Continue processing.
3943: # Side effects:
3944: # response is written to $client.
3945: #
3946: sub dump_with_regexp {
3947: my ($cmd, $tail, $client) = @_;
3948:
1.494 droeschl 3949: my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.490 droeschl 3950:
3951: if ($res =~ /^error:/) {
3952: Failure($client, \$res, "$cmd:$tail");
3953: } else {
3954: Reply($client, \$res, "$cmd:$tail");
3955: }
1.231 foxr 3956:
3957: return 1;
3958: }
3959: ®ister_handler("dump", \&dump_with_regexp, 0, 1, 0);
3960:
1.568 raeburn 3961: #
3962: # Process the encrypted dump request. Original call should
3963: # be from lonnet::dump() with seventh arg ($encrypt) set to
3964: # 1, to ensure that both request and response are encrypted.
3965: #
3966: # Parameters:
3967: # $cmd - Command keyword of request (edump).
3968: # $tail - Tail of the command.
3969: # See &dump_with_regexp for more
3970: # information about this.
3971: # $client - File open on the client.
3972: # Returns:
3973: # 1 - Continue processing
3974: # 0 - server should exit.
3975: #
3976:
3977: sub encrypted_dump_with_regexp {
3978: my ($cmd, $tail, $client) = @_;
3979: my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
3980:
3981: if ($res =~ /^error:/) {
3982: Failure($client, \$res, "$cmd:$tail");
3983: } else {
3984: if ($cipher) {
3985: my $cmdlength=length($res);
3986: $res.=" ";
3987: my $encres='';
3988: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
3989: $encres.= unpack("H16",
3990: $cipher->encrypt(substr($res,
3991: $encidx,
3992: 8)));
3993: }
3994: &Reply( $client,"enc:$cmdlength:$encres\n","$cmd:$tail");
3995: } else {
3996: &Failure( $client, "error:no_key\n","$cmd:$tail");
3997: }
3998: }
3999: }
4000: ®ister_handler("edump", \&encrypted_dump_with_regexp, 0, 1, 0);
4001:
1.231 foxr 4002: # Store a set of key=value pairs associated with a versioned name.
4003: #
4004: # Parameters:
4005: # $cmd - Request command keyword.
4006: # $tail - Tail of the request. This is a colon
4007: # separated list containing:
4008: # domain/user - User and authentication domain.
4009: # namespace - Name of the database being modified
4010: # rid - Resource keyword to modify.
4011: # what - new value associated with rid.
1.512 raeburn 4012: # laststore - (optional) version=timestamp
4013: # for most recent transaction for rid
4014: # in namespace, when cstore was called
1.231 foxr 4015: #
4016: # $client - Socket open on the client.
4017: #
4018: #
4019: # Returns:
4020: # 1 (keep on processing).
4021: # Side-Effects:
4022: # Writes to the client
1.512 raeburn 4023: # Successful storage will cause either 'ok', or, if $laststore was included
4024: # in the tail of the request, and the version number for the last transaction
4025: # is larger than the version in $laststore, delay:$numtrans , where $numtrans
4026: # is the number of store evevnts recorded for rid in namespace since
4027: # lonnet::store() was called by the client.
4028: #
1.231 foxr 4029: sub store_handler {
4030: my ($cmd, $tail, $client) = @_;
4031:
4032: my $userinput = "$cmd:$tail";
1.512 raeburn 4033: chomp($tail);
4034: my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231 foxr 4035: if ($namespace ne 'roles') {
4036:
4037: my @pairs=split(/\&/,$what);
4038: my $hashref = &tie_user_hash($udom, $uname, $namespace,
1.268 albertel 4039: &GDBM_WRCREAT(), "S",
1.231 foxr 4040: "$rid:$what");
4041: if ($hashref) {
4042: my $now = time;
1.512 raeburn 4043: my $numtrans;
4044: if ($laststore) {
4045: my ($previousversion,$previoustime) = split(/\=/,$laststore);
4046: my ($lastversion,$lasttime) = (0,0);
4047: $lastversion = $hashref->{"version:$rid"};
4048: if ($lastversion) {
4049: $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
4050: }
4051: if (($previousversion) && ($previousversion !~ /\D/)) {
4052: if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
4053: $numtrans = $lastversion - $previousversion;
4054: }
4055: } elsif ($lastversion) {
4056: $numtrans = $lastversion;
4057: }
4058: if ($numtrans) {
4059: $numtrans =~ s/D//g;
4060: }
4061: }
1.231 foxr 4062: $hashref->{"version:$rid"}++;
4063: my $version=$hashref->{"version:$rid"};
4064: my $allkeys='';
4065: foreach my $pair (@pairs) {
4066: my ($key,$value)=split(/=/,$pair);
4067: $allkeys.=$key.':';
4068: $hashref->{"$version:$rid:$key"}=$value;
4069: }
4070: $hashref->{"$version:$rid:timestamp"}=$now;
4071: $allkeys.='timestamp';
4072: $hashref->{"$version:keys:$rid"}=$allkeys;
1.311 albertel 4073: if (&untie_user_hash($hashref)) {
1.512 raeburn 4074: my $msg = 'ok';
4075: if ($numtrans) {
4076: $msg = 'delay:'.$numtrans;
4077: }
4078: &Reply($client, "$msg\n", $userinput);
1.231 foxr 4079: } else {
4080: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4081: "while attempting store\n", $userinput);
4082: }
4083: } else {
4084: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4085: "while attempting store\n", $userinput);
4086: }
4087: } else {
4088: &Failure($client, "refused\n", $userinput);
4089: }
4090:
4091: return 1;
4092: }
4093: ®ister_handler("store", \&store_handler, 0, 1, 0);
1.263 albertel 4094:
1.323 albertel 4095: # Modify a set of key=value pairs associated with a versioned name.
4096: #
4097: # Parameters:
4098: # $cmd - Request command keyword.
4099: # $tail - Tail of the request. This is a colon
4100: # separated list containing:
4101: # domain/user - User and authentication domain.
4102: # namespace - Name of the database being modified
4103: # rid - Resource keyword to modify.
4104: # v - Version item to modify
4105: # what - new value associated with rid.
4106: #
4107: # $client - Socket open on the client.
4108: #
4109: #
4110: # Returns:
4111: # 1 (keep on processing).
4112: # Side-Effects:
4113: # Writes to the client
4114: sub putstore_handler {
4115: my ($cmd, $tail, $client) = @_;
4116:
4117: my $userinput = "$cmd:$tail";
4118:
4119: my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
4120: if ($namespace ne 'roles') {
4121:
4122: chomp($what);
4123: my $hashref = &tie_user_hash($udom, $uname, $namespace,
4124: &GDBM_WRCREAT(), "M",
4125: "$rid:$v:$what");
4126: if ($hashref) {
4127: my $now = time;
4128: my %data = &hash_extract($what);
4129: my @allkeys;
4130: while (my($key,$value) = each(%data)) {
4131: push(@allkeys,$key);
4132: $hashref->{"$v:$rid:$key"} = $value;
4133: }
4134: my $allkeys = join(':',@allkeys);
4135: $hashref->{"$v:keys:$rid"}=$allkeys;
4136:
4137: if (&untie_user_hash($hashref)) {
4138: &Reply($client, "ok\n", $userinput);
4139: } else {
4140: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4141: "while attempting store\n", $userinput);
4142: }
4143: } else {
4144: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4145: "while attempting store\n", $userinput);
4146: }
4147: } else {
4148: &Failure($client, "refused\n", $userinput);
4149: }
4150:
4151: return 1;
4152: }
4153: ®ister_handler("putstore", \&putstore_handler, 0, 1, 0);
4154:
4155: sub hash_extract {
4156: my ($str)=@_;
4157: my %hash;
4158: foreach my $pair (split(/\&/,$str)) {
4159: my ($key,$value)=split(/=/,$pair);
4160: $hash{$key}=$value;
4161: }
4162: return (%hash);
4163: }
4164: sub hash_to_str {
4165: my ($hash_ref)=@_;
4166: my $str;
4167: foreach my $key (keys(%$hash_ref)) {
4168: $str.=$key.'='.$hash_ref->{$key}.'&';
4169: }
4170: $str=~s/\&$//;
4171: return $str;
4172: }
4173:
1.231 foxr 4174: #
4175: # Dump out all versions of a resource that has key=value pairs associated
4176: # with it for each version. These resources are built up via the store
4177: # command.
4178: #
4179: # Parameters:
4180: # $cmd - Command keyword.
4181: # $tail - Remainder of the request which consists of:
4182: # domain/user - User and auth. domain.
4183: # namespace - name of resource database.
4184: # rid - Resource id.
4185: # $client - socket open on the client.
4186: #
4187: # Returns:
4188: # 1 indicating the caller should not yet exit.
4189: # Side-effects:
4190: # Writes a reply to the client.
4191: # The reply is a string of the following shape:
4192: # version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
4193: # Where the 1 above represents version 1.
4194: # this continues for all pairs of keys in all versions.
4195: #
4196: #
4197: #
4198: #
4199: sub restore_handler {
4200: my ($cmd, $tail, $client) = @_;
4201:
4202: my $userinput = "$cmd:$tail"; # Only used for logging purposes.
1.351 banghart 4203: my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352 albertel 4204: $namespace=~s/\//\_/g;
1.350 albertel 4205: $namespace = &LONCAPA::clean_username($namespace);
1.349 albertel 4206:
1.231 foxr 4207: chomp($rid);
4208: my $qresult='';
1.309 albertel 4209: my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
4210: if ($hashref) {
4211: my $version=$hashref->{"version:$rid"};
1.231 foxr 4212: $qresult.="version=$version&";
4213: my $scope;
4214: for ($scope=1;$scope<=$version;$scope++) {
1.309 albertel 4215: my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231 foxr 4216: my @keys=split(/:/,$vkeys);
4217: my $key;
4218: $qresult.="$scope:keys=$vkeys&";
4219: foreach $key (@keys) {
1.309 albertel 4220: $qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231 foxr 4221: }
4222: }
1.311 albertel 4223: if (&untie_user_hash($hashref)) {
1.231 foxr 4224: $qresult=~s/\&$//;
1.387 albertel 4225: &Reply( $client, \$qresult, $userinput);
1.231 foxr 4226: } else {
4227: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4228: "while attempting restore\n", $userinput);
4229: }
4230: } else {
4231: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4232: "while attempting restore\n", $userinput);
4233: }
4234:
4235: return 1;
4236:
4237:
4238: }
4239: ®ister_handler("restore", \&restore_handler, 0,1,0);
1.234 foxr 4240:
4241: #
1.324 raeburn 4242: # Add a chat message to a synchronous discussion board.
1.234 foxr 4243: #
4244: # Parameters:
4245: # $cmd - Request keyword.
4246: # $tail - Tail of the command. A colon separated list
4247: # containing:
4248: # cdom - Domain on which the chat board lives
1.324 raeburn 4249: # cnum - Course containing the chat board.
4250: # newpost - Body of the posting.
4251: # group - Optional group, if chat board is only
4252: # accessible in a group within the course
1.234 foxr 4253: # $client - Socket open on the client.
4254: # Returns:
4255: # 1 - Indicating caller should keep on processing.
4256: #
4257: # Side-effects:
4258: # writes a reply to the client.
4259: #
4260: #
4261: sub send_chat_handler {
4262: my ($cmd, $tail, $client) = @_;
4263:
4264:
4265: my $userinput = "$cmd:$tail";
4266:
1.324 raeburn 4267: my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
4268: &chat_add($cdom,$cnum,$newpost,$group);
1.234 foxr 4269: &Reply($client, "ok\n", $userinput);
4270:
4271: return 1;
4272: }
4273: ®ister_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263 albertel 4274:
1.234 foxr 4275: #
1.324 raeburn 4276: # Retrieve the set of chat messages from a discussion board.
1.234 foxr 4277: #
4278: # Parameters:
4279: # $cmd - Command keyword that initiated the request.
4280: # $tail - Remainder of the request after the command
4281: # keyword. In this case a colon separated list of
4282: # chat domain - Which discussion board.
4283: # chat id - Discussion thread(?)
4284: # domain/user - Authentication domain and username
4285: # of the requesting person.
1.324 raeburn 4286: # group - Optional course group containing
4287: # the board.
1.234 foxr 4288: # $client - Socket open on the client program.
4289: # Returns:
4290: # 1 - continue processing
4291: # Side effects:
4292: # Response is written to the client.
4293: #
4294: sub retrieve_chat_handler {
4295: my ($cmd, $tail, $client) = @_;
4296:
4297:
4298: my $userinput = "$cmd:$tail";
4299:
1.324 raeburn 4300: my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234 foxr 4301: my $reply='';
1.324 raeburn 4302: foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234 foxr 4303: $reply.=&escape($_).':';
4304: }
4305: $reply=~s/\:$//;
1.387 albertel 4306: &Reply($client, \$reply, $userinput);
1.234 foxr 4307:
4308:
4309: return 1;
4310: }
4311: ®ister_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
4312:
4313: #
4314: # Initiate a query of an sql database. SQL query repsonses get put in
4315: # a file for later retrieval. This prevents sql query results from
4316: # bottlenecking the system. Note that with loncnew, perhaps this is
4317: # less of an issue since multiple outstanding requests can be concurrently
4318: # serviced.
4319: #
4320: # Parameters:
1.535 raeburn 4321: # $cmd - Command keyword that initiated the request.
1.234 foxr 4322: # $tail - Remainder of the command after the keyword.
4323: # For this function, this consists of a query and
4324: # 3 arguments that are self-documentingly labelled
4325: # in the original arg1, arg2, arg3.
4326: # $client - Socket open on the client.
4327: # Return:
4328: # 1 - Indicating processing should continue.
4329: # Side-effects:
4330: # a reply is written to $client.
4331: #
4332: sub send_query_handler {
4333: my ($cmd, $tail, $client) = @_;
4334:
4335: my $userinput = "$cmd:$tail";
4336:
4337: my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
4338: $query=~s/\n*$//g;
1.534 raeburn 4339: if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
4340: my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
4341: my $earlyout;
4342: if (ref($usersearchconf) eq 'HASH') {
4343: if ($currentdomainid eq $clienthomedom) {
4344: if ($query eq 'usersearch') {
4345: if ($usersearchconf->{'lcavailable'} eq '0') {
4346: $earlyout = 1;
4347: }
4348: } else {
4349: if ($usersearchconf->{'available'} eq '0') {
4350: $earlyout = 1;
4351: }
4352: }
4353: } else {
4354: if ($query eq 'usersearch') {
4355: if ($usersearchconf->{'lclocalonly'}) {
4356: $earlyout = 1;
4357: }
4358: } else {
4359: if ($usersearchconf->{'localonly'}) {
4360: $earlyout = 1;
4361: }
4362: }
4363: }
4364: }
4365: if ($earlyout) {
4366: &Reply($client, "query_not_authorized\n");
4367: return 1;
4368: }
4369: }
1.234 foxr 4370: &Reply($client, "". &sql_reply("$clientname\&$query".
4371: "\&$arg1"."\&$arg2"."\&$arg3")."\n",
4372: $userinput);
4373:
4374: return 1;
4375: }
4376: ®ister_handler("querysend", \&send_query_handler, 0, 1, 0);
4377:
4378: #
4379: # Add a reply to an sql query. SQL queries are done asyncrhonously.
4380: # The query is submitted via a "querysend" transaction.
4381: # There it is passed on to the lonsql daemon, queued and issued to
4382: # mysql.
4383: # This transaction is invoked when the sql transaction is complete
4384: # it stores the query results in flie and indicates query completion.
4385: # presumably local software then fetches this response... I'm guessing
4386: # the sequence is: lonc does a querysend, we ask lonsql to do it.
4387: # lonsql on completion of the query interacts with the lond of our
4388: # client to do a query reply storing two files:
4389: # - id - The results of the query.
4390: # - id.end - Indicating the transaction completed.
4391: # NOTE: id is a unique id assigned to the query and querysend time.
4392: # Parameters:
4393: # $cmd - Command keyword that initiated this request.
4394: # $tail - Remainder of the tail. In this case that's a colon
4395: # separated list containing the query Id and the
4396: # results of the query.
4397: # $client - Socket open on the client.
4398: # Return:
4399: # 1 - Indicating that we should continue processing.
4400: # Side effects:
4401: # ok written to the client.
4402: #
4403: sub reply_query_handler {
4404: my ($cmd, $tail, $client) = @_;
4405:
4406:
4407: my $userinput = "$cmd:$tail";
4408:
1.339 albertel 4409: my ($id,$reply)=split(/:/,$tail);
1.234 foxr 4410: my $store;
4411: my $execdir=$perlvar{'lonDaemons'};
4412: if ($store=IO::File->new(">$execdir/tmp/$id")) {
4413: $reply=~s/\&/\n/g;
4414: print $store $reply;
4415: close $store;
4416: my $store2=IO::File->new(">$execdir/tmp/$id.end");
4417: print $store2 "done\n";
4418: close $store2;
4419: &Reply($client, "ok\n", $userinput);
4420: } else {
4421: &Failure($client, "error: ".($!+0)
4422: ." IO::File->new Failed ".
4423: "while attempting queryreply\n", $userinput);
4424: }
4425:
4426:
4427: return 1;
4428: }
4429: ®ister_handler("queryreply", \&reply_query_handler, 0, 1, 0);
4430:
4431: #
4432: # Process the courseidput request. Not quite sure what this means
4433: # at the system level sense. It appears a gdbm file in the
4434: # /home/httpd/lonUsers/$domain/nohist_courseids is tied and
4435: # a set of entries made in that database.
4436: #
4437: # Parameters:
4438: # $cmd - The command keyword that initiated this request.
4439: # $tail - Tail of the command. In this case consists of a colon
4440: # separated list contaning the domain to apply this to and
4441: # an ampersand separated list of keyword=value pairs.
1.272 raeburn 4442: # Each value is a colon separated list that includes:
4443: # description, institutional code and course owner.
4444: # For backward compatibility with versions included
4445: # in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
4446: # code and/or course owner are preserved from the existing
4447: # record when writing a new record in response to 1.1 or
4448: # 1.2 implementations of lonnet::flushcourselogs().
4449: #
1.234 foxr 4450: # $client - Socket open on the client.
4451: # Returns:
4452: # 1 - indicating that processing should continue
4453: #
4454: # Side effects:
4455: # reply is written to the client.
4456: #
4457: sub put_course_id_handler {
4458: my ($cmd, $tail, $client) = @_;
4459:
4460:
4461: my $userinput = "$cmd:$tail";
4462:
1.266 raeburn 4463: my ($udom, $what) = split(/:/, $tail,2);
1.234 foxr 4464: chomp($what);
4465: my $now=time;
4466: my @pairs=split(/\&/,$what);
4467:
4468: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
4469: if ($hashref) {
4470: foreach my $pair (@pairs) {
1.271 raeburn 4471: my ($key,$courseinfo) = split(/=/,$pair,2);
4472: $courseinfo =~ s/=/:/g;
1.384 raeburn 4473: if (defined($hashref->{$key})) {
4474: my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
4475: if (ref($value) eq 'HASH') {
4476: my @items = ('description','inst_code','owner','type');
4477: my @new_items = split(/:/,$courseinfo,-1);
4478: my %storehash;
4479: for (my $i=0; $i<@new_items; $i++) {
1.391 raeburn 4480: $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384 raeburn 4481: }
4482: $hashref->{$key} =
4483: &Apache::lonnet::freeze_escape(\%storehash);
4484: my $unesc_key = &unescape($key);
4485: $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
4486: next;
1.383 raeburn 4487: }
1.384 raeburn 4488: }
4489: my @current_items = split(/:/,$hashref->{$key},-1);
4490: shift(@current_items); # remove description
4491: pop(@current_items); # remove last access
4492: my $numcurrent = scalar(@current_items);
4493: if ($numcurrent > 3) {
4494: $numcurrent = 3;
4495: }
4496: my @new_items = split(/:/,$courseinfo,-1);
4497: my $numnew = scalar(@new_items);
4498: if ($numcurrent > 0) {
4499: if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2
4500: for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
4501: $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333 raeburn 4502: }
1.272 raeburn 4503: }
4504: }
1.384 raeburn 4505: $hashref->{$key}=$courseinfo.':'.$now;
1.234 foxr 4506: }
1.311 albertel 4507: if (&untie_domain_hash($hashref)) {
1.253 foxr 4508: &Reply( $client, "ok\n", $userinput);
1.234 foxr 4509: } else {
1.253 foxr 4510: &Failure($client, "error: ".($!+0)
1.234 foxr 4511: ." untie(GDBM) Failed ".
4512: "while attempting courseidput\n", $userinput);
4513: }
4514: } else {
1.253 foxr 4515: &Failure($client, "error: ".($!+0)
1.234 foxr 4516: ." tie(GDBM) Failed ".
4517: "while attempting courseidput\n", $userinput);
4518: }
4519:
4520: return 1;
4521: }
4522: ®ister_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
4523:
1.383 raeburn 4524: sub put_course_id_hash_handler {
4525: my ($cmd, $tail, $client) = @_;
4526: my $userinput = "$cmd:$tail";
1.384 raeburn 4527: my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383 raeburn 4528: chomp($what);
4529: my $now=time;
4530: my @pairs=split(/\&/,$what);
1.384 raeburn 4531: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383 raeburn 4532: if ($hashref) {
4533: foreach my $pair (@pairs) {
4534: my ($key,$value)=split(/=/,$pair);
1.384 raeburn 4535: my $unesc_key = &unescape($key);
4536: if ($mode ne 'timeonly') {
4537: if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
4538: my $curritems = &Apache::lonnet::thaw_unescape($key);
4539: if (ref($curritems) ne 'HASH') {
4540: my @current_items = split(/:/,$hashref->{$key},-1);
4541: my $lasttime = pop(@current_items);
4542: $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
4543: } else {
4544: $hashref->{&escape('lasttime:'.$unesc_key)} = '';
4545: }
4546: }
4547: $hashref->{$key} = $value;
4548: }
4549: if ($mode ne 'notime') {
4550: $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
4551: }
1.383 raeburn 4552: }
4553: if (&untie_domain_hash($hashref)) {
4554: &Reply($client, "ok\n", $userinput);
4555: } else {
4556: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4557: "while attempting courseidputhash\n", $userinput);
4558: }
4559: } else {
4560: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4561: "while attempting courseidputhash\n", $userinput);
4562: }
4563: return 1;
4564: }
4565: ®ister_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
4566:
1.234 foxr 4567: # Retrieves the value of a course id resource keyword pattern
4568: # defined since a starting date. Both the starting date and the
4569: # keyword pattern are optional. If the starting date is not supplied it
4570: # is treated as the beginning of time. If the pattern is not found,
4571: # it is treatred as "." matching everything.
4572: #
4573: # Parameters:
4574: # $cmd - Command keyword that resulted in us being dispatched.
4575: # $tail - The remainder of the command that, in this case, consists
4576: # of a colon separated list of:
4577: # domain - The domain in which the course database is
4578: # defined.
4579: # since - Optional parameter describing the minimum
4580: # time of definition(?) of the resources that
4581: # will match the dump.
4582: # description - regular expression that is used to filter
4583: # the dump. Only keywords matching this regexp
4584: # will be used.
1.272 raeburn 4585: # institutional code - optional supplied code to filter
4586: # the dump. Only courses with an institutional code
4587: # that match the supplied code will be returned.
1.336 raeburn 4588: # owner - optional supplied username and domain of owner to
4589: # filter the dump. Only courses for which the course
4590: # owner matches the supplied username and/or domain
4591: # will be returned. Pre-2.2.0 legacy entries from
4592: # nohist_courseiddump will only contain usernames.
1.384 raeburn 4593: # type - optional parameter for selection
1.418 raeburn 4594: # regexp_ok - if 1 or -1 allow the supplied institutional code
4595: # filter to behave as a regular expression:
4596: # 1 will not exclude the course if the instcode matches the RE
4597: # -1 will exclude the course if the instcode matches the RE
1.384 raeburn 4598: # rtn_as_hash - whether to return the information available for
4599: # each matched item as a frozen hash of all
4600: # key, value pairs in the item's hash, or as a
4601: # colon-separated list of (in order) description,
4602: # institutional code, and course owner.
1.404 raeburn 4603: # selfenrollonly - filter by courses allowing self-enrollment
4604: # now or in the future (selfenrollonly = 1).
4605: # catfilter - filter by course category, assigned to a course
4606: # using manually defined categories (i.e., not
1.407 raeburn 4607: # self-cataloging based on on institutional code).
1.404 raeburn 4608: # showhidden - include course in results even if course
1.407 raeburn 4609: # was set to be excluded from course catalog (DC only).
1.404 raeburn 4610: # caller - if set to 'coursecatalog', courses set to be hidden
4611: # from course catalog will be excluded from results (unless
4612: # overridden by "showhidden".
1.427 raeburn 4613: # cloner - escaped username:domain of course cloner (if picking course to
1.419 raeburn 4614: # clone).
4615: # cc_clone_list - escaped comma separated list of courses for which
4616: # course cloner has active CC role (and so can clone
4617: # automatically).
1.427 raeburn 4618: # cloneonly - filter by courses for which cloner has rights to clone.
4619: # createdbefore - include courses for which creation date preceeded this date.
4620: # createdafter - include courses for which creation date followed this date.
4621: # creationcontext - include courses created in specified context
1.404 raeburn 4622: #
1.445 raeburn 4623: # domcloner - flag to indicate if user can create CCs in course's domain.
1.505 raeburn 4624: # If so, ability to clone course is automatic.
4625: # hasuniquecode - filter by courses for which a six character unique code has
4626: # been set.
1.445 raeburn 4627: #
1.234 foxr 4628: # $client - The socket open on the client.
4629: # Returns:
4630: # 1 - Continue processing.
4631: # Side Effects:
4632: # a reply is written to $client.
4633: sub dump_course_id_handler {
4634: my ($cmd, $tail, $client) = @_;
1.494 droeschl 4635:
4636: my $res = LONCAPA::Lond::dump_course_id_handler($tail);
4637: if ($res =~ /^error:/) {
4638: Failure($client, \$res, "$cmd:$tail");
4639: } else {
4640: Reply($client, \$res, "$cmd:$tail");
4641: }
4642:
4643: return 1;
4644:
4645: #TODO remove
1.234 foxr 4646: my $userinput = "$cmd:$tail";
4647:
1.333 raeburn 4648: my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404 raeburn 4649: $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427 raeburn 4650: $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.505 raeburn 4651: $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397 raeburn 4652: my $now = time;
1.419 raeburn 4653: my ($cloneruname,$clonerudom,%cc_clone);
1.234 foxr 4654: if (defined($description)) {
4655: $description=&unescape($description);
4656: } else {
4657: $description='.';
4658: }
1.266 raeburn 4659: if (defined($instcodefilter)) {
4660: $instcodefilter=&unescape($instcodefilter);
4661: } else {
4662: $instcodefilter='.';
4663: }
1.336 raeburn 4664: my ($ownerunamefilter,$ownerdomfilter);
1.266 raeburn 4665: if (defined($ownerfilter)) {
4666: $ownerfilter=&unescape($ownerfilter);
1.336 raeburn 4667: if ($ownerfilter ne '.' && defined($ownerfilter)) {
4668: if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
4669: $ownerunamefilter = $1;
4670: $ownerdomfilter = $2;
4671: } else {
4672: $ownerunamefilter = $ownerfilter;
4673: $ownerdomfilter = '';
4674: }
4675: }
1.266 raeburn 4676: } else {
4677: $ownerfilter='.';
4678: }
1.336 raeburn 4679:
1.282 raeburn 4680: if (defined($coursefilter)) {
4681: $coursefilter=&unescape($coursefilter);
4682: } else {
4683: $coursefilter='.';
4684: }
1.333 raeburn 4685: if (defined($typefilter)) {
4686: $typefilter=&unescape($typefilter);
4687: } else {
4688: $typefilter='.';
4689: }
1.344 raeburn 4690: if (defined($regexp_ok)) {
4691: $regexp_ok=&unescape($regexp_ok);
4692: }
1.401 raeburn 4693: if (defined($catfilter)) {
4694: $catfilter=&unescape($catfilter);
4695: }
1.419 raeburn 4696: if (defined($cloner)) {
4697: $cloner = &unescape($cloner);
4698: ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/);
4699: }
4700: if (defined($cc_clone_list)) {
4701: $cc_clone_list = &unescape($cc_clone_list);
4702: my @cc_cloners = split('&',$cc_clone_list);
4703: foreach my $cid (@cc_cloners) {
4704: my ($clonedom,$clonenum) = split(':',$cid);
4705: next if ($clonedom ne $udom);
4706: $cc_clone{$clonedom.'_'.$clonenum} = 1;
4707: }
4708: }
1.431 raeburn 4709: if ($createdbefore ne '') {
1.427 raeburn 4710: $createdbefore = &unescape($createdbefore);
4711: } else {
4712: $createdbefore = 0;
4713: }
1.431 raeburn 4714: if ($createdafter ne '') {
1.427 raeburn 4715: $createdafter = &unescape($createdafter);
4716: } else {
4717: $createdafter = 0;
4718: }
1.431 raeburn 4719: if ($creationcontext ne '') {
1.427 raeburn 4720: $creationcontext = &unescape($creationcontext);
4721: } else {
4722: $creationcontext = '.';
4723: }
1.505 raeburn 4724: unless ($hasuniquecode) {
4725: $hasuniquecode = '.';
4726: }
1.384 raeburn 4727: my $unpack = 1;
1.485 raeburn 4728: if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' &&
1.384 raeburn 4729: $typefilter eq '.') {
4730: $unpack = 0;
4731: }
4732: if (!defined($since)) { $since=0; }
1.234 foxr 4733: my $qresult='';
4734: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
4735: if ($hashref) {
1.384 raeburn 4736: while (my ($key,$value) = each(%$hashref)) {
1.397 raeburn 4737: my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427 raeburn 4738: %unesc_val,$selfenroll_end,$selfenroll_types,$created,
4739: $context);
1.384 raeburn 4740: $unesc_key = &unescape($key);
4741: if ($unesc_key =~ /^lasttime:/) {
4742: next;
4743: } else {
4744: $lasttime_key = &escape('lasttime:'.$unesc_key);
4745: }
4746: if ($hashref->{$lasttime_key} ne '') {
4747: $lasttime = $hashref->{$lasttime_key};
4748: next if ($lasttime<$since);
4749: }
1.419 raeburn 4750: my ($canclone,$valchange);
1.384 raeburn 4751: my $items = &Apache::lonnet::thaw_unescape($value);
4752: if (ref($items) eq 'HASH') {
1.429 raeburn 4753: if ($hashref->{$lasttime_key} eq '') {
1.430 raeburn 4754: next if ($since > 1);
1.429 raeburn 4755: }
1.384 raeburn 4756: $is_hash = 1;
1.445 raeburn 4757: if ($domcloner) {
4758: $canclone = 1;
4759: } elsif (defined($clonerudom)) {
1.419 raeburn 4760: if ($items->{'cloners'}) {
4761: my @cloneable = split(',',$items->{'cloners'});
4762: if (@cloneable) {
4763: if (grep(/^\*$/,@cloneable)) {
4764: $canclone = 1;
4765: } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
4766: $canclone = 1;
4767: } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
4768: $canclone = 1;
4769: }
4770: }
4771: unless ($canclone) {
4772: if ($cloneruname ne '' && $clonerudom ne '') {
4773: if ($cc_clone{$unesc_key}) {
4774: $canclone = 1;
4775: $items->{'cloners'} .= ','.$cloneruname.':'.
4776: $clonerudom;
4777: $valchange = 1;
4778: }
4779: }
4780: }
4781: } elsif (defined($cloneruname)) {
4782: if ($cc_clone{$unesc_key}) {
4783: $canclone = 1;
4784: $items->{'cloners'} = $cloneruname.':'.$clonerudom;
4785: $valchange = 1;
4786: }
1.437 raeburn 4787: unless ($canclone) {
4788: if ($items->{'owner'} =~ /:/) {
4789: if ($items->{'owner'} eq $cloner) {
4790: $canclone = 1;
4791: }
1.444 raeburn 4792: } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437 raeburn 4793: $canclone = 1;
4794: }
4795: if ($canclone) {
4796: $items->{'cloners'} = $cloneruname.':'.$clonerudom;
4797: $valchange = 1;
4798: }
4799: }
1.419 raeburn 4800: }
4801: }
1.384 raeburn 4802: if ($unpack || !$rtn_as_hash) {
4803: $unesc_val{'descr'} = $items->{'description'};
4804: $unesc_val{'inst_code'} = $items->{'inst_code'};
4805: $unesc_val{'owner'} = $items->{'owner'};
4806: $unesc_val{'type'} = $items->{'type'};
1.419 raeburn 4807: $unesc_val{'cloners'} = $items->{'cloners'};
1.427 raeburn 4808: $unesc_val{'created'} = $items->{'created'};
4809: $unesc_val{'context'} = $items->{'context'};
1.404 raeburn 4810: }
4811: $selfenroll_types = $items->{'selfenroll_types'};
4812: $selfenroll_end = $items->{'selfenroll_end_date'};
1.427 raeburn 4813: $created = $items->{'created'};
4814: $context = $items->{'context'};
1.505 raeburn 4815: if ($hasuniquecode ne '.') {
4816: next unless ($items->{'uniquecode'});
4817: }
1.404 raeburn 4818: if ($selfenrollonly) {
4819: next if (!$selfenroll_types);
4820: if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
4821: next;
1.397 raeburn 4822: }
1.404 raeburn 4823: }
1.427 raeburn 4824: if ($creationcontext ne '.') {
4825: next if (($context ne '') && ($context ne $creationcontext));
4826: }
4827: if ($createdbefore > 0) {
4828: next if (($created eq '') || ($created > $createdbefore));
4829: }
4830: if ($createdafter > 0) {
4831: next if (($created eq '') || ($created <= $createdafter));
4832: }
1.404 raeburn 4833: if ($catfilter ne '') {
1.406 raeburn 4834: next if ($items->{'categories'} eq '');
4835: my @categories = split('&',$items->{'categories'});
1.407 raeburn 4836: next if (@categories == 0);
4837: my @subcats = split('&',$catfilter);
4838: my $matchcat = 0;
4839: foreach my $cat (@categories) {
4840: if (grep(/^\Q$cat\E$/,@subcats)) {
4841: $matchcat = 1;
4842: last;
4843: }
4844: }
4845: next if (!$matchcat);
1.404 raeburn 4846: }
4847: if ($caller eq 'coursecatalog') {
1.405 raeburn 4848: if ($items->{'hidefromcat'} eq 'yes') {
4849: next if !$showhidden;
1.401 raeburn 4850: }
1.384 raeburn 4851: }
1.383 raeburn 4852: } else {
1.401 raeburn 4853: next if ($catfilter ne '');
1.419 raeburn 4854: next if ($selfenrollonly);
1.427 raeburn 4855: next if ($createdbefore || $createdafter);
4856: next if ($creationcontext ne '.');
1.419 raeburn 4857: if ((defined($clonerudom)) && (defined($cloneruname))) {
4858: if ($cc_clone{$unesc_key}) {
4859: $canclone = 1;
4860: $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
4861: }
4862: }
1.384 raeburn 4863: $is_hash = 0;
1.388 raeburn 4864: my @courseitems = split(/:/,$value);
1.403 raeburn 4865: $lasttime = pop(@courseitems);
1.402 raeburn 4866: if ($hashref->{$lasttime_key} eq '') {
4867: next if ($lasttime<$since);
4868: }
1.384 raeburn 4869: ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383 raeburn 4870: }
1.419 raeburn 4871: if ($cloneonly) {
4872: next unless ($canclone);
4873: }
1.266 raeburn 4874: my $match = 1;
1.384 raeburn 4875: if ($description ne '.') {
4876: if (!$is_hash) {
4877: $unesc_val{'descr'} = &unescape($val{'descr'});
4878: }
4879: if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266 raeburn 4880: $match = 0;
1.384 raeburn 4881: }
1.266 raeburn 4882: }
1.384 raeburn 4883: if ($instcodefilter ne '.') {
4884: if (!$is_hash) {
4885: $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
4886: }
1.418 raeburn 4887: if ($regexp_ok == 1) {
1.384 raeburn 4888: if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344 raeburn 4889: $match = 0;
4890: }
1.418 raeburn 4891: } elsif ($regexp_ok == -1) {
4892: if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
4893: $match = 0;
4894: }
1.344 raeburn 4895: } else {
1.384 raeburn 4896: if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344 raeburn 4897: $match = 0;
4898: }
1.266 raeburn 4899: }
1.234 foxr 4900: }
1.384 raeburn 4901: if ($ownerfilter ne '.') {
4902: if (!$is_hash) {
4903: $unesc_val{'owner'} = &unescape($val{'owner'});
4904: }
1.336 raeburn 4905: if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384 raeburn 4906: if ($unesc_val{'owner'} =~ /:/) {
4907: if (eval{$unesc_val{'owner'} !~
4908: /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336 raeburn 4909: $match = 0;
4910: }
4911: } else {
1.384 raeburn 4912: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336 raeburn 4913: $match = 0;
4914: }
4915: }
4916: } elsif ($ownerunamefilter ne '') {
1.384 raeburn 4917: if ($unesc_val{'owner'} =~ /:/) {
4918: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336 raeburn 4919: $match = 0;
4920: }
4921: } else {
1.384 raeburn 4922: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336 raeburn 4923: $match = 0;
4924: }
4925: }
4926: } elsif ($ownerdomfilter ne '') {
1.384 raeburn 4927: if ($unesc_val{'owner'} =~ /:/) {
4928: if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336 raeburn 4929: $match = 0;
4930: }
4931: } else {
4932: if ($ownerdomfilter ne $udom) {
4933: $match = 0;
4934: }
4935: }
1.266 raeburn 4936: }
4937: }
1.384 raeburn 4938: if ($coursefilter ne '.') {
4939: if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282 raeburn 4940: $match = 0;
4941: }
4942: }
1.384 raeburn 4943: if ($typefilter ne '.') {
4944: if (!$is_hash) {
4945: $unesc_val{'type'} = &unescape($val{'type'});
4946: }
4947: if ($unesc_val{'type'} eq '') {
1.333 raeburn 4948: if ($typefilter ne 'Course') {
4949: $match = 0;
4950: }
1.383 raeburn 4951: } else {
1.384 raeburn 4952: if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333 raeburn 4953: $match = 0;
4954: }
4955: }
4956: }
1.266 raeburn 4957: if ($match == 1) {
1.384 raeburn 4958: if ($rtn_as_hash) {
4959: if ($is_hash) {
1.419 raeburn 4960: if ($valchange) {
4961: my $newvalue = &Apache::lonnet::freeze_escape($items);
4962: $qresult.=$key.'='.$newvalue.'&';
4963: } else {
4964: $qresult.=$key.'='.$value.'&';
4965: }
1.384 raeburn 4966: } else {
1.388 raeburn 4967: my %rtnhash = ( 'description' => &unescape($val{'descr'}),
4968: 'inst_code' => &unescape($val{'inst_code'}),
4969: 'owner' => &unescape($val{'owner'}),
4970: 'type' => &unescape($val{'type'}),
1.419 raeburn 4971: 'cloners' => &unescape($val{'cloners'}),
1.384 raeburn 4972: );
4973: my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
4974: $qresult.=$key.'='.$items.'&';
4975: }
1.383 raeburn 4976: } else {
1.384 raeburn 4977: if ($is_hash) {
4978: $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
4979: &escape($unesc_val{'inst_code'}).':'.
4980: &escape($unesc_val{'owner'}).'&';
4981: } else {
4982: $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
4983: ':'.$val{'owner'}.'&';
4984: }
1.383 raeburn 4985: }
1.266 raeburn 4986: }
1.234 foxr 4987: }
1.311 albertel 4988: if (&untie_domain_hash($hashref)) {
1.234 foxr 4989: chop($qresult);
1.387 albertel 4990: &Reply($client, \$qresult, $userinput);
1.234 foxr 4991: } else {
4992: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4993: "while attempting courseiddump\n", $userinput);
4994: }
4995: } else {
4996: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4997: "while attempting courseiddump\n", $userinput);
4998: }
4999: return 1;
5000: }
5001: ®ister_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238 foxr 5002:
1.438 raeburn 5003: sub course_lastaccess_handler {
5004: my ($cmd, $tail, $client) = @_;
5005: my $userinput = "$cmd:$tail";
5006: my ($cdom,$cnum) = split(':',$tail);
5007: my (%lastaccess,$qresult);
5008: my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
5009: if ($hashref) {
5010: while (my ($key,$value) = each(%$hashref)) {
5011: my ($unesc_key,$lasttime);
5012: $unesc_key = &unescape($key);
5013: if ($cnum) {
5014: next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
5015: }
5016: if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
5017: $lastaccess{$1} = $value;
5018: } else {
5019: my $items = &Apache::lonnet::thaw_unescape($value);
5020: if (ref($items) eq 'HASH') {
5021: unless ($lastaccess{$unesc_key}) {
5022: $lastaccess{$unesc_key} = '';
5023: }
5024: } else {
5025: my @courseitems = split(':',$value);
5026: $lastaccess{$unesc_key} = pop(@courseitems);
5027: }
5028: }
5029: }
5030: foreach my $cid (sort(keys(%lastaccess))) {
5031: $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&';
5032: }
5033: if (&untie_domain_hash($hashref)) {
5034: if ($qresult) {
5035: chop($qresult);
5036: }
5037: &Reply($client, \$qresult, $userinput);
5038: } else {
5039: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5040: "while attempting lastacourseaccess\n", $userinput);
5041: }
5042: } else {
5043: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5044: "while attempting lastcourseaccess\n", $userinput);
5045: }
5046: return 1;
5047: }
5048: ®ister_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
5049:
1.561 raeburn 5050: sub course_sessions_handler {
5051: my ($cmd, $tail, $client) = @_;
5052: my $userinput = "$cmd:$tail";
5053: my ($cdom,$cnum,$lastactivity) = split(':',$tail);
5054: my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
5055: my (%sessions,$qresult);
5056: my $now=time;
5057: if (opendir(DIR,$perlvar{'lonIDsDir'})) {
5058: my $filename;
5059: while ($filename=readdir(DIR)) {
5060: next if ($filename=~/^\./);
5061: next if ($filename=~/^publicuser_/);
5062: next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.562 raeburn 5063: if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.561 raeburn 5064: my ($uname,$udom) = ($1,$2);
1.562 raeburn 5065: next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.561 raeburn 5066: my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
5067: if ($lastactivity < 0) {
1.563 raeburn 5068: next if ($mtime-$now > $lastactivity);
1.561 raeburn 5069: } else {
1.563 raeburn 5070: next if ($now-$mtime > $lastactivity);
1.561 raeburn 5071: }
5072: $sessions{$uname.':'.$udom} = $mtime;
5073: }
5074: }
5075: closedir(DIR);
5076: }
5077: foreach my $user (keys(%sessions)) {
5078: $qresult.=&escape($user).'='.$sessions{$user}.'&';
5079: }
5080: if ($qresult) {
5081: chop($qresult);
5082: }
5083: &Reply($client, \$qresult, $userinput);
5084: return 1;
5085: }
5086: ®ister_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
5087:
1.238 foxr 5088: #
1.348 raeburn 5089: # Puts an unencrypted entry in a namespace db file at the domain level
5090: #
5091: # Parameters:
5092: # $cmd - The command that got us here.
5093: # $tail - Tail of the command (remaining parameters).
5094: # $client - File descriptor connected to client.
5095: # Returns
5096: # 0 - Requested to exit, caller should shut down.
5097: # 1 - Continue processing.
5098: # Side effects:
5099: # reply is written to $client.
5100: #
5101: sub put_domain_handler {
5102: my ($cmd,$tail,$client) = @_;
5103:
5104: my $userinput = "$cmd:$tail";
5105:
5106: my ($udom,$namespace,$what) =split(/:/,$tail,3);
5107: chomp($what);
5108: my @pairs=split(/\&/,$what);
5109: my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
5110: "P", $what);
5111: if ($hashref) {
5112: foreach my $pair (@pairs) {
5113: my ($key,$value)=split(/=/,$pair);
5114: $hashref->{$key}=$value;
5115: }
5116: if (&untie_domain_hash($hashref)) {
5117: &Reply($client, "ok\n", $userinput);
5118: } else {
5119: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5120: "while attempting putdom\n", $userinput);
5121: }
5122: } else {
5123: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5124: "while attempting putdom\n", $userinput);
5125: }
5126:
5127: return 1;
5128: }
5129: ®ister_handler("putdom", \&put_domain_handler, 0, 1, 0);
5130:
1.517 raeburn 5131: # Updates one or more entries in clickers.db file at the domain level
5132: #
5133: # Parameters:
5134: # $cmd - The command that got us here.
5135: # $tail - Tail of the command (remaining parameters).
5136: # In this case a colon separated list containing:
5137: # (a) the domain for which we are updating the entries,
5138: # (b) the action required -- add or del -- and
5139: # (c) a &-separated list of entries to add or delete.
5140: # $client - File descriptor connected to client.
5141: # Returns
5142: # 1 - Continue processing.
5143: # 0 - Requested to exit, caller should shut down.
5144: # Side effects:
5145: # reply is written to $client.
5146: #
5147:
5148:
5149: sub update_clickers {
5150: my ($cmd, $tail, $client) = @_;
5151:
5152: my $userinput = "$cmd:$tail";
5153: my ($udom,$action,$what) =split(/:/,$tail,3);
5154: chomp($what);
5155:
5156: my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
5157: "U","$action:$what");
5158:
5159: if (!$hashref) {
5160: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5161: "while attempting updateclickers\n", $userinput);
5162: return 1;
5163: }
5164:
5165: my @pairs=split(/\&/,$what);
5166: foreach my $pair (@pairs) {
5167: my ($key,$value)=split(/=/,$pair);
5168: if ($action eq 'add') {
5169: if (exists($hashref->{$key})) {
5170: my @newvals = split(/,/,&unescape($value));
5171: my @currvals = split(/,/,&unescape($hashref->{$key}));
5172: my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
5173: $hashref->{$key}=&escape(join(',',@merged));
5174: } else {
5175: $hashref->{$key}=$value;
5176: }
5177: } elsif ($action eq 'del') {
5178: if (exists($hashref->{$key})) {
5179: my %current;
5180: map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
5181: map { delete($current{$_}); } split(/,/,&unescape($value));
5182: if (keys(%current)) {
5183: $hashref->{$key}=&escape(join(',',sort(keys(%current))));
5184: } else {
5185: delete($hashref->{$key});
5186: }
5187: }
5188: }
5189: }
5190: if (&untie_user_hash($hashref)) {
5191: &Reply( $client, "ok\n", $userinput);
5192: } else {
5193: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
5194: "while attempting put\n",
5195: $userinput);
5196: }
5197: return 1;
5198: }
5199: ®ister_handler("updateclickers", \&update_clickers, 0, 1, 0);
5200:
5201:
5202: # Deletes one or more entries in a namespace db file at the domain level
5203: #
5204: # Parameters:
5205: # $cmd - The command that got us here.
5206: # $tail - Tail of the command (remaining parameters).
5207: # In this case a colon separated list containing:
5208: # (a) the domain for which we are deleting the entries,
5209: # (b) &-separated list of keys to delete.
5210: # $client - File descriptor connected to client.
5211: # Returns
5212: # 1 - Continue processing.
5213: # 0 - Requested to exit, caller should shut down.
5214: # Side effects:
5215: # reply is written to $client.
5216: #
5217:
5218: sub del_domain_handler {
5219: my ($cmd,$tail,$client) = @_;
5220:
5221: my $userinput = "$cmd:$tail";
5222:
5223: my ($udom,$namespace,$what)=split(/:/,$tail,3);
5224: chomp($what);
5225: my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
5226: "D", $what);
5227: if ($hashref) {
5228: my @keys=split(/\&/,$what);
5229: foreach my $key (@keys) {
5230: delete($hashref->{$key});
5231: }
5232: if (&untie_user_hash($hashref)) {
5233: &Reply($client, "ok\n", $userinput);
5234: } else {
5235: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5236: "while attempting deldom\n", $userinput);
5237: }
5238: } else {
5239: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5240: "while attempting deldom\n", $userinput);
5241: }
5242: return 1;
5243: }
5244: ®ister_handler("deldom", \&del_domain_handler, 0, 1, 0);
5245:
5246:
1.348 raeburn 5247: # Unencrypted get from the namespace database file at the domain level.
5248: # This function retrieves a keyed item from a specific named database in the
5249: # domain directory.
5250: #
5251: # Parameters:
1.565 raeburn 5252: # $cmd - Command request keyword (getdom).
1.348 raeburn 5253: # $tail - Tail of the command. This is a colon separated list
5254: # consisting of the domain and the 'namespace'
5255: # which selects the gdbm file to do the lookup in,
5256: # & separated list of keys to lookup. Note that
5257: # the values are returned as an & separated list too.
5258: # $client - File descriptor open on the client.
5259: # Returns:
5260: # 1 - Continue processing.
5261: # 0 - Exit.
5262: # Side effects:
5263: # reply is written to $client.
5264: #
5265:
5266: sub get_domain_handler {
5267: my ($cmd, $tail, $client) = @_;
5268:
1.536 raeburn 5269: my $userinput = "$cmd:$tail";
5270:
5271: my ($udom,$namespace,$what)=split(/:/,$tail,3);
1.573 raeburn 5272: if (($namespace =~ /^enc/) || ($namespace eq 'private')) {
1.536 raeburn 5273: &Failure( $client, "refused\n", $userinput);
5274: } else {
1.565 raeburn 5275: my $res = LONCAPA::Lond::get_dom($userinput);
5276: if ($res =~ /^error:/) {
5277: &Failure($client, \$res, $userinput);
1.536 raeburn 5278: } else {
1.565 raeburn 5279: &Reply($client, \$res, $userinput);
1.536 raeburn 5280: }
5281: }
5282:
5283: return 1;
5284: }
5285: ®ister_handler("getdom", \&get_domain_handler, 0, 1, 0);
5286:
1.572 raeburn 5287: #
5288: # Encrypted get from the namespace database file at the domain level.
5289: # This function retrieves a keyed item from a specific named database in the
5290: # domain directory.
5291: #
5292: # Parameters:
5293: # $cmd - Command request keyword (egetdom).
5294: # $tail - Tail of the command. This is a colon separated list
5295: # consisting of the domain and the 'namespace'
5296: # which selects the gdbm file to do the lookup in,
5297: # & separated list of keys to lookup. Note that
5298: # the values are returned as an & separated list too.
5299: # $client - File descriptor open on the client.
5300: # Returns:
5301: # 1 - Continue processing.
5302: # 0 - Exit.
5303: # Side effects:
5304: # reply is encrypted before being written to $client.
5305: #
1.536 raeburn 5306: sub encrypted_get_domain_handler {
5307: my ($cmd, $tail, $client) = @_;
5308:
5309: my $userinput = "$cmd:$tail";
1.348 raeburn 5310:
1.573 raeburn 5311: my ($udom,$namespace,$what) = split(/:/,$tail,3);
5312: if ($namespace eq 'private') {
5313: &Failure( $client, "refused\n", $userinput);
1.565 raeburn 5314: } else {
1.573 raeburn 5315: my $res = LONCAPA::Lond::get_dom($userinput);
5316: if ($res =~ /^error:/) {
5317: &Failure($client, \$res, $userinput);
5318: } else {
5319: if ($cipher) {
5320: my $cmdlength=length($res);
5321: $res.=" ";
5322: my $encres='';
5323: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
5324: $encres.= unpack("H16",
5325: $cipher->encrypt(substr($res,
5326: $encidx,
5327: 8)));
5328: }
5329: &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
5330: } else {
5331: &Failure( $client, "error:no_key\n",$userinput);
1.536 raeburn 5332: }
1.348 raeburn 5333: }
5334: }
5335: return 1;
5336: }
1.536 raeburn 5337: ®ister_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
1.348 raeburn 5338:
1.420 raeburn 5339: #
1.572 raeburn 5340: # Encrypted get from the namespace database file at the domain level.
5341: # This function retrieves a keyed item from a specific named database in the
5342: # domain directory.
5343: #
5344: # Parameters:
5345: # $cmd - Command request keyword (lti).
5346: # $tail - Tail of the command. This is a colon-separated list
5347: # consisting of the domain, coursenum, if for LTI-
5348: # enabled deep-linking to course content using
5349: # link protection configured within a course,
5350: # context (=deeplink) if for LTI-enabled deep-linking
5351: # to course content using LTI Provider settings
5352: # configured within a course's domain, the (escaped)
5353: # launch URL, the (escaped) method (typically POST),
5354: # and a frozen hash of the LTI launch parameters
5355: # from the LTI payload.
5356: # $client - File descriptor open on the client.
5357: # Returns:
5358: # 1 - Continue processing.
5359: # 0 - Exit.
5360: # Side effects:
5361: # The reply will contain an LTI itemID, if the signed LTI payload
1.579 raeburn 5362: # could be verified using the consumer key and the shared secret
5363: # available for that key (for the itemID) for either the course or domain,
5364: # depending on values for cnum and context. The reply is encrypted before
1.572 raeburn 5365: # being written to $client.
5366: #
5367: sub lti_handler {
5368: my ($cmd, $tail, $client) = @_;
5369:
5370: my $userinput = "$cmd:$tail";
5371:
5372: my ($cdom,$cnum,$context,$escurl,$escmethod,$items) = split(/:/,$tail);
5373: my $url = &unescape($escurl);
5374: my $method = &unescape($escmethod);
5375: my $params = &Apache::lonnet::thaw_unescape($items);
5376: my $res;
5377: if ($cnum ne '') {
5378: $res = &LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
5379: } else {
5380: $res = &LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
5381: }
5382: if ($res =~ /^error:/) {
5383: &Failure($client, \$res, $userinput);
5384: } else {
5385: if ($cipher) {
5386: my $cmdlength=length($res);
5387: $res.=" ";
5388: my $encres='';
5389: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
5390: $encres.= unpack("H16",
5391: $cipher->encrypt(substr($res,
5392: $encidx,
5393: 8)));
5394: }
5395: &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
5396: } else {
5397: &Failure( $client, "error:no_key\n",$userinput);
5398: }
5399: }
5400: return 1;
5401: }
5402: ®ister_handler("lti", \<i_handler, 1, 1, 0);
5403:
5404: #
1.579 raeburn 5405: # Data for LTI payload (received encrypted) are unencrypted and
1.577 raeburn 5406: # then signed with the appropriate key and secret, before re-encrypting
1.579 raeburn 5407: # the signed payload which is sent to the client for unencryption by
5408: # the caller: lonnet::sign_lti()) before dispatch either to a web browser
5409: # (launch) or to a remote web service (roster, logout, or grade).
1.577 raeburn 5410: #
5411: # Parameters:
5412: # $cmd - Command request keyword (signlti).
5413: # $tail - Tail of the command. This is a colon-separated list
5414: # consisting of the domain, coursenum (if for an External
1.578 raeburn 5415: # Tool defined in a course), crsdef (true if defined in
1.579 raeburn 5416: # a course), type (linkprot or lti)
5417: # context (launch, roster, logout, or grade),
1.578 raeburn 5418: # escaped launch URL, numeric ID of external tool,
1.577 raeburn 5419: # version number for encryption key (if tool's LTI secret was
1.578 raeburn 5420: # encrypted before storing), a frozen hash of LTI launch
5421: # parameters, and a frozen hash of LTI information,
5422: # (e.g., method => 'HMAC-SHA1',
5423: # respfmt => 'to_authorization_header').
1.577 raeburn 5424: # $client - File descriptor open on the client.
5425: # Returns:
5426: # 1 - Continue processing.
5427: # 0 - Exit.
5428: # Side effects:
5429: # The reply will contain the LTI payload, as & separated key=value pairs,
5430: # where value is itself a frozen hash, if the required key and secret
1.579 raeburn 5431: # for the specific tool ID are available. The payload data are retrieved from
1.578 raeburn 5432: # a call to Lond::sign_lti_payload(), and the reply is encrypted before being
1.577 raeburn 5433: # written to $client.
5434: #
5435: sub sign_lti_handler {
5436: my ($cmd, $tail, $client) = @_;
5437:
5438: my $userinput = "$cmd:$tail";
5439:
1.579 raeburn 5440: my ($cdom,$cnum,$crsdef,$type,$context,$escurl,
5441: $ltinum,$keynum,$paramsref,$inforef) = split(/:/,$tail);
1.577 raeburn 5442: my $url = &unescape($escurl);
5443: my $params = &Apache::lonnet::thaw_unescape($paramsref);
5444: my $info = &Apache::lonnet::thaw_unescape($inforef);
5445: my $res =
1.579 raeburn 5446: &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,
5447: $keynum,$perlvar{'lonVersion'},$params,$info);
1.577 raeburn 5448: my $result;
5449: if (ref($res) eq 'HASH') {
5450: foreach my $key (keys(%{$res})) {
5451: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($res->{$key}).'&';
5452: }
5453: $result =~ s/\&$//;
5454: } else {
5455: $result = $res;
5456: }
5457: if ($result =~ /^error:/) {
5458: &Failure($client, \$result, $userinput);
5459: } else {
5460: if ($cipher) {
5461: my $cmdlength=length($result);
5462: $result.=" ";
5463: my $encres='';
5464: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
5465: $encres.= unpack("H16",
5466: $cipher->encrypt(substr($result,
5467: $encidx,
5468: 8)));
5469: }
5470: &Reply( $client,"enc:$cmdlength:$encres\n",$userinput);
5471: } else {
5472: &Failure( $client, "error:no_key\n",$userinput);
5473: }
5474: }
5475: return 1;
5476: }
5477: ®ister_handler("signlti", \&sign_lti_handler, 1, 1, 0);
5478:
5479: #
1.238 foxr 5480: # Puts an id to a domains id database.
5481: #
5482: # Parameters:
5483: # $cmd - The command that triggered us.
5484: # $tail - Remainder of the request other than the command. This is a
5485: # colon separated list containing:
5486: # $domain - The domain for which we are writing the id.
5487: # $pairs - The id info to write... this is and & separated list
5488: # of keyword=value.
5489: # $client - Socket open on the client.
5490: # Returns:
5491: # 1 - Continue processing.
5492: # Side effects:
5493: # reply is written to $client.
5494: #
5495: sub put_id_handler {
5496: my ($cmd,$tail,$client) = @_;
5497:
5498:
5499: my $userinput = "$cmd:$tail";
5500:
5501: my ($udom,$what)=split(/:/,$tail);
5502: chomp($what);
5503: my @pairs=split(/\&/,$what);
5504: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
5505: "P", $what);
5506: if ($hashref) {
5507: foreach my $pair (@pairs) {
5508: my ($key,$value)=split(/=/,$pair);
5509: $hashref->{$key}=$value;
5510: }
1.311 albertel 5511: if (&untie_domain_hash($hashref)) {
1.238 foxr 5512: &Reply($client, "ok\n", $userinput);
5513: } else {
5514: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5515: "while attempting idput\n", $userinput);
5516: }
5517: } else {
5518: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5519: "while attempting idput\n", $userinput);
5520: }
5521:
5522: return 1;
5523: }
1.263 albertel 5524: ®ister_handler("idput", \&put_id_handler, 0, 1, 0);
1.238 foxr 5525:
5526: #
5527: # Retrieves a set of id values from the id database.
5528: # Returns an & separated list of results, one for each requested id to the
5529: # client.
5530: #
5531: # Parameters:
5532: # $cmd - Command keyword that caused us to be dispatched.
5533: # $tail - Tail of the command. Consists of a colon separated:
5534: # domain - the domain whose id table we dump
5535: # ids Consists of an & separated list of
5536: # id keywords whose values will be fetched.
5537: # nonexisting keywords will have an empty value.
5538: # $client - Socket open on the client.
5539: #
5540: # Returns:
5541: # 1 - indicating processing should continue.
5542: # Side effects:
5543: # An & separated list of results is written to $client.
5544: #
5545: sub get_id_handler {
5546: my ($cmd, $tail, $client) = @_;
5547:
5548:
5549: my $userinput = "$client:$tail";
5550:
5551: my ($udom,$what)=split(/:/,$tail);
5552: chomp($what);
5553: my @queries=split(/\&/,$what);
5554: my $qresult='';
5555: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
5556: if ($hashref) {
5557: for (my $i=0;$i<=$#queries;$i++) {
5558: $qresult.="$hashref->{$queries[$i]}&";
5559: }
1.311 albertel 5560: if (&untie_domain_hash($hashref)) {
1.238 foxr 5561: $qresult=~s/\&$//;
1.387 albertel 5562: &Reply($client, \$qresult, $userinput);
1.238 foxr 5563: } else {
5564: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
5565: "while attempting idget\n",$userinput);
5566: }
5567: } else {
5568: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5569: "while attempting idget\n",$userinput);
5570: }
5571:
5572: return 1;
5573: }
1.263 albertel 5574: ®ister_handler("idget", \&get_id_handler, 0, 1, 0);
1.238 foxr 5575:
1.501 raeburn 5576: # Deletes one or more ids in a domain's id database.
5577: #
5578: # Parameters:
5579: # $cmd - Command keyword (iddel).
5580: # $tail - Command tail. In this case a colon
5581: # separated list containing:
5582: # The domain for which we are deleting the id(s).
5583: # &-separated list of id(s) to delete.
5584: # $client - File open on client socket.
5585: # Returns:
5586: # 1 - Continue processing
5587: # 0 - Exit server.
5588: #
5589: #
5590:
5591: sub del_id_handler {
5592: my ($cmd,$tail,$client) = @_;
5593:
5594: my $userinput = "$cmd:$tail";
5595:
5596: my ($udom,$what)=split(/:/,$tail);
5597: chomp($what);
5598: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
5599: "D", $what);
5600: if ($hashref) {
5601: my @keys=split(/\&/,$what);
5602: foreach my $key (@keys) {
5603: delete($hashref->{$key});
5604: }
5605: if (&untie_user_hash($hashref)) {
5606: &Reply($client, "ok\n", $userinput);
5607: } else {
5608: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5609: "while attempting iddel\n", $userinput);
5610: }
5611: } else {
5612: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5613: "while attempting iddel\n", $userinput);
5614: }
5615: return 1;
5616: }
5617: ®ister_handler("iddel", \&del_id_handler, 0, 1, 0);
5618:
1.238 foxr 5619: #
1.299 raeburn 5620: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database
5621: #
5622: # Parameters
5623: # $cmd - Command keyword that caused us to be dispatched.
5624: # $tail - Tail of the command. Consists of a colon separated:
5625: # domain - the domain whose dcmail we are recording
5626: # email Consists of key=value pair
5627: # where key is unique msgid
5628: # and value is message (in XML)
5629: # $client - Socket open on the client.
5630: #
5631: # Returns:
5632: # 1 - indicating processing should continue.
5633: # Side effects
5634: # reply is written to $client.
5635: #
5636: sub put_dcmail_handler {
5637: my ($cmd,$tail,$client) = @_;
5638: my $userinput = "$cmd:$tail";
1.463 foxr 5639:
5640:
1.299 raeburn 5641: my ($udom,$what)=split(/:/,$tail);
5642: chomp($what);
5643: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
5644: if ($hashref) {
5645: my ($key,$value)=split(/=/,$what);
5646: $hashref->{$key}=$value;
5647: }
1.311 albertel 5648: if (&untie_domain_hash($hashref)) {
1.299 raeburn 5649: &Reply($client, "ok\n", $userinput);
5650: } else {
5651: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5652: "while attempting dcmailput\n", $userinput);
5653: }
5654: return 1;
5655: }
5656: ®ister_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
5657:
5658: #
5659: # Retrieves broadcast e-mail from nohist_dcmail database
5660: # Returns to client an & separated list of key=value pairs,
5661: # where key is msgid and value is message information.
5662: #
5663: # Parameters
5664: # $cmd - Command keyword that caused us to be dispatched.
5665: # $tail - Tail of the command. Consists of a colon separated:
5666: # domain - the domain whose dcmail table we dump
5667: # startfilter - beginning of time window
5668: # endfilter - end of time window
5669: # sendersfilter - & separated list of username:domain
5670: # for senders to search for.
5671: # $client - Socket open on the client.
5672: #
5673: # Returns:
5674: # 1 - indicating processing should continue.
5675: # Side effects
5676: # reply (& separated list of msgid=messageinfo pairs) is
5677: # written to $client.
5678: #
5679: sub dump_dcmail_handler {
5680: my ($cmd, $tail, $client) = @_;
5681:
5682: my $userinput = "$cmd:$tail";
5683: my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
5684: chomp($sendersfilter);
5685: my @senders = ();
5686: if (defined($startfilter)) {
5687: $startfilter=&unescape($startfilter);
5688: } else {
5689: $startfilter='.';
5690: }
5691: if (defined($endfilter)) {
5692: $endfilter=&unescape($endfilter);
5693: } else {
5694: $endfilter='.';
5695: }
5696: if (defined($sendersfilter)) {
5697: $sendersfilter=&unescape($sendersfilter);
1.300 albertel 5698: @senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299 raeburn 5699: }
5700:
5701: my $qresult='';
5702: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
5703: if ($hashref) {
5704: while (my ($key,$value) = each(%$hashref)) {
5705: my $match = 1;
1.303 albertel 5706: my ($timestamp,$subj,$uname,$udom) =
5707: split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299 raeburn 5708: $subj = &unescape($subj);
5709: unless ($startfilter eq '.' || !defined($startfilter)) {
5710: if ($timestamp < $startfilter) {
5711: $match = 0;
5712: }
5713: }
5714: unless ($endfilter eq '.' || !defined($endfilter)) {
5715: if ($timestamp > $endfilter) {
5716: $match = 0;
5717: }
5718: }
5719: unless (@senders < 1) {
5720: unless (grep/^$uname:$udom$/,@senders) {
5721: $match = 0;
5722: }
5723: }
5724: if ($match == 1) {
5725: $qresult.=$key.'='.$value.'&';
5726: }
5727: }
1.311 albertel 5728: if (&untie_domain_hash($hashref)) {
1.299 raeburn 5729: chop($qresult);
1.387 albertel 5730: &Reply($client, \$qresult, $userinput);
1.299 raeburn 5731: } else {
5732: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5733: "while attempting dcmaildump\n", $userinput);
5734: }
5735: } else {
5736: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5737: "while attempting dcmaildump\n", $userinput);
5738: }
5739: return 1;
5740: }
5741:
5742: ®ister_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
5743:
5744: #
5745: # Puts domain roles in nohist_domainroles database
5746: #
5747: # Parameters
5748: # $cmd - Command keyword that caused us to be dispatched.
5749: # $tail - Tail of the command. Consists of a colon separated:
5750: # domain - the domain whose roles we are recording
5751: # role - Consists of key=value pair
5752: # where key is unique role
5753: # and value is start/end date information
5754: # $client - Socket open on the client.
5755: #
5756: # Returns:
5757: # 1 - indicating processing should continue.
5758: # Side effects
5759: # reply is written to $client.
5760: #
5761:
5762: sub put_domainroles_handler {
5763: my ($cmd,$tail,$client) = @_;
5764:
5765: my $userinput = "$cmd:$tail";
5766: my ($udom,$what)=split(/:/,$tail);
5767: chomp($what);
5768: my @pairs=split(/\&/,$what);
5769: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
5770: if ($hashref) {
5771: foreach my $pair (@pairs) {
5772: my ($key,$value)=split(/=/,$pair);
5773: $hashref->{$key}=$value;
5774: }
1.311 albertel 5775: if (&untie_domain_hash($hashref)) {
1.299 raeburn 5776: &Reply($client, "ok\n", $userinput);
5777: } else {
5778: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5779: "while attempting domroleput\n", $userinput);
5780: }
5781: } else {
5782: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5783: "while attempting domroleput\n", $userinput);
5784: }
5785:
5786: return 1;
5787: }
5788:
5789: ®ister_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
5790:
5791: #
5792: # Retrieves domain roles from nohist_domainroles database
5793: # Returns to client an & separated list of key=value pairs,
5794: # where key is role and value is start and end date information.
5795: #
5796: # Parameters
5797: # $cmd - Command keyword that caused us to be dispatched.
5798: # $tail - Tail of the command. Consists of a colon separated:
5799: # domain - the domain whose domain roles table we dump
5800: # $client - Socket open on the client.
5801: #
5802: # Returns:
5803: # 1 - indicating processing should continue.
5804: # Side effects
5805: # reply (& separated list of role=start/end info pairs) is
5806: # written to $client.
5807: #
5808: sub dump_domainroles_handler {
5809: my ($cmd, $tail, $client) = @_;
5810:
5811: my $userinput = "$cmd:$tail";
5812: my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
5813: chomp($rolesfilter);
5814: my @roles = ();
5815: if (defined($startfilter)) {
5816: $startfilter=&unescape($startfilter);
5817: } else {
5818: $startfilter='.';
5819: }
5820: if (defined($endfilter)) {
5821: $endfilter=&unescape($endfilter);
5822: } else {
5823: $endfilter='.';
5824: }
5825: if (defined($rolesfilter)) {
5826: $rolesfilter=&unescape($rolesfilter);
1.300 albertel 5827: @roles = split(/\&/,$rolesfilter);
1.299 raeburn 5828: }
1.421 raeburn 5829:
1.299 raeburn 5830: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
5831: if ($hashref) {
5832: my $qresult = '';
5833: while (my ($key,$value) = each(%$hashref)) {
5834: my $match = 1;
1.421 raeburn 5835: my ($end,$start) = split(/:/,&unescape($value));
1.299 raeburn 5836: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421 raeburn 5837: unless (@roles < 1) {
5838: unless (grep/^\Q$trole\E$/,@roles) {
5839: $match = 0;
5840: next;
5841: }
5842: }
1.299 raeburn 5843: unless ($startfilter eq '.' || !defined($startfilter)) {
1.415 raeburn 5844: if ((defined($start)) && ($start >= $startfilter)) {
1.299 raeburn 5845: $match = 0;
1.421 raeburn 5846: next;
1.299 raeburn 5847: }
5848: }
5849: unless ($endfilter eq '.' || !defined($endfilter)) {
1.421 raeburn 5850: if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299 raeburn 5851: $match = 0;
1.421 raeburn 5852: next;
1.299 raeburn 5853: }
5854: }
5855: if ($match == 1) {
5856: $qresult.=$key.'='.$value.'&';
5857: }
5858: }
1.311 albertel 5859: if (&untie_domain_hash($hashref)) {
1.299 raeburn 5860: chop($qresult);
1.387 albertel 5861: &Reply($client, \$qresult, $userinput);
1.299 raeburn 5862: } else {
5863: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5864: "while attempting domrolesdump\n", $userinput);
5865: }
5866: } else {
5867: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5868: "while attempting domrolesdump\n", $userinput);
5869: }
5870: return 1;
5871: }
5872:
5873: ®ister_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
5874:
5875:
1.238 foxr 5876: # Process the tmpput command I'm not sure what this does.. Seems to
5877: # create a file in the lonDaemons/tmp directory of the form $id.tmp
5878: # where Id is the client's ip concatenated with a sequence number.
5879: # The file will contain some value that is passed in. Is this e.g.
5880: # a login token?
5881: #
5882: # Parameters:
5883: # $cmd - The command that got us dispatched.
5884: # $tail - The remainder of the request following $cmd:
5885: # In this case this will be the contents of the file.
5886: # $client - Socket connected to the client.
5887: # Returns:
5888: # 1 indicating processing can continue.
5889: # Side effects:
5890: # A file is created in the local filesystem.
5891: # A reply is sent to the client.
5892: sub tmp_put_handler {
5893: my ($cmd, $what, $client) = @_;
5894:
5895: my $userinput = "$cmd:$what"; # Reconstruct for logging.
5896:
1.347 raeburn 5897: my ($record,$context) = split(/:/,$what);
5898: if ($context ne '') {
5899: chomp($context);
5900: $context = &unescape($context);
5901: }
5902: my ($id,$store);
1.238 foxr 5903: $tmpsnum++;
1.569 raeburn 5904: my $numtries = 0;
5905: my $execdir=$perlvar{'lonDaemons'};
5906: if (($context eq 'resetpw') || ($context eq 'createaccount') ||
5907: ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
5908: $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
5909: while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
5910: undef($id);
5911: $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
5912: $numtries ++;
5913: }
1.347 raeburn 5914: } else {
5915: $id = $$.'_'.$clientip.'_'.$tmpsnum;
5916: }
1.238 foxr 5917: $id=~s/\W/\_/g;
1.347 raeburn 5918: $record=~s/\n//g;
1.569 raeburn 5919: if (($id ne '') &&
5920: ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
1.347 raeburn 5921: print $store $record;
1.238 foxr 5922: close $store;
1.387 albertel 5923: &Reply($client, \$id, $userinput);
1.238 foxr 5924: } else {
5925: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
5926: "while attempting tmpput\n", $userinput);
5927: }
5928: return 1;
5929:
5930: }
5931: ®ister_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263 albertel 5932:
1.238 foxr 5933: # Processes the tmpget command. This command returns the contents
5934: # of a temporary resource file(?) created via tmpput.
5935: #
5936: # Paramters:
5937: # $cmd - Command that got us dispatched.
5938: # $id - Tail of the command, contain the id of the resource
5939: # we want to fetch.
5940: # $client - socket open on the client.
5941: # Return:
5942: # 1 - Inidcating processing can continue.
5943: # Side effects:
5944: # A reply is sent to the client.
5945: #
5946: sub tmp_get_handler {
5947: my ($cmd, $id, $client) = @_;
5948:
5949: my $userinput = "$cmd:$id";
5950:
5951:
5952: $id=~s/\W/\_/g;
5953: my $store;
5954: my $execdir=$perlvar{'lonDaemons'};
5955: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
5956: my $reply=<$store>;
1.387 albertel 5957: &Reply( $client, \$reply, $userinput);
1.238 foxr 5958: close $store;
5959: } else {
5960: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
5961: "while attempting tmpget\n", $userinput);
5962: }
5963:
5964: return 1;
5965: }
5966: ®ister_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263 albertel 5967:
1.238 foxr 5968: #
5969: # Process the tmpdel command. This command deletes a temp resource
5970: # created by the tmpput command.
5971: #
5972: # Parameters:
5973: # $cmd - Command that got us here.
5974: # $id - Id of the temporary resource created.
5975: # $client - socket open on the client process.
5976: #
5977: # Returns:
5978: # 1 - Indicating processing should continue.
5979: # Side Effects:
5980: # A file is deleted
5981: # A reply is sent to the client.
5982: sub tmp_del_handler {
5983: my ($cmd, $id, $client) = @_;
5984:
5985: my $userinput= "$cmd:$id";
5986:
5987: chomp($id);
5988: $id=~s/\W/\_/g;
5989: my $execdir=$perlvar{'lonDaemons'};
5990: if (unlink("$execdir/tmp/$id.tmp")) {
5991: &Reply($client, "ok\n", $userinput);
5992: } else {
5993: &Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
5994: "while attempting tmpdel\n", $userinput);
5995: }
5996:
5997: return 1;
5998:
5999: }
6000: ®ister_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263 albertel 6001:
1.238 foxr 6002: #
1.564 raeburn 6003: # Process the updatebalcookie command. This command updates a
6004: # cookie in the lonBalancedir directory on a load balancer node.
6005: #
6006: # Parameters:
6007: # $cmd - Command that got us here.
6008: # $tail - Tail of the request (escaped cookie: escaped current entry)
6009: #
6010: # $client - socket open on the client process.
6011: #
6012: # Returns:
6013: # 1 - Indicating processing should continue.
6014: # Side Effects:
6015: # A cookie file is updated from the lonBalancedir directory
6016: # A reply is sent to the client.
6017: #
6018: sub update_balcookie_handler {
6019: my ($cmd, $tail, $client) = @_;
6020:
6021: my $userinput= "$cmd:$tail";
6022: chomp($tail);
6023: my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
6024:
6025: my $updatedone;
6026: if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
6027: my $execdir=$perlvar{'lonBalanceDir'};
6028: if (-e "$execdir/$cookie.id") {
6029: my $doupdate;
6030: if (open(my $fh,'<',"$execdir/$cookie.id")) {
6031: while (my $line = <$fh>) {
6032: chomp($line);
6033: if ($line eq $lastentry) {
6034: $doupdate = 1;
6035: last;
6036: }
6037: }
6038: close($fh);
6039: }
6040: if ($doupdate) {
6041: if (open(my $fh,'>',"$execdir/$cookie.id")) {
6042: print $fh $clientname;
6043: close($fh);
6044: $updatedone = 1;
6045: }
6046: }
6047: }
6048: }
6049: if ($updatedone) {
6050: &Reply($client, "ok\n", $userinput);
6051: } else {
6052: &Failure( $client, "error: ".($!+0)."file update failed ".
6053: "while attempting updatebalcookie\n", $userinput);
6054: }
6055: return 1;
6056: }
6057: ®ister_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
6058:
6059: #
1.551 raeburn 6060: # Process the delbalcookie command. This command deletes a balancer
1.564 raeburn 6061: # cookie in the lonBalancedir directory on a load balancer node.
1.551 raeburn 6062: #
6063: # Parameters:
6064: # $cmd - Command that got us here.
6065: # $cookie - Cookie to be deleted.
6066: # $client - socket open on the client process.
6067: #
6068: # Returns:
6069: # 1 - Indicating processing should continue.
6070: # Side Effects:
6071: # A cookie file is deleted from the lonBalancedir directory
6072: # A reply is sent to the client.
6073: sub del_balcookie_handler {
6074: my ($cmd, $cookie, $client) = @_;
6075:
6076: my $userinput= "$cmd:$cookie";
6077:
6078: chomp($cookie);
1.564 raeburn 6079: $cookie = &unescape($cookie);
1.551 raeburn 6080: my $deleted = '';
6081: if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
6082: my $execdir=$perlvar{'lonBalanceDir'};
6083: if (-e "$execdir/$cookie.id") {
6084: if (open(my $fh,'<',"$execdir/$cookie.id")) {
6085: my $dodelete;
6086: while (my $line = <$fh>) {
6087: chomp($line);
6088: if ($line eq $clientname) {
6089: $dodelete = 1;
1.554 raeburn 6090: last;
1.551 raeburn 6091: }
6092: }
1.554 raeburn 6093: close($fh);
1.551 raeburn 6094: if ($dodelete) {
6095: if (unlink("$execdir/$cookie.id")) {
6096: $deleted = 1;
6097: }
6098: }
6099: }
6100: }
6101: }
6102: if ($deleted) {
6103: &Reply($client, "ok\n", $userinput);
6104: } else {
6105: &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
6106: "while attempting delbalcookie\n", $userinput);
6107: }
6108: return 1;
6109: }
6110: ®ister_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
6111:
6112: #
1.246 foxr 6113: # Processes the setannounce command. This command
6114: # creates a file named announce.txt in the top directory of
6115: # the documentn root and sets its contents. The announce.txt file is
6116: # printed in its entirety at the LonCAPA login page. Note:
6117: # once the announcement.txt fileis created it cannot be deleted.
6118: # However, setting the contents of the file to empty removes the
6119: # announcement from the login page of loncapa so who cares.
6120: #
6121: # Parameters:
6122: # $cmd - The command that got us dispatched.
6123: # $announcement - The text of the announcement.
6124: # $client - Socket open on the client process.
6125: # Retunrns:
6126: # 1 - Indicating request processing should continue
6127: # Side Effects:
6128: # The file {DocRoot}/announcement.txt is created.
6129: # A reply is sent to $client.
6130: #
6131: sub set_announce_handler {
6132: my ($cmd, $announcement, $client) = @_;
6133:
6134: my $userinput = "$cmd:$announcement";
6135:
6136: chomp($announcement);
6137: $announcement=&unescape($announcement);
6138: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
6139: '/announcement.txt')) {
6140: print $store $announcement;
6141: close $store;
6142: &Reply($client, "ok\n", $userinput);
6143: } else {
6144: &Failure($client, "error: ".($!+0)."\n", $userinput);
6145: }
6146:
6147: return 1;
6148: }
6149: ®ister_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263 albertel 6150:
1.246 foxr 6151: #
6152: # Return the version of the daemon. This can be used to determine
6153: # the compatibility of cross version installations or, alternatively to
6154: # simply know who's out of date and who isn't. Note that the version
6155: # is returned concatenated with the tail.
6156: # Parameters:
6157: # $cmd - the request that dispatched to us.
6158: # $tail - Tail of the request (client's version?).
6159: # $client - Socket open on the client.
6160: #Returns:
6161: # 1 - continue processing requests.
6162: # Side Effects:
6163: # Replies with version to $client.
6164: sub get_version_handler {
6165: my ($cmd, $tail, $client) = @_;
6166:
6167: my $userinput = $cmd.$tail;
6168:
6169: &Reply($client, &version($userinput)."\n", $userinput);
6170:
6171:
6172: return 1;
6173: }
6174: ®ister_handler("version", \&get_version_handler, 0, 1, 0);
1.263 albertel 6175:
1.246 foxr 6176: # Set the current host and domain. This is used to support
6177: # multihomed systems. Each IP of the system, or even separate daemons
6178: # on the same IP can be treated as handling a separate lonCAPA virtual
6179: # machine. This command selects the virtual lonCAPA. The client always
6180: # knows the right one since it is lonc and it is selecting the domain/system
6181: # from the hosts.tab file.
6182: # Parameters:
6183: # $cmd - Command that dispatched us.
6184: # $tail - Tail of the command (domain/host requested).
6185: # $socket - Socket open on the client.
6186: #
6187: # Returns:
6188: # 1 - Indicates the program should continue to process requests.
6189: # Side-effects:
6190: # The default domain/system context is modified for this daemon.
6191: # a reply is sent to the client.
6192: #
6193: sub set_virtual_host_handler {
6194: my ($cmd, $tail, $socket) = @_;
6195:
6196: my $userinput ="$cmd:$tail";
6197:
6198: &Reply($client, &sethost($userinput)."\n", $userinput);
6199:
6200:
6201: return 1;
6202: }
1.247 albertel 6203: ®ister_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246 foxr 6204:
6205: # Process a request to exit:
6206: # - "bye" is sent to the client.
6207: # - The client socket is shutdown and closed.
6208: # - We indicate to the caller that we should exit.
6209: # Formal Parameters:
6210: # $cmd - The command that got us here.
6211: # $tail - Tail of the command (empty).
6212: # $client - Socket open on the tail.
6213: # Returns:
6214: # 0 - Indicating the program should exit!!
6215: #
6216: sub exit_handler {
6217: my ($cmd, $tail, $client) = @_;
6218:
6219: my $userinput = "$cmd:$tail";
6220:
6221: &logthis("Client $clientip ($clientname) hanging up: $userinput");
6222: &Reply($client, "bye\n", $userinput);
6223: $client->shutdown(2); # shutdown the socket forcibly.
6224: $client->close();
6225:
6226: return 0;
6227: }
1.248 foxr 6228: ®ister_handler("exit", \&exit_handler, 0,1,1);
6229: ®ister_handler("init", \&exit_handler, 0,1,1);
6230: ®ister_handler("quit", \&exit_handler, 0,1,1);
6231:
6232: # Determine if auto-enrollment is enabled.
6233: # Note that the original had what I believe to be a defect.
6234: # The original returned 0 if the requestor was not a registerd client.
6235: # It should return "refused".
6236: # Formal Parameters:
6237: # $cmd - The command that invoked us.
6238: # $tail - The tail of the command (Extra command parameters.
6239: # $client - The socket open on the client that issued the request.
6240: # Returns:
6241: # 1 - Indicating processing should continue.
6242: #
6243: sub enrollment_enabled_handler {
6244: my ($cmd, $tail, $client) = @_;
6245: my $userinput = $cmd.":".$tail; # For logging purposes.
6246:
1.337 albertel 6247: my ($cdom) = split(/:/, $tail, 2); # Domain we're asking about.
1.582 raeburn 6248: my $outcome;
6249: eval {
6250: local($SIG{__DIE__})='DEFAULT';
6251: $outcome = &localenroll::run($cdom);
6252: };
1.387 albertel 6253: &Reply($client, \$outcome, $userinput);
1.248 foxr 6254: return 1;
6255: }
6256: ®ister_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
6257:
1.417 raeburn 6258: #
1.423 raeburn 6259: # Validate an institutional code used for a LON-CAPA course.
1.417 raeburn 6260: #
6261: # Formal Parameters:
6262: # $cmd - The command request that got us dispatched.
6263: # $tail - The tail of the command. In this case,
6264: # this is a colon separated set of words that will be split
6265: # into:
1.424 raeburn 6266: # $dom - The domain for which the check of
6267: # institutional course code will occur.
6268: #
6269: # $instcode - The institutional code for the course
6270: # being requested, or validated for rights
6271: # to request.
6272: #
6273: # $owner - The course requestor (who will be the
6274: # course owner, in the form username:domain
6275: #
1.417 raeburn 6276: # $client - Socket open on the client.
6277: # Returns:
6278: # 1 - Indicating processing should continue.
6279: #
6280: sub validate_instcode_handler {
6281: my ($cmd, $tail, $client) = @_;
6282: my $userinput = "$cmd:$tail";
1.423 raeburn 6283: my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422 raeburn 6284: $instcode = &unescape($instcode);
6285: $owner = &unescape($owner);
1.582 raeburn 6286: my ($outcome,$description,$credits);
6287: eval {
6288: local($SIG{__DIE__})='DEFAULT';
6289: ($outcome,$description,$credits) =
6290: &localenroll::validate_instcode($dom,$instcode,$owner);
6291: };
1.498 raeburn 6292: my $result = &escape($outcome).'&'.&escape($description).'&'.
6293: &escape($credits);
1.426 raeburn 6294: &Reply($client, \$result, $userinput);
1.417 raeburn 6295:
6296: return 1;
6297: }
6298: ®ister_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
6299:
1.566 raeburn 6300: #
6301: # Validate co-owner for cross-listed institutional code and
6302: # institutional course code itself used for a LON-CAPA course.
6303: #
6304: # Formal Parameters:
6305: # $cmd - The command request that got us dispatched.
6306: # $tail - The tail of the command. In this case,
6307: # this is a colon separated string containing:
6308: # $dom - Course's LON-CAPA domain
6309: # $instcode - Institutional course code for the course
6310: # $inst_xlist - Institutional course Id for the crosslisting
6311: # $coowner - Username of co-owner
6312: # (values for all but $dom have been escaped).
6313: #
6314: # $client - Socket open on the client.
6315: # Returns:
6316: # 1 - Indicating processing should continue.
6317: #
6318: sub validate_instcrosslist_handler {
6319: my ($cmd, $tail, $client) = @_;
6320: my $userinput = "$cmd:$tail";
6321: my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
6322: $instcode = &unescape($instcode);
6323: $inst_xlist = &unescape($inst_xlist);
6324: $coowner = &unescape($coowner);
1.582 raeburn 6325: my $outcome;
6326: eval {
6327: local($SIG{__DIE__})='DEFAULT';
6328: $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
6329: $inst_xlist,$coowner);
6330: };
6331:
1.566 raeburn 6332: &Reply($client, \$outcome, $userinput);
6333: return 1;
6334: }
6335: ®ister_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
6336:
1.248 foxr 6337: # Get the official sections for which auto-enrollment is possible.
6338: # Since the admin people won't know about 'unofficial sections'
6339: # we cannot auto-enroll on them.
6340: # Formal Parameters:
6341: # $cmd - The command request that got us dispatched here.
6342: # $tail - The remainder of the request. In our case this
6343: # will be split into:
6344: # $coursecode - The course name from the admin point of view.
6345: # $cdom - The course's domain(?).
6346: # $client - Socket open on the client.
6347: # Returns:
6348: # 1 - Indiciting processing should continue.
6349: #
6350: sub get_sections_handler {
6351: my ($cmd, $tail, $client) = @_;
6352: my $userinput = "$cmd:$tail";
6353:
6354: my ($coursecode, $cdom) = split(/:/, $tail);
1.582 raeburn 6355: my $seclist;
6356: eval {
6357: local($SIG{__DIE__})='DEFAULT';
6358: my @secs = &localenroll::get_sections($coursecode,$cdom);
6359: $seclist = &escape(join(':',@secs));
6360: };
1.387 albertel 6361: &Reply($client, \$seclist, $userinput);
1.248 foxr 6362: return 1;
6363: }
6364: ®ister_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
6365:
6366: # Validate the owner of a new course section.
6367: #
6368: # Formal Parameters:
6369: # $cmd - Command that got us dispatched.
6370: # $tail - the remainder of the command. For us this consists of a
6371: # colon separated string containing:
6372: # $inst - Course Id from the institutions point of view.
6373: # $owner - Proposed owner of the course.
6374: # $cdom - Domain of the course (from the institutions
6375: # point of view?)..
6376: # $client - Socket open on the client.
6377: #
6378: # Returns:
6379: # 1 - Processing should continue.
6380: #
1.582 raeburn 6381:
1.248 foxr 6382: sub validate_course_owner_handler {
6383: my ($cmd, $tail, $client) = @_;
6384: my $userinput = "$cmd:$tail";
1.470 raeburn 6385: my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
6386:
1.336 raeburn 6387: $owner = &unescape($owner);
1.470 raeburn 6388: $coowners = &unescape($coowners);
1.582 raeburn 6389: my $outcome;
6390: eval {
6391: local($SIG{__DIE__})='DEFAULT';
6392: $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
6393: };
1.387 albertel 6394: &Reply($client, \$outcome, $userinput);
1.248 foxr 6395: return 1;
6396: }
6397: ®ister_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263 albertel 6398:
1.248 foxr 6399: #
6400: # Validate a course section in the official schedule of classes
6401: # from the institutions point of view (part of autoenrollment).
6402: #
6403: # Formal Parameters:
6404: # $cmd - The command request that got us dispatched.
6405: # $tail - The tail of the command. In this case,
6406: # this is a colon separated set of words that will be split
6407: # into:
6408: # $inst_course_id - The course/section id from the
6409: # institutions point of view.
6410: # $cdom - The domain from the institutions
6411: # point of view.
6412: # $client - Socket open on the client.
6413: # Returns:
6414: # 1 - Indicating processing should continue.
6415: #
6416: sub validate_course_section_handler {
6417: my ($cmd, $tail, $client) = @_;
6418: my $userinput = "$cmd:$tail";
6419: my ($inst_course_id, $cdom) = split(/:/, $tail);
1.582 raeburn 6420: my $outcome;
6421: eval {
6422: local($SIG{__DIE__})='DEFAULT';
6423: $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
6424: };
1.387 albertel 6425: &Reply($client, \$outcome, $userinput);
1.248 foxr 6426: return 1;
6427: }
6428: ®ister_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
6429:
6430: #
1.340 raeburn 6431: # Validate course owner's access to enrollment data for specific class section.
6432: #
6433: #
6434: # Formal Parameters:
6435: # $cmd - The command request that got us dispatched.
6436: # $tail - The tail of the command. In this case this is a colon separated
1.542 raeburn 6437: # set of values that will be split into:
1.340 raeburn 6438: # $inst_class - Institutional code for the specific class section
1.542 raeburn 6439: # $ownerlist - An escaped comma-separated list of username:domain
6440: # of the course owner, and co-owner(s).
1.340 raeburn 6441: # $cdom - The domain of the course from the institution's
6442: # point of view.
6443: # $client - The socket open on the client.
6444: # Returns:
6445: # 1 - continue processing.
6446: #
6447:
6448: sub validate_class_access_handler {
6449: my ($cmd, $tail, $client) = @_;
6450: my $userinput = "$cmd:$tail";
1.383 raeburn 6451: my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392 raeburn 6452: my $owners = &unescape($ownerlist);
1.341 albertel 6453: my $outcome;
6454: eval {
6455: local($SIG{__DIE__})='DEFAULT';
1.392 raeburn 6456: $outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341 albertel 6457: };
1.387 albertel 6458: &Reply($client,\$outcome, $userinput);
1.340 raeburn 6459: return 1;
6460: }
6461: ®ister_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
6462:
6463: #
1.567 raeburn 6464: # Modify institutional sections (using customized &instsec_reformat()
6465: # routine in localenroll.pm), to either clutter or declutter, for
6466: # purposes of ensuring an institutional course section (string) can
6467: # be unambiguously separated into institutional course and section.
6468: #
6469: # Formal Parameters:
6470: # $cmd - The command request that got us dispatched.
6471: # $tail - The tail of the command. In this case this is a colon separated
6472: # set of values that will be split into:
6473: # $cdom - The LON-CAPA domain of the course.
6474: # $action - Either: clutter or declutter
6475: # clutter adds character(s) to eliminate ambiguity
6476: # declutter removes the added characters (e.g., for
6477: # display of the institutional course section string.
6478: # $info - A frozen hash in which keys are:
6479: # LON-CAPA course number:Institutional course code
6480: # and values are a reference to an array of the
6481: # items to modify -- either institutional sections,
6482: # or institutional course sections (for crosslistings).
6483: # $client - The socket open on the client.
6484: # Returns:
6485: # 1 - continue processing.
6486: #
6487:
6488: sub instsec_reformat_handler {
6489: my ($cmd, $tail, $client) = @_;
6490: my $userinput = "$cmd:$tail";
6491: my ($cdom,$action,$info) = split(/:/,$tail);
6492: my $instsecref = &Apache::lonnet::thaw_unescape($info);
6493: my ($outcome,$result);
6494: eval {
6495: local($SIG{__DIE__})='DEFAULT';
6496: $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
6497: if ($outcome eq 'ok') {
6498: if (ref($instsecref) eq 'HASH') {
6499: foreach my $key (keys(%{$instsecref})) {
6500: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
6501: }
6502: $result =~ s/\&$//;
6503: }
6504: }
6505: };
6506: if (!$@) {
6507: if ($outcome eq 'ok') {
6508: &Reply( $client, \$result, $userinput);
6509: } else {
6510: &Reply($client,\$outcome, $userinput);
6511: }
6512: } else {
6513: &Failure($client,"unknown_cmd\n",$userinput);
6514: }
6515: return 1;
6516: }
6517: ®ister_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
6518:
6519: #
1.542 raeburn 6520: # Validate course owner or co-owners(s) access to enrollment data for all sections
6521: # and crosslistings for a particular course.
6522: #
6523: #
6524: # Formal Parameters:
6525: # $cmd - The command request that got us dispatched.
6526: # $tail - The tail of the command. In this case this is a colon separated
6527: # set of values that will be split into:
6528: # $ownerlist - An escaped comma-separated list of username:domain
6529: # of the course owner, and co-owner(s).
6530: # $cdom - The domain of the course from the institution's
6531: # point of view.
6532: # $classes - Frozen hash of institutional course sections and
6533: # crosslistings.
6534: # $client - The socket open on the client.
6535: # Returns:
6536: # 1 - continue processing.
6537: #
6538:
6539: sub validate_classes_handler {
6540: my ($cmd, $tail, $client) = @_;
6541: my $userinput = "$cmd:$tail";
6542: my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
6543: my $classesref = &Apache::lonnet::thaw_unescape($classes);
6544: my $owners = &unescape($ownerlist);
6545: my $result;
6546: eval {
6547: local($SIG{__DIE__})='DEFAULT';
6548: my %validations;
6549: my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
6550: \%validations);
6551: if ($response eq 'ok') {
6552: foreach my $key (keys(%validations)) {
6553: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
6554: }
6555: $result =~ s/\&$//;
6556: } else {
6557: $result = 'error';
6558: }
6559: };
6560: if (!$@) {
6561: &Reply($client, \$result, $userinput);
6562: } else {
6563: &Failure($client,"unknown_cmd\n",$userinput);
6564: }
6565: return 1;
6566: }
6567: ®ister_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
6568:
6569: #
1.340 raeburn 6570: # Create a password for a new LON-CAPA user added by auto-enrollment.
6571: # Only used for case where authentication method for new user is localauth
1.248 foxr 6572: #
6573: # Formal Parameters:
6574: # $cmd - The command request that got us dispatched.
6575: # $tail - The tail of the command. In this case this is a colon separated
6576: # set of words that will be split into:
1.340 raeburn 6577: # $authparam - An authentication parameter (localauth parameter).
1.248 foxr 6578: # $cdom - The domain of the course from the institution's
6579: # point of view.
6580: # $client - The socket open on the client.
6581: # Returns:
6582: # 1 - continue processing.
6583: #
6584: sub create_auto_enroll_password_handler {
6585: my ($cmd, $tail, $client) = @_;
6586: my $userinput = "$cmd:$tail";
6587:
6588: my ($authparam, $cdom) = split(/:/, $userinput);
6589:
6590: my ($create_passwd,$authchk);
1.582 raeburn 6591: eval {
6592: local($SIG{__DIE__})='DEFAULT';
6593: ($authparam,$create_passwd,$create_passwd,$authchk) =
6594: &localenroll::create_password($authparam,$cdom);
6595: };
1.248 foxr 6596: &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
6597: $userinput);
6598:
6599:
6600: return 1;
6601: }
6602: ®ister_handler("autocreatepassword", \&create_auto_enroll_password_handler,
6603: 0, 1, 0);
6604:
1.522 raeburn 6605: sub auto_export_grades_handler {
6606: my ($cmd, $tail, $client) = @_;
6607: my $userinput = "$cmd:$tail";
6608: my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
6609: my $inforef = &Apache::lonnet::thaw_unescape($info);
6610: my $dataref = &Apache::lonnet::thaw_unescape($data);
6611: my ($outcome,$result);;
6612: eval {
6613: local($SIG{__DIE__})='DEFAULT';
6614: my %rtnhash;
6615: $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
6616: if ($outcome eq 'ok') {
6617: foreach my $key (keys(%rtnhash)) {
6618: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
6619: }
6620: $result =~ s/\&$//;
6621: }
6622: };
6623: if (!$@) {
6624: if ($outcome eq 'ok') {
6625: if ($cipher) {
6626: my $cmdlength=length($result);
6627: $result.=" ";
6628: my $encresult='';
6629: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
6630: $encresult.= unpack("H16",
6631: $cipher->encrypt(substr($result,
6632: $encidx,
6633: 8)));
6634: }
6635: &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
6636: } else {
6637: &Failure( $client, "error:no_key\n", $userinput);
6638: }
6639: } else {
6640: &Reply($client, "$outcome\n", $userinput);
6641: }
6642: } else {
6643: &Failure($client,"export_error\n",$userinput);
6644: }
6645: return 1;
6646: }
6647: ®ister_handler("autoexportgrades", \&auto_export_grades_handler,
1.536 raeburn 6648: 1, 1, 0);
1.522 raeburn 6649:
1.248 foxr 6650: # Retrieve and remove temporary files created by/during autoenrollment.
6651: #
6652: # Formal Parameters:
6653: # $cmd - The command that got us dispatched.
6654: # $tail - The tail of the command. In our case this is a colon
6655: # separated list that will be split into:
1.526 raeburn 6656: # $filename - The name of the file to retrieve.
1.248 foxr 6657: # The filename is given as a path relative to
6658: # the LonCAPA temp file directory.
6659: # $client - Socket open on the client.
6660: #
6661: # Returns:
6662: # 1 - Continue processing.
6663: sub retrieve_auto_file_handler {
6664: my ($cmd, $tail, $client) = @_;
6665: my $userinput = "cmd:$tail";
6666:
6667: my ($filename) = split(/:/, $tail);
6668:
6669: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.521 raeburn 6670:
6671: if ($filename =~m{/\.\./}) {
6672: &Failure($client, "refused\n", $userinput);
1.526 raeburn 6673: } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
6674: &Failure($client, "refused\n", $userinput);
1.521 raeburn 6675: } elsif ( (-e $source) && ($filename ne '') ) {
1.248 foxr 6676: my $reply = '';
6677: if (open(my $fh,$source)) {
6678: while (<$fh>) {
6679: chomp($_);
6680: $_ =~ s/^\s+//g;
6681: $_ =~ s/\s+$//g;
6682: $reply .= $_;
6683: }
6684: close($fh);
6685: &Reply($client, &escape($reply)."\n", $userinput);
6686:
6687: # Does this have to be uncommented??!? (RF).
6688: #
6689: # unlink($source);
6690: } else {
6691: &Failure($client, "error\n", $userinput);
6692: }
6693: } else {
6694: &Failure($client, "error\n", $userinput);
6695: }
6696:
6697:
6698: return 1;
6699: }
6700: ®ister_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
6701:
1.423 raeburn 6702: sub crsreq_checks_handler {
6703: my ($cmd, $tail, $client) = @_;
6704: my $userinput = "$cmd:$tail";
6705: my $dom = $tail;
6706: my $result;
1.519 raeburn 6707: my @reqtypes = ('official','unofficial','community','textbook','placement');
1.423 raeburn 6708: eval {
6709: local($SIG{__DIE__})='DEFAULT';
6710: my %validations;
1.424 raeburn 6711: my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
6712: \%validations);
1.423 raeburn 6713: if ($response eq 'ok') {
6714: foreach my $key (keys(%validations)) {
6715: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
6716: }
6717: $result =~ s/\&$//;
6718: } else {
6719: $result = 'error';
6720: }
6721: };
6722: if (!$@) {
6723: &Reply($client, \$result, $userinput);
6724: } else {
6725: &Failure($client,"unknown_cmd\n",$userinput);
6726: }
6727: return 1;
6728: }
6729: ®ister_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
6730:
6731: sub validate_crsreq_handler {
6732: my ($cmd, $tail, $client) = @_;
6733: my $userinput = "$cmd:$tail";
1.508 raeburn 6734: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423 raeburn 6735: $instcode = &unescape($instcode);
6736: $owner = &unescape($owner);
6737: $crstype = &unescape($crstype);
6738: $inststatuslist = &unescape($inststatuslist);
6739: $instcode = &unescape($instcode);
6740: $instseclist = &unescape($instseclist);
1.508 raeburn 6741: my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423 raeburn 6742: my $outcome;
6743: eval {
6744: local($SIG{__DIE__})='DEFAULT';
6745: $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
6746: $inststatuslist,$instcode,
1.508 raeburn 6747: $instseclist,$custominfo);
1.423 raeburn 6748: };
6749: if (!$@) {
6750: &Reply($client, \$outcome, $userinput);
6751: } else {
6752: &Failure($client,"unknown_cmd\n",$userinput);
6753: }
6754: return 1;
6755: }
6756: ®ister_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
6757:
1.506 raeburn 6758: sub crsreq_update_handler {
6759: my ($cmd, $tail, $client) = @_;
6760: my $userinput = "$cmd:$tail";
1.509 raeburn 6761: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
6762: $accessstart,$accessend,$infohashref) =
1.506 raeburn 6763: split(/:/, $tail);
6764: $crstype = &unescape($crstype);
6765: $action = &unescape($action);
6766: $ownername = &unescape($ownername);
6767: $ownerdomain = &unescape($ownerdomain);
6768: $fullname = &unescape($fullname);
6769: $title = &unescape($title);
6770: $code = &unescape($code);
1.509 raeburn 6771: $accessstart = &unescape($accessstart);
6772: $accessend = &unescape($accessend);
1.506 raeburn 6773: my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
6774: my ($result,$outcome);
6775: eval {
6776: local($SIG{__DIE__})='DEFAULT';
6777: my %rtnhash;
6778: $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
6779: $ownername,$ownerdomain,$fullname,
1.509 raeburn 6780: $title,$code,$accessstart,$accessend,
6781: $incoming,\%rtnhash);
1.506 raeburn 6782: if ($outcome eq 'ok') {
1.515 raeburn 6783: my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.506 raeburn 6784: foreach my $key (keys(%rtnhash)) {
6785: if (grep(/^\Q$key\E/,@posskeys)) {
6786: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
6787: }
6788: }
6789: $result =~ s/\&$//;
6790: }
6791: };
6792: if (!$@) {
6793: if ($outcome eq 'ok') {
6794: &Reply($client, \$result, $userinput);
6795: } else {
6796: &Reply($client, "format_error\n", $userinput);
6797: }
6798: } else {
6799: &Failure($client,"unknown_cmd\n",$userinput);
6800: }
6801: return 1;
6802: }
6803: ®ister_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
6804:
1.248 foxr 6805: #
6806: # Read and retrieve institutional code format (for support form).
6807: # Formal Parameters:
6808: # $cmd - Command that dispatched us.
6809: # $tail - Tail of the command. In this case it conatins
6810: # the course domain and the coursename.
6811: # $client - Socket open on the client.
6812: # Returns:
6813: # 1 - Continue processing.
6814: #
6815: sub get_institutional_code_format_handler {
6816: my ($cmd, $tail, $client) = @_;
6817: my $userinput = "$cmd:$tail";
6818:
6819: my $reply;
6820: my($cdom,$course) = split(/:/,$tail);
6821: my @pairs = split/\&/,$course;
6822: my %instcodes = ();
6823: my %codes = ();
6824: my @codetitles = ();
6825: my %cat_titles = ();
6826: my %cat_order = ();
6827: foreach (@pairs) {
6828: my ($key,$value) = split/=/,$_;
6829: $instcodes{&unescape($key)} = &unescape($value);
6830: }
1.582 raeburn 6831: my $formatreply;
6832: eval {
6833: local($SIG{__DIE__})='DEFAULT';
6834: $formatreply = &localenroll::instcode_format($cdom,
6835: \%instcodes,
6836: \%codes,
6837: \@codetitles,
6838: \%cat_titles,
6839: \%cat_order);
6840: };
1.248 foxr 6841: if ($formatreply eq 'ok') {
1.365 albertel 6842: my $codes_str = &Apache::lonnet::hash2str(%codes);
6843: my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
6844: my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
6845: my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248 foxr 6846: &Reply($client,
6847: $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
6848: .$cat_order_str."\n",
6849: $userinput);
6850: } else {
6851: # this else branch added by RF since if not ok, lonc will
6852: # hang waiting on reply until timeout.
6853: #
6854: &Reply($client, "format_error\n", $userinput);
6855: }
6856:
6857: return 1;
6858: }
1.265 albertel 6859: ®ister_handler("autoinstcodeformat",
6860: \&get_institutional_code_format_handler,0,1,0);
1.246 foxr 6861:
1.345 raeburn 6862: sub get_institutional_defaults_handler {
6863: my ($cmd, $tail, $client) = @_;
6864: my $userinput = "$cmd:$tail";
6865:
6866: my $dom = $tail;
6867: my %defaults_hash;
6868: my @code_order;
6869: my $outcome;
6870: eval {
6871: local($SIG{__DIE__})='DEFAULT';
6872: $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
6873: \@code_order);
6874: };
6875: if (!$@) {
6876: if ($outcome eq 'ok') {
6877: my $result='';
6878: while (my ($key,$value) = each(%defaults_hash)) {
6879: $result.=&escape($key).'='.&escape($value).'&';
6880: }
6881: $result .= 'code_order='.&escape(join('&',@code_order));
1.387 albertel 6882: &Reply($client,\$result,$userinput);
1.345 raeburn 6883: } else {
6884: &Reply($client,"error\n", $userinput);
6885: }
6886: } else {
6887: &Failure($client,"unknown_cmd\n",$userinput);
6888: }
6889: }
6890: ®ister_handler("autoinstcodedefaults",
6891: \&get_institutional_defaults_handler,0,1,0);
6892:
1.416 raeburn 6893: sub get_possible_instcodes_handler {
6894: my ($cmd, $tail, $client) = @_;
6895: my $userinput = "$cmd:$tail";
6896:
6897: my $reply;
6898: my $cdom = $tail;
1.417 raeburn 6899: my (@codetitles,%cat_titles,%cat_order,@code_order);
1.582 raeburn 6900: my $formatreply;
6901: eval {
6902: local($SIG{__DIE__})='DEFAULT';
6903: $formatreply = &localenroll::possible_instcodes($cdom,
6904: \@codetitles,
6905: \%cat_titles,
6906: \%cat_order,
6907: \@code_order);
6908: };
1.416 raeburn 6909: if ($formatreply eq 'ok') {
6910: my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417 raeburn 6911: $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416 raeburn 6912: foreach my $key (keys(%cat_titles)) {
6913: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
6914: }
6915: $result =~ s/\&$//;
6916: $result .= ':';
6917: foreach my $key (keys(%cat_order)) {
6918: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
6919: }
6920: $result =~ s/\&$//;
6921: &Reply($client,\$result,$userinput);
6922: } else {
6923: &Reply($client, "format_error\n", $userinput);
6924: }
6925: return 1;
6926: }
6927: ®ister_handler("autopossibleinstcodes",
6928: \&get_possible_instcodes_handler,0,1,0);
6929:
1.381 raeburn 6930: sub get_institutional_user_rules {
6931: my ($cmd, $tail, $client) = @_;
6932: my $userinput = "$cmd:$tail";
6933: my $dom = &unescape($tail);
6934: my (%rules_hash,@rules_order);
6935: my $outcome;
6936: eval {
6937: local($SIG{__DIE__})='DEFAULT';
6938: $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
6939: };
6940: if (!$@) {
6941: if ($outcome eq 'ok') {
6942: my $result;
6943: foreach my $key (keys(%rules_hash)) {
6944: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6945: }
6946: $result =~ s/\&$//;
6947: $result .= ':';
6948: if (@rules_order > 0) {
6949: foreach my $item (@rules_order) {
6950: $result .= &escape($item).'&';
6951: }
6952: }
6953: $result =~ s/\&$//;
1.387 albertel 6954: &Reply($client,\$result,$userinput);
1.381 raeburn 6955: } else {
6956: &Reply($client,"error\n", $userinput);
6957: }
6958: } else {
6959: &Failure($client,"unknown_cmd\n",$userinput);
6960: }
6961: }
6962: ®ister_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
6963:
1.389 raeburn 6964: sub get_institutional_id_rules {
6965: my ($cmd, $tail, $client) = @_;
6966: my $userinput = "$cmd:$tail";
6967: my $dom = &unescape($tail);
6968: my (%rules_hash,@rules_order);
6969: my $outcome;
6970: eval {
6971: local($SIG{__DIE__})='DEFAULT';
6972: $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
6973: };
6974: if (!$@) {
6975: if ($outcome eq 'ok') {
6976: my $result;
6977: foreach my $key (keys(%rules_hash)) {
6978: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6979: }
6980: $result =~ s/\&$//;
6981: $result .= ':';
6982: if (@rules_order > 0) {
6983: foreach my $item (@rules_order) {
6984: $result .= &escape($item).'&';
6985: }
6986: }
6987: $result =~ s/\&$//;
6988: &Reply($client,\$result,$userinput);
6989: } else {
6990: &Reply($client,"error\n", $userinput);
6991: }
6992: } else {
6993: &Failure($client,"unknown_cmd\n",$userinput);
6994: }
6995: }
6996: ®ister_handler("instidrules",\&get_institutional_id_rules,0,1,0);
6997:
1.397 raeburn 6998: sub get_institutional_selfcreate_rules {
1.396 raeburn 6999: my ($cmd, $tail, $client) = @_;
7000: my $userinput = "$cmd:$tail";
7001: my $dom = &unescape($tail);
7002: my (%rules_hash,@rules_order);
7003: my $outcome;
7004: eval {
7005: local($SIG{__DIE__})='DEFAULT';
1.397 raeburn 7006: $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396 raeburn 7007: };
7008: if (!$@) {
7009: if ($outcome eq 'ok') {
7010: my $result;
7011: foreach my $key (keys(%rules_hash)) {
7012: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
7013: }
7014: $result =~ s/\&$//;
7015: $result .= ':';
7016: if (@rules_order > 0) {
7017: foreach my $item (@rules_order) {
7018: $result .= &escape($item).'&';
7019: }
7020: }
7021: $result =~ s/\&$//;
7022: &Reply($client,\$result,$userinput);
7023: } else {
7024: &Reply($client,"error\n", $userinput);
7025: }
7026: } else {
7027: &Failure($client,"unknown_cmd\n",$userinput);
7028: }
7029: }
1.397 raeburn 7030: ®ister_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396 raeburn 7031:
1.575 raeburn 7032: sub get_unamemap_rules {
7033: my ($cmd, $tail, $client) = @_;
7034: my $userinput = "$cmd:$tail";
7035: my $dom = &unescape($tail);
7036: my (%rules_hash,@rules_order);
7037: my $outcome;
7038: eval {
7039: local($SIG{__DIE__})='DEFAULT';
7040: $outcome = &localenroll::unamemap_rules($dom,\%rules_hash,\@rules_order);
7041: };
7042: if (!$@) {
7043: if ($outcome eq 'ok') {
7044: my $result;
7045: foreach my $key (keys(%rules_hash)) {
7046: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
7047: }
7048: $result =~ s/\&$//;
7049: $result .= ':';
7050: if (@rules_order > 0) {
7051: foreach my $item (@rules_order) {
7052: $result .= &escape($item).'&';
7053: }
7054: }
7055: $result =~ s/\&$//;
7056: &Reply($client,\$result,$userinput);
7057: } else {
7058: &Reply($client,"error\n", $userinput);
7059: }
7060: } else {
7061: &Failure($client,"unknown_cmd\n",$userinput);
7062: }
7063: }
7064: ®ister_handler("unamemaprules",\&get_unamemap_rules,0,1,0);
1.381 raeburn 7065:
7066: sub institutional_username_check {
7067: my ($cmd, $tail, $client) = @_;
7068: my $userinput = "$cmd:$tail";
7069: my %rulecheck;
7070: my $outcome;
7071: my ($udom,$uname,@rules) = split(/:/,$tail);
7072: $udom = &unescape($udom);
7073: $uname = &unescape($uname);
7074: @rules = map {&unescape($_);} (@rules);
7075: eval {
7076: local($SIG{__DIE__})='DEFAULT';
7077: $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
7078: };
7079: if (!$@) {
7080: if ($outcome eq 'ok') {
7081: my $result='';
7082: foreach my $key (keys(%rulecheck)) {
7083: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
7084: }
1.387 albertel 7085: &Reply($client,\$result,$userinput);
1.381 raeburn 7086: } else {
7087: &Reply($client,"error\n", $userinput);
7088: }
7089: } else {
7090: &Failure($client,"unknown_cmd\n",$userinput);
7091: }
7092: }
7093: ®ister_handler("instrulecheck",\&institutional_username_check,0,1,0);
7094:
1.389 raeburn 7095: sub institutional_id_check {
7096: my ($cmd, $tail, $client) = @_;
7097: my $userinput = "$cmd:$tail";
7098: my %rulecheck;
7099: my $outcome;
7100: my ($udom,$id,@rules) = split(/:/,$tail);
7101: $udom = &unescape($udom);
7102: $id = &unescape($id);
7103: @rules = map {&unescape($_);} (@rules);
7104: eval {
7105: local($SIG{__DIE__})='DEFAULT';
7106: $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
7107: };
7108: if (!$@) {
7109: if ($outcome eq 'ok') {
7110: my $result='';
7111: foreach my $key (keys(%rulecheck)) {
7112: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
7113: }
7114: &Reply($client,\$result,$userinput);
7115: } else {
7116: &Reply($client,"error\n", $userinput);
7117: }
7118: } else {
7119: &Failure($client,"unknown_cmd\n",$userinput);
7120: }
7121: }
7122: ®ister_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345 raeburn 7123:
1.397 raeburn 7124: sub institutional_selfcreate_check {
1.396 raeburn 7125: my ($cmd, $tail, $client) = @_;
7126: my $userinput = "$cmd:$tail";
7127: my %rulecheck;
7128: my $outcome;
7129: my ($udom,$email,@rules) = split(/:/,$tail);
7130: $udom = &unescape($udom);
7131: $email = &unescape($email);
7132: @rules = map {&unescape($_);} (@rules);
7133: eval {
7134: local($SIG{__DIE__})='DEFAULT';
1.397 raeburn 7135: $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396 raeburn 7136: };
7137: if (!$@) {
7138: if ($outcome eq 'ok') {
7139: my $result='';
7140: foreach my $key (keys(%rulecheck)) {
7141: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
7142: }
7143: &Reply($client,\$result,$userinput);
7144: } else {
7145: &Reply($client,"error\n", $userinput);
7146: }
7147: } else {
7148: &Failure($client,"unknown_cmd\n",$userinput);
7149: }
7150: }
1.397 raeburn 7151: ®ister_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396 raeburn 7152:
1.317 raeburn 7153: # Get domain specific conditions for import of student photographs to a course
7154: #
7155: # Retrieves information from photo_permission subroutine in localenroll.
7156: # Returns outcome (ok) if no processing errors, and whether course owner is
7157: # required to accept conditions of use (yes/no).
7158: #
7159: #
7160: sub photo_permission_handler {
7161: my ($cmd, $tail, $client) = @_;
7162: my $userinput = "$cmd:$tail";
7163: my $cdom = $tail;
7164: my ($perm_reqd,$conditions);
1.320 albertel 7165: my $outcome;
7166: eval {
7167: local($SIG{__DIE__})='DEFAULT';
7168: $outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
7169: \$conditions);
7170: };
7171: if (!$@) {
7172: &Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
7173: $userinput);
7174: } else {
7175: &Failure($client,"unknown_cmd\n",$userinput);
7176: }
7177: return 1;
1.317 raeburn 7178: }
7179: ®ister_handler("autophotopermission",\&photo_permission_handler,0,1,0);
7180:
7181: #
7182: # Checks if student photo is available for a user in the domain, in the user's
7183: # directory (in /userfiles/internal/studentphoto.jpg).
7184: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
7185: # the student's photo.
7186:
7187: sub photo_check_handler {
7188: my ($cmd, $tail, $client) = @_;
7189: my $userinput = "$cmd:$tail";
7190: my ($udom,$uname,$pid) = split(/:/,$tail);
7191: $udom = &unescape($udom);
7192: $uname = &unescape($uname);
7193: $pid = &unescape($pid);
7194: my $path=&propath($udom,$uname).'/userfiles/internal/';
7195: if (!-e $path) {
7196: &mkpath($path);
7197: }
7198: my $response;
7199: my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
7200: $result .= ':'.$response;
7201: &Reply($client, &escape($result)."\n",$userinput);
1.320 albertel 7202: return 1;
1.317 raeburn 7203: }
7204: ®ister_handler("autophotocheck",\&photo_check_handler,0,1,0);
7205:
7206: #
7207: # Retrieve information from localenroll about whether to provide a button
7208: # for users who have enbled import of student photos to initiate an
7209: # update of photo files for registered students. Also include
7210: # comment to display alongside button.
7211:
7212: sub photo_choice_handler {
7213: my ($cmd, $tail, $client) = @_;
7214: my $userinput = "$cmd:$tail";
7215: my $cdom = &unescape($tail);
1.320 albertel 7216: my ($update,$comment);
7217: eval {
7218: local($SIG{__DIE__})='DEFAULT';
7219: ($update,$comment) = &localenroll::manager_photo_update($cdom);
7220: };
7221: if (!$@) {
7222: &Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
7223: } else {
7224: &Failure($client,"unknown_cmd\n",$userinput);
7225: }
7226: return 1;
1.317 raeburn 7227: }
7228: ®ister_handler("autophotochoice",\&photo_choice_handler,0,1,0);
7229:
1.265 albertel 7230: #
7231: # Gets a student's photo to exist (in the correct image type) in the user's
7232: # directory.
7233: # Formal Parameters:
7234: # $cmd - The command request that got us dispatched.
7235: # $tail - A colon separated set of words that will be split into:
7236: # $domain - student's domain
7237: # $uname - student username
7238: # $type - image type desired
7239: # $client - The socket open on the client.
7240: # Returns:
7241: # 1 - continue processing.
1.317 raeburn 7242:
1.265 albertel 7243: sub student_photo_handler {
7244: my ($cmd, $tail, $client) = @_;
1.317 raeburn 7245: my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265 albertel 7246:
1.317 raeburn 7247: my $path=&propath($domain,$uname). '/userfiles/internal/';
7248: my $filename = 'studentphoto.'.$ext;
7249: if ($type eq 'thumbnail') {
7250: $filename = 'studentphoto_tn.'.$ext;
7251: }
7252: if (-e $path.$filename) {
1.265 albertel 7253: &Reply($client,"ok\n","$cmd:$tail");
7254: return 1;
7255: }
7256: &mkpath($path);
1.317 raeburn 7257: my $file;
7258: if ($type eq 'thumbnail') {
1.320 albertel 7259: eval {
7260: local($SIG{__DIE__})='DEFAULT';
7261: $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
7262: };
1.317 raeburn 7263: } else {
7264: $file=&localstudentphoto::fetch($domain,$uname);
7265: }
1.265 albertel 7266: if (!$file) {
7267: &Failure($client,"unavailable\n","$cmd:$tail");
7268: return 1;
7269: }
1.317 raeburn 7270: if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
7271: if (-e $path.$filename) {
1.265 albertel 7272: &Reply($client,"ok\n","$cmd:$tail");
7273: return 1;
7274: }
7275: &Failure($client,"unable_to_convert\n","$cmd:$tail");
7276: return 1;
7277: }
7278: ®ister_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246 foxr 7279:
1.361 raeburn 7280: sub inst_usertypes_handler {
7281: my ($cmd, $domain, $client) = @_;
7282: my $res;
7283: my $userinput = $cmd.":".$domain; # For logging purposes.
1.370 albertel 7284: my (%typeshash,@order,$result);
7285: eval {
7286: local($SIG{__DIE__})='DEFAULT';
7287: $result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
7288: };
7289: if ($result eq 'ok') {
1.361 raeburn 7290: if (keys(%typeshash) > 0) {
7291: foreach my $key (keys(%typeshash)) {
7292: $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
7293: }
7294: }
7295: $res=~s/\&$//;
7296: $res .= ':';
7297: if (@order > 0) {
7298: foreach my $item (@order) {
7299: $res .= &escape($item).'&';
7300: }
7301: }
7302: $res=~s/\&$//;
7303: }
1.387 albertel 7304: &Reply($client, \$res, $userinput);
1.361 raeburn 7305: return 1;
7306: }
7307: ®ister_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
7308:
1.264 albertel 7309: # mkpath makes all directories for a file, expects an absolute path with a
7310: # file or a trailing / if just a dir is passed
7311: # returns 1 on success 0 on failure
7312: sub mkpath {
7313: my ($file)=@_;
7314: my @parts=split(/\//,$file,-1);
7315: my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
7316: for (my $i=3;$i<= ($#parts-1);$i++) {
1.265 albertel 7317: $now.='/'.$parts[$i];
1.264 albertel 7318: if (!-e $now) {
7319: if (!mkdir($now,0770)) { return 0; }
7320: }
7321: }
7322: return 1;
7323: }
7324:
1.207 foxr 7325: #---------------------------------------------------------------
7326: #
7327: # Getting, decoding and dispatching requests:
7328: #
7329: #
7330: # Get a Request:
7331: # Gets a Request message from the client. The transaction
7332: # is defined as a 'line' of text. We remove the new line
7333: # from the text line.
1.226 foxr 7334: #
1.211 albertel 7335: sub get_request {
1.207 foxr 7336: my $input = <$client>;
7337: chomp($input);
1.226 foxr 7338:
1.234 foxr 7339: &Debug("get_request: Request = $input\n");
1.207 foxr 7340:
7341: &status('Processing '.$clientname.':'.$input);
7342:
7343: return $input;
7344: }
1.212 foxr 7345: #---------------------------------------------------------------
7346: #
7347: # Process a request. This sub should shrink as each action
7348: # gets farmed out into a separat sub that is registered
7349: # with the dispatch hash.
7350: #
7351: # Parameters:
7352: # user_input - The request received from the client (lonc).
1.525 raeburn 7353: #
1.212 foxr 7354: # Returns:
7355: # true to keep processing, false if caller should exit.
7356: #
7357: sub process_request {
1.525 raeburn 7358: my ($userinput) = @_; # Easier for now to break style than to
7359: # fix all the userinput -> user_input.
1.212 foxr 7360: my $wasenc = 0; # True if request was encrypted.
7361: # ------------------------------------------------------------ See if encrypted
1.322 albertel 7362: # for command
7363: # sethost:<server>
7364: # <command>:<args>
7365: # we just send it to the processor
7366: # for
7367: # sethost:<server>:<command>:<args>
7368: # we do the implict set host and then do the command
7369: if ($userinput =~ /^sethost:/) {
7370: (my $cmd,my $newid,$userinput) = split(':',$userinput,3);
7371: if (defined($userinput)) {
7372: &sethost("$cmd:$newid");
7373: } else {
7374: $userinput = "$cmd:$newid";
7375: }
7376: }
7377:
1.212 foxr 7378: if ($userinput =~ /^enc/) {
7379: $userinput = decipher($userinput);
7380: $wasenc=1;
7381: if(!$userinput) { # Cipher not defined.
1.251 foxr 7382: &Failure($client, "error: Encrypted data without negotated key\n");
1.212 foxr 7383: return 0;
7384: }
7385: }
7386: Debug("process_request: $userinput\n");
7387:
1.213 foxr 7388: #
7389: # The 'correct way' to add a command to lond is now to
7390: # write a sub to execute it and Add it to the command dispatch
7391: # hash via a call to register_handler.. The comments to that
7392: # sub should give you enough to go on to show how to do this
7393: # along with the examples that are building up as this code
7394: # is getting refactored. Until all branches of the
7395: # if/elseif monster below have been factored out into
7396: # separate procesor subs, if the dispatch hash is missing
7397: # the command keyword, we will fall through to the remainder
7398: # of the if/else chain below in order to keep this thing in
7399: # working order throughout the transmogrification.
7400:
7401: my ($command, $tail) = split(/:/, $userinput, 2);
7402: chomp($command);
7403: chomp($tail);
7404: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
1.214 foxr 7405: $command =~ s/(\r)//; # And this too for parameterless commands.
7406: if(!$tail) {
7407: $tail =""; # defined but blank.
7408: }
1.213 foxr 7409:
7410: &Debug("Command received: $command, encoded = $wasenc");
7411:
7412: if(defined $Dispatcher{$command}) {
7413:
7414: my $dispatch_info = $Dispatcher{$command};
7415: my $handler = $$dispatch_info[0];
7416: my $need_encode = $$dispatch_info[1];
7417: my $client_types = $$dispatch_info[2];
7418: Debug("Matched dispatch hash: mustencode: $need_encode "
7419: ."ClientType $client_types");
7420:
7421: # Validate the request:
7422:
7423: my $ok = 1;
7424: my $requesterprivs = 0;
7425: if(&isClient()) {
7426: $requesterprivs |= $CLIENT_OK;
7427: }
7428: if(&isManager()) {
7429: $requesterprivs |= $MANAGER_OK;
7430: }
7431: if($need_encode && (!$wasenc)) {
7432: Debug("Must encode but wasn't: $need_encode $wasenc");
7433: $ok = 0;
7434: }
7435: if(($client_types & $requesterprivs) == 0) {
7436: Debug("Client not privileged to do this operation");
7437: $ok = 0;
7438: }
1.525 raeburn 7439: if ($ok) {
1.535 raeburn 7440: my $realcommand = $command;
7441: if ($command eq 'querysend') {
7442: my ($query,$rest)=split(/\:/,$tail,2);
7443: $query=~s/\n*$//g;
7444: my @possqueries =
7445: qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
7446: if (grep(/^\Q$query\E$/,@possqueries)) {
7447: $command .= '_'.$query;
7448: } elsif ($query eq 'prepare activity log') {
7449: $command .= '_activitylog';
7450: }
7451: }
1.525 raeburn 7452: if (ref($trust{$command}) eq 'HASH') {
7453: my $donechecks;
7454: if ($trust{$command}{'anywhere'}) {
7455: $donechecks = 1;
7456: } elsif ($trust{$command}{'manageronly'}) {
7457: unless (&isManager()) {
7458: $ok = 0;
7459: }
7460: $donechecks = 1;
7461: } elsif ($trust{$command}{'institutiononly'}) {
7462: unless ($clientsameinst) {
7463: $ok = 0;
7464: }
7465: $donechecks = 1;
7466: } elsif ($clientsameinst) {
7467: $donechecks = 1;
7468: }
7469: unless ($donechecks) {
7470: foreach my $rule (keys(%{$trust{$command}})) {
7471: next if ($rule eq 'remote');
7472: if ($trust{$command}{$rule}) {
7473: if ($clientprohibited{$rule}) {
7474: $ok = 0;
7475: } else {
7476: $ok = 1;
7477: $donechecks = 1;
7478: last;
7479: }
7480: }
7481: }
7482: }
7483: unless ($donechecks) {
7484: if ($trust{$command}{'remote'}) {
7485: if ($clientremoteok) {
7486: $ok = 1;
7487: } else {
7488: $ok = 0;
7489: }
7490: }
7491: }
7492: }
1.535 raeburn 7493: $command = $realcommand;
1.525 raeburn 7494: }
1.213 foxr 7495:
7496: if($ok) {
7497: Debug("Dispatching to handler $command $tail");
7498: my $keep_going = &$handler($command, $tail, $client);
7499: return $keep_going;
7500: } else {
7501: Debug("Refusing to dispatch because client did not match requirements");
7502: Failure($client, "refused\n", $userinput);
7503: return 1;
7504: }
1.525 raeburn 7505: }
1.213 foxr 7506:
1.262 foxr 7507: print $client "unknown_cmd\n";
1.212 foxr 7508: # -------------------------------------------------------------------- complete
7509: Debug("process_request - returning 1");
7510: return 1;
7511: }
1.207 foxr 7512: #
7513: # Decipher encoded traffic
7514: # Parameters:
7515: # input - Encoded data.
7516: # Returns:
7517: # Decoded data or undef if encryption key was not yet negotiated.
7518: # Implicit input:
7519: # cipher - This global holds the negotiated encryption key.
7520: #
1.211 albertel 7521: sub decipher {
1.207 foxr 7522: my ($input) = @_;
7523: my $output = '';
1.212 foxr 7524:
7525:
1.207 foxr 7526: if($cipher) {
7527: my($enc, $enclength, $encinput) = split(/:/, $input);
7528: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
7529: $output .=
7530: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
7531: }
7532: return substr($output, 0, $enclength);
7533: } else {
7534: return undef;
7535: }
7536: }
7537:
7538: #
7539: # Register a command processor. This function is invoked to register a sub
7540: # to process a request. Once registered, the ProcessRequest sub can automatically
7541: # dispatch requests to an appropriate sub, and do the top level validity checking
7542: # as well:
7543: # - Is the keyword recognized.
7544: # - Is the proper client type attempting the request.
7545: # - Is the request encrypted if it has to be.
7546: # Parameters:
7547: # $request_name - Name of the request being registered.
7548: # This is the command request that will match
7549: # against the hash keywords to lookup the information
7550: # associated with the dispatch information.
7551: # $procedure - Reference to a sub to call to process the request.
7552: # All subs get called as follows:
7553: # Procedure($cmd, $tail, $replyfd, $key)
7554: # $cmd - the actual keyword that invoked us.
7555: # $tail - the tail of the request that invoked us.
7556: # $replyfd- File descriptor connected to the client
7557: # $must_encode - True if the request must be encoded to be good.
7558: # $client_ok - True if it's ok for a client to request this.
7559: # $manager_ok - True if it's ok for a manager to request this.
7560: # Side effects:
7561: # - On success, the Dispatcher hash has an entry added for the key $RequestName
7562: # - On failure, the program will die as it's a bad internal bug to try to
7563: # register a duplicate command handler.
7564: #
1.211 albertel 7565: sub register_handler {
1.212 foxr 7566: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
1.207 foxr 7567:
7568: # Don't allow duplication#
7569:
7570: if (defined $Dispatcher{$request_name}) {
7571: die "Attempting to define a duplicate request handler for $request_name\n";
7572: }
7573: # Build the client type mask:
7574:
7575: my $client_type_mask = 0;
7576: if($client_ok) {
7577: $client_type_mask |= $CLIENT_OK;
7578: }
7579: if($manager_ok) {
7580: $client_type_mask |= $MANAGER_OK;
7581: }
7582:
7583: # Enter the hash:
7584:
7585: my @entry = ($procedure, $must_encode, $client_type_mask);
7586:
7587: $Dispatcher{$request_name} = \@entry;
7588:
7589: }
7590:
7591:
7592: #------------------------------------------------------------------
7593:
7594:
7595:
7596:
1.141 foxr 7597: #
1.96 foxr 7598: # Convert an error return code from lcpasswd to a string value.
7599: #
7600: sub lcpasswdstrerror {
7601: my $ErrorCode = shift;
1.97 foxr 7602: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 7603: return "lcpasswd Unrecognized error return value ".$ErrorCode;
7604: } else {
1.98 foxr 7605: return $passwderrors[$ErrorCode];
1.96 foxr 7606: }
7607: }
7608:
1.23 harris41 7609: # grabs exception and records it to log before exiting
7610: sub catchexception {
1.27 albertel 7611: my ($error)=@_;
1.25 www 7612: $SIG{'QUIT'}='DEFAULT';
7613: $SIG{__DIE__}='DEFAULT';
1.165 albertel 7614: &status("Catching exception");
1.190 albertel 7615: &logthis("<font color='red'>CRITICAL: "
1.373 albertel 7616: ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27 albertel 7617: ."a crash with this error msg->[$error]</font>");
1.57 www 7618: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 7619: if ($client) { print $client "error: $error\n"; }
1.59 www 7620: $server->close();
1.27 albertel 7621: die($error);
1.23 harris41 7622: }
1.63 www 7623: sub timeout {
1.165 albertel 7624: &status("Handling Timeout");
1.190 albertel 7625: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63 www 7626: &catchexception('Timeout');
7627: }
1.22 harris41 7628: # -------------------------------- Set signal handlers to record abnormal exits
7629:
1.226 foxr 7630:
1.22 harris41 7631: $SIG{'QUIT'}=\&catchexception;
7632: $SIG{__DIE__}=\&catchexception;
7633:
1.81 matthew 7634: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 7635: &status("Read loncapa.conf and loncapa_apache.conf");
7636: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 7637: %perlvar=%{$perlvarref};
1.80 harris41 7638: undef $perlvarref;
1.19 www 7639:
1.35 harris41 7640: # ----------------------------- Make sure this process is running from user=www
7641: my $wwwid=getpwnam('www');
7642: if ($wwwid!=$<) {
1.581 raeburn 7643: my $emailto="$perlvar{'lonAdmEMail'} $perlvar{'lonSysEMail'}";
1.134 albertel 7644: my $subj="LON: $currenthostid User ID mismatch";
1.550 raeburn 7645: system("echo 'User ID mismatch. lond must be run as user www.' |".
7646: " mail -s '$subj' $emailto > /dev/null");
1.35 harris41 7647: exit 1;
7648: }
7649:
1.19 www 7650: # --------------------------------------------- Check if other instance running
7651:
7652: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
7653:
7654: if (-e $pidfile) {
7655: my $lfh=IO::File->new("$pidfile");
7656: my $pide=<$lfh>;
7657: chomp($pide);
1.29 harris41 7658: if (kill 0 => $pide) { die "already running"; }
1.19 www 7659: }
1.1 albertel 7660:
7661: # ------------------------------------------------------------- Read hosts file
7662:
7663:
7664:
7665: # establish SERVER socket, bind and listen.
7666: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
7667: Type => SOCK_STREAM,
7668: Proto => 'tcp',
1.469 foxr 7669: ReuseAddr => 1,
1.1 albertel 7670: Listen => 10 )
1.29 harris41 7671: or die "making socket: $@\n";
1.1 albertel 7672:
7673: # --------------------------------------------------------- Do global variables
7674:
7675: # global variables
7676:
1.134 albertel 7677: my %children = (); # keys are current child process IDs
1.1 albertel 7678:
7679: sub REAPER { # takes care of dead children
7680: $SIG{CHLD} = \&REAPER;
1.165 albertel 7681: &status("Handling child death");
1.178 foxr 7682: my $pid;
7683: do {
7684: $pid = waitpid(-1,&WNOHANG());
7685: if (defined($children{$pid})) {
7686: &logthis("Child $pid died");
7687: delete($children{$pid});
1.183 albertel 7688: } elsif ($pid > 0) {
1.178 foxr 7689: &logthis("Unknown Child $pid died");
7690: }
7691: } while ( $pid > 0 );
7692: foreach my $child (keys(%children)) {
7693: $pid = waitpid($child,&WNOHANG());
7694: if ($pid > 0) {
7695: &logthis("Child $child - $pid looks like we missed it's death");
7696: delete($children{$pid});
7697: }
1.176 albertel 7698: }
1.165 albertel 7699: &status("Finished Handling child death");
1.1 albertel 7700: }
7701:
7702: sub HUNTSMAN { # signal handler for SIGINT
1.165 albertel 7703: &status("Killing children (INT)");
1.1 albertel 7704: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
7705: kill 'INT' => keys %children;
1.59 www 7706: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 7707: my $execdir=$perlvar{'lonDaemons'};
7708: unlink("$execdir/logs/lond.pid");
1.190 albertel 7709: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165 albertel 7710: &status("Done killing children");
1.1 albertel 7711: exit; # clean up with dignity
7712: }
7713:
7714: sub HUPSMAN { # signal handler for SIGHUP
7715: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.165 albertel 7716: &status("Killing children for restart (HUP)");
1.1 albertel 7717: kill 'INT' => keys %children;
1.59 www 7718: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190 albertel 7719: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134 albertel 7720: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 7721: unlink("$execdir/logs/lond.pid");
1.165 albertel 7722: &status("Restarting self (HUP)");
1.1 albertel 7723: exec("$execdir/lond"); # here we go again
7724: }
7725:
1.144 foxr 7726: #
1.148 foxr 7727: # Reload the Apache daemon's state.
1.150 foxr 7728: # This is done by invoking /home/httpd/perl/apachereload
7729: # a setuid perl script that can be root for us to do this job.
1.148 foxr 7730: #
7731: sub ReloadApache {
1.473 raeburn 7732: # --------------------------- Handle case of another apachereload process (locking)
1.474 raeburn 7733: if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
7734: my $execdir = $perlvar{'lonDaemons'};
7735: my $script = $execdir."/apachereload";
7736: system($script);
7737: unlink('/tmp/lock_apachereload'); # Remove the lock file.
7738: }
1.148 foxr 7739: }
7740:
7741: #
1.144 foxr 7742: # Called in response to a USR2 signal.
7743: # - Reread hosts.tab
7744: # - All children connected to hosts that were removed from hosts.tab
7745: # are killed via SIGINT
7746: # - All children connected to previously existing hosts are sent SIGUSR1
7747: # - Our internal hosts hash is updated to reflect the new contents of
7748: # hosts.tab causing connections from hosts added to hosts.tab to
7749: # now be honored.
7750: #
7751: sub UpdateHosts {
1.165 albertel 7752: &status("Reload hosts.tab");
1.147 foxr 7753: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 7754: #
7755: # The %children hash has the set of IP's we currently have children
7756: # on. These need to be matched against records in the hosts.tab
7757: # Any ip's no longer in the table get killed off they correspond to
7758: # either dropped or changed hosts. Note that the re-read of the table
7759: # will take care of new and changed hosts as connections come into being.
7760:
1.371 albertel 7761: &Apache::lonnet::reset_hosts_info();
1.532 raeburn 7762: my %active;
1.148 foxr 7763:
1.368 albertel 7764: foreach my $child (keys(%children)) {
1.148 foxr 7765: my $childip = $children{$child};
1.374 albertel 7766: if ($childip ne '127.0.0.1'
7767: && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149 foxr 7768: logthis('<font color="blue"> UpdateHosts killing child '
7769: ." $child for ip $childip </font>");
1.148 foxr 7770: kill('INT', $child);
1.149 foxr 7771: } else {
1.532 raeburn 7772: $active{$child} = $childip;
1.149 foxr 7773: logthis('<font color="green"> keeping child for ip '
7774: ." $childip (pid=$child) </font>");
1.148 foxr 7775: }
7776: }
1.532 raeburn 7777:
7778: my %oldconf = %secureconf;
7779: my %connchange;
1.555 raeburn 7780: if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.545 raeburn 7781: logthis('<font color="blue"> Reloaded SSL connection rules and cleared CRL checking history </font>');
1.532 raeburn 7782: } else {
1.545 raeburn 7783: logthis('<font color="yellow"> Failed to reload SSL connection rules and clear CRL checking history </font>');
1.532 raeburn 7784: }
7785: if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
7786: foreach my $type ('dom','intdom','other') {
7787: if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
7788: (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
7789: $connchange{$type} = 1;
7790: }
7791: }
7792: }
7793: if (keys(%connchange)) {
7794: foreach my $child (keys(%active)) {
7795: my $childip = $active{$child};
7796: if ($childip ne '127.0.0.1') {
7797: my $childhostname = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
7798: if ($childhostname ne '') {
7799: my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
7800: my ($samedom,$sameinst) = &set_client_info($childlonhost);
7801: if ($samedom) {
7802: if ($connchange{'dom'}) {
7803: logthis('<font color="blue"> UpdateHosts killing child '
7804: ." $child for ip $childip </font>");
7805: kill('INT', $child);
7806: }
7807: } elsif ($sameinst) {
7808: if ($connchange{'intdom'}) {
7809: logthis('<font color="blue"> UpdateHosts killing child '
7810: ." $child for ip $childip </font>");
7811: kill('INT', $child);
7812: }
7813: } else {
7814: if ($connchange{'other'}) {
7815: logthis('<font color="blue"> UpdateHosts killing child '
7816: ." $child for ip $childip </font>");
7817: kill('INT', $child);
7818: }
7819: }
7820: }
7821: }
7822: }
7823: }
1.148 foxr 7824: ReloadApache;
1.165 albertel 7825: &status("Finished reloading hosts.tab");
1.144 foxr 7826: }
7827:
1.57 www 7828: sub checkchildren {
1.165 albertel 7829: &status("Checking on the children (sending signals)");
1.57 www 7830: &initnewstatus();
7831: &logstatus();
7832: &logthis('Going to check on the children');
1.134 albertel 7833: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 7834: foreach (sort keys %children) {
1.221 albertel 7835: #sleep 1;
1.57 www 7836: unless (kill 'USR1' => $_) {
7837: &logthis ('Child '.$_.' is dead');
7838: &logstatus($$.' is dead');
1.221 albertel 7839: delete($children{$_});
1.57 www 7840: }
1.61 harris41 7841: }
1.63 www 7842: sleep 5;
1.212 foxr 7843: $SIG{ALRM} = sub { Debug("timeout");
7844: die "timeout"; };
1.113 albertel 7845: $SIG{__DIE__} = 'DEFAULT';
1.165 albertel 7846: &status("Checking on the children (waiting for reports)");
1.63 www 7847: foreach (sort keys %children) {
7848: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 7849: eval {
7850: alarm(300);
1.63 www 7851: &logthis('Child '.$_.' did not respond');
1.67 albertel 7852: kill 9 => $_;
1.131 albertel 7853: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
7854: #$subj="LON: $currenthostid killed lond process $_";
7855: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
7856: #$execdir=$perlvar{'lonDaemons'};
7857: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221 albertel 7858: delete($children{$_});
1.113 albertel 7859: alarm(0);
7860: }
1.63 www 7861: }
7862: }
1.113 albertel 7863: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 7864: $SIG{__DIE__} = \&catchexception;
1.165 albertel 7865: &status("Finished checking children");
1.221 albertel 7866: &logthis('Finished Checking children');
1.57 www 7867: }
7868:
1.1 albertel 7869: # --------------------------------------------------------------------- Logging
7870:
7871: sub logthis {
7872: my $message=shift;
7873: my $execdir=$perlvar{'lonDaemons'};
7874: my $fh=IO::File->new(">>$execdir/logs/lond.log");
7875: my $now=time;
7876: my $local=localtime($now);
1.58 www 7877: $lastlog=$local.': '.$message;
1.1 albertel 7878: print $fh "$local ($$): $message\n";
7879: }
7880:
1.77 foxr 7881: # ------------------------- Conditional log if $DEBUG true.
7882: sub Debug {
7883: my $message = shift;
7884: if($DEBUG) {
7885: &logthis($message);
7886: }
7887: }
1.161 foxr 7888:
7889: #
7890: # Sub to do replies to client.. this gives a hook for some
7891: # debug tracing too:
7892: # Parameters:
7893: # fd - File open on client.
7894: # reply - Text to send to client.
7895: # request - Original request from client.
7896: #
1.490 droeschl 7897: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
7898: #this is done automatically ($$reply must not contain any \n in this case).
7899: #If $reply is a string the caller has to ensure this.
1.161 foxr 7900: sub Reply {
1.192 foxr 7901: my ($fd, $reply, $request) = @_;
1.387 albertel 7902: if (ref($reply)) {
7903: print $fd $$reply;
7904: print $fd "\n";
7905: if ($DEBUG) { Debug("Request was $request Reply was $$reply"); }
7906: } else {
7907: print $fd $reply;
7908: if ($DEBUG) { Debug("Request was $request Reply was $reply"); }
7909: }
1.212 foxr 7910: $Transactions++;
7911: }
7912:
7913:
7914: #
7915: # Sub to report a failure.
7916: # This function:
7917: # - Increments the failure statistic counters.
7918: # - Invokes Reply to send the error message to the client.
7919: # Parameters:
7920: # fd - File descriptor open on the client
7921: # reply - Reply text to emit.
7922: # request - The original request message (used by Reply
7923: # to debug if that's enabled.
7924: # Implicit outputs:
7925: # $Failures- The number of failures is incremented.
7926: # Reply (invoked here) sends a message to the
7927: # client:
7928: #
7929: sub Failure {
7930: my $fd = shift;
7931: my $reply = shift;
7932: my $request = shift;
7933:
7934: $Failures++;
7935: Reply($fd, $reply, $request); # That's simple eh?
1.161 foxr 7936: }
1.57 www 7937: # ------------------------------------------------------------------ Log status
7938:
7939: sub logstatus {
1.178 foxr 7940: &status("Doing logging");
7941: my $docdir=$perlvar{'lonDocRoot'};
7942: {
7943: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200 matthew 7944: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178 foxr 7945: $fh->close();
7946: }
1.221 albertel 7947: &status("Finished $$.txt");
7948: {
7949: open(LOG,">>$docdir/lon-status/londstatus.txt");
7950: flock(LOG,LOCK_EX);
7951: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
7952: .$status."\t".$lastlog."\t $keymode\n";
1.275 albertel 7953: flock(LOG,LOCK_UN);
1.221 albertel 7954: close(LOG);
7955: }
1.178 foxr 7956: &status("Finished logging");
1.57 www 7957: }
7958:
7959: sub initnewstatus {
7960: my $docdir=$perlvar{'lonDocRoot'};
7961: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460 foxr 7962: my $now=time();
1.57 www 7963: my $local=localtime($now);
7964: print $fh "LOND status $local - parent $$\n\n";
1.64 www 7965: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 7966: while (my $filename=readdir(DIR)) {
1.64 www 7967: unlink("$docdir/lon-status/londchld/$filename");
7968: }
7969: closedir(DIR);
1.57 www 7970: }
7971:
7972: # -------------------------------------------------------------- Status setting
7973:
7974: sub status {
7975: my $what=shift;
7976: my $now=time;
7977: my $local=localtime($now);
1.178 foxr 7978: $status=$local.': '.$what;
7979: $0='lond: '.$what.' '.$local;
1.57 www 7980: }
1.11 www 7981:
1.13 www 7982: # -------------------------------------------------------------- Talk to lonsql
7983:
1.234 foxr 7984: sub sql_reply {
1.12 harris41 7985: my ($cmd)=@_;
1.234 foxr 7986: my $answer=&sub_sql_reply($cmd);
7987: if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12 harris41 7988: return $answer;
7989: }
7990:
1.234 foxr 7991: sub sub_sql_reply {
1.12 harris41 7992: my ($cmd)=@_;
7993: my $unixsock="mysqlsock";
7994: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
7995: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
7996: Type => SOCK_STREAM,
7997: Timeout => 10)
7998: or return "con_lost";
1.319 www 7999: print $sclient "$cmd:$currentdomainid\n";
1.12 harris41 8000: my $answer=<$sclient>;
8001: chomp($answer);
8002: if (!$answer) { $answer="con_lost"; }
8003: return $answer;
8004: }
8005:
1.1 albertel 8006: # --------------------------------------- Is this the home server of an author?
1.11 www 8007:
1.1 albertel 8008: sub ishome {
8009: my $author=shift;
8010: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
8011: my ($udom,$uname)=split(/\//,$author);
8012: my $proname=propath($udom,$uname);
8013: if (-e $proname) {
8014: return 'owner';
8015: } else {
8016: return 'not_owner';
8017: }
8018: }
8019:
8020: # ======================================================= Continue main program
8021: # ---------------------------------------------------- Fork once and dissociate
8022:
1.134 albertel 8023: my $fpid=fork;
1.1 albertel 8024: exit if $fpid;
1.29 harris41 8025: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 8026:
1.29 harris41 8027: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 8028:
8029: # ------------------------------------------------------- Write our PID on disk
8030:
1.134 albertel 8031: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 8032: open (PIDSAVE,">$execdir/logs/lond.pid");
8033: print PIDSAVE "$$\n";
8034: close(PIDSAVE);
1.190 albertel 8035: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57 www 8036: &status('Starting');
1.1 albertel 8037:
1.106 foxr 8038:
1.1 albertel 8039:
8040: # ----------------------------------------------------- Install signal handlers
8041:
1.57 www 8042:
1.1 albertel 8043: $SIG{CHLD} = \&REAPER;
8044: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
8045: $SIG{HUP} = \&HUPSMAN;
1.57 www 8046: $SIG{USR1} = \&checkchildren;
1.144 foxr 8047: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 8048:
1.148 foxr 8049: # Read the host hashes:
1.368 albertel 8050: &Apache::lonnet::load_hosts_tab();
1.447 raeburn 8051: my %iphost = &Apache::lonnet::get_iphost(1);
1.106 foxr 8052:
1.480 raeburn 8053: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286 albertel 8054:
1.471 raeburn 8055: my $arch = `uname -i`;
1.475 raeburn 8056: chomp($arch);
1.471 raeburn 8057: if ($arch eq 'unknown') {
8058: $arch = `uname -m`;
1.475 raeburn 8059: chomp($arch);
1.471 raeburn 8060: }
8061:
1.555 raeburn 8062: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar,\%crlchecked) eq 'ok') {
1.532 raeburn 8063: &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
8064: }
8065:
1.106 foxr 8066: # --------------------------------------------------------------
8067: # Accept connections. When a connection comes in, it is validated
8068: # and if good, a child process is created to process transactions
8069: # along the connection.
8070:
1.1 albertel 8071: while (1) {
1.165 albertel 8072: &status('Starting accept');
1.106 foxr 8073: $client = $server->accept() or next;
1.165 albertel 8074: &status('Accepted '.$client.' off to spawn');
1.386 albertel 8075: make_new_child($client);
1.165 albertel 8076: &status('Finished spawning');
1.1 albertel 8077: }
8078:
1.212 foxr 8079: sub make_new_child {
8080: my $pid;
8081: # my $cipher; # Now global
8082: my $sigset;
1.178 foxr 8083:
1.212 foxr 8084: $client = shift;
8085: &status('Starting new child '.$client);
8086: &logthis('<font color="green"> Attempting to start child ('.$client.
8087: ")</font>");
8088: # block signal for fork
8089: $sigset = POSIX::SigSet->new(SIGINT);
8090: sigprocmask(SIG_BLOCK, $sigset)
8091: or die "Can't block SIGINT for fork: $!\n";
1.178 foxr 8092:
1.212 foxr 8093: die "fork: $!" unless defined ($pid = fork);
1.178 foxr 8094:
1.212 foxr 8095: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
8096: # connection liveness.
1.178 foxr 8097:
1.212 foxr 8098: #
8099: # Figure out who we're talking to so we can record the peer in
8100: # the pid hash.
8101: #
8102: my $caller = getpeername($client);
8103: my ($port,$iaddr);
8104: if (defined($caller) && length($caller) > 0) {
8105: ($port,$iaddr)=unpack_sockaddr_in($caller);
8106: } else {
8107: &logthis("Unable to determine who caller was, getpeername returned nothing");
8108: }
8109: if (defined($iaddr)) {
8110: $clientip = inet_ntoa($iaddr);
8111: Debug("Connected with $clientip");
8112: } else {
8113: &logthis("Unable to determine clientip");
8114: $clientip='Unavailable';
8115: }
8116:
8117: if ($pid) {
8118: # Parent records the child's birth and returns.
8119: sigprocmask(SIG_UNBLOCK, $sigset)
8120: or die "Can't unblock SIGINT for fork: $!\n";
8121: $children{$pid} = $clientip;
8122: &status('Started child '.$pid);
1.462 foxr 8123: close($client);
1.212 foxr 8124: return;
8125: } else {
8126: # Child can *not* return from this subroutine.
8127: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
8128: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
8129: #don't get intercepted
8130: $SIG{USR1}= \&logstatus;
8131: $SIG{ALRM}= \&timeout;
1.468 foxr 8132: #
8133: # Block sigpipe as it gets thrownon socket disconnect and we want to
8134: # deal with that as a read faiure instead.
8135: #
8136: my $blockset = POSIX::SigSet->new(SIGPIPE);
8137: sigprocmask(SIG_BLOCK, $blockset);
8138:
1.212 foxr 8139: $lastlog='Forked ';
8140: $status='Forked';
1.178 foxr 8141:
1.212 foxr 8142: # unblock signals
8143: sigprocmask(SIG_UNBLOCK, $sigset)
8144: or die "Can't unblock SIGINT for fork: $!\n";
1.178 foxr 8145:
1.212 foxr 8146: # my $tmpsnum=0; # Now global
8147: #---------------------------------------------------- kerberos 5 initialization
8148: &Authen::Krb5::init_context();
1.511 raeburn 8149:
8150: my $no_ets;
1.571 raeburn 8151: if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
1.511 raeburn 8152: if ($1 >= 7) {
8153: $no_ets = 1;
8154: }
8155: } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
8156: if (($1 eq '9.3') || ($1 >= 12.2)) {
8157: $no_ets = 1;
8158: }
1.514 raeburn 8159: } elsif ($dist =~ /^sles(\d+)$/) {
8160: if ($1 > 11) {
8161: $no_ets = 1;
8162: }
1.511 raeburn 8163: } elsif ($dist =~ /^fedora(\d+)$/) {
8164: if ($1 < 7) {
8165: $no_ets = 1;
8166: }
8167: }
8168: unless ($no_ets) {
1.286 albertel 8169: &Authen::Krb5::init_ets();
8170: }
1.209 albertel 8171:
1.212 foxr 8172: &status('Accepted connection');
8173: # =============================================================================
8174: # do something with the connection
8175: # -----------------------------------------------------------------------------
8176: # see if we know client and 'check' for spoof IP by ineffective challenge
1.178 foxr 8177:
1.278 albertel 8178: my $outsideip=$clientip;
8179: if ($clientip eq '127.0.0.1') {
1.368 albertel 8180: $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278 albertel 8181: }
1.412 foxr 8182: &ReadManagerTable();
1.368 albertel 8183: my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278 albertel 8184: my $ismanager=($managers{$outsideip} ne undef);
1.432 raeburn 8185: $clientname = "[unknown]";
1.212 foxr 8186: if($clientrec) { # Establish client type.
8187: $ConnectionType = "client";
1.368 albertel 8188: $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212 foxr 8189: if($ismanager) {
8190: $ConnectionType = "both";
8191: }
8192: } else {
8193: $ConnectionType = "manager";
1.278 albertel 8194: $clientname = $managers{$outsideip};
1.212 foxr 8195: }
1.556 raeburn 8196: my $clientok;
1.178 foxr 8197:
1.212 foxr 8198: if ($clientrec || $ismanager) {
8199: &status("Waiting for init from $clientip $clientname");
8200: &logthis('<font color="yellow">INFO: Connection, '.
8201: $clientip.
8202: " ($clientname) connection type = $ConnectionType </font>" );
8203: &status("Connecting $clientip ($clientname))");
8204: my $remotereq=<$client>;
8205: chomp($remotereq);
8206: Debug("Got init: $remotereq");
1.337 albertel 8207:
1.212 foxr 8208: if ($remotereq =~ /^init/) {
8209: &sethost("sethost:$perlvar{'lonHostID'}");
8210: #
8211: # If the remote is attempting a local init... give that a try:
8212: #
1.432 raeburn 8213: (my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.492 droeschl 8214: # For LON-CAPA 2.9, the client session will have sent its LON-CAPA
8215: # version when initiating the connection. For LON-CAPA 2.8 and older,
8216: # the version is retrieved from the global %loncaparevs in lonnet.pm.
1.494 droeschl 8217: # $clientversion contains path to keyfile if $inittype eq 'local'
8218: # it's overridden below in this case
1.492 droeschl 8219: $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209 albertel 8220:
1.212 foxr 8221: # If the connection type is ssl, but I didn't get my
8222: # certificate files yet, then I'll drop back to
8223: # insecure (if allowed).
1.532 raeburn 8224:
8225: if ($inittype eq "ssl") {
8226: my $context;
8227: if ($clientsamedom) {
8228: $context = 'dom';
8229: if ($secureconf{'connfrom'}{'dom'} eq 'no') {
8230: $inittype = "";
8231: }
8232: } elsif ($clientsameinst) {
8233: $context = 'intdom';
8234: if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
8235: $inittype = "";
8236: }
8237: } else {
8238: $context = 'other';
8239: if ($secureconf{'connfrom'}{'other'} eq 'no') {
8240: $inittype = "";
8241: }
8242: }
8243: if ($inittype eq '') {
8244: &logthis("<font color=\"blue\"> Domain config set "
8245: ."to no ssl for $clientname (context: $context)"
8246: ." -- trying insecure auth</font>");
8247: }
8248: }
8249:
1.212 foxr 8250: if($inittype eq "ssl") {
8251: my ($ca, $cert) = lonssl::CertificateFile;
8252: my $kfile = lonssl::KeyFile;
8253: if((!$ca) ||
8254: (!$cert) ||
8255: (!$kfile)) {
8256: $inittype = ""; # This forces insecure attempt.
8257: &logthis("<font color=\"blue\"> Certificates not "
8258: ."installed -- trying insecure auth</font>");
1.224 foxr 8259: } else { # SSL certificates are in place so
1.212 foxr 8260: } # Leave the inittype alone.
8261: }
8262:
8263: if($inittype eq "local") {
1.432 raeburn 8264: $clientversion = $perlvar{'lonVersion'};
1.212 foxr 8265: my $key = LocalConnection($client, $remotereq);
8266: if($key) {
8267: Debug("Got local key $key");
8268: $clientok = 1;
8269: my $cipherkey = pack("H32", $key);
8270: $cipher = new IDEA($cipherkey);
8271: print $client "ok:local\n";
1.442 www 8272: &logthis('<font color="green">'
1.212 foxr 8273: . "Successful local authentication </font>");
8274: $keymode = "local"
1.178 foxr 8275: } else {
1.212 foxr 8276: Debug("Failed to get local key");
8277: $clientok = 0;
8278: shutdown($client, 3);
8279: close $client;
1.178 foxr 8280: }
1.212 foxr 8281: } elsif ($inittype eq "ssl") {
1.532 raeburn 8282: my $key = SSLConnection($client,$clientname);
1.212 foxr 8283: if ($key) {
8284: $clientok = 1;
8285: my $cipherkey = pack("H32", $key);
8286: $cipher = new IDEA($cipherkey);
8287: &logthis('<font color="green">'
8288: ."Successfull ssl authentication with $clientname </font>");
8289: $keymode = "ssl";
8290:
1.178 foxr 8291: } else {
1.212 foxr 8292: $clientok = 0;
8293: close $client;
1.178 foxr 8294: }
1.212 foxr 8295:
8296: } else {
8297: my $ok = InsecureConnection($client);
8298: if($ok) {
8299: $clientok = 1;
8300: &logthis('<font color="green">'
8301: ."Successful insecure authentication with $clientname </font>");
8302: print $client "ok\n";
8303: $keymode = "insecure";
1.178 foxr 8304: } else {
1.212 foxr 8305: &logthis('<font color="yellow">'
8306: ."Attempted insecure connection disallowed </font>");
8307: close $client;
8308: $clientok = 0;
1.178 foxr 8309: }
8310: }
1.212 foxr 8311: } else {
8312: &logthis(
8313: "<font color='blue'>WARNING: "
8314: ."$clientip failed to initialize: >$remotereq< </font>");
8315: &status('No init '.$clientip);
8316: }
8317: } else {
8318: &logthis(
8319: "<font color='blue'>WARNING: Unknown client $clientip</font>");
8320: &status('Hung up on '.$clientip);
8321: }
8322:
8323: if ($clientok) {
8324: # ---------------- New known client connecting, could mean machine online again
1.368 albertel 8325: if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip
1.367 albertel 8326: && $clientip ne '127.0.0.1') {
1.375 albertel 8327: &Apache::lonnet::reconlonc($clientname);
1.212 foxr 8328: }
8329: &logthis("<font color='green'>Established connection: $clientname</font>");
8330: &status('Will listen to '.$clientname);
8331: # ------------------------------------------------------------ Process requests
8332: my $keep_going = 1;
8333: my $user_input;
1.556 raeburn 8334:
1.212 foxr 8335: while(($user_input = get_request) && $keep_going) {
8336: alarm(120);
8337: Debug("Main: Got $user_input\n");
8338: $keep_going = &process_request($user_input);
1.178 foxr 8339: alarm(0);
1.569 raeburn 8340: &status('Listening to '.$clientname." ($keymode)");
1.161 foxr 8341: }
1.212 foxr 8342:
1.59 www 8343: # --------------------------------------------- client unknown or fishy, refuse
1.212 foxr 8344: } else {
1.161 foxr 8345: print $client "refused\n";
8346: $client->close();
1.190 albertel 8347: &logthis("<font color='blue'>WARNING: "
1.161 foxr 8348: ."Rejected client $clientip, closing connection</font>");
8349: }
1.525 raeburn 8350: }
1.161 foxr 8351:
1.1 albertel 8352: # =============================================================================
1.161 foxr 8353:
1.190 albertel 8354: &logthis("<font color='red'>CRITICAL: "
1.161 foxr 8355: ."Disconnect from $clientip ($clientname)</font>");
1.569 raeburn 8356:
8357:
1.161 foxr 8358: # this exit is VERY important, otherwise the child will become
8359: # a producer of more and more children, forking yourself into
8360: # process death.
8361: exit;
1.106 foxr 8362:
1.78 foxr 8363: }
1.532 raeburn 8364:
8365: #
8366: # Used to determine if a particular client is from the same domain
1.556 raeburn 8367: # as the current server, or from the same internet domain, and
8368: # also if the client can host sessions for the domain's users.
8369: # A hash is populated with keys set to commands sent by the client
8370: # which may not be executed for this domain.
1.532 raeburn 8371: #
8372: # Optional input -- the client to check for domain and internet domain.
8373: # If not specified, defaults to the package variable: $clientname
8374: #
8375: # If called in array context will not set package variables, but will
8376: # instead return an array of two values - (a) true if client is in the
1.556 raeburn 8377: # same domain as the server, and (b) true if client is in the same
8378: # internet domain.
1.532 raeburn 8379: #
8380: # If called in scalar context, sets package variables for current client:
8381: #
1.556 raeburn 8382: # $clienthomedom - LonCAPA domain of homeID for client.
8383: # $clientsamedom - LonCAPA domain same for this host and client.
8384: # $clientintdom - LonCAPA "internet domain" for client.
8385: # $clientsameinst - LonCAPA "internet domain" same for this host & client.
8386: # $clientremoteok - If current domain permits hosting on this client: 1
8387: # %clientprohibited - Commands prohibited for domain's users for this client.
8388: #
8389: # if the host and client have the same "internet domain", then the value
8390: # of $clientremoteok is not used, and no commands are prohibited.
1.532 raeburn 8391: #
8392: # returns 1 to indicate package variables have been set for current client.
8393: #
8394:
8395: sub set_client_info {
8396: my ($lonhost) = @_;
8397: $lonhost ||= $clientname;
8398: my $clienthost = &Apache::lonnet::hostname($lonhost);
8399: my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
8400: my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
8401: my $samedom = 0;
1.557 raeburn 8402: if ($perlvar{'lonDefDomain'} eq $homedom) {
1.532 raeburn 8403: $samedom = 1;
8404: }
8405: my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
8406: my $sameinst = 0;
8407: if ($intdom ne '') {
8408: my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
8409: if (ref($internet_names) eq 'ARRAY') {
8410: if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
8411: $sameinst = 1;
8412: }
8413: }
8414: }
8415: if (wantarray) {
8416: return ($samedom,$sameinst);
8417: } else {
8418: $clienthomedom = $homedom;
8419: $clientsamedom = $samedom;
8420: $clientintdom = $intdom;
8421: $clientsameinst = $sameinst;
1.556 raeburn 8422: if ($clientsameinst) {
8423: undef($clientremoteok);
8424: undef(%clientprohibited);
8425: } else {
8426: $clientremoteok = &get_remote_hostable($currentdomainid);
8427: %clientprohibited = &get_prohibited($currentdomainid);
8428: }
1.532 raeburn 8429: return 1;
8430: }
8431: }
8432:
1.261 foxr 8433: #
8434: # Determine if a user is an author for the indicated domain.
8435: #
8436: # Parameters:
8437: # domain - domain to check in .
8438: # user - Name of user to check.
8439: #
8440: # Return:
8441: # 1 - User is an author for domain.
8442: # 0 - User is not an author for domain.
8443: sub is_author {
8444: my ($domain, $user) = @_;
8445:
8446: &Debug("is_author: $user @ $domain");
8447:
8448: my $hashref = &tie_user_hash($domain, $user, "roles",
8449: &GDBM_READER());
8450:
8451: # Author role should show up as a key /domain/_au
1.78 foxr 8452:
1.321 albertel 8453: my $value;
1.487 foxr 8454: if ($hashref) {
1.78 foxr 8455:
1.487 foxr 8456: my $key = "/$domain/_au";
8457: if (defined($hashref)) {
8458: $value = $hashref->{$key};
8459: if(!untie_user_hash($hashref)) {
8460: return 'error: ' . ($!+0)." untie (GDBM) Failed";
8461: }
8462: }
8463:
8464: if(defined($value)) {
8465: &Debug("$user @ $domain is an author");
8466: }
8467: } else {
8468: return 'error: '.($!+0)." tie (GDBM) Failed";
1.261 foxr 8469: }
8470:
8471: return defined($value);
8472: }
1.78 foxr 8473: #
8474: # Checks to see if the input roleput request was to set
1.482 www 8475: # an author role. If so, creates construction space
1.78 foxr 8476: # Parameters:
8477: # request - The request sent to the rolesput subchunk.
8478: # We're looking for /domain/_au
8479: # domain - The domain in which the user is having roles doctored.
8480: # user - Name of the user for which the role is being put.
8481: # authtype - The authentication type associated with the user.
8482: #
1.289 albertel 8483: sub manage_permissions {
1.192 foxr 8484: my ($request, $domain, $user, $authtype) = @_;
1.78 foxr 8485: # See if the request is of the form /$domain/_au
1.289 albertel 8486: if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484 raeburn 8487: my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482 www 8488: unless (-e $path) {
8489: mkdir($path);
8490: }
8491: unless (-e $path.'/'.$user) {
8492: mkdir($path.'/'.$user);
8493: }
1.78 foxr 8494: }
8495: }
1.222 foxr 8496:
8497:
8498: #
8499: # Return the full path of a user password file, whether it exists or not.
8500: # Parameters:
8501: # domain - Domain in which the password file lives.
8502: # user - name of the user.
8503: # Returns:
8504: # Full passwd path:
8505: #
8506: sub password_path {
8507: my ($domain, $user) = @_;
1.264 albertel 8508: return &propath($domain, $user).'/passwd';
1.222 foxr 8509: }
8510:
8511: # Password Filename
8512: # Returns the path to a passwd file given domain and user... only if
8513: # it exists.
8514: # Parameters:
8515: # domain - Domain in which to search.
8516: # user - username.
8517: # Returns:
8518: # - If the password file exists returns its path.
8519: # - If the password file does not exist, returns undefined.
8520: #
8521: sub password_filename {
8522: my ($domain, $user) = @_;
8523:
8524: Debug ("PasswordFilename called: dom = $domain user = $user");
8525:
8526: my $path = &password_path($domain, $user);
8527: Debug("PasswordFilename got path: $path");
8528: if(-e $path) {
8529: return $path;
8530: } else {
8531: return undef;
8532: }
8533: }
8534:
8535: #
8536: # Rewrite the contents of the user's passwd file.
8537: # Parameters:
8538: # domain - domain of the user.
8539: # name - User's name.
8540: # contents - New contents of the file.
1.533 raeburn 8541: # saveold - (optional). If true save old file in a passwd.bak file.
1.222 foxr 8542: # Returns:
8543: # 0 - Failed.
8544: # 1 - Success.
8545: #
8546: sub rewrite_password_file {
1.533 raeburn 8547: my ($domain, $user, $contents, $saveold) = @_;
1.222 foxr 8548:
8549: my $file = &password_filename($domain, $user);
8550: if (defined $file) {
1.533 raeburn 8551: if ($saveold) {
8552: my $bakfile = $file.'.bak';
8553: if (CopyFile($file,$bakfile)) {
8554: chmod(0400,$bakfile);
8555: &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
8556: } else {
8557: &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
8558: }
8559: }
1.222 foxr 8560: my $pf = IO::File->new(">$file");
8561: if($pf) {
8562: print $pf "$contents\n";
8563: return 1;
8564: } else {
8565: return 0;
8566: }
8567: } else {
8568: return 0;
8569: }
8570:
8571: }
8572:
1.78 foxr 8573: #
1.222 foxr 8574: # get_auth_type - Determines the authorization type of a user in a domain.
1.78 foxr 8575:
8576: # Returns the authorization type or nouser if there is no such user.
8577: #
1.436 raeburn 8578: sub get_auth_type {
1.192 foxr 8579: my ($domain, $user) = @_;
1.78 foxr 8580:
1.222 foxr 8581: Debug("get_auth_type( $domain, $user ) \n");
1.78 foxr 8582: my $proname = &propath($domain, $user);
8583: my $passwdfile = "$proname/passwd";
8584: if( -e $passwdfile ) {
8585: my $pf = IO::File->new($passwdfile);
8586: my $realpassword = <$pf>;
8587: chomp($realpassword);
1.79 foxr 8588: Debug("Password info = $realpassword\n");
1.78 foxr 8589: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 8590: Debug("Authtype = $authtype, content = $contentpwd\n");
1.259 raeburn 8591: return "$authtype:$contentpwd";
1.224 foxr 8592: } else {
1.79 foxr 8593: Debug("Returning nouser");
1.78 foxr 8594: return "nouser";
8595: }
1.1 albertel 8596: }
8597:
1.220 foxr 8598: #
8599: # Validate a user given their domain, name and password. This utility
8600: # function is used by both AuthenticateHandler and ChangePasswordHandler
8601: # to validate the login credentials of a user.
8602: # Parameters:
8603: # $domain - The domain being logged into (this is required due to
8604: # the capability for multihomed systems.
8605: # $user - The name of the user being validated.
8606: # $password - The user's propoposed password.
8607: #
8608: # Returns:
8609: # 1 - The domain,user,pasword triplet corresponds to a valid
8610: # user.
8611: # 0 - The domain,user,password triplet is not a valid user.
8612: #
8613: sub validate_user {
1.396 raeburn 8614: my ($domain, $user, $password, $checkdefauth) = @_;
1.220 foxr 8615:
8616: # Why negative ~pi you may well ask? Well this function is about
8617: # authentication, and therefore very important to get right.
8618: # I've initialized the flag that determines whether or not I've
8619: # validated correctly to a value it's not supposed to get.
8620: # At the end of this function. I'll ensure that it's not still that
8621: # value so we don't just wind up returning some accidental value
8622: # as a result of executing an unforseen code path that
1.249 foxr 8623: # did not set $validated. At the end of valid execution paths,
8624: # validated shoule be 1 for success or 0 for failuer.
1.220 foxr 8625:
8626: my $validated = -3.14159;
8627:
8628: # How we authenticate is determined by the type of authentication
8629: # the user has been assigned. If the authentication type is
8630: # "nouser", the user does not exist so we will return 0.
8631:
1.222 foxr 8632: my $contents = &get_auth_type($domain, $user);
1.220 foxr 8633: my ($howpwd, $contentpwd) = split(/:/, $contents);
8634:
8635: my $null = pack("C",0); # Used by kerberos auth types.
8636:
1.395 raeburn 8637: if ($howpwd eq 'nouser') {
1.396 raeburn 8638: if ($checkdefauth) {
8639: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
8640: if ($domdefaults{'auth_def'} eq 'localauth') {
8641: $howpwd = $domdefaults{'auth_def'};
8642: $contentpwd = $domdefaults{'auth_arg_def'};
8643: } elsif ((($domdefaults{'auth_def'} eq 'krb4') ||
8644: ($domdefaults{'auth_def'} eq 'krb5')) &&
8645: ($domdefaults{'auth_arg_def'} ne '')) {
1.574 raeburn 8646: #
8647: # Don't attempt authentication for username and password supplied
8648: # for user without an account if uername contains @ to avoid
1.575 raeburn 8649: # call to &Authen::Krb5::parse_name() which will result in con_lost
1.574 raeburn 8650: #
8651: unless ($user =~ /\@/) {
8652: $howpwd = $domdefaults{'auth_def'};
8653: $contentpwd = $domdefaults{'auth_arg_def'};
8654: }
1.396 raeburn 8655: }
1.395 raeburn 8656: }
1.533 raeburn 8657: }
1.220 foxr 8658: if ($howpwd ne 'nouser') {
8659: if($howpwd eq "internal") { # Encrypted is in local password file.
1.518 raeburn 8660: if (length($contentpwd) == 13) {
8661: $validated = (crypt($password,$contentpwd) eq $contentpwd);
8662: if ($validated) {
1.533 raeburn 8663: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
8664: if ($domdefaults{'intauth_switch'}) {
8665: my $ncpass = &hash_passwd($domain,$password);
8666: my $saveold;
8667: if ($domdefaults{'intauth_switch'} == 2) {
8668: $saveold = 1;
8669: }
8670: if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
8671: &update_passwd_history($user,$domain,$howpwd,'conversion');
8672: &logthis("Validated password hashed with bcrypt for $user:$domain");
8673: }
1.518 raeburn 8674: }
8675: }
8676: } else {
1.533 raeburn 8677: $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.518 raeburn 8678: }
1.220 foxr 8679: }
8680: elsif ($howpwd eq "unix") { # User is a normal unix user.
8681: $contentpwd = (getpwnam($user))[1];
8682: if($contentpwd) {
8683: if($contentpwd eq 'x') { # Shadow password file...
8684: my $pwauth_path = "/usr/local/sbin/pwauth";
8685: open PWAUTH, "|$pwauth_path" or
8686: die "Cannot invoke authentication";
8687: print PWAUTH "$user\n$password\n";
8688: close PWAUTH;
8689: $validated = ! $?;
8690:
8691: } else { # Passwords in /etc/passwd.
8692: $validated = (crypt($password,
8693: $contentpwd) eq $contentpwd);
8694: }
8695: } else {
8696: $validated = 0;
8697: }
1.439 raeburn 8698: } elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
8699: my $checkwithkrb5 = 0;
8700: if ($dist =~/^fedora(\d+)$/) {
8701: if ($1 > 11) {
8702: $checkwithkrb5 = 1;
8703: }
8704: } elsif ($dist =~ /^suse([\d.]+)$/) {
8705: if ($1 > 11.1) {
8706: $checkwithkrb5 = 1;
8707: }
8708: }
8709: if ($checkwithkrb5) {
8710: $validated = &krb5_authen($password,$null,$user,$contentpwd);
8711: } else {
8712: $validated = &krb4_authen($password,$null,$user,$contentpwd);
8713: }
1.224 foxr 8714: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439 raeburn 8715: $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224 foxr 8716: } elsif ($howpwd eq "localauth") {
1.220 foxr 8717: # Authenticate via installation specific authentcation method:
8718: $validated = &localauth::localauth($user,
8719: $password,
1.353 albertel 8720: $contentpwd,
8721: $domain);
1.358 albertel 8722: if ($validated < 0) {
1.357 albertel 8723: &logthis("localauth for $contentpwd $user:$domain returned a $validated");
8724: $validated = 0;
8725: }
1.224 foxr 8726: } else { # Unrecognized auth is also bad.
1.220 foxr 8727: $validated = 0;
8728: }
8729: } else {
8730: $validated = 0;
8731: }
8732: #
8733: # $validated has the correct stat of the authentication:
8734: #
8735:
8736: unless ($validated != -3.14159) {
1.249 foxr 8737: # I >really really< want to know if this happens.
8738: # since it indicates that user authentication is badly
8739: # broken in some code path.
8740: #
8741: die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220 foxr 8742: }
8743: return $validated;
8744: }
8745:
1.518 raeburn 8746: sub check_internal_passwd {
1.533 raeburn 8747: my ($plainpass,$stored,$domain,$user) = @_;
1.518 raeburn 8748: my (undef,$method,@rest) = split(/!/,$stored);
1.533 raeburn 8749: if ($method eq 'bcrypt') {
1.518 raeburn 8750: my $result = &hash_passwd($domain,$plainpass,@rest);
8751: if ($result ne $stored) {
8752: return 0;
8753: }
1.533 raeburn 8754: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
8755: if ($domdefaults{'intauth_check'}) {
8756: # Upgrade to a larger number of rounds if necessary
8757: my $defaultcost = $domdefaults{'intauth_cost'};
8758: if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
8759: $defaultcost = 10;
8760: }
8761: if (int($rest[0])<int($defaultcost)) {
8762: if ($domdefaults{'intauth_check'} == 1) {
8763: my $ncpass = &hash_passwd($domain,$plainpass);
8764: if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
8765: &update_passwd_history($user,$domain,'internal','update cost');
8766: &logthis("Validated password hashed with bcrypt for $user:$domain");
8767: }
8768: return 1;
8769: } elsif ($domdefaults{'intauth_check'} == 2) {
8770: return 0;
8771: }
8772: }
8773: } else {
8774: return 1;
1.518 raeburn 8775: }
8776: }
8777: return 0;
8778: }
8779:
8780: sub get_last_authchg {
8781: my ($domain,$user) = @_;
8782: my $lastmod;
8783: my $logname = &propath($domain,$user).'/passwd.log';
8784: if (-e "$logname") {
8785: $lastmod = (stat("$logname"))[9];
8786: }
8787: return $lastmod;
8788: }
8789:
1.439 raeburn 8790: sub krb4_authen {
8791: my ($password,$null,$user,$contentpwd) = @_;
8792: my $validated = 0;
8793: if (!($password =~ /$null/) ) { # Null password not allowed.
8794: eval {
8795: require Authen::Krb4;
8796: };
8797: if (!$@) {
8798: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
8799: "",
8800: $contentpwd,,
8801: 'krbtgt',
8802: $contentpwd,
8803: 1,
8804: $password);
8805: if(!$k4error) {
8806: $validated = 1;
8807: } else {
8808: $validated = 0;
8809: &logthis('krb4: '.$user.', '.$contentpwd.', '.
8810: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
8811: }
8812: } else {
8813: $validated = krb5_authen($password,$null,$user,$contentpwd);
8814: }
8815: }
8816: return $validated;
8817: }
8818:
8819: sub krb5_authen {
8820: my ($password,$null,$user,$contentpwd) = @_;
8821: my $validated = 0;
8822: if(!($password =~ /$null/)) { # Null password not allowed.
8823: my $krbclient = &Authen::Krb5::parse_name($user.'@'
8824: .$contentpwd);
8825: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
8826: my $krbserver = &Authen::Krb5::parse_name($krbservice);
8827: my $credentials= &Authen::Krb5::cc_default();
8828: $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
8829: .$contentpwd));
8830: my $krbreturn;
8831: if (exists(&Authen::Krb5::get_init_creds_password)) {
8832: $krbreturn =
8833: &Authen::Krb5::get_init_creds_password($krbclient,$password,
8834: $krbservice);
8835: $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
8836: } else {
8837: $krbreturn =
8838: &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
8839: $password,$credentials);
8840: $validated = ($krbreturn == 1);
8841: }
8842: if (!$validated) {
8843: &logthis('krb5: '.$user.', '.$contentpwd.', '.
8844: &Authen::Krb5::error());
8845: }
8846: }
8847: return $validated;
8848: }
1.220 foxr 8849:
1.84 albertel 8850: sub addline {
8851: my ($fname,$hostid,$ip,$newline)=@_;
8852: my $contents;
8853: my $found=0;
1.355 albertel 8854: my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134 albertel 8855: my $sh;
1.84 albertel 8856: if ($sh=IO::File->new("$fname.subscription")) {
8857: while (my $subline=<$sh>) {
8858: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
8859: }
8860: $sh->close();
8861: }
8862: $sh=IO::File->new(">$fname.subscription");
8863: if ($contents) { print $sh $contents; }
8864: if ($newline) { print $sh $newline; }
8865: $sh->close();
8866: return $found;
1.86 www 8867: }
8868:
1.234 foxr 8869: sub get_chat {
1.324 raeburn 8870: my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310 albertel 8871:
1.87 www 8872: my @entries=();
1.324 raeburn 8873: my $namespace = 'nohist_chatroom';
8874: my $namespace_inroom = 'nohist_inchatroom';
1.335 albertel 8875: if ($group ne '') {
1.324 raeburn 8876: $namespace .= '_'.$group;
8877: $namespace_inroom .= '_'.$group;
8878: }
8879: my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310 albertel 8880: &GDBM_READER());
8881: if ($hashref) {
8882: @entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311 albertel 8883: &untie_user_hash($hashref);
1.123 www 8884: }
1.124 www 8885: my @participants=();
1.134 albertel 8886: my $cutoff=time-60;
1.324 raeburn 8887: $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310 albertel 8888: &GDBM_WRCREAT());
8889: if ($hashref) {
8890: $hashref->{$uname.':'.$udom}=time;
8891: foreach my $user (sort(keys(%$hashref))) {
8892: if ($hashref->{$user}>$cutoff) {
8893: push(@participants, 'active_participant:'.$user);
1.123 www 8894: }
8895: }
1.311 albertel 8896: &untie_user_hash($hashref);
1.86 www 8897: }
1.124 www 8898: return (@participants,@entries);
1.86 www 8899: }
8900:
1.234 foxr 8901: sub chat_add {
1.324 raeburn 8902: my ($cdom,$cname,$newchat,$group)=@_;
1.88 albertel 8903: my @entries=();
1.142 www 8904: my $time=time;
1.324 raeburn 8905: my $namespace = 'nohist_chatroom';
8906: my $logfile = 'chatroom.log';
1.335 albertel 8907: if ($group ne '') {
1.324 raeburn 8908: $namespace .= '_'.$group;
8909: $logfile = 'chatroom_'.$group.'.log';
8910: }
8911: my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310 albertel 8912: &GDBM_WRCREAT());
8913: if ($hashref) {
8914: @entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88 albertel 8915: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
8916: my ($thentime,$idnum)=split(/\_/,$lastid);
8917: my $newid=$time.'_000000';
8918: if ($thentime==$time) {
8919: $idnum=~s/^0+//;
8920: $idnum++;
8921: $idnum=substr('000000'.$idnum,-6,6);
8922: $newid=$time.'_'.$idnum;
8923: }
1.310 albertel 8924: $hashref->{$newid}=$newchat;
1.88 albertel 8925: my $expired=$time-3600;
1.310 albertel 8926: foreach my $comment (keys(%$hashref)) {
8927: my ($thistime) = ($comment=~/(\d+)\_/);
1.88 albertel 8928: if ($thistime<$expired) {
1.310 albertel 8929: delete $hashref->{$comment};
1.88 albertel 8930: }
8931: }
1.310 albertel 8932: {
8933: my $proname=&propath($cdom,$cname);
1.324 raeburn 8934: if (open(CHATLOG,">>$proname/$logfile")) {
1.310 albertel 8935: print CHATLOG ("$time:".&unescape($newchat)."\n");
8936: }
8937: close(CHATLOG);
1.142 www 8938: }
1.311 albertel 8939: &untie_user_hash($hashref);
1.86 www 8940: }
1.84 albertel 8941: }
8942:
8943: sub unsub {
8944: my ($fname,$clientip)=@_;
8945: my $result;
1.188 foxr 8946: my $unsubs = 0; # Number of successful unsubscribes:
8947:
8948:
8949: # An old way subscriptions were handled was to have a
8950: # subscription marker file:
8951:
8952: Debug("Attempting unlink of $fname.$clientname");
1.161 foxr 8953: if (unlink("$fname.$clientname")) {
1.188 foxr 8954: $unsubs++; # Successful unsub via marker file.
8955: }
8956:
8957: # The more modern way to do it is to have a subscription list
8958: # file:
8959:
1.84 albertel 8960: if (-e "$fname.subscription") {
1.161 foxr 8961: my $found=&addline($fname,$clientname,$clientip,'');
1.188 foxr 8962: if ($found) {
8963: $unsubs++;
8964: }
8965: }
8966:
8967: # If either or both of these mechanisms succeeded in unsubscribing a
8968: # resource we can return ok:
8969:
8970: if($unsubs) {
8971: $result = "ok\n";
1.84 albertel 8972: } else {
1.188 foxr 8973: $result = "not_subscribed\n";
1.84 albertel 8974: }
1.188 foxr 8975:
1.84 albertel 8976: return $result;
8977: }
8978:
1.101 www 8979: sub currentversion {
8980: my $fname=shift;
8981: my $version=-1;
8982: my $ulsdir='';
8983: if ($fname=~/^(.+)\/[^\/]+$/) {
8984: $ulsdir=$1;
8985: }
1.114 albertel 8986: my ($fnamere1,$fnamere2);
8987: # remove version if already specified
1.101 www 8988: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 8989: # get the bits that go before and after the version number
8990: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
8991: $fnamere1=$1;
8992: $fnamere2='.'.$2;
8993: }
1.101 www 8994: if (-e $fname) { $version=1; }
8995: if (-e $ulsdir) {
1.134 albertel 8996: if(-d $ulsdir) {
8997: if (opendir(LSDIR,$ulsdir)) {
1.580 raeburn 8998: if (-e $fname) {
8999: $version=0;
9000: }
1.134 albertel 9001: my $ulsfn;
9002: while ($ulsfn=readdir(LSDIR)) {
1.101 www 9003: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 9004: my $thisfile=$ulsdir.'/'.$ulsfn;
9005: unless (-l $thisfile) {
1.160 www 9006: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 9007: if ($1>$version) { $version=$1; }
9008: }
9009: }
9010: }
9011: closedir(LSDIR);
9012: $version++;
9013: }
9014: }
9015: }
9016: return $version;
1.101 www 9017: }
9018:
9019: sub thisversion {
9020: my $fname=shift;
9021: my $version=-1;
9022: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
9023: $version=$1;
9024: }
9025: return $version;
9026: }
9027:
1.84 albertel 9028: sub subscribe {
9029: my ($userinput,$clientip)=@_;
9030: my $result;
1.293 albertel 9031: my ($cmd,$fname)=split(/:/,$userinput,2);
1.84 albertel 9032: my $ownership=&ishome($fname);
9033: if ($ownership eq 'owner') {
1.101 www 9034: # explitly asking for the current version?
9035: unless (-e $fname) {
9036: my $currentversion=¤tversion($fname);
9037: if (&thisversion($fname)==$currentversion) {
9038: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
9039: my $root=$1;
9040: my $extension=$2;
9041: symlink($root.'.'.$extension,
9042: $root.'.'.$currentversion.'.'.$extension);
1.102 www 9043: unless ($extension=~/\.meta$/) {
9044: symlink($root.'.'.$extension.'.meta',
9045: $root.'.'.$currentversion.'.'.$extension.'.meta');
9046: }
1.101 www 9047: }
9048: }
9049: }
1.84 albertel 9050: if (-e $fname) {
9051: if (-d $fname) {
9052: $result="directory\n";
9053: } else {
1.161 foxr 9054: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 9055: my $now=time;
1.161 foxr 9056: my $found=&addline($fname,$clientname,$clientip,
9057: "$clientname:$clientip:$now\n");
1.84 albertel 9058: if ($found) { $result="$fname\n"; }
9059: # if they were subscribed to only meta data, delete that
9060: # subscription, when you subscribe to a file you also get
9061: # the metadata
9062: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
9063: $fname=~s/\/home\/httpd\/html\/res/raw/;
1.476 raeburn 9064: my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
9065: $protocol = 'http' if ($protocol ne 'https');
9066: $fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84 albertel 9067: $result="$fname\n";
9068: }
9069: } else {
9070: $result="not_found\n";
9071: }
9072: } else {
9073: $result="rejected\n";
9074: }
9075: return $result;
9076: }
1.287 foxr 9077: # Change the passwd of a unix user. The caller must have
9078: # first verified that the user is a loncapa user.
9079: #
9080: # Parameters:
9081: # user - Unix user name to change.
9082: # pass - New password for the user.
9083: # Returns:
9084: # ok - if success
9085: # other - Some meaningfule error message string.
9086: # NOTE:
9087: # invokes a setuid script to change the passwd.
9088: sub change_unix_password {
9089: my ($user, $pass) = @_;
9090:
9091: &Debug("change_unix_password");
9092: my $execdir=$perlvar{'lonDaemons'};
9093: &Debug("Opening lcpasswd pipeline");
9094: my $pf = IO::File->new("|$execdir/lcpasswd > "
9095: ."$perlvar{'lonDaemons'}"
9096: ."/logs/lcpasswd.log");
9097: print $pf "$user\n$pass\n$pass\n";
9098: close $pf;
9099: my $err = $?;
9100: return ($err < @passwderrors) ? $passwderrors[$err] :
9101: "pwchange_falure - unknown error";
9102:
9103:
9104: }
9105:
1.91 albertel 9106:
9107: sub make_passwd_file {
1.518 raeburn 9108: my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390 raeburn 9109: my $result="ok";
1.91 albertel 9110: if ($umode eq 'krb4' or $umode eq 'krb5') {
9111: {
9112: my $pf = IO::File->new(">$passfilename");
1.261 foxr 9113: if ($pf) {
9114: print $pf "$umode:$npass\n";
1.518 raeburn 9115: &update_passwd_history($uname,$udom,$umode,$action);
1.261 foxr 9116: } else {
9117: $result = "pass_file_failed_error";
9118: }
1.91 albertel 9119: }
9120: } elsif ($umode eq 'internal') {
1.518 raeburn 9121: my $ncpass = &hash_passwd($udom,$npass);
1.91 albertel 9122: {
9123: &Debug("Creating internal auth");
9124: my $pf = IO::File->new(">$passfilename");
1.261 foxr 9125: if($pf) {
1.518 raeburn 9126: print $pf "internal:$ncpass\n";
9127: &update_passwd_history($uname,$udom,$umode,$action);
1.261 foxr 9128: } else {
9129: $result = "pass_file_failed_error";
9130: }
1.91 albertel 9131: }
9132: } elsif ($umode eq 'localauth') {
9133: {
9134: my $pf = IO::File->new(">$passfilename");
1.261 foxr 9135: if($pf) {
9136: print $pf "localauth:$npass\n";
1.524 raeburn 9137: &update_passwd_history($uname,$udom,$umode,$action);
1.261 foxr 9138: } else {
9139: $result = "pass_file_failed_error";
9140: }
1.91 albertel 9141: }
9142: } elsif ($umode eq 'unix') {
1.502 raeburn 9143: &logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
9144: $result="no_new_unix_accounts";
1.91 albertel 9145: } elsif ($umode eq 'none') {
9146: {
1.223 foxr 9147: my $pf = IO::File->new("> $passfilename");
1.261 foxr 9148: if($pf) {
9149: print $pf "none:\n";
9150: } else {
9151: $result = "pass_file_failed_error";
9152: }
1.91 albertel 9153: }
1.543 raeburn 9154: } elsif ($umode eq 'lti') {
9155: my $pf = IO::File->new(">$passfilename");
9156: if($pf) {
9157: print $pf "lti:\n";
9158: &update_passwd_history($uname,$udom,$umode,$action);
9159: } else {
9160: $result = "pass_file_failed_error";
9161: }
1.91 albertel 9162: } else {
1.390 raeburn 9163: $result="auth_mode_error";
1.91 albertel 9164: }
9165: return $result;
1.121 albertel 9166: }
9167:
1.265 albertel 9168: sub convert_photo {
9169: my ($start,$dest)=@_;
9170: system("convert $start $dest");
9171: }
9172:
1.121 albertel 9173: sub sethost {
9174: my ($remotereq) = @_;
9175: my (undef,$hostid)=split(/:/,$remotereq);
1.322 albertel 9176: # ignore sethost if we are already correct
9177: if ($hostid eq $currenthostid) {
9178: return 'ok';
9179: }
9180:
1.121 albertel 9181: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368 albertel 9182: if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'})
9183: eq &Apache::lonnet::get_host_ip($hostid)) {
1.200 matthew 9184: $currenthostid =$hostid;
1.369 albertel 9185: $currentdomainid=&Apache::lonnet::host_domain($hostid);
1.556 raeburn 9186: &set_client_info();
1.443 www 9187: # &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121 albertel 9188: } else {
9189: &logthis("Requested host id $hostid not an alias of ".
9190: $perlvar{'lonHostID'}." refusing connection");
9191: return 'unable_to_set';
9192: }
9193: return 'ok';
9194: }
9195:
9196: sub version {
9197: my ($userinput)=@_;
9198: $remoteVERSION=(split(/:/,$userinput))[1];
9199: return "version:$VERSION";
1.127 albertel 9200: }
1.178 foxr 9201:
1.447 raeburn 9202: sub get_usersession_config {
9203: my ($dom,$name) = @_;
9204: my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
9205: if (defined($cached)) {
9206: return $usersessionconf;
9207: } else {
9208: my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
1.525 raeburn 9209: &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
9210: return $domconfig{'usersessions'};
1.447 raeburn 9211: }
9212: return;
9213: }
1.200 matthew 9214:
1.534 raeburn 9215: sub get_usersearch_config {
9216: my ($dom,$name) = @_;
9217: my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
9218: if (defined($cached)) {
9219: return $usersearchconf;
9220: } else {
9221: my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
9222: &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
9223: return $domconfig{'directorysrch'};
9224: }
9225: return;
9226: }
9227:
1.525 raeburn 9228: sub get_prohibited {
9229: my ($dom) = @_;
9230: my $name = 'trust';
9231: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
9232: unless (defined($cached)) {
9233: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
9234: &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
9235: $trustconfig = $domconfig{'trust'};
9236: }
9237: my %prohibited;
9238: if (ref($trustconfig)) {
9239: foreach my $prefix (keys(%{$trustconfig})) {
9240: if (ref($trustconfig->{$prefix}) eq 'HASH') {
9241: my $reject;
9242: if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
9243: if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
9244: $reject = 1;
9245: }
9246: }
9247: if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
9248: if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
9249: $reject = 0;
9250: } else {
9251: $reject = 1;
9252: }
9253: }
9254: if ($reject) {
9255: $prohibited{$prefix} = 1;
9256: }
9257: }
9258: }
9259: }
9260: return %prohibited;
9261: }
1.450 raeburn 9262:
1.556 raeburn 9263: sub get_remote_hostable {
9264: my ($dom) = @_;
9265: my $result;
9266: if ($clientintdom) {
9267: $result = 1;
9268: my $remsessconf = &get_usersession_config($dom,'remotesession');
9269: if (ref($remsessconf) eq 'HASH') {
9270: if (ref($remsessconf->{'remote'}) eq 'HASH') {
9271: if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
9272: if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
9273: $result = 0;
9274: }
9275: }
9276: if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
9277: if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
9278: $result = 1;
9279: } else {
9280: $result = 0;
9281: }
9282: }
9283: }
9284: }
9285: }
9286: return $result;
9287: }
9288:
1.471 raeburn 9289: sub distro_and_arch {
9290: return $dist.':'.$arch;
9291: }
9292:
1.61 harris41 9293: # ----------------------------------- POD (plain old documentation, CPAN style)
9294:
9295: =head1 NAME
9296:
9297: lond - "LON Daemon" Server (port "LOND" 5663)
9298:
9299: =head1 SYNOPSIS
9300:
1.74 harris41 9301: Usage: B<lond>
9302:
9303: Should only be run as user=www. This is a command-line script which
9304: is invoked by B<loncron>. There is no expectation that a typical user
9305: will manually start B<lond> from the command-line. (In other words,
9306: DO NOT START B<lond> YOURSELF.)
1.61 harris41 9307:
9308: =head1 DESCRIPTION
9309:
1.74 harris41 9310: There are two characteristics associated with the running of B<lond>,
9311: PROCESS MANAGEMENT (starting, stopping, handling child processes)
9312: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
9313: subscriptions, etc). These are described in two large
9314: sections below.
9315:
9316: B<PROCESS MANAGEMENT>
9317:
1.61 harris41 9318: Preforker - server who forks first. Runs as a daemon. HUPs.
9319: Uses IDEA encryption
9320:
1.74 harris41 9321: B<lond> forks off children processes that correspond to the other servers
9322: in the network. Management of these processes can be done at the
9323: parent process level or the child process level.
9324:
9325: B<logs/lond.log> is the location of log messages.
9326:
9327: The process management is now explained in terms of linux shell commands,
9328: subroutines internal to this code, and signal assignments:
9329:
9330: =over 4
9331:
9332: =item *
9333:
9334: PID is stored in B<logs/lond.pid>
9335:
9336: This is the process id number of the parent B<lond> process.
9337:
9338: =item *
9339:
9340: SIGTERM and SIGINT
9341:
9342: Parent signal assignment:
9343: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
9344:
9345: Child signal assignment:
9346: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
9347: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
9348: to restart a new child.)
9349:
9350: Command-line invocations:
9351: B<kill> B<-s> SIGTERM I<PID>
9352: B<kill> B<-s> SIGINT I<PID>
9353:
9354: Subroutine B<HUNTSMAN>:
9355: This is only invoked for the B<lond> parent I<PID>.
9356: This kills all the children, and then the parent.
9357: The B<lonc.pid> file is cleared.
9358:
9359: =item *
9360:
9361: SIGHUP
9362:
9363: Current bug:
9364: This signal can only be processed the first time
9365: on the parent process. Subsequent SIGHUP signals
9366: have no effect.
9367:
9368: Parent signal assignment:
9369: $SIG{HUP} = \&HUPSMAN;
9370:
9371: Child signal assignment:
9372: none (nothing happens)
9373:
9374: Command-line invocations:
9375: B<kill> B<-s> SIGHUP I<PID>
9376:
9377: Subroutine B<HUPSMAN>:
9378: This is only invoked for the B<lond> parent I<PID>,
9379: This kills all the children, and then the parent.
9380: The B<lond.pid> file is cleared.
9381:
9382: =item *
9383:
9384: SIGUSR1
9385:
9386: Parent signal assignment:
9387: $SIG{USR1} = \&USRMAN;
9388:
9389: Child signal assignment:
9390: $SIG{USR1}= \&logstatus;
9391:
9392: Command-line invocations:
9393: B<kill> B<-s> SIGUSR1 I<PID>
9394:
9395: Subroutine B<USRMAN>:
9396: When invoked for the B<lond> parent I<PID>,
9397: SIGUSR1 is sent to all the children, and the status of
9398: each connection is logged.
1.144 foxr 9399:
9400: =item *
9401:
9402: SIGUSR2
9403:
9404: Parent Signal assignment:
9405: $SIG{USR2} = \&UpdateHosts
9406:
9407: Child signal assignment:
9408: NONE
9409:
1.74 harris41 9410:
9411: =item *
9412:
9413: SIGCHLD
9414:
9415: Parent signal assignment:
9416: $SIG{CHLD} = \&REAPER;
9417:
9418: Child signal assignment:
9419: none
9420:
9421: Command-line invocations:
9422: B<kill> B<-s> SIGCHLD I<PID>
9423:
9424: Subroutine B<REAPER>:
9425: This is only invoked for the B<lond> parent I<PID>.
9426: Information pertaining to the child is removed.
9427: The socket port is cleaned up.
9428:
9429: =back
9430:
9431: B<SERVER-SIDE ACTIVITIES>
9432:
9433: Server-side information can be accepted in an encrypted or non-encrypted
9434: method.
9435:
9436: =over 4
9437:
9438: =item ping
9439:
9440: Query a client in the hosts.tab table; "Are you there?"
9441:
9442: =item pong
9443:
9444: Respond to a ping query.
9445:
9446: =item ekey
9447:
9448: Read in encrypted key, make cipher. Respond with a buildkey.
9449:
9450: =item load
9451:
9452: Respond with CPU load based on a computation upon /proc/loadavg.
9453:
9454: =item currentauth
9455:
9456: Reply with current authentication information (only over an
9457: encrypted channel).
9458:
9459: =item auth
9460:
9461: Only over an encrypted channel, reply as to whether a user's
9462: authentication information can be validated.
9463:
9464: =item passwd
9465:
9466: Allow for a password to be set.
9467:
9468: =item makeuser
9469:
9470: Make a user.
9471:
1.517 raeburn 9472: =item changeuserauth
1.74 harris41 9473:
9474: Allow for authentication mechanism and password to be changed.
9475:
9476: =item home
1.61 harris41 9477:
1.74 harris41 9478: Respond to a question "are you the home for a given user?"
9479:
9480: =item update
9481:
9482: Update contents of a subscribed resource.
9483:
9484: =item unsubscribe
9485:
9486: The server is unsubscribing from a resource.
9487:
9488: =item subscribe
9489:
9490: The server is subscribing to a resource.
9491:
9492: =item log
9493:
9494: Place in B<logs/lond.log>
9495:
9496: =item put
9497:
9498: stores hash in namespace
9499:
1.496 raeburn 9500: =item rolesput
1.74 harris41 9501:
9502: put a role into a user's environment
9503:
9504: =item get
9505:
9506: returns hash with keys from array
9507: reference filled in from namespace
9508:
9509: =item eget
9510:
9511: returns hash with keys from array
9512: reference filled in from namesp (encrypts the return communication)
9513:
9514: =item rolesget
9515:
9516: get a role from a user's environment
9517:
9518: =item del
9519:
9520: deletes keys out of array from namespace
9521:
9522: =item keys
9523:
9524: returns namespace keys
9525:
9526: =item dump
9527:
9528: dumps the complete (or key matching regexp) namespace into a hash
9529:
9530: =item store
9531:
9532: stores hash permanently
9533: for this url; hashref needs to be given and should be a \%hashname; the
9534: remaining args aren't required and if they aren't passed or are '' they will
9535: be derived from the ENV
9536:
9537: =item restore
9538:
9539: returns a hash for a given url
9540:
9541: =item querysend
9542:
9543: Tells client about the lonsql process that has been launched in response
9544: to a sent query.
9545:
9546: =item queryreply
9547:
9548: Accept information from lonsql and make appropriate storage in temporary
9549: file space.
9550:
9551: =item idput
9552:
9553: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
9554: for each student, defined perhaps by the institutional Registrar.)
9555:
9556: =item idget
9557:
9558: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
9559: for each student, defined perhaps by the institutional Registrar.)
9560:
1.517 raeburn 9561: =item iddel
9562:
9563: Deletes one or more ids in a domain's id database.
9564:
1.74 harris41 9565: =item tmpput
9566:
9567: Accept and store information in temporary space.
9568:
9569: =item tmpget
9570:
9571: Send along temporarily stored information.
9572:
9573: =item ls
9574:
9575: List part of a user's directory.
9576:
1.135 foxr 9577: =item pushtable
9578:
9579: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
9580: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
9581: must be restored manually in case of a problem with the new table file.
9582: pushtable requires that the request be encrypted and validated via
9583: ValidateManager. The form of the command is:
9584: enc:pushtable tablename <tablecontents> \n
9585: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
9586: cleartext newline.
9587:
1.74 harris41 9588: =item Hanging up (exit or init)
9589:
9590: What to do when a client tells the server that they (the client)
9591: are leaving the network.
9592:
9593: =item unknown command
9594:
9595: If B<lond> is sent an unknown command (not in the list above),
9596: it replys to the client "unknown_cmd".
1.135 foxr 9597:
1.74 harris41 9598:
9599: =item UNKNOWN CLIENT
9600:
9601: If the anti-spoofing algorithm cannot verify the client,
9602: the client is rejected (with a "refused" message sent
9603: to the client, and the connection is closed.
9604:
9605: =back
1.61 harris41 9606:
9607: =head1 PREREQUISITES
9608:
9609: IO::Socket
9610: IO::File
9611: Apache::File
9612: POSIX
9613: Crypt::IDEA
9614: GDBM_File
9615: Authen::Krb4
1.91 albertel 9616: Authen::Krb5
1.61 harris41 9617:
9618: =head1 COREQUISITES
9619:
1.490 droeschl 9620: none
9621:
1.61 harris41 9622: =head1 OSNAMES
9623:
9624: linux
9625:
9626: =head1 SCRIPT CATEGORIES
9627:
9628: Server/Process
9629:
9630: =cut
1.409 foxr 9631:
9632:
9633: =pod
9634:
9635: =head1 LOG MESSAGES
9636:
9637: The messages below can be emitted in the lond log. This log is located
9638: in ~httpd/perl/logs/lond.log Many log messages have HTML encapsulation
9639: to provide coloring if examined from inside a web page. Some do not.
9640: Where color is used, the colors are; Red for sometihhng to get excited
9641: about and to follow up on. Yellow for something to keep an eye on to
9642: be sure it does not get worse, Green,and Blue for informational items.
9643:
9644: In the discussions below, sometimes reference is made to ~httpd
9645: when describing file locations. There isn't really an httpd
9646: user, however there is an httpd directory that gets installed in the
9647: place that user home directories go. On linux, this is usually
9648: (always?) /home/httpd.
9649:
9650:
9651: Some messages are colorless. These are usually (not always)
9652: Green/Blue color level messages.
9653:
9654: =over 2
9655:
9656: =item (Red) LocalConnection rejecting non local: <ip> ne 127.0.0.1
9657:
9658: A local connection negotiation was attempted by
9659: a host whose IP address was not 127.0.0.1.
9660: The socket is closed and the child will exit.
9661: lond has three ways to establish an encyrption
9662: key with a client:
9663:
9664: =over 2
9665:
9666: =item local
9667:
9668: The key is written and read from a file.
9669: This is only valid for connections from localhost.
9670:
9671: =item insecure
9672:
9673: The key is generated by the server and
9674: transmitted to the client.
9675:
9676: =item ssl (secure)
9677:
9678: An ssl connection is negotiated with the client,
9679: the key is generated by the server and sent to the
9680: client across this ssl connection before the
9681: ssl connectionis terminated and clear text
9682: transmission resumes.
9683:
9684: =back
9685:
9686: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
9687:
9688: The client is local but has not sent an initialization
9689: string that is the literal "init:local" The connection
9690: is closed and the child exits.
9691:
9692: =item Red CRITICAL Can't get key file <error>
9693:
9694: SSL key negotiation is being attempted but the call to
1.549 raeburn 9695: lonssl::KeyFile failed. This usually means that the
1.409 foxr 9696: configuration file is not correctly defining or protecting
9697: the directories/files lonCertificateDirectory or
9698: lonnetPrivateKey
9699: <error> is a string that describes the reason that
9700: the key file could not be located.
9701:
9702: =item (Red) CRITICAL Can't get certificates <error>
9703:
9704: SSL key negotiation failed because we were not able to retrives our certificate
9705: or the CA's certificate in the call to lonssl::CertificateFile
9706: <error> is the textual reason this failed. Usual reasons:
9707:
9708: =over 2
1.490 droeschl 9709:
1.409 foxr 9710: =item Apache config file for loncapa incorrect:
1.490 droeschl 9711:
1.409 foxr 9712: one of the variables
9713: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
9714: undefined or incorrect
9715:
9716: =item Permission error:
9717:
9718: The directory pointed to by lonCertificateDirectory is not readable by lond
9719:
9720: =item Permission error:
9721:
9722: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
9723:
9724: =item Installation error:
9725:
9726: Either the certificate authority file or the certificate have not
9727: been installed in lonCertificateDirectory.
9728:
9729: =item (Red) CRITICAL SSL Socket promotion failed: <err>
9730:
9731: The promotion of the connection from plaintext to SSL failed
9732: <err> is the reason for the failure. There are two
9733: system calls involved in the promotion (one of which failed),
9734: a dup to produce
9735: a second fd on the raw socket over which the encrypted data
9736: will flow and IO::SOcket::SSL->new_from_fd which creates
9737: the SSL connection on the duped fd.
9738:
9739: =item (Blue) WARNING client did not respond to challenge
9740:
9741: This occurs on an insecure (non SSL) connection negotiation request.
9742: lond generates some number from the time, the PID and sends it to
9743: the client. The client must respond by echoing this information back.
9744: If the client does not do so, that's a violation of the challenge
9745: protocols and the connection will be failed.
9746:
9747: =item (Red) No manager table. Nobody can manage!!
9748:
9749: lond has the concept of privileged hosts that
9750: can perform remote management function such
9751: as update the hosts.tab. The manager hosts
9752: are described in the
9753: ~httpd/lonTabs/managers.tab file.
9754: this message is logged if this file is missing.
9755:
9756:
9757: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
9758:
9759: Reports the successful parse and registration
9760: of a specific manager.
9761:
9762: =item Green existing host <clustername:dnsname>
9763:
9764: The manager host is already defined in the hosts.tab
9765: the information in that table, rather than the info in the
9766: manager table will be used to determine the manager's ip.
9767:
9768: =item (Red) Unable to craete <filename>
9769:
9770: lond has been asked to create new versions of an administrative
9771: file (by a manager). When this is done, the new file is created
9772: in a temp file and then renamed into place so that there are always
9773: usable administrative files, even if the update fails. This failure
9774: message means that the temp file could not be created.
9775: The update is abandoned, and the old file is available for use.
9776:
9777: =item (Green) CopyFile from <oldname> to <newname> failed
9778:
9779: In an update of administrative files, the copy of the existing file to a
9780: backup file failed. The installation of the new file may still succeed,
9781: but there will not be a back up file to rever to (this should probably
9782: be yellow).
9783:
9784: =item (Green) Pushfile: backed up <oldname> to <newname>
9785:
9786: See above, the backup of the old administrative file succeeded.
9787:
9788: =item (Red) Pushfile: Unable to install <filename> <reason>
9789:
9790: The new administrative file could not be installed. In this case,
9791: the old administrative file is still in use.
9792:
9793: =item (Green) Installed new < filename>.
9794:
9795: The new administrative file was successfullly installed.
9796:
9797: =item (Red) Reinitializing lond pid=<pid>
9798:
9799: The lonc child process <pid> will be sent a USR2
9800: signal.
9801:
9802: =item (Red) Reinitializing self
9803:
9804: We've been asked to re-read our administrative files,and
9805: are doing so.
9806:
9807: =item (Yellow) error:Invalid process identifier <ident>
9808:
9809: A reinit command was received, but the target part of the
9810: command was not valid. It must be either
9811: 'lond' or 'lonc' but was <ident>
9812:
9813: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
9814:
9815: Checking to see if lond has been handed a valid edit
9816: command. It is possible the edit command is not valid
9817: in that case there are no log messages to indicate that.
9818:
9819: =item Result of password change for <username> pwchange_success
9820:
9821: The password for <username> was
9822: successfully changed.
9823:
9824: =item Unable to open <user> passwd to change password
9825:
9826: Could not rewrite the
9827: internal password file for a user
9828:
9829: =item Result of password change for <user> : <result>
1.490 droeschl 9830:
1.409 foxr 9831: A unix password change for <user> was attempted
9832: and the pipe returned <result>
9833:
9834: =item LWP GET: <message> for <fname> (<remoteurl>)
9835:
9836: The lightweight process fetch for a resource failed
9837: with <message> the local filename that should
9838: have existed/been created was <fname> the
9839: corresponding URI: <remoteurl> This is emitted in several
9840: places.
9841:
9842: =item Unable to move <transname> to <destname>
9843:
9844: From fetch_user_file_handler - the user file was replicated but could not
9845: be mv'd to its final location.
9846:
9847: =item Looking for <domain> <username>
9848:
9849: From user_has_session_handler - This should be a Debug call instead
9850: it indicates lond is about to check whether the specified user has a
9851: session active on the specified domain on the local host.
9852:
9853: =item Client <ip> (<name>) hanging up: <input>
9854:
9855: lond has been asked to exit by its client. The <ip> and <name> identify the
9856: client systemand <input> is the full exit command sent to the server.
9857:
9858: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
1.490 droeschl 9859:
1.409 foxr 9860: A lond child terminated. NOte that this termination can also occur when the
9861: child receives the QUIT or DIE signals. <pid> is the process id of the child,
9862: <hostname> the host lond is working for, and <message> the reason the child died
9863: to the best of our ability to get it (I would guess that any numeric value
9864: represents and errno value). This is immediately followed by
9865:
9866: =item Famous last words: Catching exception - <log>
9867:
9868: Where log is some recent information about the state of the child.
9869:
9870: =item Red CRITICAL: TIME OUT <pid>
9871:
9872: Some timeout occured for server <pid>. THis is normally a timeout on an LWP
9873: doing an HTTP::GET.
9874:
9875: =item child <pid> died
9876:
9877: The reaper caught a SIGCHILD for the lond child process <pid>
9878: This should be modified to also display the IP of the dying child
9879: $children{$pid}
9880:
9881: =item Unknown child 0 died
9882: A child died but the wait for it returned a pid of zero which really should not
9883: ever happen.
9884:
9885: =item Child <which> - <pid> looks like we missed it's death
9886:
9887: When a sigchild is received, the reaper process checks all children to see if they are
9888: alive. If children are dying quite quickly, the lack of signal queuing can mean
9889: that a signal hearalds the death of more than one child. If so this message indicates
9890: which other one died. <which> is the ip of a dead child
9891:
9892: =item Free socket: <shutdownretval>
9893:
9894: The HUNTSMAN sub was called due to a SIGINT in a child process. The socket is being shutdown.
9895: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
9896: to return anything. This is followed by:
9897:
9898: =item Red CRITICAL: Shutting down
9899:
9900: Just prior to exit.
9901:
9902: =item Free socket: <shutdownretval>
9903:
9904: The HUPSMAN sub was called due to a SIGHUP. all children get killsed, and lond execs itself.
9905: This is followed by:
9906:
9907: =item (Red) CRITICAL: Restarting
9908:
9909: lond is about to exec itself to restart.
9910:
9911: =item (Blue) Updating connections
9912:
9913: (In response to a USR2). All the children (except the one for localhost)
9914: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
9915:
9916: =item (Blue) UpdateHosts killing child <pid> for ip <ip>
9917:
9918: Due to USR2 as above.
9919:
9920: =item (Green) keeping child for ip <ip> (pid = <pid>)
9921:
9922: In response to USR2 as above, the child indicated is not being restarted because
9923: it's assumed that we'll always need a child for the localhost.
9924:
9925:
9926: =item Going to check on the children
9927:
9928: Parent is about to check on the health of the child processes.
9929: Note that this is in response to a USR1 sent to the parent lond.
9930: there may be one or more of the next two messages:
9931:
9932: =item <pid> is dead
9933:
9934: A child that we have in our child hash as alive has evidently died.
9935:
9936: =item Child <pid> did not respond
9937:
9938: In the health check the child <pid> did not update/produce a pid_.txt
9939: file when sent it's USR1 signal. That process is killed with a 9 signal, as it's
9940: assumed to be hung in some un-fixable way.
9941:
9942: =item Finished checking children
1.490 droeschl 9943:
1.409 foxr 9944: Master processs's USR1 processing is cojmplete.
9945:
9946: =item (Red) CRITICAL: ------- Starting ------
9947:
9948: (There are more '-'s on either side). Lond has forked itself off to
9949: form a new session and is about to start actual initialization.
9950:
9951: =item (Green) Attempting to start child (<client>)
9952:
9953: Started a new child process for <client>. Client is IO::Socket object
9954: connected to the child. This was as a result of a TCP/IP connection from a client.
9955:
9956: =item Unable to determine who caller was, getpeername returned nothing
1.490 droeschl 9957:
1.409 foxr 9958: In child process initialization. either getpeername returned undef or
9959: a zero sized object was returned. Processing continues, but in my opinion,
9960: this should be cause for the child to exit.
9961:
9962: =item Unable to determine clientip
9963:
9964: In child process initialization. The peer address from getpeername was not defined.
9965: The client address is stored as "Unavailable" and processing continues.
9966:
9967: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
1.490 droeschl 9968:
1.409 foxr 9969: In child initialization. A good connectionw as received from <ip>.
9970:
9971: =over 2
9972:
9973: =item <name>
9974:
9975: is the name of the client from hosts.tab.
9976:
9977: =item <type>
9978:
9979: Is the connection type which is either
9980:
9981: =over 2
9982:
9983: =item manager
9984:
9985: The connection is from a manager node, not in hosts.tab
9986:
9987: =item client
9988:
9989: the connection is from a non-manager in the hosts.tab
9990:
9991: =item both
9992:
9993: The connection is from a manager in the hosts.tab.
9994:
9995: =back
9996:
9997: =back
9998:
9999: =item (Blue) Certificates not installed -- trying insecure auth
10000:
10001: One of the certificate file, key file or
10002: certificate authority file could not be found for a client attempting
10003: SSL connection intiation. COnnection will be attemptied in in-secure mode.
10004: (this would be a system with an up to date lond that has not gotten a
10005: certificate from us).
10006:
10007: =item (Green) Successful local authentication
10008:
10009: A local connection successfully negotiated the encryption key.
10010: In this case the IDEA key is in a file (that is hopefully well protected).
10011:
10012: =item (Green) Successful ssl authentication with <client>
10013:
10014: The client (<client> is the peer's name in hosts.tab), has successfully
10015: negotiated an SSL connection with this child process.
10016:
10017: =item (Green) Successful insecure authentication with <client>
1.490 droeschl 10018:
1.409 foxr 10019:
10020: The client has successfully negotiated an insecure connection withthe child process.
10021:
10022: =item (Yellow) Attempted insecure connection disallowed
10023:
10024: The client attempted and failed to successfully negotiate a successful insecure
10025: connection. This can happen either because the variable londAllowInsecure is false
10026: or undefined, or becuse the child did not successfully echo back the challenge
10027: string.
10028:
10029:
10030: =back
10031:
1.441 raeburn 10032: =back
10033:
1.409 foxr 10034:
10035: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>