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