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