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