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