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