Annotation of loncom/lond, revision 1.489.2.45
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.45! raeburn 5: # $Id: lond,v 1.489.2.44 2022/02/25 09:46:25 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.45! raeburn 66: my $VERSION='$Revision: 1.489.2.44 $'; #' 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.43 raeburn 1798: if ($dist =~ /^(centos|rhes|fedora|scientific|oracle|rocky|alma)/) {
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: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1.489.2.33 raeburn 2111: my $notunique;
1.222 foxr 2112: if ($howpwd eq 'internal') {
2113: &Debug("internal auth");
1.489.2.21 raeburn 2114: my $ncpass = &hash_passwd($udom,$npass);
1.489.2.33 raeburn 2115: my (undef,$method,@rest) = split(/!/,$contentpwd);
2116: if ($method eq 'bcrypt') {
2117: my %passwdconf = &Apache::lonnet::get_passwdconf($udom);
2118: if (($passwdconf{'numsaved'}) && ($passwdconf{'numsaved'} =~ /^\d+$/)) {
2119: my @oldpasswds;
2120: my $userpath = &propath($udom,$uname);
2121: my $fullpath = $userpath.'/oldpasswds';
2122: if (-d $userpath) {
2123: my @oldfiles;
2124: if (-e $fullpath) {
2125: if (opendir(my $dir,$fullpath)) {
2126: (@oldfiles) = grep(/^\d+$/,readdir($dir));
2127: closedir($dir);
2128: }
2129: if (@oldfiles) {
2130: @oldfiles = sort { $b <=> $a } (@oldfiles);
2131: my $numremoved = 0;
2132: for (my $i=0; $i<@oldfiles; $i++) {
2133: if ($i>=$passwdconf{'numsaved'}) {
2134: if (-f "$fullpath/$oldfiles[$i]") {
2135: if (unlink("$fullpath/$oldfiles[$i]")) {
2136: $numremoved ++;
2137: }
2138: }
2139: } elsif (open(my $fh,'<',"$fullpath/$oldfiles[$i]")) {
2140: while (my $line = <$fh>) {
2141: push(@oldpasswds,$line);
2142: }
2143: close($fh);
2144: }
2145: }
2146: if ($numremoved) {
2147: &logthis("unlinked $numremoved old password files for $uname:$udom");
2148: }
2149: }
2150: }
2151: push(@oldpasswds,$contentpwd);
2152: foreach my $item (@oldpasswds) {
2153: my (undef,$method,@rest) = split(/!/,$item);
2154: if ($method eq 'bcrypt') {
2155: my $result = &hash_passwd($udom,$npass,@rest);
2156: if ($result eq $item) {
2157: $notunique = 1;
2158: last;
2159: }
2160: }
2161: }
2162: unless ($notunique) {
2163: unless (-e $fullpath) {
2164: if (&mkpath("$fullpath/")) {
2165: chmod(0700,$fullpath);
2166: }
2167: }
2168: if (-d $fullpath) {
2169: my $now = time;
2170: if (open(my $fh,'>',"$fullpath/$now")) {
2171: print $fh $contentpwd;
2172: close($fh);
2173: chmod(0400,"$fullpath/$now");
2174: }
2175: }
2176: }
2177: }
2178: }
2179: }
2180: if ($notunique) {
2181: my $msg="Result of password change for $uname:$udom - password matches one used before";
2182: if ($lonhost) {
2183: $msg .= " - request originated from: $lonhost";
2184: }
2185: &logthis($msg);
2186: &Reply($client, "prioruse\n", $userinput);
2187: } elsif (&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
1.428 raeburn 2188: my $msg="Result of password change for $uname: pwchange_success";
2189: if ($lonhost) {
2190: $msg .= " - request originated from: $lonhost";
2191: }
2192: &logthis($msg);
1.489.2.21 raeburn 2193: &update_passwd_history($uname,$udom,$howpwd,$context);
1.222 foxr 2194: &Reply($client, "ok\n", $userinput);
2195: } else {
2196: &logthis("Unable to open $uname passwd "
2197: ."to change password");
2198: &Failure( $client, "non_authorized\n",$userinput);
2199: }
1.346 raeburn 2200: } elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
1.287 foxr 2201: my $result = &change_unix_password($uname, $npass);
1.489.2.21 raeburn 2202: if ($result eq 'ok') {
2203: &update_passwd_history($uname,$udom,$howpwd,$context);
2204: }
1.222 foxr 2205: &logthis("Result of password change for $uname: ".
1.287 foxr 2206: $result);
1.387 albertel 2207: &Reply($client, \$result, $userinput);
1.222 foxr 2208: } else {
2209: # this just means that the current password mode is not
2210: # one we know how to change (e.g the kerberos auth modes or
2211: # locally written auth handler).
2212: #
2213: &Failure( $client, "auth_mode_error\n", $userinput);
2214: }
1.224 foxr 2215: } else {
1.428 raeburn 2216: if ($failure eq '') {
2217: $failure = 'non_authorized';
2218: }
2219: &Failure( $client, "$failure\n", $userinput);
1.222 foxr 2220: }
2221:
2222: return 1;
2223: }
1.263 albertel 2224: ®ister_handler("passwd", \&change_password_handler, 1, 1, 0);
1.222 foxr 2225:
1.489.2.21 raeburn 2226: sub hash_passwd {
2227: my ($domain,$plainpass,@rest) = @_;
2228: my ($salt,$cost);
2229: if (@rest) {
2230: $cost = $rest[0];
2231: # salt is first 22 characters, base-64 encoded by bcrypt
2232: my $plainsalt = substr($rest[1],0,22);
2233: $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
2234: } else {
1.489.2.26 raeburn 2235: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2236: my $defaultcost = $domdefaults{'intauth_cost'};
1.489.2.21 raeburn 2237: if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
2238: $cost = 10;
2239: } else {
2240: $cost = $defaultcost;
2241: }
2242: # Generate random 16-octet base64 salt
2243: $salt = "";
2244: $salt .= pack("C", int rand(256)) for 1..16;
2245: }
2246: my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
2247: key_nul => 1,
2248: cost => $cost,
2249: salt => $salt,
2250: }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
2251:
2252: my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
2253: &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
2254: &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
2255: return $result;
2256: }
2257:
1.225 foxr 2258: #
2259: # Create a new user. User in this case means a lon-capa user.
2260: # The user must either already exist in some authentication realm
2261: # like kerberos or the /etc/passwd. If not, a user completely local to
2262: # this loncapa system is created.
2263: #
2264: # Parameters:
2265: # $cmd - The command that got us here.
2266: # $tail - Tail of the command (remaining parameters).
2267: # $client - File descriptor connected to client.
2268: # Returns
2269: # 0 - Requested to exit, caller should shut down.
2270: # 1 - Continue processing.
2271: # Implicit inputs:
2272: # The authentication systems describe above have their own forms of implicit
2273: # input into the authentication process that are described above.
2274: sub add_user_handler {
2275:
2276: my ($cmd, $tail, $client) = @_;
2277:
2278:
2279: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
2280: my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
2281:
2282: &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
2283:
2284:
2285: if($udom eq $currentdomainid) { # Reject new users for other domains...
2286:
2287: my $oldumask=umask(0077);
2288: chomp($npass);
2289: $npass=&unescape($npass);
2290: my $passfilename = &password_path($udom, $uname);
2291: &Debug("Password file created will be:".$passfilename);
2292: if (-e $passfilename) {
2293: &Failure( $client, "already_exists\n", $userinput);
2294: } else {
2295: my $fperror='';
1.264 albertel 2296: if (!&mkpath($passfilename)) {
2297: $fperror="error: ".($!+0)." mkdir failed while attempting "
2298: ."makeuser";
1.225 foxr 2299: }
2300: unless ($fperror) {
1.489.2.21 raeburn 2301: my $result=&make_passwd_file($uname,$udom,$umode,$npass,
2302: $passfilename,'makeuser');
1.390 raeburn 2303: &Reply($client,\$result, $userinput); #BUGBUG - could be fail
1.225 foxr 2304: } else {
1.387 albertel 2305: &Failure($client, \$fperror, $userinput);
1.225 foxr 2306: }
2307: }
2308: umask($oldumask);
2309: } else {
2310: &Failure($client, "not_right_domain\n",
2311: $userinput); # Even if we are multihomed.
2312:
2313: }
2314: return 1;
2315:
2316: }
2317: ®ister_handler("makeuser", \&add_user_handler, 1, 1, 0);
2318:
2319: #
2320: # Change the authentication method of a user. Note that this may
2321: # also implicitly change the user's password if, for example, the user is
2322: # joining an existing authentication realm. Known authentication realms at
2323: # this time are:
2324: # internal - Purely internal password file (only loncapa knows this user)
2325: # local - Institutionally written authentication module.
2326: # unix - Unix user (/etc/passwd with or without /etc/shadow).
2327: # kerb4 - kerberos version 4
2328: # kerb5 - kerberos version 5
2329: #
2330: # Parameters:
2331: # $cmd - The command that got us here.
2332: # $tail - Tail of the command (remaining parameters).
2333: # $client - File descriptor connected to client.
2334: # Returns
2335: # 0 - Requested to exit, caller should shut down.
2336: # 1 - Continue processing.
2337: # Implicit inputs:
2338: # The authentication systems describe above have their own forms of implicit
2339: # input into the authentication process that are described above.
1.287 foxr 2340: # NOTE:
2341: # This is also used to change the authentication credential values (e.g. passwd).
2342: #
1.225 foxr 2343: #
2344: sub change_authentication_handler {
2345:
2346: my ($cmd, $tail, $client) = @_;
2347:
2348: my $userinput = "$cmd:$tail"; # Reconstruct user input.
2349:
2350: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
2351: &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
2352: if ($udom ne $currentdomainid) {
2353: &Failure( $client, "not_right_domain\n", $client);
2354: } else {
2355:
2356: chomp($npass);
2357:
2358: $npass=&unescape($npass);
1.261 foxr 2359: my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
1.225 foxr 2360: my $passfilename = &password_path($udom, $uname);
2361: if ($passfilename) { # Not allowed to create a new user!!
1.287 foxr 2362: # If just changing the unix passwd. need to arrange to run
1.489.2.8 raeburn 2363: # passwd since otherwise make_passwd_file will fail as
2364: # creation of unix authenticated users is no longer supported
2365: # except from the command line, when running make_domain_coordinator.pl
1.287 foxr 2366:
2367: if(($oldauth =~/^unix/) && ($umode eq "unix")) {
2368: my $result = &change_unix_password($uname, $npass);
2369: &logthis("Result of password change for $uname: ".$result);
2370: if ($result eq "ok") {
1.489.2.21 raeburn 2371: &update_passwd_history($uname,$udom,$umode,'changeuserauth');
1.390 raeburn 2372: &Reply($client, \$result);
1.288 albertel 2373: } else {
1.387 albertel 2374: &Failure($client, \$result);
1.287 foxr 2375: }
1.288 albertel 2376: } else {
1.489.2.21 raeburn 2377: my $result=&make_passwd_file($uname,$udom,$umode,$npass,
2378: $passfilename,'changeuserauth');
1.287 foxr 2379: #
2380: # If the current auth mode is internal, and the old auth mode was
2381: # unix, or krb*, and the user is an author for this domain,
2382: # re-run manage_permissions for that role in order to be able
2383: # to take ownership of the construction space back to www:www
2384: #
1.489.2.8 raeburn 2385:
2386:
1.387 albertel 2387: &Reply($client, \$result, $userinput);
1.261 foxr 2388: }
2389:
2390:
1.225 foxr 2391: } else {
1.251 foxr 2392: &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
1.225 foxr 2393: }
2394: }
2395: return 1;
2396: }
2397: ®ister_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
2398:
1.489.2.21 raeburn 2399: sub update_passwd_history {
2400: my ($uname,$udom,$umode,$context) = @_;
2401: my $proname=&propath($udom,$uname);
2402: my $now = time;
2403: if (open(my $fh,">>$proname/passwd.log")) {
2404: print $fh "$now:$umode:$context\n";
2405: close($fh);
2406: }
2407: return;
2408: }
2409:
1.489.2.45! raeburn 2410: sub inst_unamemap_check {
! 2411: my ($cmd, $tail, $client) = @_;
! 2412: my $userinput = "$cmd:$tail";
! 2413: my %rulecheck;
! 2414: my $outcome;
! 2415: my ($udom,$uname,@rules) = split(/:/,$tail);
! 2416: $udom = &unescape($udom);
! 2417: $uname = &unescape($uname);
! 2418: @rules = map {&unescape($_);} (@rules);
! 2419: eval {
! 2420: local($SIG{__DIE__})='DEFAULT';
! 2421: $outcome = &localenroll::unamemap_check($udom,$uname,\@rules,\%rulecheck);
! 2422: };
! 2423: if (!$@) {
! 2424: if ($outcome eq 'ok') {
! 2425: my $result='';
! 2426: foreach my $key (keys(%rulecheck)) {
! 2427: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
! 2428: }
! 2429: &Reply($client,\$result,$userinput);
! 2430: } else {
! 2431: &Reply($client,"error\n", $userinput);
! 2432: }
! 2433: } else {
! 2434: &Failure($client,"unknown_cmd\n",$userinput);
! 2435: }
! 2436: }
! 2437: ®ister_handler("instunamemapcheck",\&inst_unamemap_check,0,1,0);
! 2438:
! 2439:
1.225 foxr 2440: #
2441: # Determines if this is the home server for a user. The home server
2442: # for a user will have his/her lon-capa passwd file. Therefore all we need
2443: # to do is determine if this file exists.
2444: #
2445: # Parameters:
2446: # $cmd - The command that got us here.
2447: # $tail - Tail of the command (remaining parameters).
2448: # $client - File descriptor connected to client.
2449: # Returns
2450: # 0 - Requested to exit, caller should shut down.
2451: # 1 - Continue processing.
2452: # Implicit inputs:
2453: # The authentication systems describe above have their own forms of implicit
2454: # input into the authentication process that are described above.
2455: #
2456: sub is_home_handler {
2457: my ($cmd, $tail, $client) = @_;
2458:
2459: my $userinput = "$cmd:$tail";
2460:
2461: my ($udom,$uname)=split(/:/,$tail);
2462: chomp($uname);
2463: my $passfile = &password_filename($udom, $uname);
2464: if($passfile) {
2465: &Reply( $client, "found\n", $userinput);
2466: } else {
2467: &Failure($client, "not_found\n", $userinput);
2468: }
2469: return 1;
2470: }
2471: ®ister_handler("home", \&is_home_handler, 0,1,0);
2472:
2473: #
1.434 www 2474: # Process an update request for a resource.
2475: # A resource has been modified that we hold a subscription to.
1.225 foxr 2476: # If the resource is not local, then we must update, or at least invalidate our
2477: # cached copy of the resource.
2478: # Parameters:
2479: # $cmd - The command that got us here.
2480: # $tail - Tail of the command (remaining parameters).
2481: # $client - File descriptor connected to client.
2482: # Returns
2483: # 0 - Requested to exit, caller should shut down.
2484: # 1 - Continue processing.
2485: # Implicit inputs:
2486: # The authentication systems describe above have their own forms of implicit
2487: # input into the authentication process that are described above.
2488: #
2489: sub update_resource_handler {
2490:
2491: my ($cmd, $tail, $client) = @_;
2492:
2493: my $userinput = "$cmd:$tail";
2494:
2495: my $fname= $tail; # This allows interactive testing
2496:
2497:
2498: my $ownership=ishome($fname);
2499: if ($ownership eq 'not_owner') {
2500: if (-e $fname) {
1.434 www 2501: # Delete preview file, if exists
2502: unlink("$fname.tmp");
2503: # Get usage stats
1.225 foxr 2504: my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
2505: $atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
2506: my $now=time;
2507: my $since=$now-$atime;
1.434 www 2508: # If the file has not been used within lonExpire seconds,
2509: # unsubscribe from it and delete local copy
1.225 foxr 2510: if ($since>$perlvar{'lonExpire'}) {
1.365 albertel 2511: my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
1.308 albertel 2512: &devalidate_meta_cache($fname);
1.225 foxr 2513: unlink("$fname");
1.334 albertel 2514: unlink("$fname.meta");
1.225 foxr 2515: } else {
1.434 www 2516: # Yes, this is in active use. Get a fresh copy. Since it might be in
2517: # very active use and huge (like a movie), copy it to "in.transfer" filename first.
1.225 foxr 2518: my $transname="$fname.in.transfer";
1.365 albertel 2519: my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
1.225 foxr 2520: my $response;
1.455 www 2521: # FIXME: cannot replicate files that take more than two minutes to transfer?
2522: # alarm(120);
2523: # FIXME: this should use the LWP mechanism, not internal alarms.
2524: alarm(1200);
1.225 foxr 2525: {
2526: my $ua=new LWP::UserAgent;
2527: my $request=new HTTP::Request('GET',"$remoteurl");
2528: $response=$ua->request($request,$transname);
2529: }
2530: alarm(0);
2531: if ($response->is_error()) {
1.489.2.30 raeburn 2532: my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
2533: &devalidate_meta_cache($fname);
2534: if (-e $transname) {
2535: unlink($transname);
2536: }
2537: unlink($fname);
1.225 foxr 2538: my $message=$response->status_line;
2539: &logthis("LWP GET: $message for $fname ($remoteurl)");
2540: } else {
2541: if ($remoteurl!~/\.meta$/) {
1.455 www 2542: # FIXME: isn't there an internal LWP mechanism for this?
1.225 foxr 2543: alarm(120);
2544: {
2545: my $ua=new LWP::UserAgent;
2546: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2547: my $mresponse=$ua->request($mrequest,$fname.'.meta');
2548: if ($mresponse->is_error()) {
2549: unlink($fname.'.meta');
2550: }
2551: }
2552: alarm(0);
2553: }
1.434 www 2554: # we successfully transfered, copy file over to real name
1.225 foxr 2555: rename($transname,$fname);
1.308 albertel 2556: &devalidate_meta_cache($fname);
1.225 foxr 2557: }
2558: }
2559: &Reply( $client, "ok\n", $userinput);
2560: } else {
2561: &Failure($client, "not_found\n", $userinput);
2562: }
2563: } else {
2564: &Failure($client, "rejected\n", $userinput);
2565: }
2566: return 1;
2567: }
2568: ®ister_handler("update", \&update_resource_handler, 0 ,1, 0);
2569:
1.308 albertel 2570: sub devalidate_meta_cache {
2571: my ($url) = @_;
2572: use Cache::Memcached;
2573: my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
1.365 albertel 2574: $url = &Apache::lonnet::declutter($url);
1.308 albertel 2575: $url =~ s-\.meta$--;
2576: my $id = &escape('meta:'.$url);
2577: $memcache->delete($id);
2578: }
2579:
1.225 foxr 2580: #
1.226 foxr 2581: # Fetch a user file from a remote server to the user's home directory
2582: # userfiles subdir.
1.225 foxr 2583: # Parameters:
2584: # $cmd - The command that got us here.
2585: # $tail - Tail of the command (remaining parameters).
2586: # $client - File descriptor connected to client.
2587: # Returns
2588: # 0 - Requested to exit, caller should shut down.
2589: # 1 - Continue processing.
2590: #
2591: sub fetch_user_file_handler {
2592:
2593: my ($cmd, $tail, $client) = @_;
2594:
2595: my $userinput = "$cmd:$tail";
2596: my $fname = $tail;
1.232 foxr 2597: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225 foxr 2598: my $udir=&propath($udom,$uname).'/userfiles';
2599: unless (-e $udir) {
2600: mkdir($udir,0770);
2601: }
1.232 foxr 2602: Debug("fetch user file for $fname");
1.225 foxr 2603: if (-e $udir) {
2604: $ufile=~s/^[\.\~]+//;
1.232 foxr 2605:
2606: # IF necessary, create the path right down to the file.
2607: # Note that any regular files in the way of this path are
2608: # wiped out to deal with some earlier folly of mine.
2609:
1.267 raeburn 2610: if (!&mkpath($udir.'/'.$ufile)) {
1.264 albertel 2611: &Failure($client, "unable_to_create\n", $userinput);
1.232 foxr 2612: }
2613:
1.225 foxr 2614: my $destname=$udir.'/'.$ufile;
2615: my $transname=$udir.'/'.$ufile.'.in.transit';
1.476 raeburn 2616: my $clientprotocol=$Apache::lonnet::protocol{$clientname};
2617: $clientprotocol = 'http' if ($clientprotocol ne 'https');
1.486 raeburn 2618: my $clienthost = &Apache::lonnet::hostname($clientname);
2619: my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
1.225 foxr 2620: my $response;
1.232 foxr 2621: Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.225 foxr 2622: alarm(120);
2623: {
2624: my $ua=new LWP::UserAgent;
2625: my $request=new HTTP::Request('GET',"$remoteurl");
2626: $response=$ua->request($request,$transname);
2627: }
2628: alarm(0);
2629: if ($response->is_error()) {
2630: unlink($transname);
2631: my $message=$response->status_line;
2632: &logthis("LWP GET: $message for $fname ($remoteurl)");
2633: &Failure($client, "failed\n", $userinput);
2634: } else {
1.232 foxr 2635: Debug("Renaming $transname to $destname");
1.225 foxr 2636: if (!rename($transname,$destname)) {
2637: &logthis("Unable to move $transname to $destname");
2638: unlink($transname);
2639: &Failure($client, "failed\n", $userinput);
2640: } else {
1.489.2.2 raeburn 2641: if ($fname =~ /^default.+\.(page|sequence)$/) {
2642: my ($major,$minor) = split(/\./,$clientversion);
2643: if (($major < 2) || ($major == 2 && $minor < 11)) {
2644: my $now = time;
2645: &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
2646: my $key = &escape('internal.contentchange');
2647: my $what = "$key=$now";
2648: my $hashref = &tie_user_hash($udom,$uname,'environment',
2649: &GDBM_WRCREAT(),"P",$what);
2650: if ($hashref) {
2651: $hashref->{$key}=$now;
2652: if (!&untie_user_hash($hashref)) {
2653: &logthis("error: ".($!+0)." untie (GDBM) failed ".
2654: "when updating internal.contentchange");
2655: }
2656: }
2657: }
2658: }
1.225 foxr 2659: &Reply($client, "ok\n", $userinput);
2660: }
2661: }
2662: } else {
2663: &Failure($client, "not_home\n", $userinput);
2664: }
2665: return 1;
2666: }
2667: ®ister_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
2668:
1.226 foxr 2669: #
2670: # Remove a file from a user's home directory userfiles subdirectory.
2671: # Parameters:
2672: # cmd - the Lond request keyword that got us here.
2673: # tail - the part of the command past the keyword.
2674: # client- File descriptor connected with the client.
2675: #
2676: # Returns:
2677: # 1 - Continue processing.
2678: sub remove_user_file_handler {
2679: my ($cmd, $tail, $client) = @_;
2680:
2681: my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2682:
2683: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2684: if ($ufile =~m|/\.\./|) {
2685: # any files paths with /../ in them refuse
2686: # to deal with
2687: &Failure($client, "refused\n", "$cmd:$tail");
2688: } else {
2689: my $udir = &propath($udom,$uname);
2690: if (-e $udir) {
2691: my $file=$udir.'/userfiles/'.$ufile;
2692: if (-e $file) {
1.253 foxr 2693: #
2694: # If the file is a regular file unlink is fine...
1.489.2.19 raeburn 2695: # However it's possible the client wants a dir
2696: # removed, in which case rmdir is more appropriate
2697: # Note: rmdir will only remove an empty directory.
1.253 foxr 2698: #
1.240 banghart 2699: if (-f $file){
1.241 albertel 2700: unlink($file);
1.489.2.19 raeburn 2701: # for html files remove the associated .bak file
2702: # which may have been created by the editor.
2703: if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
2704: my $path = $1;
2705: if (-e $file.'.bak') {
2706: unlink($file.'.bak');
2707: }
2708: }
1.241 albertel 2709: } elsif(-d $file) {
2710: rmdir($file);
1.240 banghart 2711: }
1.226 foxr 2712: if (-e $file) {
1.253 foxr 2713: # File is still there after we deleted it ?!?
2714:
1.226 foxr 2715: &Failure($client, "failed\n", "$cmd:$tail");
2716: } else {
2717: &Reply($client, "ok\n", "$cmd:$tail");
2718: }
2719: } else {
2720: &Failure($client, "not_found\n", "$cmd:$tail");
2721: }
2722: } else {
2723: &Failure($client, "not_home\n", "$cmd:$tail");
2724: }
2725: }
2726: return 1;
2727: }
2728: ®ister_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
2729:
1.236 albertel 2730: #
2731: # make a directory in a user's home directory userfiles subdirectory.
2732: # Parameters:
2733: # cmd - the Lond request keyword that got us here.
2734: # tail - the part of the command past the keyword.
2735: # client- File descriptor connected with the client.
2736: #
2737: # Returns:
2738: # 1 - Continue processing.
2739: sub mkdir_user_file_handler {
2740: my ($cmd, $tail, $client) = @_;
2741:
2742: my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2743: $dir=&unescape($dir);
2744: my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
2745: if ($ufile =~m|/\.\./|) {
2746: # any files paths with /../ in them refuse
2747: # to deal with
2748: &Failure($client, "refused\n", "$cmd:$tail");
2749: } else {
2750: my $udir = &propath($udom,$uname);
2751: if (-e $udir) {
1.264 albertel 2752: my $newdir=$udir.'/userfiles/'.$ufile.'/';
2753: if (!&mkpath($newdir)) {
2754: &Failure($client, "failed\n", "$cmd:$tail");
1.236 albertel 2755: }
1.264 albertel 2756: &Reply($client, "ok\n", "$cmd:$tail");
1.236 albertel 2757: } else {
2758: &Failure($client, "not_home\n", "$cmd:$tail");
2759: }
2760: }
2761: return 1;
2762: }
2763: ®ister_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
2764:
1.237 albertel 2765: #
2766: # rename a file in a user's home directory userfiles subdirectory.
2767: # Parameters:
2768: # cmd - the Lond request keyword that got us here.
2769: # tail - the part of the command past the keyword.
2770: # client- File descriptor connected with the client.
2771: #
2772: # Returns:
2773: # 1 - Continue processing.
2774: sub rename_user_file_handler {
2775: my ($cmd, $tail, $client) = @_;
2776:
2777: my ($udom,$uname,$old,$new) = split(/:/, $tail);
2778: $old=&unescape($old);
2779: $new=&unescape($new);
2780: if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
2781: # any files paths with /../ in them refuse to deal with
2782: &Failure($client, "refused\n", "$cmd:$tail");
2783: } else {
2784: my $udir = &propath($udom,$uname);
2785: if (-e $udir) {
2786: my $oldfile=$udir.'/userfiles/'.$old;
2787: my $newfile=$udir.'/userfiles/'.$new;
2788: if (-e $newfile) {
2789: &Failure($client, "exists\n", "$cmd:$tail");
2790: } elsif (! -e $oldfile) {
2791: &Failure($client, "not_found\n", "$cmd:$tail");
2792: } else {
2793: if (!rename($oldfile,$newfile)) {
2794: &Failure($client, "failed\n", "$cmd:$tail");
2795: } else {
2796: &Reply($client, "ok\n", "$cmd:$tail");
2797: }
2798: }
2799: } else {
2800: &Failure($client, "not_home\n", "$cmd:$tail");
2801: }
2802: }
2803: return 1;
2804: }
2805: ®ister_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
2806:
1.227 foxr 2807: #
1.382 albertel 2808: # Checks if the specified user has an active session on the server
2809: # return ok if so, not_found if not
2810: #
2811: # Parameters:
2812: # cmd - The request keyword that dispatched to tus.
2813: # tail - The tail of the request (colon separated parameters).
2814: # client - Filehandle open on the client.
2815: # Return:
2816: # 1.
2817: sub user_has_session_handler {
2818: my ($cmd, $tail, $client) = @_;
2819:
2820: my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
2821:
2822: opendir(DIR,$perlvar{'lonIDsDir'});
2823: my $filename;
2824: while ($filename=readdir(DIR)) {
2825: last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
2826: }
2827: if ($filename) {
2828: &Reply($client, "ok\n", "$cmd:$tail");
2829: } else {
2830: &Failure($client, "not_found\n", "$cmd:$tail");
2831: }
2832: return 1;
2833:
2834: }
2835: ®ister_handler("userhassession", \&user_has_session_handler, 0,1,0);
2836:
2837: #
1.263 albertel 2838: # Authenticate access to a user file by checking that the token the user's
2839: # passed also exists in their session file
1.227 foxr 2840: #
2841: # Parameters:
2842: # cmd - The request keyword that dispatched to tus.
2843: # tail - The tail of the request (colon separated parameters).
2844: # client - Filehandle open on the client.
2845: # Return:
2846: # 1.
2847: sub token_auth_user_file_handler {
2848: my ($cmd, $tail, $client) = @_;
2849:
2850: my ($fname, $session) = split(/:/, $tail);
2851:
2852: chomp($session);
1.393 raeburn 2853: my $reply="non_auth";
1.343 albertel 2854: my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
2855: if (open(ENVIN,"$file")) {
1.332 albertel 2856: flock(ENVIN,LOCK_SH);
1.343 albertel 2857: tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
2858: if (exists($disk_env{"userfile.$fname"})) {
1.393 raeburn 2859: $reply="ok";
1.343 albertel 2860: } else {
2861: foreach my $envname (keys(%disk_env)) {
2862: if ($envname=~ m|^userfile\.\Q$fname\E|) {
1.393 raeburn 2863: $reply="ok";
1.343 albertel 2864: last;
2865: }
2866: }
1.227 foxr 2867: }
1.343 albertel 2868: untie(%disk_env);
1.227 foxr 2869: close(ENVIN);
1.387 albertel 2870: &Reply($client, \$reply, "$cmd:$tail");
1.227 foxr 2871: } else {
2872: &Failure($client, "invalid_token\n", "$cmd:$tail");
2873: }
2874: return 1;
2875:
2876: }
2877: ®ister_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229 foxr 2878:
2879: #
2880: # Unsubscribe from a resource.
2881: #
2882: # Parameters:
2883: # $cmd - The command that got us here.
2884: # $tail - Tail of the command (remaining parameters).
2885: # $client - File descriptor connected to client.
2886: # Returns
2887: # 0 - Requested to exit, caller should shut down.
2888: # 1 - Continue processing.
2889: #
2890: sub unsubscribe_handler {
2891: my ($cmd, $tail, $client) = @_;
2892:
2893: my $userinput= "$cmd:$tail";
2894:
2895: my ($fname) = split(/:/,$tail); # Split in case there's extrs.
2896:
2897: &Debug("Unsubscribing $fname");
2898: if (-e $fname) {
2899: &Debug("Exists");
2900: &Reply($client, &unsub($fname,$clientip), $userinput);
2901: } else {
2902: &Failure($client, "not_found\n", $userinput);
2903: }
2904: return 1;
2905: }
2906: ®ister_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263 albertel 2907:
1.230 foxr 2908: # Subscribe to a resource
2909: #
2910: # Parameters:
2911: # $cmd - The command that got us here.
2912: # $tail - Tail of the command (remaining parameters).
2913: # $client - File descriptor connected to client.
2914: # Returns
2915: # 0 - Requested to exit, caller should shut down.
2916: # 1 - Continue processing.
2917: #
2918: sub subscribe_handler {
2919: my ($cmd, $tail, $client)= @_;
2920:
2921: my $userinput = "$cmd:$tail";
2922:
2923: &Reply( $client, &subscribe($userinput,$clientip), $userinput);
2924:
2925: return 1;
2926: }
2927: ®ister_handler("sub", \&subscribe_handler, 0, 1, 0);
2928:
2929: #
1.379 albertel 2930: # Determine the latest version of a resource (it looks for the highest
2931: # past version and then returns that +1)
1.230 foxr 2932: #
2933: # Parameters:
2934: # $cmd - The command that got us here.
2935: # $tail - Tail of the command (remaining parameters).
1.379 albertel 2936: # (Should consist of an absolute path to a file)
1.230 foxr 2937: # $client - File descriptor connected to client.
2938: # Returns
2939: # 0 - Requested to exit, caller should shut down.
2940: # 1 - Continue processing.
2941: #
2942: sub current_version_handler {
2943: my ($cmd, $tail, $client) = @_;
2944:
2945: my $userinput= "$cmd:$tail";
2946:
2947: my $fname = $tail;
2948: &Reply( $client, ¤tversion($fname)."\n", $userinput);
2949: return 1;
2950:
2951: }
2952: ®ister_handler("currentversion", \¤t_version_handler, 0, 1, 0);
2953:
2954: # Make an entry in a user's activity log.
2955: #
2956: # Parameters:
2957: # $cmd - The command that got us here.
2958: # $tail - Tail of the command (remaining parameters).
2959: # $client - File descriptor connected to client.
2960: # Returns
2961: # 0 - Requested to exit, caller should shut down.
2962: # 1 - Continue processing.
2963: #
2964: sub activity_log_handler {
2965: my ($cmd, $tail, $client) = @_;
2966:
2967:
2968: my $userinput= "$cmd:$tail";
2969:
2970: my ($udom,$uname,$what)=split(/:/,$tail);
2971: chomp($what);
2972: my $proname=&propath($udom,$uname);
2973: my $now=time;
2974: my $hfh;
2975: if ($hfh=IO::File->new(">>$proname/activity.log")) {
2976: print $hfh "$now:$clientname:$what\n";
2977: &Reply( $client, "ok\n", $userinput);
2978: } else {
2979: &Failure($client, "error: ".($!+0)." IO::File->new Failed "
2980: ."while attempting log\n",
2981: $userinput);
2982: }
2983:
2984: return 1;
2985: }
1.263 albertel 2986: ®ister_handler("log", \&activity_log_handler, 0, 1, 0);
1.230 foxr 2987:
2988: #
2989: # Put a namespace entry in a user profile hash.
2990: # My druthers would be for this to be an encrypted interaction too.
2991: # anything that might be an inadvertent covert channel about either
2992: # user authentication or user personal information....
2993: #
2994: # Parameters:
2995: # $cmd - The command that got us here.
2996: # $tail - Tail of the command (remaining parameters).
2997: # $client - File descriptor connected to client.
2998: # Returns
2999: # 0 - Requested to exit, caller should shut down.
3000: # 1 - Continue processing.
3001: #
3002: sub put_user_profile_entry {
3003: my ($cmd, $tail, $client) = @_;
1.229 foxr 3004:
1.230 foxr 3005: my $userinput = "$cmd:$tail";
3006:
1.242 raeburn 3007: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230 foxr 3008: if ($namespace ne 'roles') {
3009: chomp($what);
3010: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3011: &GDBM_WRCREAT(),"P",$what);
3012: if($hashref) {
3013: my @pairs=split(/\&/,$what);
3014: foreach my $pair (@pairs) {
3015: my ($key,$value)=split(/=/,$pair);
3016: $hashref->{$key}=$value;
3017: }
1.311 albertel 3018: if (&untie_user_hash($hashref)) {
1.230 foxr 3019: &Reply( $client, "ok\n", $userinput);
3020: } else {
3021: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3022: "while attempting put\n",
3023: $userinput);
3024: }
3025: } else {
1.316 albertel 3026: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.230 foxr 3027: "while attempting put\n", $userinput);
3028: }
3029: } else {
3030: &Failure( $client, "refused\n", $userinput);
3031: }
3032:
3033: return 1;
3034: }
3035: ®ister_handler("put", \&put_user_profile_entry, 0, 1, 0);
3036:
1.283 albertel 3037: # Put a piece of new data in hash, returns error if entry already exists
3038: # Parameters:
3039: # $cmd - The command that got us here.
3040: # $tail - Tail of the command (remaining parameters).
3041: # $client - File descriptor connected to client.
3042: # Returns
3043: # 0 - Requested to exit, caller should shut down.
3044: # 1 - Continue processing.
3045: #
3046: sub newput_user_profile_entry {
3047: my ($cmd, $tail, $client) = @_;
3048:
3049: my $userinput = "$cmd:$tail";
3050:
3051: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
3052: if ($namespace eq 'roles') {
3053: &Failure( $client, "refused\n", $userinput);
3054: return 1;
3055: }
3056:
3057: chomp($what);
3058:
3059: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3060: &GDBM_WRCREAT(),"N",$what);
3061: if(!$hashref) {
1.316 albertel 3062: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
1.283 albertel 3063: "while attempting put\n", $userinput);
3064: return 1;
3065: }
3066:
3067: my @pairs=split(/\&/,$what);
3068: foreach my $pair (@pairs) {
3069: my ($key,$value)=split(/=/,$pair);
3070: if (exists($hashref->{$key})) {
1.489.2.17 raeburn 3071: if (!&untie_user_hash($hashref)) {
3072: &logthis("error: ".($!+0)." untie (GDBM) failed ".
3073: "while attempting newput - early out as key exists");
3074: }
1.283 albertel 3075: &Failure($client, "key_exists: ".$key."\n",$userinput);
3076: return 1;
3077: }
3078: }
3079:
3080: foreach my $pair (@pairs) {
3081: my ($key,$value)=split(/=/,$pair);
3082: $hashref->{$key}=$value;
3083: }
3084:
1.311 albertel 3085: if (&untie_user_hash($hashref)) {
1.283 albertel 3086: &Reply( $client, "ok\n", $userinput);
3087: } else {
3088: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3089: "while attempting put\n",
3090: $userinput);
3091: }
3092: return 1;
3093: }
3094: ®ister_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
3095:
1.230 foxr 3096: #
3097: # Increment a profile entry in the user history file.
3098: # The history contains keyword value pairs. In this case,
3099: # The value itself is a pair of numbers. The first, the current value
3100: # the second an increment that this function applies to the current
3101: # value.
3102: #
3103: # Parameters:
3104: # $cmd - The command that got us here.
3105: # $tail - Tail of the command (remaining parameters).
3106: # $client - File descriptor connected to client.
3107: # Returns
3108: # 0 - Requested to exit, caller should shut down.
3109: # 1 - Continue processing.
3110: #
3111: sub increment_user_value_handler {
3112: my ($cmd, $tail, $client) = @_;
3113:
3114: my $userinput = "$cmd:$tail";
3115:
3116: my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
3117: if ($namespace ne 'roles') {
3118: chomp($what);
3119: my $hashref = &tie_user_hash($udom, $uname,
3120: $namespace, &GDBM_WRCREAT(),
3121: "P",$what);
3122: if ($hashref) {
3123: my @pairs=split(/\&/,$what);
3124: foreach my $pair (@pairs) {
3125: my ($key,$value)=split(/=/,$pair);
1.284 raeburn 3126: $value = &unescape($value);
1.230 foxr 3127: # We could check that we have a number...
3128: if (! defined($value) || $value eq '') {
3129: $value = 1;
3130: }
3131: $hashref->{$key}+=$value;
1.284 raeburn 3132: if ($namespace eq 'nohist_resourcetracker') {
3133: if ($hashref->{$key} < 0) {
3134: $hashref->{$key} = 0;
3135: }
3136: }
1.230 foxr 3137: }
1.311 albertel 3138: if (&untie_user_hash($hashref)) {
1.230 foxr 3139: &Reply( $client, "ok\n", $userinput);
3140: } else {
3141: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3142: "while attempting inc\n", $userinput);
3143: }
3144: } else {
3145: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3146: "while attempting inc\n", $userinput);
3147: }
3148: } else {
3149: &Failure($client, "refused\n", $userinput);
3150: }
3151:
3152: return 1;
3153: }
3154: ®ister_handler("inc", \&increment_user_value_handler, 0, 1, 0);
3155:
3156: #
3157: # Put a new role for a user. Roles are LonCAPA's packaging of permissions.
3158: # Each 'role' a user has implies a set of permissions. Adding a new role
3159: # for a person grants the permissions packaged with that role
3160: # to that user when the role is selected.
3161: #
3162: # Parameters:
3163: # $cmd - The command string (rolesput).
3164: # $tail - The remainder of the request line. For rolesput this
3165: # consists of a colon separated list that contains:
3166: # The domain and user that is granting the role (logged).
3167: # The domain and user that is getting the role.
3168: # The roles being granted as a set of & separated pairs.
3169: # each pair a key value pair.
3170: # $client - File descriptor connected to the client.
3171: # Returns:
3172: # 0 - If the daemon should exit
3173: # 1 - To continue processing.
3174: #
3175: #
3176: sub roles_put_handler {
3177: my ($cmd, $tail, $client) = @_;
3178:
3179: my $userinput = "$cmd:$tail";
3180:
3181: my ( $exedom, $exeuser, $udom, $uname, $what) = split(/:/,$tail);
3182:
3183:
3184: my $namespace='roles';
3185: chomp($what);
3186: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3187: &GDBM_WRCREAT(), "P",
3188: "$exedom:$exeuser:$what");
3189: #
3190: # Log the attempt to set a role. The {}'s here ensure that the file
3191: # handle is open for the minimal amount of time. Since the flush
3192: # is done on close this improves the chances the log will be an un-
3193: # corrupted ordered thing.
3194: if ($hashref) {
1.261 foxr 3195: my $pass_entry = &get_auth_type($udom, $uname);
3196: my ($auth_type,$pwd) = split(/:/, $pass_entry);
3197: $auth_type = $auth_type.":";
1.230 foxr 3198: my @pairs=split(/\&/,$what);
3199: foreach my $pair (@pairs) {
3200: my ($key,$value)=split(/=/,$pair);
3201: &manage_permissions($key, $udom, $uname,
1.260 foxr 3202: $auth_type);
1.230 foxr 3203: $hashref->{$key}=$value;
3204: }
1.311 albertel 3205: if (&untie_user_hash($hashref)) {
1.230 foxr 3206: &Reply($client, "ok\n", $userinput);
3207: } else {
3208: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3209: "while attempting rolesput\n", $userinput);
3210: }
3211: } else {
3212: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3213: "while attempting rolesput\n", $userinput);
3214: }
3215: return 1;
3216: }
3217: ®ister_handler("rolesput", \&roles_put_handler, 1,1,0); # Encoded client only.
3218:
3219: #
1.231 foxr 3220: # Deletes (removes) a role for a user. This is equivalent to removing
3221: # a permissions package associated with the role from the user's profile.
3222: #
3223: # Parameters:
3224: # $cmd - The command (rolesdel)
3225: # $tail - The remainder of the request line. This consists
3226: # of:
3227: # The domain and user requesting the change (logged)
3228: # The domain and user being changed.
3229: # The roles being revoked. These are shipped to us
3230: # as a bunch of & separated role name keywords.
3231: # $client - The file handle open on the client.
3232: # Returns:
3233: # 1 - Continue processing
3234: # 0 - Exit.
3235: #
3236: sub roles_delete_handler {
3237: my ($cmd, $tail, $client) = @_;
3238:
3239: my $userinput = "$cmd:$tail";
3240:
3241: my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
3242: &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
3243: "what = ".$what);
3244: my $namespace='roles';
3245: chomp($what);
3246: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3247: &GDBM_WRCREAT(), "D",
3248: "$exedom:$exeuser:$what");
3249:
3250: if ($hashref) {
3251: my @rolekeys=split(/\&/,$what);
3252:
3253: foreach my $key (@rolekeys) {
3254: delete $hashref->{$key};
3255: }
1.315 albertel 3256: if (&untie_user_hash($hashref)) {
1.231 foxr 3257: &Reply($client, "ok\n", $userinput);
3258: } else {
3259: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3260: "while attempting rolesdel\n", $userinput);
3261: }
3262: } else {
3263: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3264: "while attempting rolesdel\n", $userinput);
3265: }
3266:
3267: return 1;
3268: }
3269: ®ister_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
3270:
3271: # Unencrypted get from a user's profile database. See
3272: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
3273: # This function retrieves a keyed item from a specific named database in the
3274: # user's directory.
3275: #
3276: # Parameters:
3277: # $cmd - Command request keyword (get).
3278: # $tail - Tail of the command. This is a colon separated list
3279: # consisting of the domain and username that uniquely
3280: # identifies the profile,
3281: # The 'namespace' which selects the gdbm file to
3282: # do the lookup in,
3283: # & separated list of keys to lookup. Note that
3284: # the values are returned as an & separated list too.
3285: # $client - File descriptor open on the client.
3286: # Returns:
3287: # 1 - Continue processing.
3288: # 0 - Exit.
3289: #
3290: sub get_profile_entry {
3291: my ($cmd, $tail, $client) = @_;
3292:
3293: my $userinput= "$cmd:$tail";
3294:
3295: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
3296: chomp($what);
1.255 foxr 3297:
1.390 raeburn 3298:
1.255 foxr 3299: my $replystring = read_profile($udom, $uname, $namespace, $what);
3300: my ($first) = split(/:/,$replystring);
3301: if($first ne "error") {
1.387 albertel 3302: &Reply($client, \$replystring, $userinput);
1.231 foxr 3303: } else {
1.255 foxr 3304: &Failure($client, $replystring." while attempting get\n", $userinput);
1.231 foxr 3305: }
3306: return 1;
1.255 foxr 3307:
3308:
1.231 foxr 3309: }
3310: ®ister_handler("get", \&get_profile_entry, 0,1,0);
3311:
3312: #
3313: # Process the encrypted get request. Note that the request is sent
3314: # in clear, but the reply is encrypted. This is a small covert channel:
3315: # information about the sensitive keys is given to the snooper. Just not
3316: # information about the values of the sensitive key. Hmm if I wanted to
3317: # know these I'd snoop for the egets. Get the profile item names from them
3318: # and then issue a get for them since there's no enforcement of the
3319: # requirement of an encrypted get for particular profile items. If I
3320: # were re-doing this, I'd force the request to be encrypted as well as the
3321: # reply. I'd also just enforce encrypted transactions for all gets since
3322: # that would prevent any covert channel snooping.
3323: #
3324: # Parameters:
3325: # $cmd - Command keyword of request (eget).
1.489.2.32 raeburn 3326: # $tail - Tail of the command. See GetProfileEntry
3327: # for more information about this.
1.231 foxr 3328: # $client - File open on the client.
3329: # Returns:
3330: # 1 - Continue processing
3331: # 0 - server should exit.
3332: sub get_profile_entry_encrypted {
3333: my ($cmd, $tail, $client) = @_;
3334:
3335: my $userinput = "$cmd:$tail";
3336:
1.339 albertel 3337: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
1.231 foxr 3338: chomp($what);
1.255 foxr 3339: my $qresult = read_profile($udom, $uname, $namespace, $what);
3340: my ($first) = split(/:/, $qresult);
3341: if($first ne "error") {
3342:
3343: if ($cipher) {
3344: my $cmdlength=length($qresult);
3345: $qresult.=" ";
3346: my $encqresult='';
3347: for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
3348: $encqresult.= unpack("H16",
3349: $cipher->encrypt(substr($qresult,
3350: $encidx,
3351: 8)));
3352: }
3353: &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
3354: } else {
1.231 foxr 3355: &Failure( $client, "error:no_key\n", $userinput);
3356: }
3357: } else {
1.255 foxr 3358: &Failure($client, "$qresult while attempting eget\n", $userinput);
3359:
1.231 foxr 3360: }
3361:
3362: return 1;
3363: }
1.255 foxr 3364: ®ister_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263 albertel 3365:
1.231 foxr 3366: #
3367: # Deletes a key in a user profile database.
3368: #
3369: # Parameters:
3370: # $cmd - Command keyword (del).
3371: # $tail - Command tail. IN this case a colon
3372: # separated list containing:
3373: # The domain and user that identifies uniquely
3374: # the identity of the user.
3375: # The profile namespace (name of the profile
3376: # database file).
3377: # & separated list of keywords to delete.
3378: # $client - File open on client socket.
3379: # Returns:
3380: # 1 - Continue processing
3381: # 0 - Exit server.
3382: #
3383: #
3384: sub delete_profile_entry {
3385: my ($cmd, $tail, $client) = @_;
3386:
3387: my $userinput = "cmd:$tail";
3388:
3389: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
3390: chomp($what);
3391: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3392: &GDBM_WRCREAT(),
3393: "D",$what);
3394: if ($hashref) {
3395: my @keys=split(/\&/,$what);
3396: foreach my $key (@keys) {
3397: delete($hashref->{$key});
3398: }
1.315 albertel 3399: if (&untie_user_hash($hashref)) {
1.231 foxr 3400: &Reply($client, "ok\n", $userinput);
3401: } else {
3402: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3403: "while attempting del\n", $userinput);
3404: }
3405: } else {
3406: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3407: "while attempting del\n", $userinput);
3408: }
3409: return 1;
3410: }
3411: ®ister_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263 albertel 3412:
1.231 foxr 3413: #
3414: # List the set of keys that are defined in a profile database file.
3415: # A successful reply from this will contain an & separated list of
3416: # the keys.
3417: # Parameters:
3418: # $cmd - Command request (keys).
3419: # $tail - Remainder of the request, a colon separated
3420: # list containing domain/user that identifies the
3421: # user being queried, and the database namespace
3422: # (database filename essentially).
3423: # $client - File open on the client.
3424: # Returns:
3425: # 1 - Continue processing.
3426: # 0 - Exit the server.
3427: #
3428: sub get_profile_keys {
3429: my ($cmd, $tail, $client) = @_;
3430:
3431: my $userinput = "$cmd:$tail";
3432:
3433: my ($udom,$uname,$namespace)=split(/:/,$tail);
3434: my $qresult='';
3435: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3436: &GDBM_READER());
3437: if ($hashref) {
3438: foreach my $key (keys %$hashref) {
3439: $qresult.="$key&";
3440: }
1.315 albertel 3441: if (&untie_user_hash($hashref)) {
1.231 foxr 3442: $qresult=~s/\&$//;
1.387 albertel 3443: &Reply($client, \$qresult, $userinput);
1.231 foxr 3444: } else {
3445: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3446: "while attempting keys\n", $userinput);
3447: }
3448: } else {
3449: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3450: "while attempting keys\n", $userinput);
3451: }
3452:
3453: return 1;
3454: }
3455: ®ister_handler("keys", \&get_profile_keys, 0, 1, 0);
3456:
3457: #
3458: # Dump the contents of a user profile database.
3459: # Note that this constitutes a very large covert channel too since
3460: # the dump will return sensitive information that is not encrypted.
3461: # The naive security assumption is that the session negotiation ensures
3462: # our client is trusted and I don't believe that's assured at present.
3463: # Sure want badly to go to ssl or tls. Of course if my peer isn't really
3464: # a LonCAPA node they could have negotiated an encryption key too so >sigh<.
3465: #
3466: # Parameters:
3467: # $cmd - The command request keyword (currentdump).
3468: # $tail - Remainder of the request, consisting of a colon
3469: # separated list that has the domain/username and
3470: # the namespace to dump (database file).
3471: # $client - file open on the remote client.
3472: # Returns:
3473: # 1 - Continue processing.
3474: # 0 - Exit the server.
3475: #
3476: sub dump_profile_database {
3477: my ($cmd, $tail, $client) = @_;
3478:
3479: my $userinput = "$cmd:$tail";
3480:
3481: my ($udom,$uname,$namespace) = split(/:/,$tail);
3482: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3483: &GDBM_READER());
3484: if ($hashref) {
3485: # Structure of %data:
3486: # $data{$symb}->{$parameter}=$value;
3487: # $data{$symb}->{'v.'.$parameter}=$version;
3488: # since $parameter will be unescaped, we do not
3489: # have to worry about silly parameter names...
3490:
3491: my $qresult='';
3492: my %data = (); # A hash of anonymous hashes..
3493: while (my ($key,$value) = each(%$hashref)) {
3494: my ($v,$symb,$param) = split(/:/,$key);
3495: next if ($v eq 'version' || $symb eq 'keys');
3496: next if (exists($data{$symb}) &&
3497: exists($data{$symb}->{$param}) &&
3498: $data{$symb}->{'v.'.$param} > $v);
3499: $data{$symb}->{$param}=$value;
3500: $data{$symb}->{'v.'.$param}=$v;
3501: }
1.311 albertel 3502: if (&untie_user_hash($hashref)) {
1.231 foxr 3503: while (my ($symb,$param_hash) = each(%data)) {
3504: while(my ($param,$value) = each (%$param_hash)){
3505: next if ($param =~ /^v\./); # Ignore versions...
3506: #
3507: # Just dump the symb=value pairs separated by &
3508: #
3509: $qresult.=$symb.':'.$param.'='.$value.'&';
3510: }
3511: }
3512: chop($qresult);
1.387 albertel 3513: &Reply($client , \$qresult, $userinput);
1.231 foxr 3514: } else {
3515: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3516: "while attempting currentdump\n", $userinput);
3517: }
3518: } else {
3519: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3520: "while attempting currentdump\n", $userinput);
3521: }
3522:
3523: return 1;
3524: }
3525: ®ister_handler("currentdump", \&dump_profile_database, 0, 1, 0);
3526:
3527: #
3528: # Dump a profile database with an optional regular expression
3529: # to match against the keys. In this dump, no effort is made
3530: # to separate symb from version information. Presumably the
3531: # databases that are dumped by this command are of a different
3532: # structure. Need to look at this and improve the documentation of
3533: # both this and the currentdump handler.
3534: # Parameters:
3535: # $cmd - The command keyword.
3536: # $tail - All of the characters after the $cmd:
3537: # These are expected to be a colon
3538: # separated list containing:
3539: # domain/user - identifying the user.
3540: # namespace - identifying the database.
3541: # regexp - optional regular expression
3542: # that is matched against
3543: # database keywords to do
3544: # selective dumps.
1.488 raeburn 3545: # range - optional range of entries
3546: # e.g., 10-20 would return the
3547: # 10th to 19th items, etc.
1.231 foxr 3548: # $client - Channel open on the client.
3549: # Returns:
3550: # 1 - Continue processing.
3551: # Side effects:
3552: # response is written to $client.
3553: #
3554: sub dump_with_regexp {
3555: my ($cmd, $tail, $client) = @_;
3556:
1.489.2.4 raeburn 3557: my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
1.231 foxr 3558:
1.489.2.4 raeburn 3559: if ($res =~ /^error:/) {
3560: &Failure($client, \$res, "$cmd:$tail");
1.231 foxr 3561: } else {
1.489.2.4 raeburn 3562: &Reply($client, \$res, "$cmd:$tail");
1.231 foxr 3563: }
3564:
3565: return 1;
3566: }
3567: ®ister_handler("dump", \&dump_with_regexp, 0, 1, 0);
3568:
3569: # Store a set of key=value pairs associated with a versioned name.
3570: #
3571: # Parameters:
3572: # $cmd - Request command keyword.
3573: # $tail - Tail of the request. This is a colon
3574: # separated list containing:
3575: # domain/user - User and authentication domain.
3576: # namespace - Name of the database being modified
3577: # rid - Resource keyword to modify.
3578: # what - new value associated with rid.
1.489.2.17 raeburn 3579: # laststore - (optional) version=timestamp
3580: # for most recent transaction for rid
3581: # in namespace, when cstore was called
1.231 foxr 3582: #
3583: # $client - Socket open on the client.
3584: #
3585: #
3586: # Returns:
3587: # 1 (keep on processing).
3588: # Side-Effects:
3589: # Writes to the client
1.489.2.17 raeburn 3590: # Successful storage will cause either 'ok', or, if $laststore was included
3591: # in the tail of the request, and the version number for the last transaction
3592: # is larger than the version in $laststore, delay:$numtrans , where $numtrans
3593: # is the number of store evevnts recorded for rid in namespace since
3594: # lonnet::store() was called by the client.
3595: #
1.231 foxr 3596: sub store_handler {
3597: my ($cmd, $tail, $client) = @_;
3598:
3599: my $userinput = "$cmd:$tail";
3600:
1.489.2.17 raeburn 3601: chomp($tail);
3602: my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
1.231 foxr 3603: if ($namespace ne 'roles') {
3604:
3605: my @pairs=split(/\&/,$what);
3606: my $hashref = &tie_user_hash($udom, $uname, $namespace,
1.268 albertel 3607: &GDBM_WRCREAT(), "S",
1.231 foxr 3608: "$rid:$what");
3609: if ($hashref) {
3610: my $now = time;
1.489.2.17 raeburn 3611: my $numtrans;
3612: if ($laststore) {
3613: my ($previousversion,$previoustime) = split(/\=/,$laststore);
3614: my ($lastversion,$lasttime) = (0,0);
3615: $lastversion = $hashref->{"version:$rid"};
3616: if ($lastversion) {
3617: $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
3618: }
3619: if (($previousversion) && ($previousversion !~ /\D/)) {
3620: if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
3621: $numtrans = $lastversion - $previousversion;
3622: }
3623: } elsif ($lastversion) {
3624: $numtrans = $lastversion;
3625: }
3626: if ($numtrans) {
3627: $numtrans =~ s/D//g;
3628: }
3629: }
3630:
1.231 foxr 3631: $hashref->{"version:$rid"}++;
3632: my $version=$hashref->{"version:$rid"};
3633: my $allkeys='';
3634: foreach my $pair (@pairs) {
3635: my ($key,$value)=split(/=/,$pair);
3636: $allkeys.=$key.':';
3637: $hashref->{"$version:$rid:$key"}=$value;
3638: }
3639: $hashref->{"$version:$rid:timestamp"}=$now;
3640: $allkeys.='timestamp';
3641: $hashref->{"$version:keys:$rid"}=$allkeys;
1.311 albertel 3642: if (&untie_user_hash($hashref)) {
1.489.2.17 raeburn 3643: my $msg = 'ok';
3644: if ($numtrans) {
3645: $msg = 'delay:'.$numtrans;
3646: }
3647: &Reply($client, "$msg\n", $userinput);
1.231 foxr 3648: } else {
3649: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3650: "while attempting store\n", $userinput);
3651: }
3652: } else {
3653: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3654: "while attempting store\n", $userinput);
3655: }
3656: } else {
3657: &Failure($client, "refused\n", $userinput);
3658: }
3659:
3660: return 1;
3661: }
3662: ®ister_handler("store", \&store_handler, 0, 1, 0);
1.263 albertel 3663:
1.323 albertel 3664: # Modify a set of key=value pairs associated with a versioned name.
3665: #
3666: # Parameters:
3667: # $cmd - Request command keyword.
3668: # $tail - Tail of the request. This is a colon
3669: # separated list containing:
3670: # domain/user - User and authentication domain.
3671: # namespace - Name of the database being modified
3672: # rid - Resource keyword to modify.
3673: # v - Version item to modify
3674: # what - new value associated with rid.
3675: #
3676: # $client - Socket open on the client.
3677: #
3678: #
3679: # Returns:
3680: # 1 (keep on processing).
3681: # Side-Effects:
3682: # Writes to the client
3683: sub putstore_handler {
3684: my ($cmd, $tail, $client) = @_;
3685:
3686: my $userinput = "$cmd:$tail";
3687:
3688: my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
3689: if ($namespace ne 'roles') {
3690:
3691: chomp($what);
3692: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3693: &GDBM_WRCREAT(), "M",
3694: "$rid:$v:$what");
3695: if ($hashref) {
3696: my $now = time;
3697: my %data = &hash_extract($what);
3698: my @allkeys;
3699: while (my($key,$value) = each(%data)) {
3700: push(@allkeys,$key);
3701: $hashref->{"$v:$rid:$key"} = $value;
3702: }
3703: my $allkeys = join(':',@allkeys);
3704: $hashref->{"$v:keys:$rid"}=$allkeys;
3705:
3706: if (&untie_user_hash($hashref)) {
3707: &Reply($client, "ok\n", $userinput);
3708: } else {
3709: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3710: "while attempting store\n", $userinput);
3711: }
3712: } else {
3713: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3714: "while attempting store\n", $userinput);
3715: }
3716: } else {
3717: &Failure($client, "refused\n", $userinput);
3718: }
3719:
3720: return 1;
3721: }
3722: ®ister_handler("putstore", \&putstore_handler, 0, 1, 0);
3723:
3724: sub hash_extract {
3725: my ($str)=@_;
3726: my %hash;
3727: foreach my $pair (split(/\&/,$str)) {
3728: my ($key,$value)=split(/=/,$pair);
3729: $hash{$key}=$value;
3730: }
3731: return (%hash);
3732: }
3733: sub hash_to_str {
3734: my ($hash_ref)=@_;
3735: my $str;
3736: foreach my $key (keys(%$hash_ref)) {
3737: $str.=$key.'='.$hash_ref->{$key}.'&';
3738: }
3739: $str=~s/\&$//;
3740: return $str;
3741: }
3742:
1.231 foxr 3743: #
3744: # Dump out all versions of a resource that has key=value pairs associated
3745: # with it for each version. These resources are built up via the store
3746: # command.
3747: #
3748: # Parameters:
3749: # $cmd - Command keyword.
3750: # $tail - Remainder of the request which consists of:
3751: # domain/user - User and auth. domain.
3752: # namespace - name of resource database.
3753: # rid - Resource id.
3754: # $client - socket open on the client.
3755: #
3756: # Returns:
3757: # 1 indicating the caller should not yet exit.
3758: # Side-effects:
3759: # Writes a reply to the client.
3760: # The reply is a string of the following shape:
3761: # version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
3762: # Where the 1 above represents version 1.
3763: # this continues for all pairs of keys in all versions.
3764: #
3765: #
3766: #
3767: #
3768: sub restore_handler {
3769: my ($cmd, $tail, $client) = @_;
3770:
3771: my $userinput = "$cmd:$tail"; # Only used for logging purposes.
1.351 banghart 3772: my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
1.352 albertel 3773: $namespace=~s/\//\_/g;
1.350 albertel 3774: $namespace = &LONCAPA::clean_username($namespace);
1.349 albertel 3775:
1.231 foxr 3776: chomp($rid);
3777: my $qresult='';
1.309 albertel 3778: my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
3779: if ($hashref) {
3780: my $version=$hashref->{"version:$rid"};
1.231 foxr 3781: $qresult.="version=$version&";
3782: my $scope;
3783: for ($scope=1;$scope<=$version;$scope++) {
1.309 albertel 3784: my $vkeys=$hashref->{"$scope:keys:$rid"};
1.231 foxr 3785: my @keys=split(/:/,$vkeys);
3786: my $key;
3787: $qresult.="$scope:keys=$vkeys&";
3788: foreach $key (@keys) {
1.309 albertel 3789: $qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
1.231 foxr 3790: }
3791: }
1.311 albertel 3792: if (&untie_user_hash($hashref)) {
1.231 foxr 3793: $qresult=~s/\&$//;
1.387 albertel 3794: &Reply( $client, \$qresult, $userinput);
1.231 foxr 3795: } else {
3796: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3797: "while attempting restore\n", $userinput);
3798: }
3799: } else {
3800: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3801: "while attempting restore\n", $userinput);
3802: }
3803:
3804: return 1;
3805:
3806:
3807: }
3808: ®ister_handler("restore", \&restore_handler, 0,1,0);
1.234 foxr 3809:
3810: #
1.324 raeburn 3811: # Add a chat message to a synchronous discussion board.
1.234 foxr 3812: #
3813: # Parameters:
3814: # $cmd - Request keyword.
3815: # $tail - Tail of the command. A colon separated list
3816: # containing:
3817: # cdom - Domain on which the chat board lives
1.324 raeburn 3818: # cnum - Course containing the chat board.
3819: # newpost - Body of the posting.
3820: # group - Optional group, if chat board is only
3821: # accessible in a group within the course
1.234 foxr 3822: # $client - Socket open on the client.
3823: # Returns:
3824: # 1 - Indicating caller should keep on processing.
3825: #
3826: # Side-effects:
3827: # writes a reply to the client.
3828: #
3829: #
3830: sub send_chat_handler {
3831: my ($cmd, $tail, $client) = @_;
3832:
3833:
3834: my $userinput = "$cmd:$tail";
3835:
1.324 raeburn 3836: my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
3837: &chat_add($cdom,$cnum,$newpost,$group);
1.234 foxr 3838: &Reply($client, "ok\n", $userinput);
3839:
3840: return 1;
3841: }
3842: ®ister_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263 albertel 3843:
1.234 foxr 3844: #
1.324 raeburn 3845: # Retrieve the set of chat messages from a discussion board.
1.234 foxr 3846: #
3847: # Parameters:
3848: # $cmd - Command keyword that initiated the request.
3849: # $tail - Remainder of the request after the command
3850: # keyword. In this case a colon separated list of
3851: # chat domain - Which discussion board.
3852: # chat id - Discussion thread(?)
3853: # domain/user - Authentication domain and username
3854: # of the requesting person.
1.324 raeburn 3855: # group - Optional course group containing
3856: # the board.
1.234 foxr 3857: # $client - Socket open on the client program.
3858: # Returns:
3859: # 1 - continue processing
3860: # Side effects:
3861: # Response is written to the client.
3862: #
3863: sub retrieve_chat_handler {
3864: my ($cmd, $tail, $client) = @_;
3865:
3866:
3867: my $userinput = "$cmd:$tail";
3868:
1.324 raeburn 3869: my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
1.234 foxr 3870: my $reply='';
1.324 raeburn 3871: foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
1.234 foxr 3872: $reply.=&escape($_).':';
3873: }
3874: $reply=~s/\:$//;
1.387 albertel 3875: &Reply($client, \$reply, $userinput);
1.234 foxr 3876:
3877:
3878: return 1;
3879: }
3880: ®ister_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
3881:
3882: #
3883: # Initiate a query of an sql database. SQL query repsonses get put in
3884: # a file for later retrieval. This prevents sql query results from
3885: # bottlenecking the system. Note that with loncnew, perhaps this is
3886: # less of an issue since multiple outstanding requests can be concurrently
3887: # serviced.
3888: #
3889: # Parameters:
3890: # $cmd - COmmand keyword that initiated the request.
3891: # $tail - Remainder of the command after the keyword.
3892: # For this function, this consists of a query and
3893: # 3 arguments that are self-documentingly labelled
3894: # in the original arg1, arg2, arg3.
3895: # $client - Socket open on the client.
3896: # Return:
3897: # 1 - Indicating processing should continue.
3898: # Side-effects:
3899: # a reply is written to $client.
3900: #
3901: sub send_query_handler {
3902: my ($cmd, $tail, $client) = @_;
3903:
3904:
3905: my $userinput = "$cmd:$tail";
3906:
3907: my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
3908: $query=~s/\n*$//g;
1.489.2.27 raeburn 3909: if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
3910: my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
3911: my $earlyout;
3912: if (ref($usersearchconf) eq 'HASH') {
3913: if ($currentdomainid eq $clienthomedom) {
3914: if ($query eq 'usersearch') {
3915: if ($usersearchconf->{'lcavailable'} eq '0') {
3916: $earlyout = 1;
3917: }
3918: } else {
3919: if ($usersearchconf->{'available'} eq '0') {
3920: $earlyout = 1;
3921: }
3922: }
3923: } else {
3924: if ($query eq 'usersearch') {
3925: if ($usersearchconf->{'lclocalonly'}) {
3926: $earlyout = 1;
3927: }
3928: } else {
3929: if ($usersearchconf->{'localonly'}) {
3930: $earlyout = 1;
3931: }
3932: }
3933: }
3934: }
3935: if ($earlyout) {
3936: &Reply($client, "query_not_authorized\n");
3937: return 1;
3938: }
3939: }
1.234 foxr 3940: &Reply($client, "". &sql_reply("$clientname\&$query".
3941: "\&$arg1"."\&$arg2"."\&$arg3")."\n",
3942: $userinput);
3943:
3944: return 1;
3945: }
3946: ®ister_handler("querysend", \&send_query_handler, 0, 1, 0);
3947:
3948: #
3949: # Add a reply to an sql query. SQL queries are done asyncrhonously.
3950: # The query is submitted via a "querysend" transaction.
3951: # There it is passed on to the lonsql daemon, queued and issued to
3952: # mysql.
3953: # This transaction is invoked when the sql transaction is complete
3954: # it stores the query results in flie and indicates query completion.
3955: # presumably local software then fetches this response... I'm guessing
3956: # the sequence is: lonc does a querysend, we ask lonsql to do it.
3957: # lonsql on completion of the query interacts with the lond of our
3958: # client to do a query reply storing two files:
3959: # - id - The results of the query.
3960: # - id.end - Indicating the transaction completed.
3961: # NOTE: id is a unique id assigned to the query and querysend time.
3962: # Parameters:
3963: # $cmd - Command keyword that initiated this request.
3964: # $tail - Remainder of the tail. In this case that's a colon
3965: # separated list containing the query Id and the
3966: # results of the query.
3967: # $client - Socket open on the client.
3968: # Return:
3969: # 1 - Indicating that we should continue processing.
3970: # Side effects:
3971: # ok written to the client.
3972: #
3973: sub reply_query_handler {
3974: my ($cmd, $tail, $client) = @_;
3975:
3976:
3977: my $userinput = "$cmd:$tail";
3978:
1.339 albertel 3979: my ($id,$reply)=split(/:/,$tail);
1.234 foxr 3980: my $store;
3981: my $execdir=$perlvar{'lonDaemons'};
3982: if ($store=IO::File->new(">$execdir/tmp/$id")) {
3983: $reply=~s/\&/\n/g;
3984: print $store $reply;
3985: close $store;
3986: my $store2=IO::File->new(">$execdir/tmp/$id.end");
3987: print $store2 "done\n";
3988: close $store2;
3989: &Reply($client, "ok\n", $userinput);
3990: } else {
3991: &Failure($client, "error: ".($!+0)
3992: ." IO::File->new Failed ".
3993: "while attempting queryreply\n", $userinput);
3994: }
3995:
3996:
3997: return 1;
3998: }
3999: ®ister_handler("queryreply", \&reply_query_handler, 0, 1, 0);
4000:
4001: #
4002: # Process the courseidput request. Not quite sure what this means
4003: # at the system level sense. It appears a gdbm file in the
4004: # /home/httpd/lonUsers/$domain/nohist_courseids is tied and
4005: # a set of entries made in that database.
4006: #
4007: # Parameters:
4008: # $cmd - The command keyword that initiated this request.
4009: # $tail - Tail of the command. In this case consists of a colon
4010: # separated list contaning the domain to apply this to and
4011: # an ampersand separated list of keyword=value pairs.
1.272 raeburn 4012: # Each value is a colon separated list that includes:
4013: # description, institutional code and course owner.
4014: # For backward compatibility with versions included
4015: # in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
4016: # code and/or course owner are preserved from the existing
4017: # record when writing a new record in response to 1.1 or
4018: # 1.2 implementations of lonnet::flushcourselogs().
4019: #
1.234 foxr 4020: # $client - Socket open on the client.
4021: # Returns:
4022: # 1 - indicating that processing should continue
4023: #
4024: # Side effects:
4025: # reply is written to the client.
4026: #
4027: sub put_course_id_handler {
4028: my ($cmd, $tail, $client) = @_;
4029:
4030:
4031: my $userinput = "$cmd:$tail";
4032:
1.266 raeburn 4033: my ($udom, $what) = split(/:/, $tail,2);
1.234 foxr 4034: chomp($what);
4035: my $now=time;
4036: my @pairs=split(/\&/,$what);
4037:
4038: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
4039: if ($hashref) {
4040: foreach my $pair (@pairs) {
1.271 raeburn 4041: my ($key,$courseinfo) = split(/=/,$pair,2);
4042: $courseinfo =~ s/=/:/g;
1.384 raeburn 4043: if (defined($hashref->{$key})) {
4044: my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
4045: if (ref($value) eq 'HASH') {
4046: my @items = ('description','inst_code','owner','type');
4047: my @new_items = split(/:/,$courseinfo,-1);
4048: my %storehash;
4049: for (my $i=0; $i<@new_items; $i++) {
1.391 raeburn 4050: $storehash{$items[$i]} = &unescape($new_items[$i]);
1.384 raeburn 4051: }
4052: $hashref->{$key} =
4053: &Apache::lonnet::freeze_escape(\%storehash);
4054: my $unesc_key = &unescape($key);
4055: $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
4056: next;
1.383 raeburn 4057: }
1.384 raeburn 4058: }
4059: my @current_items = split(/:/,$hashref->{$key},-1);
4060: shift(@current_items); # remove description
4061: pop(@current_items); # remove last access
4062: my $numcurrent = scalar(@current_items);
4063: if ($numcurrent > 3) {
4064: $numcurrent = 3;
4065: }
4066: my @new_items = split(/:/,$courseinfo,-1);
4067: my $numnew = scalar(@new_items);
4068: if ($numcurrent > 0) {
4069: if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2
4070: for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
4071: $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
1.333 raeburn 4072: }
1.272 raeburn 4073: }
4074: }
1.384 raeburn 4075: $hashref->{$key}=$courseinfo.':'.$now;
1.234 foxr 4076: }
1.311 albertel 4077: if (&untie_domain_hash($hashref)) {
1.253 foxr 4078: &Reply( $client, "ok\n", $userinput);
1.234 foxr 4079: } else {
1.253 foxr 4080: &Failure($client, "error: ".($!+0)
1.234 foxr 4081: ." untie(GDBM) Failed ".
4082: "while attempting courseidput\n", $userinput);
4083: }
4084: } else {
1.253 foxr 4085: &Failure($client, "error: ".($!+0)
1.234 foxr 4086: ." tie(GDBM) Failed ".
4087: "while attempting courseidput\n", $userinput);
4088: }
4089:
4090: return 1;
4091: }
4092: ®ister_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
4093:
1.383 raeburn 4094: sub put_course_id_hash_handler {
4095: my ($cmd, $tail, $client) = @_;
4096: my $userinput = "$cmd:$tail";
1.384 raeburn 4097: my ($udom,$mode,$what) = split(/:/, $tail,3);
1.383 raeburn 4098: chomp($what);
4099: my $now=time;
4100: my @pairs=split(/\&/,$what);
1.384 raeburn 4101: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
1.383 raeburn 4102: if ($hashref) {
4103: foreach my $pair (@pairs) {
4104: my ($key,$value)=split(/=/,$pair);
1.384 raeburn 4105: my $unesc_key = &unescape($key);
4106: if ($mode ne 'timeonly') {
4107: if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
4108: my $curritems = &Apache::lonnet::thaw_unescape($key);
4109: if (ref($curritems) ne 'HASH') {
4110: my @current_items = split(/:/,$hashref->{$key},-1);
4111: my $lasttime = pop(@current_items);
4112: $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
4113: } else {
4114: $hashref->{&escape('lasttime:'.$unesc_key)} = '';
4115: }
4116: }
4117: $hashref->{$key} = $value;
4118: }
4119: if ($mode ne 'notime') {
4120: $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
4121: }
1.383 raeburn 4122: }
4123: if (&untie_domain_hash($hashref)) {
4124: &Reply($client, "ok\n", $userinput);
4125: } else {
4126: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4127: "while attempting courseidputhash\n", $userinput);
4128: }
4129: } else {
4130: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4131: "while attempting courseidputhash\n", $userinput);
4132: }
4133: return 1;
4134: }
4135: ®ister_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
4136:
1.234 foxr 4137: # Retrieves the value of a course id resource keyword pattern
4138: # defined since a starting date. Both the starting date and the
4139: # keyword pattern are optional. If the starting date is not supplied it
4140: # is treated as the beginning of time. If the pattern is not found,
4141: # it is treatred as "." matching everything.
4142: #
4143: # Parameters:
4144: # $cmd - Command keyword that resulted in us being dispatched.
4145: # $tail - The remainder of the command that, in this case, consists
4146: # of a colon separated list of:
4147: # domain - The domain in which the course database is
4148: # defined.
4149: # since - Optional parameter describing the minimum
4150: # time of definition(?) of the resources that
4151: # will match the dump.
4152: # description - regular expression that is used to filter
4153: # the dump. Only keywords matching this regexp
4154: # will be used.
1.272 raeburn 4155: # institutional code - optional supplied code to filter
4156: # the dump. Only courses with an institutional code
4157: # that match the supplied code will be returned.
1.336 raeburn 4158: # owner - optional supplied username and domain of owner to
4159: # filter the dump. Only courses for which the course
4160: # owner matches the supplied username and/or domain
4161: # will be returned. Pre-2.2.0 legacy entries from
4162: # nohist_courseiddump will only contain usernames.
1.384 raeburn 4163: # type - optional parameter for selection
1.418 raeburn 4164: # regexp_ok - if 1 or -1 allow the supplied institutional code
4165: # filter to behave as a regular expression:
4166: # 1 will not exclude the course if the instcode matches the RE
4167: # -1 will exclude the course if the instcode matches the RE
1.384 raeburn 4168: # rtn_as_hash - whether to return the information available for
4169: # each matched item as a frozen hash of all
4170: # key, value pairs in the item's hash, or as a
4171: # colon-separated list of (in order) description,
4172: # institutional code, and course owner.
1.404 raeburn 4173: # selfenrollonly - filter by courses allowing self-enrollment
4174: # now or in the future (selfenrollonly = 1).
4175: # catfilter - filter by course category, assigned to a course
4176: # using manually defined categories (i.e., not
1.407 raeburn 4177: # self-cataloging based on on institutional code).
1.404 raeburn 4178: # showhidden - include course in results even if course
1.407 raeburn 4179: # was set to be excluded from course catalog (DC only).
1.404 raeburn 4180: # caller - if set to 'coursecatalog', courses set to be hidden
4181: # from course catalog will be excluded from results (unless
4182: # overridden by "showhidden".
1.427 raeburn 4183: # cloner - escaped username:domain of course cloner (if picking course to
1.419 raeburn 4184: # clone).
4185: # cc_clone_list - escaped comma separated list of courses for which
4186: # course cloner has active CC role (and so can clone
4187: # automatically).
1.427 raeburn 4188: # cloneonly - filter by courses for which cloner has rights to clone.
4189: # createdbefore - include courses for which creation date preceeded this date.
4190: # createdafter - include courses for which creation date followed this date.
4191: # creationcontext - include courses created in specified context
1.404 raeburn 4192: #
1.445 raeburn 4193: # domcloner - flag to indicate if user can create CCs in course's domain.
1.489.2.11 raeburn 4194: # If so, ability to clone course is automatic.
4195: # hasuniquecode - filter by courses for which a six character unique code has
4196: # been set.
1.445 raeburn 4197: #
1.234 foxr 4198: # $client - The socket open on the client.
4199: # Returns:
4200: # 1 - Continue processing.
4201: # Side Effects:
4202: # a reply is written to $client.
4203: sub dump_course_id_handler {
4204: my ($cmd, $tail, $client) = @_;
4205: my $userinput = "$cmd:$tail";
4206:
1.333 raeburn 4207: my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
1.404 raeburn 4208: $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
1.427 raeburn 4209: $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
1.489.2.11 raeburn 4210: $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
1.397 raeburn 4211: my $now = time;
1.419 raeburn 4212: my ($cloneruname,$clonerudom,%cc_clone);
1.234 foxr 4213: if (defined($description)) {
4214: $description=&unescape($description);
4215: } else {
4216: $description='.';
4217: }
1.266 raeburn 4218: if (defined($instcodefilter)) {
4219: $instcodefilter=&unescape($instcodefilter);
4220: } else {
4221: $instcodefilter='.';
4222: }
1.336 raeburn 4223: my ($ownerunamefilter,$ownerdomfilter);
1.266 raeburn 4224: if (defined($ownerfilter)) {
4225: $ownerfilter=&unescape($ownerfilter);
1.336 raeburn 4226: if ($ownerfilter ne '.' && defined($ownerfilter)) {
4227: if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
4228: $ownerunamefilter = $1;
4229: $ownerdomfilter = $2;
4230: } else {
4231: $ownerunamefilter = $ownerfilter;
4232: $ownerdomfilter = '';
4233: }
4234: }
1.266 raeburn 4235: } else {
4236: $ownerfilter='.';
4237: }
1.336 raeburn 4238:
1.282 raeburn 4239: if (defined($coursefilter)) {
4240: $coursefilter=&unescape($coursefilter);
4241: } else {
4242: $coursefilter='.';
4243: }
1.333 raeburn 4244: if (defined($typefilter)) {
4245: $typefilter=&unescape($typefilter);
4246: } else {
4247: $typefilter='.';
4248: }
1.344 raeburn 4249: if (defined($regexp_ok)) {
4250: $regexp_ok=&unescape($regexp_ok);
4251: }
1.401 raeburn 4252: if (defined($catfilter)) {
4253: $catfilter=&unescape($catfilter);
4254: }
1.419 raeburn 4255: if (defined($cloner)) {
4256: $cloner = &unescape($cloner);
4257: ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/);
4258: }
4259: if (defined($cc_clone_list)) {
4260: $cc_clone_list = &unescape($cc_clone_list);
4261: my @cc_cloners = split('&',$cc_clone_list);
4262: foreach my $cid (@cc_cloners) {
4263: my ($clonedom,$clonenum) = split(':',$cid);
4264: next if ($clonedom ne $udom);
4265: $cc_clone{$clonedom.'_'.$clonenum} = 1;
4266: }
4267: }
1.431 raeburn 4268: if ($createdbefore ne '') {
1.427 raeburn 4269: $createdbefore = &unescape($createdbefore);
4270: } else {
4271: $createdbefore = 0;
4272: }
1.431 raeburn 4273: if ($createdafter ne '') {
1.427 raeburn 4274: $createdafter = &unescape($createdafter);
4275: } else {
4276: $createdafter = 0;
4277: }
1.431 raeburn 4278: if ($creationcontext ne '') {
1.427 raeburn 4279: $creationcontext = &unescape($creationcontext);
4280: } else {
4281: $creationcontext = '.';
4282: }
1.489.2.11 raeburn 4283: unless ($hasuniquecode) {
4284: $hasuniquecode = '.';
4285: }
1.384 raeburn 4286: my $unpack = 1;
1.485 raeburn 4287: if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' &&
1.384 raeburn 4288: $typefilter eq '.') {
4289: $unpack = 0;
4290: }
4291: if (!defined($since)) { $since=0; }
1.234 foxr 4292: my $qresult='';
4293: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
4294: if ($hashref) {
1.384 raeburn 4295: while (my ($key,$value) = each(%$hashref)) {
1.397 raeburn 4296: my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
1.427 raeburn 4297: %unesc_val,$selfenroll_end,$selfenroll_types,$created,
4298: $context);
1.384 raeburn 4299: $unesc_key = &unescape($key);
4300: if ($unesc_key =~ /^lasttime:/) {
4301: next;
4302: } else {
4303: $lasttime_key = &escape('lasttime:'.$unesc_key);
4304: }
4305: if ($hashref->{$lasttime_key} ne '') {
4306: $lasttime = $hashref->{$lasttime_key};
4307: next if ($lasttime<$since);
4308: }
1.419 raeburn 4309: my ($canclone,$valchange);
1.384 raeburn 4310: my $items = &Apache::lonnet::thaw_unescape($value);
4311: if (ref($items) eq 'HASH') {
1.429 raeburn 4312: if ($hashref->{$lasttime_key} eq '') {
1.430 raeburn 4313: next if ($since > 1);
1.429 raeburn 4314: }
1.384 raeburn 4315: $is_hash = 1;
1.445 raeburn 4316: if ($domcloner) {
4317: $canclone = 1;
4318: } elsif (defined($clonerudom)) {
1.419 raeburn 4319: if ($items->{'cloners'}) {
4320: my @cloneable = split(',',$items->{'cloners'});
4321: if (@cloneable) {
4322: if (grep(/^\*$/,@cloneable)) {
4323: $canclone = 1;
4324: } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
4325: $canclone = 1;
4326: } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
4327: $canclone = 1;
4328: }
4329: }
4330: unless ($canclone) {
4331: if ($cloneruname ne '' && $clonerudom ne '') {
4332: if ($cc_clone{$unesc_key}) {
4333: $canclone = 1;
4334: $items->{'cloners'} .= ','.$cloneruname.':'.
4335: $clonerudom;
4336: $valchange = 1;
4337: }
4338: }
4339: }
4340: } elsif (defined($cloneruname)) {
4341: if ($cc_clone{$unesc_key}) {
4342: $canclone = 1;
4343: $items->{'cloners'} = $cloneruname.':'.$clonerudom;
4344: $valchange = 1;
4345: }
1.437 raeburn 4346: unless ($canclone) {
4347: if ($items->{'owner'} =~ /:/) {
4348: if ($items->{'owner'} eq $cloner) {
4349: $canclone = 1;
4350: }
1.444 raeburn 4351: } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
1.437 raeburn 4352: $canclone = 1;
4353: }
4354: if ($canclone) {
4355: $items->{'cloners'} = $cloneruname.':'.$clonerudom;
4356: $valchange = 1;
4357: }
4358: }
1.419 raeburn 4359: }
4360: }
1.384 raeburn 4361: if ($unpack || !$rtn_as_hash) {
4362: $unesc_val{'descr'} = $items->{'description'};
4363: $unesc_val{'inst_code'} = $items->{'inst_code'};
4364: $unesc_val{'owner'} = $items->{'owner'};
4365: $unesc_val{'type'} = $items->{'type'};
1.419 raeburn 4366: $unesc_val{'cloners'} = $items->{'cloners'};
1.427 raeburn 4367: $unesc_val{'created'} = $items->{'created'};
4368: $unesc_val{'context'} = $items->{'context'};
1.404 raeburn 4369: }
4370: $selfenroll_types = $items->{'selfenroll_types'};
4371: $selfenroll_end = $items->{'selfenroll_end_date'};
1.427 raeburn 4372: $created = $items->{'created'};
4373: $context = $items->{'context'};
1.489.2.11 raeburn 4374: if ($hasuniquecode ne '.') {
4375: next unless ($items->{'uniquecode'});
4376: }
1.404 raeburn 4377: if ($selfenrollonly) {
4378: next if (!$selfenroll_types);
4379: if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
4380: next;
1.397 raeburn 4381: }
1.404 raeburn 4382: }
1.427 raeburn 4383: if ($creationcontext ne '.') {
4384: next if (($context ne '') && ($context ne $creationcontext));
4385: }
4386: if ($createdbefore > 0) {
4387: next if (($created eq '') || ($created > $createdbefore));
4388: }
4389: if ($createdafter > 0) {
4390: next if (($created eq '') || ($created <= $createdafter));
4391: }
1.404 raeburn 4392: if ($catfilter ne '') {
1.406 raeburn 4393: next if ($items->{'categories'} eq '');
4394: my @categories = split('&',$items->{'categories'});
1.407 raeburn 4395: next if (@categories == 0);
4396: my @subcats = split('&',$catfilter);
4397: my $matchcat = 0;
4398: foreach my $cat (@categories) {
4399: if (grep(/^\Q$cat\E$/,@subcats)) {
4400: $matchcat = 1;
4401: last;
4402: }
4403: }
4404: next if (!$matchcat);
1.404 raeburn 4405: }
4406: if ($caller eq 'coursecatalog') {
1.405 raeburn 4407: if ($items->{'hidefromcat'} eq 'yes') {
4408: next if !$showhidden;
1.401 raeburn 4409: }
1.384 raeburn 4410: }
1.383 raeburn 4411: } else {
1.401 raeburn 4412: next if ($catfilter ne '');
1.419 raeburn 4413: next if ($selfenrollonly);
1.427 raeburn 4414: next if ($createdbefore || $createdafter);
4415: next if ($creationcontext ne '.');
1.419 raeburn 4416: if ((defined($clonerudom)) && (defined($cloneruname))) {
4417: if ($cc_clone{$unesc_key}) {
4418: $canclone = 1;
4419: $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
4420: }
4421: }
1.384 raeburn 4422: $is_hash = 0;
1.388 raeburn 4423: my @courseitems = split(/:/,$value);
1.403 raeburn 4424: $lasttime = pop(@courseitems);
1.402 raeburn 4425: if ($hashref->{$lasttime_key} eq '') {
4426: next if ($lasttime<$since);
4427: }
1.384 raeburn 4428: ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
1.383 raeburn 4429: }
1.419 raeburn 4430: if ($cloneonly) {
4431: next unless ($canclone);
4432: }
1.266 raeburn 4433: my $match = 1;
1.384 raeburn 4434: if ($description ne '.') {
4435: if (!$is_hash) {
4436: $unesc_val{'descr'} = &unescape($val{'descr'});
4437: }
4438: if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
1.266 raeburn 4439: $match = 0;
1.384 raeburn 4440: }
1.266 raeburn 4441: }
1.384 raeburn 4442: if ($instcodefilter ne '.') {
4443: if (!$is_hash) {
4444: $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
4445: }
1.418 raeburn 4446: if ($regexp_ok == 1) {
1.384 raeburn 4447: if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
1.344 raeburn 4448: $match = 0;
4449: }
1.418 raeburn 4450: } elsif ($regexp_ok == -1) {
4451: if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
4452: $match = 0;
4453: }
1.344 raeburn 4454: } else {
1.384 raeburn 4455: if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
1.344 raeburn 4456: $match = 0;
4457: }
1.266 raeburn 4458: }
1.234 foxr 4459: }
1.384 raeburn 4460: if ($ownerfilter ne '.') {
4461: if (!$is_hash) {
4462: $unesc_val{'owner'} = &unescape($val{'owner'});
4463: }
1.336 raeburn 4464: if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
1.384 raeburn 4465: if ($unesc_val{'owner'} =~ /:/) {
4466: if (eval{$unesc_val{'owner'} !~
4467: /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
1.336 raeburn 4468: $match = 0;
4469: }
4470: } else {
1.384 raeburn 4471: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336 raeburn 4472: $match = 0;
4473: }
4474: }
4475: } elsif ($ownerunamefilter ne '') {
1.384 raeburn 4476: if ($unesc_val{'owner'} =~ /:/) {
4477: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
1.336 raeburn 4478: $match = 0;
4479: }
4480: } else {
1.384 raeburn 4481: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
1.336 raeburn 4482: $match = 0;
4483: }
4484: }
4485: } elsif ($ownerdomfilter ne '') {
1.384 raeburn 4486: if ($unesc_val{'owner'} =~ /:/) {
4487: if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
1.336 raeburn 4488: $match = 0;
4489: }
4490: } else {
4491: if ($ownerdomfilter ne $udom) {
4492: $match = 0;
4493: }
4494: }
1.266 raeburn 4495: }
4496: }
1.384 raeburn 4497: if ($coursefilter ne '.') {
4498: if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
1.282 raeburn 4499: $match = 0;
4500: }
4501: }
1.384 raeburn 4502: if ($typefilter ne '.') {
4503: if (!$is_hash) {
4504: $unesc_val{'type'} = &unescape($val{'type'});
4505: }
4506: if ($unesc_val{'type'} eq '') {
1.333 raeburn 4507: if ($typefilter ne 'Course') {
4508: $match = 0;
4509: }
1.383 raeburn 4510: } else {
1.384 raeburn 4511: if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
1.333 raeburn 4512: $match = 0;
4513: }
4514: }
4515: }
1.266 raeburn 4516: if ($match == 1) {
1.384 raeburn 4517: if ($rtn_as_hash) {
4518: if ($is_hash) {
1.419 raeburn 4519: if ($valchange) {
4520: my $newvalue = &Apache::lonnet::freeze_escape($items);
4521: $qresult.=$key.'='.$newvalue.'&';
4522: } else {
4523: $qresult.=$key.'='.$value.'&';
4524: }
1.384 raeburn 4525: } else {
1.388 raeburn 4526: my %rtnhash = ( 'description' => &unescape($val{'descr'}),
4527: 'inst_code' => &unescape($val{'inst_code'}),
4528: 'owner' => &unescape($val{'owner'}),
4529: 'type' => &unescape($val{'type'}),
1.419 raeburn 4530: 'cloners' => &unescape($val{'cloners'}),
1.384 raeburn 4531: );
4532: my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
4533: $qresult.=$key.'='.$items.'&';
4534: }
1.383 raeburn 4535: } else {
1.384 raeburn 4536: if ($is_hash) {
4537: $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
4538: &escape($unesc_val{'inst_code'}).':'.
4539: &escape($unesc_val{'owner'}).'&';
4540: } else {
4541: $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
4542: ':'.$val{'owner'}.'&';
4543: }
1.383 raeburn 4544: }
1.266 raeburn 4545: }
1.234 foxr 4546: }
1.311 albertel 4547: if (&untie_domain_hash($hashref)) {
1.234 foxr 4548: chop($qresult);
1.387 albertel 4549: &Reply($client, \$qresult, $userinput);
1.234 foxr 4550: } else {
4551: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4552: "while attempting courseiddump\n", $userinput);
4553: }
4554: } else {
4555: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4556: "while attempting courseiddump\n", $userinput);
4557: }
4558: return 1;
4559: }
4560: ®ister_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238 foxr 4561:
1.438 raeburn 4562: sub course_lastaccess_handler {
4563: my ($cmd, $tail, $client) = @_;
4564: my $userinput = "$cmd:$tail";
4565: my ($cdom,$cnum) = split(':',$tail);
4566: my (%lastaccess,$qresult);
4567: my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
4568: if ($hashref) {
4569: while (my ($key,$value) = each(%$hashref)) {
4570: my ($unesc_key,$lasttime);
4571: $unesc_key = &unescape($key);
4572: if ($cnum) {
4573: next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
4574: }
4575: if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
4576: $lastaccess{$1} = $value;
4577: } else {
4578: my $items = &Apache::lonnet::thaw_unescape($value);
4579: if (ref($items) eq 'HASH') {
4580: unless ($lastaccess{$unesc_key}) {
4581: $lastaccess{$unesc_key} = '';
4582: }
4583: } else {
4584: my @courseitems = split(':',$value);
4585: $lastaccess{$unesc_key} = pop(@courseitems);
4586: }
4587: }
4588: }
4589: foreach my $cid (sort(keys(%lastaccess))) {
4590: $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&';
4591: }
4592: if (&untie_domain_hash($hashref)) {
4593: if ($qresult) {
4594: chop($qresult);
4595: }
4596: &Reply($client, \$qresult, $userinput);
4597: } else {
4598: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4599: "while attempting lastacourseaccess\n", $userinput);
4600: }
4601: } else {
4602: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4603: "while attempting lastcourseaccess\n", $userinput);
4604: }
4605: return 1;
4606: }
4607: ®ister_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
4608:
1.489.2.36 raeburn 4609: sub course_sessions_handler {
4610: my ($cmd, $tail, $client) = @_;
4611: my $userinput = "$cmd:$tail";
4612: my ($cdom,$cnum,$lastactivity) = split(':',$tail);
4613: my $dbsuffix = '_'.$cdom.'_'.$cnum.'.db';
4614: my (%sessions,$qresult);
4615: my $now=time;
4616: if (opendir(DIR,$perlvar{'lonIDsDir'})) {
4617: my $filename;
4618: while ($filename=readdir(DIR)) {
4619: next if ($filename=~/^\./);
4620: next if ($filename=~/^publicuser_/);
4621: next if ($filename=~/^[a-f0-9]+_(linked|lti_\d+)\.id$/);
1.489.2.37 raeburn 4622: if ($filename =~ /^($LONCAPA::match_username)_\d+_($LONCAPA::match_domain)_/) {
1.489.2.36 raeburn 4623: my ($uname,$udom) = ($1,$2);
1.489.2.37 raeburn 4624: next unless (-e "$perlvar{'lonDaemons'}/tmp/$uname$dbsuffix");
1.489.2.36 raeburn 4625: my $mtime = (stat("$perlvar{'lonIDsDir'}/$filename"))[9];
4626: if ($lastactivity < 0) {
1.489.2.38 raeburn 4627: next if ($mtime-$now > $lastactivity);
1.489.2.36 raeburn 4628: } else {
1.489.2.38 raeburn 4629: next if ($now-$mtime > $lastactivity);
1.489.2.36 raeburn 4630: }
4631: $sessions{$uname.':'.$udom} = $mtime;
4632: }
4633: }
4634: closedir(DIR);
4635: }
4636: foreach my $user (keys(%sessions)) {
4637: $qresult.=&escape($user).'='.$sessions{$user}.'&';
4638: }
4639: if ($qresult) {
4640: chop($qresult);
4641: }
4642: &Reply($client, \$qresult, $userinput);
4643: return 1;
4644: }
4645: ®ister_handler("coursesessions",\&course_sessions_handler, 0, 1, 0);
4646:
1.238 foxr 4647: #
1.348 raeburn 4648: # Puts an unencrypted entry in a namespace db file at the domain level
4649: #
4650: # Parameters:
4651: # $cmd - The command that got us here.
4652: # $tail - Tail of the command (remaining parameters).
4653: # $client - File descriptor connected to client.
4654: # Returns
4655: # 0 - Requested to exit, caller should shut down.
4656: # 1 - Continue processing.
4657: # Side effects:
4658: # reply is written to $client.
4659: #
4660: sub put_domain_handler {
4661: my ($cmd,$tail,$client) = @_;
4662:
4663: my $userinput = "$cmd:$tail";
4664:
4665: my ($udom,$namespace,$what) =split(/:/,$tail,3);
4666: chomp($what);
4667: my @pairs=split(/\&/,$what);
4668: my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
4669: "P", $what);
4670: if ($hashref) {
4671: foreach my $pair (@pairs) {
4672: my ($key,$value)=split(/=/,$pair);
4673: $hashref->{$key}=$value;
4674: }
4675: if (&untie_domain_hash($hashref)) {
4676: &Reply($client, "ok\n", $userinput);
4677: } else {
4678: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4679: "while attempting putdom\n", $userinput);
4680: }
4681: } else {
4682: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4683: "while attempting putdom\n", $userinput);
4684: }
4685:
4686: return 1;
4687: }
4688: ®ister_handler("putdom", \&put_domain_handler, 0, 1, 0);
4689:
4690: # Unencrypted get from the namespace database file at the domain level.
4691: # This function retrieves a keyed item from a specific named database in the
4692: # domain directory.
4693: #
4694: # Parameters:
1.489.2.40 raeburn 4695: # $cmd - Command request keyword (getdom).
1.348 raeburn 4696: # $tail - Tail of the command. This is a colon separated list
4697: # consisting of the domain and the 'namespace'
4698: # which selects the gdbm file to do the lookup in,
4699: # & separated list of keys to lookup. Note that
4700: # the values are returned as an & separated list too.
4701: # $client - File descriptor open on the client.
4702: # Returns:
4703: # 1 - Continue processing.
4704: # 0 - Exit.
4705: # Side effects:
4706: # reply is written to $client.
4707: #
4708:
4709: sub get_domain_handler {
4710: my ($cmd, $tail, $client) = @_;
4711:
1.489.2.34 raeburn 4712: my $userinput = "$cmd:$tail";
1.348 raeburn 4713:
4714: my ($udom,$namespace,$what)=split(/:/,$tail,3);
1.489.2.40 raeburn 4715: my $res = LONCAPA::Lond::get_dom($userinput);
4716: if ($res =~ /^error:/) {
4717: &Failure($client, \$res, $userinput);
1.348 raeburn 4718: } else {
1.489.2.40 raeburn 4719: &Reply($client, \$res, $userinput);
1.348 raeburn 4720: }
4721:
4722: return 1;
4723: }
1.360 raeburn 4724: ®ister_handler("getdom", \&get_domain_handler, 0, 1, 0);
1.348 raeburn 4725:
1.420 raeburn 4726: #
1.238 foxr 4727: # Puts an id to a domains id database.
4728: #
4729: # Parameters:
4730: # $cmd - The command that triggered us.
4731: # $tail - Remainder of the request other than the command. This is a
4732: # colon separated list containing:
4733: # $domain - The domain for which we are writing the id.
4734: # $pairs - The id info to write... this is and & separated list
4735: # of keyword=value.
4736: # $client - Socket open on the client.
4737: # Returns:
4738: # 1 - Continue processing.
4739: # Side effects:
4740: # reply is written to $client.
4741: #
4742: sub put_id_handler {
4743: my ($cmd,$tail,$client) = @_;
4744:
4745:
4746: my $userinput = "$cmd:$tail";
4747:
4748: my ($udom,$what)=split(/:/,$tail);
4749: chomp($what);
4750: my @pairs=split(/\&/,$what);
4751: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
4752: "P", $what);
4753: if ($hashref) {
4754: foreach my $pair (@pairs) {
4755: my ($key,$value)=split(/=/,$pair);
4756: $hashref->{$key}=$value;
4757: }
1.311 albertel 4758: if (&untie_domain_hash($hashref)) {
1.238 foxr 4759: &Reply($client, "ok\n", $userinput);
4760: } else {
4761: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4762: "while attempting idput\n", $userinput);
4763: }
4764: } else {
4765: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4766: "while attempting idput\n", $userinput);
4767: }
4768:
4769: return 1;
4770: }
1.263 albertel 4771: ®ister_handler("idput", \&put_id_handler, 0, 1, 0);
1.238 foxr 4772:
4773: #
4774: # Retrieves a set of id values from the id database.
4775: # Returns an & separated list of results, one for each requested id to the
4776: # client.
4777: #
4778: # Parameters:
4779: # $cmd - Command keyword that caused us to be dispatched.
4780: # $tail - Tail of the command. Consists of a colon separated:
4781: # domain - the domain whose id table we dump
4782: # ids Consists of an & separated list of
4783: # id keywords whose values will be fetched.
4784: # nonexisting keywords will have an empty value.
4785: # $client - Socket open on the client.
4786: #
4787: # Returns:
4788: # 1 - indicating processing should continue.
4789: # Side effects:
4790: # An & separated list of results is written to $client.
4791: #
4792: sub get_id_handler {
4793: my ($cmd, $tail, $client) = @_;
4794:
4795:
4796: my $userinput = "$client:$tail";
4797:
4798: my ($udom,$what)=split(/:/,$tail);
4799: chomp($what);
4800: my @queries=split(/\&/,$what);
4801: my $qresult='';
4802: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
4803: if ($hashref) {
4804: for (my $i=0;$i<=$#queries;$i++) {
4805: $qresult.="$hashref->{$queries[$i]}&";
4806: }
1.311 albertel 4807: if (&untie_domain_hash($hashref)) {
1.238 foxr 4808: $qresult=~s/\&$//;
1.387 albertel 4809: &Reply($client, \$qresult, $userinput);
1.238 foxr 4810: } else {
4811: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
4812: "while attempting idget\n",$userinput);
4813: }
4814: } else {
4815: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4816: "while attempting idget\n",$userinput);
4817: }
4818:
4819: return 1;
4820: }
1.263 albertel 4821: ®ister_handler("idget", \&get_id_handler, 0, 1, 0);
1.238 foxr 4822:
1.489.2.7 raeburn 4823: # Deletes one or more ids in a domain's id database.
1.489.2.6 raeburn 4824: #
4825: # Parameters:
4826: # $cmd - Command keyword (iddel).
4827: # $tail - Command tail. In this case a colon
4828: # separated list containing:
4829: # The domain for which we are deleting the id(s).
4830: # &-separated list of id(s) to delete.
4831: # $client - File open on client socket.
4832: # Returns:
4833: # 1 - Continue processing
4834: # 0 - Exit server.
4835: #
4836: #
4837:
4838: sub del_id_handler {
4839: my ($cmd,$tail,$client) = @_;
4840:
4841: my $userinput = "$cmd:$tail";
4842:
4843: my ($udom,$what)=split(/:/,$tail);
4844: chomp($what);
4845: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
4846: "D", $what);
4847: if ($hashref) {
4848: my @keys=split(/\&/,$what);
4849: foreach my $key (@keys) {
4850: delete($hashref->{$key});
4851: }
4852: if (&untie_user_hash($hashref)) {
4853: &Reply($client, "ok\n", $userinput);
4854: } else {
4855: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4856: "while attempting iddel\n", $userinput);
4857: }
4858: } else {
4859: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4860: "while attempting iddel\n", $userinput);
4861: }
4862: return 1;
4863: }
4864: ®ister_handler("iddel", \&del_id_handler, 0, 1, 0);
4865:
1.238 foxr 4866: #
1.299 raeburn 4867: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail 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 dcmail we are recording
4873: # email Consists of key=value pair
4874: # where key is unique msgid
4875: # and value is message (in XML)
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: sub put_dcmail_handler {
4884: my ($cmd,$tail,$client) = @_;
4885: my $userinput = "$cmd:$tail";
1.463 foxr 4886:
4887:
1.299 raeburn 4888: my ($udom,$what)=split(/:/,$tail);
4889: chomp($what);
4890: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
4891: if ($hashref) {
4892: my ($key,$value)=split(/=/,$what);
4893: $hashref->{$key}=$value;
4894: }
1.311 albertel 4895: if (&untie_domain_hash($hashref)) {
1.299 raeburn 4896: &Reply($client, "ok\n", $userinput);
4897: } else {
4898: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4899: "while attempting dcmailput\n", $userinput);
4900: }
4901: return 1;
4902: }
4903: ®ister_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
4904:
4905: #
4906: # Retrieves broadcast e-mail from nohist_dcmail database
4907: # Returns to client an & separated list of key=value pairs,
4908: # where key is msgid and value is message information.
4909: #
4910: # Parameters
4911: # $cmd - Command keyword that caused us to be dispatched.
4912: # $tail - Tail of the command. Consists of a colon separated:
4913: # domain - the domain whose dcmail table we dump
4914: # startfilter - beginning of time window
4915: # endfilter - end of time window
4916: # sendersfilter - & separated list of username:domain
4917: # for senders to search for.
4918: # $client - Socket open on the client.
4919: #
4920: # Returns:
4921: # 1 - indicating processing should continue.
4922: # Side effects
4923: # reply (& separated list of msgid=messageinfo pairs) is
4924: # written to $client.
4925: #
4926: sub dump_dcmail_handler {
4927: my ($cmd, $tail, $client) = @_;
4928:
4929: my $userinput = "$cmd:$tail";
4930: my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
4931: chomp($sendersfilter);
4932: my @senders = ();
4933: if (defined($startfilter)) {
4934: $startfilter=&unescape($startfilter);
4935: } else {
4936: $startfilter='.';
4937: }
4938: if (defined($endfilter)) {
4939: $endfilter=&unescape($endfilter);
4940: } else {
4941: $endfilter='.';
4942: }
4943: if (defined($sendersfilter)) {
4944: $sendersfilter=&unescape($sendersfilter);
1.300 albertel 4945: @senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299 raeburn 4946: }
4947:
4948: my $qresult='';
4949: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
4950: if ($hashref) {
4951: while (my ($key,$value) = each(%$hashref)) {
4952: my $match = 1;
1.303 albertel 4953: my ($timestamp,$subj,$uname,$udom) =
4954: split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299 raeburn 4955: $subj = &unescape($subj);
4956: unless ($startfilter eq '.' || !defined($startfilter)) {
4957: if ($timestamp < $startfilter) {
4958: $match = 0;
4959: }
4960: }
4961: unless ($endfilter eq '.' || !defined($endfilter)) {
4962: if ($timestamp > $endfilter) {
4963: $match = 0;
4964: }
4965: }
4966: unless (@senders < 1) {
4967: unless (grep/^$uname:$udom$/,@senders) {
4968: $match = 0;
4969: }
4970: }
4971: if ($match == 1) {
4972: $qresult.=$key.'='.$value.'&';
4973: }
4974: }
1.311 albertel 4975: if (&untie_domain_hash($hashref)) {
1.299 raeburn 4976: chop($qresult);
1.387 albertel 4977: &Reply($client, \$qresult, $userinput);
1.299 raeburn 4978: } else {
4979: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4980: "while attempting dcmaildump\n", $userinput);
4981: }
4982: } else {
4983: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4984: "while attempting dcmaildump\n", $userinput);
4985: }
4986: return 1;
4987: }
4988:
4989: ®ister_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
4990:
4991: #
4992: # Puts domain roles in nohist_domainroles database
4993: #
4994: # Parameters
4995: # $cmd - Command keyword that caused us to be dispatched.
4996: # $tail - Tail of the command. Consists of a colon separated:
4997: # domain - the domain whose roles we are recording
4998: # role - Consists of key=value pair
4999: # where key is unique role
5000: # and value is start/end date information
5001: # $client - Socket open on the client.
5002: #
5003: # Returns:
5004: # 1 - indicating processing should continue.
5005: # Side effects
5006: # reply is written to $client.
5007: #
5008:
5009: sub put_domainroles_handler {
5010: my ($cmd,$tail,$client) = @_;
5011:
5012: my $userinput = "$cmd:$tail";
5013: my ($udom,$what)=split(/:/,$tail);
5014: chomp($what);
5015: my @pairs=split(/\&/,$what);
5016: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
5017: if ($hashref) {
5018: foreach my $pair (@pairs) {
5019: my ($key,$value)=split(/=/,$pair);
5020: $hashref->{$key}=$value;
5021: }
1.311 albertel 5022: if (&untie_domain_hash($hashref)) {
1.299 raeburn 5023: &Reply($client, "ok\n", $userinput);
5024: } else {
5025: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5026: "while attempting domroleput\n", $userinput);
5027: }
5028: } else {
5029: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5030: "while attempting domroleput\n", $userinput);
5031: }
5032:
5033: return 1;
5034: }
5035:
5036: ®ister_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
5037:
5038: #
5039: # Retrieves domain roles from nohist_domainroles database
5040: # Returns to client an & separated list of key=value pairs,
5041: # where key is role and value is start and end date information.
5042: #
5043: # Parameters
5044: # $cmd - Command keyword that caused us to be dispatched.
5045: # $tail - Tail of the command. Consists of a colon separated:
5046: # domain - the domain whose domain roles table we dump
5047: # $client - Socket open on the client.
5048: #
5049: # Returns:
5050: # 1 - indicating processing should continue.
5051: # Side effects
5052: # reply (& separated list of role=start/end info pairs) is
5053: # written to $client.
5054: #
5055: sub dump_domainroles_handler {
5056: my ($cmd, $tail, $client) = @_;
5057:
5058: my $userinput = "$cmd:$tail";
5059: my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
5060: chomp($rolesfilter);
5061: my @roles = ();
5062: if (defined($startfilter)) {
5063: $startfilter=&unescape($startfilter);
5064: } else {
5065: $startfilter='.';
5066: }
5067: if (defined($endfilter)) {
5068: $endfilter=&unescape($endfilter);
5069: } else {
5070: $endfilter='.';
5071: }
5072: if (defined($rolesfilter)) {
5073: $rolesfilter=&unescape($rolesfilter);
1.300 albertel 5074: @roles = split(/\&/,$rolesfilter);
1.299 raeburn 5075: }
1.421 raeburn 5076:
1.299 raeburn 5077: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
5078: if ($hashref) {
5079: my $qresult = '';
5080: while (my ($key,$value) = each(%$hashref)) {
5081: my $match = 1;
1.421 raeburn 5082: my ($end,$start) = split(/:/,&unescape($value));
1.299 raeburn 5083: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
1.421 raeburn 5084: unless (@roles < 1) {
5085: unless (grep/^\Q$trole\E$/,@roles) {
5086: $match = 0;
5087: next;
5088: }
5089: }
1.299 raeburn 5090: unless ($startfilter eq '.' || !defined($startfilter)) {
1.415 raeburn 5091: if ((defined($start)) && ($start >= $startfilter)) {
1.299 raeburn 5092: $match = 0;
1.421 raeburn 5093: next;
1.299 raeburn 5094: }
5095: }
5096: unless ($endfilter eq '.' || !defined($endfilter)) {
1.421 raeburn 5097: if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
1.299 raeburn 5098: $match = 0;
1.421 raeburn 5099: next;
1.299 raeburn 5100: }
5101: }
5102: if ($match == 1) {
5103: $qresult.=$key.'='.$value.'&';
5104: }
5105: }
1.311 albertel 5106: if (&untie_domain_hash($hashref)) {
1.299 raeburn 5107: chop($qresult);
1.387 albertel 5108: &Reply($client, \$qresult, $userinput);
1.299 raeburn 5109: } else {
5110: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5111: "while attempting domrolesdump\n", $userinput);
5112: }
5113: } else {
5114: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5115: "while attempting domrolesdump\n", $userinput);
5116: }
5117: return 1;
5118: }
5119:
5120: ®ister_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
5121:
5122:
1.238 foxr 5123: # Process the tmpput command I'm not sure what this does.. Seems to
5124: # create a file in the lonDaemons/tmp directory of the form $id.tmp
5125: # where Id is the client's ip concatenated with a sequence number.
5126: # The file will contain some value that is passed in. Is this e.g.
5127: # a login token?
5128: #
5129: # Parameters:
5130: # $cmd - The command that got us dispatched.
5131: # $tail - The remainder of the request following $cmd:
5132: # In this case this will be the contents of the file.
5133: # $client - Socket connected to the client.
5134: # Returns:
5135: # 1 indicating processing can continue.
5136: # Side effects:
5137: # A file is created in the local filesystem.
5138: # A reply is sent to the client.
5139: sub tmp_put_handler {
5140: my ($cmd, $what, $client) = @_;
5141:
5142: my $userinput = "$cmd:$what"; # Reconstruct for logging.
5143:
1.347 raeburn 5144: my ($record,$context) = split(/:/,$what);
5145: if ($context ne '') {
5146: chomp($context);
5147: $context = &unescape($context);
5148: }
5149: my ($id,$store);
1.238 foxr 5150: $tmpsnum++;
1.489.2.42 raeburn 5151: my $numtries = 0;
5152: my $execdir=$perlvar{'lonDaemons'};
5153: if (($context eq 'resetpw') || ($context eq 'createaccount') ||
5154: ($context eq 'sso') || ($context eq 'link') || ($context eq 'retry')) {
5155: $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
5156: while ((-e "$execdir/tmp/$id.tmp") && ($numtries <10)) {
5157: undef($id);
5158: $id = &md5_hex(&md5_hex(time.{}.rand().$$.$tmpsnum));
5159: $numtries ++;
5160: }
1.347 raeburn 5161: } else {
5162: $id = $$.'_'.$clientip.'_'.$tmpsnum;
5163: }
1.238 foxr 5164: $id=~s/\W/\_/g;
1.347 raeburn 5165: $record=~s/\n//g;
1.489.2.42 raeburn 5166: if (($id ne '') &&
5167: ($store=IO::File->new(">$execdir/tmp/$id.tmp"))) {
1.347 raeburn 5168: print $store $record;
1.238 foxr 5169: close $store;
1.387 albertel 5170: &Reply($client, \$id, $userinput);
1.238 foxr 5171: } else {
5172: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
5173: "while attempting tmpput\n", $userinput);
5174: }
5175: return 1;
5176:
5177: }
5178: ®ister_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263 albertel 5179:
1.238 foxr 5180: # Processes the tmpget command. This command returns the contents
5181: # of a temporary resource file(?) created via tmpput.
5182: #
5183: # Paramters:
5184: # $cmd - Command that got us dispatched.
5185: # $id - Tail of the command, contain the id of the resource
5186: # we want to fetch.
5187: # $client - socket open on the client.
5188: # Return:
5189: # 1 - Inidcating processing can continue.
5190: # Side effects:
5191: # A reply is sent to the client.
5192: #
5193: sub tmp_get_handler {
5194: my ($cmd, $id, $client) = @_;
5195:
5196: my $userinput = "$cmd:$id";
5197:
5198:
5199: $id=~s/\W/\_/g;
5200: my $store;
5201: my $execdir=$perlvar{'lonDaemons'};
5202: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
5203: my $reply=<$store>;
1.387 albertel 5204: &Reply( $client, \$reply, $userinput);
1.238 foxr 5205: close $store;
5206: } else {
5207: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
5208: "while attempting tmpget\n", $userinput);
5209: }
5210:
5211: return 1;
5212: }
5213: ®ister_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263 albertel 5214:
1.238 foxr 5215: #
5216: # Process the tmpdel command. This command deletes a temp resource
5217: # created by the tmpput command.
5218: #
5219: # Parameters:
5220: # $cmd - Command that got us here.
5221: # $id - Id of the temporary resource created.
5222: # $client - socket open on the client process.
5223: #
5224: # Returns:
5225: # 1 - Indicating processing should continue.
5226: # Side Effects:
5227: # A file is deleted
5228: # A reply is sent to the client.
5229: sub tmp_del_handler {
5230: my ($cmd, $id, $client) = @_;
5231:
5232: my $userinput= "$cmd:$id";
5233:
5234: chomp($id);
5235: $id=~s/\W/\_/g;
5236: my $execdir=$perlvar{'lonDaemons'};
5237: if (unlink("$execdir/tmp/$id.tmp")) {
5238: &Reply($client, "ok\n", $userinput);
5239: } else {
5240: &Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
5241: "while attempting tmpdel\n", $userinput);
5242: }
5243:
5244: return 1;
5245:
5246: }
5247: ®ister_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263 albertel 5248:
1.238 foxr 5249: #
1.489.2.39 raeburn 5250: # Process the updatebalcookie command. This command updates a
5251: # cookie in the lonBalancedir directory on a load balancer node.
5252: #
5253: # Parameters:
5254: # $cmd - Command that got us here.
5255: # $tail - Tail of the request (escaped cookie: escaped current entry)
5256: #
5257: # $client - socket open on the client process.
5258: #
5259: # Returns:
5260: # 1 - Indicating processing should continue.
5261: # Side Effects:
5262: # A cookie file is updated from the lonBalancedir directory
5263: # A reply is sent to the client.
5264: #
5265: sub update_balcookie_handler {
5266: my ($cmd, $tail, $client) = @_;
5267:
5268: my $userinput= "$cmd:$tail";
5269: chomp($tail);
5270: my ($cookie,$lastentry) = map { &unescape($_) } (split(/:/,$tail));
5271:
5272: my $updatedone;
5273: if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
5274: my $execdir=$perlvar{'lonBalanceDir'};
5275: if (-e "$execdir/$cookie.id") {
5276: my $doupdate;
5277: if (open(my $fh,'<',"$execdir/$cookie.id")) {
5278: while (my $line = <$fh>) {
5279: chomp($line);
5280: if ($line eq $lastentry) {
5281: $doupdate = 1;
5282: last;
5283: }
5284: }
5285: close($fh);
5286: }
5287: if ($doupdate) {
5288: if (open(my $fh,'>',"$execdir/$cookie.id")) {
5289: print $fh $clientname;
5290: close($fh);
5291: $updatedone = 1;
5292: }
5293: }
5294: }
5295: }
5296: if ($updatedone) {
5297: &Reply($client, "ok\n", $userinput);
5298: } else {
5299: &Failure( $client, "error: ".($!+0)."file update failed ".
5300: "while attempting updatebalcookie\n", $userinput);
5301: }
5302: return 1;
5303: }
5304: ®ister_handler("updatebalcookie", \&update_balcookie_handler, 0, 1, 0);
5305:
5306: #
1.489.2.32 raeburn 5307: # Process the delbalcookie command. This command deletes a balancer
1.489.2.39 raeburn 5308: # cookie in the lonBalancedir directory on a load balancer node.
1.489.2.32 raeburn 5309: #
5310: # Parameters:
5311: # $cmd - Command that got us here.
5312: # $cookie - Cookie to be deleted.
5313: # $client - socket open on the client process.
5314: #
5315: # Returns:
5316: # 1 - Indicating processing should continue.
5317: # Side Effects:
5318: # A cookie file is deleted from the lonBalancedir directory
5319: # A reply is sent to the client.
5320: sub del_balcookie_handler {
5321: my ($cmd, $cookie, $client) = @_;
5322:
5323: my $userinput= "$cmd:$cookie";
5324:
5325: chomp($cookie);
1.489.2.39 raeburn 5326: $cookie = &unescape($cookie);
1.489.2.32 raeburn 5327: my $deleted = '';
5328: if ($cookie =~ /^$LONCAPA::match_domain\_$LONCAPA::match_username\_[a-f0-9]{32}$/) {
5329: my $execdir=$perlvar{'lonBalanceDir'};
5330: if (-e "$execdir/$cookie.id") {
5331: if (open(my $fh,'<',"$execdir/$cookie.id")) {
5332: my $dodelete;
5333: while (my $line = <$fh>) {
5334: chomp($line);
5335: if ($line eq $clientname) {
5336: $dodelete = 1;
5337: last;
5338: }
5339: }
5340: close($fh);
5341: if ($dodelete) {
5342: if (unlink("$execdir/$cookie.id")) {
5343: $deleted = 1;
5344: }
5345: }
5346: }
5347: }
5348: }
5349: if ($deleted) {
5350: &Reply($client, "ok\n", $userinput);
5351: } else {
5352: &Failure( $client, "error: ".($!+0)."Unlinking cookie file Failed ".
5353: "while attempting delbalcookie\n", $userinput);
5354: }
5355: return 1;
5356: }
5357: ®ister_handler("delbalcookie", \&del_balcookie_handler, 0, 1, 0);
5358:
5359: #
1.246 foxr 5360: # Processes the setannounce command. This command
5361: # creates a file named announce.txt in the top directory of
5362: # the documentn root and sets its contents. The announce.txt file is
5363: # printed in its entirety at the LonCAPA login page. Note:
5364: # once the announcement.txt fileis created it cannot be deleted.
5365: # However, setting the contents of the file to empty removes the
5366: # announcement from the login page of loncapa so who cares.
5367: #
5368: # Parameters:
5369: # $cmd - The command that got us dispatched.
5370: # $announcement - The text of the announcement.
5371: # $client - Socket open on the client process.
5372: # Retunrns:
5373: # 1 - Indicating request processing should continue
5374: # Side Effects:
5375: # The file {DocRoot}/announcement.txt is created.
5376: # A reply is sent to $client.
5377: #
5378: sub set_announce_handler {
5379: my ($cmd, $announcement, $client) = @_;
5380:
5381: my $userinput = "$cmd:$announcement";
5382:
5383: chomp($announcement);
5384: $announcement=&unescape($announcement);
5385: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
5386: '/announcement.txt')) {
5387: print $store $announcement;
5388: close $store;
5389: &Reply($client, "ok\n", $userinput);
5390: } else {
5391: &Failure($client, "error: ".($!+0)."\n", $userinput);
5392: }
5393:
5394: return 1;
5395: }
5396: ®ister_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263 albertel 5397:
1.246 foxr 5398: #
5399: # Return the version of the daemon. This can be used to determine
5400: # the compatibility of cross version installations or, alternatively to
5401: # simply know who's out of date and who isn't. Note that the version
5402: # is returned concatenated with the tail.
5403: # Parameters:
5404: # $cmd - the request that dispatched to us.
5405: # $tail - Tail of the request (client's version?).
5406: # $client - Socket open on the client.
5407: #Returns:
5408: # 1 - continue processing requests.
5409: # Side Effects:
5410: # Replies with version to $client.
5411: sub get_version_handler {
5412: my ($cmd, $tail, $client) = @_;
5413:
5414: my $userinput = $cmd.$tail;
5415:
5416: &Reply($client, &version($userinput)."\n", $userinput);
5417:
5418:
5419: return 1;
5420: }
5421: ®ister_handler("version", \&get_version_handler, 0, 1, 0);
1.263 albertel 5422:
1.246 foxr 5423: # Set the current host and domain. This is used to support
5424: # multihomed systems. Each IP of the system, or even separate daemons
5425: # on the same IP can be treated as handling a separate lonCAPA virtual
5426: # machine. This command selects the virtual lonCAPA. The client always
5427: # knows the right one since it is lonc and it is selecting the domain/system
5428: # from the hosts.tab file.
5429: # Parameters:
5430: # $cmd - Command that dispatched us.
5431: # $tail - Tail of the command (domain/host requested).
5432: # $socket - Socket open on the client.
5433: #
5434: # Returns:
5435: # 1 - Indicates the program should continue to process requests.
5436: # Side-effects:
5437: # The default domain/system context is modified for this daemon.
5438: # a reply is sent to the client.
5439: #
5440: sub set_virtual_host_handler {
5441: my ($cmd, $tail, $socket) = @_;
5442:
5443: my $userinput ="$cmd:$tail";
5444:
5445: &Reply($client, &sethost($userinput)."\n", $userinput);
5446:
5447:
5448: return 1;
5449: }
1.247 albertel 5450: ®ister_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246 foxr 5451:
5452: # Process a request to exit:
5453: # - "bye" is sent to the client.
5454: # - The client socket is shutdown and closed.
5455: # - We indicate to the caller that we should exit.
5456: # Formal Parameters:
5457: # $cmd - The command that got us here.
5458: # $tail - Tail of the command (empty).
5459: # $client - Socket open on the tail.
5460: # Returns:
5461: # 0 - Indicating the program should exit!!
5462: #
5463: sub exit_handler {
5464: my ($cmd, $tail, $client) = @_;
5465:
5466: my $userinput = "$cmd:$tail";
5467:
5468: &logthis("Client $clientip ($clientname) hanging up: $userinput");
5469: &Reply($client, "bye\n", $userinput);
5470: $client->shutdown(2); # shutdown the socket forcibly.
5471: $client->close();
5472:
5473: return 0;
5474: }
1.248 foxr 5475: ®ister_handler("exit", \&exit_handler, 0,1,1);
5476: ®ister_handler("init", \&exit_handler, 0,1,1);
5477: ®ister_handler("quit", \&exit_handler, 0,1,1);
5478:
5479: # Determine if auto-enrollment is enabled.
5480: # Note that the original had what I believe to be a defect.
5481: # The original returned 0 if the requestor was not a registerd client.
5482: # It should return "refused".
5483: # Formal Parameters:
5484: # $cmd - The command that invoked us.
5485: # $tail - The tail of the command (Extra command parameters.
5486: # $client - The socket open on the client that issued the request.
5487: # Returns:
5488: # 1 - Indicating processing should continue.
5489: #
5490: sub enrollment_enabled_handler {
5491: my ($cmd, $tail, $client) = @_;
5492: my $userinput = $cmd.":".$tail; # For logging purposes.
5493:
5494:
1.337 albertel 5495: my ($cdom) = split(/:/, $tail, 2); # Domain we're asking about.
5496:
1.248 foxr 5497: my $outcome = &localenroll::run($cdom);
1.387 albertel 5498: &Reply($client, \$outcome, $userinput);
1.248 foxr 5499:
5500: return 1;
5501: }
5502: ®ister_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
5503:
1.417 raeburn 5504: #
1.423 raeburn 5505: # Validate an institutional code used for a LON-CAPA course.
1.417 raeburn 5506: #
5507: # Formal Parameters:
5508: # $cmd - The command request that got us dispatched.
5509: # $tail - The tail of the command. In this case,
5510: # this is a colon separated set of words that will be split
5511: # into:
1.424 raeburn 5512: # $dom - The domain for which the check of
5513: # institutional course code will occur.
5514: #
5515: # $instcode - The institutional code for the course
5516: # being requested, or validated for rights
5517: # to request.
5518: #
5519: # $owner - The course requestor (who will be the
5520: # course owner, in the form username:domain
5521: #
1.417 raeburn 5522: # $client - Socket open on the client.
5523: # Returns:
5524: # 1 - Indicating processing should continue.
5525: #
5526: sub validate_instcode_handler {
5527: my ($cmd, $tail, $client) = @_;
5528: my $userinput = "$cmd:$tail";
1.423 raeburn 5529: my ($dom,$instcode,$owner) = split(/:/, $tail);
1.422 raeburn 5530: $instcode = &unescape($instcode);
5531: $owner = &unescape($owner);
1.489.2.3 raeburn 5532: my ($outcome,$description,$credits) =
1.426 raeburn 5533: &localenroll::validate_instcode($dom,$instcode,$owner);
1.489.2.3 raeburn 5534: my $result = &escape($outcome).'&'.&escape($description).'&'.
5535: &escape($credits);
1.426 raeburn 5536: &Reply($client, \$result, $userinput);
1.417 raeburn 5537:
5538: return 1;
5539: }
5540: ®ister_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
5541:
1.489.2.41 raeburn 5542: #
5543: # Validate co-owner for cross-listed institutional code and
5544: # institutional course code itself used for a LON-CAPA course.
5545: #
5546: # Formal Parameters:
5547: # $cmd - The command request that got us dispatched.
5548: # $tail - The tail of the command. In this case,
5549: # this is a colon separated string containing:
5550: # $dom - Course's LON-CAPA domain
5551: # $instcode - Institutional course code for the course
5552: # $inst_xlist - Institutional course Id for the crosslisting
5553: # $coowner - Username of co-owner
5554: # (values for all but $dom have been escaped).
5555: #
5556: # $client - Socket open on the client.
5557: # Returns:
5558: # 1 - Indicating processing should continue.
5559: #
5560: sub validate_instcrosslist_handler {
5561: my ($cmd, $tail, $client) = @_;
5562: my $userinput = "$cmd:$tail";
5563: my ($dom,$instcode,$inst_xlist,$coowner) = split(/:/,$tail);
5564: $instcode = &unescape($instcode);
5565: $inst_xlist = &unescape($inst_xlist);
5566: $coowner = &unescape($coowner);
5567: my $outcome = &localenroll::validate_crosslist_access($dom,$instcode,
5568: $inst_xlist,$coowner);
5569: &Reply($client, \$outcome, $userinput);
5570:
5571: return 1;
5572: }
5573: ®ister_handler("autovalidateinstcrosslist", \&validate_instcrosslist_handler, 0, 1, 0);
5574:
1.248 foxr 5575: # Get the official sections for which auto-enrollment is possible.
5576: # Since the admin people won't know about 'unofficial sections'
5577: # we cannot auto-enroll on them.
5578: # Formal Parameters:
5579: # $cmd - The command request that got us dispatched here.
5580: # $tail - The remainder of the request. In our case this
5581: # will be split into:
5582: # $coursecode - The course name from the admin point of view.
5583: # $cdom - The course's domain(?).
5584: # $client - Socket open on the client.
5585: # Returns:
5586: # 1 - Indiciting processing should continue.
5587: #
5588: sub get_sections_handler {
5589: my ($cmd, $tail, $client) = @_;
5590: my $userinput = "$cmd:$tail";
5591:
5592: my ($coursecode, $cdom) = split(/:/, $tail);
5593: my @secs = &localenroll::get_sections($coursecode,$cdom);
5594: my $seclist = &escape(join(':',@secs));
5595:
1.387 albertel 5596: &Reply($client, \$seclist, $userinput);
1.248 foxr 5597:
5598:
5599: return 1;
5600: }
5601: ®ister_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
5602:
5603: # Validate the owner of a new course section.
5604: #
5605: # Formal Parameters:
5606: # $cmd - Command that got us dispatched.
5607: # $tail - the remainder of the command. For us this consists of a
5608: # colon separated string containing:
5609: # $inst - Course Id from the institutions point of view.
5610: # $owner - Proposed owner of the course.
5611: # $cdom - Domain of the course (from the institutions
5612: # point of view?)..
5613: # $client - Socket open on the client.
5614: #
5615: # Returns:
5616: # 1 - Processing should continue.
5617: #
5618: sub validate_course_owner_handler {
5619: my ($cmd, $tail, $client) = @_;
5620: my $userinput = "$cmd:$tail";
1.470 raeburn 5621: my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
5622:
1.336 raeburn 5623: $owner = &unescape($owner);
1.470 raeburn 5624: $coowners = &unescape($coowners);
5625: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
1.387 albertel 5626: &Reply($client, \$outcome, $userinput);
1.248 foxr 5627:
5628:
5629:
5630: return 1;
5631: }
5632: ®ister_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263 albertel 5633:
1.248 foxr 5634: #
5635: # Validate a course section in the official schedule of classes
5636: # from the institutions point of view (part of autoenrollment).
5637: #
5638: # Formal Parameters:
5639: # $cmd - The command request that got us dispatched.
5640: # $tail - The tail of the command. In this case,
5641: # this is a colon separated set of words that will be split
5642: # into:
5643: # $inst_course_id - The course/section id from the
5644: # institutions point of view.
5645: # $cdom - The domain from the institutions
5646: # point of view.
5647: # $client - Socket open on the client.
5648: # Returns:
5649: # 1 - Indicating processing should continue.
5650: #
5651: sub validate_course_section_handler {
5652: my ($cmd, $tail, $client) = @_;
5653: my $userinput = "$cmd:$tail";
5654: my ($inst_course_id, $cdom) = split(/:/, $tail);
5655:
5656: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
1.387 albertel 5657: &Reply($client, \$outcome, $userinput);
1.248 foxr 5658:
5659:
5660: return 1;
5661: }
5662: ®ister_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
5663:
5664: #
1.340 raeburn 5665: # Validate course owner's access to enrollment data for specific class section.
5666: #
5667: #
5668: # Formal Parameters:
5669: # $cmd - The command request that got us dispatched.
5670: # $tail - The tail of the command. In this case this is a colon separated
1.489.2.29 raeburn 5671: # set of values that will be split into:
1.340 raeburn 5672: # $inst_class - Institutional code for the specific class section
1.489.2.29 raeburn 5673: # $ownerlist - An escaped comma-separated list of username:domain
5674: # of the course owner, and co-owner(s).
1.340 raeburn 5675: # $cdom - The domain of the course from the institution's
5676: # point of view.
5677: # $client - The socket open on the client.
5678: # Returns:
5679: # 1 - continue processing.
5680: #
5681:
5682: sub validate_class_access_handler {
5683: my ($cmd, $tail, $client) = @_;
5684: my $userinput = "$cmd:$tail";
1.383 raeburn 5685: my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
1.392 raeburn 5686: my $owners = &unescape($ownerlist);
1.341 albertel 5687: my $outcome;
5688: eval {
5689: local($SIG{__DIE__})='DEFAULT';
1.392 raeburn 5690: $outcome=&localenroll::check_section($inst_class,$owners,$cdom);
1.341 albertel 5691: };
1.387 albertel 5692: &Reply($client,\$outcome, $userinput);
1.340 raeburn 5693:
5694: return 1;
5695: }
5696: ®ister_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
5697:
5698: #
1.489.2.41 raeburn 5699: # Modify institutional sections (using customized &instsec_reformat()
5700: # routine in localenroll.pm), to either clutter or declutter, for
5701: # purposes of ensuring an institutional course section (string) can
5702: # be unambiguously separated into institutional course and section.
5703: #
5704: # Formal Parameters:
5705: # $cmd - The command request that got us dispatched.
5706: # $tail - The tail of the command. In this case this is a colon separated
5707: # set of values that will be split into:
5708: # $cdom - The LON-CAPA domain of the course.
5709: # $action - Either: clutter or declutter
5710: # clutter adds character(s) to eliminate ambiguity
5711: # declutter removes the added characters (e.g., for
5712: # display of the institutional course section string.
5713: # $info - A frozen hash in which keys are:
5714: # LON-CAPA course number:Institutional course code
5715: # and values are a reference to an array of the
5716: # items to modify -- either institutional sections,
5717: # or institutional course sections (for crosslistings).
5718: # $client - The socket open on the client.
5719: # Returns:
5720: # 1 - continue processing.
5721: #
5722:
5723: sub instsec_reformat_handler {
5724: my ($cmd, $tail, $client) = @_;
5725: my $userinput = "$cmd:$tail";
5726: my ($cdom,$action,$info) = split(/:/,$tail);
5727: my $instsecref = &Apache::lonnet::thaw_unescape($info);
5728: my ($outcome,$result);
5729: eval {
5730: local($SIG{__DIE__})='DEFAULT';
5731: $outcome=&localenroll::instsec_reformat($cdom,$action,$instsecref);
5732: if ($outcome eq 'ok') {
5733: if (ref($instsecref) eq 'HASH') {
5734: foreach my $key (keys(%{$instsecref})) {
5735: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($instsecref->{$key}).'&';
5736: }
5737: $result =~ s/\&$//;
5738: }
5739: }
5740: };
5741: if (!$@) {
5742: if ($outcome eq 'ok') {
5743: &Reply( $client, \$result, $userinput);
5744: } else {
5745: &Reply($client,\$outcome, $userinput);
5746: }
5747: } else {
5748: &Failure($client,"unknown_cmd\n",$userinput);
5749: }
5750: return 1;
5751: }
5752: ®ister_handler("autoinstsecreformat",\&instsec_reformat_handler, 0, 1, 0);
5753:
5754: #
1.489.2.29 raeburn 5755: # Validate course owner or co-owners(s) access to enrollment data for all sections
5756: # and crosslistings for a particular course.
5757: #
5758: #
5759: # Formal Parameters:
5760: # $cmd - The command request that got us dispatched.
5761: # $tail - The tail of the command. In this case this is a colon separated
5762: # set of values that will be split into:
5763: # $ownerlist - An escaped comma-separated list of username:domain
5764: # of the course owner, and co-owner(s).
5765: # $cdom - The domain of the course from the institution's
5766: # point of view.
5767: # $classes - Frozen hash of institutional course sections and
5768: # crosslistings.
5769: # $client - The socket open on the client.
5770: # Returns:
5771: # 1 - continue processing.
5772: #
5773:
5774: sub validate_classes_handler {
5775: my ($cmd, $tail, $client) = @_;
5776: my $userinput = "$cmd:$tail";
5777: my ($ownerlist,$cdom,$classes) = split(/:/, $tail);
5778: my $classesref = &Apache::lonnet::thaw_unescape($classes);
5779: my $owners = &unescape($ownerlist);
5780: my $result;
5781: eval {
5782: local($SIG{__DIE__})='DEFAULT';
5783: my %validations;
5784: my $response = &localenroll::check_instclasses($owners,$cdom,$classesref,
5785: \%validations);
5786: if ($response eq 'ok') {
5787: foreach my $key (keys(%validations)) {
5788: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
5789: }
5790: $result =~ s/\&$//;
5791: } else {
5792: $result = 'error';
5793: }
5794: };
5795: if (!$@) {
5796: &Reply($client, \$result, $userinput);
5797: } else {
5798: &Failure($client,"unknown_cmd\n",$userinput);
5799: }
5800: return 1;
5801: }
5802: ®ister_handler("autovalidateinstclasses", \&validate_classes_handler, 0, 1, 0);
5803:
5804: #
1.340 raeburn 5805: # Create a password for a new LON-CAPA user added by auto-enrollment.
5806: # Only used for case where authentication method for new user is localauth
1.248 foxr 5807: #
5808: # Formal Parameters:
5809: # $cmd - The command request that got us dispatched.
5810: # $tail - The tail of the command. In this case this is a colon separated
5811: # set of words that will be split into:
1.340 raeburn 5812: # $authparam - An authentication parameter (localauth parameter).
1.248 foxr 5813: # $cdom - The domain of the course from the institution's
5814: # point of view.
5815: # $client - The socket open on the client.
5816: # Returns:
5817: # 1 - continue processing.
5818: #
5819: sub create_auto_enroll_password_handler {
5820: my ($cmd, $tail, $client) = @_;
5821: my $userinput = "$cmd:$tail";
5822:
5823: my ($authparam, $cdom) = split(/:/, $userinput);
5824:
5825: my ($create_passwd,$authchk);
5826: ($authparam,
5827: $create_passwd,
5828: $authchk) = &localenroll::create_password($authparam,$cdom);
5829:
5830: &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
5831: $userinput);
5832:
5833:
5834: return 1;
5835: }
5836: ®ister_handler("autocreatepassword", \&create_auto_enroll_password_handler,
5837: 0, 1, 0);
5838:
1.489.2.22 raeburn 5839: sub auto_export_grades_handler {
5840: my ($cmd, $tail, $client) = @_;
5841: my $userinput = "$cmd:$tail";
5842: my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
5843: my $inforef = &Apache::lonnet::thaw_unescape($info);
5844: my $dataref = &Apache::lonnet::thaw_unescape($data);
5845: my ($outcome,$result);;
5846: eval {
5847: local($SIG{__DIE__})='DEFAULT';
5848: my %rtnhash;
5849: $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
5850: if ($outcome eq 'ok') {
5851: foreach my $key (keys(%rtnhash)) {
5852: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
5853: }
5854: $result =~ s/\&$//;
5855: }
5856: };
5857: if (!$@) {
5858: if ($outcome eq 'ok') {
5859: if ($cipher) {
5860: my $cmdlength=length($result);
5861: $result.=" ";
5862: my $encresult='';
5863: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
5864: $encresult.= unpack("H16",
5865: $cipher->encrypt(substr($result,
5866: $encidx,
5867: 8)));
5868: }
5869: &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
5870: } else {
5871: &Failure( $client, "error:no_key\n", $userinput);
5872: }
5873: } else {
5874: &Reply($client, "$outcome\n", $userinput);
5875: }
5876: } else {
5877: &Failure($client,"export_error\n",$userinput);
5878: }
5879: return 1;
5880: }
5881: ®ister_handler("autoexportgrades", \&auto_export_grades_handler,
1.489.2.35 raeburn 5882: 1, 1, 0);
1.489.2.22 raeburn 5883:
5884:
1.248 foxr 5885: # Retrieve and remove temporary files created by/during autoenrollment.
5886: #
5887: # Formal Parameters:
5888: # $cmd - The command that got us dispatched.
5889: # $tail - The tail of the command. In our case this is a colon
5890: # separated list that will be split into:
1.489.2.24 raeburn 5891: # $filename - The name of the file to retrieve.
1.248 foxr 5892: # The filename is given as a path relative to
5893: # the LonCAPA temp file directory.
5894: # $client - Socket open on the client.
5895: #
5896: # Returns:
5897: # 1 - Continue processing.
5898: sub retrieve_auto_file_handler {
5899: my ($cmd, $tail, $client) = @_;
5900: my $userinput = "cmd:$tail";
5901:
5902: my ($filename) = split(/:/, $tail);
5903:
5904: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
1.489.2.20 raeburn 5905: if ($filename =~m{/\.\./}) {
5906: &Failure($client, "refused\n", $userinput);
1.489.2.24 raeburn 5907: } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
5908: &Failure($client, "refused\n", $userinput);
1.489.2.20 raeburn 5909: } elsif ( (-e $source) && ($filename ne '') ) {
1.248 foxr 5910: my $reply = '';
5911: if (open(my $fh,$source)) {
5912: while (<$fh>) {
5913: chomp($_);
5914: $_ =~ s/^\s+//g;
5915: $_ =~ s/\s+$//g;
5916: $reply .= $_;
5917: }
5918: close($fh);
5919: &Reply($client, &escape($reply)."\n", $userinput);
5920:
5921: # Does this have to be uncommented??!? (RF).
5922: #
5923: # unlink($source);
5924: } else {
5925: &Failure($client, "error\n", $userinput);
5926: }
5927: } else {
5928: &Failure($client, "error\n", $userinput);
5929: }
5930:
5931:
5932: return 1;
5933: }
5934: ®ister_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
5935:
1.423 raeburn 5936: sub crsreq_checks_handler {
5937: my ($cmd, $tail, $client) = @_;
5938: my $userinput = "$cmd:$tail";
5939: my $dom = $tail;
5940: my $result;
1.489.2.12 raeburn 5941: my @reqtypes = ('official','unofficial','community','textbook');
1.423 raeburn 5942: eval {
5943: local($SIG{__DIE__})='DEFAULT';
5944: my %validations;
1.424 raeburn 5945: my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
5946: \%validations);
1.423 raeburn 5947: if ($response eq 'ok') {
5948: foreach my $key (keys(%validations)) {
5949: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
5950: }
5951: $result =~ s/\&$//;
5952: } else {
5953: $result = 'error';
5954: }
5955: };
5956: if (!$@) {
5957: &Reply($client, \$result, $userinput);
5958: } else {
5959: &Failure($client,"unknown_cmd\n",$userinput);
5960: }
5961: return 1;
5962: }
5963: ®ister_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
5964:
5965: sub validate_crsreq_handler {
5966: my ($cmd, $tail, $client) = @_;
5967: my $userinput = "$cmd:$tail";
1.489.2.13 raeburn 5968: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
1.423 raeburn 5969: $instcode = &unescape($instcode);
5970: $owner = &unescape($owner);
5971: $crstype = &unescape($crstype);
5972: $inststatuslist = &unescape($inststatuslist);
5973: $instcode = &unescape($instcode);
5974: $instseclist = &unescape($instseclist);
1.489.2.13 raeburn 5975: my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
1.423 raeburn 5976: my $outcome;
5977: eval {
5978: local($SIG{__DIE__})='DEFAULT';
5979: $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
5980: $inststatuslist,$instcode,
1.489.2.13 raeburn 5981: $instseclist,$custominfo);
1.423 raeburn 5982: };
5983: if (!$@) {
5984: &Reply($client, \$outcome, $userinput);
5985: } else {
5986: &Failure($client,"unknown_cmd\n",$userinput);
5987: }
5988: return 1;
5989: }
5990: ®ister_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
5991:
1.489.2.11 raeburn 5992: sub crsreq_update_handler {
5993: my ($cmd, $tail, $client) = @_;
5994: my $userinput = "$cmd:$tail";
1.489.2.14 raeburn 5995: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
5996: $accessstart,$accessend,$infohashref) =
1.489.2.11 raeburn 5997: split(/:/, $tail);
5998: $crstype = &unescape($crstype);
5999: $action = &unescape($action);
6000: $ownername = &unescape($ownername);
6001: $ownerdomain = &unescape($ownerdomain);
6002: $fullname = &unescape($fullname);
6003: $title = &unescape($title);
6004: $code = &unescape($code);
1.489.2.14 raeburn 6005: $accessstart = &unescape($accessstart);
6006: $accessend = &unescape($accessend);
1.489.2.11 raeburn 6007: my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
6008: my ($result,$outcome);
6009: eval {
6010: local($SIG{__DIE__})='DEFAULT';
6011: my %rtnhash;
6012: $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
6013: $ownername,$ownerdomain,$fullname,
1.489.2.14 raeburn 6014: $title,$code,$accessstart,$accessend,
6015: $incoming,\%rtnhash);
1.489.2.11 raeburn 6016: if ($outcome eq 'ok') {
1.489.2.18 raeburn 6017: my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
1.489.2.11 raeburn 6018: foreach my $key (keys(%rtnhash)) {
6019: if (grep(/^\Q$key\E/,@posskeys)) {
6020: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
6021: }
6022: }
6023: $result =~ s/\&$//;
6024: }
6025: };
6026: if (!$@) {
6027: if ($outcome eq 'ok') {
6028: &Reply($client, \$result, $userinput);
6029: } else {
6030: &Reply($client, "format_error\n", $userinput);
6031: }
6032: } else {
6033: &Failure($client,"unknown_cmd\n",$userinput);
6034: }
6035: return 1;
6036: }
6037: ®ister_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
6038:
1.248 foxr 6039: #
6040: # Read and retrieve institutional code format (for support form).
6041: # Formal Parameters:
6042: # $cmd - Command that dispatched us.
6043: # $tail - Tail of the command. In this case it conatins
6044: # the course domain and the coursename.
6045: # $client - Socket open on the client.
6046: # Returns:
6047: # 1 - Continue processing.
6048: #
6049: sub get_institutional_code_format_handler {
6050: my ($cmd, $tail, $client) = @_;
6051: my $userinput = "$cmd:$tail";
6052:
6053: my $reply;
6054: my($cdom,$course) = split(/:/,$tail);
6055: my @pairs = split/\&/,$course;
6056: my %instcodes = ();
6057: my %codes = ();
6058: my @codetitles = ();
6059: my %cat_titles = ();
6060: my %cat_order = ();
6061: foreach (@pairs) {
6062: my ($key,$value) = split/=/,$_;
6063: $instcodes{&unescape($key)} = &unescape($value);
6064: }
6065: my $formatreply = &localenroll::instcode_format($cdom,
6066: \%instcodes,
6067: \%codes,
6068: \@codetitles,
6069: \%cat_titles,
6070: \%cat_order);
6071: if ($formatreply eq 'ok') {
1.365 albertel 6072: my $codes_str = &Apache::lonnet::hash2str(%codes);
6073: my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
6074: my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
6075: my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
1.248 foxr 6076: &Reply($client,
6077: $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
6078: .$cat_order_str."\n",
6079: $userinput);
6080: } else {
6081: # this else branch added by RF since if not ok, lonc will
6082: # hang waiting on reply until timeout.
6083: #
6084: &Reply($client, "format_error\n", $userinput);
6085: }
6086:
6087: return 1;
6088: }
1.265 albertel 6089: ®ister_handler("autoinstcodeformat",
6090: \&get_institutional_code_format_handler,0,1,0);
1.246 foxr 6091:
1.345 raeburn 6092: sub get_institutional_defaults_handler {
6093: my ($cmd, $tail, $client) = @_;
6094: my $userinput = "$cmd:$tail";
6095:
6096: my $dom = $tail;
6097: my %defaults_hash;
6098: my @code_order;
6099: my $outcome;
6100: eval {
6101: local($SIG{__DIE__})='DEFAULT';
6102: $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
6103: \@code_order);
6104: };
6105: if (!$@) {
6106: if ($outcome eq 'ok') {
6107: my $result='';
6108: while (my ($key,$value) = each(%defaults_hash)) {
6109: $result.=&escape($key).'='.&escape($value).'&';
6110: }
6111: $result .= 'code_order='.&escape(join('&',@code_order));
1.387 albertel 6112: &Reply($client,\$result,$userinput);
1.345 raeburn 6113: } else {
6114: &Reply($client,"error\n", $userinput);
6115: }
6116: } else {
6117: &Failure($client,"unknown_cmd\n",$userinput);
6118: }
6119: }
6120: ®ister_handler("autoinstcodedefaults",
6121: \&get_institutional_defaults_handler,0,1,0);
6122:
1.416 raeburn 6123: sub get_possible_instcodes_handler {
6124: my ($cmd, $tail, $client) = @_;
6125: my $userinput = "$cmd:$tail";
6126:
6127: my $reply;
6128: my $cdom = $tail;
1.417 raeburn 6129: my (@codetitles,%cat_titles,%cat_order,@code_order);
1.416 raeburn 6130: my $formatreply = &localenroll::possible_instcodes($cdom,
6131: \@codetitles,
6132: \%cat_titles,
1.417 raeburn 6133: \%cat_order,
6134: \@code_order);
1.416 raeburn 6135: if ($formatreply eq 'ok') {
6136: my $result = join('&',map {&escape($_);} (@codetitles)).':';
1.417 raeburn 6137: $result .= join('&',map {&escape($_);} (@code_order)).':';
1.416 raeburn 6138: foreach my $key (keys(%cat_titles)) {
6139: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
6140: }
6141: $result =~ s/\&$//;
6142: $result .= ':';
6143: foreach my $key (keys(%cat_order)) {
6144: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
6145: }
6146: $result =~ s/\&$//;
6147: &Reply($client,\$result,$userinput);
6148: } else {
6149: &Reply($client, "format_error\n", $userinput);
6150: }
6151: return 1;
6152: }
6153: ®ister_handler("autopossibleinstcodes",
6154: \&get_possible_instcodes_handler,0,1,0);
6155:
1.381 raeburn 6156: sub get_institutional_user_rules {
6157: my ($cmd, $tail, $client) = @_;
6158: my $userinput = "$cmd:$tail";
6159: my $dom = &unescape($tail);
6160: my (%rules_hash,@rules_order);
6161: my $outcome;
6162: eval {
6163: local($SIG{__DIE__})='DEFAULT';
6164: $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
6165: };
6166: if (!$@) {
6167: if ($outcome eq 'ok') {
6168: my $result;
6169: foreach my $key (keys(%rules_hash)) {
6170: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6171: }
6172: $result =~ s/\&$//;
6173: $result .= ':';
6174: if (@rules_order > 0) {
6175: foreach my $item (@rules_order) {
6176: $result .= &escape($item).'&';
6177: }
6178: }
6179: $result =~ s/\&$//;
1.387 albertel 6180: &Reply($client,\$result,$userinput);
1.381 raeburn 6181: } else {
6182: &Reply($client,"error\n", $userinput);
6183: }
6184: } else {
6185: &Failure($client,"unknown_cmd\n",$userinput);
6186: }
6187: }
6188: ®ister_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
6189:
1.389 raeburn 6190: sub get_institutional_id_rules {
6191: my ($cmd, $tail, $client) = @_;
6192: my $userinput = "$cmd:$tail";
6193: my $dom = &unescape($tail);
6194: my (%rules_hash,@rules_order);
6195: my $outcome;
6196: eval {
6197: local($SIG{__DIE__})='DEFAULT';
6198: $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
6199: };
6200: if (!$@) {
6201: if ($outcome eq 'ok') {
6202: my $result;
6203: foreach my $key (keys(%rules_hash)) {
6204: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6205: }
6206: $result =~ s/\&$//;
6207: $result .= ':';
6208: if (@rules_order > 0) {
6209: foreach my $item (@rules_order) {
6210: $result .= &escape($item).'&';
6211: }
6212: }
6213: $result =~ s/\&$//;
6214: &Reply($client,\$result,$userinput);
6215: } else {
6216: &Reply($client,"error\n", $userinput);
6217: }
6218: } else {
6219: &Failure($client,"unknown_cmd\n",$userinput);
6220: }
6221: }
6222: ®ister_handler("instidrules",\&get_institutional_id_rules,0,1,0);
6223:
1.397 raeburn 6224: sub get_institutional_selfcreate_rules {
1.396 raeburn 6225: my ($cmd, $tail, $client) = @_;
6226: my $userinput = "$cmd:$tail";
6227: my $dom = &unescape($tail);
6228: my (%rules_hash,@rules_order);
6229: my $outcome;
6230: eval {
6231: local($SIG{__DIE__})='DEFAULT';
1.397 raeburn 6232: $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
1.396 raeburn 6233: };
6234: if (!$@) {
6235: if ($outcome eq 'ok') {
6236: my $result;
6237: foreach my $key (keys(%rules_hash)) {
6238: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6239: }
6240: $result =~ s/\&$//;
6241: $result .= ':';
6242: if (@rules_order > 0) {
6243: foreach my $item (@rules_order) {
6244: $result .= &escape($item).'&';
6245: }
6246: }
6247: $result =~ s/\&$//;
6248: &Reply($client,\$result,$userinput);
6249: } else {
6250: &Reply($client,"error\n", $userinput);
6251: }
6252: } else {
6253: &Failure($client,"unknown_cmd\n",$userinput);
6254: }
6255: }
1.397 raeburn 6256: ®ister_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
1.396 raeburn 6257:
1.489.2.45! raeburn 6258: sub get_unamemap_rules {
! 6259: my ($cmd, $tail, $client) = @_;
! 6260: my $userinput = "$cmd:$tail";
! 6261: my $dom = &unescape($tail);
! 6262: my (%rules_hash,@rules_order);
! 6263: my $outcome;
! 6264: eval {
! 6265: local($SIG{__DIE__})='DEFAULT';
! 6266: $outcome = &localenroll::unamemap_rules($dom,\%rules_hash,\@rules_order);
! 6267: };
! 6268: if (!$@) {
! 6269: if ($outcome eq 'ok') {
! 6270: my $result;
! 6271: foreach my $key (keys(%rules_hash)) {
! 6272: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
! 6273: }
! 6274: $result =~ s/\&$//;
! 6275: $result .= ':';
! 6276: if (@rules_order > 0) {
! 6277: foreach my $item (@rules_order) {
! 6278: $result .= &escape($item).'&';
! 6279: }
! 6280: }
! 6281: $result =~ s/\&$//;
! 6282: &Reply($client,\$result,$userinput);
! 6283: } else {
! 6284: &Reply($client,"error\n", $userinput);
! 6285: }
! 6286: } else {
! 6287: &Failure($client,"unknown_cmd\n",$userinput);
! 6288: }
! 6289: }
! 6290: ®ister_handler("unamemaprules",\&get_unamemap_rules,0,1,0);
1.381 raeburn 6291:
6292: sub institutional_username_check {
6293: my ($cmd, $tail, $client) = @_;
6294: my $userinput = "$cmd:$tail";
6295: my %rulecheck;
6296: my $outcome;
6297: my ($udom,$uname,@rules) = split(/:/,$tail);
6298: $udom = &unescape($udom);
6299: $uname = &unescape($uname);
6300: @rules = map {&unescape($_);} (@rules);
6301: eval {
6302: local($SIG{__DIE__})='DEFAULT';
6303: $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
6304: };
6305: if (!$@) {
6306: if ($outcome eq 'ok') {
6307: my $result='';
6308: foreach my $key (keys(%rulecheck)) {
6309: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
6310: }
1.387 albertel 6311: &Reply($client,\$result,$userinput);
1.381 raeburn 6312: } else {
6313: &Reply($client,"error\n", $userinput);
6314: }
6315: } else {
6316: &Failure($client,"unknown_cmd\n",$userinput);
6317: }
6318: }
6319: ®ister_handler("instrulecheck",\&institutional_username_check,0,1,0);
6320:
1.389 raeburn 6321: sub institutional_id_check {
6322: my ($cmd, $tail, $client) = @_;
6323: my $userinput = "$cmd:$tail";
6324: my %rulecheck;
6325: my $outcome;
6326: my ($udom,$id,@rules) = split(/:/,$tail);
6327: $udom = &unescape($udom);
6328: $id = &unescape($id);
6329: @rules = map {&unescape($_);} (@rules);
6330: eval {
6331: local($SIG{__DIE__})='DEFAULT';
6332: $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
6333: };
6334: if (!$@) {
6335: if ($outcome eq 'ok') {
6336: my $result='';
6337: foreach my $key (keys(%rulecheck)) {
6338: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
6339: }
6340: &Reply($client,\$result,$userinput);
6341: } else {
6342: &Reply($client,"error\n", $userinput);
6343: }
6344: } else {
6345: &Failure($client,"unknown_cmd\n",$userinput);
6346: }
6347: }
6348: ®ister_handler("instidrulecheck",\&institutional_id_check,0,1,0);
1.345 raeburn 6349:
1.397 raeburn 6350: sub institutional_selfcreate_check {
1.396 raeburn 6351: my ($cmd, $tail, $client) = @_;
6352: my $userinput = "$cmd:$tail";
6353: my %rulecheck;
6354: my $outcome;
6355: my ($udom,$email,@rules) = split(/:/,$tail);
6356: $udom = &unescape($udom);
6357: $email = &unescape($email);
6358: @rules = map {&unescape($_);} (@rules);
6359: eval {
6360: local($SIG{__DIE__})='DEFAULT';
1.397 raeburn 6361: $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
1.396 raeburn 6362: };
6363: if (!$@) {
6364: if ($outcome eq 'ok') {
6365: my $result='';
6366: foreach my $key (keys(%rulecheck)) {
6367: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
6368: }
6369: &Reply($client,\$result,$userinput);
6370: } else {
6371: &Reply($client,"error\n", $userinput);
6372: }
6373: } else {
6374: &Failure($client,"unknown_cmd\n",$userinput);
6375: }
6376: }
1.397 raeburn 6377: ®ister_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
1.396 raeburn 6378:
1.317 raeburn 6379: # Get domain specific conditions for import of student photographs to a course
6380: #
6381: # Retrieves information from photo_permission subroutine in localenroll.
6382: # Returns outcome (ok) if no processing errors, and whether course owner is
6383: # required to accept conditions of use (yes/no).
6384: #
6385: #
6386: sub photo_permission_handler {
6387: my ($cmd, $tail, $client) = @_;
6388: my $userinput = "$cmd:$tail";
6389: my $cdom = $tail;
6390: my ($perm_reqd,$conditions);
1.320 albertel 6391: my $outcome;
6392: eval {
6393: local($SIG{__DIE__})='DEFAULT';
6394: $outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
6395: \$conditions);
6396: };
6397: if (!$@) {
6398: &Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
6399: $userinput);
6400: } else {
6401: &Failure($client,"unknown_cmd\n",$userinput);
6402: }
6403: return 1;
1.317 raeburn 6404: }
6405: ®ister_handler("autophotopermission",\&photo_permission_handler,0,1,0);
6406:
6407: #
6408: # Checks if student photo is available for a user in the domain, in the user's
6409: # directory (in /userfiles/internal/studentphoto.jpg).
6410: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
6411: # the student's photo.
6412:
6413: sub photo_check_handler {
6414: my ($cmd, $tail, $client) = @_;
6415: my $userinput = "$cmd:$tail";
6416: my ($udom,$uname,$pid) = split(/:/,$tail);
6417: $udom = &unescape($udom);
6418: $uname = &unescape($uname);
6419: $pid = &unescape($pid);
6420: my $path=&propath($udom,$uname).'/userfiles/internal/';
6421: if (!-e $path) {
6422: &mkpath($path);
6423: }
6424: my $response;
6425: my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
6426: $result .= ':'.$response;
6427: &Reply($client, &escape($result)."\n",$userinput);
1.320 albertel 6428: return 1;
1.317 raeburn 6429: }
6430: ®ister_handler("autophotocheck",\&photo_check_handler,0,1,0);
6431:
6432: #
6433: # Retrieve information from localenroll about whether to provide a button
6434: # for users who have enbled import of student photos to initiate an
6435: # update of photo files for registered students. Also include
6436: # comment to display alongside button.
6437:
6438: sub photo_choice_handler {
6439: my ($cmd, $tail, $client) = @_;
6440: my $userinput = "$cmd:$tail";
6441: my $cdom = &unescape($tail);
1.320 albertel 6442: my ($update,$comment);
6443: eval {
6444: local($SIG{__DIE__})='DEFAULT';
6445: ($update,$comment) = &localenroll::manager_photo_update($cdom);
6446: };
6447: if (!$@) {
6448: &Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
6449: } else {
6450: &Failure($client,"unknown_cmd\n",$userinput);
6451: }
6452: return 1;
1.317 raeburn 6453: }
6454: ®ister_handler("autophotochoice",\&photo_choice_handler,0,1,0);
6455:
1.265 albertel 6456: #
6457: # Gets a student's photo to exist (in the correct image type) in the user's
6458: # directory.
6459: # Formal Parameters:
6460: # $cmd - The command request that got us dispatched.
6461: # $tail - A colon separated set of words that will be split into:
6462: # $domain - student's domain
6463: # $uname - student username
6464: # $type - image type desired
6465: # $client - The socket open on the client.
6466: # Returns:
6467: # 1 - continue processing.
1.317 raeburn 6468:
1.265 albertel 6469: sub student_photo_handler {
6470: my ($cmd, $tail, $client) = @_;
1.317 raeburn 6471: my ($domain,$uname,$ext,$type) = split(/:/, $tail);
1.265 albertel 6472:
1.317 raeburn 6473: my $path=&propath($domain,$uname). '/userfiles/internal/';
6474: my $filename = 'studentphoto.'.$ext;
6475: if ($type eq 'thumbnail') {
6476: $filename = 'studentphoto_tn.'.$ext;
6477: }
6478: if (-e $path.$filename) {
1.265 albertel 6479: &Reply($client,"ok\n","$cmd:$tail");
6480: return 1;
6481: }
6482: &mkpath($path);
1.317 raeburn 6483: my $file;
6484: if ($type eq 'thumbnail') {
1.320 albertel 6485: eval {
6486: local($SIG{__DIE__})='DEFAULT';
6487: $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
6488: };
1.317 raeburn 6489: } else {
6490: $file=&localstudentphoto::fetch($domain,$uname);
6491: }
1.265 albertel 6492: if (!$file) {
6493: &Failure($client,"unavailable\n","$cmd:$tail");
6494: return 1;
6495: }
1.317 raeburn 6496: if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
6497: if (-e $path.$filename) {
1.265 albertel 6498: &Reply($client,"ok\n","$cmd:$tail");
6499: return 1;
6500: }
6501: &Failure($client,"unable_to_convert\n","$cmd:$tail");
6502: return 1;
6503: }
6504: ®ister_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246 foxr 6505:
1.361 raeburn 6506: sub inst_usertypes_handler {
6507: my ($cmd, $domain, $client) = @_;
6508: my $res;
6509: my $userinput = $cmd.":".$domain; # For logging purposes.
1.370 albertel 6510: my (%typeshash,@order,$result);
6511: eval {
6512: local($SIG{__DIE__})='DEFAULT';
6513: $result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
6514: };
6515: if ($result eq 'ok') {
1.361 raeburn 6516: if (keys(%typeshash) > 0) {
6517: foreach my $key (keys(%typeshash)) {
6518: $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
6519: }
6520: }
6521: $res=~s/\&$//;
6522: $res .= ':';
6523: if (@order > 0) {
6524: foreach my $item (@order) {
6525: $res .= &escape($item).'&';
6526: }
6527: }
6528: $res=~s/\&$//;
6529: }
1.387 albertel 6530: &Reply($client, \$res, $userinput);
1.361 raeburn 6531: return 1;
6532: }
6533: ®ister_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
6534:
1.264 albertel 6535: # mkpath makes all directories for a file, expects an absolute path with a
6536: # file or a trailing / if just a dir is passed
6537: # returns 1 on success 0 on failure
6538: sub mkpath {
6539: my ($file)=@_;
6540: my @parts=split(/\//,$file,-1);
6541: my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
6542: for (my $i=3;$i<= ($#parts-1);$i++) {
1.265 albertel 6543: $now.='/'.$parts[$i];
1.264 albertel 6544: if (!-e $now) {
6545: if (!mkdir($now,0770)) { return 0; }
6546: }
6547: }
6548: return 1;
6549: }
6550:
1.207 foxr 6551: #---------------------------------------------------------------
6552: #
6553: # Getting, decoding and dispatching requests:
6554: #
6555: #
6556: # Get a Request:
6557: # Gets a Request message from the client. The transaction
6558: # is defined as a 'line' of text. We remove the new line
6559: # from the text line.
1.226 foxr 6560: #
1.211 albertel 6561: sub get_request {
1.207 foxr 6562: my $input = <$client>;
6563: chomp($input);
1.226 foxr 6564:
1.234 foxr 6565: &Debug("get_request: Request = $input\n");
1.207 foxr 6566:
6567: &status('Processing '.$clientname.':'.$input);
6568:
6569: return $input;
6570: }
1.212 foxr 6571: #---------------------------------------------------------------
6572: #
6573: # Process a request. This sub should shrink as each action
6574: # gets farmed out into a separat sub that is registered
6575: # with the dispatch hash.
6576: #
6577: # Parameters:
6578: # user_input - The request received from the client (lonc).
6579: # Returns:
6580: # true to keep processing, false if caller should exit.
6581: #
6582: sub process_request {
6583: my ($userinput) = @_; # Easier for now to break style than to
6584: # fix all the userinput -> user_input.
6585: my $wasenc = 0; # True if request was encrypted.
6586: # ------------------------------------------------------------ See if encrypted
1.322 albertel 6587: # for command
6588: # sethost:<server>
6589: # <command>:<args>
6590: # we just send it to the processor
6591: # for
6592: # sethost:<server>:<command>:<args>
6593: # we do the implict set host and then do the command
6594: if ($userinput =~ /^sethost:/) {
6595: (my $cmd,my $newid,$userinput) = split(':',$userinput,3);
6596: if (defined($userinput)) {
6597: &sethost("$cmd:$newid");
6598: } else {
6599: $userinput = "$cmd:$newid";
6600: }
6601: }
6602:
1.212 foxr 6603: if ($userinput =~ /^enc/) {
6604: $userinput = decipher($userinput);
6605: $wasenc=1;
6606: if(!$userinput) { # Cipher not defined.
1.251 foxr 6607: &Failure($client, "error: Encrypted data without negotated key\n");
1.212 foxr 6608: return 0;
6609: }
6610: }
6611: Debug("process_request: $userinput\n");
6612:
1.213 foxr 6613: #
6614: # The 'correct way' to add a command to lond is now to
6615: # write a sub to execute it and Add it to the command dispatch
6616: # hash via a call to register_handler.. The comments to that
6617: # sub should give you enough to go on to show how to do this
6618: # along with the examples that are building up as this code
6619: # is getting refactored. Until all branches of the
6620: # if/elseif monster below have been factored out into
6621: # separate procesor subs, if the dispatch hash is missing
6622: # the command keyword, we will fall through to the remainder
6623: # of the if/else chain below in order to keep this thing in
6624: # working order throughout the transmogrification.
6625:
6626: my ($command, $tail) = split(/:/, $userinput, 2);
6627: chomp($command);
6628: chomp($tail);
6629: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
1.214 foxr 6630: $command =~ s/(\r)//; # And this too for parameterless commands.
6631: if(!$tail) {
6632: $tail =""; # defined but blank.
6633: }
1.213 foxr 6634:
6635: &Debug("Command received: $command, encoded = $wasenc");
6636:
6637: if(defined $Dispatcher{$command}) {
6638:
6639: my $dispatch_info = $Dispatcher{$command};
6640: my $handler = $$dispatch_info[0];
6641: my $need_encode = $$dispatch_info[1];
6642: my $client_types = $$dispatch_info[2];
6643: Debug("Matched dispatch hash: mustencode: $need_encode "
6644: ."ClientType $client_types");
6645:
6646: # Validate the request:
6647:
6648: my $ok = 1;
6649: my $requesterprivs = 0;
6650: if(&isClient()) {
6651: $requesterprivs |= $CLIENT_OK;
6652: }
6653: if(&isManager()) {
6654: $requesterprivs |= $MANAGER_OK;
6655: }
6656: if($need_encode && (!$wasenc)) {
6657: Debug("Must encode but wasn't: $need_encode $wasenc");
6658: $ok = 0;
6659: }
6660: if(($client_types & $requesterprivs) == 0) {
6661: Debug("Client not privileged to do this operation");
6662: $ok = 0;
6663: }
6664:
6665: if($ok) {
6666: Debug("Dispatching to handler $command $tail");
6667: my $keep_going = &$handler($command, $tail, $client);
6668: return $keep_going;
6669: } else {
6670: Debug("Refusing to dispatch because client did not match requirements");
6671: Failure($client, "refused\n", $userinput);
6672: return 1;
6673: }
6674:
6675: }
6676:
1.262 foxr 6677: print $client "unknown_cmd\n";
1.212 foxr 6678: # -------------------------------------------------------------------- complete
6679: Debug("process_request - returning 1");
6680: return 1;
6681: }
1.207 foxr 6682: #
6683: # Decipher encoded traffic
6684: # Parameters:
6685: # input - Encoded data.
6686: # Returns:
6687: # Decoded data or undef if encryption key was not yet negotiated.
6688: # Implicit input:
6689: # cipher - This global holds the negotiated encryption key.
6690: #
1.211 albertel 6691: sub decipher {
1.207 foxr 6692: my ($input) = @_;
6693: my $output = '';
1.212 foxr 6694:
6695:
1.207 foxr 6696: if($cipher) {
6697: my($enc, $enclength, $encinput) = split(/:/, $input);
6698: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
6699: $output .=
6700: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
6701: }
6702: return substr($output, 0, $enclength);
6703: } else {
6704: return undef;
6705: }
6706: }
6707:
6708: #
6709: # Register a command processor. This function is invoked to register a sub
6710: # to process a request. Once registered, the ProcessRequest sub can automatically
6711: # dispatch requests to an appropriate sub, and do the top level validity checking
6712: # as well:
6713: # - Is the keyword recognized.
6714: # - Is the proper client type attempting the request.
6715: # - Is the request encrypted if it has to be.
6716: # Parameters:
6717: # $request_name - Name of the request being registered.
6718: # This is the command request that will match
6719: # against the hash keywords to lookup the information
6720: # associated with the dispatch information.
6721: # $procedure - Reference to a sub to call to process the request.
6722: # All subs get called as follows:
6723: # Procedure($cmd, $tail, $replyfd, $key)
6724: # $cmd - the actual keyword that invoked us.
6725: # $tail - the tail of the request that invoked us.
6726: # $replyfd- File descriptor connected to the client
6727: # $must_encode - True if the request must be encoded to be good.
6728: # $client_ok - True if it's ok for a client to request this.
6729: # $manager_ok - True if it's ok for a manager to request this.
6730: # Side effects:
6731: # - On success, the Dispatcher hash has an entry added for the key $RequestName
6732: # - On failure, the program will die as it's a bad internal bug to try to
6733: # register a duplicate command handler.
6734: #
1.211 albertel 6735: sub register_handler {
1.212 foxr 6736: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
1.207 foxr 6737:
6738: # Don't allow duplication#
6739:
6740: if (defined $Dispatcher{$request_name}) {
6741: die "Attempting to define a duplicate request handler for $request_name\n";
6742: }
6743: # Build the client type mask:
6744:
6745: my $client_type_mask = 0;
6746: if($client_ok) {
6747: $client_type_mask |= $CLIENT_OK;
6748: }
6749: if($manager_ok) {
6750: $client_type_mask |= $MANAGER_OK;
6751: }
6752:
6753: # Enter the hash:
6754:
6755: my @entry = ($procedure, $must_encode, $client_type_mask);
6756:
6757: $Dispatcher{$request_name} = \@entry;
6758:
6759: }
6760:
6761:
6762: #------------------------------------------------------------------
6763:
6764:
6765:
6766:
1.141 foxr 6767: #
1.96 foxr 6768: # Convert an error return code from lcpasswd to a string value.
6769: #
6770: sub lcpasswdstrerror {
6771: my $ErrorCode = shift;
1.97 foxr 6772: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 6773: return "lcpasswd Unrecognized error return value ".$ErrorCode;
6774: } else {
1.98 foxr 6775: return $passwderrors[$ErrorCode];
1.96 foxr 6776: }
6777: }
6778:
1.23 harris41 6779: # grabs exception and records it to log before exiting
6780: sub catchexception {
1.27 albertel 6781: my ($error)=@_;
1.25 www 6782: $SIG{'QUIT'}='DEFAULT';
6783: $SIG{__DIE__}='DEFAULT';
1.165 albertel 6784: &status("Catching exception");
1.190 albertel 6785: &logthis("<font color='red'>CRITICAL: "
1.373 albertel 6786: ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
1.27 albertel 6787: ."a crash with this error msg->[$error]</font>");
1.57 www 6788: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 6789: if ($client) { print $client "error: $error\n"; }
1.59 www 6790: $server->close();
1.27 albertel 6791: die($error);
1.23 harris41 6792: }
1.63 www 6793: sub timeout {
1.165 albertel 6794: &status("Handling Timeout");
1.190 albertel 6795: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63 www 6796: &catchexception('Timeout');
6797: }
1.22 harris41 6798: # -------------------------------- Set signal handlers to record abnormal exits
6799:
1.226 foxr 6800:
1.22 harris41 6801: $SIG{'QUIT'}=\&catchexception;
6802: $SIG{__DIE__}=\&catchexception;
6803:
1.81 matthew 6804: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 6805: &status("Read loncapa.conf and loncapa_apache.conf");
6806: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 6807: %perlvar=%{$perlvarref};
1.80 harris41 6808: undef $perlvarref;
1.19 www 6809:
1.35 harris41 6810: # ----------------------------- Make sure this process is running from user=www
6811: my $wwwid=getpwnam('www');
6812: if ($wwwid!=$<) {
1.134 albertel 6813: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
6814: my $subj="LON: $currenthostid User ID mismatch";
1.489.2.31 raeburn 6815: system("echo 'User ID mismatch. lond must be run as user www.' |".
6816: " mail -s '$subj' $emailto > /dev/null");
1.35 harris41 6817: exit 1;
6818: }
6819:
1.19 www 6820: # --------------------------------------------- Check if other instance running
6821:
6822: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
6823:
6824: if (-e $pidfile) {
6825: my $lfh=IO::File->new("$pidfile");
6826: my $pide=<$lfh>;
6827: chomp($pide);
1.29 harris41 6828: if (kill 0 => $pide) { die "already running"; }
1.19 www 6829: }
1.1 albertel 6830:
6831: # ------------------------------------------------------------- Read hosts file
6832:
6833:
6834:
6835: # establish SERVER socket, bind and listen.
6836: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
6837: Type => SOCK_STREAM,
6838: Proto => 'tcp',
1.469 foxr 6839: ReuseAddr => 1,
1.1 albertel 6840: Listen => 10 )
1.29 harris41 6841: or die "making socket: $@\n";
1.1 albertel 6842:
6843: # --------------------------------------------------------- Do global variables
6844:
6845: # global variables
6846:
1.134 albertel 6847: my %children = (); # keys are current child process IDs
1.1 albertel 6848:
6849: sub REAPER { # takes care of dead children
6850: $SIG{CHLD} = \&REAPER;
1.165 albertel 6851: &status("Handling child death");
1.178 foxr 6852: my $pid;
6853: do {
6854: $pid = waitpid(-1,&WNOHANG());
6855: if (defined($children{$pid})) {
6856: &logthis("Child $pid died");
6857: delete($children{$pid});
1.183 albertel 6858: } elsif ($pid > 0) {
1.178 foxr 6859: &logthis("Unknown Child $pid died");
6860: }
6861: } while ( $pid > 0 );
6862: foreach my $child (keys(%children)) {
6863: $pid = waitpid($child,&WNOHANG());
6864: if ($pid > 0) {
6865: &logthis("Child $child - $pid looks like we missed it's death");
6866: delete($children{$pid});
6867: }
1.176 albertel 6868: }
1.165 albertel 6869: &status("Finished Handling child death");
1.1 albertel 6870: }
6871:
6872: sub HUNTSMAN { # signal handler for SIGINT
1.165 albertel 6873: &status("Killing children (INT)");
1.1 albertel 6874: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
6875: kill 'INT' => keys %children;
1.59 www 6876: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 6877: my $execdir=$perlvar{'lonDaemons'};
6878: unlink("$execdir/logs/lond.pid");
1.190 albertel 6879: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165 albertel 6880: &status("Done killing children");
1.1 albertel 6881: exit; # clean up with dignity
6882: }
6883:
6884: sub HUPSMAN { # signal handler for SIGHUP
6885: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.165 albertel 6886: &status("Killing children for restart (HUP)");
1.1 albertel 6887: kill 'INT' => keys %children;
1.59 www 6888: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190 albertel 6889: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134 albertel 6890: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 6891: unlink("$execdir/logs/lond.pid");
1.165 albertel 6892: &status("Restarting self (HUP)");
1.1 albertel 6893: exec("$execdir/lond"); # here we go again
6894: }
6895:
1.144 foxr 6896: #
1.148 foxr 6897: # Reload the Apache daemon's state.
1.150 foxr 6898: # This is done by invoking /home/httpd/perl/apachereload
6899: # a setuid perl script that can be root for us to do this job.
1.148 foxr 6900: #
6901: sub ReloadApache {
1.473 raeburn 6902: # --------------------------- Handle case of another apachereload process (locking)
1.474 raeburn 6903: if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
6904: my $execdir = $perlvar{'lonDaemons'};
6905: my $script = $execdir."/apachereload";
6906: system($script);
6907: unlink('/tmp/lock_apachereload'); # Remove the lock file.
6908: }
1.148 foxr 6909: }
6910:
6911: #
1.144 foxr 6912: # Called in response to a USR2 signal.
6913: # - Reread hosts.tab
6914: # - All children connected to hosts that were removed from hosts.tab
6915: # are killed via SIGINT
6916: # - All children connected to previously existing hosts are sent SIGUSR1
6917: # - Our internal hosts hash is updated to reflect the new contents of
6918: # hosts.tab causing connections from hosts added to hosts.tab to
6919: # now be honored.
6920: #
6921: sub UpdateHosts {
1.165 albertel 6922: &status("Reload hosts.tab");
1.147 foxr 6923: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 6924: #
6925: # The %children hash has the set of IP's we currently have children
6926: # on. These need to be matched against records in the hosts.tab
6927: # Any ip's no longer in the table get killed off they correspond to
6928: # either dropped or changed hosts. Note that the re-read of the table
6929: # will take care of new and changed hosts as connections come into being.
6930:
1.371 albertel 6931: &Apache::lonnet::reset_hosts_info();
1.148 foxr 6932:
1.368 albertel 6933: foreach my $child (keys(%children)) {
1.148 foxr 6934: my $childip = $children{$child};
1.374 albertel 6935: if ($childip ne '127.0.0.1'
6936: && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
1.149 foxr 6937: logthis('<font color="blue"> UpdateHosts killing child '
6938: ." $child for ip $childip </font>");
1.148 foxr 6939: kill('INT', $child);
1.149 foxr 6940: } else {
6941: logthis('<font color="green"> keeping child for ip '
6942: ." $childip (pid=$child) </font>");
1.148 foxr 6943: }
6944: }
6945: ReloadApache;
1.165 albertel 6946: &status("Finished reloading hosts.tab");
1.144 foxr 6947: }
6948:
1.148 foxr 6949:
1.57 www 6950: sub checkchildren {
1.165 albertel 6951: &status("Checking on the children (sending signals)");
1.57 www 6952: &initnewstatus();
6953: &logstatus();
6954: &logthis('Going to check on the children');
1.134 albertel 6955: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 6956: foreach (sort keys %children) {
1.221 albertel 6957: #sleep 1;
1.57 www 6958: unless (kill 'USR1' => $_) {
6959: &logthis ('Child '.$_.' is dead');
6960: &logstatus($$.' is dead');
1.221 albertel 6961: delete($children{$_});
1.57 www 6962: }
1.61 harris41 6963: }
1.63 www 6964: sleep 5;
1.212 foxr 6965: $SIG{ALRM} = sub { Debug("timeout");
6966: die "timeout"; };
1.113 albertel 6967: $SIG{__DIE__} = 'DEFAULT';
1.165 albertel 6968: &status("Checking on the children (waiting for reports)");
1.63 www 6969: foreach (sort keys %children) {
6970: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 6971: eval {
6972: alarm(300);
1.63 www 6973: &logthis('Child '.$_.' did not respond');
1.67 albertel 6974: kill 9 => $_;
1.131 albertel 6975: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
6976: #$subj="LON: $currenthostid killed lond process $_";
6977: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
6978: #$execdir=$perlvar{'lonDaemons'};
6979: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221 albertel 6980: delete($children{$_});
1.113 albertel 6981: alarm(0);
6982: }
1.63 www 6983: }
6984: }
1.113 albertel 6985: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 6986: $SIG{__DIE__} = \&catchexception;
1.165 albertel 6987: &status("Finished checking children");
1.221 albertel 6988: &logthis('Finished Checking children');
1.57 www 6989: }
6990:
1.1 albertel 6991: # --------------------------------------------------------------------- Logging
6992:
6993: sub logthis {
6994: my $message=shift;
6995: my $execdir=$perlvar{'lonDaemons'};
6996: my $fh=IO::File->new(">>$execdir/logs/lond.log");
6997: my $now=time;
6998: my $local=localtime($now);
1.58 www 6999: $lastlog=$local.': '.$message;
1.1 albertel 7000: print $fh "$local ($$): $message\n";
7001: }
7002:
1.77 foxr 7003: # ------------------------- Conditional log if $DEBUG true.
7004: sub Debug {
7005: my $message = shift;
7006: if($DEBUG) {
7007: &logthis($message);
7008: }
7009: }
1.161 foxr 7010:
7011: #
7012: # Sub to do replies to client.. this gives a hook for some
7013: # debug tracing too:
7014: # Parameters:
7015: # fd - File open on client.
7016: # reply - Text to send to client.
7017: # request - Original request from client.
7018: #
7019: sub Reply {
1.192 foxr 7020: my ($fd, $reply, $request) = @_;
1.387 albertel 7021: if (ref($reply)) {
7022: print $fd $$reply;
7023: print $fd "\n";
7024: if ($DEBUG) { Debug("Request was $request Reply was $$reply"); }
7025: } else {
7026: print $fd $reply;
7027: if ($DEBUG) { Debug("Request was $request Reply was $reply"); }
7028: }
1.212 foxr 7029: $Transactions++;
7030: }
7031:
7032:
7033: #
7034: # Sub to report a failure.
7035: # This function:
7036: # - Increments the failure statistic counters.
7037: # - Invokes Reply to send the error message to the client.
7038: # Parameters:
7039: # fd - File descriptor open on the client
7040: # reply - Reply text to emit.
7041: # request - The original request message (used by Reply
7042: # to debug if that's enabled.
7043: # Implicit outputs:
7044: # $Failures- The number of failures is incremented.
7045: # Reply (invoked here) sends a message to the
7046: # client:
7047: #
7048: sub Failure {
7049: my $fd = shift;
7050: my $reply = shift;
7051: my $request = shift;
7052:
7053: $Failures++;
7054: Reply($fd, $reply, $request); # That's simple eh?
1.161 foxr 7055: }
1.57 www 7056: # ------------------------------------------------------------------ Log status
7057:
7058: sub logstatus {
1.178 foxr 7059: &status("Doing logging");
7060: my $docdir=$perlvar{'lonDocRoot'};
7061: {
7062: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200 matthew 7063: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178 foxr 7064: $fh->close();
7065: }
1.221 albertel 7066: &status("Finished $$.txt");
7067: {
7068: open(LOG,">>$docdir/lon-status/londstatus.txt");
7069: flock(LOG,LOCK_EX);
7070: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
7071: .$status."\t".$lastlog."\t $keymode\n";
1.275 albertel 7072: flock(LOG,LOCK_UN);
1.221 albertel 7073: close(LOG);
7074: }
1.178 foxr 7075: &status("Finished logging");
1.57 www 7076: }
7077:
7078: sub initnewstatus {
7079: my $docdir=$perlvar{'lonDocRoot'};
7080: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
1.460 foxr 7081: my $now=time();
1.57 www 7082: my $local=localtime($now);
7083: print $fh "LOND status $local - parent $$\n\n";
1.64 www 7084: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 7085: while (my $filename=readdir(DIR)) {
1.64 www 7086: unlink("$docdir/lon-status/londchld/$filename");
7087: }
7088: closedir(DIR);
1.57 www 7089: }
7090:
7091: # -------------------------------------------------------------- Status setting
7092:
7093: sub status {
7094: my $what=shift;
7095: my $now=time;
7096: my $local=localtime($now);
1.178 foxr 7097: $status=$local.': '.$what;
7098: $0='lond: '.$what.' '.$local;
1.57 www 7099: }
1.11 www 7100:
1.13 www 7101: # -------------------------------------------------------------- Talk to lonsql
7102:
1.234 foxr 7103: sub sql_reply {
1.12 harris41 7104: my ($cmd)=@_;
1.234 foxr 7105: my $answer=&sub_sql_reply($cmd);
7106: if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12 harris41 7107: return $answer;
7108: }
7109:
1.234 foxr 7110: sub sub_sql_reply {
1.12 harris41 7111: my ($cmd)=@_;
7112: my $unixsock="mysqlsock";
7113: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
7114: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
7115: Type => SOCK_STREAM,
7116: Timeout => 10)
7117: or return "con_lost";
1.319 www 7118: print $sclient "$cmd:$currentdomainid\n";
1.12 harris41 7119: my $answer=<$sclient>;
7120: chomp($answer);
7121: if (!$answer) { $answer="con_lost"; }
7122: return $answer;
7123: }
7124:
1.1 albertel 7125: # --------------------------------------- Is this the home server of an author?
1.11 www 7126:
1.1 albertel 7127: sub ishome {
7128: my $author=shift;
7129: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
7130: my ($udom,$uname)=split(/\//,$author);
7131: my $proname=propath($udom,$uname);
7132: if (-e $proname) {
7133: return 'owner';
7134: } else {
7135: return 'not_owner';
7136: }
7137: }
7138:
7139: # ======================================================= Continue main program
7140: # ---------------------------------------------------- Fork once and dissociate
7141:
1.134 albertel 7142: my $fpid=fork;
1.1 albertel 7143: exit if $fpid;
1.29 harris41 7144: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 7145:
1.29 harris41 7146: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 7147:
7148: # ------------------------------------------------------- Write our PID on disk
7149:
1.134 albertel 7150: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 7151: open (PIDSAVE,">$execdir/logs/lond.pid");
7152: print PIDSAVE "$$\n";
7153: close(PIDSAVE);
1.190 albertel 7154: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57 www 7155: &status('Starting');
1.1 albertel 7156:
1.106 foxr 7157:
1.1 albertel 7158:
7159: # ----------------------------------------------------- Install signal handlers
7160:
1.57 www 7161:
1.1 albertel 7162: $SIG{CHLD} = \&REAPER;
7163: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
7164: $SIG{HUP} = \&HUPSMAN;
1.57 www 7165: $SIG{USR1} = \&checkchildren;
1.144 foxr 7166: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 7167:
1.148 foxr 7168: # Read the host hashes:
1.368 albertel 7169: &Apache::lonnet::load_hosts_tab();
1.447 raeburn 7170: my %iphost = &Apache::lonnet::get_iphost(1);
1.106 foxr 7171:
1.480 raeburn 7172: $dist=`$perlvar{'lonDaemons'}/distprobe`;
1.286 albertel 7173:
1.471 raeburn 7174: my $arch = `uname -i`;
1.475 raeburn 7175: chomp($arch);
1.471 raeburn 7176: if ($arch eq 'unknown') {
7177: $arch = `uname -m`;
1.475 raeburn 7178: chomp($arch);
1.471 raeburn 7179: }
7180:
1.106 foxr 7181: # --------------------------------------------------------------
7182: # Accept connections. When a connection comes in, it is validated
7183: # and if good, a child process is created to process transactions
7184: # along the connection.
7185:
1.1 albertel 7186: while (1) {
1.165 albertel 7187: &status('Starting accept');
1.106 foxr 7188: $client = $server->accept() or next;
1.165 albertel 7189: &status('Accepted '.$client.' off to spawn');
1.386 albertel 7190: make_new_child($client);
1.165 albertel 7191: &status('Finished spawning');
1.1 albertel 7192: }
7193:
1.212 foxr 7194: sub make_new_child {
7195: my $pid;
7196: # my $cipher; # Now global
7197: my $sigset;
1.178 foxr 7198:
1.212 foxr 7199: $client = shift;
7200: &status('Starting new child '.$client);
7201: &logthis('<font color="green"> Attempting to start child ('.$client.
7202: ")</font>");
7203: # block signal for fork
7204: $sigset = POSIX::SigSet->new(SIGINT);
7205: sigprocmask(SIG_BLOCK, $sigset)
7206: or die "Can't block SIGINT for fork: $!\n";
1.178 foxr 7207:
1.212 foxr 7208: die "fork: $!" unless defined ($pid = fork);
1.178 foxr 7209:
1.212 foxr 7210: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
7211: # connection liveness.
1.178 foxr 7212:
1.212 foxr 7213: #
7214: # Figure out who we're talking to so we can record the peer in
7215: # the pid hash.
7216: #
7217: my $caller = getpeername($client);
7218: my ($port,$iaddr);
7219: if (defined($caller) && length($caller) > 0) {
7220: ($port,$iaddr)=unpack_sockaddr_in($caller);
7221: } else {
7222: &logthis("Unable to determine who caller was, getpeername returned nothing");
7223: }
7224: if (defined($iaddr)) {
7225: $clientip = inet_ntoa($iaddr);
7226: Debug("Connected with $clientip");
7227: } else {
7228: &logthis("Unable to determine clientip");
7229: $clientip='Unavailable';
7230: }
7231:
7232: if ($pid) {
7233: # Parent records the child's birth and returns.
7234: sigprocmask(SIG_UNBLOCK, $sigset)
7235: or die "Can't unblock SIGINT for fork: $!\n";
7236: $children{$pid} = $clientip;
7237: &status('Started child '.$pid);
1.462 foxr 7238: close($client);
1.212 foxr 7239: return;
7240: } else {
7241: # Child can *not* return from this subroutine.
7242: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
7243: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
7244: #don't get intercepted
7245: $SIG{USR1}= \&logstatus;
7246: $SIG{ALRM}= \&timeout;
1.468 foxr 7247: #
7248: # Block sigpipe as it gets thrownon socket disconnect and we want to
7249: # deal with that as a read faiure instead.
7250: #
7251: my $blockset = POSIX::SigSet->new(SIGPIPE);
7252: sigprocmask(SIG_BLOCK, $blockset);
7253:
1.212 foxr 7254: $lastlog='Forked ';
7255: $status='Forked';
1.178 foxr 7256:
1.212 foxr 7257: # unblock signals
7258: sigprocmask(SIG_UNBLOCK, $sigset)
7259: or die "Can't unblock SIGINT for fork: $!\n";
1.178 foxr 7260:
1.212 foxr 7261: # my $tmpsnum=0; # Now global
7262: #---------------------------------------------------- kerberos 5 initialization
7263: &Authen::Krb5::init_context();
1.489.2.16 raeburn 7264:
7265: my $no_ets;
1.489.2.43 raeburn 7266: if ($dist =~ /^(?:centos|rhes|scientific|oracle|rocky|alma)(\d+)/) {
1.489.2.16 raeburn 7267: if ($1 >= 7) {
7268: $no_ets = 1;
7269: }
7270: } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
7271: if (($1 eq '9.3') || ($1 >= 12.2)) {
7272: $no_ets = 1;
7273: }
1.489.2.17 raeburn 7274: } elsif ($dist =~ /^sles(\d+)$/) {
7275: if ($1 > 11) {
7276: $no_ets = 1;
7277: }
1.489.2.16 raeburn 7278: } elsif ($dist =~ /^fedora(\d+)$/) {
7279: if ($1 < 7) {
7280: $no_ets = 1;
7281: }
7282: }
7283: unless ($no_ets) {
7284: &Authen::Krb5::init_ets();
7285: }
1.209 albertel 7286:
1.212 foxr 7287: &status('Accepted connection');
7288: # =============================================================================
7289: # do something with the connection
7290: # -----------------------------------------------------------------------------
7291: # see if we know client and 'check' for spoof IP by ineffective challenge
1.178 foxr 7292:
1.278 albertel 7293: my $outsideip=$clientip;
7294: if ($clientip eq '127.0.0.1') {
1.368 albertel 7295: $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
1.278 albertel 7296: }
1.412 foxr 7297: &ReadManagerTable();
1.368 albertel 7298: my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
1.278 albertel 7299: my $ismanager=($managers{$outsideip} ne undef);
1.432 raeburn 7300: $clientname = "[unknown]";
1.212 foxr 7301: if($clientrec) { # Establish client type.
7302: $ConnectionType = "client";
1.368 albertel 7303: $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
1.212 foxr 7304: if($ismanager) {
7305: $ConnectionType = "both";
7306: }
7307: } else {
7308: $ConnectionType = "manager";
1.278 albertel 7309: $clientname = $managers{$outsideip};
1.212 foxr 7310: }
7311: my $clientok;
1.178 foxr 7312:
1.212 foxr 7313: if ($clientrec || $ismanager) {
7314: &status("Waiting for init from $clientip $clientname");
7315: &logthis('<font color="yellow">INFO: Connection, '.
7316: $clientip.
7317: " ($clientname) connection type = $ConnectionType </font>" );
7318: &status("Connecting $clientip ($clientname))");
7319: my $remotereq=<$client>;
7320: chomp($remotereq);
7321: Debug("Got init: $remotereq");
1.337 albertel 7322:
1.212 foxr 7323: if ($remotereq =~ /^init/) {
7324: &sethost("sethost:$perlvar{'lonHostID'}");
7325: #
7326: # If the remote is attempting a local init... give that a try:
7327: #
1.432 raeburn 7328: (my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
1.489.2.4 raeburn 7329: # For LON-CAPA 2.9, the client session will have sent its LON-CAPA
7330: # version when initiating the connection. For LON-CAPA 2.8 and older,
7331: # the version is retrieved from the global %loncaparevs in lonnet.pm.
7332: # $clientversion contains path to keyfile if $inittype eq 'local'
7333: # it's overridden below in this case
7334: $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
1.209 albertel 7335:
1.212 foxr 7336: # If the connection type is ssl, but I didn't get my
7337: # certificate files yet, then I'll drop back to
7338: # insecure (if allowed).
7339:
7340: if($inittype eq "ssl") {
7341: my ($ca, $cert) = lonssl::CertificateFile;
7342: my $kfile = lonssl::KeyFile;
7343: if((!$ca) ||
7344: (!$cert) ||
7345: (!$kfile)) {
7346: $inittype = ""; # This forces insecure attempt.
7347: &logthis("<font color=\"blue\"> Certificates not "
7348: ."installed -- trying insecure auth</font>");
1.224 foxr 7349: } else { # SSL certificates are in place so
1.212 foxr 7350: } # Leave the inittype alone.
7351: }
7352:
7353: if($inittype eq "local") {
1.432 raeburn 7354: $clientversion = $perlvar{'lonVersion'};
1.212 foxr 7355: my $key = LocalConnection($client, $remotereq);
7356: if($key) {
7357: Debug("Got local key $key");
7358: $clientok = 1;
7359: my $cipherkey = pack("H32", $key);
7360: $cipher = new IDEA($cipherkey);
7361: print $client "ok:local\n";
1.442 www 7362: &logthis('<font color="green">'
1.212 foxr 7363: . "Successful local authentication </font>");
7364: $keymode = "local"
1.178 foxr 7365: } else {
1.212 foxr 7366: Debug("Failed to get local key");
7367: $clientok = 0;
7368: shutdown($client, 3);
7369: close $client;
1.178 foxr 7370: }
1.212 foxr 7371: } elsif ($inittype eq "ssl") {
7372: my $key = SSLConnection($client);
7373: if ($key) {
7374: $clientok = 1;
7375: my $cipherkey = pack("H32", $key);
7376: $cipher = new IDEA($cipherkey);
7377: &logthis('<font color="green">'
7378: ."Successfull ssl authentication with $clientname </font>");
7379: $keymode = "ssl";
7380:
1.178 foxr 7381: } else {
1.212 foxr 7382: $clientok = 0;
7383: close $client;
1.178 foxr 7384: }
1.212 foxr 7385:
7386: } else {
7387: my $ok = InsecureConnection($client);
7388: if($ok) {
7389: $clientok = 1;
7390: &logthis('<font color="green">'
7391: ."Successful insecure authentication with $clientname </font>");
7392: print $client "ok\n";
7393: $keymode = "insecure";
1.178 foxr 7394: } else {
1.212 foxr 7395: &logthis('<font color="yellow">'
7396: ."Attempted insecure connection disallowed </font>");
7397: close $client;
7398: $clientok = 0;
1.178 foxr 7399: }
7400: }
1.212 foxr 7401: } else {
7402: &logthis(
7403: "<font color='blue'>WARNING: "
7404: ."$clientip failed to initialize: >$remotereq< </font>");
7405: &status('No init '.$clientip);
7406: }
7407: } else {
7408: &logthis(
7409: "<font color='blue'>WARNING: Unknown client $clientip</font>");
7410: &status('Hung up on '.$clientip);
7411: }
7412:
7413: if ($clientok) {
7414: # ---------------- New known client connecting, could mean machine online again
1.368 albertel 7415: if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip
1.367 albertel 7416: && $clientip ne '127.0.0.1') {
1.375 albertel 7417: &Apache::lonnet::reconlonc($clientname);
1.212 foxr 7418: }
7419: &logthis("<font color='green'>Established connection: $clientname</font>");
7420: &status('Will listen to '.$clientname);
7421: # ------------------------------------------------------------ Process requests
7422: my $keep_going = 1;
7423: my $user_input;
1.448 raeburn 7424: my $clienthost = &Apache::lonnet::hostname($clientname);
7425: my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
7426: $clienthomedom = &Apache::lonnet::host_domain($clientserverhomeID);
1.212 foxr 7427: while(($user_input = get_request) && $keep_going) {
7428: alarm(120);
7429: Debug("Main: Got $user_input\n");
7430: $keep_going = &process_request($user_input);
1.178 foxr 7431: alarm(0);
1.489.2.42 raeburn 7432: &status('Listening to '.$clientname." ($keymode)");
1.161 foxr 7433: }
1.212 foxr 7434:
1.59 www 7435: # --------------------------------------------- client unknown or fishy, refuse
1.212 foxr 7436: } else {
1.161 foxr 7437: print $client "refused\n";
7438: $client->close();
1.190 albertel 7439: &logthis("<font color='blue'>WARNING: "
1.161 foxr 7440: ."Rejected client $clientip, closing connection</font>");
7441: }
1.212 foxr 7442: }
1.161 foxr 7443:
1.1 albertel 7444: # =============================================================================
1.161 foxr 7445:
1.190 albertel 7446: &logthis("<font color='red'>CRITICAL: "
1.161 foxr 7447: ."Disconnect from $clientip ($clientname)</font>");
1.489.2.42 raeburn 7448:
7449:
1.161 foxr 7450: # this exit is VERY important, otherwise the child will become
7451: # a producer of more and more children, forking yourself into
7452: # process death.
7453: exit;
1.106 foxr 7454:
1.78 foxr 7455: }
1.261 foxr 7456: #
7457: # Determine if a user is an author for the indicated domain.
7458: #
7459: # Parameters:
7460: # domain - domain to check in .
7461: # user - Name of user to check.
7462: #
7463: # Return:
7464: # 1 - User is an author for domain.
7465: # 0 - User is not an author for domain.
7466: sub is_author {
7467: my ($domain, $user) = @_;
7468:
7469: &Debug("is_author: $user @ $domain");
7470:
7471: my $hashref = &tie_user_hash($domain, $user, "roles",
7472: &GDBM_READER());
7473:
7474: # Author role should show up as a key /domain/_au
1.78 foxr 7475:
1.321 albertel 7476: my $value;
1.487 foxr 7477: if ($hashref) {
1.78 foxr 7478:
1.487 foxr 7479: my $key = "/$domain/_au";
7480: if (defined($hashref)) {
7481: $value = $hashref->{$key};
7482: if(!untie_user_hash($hashref)) {
7483: return 'error: ' . ($!+0)." untie (GDBM) Failed";
7484: }
7485: }
7486:
7487: if(defined($value)) {
7488: &Debug("$user @ $domain is an author");
7489: }
7490: } else {
7491: return 'error: '.($!+0)." tie (GDBM) Failed";
1.261 foxr 7492: }
7493:
7494: return defined($value);
7495: }
1.78 foxr 7496: #
7497: # Checks to see if the input roleput request was to set
1.482 www 7498: # an author role. If so, creates construction space
1.78 foxr 7499: # Parameters:
7500: # request - The request sent to the rolesput subchunk.
7501: # We're looking for /domain/_au
7502: # domain - The domain in which the user is having roles doctored.
7503: # user - Name of the user for which the role is being put.
7504: # authtype - The authentication type associated with the user.
7505: #
1.289 albertel 7506: sub manage_permissions {
1.192 foxr 7507: my ($request, $domain, $user, $authtype) = @_;
1.78 foxr 7508: # See if the request is of the form /$domain/_au
1.289 albertel 7509: if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.484 raeburn 7510: my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
1.482 www 7511: unless (-e $path) {
7512: mkdir($path);
7513: }
7514: unless (-e $path.'/'.$user) {
7515: mkdir($path.'/'.$user);
7516: }
1.78 foxr 7517: }
7518: }
1.222 foxr 7519:
7520:
7521: #
7522: # Return the full path of a user password file, whether it exists or not.
7523: # Parameters:
7524: # domain - Domain in which the password file lives.
7525: # user - name of the user.
7526: # Returns:
7527: # Full passwd path:
7528: #
7529: sub password_path {
7530: my ($domain, $user) = @_;
1.264 albertel 7531: return &propath($domain, $user).'/passwd';
1.222 foxr 7532: }
7533:
7534: # Password Filename
7535: # Returns the path to a passwd file given domain and user... only if
7536: # it exists.
7537: # Parameters:
7538: # domain - Domain in which to search.
7539: # user - username.
7540: # Returns:
7541: # - If the password file exists returns its path.
7542: # - If the password file does not exist, returns undefined.
7543: #
7544: sub password_filename {
7545: my ($domain, $user) = @_;
7546:
7547: Debug ("PasswordFilename called: dom = $domain user = $user");
7548:
7549: my $path = &password_path($domain, $user);
7550: Debug("PasswordFilename got path: $path");
7551: if(-e $path) {
7552: return $path;
7553: } else {
7554: return undef;
7555: }
7556: }
7557:
7558: #
7559: # Rewrite the contents of the user's passwd file.
7560: # Parameters:
7561: # domain - domain of the user.
7562: # name - User's name.
7563: # contents - New contents of the file.
1.489.2.26 raeburn 7564: # saveold - (optional). If true save old file in a passwd.bak file.
1.222 foxr 7565: # Returns:
7566: # 0 - Failed.
7567: # 1 - Success.
7568: #
7569: sub rewrite_password_file {
1.489.2.26 raeburn 7570: my ($domain, $user, $contents, $saveold) = @_;
1.222 foxr 7571:
7572: my $file = &password_filename($domain, $user);
7573: if (defined $file) {
1.489.2.26 raeburn 7574: if ($saveold) {
7575: my $bakfile = $file.'.bak';
7576: if (CopyFile($file,$bakfile)) {
7577: chmod(0400,$bakfile);
7578: &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
7579: } else {
7580: &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
7581: }
7582: }
1.222 foxr 7583: my $pf = IO::File->new(">$file");
7584: if($pf) {
7585: print $pf "$contents\n";
7586: return 1;
7587: } else {
7588: return 0;
7589: }
7590: } else {
7591: return 0;
7592: }
7593:
7594: }
7595:
1.78 foxr 7596: #
1.222 foxr 7597: # get_auth_type - Determines the authorization type of a user in a domain.
1.78 foxr 7598:
7599: # Returns the authorization type or nouser if there is no such user.
7600: #
1.436 raeburn 7601: sub get_auth_type {
1.192 foxr 7602: my ($domain, $user) = @_;
1.78 foxr 7603:
1.222 foxr 7604: Debug("get_auth_type( $domain, $user ) \n");
1.78 foxr 7605: my $proname = &propath($domain, $user);
7606: my $passwdfile = "$proname/passwd";
7607: if( -e $passwdfile ) {
7608: my $pf = IO::File->new($passwdfile);
7609: my $realpassword = <$pf>;
7610: chomp($realpassword);
1.79 foxr 7611: Debug("Password info = $realpassword\n");
1.78 foxr 7612: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 7613: Debug("Authtype = $authtype, content = $contentpwd\n");
1.259 raeburn 7614: return "$authtype:$contentpwd";
1.224 foxr 7615: } else {
1.79 foxr 7616: Debug("Returning nouser");
1.78 foxr 7617: return "nouser";
7618: }
1.1 albertel 7619: }
7620:
1.220 foxr 7621: #
7622: # Validate a user given their domain, name and password. This utility
7623: # function is used by both AuthenticateHandler and ChangePasswordHandler
7624: # to validate the login credentials of a user.
7625: # Parameters:
7626: # $domain - The domain being logged into (this is required due to
7627: # the capability for multihomed systems.
7628: # $user - The name of the user being validated.
7629: # $password - The user's propoposed password.
7630: #
7631: # Returns:
7632: # 1 - The domain,user,pasword triplet corresponds to a valid
7633: # user.
7634: # 0 - The domain,user,password triplet is not a valid user.
7635: #
7636: sub validate_user {
1.396 raeburn 7637: my ($domain, $user, $password, $checkdefauth) = @_;
1.220 foxr 7638:
7639: # Why negative ~pi you may well ask? Well this function is about
7640: # authentication, and therefore very important to get right.
7641: # I've initialized the flag that determines whether or not I've
7642: # validated correctly to a value it's not supposed to get.
7643: # At the end of this function. I'll ensure that it's not still that
7644: # value so we don't just wind up returning some accidental value
7645: # as a result of executing an unforseen code path that
1.249 foxr 7646: # did not set $validated. At the end of valid execution paths,
7647: # validated shoule be 1 for success or 0 for failuer.
1.220 foxr 7648:
7649: my $validated = -3.14159;
7650:
7651: # How we authenticate is determined by the type of authentication
7652: # the user has been assigned. If the authentication type is
7653: # "nouser", the user does not exist so we will return 0.
7654:
1.222 foxr 7655: my $contents = &get_auth_type($domain, $user);
1.220 foxr 7656: my ($howpwd, $contentpwd) = split(/:/, $contents);
7657:
7658: my $null = pack("C",0); # Used by kerberos auth types.
7659:
1.395 raeburn 7660: if ($howpwd eq 'nouser') {
1.396 raeburn 7661: if ($checkdefauth) {
7662: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
7663: if ($domdefaults{'auth_def'} eq 'localauth') {
7664: $howpwd = $domdefaults{'auth_def'};
7665: $contentpwd = $domdefaults{'auth_arg_def'};
7666: } elsif ((($domdefaults{'auth_def'} eq 'krb4') ||
7667: ($domdefaults{'auth_def'} eq 'krb5')) &&
7668: ($domdefaults{'auth_arg_def'} ne '')) {
1.489.2.44 raeburn 7669: #
7670: # Don't attempt authentication for username and password supplied
7671: # for user without an account if uername contains @ to avoid
7672: # call to &Authen::Krb5::parse_name() which will result in con_lost
7673: #
7674: unless ($user =~ /\@/) {
7675: $howpwd = $domdefaults{'auth_def'};
7676: $contentpwd = $domdefaults{'auth_arg_def'};
7677: }
1.396 raeburn 7678: }
1.395 raeburn 7679: }
1.489.2.26 raeburn 7680: }
1.220 foxr 7681: if ($howpwd ne 'nouser') {
7682: if($howpwd eq "internal") { # Encrypted is in local password file.
1.489.2.21 raeburn 7683: if (length($contentpwd) == 13) {
7684: $validated = (crypt($password,$contentpwd) eq $contentpwd);
7685: if ($validated) {
1.489.2.26 raeburn 7686: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
7687: if ($domdefaults{'intauth_switch'}) {
7688: my $ncpass = &hash_passwd($domain,$password);
7689: my $saveold;
7690: if ($domdefaults{'intauth_switch'} == 2) {
7691: $saveold = 1;
7692: }
7693: if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
7694: &update_passwd_history($user,$domain,$howpwd,'conversion');
7695: &logthis("Validated password hashed with bcrypt for $user:$domain");
7696: }
1.489.2.21 raeburn 7697: }
7698: }
7699: } else {
1.489.2.26 raeburn 7700: $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
1.489.2.21 raeburn 7701: }
1.220 foxr 7702: }
7703: elsif ($howpwd eq "unix") { # User is a normal unix user.
7704: $contentpwd = (getpwnam($user))[1];
7705: if($contentpwd) {
7706: if($contentpwd eq 'x') { # Shadow password file...
7707: my $pwauth_path = "/usr/local/sbin/pwauth";
7708: open PWAUTH, "|$pwauth_path" or
7709: die "Cannot invoke authentication";
7710: print PWAUTH "$user\n$password\n";
7711: close PWAUTH;
7712: $validated = ! $?;
7713:
7714: } else { # Passwords in /etc/passwd.
7715: $validated = (crypt($password,
7716: $contentpwd) eq $contentpwd);
7717: }
7718: } else {
7719: $validated = 0;
7720: }
1.439 raeburn 7721: } elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
7722: my $checkwithkrb5 = 0;
7723: if ($dist =~/^fedora(\d+)$/) {
7724: if ($1 > 11) {
7725: $checkwithkrb5 = 1;
7726: }
7727: } elsif ($dist =~ /^suse([\d.]+)$/) {
7728: if ($1 > 11.1) {
7729: $checkwithkrb5 = 1;
7730: }
7731: }
7732: if ($checkwithkrb5) {
7733: $validated = &krb5_authen($password,$null,$user,$contentpwd);
7734: } else {
7735: $validated = &krb4_authen($password,$null,$user,$contentpwd);
7736: }
1.224 foxr 7737: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.439 raeburn 7738: $validated = &krb5_authen($password,$null,$user,$contentpwd);
1.224 foxr 7739: } elsif ($howpwd eq "localauth") {
1.220 foxr 7740: # Authenticate via installation specific authentcation method:
7741: $validated = &localauth::localauth($user,
7742: $password,
1.353 albertel 7743: $contentpwd,
7744: $domain);
1.358 albertel 7745: if ($validated < 0) {
1.357 albertel 7746: &logthis("localauth for $contentpwd $user:$domain returned a $validated");
7747: $validated = 0;
7748: }
1.224 foxr 7749: } else { # Unrecognized auth is also bad.
1.220 foxr 7750: $validated = 0;
7751: }
7752: } else {
7753: $validated = 0;
7754: }
7755: #
7756: # $validated has the correct stat of the authentication:
7757: #
7758:
7759: unless ($validated != -3.14159) {
1.249 foxr 7760: # I >really really< want to know if this happens.
7761: # since it indicates that user authentication is badly
7762: # broken in some code path.
7763: #
7764: die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220 foxr 7765: }
7766: return $validated;
7767: }
7768:
1.489.2.21 raeburn 7769: sub check_internal_passwd {
1.489.2.26 raeburn 7770: my ($plainpass,$stored,$domain,$user) = @_;
1.489.2.21 raeburn 7771: my (undef,$method,@rest) = split(/!/,$stored);
1.489.2.26 raeburn 7772: if ($method eq 'bcrypt') {
1.489.2.21 raeburn 7773: my $result = &hash_passwd($domain,$plainpass,@rest);
7774: if ($result ne $stored) {
7775: return 0;
7776: }
1.489.2.26 raeburn 7777: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
7778: if ($domdefaults{'intauth_check'}) {
7779: # Upgrade to a larger number of rounds if necessary
7780: my $defaultcost = $domdefaults{'intauth_cost'};
7781: if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
7782: $defaultcost = 10;
7783: }
7784: if (int($rest[0])<int($defaultcost)) {
7785: if ($domdefaults{'intauth_check'} == 1) {
7786: my $ncpass = &hash_passwd($domain,$plainpass);
7787: if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
7788: &update_passwd_history($user,$domain,'internal','update cost');
7789: &logthis("Validated password hashed with bcrypt for $user:$domain");
7790: }
7791: return 1;
7792: } elsif ($domdefaults{'intauth_check'} == 2) {
7793: return 0;
7794: }
7795: }
7796: } else {
7797: return 1;
1.489.2.21 raeburn 7798: }
7799: }
7800: return 0;
7801: }
7802:
7803: sub get_last_authchg {
7804: my ($domain,$user) = @_;
7805: my $lastmod;
7806: my $logname = &propath($domain,$user).'/passwd.log';
7807: if (-e "$logname") {
7808: $lastmod = (stat("$logname"))[9];
7809: }
7810: return $lastmod;
7811: }
7812:
1.439 raeburn 7813: sub krb4_authen {
7814: my ($password,$null,$user,$contentpwd) = @_;
7815: my $validated = 0;
7816: if (!($password =~ /$null/) ) { # Null password not allowed.
7817: eval {
7818: require Authen::Krb4;
7819: };
7820: if (!$@) {
7821: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
7822: "",
7823: $contentpwd,,
7824: 'krbtgt',
7825: $contentpwd,
7826: 1,
7827: $password);
7828: if(!$k4error) {
7829: $validated = 1;
7830: } else {
7831: $validated = 0;
7832: &logthis('krb4: '.$user.', '.$contentpwd.', '.
7833: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
7834: }
7835: } else {
7836: $validated = krb5_authen($password,$null,$user,$contentpwd);
7837: }
7838: }
7839: return $validated;
7840: }
7841:
7842: sub krb5_authen {
7843: my ($password,$null,$user,$contentpwd) = @_;
7844: my $validated = 0;
7845: if(!($password =~ /$null/)) { # Null password not allowed.
7846: my $krbclient = &Authen::Krb5::parse_name($user.'@'
7847: .$contentpwd);
7848: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
7849: my $krbserver = &Authen::Krb5::parse_name($krbservice);
7850: my $credentials= &Authen::Krb5::cc_default();
7851: $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
7852: .$contentpwd));
7853: my $krbreturn;
7854: if (exists(&Authen::Krb5::get_init_creds_password)) {
7855: $krbreturn =
7856: &Authen::Krb5::get_init_creds_password($krbclient,$password,
7857: $krbservice);
7858: $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
7859: } else {
7860: $krbreturn =
7861: &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
7862: $password,$credentials);
7863: $validated = ($krbreturn == 1);
7864: }
7865: if (!$validated) {
7866: &logthis('krb5: '.$user.', '.$contentpwd.', '.
7867: &Authen::Krb5::error());
7868: }
7869: }
7870: return $validated;
7871: }
1.220 foxr 7872:
1.84 albertel 7873: sub addline {
7874: my ($fname,$hostid,$ip,$newline)=@_;
7875: my $contents;
7876: my $found=0;
1.355 albertel 7877: my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
1.134 albertel 7878: my $sh;
1.84 albertel 7879: if ($sh=IO::File->new("$fname.subscription")) {
7880: while (my $subline=<$sh>) {
7881: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
7882: }
7883: $sh->close();
7884: }
7885: $sh=IO::File->new(">$fname.subscription");
7886: if ($contents) { print $sh $contents; }
7887: if ($newline) { print $sh $newline; }
7888: $sh->close();
7889: return $found;
1.86 www 7890: }
7891:
1.234 foxr 7892: sub get_chat {
1.324 raeburn 7893: my ($cdom,$cname,$udom,$uname,$group)=@_;
1.310 albertel 7894:
1.87 www 7895: my @entries=();
1.324 raeburn 7896: my $namespace = 'nohist_chatroom';
7897: my $namespace_inroom = 'nohist_inchatroom';
1.335 albertel 7898: if ($group ne '') {
1.324 raeburn 7899: $namespace .= '_'.$group;
7900: $namespace_inroom .= '_'.$group;
7901: }
7902: my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310 albertel 7903: &GDBM_READER());
7904: if ($hashref) {
7905: @entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.311 albertel 7906: &untie_user_hash($hashref);
1.123 www 7907: }
1.124 www 7908: my @participants=();
1.134 albertel 7909: my $cutoff=time-60;
1.324 raeburn 7910: $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
1.310 albertel 7911: &GDBM_WRCREAT());
7912: if ($hashref) {
7913: $hashref->{$uname.':'.$udom}=time;
7914: foreach my $user (sort(keys(%$hashref))) {
7915: if ($hashref->{$user}>$cutoff) {
7916: push(@participants, 'active_participant:'.$user);
1.123 www 7917: }
7918: }
1.311 albertel 7919: &untie_user_hash($hashref);
1.86 www 7920: }
1.124 www 7921: return (@participants,@entries);
1.86 www 7922: }
7923:
1.234 foxr 7924: sub chat_add {
1.324 raeburn 7925: my ($cdom,$cname,$newchat,$group)=@_;
1.88 albertel 7926: my @entries=();
1.142 www 7927: my $time=time;
1.324 raeburn 7928: my $namespace = 'nohist_chatroom';
7929: my $logfile = 'chatroom.log';
1.335 albertel 7930: if ($group ne '') {
1.324 raeburn 7931: $namespace .= '_'.$group;
7932: $logfile = 'chatroom_'.$group.'.log';
7933: }
7934: my $hashref = &tie_user_hash($cdom, $cname, $namespace,
1.310 albertel 7935: &GDBM_WRCREAT());
7936: if ($hashref) {
7937: @entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
1.88 albertel 7938: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
7939: my ($thentime,$idnum)=split(/\_/,$lastid);
7940: my $newid=$time.'_000000';
7941: if ($thentime==$time) {
7942: $idnum=~s/^0+//;
7943: $idnum++;
7944: $idnum=substr('000000'.$idnum,-6,6);
7945: $newid=$time.'_'.$idnum;
7946: }
1.310 albertel 7947: $hashref->{$newid}=$newchat;
1.88 albertel 7948: my $expired=$time-3600;
1.310 albertel 7949: foreach my $comment (keys(%$hashref)) {
7950: my ($thistime) = ($comment=~/(\d+)\_/);
1.88 albertel 7951: if ($thistime<$expired) {
1.310 albertel 7952: delete $hashref->{$comment};
1.88 albertel 7953: }
7954: }
1.310 albertel 7955: {
7956: my $proname=&propath($cdom,$cname);
1.324 raeburn 7957: if (open(CHATLOG,">>$proname/$logfile")) {
1.310 albertel 7958: print CHATLOG ("$time:".&unescape($newchat)."\n");
7959: }
7960: close(CHATLOG);
1.142 www 7961: }
1.311 albertel 7962: &untie_user_hash($hashref);
1.86 www 7963: }
1.84 albertel 7964: }
7965:
7966: sub unsub {
7967: my ($fname,$clientip)=@_;
7968: my $result;
1.188 foxr 7969: my $unsubs = 0; # Number of successful unsubscribes:
7970:
7971:
7972: # An old way subscriptions were handled was to have a
7973: # subscription marker file:
7974:
7975: Debug("Attempting unlink of $fname.$clientname");
1.161 foxr 7976: if (unlink("$fname.$clientname")) {
1.188 foxr 7977: $unsubs++; # Successful unsub via marker file.
7978: }
7979:
7980: # The more modern way to do it is to have a subscription list
7981: # file:
7982:
1.84 albertel 7983: if (-e "$fname.subscription") {
1.161 foxr 7984: my $found=&addline($fname,$clientname,$clientip,'');
1.188 foxr 7985: if ($found) {
7986: $unsubs++;
7987: }
7988: }
7989:
7990: # If either or both of these mechanisms succeeded in unsubscribing a
7991: # resource we can return ok:
7992:
7993: if($unsubs) {
7994: $result = "ok\n";
1.84 albertel 7995: } else {
1.188 foxr 7996: $result = "not_subscribed\n";
1.84 albertel 7997: }
1.188 foxr 7998:
1.84 albertel 7999: return $result;
8000: }
8001:
1.101 www 8002: sub currentversion {
8003: my $fname=shift;
8004: my $version=-1;
8005: my $ulsdir='';
8006: if ($fname=~/^(.+)\/[^\/]+$/) {
8007: $ulsdir=$1;
8008: }
1.114 albertel 8009: my ($fnamere1,$fnamere2);
8010: # remove version if already specified
1.101 www 8011: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 8012: # get the bits that go before and after the version number
8013: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
8014: $fnamere1=$1;
8015: $fnamere2='.'.$2;
8016: }
1.101 www 8017: if (-e $fname) { $version=1; }
8018: if (-e $ulsdir) {
1.134 albertel 8019: if(-d $ulsdir) {
8020: if (opendir(LSDIR,$ulsdir)) {
8021: my $ulsfn;
8022: while ($ulsfn=readdir(LSDIR)) {
1.101 www 8023: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 8024: my $thisfile=$ulsdir.'/'.$ulsfn;
8025: unless (-l $thisfile) {
1.160 www 8026: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 8027: if ($1>$version) { $version=$1; }
8028: }
8029: }
8030: }
8031: closedir(LSDIR);
8032: $version++;
8033: }
8034: }
8035: }
8036: return $version;
1.101 www 8037: }
8038:
8039: sub thisversion {
8040: my $fname=shift;
8041: my $version=-1;
8042: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
8043: $version=$1;
8044: }
8045: return $version;
8046: }
8047:
1.84 albertel 8048: sub subscribe {
8049: my ($userinput,$clientip)=@_;
8050: my $result;
1.293 albertel 8051: my ($cmd,$fname)=split(/:/,$userinput,2);
1.84 albertel 8052: my $ownership=&ishome($fname);
8053: if ($ownership eq 'owner') {
1.101 www 8054: # explitly asking for the current version?
8055: unless (-e $fname) {
8056: my $currentversion=¤tversion($fname);
8057: if (&thisversion($fname)==$currentversion) {
8058: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
8059: my $root=$1;
8060: my $extension=$2;
8061: symlink($root.'.'.$extension,
8062: $root.'.'.$currentversion.'.'.$extension);
1.102 www 8063: unless ($extension=~/\.meta$/) {
8064: symlink($root.'.'.$extension.'.meta',
8065: $root.'.'.$currentversion.'.'.$extension.'.meta');
8066: }
1.101 www 8067: }
8068: }
8069: }
1.84 albertel 8070: if (-e $fname) {
8071: if (-d $fname) {
8072: $result="directory\n";
8073: } else {
1.161 foxr 8074: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 8075: my $now=time;
1.161 foxr 8076: my $found=&addline($fname,$clientname,$clientip,
8077: "$clientname:$clientip:$now\n");
1.84 albertel 8078: if ($found) { $result="$fname\n"; }
8079: # if they were subscribed to only meta data, delete that
8080: # subscription, when you subscribe to a file you also get
8081: # the metadata
8082: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
8083: $fname=~s/\/home\/httpd\/html\/res/raw/;
1.476 raeburn 8084: my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
8085: $protocol = 'http' if ($protocol ne 'https');
8086: $fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
1.84 albertel 8087: $result="$fname\n";
8088: }
8089: } else {
8090: $result="not_found\n";
8091: }
8092: } else {
8093: $result="rejected\n";
8094: }
8095: return $result;
8096: }
1.287 foxr 8097: # Change the passwd of a unix user. The caller must have
8098: # first verified that the user is a loncapa user.
8099: #
8100: # Parameters:
8101: # user - Unix user name to change.
8102: # pass - New password for the user.
8103: # Returns:
8104: # ok - if success
8105: # other - Some meaningfule error message string.
8106: # NOTE:
8107: # invokes a setuid script to change the passwd.
8108: sub change_unix_password {
8109: my ($user, $pass) = @_;
8110:
8111: &Debug("change_unix_password");
8112: my $execdir=$perlvar{'lonDaemons'};
8113: &Debug("Opening lcpasswd pipeline");
8114: my $pf = IO::File->new("|$execdir/lcpasswd > "
8115: ."$perlvar{'lonDaemons'}"
8116: ."/logs/lcpasswd.log");
8117: print $pf "$user\n$pass\n$pass\n";
8118: close $pf;
8119: my $err = $?;
8120: return ($err < @passwderrors) ? $passwderrors[$err] :
8121: "pwchange_falure - unknown error";
8122:
8123:
8124: }
8125:
1.91 albertel 8126:
8127: sub make_passwd_file {
1.489.2.21 raeburn 8128: my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
1.390 raeburn 8129: my $result="ok";
1.91 albertel 8130: if ($umode eq 'krb4' or $umode eq 'krb5') {
8131: {
8132: my $pf = IO::File->new(">$passfilename");
1.261 foxr 8133: if ($pf) {
8134: print $pf "$umode:$npass\n";
1.489.2.21 raeburn 8135: &update_passwd_history($uname,$udom,$umode,$action);
1.261 foxr 8136: } else {
8137: $result = "pass_file_failed_error";
8138: }
1.91 albertel 8139: }
8140: } elsif ($umode eq 'internal') {
1.489.2.21 raeburn 8141: my $ncpass = &hash_passwd($udom,$npass);
1.91 albertel 8142: {
8143: &Debug("Creating internal auth");
8144: my $pf = IO::File->new(">$passfilename");
1.261 foxr 8145: if($pf) {
8146: print $pf "internal:$ncpass\n";
1.489.2.21 raeburn 8147: &update_passwd_history($uname,$udom,$umode,$action);
1.261 foxr 8148: } else {
8149: $result = "pass_file_failed_error";
8150: }
1.91 albertel 8151: }
8152: } elsif ($umode eq 'localauth') {
8153: {
8154: my $pf = IO::File->new(">$passfilename");
1.261 foxr 8155: if($pf) {
8156: print $pf "localauth:$npass\n";
1.489.2.21 raeburn 8157: &update_passwd_history($uname,$udom,$umode,$action);
1.261 foxr 8158: } else {
8159: $result = "pass_file_failed_error";
8160: }
1.91 albertel 8161: }
8162: } elsif ($umode eq 'unix') {
1.489.2.8 raeburn 8163: &logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
8164: $result="no_new_unix_accounts";
1.91 albertel 8165: } elsif ($umode eq 'none') {
8166: {
1.223 foxr 8167: my $pf = IO::File->new("> $passfilename");
1.261 foxr 8168: if($pf) {
8169: print $pf "none:\n";
8170: } else {
8171: $result = "pass_file_failed_error";
8172: }
1.91 albertel 8173: }
8174: } else {
1.390 raeburn 8175: $result="auth_mode_error";
1.91 albertel 8176: }
8177: return $result;
1.121 albertel 8178: }
8179:
1.265 albertel 8180: sub convert_photo {
8181: my ($start,$dest)=@_;
8182: system("convert $start $dest");
8183: }
8184:
1.121 albertel 8185: sub sethost {
8186: my ($remotereq) = @_;
8187: my (undef,$hostid)=split(/:/,$remotereq);
1.322 albertel 8188: # ignore sethost if we are already correct
8189: if ($hostid eq $currenthostid) {
8190: return 'ok';
8191: }
8192:
1.121 albertel 8193: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
1.368 albertel 8194: if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'})
8195: eq &Apache::lonnet::get_host_ip($hostid)) {
1.200 matthew 8196: $currenthostid =$hostid;
1.369 albertel 8197: $currentdomainid=&Apache::lonnet::host_domain($hostid);
1.443 www 8198: # &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
1.121 albertel 8199: } else {
8200: &logthis("Requested host id $hostid not an alias of ".
8201: $perlvar{'lonHostID'}." refusing connection");
8202: return 'unable_to_set';
8203: }
8204: return 'ok';
8205: }
8206:
8207: sub version {
8208: my ($userinput)=@_;
8209: $remoteVERSION=(split(/:/,$userinput))[1];
8210: return "version:$VERSION";
1.127 albertel 8211: }
1.178 foxr 8212:
1.447 raeburn 8213: sub get_usersession_config {
8214: my ($dom,$name) = @_;
8215: my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
8216: if (defined($cached)) {
8217: return $usersessionconf;
8218: } else {
8219: my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
8220: if (ref($domconfig{'usersessions'}) eq 'HASH') {
8221: &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
8222: return $domconfig{'usersessions'};
8223: }
8224: }
8225: return;
8226: }
1.200 matthew 8227:
1.489.2.27 raeburn 8228: sub get_usersearch_config {
8229: my ($dom,$name) = @_;
8230: my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
8231: if (defined($cached)) {
8232: return $usersearchconf;
8233: } else {
8234: my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
8235: &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},3600);
8236: return $domconfig{'directorysrch'};
8237: }
8238: return;
8239: }
1.450 raeburn 8240:
1.471 raeburn 8241: sub distro_and_arch {
8242: return $dist.':'.$arch;
8243: }
8244:
1.61 harris41 8245: # ----------------------------------- POD (plain old documentation, CPAN style)
8246:
8247: =head1 NAME
8248:
8249: lond - "LON Daemon" Server (port "LOND" 5663)
8250:
8251: =head1 SYNOPSIS
8252:
1.74 harris41 8253: Usage: B<lond>
8254:
8255: Should only be run as user=www. This is a command-line script which
8256: is invoked by B<loncron>. There is no expectation that a typical user
8257: will manually start B<lond> from the command-line. (In other words,
8258: DO NOT START B<lond> YOURSELF.)
1.61 harris41 8259:
8260: =head1 DESCRIPTION
8261:
1.74 harris41 8262: There are two characteristics associated with the running of B<lond>,
8263: PROCESS MANAGEMENT (starting, stopping, handling child processes)
8264: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
8265: subscriptions, etc). These are described in two large
8266: sections below.
8267:
8268: B<PROCESS MANAGEMENT>
8269:
1.61 harris41 8270: Preforker - server who forks first. Runs as a daemon. HUPs.
8271: Uses IDEA encryption
8272:
1.74 harris41 8273: B<lond> forks off children processes that correspond to the other servers
8274: in the network. Management of these processes can be done at the
8275: parent process level or the child process level.
8276:
8277: B<logs/lond.log> is the location of log messages.
8278:
8279: The process management is now explained in terms of linux shell commands,
8280: subroutines internal to this code, and signal assignments:
8281:
8282: =over 4
8283:
8284: =item *
8285:
8286: PID is stored in B<logs/lond.pid>
8287:
8288: This is the process id number of the parent B<lond> process.
8289:
8290: =item *
8291:
8292: SIGTERM and SIGINT
8293:
8294: Parent signal assignment:
8295: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
8296:
8297: Child signal assignment:
8298: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
8299: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
8300: to restart a new child.)
8301:
8302: Command-line invocations:
8303: B<kill> B<-s> SIGTERM I<PID>
8304: B<kill> B<-s> SIGINT I<PID>
8305:
8306: Subroutine B<HUNTSMAN>:
8307: This is only invoked for the B<lond> parent I<PID>.
8308: This kills all the children, and then the parent.
8309: The B<lonc.pid> file is cleared.
8310:
8311: =item *
8312:
8313: SIGHUP
8314:
8315: Current bug:
8316: This signal can only be processed the first time
8317: on the parent process. Subsequent SIGHUP signals
8318: have no effect.
8319:
8320: Parent signal assignment:
8321: $SIG{HUP} = \&HUPSMAN;
8322:
8323: Child signal assignment:
8324: none (nothing happens)
8325:
8326: Command-line invocations:
8327: B<kill> B<-s> SIGHUP I<PID>
8328:
8329: Subroutine B<HUPSMAN>:
8330: This is only invoked for the B<lond> parent I<PID>,
8331: This kills all the children, and then the parent.
8332: The B<lond.pid> file is cleared.
8333:
8334: =item *
8335:
8336: SIGUSR1
8337:
8338: Parent signal assignment:
8339: $SIG{USR1} = \&USRMAN;
8340:
8341: Child signal assignment:
8342: $SIG{USR1}= \&logstatus;
8343:
8344: Command-line invocations:
8345: B<kill> B<-s> SIGUSR1 I<PID>
8346:
8347: Subroutine B<USRMAN>:
8348: When invoked for the B<lond> parent I<PID>,
8349: SIGUSR1 is sent to all the children, and the status of
8350: each connection is logged.
1.144 foxr 8351:
8352: =item *
8353:
8354: SIGUSR2
8355:
8356: Parent Signal assignment:
8357: $SIG{USR2} = \&UpdateHosts
8358:
8359: Child signal assignment:
8360: NONE
8361:
1.74 harris41 8362:
8363: =item *
8364:
8365: SIGCHLD
8366:
8367: Parent signal assignment:
8368: $SIG{CHLD} = \&REAPER;
8369:
8370: Child signal assignment:
8371: none
8372:
8373: Command-line invocations:
8374: B<kill> B<-s> SIGCHLD I<PID>
8375:
8376: Subroutine B<REAPER>:
8377: This is only invoked for the B<lond> parent I<PID>.
8378: Information pertaining to the child is removed.
8379: The socket port is cleaned up.
8380:
8381: =back
8382:
8383: B<SERVER-SIDE ACTIVITIES>
8384:
8385: Server-side information can be accepted in an encrypted or non-encrypted
8386: method.
8387:
8388: =over 4
8389:
8390: =item ping
8391:
8392: Query a client in the hosts.tab table; "Are you there?"
8393:
8394: =item pong
8395:
8396: Respond to a ping query.
8397:
8398: =item ekey
8399:
8400: Read in encrypted key, make cipher. Respond with a buildkey.
8401:
8402: =item load
8403:
8404: Respond with CPU load based on a computation upon /proc/loadavg.
8405:
8406: =item currentauth
8407:
8408: Reply with current authentication information (only over an
8409: encrypted channel).
8410:
8411: =item auth
8412:
8413: Only over an encrypted channel, reply as to whether a user's
8414: authentication information can be validated.
8415:
8416: =item passwd
8417:
8418: Allow for a password to be set.
8419:
8420: =item makeuser
8421:
8422: Make a user.
8423:
8424: =item passwd
8425:
8426: Allow for authentication mechanism and password to be changed.
8427:
8428: =item home
1.61 harris41 8429:
1.74 harris41 8430: Respond to a question "are you the home for a given user?"
8431:
8432: =item update
8433:
8434: Update contents of a subscribed resource.
8435:
8436: =item unsubscribe
8437:
8438: The server is unsubscribing from a resource.
8439:
8440: =item subscribe
8441:
8442: The server is subscribing to a resource.
8443:
8444: =item log
8445:
8446: Place in B<logs/lond.log>
8447:
8448: =item put
8449:
8450: stores hash in namespace
8451:
1.489.2.2 raeburn 8452: =item rolesput
1.74 harris41 8453:
8454: put a role into a user's environment
8455:
8456: =item get
8457:
8458: returns hash with keys from array
8459: reference filled in from namespace
8460:
8461: =item eget
8462:
8463: returns hash with keys from array
8464: reference filled in from namesp (encrypts the return communication)
8465:
8466: =item rolesget
8467:
8468: get a role from a user's environment
8469:
8470: =item del
8471:
8472: deletes keys out of array from namespace
8473:
8474: =item keys
8475:
8476: returns namespace keys
8477:
8478: =item dump
8479:
8480: dumps the complete (or key matching regexp) namespace into a hash
8481:
8482: =item store
8483:
8484: stores hash permanently
8485: for this url; hashref needs to be given and should be a \%hashname; the
8486: remaining args aren't required and if they aren't passed or are '' they will
8487: be derived from the ENV
8488:
8489: =item restore
8490:
8491: returns a hash for a given url
8492:
8493: =item querysend
8494:
8495: Tells client about the lonsql process that has been launched in response
8496: to a sent query.
8497:
8498: =item queryreply
8499:
8500: Accept information from lonsql and make appropriate storage in temporary
8501: file space.
8502:
8503: =item idput
8504:
8505: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
8506: for each student, defined perhaps by the institutional Registrar.)
8507:
8508: =item idget
8509:
8510: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
8511: for each student, defined perhaps by the institutional Registrar.)
8512:
8513: =item tmpput
8514:
8515: Accept and store information in temporary space.
8516:
8517: =item tmpget
8518:
8519: Send along temporarily stored information.
8520:
8521: =item ls
8522:
8523: List part of a user's directory.
8524:
1.135 foxr 8525: =item pushtable
8526:
8527: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
8528: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
8529: must be restored manually in case of a problem with the new table file.
8530: pushtable requires that the request be encrypted and validated via
8531: ValidateManager. The form of the command is:
8532: enc:pushtable tablename <tablecontents> \n
8533: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
8534: cleartext newline.
8535:
1.74 harris41 8536: =item Hanging up (exit or init)
8537:
8538: What to do when a client tells the server that they (the client)
8539: are leaving the network.
8540:
8541: =item unknown command
8542:
8543: If B<lond> is sent an unknown command (not in the list above),
8544: it replys to the client "unknown_cmd".
1.135 foxr 8545:
1.74 harris41 8546:
8547: =item UNKNOWN CLIENT
8548:
8549: If the anti-spoofing algorithm cannot verify the client,
8550: the client is rejected (with a "refused" message sent
8551: to the client, and the connection is closed.
8552:
8553: =back
1.61 harris41 8554:
8555: =head1 PREREQUISITES
8556:
8557: IO::Socket
8558: IO::File
8559: Apache::File
8560: POSIX
8561: Crypt::IDEA
8562: LWP::UserAgent()
8563: GDBM_File
8564: Authen::Krb4
1.91 albertel 8565: Authen::Krb5
1.61 harris41 8566:
8567: =head1 COREQUISITES
8568:
8569: =head1 OSNAMES
8570:
8571: linux
8572:
8573: =head1 SCRIPT CATEGORIES
8574:
8575: Server/Process
8576:
8577: =cut
1.409 foxr 8578:
8579:
8580: =pod
8581:
8582: =head1 LOG MESSAGES
8583:
8584: The messages below can be emitted in the lond log. This log is located
8585: in ~httpd/perl/logs/lond.log Many log messages have HTML encapsulation
8586: to provide coloring if examined from inside a web page. Some do not.
8587: Where color is used, the colors are; Red for sometihhng to get excited
8588: about and to follow up on. Yellow for something to keep an eye on to
8589: be sure it does not get worse, Green,and Blue for informational items.
8590:
8591: In the discussions below, sometimes reference is made to ~httpd
8592: when describing file locations. There isn't really an httpd
8593: user, however there is an httpd directory that gets installed in the
8594: place that user home directories go. On linux, this is usually
8595: (always?) /home/httpd.
8596:
8597:
8598: Some messages are colorless. These are usually (not always)
8599: Green/Blue color level messages.
8600:
8601: =over 2
8602:
8603: =item (Red) LocalConnection rejecting non local: <ip> ne 127.0.0.1
8604:
8605: A local connection negotiation was attempted by
8606: a host whose IP address was not 127.0.0.1.
8607: The socket is closed and the child will exit.
8608: lond has three ways to establish an encyrption
8609: key with a client:
8610:
8611: =over 2
8612:
8613: =item local
8614:
8615: The key is written and read from a file.
8616: This is only valid for connections from localhost.
8617:
8618: =item insecure
8619:
8620: The key is generated by the server and
8621: transmitted to the client.
8622:
8623: =item ssl (secure)
8624:
8625: An ssl connection is negotiated with the client,
8626: the key is generated by the server and sent to the
8627: client across this ssl connection before the
8628: ssl connectionis terminated and clear text
8629: transmission resumes.
8630:
8631: =back
8632:
8633: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
8634:
8635: The client is local but has not sent an initialization
8636: string that is the literal "init:local" The connection
8637: is closed and the child exits.
8638:
8639: =item Red CRITICAL Can't get key file <error>
8640:
8641: SSL key negotiation is being attempted but the call to
8642: lonssl::KeyFile failed. This usually means that the
8643: configuration file is not correctly defining or protecting
8644: the directories/files lonCertificateDirectory or
8645: lonnetPrivateKey
8646: <error> is a string that describes the reason that
8647: the key file could not be located.
8648:
8649: =item (Red) CRITICAL Can't get certificates <error>
8650:
8651: SSL key negotiation failed because we were not able to retrives our certificate
8652: or the CA's certificate in the call to lonssl::CertificateFile
8653: <error> is the textual reason this failed. Usual reasons:
8654:
8655: =over 2
8656:
8657: =item Apache config file for loncapa incorrect:
8658:
8659: one of the variables
8660: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
8661: undefined or incorrect
8662:
8663: =item Permission error:
8664:
8665: The directory pointed to by lonCertificateDirectory is not readable by lond
8666:
8667: =item Permission error:
8668:
8669: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
8670:
8671: =item Installation error:
8672:
8673: Either the certificate authority file or the certificate have not
8674: been installed in lonCertificateDirectory.
8675:
8676: =item (Red) CRITICAL SSL Socket promotion failed: <err>
8677:
8678: The promotion of the connection from plaintext to SSL failed
8679: <err> is the reason for the failure. There are two
8680: system calls involved in the promotion (one of which failed),
8681: a dup to produce
8682: a second fd on the raw socket over which the encrypted data
8683: will flow and IO::SOcket::SSL->new_from_fd which creates
8684: the SSL connection on the duped fd.
8685:
8686: =item (Blue) WARNING client did not respond to challenge
8687:
8688: This occurs on an insecure (non SSL) connection negotiation request.
8689: lond generates some number from the time, the PID and sends it to
8690: the client. The client must respond by echoing this information back.
8691: If the client does not do so, that's a violation of the challenge
8692: protocols and the connection will be failed.
8693:
8694: =item (Red) No manager table. Nobody can manage!!
8695:
8696: lond has the concept of privileged hosts that
8697: can perform remote management function such
8698: as update the hosts.tab. The manager hosts
8699: are described in the
8700: ~httpd/lonTabs/managers.tab file.
8701: this message is logged if this file is missing.
8702:
8703:
8704: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
8705:
8706: Reports the successful parse and registration
8707: of a specific manager.
8708:
8709: =item Green existing host <clustername:dnsname>
8710:
8711: The manager host is already defined in the hosts.tab
8712: the information in that table, rather than the info in the
8713: manager table will be used to determine the manager's ip.
8714:
8715: =item (Red) Unable to craete <filename>
8716:
8717: lond has been asked to create new versions of an administrative
8718: file (by a manager). When this is done, the new file is created
8719: in a temp file and then renamed into place so that there are always
8720: usable administrative files, even if the update fails. This failure
8721: message means that the temp file could not be created.
8722: The update is abandoned, and the old file is available for use.
8723:
8724: =item (Green) CopyFile from <oldname> to <newname> failed
8725:
8726: In an update of administrative files, the copy of the existing file to a
8727: backup file failed. The installation of the new file may still succeed,
8728: but there will not be a back up file to rever to (this should probably
8729: be yellow).
8730:
8731: =item (Green) Pushfile: backed up <oldname> to <newname>
8732:
8733: See above, the backup of the old administrative file succeeded.
8734:
8735: =item (Red) Pushfile: Unable to install <filename> <reason>
8736:
8737: The new administrative file could not be installed. In this case,
8738: the old administrative file is still in use.
8739:
8740: =item (Green) Installed new < filename>.
8741:
8742: The new administrative file was successfullly installed.
8743:
8744: =item (Red) Reinitializing lond pid=<pid>
8745:
8746: The lonc child process <pid> will be sent a USR2
8747: signal.
8748:
8749: =item (Red) Reinitializing self
8750:
8751: We've been asked to re-read our administrative files,and
8752: are doing so.
8753:
8754: =item (Yellow) error:Invalid process identifier <ident>
8755:
8756: A reinit command was received, but the target part of the
8757: command was not valid. It must be either
8758: 'lond' or 'lonc' but was <ident>
8759:
8760: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
8761:
8762: Checking to see if lond has been handed a valid edit
8763: command. It is possible the edit command is not valid
8764: in that case there are no log messages to indicate that.
8765:
8766: =item Result of password change for <username> pwchange_success
8767:
8768: The password for <username> was
8769: successfully changed.
8770:
8771: =item Unable to open <user> passwd to change password
8772:
8773: Could not rewrite the
8774: internal password file for a user
8775:
8776: =item Result of password change for <user> : <result>
8777:
8778: A unix password change for <user> was attempted
8779: and the pipe returned <result>
8780:
8781: =item LWP GET: <message> for <fname> (<remoteurl>)
8782:
8783: The lightweight process fetch for a resource failed
8784: with <message> the local filename that should
8785: have existed/been created was <fname> the
8786: corresponding URI: <remoteurl> This is emitted in several
8787: places.
8788:
8789: =item Unable to move <transname> to <destname>
8790:
8791: From fetch_user_file_handler - the user file was replicated but could not
8792: be mv'd to its final location.
8793:
8794: =item Looking for <domain> <username>
8795:
8796: From user_has_session_handler - This should be a Debug call instead
8797: it indicates lond is about to check whether the specified user has a
8798: session active on the specified domain on the local host.
8799:
8800: =item Client <ip> (<name>) hanging up: <input>
8801:
8802: lond has been asked to exit by its client. The <ip> and <name> identify the
8803: client systemand <input> is the full exit command sent to the server.
8804:
8805: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
8806:
8807: A lond child terminated. NOte that this termination can also occur when the
8808: child receives the QUIT or DIE signals. <pid> is the process id of the child,
8809: <hostname> the host lond is working for, and <message> the reason the child died
8810: to the best of our ability to get it (I would guess that any numeric value
8811: represents and errno value). This is immediately followed by
8812:
8813: =item Famous last words: Catching exception - <log>
8814:
8815: Where log is some recent information about the state of the child.
8816:
8817: =item Red CRITICAL: TIME OUT <pid>
8818:
8819: Some timeout occured for server <pid>. THis is normally a timeout on an LWP
8820: doing an HTTP::GET.
8821:
8822: =item child <pid> died
8823:
8824: The reaper caught a SIGCHILD for the lond child process <pid>
8825: This should be modified to also display the IP of the dying child
8826: $children{$pid}
8827:
8828: =item Unknown child 0 died
8829: A child died but the wait for it returned a pid of zero which really should not
8830: ever happen.
8831:
8832: =item Child <which> - <pid> looks like we missed it's death
8833:
8834: When a sigchild is received, the reaper process checks all children to see if they are
8835: alive. If children are dying quite quickly, the lack of signal queuing can mean
8836: that a signal hearalds the death of more than one child. If so this message indicates
8837: which other one died. <which> is the ip of a dead child
8838:
8839: =item Free socket: <shutdownretval>
8840:
8841: The HUNTSMAN sub was called due to a SIGINT in a child process. The socket is being shutdown.
8842: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
8843: to return anything. This is followed by:
8844:
8845: =item Red CRITICAL: Shutting down
8846:
8847: Just prior to exit.
8848:
8849: =item Free socket: <shutdownretval>
8850:
8851: The HUPSMAN sub was called due to a SIGHUP. all children get killsed, and lond execs itself.
8852: This is followed by:
8853:
8854: =item (Red) CRITICAL: Restarting
8855:
8856: lond is about to exec itself to restart.
8857:
8858: =item (Blue) Updating connections
8859:
8860: (In response to a USR2). All the children (except the one for localhost)
8861: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
8862:
8863: =item (Blue) UpdateHosts killing child <pid> for ip <ip>
8864:
8865: Due to USR2 as above.
8866:
8867: =item (Green) keeping child for ip <ip> (pid = <pid>)
8868:
8869: In response to USR2 as above, the child indicated is not being restarted because
8870: it's assumed that we'll always need a child for the localhost.
8871:
8872:
8873: =item Going to check on the children
8874:
8875: Parent is about to check on the health of the child processes.
8876: Note that this is in response to a USR1 sent to the parent lond.
8877: there may be one or more of the next two messages:
8878:
8879: =item <pid> is dead
8880:
8881: A child that we have in our child hash as alive has evidently died.
8882:
8883: =item Child <pid> did not respond
8884:
8885: In the health check the child <pid> did not update/produce a pid_.txt
8886: file when sent it's USR1 signal. That process is killed with a 9 signal, as it's
8887: assumed to be hung in some un-fixable way.
8888:
8889: =item Finished checking children
8890:
8891: Master processs's USR1 processing is cojmplete.
8892:
8893: =item (Red) CRITICAL: ------- Starting ------
8894:
8895: (There are more '-'s on either side). Lond has forked itself off to
8896: form a new session and is about to start actual initialization.
8897:
8898: =item (Green) Attempting to start child (<client>)
8899:
8900: Started a new child process for <client>. Client is IO::Socket object
8901: connected to the child. This was as a result of a TCP/IP connection from a client.
8902:
8903: =item Unable to determine who caller was, getpeername returned nothing
8904:
8905: In child process initialization. either getpeername returned undef or
8906: a zero sized object was returned. Processing continues, but in my opinion,
8907: this should be cause for the child to exit.
8908:
8909: =item Unable to determine clientip
8910:
8911: In child process initialization. The peer address from getpeername was not defined.
8912: The client address is stored as "Unavailable" and processing continues.
8913:
8914: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
8915:
8916: In child initialization. A good connectionw as received from <ip>.
8917:
8918: =over 2
8919:
8920: =item <name>
8921:
8922: is the name of the client from hosts.tab.
8923:
8924: =item <type>
8925:
8926: Is the connection type which is either
8927:
8928: =over 2
8929:
8930: =item manager
8931:
8932: The connection is from a manager node, not in hosts.tab
8933:
8934: =item client
8935:
8936: the connection is from a non-manager in the hosts.tab
8937:
8938: =item both
8939:
8940: The connection is from a manager in the hosts.tab.
8941:
8942: =back
8943:
8944: =back
8945:
8946: =item (Blue) Certificates not installed -- trying insecure auth
8947:
8948: One of the certificate file, key file or
8949: certificate authority file could not be found for a client attempting
8950: SSL connection intiation. COnnection will be attemptied in in-secure mode.
8951: (this would be a system with an up to date lond that has not gotten a
8952: certificate from us).
8953:
8954: =item (Green) Successful local authentication
8955:
8956: A local connection successfully negotiated the encryption key.
8957: In this case the IDEA key is in a file (that is hopefully well protected).
8958:
8959: =item (Green) Successful ssl authentication with <client>
8960:
8961: The client (<client> is the peer's name in hosts.tab), has successfully
8962: negotiated an SSL connection with this child process.
8963:
8964: =item (Green) Successful insecure authentication with <client>
8965:
8966:
8967: The client has successfully negotiated an insecure connection withthe child process.
8968:
8969: =item (Yellow) Attempted insecure connection disallowed
8970:
8971: The client attempted and failed to successfully negotiate a successful insecure
8972: connection. This can happen either because the variable londAllowInsecure is false
8973: or undefined, or becuse the child did not successfully echo back the challenge
8974: string.
8975:
8976:
8977: =back
8978:
1.441 raeburn 8979: =back
8980:
1.409 foxr 8981:
8982: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>