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