Annotation of loncom/lond, revision 1.302
1.1 albertel 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60 www 4: #
1.302 ! raeburn 5: # $Id: lond,v 1.301 2005/10/17 20:09:01 www 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.302 ! raeburn 62: my $VERSION='$Revision: 1.301 $'; #' 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) {
1.301 www 1425: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1.239 foxr 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) {
1.301 www 1493: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1.280 matthew 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);
1.300 albertel 3589: @senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299 raeburn 3590: }
3591:
3592: my $qresult='';
3593: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
3594: if ($hashref) {
3595: while (my ($key,$value) = each(%$hashref)) {
3596: my $match = 1;
1.302 ! raeburn 3597: $key = &unescape($key);
1.299 raeburn 3598: my ($timestamp,$subj,$uname,$udom) = split(/:/,&unescape($key),5);
3599: $timestamp = &unescape($timestamp);
3600: $subj = &unescape($subj);
3601: $uname = &unescape($uname);
3602: $udom = &unescape($udom);
3603: unless ($startfilter eq '.' || !defined($startfilter)) {
3604: if ($timestamp < $startfilter) {
3605: $match = 0;
3606: }
3607: }
3608: unless ($endfilter eq '.' || !defined($endfilter)) {
3609: if ($timestamp > $endfilter) {
3610: $match = 0;
3611: }
3612: }
3613: unless (@senders < 1) {
3614: unless (grep/^$uname:$udom$/,@senders) {
3615: $match = 0;
3616: }
3617: }
3618: if ($match == 1) {
3619: $qresult.=$key.'='.$value.'&';
3620: }
3621: }
3622: if (untie(%$hashref)) {
3623: chop($qresult);
3624: &Reply($client, "$qresult\n", $userinput);
3625: } else {
3626: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3627: "while attempting dcmaildump\n", $userinput);
3628: }
3629: } else {
3630: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3631: "while attempting dcmaildump\n", $userinput);
3632: }
3633: return 1;
3634: }
3635:
3636: ®ister_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
3637:
3638: #
3639: # Puts domain roles in nohist_domainroles database
3640: #
3641: # Parameters
3642: # $cmd - Command keyword that caused us to be dispatched.
3643: # $tail - Tail of the command. Consists of a colon separated:
3644: # domain - the domain whose roles we are recording
3645: # role - Consists of key=value pair
3646: # where key is unique role
3647: # and value is start/end date information
3648: # $client - Socket open on the client.
3649: #
3650: # Returns:
3651: # 1 - indicating processing should continue.
3652: # Side effects
3653: # reply is written to $client.
3654: #
3655:
3656: sub put_domainroles_handler {
3657: my ($cmd,$tail,$client) = @_;
3658:
3659: my $userinput = "$cmd:$tail";
3660: my ($udom,$what)=split(/:/,$tail);
3661: chomp($what);
3662: my @pairs=split(/\&/,$what);
3663: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
3664: if ($hashref) {
3665: foreach my $pair (@pairs) {
3666: my ($key,$value)=split(/=/,$pair);
3667: $hashref->{$key}=$value;
3668: }
3669: if (untie(%$hashref)) {
3670: &Reply($client, "ok\n", $userinput);
3671: } else {
3672: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3673: "while attempting domroleput\n", $userinput);
3674: }
3675: } else {
3676: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3677: "while attempting domroleput\n", $userinput);
3678: }
3679:
3680: return 1;
3681: }
3682:
3683: ®ister_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
3684:
3685: #
3686: # Retrieves domain roles from nohist_domainroles database
3687: # Returns to client an & separated list of key=value pairs,
3688: # where key is role and value is start and end date information.
3689: #
3690: # Parameters
3691: # $cmd - Command keyword that caused us to be dispatched.
3692: # $tail - Tail of the command. Consists of a colon separated:
3693: # domain - the domain whose domain roles table we dump
3694: # $client - Socket open on the client.
3695: #
3696: # Returns:
3697: # 1 - indicating processing should continue.
3698: # Side effects
3699: # reply (& separated list of role=start/end info pairs) is
3700: # written to $client.
3701: #
3702: sub dump_domainroles_handler {
3703: my ($cmd, $tail, $client) = @_;
3704:
3705: my $userinput = "$cmd:$tail";
3706: my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
3707: chomp($rolesfilter);
3708: my @roles = ();
3709: if (defined($startfilter)) {
3710: $startfilter=&unescape($startfilter);
3711: } else {
3712: $startfilter='.';
3713: }
3714: if (defined($endfilter)) {
3715: $endfilter=&unescape($endfilter);
3716: } else {
3717: $endfilter='.';
3718: }
3719: if (defined($rolesfilter)) {
3720: $rolesfilter=&unescape($rolesfilter);
1.300 albertel 3721: @roles = split(/\&/,$rolesfilter);
1.299 raeburn 3722: }
3723:
3724: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
3725: if ($hashref) {
3726: my $qresult = '';
3727: while (my ($key,$value) = each(%$hashref)) {
3728: my $match = 1;
3729: my ($start,$end) = split(/:/,&unescape($value));
3730: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
3731: unless ($startfilter eq '.' || !defined($startfilter)) {
3732: if ($start >= $startfilter) {
3733: $match = 0;
3734: }
3735: }
3736: unless ($endfilter eq '.' || !defined($endfilter)) {
3737: if ($end <= $endfilter) {
3738: $match = 0;
3739: }
3740: }
3741: unless (@roles < 1) {
3742: unless (grep/^$trole$/,@roles) {
3743: $match = 0;
3744: }
3745: }
3746: if ($match == 1) {
3747: $qresult.=$key.'='.$value.'&';
3748: }
3749: }
3750: if (untie(%$hashref)) {
3751: chop($qresult);
3752: &Reply($client, "$qresult\n", $userinput);
3753: } else {
3754: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3755: "while attempting domrolesdump\n", $userinput);
3756: }
3757: } else {
3758: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3759: "while attempting domrolesdump\n", $userinput);
3760: }
3761: return 1;
3762: }
3763:
3764: ®ister_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
3765:
3766:
1.238 foxr 3767: # Process the tmpput command I'm not sure what this does.. Seems to
3768: # create a file in the lonDaemons/tmp directory of the form $id.tmp
3769: # where Id is the client's ip concatenated with a sequence number.
3770: # The file will contain some value that is passed in. Is this e.g.
3771: # a login token?
3772: #
3773: # Parameters:
3774: # $cmd - The command that got us dispatched.
3775: # $tail - The remainder of the request following $cmd:
3776: # In this case this will be the contents of the file.
3777: # $client - Socket connected to the client.
3778: # Returns:
3779: # 1 indicating processing can continue.
3780: # Side effects:
3781: # A file is created in the local filesystem.
3782: # A reply is sent to the client.
3783: sub tmp_put_handler {
3784: my ($cmd, $what, $client) = @_;
3785:
3786: my $userinput = "$cmd:$what"; # Reconstruct for logging.
3787:
3788:
3789: my $store;
3790: $tmpsnum++;
3791: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
3792: $id=~s/\W/\_/g;
3793: $what=~s/\n//g;
3794: my $execdir=$perlvar{'lonDaemons'};
3795: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
3796: print $store $what;
3797: close $store;
3798: &Reply($client, "$id\n", $userinput);
3799: } else {
3800: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
3801: "while attempting tmpput\n", $userinput);
3802: }
3803: return 1;
3804:
3805: }
3806: ®ister_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263 albertel 3807:
1.238 foxr 3808: # Processes the tmpget command. This command returns the contents
3809: # of a temporary resource file(?) created via tmpput.
3810: #
3811: # Paramters:
3812: # $cmd - Command that got us dispatched.
3813: # $id - Tail of the command, contain the id of the resource
3814: # we want to fetch.
3815: # $client - socket open on the client.
3816: # Return:
3817: # 1 - Inidcating processing can continue.
3818: # Side effects:
3819: # A reply is sent to the client.
3820: #
3821: sub tmp_get_handler {
3822: my ($cmd, $id, $client) = @_;
3823:
3824: my $userinput = "$cmd:$id";
3825:
3826:
3827: $id=~s/\W/\_/g;
3828: my $store;
3829: my $execdir=$perlvar{'lonDaemons'};
3830: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
3831: my $reply=<$store>;
3832: &Reply( $client, "$reply\n", $userinput);
3833: close $store;
3834: } else {
3835: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
3836: "while attempting tmpget\n", $userinput);
3837: }
3838:
3839: return 1;
3840: }
3841: ®ister_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263 albertel 3842:
1.238 foxr 3843: #
3844: # Process the tmpdel command. This command deletes a temp resource
3845: # created by the tmpput command.
3846: #
3847: # Parameters:
3848: # $cmd - Command that got us here.
3849: # $id - Id of the temporary resource created.
3850: # $client - socket open on the client process.
3851: #
3852: # Returns:
3853: # 1 - Indicating processing should continue.
3854: # Side Effects:
3855: # A file is deleted
3856: # A reply is sent to the client.
3857: sub tmp_del_handler {
3858: my ($cmd, $id, $client) = @_;
3859:
3860: my $userinput= "$cmd:$id";
3861:
3862: chomp($id);
3863: $id=~s/\W/\_/g;
3864: my $execdir=$perlvar{'lonDaemons'};
3865: if (unlink("$execdir/tmp/$id.tmp")) {
3866: &Reply($client, "ok\n", $userinput);
3867: } else {
3868: &Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
3869: "while attempting tmpdel\n", $userinput);
3870: }
3871:
3872: return 1;
3873:
3874: }
3875: ®ister_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263 albertel 3876:
1.238 foxr 3877: #
1.246 foxr 3878: # Processes the setannounce command. This command
3879: # creates a file named announce.txt in the top directory of
3880: # the documentn root and sets its contents. The announce.txt file is
3881: # printed in its entirety at the LonCAPA login page. Note:
3882: # once the announcement.txt fileis created it cannot be deleted.
3883: # However, setting the contents of the file to empty removes the
3884: # announcement from the login page of loncapa so who cares.
3885: #
3886: # Parameters:
3887: # $cmd - The command that got us dispatched.
3888: # $announcement - The text of the announcement.
3889: # $client - Socket open on the client process.
3890: # Retunrns:
3891: # 1 - Indicating request processing should continue
3892: # Side Effects:
3893: # The file {DocRoot}/announcement.txt is created.
3894: # A reply is sent to $client.
3895: #
3896: sub set_announce_handler {
3897: my ($cmd, $announcement, $client) = @_;
3898:
3899: my $userinput = "$cmd:$announcement";
3900:
3901: chomp($announcement);
3902: $announcement=&unescape($announcement);
3903: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
3904: '/announcement.txt')) {
3905: print $store $announcement;
3906: close $store;
3907: &Reply($client, "ok\n", $userinput);
3908: } else {
3909: &Failure($client, "error: ".($!+0)."\n", $userinput);
3910: }
3911:
3912: return 1;
3913: }
3914: ®ister_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263 albertel 3915:
1.246 foxr 3916: #
3917: # Return the version of the daemon. This can be used to determine
3918: # the compatibility of cross version installations or, alternatively to
3919: # simply know who's out of date and who isn't. Note that the version
3920: # is returned concatenated with the tail.
3921: # Parameters:
3922: # $cmd - the request that dispatched to us.
3923: # $tail - Tail of the request (client's version?).
3924: # $client - Socket open on the client.
3925: #Returns:
3926: # 1 - continue processing requests.
3927: # Side Effects:
3928: # Replies with version to $client.
3929: sub get_version_handler {
3930: my ($cmd, $tail, $client) = @_;
3931:
3932: my $userinput = $cmd.$tail;
3933:
3934: &Reply($client, &version($userinput)."\n", $userinput);
3935:
3936:
3937: return 1;
3938: }
3939: ®ister_handler("version", \&get_version_handler, 0, 1, 0);
1.263 albertel 3940:
1.246 foxr 3941: # Set the current host and domain. This is used to support
3942: # multihomed systems. Each IP of the system, or even separate daemons
3943: # on the same IP can be treated as handling a separate lonCAPA virtual
3944: # machine. This command selects the virtual lonCAPA. The client always
3945: # knows the right one since it is lonc and it is selecting the domain/system
3946: # from the hosts.tab file.
3947: # Parameters:
3948: # $cmd - Command that dispatched us.
3949: # $tail - Tail of the command (domain/host requested).
3950: # $socket - Socket open on the client.
3951: #
3952: # Returns:
3953: # 1 - Indicates the program should continue to process requests.
3954: # Side-effects:
3955: # The default domain/system context is modified for this daemon.
3956: # a reply is sent to the client.
3957: #
3958: sub set_virtual_host_handler {
3959: my ($cmd, $tail, $socket) = @_;
3960:
3961: my $userinput ="$cmd:$tail";
3962:
3963: &Reply($client, &sethost($userinput)."\n", $userinput);
3964:
3965:
3966: return 1;
3967: }
1.247 albertel 3968: ®ister_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246 foxr 3969:
3970: # Process a request to exit:
3971: # - "bye" is sent to the client.
3972: # - The client socket is shutdown and closed.
3973: # - We indicate to the caller that we should exit.
3974: # Formal Parameters:
3975: # $cmd - The command that got us here.
3976: # $tail - Tail of the command (empty).
3977: # $client - Socket open on the tail.
3978: # Returns:
3979: # 0 - Indicating the program should exit!!
3980: #
3981: sub exit_handler {
3982: my ($cmd, $tail, $client) = @_;
3983:
3984: my $userinput = "$cmd:$tail";
3985:
3986: &logthis("Client $clientip ($clientname) hanging up: $userinput");
3987: &Reply($client, "bye\n", $userinput);
3988: $client->shutdown(2); # shutdown the socket forcibly.
3989: $client->close();
3990:
3991: return 0;
3992: }
1.248 foxr 3993: ®ister_handler("exit", \&exit_handler, 0,1,1);
3994: ®ister_handler("init", \&exit_handler, 0,1,1);
3995: ®ister_handler("quit", \&exit_handler, 0,1,1);
3996:
3997: # Determine if auto-enrollment is enabled.
3998: # Note that the original had what I believe to be a defect.
3999: # The original returned 0 if the requestor was not a registerd client.
4000: # It should return "refused".
4001: # Formal Parameters:
4002: # $cmd - The command that invoked us.
4003: # $tail - The tail of the command (Extra command parameters.
4004: # $client - The socket open on the client that issued the request.
4005: # Returns:
4006: # 1 - Indicating processing should continue.
4007: #
4008: sub enrollment_enabled_handler {
4009: my ($cmd, $tail, $client) = @_;
4010: my $userinput = $cmd.":".$tail; # For logging purposes.
4011:
4012:
4013: my $cdom = split(/:/, $tail); # Domain we're asking about.
4014: my $outcome = &localenroll::run($cdom);
4015: &Reply($client, "$outcome\n", $userinput);
4016:
4017: return 1;
4018: }
4019: ®ister_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
4020:
4021: # Get the official sections for which auto-enrollment is possible.
4022: # Since the admin people won't know about 'unofficial sections'
4023: # we cannot auto-enroll on them.
4024: # Formal Parameters:
4025: # $cmd - The command request that got us dispatched here.
4026: # $tail - The remainder of the request. In our case this
4027: # will be split into:
4028: # $coursecode - The course name from the admin point of view.
4029: # $cdom - The course's domain(?).
4030: # $client - Socket open on the client.
4031: # Returns:
4032: # 1 - Indiciting processing should continue.
4033: #
4034: sub get_sections_handler {
4035: my ($cmd, $tail, $client) = @_;
4036: my $userinput = "$cmd:$tail";
4037:
4038: my ($coursecode, $cdom) = split(/:/, $tail);
4039: my @secs = &localenroll::get_sections($coursecode,$cdom);
4040: my $seclist = &escape(join(':',@secs));
4041:
4042: &Reply($client, "$seclist\n", $userinput);
4043:
4044:
4045: return 1;
4046: }
4047: ®ister_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
4048:
4049: # Validate the owner of a new course section.
4050: #
4051: # Formal Parameters:
4052: # $cmd - Command that got us dispatched.
4053: # $tail - the remainder of the command. For us this consists of a
4054: # colon separated string containing:
4055: # $inst - Course Id from the institutions point of view.
4056: # $owner - Proposed owner of the course.
4057: # $cdom - Domain of the course (from the institutions
4058: # point of view?)..
4059: # $client - Socket open on the client.
4060: #
4061: # Returns:
4062: # 1 - Processing should continue.
4063: #
4064: sub validate_course_owner_handler {
4065: my ($cmd, $tail, $client) = @_;
4066: my $userinput = "$cmd:$tail";
4067: my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
4068:
4069: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
4070: &Reply($client, "$outcome\n", $userinput);
4071:
4072:
4073:
4074: return 1;
4075: }
4076: ®ister_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263 albertel 4077:
1.248 foxr 4078: #
4079: # Validate a course section in the official schedule of classes
4080: # from the institutions point of view (part of autoenrollment).
4081: #
4082: # Formal Parameters:
4083: # $cmd - The command request that got us dispatched.
4084: # $tail - The tail of the command. In this case,
4085: # this is a colon separated set of words that will be split
4086: # into:
4087: # $inst_course_id - The course/section id from the
4088: # institutions point of view.
4089: # $cdom - The domain from the institutions
4090: # point of view.
4091: # $client - Socket open on the client.
4092: # Returns:
4093: # 1 - Indicating processing should continue.
4094: #
4095: sub validate_course_section_handler {
4096: my ($cmd, $tail, $client) = @_;
4097: my $userinput = "$cmd:$tail";
4098: my ($inst_course_id, $cdom) = split(/:/, $tail);
4099:
4100: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
4101: &Reply($client, "$outcome\n", $userinput);
4102:
4103:
4104: return 1;
4105: }
4106: ®ister_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
4107:
4108: #
4109: # Create a password for a new auto-enrollment user.
4110: # I think/guess, this password allows access to the institutions
4111: # AIS class list server/services. Stuart can correct this comment
4112: # when he finds out how wrong I am.
4113: #
4114: # Formal Parameters:
4115: # $cmd - The command request that got us dispatched.
4116: # $tail - The tail of the command. In this case this is a colon separated
4117: # set of words that will be split into:
4118: # $authparam - An authentication parameter (username??).
4119: # $cdom - The domain of the course from the institution's
4120: # point of view.
4121: # $client - The socket open on the client.
4122: # Returns:
4123: # 1 - continue processing.
4124: #
4125: sub create_auto_enroll_password_handler {
4126: my ($cmd, $tail, $client) = @_;
4127: my $userinput = "$cmd:$tail";
4128:
4129: my ($authparam, $cdom) = split(/:/, $userinput);
4130:
4131: my ($create_passwd,$authchk);
4132: ($authparam,
4133: $create_passwd,
4134: $authchk) = &localenroll::create_password($authparam,$cdom);
4135:
4136: &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
4137: $userinput);
4138:
4139:
4140: return 1;
4141: }
4142: ®ister_handler("autocreatepassword", \&create_auto_enroll_password_handler,
4143: 0, 1, 0);
4144:
4145: # Retrieve and remove temporary files created by/during autoenrollment.
4146: #
4147: # Formal Parameters:
4148: # $cmd - The command that got us dispatched.
4149: # $tail - The tail of the command. In our case this is a colon
4150: # separated list that will be split into:
4151: # $filename - The name of the file to remove.
4152: # The filename is given as a path relative to
4153: # the LonCAPA temp file directory.
4154: # $client - Socket open on the client.
4155: #
4156: # Returns:
4157: # 1 - Continue processing.
4158: sub retrieve_auto_file_handler {
4159: my ($cmd, $tail, $client) = @_;
4160: my $userinput = "cmd:$tail";
4161:
4162: my ($filename) = split(/:/, $tail);
4163:
4164: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
4165: if ( (-e $source) && ($filename ne '') ) {
4166: my $reply = '';
4167: if (open(my $fh,$source)) {
4168: while (<$fh>) {
4169: chomp($_);
4170: $_ =~ s/^\s+//g;
4171: $_ =~ s/\s+$//g;
4172: $reply .= $_;
4173: }
4174: close($fh);
4175: &Reply($client, &escape($reply)."\n", $userinput);
4176:
4177: # Does this have to be uncommented??!? (RF).
4178: #
4179: # unlink($source);
4180: } else {
4181: &Failure($client, "error\n", $userinput);
4182: }
4183: } else {
4184: &Failure($client, "error\n", $userinput);
4185: }
4186:
4187:
4188: return 1;
4189: }
4190: ®ister_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
4191:
4192: #
4193: # Read and retrieve institutional code format (for support form).
4194: # Formal Parameters:
4195: # $cmd - Command that dispatched us.
4196: # $tail - Tail of the command. In this case it conatins
4197: # the course domain and the coursename.
4198: # $client - Socket open on the client.
4199: # Returns:
4200: # 1 - Continue processing.
4201: #
4202: sub get_institutional_code_format_handler {
4203: my ($cmd, $tail, $client) = @_;
4204: my $userinput = "$cmd:$tail";
4205:
4206: my $reply;
4207: my($cdom,$course) = split(/:/,$tail);
4208: my @pairs = split/\&/,$course;
4209: my %instcodes = ();
4210: my %codes = ();
4211: my @codetitles = ();
4212: my %cat_titles = ();
4213: my %cat_order = ();
4214: foreach (@pairs) {
4215: my ($key,$value) = split/=/,$_;
4216: $instcodes{&unescape($key)} = &unescape($value);
4217: }
4218: my $formatreply = &localenroll::instcode_format($cdom,
4219: \%instcodes,
4220: \%codes,
4221: \@codetitles,
4222: \%cat_titles,
4223: \%cat_order);
4224: if ($formatreply eq 'ok') {
4225: my $codes_str = &hash2str(%codes);
4226: my $codetitles_str = &array2str(@codetitles);
4227: my $cat_titles_str = &hash2str(%cat_titles);
4228: my $cat_order_str = &hash2str(%cat_order);
4229: &Reply($client,
4230: $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
4231: .$cat_order_str."\n",
4232: $userinput);
4233: } else {
4234: # this else branch added by RF since if not ok, lonc will
4235: # hang waiting on reply until timeout.
4236: #
4237: &Reply($client, "format_error\n", $userinput);
4238: }
4239:
4240: return 1;
4241: }
1.265 albertel 4242: ®ister_handler("autoinstcodeformat",
4243: \&get_institutional_code_format_handler,0,1,0);
1.246 foxr 4244:
1.265 albertel 4245: #
4246: # Gets a student's photo to exist (in the correct image type) in the user's
4247: # directory.
4248: # Formal Parameters:
4249: # $cmd - The command request that got us dispatched.
4250: # $tail - A colon separated set of words that will be split into:
4251: # $domain - student's domain
4252: # $uname - student username
4253: # $type - image type desired
4254: # $client - The socket open on the client.
4255: # Returns:
4256: # 1 - continue processing.
4257: sub student_photo_handler {
4258: my ($cmd, $tail, $client) = @_;
4259: my ($domain,$uname,$type) = split(/:/, $tail);
4260:
4261: my $path=&propath($domain,$uname).
4262: '/userfiles/internal/studentphoto.'.$type;
4263: if (-e $path) {
4264: &Reply($client,"ok\n","$cmd:$tail");
4265: return 1;
4266: }
4267: &mkpath($path);
4268: my $file=&localstudentphoto::fetch($domain,$uname);
4269: if (!$file) {
4270: &Failure($client,"unavailable\n","$cmd:$tail");
4271: return 1;
4272: }
4273: if (!-e $path) { &convert_photo($file,$path); }
4274: if (-e $path) {
4275: &Reply($client,"ok\n","$cmd:$tail");
4276: return 1;
4277: }
4278: &Failure($client,"unable_to_convert\n","$cmd:$tail");
4279: return 1;
4280: }
4281: ®ister_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246 foxr 4282:
1.264 albertel 4283: # mkpath makes all directories for a file, expects an absolute path with a
4284: # file or a trailing / if just a dir is passed
4285: # returns 1 on success 0 on failure
4286: sub mkpath {
4287: my ($file)=@_;
4288: my @parts=split(/\//,$file,-1);
4289: my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
4290: for (my $i=3;$i<= ($#parts-1);$i++) {
1.265 albertel 4291: $now.='/'.$parts[$i];
1.264 albertel 4292: if (!-e $now) {
4293: if (!mkdir($now,0770)) { return 0; }
4294: }
4295: }
4296: return 1;
4297: }
4298:
1.207 foxr 4299: #---------------------------------------------------------------
4300: #
4301: # Getting, decoding and dispatching requests:
4302: #
4303: #
4304: # Get a Request:
4305: # Gets a Request message from the client. The transaction
4306: # is defined as a 'line' of text. We remove the new line
4307: # from the text line.
1.226 foxr 4308: #
1.211 albertel 4309: sub get_request {
1.207 foxr 4310: my $input = <$client>;
4311: chomp($input);
1.226 foxr 4312:
1.234 foxr 4313: &Debug("get_request: Request = $input\n");
1.207 foxr 4314:
4315: &status('Processing '.$clientname.':'.$input);
4316:
4317: return $input;
4318: }
1.212 foxr 4319: #---------------------------------------------------------------
4320: #
4321: # Process a request. This sub should shrink as each action
4322: # gets farmed out into a separat sub that is registered
4323: # with the dispatch hash.
4324: #
4325: # Parameters:
4326: # user_input - The request received from the client (lonc).
4327: # Returns:
4328: # true to keep processing, false if caller should exit.
4329: #
4330: sub process_request {
4331: my ($userinput) = @_; # Easier for now to break style than to
4332: # fix all the userinput -> user_input.
4333: my $wasenc = 0; # True if request was encrypted.
4334: # ------------------------------------------------------------ See if encrypted
4335: if ($userinput =~ /^enc/) {
4336: $userinput = decipher($userinput);
4337: $wasenc=1;
4338: if(!$userinput) { # Cipher not defined.
1.251 foxr 4339: &Failure($client, "error: Encrypted data without negotated key\n");
1.212 foxr 4340: return 0;
4341: }
4342: }
4343: Debug("process_request: $userinput\n");
4344:
1.213 foxr 4345: #
4346: # The 'correct way' to add a command to lond is now to
4347: # write a sub to execute it and Add it to the command dispatch
4348: # hash via a call to register_handler.. The comments to that
4349: # sub should give you enough to go on to show how to do this
4350: # along with the examples that are building up as this code
4351: # is getting refactored. Until all branches of the
4352: # if/elseif monster below have been factored out into
4353: # separate procesor subs, if the dispatch hash is missing
4354: # the command keyword, we will fall through to the remainder
4355: # of the if/else chain below in order to keep this thing in
4356: # working order throughout the transmogrification.
4357:
4358: my ($command, $tail) = split(/:/, $userinput, 2);
4359: chomp($command);
4360: chomp($tail);
4361: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
1.214 foxr 4362: $command =~ s/(\r)//; # And this too for parameterless commands.
4363: if(!$tail) {
4364: $tail =""; # defined but blank.
4365: }
1.213 foxr 4366:
4367: &Debug("Command received: $command, encoded = $wasenc");
4368:
4369: if(defined $Dispatcher{$command}) {
4370:
4371: my $dispatch_info = $Dispatcher{$command};
4372: my $handler = $$dispatch_info[0];
4373: my $need_encode = $$dispatch_info[1];
4374: my $client_types = $$dispatch_info[2];
4375: Debug("Matched dispatch hash: mustencode: $need_encode "
4376: ."ClientType $client_types");
4377:
4378: # Validate the request:
4379:
4380: my $ok = 1;
4381: my $requesterprivs = 0;
4382: if(&isClient()) {
4383: $requesterprivs |= $CLIENT_OK;
4384: }
4385: if(&isManager()) {
4386: $requesterprivs |= $MANAGER_OK;
4387: }
4388: if($need_encode && (!$wasenc)) {
4389: Debug("Must encode but wasn't: $need_encode $wasenc");
4390: $ok = 0;
4391: }
4392: if(($client_types & $requesterprivs) == 0) {
4393: Debug("Client not privileged to do this operation");
4394: $ok = 0;
4395: }
4396:
4397: if($ok) {
4398: Debug("Dispatching to handler $command $tail");
4399: my $keep_going = &$handler($command, $tail, $client);
4400: return $keep_going;
4401: } else {
4402: Debug("Refusing to dispatch because client did not match requirements");
4403: Failure($client, "refused\n", $userinput);
4404: return 1;
4405: }
4406:
4407: }
4408:
1.262 foxr 4409: print $client "unknown_cmd\n";
1.212 foxr 4410: # -------------------------------------------------------------------- complete
4411: Debug("process_request - returning 1");
4412: return 1;
4413: }
1.207 foxr 4414: #
4415: # Decipher encoded traffic
4416: # Parameters:
4417: # input - Encoded data.
4418: # Returns:
4419: # Decoded data or undef if encryption key was not yet negotiated.
4420: # Implicit input:
4421: # cipher - This global holds the negotiated encryption key.
4422: #
1.211 albertel 4423: sub decipher {
1.207 foxr 4424: my ($input) = @_;
4425: my $output = '';
1.212 foxr 4426:
4427:
1.207 foxr 4428: if($cipher) {
4429: my($enc, $enclength, $encinput) = split(/:/, $input);
4430: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
4431: $output .=
4432: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
4433: }
4434: return substr($output, 0, $enclength);
4435: } else {
4436: return undef;
4437: }
4438: }
4439:
4440: #
4441: # Register a command processor. This function is invoked to register a sub
4442: # to process a request. Once registered, the ProcessRequest sub can automatically
4443: # dispatch requests to an appropriate sub, and do the top level validity checking
4444: # as well:
4445: # - Is the keyword recognized.
4446: # - Is the proper client type attempting the request.
4447: # - Is the request encrypted if it has to be.
4448: # Parameters:
4449: # $request_name - Name of the request being registered.
4450: # This is the command request that will match
4451: # against the hash keywords to lookup the information
4452: # associated with the dispatch information.
4453: # $procedure - Reference to a sub to call to process the request.
4454: # All subs get called as follows:
4455: # Procedure($cmd, $tail, $replyfd, $key)
4456: # $cmd - the actual keyword that invoked us.
4457: # $tail - the tail of the request that invoked us.
4458: # $replyfd- File descriptor connected to the client
4459: # $must_encode - True if the request must be encoded to be good.
4460: # $client_ok - True if it's ok for a client to request this.
4461: # $manager_ok - True if it's ok for a manager to request this.
4462: # Side effects:
4463: # - On success, the Dispatcher hash has an entry added for the key $RequestName
4464: # - On failure, the program will die as it's a bad internal bug to try to
4465: # register a duplicate command handler.
4466: #
1.211 albertel 4467: sub register_handler {
1.212 foxr 4468: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
1.207 foxr 4469:
4470: # Don't allow duplication#
4471:
4472: if (defined $Dispatcher{$request_name}) {
4473: die "Attempting to define a duplicate request handler for $request_name\n";
4474: }
4475: # Build the client type mask:
4476:
4477: my $client_type_mask = 0;
4478: if($client_ok) {
4479: $client_type_mask |= $CLIENT_OK;
4480: }
4481: if($manager_ok) {
4482: $client_type_mask |= $MANAGER_OK;
4483: }
4484:
4485: # Enter the hash:
4486:
4487: my @entry = ($procedure, $must_encode, $client_type_mask);
4488:
4489: $Dispatcher{$request_name} = \@entry;
4490:
4491: }
4492:
4493:
4494: #------------------------------------------------------------------
4495:
4496:
4497:
4498:
1.141 foxr 4499: #
1.96 foxr 4500: # Convert an error return code from lcpasswd to a string value.
4501: #
4502: sub lcpasswdstrerror {
4503: my $ErrorCode = shift;
1.97 foxr 4504: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 4505: return "lcpasswd Unrecognized error return value ".$ErrorCode;
4506: } else {
1.98 foxr 4507: return $passwderrors[$ErrorCode];
1.96 foxr 4508: }
4509: }
4510:
1.97 foxr 4511: #
4512: # Convert an error return code from lcuseradd to a string value:
4513: #
4514: sub lcuseraddstrerror {
4515: my $ErrorCode = shift;
4516: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
4517: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
4518: } else {
1.98 foxr 4519: return $adderrors[$ErrorCode];
1.97 foxr 4520: }
4521: }
4522:
1.23 harris41 4523: # grabs exception and records it to log before exiting
4524: sub catchexception {
1.27 albertel 4525: my ($error)=@_;
1.25 www 4526: $SIG{'QUIT'}='DEFAULT';
4527: $SIG{__DIE__}='DEFAULT';
1.165 albertel 4528: &status("Catching exception");
1.190 albertel 4529: &logthis("<font color='red'>CRITICAL: "
1.134 albertel 4530: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27 albertel 4531: ."a crash with this error msg->[$error]</font>");
1.57 www 4532: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 4533: if ($client) { print $client "error: $error\n"; }
1.59 www 4534: $server->close();
1.27 albertel 4535: die($error);
1.23 harris41 4536: }
1.63 www 4537: sub timeout {
1.165 albertel 4538: &status("Handling Timeout");
1.190 albertel 4539: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63 www 4540: &catchexception('Timeout');
4541: }
1.22 harris41 4542: # -------------------------------- Set signal handlers to record abnormal exits
4543:
1.226 foxr 4544:
1.22 harris41 4545: $SIG{'QUIT'}=\&catchexception;
4546: $SIG{__DIE__}=\&catchexception;
4547:
1.81 matthew 4548: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 4549: &status("Read loncapa.conf and loncapa_apache.conf");
4550: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 4551: %perlvar=%{$perlvarref};
1.80 harris41 4552: undef $perlvarref;
1.19 www 4553:
1.35 harris41 4554: # ----------------------------- Make sure this process is running from user=www
4555: my $wwwid=getpwnam('www');
4556: if ($wwwid!=$<) {
1.134 albertel 4557: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
4558: my $subj="LON: $currenthostid User ID mismatch";
1.37 harris41 4559: system("echo 'User ID mismatch. lond must be run as user www.' |\
1.35 harris41 4560: mailto $emailto -s '$subj' > /dev/null");
4561: exit 1;
4562: }
4563:
1.19 www 4564: # --------------------------------------------- Check if other instance running
4565:
4566: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
4567:
4568: if (-e $pidfile) {
4569: my $lfh=IO::File->new("$pidfile");
4570: my $pide=<$lfh>;
4571: chomp($pide);
1.29 harris41 4572: if (kill 0 => $pide) { die "already running"; }
1.19 www 4573: }
1.1 albertel 4574:
4575: # ------------------------------------------------------------- Read hosts file
4576:
4577:
4578:
4579: # establish SERVER socket, bind and listen.
4580: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
4581: Type => SOCK_STREAM,
4582: Proto => 'tcp',
4583: Reuse => 1,
4584: Listen => 10 )
1.29 harris41 4585: or die "making socket: $@\n";
1.1 albertel 4586:
4587: # --------------------------------------------------------- Do global variables
4588:
4589: # global variables
4590:
1.134 albertel 4591: my %children = (); # keys are current child process IDs
1.1 albertel 4592:
4593: sub REAPER { # takes care of dead children
4594: $SIG{CHLD} = \&REAPER;
1.165 albertel 4595: &status("Handling child death");
1.178 foxr 4596: my $pid;
4597: do {
4598: $pid = waitpid(-1,&WNOHANG());
4599: if (defined($children{$pid})) {
4600: &logthis("Child $pid died");
4601: delete($children{$pid});
1.183 albertel 4602: } elsif ($pid > 0) {
1.178 foxr 4603: &logthis("Unknown Child $pid died");
4604: }
4605: } while ( $pid > 0 );
4606: foreach my $child (keys(%children)) {
4607: $pid = waitpid($child,&WNOHANG());
4608: if ($pid > 0) {
4609: &logthis("Child $child - $pid looks like we missed it's death");
4610: delete($children{$pid});
4611: }
1.176 albertel 4612: }
1.165 albertel 4613: &status("Finished Handling child death");
1.1 albertel 4614: }
4615:
4616: sub HUNTSMAN { # signal handler for SIGINT
1.165 albertel 4617: &status("Killing children (INT)");
1.1 albertel 4618: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
4619: kill 'INT' => keys %children;
1.59 www 4620: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 4621: my $execdir=$perlvar{'lonDaemons'};
4622: unlink("$execdir/logs/lond.pid");
1.190 albertel 4623: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165 albertel 4624: &status("Done killing children");
1.1 albertel 4625: exit; # clean up with dignity
4626: }
4627:
4628: sub HUPSMAN { # signal handler for SIGHUP
4629: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.165 albertel 4630: &status("Killing children for restart (HUP)");
1.1 albertel 4631: kill 'INT' => keys %children;
1.59 www 4632: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190 albertel 4633: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134 albertel 4634: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 4635: unlink("$execdir/logs/lond.pid");
1.165 albertel 4636: &status("Restarting self (HUP)");
1.1 albertel 4637: exec("$execdir/lond"); # here we go again
4638: }
4639:
1.144 foxr 4640: #
1.148 foxr 4641: # Kill off hashes that describe the host table prior to re-reading it.
4642: # Hashes affected are:
1.200 matthew 4643: # %hostid, %hostdom %hostip %hostdns.
1.148 foxr 4644: #
4645: sub KillHostHashes {
4646: foreach my $key (keys %hostid) {
4647: delete $hostid{$key};
4648: }
4649: foreach my $key (keys %hostdom) {
4650: delete $hostdom{$key};
4651: }
4652: foreach my $key (keys %hostip) {
4653: delete $hostip{$key};
4654: }
1.200 matthew 4655: foreach my $key (keys %hostdns) {
4656: delete $hostdns{$key};
4657: }
1.148 foxr 4658: }
4659: #
4660: # Read in the host table from file and distribute it into the various hashes:
4661: #
4662: # - %hostid - Indexed by IP, the loncapa hostname.
4663: # - %hostdom - Indexed by loncapa hostname, the domain.
4664: # - %hostip - Indexed by hostid, the Ip address of the host.
4665: sub ReadHostTable {
4666:
4667: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200 matthew 4668: my $myloncapaname = $perlvar{'lonHostID'};
4669: Debug("My loncapa name is : $myloncapaname");
1.296 albertel 4670: my %name_to_ip;
1.148 foxr 4671: while (my $configline=<CONFIG>) {
1.277 albertel 4672: if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
4673: my ($id,$domain,$role,$name)=split(/:/,$configline);
4674: $name=~s/\s//g;
1.296 albertel 4675: my $ip;
4676: if (!exists($name_to_ip{$name})) {
4677: $ip = gethostbyname($name);
4678: if (!$ip || length($ip) ne 4) {
4679: &logthis("Skipping host $id name $name no IP found\n");
4680: next;
4681: }
4682: $ip=inet_ntoa($ip);
4683: $name_to_ip{$name} = $ip;
4684: } else {
4685: $ip = $name_to_ip{$name};
1.277 albertel 4686: }
1.200 matthew 4687: $hostid{$ip}=$id; # LonCAPA name of host by IP.
4688: $hostdom{$id}=$domain; # LonCAPA domain name of host.
1.277 albertel 4689: $hostip{$id}=$ip; # IP address of host.
1.200 matthew 4690: $hostdns{$name} = $id; # LonCAPA name of host by DNS.
4691:
4692: if ($id eq $perlvar{'lonHostID'}) {
4693: Debug("Found me in the host table: $name");
4694: $thisserver=$name;
4695: }
1.178 foxr 4696: }
1.148 foxr 4697: }
4698: close(CONFIG);
4699: }
4700: #
4701: # Reload the Apache daemon's state.
1.150 foxr 4702: # This is done by invoking /home/httpd/perl/apachereload
4703: # a setuid perl script that can be root for us to do this job.
1.148 foxr 4704: #
4705: sub ReloadApache {
1.150 foxr 4706: my $execdir = $perlvar{'lonDaemons'};
4707: my $script = $execdir."/apachereload";
4708: system($script);
1.148 foxr 4709: }
4710:
4711: #
1.144 foxr 4712: # Called in response to a USR2 signal.
4713: # - Reread hosts.tab
4714: # - All children connected to hosts that were removed from hosts.tab
4715: # are killed via SIGINT
4716: # - All children connected to previously existing hosts are sent SIGUSR1
4717: # - Our internal hosts hash is updated to reflect the new contents of
4718: # hosts.tab causing connections from hosts added to hosts.tab to
4719: # now be honored.
4720: #
4721: sub UpdateHosts {
1.165 albertel 4722: &status("Reload hosts.tab");
1.147 foxr 4723: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 4724: #
4725: # The %children hash has the set of IP's we currently have children
4726: # on. These need to be matched against records in the hosts.tab
4727: # Any ip's no longer in the table get killed off they correspond to
4728: # either dropped or changed hosts. Note that the re-read of the table
4729: # will take care of new and changed hosts as connections come into being.
4730:
4731:
4732: KillHostHashes;
4733: ReadHostTable;
4734:
4735: foreach my $child (keys %children) {
4736: my $childip = $children{$child};
4737: if(!$hostid{$childip}) {
1.149 foxr 4738: logthis('<font color="blue"> UpdateHosts killing child '
4739: ." $child for ip $childip </font>");
1.148 foxr 4740: kill('INT', $child);
1.149 foxr 4741: } else {
4742: logthis('<font color="green"> keeping child for ip '
4743: ." $childip (pid=$child) </font>");
1.148 foxr 4744: }
4745: }
4746: ReloadApache;
1.165 albertel 4747: &status("Finished reloading hosts.tab");
1.144 foxr 4748: }
4749:
1.148 foxr 4750:
1.57 www 4751: sub checkchildren {
1.165 albertel 4752: &status("Checking on the children (sending signals)");
1.57 www 4753: &initnewstatus();
4754: &logstatus();
4755: &logthis('Going to check on the children');
1.134 albertel 4756: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 4757: foreach (sort keys %children) {
1.221 albertel 4758: #sleep 1;
1.57 www 4759: unless (kill 'USR1' => $_) {
4760: &logthis ('Child '.$_.' is dead');
4761: &logstatus($$.' is dead');
1.221 albertel 4762: delete($children{$_});
1.57 www 4763: }
1.61 harris41 4764: }
1.63 www 4765: sleep 5;
1.212 foxr 4766: $SIG{ALRM} = sub { Debug("timeout");
4767: die "timeout"; };
1.113 albertel 4768: $SIG{__DIE__} = 'DEFAULT';
1.165 albertel 4769: &status("Checking on the children (waiting for reports)");
1.63 www 4770: foreach (sort keys %children) {
4771: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 4772: eval {
4773: alarm(300);
1.63 www 4774: &logthis('Child '.$_.' did not respond');
1.67 albertel 4775: kill 9 => $_;
1.131 albertel 4776: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
4777: #$subj="LON: $currenthostid killed lond process $_";
4778: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
4779: #$execdir=$perlvar{'lonDaemons'};
4780: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221 albertel 4781: delete($children{$_});
1.113 albertel 4782: alarm(0);
4783: }
1.63 www 4784: }
4785: }
1.113 albertel 4786: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 4787: $SIG{__DIE__} = \&catchexception;
1.165 albertel 4788: &status("Finished checking children");
1.221 albertel 4789: &logthis('Finished Checking children');
1.57 www 4790: }
4791:
1.1 albertel 4792: # --------------------------------------------------------------------- Logging
4793:
4794: sub logthis {
4795: my $message=shift;
4796: my $execdir=$perlvar{'lonDaemons'};
4797: my $fh=IO::File->new(">>$execdir/logs/lond.log");
4798: my $now=time;
4799: my $local=localtime($now);
1.58 www 4800: $lastlog=$local.': '.$message;
1.1 albertel 4801: print $fh "$local ($$): $message\n";
4802: }
4803:
1.77 foxr 4804: # ------------------------- Conditional log if $DEBUG true.
4805: sub Debug {
4806: my $message = shift;
4807: if($DEBUG) {
4808: &logthis($message);
4809: }
4810: }
1.161 foxr 4811:
4812: #
4813: # Sub to do replies to client.. this gives a hook for some
4814: # debug tracing too:
4815: # Parameters:
4816: # fd - File open on client.
4817: # reply - Text to send to client.
4818: # request - Original request from client.
4819: #
4820: sub Reply {
1.192 foxr 4821: my ($fd, $reply, $request) = @_;
1.161 foxr 4822: print $fd $reply;
4823: Debug("Request was $request Reply was $reply");
4824:
1.212 foxr 4825: $Transactions++;
4826: }
4827:
4828:
4829: #
4830: # Sub to report a failure.
4831: # This function:
4832: # - Increments the failure statistic counters.
4833: # - Invokes Reply to send the error message to the client.
4834: # Parameters:
4835: # fd - File descriptor open on the client
4836: # reply - Reply text to emit.
4837: # request - The original request message (used by Reply
4838: # to debug if that's enabled.
4839: # Implicit outputs:
4840: # $Failures- The number of failures is incremented.
4841: # Reply (invoked here) sends a message to the
4842: # client:
4843: #
4844: sub Failure {
4845: my $fd = shift;
4846: my $reply = shift;
4847: my $request = shift;
4848:
4849: $Failures++;
4850: Reply($fd, $reply, $request); # That's simple eh?
1.161 foxr 4851: }
1.57 www 4852: # ------------------------------------------------------------------ Log status
4853:
4854: sub logstatus {
1.178 foxr 4855: &status("Doing logging");
4856: my $docdir=$perlvar{'lonDocRoot'};
4857: {
4858: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200 matthew 4859: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178 foxr 4860: $fh->close();
4861: }
1.221 albertel 4862: &status("Finished $$.txt");
4863: {
4864: open(LOG,">>$docdir/lon-status/londstatus.txt");
4865: flock(LOG,LOCK_EX);
4866: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
4867: .$status."\t".$lastlog."\t $keymode\n";
1.275 albertel 4868: flock(LOG,LOCK_UN);
1.221 albertel 4869: close(LOG);
4870: }
1.178 foxr 4871: &status("Finished logging");
1.57 www 4872: }
4873:
4874: sub initnewstatus {
4875: my $docdir=$perlvar{'lonDocRoot'};
4876: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
4877: my $now=time;
4878: my $local=localtime($now);
4879: print $fh "LOND status $local - parent $$\n\n";
1.64 www 4880: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 4881: while (my $filename=readdir(DIR)) {
1.64 www 4882: unlink("$docdir/lon-status/londchld/$filename");
4883: }
4884: closedir(DIR);
1.57 www 4885: }
4886:
4887: # -------------------------------------------------------------- Status setting
4888:
4889: sub status {
4890: my $what=shift;
4891: my $now=time;
4892: my $local=localtime($now);
1.178 foxr 4893: $status=$local.': '.$what;
4894: $0='lond: '.$what.' '.$local;
1.57 www 4895: }
1.11 www 4896:
4897: # -------------------------------------------------------- Escape Special Chars
4898:
4899: sub escape {
4900: my $str=shift;
4901: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
4902: return $str;
4903: }
4904:
4905: # ----------------------------------------------------- Un-Escape Special Chars
4906:
4907: sub unescape {
4908: my $str=shift;
4909: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
4910: return $str;
4911: }
4912:
1.1 albertel 4913: # ----------------------------------------------------------- Send USR1 to lonc
4914:
4915: sub reconlonc {
4916: my $peerfile=shift;
4917: &logthis("Trying to reconnect for $peerfile");
4918: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
4919: if (my $fh=IO::File->new("$loncfile")) {
4920: my $loncpid=<$fh>;
4921: chomp($loncpid);
4922: if (kill 0 => $loncpid) {
4923: &logthis("lonc at pid $loncpid responding, sending USR1");
4924: kill USR1 => $loncpid;
4925: } else {
1.9 www 4926: &logthis(
1.190 albertel 4927: "<font color='red'>CRITICAL: "
1.9 www 4928: ."lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 4929: }
4930: } else {
1.190 albertel 4931: &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1 albertel 4932: }
4933: }
4934:
4935: # -------------------------------------------------- Non-critical communication
1.11 www 4936:
1.1 albertel 4937: sub subreply {
4938: my ($cmd,$server)=@_;
4939: my $peerfile="$perlvar{'lonSockDir'}/$server";
4940: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
4941: Type => SOCK_STREAM,
4942: Timeout => 10)
4943: or return "con_lost";
4944: print $sclient "$cmd\n";
4945: my $answer=<$sclient>;
4946: chomp($answer);
4947: if (!$answer) { $answer="con_lost"; }
4948: return $answer;
4949: }
4950:
4951: sub reply {
4952: my ($cmd,$server)=@_;
4953: my $answer;
1.115 albertel 4954: if ($server ne $currenthostid) {
1.1 albertel 4955: $answer=subreply($cmd,$server);
4956: if ($answer eq 'con_lost') {
4957: $answer=subreply("ping",$server);
4958: if ($answer ne $server) {
1.115 albertel 4959: &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1 albertel 4960: &reconlonc("$perlvar{'lonSockDir'}/$server");
4961: }
4962: $answer=subreply($cmd,$server);
4963: }
4964: } else {
4965: $answer='self_reply';
4966: }
4967: return $answer;
4968: }
4969:
1.13 www 4970: # -------------------------------------------------------------- Talk to lonsql
4971:
1.234 foxr 4972: sub sql_reply {
1.12 harris41 4973: my ($cmd)=@_;
1.234 foxr 4974: my $answer=&sub_sql_reply($cmd);
4975: if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12 harris41 4976: return $answer;
4977: }
4978:
1.234 foxr 4979: sub sub_sql_reply {
1.12 harris41 4980: my ($cmd)=@_;
4981: my $unixsock="mysqlsock";
4982: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
4983: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
4984: Type => SOCK_STREAM,
4985: Timeout => 10)
4986: or return "con_lost";
4987: print $sclient "$cmd\n";
4988: my $answer=<$sclient>;
4989: chomp($answer);
4990: if (!$answer) { $answer="con_lost"; }
4991: return $answer;
4992: }
4993:
1.1 albertel 4994: # -------------------------------------------- Return path to profile directory
1.11 www 4995:
1.1 albertel 4996: sub propath {
4997: my ($udom,$uname)=@_;
4998: $udom=~s/\W//g;
4999: $uname=~s/\W//g;
1.16 www 5000: my $subdir=$uname.'__';
1.1 albertel 5001: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5002: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
5003: return $proname;
5004: }
5005:
5006: # --------------------------------------- Is this the home server of an author?
1.11 www 5007:
1.1 albertel 5008: sub ishome {
5009: my $author=shift;
5010: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
5011: my ($udom,$uname)=split(/\//,$author);
5012: my $proname=propath($udom,$uname);
5013: if (-e $proname) {
5014: return 'owner';
5015: } else {
5016: return 'not_owner';
5017: }
5018: }
5019:
5020: # ======================================================= Continue main program
5021: # ---------------------------------------------------- Fork once and dissociate
5022:
1.134 albertel 5023: my $fpid=fork;
1.1 albertel 5024: exit if $fpid;
1.29 harris41 5025: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 5026:
1.29 harris41 5027: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 5028:
5029: # ------------------------------------------------------- Write our PID on disk
5030:
1.134 albertel 5031: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 5032: open (PIDSAVE,">$execdir/logs/lond.pid");
5033: print PIDSAVE "$$\n";
5034: close(PIDSAVE);
1.190 albertel 5035: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57 www 5036: &status('Starting');
1.1 albertel 5037:
1.106 foxr 5038:
1.1 albertel 5039:
5040: # ----------------------------------------------------- Install signal handlers
5041:
1.57 www 5042:
1.1 albertel 5043: $SIG{CHLD} = \&REAPER;
5044: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
5045: $SIG{HUP} = \&HUPSMAN;
1.57 www 5046: $SIG{USR1} = \&checkchildren;
1.144 foxr 5047: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 5048:
1.148 foxr 5049: # Read the host hashes:
5050:
5051: ReadHostTable;
1.106 foxr 5052:
1.286 albertel 5053: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
5054:
1.106 foxr 5055: # --------------------------------------------------------------
5056: # Accept connections. When a connection comes in, it is validated
5057: # and if good, a child process is created to process transactions
5058: # along the connection.
5059:
1.1 albertel 5060: while (1) {
1.165 albertel 5061: &status('Starting accept');
1.106 foxr 5062: $client = $server->accept() or next;
1.165 albertel 5063: &status('Accepted '.$client.' off to spawn');
1.106 foxr 5064: make_new_child($client);
1.165 albertel 5065: &status('Finished spawning');
1.1 albertel 5066: }
5067:
1.212 foxr 5068: sub make_new_child {
5069: my $pid;
5070: # my $cipher; # Now global
5071: my $sigset;
1.178 foxr 5072:
1.212 foxr 5073: $client = shift;
5074: &status('Starting new child '.$client);
5075: &logthis('<font color="green"> Attempting to start child ('.$client.
5076: ")</font>");
5077: # block signal for fork
5078: $sigset = POSIX::SigSet->new(SIGINT);
5079: sigprocmask(SIG_BLOCK, $sigset)
5080: or die "Can't block SIGINT for fork: $!\n";
1.178 foxr 5081:
1.212 foxr 5082: die "fork: $!" unless defined ($pid = fork);
1.178 foxr 5083:
1.212 foxr 5084: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
5085: # connection liveness.
1.178 foxr 5086:
1.212 foxr 5087: #
5088: # Figure out who we're talking to so we can record the peer in
5089: # the pid hash.
5090: #
5091: my $caller = getpeername($client);
5092: my ($port,$iaddr);
5093: if (defined($caller) && length($caller) > 0) {
5094: ($port,$iaddr)=unpack_sockaddr_in($caller);
5095: } else {
5096: &logthis("Unable to determine who caller was, getpeername returned nothing");
5097: }
5098: if (defined($iaddr)) {
5099: $clientip = inet_ntoa($iaddr);
5100: Debug("Connected with $clientip");
5101: } else {
5102: &logthis("Unable to determine clientip");
5103: $clientip='Unavailable';
5104: }
5105:
5106: if ($pid) {
5107: # Parent records the child's birth and returns.
5108: sigprocmask(SIG_UNBLOCK, $sigset)
5109: or die "Can't unblock SIGINT for fork: $!\n";
5110: $children{$pid} = $clientip;
5111: &status('Started child '.$pid);
5112: return;
5113: } else {
5114: # Child can *not* return from this subroutine.
5115: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
5116: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
5117: #don't get intercepted
5118: $SIG{USR1}= \&logstatus;
5119: $SIG{ALRM}= \&timeout;
5120: $lastlog='Forked ';
5121: $status='Forked';
1.178 foxr 5122:
1.212 foxr 5123: # unblock signals
5124: sigprocmask(SIG_UNBLOCK, $sigset)
5125: or die "Can't unblock SIGINT for fork: $!\n";
1.178 foxr 5126:
1.212 foxr 5127: # my $tmpsnum=0; # Now global
5128: #---------------------------------------------------- kerberos 5 initialization
5129: &Authen::Krb5::init_context();
1.297 raeburn 5130: unless (($dist eq 'fedora4') || ($dist eq 'suse9.3')) {
1.286 albertel 5131: &Authen::Krb5::init_ets();
5132: }
1.209 albertel 5133:
1.212 foxr 5134: &status('Accepted connection');
5135: # =============================================================================
5136: # do something with the connection
5137: # -----------------------------------------------------------------------------
5138: # see if we know client and 'check' for spoof IP by ineffective challenge
1.178 foxr 5139:
1.212 foxr 5140: ReadManagerTable; # May also be a manager!!
5141:
1.278 albertel 5142: my $outsideip=$clientip;
5143: if ($clientip eq '127.0.0.1') {
5144: $outsideip=$hostip{$perlvar{'lonHostID'}};
5145: }
5146:
5147: my $clientrec=($hostid{$outsideip} ne undef);
5148: my $ismanager=($managers{$outsideip} ne undef);
1.212 foxr 5149: $clientname = "[unknonwn]";
5150: if($clientrec) { # Establish client type.
5151: $ConnectionType = "client";
1.278 albertel 5152: $clientname = $hostid{$outsideip};
1.212 foxr 5153: if($ismanager) {
5154: $ConnectionType = "both";
5155: }
5156: } else {
5157: $ConnectionType = "manager";
1.278 albertel 5158: $clientname = $managers{$outsideip};
1.212 foxr 5159: }
5160: my $clientok;
1.178 foxr 5161:
1.212 foxr 5162: if ($clientrec || $ismanager) {
5163: &status("Waiting for init from $clientip $clientname");
5164: &logthis('<font color="yellow">INFO: Connection, '.
5165: $clientip.
5166: " ($clientname) connection type = $ConnectionType </font>" );
5167: &status("Connecting $clientip ($clientname))");
5168: my $remotereq=<$client>;
5169: chomp($remotereq);
5170: Debug("Got init: $remotereq");
5171: my $inikeyword = split(/:/, $remotereq);
5172: if ($remotereq =~ /^init/) {
5173: &sethost("sethost:$perlvar{'lonHostID'}");
5174: #
5175: # If the remote is attempting a local init... give that a try:
5176: #
5177: my ($i, $inittype) = split(/:/, $remotereq);
1.209 albertel 5178:
1.212 foxr 5179: # If the connection type is ssl, but I didn't get my
5180: # certificate files yet, then I'll drop back to
5181: # insecure (if allowed).
5182:
5183: if($inittype eq "ssl") {
5184: my ($ca, $cert) = lonssl::CertificateFile;
5185: my $kfile = lonssl::KeyFile;
5186: if((!$ca) ||
5187: (!$cert) ||
5188: (!$kfile)) {
5189: $inittype = ""; # This forces insecure attempt.
5190: &logthis("<font color=\"blue\"> Certificates not "
5191: ."installed -- trying insecure auth</font>");
1.224 foxr 5192: } else { # SSL certificates are in place so
1.212 foxr 5193: } # Leave the inittype alone.
5194: }
5195:
5196: if($inittype eq "local") {
5197: my $key = LocalConnection($client, $remotereq);
5198: if($key) {
5199: Debug("Got local key $key");
5200: $clientok = 1;
5201: my $cipherkey = pack("H32", $key);
5202: $cipher = new IDEA($cipherkey);
5203: print $client "ok:local\n";
5204: &logthis('<font color="green"'
5205: . "Successful local authentication </font>");
5206: $keymode = "local"
1.178 foxr 5207: } else {
1.212 foxr 5208: Debug("Failed to get local key");
5209: $clientok = 0;
5210: shutdown($client, 3);
5211: close $client;
1.178 foxr 5212: }
1.212 foxr 5213: } elsif ($inittype eq "ssl") {
5214: my $key = SSLConnection($client);
5215: if ($key) {
5216: $clientok = 1;
5217: my $cipherkey = pack("H32", $key);
5218: $cipher = new IDEA($cipherkey);
5219: &logthis('<font color="green">'
5220: ."Successfull ssl authentication with $clientname </font>");
5221: $keymode = "ssl";
5222:
1.178 foxr 5223: } else {
1.212 foxr 5224: $clientok = 0;
5225: close $client;
1.178 foxr 5226: }
1.212 foxr 5227:
5228: } else {
5229: my $ok = InsecureConnection($client);
5230: if($ok) {
5231: $clientok = 1;
5232: &logthis('<font color="green">'
5233: ."Successful insecure authentication with $clientname </font>");
5234: print $client "ok\n";
5235: $keymode = "insecure";
1.178 foxr 5236: } else {
1.212 foxr 5237: &logthis('<font color="yellow">'
5238: ."Attempted insecure connection disallowed </font>");
5239: close $client;
5240: $clientok = 0;
1.178 foxr 5241:
5242: }
5243: }
1.212 foxr 5244: } else {
5245: &logthis(
5246: "<font color='blue'>WARNING: "
5247: ."$clientip failed to initialize: >$remotereq< </font>");
5248: &status('No init '.$clientip);
5249: }
5250:
5251: } else {
5252: &logthis(
5253: "<font color='blue'>WARNING: Unknown client $clientip</font>");
5254: &status('Hung up on '.$clientip);
5255: }
5256:
5257: if ($clientok) {
5258: # ---------------- New known client connecting, could mean machine online again
5259:
5260: foreach my $id (keys(%hostip)) {
5261: if ($hostip{$id} ne $clientip ||
5262: $hostip{$currenthostid} eq $clientip) {
5263: # no need to try to do recon's to myself
5264: next;
5265: }
5266: &reconlonc("$perlvar{'lonSockDir'}/$id");
5267: }
5268: &logthis("<font color='green'>Established connection: $clientname</font>");
5269: &status('Will listen to '.$clientname);
5270: # ------------------------------------------------------------ Process requests
5271: my $keep_going = 1;
5272: my $user_input;
5273: while(($user_input = get_request) && $keep_going) {
5274: alarm(120);
5275: Debug("Main: Got $user_input\n");
5276: $keep_going = &process_request($user_input);
1.178 foxr 5277: alarm(0);
1.212 foxr 5278: &status('Listening to '.$clientname." ($keymode)");
1.161 foxr 5279: }
1.212 foxr 5280:
1.59 www 5281: # --------------------------------------------- client unknown or fishy, refuse
1.212 foxr 5282: } else {
1.161 foxr 5283: print $client "refused\n";
5284: $client->close();
1.190 albertel 5285: &logthis("<font color='blue'>WARNING: "
1.161 foxr 5286: ."Rejected client $clientip, closing connection</font>");
5287: }
1.212 foxr 5288: }
1.161 foxr 5289:
1.1 albertel 5290: # =============================================================================
1.161 foxr 5291:
1.190 albertel 5292: &logthis("<font color='red'>CRITICAL: "
1.161 foxr 5293: ."Disconnect from $clientip ($clientname)</font>");
5294:
5295:
5296: # this exit is VERY important, otherwise the child will become
5297: # a producer of more and more children, forking yourself into
5298: # process death.
5299: exit;
1.106 foxr 5300:
1.78 foxr 5301: }
1.261 foxr 5302: #
5303: # Determine if a user is an author for the indicated domain.
5304: #
5305: # Parameters:
5306: # domain - domain to check in .
5307: # user - Name of user to check.
5308: #
5309: # Return:
5310: # 1 - User is an author for domain.
5311: # 0 - User is not an author for domain.
5312: sub is_author {
5313: my ($domain, $user) = @_;
5314:
5315: &Debug("is_author: $user @ $domain");
5316:
5317: my $hashref = &tie_user_hash($domain, $user, "roles",
5318: &GDBM_READER());
5319:
5320: # Author role should show up as a key /domain/_au
1.78 foxr 5321:
1.261 foxr 5322: my $key = "/$domain/_au";
5323: my $value = $hashref->{$key};
1.78 foxr 5324:
1.261 foxr 5325: if(defined($value)) {
5326: &Debug("$user @ $domain is an author");
5327: }
5328:
5329: return defined($value);
5330: }
1.78 foxr 5331: #
5332: # Checks to see if the input roleput request was to set
5333: # an author role. If so, invokes the lchtmldir script to set
5334: # up a correct public_html
5335: # Parameters:
5336: # request - The request sent to the rolesput subchunk.
5337: # We're looking for /domain/_au
5338: # domain - The domain in which the user is having roles doctored.
5339: # user - Name of the user for which the role is being put.
5340: # authtype - The authentication type associated with the user.
5341: #
1.289 albertel 5342: sub manage_permissions {
1.192 foxr 5343: my ($request, $domain, $user, $authtype) = @_;
1.78 foxr 5344:
1.261 foxr 5345: &Debug("manage_permissions: $request $domain $user $authtype");
5346:
1.78 foxr 5347: # See if the request is of the form /$domain/_au
1.289 albertel 5348: if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.78 foxr 5349: my $execdir = $perlvar{'lonDaemons'};
5350: my $userhome= "/home/$user" ;
1.134 albertel 5351: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261 foxr 5352: &Debug("Setting homedir permissions for $userhome");
1.78 foxr 5353: system("$execdir/lchtmldir $userhome $user $authtype");
5354: }
5355: }
1.222 foxr 5356:
5357:
5358: #
5359: # Return the full path of a user password file, whether it exists or not.
5360: # Parameters:
5361: # domain - Domain in which the password file lives.
5362: # user - name of the user.
5363: # Returns:
5364: # Full passwd path:
5365: #
5366: sub password_path {
5367: my ($domain, $user) = @_;
1.264 albertel 5368: return &propath($domain, $user).'/passwd';
1.222 foxr 5369: }
5370:
5371: # Password Filename
5372: # Returns the path to a passwd file given domain and user... only if
5373: # it exists.
5374: # Parameters:
5375: # domain - Domain in which to search.
5376: # user - username.
5377: # Returns:
5378: # - If the password file exists returns its path.
5379: # - If the password file does not exist, returns undefined.
5380: #
5381: sub password_filename {
5382: my ($domain, $user) = @_;
5383:
5384: Debug ("PasswordFilename called: dom = $domain user = $user");
5385:
5386: my $path = &password_path($domain, $user);
5387: Debug("PasswordFilename got path: $path");
5388: if(-e $path) {
5389: return $path;
5390: } else {
5391: return undef;
5392: }
5393: }
5394:
5395: #
5396: # Rewrite the contents of the user's passwd file.
5397: # Parameters:
5398: # domain - domain of the user.
5399: # name - User's name.
5400: # contents - New contents of the file.
5401: # Returns:
5402: # 0 - Failed.
5403: # 1 - Success.
5404: #
5405: sub rewrite_password_file {
5406: my ($domain, $user, $contents) = @_;
5407:
5408: my $file = &password_filename($domain, $user);
5409: if (defined $file) {
5410: my $pf = IO::File->new(">$file");
5411: if($pf) {
5412: print $pf "$contents\n";
5413: return 1;
5414: } else {
5415: return 0;
5416: }
5417: } else {
5418: return 0;
5419: }
5420:
5421: }
5422:
1.78 foxr 5423: #
1.222 foxr 5424: # get_auth_type - Determines the authorization type of a user in a domain.
1.78 foxr 5425:
5426: # Returns the authorization type or nouser if there is no such user.
5427: #
1.222 foxr 5428: sub get_auth_type
1.78 foxr 5429: {
1.192 foxr 5430:
5431: my ($domain, $user) = @_;
1.78 foxr 5432:
1.222 foxr 5433: Debug("get_auth_type( $domain, $user ) \n");
1.78 foxr 5434: my $proname = &propath($domain, $user);
5435: my $passwdfile = "$proname/passwd";
5436: if( -e $passwdfile ) {
5437: my $pf = IO::File->new($passwdfile);
5438: my $realpassword = <$pf>;
5439: chomp($realpassword);
1.79 foxr 5440: Debug("Password info = $realpassword\n");
1.78 foxr 5441: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 5442: Debug("Authtype = $authtype, content = $contentpwd\n");
1.259 raeburn 5443: return "$authtype:$contentpwd";
1.224 foxr 5444: } else {
1.79 foxr 5445: Debug("Returning nouser");
1.78 foxr 5446: return "nouser";
5447: }
1.1 albertel 5448: }
5449:
1.220 foxr 5450: #
5451: # Validate a user given their domain, name and password. This utility
5452: # function is used by both AuthenticateHandler and ChangePasswordHandler
5453: # to validate the login credentials of a user.
5454: # Parameters:
5455: # $domain - The domain being logged into (this is required due to
5456: # the capability for multihomed systems.
5457: # $user - The name of the user being validated.
5458: # $password - The user's propoposed password.
5459: #
5460: # Returns:
5461: # 1 - The domain,user,pasword triplet corresponds to a valid
5462: # user.
5463: # 0 - The domain,user,password triplet is not a valid user.
5464: #
5465: sub validate_user {
5466: my ($domain, $user, $password) = @_;
5467:
5468:
5469: # Why negative ~pi you may well ask? Well this function is about
5470: # authentication, and therefore very important to get right.
5471: # I've initialized the flag that determines whether or not I've
5472: # validated correctly to a value it's not supposed to get.
5473: # At the end of this function. I'll ensure that it's not still that
5474: # value so we don't just wind up returning some accidental value
5475: # as a result of executing an unforseen code path that
1.249 foxr 5476: # did not set $validated. At the end of valid execution paths,
5477: # validated shoule be 1 for success or 0 for failuer.
1.220 foxr 5478:
5479: my $validated = -3.14159;
5480:
5481: # How we authenticate is determined by the type of authentication
5482: # the user has been assigned. If the authentication type is
5483: # "nouser", the user does not exist so we will return 0.
5484:
1.222 foxr 5485: my $contents = &get_auth_type($domain, $user);
1.220 foxr 5486: my ($howpwd, $contentpwd) = split(/:/, $contents);
5487:
5488: my $null = pack("C",0); # Used by kerberos auth types.
5489:
5490: if ($howpwd ne 'nouser') {
5491:
5492: if($howpwd eq "internal") { # Encrypted is in local password file.
5493: $validated = (crypt($password, $contentpwd) eq $contentpwd);
5494: }
5495: elsif ($howpwd eq "unix") { # User is a normal unix user.
5496: $contentpwd = (getpwnam($user))[1];
5497: if($contentpwd) {
5498: if($contentpwd eq 'x') { # Shadow password file...
5499: my $pwauth_path = "/usr/local/sbin/pwauth";
5500: open PWAUTH, "|$pwauth_path" or
5501: die "Cannot invoke authentication";
5502: print PWAUTH "$user\n$password\n";
5503: close PWAUTH;
5504: $validated = ! $?;
5505:
5506: } else { # Passwords in /etc/passwd.
5507: $validated = (crypt($password,
5508: $contentpwd) eq $contentpwd);
5509: }
5510: } else {
5511: $validated = 0;
5512: }
5513: }
5514: elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
5515: if(! ($password =~ /$null/) ) {
5516: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
5517: "",
5518: $contentpwd,,
5519: 'krbtgt',
5520: $contentpwd,
5521: 1,
5522: $password);
5523: if(!$k4error) {
5524: $validated = 1;
1.224 foxr 5525: } else {
1.220 foxr 5526: $validated = 0;
5527: &logthis('krb4: '.$user.', '.$contentpwd.', '.
5528: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
5529: }
1.224 foxr 5530: } else {
1.220 foxr 5531: $validated = 0; # Password has a match with null.
5532: }
1.224 foxr 5533: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220 foxr 5534: if(!($password =~ /$null/)) { # Null password not allowed.
5535: my $krbclient = &Authen::Krb5::parse_name($user.'@'
5536: .$contentpwd);
5537: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
5538: my $krbserver = &Authen::Krb5::parse_name($krbservice);
5539: my $credentials= &Authen::Krb5::cc_default();
5540: $credentials->initialize($krbclient);
1.270 matthew 5541: my $krbreturn = &Authen::Krb5::get_in_tkt_with_password($krbclient,
1.220 foxr 5542: $krbserver,
5543: $password,
5544: $credentials);
5545: $validated = ($krbreturn == 1);
1.224 foxr 5546: } else {
1.220 foxr 5547: $validated = 0;
5548: }
1.224 foxr 5549: } elsif ($howpwd eq "localauth") {
1.220 foxr 5550: # Authenticate via installation specific authentcation method:
5551: $validated = &localauth::localauth($user,
5552: $password,
5553: $contentpwd);
1.224 foxr 5554: } else { # Unrecognized auth is also bad.
1.220 foxr 5555: $validated = 0;
5556: }
5557: } else {
5558: $validated = 0;
5559: }
5560: #
5561: # $validated has the correct stat of the authentication:
5562: #
5563:
5564: unless ($validated != -3.14159) {
1.249 foxr 5565: # I >really really< want to know if this happens.
5566: # since it indicates that user authentication is badly
5567: # broken in some code path.
5568: #
5569: die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220 foxr 5570: }
5571: return $validated;
5572: }
5573:
5574:
1.84 albertel 5575: sub addline {
5576: my ($fname,$hostid,$ip,$newline)=@_;
5577: my $contents;
5578: my $found=0;
5579: my $expr='^'.$hostid.':'.$ip.':';
5580: $expr =~ s/\./\\\./g;
1.134 albertel 5581: my $sh;
1.84 albertel 5582: if ($sh=IO::File->new("$fname.subscription")) {
5583: while (my $subline=<$sh>) {
5584: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
5585: }
5586: $sh->close();
5587: }
5588: $sh=IO::File->new(">$fname.subscription");
5589: if ($contents) { print $sh $contents; }
5590: if ($newline) { print $sh $newline; }
5591: $sh->close();
5592: return $found;
1.86 www 5593: }
5594:
1.234 foxr 5595: sub get_chat {
1.122 www 5596: my ($cdom,$cname,$udom,$uname)=@_;
1.87 www 5597: my %hash;
5598: my $proname=&propath($cdom,$cname);
5599: my @entries=();
1.88 albertel 5600: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
5601: &GDBM_READER(),0640)) {
5602: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
5603: untie %hash;
1.123 www 5604: }
1.124 www 5605: my @participants=();
1.134 albertel 5606: my $cutoff=time-60;
1.123 www 5607: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124 www 5608: &GDBM_WRCREAT(),0640)) {
5609: $hash{$uname.':'.$udom}=time;
1.123 www 5610: foreach (sort keys %hash) {
5611: if ($hash{$_}>$cutoff) {
1.124 www 5612: $participants[$#participants+1]='active_participant:'.$_;
1.123 www 5613: }
5614: }
5615: untie %hash;
1.86 www 5616: }
1.124 www 5617: return (@participants,@entries);
1.86 www 5618: }
5619:
1.234 foxr 5620: sub chat_add {
1.88 albertel 5621: my ($cdom,$cname,$newchat)=@_;
5622: my %hash;
5623: my $proname=&propath($cdom,$cname);
5624: my @entries=();
1.142 www 5625: my $time=time;
1.88 albertel 5626: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
5627: &GDBM_WRCREAT(),0640)) {
5628: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
5629: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
5630: my ($thentime,$idnum)=split(/\_/,$lastid);
5631: my $newid=$time.'_000000';
5632: if ($thentime==$time) {
5633: $idnum=~s/^0+//;
5634: $idnum++;
5635: $idnum=substr('000000'.$idnum,-6,6);
5636: $newid=$time.'_'.$idnum;
5637: }
5638: $hash{$newid}=$newchat;
5639: my $expired=$time-3600;
5640: foreach (keys %hash) {
5641: my ($thistime)=($_=~/(\d+)\_/);
5642: if ($thistime<$expired) {
1.89 www 5643: delete $hash{$_};
1.88 albertel 5644: }
5645: }
5646: untie %hash;
1.142 www 5647: }
5648: {
5649: my $hfh;
5650: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
5651: print $hfh "$time:".&unescape($newchat)."\n";
5652: }
1.86 www 5653: }
1.84 albertel 5654: }
5655:
5656: sub unsub {
5657: my ($fname,$clientip)=@_;
5658: my $result;
1.188 foxr 5659: my $unsubs = 0; # Number of successful unsubscribes:
5660:
5661:
5662: # An old way subscriptions were handled was to have a
5663: # subscription marker file:
5664:
5665: Debug("Attempting unlink of $fname.$clientname");
1.161 foxr 5666: if (unlink("$fname.$clientname")) {
1.188 foxr 5667: $unsubs++; # Successful unsub via marker file.
5668: }
5669:
5670: # The more modern way to do it is to have a subscription list
5671: # file:
5672:
1.84 albertel 5673: if (-e "$fname.subscription") {
1.161 foxr 5674: my $found=&addline($fname,$clientname,$clientip,'');
1.188 foxr 5675: if ($found) {
5676: $unsubs++;
5677: }
5678: }
5679:
5680: # If either or both of these mechanisms succeeded in unsubscribing a
5681: # resource we can return ok:
5682:
5683: if($unsubs) {
5684: $result = "ok\n";
1.84 albertel 5685: } else {
1.188 foxr 5686: $result = "not_subscribed\n";
1.84 albertel 5687: }
1.188 foxr 5688:
1.84 albertel 5689: return $result;
5690: }
5691:
1.101 www 5692: sub currentversion {
5693: my $fname=shift;
5694: my $version=-1;
5695: my $ulsdir='';
5696: if ($fname=~/^(.+)\/[^\/]+$/) {
5697: $ulsdir=$1;
5698: }
1.114 albertel 5699: my ($fnamere1,$fnamere2);
5700: # remove version if already specified
1.101 www 5701: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 5702: # get the bits that go before and after the version number
5703: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
5704: $fnamere1=$1;
5705: $fnamere2='.'.$2;
5706: }
1.101 www 5707: if (-e $fname) { $version=1; }
5708: if (-e $ulsdir) {
1.134 albertel 5709: if(-d $ulsdir) {
5710: if (opendir(LSDIR,$ulsdir)) {
5711: my $ulsfn;
5712: while ($ulsfn=readdir(LSDIR)) {
1.101 www 5713: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 5714: my $thisfile=$ulsdir.'/'.$ulsfn;
5715: unless (-l $thisfile) {
1.160 www 5716: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 5717: if ($1>$version) { $version=$1; }
5718: }
5719: }
5720: }
5721: closedir(LSDIR);
5722: $version++;
5723: }
5724: }
5725: }
5726: return $version;
1.101 www 5727: }
5728:
5729: sub thisversion {
5730: my $fname=shift;
5731: my $version=-1;
5732: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
5733: $version=$1;
5734: }
5735: return $version;
5736: }
5737:
1.84 albertel 5738: sub subscribe {
5739: my ($userinput,$clientip)=@_;
5740: my $result;
1.293 albertel 5741: my ($cmd,$fname)=split(/:/,$userinput,2);
1.84 albertel 5742: my $ownership=&ishome($fname);
5743: if ($ownership eq 'owner') {
1.101 www 5744: # explitly asking for the current version?
5745: unless (-e $fname) {
5746: my $currentversion=¤tversion($fname);
5747: if (&thisversion($fname)==$currentversion) {
5748: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
5749: my $root=$1;
5750: my $extension=$2;
5751: symlink($root.'.'.$extension,
5752: $root.'.'.$currentversion.'.'.$extension);
1.102 www 5753: unless ($extension=~/\.meta$/) {
5754: symlink($root.'.'.$extension.'.meta',
5755: $root.'.'.$currentversion.'.'.$extension.'.meta');
5756: }
1.101 www 5757: }
5758: }
5759: }
1.84 albertel 5760: if (-e $fname) {
5761: if (-d $fname) {
5762: $result="directory\n";
5763: } else {
1.161 foxr 5764: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 5765: my $now=time;
1.161 foxr 5766: my $found=&addline($fname,$clientname,$clientip,
5767: "$clientname:$clientip:$now\n");
1.84 albertel 5768: if ($found) { $result="$fname\n"; }
5769: # if they were subscribed to only meta data, delete that
5770: # subscription, when you subscribe to a file you also get
5771: # the metadata
5772: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
5773: $fname=~s/\/home\/httpd\/html\/res/raw/;
5774: $fname="http://$thisserver/".$fname;
5775: $result="$fname\n";
5776: }
5777: } else {
5778: $result="not_found\n";
5779: }
5780: } else {
5781: $result="rejected\n";
5782: }
5783: return $result;
5784: }
1.287 foxr 5785: # Change the passwd of a unix user. The caller must have
5786: # first verified that the user is a loncapa user.
5787: #
5788: # Parameters:
5789: # user - Unix user name to change.
5790: # pass - New password for the user.
5791: # Returns:
5792: # ok - if success
5793: # other - Some meaningfule error message string.
5794: # NOTE:
5795: # invokes a setuid script to change the passwd.
5796: sub change_unix_password {
5797: my ($user, $pass) = @_;
5798:
5799: &Debug("change_unix_password");
5800: my $execdir=$perlvar{'lonDaemons'};
5801: &Debug("Opening lcpasswd pipeline");
5802: my $pf = IO::File->new("|$execdir/lcpasswd > "
5803: ."$perlvar{'lonDaemons'}"
5804: ."/logs/lcpasswd.log");
5805: print $pf "$user\n$pass\n$pass\n";
5806: close $pf;
5807: my $err = $?;
5808: return ($err < @passwderrors) ? $passwderrors[$err] :
5809: "pwchange_falure - unknown error";
5810:
5811:
5812: }
5813:
1.91 albertel 5814:
5815: sub make_passwd_file {
1.98 foxr 5816: my ($uname, $umode,$npass,$passfilename)=@_;
1.91 albertel 5817: my $result="ok\n";
5818: if ($umode eq 'krb4' or $umode eq 'krb5') {
5819: {
5820: my $pf = IO::File->new(">$passfilename");
1.261 foxr 5821: if ($pf) {
5822: print $pf "$umode:$npass\n";
5823: } else {
5824: $result = "pass_file_failed_error";
5825: }
1.91 albertel 5826: }
5827: } elsif ($umode eq 'internal') {
5828: my $salt=time;
5829: $salt=substr($salt,6,2);
5830: my $ncpass=crypt($npass,$salt);
5831: {
5832: &Debug("Creating internal auth");
5833: my $pf = IO::File->new(">$passfilename");
1.261 foxr 5834: if($pf) {
5835: print $pf "internal:$ncpass\n";
5836: } else {
5837: $result = "pass_file_failed_error";
5838: }
1.91 albertel 5839: }
5840: } elsif ($umode eq 'localauth') {
5841: {
5842: my $pf = IO::File->new(">$passfilename");
1.261 foxr 5843: if($pf) {
5844: print $pf "localauth:$npass\n";
5845: } else {
5846: $result = "pass_file_failed_error";
5847: }
1.91 albertel 5848: }
5849: } elsif ($umode eq 'unix') {
5850: {
1.186 foxr 5851: #
5852: # Don't allow the creation of privileged accounts!!! that would
5853: # be real bad!!!
5854: #
5855: my $uid = getpwnam($uname);
5856: if((defined $uid) && ($uid == 0)) {
5857: &logthis(">>>Attempted to create privilged account blocked");
5858: return "no_priv_account_error\n";
5859: }
5860:
1.223 foxr 5861: my $execpath ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224 foxr 5862:
5863: my $lc_error_file = $execdir."/tmp/lcuseradd".$$.".status";
1.91 albertel 5864: {
5865: &Debug("Executing external: ".$execpath);
1.98 foxr 5866: &Debug("user = ".$uname.", Password =". $npass);
1.132 matthew 5867: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91 albertel 5868: print $se "$uname\n";
5869: print $se "$npass\n";
5870: print $se "$npass\n";
1.223 foxr 5871: print $se "$lc_error_file\n"; # Status -> unique file.
1.97 foxr 5872: }
1.285 foxr 5873: if (-r $lc_error_file) {
5874: &Debug("Opening error file: $lc_error_file");
5875: my $error = IO::File->new("< $lc_error_file");
5876: my $useraddok = <$error>;
5877: $error->close;
5878: unlink($lc_error_file);
5879:
5880: chomp $useraddok;
5881:
5882: if($useraddok > 0) {
5883: my $error_text = &lcuseraddstrerror($useraddok);
5884: &logthis("Failed lcuseradd: $error_text");
5885: $result = "lcuseradd_failed:$error_text\n";
5886: } else {
5887: my $pf = IO::File->new(">$passfilename");
5888: if($pf) {
5889: print $pf "unix:\n";
5890: } else {
5891: $result = "pass_file_failed_error";
5892: }
5893: }
1.224 foxr 5894: } else {
1.285 foxr 5895: &Debug("Could not locate lcuseradd error: $lc_error_file");
5896: $result="bug_lcuseradd_no_output_file";
1.91 albertel 5897: }
5898: }
5899: } elsif ($umode eq 'none') {
5900: {
1.223 foxr 5901: my $pf = IO::File->new("> $passfilename");
1.261 foxr 5902: if($pf) {
5903: print $pf "none:\n";
5904: } else {
5905: $result = "pass_file_failed_error";
5906: }
1.91 albertel 5907: }
5908: } else {
5909: $result="auth_mode_error\n";
5910: }
5911: return $result;
1.121 albertel 5912: }
5913:
1.265 albertel 5914: sub convert_photo {
5915: my ($start,$dest)=@_;
5916: system("convert $start $dest");
5917: }
5918:
1.121 albertel 5919: sub sethost {
5920: my ($remotereq) = @_;
5921: my (undef,$hostid)=split(/:/,$remotereq);
5922: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
5923: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200 matthew 5924: $currenthostid =$hostid;
1.121 albertel 5925: $currentdomainid=$hostdom{$hostid};
5926: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
5927: } else {
5928: &logthis("Requested host id $hostid not an alias of ".
5929: $perlvar{'lonHostID'}." refusing connection");
5930: return 'unable_to_set';
5931: }
5932: return 'ok';
5933: }
5934:
5935: sub version {
5936: my ($userinput)=@_;
5937: $remoteVERSION=(split(/:/,$userinput))[1];
5938: return "version:$VERSION";
1.127 albertel 5939: }
1.178 foxr 5940:
1.128 albertel 5941: #There is a copy of this in lonnet.pm
1.127 albertel 5942: sub userload {
5943: my $numusers=0;
5944: {
5945: opendir(LONIDS,$perlvar{'lonIDsDir'});
5946: my $filename;
5947: my $curtime=time;
5948: while ($filename=readdir(LONIDS)) {
5949: if ($filename eq '.' || $filename eq '..') {next;}
1.138 albertel 5950: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159 albertel 5951: if ($curtime-$mtime < 1800) { $numusers++; }
1.127 albertel 5952: }
5953: closedir(LONIDS);
5954: }
5955: my $userloadpercent=0;
5956: my $maxuserload=$perlvar{'lonUserLoadLim'};
5957: if ($maxuserload) {
1.129 albertel 5958: $userloadpercent=100*$numusers/$maxuserload;
1.127 albertel 5959: }
1.130 albertel 5960: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127 albertel 5961: return $userloadpercent;
1.91 albertel 5962: }
5963:
1.205 raeburn 5964: # Routines for serializing arrays and hashes (copies from lonnet)
5965:
5966: sub array2str {
5967: my (@array) = @_;
5968: my $result=&arrayref2str(\@array);
5969: $result=~s/^__ARRAY_REF__//;
5970: $result=~s/__END_ARRAY_REF__$//;
5971: return $result;
5972: }
5973:
5974: sub arrayref2str {
5975: my ($arrayref) = @_;
5976: my $result='__ARRAY_REF__';
5977: foreach my $elem (@$arrayref) {
5978: if(ref($elem) eq 'ARRAY') {
5979: $result.=&arrayref2str($elem).'&';
5980: } elsif(ref($elem) eq 'HASH') {
5981: $result.=&hashref2str($elem).'&';
5982: } elsif(ref($elem)) {
5983: #print("Got a ref of ".(ref($elem))." skipping.");
5984: } else {
5985: $result.=&escape($elem).'&';
5986: }
5987: }
5988: $result=~s/\&$//;
5989: $result .= '__END_ARRAY_REF__';
5990: return $result;
5991: }
5992:
5993: sub hash2str {
5994: my (%hash) = @_;
5995: my $result=&hashref2str(\%hash);
5996: $result=~s/^__HASH_REF__//;
5997: $result=~s/__END_HASH_REF__$//;
5998: return $result;
5999: }
6000:
6001: sub hashref2str {
6002: my ($hashref)=@_;
6003: my $result='__HASH_REF__';
6004: foreach (sort(keys(%$hashref))) {
6005: if (ref($_) eq 'ARRAY') {
6006: $result.=&arrayref2str($_).'=';
6007: } elsif (ref($_) eq 'HASH') {
6008: $result.=&hashref2str($_).'=';
6009: } elsif (ref($_)) {
6010: $result.='=';
6011: #print("Got a ref of ".(ref($_))." skipping.");
6012: } else {
6013: if ($_) {$result.=&escape($_).'=';} else { last; }
6014: }
6015:
6016: if(ref($hashref->{$_}) eq 'ARRAY') {
6017: $result.=&arrayref2str($hashref->{$_}).'&';
6018: } elsif(ref($hashref->{$_}) eq 'HASH') {
6019: $result.=&hashref2str($hashref->{$_}).'&';
6020: } elsif(ref($hashref->{$_})) {
6021: $result.='&';
6022: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
6023: } else {
6024: $result.=&escape($hashref->{$_}).'&';
6025: }
6026: }
6027: $result=~s/\&$//;
6028: $result .= '__END_HASH_REF__';
6029: return $result;
6030: }
1.200 matthew 6031:
1.61 harris41 6032: # ----------------------------------- POD (plain old documentation, CPAN style)
6033:
6034: =head1 NAME
6035:
6036: lond - "LON Daemon" Server (port "LOND" 5663)
6037:
6038: =head1 SYNOPSIS
6039:
1.74 harris41 6040: Usage: B<lond>
6041:
6042: Should only be run as user=www. This is a command-line script which
6043: is invoked by B<loncron>. There is no expectation that a typical user
6044: will manually start B<lond> from the command-line. (In other words,
6045: DO NOT START B<lond> YOURSELF.)
1.61 harris41 6046:
6047: =head1 DESCRIPTION
6048:
1.74 harris41 6049: There are two characteristics associated with the running of B<lond>,
6050: PROCESS MANAGEMENT (starting, stopping, handling child processes)
6051: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
6052: subscriptions, etc). These are described in two large
6053: sections below.
6054:
6055: B<PROCESS MANAGEMENT>
6056:
1.61 harris41 6057: Preforker - server who forks first. Runs as a daemon. HUPs.
6058: Uses IDEA encryption
6059:
1.74 harris41 6060: B<lond> forks off children processes that correspond to the other servers
6061: in the network. Management of these processes can be done at the
6062: parent process level or the child process level.
6063:
6064: B<logs/lond.log> is the location of log messages.
6065:
6066: The process management is now explained in terms of linux shell commands,
6067: subroutines internal to this code, and signal assignments:
6068:
6069: =over 4
6070:
6071: =item *
6072:
6073: PID is stored in B<logs/lond.pid>
6074:
6075: This is the process id number of the parent B<lond> process.
6076:
6077: =item *
6078:
6079: SIGTERM and SIGINT
6080:
6081: Parent signal assignment:
6082: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
6083:
6084: Child signal assignment:
6085: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
6086: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
6087: to restart a new child.)
6088:
6089: Command-line invocations:
6090: B<kill> B<-s> SIGTERM I<PID>
6091: B<kill> B<-s> SIGINT I<PID>
6092:
6093: Subroutine B<HUNTSMAN>:
6094: This is only invoked for the B<lond> parent I<PID>.
6095: This kills all the children, and then the parent.
6096: The B<lonc.pid> file is cleared.
6097:
6098: =item *
6099:
6100: SIGHUP
6101:
6102: Current bug:
6103: This signal can only be processed the first time
6104: on the parent process. Subsequent SIGHUP signals
6105: have no effect.
6106:
6107: Parent signal assignment:
6108: $SIG{HUP} = \&HUPSMAN;
6109:
6110: Child signal assignment:
6111: none (nothing happens)
6112:
6113: Command-line invocations:
6114: B<kill> B<-s> SIGHUP I<PID>
6115:
6116: Subroutine B<HUPSMAN>:
6117: This is only invoked for the B<lond> parent I<PID>,
6118: This kills all the children, and then the parent.
6119: The B<lond.pid> file is cleared.
6120:
6121: =item *
6122:
6123: SIGUSR1
6124:
6125: Parent signal assignment:
6126: $SIG{USR1} = \&USRMAN;
6127:
6128: Child signal assignment:
6129: $SIG{USR1}= \&logstatus;
6130:
6131: Command-line invocations:
6132: B<kill> B<-s> SIGUSR1 I<PID>
6133:
6134: Subroutine B<USRMAN>:
6135: When invoked for the B<lond> parent I<PID>,
6136: SIGUSR1 is sent to all the children, and the status of
6137: each connection is logged.
1.144 foxr 6138:
6139: =item *
6140:
6141: SIGUSR2
6142:
6143: Parent Signal assignment:
6144: $SIG{USR2} = \&UpdateHosts
6145:
6146: Child signal assignment:
6147: NONE
6148:
1.74 harris41 6149:
6150: =item *
6151:
6152: SIGCHLD
6153:
6154: Parent signal assignment:
6155: $SIG{CHLD} = \&REAPER;
6156:
6157: Child signal assignment:
6158: none
6159:
6160: Command-line invocations:
6161: B<kill> B<-s> SIGCHLD I<PID>
6162:
6163: Subroutine B<REAPER>:
6164: This is only invoked for the B<lond> parent I<PID>.
6165: Information pertaining to the child is removed.
6166: The socket port is cleaned up.
6167:
6168: =back
6169:
6170: B<SERVER-SIDE ACTIVITIES>
6171:
6172: Server-side information can be accepted in an encrypted or non-encrypted
6173: method.
6174:
6175: =over 4
6176:
6177: =item ping
6178:
6179: Query a client in the hosts.tab table; "Are you there?"
6180:
6181: =item pong
6182:
6183: Respond to a ping query.
6184:
6185: =item ekey
6186:
6187: Read in encrypted key, make cipher. Respond with a buildkey.
6188:
6189: =item load
6190:
6191: Respond with CPU load based on a computation upon /proc/loadavg.
6192:
6193: =item currentauth
6194:
6195: Reply with current authentication information (only over an
6196: encrypted channel).
6197:
6198: =item auth
6199:
6200: Only over an encrypted channel, reply as to whether a user's
6201: authentication information can be validated.
6202:
6203: =item passwd
6204:
6205: Allow for a password to be set.
6206:
6207: =item makeuser
6208:
6209: Make a user.
6210:
6211: =item passwd
6212:
6213: Allow for authentication mechanism and password to be changed.
6214:
6215: =item home
1.61 harris41 6216:
1.74 harris41 6217: Respond to a question "are you the home for a given user?"
6218:
6219: =item update
6220:
6221: Update contents of a subscribed resource.
6222:
6223: =item unsubscribe
6224:
6225: The server is unsubscribing from a resource.
6226:
6227: =item subscribe
6228:
6229: The server is subscribing to a resource.
6230:
6231: =item log
6232:
6233: Place in B<logs/lond.log>
6234:
6235: =item put
6236:
6237: stores hash in namespace
6238:
1.230 foxr 6239: =item rolesputy
1.74 harris41 6240:
6241: put a role into a user's environment
6242:
6243: =item get
6244:
6245: returns hash with keys from array
6246: reference filled in from namespace
6247:
6248: =item eget
6249:
6250: returns hash with keys from array
6251: reference filled in from namesp (encrypts the return communication)
6252:
6253: =item rolesget
6254:
6255: get a role from a user's environment
6256:
6257: =item del
6258:
6259: deletes keys out of array from namespace
6260:
6261: =item keys
6262:
6263: returns namespace keys
6264:
6265: =item dump
6266:
6267: dumps the complete (or key matching regexp) namespace into a hash
6268:
6269: =item store
6270:
6271: stores hash permanently
6272: for this url; hashref needs to be given and should be a \%hashname; the
6273: remaining args aren't required and if they aren't passed or are '' they will
6274: be derived from the ENV
6275:
6276: =item restore
6277:
6278: returns a hash for a given url
6279:
6280: =item querysend
6281:
6282: Tells client about the lonsql process that has been launched in response
6283: to a sent query.
6284:
6285: =item queryreply
6286:
6287: Accept information from lonsql and make appropriate storage in temporary
6288: file space.
6289:
6290: =item idput
6291:
6292: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
6293: for each student, defined perhaps by the institutional Registrar.)
6294:
6295: =item idget
6296:
6297: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
6298: for each student, defined perhaps by the institutional Registrar.)
6299:
6300: =item tmpput
6301:
6302: Accept and store information in temporary space.
6303:
6304: =item tmpget
6305:
6306: Send along temporarily stored information.
6307:
6308: =item ls
6309:
6310: List part of a user's directory.
6311:
1.135 foxr 6312: =item pushtable
6313:
6314: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
6315: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
6316: must be restored manually in case of a problem with the new table file.
6317: pushtable requires that the request be encrypted and validated via
6318: ValidateManager. The form of the command is:
6319: enc:pushtable tablename <tablecontents> \n
6320: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
6321: cleartext newline.
6322:
1.74 harris41 6323: =item Hanging up (exit or init)
6324:
6325: What to do when a client tells the server that they (the client)
6326: are leaving the network.
6327:
6328: =item unknown command
6329:
6330: If B<lond> is sent an unknown command (not in the list above),
6331: it replys to the client "unknown_cmd".
1.135 foxr 6332:
1.74 harris41 6333:
6334: =item UNKNOWN CLIENT
6335:
6336: If the anti-spoofing algorithm cannot verify the client,
6337: the client is rejected (with a "refused" message sent
6338: to the client, and the connection is closed.
6339:
6340: =back
1.61 harris41 6341:
6342: =head1 PREREQUISITES
6343:
6344: IO::Socket
6345: IO::File
6346: Apache::File
6347: Symbol
6348: POSIX
6349: Crypt::IDEA
6350: LWP::UserAgent()
6351: GDBM_File
6352: Authen::Krb4
1.91 albertel 6353: Authen::Krb5
1.61 harris41 6354:
6355: =head1 COREQUISITES
6356:
6357: =head1 OSNAMES
6358:
6359: linux
6360:
6361: =head1 SCRIPT CATEGORIES
6362:
6363: Server/Process
6364:
6365: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>