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