Annotation of loncom/lond, revision 1.214
1.1 albertel 1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
1.60 www 4: #
1.214 ! foxr 5: # $Id: lond,v 1.213 2004/07/27 10:50:37 foxr Exp $
1.60 www 6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
1.167 foxr 13: # the Free Software Foundation; either version 2 of the License, or
1.60 www 14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
1.178 foxr 23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1.60 www 24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
1.161 foxr 27:
28:
1.60 www 29: # http://www.lon-capa.org/
30: #
1.54 harris41 31:
1.134 albertel 32: use strict;
1.80 harris41 33: use lib '/home/httpd/lib/perl/';
34: use LONCAPA::Configuration;
35:
1.1 albertel 36: use IO::Socket;
37: use IO::File;
1.126 albertel 38: #use Apache::File;
1.1 albertel 39: use Symbol;
40: use POSIX;
41: use Crypt::IDEA;
42: use LWP::UserAgent();
1.3 www 43: use GDBM_File;
44: use Authen::Krb4;
1.91 albertel 45: use Authen::Krb5;
1.49 albertel 46: use lib '/home/httpd/lib/perl/';
47: use localauth;
1.193 raeburn 48: use localenroll;
1.143 foxr 49: use File::Copy;
1.169 foxr 50: use LONCAPA::ConfigFileEdit;
1.200 matthew 51: use LONCAPA::lonlocal;
52: use LONCAPA::lonssl;
1.1 albertel 53:
1.204 albertel 54: my $DEBUG = 0; # Non zero to enable debug log entries.
1.77 foxr 55:
1.57 www 56: my $status='';
57: my $lastlog='';
58:
1.214 ! foxr 59: my $VERSION='$Revision: 1.213 $'; #' stupid emacs
1.121 albertel 60: my $remoteVERSION;
1.214 ! foxr 61: my $currenthostid="default";
1.115 albertel 62: my $currentdomainid;
1.134 albertel 63:
64: my $client;
1.200 matthew 65: my $clientip; # IP address of client.
66: my $clientdns; # DNS name of client.
67: my $clientname; # LonCAPA name of client.
1.140 foxr 68:
1.134 albertel 69: my $server;
1.200 matthew 70: my $thisserver; # DNS of us.
71:
72: my $keymode;
1.198 foxr 73:
1.207 foxr 74: my $cipher; # Cipher key negotiated with client
75: my $tmpsnum = 0; # Id of tmpputs.
76:
1.178 foxr 77: #
78: # Connection type is:
79: # client - All client actions are allowed
80: # manager - only management functions allowed.
81: # both - Both management and client actions are allowed
82: #
1.161 foxr 83:
1.178 foxr 84: my $ConnectionType;
1.161 foxr 85:
1.200 matthew 86: my %hostid; # ID's for hosts in cluster by ip.
87: my %hostdom; # LonCAPA domain for hosts in cluster.
88: my %hostip; # IPs for hosts in cluster.
89: my %hostdns; # ID's of hosts looked up by DNS name.
1.161 foxr 90:
1.178 foxr 91: my %managers; # Ip -> manager names
1.161 foxr 92:
1.178 foxr 93: my %perlvar; # Will have the apache conf defined perl vars.
1.134 albertel 94:
1.178 foxr 95: #
1.207 foxr 96: # The hash below is used for command dispatching, and is therefore keyed on the request keyword.
97: # Each element of the hash contains a reference to an array that contains:
98: # A reference to a sub that executes the request corresponding to the keyword.
99: # A flag that is true if the request must be encoded to be acceptable.
100: # A mask with bits as follows:
101: # CLIENT_OK - Set when the function is allowed by ordinary clients
102: # MANAGER_OK - Set when the function is allowed to manager clients.
103: #
104: my $CLIENT_OK = 1;
105: my $MANAGER_OK = 2;
106: my %Dispatcher;
107:
108:
109: #
1.178 foxr 110: # The array below are password error strings."
111: #
112: my $lastpwderror = 13; # Largest error number from lcpasswd.
113: my @passwderrors = ("ok",
114: "lcpasswd must be run as user 'www'",
115: "lcpasswd got incorrect number of arguments",
116: "lcpasswd did not get the right nubmer of input text lines",
117: "lcpasswd too many simultaneous pwd changes in progress",
118: "lcpasswd User does not exist.",
119: "lcpasswd Incorrect current passwd",
120: "lcpasswd Unable to su to root.",
121: "lcpasswd Cannot set new passwd.",
122: "lcpasswd Username has invalid characters",
123: "lcpasswd Invalid characters in password",
124: "11", "12",
125: "lcpasswd Password mismatch");
1.97 foxr 126:
127:
1.178 foxr 128: # The array below are lcuseradd error strings.:
1.97 foxr 129:
1.178 foxr 130: my $lastadderror = 13;
131: my @adderrors = ("ok",
132: "User ID mismatch, lcuseradd must run as user www",
133: "lcuseradd Incorrect number of command line parameters must be 3",
134: "lcuseradd Incorrect number of stdinput lines, must be 3",
135: "lcuseradd Too many other simultaneous pwd changes in progress",
136: "lcuseradd User does not exist",
137: "lcuseradd Unable to make www member of users's group",
138: "lcuseradd Unable to su to root",
139: "lcuseradd Unable to set password",
140: "lcuseradd Usrname has invalid characters",
141: "lcuseradd Password has an invalid character",
142: "lcuseradd User already exists",
143: "lcuseradd Could not add user.",
144: "lcuseradd Password mismatch");
1.97 foxr 145:
1.96 foxr 146:
1.207 foxr 147:
148: #
149: # Statistics that are maintained and dislayed in the status line.
150: #
1.212 foxr 151: my $Transactions = 0; # Number of attempted transactions.
152: my $Failures = 0; # Number of transcations failed.
1.207 foxr 153:
154: # ResetStatistics:
155: # Resets the statistics counters:
156: #
157: sub ResetStatistics {
158: $Transactions = 0;
159: $Failures = 0;
160: }
161:
162:
163:
1.200 matthew 164: #------------------------------------------------------------------------
165: #
166: # LocalConnection
167: # Completes the formation of a locally authenticated connection.
168: # This function will ensure that the 'remote' client is really the
169: # local host. If not, the connection is closed, and the function fails.
170: # If so, initcmd is parsed for the name of a file containing the
171: # IDEA session key. The fie is opened, read, deleted and the session
172: # key returned to the caller.
173: #
174: # Parameters:
175: # $Socket - Socket open on client.
176: # $initcmd - The full text of the init command.
177: #
178: # Implicit inputs:
179: # $clientdns - The DNS name of the remote client.
180: # $thisserver - Our DNS name.
181: #
182: # Returns:
183: # IDEA session key on success.
184: # undef on failure.
185: #
186: sub LocalConnection {
187: my ($Socket, $initcmd) = @_;
188: Debug("Attempting local connection: $initcmd client: $clientdns me: $thisserver");
189: if($clientdns ne $thisserver) {
190: &logthis('<font color="red"> LocalConnection rejecting non local: '
191: ."$clientdns ne $thisserver </font>");
192: close $Socket;
193: return undef;
194: }
195: else {
196: chomp($initcmd); # Get rid of \n in filename.
197: my ($init, $type, $name) = split(/:/, $initcmd);
198: Debug(" Init command: $init $type $name ");
199:
200: # Require that $init = init, and $type = local: Otherwise
201: # the caller is insane:
202:
203: if(($init ne "init") && ($type ne "local")) {
204: &logthis('<font color = "red"> LocalConnection: caller is insane! '
205: ."init = $init, and type = $type </font>");
206: close($Socket);;
207: return undef;
208:
209: }
210: # Now get the key filename:
211:
212: my $IDEAKey = lonlocal::ReadKeyFile($name);
213: return $IDEAKey;
214: }
215: }
216: #------------------------------------------------------------------------------
217: #
218: # SSLConnection
219: # Completes the formation of an ssh authenticated connection. The
220: # socket is promoted to an ssl socket. If this promotion and the associated
221: # certificate exchange are successful, the IDEA key is generated and sent
222: # to the remote peer via the SSL tunnel. The IDEA key is also returned to
223: # the caller after the SSL tunnel is torn down.
224: #
225: # Parameters:
226: # Name Type Purpose
227: # $Socket IO::Socket::INET Plaintext socket.
228: #
229: # Returns:
230: # IDEA key on success.
231: # undef on failure.
232: #
233: sub SSLConnection {
234: my $Socket = shift;
235:
236: Debug("SSLConnection: ");
237: my $KeyFile = lonssl::KeyFile();
238: if(!$KeyFile) {
239: my $err = lonssl::LastError();
240: &logthis("<font color=\"red\"> CRITICAL"
241: ."Can't get key file $err </font>");
242: return undef;
243: }
244: my ($CACertificate,
245: $Certificate) = lonssl::CertificateFile();
246:
247:
248: # If any of the key, certificate or certificate authority
249: # certificate filenames are not defined, this can't work.
250:
251: if((!$Certificate) || (!$CACertificate)) {
252: my $err = lonssl::LastError();
253: &logthis("<font color=\"red\"> CRITICAL"
254: ."Can't get certificates: $err </font>");
255:
256: return undef;
257: }
258: Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
259:
260: # Indicate to our peer that we can procede with
261: # a transition to ssl authentication:
262:
263: print $Socket "ok:ssl\n";
264:
265: Debug("Approving promotion -> ssl");
266: # And do so:
267:
268: my $SSLSocket = lonssl::PromoteServerSocket($Socket,
269: $CACertificate,
270: $Certificate,
271: $KeyFile);
272: if(! ($SSLSocket) ) { # SSL socket promotion failed.
273: my $err = lonssl::LastError();
274: &logthis("<font color=\"red\"> CRITICAL "
275: ."SSL Socket promotion failed: $err </font>");
276: return undef;
277: }
278: Debug("SSL Promotion successful");
279:
280: #
281: # The only thing we'll use the socket for is to send the IDEA key
282: # to the peer:
283:
284: my $Key = lonlocal::CreateCipherKey();
285: print $SSLSocket "$Key\n";
286:
287: lonssl::Close($SSLSocket);
288:
289: Debug("Key exchange complete: $Key");
290:
291: return $Key;
292: }
293: #
294: # InsecureConnection:
295: # If insecure connections are allowd,
296: # exchange a challenge with the client to 'validate' the
297: # client (not really, but that's the protocol):
298: # We produce a challenge string that's sent to the client.
299: # The client must then echo the challenge verbatim to us.
300: #
301: # Parameter:
302: # Socket - Socket open on the client.
303: # Returns:
304: # 1 - success.
305: # 0 - failure (e.g.mismatch or insecure not allowed).
306: #
307: sub InsecureConnection {
308: my $Socket = shift;
309:
310: # Don't even start if insecure connections are not allowed.
311:
312: if(! $perlvar{londAllowInsecure}) { # Insecure connections not allowed.
313: return 0;
314: }
315:
316: # Fabricate a challenge string and send it..
317:
318: my $challenge = "$$".time; # pid + time.
319: print $Socket "$challenge\n";
320: &status("Waiting for challenge reply");
321:
322: my $answer = <$Socket>;
323: $answer =~s/\W//g;
324: if($challenge eq $answer) {
325: return 1;
326: }
327: else {
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: }
335:
1.96 foxr 336: #
1.140 foxr 337: # GetCertificate: Given a transaction that requires a certificate,
338: # this function will extract the certificate from the transaction
339: # request. Note that at this point, the only concept of a certificate
340: # is the hostname to which we are connected.
341: #
342: # Parameter:
343: # request - The request sent by our client (this parameterization may
344: # need to change when we really use a certificate granting
345: # authority.
346: #
347: sub GetCertificate {
348: my $request = shift;
349:
350: return $clientip;
351: }
1.161 foxr 352:
1.178 foxr 353: #
354: # Return true if client is a manager.
355: #
356: sub isManager {
357: return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
358: }
359: #
360: # Return tru if client can do client functions
361: #
362: sub isClient {
363: return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
364: }
1.161 foxr 365:
366:
1.156 foxr 367: #
368: # ReadManagerTable: Reads in the current manager table. For now this is
369: # done on each manager authentication because:
370: # - These authentications are not frequent
371: # - This allows dynamic changes to the manager table
372: # without the need to signal to the lond.
373: #
374:
375: sub ReadManagerTable {
376:
377: # Clean out the old table first..
378:
1.166 foxr 379: foreach my $key (keys %managers) {
380: delete $managers{$key};
381: }
382:
383: my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
384: if (!open (MANAGERS, $tablename)) {
385: logthis('<font color="red">No manager table. Nobody can manage!!</font>');
386: return;
387: }
388: while(my $host = <MANAGERS>) {
389: chomp($host);
390: if ($host =~ "^#") { # Comment line.
391: next;
392: }
393: if (!defined $hostip{$host}) { # This is a non cluster member
1.161 foxr 394: # The entry is of the form:
395: # cluname:hostname
396: # cluname - A 'cluster hostname' is needed in order to negotiate
397: # the host key.
398: # hostname- The dns name of the host.
399: #
1.166 foxr 400: my($cluname, $dnsname) = split(/:/, $host);
401:
402: my $ip = gethostbyname($dnsname);
403: if(defined($ip)) { # bad names don't deserve entry.
404: my $hostip = inet_ntoa($ip);
405: $managers{$hostip} = $cluname;
406: logthis('<font color="green"> registering manager '.
407: "$dnsname as $cluname with $hostip </font>\n");
408: }
409: } else {
410: logthis('<font color="green"> existing host'." $host</font>\n");
411: $managers{$hostip{$host}} = $host; # Use info from cluster tab if clumemeber
412: }
413: }
1.156 foxr 414: }
1.140 foxr 415:
416: #
417: # ValidManager: Determines if a given certificate represents a valid manager.
418: # in this primitive implementation, the 'certificate' is
419: # just the connecting loncapa client name. This is checked
420: # against a valid client list in the configuration.
421: #
422: #
423: sub ValidManager {
424: my $certificate = shift;
425:
1.163 foxr 426: return isManager;
1.140 foxr 427: }
428: #
1.143 foxr 429: # CopyFile: Called as part of the process of installing a
430: # new configuration file. This function copies an existing
431: # file to a backup file.
432: # Parameters:
433: # oldfile - Name of the file to backup.
434: # newfile - Name of the backup file.
435: # Return:
436: # 0 - Failure (errno has failure reason).
437: # 1 - Success.
438: #
439: sub CopyFile {
1.192 foxr 440:
441: my ($oldfile, $newfile) = @_;
1.143 foxr 442:
443: # The file must exist:
444:
445: if(-e $oldfile) {
446:
447: # Read the old file.
448:
449: my $oldfh = IO::File->new("< $oldfile");
450: if(!$oldfh) {
451: return 0;
452: }
453: my @contents = <$oldfh>; # Suck in the entire file.
454:
455: # write the backup file:
456:
457: my $newfh = IO::File->new("> $newfile");
458: if(!(defined $newfh)){
459: return 0;
460: }
461: my $lines = scalar @contents;
462: for (my $i =0; $i < $lines; $i++) {
463: print $newfh ($contents[$i]);
464: }
465:
466: $oldfh->close;
467: $newfh->close;
468:
469: chmod(0660, $newfile);
470:
471: return 1;
472:
473: } else {
474: return 0;
475: }
476: }
1.157 foxr 477: #
478: # Host files are passed out with externally visible host IPs.
479: # If, for example, we are behind a fire-wall or NAT host, our
480: # internally visible IP may be different than the externally
481: # visible IP. Therefore, we always adjust the contents of the
482: # host file so that the entry for ME is the IP that we believe
483: # we have. At present, this is defined as the entry that
484: # DNS has for us. If by some chance we are not able to get a
485: # DNS translation for us, then we assume that the host.tab file
486: # is correct.
487: # BUGBUGBUG - in the future, we really should see if we can
488: # easily query the interface(s) instead.
489: # Parameter(s):
490: # contents - The contents of the host.tab to check.
491: # Returns:
492: # newcontents - The adjusted contents.
493: #
494: #
495: sub AdjustHostContents {
496: my $contents = shift;
497: my $adjusted;
498: my $me = $perlvar{'lonHostID'};
499:
1.166 foxr 500: foreach my $line (split(/\n/,$contents)) {
1.157 foxr 501: if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/))) {
502: chomp($line);
503: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
504: if ($id eq $me) {
1.166 foxr 505: my $ip = gethostbyname($name);
506: my $ipnew = inet_ntoa($ip);
507: $ip = $ipnew;
1.157 foxr 508: # Reconstruct the host line and append to adjusted:
509:
1.166 foxr 510: my $newline = "$id:$domain:$role:$name:$ip";
511: if($maxcon ne "") { # Not all hosts have loncnew tuning params
512: $newline .= ":$maxcon:$idleto:$mincon";
513: }
514: $adjusted .= $newline."\n";
1.157 foxr 515:
1.166 foxr 516: } else { # Not me, pass unmodified.
517: $adjusted .= $line."\n";
518: }
1.157 foxr 519: } else { # Blank or comment never re-written.
520: $adjusted .= $line."\n"; # Pass blanks and comments as is.
521: }
1.166 foxr 522: }
523: return $adjusted;
1.157 foxr 524: }
1.143 foxr 525: #
526: # InstallFile: Called to install an administrative file:
527: # - The file is created with <name>.tmp
528: # - The <name>.tmp file is then mv'd to <name>
529: # This lugubrious procedure is done to ensure that we are never without
530: # a valid, even if dated, version of the file regardless of who crashes
531: # and when the crash occurs.
532: #
533: # Parameters:
534: # Name of the file
535: # File Contents.
536: # Return:
537: # nonzero - success.
538: # 0 - failure and $! has an errno.
539: #
540: sub InstallFile {
1.192 foxr 541:
542: my ($Filename, $Contents) = @_;
1.143 foxr 543: my $TempFile = $Filename.".tmp";
544:
545: # Open the file for write:
546:
547: my $fh = IO::File->new("> $TempFile"); # Write to temp.
548: if(!(defined $fh)) {
549: &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
550: return 0;
551: }
552: # write the contents of the file:
553:
554: print $fh ($Contents);
555: $fh->close; # In case we ever have a filesystem w. locking
556:
557: chmod(0660, $TempFile);
558:
559: # Now we can move install the file in position.
560:
561: move($TempFile, $Filename);
562:
563: return 1;
564: }
1.200 matthew 565:
566:
1.169 foxr 567: #
568: # ConfigFileFromSelector: converts a configuration file selector
569: # (one of host or domain at this point) into a
570: # configuration file pathname.
571: #
572: # Parameters:
573: # selector - Configuration file selector.
574: # Returns:
575: # Full path to the file or undef if the selector is invalid.
576: #
577: sub ConfigFileFromSelector {
578: my $selector = shift;
579: my $tablefile;
580:
581: my $tabledir = $perlvar{'lonTabDir'}.'/';
582: if ($selector eq "hosts") {
583: $tablefile = $tabledir."hosts.tab";
584: } elsif ($selector eq "domain") {
585: $tablefile = $tabledir."domain.tab";
586: } else {
587: return undef;
588: }
589: return $tablefile;
1.143 foxr 590:
1.169 foxr 591: }
1.143 foxr 592: #
1.141 foxr 593: # PushFile: Called to do an administrative push of a file.
594: # - Ensure the file being pushed is one we support.
595: # - Backup the old file to <filename.saved>
596: # - Separate the contents of the new file out from the
597: # rest of the request.
598: # - Write the new file.
599: # Parameter:
600: # Request - The entire user request. This consists of a : separated
601: # string pushfile:tablename:contents.
602: # NOTE: The contents may have :'s in it as well making things a bit
603: # more interesting... but not much.
604: # Returns:
605: # String to send to client ("ok" or "refused" if bad file).
606: #
607: sub PushFile {
608: my $request = shift;
609: my ($command, $filename, $contents) = split(":", $request, 3);
610:
611: # At this point in time, pushes for only the following tables are
612: # supported:
613: # hosts.tab ($filename eq host).
614: # domain.tab ($filename eq domain).
615: # Construct the destination filename or reject the request.
616: #
617: # lonManage is supposed to ensure this, however this session could be
618: # part of some elaborate spoof that managed somehow to authenticate.
619: #
620:
1.169 foxr 621:
622: my $tablefile = ConfigFileFromSelector($filename);
623: if(! (defined $tablefile)) {
1.141 foxr 624: return "refused";
625: }
626: #
627: # >copy< the old table to the backup table
628: # don't rename in case system crashes/reboots etc. in the time
629: # window between a rename and write.
630: #
631: my $backupfile = $tablefile;
632: $backupfile =~ s/\.tab$/.old/;
1.143 foxr 633: if(!CopyFile($tablefile, $backupfile)) {
634: &logthis('<font color="green"> CopyFile from '.$tablefile." to ".$backupfile." failed </font>");
635: return "error:$!";
636: }
1.141 foxr 637: &logthis('<font color="green"> Pushfile: backed up '
638: .$tablefile." to $backupfile</font>");
639:
1.157 foxr 640: # If the file being pushed is the host file, we adjust the entry for ourself so that the
641: # IP will be our current IP as looked up in dns. Note this is only 99% good as it's possible
642: # to conceive of conditions where we don't have a DNS entry locally. This is possible in a
643: # network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
644: # that possibilty.
645:
646: if($filename eq "host") {
647: $contents = AdjustHostContents($contents);
648: }
649:
1.141 foxr 650: # Install the new file:
651:
1.143 foxr 652: if(!InstallFile($tablefile, $contents)) {
653: &logthis('<font color="red"> Pushfile: unable to install '
1.145 foxr 654: .$tablefile." $! </font>");
1.143 foxr 655: return "error:$!";
656: }
657: else {
658: &logthis('<font color="green"> Installed new '.$tablefile
659: ."</font>");
660:
661: }
662:
1.141 foxr 663:
664: # Indicate success:
665:
666: return "ok";
667:
668: }
1.145 foxr 669:
670: #
671: # Called to re-init either lonc or lond.
672: #
673: # Parameters:
674: # request - The full request by the client. This is of the form
675: # reinit:<process>
676: # where <process> is allowed to be either of
677: # lonc or lond
678: #
679: # Returns:
680: # The string to be sent back to the client either:
681: # ok - Everything worked just fine.
682: # error:why - There was a failure and why describes the reason.
683: #
684: #
685: sub ReinitProcess {
686: my $request = shift;
687:
1.146 foxr 688:
689: # separate the request (reinit) from the process identifier and
690: # validate it producing the name of the .pid file for the process.
691: #
692: #
693: my ($junk, $process) = split(":", $request);
1.147 foxr 694: my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
1.146 foxr 695: if($process eq 'lonc') {
696: $processpidfile = $processpidfile."lonc.pid";
1.147 foxr 697: if (!open(PIDFILE, "< $processpidfile")) {
698: return "error:Open failed for $processpidfile";
699: }
700: my $loncpid = <PIDFILE>;
701: close(PIDFILE);
702: logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
703: ."</font>");
704: kill("USR2", $loncpid);
1.146 foxr 705: } elsif ($process eq 'lond') {
1.147 foxr 706: logthis('<font color="red"> Reinitializing self (lond) </font>');
707: &UpdateHosts; # Lond is us!!
1.146 foxr 708: } else {
709: &logthis('<font color="yellow" Invalid reinit request for '.$process
710: ."</font>");
711: return "error:Invalid process identifier $process";
712: }
1.145 foxr 713: return 'ok';
714: }
1.168 foxr 715: # Validate a line in a configuration file edit script:
716: # Validation includes:
717: # - Ensuring the command is valid.
718: # - Ensuring the command has sufficient parameters
719: # Parameters:
720: # scriptline - A line to validate (\n has been stripped for what it's worth).
1.167 foxr 721: #
1.168 foxr 722: # Return:
723: # 0 - Invalid scriptline.
724: # 1 - Valid scriptline
725: # NOTE:
726: # Only the command syntax is checked, not the executability of the
727: # command.
728: #
729: sub isValidEditCommand {
730: my $scriptline = shift;
731:
732: # Line elements are pipe separated:
733:
734: my ($command, $key, $newline) = split(/\|/, $scriptline);
735: &logthis('<font color="green"> isValideditCommand checking: '.
736: "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
737:
738: if ($command eq "delete") {
739: #
740: # key with no newline.
741: #
742: if( ($key eq "") || ($newline ne "")) {
743: return 0; # Must have key but no newline.
744: } else {
745: return 1; # Valid syntax.
746: }
1.169 foxr 747: } elsif ($command eq "replace") {
1.168 foxr 748: #
749: # key and newline:
750: #
751: if (($key eq "") || ($newline eq "")) {
752: return 0;
753: } else {
754: return 1;
755: }
1.169 foxr 756: } elsif ($command eq "append") {
757: if (($key ne "") && ($newline eq "")) {
758: return 1;
759: } else {
760: return 0;
761: }
1.168 foxr 762: } else {
763: return 0; # Invalid command.
764: }
765: return 0; # Should not get here!!!
766: }
1.169 foxr 767: #
768: # ApplyEdit - Applies an edit command to a line in a configuration
769: # file. It is the caller's responsiblity to validate the
770: # edit line.
771: # Parameters:
772: # $directive - A single edit directive to apply.
773: # Edit directives are of the form:
774: # append|newline - Appends a new line to the file.
775: # replace|key|newline - Replaces the line with key value 'key'
776: # delete|key - Deletes the line with key value 'key'.
777: # $editor - A config file editor object that contains the
778: # file being edited.
779: #
780: sub ApplyEdit {
1.192 foxr 781:
782: my ($directive, $editor) = @_;
1.169 foxr 783:
784: # Break the directive down into its command and its parameters
785: # (at most two at this point. The meaning of the parameters, if in fact
786: # they exist depends on the command).
787:
788: my ($command, $p1, $p2) = split(/\|/, $directive);
789:
790: if($command eq "append") {
791: $editor->Append($p1); # p1 - key p2 null.
792: } elsif ($command eq "replace") {
793: $editor->ReplaceLine($p1, $p2); # p1 - key p2 = newline.
794: } elsif ($command eq "delete") {
795: $editor->DeleteLine($p1); # p1 - key p2 null.
796: } else { # Should not get here!!!
797: die "Invalid command given to ApplyEdit $command"
798: }
799: }
800: #
801: # AdjustOurHost:
802: # Adjusts a host file stored in a configuration file editor object
803: # for the true IP address of this host. This is necessary for hosts
804: # that live behind a firewall.
805: # Those hosts have a publicly distributed IP of the firewall, but
806: # internally must use their actual IP. We assume that a given
807: # host only has a single IP interface for now.
808: # Formal Parameters:
809: # editor - The configuration file editor to adjust. This
810: # editor is assumed to contain a hosts.tab file.
811: # Strategy:
812: # - Figure out our hostname.
813: # - Lookup the entry for this host.
814: # - Modify the line to contain our IP
815: # - Do a replace for this host.
816: sub AdjustOurHost {
817: my $editor = shift;
818:
819: # figure out who I am.
820:
821: my $myHostName = $perlvar{'lonHostID'}; # LonCAPA hostname.
822:
823: # Get my host file entry.
824:
825: my $ConfigLine = $editor->Find($myHostName);
826: if(! (defined $ConfigLine)) {
827: die "AdjustOurHost - no entry for me in hosts file $myHostName";
828: }
829: # figure out my IP:
830: # Use the config line to get my hostname.
831: # Use gethostbyname to translate that into an IP address.
832: #
833: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
834: my $BinaryIp = gethostbyname($name);
835: my $ip = inet_ntoa($ip);
836: #
837: # Reassemble the config line from the elements in the list.
838: # Note that if the loncnew items were not present before, they will
839: # be now even if they would be empty
840: #
841: my $newConfigLine = $id;
842: foreach my $item ($domain, $role, $name, $ip, $maxcon, $idleto, $mincon) {
843: $newConfigLine .= ":".$item;
844: }
845: # Replace the line:
846:
847: $editor->ReplaceLine($id, $newConfigLine);
848:
849: }
850: #
851: # ReplaceConfigFile:
852: # Replaces a configuration file with the contents of a
853: # configuration file editor object.
854: # This is done by:
855: # - Copying the target file to <filename>.old
856: # - Writing the new file to <filename>.tmp
857: # - Moving <filename.tmp> -> <filename>
858: # This laborious process ensures that the system is never without
859: # a configuration file that's at least valid (even if the contents
860: # may be dated).
861: # Parameters:
862: # filename - Name of the file to modify... this is a full path.
863: # editor - Editor containing the file.
864: #
865: sub ReplaceConfigFile {
1.192 foxr 866:
867: my ($filename, $editor) = @_;
1.168 foxr 868:
1.169 foxr 869: CopyFile ($filename, $filename.".old");
870:
871: my $contents = $editor->Get(); # Get the contents of the file.
872:
873: InstallFile($filename, $contents);
874: }
1.168 foxr 875: #
876: #
877: # Called to edit a configuration table file
1.167 foxr 878: # Parameters:
879: # request - The entire command/request sent by lonc or lonManage
880: # Return:
881: # The reply to send to the client.
1.168 foxr 882: #
1.167 foxr 883: sub EditFile {
884: my $request = shift;
885:
886: # Split the command into it's pieces: edit:filetype:script
887:
1.168 foxr 888: my ($request, $filetype, $script) = split(/:/, $request,3); # : in script
1.167 foxr 889:
890: # Check the pre-coditions for success:
891:
892: if($request != "edit") { # Something is amiss afoot alack.
893: return "error:edit request detected, but request != 'edit'\n";
894: }
895: if( ($filetype ne "hosts") &&
896: ($filetype ne "domain")) {
897: return "error:edit requested with invalid file specifier: $filetype \n";
898: }
899:
900: # Split the edit script and check it's validity.
1.168 foxr 901:
902: my @scriptlines = split(/\n/, $script); # one line per element.
903: my $linecount = scalar(@scriptlines);
904: for(my $i = 0; $i < $linecount; $i++) {
905: chomp($scriptlines[$i]);
906: if(!isValidEditCommand($scriptlines[$i])) {
907: return "error:edit with bad script line: '$scriptlines[$i]' \n";
908: }
909: }
1.145 foxr 910:
1.167 foxr 911: # Execute the edit operation.
1.169 foxr 912: # - Create a config file editor for the appropriate file and
913: # - execute each command in the script:
914: #
915: my $configfile = ConfigFileFromSelector($filetype);
916: if (!(defined $configfile)) {
917: return "refused\n";
918: }
919: my $editor = ConfigFileEdit->new($configfile);
1.167 foxr 920:
1.169 foxr 921: for (my $i = 0; $i < $linecount; $i++) {
922: ApplyEdit($scriptlines[$i], $editor);
923: }
924: # If the file is the host file, ensure that our host is
925: # adjusted to have our ip:
926: #
927: if($filetype eq "host") {
928: AdjustOurHost($editor);
929: }
930: # Finally replace the current file with our file.
931: #
932: ReplaceConfigFile($configfile, $editor);
1.167 foxr 933:
934: return "ok\n";
935: }
1.207 foxr 936:
937: #---------------------------------------------------------------
938: #
939: # Manipulation of hash based databases (factoring out common code
940: # for later use as we refactor.
941: #
942: # Ties a domain level resource file to a hash.
943: # If requested a history entry is created in the associated hist file.
944: #
945: # Parameters:
946: # domain - Name of the domain in which the resource file lives.
947: # namespace - Name of the hash within that domain.
948: # how - How to tie the hash (e.g. GDBM_WRCREAT()).
949: # loghead - Optional parameter, if present a log entry is created
950: # in the associated history file and this is the first part
951: # of that entry.
952: # logtail - Goes along with loghead, The actual logentry is of the
953: # form $loghead:<timestamp>:logtail.
954: # Returns:
955: # Reference to a hash bound to the db file or alternatively undef
956: # if the tie failed.
957: #
1.209 albertel 958: sub tie_domain_hash {
1.210 albertel 959: my ($domain,$namespace,$how,$loghead,$logtail) = @_;
1.207 foxr 960:
961: # Filter out any whitespace in the domain name:
962:
963: $domain =~ s/\W//g;
964:
965: # We have enough to go on to tie the hash:
966:
967: my $user_top_dir = $perlvar{'lonUsersDir'};
968: my $domain_dir = $user_top_dir."/$domain";
969: my $resource_file = $domain_dir."/$namespace.db";
970: my %hash;
971: if(tie(%hash, 'GDBM_File', $resource_file, $how, 0640)) {
1.211 albertel 972: if (defined($loghead)) { # Need to log the operation.
1.210 albertel 973: my $logFh = IO::File->new(">>$domain_dir/$namespace.hist");
1.207 foxr 974: if($logFh) {
975: my $timestamp = time;
976: print $logFh "$loghead:$timestamp:$logtail\n";
977: }
1.210 albertel 978: $logFh->close;
1.207 foxr 979: }
980: return \%hash; # Return the tied hash.
1.210 albertel 981: } else {
1.207 foxr 982: return undef; # Tie failed.
983: }
984: }
985:
986: #
987: # Ties a user's resource file to a hash.
988: # If necessary, an appropriate history
989: # log file entry is made as well.
990: # This sub factors out common code from the subs that manipulate
991: # the various gdbm files that keep keyword value pairs.
992: # Parameters:
993: # domain - Name of the domain the user is in.
994: # user - Name of the 'current user'.
995: # namespace - Namespace representing the file to tie.
996: # how - What the tie is done to (e.g. GDBM_WRCREAT().
997: # loghead - Optional first part of log entry if there may be a
998: # history file.
999: # what - Optional tail of log entry if there may be a history
1000: # file.
1001: # Returns:
1002: # hash to which the database is tied. It's up to the caller to untie.
1003: # undef if the has could not be tied.
1004: #
1.210 albertel 1005: sub tie_user_hash {
1006: my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
1.207 foxr 1007:
1008: $namespace=~s/\//\_/g; # / -> _
1009: $namespace=~s/\W//g; # whitespace eliminated.
1010: my $proname = propath($domain, $user);
1011:
1012: # Tie the database.
1013:
1014: my %hash;
1015: if(tie(%hash, 'GDBM_File', "$proname/$namespace.db",
1016: $how, 0640)) {
1.209 albertel 1017: # If this is a namespace for which a history is kept,
1018: # make the history log entry:
1.211 albertel 1019: if (($namespace =~/^nohist\_/) && (defined($loghead))) {
1.209 albertel 1020: my $args = scalar @_;
1021: Debug(" Opening history: $namespace $args");
1022: my $hfh = IO::File->new(">>$proname/$namespace.hist");
1023: if($hfh) {
1024: my $now = time;
1025: print $hfh "$loghead:$now:$what\n";
1026: }
1.210 albertel 1027: $hfh->close;
1.209 albertel 1028: }
1.207 foxr 1029: return \%hash;
1.209 albertel 1030: } else {
1.207 foxr 1031: return undef;
1032: }
1033:
1034: }
1.214 ! foxr 1035:
! 1036: #--------------------- Request Handlers --------------------------------------------
! 1037: #
! 1038: # By convention each request handler registers itself prior to the sub declaration:
! 1039: #
! 1040:
! 1041: # Handles ping requests.
! 1042: # Parameters:
! 1043: # $cmd - the actual keyword that invoked us.
! 1044: # $tail - the tail of the request that invoked us.
! 1045: # $replyfd- File descriptor connected to the client
! 1046: # Implicit Inputs:
! 1047: # $currenthostid - Global variable that carries the name of the host we are
! 1048: # known as.
! 1049: # Returns:
! 1050: # 1 - Ok to continue processing.
! 1051: # 0 - Program should exit.
! 1052: # Side effects:
! 1053: # Reply information is sent to the client.
! 1054:
! 1055: sub ping_handler {
! 1056: my ($cmd, $tail, $client) = @_;
! 1057: Debug("$cmd $tail $client .. $currenthostid:");
! 1058:
! 1059: Reply( $client,"$currenthostid\n","$cmd:$tail");
! 1060:
! 1061: return 1;
! 1062: }
! 1063: ®ister_handler("ping", \&ping_handler, 0, 1, 1); # Ping unencoded, client or manager.
! 1064:
! 1065:
1.207 foxr 1066: #---------------------------------------------------------------
1067: #
1068: # Getting, decoding and dispatching requests:
1069: #
1070:
1071: #
1072: # Get a Request:
1073: # Gets a Request message from the client. The transaction
1074: # is defined as a 'line' of text. We remove the new line
1075: # from the text line.
1076: #
1.211 albertel 1077: sub get_request {
1.207 foxr 1078: my $input = <$client>;
1079: chomp($input);
1080:
1.212 foxr 1081: Debug("get_request: Request = $input\n");
1.207 foxr 1082:
1083: &status('Processing '.$clientname.':'.$input);
1084:
1085: return $input;
1086: }
1.212 foxr 1087: #---------------------------------------------------------------
1088: #
1089: # Process a request. This sub should shrink as each action
1090: # gets farmed out into a separat sub that is registered
1091: # with the dispatch hash.
1092: #
1093: # Parameters:
1094: # user_input - The request received from the client (lonc).
1095: # Returns:
1096: # true to keep processing, false if caller should exit.
1097: #
1098: sub process_request {
1099: my ($userinput) = @_; # Easier for now to break style than to
1100: # fix all the userinput -> user_input.
1101: my $wasenc = 0; # True if request was encrypted.
1102: # ------------------------------------------------------------ See if encrypted
1103: if ($userinput =~ /^enc/) {
1104: $userinput = decipher($userinput);
1105: $wasenc=1;
1106: if(!$userinput) { # Cipher not defined.
1107: &Failure($client, "error: Encrypted data without negotated key");
1108: return 0;
1109: }
1110: }
1111: Debug("process_request: $userinput\n");
1112:
1.213 foxr 1113: #
1114: # The 'correct way' to add a command to lond is now to
1115: # write a sub to execute it and Add it to the command dispatch
1116: # hash via a call to register_handler.. The comments to that
1117: # sub should give you enough to go on to show how to do this
1118: # along with the examples that are building up as this code
1119: # is getting refactored. Until all branches of the
1120: # if/elseif monster below have been factored out into
1121: # separate procesor subs, if the dispatch hash is missing
1122: # the command keyword, we will fall through to the remainder
1123: # of the if/else chain below in order to keep this thing in
1124: # working order throughout the transmogrification.
1125:
1126: my ($command, $tail) = split(/:/, $userinput, 2);
1127: chomp($command);
1128: chomp($tail);
1129: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
1.214 ! foxr 1130: $command =~ s/(\r)//; # And this too for parameterless commands.
! 1131: if(!$tail) {
! 1132: $tail =""; # defined but blank.
! 1133: }
1.213 foxr 1134:
1135: &Debug("Command received: $command, encoded = $wasenc");
1136:
1137: if(defined $Dispatcher{$command}) {
1138:
1139: my $dispatch_info = $Dispatcher{$command};
1140: my $handler = $$dispatch_info[0];
1141: my $need_encode = $$dispatch_info[1];
1142: my $client_types = $$dispatch_info[2];
1143: Debug("Matched dispatch hash: mustencode: $need_encode "
1144: ."ClientType $client_types");
1145:
1146: # Validate the request:
1147:
1148: my $ok = 1;
1149: my $requesterprivs = 0;
1150: if(&isClient()) {
1151: $requesterprivs |= $CLIENT_OK;
1152: }
1153: if(&isManager()) {
1154: $requesterprivs |= $MANAGER_OK;
1155: }
1156: if($need_encode && (!$wasenc)) {
1157: Debug("Must encode but wasn't: $need_encode $wasenc");
1158: $ok = 0;
1159: }
1160: if(($client_types & $requesterprivs) == 0) {
1161: Debug("Client not privileged to do this operation");
1162: $ok = 0;
1163: }
1164:
1165: if($ok) {
1166: Debug("Dispatching to handler $command $tail");
1167: my $keep_going = &$handler($command, $tail, $client);
1168: return $keep_going;
1169: } else {
1170: Debug("Refusing to dispatch because client did not match requirements");
1171: Failure($client, "refused\n", $userinput);
1172: return 1;
1173: }
1174:
1175: }
1176:
1.212 foxr 1177: # ------------------------------------------------------------- Normal commands
1.214 ! foxr 1178: if ($userinput =~ /^pong/) { # client only
1.212 foxr 1179: if(isClient) {
1180: my $reply=&reply("ping",$clientname);
1181: print $client "$currenthostid:$reply\n";
1182: } else {
1183: Reply($client, "refused\n", $userinput);
1184: }
1185: # ------------------------------------------------------------------------ ekey
1186: } elsif ($userinput =~ /^ekey/) { # ok for both clients & mgrs
1187: my $buildkey=time.$$.int(rand 100000);
1188: $buildkey=~tr/1-6/A-F/;
1189: $buildkey=int(rand 100000).$buildkey.int(rand 100000);
1190: my $key=$currenthostid.$clientname;
1191: $key=~tr/a-z/A-Z/;
1192: $key=~tr/G-P/0-9/;
1193: $key=~tr/Q-Z/0-9/;
1194: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
1195: $key=substr($key,0,32);
1196: my $cipherkey=pack("H32",$key);
1197: $cipher=new IDEA $cipherkey;
1198: print $client "$buildkey\n";
1199: # ------------------------------------------------------------------------ load
1200: } elsif ($userinput =~ /^load/) { # client only
1201: if (isClient) {
1202: my $loadavg;
1203: {
1204: my $loadfile=IO::File->new('/proc/loadavg');
1205: $loadavg=<$loadfile>;
1206: }
1207: $loadavg =~ s/\s.*//g;
1208: my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
1209: print $client "$loadpercent\n";
1210: } else {
1211: Reply($client, "refused\n", $userinput);
1212:
1213: }
1214: # -------------------------------------------------------------------- userload
1215: } elsif ($userinput =~ /^userload/) { # client only
1216: if(isClient) {
1217: my $userloadpercent=&userload();
1218: print $client "$userloadpercent\n";
1219: } else {
1220: Reply($client, "refused\n", $userinput);
1221:
1222: }
1223: #
1224: # Transactions requiring encryption:
1225: #
1226: # ----------------------------------------------------------------- currentauth
1227: } elsif ($userinput =~ /^currentauth/) {
1228: if (($wasenc==1) && isClient) { # Encoded & client only.
1229: my ($cmd,$udom,$uname)=split(/:/,$userinput);
1230: my $result = GetAuthType($udom, $uname);
1231: if($result eq "nouser") {
1232: print $client "unknown_user\n";
1233: }
1234: else {
1235: print $client "$result\n";
1236: }
1237: } else {
1238: Reply($client, "refused\n", $userinput);
1239:
1240: }
1241: #--------------------------------------------------------------------- pushfile
1242: } elsif($userinput =~ /^pushfile/) { # encoded & manager.
1243: if(($wasenc == 1) && isManager) {
1244: my $cert = GetCertificate($userinput);
1245: if(ValidManager($cert)) {
1246: my $reply = PushFile($userinput);
1247: print $client "$reply\n";
1248: } else {
1249: print $client "refused\n";
1250: }
1251: } else {
1252: Reply($client, "refused\n", $userinput);
1253:
1254: }
1255: #--------------------------------------------------------------------- reinit
1256: } elsif($userinput =~ /^reinit/) { # Encoded and manager
1257: if (($wasenc == 1) && isManager) {
1258: my $cert = GetCertificate($userinput);
1259: if(ValidManager($cert)) {
1260: chomp($userinput);
1261: my $reply = ReinitProcess($userinput);
1262: print $client "$reply\n";
1263: } else {
1264: print $client "refused\n";
1265: }
1266: } else {
1267: Reply($client, "refused\n", $userinput);
1268: }
1269: #------------------------------------------------------------------------- edit
1270: } elsif ($userinput =~ /^edit/) { # encoded and manager:
1271: if(($wasenc ==1) && (isManager)) {
1272: my $cert = GetCertificate($userinput);
1273: if(ValidManager($cert)) {
1274: my($command, $filetype, $script) = split(/:/, $userinput);
1275: if (($filetype eq "hosts") || ($filetype eq "domain")) {
1276: if($script ne "") {
1277: Reply($client, EditFile($userinput));
1278: } else {
1279: Reply($client,"refused\n",$userinput);
1280: }
1281: } else {
1282: Reply($client,"refused\n",$userinput);
1283: }
1284: } else {
1285: Reply($client,"refused\n",$userinput);
1286: }
1287: } else {
1288: Reply($client,"refused\n",$userinput);
1289: }
1290: # ------------------------------------------------------------------------ auth
1291: } elsif ($userinput =~ /^auth/) { # Encoded and client only.
1292: if (($wasenc==1) && isClient) {
1293: my ($cmd,$udom,$uname,$upass)=split(/:/,$userinput);
1294: chomp($upass);
1295: $upass=unescape($upass);
1296: my $proname=propath($udom,$uname);
1297: my $passfilename="$proname/passwd";
1298: if (-e $passfilename) {
1299: my $pf = IO::File->new($passfilename);
1300: my $realpasswd=<$pf>;
1301: chomp($realpasswd);
1302: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1303: my $pwdcorrect=0;
1304: if ($howpwd eq 'internal') {
1305: &Debug("Internal auth");
1306: $pwdcorrect=
1307: (crypt($upass,$contentpwd) eq $contentpwd);
1308: } elsif ($howpwd eq 'unix') {
1309: &Debug("Unix auth");
1310: if((getpwnam($uname))[1] eq "") { #no such user!
1311: $pwdcorrect = 0;
1312: } else {
1313: $contentpwd=(getpwnam($uname))[1];
1314: my $pwauth_path="/usr/local/sbin/pwauth";
1315: unless ($contentpwd eq 'x') {
1316: $pwdcorrect=
1317: (crypt($upass,$contentpwd) eq
1318: $contentpwd);
1319: }
1320:
1321: elsif (-e $pwauth_path) {
1322: open PWAUTH, "|$pwauth_path" or
1323: die "Cannot invoke authentication";
1324: print PWAUTH "$uname\n$upass\n";
1325: close PWAUTH;
1326: $pwdcorrect=!$?;
1327: }
1328: }
1329: } elsif ($howpwd eq 'krb4') {
1330: my $null=pack("C",0);
1331: unless ($upass=~/$null/) {
1332: my $krb4_error = &Authen::Krb4::get_pw_in_tkt
1333: ($uname,"",$contentpwd,'krbtgt',
1334: $contentpwd,1,$upass);
1335: if (!$krb4_error) {
1336: $pwdcorrect = 1;
1337: } else {
1338: $pwdcorrect=0;
1339: # log error if it is not a bad password
1340: if ($krb4_error != 62) {
1341: &logthis('krb4:'.$uname.','.
1342: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
1343: }
1344: }
1345: }
1346: } elsif ($howpwd eq 'krb5') {
1347: my $null=pack("C",0);
1348: unless ($upass=~/$null/) {
1349: my $krbclient=&Authen::Krb5::parse_name($uname.'@'.$contentpwd);
1350: my $krbservice="krbtgt/".$contentpwd."\@".$contentpwd;
1351: my $krbserver=&Authen::Krb5::parse_name($krbservice);
1352: my $credentials=&Authen::Krb5::cc_default();
1353: $credentials->initialize($krbclient);
1354: my $krbreturn =
1355: &Authen::Krb5::get_in_tkt_with_password(
1356: $krbclient,$krbserver,$upass,$credentials);
1357: # unless ($krbreturn) {
1358: # &logthis("Krb5 Error: ".
1359: # &Authen::Krb5::error());
1360: # }
1361: $pwdcorrect = ($krbreturn == 1);
1362: } else { $pwdcorrect=0; }
1363: } elsif ($howpwd eq 'localauth') {
1364: $pwdcorrect=&localauth::localauth($uname,$upass,
1365: $contentpwd);
1366: }
1367: if ($pwdcorrect) {
1368: print $client "authorized\n";
1369: } else {
1370: print $client "non_authorized\n";
1371: }
1372: } else {
1373: print $client "unknown_user\n";
1374: }
1375: } else {
1376: Reply($client, "refused\n", $userinput);
1377:
1378: }
1379: # ---------------------------------------------------------------------- passwd
1380: } elsif ($userinput =~ /^passwd/) { # encoded and client
1381: if (($wasenc==1) && isClient) {
1382: my
1383: ($cmd,$udom,$uname,$upass,$npass)=split(/:/,$userinput);
1384: chomp($npass);
1385: $upass=&unescape($upass);
1386: $npass=&unescape($npass);
1387: &Debug("Trying to change password for $uname");
1388: my $proname=propath($udom,$uname);
1389: my $passfilename="$proname/passwd";
1390: if (-e $passfilename) {
1391: my $realpasswd;
1392: { my $pf = IO::File->new($passfilename);
1393: $realpasswd=<$pf>; }
1394: chomp($realpasswd);
1395: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
1396: if ($howpwd eq 'internal') {
1397: &Debug("internal auth");
1398: if (crypt($upass,$contentpwd) eq $contentpwd) {
1399: my $salt=time;
1400: $salt=substr($salt,6,2);
1401: my $ncpass=crypt($npass,$salt);
1402: {
1403: my $pf;
1404: if ($pf = IO::File->new(">$passfilename")) {
1405: print $pf "internal:$ncpass\n";
1406: &logthis("Result of password change for $uname: pwchange_success");
1407: print $client "ok\n";
1408: } else {
1409: &logthis("Unable to open $uname passwd to change password");
1410: print $client "non_authorized\n";
1411: }
1412: }
1413:
1414: } else {
1415: print $client "non_authorized\n";
1416: }
1417: } elsif ($howpwd eq 'unix') {
1418: # Unix means we have to access /etc/password
1419: # one way or another.
1420: # First: Make sure the current password is
1421: # correct
1422: &Debug("auth is unix");
1423: $contentpwd=(getpwnam($uname))[1];
1424: my $pwdcorrect = "0";
1425: my $pwauth_path="/usr/local/sbin/pwauth";
1426: unless ($contentpwd eq 'x') {
1427: $pwdcorrect=
1428: (crypt($upass,$contentpwd) eq $contentpwd);
1429: } elsif (-e $pwauth_path) {
1430: open PWAUTH, "|$pwauth_path" or
1431: die "Cannot invoke authentication";
1432: print PWAUTH "$uname\n$upass\n";
1433: close PWAUTH;
1434: &Debug("exited pwauth with $? ($uname,$upass) ");
1435: $pwdcorrect=($? == 0);
1436: }
1437: if ($pwdcorrect) {
1438: my $execdir=$perlvar{'lonDaemons'};
1439: &Debug("Opening lcpasswd pipeline");
1440: my $pf = IO::File->new("|$execdir/lcpasswd > $perlvar{'lonDaemons'}/logs/lcpasswd.log");
1441: print $pf "$uname\n$npass\n$npass\n";
1442: close $pf;
1443: my $err = $?;
1444: my $result = ($err>0 ? 'pwchange_failure'
1445: : 'ok');
1446: &logthis("Result of password change for $uname: ".
1447: &lcpasswdstrerror($?));
1448: print $client "$result\n";
1449: } else {
1450: print $client "non_authorized\n";
1451: }
1452: } else {
1453: print $client "auth_mode_error\n";
1454: }
1455: } else {
1456: print $client "unknown_user\n";
1457: }
1458: } else {
1459: Reply($client, "refused\n", $userinput);
1460:
1461: }
1462: # -------------------------------------------------------------------- makeuser
1463: } elsif ($userinput =~ /^makeuser/) { # encoded and client.
1464: &Debug("Make user received");
1465: my $oldumask=umask(0077);
1466: if (($wasenc==1) && isClient) {
1467: my
1468: ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
1469: &Debug("cmd =".$cmd." $udom =".$udom.
1470: " uname=".$uname);
1471: chomp($npass);
1472: $npass=&unescape($npass);
1473: my $proname=propath($udom,$uname);
1474: my $passfilename="$proname/passwd";
1475: &Debug("Password file created will be:".
1476: $passfilename);
1477: if (-e $passfilename) {
1478: print $client "already_exists\n";
1479: } elsif ($udom ne $currentdomainid) {
1480: print $client "not_right_domain\n";
1481: } else {
1482: my @fpparts=split(/\//,$proname);
1483: my $fpnow=$fpparts[0].'/'.$fpparts[1].'/'.$fpparts[2];
1484: my $fperror='';
1485: for (my $i=3;$i<=$#fpparts;$i++) {
1486: $fpnow.='/'.$fpparts[$i];
1487: unless (-e $fpnow) {
1488: unless (mkdir($fpnow,0777)) {
1489: $fperror="error: ".($!+0)
1490: ." mkdir failed while attempting "
1491: ."makeuser";
1492: }
1493: }
1494: }
1495: unless ($fperror) {
1496: my $result=&make_passwd_file($uname, $umode,$npass,
1497: $passfilename);
1498: print $client $result;
1499: } else {
1500: print $client "$fperror\n";
1501: }
1502: }
1503: } else {
1504: Reply($client, "refused\n", $userinput);
1505:
1506: }
1507: umask($oldumask);
1508: # -------------------------------------------------------------- changeuserauth
1509: } elsif ($userinput =~ /^changeuserauth/) { # encoded & client
1510: &Debug("Changing authorization");
1511: if (($wasenc==1) && isClient) {
1512: my
1513: ($cmd,$udom,$uname,$umode,$npass)=split(/:/,$userinput);
1514: chomp($npass);
1515: &Debug("cmd = ".$cmd." domain= ".$udom.
1516: "uname =".$uname." umode= ".$umode);
1517: $npass=&unescape($npass);
1518: my $proname=&propath($udom,$uname);
1519: my $passfilename="$proname/passwd";
1520: if ($udom ne $currentdomainid) {
1521: print $client "not_right_domain\n";
1522: } else {
1523: my $result=&make_passwd_file($uname, $umode,$npass,
1524: $passfilename);
1525: print $client $result;
1526: }
1527: } else {
1528: Reply($client, "refused\n", $userinput);
1529:
1530: }
1531: # ------------------------------------------------------------------------ home
1532: } elsif ($userinput =~ /^home/) { # client clear or encoded
1533: if(isClient) {
1534: my ($cmd,$udom,$uname)=split(/:/,$userinput);
1535: chomp($uname);
1536: my $proname=propath($udom,$uname);
1537: if (-e $proname) {
1538: print $client "found\n";
1539: } else {
1540: print $client "not_found\n";
1541: }
1542: } else {
1543: Reply($client, "refused\n", $userinput);
1544:
1545: }
1546: # ---------------------------------------------------------------------- update
1547: } elsif ($userinput =~ /^update/) { # client clear or encoded.
1548: if(isClient) {
1549: my ($cmd,$fname)=split(/:/,$userinput);
1550: my $ownership=ishome($fname);
1551: if ($ownership eq 'not_owner') {
1552: if (-e $fname) {
1553: my ($dev,$ino,$mode,$nlink,
1554: $uid,$gid,$rdev,$size,
1555: $atime,$mtime,$ctime,
1556: $blksize,$blocks)=stat($fname);
1557: my $now=time;
1558: my $since=$now-$atime;
1559: if ($since>$perlvar{'lonExpire'}) {
1560: my $reply=
1561: &reply("unsub:$fname","$clientname");
1562: unlink("$fname");
1563: } else {
1564: my $transname="$fname.in.transfer";
1565: my $remoteurl=
1566: &reply("sub:$fname","$clientname");
1567: my $response;
1568: {
1569: my $ua=new LWP::UserAgent;
1570: my $request=new HTTP::Request('GET',"$remoteurl");
1571: $response=$ua->request($request,$transname);
1572: }
1573: if ($response->is_error()) {
1574: unlink($transname);
1575: my $message=$response->status_line;
1576: &logthis(
1577: "LWP GET: $message for $fname ($remoteurl)");
1578: } else {
1579: if ($remoteurl!~/\.meta$/) {
1580: my $ua=new LWP::UserAgent;
1581: my $mrequest=
1582: new HTTP::Request('GET',$remoteurl.'.meta');
1583: my $mresponse=
1584: $ua->request($mrequest,$fname.'.meta');
1585: if ($mresponse->is_error()) {
1586: unlink($fname.'.meta');
1587: }
1588: }
1589: rename($transname,$fname);
1590: }
1591: }
1592: print $client "ok\n";
1593: } else {
1594: print $client "not_found\n";
1595: }
1596: } else {
1597: print $client "rejected\n";
1598: }
1599: } else {
1600: Reply($client, "refused\n", $userinput);
1601:
1602: }
1603: # -------------------------------------- fetch a user file from a remote server
1604: } elsif ($userinput =~ /^fetchuserfile/) { # Client clear or enc.
1605: if(isClient) {
1606: my ($cmd,$fname)=split(/:/,$userinput);
1607: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1608: my $udir=propath($udom,$uname).'/userfiles';
1609: unless (-e $udir) { mkdir($udir,0770); }
1610: if (-e $udir) {
1611: $ufile=~s/^[\.\~]+//;
1612: my $path = $udir;
1613: if ($ufile =~m|(.+)/([^/]+)$|) {
1614: my @parts=split('/',$1);
1615: foreach my $part (@parts) {
1616: $path .= '/'.$part;
1617: if ((-e $path)!=1) {
1618: mkdir($path,0770);
1619: }
1620: }
1621: }
1622: my $destname=$udir.'/'.$ufile;
1623: my $transname=$udir.'/'.$ufile.'.in.transit';
1624: my $remoteurl='http://'.$clientip.'/userfiles/'.$fname;
1625: my $response;
1626: {
1627: my $ua=new LWP::UserAgent;
1628: my $request=new HTTP::Request('GET',"$remoteurl");
1629: $response=$ua->request($request,$transname);
1630: }
1631: if ($response->is_error()) {
1632: unlink($transname);
1633: my $message=$response->status_line;
1634: &logthis("LWP GET: $message for $fname ($remoteurl)");
1635: print $client "failed\n";
1636: } else {
1637: if (!rename($transname,$destname)) {
1638: &logthis("Unable to move $transname to $destname");
1639: unlink($transname);
1640: print $client "failed\n";
1641: } else {
1642: print $client "ok\n";
1643: }
1644: }
1645: } else {
1646: print $client "not_home\n";
1647: }
1648: } else {
1649: Reply($client, "refused\n", $userinput);
1650: }
1651: # --------------------------------------------------------- remove a user file
1652: } elsif ($userinput =~ /^removeuserfile/) { # Client clear or enc.
1653: if(isClient) {
1654: my ($cmd,$fname)=split(/:/,$userinput);
1655: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
1656: &logthis("$udom - $uname - $ufile");
1657: if ($ufile =~m|/\.\./|) {
1658: # any files paths with /../ in them refuse
1659: # to deal with
1660: print $client "refused\n";
1661: } else {
1662: my $udir=propath($udom,$uname);
1663: if (-e $udir) {
1664: my $file=$udir.'/userfiles/'.$ufile;
1665: if (-e $file) {
1666: unlink($file);
1667: if (-e $file) {
1668: print $client "failed\n";
1669: } else {
1670: print $client "ok\n";
1671: }
1672: } else {
1673: print $client "not_found\n";
1674: }
1675: } else {
1676: print $client "not_home\n";
1677: }
1678: }
1679: } else {
1680: Reply($client, "refused\n", $userinput);
1681: }
1682: # ------------------------------------------ authenticate access to a user file
1683: } elsif ($userinput =~ /^tokenauthuserfile/) { # Client only
1684: if(isClient) {
1685: my ($cmd,$fname,$session)=split(/:/,$userinput);
1686: chomp($session);
1687: my $reply='non_auth';
1688: if (open(ENVIN,$perlvar{'lonIDsDir'}.'/'.
1689: $session.'.id')) {
1690: while (my $line=<ENVIN>) {
1691: if ($line=~ m|userfile\.\Q$fname\E\=|) { $reply='ok'; }
1692: }
1693: close(ENVIN);
1694: print $client $reply."\n";
1695: } else {
1696: print $client "invalid_token\n";
1697: }
1698: } else {
1699: Reply($client, "refused\n", $userinput);
1700:
1701: }
1702: # ----------------------------------------------------------------- unsubscribe
1703: } elsif ($userinput =~ /^unsub/) {
1704: if(isClient) {
1705: my ($cmd,$fname)=split(/:/,$userinput);
1706: if (-e $fname) {
1707: print $client &unsub($fname,$clientip);
1708: } else {
1709: print $client "not_found\n";
1710: }
1711: } else {
1712: Reply($client, "refused\n", $userinput);
1713:
1714: }
1715: # ------------------------------------------------------------------- subscribe
1716: } elsif ($userinput =~ /^sub/) {
1717: if(isClient) {
1718: print $client &subscribe($userinput,$clientip);
1719: } else {
1720: Reply($client, "refused\n", $userinput);
1721:
1722: }
1723: # ------------------------------------------------------------- current version
1724: } elsif ($userinput =~ /^currentversion/) {
1725: if(isClient) {
1726: my ($cmd,$fname)=split(/:/,$userinput);
1727: print $client ¤tversion($fname)."\n";
1728: } else {
1729: Reply($client, "refused\n", $userinput);
1730:
1731: }
1732: # ------------------------------------------------------------------------- log
1733: } elsif ($userinput =~ /^log/) {
1734: if(isClient) {
1735: my ($cmd,$udom,$uname,$what)=split(/:/,$userinput);
1736: chomp($what);
1737: my $proname=propath($udom,$uname);
1738: my $now=time;
1739: {
1740: my $hfh;
1741: if ($hfh=IO::File->new(">>$proname/activity.log")) {
1742: print $hfh "$now:$clientname:$what\n";
1743: print $client "ok\n";
1744: } else {
1745: print $client "error: ".($!+0)
1746: ." IO::File->new Failed "
1747: ."while attempting log\n";
1748: }
1749: }
1750: } else {
1751: Reply($client, "refused\n", $userinput);
1752:
1753: }
1754: # ------------------------------------------------------------------------- put
1755: } elsif ($userinput =~ /^put/) {
1756: if(isClient) {
1757: my ($cmd,$udom,$uname,$namespace,$what)
1758: =split(/:/,$userinput,5);
1759: $namespace=~s/\//\_/g;
1760: $namespace=~s/\W//g;
1761: if ($namespace ne 'roles') {
1762: chomp($what);
1763: my $proname=propath($udom,$uname);
1764: my $now=time;
1765: my @pairs=split(/\&/,$what);
1766: my %hash;
1767: if (tie(%hash,'GDBM_File',
1768: "$proname/$namespace.db",
1769: &GDBM_WRCREAT(),0640)) {
1770: unless ($namespace=~/^nohist\_/) {
1771: my $hfh;
1772: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
1773: }
1774:
1775: foreach my $pair (@pairs) {
1776: my ($key,$value)=split(/=/,$pair);
1777: $hash{$key}=$value;
1778: }
1779: if (untie(%hash)) {
1780: print $client "ok\n";
1781: } else {
1782: print $client "error: ".($!+0)
1783: ." untie(GDBM) failed ".
1784: "while attempting put\n";
1785: }
1786: } else {
1787: print $client "error: ".($!)
1788: ." tie(GDBM) Failed ".
1789: "while attempting put\n";
1790: }
1791: } else {
1792: print $client "refused\n";
1793: }
1794: } else {
1795: Reply($client, "refused\n", $userinput);
1796:
1797: }
1798: # ------------------------------------------------------------------- inc
1799: } elsif ($userinput =~ /^inc:/) {
1800: if(isClient) {
1801: my ($cmd,$udom,$uname,$namespace,$what)
1802: =split(/:/,$userinput);
1803: $namespace=~s/\//\_/g;
1804: $namespace=~s/\W//g;
1805: if ($namespace ne 'roles') {
1806: chomp($what);
1807: my $proname=propath($udom,$uname);
1808: my $now=time;
1809: my @pairs=split(/\&/,$what);
1810: my %hash;
1811: if (tie(%hash,'GDBM_File',
1812: "$proname/$namespace.db",
1813: &GDBM_WRCREAT(),0640)) {
1814: unless ($namespace=~/^nohist\_/) {
1815: my $hfh;
1816: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "P:$now:$what\n"; }
1817: }
1818: foreach my $pair (@pairs) {
1819: my ($key,$value)=split(/=/,$pair);
1820: # We could check that we have a number...
1821: if (! defined($value) || $value eq '') {
1822: $value = 1;
1823: }
1824: $hash{$key}+=$value;
1825: }
1826: if (untie(%hash)) {
1827: print $client "ok\n";
1828: } else {
1829: print $client "error: ".($!+0)
1830: ." untie(GDBM) failed ".
1831: "while attempting inc\n";
1832: }
1833: } else {
1834: print $client "error: ".($!)
1835: ." tie(GDBM) Failed ".
1836: "while attempting inc\n";
1837: }
1838: } else {
1839: print $client "refused\n";
1840: }
1841: } else {
1842: Reply($client, "refused\n", $userinput);
1843:
1844: }
1845: # -------------------------------------------------------------------- rolesput
1846: } elsif ($userinput =~ /^rolesput/) {
1847: if(isClient) {
1848: &Debug("rolesput");
1849: if ($wasenc==1) {
1850: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
1851: =split(/:/,$userinput);
1852: &Debug("cmd = ".$cmd." exedom= ".$exedom.
1853: "user = ".$exeuser." udom=".$udom.
1854: "what = ".$what);
1855: my $namespace='roles';
1856: chomp($what);
1857: my $proname=propath($udom,$uname);
1858: my $now=time;
1859: my @pairs=split(/\&/,$what);
1860: my %hash;
1861: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1862: {
1863: my $hfh;
1864: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
1865: print $hfh "P:$now:$exedom:$exeuser:$what\n";
1866: }
1867: }
1868:
1869: foreach my $pair (@pairs) {
1870: my ($key,$value)=split(/=/,$pair);
1871: &ManagePermissions($key, $udom, $uname,
1872: &GetAuthType( $udom,
1873: $uname));
1874: $hash{$key}=$value;
1875: }
1876: if (untie(%hash)) {
1877: print $client "ok\n";
1878: } else {
1879: print $client "error: ".($!+0)
1880: ." untie(GDBM) Failed ".
1881: "while attempting rolesput\n";
1882: }
1883: } else {
1884: print $client "error: ".($!+0)
1885: ." tie(GDBM) Failed ".
1886: "while attempting rolesput\n";
1887: }
1888: } else {
1889: print $client "refused\n";
1890: }
1891: } else {
1892: Reply($client, "refused\n", $userinput);
1893:
1894: }
1895: # -------------------------------------------------------------------- rolesdel
1896: } elsif ($userinput =~ /^rolesdel/) {
1897: if(isClient) {
1898: &Debug("rolesdel");
1899: if ($wasenc==1) {
1900: my ($cmd,$exedom,$exeuser,$udom,$uname,$what)
1901: =split(/:/,$userinput);
1902: &Debug("cmd = ".$cmd." exedom= ".$exedom.
1903: "user = ".$exeuser." udom=".$udom.
1904: "what = ".$what);
1905: my $namespace='roles';
1906: chomp($what);
1907: my $proname=propath($udom,$uname);
1908: my $now=time;
1909: my @rolekeys=split(/\&/,$what);
1910: my %hash;
1911: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
1912: {
1913: my $hfh;
1914: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
1915: print $hfh "D:$now:$exedom:$exeuser:$what\n";
1916: }
1917: }
1918: foreach my $key (@rolekeys) {
1919: delete $hash{$key};
1920: }
1921: if (untie(%hash)) {
1922: print $client "ok\n";
1923: } else {
1924: print $client "error: ".($!+0)
1925: ." untie(GDBM) Failed ".
1926: "while attempting rolesdel\n";
1927: }
1928: } else {
1929: print $client "error: ".($!+0)
1930: ." tie(GDBM) Failed ".
1931: "while attempting rolesdel\n";
1932: }
1933: } else {
1934: print $client "refused\n";
1935: }
1936: } else {
1937: Reply($client, "refused\n", $userinput);
1938:
1939: }
1940: # ------------------------------------------------------------------------- get
1941: } elsif ($userinput =~ /^get/) {
1942: if(isClient) {
1943: my ($cmd,$udom,$uname,$namespace,$what)
1944: =split(/:/,$userinput);
1945: $namespace=~s/\//\_/g;
1946: $namespace=~s/\W//g;
1947: chomp($what);
1948: my @queries=split(/\&/,$what);
1949: my $proname=propath($udom,$uname);
1950: my $qresult='';
1951: my %hash;
1952: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
1953: for (my $i=0;$i<=$#queries;$i++) {
1954: $qresult.="$hash{$queries[$i]}&";
1955: }
1956: if (untie(%hash)) {
1957: $qresult=~s/\&$//;
1958: print $client "$qresult\n";
1959: } else {
1960: print $client "error: ".($!+0)
1961: ." untie(GDBM) Failed ".
1962: "while attempting get\n";
1963: }
1964: } else {
1965: if ($!+0 == 2) {
1966: print $client "error:No such file or ".
1967: "GDBM reported bad block error\n";
1968: } else {
1969: print $client "error: ".($!+0)
1970: ." tie(GDBM) Failed ".
1971: "while attempting get\n";
1972: }
1973: }
1974: } else {
1975: Reply($client, "refused\n", $userinput);
1976:
1977: }
1978: # ------------------------------------------------------------------------ eget
1979: } elsif ($userinput =~ /^eget/) {
1980: if (isClient) {
1981: my ($cmd,$udom,$uname,$namespace,$what)
1982: =split(/:/,$userinput);
1983: $namespace=~s/\//\_/g;
1984: $namespace=~s/\W//g;
1985: chomp($what);
1986: my @queries=split(/\&/,$what);
1987: my $proname=propath($udom,$uname);
1988: my $qresult='';
1989: my %hash;
1990: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
1991: for (my $i=0;$i<=$#queries;$i++) {
1992: $qresult.="$hash{$queries[$i]}&";
1993: }
1994: if (untie(%hash)) {
1995: $qresult=~s/\&$//;
1996: if ($cipher) {
1997: my $cmdlength=length($qresult);
1998: $qresult.=" ";
1999: my $encqresult='';
2000: for
2001: (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
2002: $encqresult.=
2003: unpack("H16",
2004: $cipher->encrypt(substr($qresult,$encidx,8)));
2005: }
2006: print $client "enc:$cmdlength:$encqresult\n";
2007: } else {
2008: print $client "error:no_key\n";
2009: }
2010: } else {
2011: print $client "error: ".($!+0)
2012: ." untie(GDBM) Failed ".
2013: "while attempting eget\n";
2014: }
2015: } else {
2016: print $client "error: ".($!+0)
2017: ." tie(GDBM) Failed ".
2018: "while attempting eget\n";
2019: }
2020: } else {
2021: Reply($client, "refused\n", $userinput);
2022:
2023: }
2024: # ------------------------------------------------------------------------- del
2025: } elsif ($userinput =~ /^del/) {
2026: if(isClient) {
2027: my ($cmd,$udom,$uname,$namespace,$what)
2028: =split(/:/,$userinput);
2029: $namespace=~s/\//\_/g;
2030: $namespace=~s/\W//g;
2031: chomp($what);
2032: my $proname=propath($udom,$uname);
2033: my $now=time;
2034: my @keys=split(/\&/,$what);
2035: my %hash;
2036: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2037: unless ($namespace=~/^nohist\_/) {
2038: my $hfh;
2039: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) { print $hfh "D:$now:$what\n"; }
2040: }
2041: foreach my $key (@keys) {
2042: delete($hash{$key});
2043: }
2044: if (untie(%hash)) {
2045: print $client "ok\n";
2046: } else {
2047: print $client "error: ".($!+0)
2048: ." untie(GDBM) Failed ".
2049: "while attempting del\n";
2050: }
2051: } else {
2052: print $client "error: ".($!+0)
2053: ." tie(GDBM) Failed ".
2054: "while attempting del\n";
2055: }
2056: } else {
2057: Reply($client, "refused\n", $userinput);
2058:
2059: }
2060: # ------------------------------------------------------------------------ keys
2061: } elsif ($userinput =~ /^keys/) {
2062: if(isClient) {
2063: my ($cmd,$udom,$uname,$namespace)
2064: =split(/:/,$userinput);
2065: $namespace=~s/\//\_/g;
2066: $namespace=~s/\W//g;
2067: my $proname=propath($udom,$uname);
2068: my $qresult='';
2069: my %hash;
2070: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2071: foreach my $key (keys %hash) {
2072: $qresult.="$key&";
2073: }
2074: if (untie(%hash)) {
2075: $qresult=~s/\&$//;
2076: print $client "$qresult\n";
2077: } else {
2078: print $client "error: ".($!+0)
2079: ." untie(GDBM) Failed ".
2080: "while attempting keys\n";
2081: }
2082: } else {
2083: print $client "error: ".($!+0)
2084: ." tie(GDBM) Failed ".
2085: "while attempting keys\n";
2086: }
2087: } else {
2088: Reply($client, "refused\n", $userinput);
2089:
2090: }
2091: # ----------------------------------------------------------------- dumpcurrent
2092: } elsif ($userinput =~ /^currentdump/) {
2093: if (isClient) {
2094: my ($cmd,$udom,$uname,$namespace)
2095: =split(/:/,$userinput);
2096: $namespace=~s/\//\_/g;
2097: $namespace=~s/\W//g;
2098: my $qresult='';
2099: my $proname=propath($udom,$uname);
2100: my %hash;
2101: if (tie(%hash,'GDBM_File',
2102: "$proname/$namespace.db",
2103: &GDBM_READER(),0640)) {
2104: # Structure of %data:
2105: # $data{$symb}->{$parameter}=$value;
2106: # $data{$symb}->{'v.'.$parameter}=$version;
2107: # since $parameter will be unescaped, we do not
2108: # have to worry about silly parameter names...
2109: my %data = ();
2110: while (my ($key,$value) = each(%hash)) {
2111: my ($v,$symb,$param) = split(/:/,$key);
2112: next if ($v eq 'version' || $symb eq 'keys');
2113: next if (exists($data{$symb}) &&
2114: exists($data{$symb}->{$param}) &&
2115: $data{$symb}->{'v.'.$param} > $v);
2116: $data{$symb}->{$param}=$value;
2117: $data{$symb}->{'v.'.$param}=$v;
2118: }
2119: if (untie(%hash)) {
2120: while (my ($symb,$param_hash) = each(%data)) {
2121: while(my ($param,$value) = each (%$param_hash)){
2122: next if ($param =~ /^v\./);
2123: $qresult.=$symb.':'.$param.'='.$value.'&';
2124: }
2125: }
2126: chop($qresult);
2127: print $client "$qresult\n";
2128: } else {
2129: print $client "error: ".($!+0)
2130: ." untie(GDBM) Failed ".
2131: "while attempting currentdump\n";
2132: }
2133: } else {
2134: print $client "error: ".($!+0)
2135: ." tie(GDBM) Failed ".
2136: "while attempting currentdump\n";
2137: }
2138: } else {
2139: Reply($client, "refused\n", $userinput);
2140: }
2141: # ------------------------------------------------------------------------ dump
2142: } elsif ($userinput =~ /^dump/) {
2143: if(isClient) {
2144: my ($cmd,$udom,$uname,$namespace,$regexp)
2145: =split(/:/,$userinput);
2146: $namespace=~s/\//\_/g;
2147: $namespace=~s/\W//g;
2148: if (defined($regexp)) {
2149: $regexp=&unescape($regexp);
2150: } else {
2151: $regexp='.';
2152: }
2153: my $qresult='';
2154: my $proname=propath($udom,$uname);
2155: my %hash;
2156: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2157: while (my ($key,$value) = each(%hash)) {
2158: if ($regexp eq '.') {
2159: $qresult.=$key.'='.$value.'&';
2160: } else {
2161: my $unescapeKey = &unescape($key);
2162: if (eval('$unescapeKey=~/$regexp/')) {
2163: $qresult.="$key=$value&";
2164: }
2165: }
2166: }
2167: if (untie(%hash)) {
2168: chop($qresult);
2169: print $client "$qresult\n";
2170: } else {
2171: print $client "error: ".($!+0)
2172: ." untie(GDBM) Failed ".
2173: "while attempting dump\n";
2174: }
2175: } else {
2176: print $client "error: ".($!+0)
2177: ." tie(GDBM) Failed ".
2178: "while attempting dump\n";
2179: }
2180: } else {
2181: Reply($client, "refused\n", $userinput);
2182:
2183: }
2184: # ----------------------------------------------------------------------- store
2185: } elsif ($userinput =~ /^store/) {
2186: if(isClient) {
2187: my ($cmd,$udom,$uname,$namespace,$rid,$what)
2188: =split(/:/,$userinput);
2189: $namespace=~s/\//\_/g;
2190: $namespace=~s/\W//g;
2191: if ($namespace ne 'roles') {
2192: chomp($what);
2193: my $proname=propath($udom,$uname);
2194: my $now=time;
2195: my @pairs=split(/\&/,$what);
2196: my %hash;
2197: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_WRCREAT(),0640)) {
2198: unless ($namespace=~/^nohist\_/) {
2199: my $hfh;
2200: if ($hfh=IO::File->new(">>$proname/$namespace.hist")) {
2201: print $hfh "P:$now:$rid:$what\n";
2202: }
2203: }
2204: my @previouskeys=split(/&/,$hash{"keys:$rid"});
2205: my $key;
2206: $hash{"version:$rid"}++;
2207: my $version=$hash{"version:$rid"};
2208: my $allkeys='';
2209: foreach my $pair (@pairs) {
2210: my ($key,$value)=split(/=/,$pair);
2211: $allkeys.=$key.':';
2212: $hash{"$version:$rid:$key"}=$value;
2213: }
2214: $hash{"$version:$rid:timestamp"}=$now;
2215: $allkeys.='timestamp';
2216: $hash{"$version:keys:$rid"}=$allkeys;
2217: if (untie(%hash)) {
2218: print $client "ok\n";
2219: } else {
2220: print $client "error: ".($!+0)
2221: ." untie(GDBM) Failed ".
2222: "while attempting store\n";
2223: }
2224: } else {
2225: print $client "error: ".($!+0)
2226: ." tie(GDBM) Failed ".
2227: "while attempting store\n";
2228: }
2229: } else {
2230: print $client "refused\n";
2231: }
2232: } else {
2233: Reply($client, "refused\n", $userinput);
2234:
2235: }
2236: # --------------------------------------------------------------------- restore
2237: } elsif ($userinput =~ /^restore/) {
2238: if(isClient) {
2239: my ($cmd,$udom,$uname,$namespace,$rid)
2240: =split(/:/,$userinput);
2241: $namespace=~s/\//\_/g;
2242: $namespace=~s/\W//g;
2243: chomp($rid);
2244: my $proname=propath($udom,$uname);
2245: my $qresult='';
2246: my %hash;
2247: if (tie(%hash,'GDBM_File',"$proname/$namespace.db",&GDBM_READER(),0640)) {
2248: my $version=$hash{"version:$rid"};
2249: $qresult.="version=$version&";
2250: my $scope;
2251: for ($scope=1;$scope<=$version;$scope++) {
2252: my $vkeys=$hash{"$scope:keys:$rid"};
2253: my @keys=split(/:/,$vkeys);
2254: my $key;
2255: $qresult.="$scope:keys=$vkeys&";
2256: foreach $key (@keys) {
2257: $qresult.="$scope:$key=".$hash{"$scope:$rid:$key"}."&";
2258: }
2259: }
2260: if (untie(%hash)) {
2261: $qresult=~s/\&$//;
2262: print $client "$qresult\n";
2263: } else {
2264: print $client "error: ".($!+0)
2265: ." untie(GDBM) Failed ".
2266: "while attempting restore\n";
2267: }
2268: } else {
2269: print $client "error: ".($!+0)
2270: ." tie(GDBM) Failed ".
2271: "while attempting restore\n";
2272: }
2273: } else {
2274: Reply($client, "refused\n", $userinput);
2275:
2276: }
2277: # -------------------------------------------------------------------- chatsend
2278: } elsif ($userinput =~ /^chatsend/) {
2279: if(isClient) {
2280: my ($cmd,$cdom,$cnum,$newpost)=split(/\:/,$userinput);
2281: &chatadd($cdom,$cnum,$newpost);
2282: print $client "ok\n";
2283: } else {
2284: Reply($client, "refused\n", $userinput);
2285:
2286: }
2287: # -------------------------------------------------------------------- chatretr
2288: } elsif ($userinput =~ /^chatretr/) {
2289: if(isClient) {
2290: my
2291: ($cmd,$cdom,$cnum,$udom,$uname)=split(/\:/,$userinput);
2292: my $reply='';
2293: foreach (&getchat($cdom,$cnum,$udom,$uname)) {
2294: $reply.=&escape($_).':';
2295: }
2296: $reply=~s/\:$//;
2297: print $client $reply."\n";
2298: } else {
2299: Reply($client, "refused\n", $userinput);
2300:
2301: }
2302: # ------------------------------------------------------------------- querysend
2303: } elsif ($userinput =~ /^querysend/) {
2304: if (isClient) {
2305: my ($cmd,$query,
2306: $arg1,$arg2,$arg3)=split(/\:/,$userinput);
2307: $query=~s/\n*$//g;
2308: print $client "".
2309: sqlreply("$clientname\&$query".
2310: "\&$arg1"."\&$arg2"."\&$arg3")."\n";
2311: } else {
2312: Reply($client, "refused\n", $userinput);
2313:
2314: }
2315: # ------------------------------------------------------------------ queryreply
2316: } elsif ($userinput =~ /^queryreply/) {
2317: if(isClient) {
2318: my ($cmd,$id,$reply)=split(/:/,$userinput);
2319: my $store;
2320: my $execdir=$perlvar{'lonDaemons'};
2321: if ($store=IO::File->new(">$execdir/tmp/$id")) {
2322: $reply=~s/\&/\n/g;
2323: print $store $reply;
2324: close $store;
2325: my $store2=IO::File->new(">$execdir/tmp/$id.end");
2326: print $store2 "done\n";
2327: close $store2;
2328: print $client "ok\n";
2329: }
2330: else {
2331: print $client "error: ".($!+0)
2332: ." IO::File->new Failed ".
2333: "while attempting queryreply\n";
2334: }
2335: } else {
2336: Reply($client, "refused\n", $userinput);
2337:
2338: }
2339: # ----------------------------------------------------------------- courseidput
2340: } elsif ($userinput =~ /^courseidput/) {
2341: if(isClient) {
2342: my ($cmd,$udom,$what)=split(/:/,$userinput);
2343: chomp($what);
2344: $udom=~s/\W//g;
2345: my $proname=
2346: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
2347: my $now=time;
2348: my @pairs=split(/\&/,$what);
2349: my %hash;
2350: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
2351: foreach my $pair (@pairs) {
2352: my ($key,$descr,$inst_code)=split(/=/,$pair);
2353: $hash{$key}=$descr.':'.$inst_code.':'.$now;
2354: }
2355: if (untie(%hash)) {
2356: print $client "ok\n";
2357: } else {
2358: print $client "error: ".($!+0)
2359: ." untie(GDBM) Failed ".
2360: "while attempting courseidput\n";
2361: }
2362: } else {
2363: print $client "error: ".($!+0)
2364: ." tie(GDBM) Failed ".
2365: "while attempting courseidput\n";
2366: }
2367: } else {
2368: Reply($client, "refused\n", $userinput);
2369:
2370: }
2371: # ---------------------------------------------------------------- courseiddump
2372: } elsif ($userinput =~ /^courseiddump/) {
2373: if(isClient) {
2374: my ($cmd,$udom,$since,$description)
2375: =split(/:/,$userinput);
2376: if (defined($description)) {
2377: $description=&unescape($description);
2378: } else {
2379: $description='.';
2380: }
2381: unless (defined($since)) { $since=0; }
2382: my $qresult='';
2383: my $proname=
2384: "$perlvar{'lonUsersDir'}/$udom/nohist_courseids";
2385: my %hash;
2386: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
2387: while (my ($key,$value) = each(%hash)) {
2388: my ($descr,$lasttime,$inst_code);
2389: if ($value =~ m/^([^\:]*):([^\:]*):(\d+)$/) {
2390: ($descr,$inst_code,$lasttime)=($1,$2,$3);
2391: } else {
2392: ($descr,$lasttime) = split(/\:/,$value);
2393: }
2394: if ($lasttime<$since) { next; }
2395: if ($description eq '.') {
2396: $qresult.=$key.'='.$descr.':'.$inst_code.'&';
2397: } else {
2398: my $unescapeVal = &unescape($descr);
2399: if (eval('$unescapeVal=~/\Q$description\E/i')) {
2400: $qresult.=$key.'='.$descr.':'.$inst_code.'&';
2401: }
2402: }
2403: }
2404: if (untie(%hash)) {
2405: chop($qresult);
2406: print $client "$qresult\n";
2407: } else {
2408: print $client "error: ".($!+0)
2409: ." untie(GDBM) Failed ".
2410: "while attempting courseiddump\n";
2411: }
2412: } else {
2413: print $client "error: ".($!+0)
2414: ." tie(GDBM) Failed ".
2415: "while attempting courseiddump\n";
2416: }
2417: } else {
2418: Reply($client, "refused\n", $userinput);
2419:
2420: }
2421: # ----------------------------------------------------------------------- idput
2422: } elsif ($userinput =~ /^idput/) {
2423: if(isClient) {
2424: my ($cmd,$udom,$what)=split(/:/,$userinput);
2425: chomp($what);
2426: $udom=~s/\W//g;
2427: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
2428: my $now=time;
2429: my @pairs=split(/\&/,$what);
2430: my %hash;
2431: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_WRCREAT(),0640)) {
2432: {
2433: my $hfh;
2434: if ($hfh=IO::File->new(">>$proname.hist")) {
2435: print $hfh "P:$now:$what\n";
2436: }
2437: }
2438: foreach my $pair (@pairs) {
2439: my ($key,$value)=split(/=/,$pair);
2440: $hash{$key}=$value;
2441: }
2442: if (untie(%hash)) {
2443: print $client "ok\n";
2444: } else {
2445: print $client "error: ".($!+0)
2446: ." untie(GDBM) Failed ".
2447: "while attempting idput\n";
2448: }
2449: } else {
2450: print $client "error: ".($!+0)
2451: ." tie(GDBM) Failed ".
2452: "while attempting idput\n";
2453: }
2454: } else {
2455: Reply($client, "refused\n", $userinput);
2456:
2457: }
2458: # ----------------------------------------------------------------------- idget
2459: } elsif ($userinput =~ /^idget/) {
2460: if(isClient) {
2461: my ($cmd,$udom,$what)=split(/:/,$userinput);
2462: chomp($what);
2463: $udom=~s/\W//g;
2464: my $proname="$perlvar{'lonUsersDir'}/$udom/ids";
2465: my @queries=split(/\&/,$what);
2466: my $qresult='';
2467: my %hash;
2468: if (tie(%hash,'GDBM_File',"$proname.db",&GDBM_READER(),0640)) {
2469: for (my $i=0;$i<=$#queries;$i++) {
2470: $qresult.="$hash{$queries[$i]}&";
2471: }
2472: if (untie(%hash)) {
2473: $qresult=~s/\&$//;
2474: print $client "$qresult\n";
2475: } else {
2476: print $client "error: ".($!+0)
2477: ." untie(GDBM) Failed ".
2478: "while attempting idget\n";
2479: }
2480: } else {
2481: print $client "error: ".($!+0)
2482: ." tie(GDBM) Failed ".
2483: "while attempting idget\n";
2484: }
2485: } else {
2486: Reply($client, "refused\n", $userinput);
2487:
2488: }
2489: # ---------------------------------------------------------------------- tmpput
2490: } elsif ($userinput =~ /^tmpput/) {
2491: if(isClient) {
2492: my ($cmd,$what)=split(/:/,$userinput);
2493: my $store;
2494: $tmpsnum++;
2495: my $id=$$.'_'.$clientip.'_'.$tmpsnum;
2496: $id=~s/\W/\_/g;
2497: $what=~s/\n//g;
2498: my $execdir=$perlvar{'lonDaemons'};
2499: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
2500: print $store $what;
2501: close $store;
2502: print $client "$id\n";
2503: }
2504: else {
2505: print $client "error: ".($!+0)
2506: ."IO::File->new Failed ".
2507: "while attempting tmpput\n";
2508: }
2509: } else {
2510: Reply($client, "refused\n", $userinput);
2511:
2512: }
2513:
2514: # ---------------------------------------------------------------------- tmpget
2515: } elsif ($userinput =~ /^tmpget/) {
2516: if(isClient) {
2517: my ($cmd,$id)=split(/:/,$userinput);
2518: chomp($id);
2519: $id=~s/\W/\_/g;
2520: my $store;
2521: my $execdir=$perlvar{'lonDaemons'};
2522: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
2523: my $reply=<$store>;
2524: print $client "$reply\n";
2525: close $store;
2526: }
2527: else {
2528: print $client "error: ".($!+0)
2529: ."IO::File->new Failed ".
2530: "while attempting tmpget\n";
2531: }
2532: } else {
2533: Reply($client, "refused\n", $userinput);
2534:
2535: }
2536: # ---------------------------------------------------------------------- tmpdel
2537: } elsif ($userinput =~ /^tmpdel/) {
2538: if(isClient) {
2539: my ($cmd,$id)=split(/:/,$userinput);
2540: chomp($id);
2541: $id=~s/\W/\_/g;
2542: my $execdir=$perlvar{'lonDaemons'};
2543: if (unlink("$execdir/tmp/$id.tmp")) {
2544: print $client "ok\n";
2545: } else {
2546: print $client "error: ".($!+0)
2547: ."Unlink tmp Failed ".
2548: "while attempting tmpdel\n";
2549: }
2550: } else {
2551: Reply($client, "refused\n", $userinput);
2552:
2553: }
2554: # ----------------------------------------- portfolio directory list (portls)
2555: } elsif ($userinput =~ /^portls/) {
2556: if(isClient) {
2557: my ($cmd,$uname,$udom)=split(/:/,$userinput);
2558: my $udir=propath($udom,$uname).'/userfiles/portfolio';
2559: my $dirLine='';
2560: my $dirContents='';
2561: if (opendir(LSDIR,$udir.'/')){
2562: while ($dirLine = readdir(LSDIR)){
2563: $dirContents = $dirContents.$dirLine.'<br />';
2564: }
2565: } else {
2566: $dirContents = "No directory found\n";
2567: }
2568: print $client $dirContents."\n";
2569: } else {
2570: Reply($client, "refused\n", $userinput);
2571: }
2572: # -------------------------------------------------------------------------- ls
2573: } elsif ($userinput =~ /^ls/) {
2574: if(isClient) {
2575: my $obs;
2576: my $rights;
2577: my ($cmd,$ulsdir)=split(/:/,$userinput);
2578: my $ulsout='';
2579: my $ulsfn;
2580: if (-e $ulsdir) {
2581: if(-d $ulsdir) {
2582: if (opendir(LSDIR,$ulsdir)) {
2583: while ($ulsfn=readdir(LSDIR)) {
2584: undef $obs, $rights;
2585: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
2586: #We do some obsolete checking here
2587: if(-e $ulsdir.'/'.$ulsfn.".meta") {
2588: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
2589: my @obsolete=<FILE>;
2590: foreach my $obsolete (@obsolete) {
2591: if($obsolete =~ m|(<obsolete>)(on)|) { $obs = 1; }
2592: if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
2593: }
2594: }
2595: $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
2596: if($obs eq '1') { $ulsout.="&1"; }
2597: else { $ulsout.="&0"; }
2598: if($rights eq '1') { $ulsout.="&1:"; }
2599: else { $ulsout.="&0:"; }
2600: }
2601: closedir(LSDIR);
2602: }
2603: } else {
2604: my @ulsstats=stat($ulsdir);
2605: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
2606: }
2607: } else {
2608: $ulsout='no_such_dir';
2609: }
2610: if ($ulsout eq '') { $ulsout='empty'; }
2611: print $client "$ulsout\n";
2612: } else {
2613: Reply($client, "refused\n", $userinput);
2614:
2615: }
2616: # ----------------------------------------------------------------- setannounce
2617: } elsif ($userinput =~ /^setannounce/) {
2618: if (isClient) {
2619: my ($cmd,$announcement)=split(/:/,$userinput);
2620: chomp($announcement);
2621: $announcement=&unescape($announcement);
2622: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
2623: '/announcement.txt')) {
2624: print $store $announcement;
2625: close $store;
2626: print $client "ok\n";
2627: } else {
2628: print $client "error: ".($!+0)."\n";
2629: }
2630: } else {
2631: Reply($client, "refused\n", $userinput);
2632:
2633: }
2634: # ------------------------------------------------------------------ Hanging up
2635: } elsif (($userinput =~ /^exit/) ||
2636: ($userinput =~ /^init/)) { # no restrictions.
2637: &logthis(
2638: "Client $clientip ($clientname) hanging up: $userinput");
2639: print $client "bye\n";
2640: $client->shutdown(2); # shutdown the socket forcibly.
2641: $client->close();
2642: return 0;
2643:
2644: # ---------------------------------- set current host/domain
2645: } elsif ($userinput =~ /^sethost:/) {
2646: if (isClient) {
2647: print $client &sethost($userinput)."\n";
2648: } else {
2649: print $client "refused\n";
2650: }
2651: #---------------------------------- request file (?) version.
2652: } elsif ($userinput =~/^version:/) {
2653: if (isClient) {
2654: print $client &version($userinput)."\n";
2655: } else {
2656: print $client "refused\n";
2657: }
2658: #------------------------------- is auto-enrollment enabled?
2659: } elsif ($userinput =~/^autorun:/) {
2660: if (isClient) {
2661: my ($cmd,$cdom) = split(/:/,$userinput);
2662: my $outcome = &localenroll::run($cdom);
2663: print $client "$outcome\n";
2664: } else {
2665: print $client "0\n";
2666: }
2667: #------------------------------- get official sections (for auto-enrollment).
2668: } elsif ($userinput =~/^autogetsections:/) {
2669: if (isClient) {
2670: my ($cmd,$coursecode,$cdom)=split(/:/,$userinput);
2671: my @secs = &localenroll::get_sections($coursecode,$cdom);
2672: my $seclist = &escape(join(':',@secs));
2673: print $client "$seclist\n";
2674: } else {
2675: print $client "refused\n";
2676: }
2677: #----------------------- validate owner of new course section (for auto-enrollment).
2678: } elsif ($userinput =~/^autonewcourse:/) {
2679: if (isClient) {
2680: my ($cmd,$inst_course_id,$owner,$cdom)=split(/:/,$userinput);
2681: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom);
2682: print $client "$outcome\n";
2683: } else {
2684: print $client "refused\n";
2685: }
2686: #-------------- validate course section in schedule of classes (for auto-enrollment).
2687: } elsif ($userinput =~/^autovalidatecourse:/) {
2688: if (isClient) {
2689: my ($cmd,$inst_course_id,$cdom)=split(/:/,$userinput);
2690: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
2691: print $client "$outcome\n";
2692: } else {
2693: print $client "refused\n";
2694: }
2695: #--------------------------- create password for new user (for auto-enrollment).
2696: } elsif ($userinput =~/^autocreatepassword:/) {
2697: if (isClient) {
2698: my ($cmd,$authparam,$cdom)=split(/:/,$userinput);
2699: my ($create_passwd,$authchk);
2700: ($authparam,$create_passwd,$authchk) = &localenroll::create_password($authparam,$cdom);
2701: print $client &escape($authparam.':'.$create_passwd.':'.$authchk)."\n";
2702: } else {
2703: print $client "refused\n";
2704: }
2705: #--------------------------- read and remove temporary files (for auto-enrollment).
2706: } elsif ($userinput =~/^autoretrieve:/) {
2707: if (isClient) {
2708: my ($cmd,$filename) = split(/:/,$userinput);
2709: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
2710: if ( (-e $source) && ($filename ne '') ) {
2711: my $reply = '';
2712: if (open(my $fh,$source)) {
2713: while (<$fh>) {
2714: chomp($_);
2715: $_ =~ s/^\s+//g;
2716: $_ =~ s/\s+$//g;
2717: $reply .= $_;
2718: }
2719: close($fh);
2720: print $client &escape($reply)."\n";
2721: # unlink($source);
2722: } else {
2723: print $client "error\n";
2724: }
2725: } else {
2726: print $client "error\n";
2727: }
2728: } else {
2729: print $client "refused\n";
2730: }
2731: #--------------------- read and retrieve institutional code format (for support form).
2732: } elsif ($userinput =~/^autoinstcodeformat:/) {
2733: if (isClient) {
2734: my $reply;
2735: my($cmd,$cdom,$course) = split(/:/,$userinput);
2736: my @pairs = split/\&/,$course;
2737: my %instcodes = ();
2738: my %codes = ();
2739: my @codetitles = ();
2740: my %cat_titles = ();
2741: my %cat_order = ();
2742: foreach (@pairs) {
2743: my ($key,$value) = split/=/,$_;
2744: $instcodes{&unescape($key)} = &unescape($value);
2745: }
2746: my $formatreply = &localenroll::instcode_format($cdom,\%instcodes,\%codes,\@codetitles,\%cat_titles,\%cat_order);
2747: if ($formatreply eq 'ok') {
2748: my $codes_str = &hash2str(%codes);
2749: my $codetitles_str = &array2str(@codetitles);
2750: my $cat_titles_str = &hash2str(%cat_titles);
2751: my $cat_order_str = &hash2str(%cat_order);
2752: print $client $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'.$cat_order_str."\n";
2753: }
2754: } else {
2755: print $client "refused\n";
2756: }
2757: # ------------------------------------------------------------- unknown command
2758:
2759: } else {
2760: # unknown command
2761: print $client "unknown_cmd\n";
2762: }
2763: # -------------------------------------------------------------------- complete
2764: Debug("process_request - returning 1");
2765: return 1;
2766: }
1.207 foxr 2767: #
2768: # Decipher encoded traffic
2769: # Parameters:
2770: # input - Encoded data.
2771: # Returns:
2772: # Decoded data or undef if encryption key was not yet negotiated.
2773: # Implicit input:
2774: # cipher - This global holds the negotiated encryption key.
2775: #
1.211 albertel 2776: sub decipher {
1.207 foxr 2777: my ($input) = @_;
2778: my $output = '';
1.212 foxr 2779:
2780:
1.207 foxr 2781: if($cipher) {
2782: my($enc, $enclength, $encinput) = split(/:/, $input);
2783: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
2784: $output .=
2785: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
2786: }
2787: return substr($output, 0, $enclength);
2788: } else {
2789: return undef;
2790: }
2791: }
2792:
2793: #
2794: # Register a command processor. This function is invoked to register a sub
2795: # to process a request. Once registered, the ProcessRequest sub can automatically
2796: # dispatch requests to an appropriate sub, and do the top level validity checking
2797: # as well:
2798: # - Is the keyword recognized.
2799: # - Is the proper client type attempting the request.
2800: # - Is the request encrypted if it has to be.
2801: # Parameters:
2802: # $request_name - Name of the request being registered.
2803: # This is the command request that will match
2804: # against the hash keywords to lookup the information
2805: # associated with the dispatch information.
2806: # $procedure - Reference to a sub to call to process the request.
2807: # All subs get called as follows:
2808: # Procedure($cmd, $tail, $replyfd, $key)
2809: # $cmd - the actual keyword that invoked us.
2810: # $tail - the tail of the request that invoked us.
2811: # $replyfd- File descriptor connected to the client
2812: # $must_encode - True if the request must be encoded to be good.
2813: # $client_ok - True if it's ok for a client to request this.
2814: # $manager_ok - True if it's ok for a manager to request this.
2815: # Side effects:
2816: # - On success, the Dispatcher hash has an entry added for the key $RequestName
2817: # - On failure, the program will die as it's a bad internal bug to try to
2818: # register a duplicate command handler.
2819: #
1.211 albertel 2820: sub register_handler {
1.212 foxr 2821: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
1.207 foxr 2822:
2823: # Don't allow duplication#
2824:
2825: if (defined $Dispatcher{$request_name}) {
2826: die "Attempting to define a duplicate request handler for $request_name\n";
2827: }
2828: # Build the client type mask:
2829:
2830: my $client_type_mask = 0;
2831: if($client_ok) {
2832: $client_type_mask |= $CLIENT_OK;
2833: }
2834: if($manager_ok) {
2835: $client_type_mask |= $MANAGER_OK;
2836: }
2837:
2838: # Enter the hash:
2839:
2840: my @entry = ($procedure, $must_encode, $client_type_mask);
2841:
2842: $Dispatcher{$request_name} = \@entry;
2843:
2844:
2845: }
2846:
2847:
2848: #------------------------------------------------------------------
2849:
2850:
2851:
2852:
1.141 foxr 2853: #
1.96 foxr 2854: # Convert an error return code from lcpasswd to a string value.
2855: #
2856: sub lcpasswdstrerror {
2857: my $ErrorCode = shift;
1.97 foxr 2858: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
1.96 foxr 2859: return "lcpasswd Unrecognized error return value ".$ErrorCode;
2860: } else {
1.98 foxr 2861: return $passwderrors[$ErrorCode];
1.96 foxr 2862: }
2863: }
2864:
1.97 foxr 2865: #
2866: # Convert an error return code from lcuseradd to a string value:
2867: #
2868: sub lcuseraddstrerror {
2869: my $ErrorCode = shift;
2870: if(($ErrorCode < 0) || ($ErrorCode > $lastadderror)) {
2871: return "lcuseradd - Unrecognized error code: ".$ErrorCode;
2872: } else {
1.98 foxr 2873: return $adderrors[$ErrorCode];
1.97 foxr 2874: }
2875: }
2876:
1.23 harris41 2877: # grabs exception and records it to log before exiting
2878: sub catchexception {
1.27 albertel 2879: my ($error)=@_;
1.25 www 2880: $SIG{'QUIT'}='DEFAULT';
2881: $SIG{__DIE__}='DEFAULT';
1.165 albertel 2882: &status("Catching exception");
1.190 albertel 2883: &logthis("<font color='red'>CRITICAL: "
1.134 albertel 2884: ."ABNORMAL EXIT. Child $$ for server $thisserver died through "
1.27 albertel 2885: ."a crash with this error msg->[$error]</font>");
1.57 www 2886: &logthis('Famous last words: '.$status.' - '.$lastlog);
1.27 albertel 2887: if ($client) { print $client "error: $error\n"; }
1.59 www 2888: $server->close();
1.27 albertel 2889: die($error);
1.23 harris41 2890: }
2891:
1.63 www 2892: sub timeout {
1.165 albertel 2893: &status("Handling Timeout");
1.190 albertel 2894: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
1.63 www 2895: &catchexception('Timeout');
2896: }
1.22 harris41 2897: # -------------------------------- Set signal handlers to record abnormal exits
2898:
2899: $SIG{'QUIT'}=\&catchexception;
2900: $SIG{__DIE__}=\&catchexception;
2901:
1.81 matthew 2902: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
1.95 harris41 2903: &status("Read loncapa.conf and loncapa_apache.conf");
2904: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
1.141 foxr 2905: %perlvar=%{$perlvarref};
1.80 harris41 2906: undef $perlvarref;
1.19 www 2907:
1.35 harris41 2908: # ----------------------------- Make sure this process is running from user=www
2909: my $wwwid=getpwnam('www');
2910: if ($wwwid!=$<) {
1.134 albertel 2911: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
2912: my $subj="LON: $currenthostid User ID mismatch";
1.37 harris41 2913: system("echo 'User ID mismatch. lond must be run as user www.' |\
1.35 harris41 2914: mailto $emailto -s '$subj' > /dev/null");
2915: exit 1;
2916: }
2917:
1.19 www 2918: # --------------------------------------------- Check if other instance running
2919:
2920: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
2921:
2922: if (-e $pidfile) {
2923: my $lfh=IO::File->new("$pidfile");
2924: my $pide=<$lfh>;
2925: chomp($pide);
1.29 harris41 2926: if (kill 0 => $pide) { die "already running"; }
1.19 www 2927: }
1.1 albertel 2928:
2929: # ------------------------------------------------------------- Read hosts file
2930:
2931:
2932:
2933: # establish SERVER socket, bind and listen.
2934: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
2935: Type => SOCK_STREAM,
2936: Proto => 'tcp',
2937: Reuse => 1,
2938: Listen => 10 )
1.29 harris41 2939: or die "making socket: $@\n";
1.1 albertel 2940:
2941: # --------------------------------------------------------- Do global variables
2942:
2943: # global variables
2944:
1.134 albertel 2945: my %children = (); # keys are current child process IDs
1.1 albertel 2946:
2947: sub REAPER { # takes care of dead children
2948: $SIG{CHLD} = \&REAPER;
1.165 albertel 2949: &status("Handling child death");
1.178 foxr 2950: my $pid;
2951: do {
2952: $pid = waitpid(-1,&WNOHANG());
2953: if (defined($children{$pid})) {
2954: &logthis("Child $pid died");
2955: delete($children{$pid});
1.183 albertel 2956: } elsif ($pid > 0) {
1.178 foxr 2957: &logthis("Unknown Child $pid died");
2958: }
2959: } while ( $pid > 0 );
2960: foreach my $child (keys(%children)) {
2961: $pid = waitpid($child,&WNOHANG());
2962: if ($pid > 0) {
2963: &logthis("Child $child - $pid looks like we missed it's death");
2964: delete($children{$pid});
2965: }
1.176 albertel 2966: }
1.165 albertel 2967: &status("Finished Handling child death");
1.1 albertel 2968: }
2969:
2970: sub HUNTSMAN { # signal handler for SIGINT
1.165 albertel 2971: &status("Killing children (INT)");
1.1 albertel 2972: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
2973: kill 'INT' => keys %children;
1.59 www 2974: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.1 albertel 2975: my $execdir=$perlvar{'lonDaemons'};
2976: unlink("$execdir/logs/lond.pid");
1.190 albertel 2977: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
1.165 albertel 2978: &status("Done killing children");
1.1 albertel 2979: exit; # clean up with dignity
2980: }
2981:
2982: sub HUPSMAN { # signal handler for SIGHUP
2983: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.165 albertel 2984: &status("Killing children for restart (HUP)");
1.1 albertel 2985: kill 'INT' => keys %children;
1.59 www 2986: &logthis("Free socket: ".shutdown($server,2)); # free up socket
1.190 albertel 2987: &logthis("<font color='red'>CRITICAL: Restarting</font>");
1.134 albertel 2988: my $execdir=$perlvar{'lonDaemons'};
1.30 harris41 2989: unlink("$execdir/logs/lond.pid");
1.165 albertel 2990: &status("Restarting self (HUP)");
1.1 albertel 2991: exec("$execdir/lond"); # here we go again
2992: }
2993:
1.144 foxr 2994: #
1.148 foxr 2995: # Kill off hashes that describe the host table prior to re-reading it.
2996: # Hashes affected are:
1.200 matthew 2997: # %hostid, %hostdom %hostip %hostdns.
1.148 foxr 2998: #
2999: sub KillHostHashes {
3000: foreach my $key (keys %hostid) {
3001: delete $hostid{$key};
3002: }
3003: foreach my $key (keys %hostdom) {
3004: delete $hostdom{$key};
3005: }
3006: foreach my $key (keys %hostip) {
3007: delete $hostip{$key};
3008: }
1.200 matthew 3009: foreach my $key (keys %hostdns) {
3010: delete $hostdns{$key};
3011: }
1.148 foxr 3012: }
3013: #
3014: # Read in the host table from file and distribute it into the various hashes:
3015: #
3016: # - %hostid - Indexed by IP, the loncapa hostname.
3017: # - %hostdom - Indexed by loncapa hostname, the domain.
3018: # - %hostip - Indexed by hostid, the Ip address of the host.
3019: sub ReadHostTable {
3020:
3021: open (CONFIG,"$perlvar{'lonTabDir'}/hosts.tab") || die "Can't read host file";
1.200 matthew 3022: my $myloncapaname = $perlvar{'lonHostID'};
3023: Debug("My loncapa name is : $myloncapaname");
1.148 foxr 3024: while (my $configline=<CONFIG>) {
1.178 foxr 3025: if (!($configline =~ /^\s*\#/)) {
3026: my ($id,$domain,$role,$name,$ip)=split(/:/,$configline);
3027: chomp($ip); $ip=~s/\D+$//;
1.200 matthew 3028: $hostid{$ip}=$id; # LonCAPA name of host by IP.
3029: $hostdom{$id}=$domain; # LonCAPA domain name of host.
3030: $hostip{$id}=$ip; # IP address of host.
3031: $hostdns{$name} = $id; # LonCAPA name of host by DNS.
3032:
3033: if ($id eq $perlvar{'lonHostID'}) {
3034: Debug("Found me in the host table: $name");
3035: $thisserver=$name;
3036: }
1.178 foxr 3037: }
1.148 foxr 3038: }
3039: close(CONFIG);
3040: }
3041: #
3042: # Reload the Apache daemon's state.
1.150 foxr 3043: # This is done by invoking /home/httpd/perl/apachereload
3044: # a setuid perl script that can be root for us to do this job.
1.148 foxr 3045: #
3046: sub ReloadApache {
1.150 foxr 3047: my $execdir = $perlvar{'lonDaemons'};
3048: my $script = $execdir."/apachereload";
3049: system($script);
1.148 foxr 3050: }
3051:
3052: #
1.144 foxr 3053: # Called in response to a USR2 signal.
3054: # - Reread hosts.tab
3055: # - All children connected to hosts that were removed from hosts.tab
3056: # are killed via SIGINT
3057: # - All children connected to previously existing hosts are sent SIGUSR1
3058: # - Our internal hosts hash is updated to reflect the new contents of
3059: # hosts.tab causing connections from hosts added to hosts.tab to
3060: # now be honored.
3061: #
3062: sub UpdateHosts {
1.165 albertel 3063: &status("Reload hosts.tab");
1.147 foxr 3064: logthis('<font color="blue"> Updating connections </font>');
1.148 foxr 3065: #
3066: # The %children hash has the set of IP's we currently have children
3067: # on. These need to be matched against records in the hosts.tab
3068: # Any ip's no longer in the table get killed off they correspond to
3069: # either dropped or changed hosts. Note that the re-read of the table
3070: # will take care of new and changed hosts as connections come into being.
3071:
3072:
3073: KillHostHashes;
3074: ReadHostTable;
3075:
3076: foreach my $child (keys %children) {
3077: my $childip = $children{$child};
3078: if(!$hostid{$childip}) {
1.149 foxr 3079: logthis('<font color="blue"> UpdateHosts killing child '
3080: ." $child for ip $childip </font>");
1.148 foxr 3081: kill('INT', $child);
1.149 foxr 3082: } else {
3083: logthis('<font color="green"> keeping child for ip '
3084: ." $childip (pid=$child) </font>");
1.148 foxr 3085: }
3086: }
3087: ReloadApache;
1.165 albertel 3088: &status("Finished reloading hosts.tab");
1.144 foxr 3089: }
3090:
1.148 foxr 3091:
1.57 www 3092: sub checkchildren {
1.165 albertel 3093: &status("Checking on the children (sending signals)");
1.57 www 3094: &initnewstatus();
3095: &logstatus();
3096: &logthis('Going to check on the children');
1.134 albertel 3097: my $docdir=$perlvar{'lonDocRoot'};
1.61 harris41 3098: foreach (sort keys %children) {
1.57 www 3099: sleep 1;
3100: unless (kill 'USR1' => $_) {
3101: &logthis ('Child '.$_.' is dead');
3102: &logstatus($$.' is dead');
3103: }
1.61 harris41 3104: }
1.63 www 3105: sleep 5;
1.212 foxr 3106: $SIG{ALRM} = sub { Debug("timeout");
3107: die "timeout"; };
1.113 albertel 3108: $SIG{__DIE__} = 'DEFAULT';
1.165 albertel 3109: &status("Checking on the children (waiting for reports)");
1.63 www 3110: foreach (sort keys %children) {
3111: unless (-e "$docdir/lon-status/londchld/$_.txt") {
1.113 albertel 3112: eval {
3113: alarm(300);
1.63 www 3114: &logthis('Child '.$_.' did not respond');
1.67 albertel 3115: kill 9 => $_;
1.131 albertel 3116: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
3117: #$subj="LON: $currenthostid killed lond process $_";
3118: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
3119: #$execdir=$perlvar{'lonDaemons'};
3120: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
1.113 albertel 3121: alarm(0);
3122: }
1.63 www 3123: }
3124: }
1.113 albertel 3125: $SIG{ALRM} = 'DEFAULT';
1.155 albertel 3126: $SIG{__DIE__} = \&catchexception;
1.165 albertel 3127: &status("Finished checking children");
1.57 www 3128: }
3129:
1.1 albertel 3130: # --------------------------------------------------------------------- Logging
3131:
3132: sub logthis {
3133: my $message=shift;
3134: my $execdir=$perlvar{'lonDaemons'};
3135: my $fh=IO::File->new(">>$execdir/logs/lond.log");
3136: my $now=time;
3137: my $local=localtime($now);
1.58 www 3138: $lastlog=$local.': '.$message;
1.1 albertel 3139: print $fh "$local ($$): $message\n";
3140: }
3141:
1.77 foxr 3142: # ------------------------- Conditional log if $DEBUG true.
3143: sub Debug {
3144: my $message = shift;
3145: if($DEBUG) {
3146: &logthis($message);
3147: }
3148: }
1.161 foxr 3149:
3150: #
3151: # Sub to do replies to client.. this gives a hook for some
3152: # debug tracing too:
3153: # Parameters:
3154: # fd - File open on client.
3155: # reply - Text to send to client.
3156: # request - Original request from client.
3157: #
3158: sub Reply {
1.192 foxr 3159: my ($fd, $reply, $request) = @_;
1.161 foxr 3160: print $fd $reply;
3161: Debug("Request was $request Reply was $reply");
3162:
1.212 foxr 3163: $Transactions++;
3164:
3165:
3166: }
3167:
3168:
3169: #
3170: # Sub to report a failure.
3171: # This function:
3172: # - Increments the failure statistic counters.
3173: # - Invokes Reply to send the error message to the client.
3174: # Parameters:
3175: # fd - File descriptor open on the client
3176: # reply - Reply text to emit.
3177: # request - The original request message (used by Reply
3178: # to debug if that's enabled.
3179: # Implicit outputs:
3180: # $Failures- The number of failures is incremented.
3181: # Reply (invoked here) sends a message to the
3182: # client:
3183: #
3184: sub Failure {
3185: my $fd = shift;
3186: my $reply = shift;
3187: my $request = shift;
3188:
3189: $Failures++;
3190: Reply($fd, $reply, $request); # That's simple eh?
1.161 foxr 3191: }
1.57 www 3192: # ------------------------------------------------------------------ Log status
3193:
3194: sub logstatus {
1.178 foxr 3195: &status("Doing logging");
3196: my $docdir=$perlvar{'lonDocRoot'};
3197: {
3198: my $fh=IO::File->new(">>$docdir/lon-status/londstatus.txt");
1.200 matthew 3199: print $fh $$."\t".$clientname."\t".$currenthostid."\t"
3200: .$status."\t".$lastlog."\t $keymode\n";
1.178 foxr 3201: $fh->close();
3202: }
3203: &status("Finished londstatus.txt");
3204: {
3205: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
1.200 matthew 3206: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
1.178 foxr 3207: $fh->close();
3208: }
3209: &status("Finished logging");
1.57 www 3210: }
3211:
3212: sub initnewstatus {
3213: my $docdir=$perlvar{'lonDocRoot'};
3214: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
3215: my $now=time;
3216: my $local=localtime($now);
3217: print $fh "LOND status $local - parent $$\n\n";
1.64 www 3218: opendir(DIR,"$docdir/lon-status/londchld");
1.134 albertel 3219: while (my $filename=readdir(DIR)) {
1.64 www 3220: unlink("$docdir/lon-status/londchld/$filename");
3221: }
3222: closedir(DIR);
1.57 www 3223: }
3224:
3225: # -------------------------------------------------------------- Status setting
3226:
3227: sub status {
3228: my $what=shift;
3229: my $now=time;
3230: my $local=localtime($now);
1.178 foxr 3231: $status=$local.': '.$what;
3232: $0='lond: '.$what.' '.$local;
1.57 www 3233: }
1.11 www 3234:
3235: # -------------------------------------------------------- Escape Special Chars
3236:
3237: sub escape {
3238: my $str=shift;
3239: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
3240: return $str;
3241: }
3242:
3243: # ----------------------------------------------------- Un-Escape Special Chars
3244:
3245: sub unescape {
3246: my $str=shift;
3247: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
3248: return $str;
3249: }
3250:
1.1 albertel 3251: # ----------------------------------------------------------- Send USR1 to lonc
3252:
3253: sub reconlonc {
3254: my $peerfile=shift;
3255: &logthis("Trying to reconnect for $peerfile");
3256: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
3257: if (my $fh=IO::File->new("$loncfile")) {
3258: my $loncpid=<$fh>;
3259: chomp($loncpid);
3260: if (kill 0 => $loncpid) {
3261: &logthis("lonc at pid $loncpid responding, sending USR1");
3262: kill USR1 => $loncpid;
3263: } else {
1.9 www 3264: &logthis(
1.190 albertel 3265: "<font color='red'>CRITICAL: "
1.9 www 3266: ."lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 3267: }
3268: } else {
1.190 albertel 3269: &logthis('<font color="red">CRITICAL: lonc not running, giving up</font>');
1.1 albertel 3270: }
3271: }
3272:
3273: # -------------------------------------------------- Non-critical communication
1.11 www 3274:
1.1 albertel 3275: sub subreply {
3276: my ($cmd,$server)=@_;
3277: my $peerfile="$perlvar{'lonSockDir'}/$server";
3278: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
3279: Type => SOCK_STREAM,
3280: Timeout => 10)
3281: or return "con_lost";
3282: print $sclient "$cmd\n";
3283: my $answer=<$sclient>;
3284: chomp($answer);
3285: if (!$answer) { $answer="con_lost"; }
3286: return $answer;
3287: }
3288:
3289: sub reply {
3290: my ($cmd,$server)=@_;
3291: my $answer;
1.115 albertel 3292: if ($server ne $currenthostid) {
1.1 albertel 3293: $answer=subreply($cmd,$server);
3294: if ($answer eq 'con_lost') {
3295: $answer=subreply("ping",$server);
3296: if ($answer ne $server) {
1.115 albertel 3297: &logthis("sub reply: answer != server answer is $answer, server is $server");
1.1 albertel 3298: &reconlonc("$perlvar{'lonSockDir'}/$server");
3299: }
3300: $answer=subreply($cmd,$server);
3301: }
3302: } else {
3303: $answer='self_reply';
3304: }
3305: return $answer;
3306: }
3307:
1.13 www 3308: # -------------------------------------------------------------- Talk to lonsql
3309:
1.12 harris41 3310: sub sqlreply {
3311: my ($cmd)=@_;
3312: my $answer=subsqlreply($cmd);
3313: if ($answer eq 'con_lost') { $answer=subsqlreply($cmd); }
3314: return $answer;
3315: }
3316:
3317: sub subsqlreply {
3318: my ($cmd)=@_;
3319: my $unixsock="mysqlsock";
3320: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
3321: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
3322: Type => SOCK_STREAM,
3323: Timeout => 10)
3324: or return "con_lost";
3325: print $sclient "$cmd\n";
3326: my $answer=<$sclient>;
3327: chomp($answer);
3328: if (!$answer) { $answer="con_lost"; }
3329: return $answer;
3330: }
3331:
1.1 albertel 3332: # -------------------------------------------- Return path to profile directory
1.11 www 3333:
1.1 albertel 3334: sub propath {
3335: my ($udom,$uname)=@_;
3336: $udom=~s/\W//g;
3337: $uname=~s/\W//g;
1.16 www 3338: my $subdir=$uname.'__';
1.1 albertel 3339: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
3340: my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
3341: return $proname;
3342: }
3343:
3344: # --------------------------------------- Is this the home server of an author?
1.11 www 3345:
1.1 albertel 3346: sub ishome {
3347: my $author=shift;
3348: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3349: my ($udom,$uname)=split(/\//,$author);
3350: my $proname=propath($udom,$uname);
3351: if (-e $proname) {
3352: return 'owner';
3353: } else {
3354: return 'not_owner';
3355: }
3356: }
3357:
3358: # ======================================================= Continue main program
3359: # ---------------------------------------------------- Fork once and dissociate
3360:
1.134 albertel 3361: my $fpid=fork;
1.1 albertel 3362: exit if $fpid;
1.29 harris41 3363: die "Couldn't fork: $!" unless defined ($fpid);
1.1 albertel 3364:
1.29 harris41 3365: POSIX::setsid() or die "Can't start new session: $!";
1.1 albertel 3366:
3367: # ------------------------------------------------------- Write our PID on disk
3368:
1.134 albertel 3369: my $execdir=$perlvar{'lonDaemons'};
1.1 albertel 3370: open (PIDSAVE,">$execdir/logs/lond.pid");
3371: print PIDSAVE "$$\n";
3372: close(PIDSAVE);
1.190 albertel 3373: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
1.57 www 3374: &status('Starting');
1.1 albertel 3375:
1.106 foxr 3376:
1.1 albertel 3377:
3378: # ----------------------------------------------------- Install signal handlers
3379:
1.57 www 3380:
1.1 albertel 3381: $SIG{CHLD} = \&REAPER;
3382: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
3383: $SIG{HUP} = \&HUPSMAN;
1.57 www 3384: $SIG{USR1} = \&checkchildren;
1.144 foxr 3385: $SIG{USR2} = \&UpdateHosts;
1.106 foxr 3386:
1.148 foxr 3387: # Read the host hashes:
3388:
3389: ReadHostTable;
1.106 foxr 3390:
3391: # --------------------------------------------------------------
3392: # Accept connections. When a connection comes in, it is validated
3393: # and if good, a child process is created to process transactions
3394: # along the connection.
3395:
1.1 albertel 3396: while (1) {
1.165 albertel 3397: &status('Starting accept');
1.106 foxr 3398: $client = $server->accept() or next;
1.165 albertel 3399: &status('Accepted '.$client.' off to spawn');
1.106 foxr 3400: make_new_child($client);
1.165 albertel 3401: &status('Finished spawning');
1.1 albertel 3402: }
3403:
1.212 foxr 3404: sub make_new_child {
3405: my $pid;
3406: # my $cipher; # Now global
3407: my $sigset;
1.178 foxr 3408:
1.212 foxr 3409: $client = shift;
3410: &status('Starting new child '.$client);
3411: &logthis('<font color="green"> Attempting to start child ('.$client.
3412: ")</font>");
3413: # block signal for fork
3414: $sigset = POSIX::SigSet->new(SIGINT);
3415: sigprocmask(SIG_BLOCK, $sigset)
3416: or die "Can't block SIGINT for fork: $!\n";
1.178 foxr 3417:
1.212 foxr 3418: die "fork: $!" unless defined ($pid = fork);
1.178 foxr 3419:
1.212 foxr 3420: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
3421: # connection liveness.
1.178 foxr 3422:
1.212 foxr 3423: #
3424: # Figure out who we're talking to so we can record the peer in
3425: # the pid hash.
3426: #
3427: my $caller = getpeername($client);
3428: my ($port,$iaddr);
3429: if (defined($caller) && length($caller) > 0) {
3430: ($port,$iaddr)=unpack_sockaddr_in($caller);
3431: } else {
3432: &logthis("Unable to determine who caller was, getpeername returned nothing");
3433: }
3434: if (defined($iaddr)) {
3435: $clientip = inet_ntoa($iaddr);
3436: Debug("Connected with $clientip");
3437: $clientdns = gethostbyaddr($iaddr, AF_INET);
3438: Debug("Connected with $clientdns by name");
3439: } else {
3440: &logthis("Unable to determine clientip");
3441: $clientip='Unavailable';
3442: }
3443:
3444: if ($pid) {
3445: # Parent records the child's birth and returns.
3446: sigprocmask(SIG_UNBLOCK, $sigset)
3447: or die "Can't unblock SIGINT for fork: $!\n";
3448: $children{$pid} = $clientip;
3449: &status('Started child '.$pid);
3450: return;
3451: } else {
3452: # Child can *not* return from this subroutine.
3453: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
3454: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
3455: #don't get intercepted
3456: $SIG{USR1}= \&logstatus;
3457: $SIG{ALRM}= \&timeout;
3458: $lastlog='Forked ';
3459: $status='Forked';
1.178 foxr 3460:
1.212 foxr 3461: # unblock signals
3462: sigprocmask(SIG_UNBLOCK, $sigset)
3463: or die "Can't unblock SIGINT for fork: $!\n";
1.178 foxr 3464:
1.212 foxr 3465: # my $tmpsnum=0; # Now global
3466: #---------------------------------------------------- kerberos 5 initialization
3467: &Authen::Krb5::init_context();
3468: &Authen::Krb5::init_ets();
1.209 albertel 3469:
1.212 foxr 3470: &status('Accepted connection');
3471: # =============================================================================
3472: # do something with the connection
3473: # -----------------------------------------------------------------------------
3474: # see if we know client and 'check' for spoof IP by ineffective challenge
1.178 foxr 3475:
1.212 foxr 3476: ReadManagerTable; # May also be a manager!!
3477:
3478: my $clientrec=($hostid{$clientip} ne undef);
3479: my $ismanager=($managers{$clientip} ne undef);
3480: $clientname = "[unknonwn]";
3481: if($clientrec) { # Establish client type.
3482: $ConnectionType = "client";
3483: $clientname = $hostid{$clientip};
3484: if($ismanager) {
3485: $ConnectionType = "both";
3486: }
3487: } else {
3488: $ConnectionType = "manager";
3489: $clientname = $managers{$clientip};
3490: }
3491: my $clientok;
1.178 foxr 3492:
1.212 foxr 3493: if ($clientrec || $ismanager) {
3494: &status("Waiting for init from $clientip $clientname");
3495: &logthis('<font color="yellow">INFO: Connection, '.
3496: $clientip.
3497: " ($clientname) connection type = $ConnectionType </font>" );
3498: &status("Connecting $clientip ($clientname))");
3499: my $remotereq=<$client>;
3500: chomp($remotereq);
3501: Debug("Got init: $remotereq");
3502: my $inikeyword = split(/:/, $remotereq);
3503: if ($remotereq =~ /^init/) {
3504: &sethost("sethost:$perlvar{'lonHostID'}");
3505: #
3506: # If the remote is attempting a local init... give that a try:
3507: #
3508: my ($i, $inittype) = split(/:/, $remotereq);
1.209 albertel 3509:
1.212 foxr 3510: # If the connection type is ssl, but I didn't get my
3511: # certificate files yet, then I'll drop back to
3512: # insecure (if allowed).
3513:
3514: if($inittype eq "ssl") {
3515: my ($ca, $cert) = lonssl::CertificateFile;
3516: my $kfile = lonssl::KeyFile;
3517: if((!$ca) ||
3518: (!$cert) ||
3519: (!$kfile)) {
3520: $inittype = ""; # This forces insecure attempt.
3521: &logthis("<font color=\"blue\"> Certificates not "
3522: ."installed -- trying insecure auth</font>");
1.178 foxr 3523: }
1.212 foxr 3524: else { # SSL certificates are in place so
3525: } # Leave the inittype alone.
3526: }
3527:
3528: if($inittype eq "local") {
3529: my $key = LocalConnection($client, $remotereq);
3530: if($key) {
3531: Debug("Got local key $key");
3532: $clientok = 1;
3533: my $cipherkey = pack("H32", $key);
3534: $cipher = new IDEA($cipherkey);
3535: print $client "ok:local\n";
3536: &logthis('<font color="green"'
3537: . "Successful local authentication </font>");
3538: $keymode = "local"
1.178 foxr 3539: } else {
1.212 foxr 3540: Debug("Failed to get local key");
3541: $clientok = 0;
3542: shutdown($client, 3);
3543: close $client;
1.178 foxr 3544: }
1.212 foxr 3545: } elsif ($inittype eq "ssl") {
3546: my $key = SSLConnection($client);
3547: if ($key) {
3548: $clientok = 1;
3549: my $cipherkey = pack("H32", $key);
3550: $cipher = new IDEA($cipherkey);
3551: &logthis('<font color="green">'
3552: ."Successfull ssl authentication with $clientname </font>");
3553: $keymode = "ssl";
3554:
1.178 foxr 3555: } else {
1.212 foxr 3556: $clientok = 0;
3557: close $client;
1.178 foxr 3558: }
1.212 foxr 3559:
3560: } else {
3561: my $ok = InsecureConnection($client);
3562: if($ok) {
3563: $clientok = 1;
3564: &logthis('<font color="green">'
3565: ."Successful insecure authentication with $clientname </font>");
3566: print $client "ok\n";
3567: $keymode = "insecure";
1.178 foxr 3568: } else {
1.212 foxr 3569: &logthis('<font color="yellow">'
3570: ."Attempted insecure connection disallowed </font>");
3571: close $client;
3572: $clientok = 0;
1.178 foxr 3573:
3574: }
3575: }
1.212 foxr 3576: } else {
3577: &logthis(
3578: "<font color='blue'>WARNING: "
3579: ."$clientip failed to initialize: >$remotereq< </font>");
3580: &status('No init '.$clientip);
3581: }
3582:
3583: } else {
3584: &logthis(
3585: "<font color='blue'>WARNING: Unknown client $clientip</font>");
3586: &status('Hung up on '.$clientip);
3587: }
3588:
3589: if ($clientok) {
3590: # ---------------- New known client connecting, could mean machine online again
3591:
3592: foreach my $id (keys(%hostip)) {
3593: if ($hostip{$id} ne $clientip ||
3594: $hostip{$currenthostid} eq $clientip) {
3595: # no need to try to do recon's to myself
3596: next;
3597: }
3598: &reconlonc("$perlvar{'lonSockDir'}/$id");
3599: }
3600: &logthis("<font color='green'>Established connection: $clientname</font>");
3601: &status('Will listen to '.$clientname);
3602: # ------------------------------------------------------------ Process requests
3603: my $keep_going = 1;
3604: my $user_input;
3605: while(($user_input = get_request) && $keep_going) {
3606: alarm(120);
3607: Debug("Main: Got $user_input\n");
3608: $keep_going = &process_request($user_input);
1.178 foxr 3609: alarm(0);
1.212 foxr 3610: &status('Listening to '.$clientname." ($keymode)");
1.161 foxr 3611: }
1.212 foxr 3612:
1.59 www 3613: # --------------------------------------------- client unknown or fishy, refuse
1.212 foxr 3614: } else {
1.161 foxr 3615: print $client "refused\n";
3616: $client->close();
1.190 albertel 3617: &logthis("<font color='blue'>WARNING: "
1.161 foxr 3618: ."Rejected client $clientip, closing connection</font>");
3619: }
1.212 foxr 3620: }
1.161 foxr 3621:
1.1 albertel 3622: # =============================================================================
1.161 foxr 3623:
1.190 albertel 3624: &logthis("<font color='red'>CRITICAL: "
1.161 foxr 3625: ."Disconnect from $clientip ($clientname)</font>");
3626:
3627:
3628: # this exit is VERY important, otherwise the child will become
3629: # a producer of more and more children, forking yourself into
3630: # process death.
3631: exit;
1.106 foxr 3632:
1.78 foxr 3633: }
3634:
3635:
3636: #
3637: # Checks to see if the input roleput request was to set
3638: # an author role. If so, invokes the lchtmldir script to set
3639: # up a correct public_html
3640: # Parameters:
3641: # request - The request sent to the rolesput subchunk.
3642: # We're looking for /domain/_au
3643: # domain - The domain in which the user is having roles doctored.
3644: # user - Name of the user for which the role is being put.
3645: # authtype - The authentication type associated with the user.
3646: #
3647: sub ManagePermissions
3648: {
1.192 foxr 3649:
3650: my ($request, $domain, $user, $authtype) = @_;
1.78 foxr 3651:
3652: # See if the request is of the form /$domain/_au
3653: if($request =~ /^(\/$domain\/_au)$/) { # It's an author rolesput...
3654: my $execdir = $perlvar{'lonDaemons'};
3655: my $userhome= "/home/$user" ;
1.134 albertel 3656: &logthis("system $execdir/lchtmldir $userhome $user $authtype");
1.78 foxr 3657: system("$execdir/lchtmldir $userhome $user $authtype");
3658: }
3659: }
3660: #
3661: # GetAuthType - Determines the authorization type of a user in a domain.
3662:
3663: # Returns the authorization type or nouser if there is no such user.
3664: #
3665: sub GetAuthType
3666: {
1.192 foxr 3667:
3668: my ($domain, $user) = @_;
1.78 foxr 3669:
1.79 foxr 3670: Debug("GetAuthType( $domain, $user ) \n");
1.78 foxr 3671: my $proname = &propath($domain, $user);
3672: my $passwdfile = "$proname/passwd";
3673: if( -e $passwdfile ) {
3674: my $pf = IO::File->new($passwdfile);
3675: my $realpassword = <$pf>;
3676: chomp($realpassword);
1.79 foxr 3677: Debug("Password info = $realpassword\n");
1.78 foxr 3678: my ($authtype, $contentpwd) = split(/:/, $realpassword);
1.79 foxr 3679: Debug("Authtype = $authtype, content = $contentpwd\n");
1.78 foxr 3680: my $availinfo = '';
1.91 albertel 3681: if($authtype eq 'krb4' or $authtype eq 'krb5') {
1.78 foxr 3682: $availinfo = $contentpwd;
3683: }
1.79 foxr 3684:
1.78 foxr 3685: return "$authtype:$availinfo";
3686: }
3687: else {
1.79 foxr 3688: Debug("Returning nouser");
1.78 foxr 3689: return "nouser";
3690: }
1.1 albertel 3691: }
3692:
1.84 albertel 3693: sub addline {
3694: my ($fname,$hostid,$ip,$newline)=@_;
3695: my $contents;
3696: my $found=0;
3697: my $expr='^'.$hostid.':'.$ip.':';
3698: $expr =~ s/\./\\\./g;
1.134 albertel 3699: my $sh;
1.84 albertel 3700: if ($sh=IO::File->new("$fname.subscription")) {
3701: while (my $subline=<$sh>) {
3702: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
3703: }
3704: $sh->close();
3705: }
3706: $sh=IO::File->new(">$fname.subscription");
3707: if ($contents) { print $sh $contents; }
3708: if ($newline) { print $sh $newline; }
3709: $sh->close();
3710: return $found;
1.86 www 3711: }
3712:
3713: sub getchat {
1.122 www 3714: my ($cdom,$cname,$udom,$uname)=@_;
1.87 www 3715: my %hash;
3716: my $proname=&propath($cdom,$cname);
3717: my @entries=();
1.88 albertel 3718: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
3719: &GDBM_READER(),0640)) {
3720: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
3721: untie %hash;
1.123 www 3722: }
1.124 www 3723: my @participants=();
1.134 albertel 3724: my $cutoff=time-60;
1.123 www 3725: if (tie(%hash,'GDBM_File',"$proname/nohist_inchatroom.db",
1.124 www 3726: &GDBM_WRCREAT(),0640)) {
3727: $hash{$uname.':'.$udom}=time;
1.123 www 3728: foreach (sort keys %hash) {
3729: if ($hash{$_}>$cutoff) {
1.124 www 3730: $participants[$#participants+1]='active_participant:'.$_;
1.123 www 3731: }
3732: }
3733: untie %hash;
1.86 www 3734: }
1.124 www 3735: return (@participants,@entries);
1.86 www 3736: }
3737:
3738: sub chatadd {
1.88 albertel 3739: my ($cdom,$cname,$newchat)=@_;
3740: my %hash;
3741: my $proname=&propath($cdom,$cname);
3742: my @entries=();
1.142 www 3743: my $time=time;
1.88 albertel 3744: if (tie(%hash,'GDBM_File',"$proname/nohist_chatroom.db",
3745: &GDBM_WRCREAT(),0640)) {
3746: @entries=map { $_.':'.$hash{$_} } sort keys %hash;
3747: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
3748: my ($thentime,$idnum)=split(/\_/,$lastid);
3749: my $newid=$time.'_000000';
3750: if ($thentime==$time) {
3751: $idnum=~s/^0+//;
3752: $idnum++;
3753: $idnum=substr('000000'.$idnum,-6,6);
3754: $newid=$time.'_'.$idnum;
3755: }
3756: $hash{$newid}=$newchat;
3757: my $expired=$time-3600;
3758: foreach (keys %hash) {
3759: my ($thistime)=($_=~/(\d+)\_/);
3760: if ($thistime<$expired) {
1.89 www 3761: delete $hash{$_};
1.88 albertel 3762: }
3763: }
3764: untie %hash;
1.142 www 3765: }
3766: {
3767: my $hfh;
3768: if ($hfh=IO::File->new(">>$proname/chatroom.log")) {
3769: print $hfh "$time:".&unescape($newchat)."\n";
3770: }
1.86 www 3771: }
1.84 albertel 3772: }
3773:
3774: sub unsub {
3775: my ($fname,$clientip)=@_;
3776: my $result;
1.188 foxr 3777: my $unsubs = 0; # Number of successful unsubscribes:
3778:
3779:
3780: # An old way subscriptions were handled was to have a
3781: # subscription marker file:
3782:
3783: Debug("Attempting unlink of $fname.$clientname");
1.161 foxr 3784: if (unlink("$fname.$clientname")) {
1.188 foxr 3785: $unsubs++; # Successful unsub via marker file.
3786: }
3787:
3788: # The more modern way to do it is to have a subscription list
3789: # file:
3790:
1.84 albertel 3791: if (-e "$fname.subscription") {
1.161 foxr 3792: my $found=&addline($fname,$clientname,$clientip,'');
1.188 foxr 3793: if ($found) {
3794: $unsubs++;
3795: }
3796: }
3797:
3798: # If either or both of these mechanisms succeeded in unsubscribing a
3799: # resource we can return ok:
3800:
3801: if($unsubs) {
3802: $result = "ok\n";
1.84 albertel 3803: } else {
1.188 foxr 3804: $result = "not_subscribed\n";
1.84 albertel 3805: }
1.188 foxr 3806:
1.84 albertel 3807: return $result;
3808: }
3809:
1.101 www 3810: sub currentversion {
3811: my $fname=shift;
3812: my $version=-1;
3813: my $ulsdir='';
3814: if ($fname=~/^(.+)\/[^\/]+$/) {
3815: $ulsdir=$1;
3816: }
1.114 albertel 3817: my ($fnamere1,$fnamere2);
3818: # remove version if already specified
1.101 www 3819: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
1.114 albertel 3820: # get the bits that go before and after the version number
3821: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
3822: $fnamere1=$1;
3823: $fnamere2='.'.$2;
3824: }
1.101 www 3825: if (-e $fname) { $version=1; }
3826: if (-e $ulsdir) {
1.134 albertel 3827: if(-d $ulsdir) {
3828: if (opendir(LSDIR,$ulsdir)) {
3829: my $ulsfn;
3830: while ($ulsfn=readdir(LSDIR)) {
1.101 www 3831: # see if this is a regular file (ignore links produced earlier)
1.134 albertel 3832: my $thisfile=$ulsdir.'/'.$ulsfn;
3833: unless (-l $thisfile) {
1.160 www 3834: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
1.134 albertel 3835: if ($1>$version) { $version=$1; }
3836: }
3837: }
3838: }
3839: closedir(LSDIR);
3840: $version++;
3841: }
3842: }
3843: }
3844: return $version;
1.101 www 3845: }
3846:
3847: sub thisversion {
3848: my $fname=shift;
3849: my $version=-1;
3850: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
3851: $version=$1;
3852: }
3853: return $version;
3854: }
3855:
1.84 albertel 3856: sub subscribe {
3857: my ($userinput,$clientip)=@_;
3858: my $result;
3859: my ($cmd,$fname)=split(/:/,$userinput);
3860: my $ownership=&ishome($fname);
3861: if ($ownership eq 'owner') {
1.101 www 3862: # explitly asking for the current version?
3863: unless (-e $fname) {
3864: my $currentversion=¤tversion($fname);
3865: if (&thisversion($fname)==$currentversion) {
3866: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
3867: my $root=$1;
3868: my $extension=$2;
3869: symlink($root.'.'.$extension,
3870: $root.'.'.$currentversion.'.'.$extension);
1.102 www 3871: unless ($extension=~/\.meta$/) {
3872: symlink($root.'.'.$extension.'.meta',
3873: $root.'.'.$currentversion.'.'.$extension.'.meta');
3874: }
1.101 www 3875: }
3876: }
3877: }
1.84 albertel 3878: if (-e $fname) {
3879: if (-d $fname) {
3880: $result="directory\n";
3881: } else {
1.161 foxr 3882: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
1.134 albertel 3883: my $now=time;
1.161 foxr 3884: my $found=&addline($fname,$clientname,$clientip,
3885: "$clientname:$clientip:$now\n");
1.84 albertel 3886: if ($found) { $result="$fname\n"; }
3887: # if they were subscribed to only meta data, delete that
3888: # subscription, when you subscribe to a file you also get
3889: # the metadata
3890: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
3891: $fname=~s/\/home\/httpd\/html\/res/raw/;
3892: $fname="http://$thisserver/".$fname;
3893: $result="$fname\n";
3894: }
3895: } else {
3896: $result="not_found\n";
3897: }
3898: } else {
3899: $result="rejected\n";
3900: }
3901: return $result;
3902: }
1.91 albertel 3903:
3904: sub make_passwd_file {
1.98 foxr 3905: my ($uname, $umode,$npass,$passfilename)=@_;
1.91 albertel 3906: my $result="ok\n";
3907: if ($umode eq 'krb4' or $umode eq 'krb5') {
3908: {
3909: my $pf = IO::File->new(">$passfilename");
3910: print $pf "$umode:$npass\n";
3911: }
3912: } elsif ($umode eq 'internal') {
3913: my $salt=time;
3914: $salt=substr($salt,6,2);
3915: my $ncpass=crypt($npass,$salt);
3916: {
3917: &Debug("Creating internal auth");
3918: my $pf = IO::File->new(">$passfilename");
3919: print $pf "internal:$ncpass\n";
3920: }
3921: } elsif ($umode eq 'localauth') {
3922: {
3923: my $pf = IO::File->new(">$passfilename");
3924: print $pf "localauth:$npass\n";
3925: }
3926: } elsif ($umode eq 'unix') {
3927: {
1.186 foxr 3928: #
3929: # Don't allow the creation of privileged accounts!!! that would
3930: # be real bad!!!
3931: #
3932: my $uid = getpwnam($uname);
3933: if((defined $uid) && ($uid == 0)) {
3934: &logthis(">>>Attempted to create privilged account blocked");
3935: return "no_priv_account_error\n";
3936: }
3937:
1.91 albertel 3938: my $execpath="$perlvar{'lonDaemons'}/"."lcuseradd";
3939: {
3940: &Debug("Executing external: ".$execpath);
1.98 foxr 3941: &Debug("user = ".$uname.", Password =". $npass);
1.132 matthew 3942: my $se = IO::File->new("|$execpath > $perlvar{'lonDaemons'}/logs/lcuseradd.log");
1.91 albertel 3943: print $se "$uname\n";
3944: print $se "$npass\n";
3945: print $se "$npass\n";
1.97 foxr 3946: }
3947: my $useraddok = $?;
3948: if($useraddok > 0) {
3949: &logthis("Failed lcuseradd: ".&lcuseraddstrerror($useraddok));
1.91 albertel 3950: }
3951: my $pf = IO::File->new(">$passfilename");
3952: print $pf "unix:\n";
3953: }
3954: } elsif ($umode eq 'none') {
3955: {
3956: my $pf = IO::File->new(">$passfilename");
3957: print $pf "none:\n";
3958: }
3959: } else {
3960: $result="auth_mode_error\n";
3961: }
3962: return $result;
1.121 albertel 3963: }
3964:
3965: sub sethost {
3966: my ($remotereq) = @_;
3967: my (undef,$hostid)=split(/:/,$remotereq);
3968: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
3969: if ($hostip{$perlvar{'lonHostID'}} eq $hostip{$hostid}) {
1.200 matthew 3970: $currenthostid =$hostid;
1.121 albertel 3971: $currentdomainid=$hostdom{$hostid};
3972: &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
3973: } else {
3974: &logthis("Requested host id $hostid not an alias of ".
3975: $perlvar{'lonHostID'}." refusing connection");
3976: return 'unable_to_set';
3977: }
3978: return 'ok';
3979: }
3980:
3981: sub version {
3982: my ($userinput)=@_;
3983: $remoteVERSION=(split(/:/,$userinput))[1];
3984: return "version:$VERSION";
1.127 albertel 3985: }
1.178 foxr 3986:
1.128 albertel 3987: #There is a copy of this in lonnet.pm
1.127 albertel 3988: sub userload {
3989: my $numusers=0;
3990: {
3991: opendir(LONIDS,$perlvar{'lonIDsDir'});
3992: my $filename;
3993: my $curtime=time;
3994: while ($filename=readdir(LONIDS)) {
3995: if ($filename eq '.' || $filename eq '..') {next;}
1.138 albertel 3996: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.159 albertel 3997: if ($curtime-$mtime < 1800) { $numusers++; }
1.127 albertel 3998: }
3999: closedir(LONIDS);
4000: }
4001: my $userloadpercent=0;
4002: my $maxuserload=$perlvar{'lonUserLoadLim'};
4003: if ($maxuserload) {
1.129 albertel 4004: $userloadpercent=100*$numusers/$maxuserload;
1.127 albertel 4005: }
1.130 albertel 4006: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.127 albertel 4007: return $userloadpercent;
1.91 albertel 4008: }
4009:
1.205 raeburn 4010: # Routines for serializing arrays and hashes (copies from lonnet)
4011:
4012: sub array2str {
4013: my (@array) = @_;
4014: my $result=&arrayref2str(\@array);
4015: $result=~s/^__ARRAY_REF__//;
4016: $result=~s/__END_ARRAY_REF__$//;
4017: return $result;
4018: }
4019:
4020: sub arrayref2str {
4021: my ($arrayref) = @_;
4022: my $result='__ARRAY_REF__';
4023: foreach my $elem (@$arrayref) {
4024: if(ref($elem) eq 'ARRAY') {
4025: $result.=&arrayref2str($elem).'&';
4026: } elsif(ref($elem) eq 'HASH') {
4027: $result.=&hashref2str($elem).'&';
4028: } elsif(ref($elem)) {
4029: #print("Got a ref of ".(ref($elem))." skipping.");
4030: } else {
4031: $result.=&escape($elem).'&';
4032: }
4033: }
4034: $result=~s/\&$//;
4035: $result .= '__END_ARRAY_REF__';
4036: return $result;
4037: }
4038:
4039: sub hash2str {
4040: my (%hash) = @_;
4041: my $result=&hashref2str(\%hash);
4042: $result=~s/^__HASH_REF__//;
4043: $result=~s/__END_HASH_REF__$//;
4044: return $result;
4045: }
4046:
4047: sub hashref2str {
4048: my ($hashref)=@_;
4049: my $result='__HASH_REF__';
4050: foreach (sort(keys(%$hashref))) {
4051: if (ref($_) eq 'ARRAY') {
4052: $result.=&arrayref2str($_).'=';
4053: } elsif (ref($_) eq 'HASH') {
4054: $result.=&hashref2str($_).'=';
4055: } elsif (ref($_)) {
4056: $result.='=';
4057: #print("Got a ref of ".(ref($_))." skipping.");
4058: } else {
4059: if ($_) {$result.=&escape($_).'=';} else { last; }
4060: }
4061:
4062: if(ref($hashref->{$_}) eq 'ARRAY') {
4063: $result.=&arrayref2str($hashref->{$_}).'&';
4064: } elsif(ref($hashref->{$_}) eq 'HASH') {
4065: $result.=&hashref2str($hashref->{$_}).'&';
4066: } elsif(ref($hashref->{$_})) {
4067: $result.='&';
4068: #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
4069: } else {
4070: $result.=&escape($hashref->{$_}).'&';
4071: }
4072: }
4073: $result=~s/\&$//;
4074: $result .= '__END_HASH_REF__';
4075: return $result;
4076: }
1.200 matthew 4077:
1.61 harris41 4078: # ----------------------------------- POD (plain old documentation, CPAN style)
4079:
4080: =head1 NAME
4081:
4082: lond - "LON Daemon" Server (port "LOND" 5663)
4083:
4084: =head1 SYNOPSIS
4085:
1.74 harris41 4086: Usage: B<lond>
4087:
4088: Should only be run as user=www. This is a command-line script which
4089: is invoked by B<loncron>. There is no expectation that a typical user
4090: will manually start B<lond> from the command-line. (In other words,
4091: DO NOT START B<lond> YOURSELF.)
1.61 harris41 4092:
4093: =head1 DESCRIPTION
4094:
1.74 harris41 4095: There are two characteristics associated with the running of B<lond>,
4096: PROCESS MANAGEMENT (starting, stopping, handling child processes)
4097: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
4098: subscriptions, etc). These are described in two large
4099: sections below.
4100:
4101: B<PROCESS MANAGEMENT>
4102:
1.61 harris41 4103: Preforker - server who forks first. Runs as a daemon. HUPs.
4104: Uses IDEA encryption
4105:
1.74 harris41 4106: B<lond> forks off children processes that correspond to the other servers
4107: in the network. Management of these processes can be done at the
4108: parent process level or the child process level.
4109:
4110: B<logs/lond.log> is the location of log messages.
4111:
4112: The process management is now explained in terms of linux shell commands,
4113: subroutines internal to this code, and signal assignments:
4114:
4115: =over 4
4116:
4117: =item *
4118:
4119: PID is stored in B<logs/lond.pid>
4120:
4121: This is the process id number of the parent B<lond> process.
4122:
4123: =item *
4124:
4125: SIGTERM and SIGINT
4126:
4127: Parent signal assignment:
4128: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
4129:
4130: Child signal assignment:
4131: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
4132: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
4133: to restart a new child.)
4134:
4135: Command-line invocations:
4136: B<kill> B<-s> SIGTERM I<PID>
4137: B<kill> B<-s> SIGINT I<PID>
4138:
4139: Subroutine B<HUNTSMAN>:
4140: This is only invoked for the B<lond> parent I<PID>.
4141: This kills all the children, and then the parent.
4142: The B<lonc.pid> file is cleared.
4143:
4144: =item *
4145:
4146: SIGHUP
4147:
4148: Current bug:
4149: This signal can only be processed the first time
4150: on the parent process. Subsequent SIGHUP signals
4151: have no effect.
4152:
4153: Parent signal assignment:
4154: $SIG{HUP} = \&HUPSMAN;
4155:
4156: Child signal assignment:
4157: none (nothing happens)
4158:
4159: Command-line invocations:
4160: B<kill> B<-s> SIGHUP I<PID>
4161:
4162: Subroutine B<HUPSMAN>:
4163: This is only invoked for the B<lond> parent I<PID>,
4164: This kills all the children, and then the parent.
4165: The B<lond.pid> file is cleared.
4166:
4167: =item *
4168:
4169: SIGUSR1
4170:
4171: Parent signal assignment:
4172: $SIG{USR1} = \&USRMAN;
4173:
4174: Child signal assignment:
4175: $SIG{USR1}= \&logstatus;
4176:
4177: Command-line invocations:
4178: B<kill> B<-s> SIGUSR1 I<PID>
4179:
4180: Subroutine B<USRMAN>:
4181: When invoked for the B<lond> parent I<PID>,
4182: SIGUSR1 is sent to all the children, and the status of
4183: each connection is logged.
1.144 foxr 4184:
4185: =item *
4186:
4187: SIGUSR2
4188:
4189: Parent Signal assignment:
4190: $SIG{USR2} = \&UpdateHosts
4191:
4192: Child signal assignment:
4193: NONE
4194:
1.74 harris41 4195:
4196: =item *
4197:
4198: SIGCHLD
4199:
4200: Parent signal assignment:
4201: $SIG{CHLD} = \&REAPER;
4202:
4203: Child signal assignment:
4204: none
4205:
4206: Command-line invocations:
4207: B<kill> B<-s> SIGCHLD I<PID>
4208:
4209: Subroutine B<REAPER>:
4210: This is only invoked for the B<lond> parent I<PID>.
4211: Information pertaining to the child is removed.
4212: The socket port is cleaned up.
4213:
4214: =back
4215:
4216: B<SERVER-SIDE ACTIVITIES>
4217:
4218: Server-side information can be accepted in an encrypted or non-encrypted
4219: method.
4220:
4221: =over 4
4222:
4223: =item ping
4224:
4225: Query a client in the hosts.tab table; "Are you there?"
4226:
4227: =item pong
4228:
4229: Respond to a ping query.
4230:
4231: =item ekey
4232:
4233: Read in encrypted key, make cipher. Respond with a buildkey.
4234:
4235: =item load
4236:
4237: Respond with CPU load based on a computation upon /proc/loadavg.
4238:
4239: =item currentauth
4240:
4241: Reply with current authentication information (only over an
4242: encrypted channel).
4243:
4244: =item auth
4245:
4246: Only over an encrypted channel, reply as to whether a user's
4247: authentication information can be validated.
4248:
4249: =item passwd
4250:
4251: Allow for a password to be set.
4252:
4253: =item makeuser
4254:
4255: Make a user.
4256:
4257: =item passwd
4258:
4259: Allow for authentication mechanism and password to be changed.
4260:
4261: =item home
1.61 harris41 4262:
1.74 harris41 4263: Respond to a question "are you the home for a given user?"
4264:
4265: =item update
4266:
4267: Update contents of a subscribed resource.
4268:
4269: =item unsubscribe
4270:
4271: The server is unsubscribing from a resource.
4272:
4273: =item subscribe
4274:
4275: The server is subscribing to a resource.
4276:
4277: =item log
4278:
4279: Place in B<logs/lond.log>
4280:
4281: =item put
4282:
4283: stores hash in namespace
4284:
4285: =item rolesput
4286:
4287: put a role into a user's environment
4288:
4289: =item get
4290:
4291: returns hash with keys from array
4292: reference filled in from namespace
4293:
4294: =item eget
4295:
4296: returns hash with keys from array
4297: reference filled in from namesp (encrypts the return communication)
4298:
4299: =item rolesget
4300:
4301: get a role from a user's environment
4302:
4303: =item del
4304:
4305: deletes keys out of array from namespace
4306:
4307: =item keys
4308:
4309: returns namespace keys
4310:
4311: =item dump
4312:
4313: dumps the complete (or key matching regexp) namespace into a hash
4314:
4315: =item store
4316:
4317: stores hash permanently
4318: for this url; hashref needs to be given and should be a \%hashname; the
4319: remaining args aren't required and if they aren't passed or are '' they will
4320: be derived from the ENV
4321:
4322: =item restore
4323:
4324: returns a hash for a given url
4325:
4326: =item querysend
4327:
4328: Tells client about the lonsql process that has been launched in response
4329: to a sent query.
4330:
4331: =item queryreply
4332:
4333: Accept information from lonsql and make appropriate storage in temporary
4334: file space.
4335:
4336: =item idput
4337:
4338: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
4339: for each student, defined perhaps by the institutional Registrar.)
4340:
4341: =item idget
4342:
4343: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
4344: for each student, defined perhaps by the institutional Registrar.)
4345:
4346: =item tmpput
4347:
4348: Accept and store information in temporary space.
4349:
4350: =item tmpget
4351:
4352: Send along temporarily stored information.
4353:
4354: =item ls
4355:
4356: List part of a user's directory.
4357:
1.135 foxr 4358: =item pushtable
4359:
4360: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
4361: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
4362: must be restored manually in case of a problem with the new table file.
4363: pushtable requires that the request be encrypted and validated via
4364: ValidateManager. The form of the command is:
4365: enc:pushtable tablename <tablecontents> \n
4366: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
4367: cleartext newline.
4368:
1.74 harris41 4369: =item Hanging up (exit or init)
4370:
4371: What to do when a client tells the server that they (the client)
4372: are leaving the network.
4373:
4374: =item unknown command
4375:
4376: If B<lond> is sent an unknown command (not in the list above),
4377: it replys to the client "unknown_cmd".
1.135 foxr 4378:
1.74 harris41 4379:
4380: =item UNKNOWN CLIENT
4381:
4382: If the anti-spoofing algorithm cannot verify the client,
4383: the client is rejected (with a "refused" message sent
4384: to the client, and the connection is closed.
4385:
4386: =back
1.61 harris41 4387:
4388: =head1 PREREQUISITES
4389:
4390: IO::Socket
4391: IO::File
4392: Apache::File
4393: Symbol
4394: POSIX
4395: Crypt::IDEA
4396: LWP::UserAgent()
4397: GDBM_File
4398: Authen::Krb4
1.91 albertel 4399: Authen::Krb5
1.61 harris41 4400:
4401: =head1 COREQUISITES
4402:
4403: =head1 OSNAMES
4404:
4405: linux
4406:
4407: =head1 SCRIPT CATEGORIES
4408:
4409: Server/Process
4410:
4411: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>