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