Annotation of loncom/lond, revision 1.305
1.1 albertel 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60 www 4: #
1.305 ! albertel 5: # $Id: lond,v 1.304 2005/12/10 00:46:23 raeburn Exp $
1.60 www 6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
1.167 foxr 13: # the Free Software Foundation; either version 2 of the License, or
1.60 www 14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
1.178 foxr 23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1.60 www 24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
1.161 foxr 27:
28:
1.60 www 29: # http://www.lon-capa.org/
30: #
1.54 harris41 31:
1.134 albertel 32: use strict;
1.80 harris41 33: use lib '/home/httpd/lib/perl/';
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.305 ! albertel 62: my $VERSION='$Revision: 1.304 $'; #' 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--;
1.305 ! albertel 1981: $url=~s-\.meta$--;
1.298 albertel 1982: my $id=&escape('meta:'.$url);
1983: $memcache->delete($id);
1.225 foxr 1984: }
1985: }
1986: &Reply( $client, "ok\n", $userinput);
1987: } else {
1988: &Failure($client, "not_found\n", $userinput);
1989: }
1990: } else {
1991: &Failure($client, "rejected\n", $userinput);
1992: }
1993: return 1;
1994: }
1995: ®ister_handler("update", \&update_resource_handler, 0 ,1, 0);
1996:
1997: #
1.226 foxr 1998: # Fetch a user file from a remote server to the user's home directory
1999: # userfiles subdir.
1.225 foxr 2000: # Parameters:
2001: # $cmd - The command that got us here.
2002: # $tail - Tail of the command (remaining parameters).
2003: # $client - File descriptor connected to client.
2004: # Returns
2005: # 0 - Requested to exit, caller should shut down.
2006: # 1 - Continue processing.
2007: #
2008: sub fetch_user_file_handler {
2009:
2010: my ($cmd, $tail, $client) = @_;
2011:
2012: my $userinput = "$cmd:$tail";
2013: my $fname = $tail;
1.232 foxr 2014: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1.225 foxr 2015: my $udir=&propath($udom,$uname).'/userfiles';
2016: unless (-e $udir) {
2017: mkdir($udir,0770);
2018: }
1.232 foxr 2019: Debug("fetch user file for $fname");
1.225 foxr 2020: if (-e $udir) {
2021: $ufile=~s/^[\.\~]+//;
1.232 foxr 2022:
2023: # IF necessary, create the path right down to the file.
2024: # Note that any regular files in the way of this path are
2025: # wiped out to deal with some earlier folly of mine.
2026:
1.267 raeburn 2027: if (!&mkpath($udir.'/'.$ufile)) {
1.264 albertel 2028: &Failure($client, "unable_to_create\n", $userinput);
1.232 foxr 2029: }
2030:
1.225 foxr 2031: my $destname=$udir.'/'.$ufile;
2032: my $transname=$udir.'/'.$ufile.'.in.transit';
2033: my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
2034: my $response;
1.232 foxr 2035: Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
1.225 foxr 2036: alarm(120);
2037: {
2038: my $ua=new LWP::UserAgent;
2039: my $request=new HTTP::Request('GET',"$remoteurl");
2040: $response=$ua->request($request,$transname);
2041: }
2042: alarm(0);
2043: if ($response->is_error()) {
2044: unlink($transname);
2045: my $message=$response->status_line;
2046: &logthis("LWP GET: $message for $fname ($remoteurl)");
2047: &Failure($client, "failed\n", $userinput);
2048: } else {
1.232 foxr 2049: Debug("Renaming $transname to $destname");
1.225 foxr 2050: if (!rename($transname,$destname)) {
2051: &logthis("Unable to move $transname to $destname");
2052: unlink($transname);
2053: &Failure($client, "failed\n", $userinput);
2054: } else {
2055: &Reply($client, "ok\n", $userinput);
2056: }
2057: }
2058: } else {
2059: &Failure($client, "not_home\n", $userinput);
2060: }
2061: return 1;
2062: }
2063: ®ister_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
2064:
1.226 foxr 2065: #
2066: # Remove a file from a user's home directory userfiles subdirectory.
2067: # Parameters:
2068: # cmd - the Lond request keyword that got us here.
2069: # tail - the part of the command past the keyword.
2070: # client- File descriptor connected with the client.
2071: #
2072: # Returns:
2073: # 1 - Continue processing.
2074: sub remove_user_file_handler {
2075: my ($cmd, $tail, $client) = @_;
2076:
2077: my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2078:
2079: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2080: if ($ufile =~m|/\.\./|) {
2081: # any files paths with /../ in them refuse
2082: # to deal with
2083: &Failure($client, "refused\n", "$cmd:$tail");
2084: } else {
2085: my $udir = &propath($udom,$uname);
2086: if (-e $udir) {
2087: my $file=$udir.'/userfiles/'.$ufile;
2088: if (-e $file) {
1.253 foxr 2089: #
2090: # If the file is a regular file unlink is fine...
2091: # However it's possible the client wants a dir.
2092: # removed, in which case rmdir is more approprate:
2093: #
1.240 banghart 2094: if (-f $file){
1.241 albertel 2095: unlink($file);
2096: } elsif(-d $file) {
2097: rmdir($file);
1.240 banghart 2098: }
1.226 foxr 2099: if (-e $file) {
1.253 foxr 2100: # File is still there after we deleted it ?!?
2101:
1.226 foxr 2102: &Failure($client, "failed\n", "$cmd:$tail");
2103: } else {
2104: &Reply($client, "ok\n", "$cmd:$tail");
2105: }
2106: } else {
2107: &Failure($client, "not_found\n", "$cmd:$tail");
2108: }
2109: } else {
2110: &Failure($client, "not_home\n", "$cmd:$tail");
2111: }
2112: }
2113: return 1;
2114: }
2115: ®ister_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
2116:
1.236 albertel 2117: #
2118: # make a directory in a user's home directory userfiles subdirectory.
2119: # Parameters:
2120: # cmd - the Lond request keyword that got us here.
2121: # tail - the part of the command past the keyword.
2122: # client- File descriptor connected with the client.
2123: #
2124: # Returns:
2125: # 1 - Continue processing.
2126: sub mkdir_user_file_handler {
2127: my ($cmd, $tail, $client) = @_;
2128:
2129: my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2130: $dir=&unescape($dir);
2131: my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
2132: if ($ufile =~m|/\.\./|) {
2133: # any files paths with /../ in them refuse
2134: # to deal with
2135: &Failure($client, "refused\n", "$cmd:$tail");
2136: } else {
2137: my $udir = &propath($udom,$uname);
2138: if (-e $udir) {
1.264 albertel 2139: my $newdir=$udir.'/userfiles/'.$ufile.'/';
2140: if (!&mkpath($newdir)) {
2141: &Failure($client, "failed\n", "$cmd:$tail");
1.236 albertel 2142: }
1.264 albertel 2143: &Reply($client, "ok\n", "$cmd:$tail");
1.236 albertel 2144: } else {
2145: &Failure($client, "not_home\n", "$cmd:$tail");
2146: }
2147: }
2148: return 1;
2149: }
2150: ®ister_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
2151:
1.237 albertel 2152: #
2153: # rename a file in a user's home directory userfiles subdirectory.
2154: # Parameters:
2155: # cmd - the Lond request keyword that got us here.
2156: # tail - the part of the command past the keyword.
2157: # client- File descriptor connected with the client.
2158: #
2159: # Returns:
2160: # 1 - Continue processing.
2161: sub rename_user_file_handler {
2162: my ($cmd, $tail, $client) = @_;
2163:
2164: my ($udom,$uname,$old,$new) = split(/:/, $tail);
2165: $old=&unescape($old);
2166: $new=&unescape($new);
2167: if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
2168: # any files paths with /../ in them refuse to deal with
2169: &Failure($client, "refused\n", "$cmd:$tail");
2170: } else {
2171: my $udir = &propath($udom,$uname);
2172: if (-e $udir) {
2173: my $oldfile=$udir.'/userfiles/'.$old;
2174: my $newfile=$udir.'/userfiles/'.$new;
2175: if (-e $newfile) {
2176: &Failure($client, "exists\n", "$cmd:$tail");
2177: } elsif (! -e $oldfile) {
2178: &Failure($client, "not_found\n", "$cmd:$tail");
2179: } else {
2180: if (!rename($oldfile,$newfile)) {
2181: &Failure($client, "failed\n", "$cmd:$tail");
2182: } else {
2183: &Reply($client, "ok\n", "$cmd:$tail");
2184: }
2185: }
2186: } else {
2187: &Failure($client, "not_home\n", "$cmd:$tail");
2188: }
2189: }
2190: return 1;
2191: }
2192: ®ister_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
2193:
1.227 foxr 2194: #
1.263 albertel 2195: # Authenticate access to a user file by checking that the token the user's
2196: # passed also exists in their session file
1.227 foxr 2197: #
2198: # Parameters:
2199: # cmd - The request keyword that dispatched to tus.
2200: # tail - The tail of the request (colon separated parameters).
2201: # client - Filehandle open on the client.
2202: # Return:
2203: # 1.
2204: sub token_auth_user_file_handler {
2205: my ($cmd, $tail, $client) = @_;
2206:
2207: my ($fname, $session) = split(/:/, $tail);
2208:
2209: chomp($session);
1.251 foxr 2210: my $reply="non_auth\n";
1.227 foxr 2211: if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
2212: $session.'.id')) {
2213: while (my $line=<ENVIN>) {
1.251 foxr 2214: if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply="ok\n"; }
1.227 foxr 2215: }
2216: close(ENVIN);
1.251 foxr 2217: &Reply($client, $reply, "$cmd:$tail");
1.227 foxr 2218: } else {
2219: &Failure($client, "invalid_token\n", "$cmd:$tail");
2220: }
2221: return 1;
2222:
2223: }
2224: ®ister_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
1.229 foxr 2225:
2226: #
2227: # Unsubscribe from a resource.
2228: #
2229: # Parameters:
2230: # $cmd - The command that got us here.
2231: # $tail - Tail of the command (remaining parameters).
2232: # $client - File descriptor connected to client.
2233: # Returns
2234: # 0 - Requested to exit, caller should shut down.
2235: # 1 - Continue processing.
2236: #
2237: sub unsubscribe_handler {
2238: my ($cmd, $tail, $client) = @_;
2239:
2240: my $userinput= "$cmd:$tail";
2241:
2242: my ($fname) = split(/:/,$tail); # Split in case there's extrs.
2243:
2244: &Debug("Unsubscribing $fname");
2245: if (-e $fname) {
2246: &Debug("Exists");
2247: &Reply($client, &unsub($fname,$clientip), $userinput);
2248: } else {
2249: &Failure($client, "not_found\n", $userinput);
2250: }
2251: return 1;
2252: }
2253: ®ister_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
1.263 albertel 2254:
1.230 foxr 2255: # Subscribe to a resource
2256: #
2257: # Parameters:
2258: # $cmd - The command that got us here.
2259: # $tail - Tail of the command (remaining parameters).
2260: # $client - File descriptor connected to client.
2261: # Returns
2262: # 0 - Requested to exit, caller should shut down.
2263: # 1 - Continue processing.
2264: #
2265: sub subscribe_handler {
2266: my ($cmd, $tail, $client)= @_;
2267:
2268: my $userinput = "$cmd:$tail";
2269:
2270: &Reply( $client, &subscribe($userinput,$clientip), $userinput);
2271:
2272: return 1;
2273: }
2274: ®ister_handler("sub", \&subscribe_handler, 0, 1, 0);
2275:
2276: #
2277: # Determine the version of a resource (?) Or is it return
2278: # the top version of the resource? Not yet clear from the
2279: # code in currentversion.
2280: #
2281: # Parameters:
2282: # $cmd - The command that got us here.
2283: # $tail - Tail of the command (remaining parameters).
2284: # $client - File descriptor connected to client.
2285: # Returns
2286: # 0 - Requested to exit, caller should shut down.
2287: # 1 - Continue processing.
2288: #
2289: sub current_version_handler {
2290: my ($cmd, $tail, $client) = @_;
2291:
2292: my $userinput= "$cmd:$tail";
2293:
2294: my $fname = $tail;
2295: &Reply( $client, ¤tversion($fname)."\n", $userinput);
2296: return 1;
2297:
2298: }
2299: ®ister_handler("currentversion", \¤t_version_handler, 0, 1, 0);
2300:
2301: # Make an entry in a user's activity log.
2302: #
2303: # Parameters:
2304: # $cmd - The command that got us here.
2305: # $tail - Tail of the command (remaining parameters).
2306: # $client - File descriptor connected to client.
2307: # Returns
2308: # 0 - Requested to exit, caller should shut down.
2309: # 1 - Continue processing.
2310: #
2311: sub activity_log_handler {
2312: my ($cmd, $tail, $client) = @_;
2313:
2314:
2315: my $userinput= "$cmd:$tail";
2316:
2317: my ($udom,$uname,$what)=split(/:/,$tail);
2318: chomp($what);
2319: my $proname=&propath($udom,$uname);
2320: my $now=time;
2321: my $hfh;
2322: if ($hfh=IO::File->new(">>$proname/activity.log")) {
2323: print $hfh "$now:$clientname:$what\n";
2324: &Reply( $client, "ok\n", $userinput);
2325: } else {
2326: &Failure($client, "error: ".($!+0)." IO::File->new Failed "
2327: ."while attempting log\n",
2328: $userinput);
2329: }
2330:
2331: return 1;
2332: }
1.263 albertel 2333: ®ister_handler("log", \&activity_log_handler, 0, 1, 0);
1.230 foxr 2334:
2335: #
2336: # Put a namespace entry in a user profile hash.
2337: # My druthers would be for this to be an encrypted interaction too.
2338: # anything that might be an inadvertent covert channel about either
2339: # user authentication or user personal information....
2340: #
2341: # Parameters:
2342: # $cmd - The command that got us here.
2343: # $tail - Tail of the command (remaining parameters).
2344: # $client - File descriptor connected to client.
2345: # Returns
2346: # 0 - Requested to exit, caller should shut down.
2347: # 1 - Continue processing.
2348: #
2349: sub put_user_profile_entry {
2350: my ($cmd, $tail, $client) = @_;
1.229 foxr 2351:
1.230 foxr 2352: my $userinput = "$cmd:$tail";
2353:
1.242 raeburn 2354: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
1.230 foxr 2355: if ($namespace ne 'roles') {
2356: chomp($what);
2357: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2358: &GDBM_WRCREAT(),"P",$what);
2359: if($hashref) {
2360: my @pairs=split(/\&/,$what);
2361: foreach my $pair (@pairs) {
2362: my ($key,$value)=split(/=/,$pair);
2363: $hashref->{$key}=$value;
2364: }
2365: if (untie(%$hashref)) {
2366: &Reply( $client, "ok\n", $userinput);
2367: } else {
2368: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2369: "while attempting put\n",
2370: $userinput);
2371: }
2372: } else {
2373: &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
2374: "while attempting put\n", $userinput);
2375: }
2376: } else {
2377: &Failure( $client, "refused\n", $userinput);
2378: }
2379:
2380: return 1;
2381: }
2382: ®ister_handler("put", \&put_user_profile_entry, 0, 1, 0);
2383:
1.283 albertel 2384: # Put a piece of new data in hash, returns error if entry already exists
2385: # Parameters:
2386: # $cmd - The command that got us here.
2387: # $tail - Tail of the command (remaining parameters).
2388: # $client - File descriptor connected to client.
2389: # Returns
2390: # 0 - Requested to exit, caller should shut down.
2391: # 1 - Continue processing.
2392: #
2393: sub newput_user_profile_entry {
2394: my ($cmd, $tail, $client) = @_;
2395:
2396: my $userinput = "$cmd:$tail";
2397:
2398: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
2399: if ($namespace eq 'roles') {
2400: &Failure( $client, "refused\n", $userinput);
2401: return 1;
2402: }
2403:
2404: chomp($what);
2405:
2406: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2407: &GDBM_WRCREAT(),"N",$what);
2408: if(!$hashref) {
2409: &Failure( $client, "error: ".($!)." tie(GDBM) Failed ".
2410: "while attempting put\n", $userinput);
2411: return 1;
2412: }
2413:
2414: my @pairs=split(/\&/,$what);
2415: foreach my $pair (@pairs) {
2416: my ($key,$value)=split(/=/,$pair);
2417: if (exists($hashref->{$key})) {
2418: &Failure($client, "key_exists: ".$key."\n",$userinput);
2419: return 1;
2420: }
2421: }
2422:
2423: foreach my $pair (@pairs) {
2424: my ($key,$value)=split(/=/,$pair);
2425: $hashref->{$key}=$value;
2426: }
2427:
2428: if (untie(%$hashref)) {
2429: &Reply( $client, "ok\n", $userinput);
2430: } else {
2431: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2432: "while attempting put\n",
2433: $userinput);
2434: }
2435: return 1;
2436: }
2437: ®ister_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
2438:
1.230 foxr 2439: #
2440: # Increment a profile entry in the user history file.
2441: # The history contains keyword value pairs. In this case,
2442: # The value itself is a pair of numbers. The first, the current value
2443: # the second an increment that this function applies to the current
2444: # value.
2445: #
2446: # Parameters:
2447: # $cmd - The command that got us here.
2448: # $tail - Tail of the command (remaining parameters).
2449: # $client - File descriptor connected to client.
2450: # Returns
2451: # 0 - Requested to exit, caller should shut down.
2452: # 1 - Continue processing.
2453: #
2454: sub increment_user_value_handler {
2455: my ($cmd, $tail, $client) = @_;
2456:
2457: my $userinput = "$cmd:$tail";
2458:
2459: my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
2460: if ($namespace ne 'roles') {
2461: chomp($what);
2462: my $hashref = &tie_user_hash($udom, $uname,
2463: $namespace, &GDBM_WRCREAT(),
2464: "P",$what);
2465: if ($hashref) {
2466: my @pairs=split(/\&/,$what);
2467: foreach my $pair (@pairs) {
2468: my ($key,$value)=split(/=/,$pair);
1.284 raeburn 2469: $value = &unescape($value);
1.230 foxr 2470: # We could check that we have a number...
2471: if (! defined($value) || $value eq '') {
2472: $value = 1;
2473: }
2474: $hashref->{$key}+=$value;
1.284 raeburn 2475: if ($namespace eq 'nohist_resourcetracker') {
2476: if ($hashref->{$key} < 0) {
2477: $hashref->{$key} = 0;
2478: }
2479: }
1.230 foxr 2480: }
2481: if (untie(%$hashref)) {
2482: &Reply( $client, "ok\n", $userinput);
2483: } else {
2484: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
2485: "while attempting inc\n", $userinput);
2486: }
2487: } else {
2488: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2489: "while attempting inc\n", $userinput);
2490: }
2491: } else {
2492: &Failure($client, "refused\n", $userinput);
2493: }
2494:
2495: return 1;
2496: }
2497: ®ister_handler("inc", \&increment_user_value_handler, 0, 1, 0);
2498:
2499: #
2500: # Put a new role for a user. Roles are LonCAPA's packaging of permissions.
2501: # Each 'role' a user has implies a set of permissions. Adding a new role
2502: # for a person grants the permissions packaged with that role
2503: # to that user when the role is selected.
2504: #
2505: # Parameters:
2506: # $cmd - The command string (rolesput).
2507: # $tail - The remainder of the request line. For rolesput this
2508: # consists of a colon separated list that contains:
2509: # The domain and user that is granting the role (logged).
2510: # The domain and user that is getting the role.
2511: # The roles being granted as a set of & separated pairs.
2512: # each pair a key value pair.
2513: # $client - File descriptor connected to the client.
2514: # Returns:
2515: # 0 - If the daemon should exit
2516: # 1 - To continue processing.
2517: #
2518: #
2519: sub roles_put_handler {
2520: my ($cmd, $tail, $client) = @_;
2521:
2522: my $userinput = "$cmd:$tail";
2523:
2524: my ( $exedom, $exeuser, $udom, $uname, $what) = split(/:/,$tail);
2525:
2526:
2527: my $namespace='roles';
2528: chomp($what);
2529: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2530: &GDBM_WRCREAT(), "P",
2531: "$exedom:$exeuser:$what");
2532: #
2533: # Log the attempt to set a role. The {}'s here ensure that the file
2534: # handle is open for the minimal amount of time. Since the flush
2535: # is done on close this improves the chances the log will be an un-
2536: # corrupted ordered thing.
2537: if ($hashref) {
1.261 foxr 2538: my $pass_entry = &get_auth_type($udom, $uname);
2539: my ($auth_type,$pwd) = split(/:/, $pass_entry);
2540: $auth_type = $auth_type.":";
1.230 foxr 2541: my @pairs=split(/\&/,$what);
2542: foreach my $pair (@pairs) {
2543: my ($key,$value)=split(/=/,$pair);
2544: &manage_permissions($key, $udom, $uname,
1.260 foxr 2545: $auth_type);
1.230 foxr 2546: $hashref->{$key}=$value;
2547: }
2548: if (untie($hashref)) {
2549: &Reply($client, "ok\n", $userinput);
2550: } else {
2551: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2552: "while attempting rolesput\n", $userinput);
2553: }
2554: } else {
2555: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2556: "while attempting rolesput\n", $userinput);
2557: }
2558: return 1;
2559: }
2560: ®ister_handler("rolesput", \&roles_put_handler, 1,1,0); # Encoded client only.
2561:
2562: #
1.231 foxr 2563: # Deletes (removes) a role for a user. This is equivalent to removing
2564: # a permissions package associated with the role from the user's profile.
2565: #
2566: # Parameters:
2567: # $cmd - The command (rolesdel)
2568: # $tail - The remainder of the request line. This consists
2569: # of:
2570: # The domain and user requesting the change (logged)
2571: # The domain and user being changed.
2572: # The roles being revoked. These are shipped to us
2573: # as a bunch of & separated role name keywords.
2574: # $client - The file handle open on the client.
2575: # Returns:
2576: # 1 - Continue processing
2577: # 0 - Exit.
2578: #
2579: sub roles_delete_handler {
2580: my ($cmd, $tail, $client) = @_;
2581:
2582: my $userinput = "$cmd:$tail";
2583:
2584: my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
2585: &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
2586: "what = ".$what);
2587: my $namespace='roles';
2588: chomp($what);
2589: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2590: &GDBM_WRCREAT(), "D",
2591: "$exedom:$exeuser:$what");
2592:
2593: if ($hashref) {
2594: my @rolekeys=split(/\&/,$what);
2595:
2596: foreach my $key (@rolekeys) {
2597: delete $hashref->{$key};
2598: }
2599: if (untie(%$hashref)) {
2600: &Reply($client, "ok\n", $userinput);
2601: } else {
2602: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2603: "while attempting rolesdel\n", $userinput);
2604: }
2605: } else {
2606: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2607: "while attempting rolesdel\n", $userinput);
2608: }
2609:
2610: return 1;
2611: }
2612: ®ister_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
2613:
2614: # Unencrypted get from a user's profile database. See
2615: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
2616: # This function retrieves a keyed item from a specific named database in the
2617: # user's directory.
2618: #
2619: # Parameters:
2620: # $cmd - Command request keyword (get).
2621: # $tail - Tail of the command. This is a colon separated list
2622: # consisting of the domain and username that uniquely
2623: # identifies the profile,
2624: # The 'namespace' which selects the gdbm file to
2625: # do the lookup in,
2626: # & separated list of keys to lookup. Note that
2627: # the values are returned as an & separated list too.
2628: # $client - File descriptor open on the client.
2629: # Returns:
2630: # 1 - Continue processing.
2631: # 0 - Exit.
2632: #
2633: sub get_profile_entry {
2634: my ($cmd, $tail, $client) = @_;
2635:
2636: my $userinput= "$cmd:$tail";
2637:
2638: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2639: chomp($what);
1.255 foxr 2640:
2641: my $replystring = read_profile($udom, $uname, $namespace, $what);
2642: my ($first) = split(/:/,$replystring);
2643: if($first ne "error") {
2644: &Reply($client, "$replystring\n", $userinput);
1.231 foxr 2645: } else {
1.255 foxr 2646: &Failure($client, $replystring." while attempting get\n", $userinput);
1.231 foxr 2647: }
2648: return 1;
1.255 foxr 2649:
2650:
1.231 foxr 2651: }
2652: ®ister_handler("get", \&get_profile_entry, 0,1,0);
2653:
2654: #
2655: # Process the encrypted get request. Note that the request is sent
2656: # in clear, but the reply is encrypted. This is a small covert channel:
2657: # information about the sensitive keys is given to the snooper. Just not
2658: # information about the values of the sensitive key. Hmm if I wanted to
2659: # know these I'd snoop for the egets. Get the profile item names from them
2660: # and then issue a get for them since there's no enforcement of the
2661: # requirement of an encrypted get for particular profile items. If I
2662: # were re-doing this, I'd force the request to be encrypted as well as the
2663: # reply. I'd also just enforce encrypted transactions for all gets since
2664: # that would prevent any covert channel snooping.
2665: #
2666: # Parameters:
2667: # $cmd - Command keyword of request (eget).
2668: # $tail - Tail of the command. See GetProfileEntry
# for more information about this.
2669: # $client - File open on the client.
2670: # Returns:
2671: # 1 - Continue processing
2672: # 0 - server should exit.
2673: sub get_profile_entry_encrypted {
2674: my ($cmd, $tail, $client) = @_;
2675:
2676: my $userinput = "$cmd:$tail";
2677:
2678: my ($cmd,$udom,$uname,$namespace,$what) = split(/:/,$userinput);
2679: chomp($what);
1.255 foxr 2680: my $qresult = read_profile($udom, $uname, $namespace, $what);
2681: my ($first) = split(/:/, $qresult);
2682: if($first ne "error") {
2683:
2684: if ($cipher) {
2685: my $cmdlength=length($qresult);
2686: $qresult.=" ";
2687: my $encqresult='';
2688: for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
2689: $encqresult.= unpack("H16",
2690: $cipher->encrypt(substr($qresult,
2691: $encidx,
2692: 8)));
2693: }
2694: &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
2695: } else {
1.231 foxr 2696: &Failure( $client, "error:no_key\n", $userinput);
2697: }
2698: } else {
1.255 foxr 2699: &Failure($client, "$qresult while attempting eget\n", $userinput);
2700:
1.231 foxr 2701: }
2702:
2703: return 1;
2704: }
1.255 foxr 2705: ®ister_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
1.263 albertel 2706:
1.231 foxr 2707: #
2708: # Deletes a key in a user profile database.
2709: #
2710: # Parameters:
2711: # $cmd - Command keyword (del).
2712: # $tail - Command tail. IN this case a colon
2713: # separated list containing:
2714: # The domain and user that identifies uniquely
2715: # the identity of the user.
2716: # The profile namespace (name of the profile
2717: # database file).
2718: # & separated list of keywords to delete.
2719: # $client - File open on client socket.
2720: # Returns:
2721: # 1 - Continue processing
2722: # 0 - Exit server.
2723: #
2724: #
2725: sub delete_profile_entry {
2726: my ($cmd, $tail, $client) = @_;
2727:
2728: my $userinput = "cmd:$tail";
2729:
2730: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
2731: chomp($what);
2732: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2733: &GDBM_WRCREAT(),
2734: "D",$what);
2735: if ($hashref) {
2736: my @keys=split(/\&/,$what);
2737: foreach my $key (@keys) {
2738: delete($hashref->{$key});
2739: }
2740: if (untie(%$hashref)) {
2741: &Reply($client, "ok\n", $userinput);
2742: } else {
2743: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2744: "while attempting del\n", $userinput);
2745: }
2746: } else {
2747: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2748: "while attempting del\n", $userinput);
2749: }
2750: return 1;
2751: }
2752: ®ister_handler("del", \&delete_profile_entry, 0, 1, 0);
1.263 albertel 2753:
1.231 foxr 2754: #
2755: # List the set of keys that are defined in a profile database file.
2756: # A successful reply from this will contain an & separated list of
2757: # the keys.
2758: # Parameters:
2759: # $cmd - Command request (keys).
2760: # $tail - Remainder of the request, a colon separated
2761: # list containing domain/user that identifies the
2762: # user being queried, and the database namespace
2763: # (database filename essentially).
2764: # $client - File open on the client.
2765: # Returns:
2766: # 1 - Continue processing.
2767: # 0 - Exit the server.
2768: #
2769: sub get_profile_keys {
2770: my ($cmd, $tail, $client) = @_;
2771:
2772: my $userinput = "$cmd:$tail";
2773:
2774: my ($udom,$uname,$namespace)=split(/:/,$tail);
2775: my $qresult='';
2776: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2777: &GDBM_READER());
2778: if ($hashref) {
2779: foreach my $key (keys %$hashref) {
2780: $qresult.="$key&";
2781: }
2782: if (untie(%$hashref)) {
2783: $qresult=~s/\&$//;
2784: &Reply($client, "$qresult\n", $userinput);
2785: } else {
2786: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2787: "while attempting keys\n", $userinput);
2788: }
2789: } else {
2790: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2791: "while attempting keys\n", $userinput);
2792: }
2793:
2794: return 1;
2795: }
2796: ®ister_handler("keys", \&get_profile_keys, 0, 1, 0);
2797:
2798: #
2799: # Dump the contents of a user profile database.
2800: # Note that this constitutes a very large covert channel too since
2801: # the dump will return sensitive information that is not encrypted.
2802: # The naive security assumption is that the session negotiation ensures
2803: # our client is trusted and I don't believe that's assured at present.
2804: # Sure want badly to go to ssl or tls. Of course if my peer isn't really
2805: # a LonCAPA node they could have negotiated an encryption key too so >sigh<.
2806: #
2807: # Parameters:
2808: # $cmd - The command request keyword (currentdump).
2809: # $tail - Remainder of the request, consisting of a colon
2810: # separated list that has the domain/username and
2811: # the namespace to dump (database file).
2812: # $client - file open on the remote client.
2813: # Returns:
2814: # 1 - Continue processing.
2815: # 0 - Exit the server.
2816: #
2817: sub dump_profile_database {
2818: my ($cmd, $tail, $client) = @_;
2819:
2820: my $userinput = "$cmd:$tail";
2821:
2822: my ($udom,$uname,$namespace) = split(/:/,$tail);
2823: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2824: &GDBM_READER());
2825: if ($hashref) {
2826: # Structure of %data:
2827: # $data{$symb}->{$parameter}=$value;
2828: # $data{$symb}->{'v.'.$parameter}=$version;
2829: # since $parameter will be unescaped, we do not
2830: # have to worry about silly parameter names...
2831:
2832: my $qresult='';
2833: my %data = (); # A hash of anonymous hashes..
2834: while (my ($key,$value) = each(%$hashref)) {
2835: my ($v,$symb,$param) = split(/:/,$key);
2836: next if ($v eq 'version' || $symb eq 'keys');
2837: next if (exists($data{$symb}) &&
2838: exists($data{$symb}->{$param}) &&
2839: $data{$symb}->{'v.'.$param} > $v);
2840: $data{$symb}->{$param}=$value;
2841: $data{$symb}->{'v.'.$param}=$v;
2842: }
2843: if (untie(%$hashref)) {
2844: while (my ($symb,$param_hash) = each(%data)) {
2845: while(my ($param,$value) = each (%$param_hash)){
2846: next if ($param =~ /^v\./); # Ignore versions...
2847: #
2848: # Just dump the symb=value pairs separated by &
2849: #
2850: $qresult.=$symb.':'.$param.'='.$value.'&';
2851: }
2852: }
2853: chop($qresult);
2854: &Reply($client , "$qresult\n", $userinput);
2855: } else {
2856: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2857: "while attempting currentdump\n", $userinput);
2858: }
2859: } else {
2860: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2861: "while attempting currentdump\n", $userinput);
2862: }
2863:
2864: return 1;
2865: }
2866: ®ister_handler("currentdump", \&dump_profile_database, 0, 1, 0);
2867:
2868: #
2869: # Dump a profile database with an optional regular expression
2870: # to match against the keys. In this dump, no effort is made
2871: # to separate symb from version information. Presumably the
2872: # databases that are dumped by this command are of a different
2873: # structure. Need to look at this and improve the documentation of
2874: # both this and the currentdump handler.
2875: # Parameters:
2876: # $cmd - The command keyword.
2877: # $tail - All of the characters after the $cmd:
2878: # These are expected to be a colon
2879: # separated list containing:
2880: # domain/user - identifying the user.
2881: # namespace - identifying the database.
2882: # regexp - optional regular expression
2883: # that is matched against
2884: # database keywords to do
2885: # selective dumps.
2886: # $client - Channel open on the client.
2887: # Returns:
2888: # 1 - Continue processing.
2889: # Side effects:
2890: # response is written to $client.
2891: #
2892: sub dump_with_regexp {
2893: my ($cmd, $tail, $client) = @_;
2894:
2895:
2896: my $userinput = "$cmd:$tail";
2897:
2898: my ($udom,$uname,$namespace,$regexp)=split(/:/,$tail);
2899: if (defined($regexp)) {
2900: $regexp=&unescape($regexp);
2901: } else {
2902: $regexp='.';
2903: }
2904: my $hashref = &tie_user_hash($udom, $uname, $namespace,
2905: &GDBM_READER());
2906: if ($hashref) {
2907: my $qresult='';
2908: while (my ($key,$value) = each(%$hashref)) {
2909: if ($regexp eq '.') {
2910: $qresult.=$key.'='.$value.'&';
2911: } else {
2912: my $unescapeKey = &unescape($key);
2913: if (eval('$unescapeKey=~/$regexp/')) {
2914: $qresult.="$key=$value&";
2915: }
2916: }
2917: }
2918: if (untie(%$hashref)) {
2919: chop($qresult);
2920: &Reply($client, "$qresult\n", $userinput);
2921: } else {
2922: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
2923: "while attempting dump\n", $userinput);
2924: }
2925: } else {
2926: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
2927: "while attempting dump\n", $userinput);
2928: }
2929:
2930: return 1;
2931: }
2932: ®ister_handler("dump", \&dump_with_regexp, 0, 1, 0);
2933:
2934: # Store a set of key=value pairs associated with a versioned name.
2935: #
2936: # Parameters:
2937: # $cmd - Request command keyword.
2938: # $tail - Tail of the request. This is a colon
2939: # separated list containing:
2940: # domain/user - User and authentication domain.
2941: # namespace - Name of the database being modified
2942: # rid - Resource keyword to modify.
2943: # what - new value associated with rid.
2944: #
2945: # $client - Socket open on the client.
2946: #
2947: #
2948: # Returns:
2949: # 1 (keep on processing).
2950: # Side-Effects:
2951: # Writes to the client
2952: sub store_handler {
2953: my ($cmd, $tail, $client) = @_;
2954:
2955: my $userinput = "$cmd:$tail";
2956:
2957: my ($udom,$uname,$namespace,$rid,$what) =split(/:/,$tail);
2958: if ($namespace ne 'roles') {
2959:
2960: chomp($what);
2961: my @pairs=split(/\&/,$what);
2962: my $hashref = &tie_user_hash($udom, $uname, $namespace,
1.268 albertel 2963: &GDBM_WRCREAT(), "S",
1.231 foxr 2964: "$rid:$what");
2965: if ($hashref) {
2966: my $now = time;
2967: my @previouskeys=split(/&/,$hashref->{"keys:$rid"});
2968: my $key;
2969: $hashref->{"version:$rid"}++;
2970: my $version=$hashref->{"version:$rid"};
2971: my $allkeys='';
2972: foreach my $pair (@pairs) {
2973: my ($key,$value)=split(/=/,$pair);
2974: $allkeys.=$key.':';
2975: $hashref->{"$version:$rid:$key"}=$value;
2976: }
2977: $hashref->{"$version:$rid:timestamp"}=$now;
2978: $allkeys.='timestamp';
2979: $hashref->{"$version:keys:$rid"}=$allkeys;
2980: if (untie($hashref)) {
2981: &Reply($client, "ok\n", $userinput);
2982: } else {
2983: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
2984: "while attempting store\n", $userinput);
2985: }
2986: } else {
2987: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
2988: "while attempting store\n", $userinput);
2989: }
2990: } else {
2991: &Failure($client, "refused\n", $userinput);
2992: }
2993:
2994: return 1;
2995: }
2996: ®ister_handler("store", \&store_handler, 0, 1, 0);
1.263 albertel 2997:
1.231 foxr 2998: #
2999: # Dump out all versions of a resource that has key=value pairs associated
3000: # with it for each version. These resources are built up via the store
3001: # command.
3002: #
3003: # Parameters:
3004: # $cmd - Command keyword.
3005: # $tail - Remainder of the request which consists of:
3006: # domain/user - User and auth. domain.
3007: # namespace - name of resource database.
3008: # rid - Resource id.
3009: # $client - socket open on the client.
3010: #
3011: # Returns:
3012: # 1 indicating the caller should not yet exit.
3013: # Side-effects:
3014: # Writes a reply to the client.
3015: # The reply is a string of the following shape:
3016: # version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
3017: # Where the 1 above represents version 1.
3018: # this continues for all pairs of keys in all versions.
3019: #
3020: #
3021: #
3022: #
3023: sub restore_handler {
3024: my ($cmd, $tail, $client) = @_;
3025:
3026: my $userinput = "$cmd:$tail"; # Only used for logging purposes.
3027:
3028: my ($cmd,$udom,$uname,$namespace,$rid) = split(/:/,$userinput);
3029: $namespace=~s/\//\_/g;
3030: $namespace=~s/\W//g;
3031: chomp($rid);
3032: my $proname=&propath($udom,$uname);
3033: my $qresult='';
3034: my %hash;
3035: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",
3036: &GDBM_READER(),0640)) {
3037: my $version=$hash{"version:$rid"};
3038: $qresult.="version=$version&";
3039: my $scope;
3040: for ($scope=1;$scope<=$version;$scope++) {
3041: my $vkeys=$hash{"$scope:keys:$rid"};
3042: my @keys=split(/:/,$vkeys);
3043: my $key;
3044: $qresult.="$scope:keys=$vkeys&";
3045: foreach $key (@keys) {
3046: $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
3047: }
3048: }
3049: if (untie(%hash)) {
3050: $qresult=~s/\&$//;
3051: &Reply( $client, "$qresult\n", $userinput);
3052: } else {
3053: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3054: "while attempting restore\n", $userinput);
3055: }
3056: } else {
3057: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3058: "while attempting restore\n", $userinput);
3059: }
3060:
3061: return 1;
3062:
3063:
3064: }
3065: ®ister_handler("restore", \&restore_handler, 0,1,0);
1.234 foxr 3066:
3067: #
3068: # Add a chat message to to a discussion board.
3069: #
3070: # Parameters:
3071: # $cmd - Request keyword.
3072: # $tail - Tail of the command. A colon separated list
3073: # containing:
3074: # cdom - Domain on which the chat board lives
3075: # cnum - Identifier of the discussion group.
3076: # post - Body of the posting.
3077: # $client - Socket open on the client.
3078: # Returns:
3079: # 1 - Indicating caller should keep on processing.
3080: #
3081: # Side-effects:
3082: # writes a reply to the client.
3083: #
3084: #
3085: sub send_chat_handler {
3086: my ($cmd, $tail, $client) = @_;
3087:
3088:
3089: my $userinput = "$cmd:$tail";
3090:
3091: my ($cdom,$cnum,$newpost)=split(/\:/,$tail);
3092: &chat_add($cdom,$cnum,$newpost);
3093: &Reply($client, "ok\n", $userinput);
3094:
3095: return 1;
3096: }
3097: ®ister_handler("chatsend", \&send_chat_handler, 0, 1, 0);
1.263 albertel 3098:
1.234 foxr 3099: #
3100: # Retrieve the set of chat messagss from a discussion board.
3101: #
3102: # Parameters:
3103: # $cmd - Command keyword that initiated the request.
3104: # $tail - Remainder of the request after the command
3105: # keyword. In this case a colon separated list of
3106: # chat domain - Which discussion board.
3107: # chat id - Discussion thread(?)
3108: # domain/user - Authentication domain and username
3109: # of the requesting person.
3110: # $client - Socket open on the client program.
3111: # Returns:
3112: # 1 - continue processing
3113: # Side effects:
3114: # Response is written to the client.
3115: #
3116: sub retrieve_chat_handler {
3117: my ($cmd, $tail, $client) = @_;
3118:
3119:
3120: my $userinput = "$cmd:$tail";
3121:
3122: my ($cdom,$cnum,$udom,$uname)=split(/\:/,$tail);
3123: my $reply='';
3124: foreach (&get_chat($cdom,$cnum,$udom,$uname)) {
3125: $reply.=&escape($_).':';
3126: }
3127: $reply=~s/\:$//;
3128: &Reply($client, $reply."\n", $userinput);
3129:
3130:
3131: return 1;
3132: }
3133: ®ister_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
3134:
3135: #
3136: # Initiate a query of an sql database. SQL query repsonses get put in
3137: # a file for later retrieval. This prevents sql query results from
3138: # bottlenecking the system. Note that with loncnew, perhaps this is
3139: # less of an issue since multiple outstanding requests can be concurrently
3140: # serviced.
3141: #
3142: # Parameters:
3143: # $cmd - COmmand keyword that initiated the request.
3144: # $tail - Remainder of the command after the keyword.
3145: # For this function, this consists of a query and
3146: # 3 arguments that are self-documentingly labelled
3147: # in the original arg1, arg2, arg3.
3148: # $client - Socket open on the client.
3149: # Return:
3150: # 1 - Indicating processing should continue.
3151: # Side-effects:
3152: # a reply is written to $client.
3153: #
3154: sub send_query_handler {
3155: my ($cmd, $tail, $client) = @_;
3156:
3157:
3158: my $userinput = "$cmd:$tail";
3159:
3160: my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
3161: $query=~s/\n*$//g;
3162: &Reply($client, "". &sql_reply("$clientname\&$query".
3163: "\&$arg1"."\&$arg2"."\&$arg3")."\n",
3164: $userinput);
3165:
3166: return 1;
3167: }
3168: ®ister_handler("querysend", \&send_query_handler, 0, 1, 0);
3169:
3170: #
3171: # Add a reply to an sql query. SQL queries are done asyncrhonously.
3172: # The query is submitted via a "querysend" transaction.
3173: # There it is passed on to the lonsql daemon, queued and issued to
3174: # mysql.
3175: # This transaction is invoked when the sql transaction is complete
3176: # it stores the query results in flie and indicates query completion.
3177: # presumably local software then fetches this response... I'm guessing
3178: # the sequence is: lonc does a querysend, we ask lonsql to do it.
3179: # lonsql on completion of the query interacts with the lond of our
3180: # client to do a query reply storing two files:
3181: # - id - The results of the query.
3182: # - id.end - Indicating the transaction completed.
3183: # NOTE: id is a unique id assigned to the query and querysend time.
3184: # Parameters:
3185: # $cmd - Command keyword that initiated this request.
3186: # $tail - Remainder of the tail. In this case that's a colon
3187: # separated list containing the query Id and the
3188: # results of the query.
3189: # $client - Socket open on the client.
3190: # Return:
3191: # 1 - Indicating that we should continue processing.
3192: # Side effects:
3193: # ok written to the client.
3194: #
3195: sub reply_query_handler {
3196: my ($cmd, $tail, $client) = @_;
3197:
3198:
3199: my $userinput = "$cmd:$tail";
3200:
3201: my ($cmd,$id,$reply)=split(/:/,$userinput);
3202: my $store;
3203: my $execdir=$perlvar{'lonDaemons'};
3204: if ($store=IO::File->new(">$execdir/tmp/$id")) {
3205: $reply=~s/\&/\n/g;
3206: print $store $reply;
3207: close $store;
3208: my $store2=IO::File->new(">$execdir/tmp/$id.end");
3209: print $store2 "done\n";
3210: close $store2;
3211: &Reply($client, "ok\n", $userinput);
3212: } else {
3213: &Failure($client, "error: ".($!+0)
3214: ." IO::File->new Failed ".
3215: "while attempting queryreply\n", $userinput);
3216: }
3217:
3218:
3219: return 1;
3220: }
3221: ®ister_handler("queryreply", \&reply_query_handler, 0, 1, 0);
3222:
3223: #
3224: # Process the courseidput request. Not quite sure what this means
3225: # at the system level sense. It appears a gdbm file in the
3226: # /home/httpd/lonUsers/$domain/nohist_courseids is tied and
3227: # a set of entries made in that database.
3228: #
3229: # Parameters:
3230: # $cmd - The command keyword that initiated this request.
3231: # $tail - Tail of the command. In this case consists of a colon
3232: # separated list contaning the domain to apply this to and
3233: # an ampersand separated list of keyword=value pairs.
1.272 raeburn 3234: # Each value is a colon separated list that includes:
3235: # description, institutional code and course owner.
3236: # For backward compatibility with versions included
3237: # in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
3238: # code and/or course owner are preserved from the existing
3239: # record when writing a new record in response to 1.1 or
3240: # 1.2 implementations of lonnet::flushcourselogs().
3241: #
1.234 foxr 3242: # $client - Socket open on the client.
3243: # Returns:
3244: # 1 - indicating that processing should continue
3245: #
3246: # Side effects:
3247: # reply is written to the client.
3248: #
3249: sub put_course_id_handler {
3250: my ($cmd, $tail, $client) = @_;
3251:
3252:
3253: my $userinput = "$cmd:$tail";
3254:
1.266 raeburn 3255: my ($udom, $what) = split(/:/, $tail,2);
1.234 foxr 3256: chomp($what);
3257: my $now=time;
3258: my @pairs=split(/\&/,$what);
3259:
3260: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3261: if ($hashref) {
3262: foreach my $pair (@pairs) {
1.271 raeburn 3263: my ($key,$courseinfo) = split(/=/,$pair,2);
3264: $courseinfo =~ s/=/:/g;
1.272 raeburn 3265:
1.273 albertel 3266: my @current_items = split(/:/,$hashref->{$key});
3267: shift(@current_items); # remove description
3268: pop(@current_items); # remove last access
1.272 raeburn 3269: my $numcurrent = scalar(@current_items);
3270:
1.273 albertel 3271: my @new_items = split(/:/,$courseinfo);
1.272 raeburn 3272: my $numnew = scalar(@new_items);
3273: if ($numcurrent > 0) {
3274: if ($numnew == 1) { # flushcourselogs() from 1.1 or earlier
3275: $courseinfo .= ':'.join(':',@current_items);
3276: } elsif ($numnew == 2) { # flushcourselogs() from 1.2.X
3277: $courseinfo .= ':'.$current_items[$numcurrent-1];
3278: }
3279: }
1.266 raeburn 3280: $hashref->{$key}=$courseinfo.':'.$now;
1.234 foxr 3281: }
3282: if (untie(%$hashref)) {
1.253 foxr 3283: &Reply( $client, "ok\n", $userinput);
1.234 foxr 3284: } else {
1.253 foxr 3285: &Failure($client, "error: ".($!+0)
1.234 foxr 3286: ." untie(GDBM) Failed ".
3287: "while attempting courseidput\n", $userinput);
3288: }
3289: } else {
1.253 foxr 3290: &Failure($client, "error: ".($!+0)
1.234 foxr 3291: ." tie(GDBM) Failed ".
3292: "while attempting courseidput\n", $userinput);
3293: }
1.253 foxr 3294:
1.234 foxr 3295:
3296: return 1;
3297: }
3298: ®ister_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
3299:
3300: # Retrieves the value of a course id resource keyword pattern
3301: # defined since a starting date. Both the starting date and the
3302: # keyword pattern are optional. If the starting date is not supplied it
3303: # is treated as the beginning of time. If the pattern is not found,
3304: # it is treatred as "." matching everything.
3305: #
3306: # Parameters:
3307: # $cmd - Command keyword that resulted in us being dispatched.
3308: # $tail - The remainder of the command that, in this case, consists
3309: # of a colon separated list of:
3310: # domain - The domain in which the course database is
3311: # defined.
3312: # since - Optional parameter describing the minimum
3313: # time of definition(?) of the resources that
3314: # will match the dump.
3315: # description - regular expression that is used to filter
3316: # the dump. Only keywords matching this regexp
3317: # will be used.
1.272 raeburn 3318: # institutional code - optional supplied code to filter
3319: # the dump. Only courses with an institutional code
3320: # that match the supplied code will be returned.
3321: # owner - optional supplied username of owner to filter
3322: # the dump. Only courses for which the course
3323: # owner matches the supplied username will be
1.274 albertel 3324: # returned. Implicit assumption that owner
3325: # is a user in the domain in which the
3326: # course database is defined.
1.234 foxr 3327: # $client - The socket open on the client.
3328: # Returns:
3329: # 1 - Continue processing.
3330: # Side Effects:
3331: # a reply is written to $client.
3332: sub dump_course_id_handler {
3333: my ($cmd, $tail, $client) = @_;
3334:
3335: my $userinput = "$cmd:$tail";
3336:
1.282 raeburn 3337: my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter) =split(/:/,$tail);
1.234 foxr 3338: if (defined($description)) {
3339: $description=&unescape($description);
3340: } else {
3341: $description='.';
3342: }
1.266 raeburn 3343: if (defined($instcodefilter)) {
3344: $instcodefilter=&unescape($instcodefilter);
3345: } else {
3346: $instcodefilter='.';
3347: }
3348: if (defined($ownerfilter)) {
3349: $ownerfilter=&unescape($ownerfilter);
3350: } else {
3351: $ownerfilter='.';
3352: }
1.282 raeburn 3353: if (defined($coursefilter)) {
3354: $coursefilter=&unescape($coursefilter);
3355: } else {
3356: $coursefilter='.';
3357: }
1.266 raeburn 3358:
1.234 foxr 3359: unless (defined($since)) { $since=0; }
3360: my $qresult='';
3361: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
3362: if ($hashref) {
3363: while (my ($key,$value) = each(%$hashref)) {
1.266 raeburn 3364: my ($descr,$lasttime,$inst_code,$owner);
1.274 albertel 3365: my @courseitems = split(/:/,$value);
3366: $lasttime = pop(@courseitems);
3367: ($descr,$inst_code,$owner)=@courseitems;
1.234 foxr 3368: if ($lasttime<$since) { next; }
1.266 raeburn 3369: my $match = 1;
3370: unless ($description eq '.') {
3371: my $unescapeDescr = &unescape($descr);
3372: unless (eval('$unescapeDescr=~/\Q$description\E/i')) {
3373: $match = 0;
1.234 foxr 3374: }
1.266 raeburn 3375: }
3376: unless ($instcodefilter eq '.' || !defined($instcodefilter)) {
3377: my $unescapeInstcode = &unescape($inst_code);
3378: unless (eval('$unescapeInstcode=~/\Q$instcodefilter\E/i')) {
3379: $match = 0;
3380: }
1.234 foxr 3381: }
1.266 raeburn 3382: unless ($ownerfilter eq '.' || !defined($ownerfilter)) {
3383: my $unescapeOwner = &unescape($owner);
3384: unless (eval('$unescapeOwner=~/\Q$ownerfilter\E/i')) {
3385: $match = 0;
3386: }
3387: }
1.282 raeburn 3388: unless ($coursefilter eq '.' || !defined($coursefilter)) {
3389: my $unescapeCourse = &unescape($key);
3390: unless (eval('$unescapeCourse=~/^$udom(_)\Q$coursefilter\E$/')) {
3391: $match = 0;
3392: }
3393: }
1.266 raeburn 3394: if ($match == 1) {
3395: $qresult.=$key.'='.$descr.':'.$inst_code.':'.$owner.'&';
3396: }
1.234 foxr 3397: }
3398: if (untie(%$hashref)) {
3399: chop($qresult);
3400: &Reply($client, "$qresult\n", $userinput);
3401: } else {
3402: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3403: "while attempting courseiddump\n", $userinput);
3404: }
3405: } else {
3406: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3407: "while attempting courseiddump\n", $userinput);
3408: }
3409:
3410:
3411: return 1;
3412: }
3413: ®ister_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
1.238 foxr 3414:
3415: #
3416: # Puts an id to a domains id database.
3417: #
3418: # Parameters:
3419: # $cmd - The command that triggered us.
3420: # $tail - Remainder of the request other than the command. This is a
3421: # colon separated list containing:
3422: # $domain - The domain for which we are writing the id.
3423: # $pairs - The id info to write... this is and & separated list
3424: # of keyword=value.
3425: # $client - Socket open on the client.
3426: # Returns:
3427: # 1 - Continue processing.
3428: # Side effects:
3429: # reply is written to $client.
3430: #
3431: sub put_id_handler {
3432: my ($cmd,$tail,$client) = @_;
3433:
3434:
3435: my $userinput = "$cmd:$tail";
3436:
3437: my ($udom,$what)=split(/:/,$tail);
3438: chomp($what);
3439: my @pairs=split(/\&/,$what);
3440: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
3441: "P", $what);
3442: if ($hashref) {
3443: foreach my $pair (@pairs) {
3444: my ($key,$value)=split(/=/,$pair);
3445: $hashref->{$key}=$value;
3446: }
3447: if (untie(%$hashref)) {
3448: &Reply($client, "ok\n", $userinput);
3449: } else {
3450: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3451: "while attempting idput\n", $userinput);
3452: }
3453: } else {
3454: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3455: "while attempting idput\n", $userinput);
3456: }
3457:
3458: return 1;
3459: }
1.263 albertel 3460: ®ister_handler("idput", \&put_id_handler, 0, 1, 0);
1.238 foxr 3461:
3462: #
3463: # Retrieves a set of id values from the id database.
3464: # Returns an & separated list of results, one for each requested id to the
3465: # client.
3466: #
3467: # Parameters:
3468: # $cmd - Command keyword that caused us to be dispatched.
3469: # $tail - Tail of the command. Consists of a colon separated:
3470: # domain - the domain whose id table we dump
3471: # ids Consists of an & separated list of
3472: # id keywords whose values will be fetched.
3473: # nonexisting keywords will have an empty value.
3474: # $client - Socket open on the client.
3475: #
3476: # Returns:
3477: # 1 - indicating processing should continue.
3478: # Side effects:
3479: # An & separated list of results is written to $client.
3480: #
3481: sub get_id_handler {
3482: my ($cmd, $tail, $client) = @_;
3483:
3484:
3485: my $userinput = "$client:$tail";
3486:
3487: my ($udom,$what)=split(/:/,$tail);
3488: chomp($what);
3489: my @queries=split(/\&/,$what);
3490: my $qresult='';
3491: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
3492: if ($hashref) {
3493: for (my $i=0;$i<=$#queries;$i++) {
3494: $qresult.="$hashref->{$queries[$i]}&";
3495: }
3496: if (untie(%$hashref)) {
3497: $qresult=~s/\&$//;
3498: &Reply($client, "$qresult\n", $userinput);
3499: } else {
3500: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3501: "while attempting idget\n",$userinput);
3502: }
3503: } else {
3504: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3505: "while attempting idget\n",$userinput);
3506: }
3507:
3508: return 1;
3509: }
1.263 albertel 3510: ®ister_handler("idget", \&get_id_handler, 0, 1, 0);
1.238 foxr 3511:
3512: #
1.299 raeburn 3513: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database
3514: #
3515: # Parameters
3516: # $cmd - Command keyword that caused us to be dispatched.
3517: # $tail - Tail of the command. Consists of a colon separated:
3518: # domain - the domain whose dcmail we are recording
3519: # email Consists of key=value pair
3520: # where key is unique msgid
3521: # and value is message (in XML)
3522: # $client - Socket open on the client.
3523: #
3524: # Returns:
3525: # 1 - indicating processing should continue.
3526: # Side effects
3527: # reply is written to $client.
3528: #
3529: sub put_dcmail_handler {
3530: my ($cmd,$tail,$client) = @_;
3531: my $userinput = "$cmd:$tail";
3532:
3533: my ($udom,$what)=split(/:/,$tail);
3534: chomp($what);
3535: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
3536: if ($hashref) {
3537: my ($key,$value)=split(/=/,$what);
3538: $hashref->{$key}=$value;
3539: }
3540: if (untie(%$hashref)) {
3541: &Reply($client, "ok\n", $userinput);
3542: } else {
3543: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3544: "while attempting dcmailput\n", $userinput);
3545: }
3546: return 1;
3547: }
3548: ®ister_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
3549:
3550: #
3551: # Retrieves broadcast e-mail from nohist_dcmail database
3552: # Returns to client an & separated list of key=value pairs,
3553: # where key is msgid and value is message information.
3554: #
3555: # Parameters
3556: # $cmd - Command keyword that caused us to be dispatched.
3557: # $tail - Tail of the command. Consists of a colon separated:
3558: # domain - the domain whose dcmail table we dump
3559: # startfilter - beginning of time window
3560: # endfilter - end of time window
3561: # sendersfilter - & separated list of username:domain
3562: # for senders to search for.
3563: # $client - Socket open on the client.
3564: #
3565: # Returns:
3566: # 1 - indicating processing should continue.
3567: # Side effects
3568: # reply (& separated list of msgid=messageinfo pairs) is
3569: # written to $client.
3570: #
3571: sub dump_dcmail_handler {
3572: my ($cmd, $tail, $client) = @_;
3573:
3574: my $userinput = "$cmd:$tail";
3575: my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
3576: chomp($sendersfilter);
3577: my @senders = ();
3578: if (defined($startfilter)) {
3579: $startfilter=&unescape($startfilter);
3580: } else {
3581: $startfilter='.';
3582: }
3583: if (defined($endfilter)) {
3584: $endfilter=&unescape($endfilter);
3585: } else {
3586: $endfilter='.';
3587: }
3588: if (defined($sendersfilter)) {
3589: $sendersfilter=&unescape($sendersfilter);
1.300 albertel 3590: @senders = map { &unescape($_) } split(/\&/,$sendersfilter);
1.299 raeburn 3591: }
3592:
3593: my $qresult='';
3594: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
3595: if ($hashref) {
3596: while (my ($key,$value) = each(%$hashref)) {
3597: my $match = 1;
1.303 albertel 3598: my ($timestamp,$subj,$uname,$udom) =
3599: split(/:/,&unescape(&unescape($key)),5); # yes, twice really
1.299 raeburn 3600: $subj = &unescape($subj);
3601: unless ($startfilter eq '.' || !defined($startfilter)) {
3602: if ($timestamp < $startfilter) {
3603: $match = 0;
3604: }
3605: }
3606: unless ($endfilter eq '.' || !defined($endfilter)) {
3607: if ($timestamp > $endfilter) {
3608: $match = 0;
3609: }
3610: }
3611: unless (@senders < 1) {
3612: unless (grep/^$uname:$udom$/,@senders) {
3613: $match = 0;
3614: }
3615: }
3616: if ($match == 1) {
3617: $qresult.=$key.'='.$value.'&';
3618: }
3619: }
3620: if (untie(%$hashref)) {
3621: chop($qresult);
3622: &Reply($client, "$qresult\n", $userinput);
3623: } else {
3624: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3625: "while attempting dcmaildump\n", $userinput);
3626: }
3627: } else {
3628: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3629: "while attempting dcmaildump\n", $userinput);
3630: }
3631: return 1;
3632: }
3633:
3634: ®ister_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
3635:
3636: #
3637: # Puts domain roles in nohist_domainroles database
3638: #
3639: # Parameters
3640: # $cmd - Command keyword that caused us to be dispatched.
3641: # $tail - Tail of the command. Consists of a colon separated:
3642: # domain - the domain whose roles we are recording
3643: # role - Consists of key=value pair
3644: # where key is unique role
3645: # and value is start/end date information
3646: # $client - Socket open on the client.
3647: #
3648: # Returns:
3649: # 1 - indicating processing should continue.
3650: # Side effects
3651: # reply is written to $client.
3652: #
3653:
3654: sub put_domainroles_handler {
3655: my ($cmd,$tail,$client) = @_;
3656:
3657: my $userinput = "$cmd:$tail";
3658: my ($udom,$what)=split(/:/,$tail);
3659: chomp($what);
3660: my @pairs=split(/\&/,$what);
3661: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
3662: if ($hashref) {
3663: foreach my $pair (@pairs) {
3664: my ($key,$value)=split(/=/,$pair);
3665: $hashref->{$key}=$value;
3666: }
3667: if (untie(%$hashref)) {
3668: &Reply($client, "ok\n", $userinput);
3669: } else {
3670: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3671: "while attempting domroleput\n", $userinput);
3672: }
3673: } else {
3674: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3675: "while attempting domroleput\n", $userinput);
3676: }
3677:
3678: return 1;
3679: }
3680:
3681: ®ister_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
3682:
3683: #
3684: # Retrieves domain roles from nohist_domainroles database
3685: # Returns to client an & separated list of key=value pairs,
3686: # where key is role and value is start and end date information.
3687: #
3688: # Parameters
3689: # $cmd - Command keyword that caused us to be dispatched.
3690: # $tail - Tail of the command. Consists of a colon separated:
3691: # domain - the domain whose domain roles table we dump
3692: # $client - Socket open on the client.
3693: #
3694: # Returns:
3695: # 1 - indicating processing should continue.
3696: # Side effects
3697: # reply (& separated list of role=start/end info pairs) is
3698: # written to $client.
3699: #
3700: sub dump_domainroles_handler {
3701: my ($cmd, $tail, $client) = @_;
3702:
3703: my $userinput = "$cmd:$tail";
3704: my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
3705: chomp($rolesfilter);
3706: my @roles = ();
3707: if (defined($startfilter)) {
3708: $startfilter=&unescape($startfilter);
3709: } else {
3710: $startfilter='.';
3711: }
3712: if (defined($endfilter)) {
3713: $endfilter=&unescape($endfilter);
3714: } else {
3715: $endfilter='.';
3716: }
3717: if (defined($rolesfilter)) {
3718: $rolesfilter=&unescape($rolesfilter);
1.300 albertel 3719: @roles = split(/\&/,$rolesfilter);
1.299 raeburn 3720: }
3721:
3722: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
3723: if ($hashref) {
3724: my $qresult = '';
3725: while (my ($key,$value) = each(%$hashref)) {
3726: my $match = 1;
3727: my ($start,$end) = split(/:/,&unescape($value));
3728: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
3729: unless ($startfilter eq '.' || !defined($startfilter)) {
3730: if ($start >= $startfilter) {
3731: $match = 0;
3732: }
3733: }
3734: unless ($endfilter eq '.' || !defined($endfilter)) {
3735: if ($end <= $endfilter) {
3736: $match = 0;
3737: }
3738: }
3739: unless (@roles < 1) {
3740: unless (grep/^$trole$/,@roles) {
3741: $match = 0;
3742: }
3743: }
3744: if ($match == 1) {
3745: $qresult.=$key.'='.$value.'&';
3746: }
3747: }
3748: if (untie(%$hashref)) {
3749: chop($qresult);
3750: &Reply($client, "$qresult\n", $userinput);
3751: } else {
3752: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3753: "while attempting domrolesdump\n", $userinput);
3754: }
3755: } else {
3756: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3757: "while attempting domrolesdump\n", $userinput);
3758: }
3759: return 1;
3760: }
3761:
3762: ®ister_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
3763:
3764:
1.238 foxr 3765: # Process the tmpput command I'm not sure what this does.. Seems to
3766: # create a file in the lonDaemons/tmp directory of the form $id.tmp
3767: # where Id is the client's ip concatenated with a sequence number.
3768: # The file will contain some value that is passed in. Is this e.g.
3769: # a login token?
3770: #
3771: # Parameters:
3772: # $cmd - The command that got us dispatched.
3773: # $tail - The remainder of the request following $cmd:
3774: # In this case this will be the contents of the file.
3775: # $client - Socket connected to the client.
3776: # Returns:
3777: # 1 indicating processing can continue.
3778: # Side effects:
3779: # A file is created in the local filesystem.
3780: # A reply is sent to the client.
3781: sub tmp_put_handler {
3782: my ($cmd, $what, $client) = @_;
3783:
3784: my $userinput = "$cmd:$what"; # Reconstruct for logging.
3785:
3786:
3787: my $store;
3788: $tmpsnum++;
3789: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
3790: $id=~s/\W/\_/g;
3791: $what=~s/\n//g;
3792: my $execdir=$perlvar{'lonDaemons'};
3793: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
3794: print $store $what;
3795: close $store;
3796: &Reply($client, "$id\n", $userinput);
3797: } else {
3798: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
3799: "while attempting tmpput\n", $userinput);
3800: }
3801: return 1;
3802:
3803: }
3804: ®ister_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
1.263 albertel 3805:
1.238 foxr 3806: # Processes the tmpget command. This command returns the contents
3807: # of a temporary resource file(?) created via tmpput.
3808: #
3809: # Paramters:
3810: # $cmd - Command that got us dispatched.
3811: # $id - Tail of the command, contain the id of the resource
3812: # we want to fetch.
3813: # $client - socket open on the client.
3814: # Return:
3815: # 1 - Inidcating processing can continue.
3816: # Side effects:
3817: # A reply is sent to the client.
3818: #
3819: sub tmp_get_handler {
3820: my ($cmd, $id, $client) = @_;
3821:
3822: my $userinput = "$cmd:$id";
3823:
3824:
3825: $id=~s/\W/\_/g;
3826: my $store;
3827: my $execdir=$perlvar{'lonDaemons'};
3828: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
3829: my $reply=<$store>;
3830: &Reply( $client, "$reply\n", $userinput);
3831: close $store;
3832: } else {
3833: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
3834: "while attempting tmpget\n", $userinput);
3835: }
3836:
3837: return 1;
3838: }
3839: ®ister_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
1.263 albertel 3840:
1.238 foxr 3841: #
3842: # Process the tmpdel command. This command deletes a temp resource
3843: # created by the tmpput command.
3844: #
3845: # Parameters:
3846: # $cmd - Command that got us here.
3847: # $id - Id of the temporary resource created.
3848: # $client - socket open on the client process.
3849: #
3850: # Returns:
3851: # 1 - Indicating processing should continue.
3852: # Side Effects:
3853: # A file is deleted
3854: # A reply is sent to the client.
3855: sub tmp_del_handler {
3856: my ($cmd, $id, $client) = @_;
3857:
3858: my $userinput= "$cmd:$id";
3859:
3860: chomp($id);
3861: $id=~s/\W/\_/g;
3862: my $execdir=$perlvar{'lonDaemons'};
3863: if (unlink("$execdir/tmp/$id.tmp")) {
3864: &Reply($client, "ok\n", $userinput);
3865: } else {
3866: &Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
3867: "while attempting tmpdel\n", $userinput);
3868: }
3869:
3870: return 1;
3871:
3872: }
3873: ®ister_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
1.263 albertel 3874:
1.238 foxr 3875: #
1.246 foxr 3876: # Processes the setannounce command. This command
3877: # creates a file named announce.txt in the top directory of
3878: # the documentn root and sets its contents. The announce.txt file is
3879: # printed in its entirety at the LonCAPA login page. Note:
3880: # once the announcement.txt fileis created it cannot be deleted.
3881: # However, setting the contents of the file to empty removes the
3882: # announcement from the login page of loncapa so who cares.
3883: #
3884: # Parameters:
3885: # $cmd - The command that got us dispatched.
3886: # $announcement - The text of the announcement.
3887: # $client - Socket open on the client process.
3888: # Retunrns:
3889: # 1 - Indicating request processing should continue
3890: # Side Effects:
3891: # The file {DocRoot}/announcement.txt is created.
3892: # A reply is sent to $client.
3893: #
3894: sub set_announce_handler {
3895: my ($cmd, $announcement, $client) = @_;
3896:
3897: my $userinput = "$cmd:$announcement";
3898:
3899: chomp($announcement);
3900: $announcement=&unescape($announcement);
3901: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
3902: '/announcement.txt')) {
3903: print $store $announcement;
3904: close $store;
3905: &Reply($client, "ok\n", $userinput);
3906: } else {
3907: &Failure($client, "error: ".($!+0)."\n", $userinput);
3908: }
3909:
3910: return 1;
3911: }
3912: ®ister_handler("setannounce", \&set_announce_handler, 0, 1, 0);
1.263 albertel 3913:
1.246 foxr 3914: #
3915: # Return the version of the daemon. This can be used to determine
3916: # the compatibility of cross version installations or, alternatively to
3917: # simply know who's out of date and who isn't. Note that the version
3918: # is returned concatenated with the tail.
3919: # Parameters:
3920: # $cmd - the request that dispatched to us.
3921: # $tail - Tail of the request (client's version?).
3922: # $client - Socket open on the client.
3923: #Returns:
3924: # 1 - continue processing requests.
3925: # Side Effects:
3926: # Replies with version to $client.
3927: sub get_version_handler {
3928: my ($cmd, $tail, $client) = @_;
3929:
3930: my $userinput = $cmd.$tail;
3931:
3932: &Reply($client, &version($userinput)."\n", $userinput);
3933:
3934:
3935: return 1;
3936: }
3937: ®ister_handler("version", \&get_version_handler, 0, 1, 0);
1.263 albertel 3938:
1.246 foxr 3939: # Set the current host and domain. This is used to support
3940: # multihomed systems. Each IP of the system, or even separate daemons
3941: # on the same IP can be treated as handling a separate lonCAPA virtual
3942: # machine. This command selects the virtual lonCAPA. The client always
3943: # knows the right one since it is lonc and it is selecting the domain/system
3944: # from the hosts.tab file.
3945: # Parameters:
3946: # $cmd - Command that dispatched us.
3947: # $tail - Tail of the command (domain/host requested).
3948: # $socket - Socket open on the client.
3949: #
3950: # Returns:
3951: # 1 - Indicates the program should continue to process requests.
3952: # Side-effects:
3953: # The default domain/system context is modified for this daemon.
3954: # a reply is sent to the client.
3955: #
3956: sub set_virtual_host_handler {
3957: my ($cmd, $tail, $socket) = @_;
3958:
3959: my $userinput ="$cmd:$tail";
3960:
3961: &Reply($client, &sethost($userinput)."\n", $userinput);
3962:
3963:
3964: return 1;
3965: }
1.247 albertel 3966: ®ister_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
1.246 foxr 3967:
3968: # Process a request to exit:
3969: # - "bye" is sent to the client.
3970: # - The client socket is shutdown and closed.
3971: # - We indicate to the caller that we should exit.
3972: # Formal Parameters:
3973: # $cmd - The command that got us here.
3974: # $tail - Tail of the command (empty).
3975: # $client - Socket open on the tail.
3976: # Returns:
3977: # 0 - Indicating the program should exit!!
3978: #
3979: sub exit_handler {
3980: my ($cmd, $tail, $client) = @_;
3981:
3982: my $userinput = "$cmd:$tail";
3983:
3984: &logthis("Client $clientip ($clientname) hanging up: $userinput");
3985: &Reply($client, "bye\n", $userinput);
3986: $client->shutdown(2); # shutdown the socket forcibly.
3987: $client->close();
3988:
3989: return 0;
3990: }
1.248 foxr 3991: ®ister_handler("exit", \&exit_handler, 0,1,1);
3992: ®ister_handler("init", \&exit_handler, 0,1,1);
3993: ®ister_handler("quit", \&exit_handler, 0,1,1);
3994:
3995: # Determine if auto-enrollment is enabled.
3996: # Note that the original had what I believe to be a defect.
3997: # The original returned 0 if the requestor was not a registerd client.
3998: # It should return "refused".
3999: # Formal Parameters:
4000: # $cmd - The command that invoked us.
4001: # $tail - The tail of the command (Extra command parameters.
4002: # $client - The socket open on the client that issued the request.
4003: # Returns:
4004: # 1 - Indicating processing should continue.
4005: #
4006: sub enrollment_enabled_handler {
4007: my ($cmd, $tail, $client) = @_;
4008: my $userinput = $cmd.":".$tail; # For logging purposes.
4009:
4010:
4011: my $cdom = split(/:/, $tail); # Domain we're asking about.
4012: my $outcome = &localenroll::run($cdom);
4013: &Reply($client, "$outcome\n", $userinput);
4014:
4015: return 1;
4016: }
4017: ®ister_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
4018:
4019: # Get the official sections for which auto-enrollment is possible.
4020: # Since the admin people won't know about 'unofficial sections'
4021: # we cannot auto-enroll on them.
4022: # Formal Parameters:
4023: # $cmd - The command request that got us dispatched here.
4024: # $tail - The remainder of the request. In our case this
4025: # will be split into:
4026: # $coursecode - The course name from the admin point of view.
4027: # $cdom - The course's domain(?).
4028: # $client - Socket open on the client.
4029: # Returns:
4030: # 1 - Indiciting processing should continue.
4031: #
4032: sub get_sections_handler {
4033: my ($cmd, $tail, $client) = @_;
4034: my $userinput = "$cmd:$tail";
4035:
4036: my ($coursecode, $cdom) = split(/:/, $tail);
4037: my @secs = &localenroll::get_sections($coursecode,$cdom);
4038: my $seclist = &escape(join(':',@secs));
4039:
4040: &Reply($client, "$seclist\n", $userinput);
4041:
4042:
4043: return 1;
4044: }
4045: ®ister_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
4046:
4047: # Validate the owner of a new course section.
4048: #
4049: # Formal Parameters:
4050: # $cmd - Command that got us dispatched.
4051: # $tail - the remainder of the command. For us this consists of a
4052: # colon separated string containing:
4053: # $inst - Course Id from the institutions point of view.
4054: # $owner - Proposed owner of the course.
4055: # $cdom - Domain of the course (from the institutions
4056: # point of view?)..
4057: # $client - Socket open on the client.
4058: #
4059: # Returns:
4060: # 1 - Processing should continue.
4061: #
4062: sub validate_course_owner_handler {
4063: my ($cmd, $tail, $client) = @_;
4064: my $userinput = "$cmd:$tail";
4065: my ($inst_course_id, $owner, $cdom) = split(/:/, $tail);
4066:
4067: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
4068: &Reply($client, "$outcome\n", $userinput);
4069:
4070:
4071:
4072: return 1;
4073: }
4074: ®ister_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
1.263 albertel 4075:
1.248 foxr 4076: #
4077: # Validate a course section in the official schedule of classes
4078: # from the institutions point of view (part of autoenrollment).
4079: #
4080: # Formal Parameters:
4081: # $cmd - The command request that got us dispatched.
4082: # $tail - The tail of the command. In this case,
4083: # this is a colon separated set of words that will be split
4084: # into:
4085: # $inst_course_id - The course/section id from the
4086: # institutions point of view.
4087: # $cdom - The domain from the institutions
4088: # point of view.
4089: # $client - Socket open on the client.
4090: # Returns:
4091: # 1 - Indicating processing should continue.
4092: #
4093: sub validate_course_section_handler {
4094: my ($cmd, $tail, $client) = @_;
4095: my $userinput = "$cmd:$tail";
4096: my ($inst_course_id, $cdom) = split(/:/, $tail);
4097:
4098: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
4099: &Reply($client, "$outcome\n", $userinput);
4100:
4101:
4102: return 1;
4103: }
4104: ®ister_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
4105:
4106: #
4107: # Create a password for a new auto-enrollment user.
4108: # I think/guess, this password allows access to the institutions
4109: # AIS class list server/services. Stuart can correct this comment
4110: # when he finds out how wrong I am.
4111: #
4112: # Formal Parameters:
4113: # $cmd - The command request that got us dispatched.
4114: # $tail - The tail of the command. In this case this is a colon separated
4115: # set of words that will be split into:
4116: # $authparam - An authentication parameter (username??).
4117: # $cdom - The domain of the course from the institution's
4118: # point of view.
4119: # $client - The socket open on the client.
4120: # Returns:
4121: # 1 - continue processing.
4122: #
4123: sub create_auto_enroll_password_handler {
4124: my ($cmd, $tail, $client) = @_;
4125: my $userinput = "$cmd:$tail";
4126:
4127: my ($authparam, $cdom) = split(/:/, $userinput);
4128:
4129: my ($create_passwd,$authchk);
4130: ($authparam,
4131: $create_passwd,
4132: $authchk) = &localenroll::create_password($authparam,$cdom);
4133:
4134: &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
4135: $userinput);
4136:
4137:
4138: return 1;
4139: }
4140: ®ister_handler("autocreatepassword", \&create_auto_enroll_password_handler,
4141: 0, 1, 0);
4142:
4143: # Retrieve and remove temporary files created by/during autoenrollment.
4144: #
4145: # Formal Parameters:
4146: # $cmd - The command that got us dispatched.
4147: # $tail - The tail of the command. In our case this is a colon
4148: # separated list that will be split into:
4149: # $filename - The name of the file to remove.
4150: # The filename is given as a path relative to
4151: # the LonCAPA temp file directory.
4152: # $client - Socket open on the client.
4153: #
4154: # Returns:
4155: # 1 - Continue processing.
4156: sub retrieve_auto_file_handler {
4157: my ($cmd, $tail, $client) = @_;
4158: my $userinput = "cmd:$tail";
4159:
4160: my ($filename) = split(/:/, $tail);
4161:
4162: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
4163: if ( (-e $source) && ($filename ne '') ) {
4164: my $reply = '';
4165: if (open(my $fh,$source)) {
4166: while (<$fh>) {
4167: chomp($_);
4168: $_ =~ s/^\s+//g;
4169: $_ =~ s/\s+$//g;
4170: $reply .= $_;
4171: }
4172: close($fh);
4173: &Reply($client, &escape($reply)."\n", $userinput);
4174:
4175: # Does this have to be uncommented??!? (RF).
4176: #
4177: # unlink($source);
4178: } else {
4179: &Failure($client, "error\n", $userinput);
4180: }
4181: } else {
4182: &Failure($client, "error\n", $userinput);
4183: }
4184:
4185:
4186: return 1;
4187: }
4188: ®ister_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
4189:
4190: #
4191: # Read and retrieve institutional code format (for support form).
4192: # Formal Parameters:
4193: # $cmd - Command that dispatched us.
4194: # $tail - Tail of the command. In this case it conatins
4195: # the course domain and the coursename.
4196: # $client - Socket open on the client.
4197: # Returns:
4198: # 1 - Continue processing.
4199: #
4200: sub get_institutional_code_format_handler {
4201: my ($cmd, $tail, $client) = @_;
4202: my $userinput = "$cmd:$tail";
4203:
4204: my $reply;
4205: my($cdom,$course) = split(/:/,$tail);
4206: my @pairs = split/\&/,$course;
4207: my %instcodes = ();
4208: my %codes = ();
4209: my @codetitles = ();
4210: my %cat_titles = ();
4211: my %cat_order = ();
4212: foreach (@pairs) {
4213: my ($key,$value) = split/=/,$_;
4214: $instcodes{&unescape($key)} = &unescape($value);
4215: }
4216: my $formatreply = &localenroll::instcode_format($cdom,
4217: \%instcodes,
4218: \%codes,
4219: \@codetitles,
4220: \%cat_titles,
4221: \%cat_order);
4222: if ($formatreply eq 'ok') {
4223: my $codes_str = &hash2str(%codes);
4224: my $codetitles_str = &array2str(@codetitles);
4225: my $cat_titles_str = &hash2str(%cat_titles);
4226: my $cat_order_str = &hash2str(%cat_order);
4227: &Reply($client,
4228: $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
4229: .$cat_order_str."\n",
4230: $userinput);
4231: } else {
4232: # this else branch added by RF since if not ok, lonc will
4233: # hang waiting on reply until timeout.
4234: #
4235: &Reply($client, "format_error\n", $userinput);
4236: }
4237:
4238: return 1;
4239: }
1.265 albertel 4240: ®ister_handler("autoinstcodeformat",
4241: \&get_institutional_code_format_handler,0,1,0);
1.246 foxr 4242:
1.265 albertel 4243: #
4244: # Gets a student's photo to exist (in the correct image type) in the user's
4245: # directory.
4246: # Formal Parameters:
4247: # $cmd - The command request that got us dispatched.
4248: # $tail - A colon separated set of words that will be split into:
4249: # $domain - student's domain
4250: # $uname - student username
4251: # $type - image type desired
4252: # $client - The socket open on the client.
4253: # Returns:
4254: # 1 - continue processing.
4255: sub student_photo_handler {
4256: my ($cmd, $tail, $client) = @_;
4257: my ($domain,$uname,$type) = split(/:/, $tail);
4258:
4259: my $path=&propath($domain,$uname).
4260: '/userfiles/internal/studentphoto.'.$type;
4261: if (-e $path) {
4262: &Reply($client,"ok\n","$cmd:$tail");
4263: return 1;
4264: }
4265: &mkpath($path);
4266: my $file=&localstudentphoto::fetch($domain,$uname);
4267: if (!$file) {
4268: &Failure($client,"unavailable\n","$cmd:$tail");
4269: return 1;
4270: }
4271: if (!-e $path) { &convert_photo($file,$path); }
4272: if (-e $path) {
4273: &Reply($client,"ok\n","$cmd:$tail");
4274: return 1;
4275: }
4276: &Failure($client,"unable_to_convert\n","$cmd:$tail");
4277: return 1;
4278: }
4279: ®ister_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
1.246 foxr 4280:
1.264 albertel 4281: # mkpath makes all directories for a file, expects an absolute path with a
4282: # file or a trailing / if just a dir is passed
4283: # returns 1 on success 0 on failure
4284: sub mkpath {
4285: my ($file)=@_;
4286: my @parts=split(/\//,$file,-1);
4287: my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
4288: for (my $i=3;$i<= ($#parts-1);$i++) {
1.265 albertel 4289: $now.='/'.$parts[$i];
1.264 albertel 4290: if (!-e $now) {
4291: if (!mkdir($now,0770)) { return 0; }
4292: }
4293: }
4294: return 1;
4295: }
4296:
1.207 foxr 4297: #---------------------------------------------------------------
4298: #
4299: # Getting, decoding and dispatching requests:
4300: #
4301: #
4302: # Get a Request:
4303: # Gets a Request message from the client. The transaction
4304: # is defined as a 'line' of text. We remove the new line
4305: # from the text line.
1.226 foxr 4306: #
1.211 albertel 4307: sub get_request {
1.207 foxr 4308: my $input = <$client>;
4309: chomp($input);
1.226 foxr 4310:
1.234 foxr 4311: &Debug("get_request: Request = $input\n");
1.207 foxr 4312:
4313: &status('Processing '.$clientname.':'.$input);
4314:
4315: return $input;
4316: }
1.212 foxr 4317: #---------------------------------------------------------------
4318: #
4319: # Process a request. This sub should shrink as each action
4320: # gets farmed out into a separat sub that is registered
4321: # with the dispatch hash.
4322: #
4323: # Parameters:
4324: # user_input - The request received from the client (lonc).
4325: # Returns:
4326: # true to keep processing, false if caller should exit.
4327: #
4328: sub process_request {
4329: my ($userinput) = @_; # Easier for now to break style than to
4330: # fix all the userinput -> user_input.
4331: my $wasenc = 0; # True if request was encrypted.
4332: # ------------------------------------------------------------ See if encrypted
4333: if ($userinput =~ /^enc/) {
4334: $userinput = decipher($userinput);
4335: $wasenc=1;
4336: if(!$userinput) { # Cipher not defined.
1.251 foxr 4337: &Failure($client, "error: Encrypted data without negotated key\n");
1.212 foxr 4338: return 0;
4339: }
4340: }
4341: Debug("process_request: $userinput\n");
4342:
1.213 foxr 4343: #
4344: # The 'correct way' to add a command to lond is now to
4345: # write a sub to execute it and Add it to the command dispatch
4346: # hash via a call to register_handler.. The comments to that
4347: # sub should give you enough to go on to show how to do this
4348: # along with the examples that are building up as this code
4349: # is getting refactored. Until all branches of the
4350: # if/elseif monster below have been factored out into
4351: # separate procesor subs, if the dispatch hash is missing
4352: # the command keyword, we will fall through to the remainder
4353: # of the if/else chain below in order to keep this thing in
4354: # working order throughout the transmogrification.
4355:
4356: my ($command, $tail) = split(/:/, $userinput, 2);
4357: chomp($command);
4358: chomp($tail);
4359: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
1.214 foxr 4360: $command =~ s/(\r)//; # And this too for parameterless commands.
4361: if(!$tail) {
4362: $tail =""; # defined but blank.
4363: }
1.213 foxr 4364:
4365: &Debug("Command received: $command, encoded = $wasenc");
4366:
4367: if(defined $Dispatcher{$command}) {
4368:
4369: my $dispatch_info = $Dispatcher{$command};
4370: my $handler = $$dispatch_info[0];
4371: my $need_encode = $$dispatch_info[1];
4372: my $client_types = $$dispatch_info[2];
4373: Debug("Matched dispatch hash: mustencode: $need_encode "
4374: ."ClientType $client_types");
4375:
4376: # Validate the request:
4377:
4378: my $ok = 1;
4379: my $requesterprivs = 0;
4380: if(&isClient()) {
4381: $requesterprivs |= $CLIENT_OK;
4382: }
4383: if(&isManager()) {
4384: $requesterprivs |= $MANAGER_OK;
4385: }
4386: if($need_encode && (!$wasenc)) {
4387: Debug("Must encode but wasn't: $need_encode $wasenc");
4388: $ok = 0;
4389: }
4390: if(($client_types & $requesterprivs) == 0) {
4391: Debug("Client not privileged to do this operation");
4392: $ok = 0;
4393: }
4394:
4395: if($ok) {
4396: Debug("Dispatching to handler $command $tail");
4397: my $keep_going = &$handler($command, $tail, $client);
4398: return $keep_going;
4399: } else {
4400: Debug("Refusing to dispatch because client did not match requirements");
4401: Failure($client, "refused\n", $userinput);
4402: return 1;
4403: }
4404:
4405: }
4406:
1.262 foxr 4407: print $client "unknown_cmd\n";
1.212 foxr 4408: # -------------------------------------------------------------------- complete
4409: Debug("process_request - returning 1");
4410: return 1;
4411: }
1.207 foxr 4412: #
4413: # Decipher encoded traffic
4414: # Parameters:
4415: # input - Encoded data.
4416: # Returns:
4417: # Decoded data or undef if encryption key was not yet negotiated.
4418: # Implicit input:
4419: # cipher - This global holds the negotiated encryption key.
4420: #
1.211 albertel 4421: sub decipher {
1.207 foxr 4422: my ($input) = @_;
4423: my $output = '';
1.212 foxr 4424:
4425:
1.207 foxr 4426: if($cipher) {
4427: my($enc, $enclength, $encinput) = split(/:/, $input);
4428: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
4429: $output .=
4430: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
4431: }
4432: return substr($output, 0, $enclength);
4433: } else {
4434: return undef;
4435: }
4436: }
4437:
4438: #
4439: # Register a command processor. This function is invoked to register a sub
4440: # to process a request. Once registered, the ProcessRequest sub can automatically
4441: # dispatch requests to an appropriate sub, and do the top level validity checking
4442: # as well:
4443: # - Is the keyword recognized.
4444: # - Is the proper client type attempting the request.
4445: # - Is the request encrypted if it has to be.
4446: # Parameters:
4447: # $request_name - Name of the request being registered.
4448: # This is the command request that will match
4449: # against the hash keywords to lookup the information
4450: # associated with the dispatch information.
4451: # $procedure - Reference to a sub to call to process the request.
4452: # All subs get called as follows:
4453: # Procedure($cmd, $tail, $replyfd, $key)
4454: # $cmd - the actual keyword that invoked us.
4455: # $tail - the tail of the request that invoked us.
4456: # $replyfd- File descriptor connected to the client
4457: # $must_encode - True if the request must be encoded to be good.
4458: # $client_ok - True if it's ok for a client to request this.
4459: # $manager_ok - True if it's ok for a manager to request this.
4460: # Side effects:
4461: # - On success, the Dispatcher hash has an entry added for the key $RequestName
4462: # - On failure, the program will die as it's a bad internal bug to try to
4463: # register a duplicate command handler.
4464: #
1.211 albertel 4465: sub register_handler {
1.212 foxr 4466: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
1.207 foxr 4467:
4468: # Don't allow duplication#
4469:
4470: if (defined $Dispatcher{$request_name}) {
4471: die "Attempting to define a duplicate request handler for $request_name\n";
4472: }
4473: # Build the client type mask:
4474:
4475: my $client_type_mask = 0;
4476: if($client_ok) {
4477: $client_type_mask |= $CLIENT_OK;
4478: }
4479: if($manager_ok) {
4480: $client_type_mask |= $MANAGER_OK;
4481: }
4482:
4483: # Enter the hash:
4484:
4485: my @entry = ($procedure, $must_encode, $client_type_mask);
4486:
4487: $Dispatcher{$request_name} = \@entry;
4488:
4489: }
4490:
4491:
4492: #------------------------------------------------------------------
4493:
4494:
4495:
4496:
1.141 foxr 4497: #
1.96 foxr 4498: # Convert an error return code from lcpasswd to a string value.
4499: #
4500: sub lcpasswdstrerror {
4501: my $ErrorCode = shift;
1.97 foxr 4502: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 4503: return "lcpasswd Unrecognized error return value ".$ErrorCode;
4504: } else {
1.98 foxr 4505: return $passwderrors[$ErrorCode];
1.96 foxr 4506: }
4507: }
4508:
1.97 foxr 4509: #
4510: # Convert an error return code from lcuseradd to a string value:
4511: #
4512: sub lcuseraddstrerror {
4513: my $ErrorCode = shift;
4514: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
4515: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
4516: } else {
1.98 foxr 4517: return $adderrors[$ErrorCode];
1.97 foxr 4518: }
4519: }
4520:
1.23 harris41 4521: # grabs exception and records it to log before exiting
4522: sub catchexception {
1.27 albertel 4523: my ($error)=@_;
1.25 www 4524: $SIG{'QUIT'}='DEFAULT';
4525: $SIG{__DIE__}='DEFAULT';
1.165 albertel 4526: &status("Catching exception");
1.190 albertel 4527: &logthis("<font color='red'>CRITICAL: "
1.134 albertel 4528: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27 albertel 4529: ."a crash with this error msg->[$error]</font>");
1.57 www 4530: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 4531: if ($client) { print $client "error: $error\n"; }
1.59 www 4532: $server->close();
1.27 albertel 4533: die($error);
1.23 harris41 4534: }
1.63 www 4535: sub timeout {
1.165 albertel 4536: &status("Handling Timeout");
1.190 albertel 4537: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63 www 4538: &catchexception('Timeout');
4539: }
1.22 harris41 4540: # -------------------------------- Set signal handlers to record abnormal exits
4541:
1.226 foxr 4542:
1.22 harris41 4543: $SIG{'QUIT'}=\&catchexception;
4544: $SIG{__DIE__}=\&catchexception;
4545:
1.81 matthew 4546: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 4547: &status("Read loncapa.conf and loncapa_apache.conf");
4548: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 4549: %perlvar=%{$perlvarref};
1.80 harris41 4550: undef $perlvarref;
1.19 www 4551:
1.35 harris41 4552: # ----------------------------- Make sure this process is running from user=www
4553: my $wwwid=getpwnam('www');
4554: if ($wwwid!=$<) {
1.134 albertel 4555: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
4556: my $subj="LON: $currenthostid User ID mismatch";
1.37 harris41 4557: system("echo 'User ID mismatch. lond must be run as user www.' |\
1.35 harris41 4558: mailto $emailto -s '$subj' > /dev/null");
4559: exit 1;
4560: }
4561:
1.19 www 4562: # --------------------------------------------- Check if other instance running
4563:
4564: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
4565:
4566: if (-e $pidfile) {
4567: my $lfh=IO::File->new("$pidfile");
4568: my $pide=<$lfh>;
4569: chomp($pide);
1.29 harris41 4570: if (kill 0 => $pide) { die "already running"; }
1.19 www 4571: }
1.1 albertel 4572:
4573: # ------------------------------------------------------------- Read hosts file
4574:
4575:
4576:
4577: # establish SERVER socket, bind and listen.
4578: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
4579: Type => SOCK_STREAM,
4580: Proto => 'tcp',
4581: Reuse => 1,
4582: Listen => 10 )
1.29 harris41 4583: or die "making socket: $@\n";
1.1 albertel 4584:
4585: # --------------------------------------------------------- Do global variables
4586:
4587: # global variables
4588:
1.134 albertel 4589: my %children = (); # keys are current child process IDs
1.1 albertel 4590:
4591: sub REAPER { # takes care of dead children
4592: $SIG{CHLD} = \&REAPER;
1.165 albertel 4593: &status("Handling child death");
1.178 foxr 4594: my $pid;
4595: do {
4596: $pid = waitpid(-1,&WNOHANG());
4597: if (defined($children{$pid})) {
4598: &logthis("Child $pid died");
4599: delete($children{$pid});
1.183 albertel 4600: } elsif ($pid > 0) {
1.178 foxr 4601: &logthis("Unknown Child $pid died");
4602: }
4603: } while ( $pid > 0 );
4604: foreach my $child (keys(%children)) {
4605: $pid = waitpid($child,&WNOHANG());
4606: if ($pid > 0) {
4607: &logthis("Child $child - $pid looks like we missed it's death");
4608: delete($children{$pid});
4609: }
1.176 albertel 4610: }
1.165 albertel 4611: &status("Finished Handling child death");
1.1 albertel 4612: }
4613:
4614: sub HUNTSMAN { # signal handler for SIGINT
1.165 albertel 4615: &status("Killing children (INT)");
1.1 albertel 4616: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
4617: kill 'INT' => keys %children;
1.59 www 4618: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 4619: my $execdir=$perlvar{'lonDaemons'};
4620: unlink("$execdir/logs/lond.pid");
1.190 albertel 4621: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165 albertel 4622: &status("Done killing children");
1.1 albertel 4623: exit; # clean up with dignity
4624: }
4625:
4626: sub HUPSMAN { # signal handler for SIGHUP
4627: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.165 albertel 4628: &status("Killing children for restart (HUP)");
1.1 albertel 4629: kill 'INT' => keys %children;
1.59 www 4630: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190 albertel 4631: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134 albertel 4632: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 4633: unlink("$execdir/logs/lond.pid");
1.165 albertel 4634: &status("Restarting self (HUP)");
1.1 albertel 4635: exec("$execdir/lond"); # here we go again
4636: }
4637:
1.144 foxr 4638: #
1.148 foxr 4639: # Kill off hashes that describe the host table prior to re-reading it.
4640: # Hashes affected are:
1.200 matthew 4641: # %hostid, %hostdom %hostip %hostdns.
1.148 foxr 4642: #
4643: sub KillHostHashes {
4644: foreach my $key (keys %hostid) {
4645: delete $hostid{$key};
4646: }
4647: foreach my $key (keys %hostdom) {
4648: delete $hostdom{$key};
4649: }
4650: foreach my $key (keys %hostip) {
4651: delete $hostip{$key};
4652: }
1.200 matthew 4653: foreach my $key (keys %hostdns) {
4654: delete $hostdns{$key};
4655: }
1.148 foxr 4656: }
4657: #
4658: # Read in the host table from file and distribute it into the various hashes:
4659: #
4660: # - %hostid - Indexed by IP, the loncapa hostname.
4661: # - %hostdom - Indexed by loncapa hostname, the domain.
4662: # - %hostip - Indexed by hostid, the Ip address of the host.
4663: sub ReadHostTable {
4664:
4665: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200 matthew 4666: my $myloncapaname = $perlvar{'lonHostID'};
4667: Debug("My loncapa name is : $myloncapaname");
1.296 albertel 4668: my %name_to_ip;
1.148 foxr 4669: while (my $configline=<CONFIG>) {
1.277 albertel 4670: if ($configline !~ /^\s*\#/ && $configline !~ /^\s*$/ ) {
4671: my ($id,$domain,$role,$name)=split(/:/,$configline);
4672: $name=~s/\s//g;
1.296 albertel 4673: my $ip;
4674: if (!exists($name_to_ip{$name})) {
4675: $ip = gethostbyname($name);
4676: if (!$ip || length($ip) ne 4) {
4677: &logthis("Skipping host $id name $name no IP found\n");
4678: next;
4679: }
4680: $ip=inet_ntoa($ip);
4681: $name_to_ip{$name} = $ip;
4682: } else {
4683: $ip = $name_to_ip{$name};
1.277 albertel 4684: }
1.200 matthew 4685: $hostid{$ip}=$id; # LonCAPA name of host by IP.
4686: $hostdom{$id}=$domain; # LonCAPA domain name of host.
1.277 albertel 4687: $hostip{$id}=$ip; # IP address of host.
1.200 matthew 4688: $hostdns{$name} = $id; # LonCAPA name of host by DNS.
4689:
4690: if ($id eq $perlvar{'lonHostID'}) {
4691: Debug("Found me in the host table: $name");
4692: $thisserver=$name;
4693: }
1.178 foxr 4694: }
1.148 foxr 4695: }
4696: close(CONFIG);
4697: }
4698: #
4699: # Reload the Apache daemon's state.
1.150 foxr 4700: # This is done by invoking /home/httpd/perl/apachereload
4701: # a setuid perl script that can be root for us to do this job.
1.148 foxr 4702: #
4703: sub ReloadApache {
1.150 foxr 4704: my $execdir = $perlvar{'lonDaemons'};
4705: my $script = $execdir."/apachereload";
4706: system($script);
1.148 foxr 4707: }
4708:
4709: #
1.144 foxr 4710: # Called in response to a USR2 signal.
4711: # - Reread hosts.tab
4712: # - All children connected to hosts that were removed from hosts.tab
4713: # are killed via SIGINT
4714: # - All children connected to previously existing hosts are sent SIGUSR1
4715: # - Our internal hosts hash is updated to reflect the new contents of
4716: # hosts.tab causing connections from hosts added to hosts.tab to
4717: # now be honored.
4718: #
4719: sub UpdateHosts {
1.165 albertel 4720: &status("Reload hosts.tab");
1.147 foxr 4721: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 4722: #
4723: # The %children hash has the set of IP's we currently have children
4724: # on. These need to be matched against records in the hosts.tab
4725: # Any ip's no longer in the table get killed off they correspond to
4726: # either dropped or changed hosts. Note that the re-read of the table
4727: # will take care of new and changed hosts as connections come into being.
4728:
4729:
4730: KillHostHashes;
4731: ReadHostTable;
4732:
4733: foreach my $child (keys %children) {
4734: my $childip = $children{$child};
4735: if(!$hostid{$childip}) {
1.149 foxr 4736: logthis('<font color="blue"> UpdateHosts killing child '
4737: ." $child for ip $childip </font>");
1.148 foxr 4738: kill('INT', $child);
1.149 foxr 4739: } else {
4740: logthis('<font color="green"> keeping child for ip '
4741: ." $childip (pid=$child) </font>");
1.148 foxr 4742: }
4743: }
4744: ReloadApache;
1.165 albertel 4745: &status("Finished reloading hosts.tab");
1.144 foxr 4746: }
4747:
1.148 foxr 4748:
1.57 www 4749: sub checkchildren {
1.165 albertel 4750: &status("Checking on the children (sending signals)");
1.57 www 4751: &initnewstatus();
4752: &logstatus();
4753: &logthis('Going to check on the children');
1.134 albertel 4754: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 4755: foreach (sort keys %children) {
1.221 albertel 4756: #sleep 1;
1.57 www 4757: unless (kill 'USR1' => $_) {
4758: &logthis ('Child '.$_.' is dead');
4759: &logstatus($$.' is dead');
1.221 albertel 4760: delete($children{$_});
1.57 www 4761: }
1.61 harris41 4762: }
1.63 www 4763: sleep 5;
1.212 foxr 4764: $SIG{ALRM} = sub { Debug("timeout");
4765: die "timeout"; };
1.113 albertel 4766: $SIG{__DIE__} = 'DEFAULT';
1.165 albertel 4767: &status("Checking on the children (waiting for reports)");
1.63 www 4768: foreach (sort keys %children) {
4769: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 4770: eval {
4771: alarm(300);
1.63 www 4772: &logthis('Child '.$_.' did not respond');
1.67 albertel 4773: kill 9 => $_;
1.131 albertel 4774: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
4775: #$subj="LON: $currenthostid killed lond process $_";
4776: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
4777: #$execdir=$perlvar{'lonDaemons'};
4778: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.221 albertel 4779: delete($children{$_});
1.113 albertel 4780: alarm(0);
4781: }
1.63 www 4782: }
4783: }
1.113 albertel 4784: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 4785: $SIG{__DIE__} = \&catchexception;
1.165 albertel 4786: &status("Finished checking children");
1.221 albertel 4787: &logthis('Finished Checking children');
1.57 www 4788: }
4789:
1.1 albertel 4790: # --------------------------------------------------------------------- Logging
4791:
4792: sub logthis {
4793: my $message=shift;
4794: my $execdir=$perlvar{'lonDaemons'};
4795: my $fh=IO::File->new(">>$execdir/logs/lond.log");
4796: my $now=time;
4797: my $local=localtime($now);
1.58 www 4798: $lastlog=$local.': '.$message;
1.1 albertel 4799: print $fh "$local ($$): $message\n";
4800: }
4801:
1.77 foxr 4802: # ------------------------- Conditional log if $DEBUG true.
4803: sub Debug {
4804: my $message = shift;
4805: if($DEBUG) {
4806: &logthis($message);
4807: }
4808: }
1.161 foxr 4809:
4810: #
4811: # Sub to do replies to client.. this gives a hook for some
4812: # debug tracing too:
4813: # Parameters:
4814: # fd - File open on client.
4815: # reply - Text to send to client.
4816: # request - Original request from client.
4817: #
4818: sub Reply {
1.192 foxr 4819: my ($fd, $reply, $request) = @_;
1.161 foxr 4820: print $fd $reply;
4821: Debug("Request was $request Reply was $reply");
4822:
1.212 foxr 4823: $Transactions++;
4824: }
4825:
4826:
4827: #
4828: # Sub to report a failure.
4829: # This function:
4830: # - Increments the failure statistic counters.
4831: # - Invokes Reply to send the error message to the client.
4832: # Parameters:
4833: # fd - File descriptor open on the client
4834: # reply - Reply text to emit.
4835: # request - The original request message (used by Reply
4836: # to debug if that's enabled.
4837: # Implicit outputs:
4838: # $Failures- The number of failures is incremented.
4839: # Reply (invoked here) sends a message to the
4840: # client:
4841: #
4842: sub Failure {
4843: my $fd = shift;
4844: my $reply = shift;
4845: my $request = shift;
4846:
4847: $Failures++;
4848: Reply($fd, $reply, $request); # That's simple eh?
1.161 foxr 4849: }
1.57 www 4850: # ------------------------------------------------------------------ Log status
4851:
4852: sub logstatus {
1.178 foxr 4853: &status("Doing logging");
4854: my $docdir=$perlvar{'lonDocRoot'};
4855: {
4856: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200 matthew 4857: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178 foxr 4858: $fh->close();
4859: }
1.221 albertel 4860: &status("Finished $$.txt");
4861: {
4862: open(LOG,">>$docdir/lon-status/londstatus.txt");
4863: flock(LOG,LOCK_EX);
4864: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
4865: .$status."\t".$lastlog."\t $keymode\n";
1.275 albertel 4866: flock(LOG,LOCK_UN);
1.221 albertel 4867: close(LOG);
4868: }
1.178 foxr 4869: &status("Finished logging");
1.57 www 4870: }
4871:
4872: sub initnewstatus {
4873: my $docdir=$perlvar{'lonDocRoot'};
4874: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
4875: my $now=time;
4876: my $local=localtime($now);
4877: print $fh "LOND status $local - parent $$\n\n";
1.64 www 4878: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 4879: while (my $filename=readdir(DIR)) {
1.64 www 4880: unlink("$docdir/lon-status/londchld/$filename");
4881: }
4882: closedir(DIR);
1.57 www 4883: }
4884:
4885: # -------------------------------------------------------------- Status setting
4886:
4887: sub status {
4888: my $what=shift;
4889: my $now=time;
4890: my $local=localtime($now);
1.178 foxr 4891: $status=$local.': '.$what;
4892: $0='lond: '.$what.' '.$local;
1.57 www 4893: }
1.11 www 4894:
4895: # -------------------------------------------------------- Escape Special Chars
4896:
4897: sub escape {
4898: my $str=shift;
4899: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
4900: return $str;
4901: }
4902:
4903: # ----------------------------------------------------- Un-Escape Special Chars
4904:
4905: sub unescape {
4906: my $str=shift;
4907: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
4908: return $str;
4909: }
4910:
1.1 albertel 4911: # ----------------------------------------------------------- Send USR1 to lonc
4912:
4913: sub reconlonc {
4914: my $peerfile=shift;
4915: &logthis("Trying to reconnect for $peerfile");
4916: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
4917: if (my $fh=IO::File->new("$loncfile")) {
4918: my $loncpid=<$fh>;
4919: chomp($loncpid);
4920: if (kill 0 => $loncpid) {
4921: &logthis("lonc at pid $loncpid responding, sending USR1");
4922: kill USR1 => $loncpid;
4923: } else {
1.9 www 4924: &logthis(
1.190 albertel 4925: "<font color='red'>CRITICAL: "
1.9 www 4926: ."lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 4927: }
4928: } else {
1.190 albertel 4929: &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1 albertel 4930: }
4931: }
4932:
4933: # -------------------------------------------------- Non-critical communication
1.11 www 4934:
1.1 albertel 4935: sub subreply {
4936: my ($cmd,$server)=@_;
4937: my $peerfile="$perlvar{'lonSockDir'}/$server";
4938: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
4939: Type => SOCK_STREAM,
4940: Timeout => 10)
4941: or return "con_lost";
4942: print $sclient "$cmd\n";
4943: my $answer=<$sclient>;
4944: chomp($answer);
4945: if (!$answer) { $answer="con_lost"; }
4946: return $answer;
4947: }
4948:
4949: sub reply {
4950: my ($cmd,$server)=@_;
4951: my $answer;
1.115 albertel 4952: if ($server ne $currenthostid) {
1.1 albertel 4953: $answer=subreply($cmd,$server);
4954: if ($answer eq 'con_lost') {
4955: $answer=subreply("ping",$server);
4956: if ($answer ne $server) {
1.115 albertel 4957: &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1 albertel 4958: &reconlonc("$perlvar{'lonSockDir'}/$server");
4959: }
4960: $answer=subreply($cmd,$server);
4961: }
4962: } else {
4963: $answer='self_reply';
4964: }
4965: return $answer;
4966: }
4967:
1.13 www 4968: # -------------------------------------------------------------- Talk to lonsql
4969:
1.234 foxr 4970: sub sql_reply {
1.12 harris41 4971: my ($cmd)=@_;
1.234 foxr 4972: my $answer=&sub_sql_reply($cmd);
4973: if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
1.12 harris41 4974: return $answer;
4975: }
4976:
1.234 foxr 4977: sub sub_sql_reply {
1.12 harris41 4978: my ($cmd)=@_;
4979: my $unixsock="mysqlsock";
4980: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
4981: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
4982: Type => SOCK_STREAM,
4983: Timeout => 10)
4984: or return "con_lost";
4985: print $sclient "$cmd\n";
4986: my $answer=<$sclient>;
4987: chomp($answer);
4988: if (!$answer) { $answer="con_lost"; }
4989: return $answer;
4990: }
4991:
1.1 albertel 4992: # -------------------------------------------- Return path to profile directory
1.11 www 4993:
1.1 albertel 4994: sub propath {
4995: my ($udom,$uname)=@_;
4996: $udom=~s/\W//g;
4997: $uname=~s/\W//g;
1.16 www 4998: my $subdir=$uname.'__';
1.1 albertel 4999: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
5000: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
5001: return $proname;
5002: }
5003:
5004: # --------------------------------------- Is this the home server of an author?
1.11 www 5005:
1.1 albertel 5006: sub ishome {
5007: my $author=shift;
5008: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
5009: my ($udom,$uname)=split(/\//,$author);
5010: my $proname=propath($udom,$uname);
5011: if (-e $proname) {
5012: return 'owner';
5013: } else {
5014: return 'not_owner';
5015: }
5016: }
5017:
5018: # ======================================================= Continue main program
5019: # ---------------------------------------------------- Fork once and dissociate
5020:
1.134 albertel 5021: my $fpid=fork;
1.1 albertel 5022: exit if $fpid;
1.29 harris41 5023: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 5024:
1.29 harris41 5025: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 5026:
5027: # ------------------------------------------------------- Write our PID on disk
5028:
1.134 albertel 5029: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 5030: open (PIDSAVE,">$execdir/logs/lond.pid");
5031: print PIDSAVE "$$\n";
5032: close(PIDSAVE);
1.190 albertel 5033: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57 www 5034: &status('Starting');
1.1 albertel 5035:
1.106 foxr 5036:
1.1 albertel 5037:
5038: # ----------------------------------------------------- Install signal handlers
5039:
1.57 www 5040:
1.1 albertel 5041: $SIG{CHLD} = \&REAPER;
5042: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
5043: $SIG{HUP} = \&HUPSMAN;
1.57 www 5044: $SIG{USR1} = \&checkchildren;
1.144 foxr 5045: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 5046:
1.148 foxr 5047: # Read the host hashes:
5048:
5049: ReadHostTable;
1.106 foxr 5050:
1.286 albertel 5051: my $dist=`$perlvar{'lonDaemons'}/distprobe`;
5052:
1.106 foxr 5053: # --------------------------------------------------------------
5054: # Accept connections. When a connection comes in, it is validated
5055: # and if good, a child process is created to process transactions
5056: # along the connection.
5057:
1.1 albertel 5058: while (1) {
1.165 albertel 5059: &status('Starting accept');
1.106 foxr 5060: $client = $server->accept() or next;
1.165 albertel 5061: &status('Accepted '.$client.' off to spawn');
1.106 foxr 5062: make_new_child($client);
1.165 albertel 5063: &status('Finished spawning');
1.1 albertel 5064: }
5065:
1.212 foxr 5066: sub make_new_child {
5067: my $pid;
5068: # my $cipher; # Now global
5069: my $sigset;
1.178 foxr 5070:
1.212 foxr 5071: $client = shift;
5072: &status('Starting new child '.$client);
5073: &logthis('<font color="green"> Attempting to start child ('.$client.
5074: ")</font>");
5075: # block signal for fork
5076: $sigset = POSIX::SigSet->new(SIGINT);
5077: sigprocmask(SIG_BLOCK, $sigset)
5078: or die "Can't block SIGINT for fork: $!\n";
1.178 foxr 5079:
1.212 foxr 5080: die "fork: $!" unless defined ($pid = fork);
1.178 foxr 5081:
1.212 foxr 5082: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
5083: # connection liveness.
1.178 foxr 5084:
1.212 foxr 5085: #
5086: # Figure out who we're talking to so we can record the peer in
5087: # the pid hash.
5088: #
5089: my $caller = getpeername($client);
5090: my ($port,$iaddr);
5091: if (defined($caller) && length($caller) > 0) {
5092: ($port,$iaddr)=unpack_sockaddr_in($caller);
5093: } else {
5094: &logthis("Unable to determine who caller was, getpeername returned nothing");
5095: }
5096: if (defined($iaddr)) {
5097: $clientip = inet_ntoa($iaddr);
5098: Debug("Connected with $clientip");
5099: } else {
5100: &logthis("Unable to determine clientip");
5101: $clientip='Unavailable';
5102: }
5103:
5104: if ($pid) {
5105: # Parent records the child's birth and returns.
5106: sigprocmask(SIG_UNBLOCK, $sigset)
5107: or die "Can't unblock SIGINT for fork: $!\n";
5108: $children{$pid} = $clientip;
5109: &status('Started child '.$pid);
5110: return;
5111: } else {
5112: # Child can *not* return from this subroutine.
5113: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
5114: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
5115: #don't get intercepted
5116: $SIG{USR1}= \&logstatus;
5117: $SIG{ALRM}= \&timeout;
5118: $lastlog='Forked ';
5119: $status='Forked';
1.178 foxr 5120:
1.212 foxr 5121: # unblock signals
5122: sigprocmask(SIG_UNBLOCK, $sigset)
5123: or die "Can't unblock SIGINT for fork: $!\n";
1.178 foxr 5124:
1.212 foxr 5125: # my $tmpsnum=0; # Now global
5126: #---------------------------------------------------- kerberos 5 initialization
5127: &Authen::Krb5::init_context();
1.297 raeburn 5128: unless (($dist eq 'fedora4') || ($dist eq 'suse9.3')) {
1.286 albertel 5129: &Authen::Krb5::init_ets();
5130: }
1.209 albertel 5131:
1.212 foxr 5132: &status('Accepted connection');
5133: # =============================================================================
5134: # do something with the connection
5135: # -----------------------------------------------------------------------------
5136: # see if we know client and 'check' for spoof IP by ineffective challenge
1.178 foxr 5137:
1.212 foxr 5138: ReadManagerTable; # May also be a manager!!
5139:
1.278 albertel 5140: my $outsideip=$clientip;
5141: if ($clientip eq '127.0.0.1') {
5142: $outsideip=$hostip{$perlvar{'lonHostID'}};
5143: }
5144:
5145: my $clientrec=($hostid{$outsideip} ne undef);
5146: my $ismanager=($managers{$outsideip} ne undef);
1.212 foxr 5147: $clientname = "[unknonwn]";
5148: if($clientrec) { # Establish client type.
5149: $ConnectionType = "client";
1.278 albertel 5150: $clientname = $hostid{$outsideip};
1.212 foxr 5151: if($ismanager) {
5152: $ConnectionType = "both";
5153: }
5154: } else {
5155: $ConnectionType = "manager";
1.278 albertel 5156: $clientname = $managers{$outsideip};
1.212 foxr 5157: }
5158: my $clientok;
1.178 foxr 5159:
1.212 foxr 5160: if ($clientrec || $ismanager) {
5161: &status("Waiting for init from $clientip $clientname");
5162: &logthis('<font color="yellow">INFO: Connection, '.
5163: $clientip.
5164: " ($clientname) connection type = $ConnectionType </font>" );
5165: &status("Connecting $clientip ($clientname))");
5166: my $remotereq=<$client>;
5167: chomp($remotereq);
5168: Debug("Got init: $remotereq");
5169: my $inikeyword = split(/:/, $remotereq);
5170: if ($remotereq =~ /^init/) {
5171: &sethost("sethost:$perlvar{'lonHostID'}");
5172: #
5173: # If the remote is attempting a local init... give that a try:
5174: #
5175: my ($i, $inittype) = split(/:/, $remotereq);
1.209 albertel 5176:
1.212 foxr 5177: # If the connection type is ssl, but I didn't get my
5178: # certificate files yet, then I'll drop back to
5179: # insecure (if allowed).
5180:
5181: if($inittype eq "ssl") {
5182: my ($ca, $cert) = lonssl::CertificateFile;
5183: my $kfile = lonssl::KeyFile;
5184: if((!$ca) ||
5185: (!$cert) ||
5186: (!$kfile)) {
5187: $inittype = ""; # This forces insecure attempt.
5188: &logthis("<font color=\"blue\"> Certificates not "
5189: ."installed -- trying insecure auth</font>");
1.224 foxr 5190: } else { # SSL certificates are in place so
1.212 foxr 5191: } # Leave the inittype alone.
5192: }
5193:
5194: if($inittype eq "local") {
5195: my $key = LocalConnection($client, $remotereq);
5196: if($key) {
5197: Debug("Got local key $key");
5198: $clientok = 1;
5199: my $cipherkey = pack("H32", $key);
5200: $cipher = new IDEA($cipherkey);
5201: print $client "ok:local\n";
5202: &logthis('<font color="green"'
5203: . "Successful local authentication </font>");
5204: $keymode = "local"
1.178 foxr 5205: } else {
1.212 foxr 5206: Debug("Failed to get local key");
5207: $clientok = 0;
5208: shutdown($client, 3);
5209: close $client;
1.178 foxr 5210: }
1.212 foxr 5211: } elsif ($inittype eq "ssl") {
5212: my $key = SSLConnection($client);
5213: if ($key) {
5214: $clientok = 1;
5215: my $cipherkey = pack("H32", $key);
5216: $cipher = new IDEA($cipherkey);
5217: &logthis('<font color="green">'
5218: ."Successfull ssl authentication with $clientname </font>");
5219: $keymode = "ssl";
5220:
1.178 foxr 5221: } else {
1.212 foxr 5222: $clientok = 0;
5223: close $client;
1.178 foxr 5224: }
1.212 foxr 5225:
5226: } else {
5227: my $ok = InsecureConnection($client);
5228: if($ok) {
5229: $clientok = 1;
5230: &logthis('<font color="green">'
5231: ."Successful insecure authentication with $clientname </font>");
5232: print $client "ok\n";
5233: $keymode = "insecure";
1.178 foxr 5234: } else {
1.212 foxr 5235: &logthis('<font color="yellow">'
5236: ."Attempted insecure connection disallowed </font>");
5237: close $client;
5238: $clientok = 0;
1.178 foxr 5239:
5240: }
5241: }
1.212 foxr 5242: } else {
5243: &logthis(
5244: "<font color='blue'>WARNING: "
5245: ."$clientip failed to initialize: >$remotereq< </font>");
5246: &status('No init '.$clientip);
5247: }
5248:
5249: } else {
5250: &logthis(
5251: "<font color='blue'>WARNING: Unknown client $clientip</font>");
5252: &status('Hung up on '.$clientip);
5253: }
5254:
5255: if ($clientok) {
5256: # ---------------- New known client connecting, could mean machine online again
5257:
5258: foreach my $id (keys(%hostip)) {
5259: if ($hostip{$id} ne $clientip ||
5260: $hostip{$currenthostid} eq $clientip) {
5261: # no need to try to do recon's to myself
5262: next;
5263: }
5264: &reconlonc("$perlvar{'lonSockDir'}/$id");
5265: }
5266: &logthis("<font color='green'>Established connection: $clientname</font>");
5267: &status('Will listen to '.$clientname);
5268: # ------------------------------------------------------------ Process requests
5269: my $keep_going = 1;
5270: my $user_input;
5271: while(($user_input = get_request) && $keep_going) {
5272: alarm(120);
5273: Debug("Main: Got $user_input\n");
5274: $keep_going = &process_request($user_input);
1.178 foxr 5275: alarm(0);
1.212 foxr 5276: &status('Listening to '.$clientname." ($keymode)");
1.161 foxr 5277: }
1.212 foxr 5278:
1.59 www 5279: # --------------------------------------------- client unknown or fishy, refuse
1.212 foxr 5280: } else {
1.161 foxr 5281: print $client "refused\n";
5282: $client->close();
1.190 albertel 5283: &logthis("<font color='blue'>WARNING: "
1.161 foxr 5284: ."Rejected client $clientip, closing connection</font>");
5285: }
1.212 foxr 5286: }
1.161 foxr 5287:
1.1 albertel 5288: # =============================================================================
1.161 foxr 5289:
1.190 albertel 5290: &logthis("<font color='red'>CRITICAL: "
1.161 foxr 5291: ."Disconnect from $clientip ($clientname)</font>");
5292:
5293:
5294: # this exit is VERY important, otherwise the child will become
5295: # a producer of more and more children, forking yourself into
5296: # process death.
5297: exit;
1.106 foxr 5298:
1.78 foxr 5299: }
1.261 foxr 5300: #
5301: # Determine if a user is an author for the indicated domain.
5302: #
5303: # Parameters:
5304: # domain - domain to check in .
5305: # user - Name of user to check.
5306: #
5307: # Return:
5308: # 1 - User is an author for domain.
5309: # 0 - User is not an author for domain.
5310: sub is_author {
5311: my ($domain, $user) = @_;
5312:
5313: &Debug("is_author: $user @ $domain");
5314:
5315: my $hashref = &tie_user_hash($domain, $user, "roles",
5316: &GDBM_READER());
5317:
5318: # Author role should show up as a key /domain/_au
1.78 foxr 5319:
1.261 foxr 5320: my $key = "/$domain/_au";
5321: my $value = $hashref->{$key};
1.78 foxr 5322:
1.261 foxr 5323: if(defined($value)) {
5324: &Debug("$user @ $domain is an author");
5325: }
5326:
5327: return defined($value);
5328: }
1.78 foxr 5329: #
5330: # Checks to see if the input roleput request was to set
5331: # an author role. If so, invokes the lchtmldir script to set
5332: # up a correct public_html
5333: # Parameters:
5334: # request - The request sent to the rolesput subchunk.
5335: # We're looking for /domain/_au
5336: # domain - The domain in which the user is having roles doctored.
5337: # user - Name of the user for which the role is being put.
5338: # authtype - The authentication type associated with the user.
5339: #
1.289 albertel 5340: sub manage_permissions {
1.192 foxr 5341: my ($request, $domain, $user, $authtype) = @_;
1.78 foxr 5342:
1.261 foxr 5343: &Debug("manage_permissions: $request $domain $user $authtype");
5344:
1.78 foxr 5345: # See if the request is of the form /$domain/_au
1.289 albertel 5346: if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
1.78 foxr 5347: my $execdir = $perlvar{'lonDaemons'};
5348: my $userhome= "/home/$user" ;
1.134 albertel 5349: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.261 foxr 5350: &Debug("Setting homedir permissions for $userhome");
1.78 foxr 5351: system("$execdir/lchtmldir $userhome $user $authtype");
5352: }
5353: }
1.222 foxr 5354:
5355:
5356: #
5357: # Return the full path of a user password file, whether it exists or not.
5358: # Parameters:
5359: # domain - Domain in which the password file lives.
5360: # user - name of the user.
5361: # Returns:
5362: # Full passwd path:
5363: #
5364: sub password_path {
5365: my ($domain, $user) = @_;
1.264 albertel 5366: return &propath($domain, $user).'/passwd';
1.222 foxr 5367: }
5368:
5369: # Password Filename
5370: # Returns the path to a passwd file given domain and user... only if
5371: # it exists.
5372: # Parameters:
5373: # domain - Domain in which to search.
5374: # user - username.
5375: # Returns:
5376: # - If the password file exists returns its path.
5377: # - If the password file does not exist, returns undefined.
5378: #
5379: sub password_filename {
5380: my ($domain, $user) = @_;
5381:
5382: Debug ("PasswordFilename called: dom = $domain user = $user");
5383:
5384: my $path = &password_path($domain, $user);
5385: Debug("PasswordFilename got path: $path");
5386: if(-e $path) {
5387: return $path;
5388: } else {
5389: return undef;
5390: }
5391: }
5392:
5393: #
5394: # Rewrite the contents of the user's passwd file.
5395: # Parameters:
5396: # domain - domain of the user.
5397: # name - User's name.
5398: # contents - New contents of the file.
5399: # Returns:
5400: # 0 - Failed.
5401: # 1 - Success.
5402: #
5403: sub rewrite_password_file {
5404: my ($domain, $user, $contents) = @_;
5405:
5406: my $file = &password_filename($domain, $user);
5407: if (defined $file) {
5408: my $pf = IO::File->new(">$file");
5409: if($pf) {
5410: print $pf "$contents\n";
5411: return 1;
5412: } else {
5413: return 0;
5414: }
5415: } else {
5416: return 0;
5417: }
5418:
5419: }
5420:
1.78 foxr 5421: #
1.222 foxr 5422: # get_auth_type - Determines the authorization type of a user in a domain.
1.78 foxr 5423:
5424: # Returns the authorization type or nouser if there is no such user.
5425: #
1.222 foxr 5426: sub get_auth_type
1.78 foxr 5427: {
1.192 foxr 5428:
5429: my ($domain, $user) = @_;
1.78 foxr 5430:
1.222 foxr 5431: Debug("get_auth_type( $domain, $user ) \n");
1.78 foxr 5432: my $proname = &propath($domain, $user);
5433: my $passwdfile = "$proname/passwd";
5434: if( -e $passwdfile ) {
5435: my $pf = IO::File->new($passwdfile);
5436: my $realpassword = <$pf>;
5437: chomp($realpassword);
1.79 foxr 5438: Debug("Password info = $realpassword\n");
1.78 foxr 5439: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 5440: Debug("Authtype = $authtype, content = $contentpwd\n");
1.259 raeburn 5441: return "$authtype:$contentpwd";
1.224 foxr 5442: } else {
1.79 foxr 5443: Debug("Returning nouser");
1.78 foxr 5444: return "nouser";
5445: }
1.1 albertel 5446: }
5447:
1.220 foxr 5448: #
5449: # Validate a user given their domain, name and password. This utility
5450: # function is used by both AuthenticateHandler and ChangePasswordHandler
5451: # to validate the login credentials of a user.
5452: # Parameters:
5453: # $domain - The domain being logged into (this is required due to
5454: # the capability for multihomed systems.
5455: # $user - The name of the user being validated.
5456: # $password - The user's propoposed password.
5457: #
5458: # Returns:
5459: # 1 - The domain,user,pasword triplet corresponds to a valid
5460: # user.
5461: # 0 - The domain,user,password triplet is not a valid user.
5462: #
5463: sub validate_user {
5464: my ($domain, $user, $password) = @_;
5465:
5466:
5467: # Why negative ~pi you may well ask? Well this function is about
5468: # authentication, and therefore very important to get right.
5469: # I've initialized the flag that determines whether or not I've
5470: # validated correctly to a value it's not supposed to get.
5471: # At the end of this function. I'll ensure that it's not still that
5472: # value so we don't just wind up returning some accidental value
5473: # as a result of executing an unforseen code path that
1.249 foxr 5474: # did not set $validated. At the end of valid execution paths,
5475: # validated shoule be 1 for success or 0 for failuer.
1.220 foxr 5476:
5477: my $validated = -3.14159;
5478:
5479: # How we authenticate is determined by the type of authentication
5480: # the user has been assigned. If the authentication type is
5481: # "nouser", the user does not exist so we will return 0.
5482:
1.222 foxr 5483: my $contents = &get_auth_type($domain, $user);
1.220 foxr 5484: my ($howpwd, $contentpwd) = split(/:/, $contents);
5485:
5486: my $null = pack("C",0); # Used by kerberos auth types.
5487:
5488: if ($howpwd ne 'nouser') {
5489:
5490: if($howpwd eq "internal") { # Encrypted is in local password file.
5491: $validated = (crypt($password, $contentpwd) eq $contentpwd);
5492: }
5493: elsif ($howpwd eq "unix") { # User is a normal unix user.
5494: $contentpwd = (getpwnam($user))[1];
5495: if($contentpwd) {
5496: if($contentpwd eq 'x') { # Shadow password file...
5497: my $pwauth_path = "/usr/local/sbin/pwauth";
5498: open PWAUTH, "|$pwauth_path" or
5499: die "Cannot invoke authentication";
5500: print PWAUTH "$user\n$password\n";
5501: close PWAUTH;
5502: $validated = ! $?;
5503:
5504: } else { # Passwords in /etc/passwd.
5505: $validated = (crypt($password,
5506: $contentpwd) eq $contentpwd);
5507: }
5508: } else {
5509: $validated = 0;
5510: }
5511: }
5512: elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
5513: if(! ($password =~ /$null/) ) {
5514: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
5515: "",
5516: $contentpwd,,
5517: 'krbtgt',
5518: $contentpwd,
5519: 1,
5520: $password);
5521: if(!$k4error) {
5522: $validated = 1;
1.224 foxr 5523: } else {
1.220 foxr 5524: $validated = 0;
5525: &logthis('krb4: '.$user.', '.$contentpwd.', '.
5526: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
5527: }
1.224 foxr 5528: } else {
1.220 foxr 5529: $validated = 0; # Password has a match with null.
5530: }
1.224 foxr 5531: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
1.220 foxr 5532: if(!($password =~ /$null/)) { # Null password not allowed.
5533: my $krbclient = &Authen::Krb5::parse_name($user.'@'
5534: .$contentpwd);
5535: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
5536: my $krbserver = &Authen::Krb5::parse_name($krbservice);
5537: my $credentials= &Authen::Krb5::cc_default();
5538: $credentials->initialize($krbclient);
1.270 matthew 5539: my $krbreturn = &Authen::Krb5::get_in_tkt_with_password($krbclient,
1.220 foxr 5540: $krbserver,
5541: $password,
5542: $credentials);
5543: $validated = ($krbreturn == 1);
1.224 foxr 5544: } else {
1.220 foxr 5545: $validated = 0;
5546: }
1.224 foxr 5547: } elsif ($howpwd eq "localauth") {
1.220 foxr 5548: # Authenticate via installation specific authentcation method:
5549: $validated = &localauth::localauth($user,
5550: $password,
5551: $contentpwd);
1.224 foxr 5552: } else { # Unrecognized auth is also bad.
1.220 foxr 5553: $validated = 0;
5554: }
5555: } else {
5556: $validated = 0;
5557: }
5558: #
5559: # $validated has the correct stat of the authentication:
5560: #
5561:
5562: unless ($validated != -3.14159) {
1.249 foxr 5563: # I >really really< want to know if this happens.
5564: # since it indicates that user authentication is badly
5565: # broken in some code path.
5566: #
5567: die "ValidateUser - failed to set the value of validated $domain, $user $password";
1.220 foxr 5568: }
5569: return $validated;
5570: }
5571:
5572:
1.84 albertel 5573: sub addline {
5574: my ($fname,$hostid,$ip,$newline)=@_;
5575: my $contents;
5576: my $found=0;
5577: my $expr='^'.$hostid.':'.$ip.':';
5578: $expr =~ s/\./\\\./g;
1.134 albertel 5579: my $sh;
1.84 albertel 5580: if ($sh=IO::File->new("$fname.subscription")) {
5581: while (my $subline=<$sh>) {
5582: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
5583: }
5584: $sh->close();
5585: }
5586: $sh=IO::File->new(">$fname.subscription");
5587: if ($contents) { print $sh $contents; }
5588: if ($newline) { print $sh $newline; }
5589: $sh->close();
5590: return $found;
1.86 www 5591: }
5592:
1.234 foxr 5593: sub get_chat {
1.122 www 5594: my ($cdom,$cname,$udom,$uname)=@_;
1.87 www 5595: my %hash;
5596: my $proname=&propath($cdom,$cname);
5597: my @entries=();
1.88 albertel 5598: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
5599: &GDBM_READER(),0640)) {
5600: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
5601: untie %hash;
1.123 www 5602: }
1.124 www 5603: my @participants=();
1.134 albertel 5604: my $cutoff=time-60;
1.123 www 5605: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124 www 5606: &GDBM_WRCREAT(),0640)) {
5607: $hash{$uname.':'.$udom}=time;
1.123 www 5608: foreach (sort keys %hash) {
5609: if ($hash{$_}>$cutoff) {
1.124 www 5610: $participants[$#participants+1]='active_participant:'.$_;
1.123 www 5611: }
5612: }
5613: untie %hash;
1.86 www 5614: }
1.124 www 5615: return (@participants,@entries);
1.86 www 5616: }
5617:
1.234 foxr 5618: sub chat_add {
1.88 albertel 5619: my ($cdom,$cname,$newchat)=@_;
5620: my %hash;
5621: my $proname=&propath($cdom,$cname);
5622: my @entries=();
1.142 www 5623: my $time=time;
1.88 albertel 5624: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
5625: &GDBM_WRCREAT(),0640)) {
5626: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
5627: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
5628: my ($thentime,$idnum)=split(/\_/,$lastid);
5629: my $newid=$time.'_000000';
5630: if ($thentime==$time) {
5631: $idnum=~s/^0+//;
5632: $idnum++;
5633: $idnum=substr('000000'.$idnum,-6,6);
5634: $newid=$time.'_'.$idnum;
5635: }
5636: $hash{$newid}=$newchat;
5637: my $expired=$time-3600;
5638: foreach (keys %hash) {
5639: my ($thistime)=($_=~/(\d+)\_/);
5640: if ($thistime<$expired) {
1.89 www 5641: delete $hash{$_};
1.88 albertel 5642: }
5643: }
5644: untie %hash;
1.142 www 5645: }
5646: {
5647: my $hfh;
5648: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
5649: print $hfh "$time:".&unescape($newchat)."\n";
5650: }
1.86 www 5651: }
1.84 albertel 5652: }
5653:
5654: sub unsub {
5655: my ($fname,$clientip)=@_;
5656: my $result;
1.188 foxr 5657: my $unsubs = 0; # Number of successful unsubscribes:
5658:
5659:
5660: # An old way subscriptions were handled was to have a
5661: # subscription marker file:
5662:
5663: Debug("Attempting unlink of $fname.$clientname");
1.161 foxr 5664: if (unlink("$fname.$clientname")) {
1.188 foxr 5665: $unsubs++; # Successful unsub via marker file.
5666: }
5667:
5668: # The more modern way to do it is to have a subscription list
5669: # file:
5670:
1.84 albertel 5671: if (-e "$fname.subscription") {
1.161 foxr 5672: my $found=&addline($fname,$clientname,$clientip,'');
1.188 foxr 5673: if ($found) {
5674: $unsubs++;
5675: }
5676: }
5677:
5678: # If either or both of these mechanisms succeeded in unsubscribing a
5679: # resource we can return ok:
5680:
5681: if($unsubs) {
5682: $result = "ok\n";
1.84 albertel 5683: } else {
1.188 foxr 5684: $result = "not_subscribed\n";
1.84 albertel 5685: }
1.188 foxr 5686:
1.84 albertel 5687: return $result;
5688: }
5689:
1.101 www 5690: sub currentversion {
5691: my $fname=shift;
5692: my $version=-1;
5693: my $ulsdir='';
5694: if ($fname=~/^(.+)\/[^\/]+$/) {
5695: $ulsdir=$1;
5696: }
1.114 albertel 5697: my ($fnamere1,$fnamere2);
5698: # remove version if already specified
1.101 www 5699: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 5700: # get the bits that go before and after the version number
5701: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
5702: $fnamere1=$1;
5703: $fnamere2='.'.$2;
5704: }
1.101 www 5705: if (-e $fname) { $version=1; }
5706: if (-e $ulsdir) {
1.134 albertel 5707: if(-d $ulsdir) {
5708: if (opendir(LSDIR,$ulsdir)) {
5709: my $ulsfn;
5710: while ($ulsfn=readdir(LSDIR)) {
1.101 www 5711: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 5712: my $thisfile=$ulsdir.'/'.$ulsfn;
5713: unless (-l $thisfile) {
1.160 www 5714: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 5715: if ($1>$version) { $version=$1; }
5716: }
5717: }
5718: }
5719: closedir(LSDIR);
5720: $version++;
5721: }
5722: }
5723: }
5724: return $version;
1.101 www 5725: }
5726:
5727: sub thisversion {
5728: my $fname=shift;
5729: my $version=-1;
5730: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
5731: $version=$1;
5732: }
5733: return $version;
5734: }
5735:
1.84 albertel 5736: sub subscribe {
5737: my ($userinput,$clientip)=@_;
5738: my $result;
1.293 albertel 5739: my ($cmd,$fname)=split(/:/,$userinput,2);
1.84 albertel 5740: my $ownership=&ishome($fname);
5741: if ($ownership eq 'owner') {
1.101 www 5742: # explitly asking for the current version?
5743: unless (-e $fname) {
5744: my $currentversion=¤tversion($fname);
5745: if (&thisversion($fname)==$currentversion) {
5746: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
5747: my $root=$1;
5748: my $extension=$2;
5749: symlink($root.'.'.$extension,
5750: $root.'.'.$currentversion.'.'.$extension);
1.102 www 5751: unless ($extension=~/\.meta$/) {
5752: symlink($root.'.'.$extension.'.meta',
5753: $root.'.'.$currentversion.'.'.$extension.'.meta');
5754: }
1.101 www 5755: }
5756: }
5757: }
1.84 albertel 5758: if (-e $fname) {
5759: if (-d $fname) {
5760: $result="directory\n";
5761: } else {
1.161 foxr 5762: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 5763: my $now=time;
1.161 foxr 5764: my $found=&addline($fname,$clientname,$clientip,
5765: "$clientname:$clientip:$now\n");
1.84 albertel 5766: if ($found) { $result="$fname\n"; }
5767: # if they were subscribed to only meta data, delete that
5768: # subscription, when you subscribe to a file you also get
5769: # the metadata
5770: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
5771: $fname=~s/\/home\/httpd\/html\/res/raw/;
5772: $fname="http://$thisserver/".$fname;
5773: $result="$fname\n";
5774: }
5775: } else {
5776: $result="not_found\n";
5777: }
5778: } else {
5779: $result="rejected\n";
5780: }
5781: return $result;
5782: }
1.287 foxr 5783: # Change the passwd of a unix user. The caller must have
5784: # first verified that the user is a loncapa user.
5785: #
5786: # Parameters:
5787: # user - Unix user name to change.
5788: # pass - New password for the user.
5789: # Returns:
5790: # ok - if success
5791: # other - Some meaningfule error message string.
5792: # NOTE:
5793: # invokes a setuid script to change the passwd.
5794: sub change_unix_password {
5795: my ($user, $pass) = @_;
5796:
5797: &Debug("change_unix_password");
5798: my $execdir=$perlvar{'lonDaemons'};
5799: &Debug("Opening lcpasswd pipeline");
5800: my $pf = IO::File->new("|$execdir/lcpasswd > "
5801: ."$perlvar{'lonDaemons'}"
5802: ."/logs/lcpasswd.log");
5803: print $pf "$user\n$pass\n$pass\n";
5804: close $pf;
5805: my $err = $?;
5806: return ($err < @passwderrors) ? $passwderrors[$err] :
5807: "pwchange_falure - unknown error";
5808:
5809:
5810: }
5811:
1.91 albertel 5812:
5813: sub make_passwd_file {
1.98 foxr 5814: my ($uname, $umode,$npass,$passfilename)=@_;
1.91 albertel 5815: my $result="ok\n";
5816: if ($umode eq 'krb4' or $umode eq 'krb5') {
5817: {
5818: my $pf = IO::File->new(">$passfilename");
1.261 foxr 5819: if ($pf) {
5820: print $pf "$umode:$npass\n";
5821: } else {
5822: $result = "pass_file_failed_error";
5823: }
1.91 albertel 5824: }
5825: } elsif ($umode eq 'internal') {
5826: my $salt=time;
5827: $salt=substr($salt,6,2);
5828: my $ncpass=crypt($npass,$salt);
5829: {
5830: &Debug("Creating internal auth");
5831: my $pf = IO::File->new(">$passfilename");
1.261 foxr 5832: if($pf) {
5833: print $pf "internal:$ncpass\n";
5834: } else {
5835: $result = "pass_file_failed_error";
5836: }
1.91 albertel 5837: }
5838: } elsif ($umode eq 'localauth') {
5839: {
5840: my $pf = IO::File->new(">$passfilename");
1.261 foxr 5841: if($pf) {
5842: print $pf "localauth:$npass\n";
5843: } else {
5844: $result = "pass_file_failed_error";
5845: }
1.91 albertel 5846: }
5847: } elsif ($umode eq 'unix') {
5848: {
1.186 foxr 5849: #
5850: # Don't allow the creation of privileged accounts!!! that would
5851: # be real bad!!!
5852: #
5853: my $uid = getpwnam($uname);
5854: if((defined $uid) && ($uid == 0)) {
5855: &logthis(">>>Attempted to create privilged account blocked");
5856: return "no_priv_account_error\n";
5857: }
5858:
1.223 foxr 5859: my $execpath ="$perlvar{'lonDaemons'}/"."lcuseradd";
1.224 foxr 5860:
5861: my $lc_error_file = $execdir."/tmp/lcuseradd".$$.".status";
1.91 albertel 5862: {
5863: &Debug("Executing external: ".$execpath);
1.98 foxr 5864: &Debug("user = ".$uname.", Password =". $npass);
1.132 matthew 5865: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91 albertel 5866: print $se "$uname\n";
5867: print $se "$npass\n";
5868: print $se "$npass\n";
1.223 foxr 5869: print $se "$lc_error_file\n"; # Status -> unique file.
1.97 foxr 5870: }
1.285 foxr 5871: if (-r $lc_error_file) {
5872: &Debug("Opening error file: $lc_error_file");
5873: my $error = IO::File->new("< $lc_error_file");
5874: my $useraddok = <$error>;
5875: $error->close;
5876: unlink($lc_error_file);
5877:
5878: chomp $useraddok;
5879:
5880: if($useraddok > 0) {
5881: my $error_text = &lcuseraddstrerror($useraddok);
5882: &logthis("Failed lcuseradd: $error_text");
5883: $result = "lcuseradd_failed:$error_text\n";
5884: } else {
5885: my $pf = IO::File->new(">$passfilename");
5886: if($pf) {
5887: print $pf "unix:\n";
5888: } else {
5889: $result = "pass_file_failed_error";
5890: }
5891: }
1.224 foxr 5892: } else {
1.285 foxr 5893: &Debug("Could not locate lcuseradd error: $lc_error_file");
5894: $result="bug_lcuseradd_no_output_file";
1.91 albertel 5895: }
5896: }
5897: } elsif ($umode eq 'none') {
5898: {
1.223 foxr 5899: my $pf = IO::File->new("> $passfilename");
1.261 foxr 5900: if($pf) {
5901: print $pf "none:\n";
5902: } else {
5903: $result = "pass_file_failed_error";
5904: }
1.91 albertel 5905: }
5906: } else {
5907: $result="auth_mode_error\n";
5908: }
5909: return $result;
1.121 albertel 5910: }
5911:
1.265 albertel 5912: sub convert_photo {
5913: my ($start,$dest)=@_;
5914: system("convert $start $dest");
5915: }
5916:
1.121 albertel 5917: sub sethost {
5918: my ($remotereq) = @_;
5919: my (undef,$hostid)=split(/:/,$remotereq);
5920: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
5921: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200 matthew 5922: $currenthostid =$hostid;
1.121 albertel 5923: $currentdomainid=$hostdom{$hostid};
5924: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
5925: } else {
5926: &logthis("Requested host id $hostid not an alias of ".
5927: $perlvar{'lonHostID'}." refusing connection");
5928: return 'unable_to_set';
5929: }
5930: return 'ok';
5931: }
5932:
5933: sub version {
5934: my ($userinput)=@_;
5935: $remoteVERSION=(split(/:/,$userinput))[1];
5936: return "version:$VERSION";
1.127 albertel 5937: }
1.178 foxr 5938:
1.128 albertel 5939: #There is a copy of this in lonnet.pm
1.127 albertel 5940: sub userload {
5941: my $numusers=0;
5942: {
5943: opendir(LONIDS,$perlvar{'lonIDsDir'});
5944: my $filename;
5945: my $curtime=time;
5946: while ($filename=readdir(LONIDS)) {
5947: if ($filename eq '.' || $filename eq '..') {next;}
1.138 albertel 5948: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159 albertel 5949: if ($curtime-$mtime < 1800) { $numusers++; }
1.127 albertel 5950: }
5951: closedir(LONIDS);
5952: }
5953: my $userloadpercent=0;
5954: my $maxuserload=$perlvar{'lonUserLoadLim'};
5955: if ($maxuserload) {
1.129 albertel 5956: $userloadpercent=100*$numusers/$maxuserload;
1.127 albertel 5957: }
1.130 albertel 5958: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127 albertel 5959: return $userloadpercent;
1.91 albertel 5960: }
5961:
1.205 raeburn 5962: # Routines for serializing arrays and hashes (copies from lonnet)
5963:
5964: sub array2str {
5965: my (@array) = @_;
5966: my $result=&arrayref2str(\@array);
5967: $result=~s/^__ARRAY_REF__//;
5968: $result=~s/__END_ARRAY_REF__$//;
5969: return $result;
5970: }
5971:
5972: sub arrayref2str {
5973: my ($arrayref) = @_;
5974: my $result='__ARRAY_REF__';
5975: foreach my $elem (@$arrayref) {
5976: if(ref($elem) eq 'ARRAY') {
5977: $result.=&arrayref2str($elem).'&';
5978: } elsif(ref($elem) eq 'HASH') {
5979: $result.=&hashref2str($elem).'&';
5980: } elsif(ref($elem)) {
5981: #print("Got a ref of ".(ref($elem))." skipping.");
5982: } else {
5983: $result.=&escape($elem).'&';
5984: }
5985: }
5986: $result=~s/\&$//;
5987: $result .= '__END_ARRAY_REF__';
5988: return $result;
5989: }
5990:
5991: sub hash2str {
5992: my (%hash) = @_;
5993: my $result=&hashref2str(\%hash);
5994: $result=~s/^__HASH_REF__//;
5995: $result=~s/__END_HASH_REF__$//;
5996: return $result;
5997: }
5998:
5999: sub hashref2str {
6000: my ($hashref)=@_;
6001: my $result='__HASH_REF__';
6002: foreach (sort(keys(%$hashref))) {
6003: if (ref($_) eq 'ARRAY') {
6004: $result.=&arrayref2str($_).'=';
6005: } elsif (ref($_) eq 'HASH') {
6006: $result.=&hashref2str($_).'=';
6007: } elsif (ref($_)) {
6008: $result.='=';
6009: #print("Got a ref of ".(ref($_))." skipping.");
6010: } else {
6011: if ($_) {$result.=&escape($_).'=';} else { last; }
6012: }
6013:
6014: if(ref($hashref->{$_}) eq 'ARRAY') {
6015: $result.=&arrayref2str($hashref->{$_}).'&';
6016: } elsif(ref($hashref->{$_}) eq 'HASH') {
6017: $result.=&hashref2str($hashref->{$_}).'&';
6018: } elsif(ref($hashref->{$_})) {
6019: $result.='&';
6020: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
6021: } else {
6022: $result.=&escape($hashref->{$_}).'&';
6023: }
6024: }
6025: $result=~s/\&$//;
6026: $result .= '__END_HASH_REF__';
6027: return $result;
6028: }
1.200 matthew 6029:
1.61 harris41 6030: # ----------------------------------- POD (plain old documentation, CPAN style)
6031:
6032: =head1 NAME
6033:
6034: lond - "LON Daemon" Server (port "LOND" 5663)
6035:
6036: =head1 SYNOPSIS
6037:
1.74 harris41 6038: Usage: B<lond>
6039:
6040: Should only be run as user=www. This is a command-line script which
6041: is invoked by B<loncron>. There is no expectation that a typical user
6042: will manually start B<lond> from the command-line. (In other words,
6043: DO NOT START B<lond> YOURSELF.)
1.61 harris41 6044:
6045: =head1 DESCRIPTION
6046:
1.74 harris41 6047: There are two characteristics associated with the running of B<lond>,
6048: PROCESS MANAGEMENT (starting, stopping, handling child processes)
6049: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
6050: subscriptions, etc). These are described in two large
6051: sections below.
6052:
6053: B<PROCESS MANAGEMENT>
6054:
1.61 harris41 6055: Preforker - server who forks first. Runs as a daemon. HUPs.
6056: Uses IDEA encryption
6057:
1.74 harris41 6058: B<lond> forks off children processes that correspond to the other servers
6059: in the network. Management of these processes can be done at the
6060: parent process level or the child process level.
6061:
6062: B<logs/lond.log> is the location of log messages.
6063:
6064: The process management is now explained in terms of linux shell commands,
6065: subroutines internal to this code, and signal assignments:
6066:
6067: =over 4
6068:
6069: =item *
6070:
6071: PID is stored in B<logs/lond.pid>
6072:
6073: This is the process id number of the parent B<lond> process.
6074:
6075: =item *
6076:
6077: SIGTERM and SIGINT
6078:
6079: Parent signal assignment:
6080: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
6081:
6082: Child signal assignment:
6083: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
6084: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
6085: to restart a new child.)
6086:
6087: Command-line invocations:
6088: B<kill> B<-s> SIGTERM I<PID>
6089: B<kill> B<-s> SIGINT I<PID>
6090:
6091: Subroutine B<HUNTSMAN>:
6092: This is only invoked for the B<lond> parent I<PID>.
6093: This kills all the children, and then the parent.
6094: The B<lonc.pid> file is cleared.
6095:
6096: =item *
6097:
6098: SIGHUP
6099:
6100: Current bug:
6101: This signal can only be processed the first time
6102: on the parent process. Subsequent SIGHUP signals
6103: have no effect.
6104:
6105: Parent signal assignment:
6106: $SIG{HUP} = \&HUPSMAN;
6107:
6108: Child signal assignment:
6109: none (nothing happens)
6110:
6111: Command-line invocations:
6112: B<kill> B<-s> SIGHUP I<PID>
6113:
6114: Subroutine B<HUPSMAN>:
6115: This is only invoked for the B<lond> parent I<PID>,
6116: This kills all the children, and then the parent.
6117: The B<lond.pid> file is cleared.
6118:
6119: =item *
6120:
6121: SIGUSR1
6122:
6123: Parent signal assignment:
6124: $SIG{USR1} = \&USRMAN;
6125:
6126: Child signal assignment:
6127: $SIG{USR1}= \&logstatus;
6128:
6129: Command-line invocations:
6130: B<kill> B<-s> SIGUSR1 I<PID>
6131:
6132: Subroutine B<USRMAN>:
6133: When invoked for the B<lond> parent I<PID>,
6134: SIGUSR1 is sent to all the children, and the status of
6135: each connection is logged.
1.144 foxr 6136:
6137: =item *
6138:
6139: SIGUSR2
6140:
6141: Parent Signal assignment:
6142: $SIG{USR2} = \&UpdateHosts
6143:
6144: Child signal assignment:
6145: NONE
6146:
1.74 harris41 6147:
6148: =item *
6149:
6150: SIGCHLD
6151:
6152: Parent signal assignment:
6153: $SIG{CHLD} = \&REAPER;
6154:
6155: Child signal assignment:
6156: none
6157:
6158: Command-line invocations:
6159: B<kill> B<-s> SIGCHLD I<PID>
6160:
6161: Subroutine B<REAPER>:
6162: This is only invoked for the B<lond> parent I<PID>.
6163: Information pertaining to the child is removed.
6164: The socket port is cleaned up.
6165:
6166: =back
6167:
6168: B<SERVER-SIDE ACTIVITIES>
6169:
6170: Server-side information can be accepted in an encrypted or non-encrypted
6171: method.
6172:
6173: =over 4
6174:
6175: =item ping
6176:
6177: Query a client in the hosts.tab table; "Are you there?"
6178:
6179: =item pong
6180:
6181: Respond to a ping query.
6182:
6183: =item ekey
6184:
6185: Read in encrypted key, make cipher. Respond with a buildkey.
6186:
6187: =item load
6188:
6189: Respond with CPU load based on a computation upon /proc/loadavg.
6190:
6191: =item currentauth
6192:
6193: Reply with current authentication information (only over an
6194: encrypted channel).
6195:
6196: =item auth
6197:
6198: Only over an encrypted channel, reply as to whether a user's
6199: authentication information can be validated.
6200:
6201: =item passwd
6202:
6203: Allow for a password to be set.
6204:
6205: =item makeuser
6206:
6207: Make a user.
6208:
6209: =item passwd
6210:
6211: Allow for authentication mechanism and password to be changed.
6212:
6213: =item home
1.61 harris41 6214:
1.74 harris41 6215: Respond to a question "are you the home for a given user?"
6216:
6217: =item update
6218:
6219: Update contents of a subscribed resource.
6220:
6221: =item unsubscribe
6222:
6223: The server is unsubscribing from a resource.
6224:
6225: =item subscribe
6226:
6227: The server is subscribing to a resource.
6228:
6229: =item log
6230:
6231: Place in B<logs/lond.log>
6232:
6233: =item put
6234:
6235: stores hash in namespace
6236:
1.230 foxr 6237: =item rolesputy
1.74 harris41 6238:
6239: put a role into a user's environment
6240:
6241: =item get
6242:
6243: returns hash with keys from array
6244: reference filled in from namespace
6245:
6246: =item eget
6247:
6248: returns hash with keys from array
6249: reference filled in from namesp (encrypts the return communication)
6250:
6251: =item rolesget
6252:
6253: get a role from a user's environment
6254:
6255: =item del
6256:
6257: deletes keys out of array from namespace
6258:
6259: =item keys
6260:
6261: returns namespace keys
6262:
6263: =item dump
6264:
6265: dumps the complete (or key matching regexp) namespace into a hash
6266:
6267: =item store
6268:
6269: stores hash permanently
6270: for this url; hashref needs to be given and should be a \%hashname; the
6271: remaining args aren't required and if they aren't passed or are '' they will
6272: be derived from the ENV
6273:
6274: =item restore
6275:
6276: returns a hash for a given url
6277:
6278: =item querysend
6279:
6280: Tells client about the lonsql process that has been launched in response
6281: to a sent query.
6282:
6283: =item queryreply
6284:
6285: Accept information from lonsql and make appropriate storage in temporary
6286: file space.
6287:
6288: =item idput
6289:
6290: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
6291: for each student, defined perhaps by the institutional Registrar.)
6292:
6293: =item idget
6294:
6295: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
6296: for each student, defined perhaps by the institutional Registrar.)
6297:
6298: =item tmpput
6299:
6300: Accept and store information in temporary space.
6301:
6302: =item tmpget
6303:
6304: Send along temporarily stored information.
6305:
6306: =item ls
6307:
6308: List part of a user's directory.
6309:
1.135 foxr 6310: =item pushtable
6311:
6312: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
6313: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
6314: must be restored manually in case of a problem with the new table file.
6315: pushtable requires that the request be encrypted and validated via
6316: ValidateManager. The form of the command is:
6317: enc:pushtable tablename <tablecontents> \n
6318: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
6319: cleartext newline.
6320:
1.74 harris41 6321: =item Hanging up (exit or init)
6322:
6323: What to do when a client tells the server that they (the client)
6324: are leaving the network.
6325:
6326: =item unknown command
6327:
6328: If B<lond> is sent an unknown command (not in the list above),
6329: it replys to the client "unknown_cmd".
1.135 foxr 6330:
1.74 harris41 6331:
6332: =item UNKNOWN CLIENT
6333:
6334: If the anti-spoofing algorithm cannot verify the client,
6335: the client is rejected (with a "refused" message sent
6336: to the client, and the connection is closed.
6337:
6338: =back
1.61 harris41 6339:
6340: =head1 PREREQUISITES
6341:
6342: IO::Socket
6343: IO::File
6344: Apache::File
6345: Symbol
6346: POSIX
6347: Crypt::IDEA
6348: LWP::UserAgent()
6349: GDBM_File
6350: Authen::Krb4
1.91 albertel 6351: Authen::Krb5
1.61 harris41 6352:
6353: =head1 COREQUISITES
6354:
6355: =head1 OSNAMES
6356:
6357: linux
6358:
6359: =head1 SCRIPT CATEGORIES
6360:
6361: Server/Process
6362:
6363: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>