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