1: #!/usr/bin/perl
2: # The LearningOnline Network
3: # lond "LON Daemon" Server (port "LOND" 5663)
4: #
5: # $Id: lond,v 1.540 2017/06/06 20:03:24 raeburn Exp $
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
13: # the Free Software Foundation; either version 2 of the License, or
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
23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
27:
28:
29: # http://www.lon-capa.org/
30: #
31:
32: use strict;
33: use lib '/home/httpd/lib/perl/';
34: use LONCAPA;
35: use LONCAPA::Configuration;
36: use LONCAPA::Lond;
37:
38: use Socket;
39: use IO::Socket;
40: use IO::File;
41: #use Apache::File;
42: use POSIX;
43: use Crypt::IDEA;
44: use HTTP::Request;
45: use Digest::MD5 qw(md5_hex);
46: use GDBM_File;
47: use Authen::Krb5;
48: use localauth;
49: use localenroll;
50: use localstudentphoto;
51: use File::Copy;
52: use File::Find;
53: use LONCAPA::lonlocal;
54: use LONCAPA::lonssl;
55: use Fcntl qw(:flock);
56: use Apache::lonnet;
57: use Mail::Send;
58: use Crypt::Eksblowfish::Bcrypt;
59: use Digest::SHA;
60: use Encode;
61: use LONCAPA::LWPReq;
62:
63: my $DEBUG = 0; # Non zero to enable debug log entries.
64:
65: my $status='';
66: my $lastlog='';
67:
68: my $VERSION='$Revision: 1.540 $'; #' stupid emacs
69: my $remoteVERSION;
70: my $currenthostid="default";
71: my $currentdomainid;
72:
73: my $client;
74: my $clientip; # IP address of client.
75: my $clientname; # LonCAPA name of client.
76: my $clientversion; # LonCAPA version running on client.
77: my $clienthomedom; # LonCAPA domain of homeID for client.
78: my $clientintdom; # LonCAPA "internet domain" for client.
79: my $clientsamedom; # LonCAPA domain same for this host
80: # and client.
81: my $clientsameinst; # LonCAPA "internet domain" same for
82: # this host and client.
83: my $clientremoteok; # Client allowed to host domain's users.
84: # (version constraints ignored), not set
85: # if this host and client share "internet domain".
86: my %clientprohibited; # Actions prohibited on client;
87:
88: my $server;
89:
90: my $keymode;
91:
92: my $cipher; # Cipher key negotiated with client
93: my $tmpsnum = 0; # Id of tmpputs.
94:
95: #
96: # Connection type is:
97: # client - All client actions are allowed
98: # manager - only management functions allowed.
99: # both - Both management and client actions are allowed
100: #
101:
102: my $ConnectionType;
103:
104: my %managers; # Ip -> manager names
105:
106: my %perlvar; # Will have the apache conf defined perl vars.
107:
108: my %secureconf; # Will have requirements for security
109: # of lond connections
110:
111: my $dist;
112:
113: #
114: # The hash below is used for command dispatching, and is therefore keyed on the request keyword.
115: # Each element of the hash contains a reference to an array that contains:
116: # A reference to a sub that executes the request corresponding to the keyword.
117: # A flag that is true if the request must be encoded to be acceptable.
118: # A mask with bits as follows:
119: # CLIENT_OK - Set when the function is allowed by ordinary clients
120: # MANAGER_OK - Set when the function is allowed to manager clients.
121: #
122: my $CLIENT_OK = 1;
123: my $MANAGER_OK = 2;
124: my %Dispatcher;
125:
126:
127: #
128: # The array below are password error strings."
129: #
130: my $lastpwderror = 13; # Largest error number from lcpasswd.
131: my @passwderrors = ("ok",
132: "pwchange_failure - lcpasswd must be run as user 'www'",
133: "pwchange_failure - lcpasswd got incorrect number of arguments",
134: "pwchange_failure - lcpasswd did not get the right nubmer of input text lines",
135: "pwchange_failure - lcpasswd too many simultaneous pwd changes in progress",
136: "pwchange_failure - lcpasswd User does not exist.",
137: "pwchange_failure - lcpasswd Incorrect current passwd",
138: "pwchange_failure - lcpasswd Unable to su to root.",
139: "pwchange_failure - lcpasswd Cannot set new passwd.",
140: "pwchange_failure - lcpasswd Username has invalid characters",
141: "pwchange_failure - lcpasswd Invalid characters in password",
142: "pwchange_failure - lcpasswd User already exists",
143: "pwchange_failure - lcpasswd Something went wrong with user addition.",
144: "pwchange_failure - lcpasswd Password mismatch",
145: "pwchange_failure - lcpasswd Error filename is invalid");
146:
147:
148: # This array are the errors from lcinstallfile:
149:
150: my @installerrors = ("ok",
151: "Initial user id of client not that of www",
152: "Usage error, not enough command line arguments",
153: "Source filename does not exist",
154: "Destination filename does not exist",
155: "Some file operation failed",
156: "Invalid table filename."
157: );
158:
159: #
160: # The %trust hash classifies commands according to type of trust
161: # required for execution of the command.
162: #
163: # When clients from a different institution request execution of a
164: # particular command, the trust settings for that institution set
165: # for this domain (or default domain for a multi-domain server) will
166: # be checked to see if running the command is allowed.
167: #
168: # Trust types which depend on the "Trust" domain configuration
169: # for the machine's default domain are:
170: #
171: # content ("Access to this domain's content by others")
172: # shared ("Access to other domain's content by this domain")
173: # enroll ("Enrollment in this domain's courses by others")
174: # coaurem ("Co-author roles for this domain's users elsewhere")
175: # domroles ("Domain roles in this domain assignable to others")
176: # catalog ("Course Catalog for this domain displayed elsewhere")
177: # reqcrs ("Requests for creation of courses in this domain by others")
178: # msg ("Users in other domains can send messages to this domain")
179: #
180: # Trust type which depends on the User Session Hosting (remote)
181: # domain configuration for machine's default domain is: "remote".
182: #
183: # Trust types which depend on contents of manager.tab in
184: # /home/httpd/lonTabs is: "manageronly".
185: #
186: # Trust type which requires client to share the same LON-CAPA
187: # "internet domain" (i.e., same institution as this server) is:
188: # "institutiononly".
189: #
190:
191: my %trust = (
192: auth => {remote => 1},
193: autocreatepassword => {remote => 1},
194: autocrsreqchecks => {remote => 1, reqcrs => 1},
195: autocrsrequpdate => {remote => 1},
196: autocrsreqvalidation => {remote => 1},
197: autogetsections => {remote => 1},
198: autoinstcodedefaults => {remote => 1, catalog => 1},
199: autoinstcodeformat => {remote => 1, catalog => 1},
200: autonewcourse => {remote => 1, reqcrs => 1},
201: autophotocheck => {remote => 1, enroll => 1},
202: autophotochoice => {remote => 1},
203: autophotopermission => {remote => 1, enroll => 1},
204: autopossibleinstcodes => {remote => 1, reqcrs => 1},
205: autoretrieve => {remote => 1, enroll => 1, catalog => 1},
206: autorun => {remote => 1, enroll => 1, reqcrs => 1},
207: autovalidateclass_sec => {catalog => 1},
208: autovalidatecourse => {remote => 1, enroll => 1},
209: autovalidateinstcode => {domroles => 1, remote => 1, enroll => 1},
210: changeuserauth => {remote => 1, domroles => 1},
211: chatretr => {remote => 1, enroll => 1},
212: chatsend => {remote => 1, enroll => 1},
213: courseiddump => {remote => 1, domroles => 1, enroll => 1},
214: courseidput => {remote => 1, domroles => 1, enroll => 1},
215: courseidputhash => {remote => 1, domroles => 1, enroll => 1},
216: courselastaccess => {remote => 1, domroles => 1, enroll => 1},
217: currentauth => {remote => 1, domroles => 1, enroll => 1},
218: currentdump => {remote => 1, enroll => 1},
219: currentversion => {remote=> 1, content => 1},
220: dcmaildump => {remote => 1, domroles => 1},
221: dcmailput => {remote => 1, domroles => 1},
222: del => {remote => 1, domroles => 1, enroll => 1, content => 1},
223: deldom => {remote => 1, domroles => 1}, # not currently used
224: devalidatecache => {institutiononly => 1},
225: domroleput => {remote => 1, enroll => 1},
226: domrolesdump => {remote => 1, catalog => 1},
227: du => {remote => 1, enroll => 1},
228: du2 => {remote => 1, enroll => 1},
229: dump => {remote => 1, enroll => 1, domroles => 1},
230: edit => {institutiononly => 1}, #not used currently
231: eget => {remote => 1, domroles => 1, enroll => 1}, #not used currently
232: egetdom => {remote => 1, domroles => 1, enroll => 1, },
233: ekey => {}, #not used currently
234: exit => {anywhere => 1},
235: fetchuserfile => {remote => 1, enroll => 1},
236: get => {remote => 1, domroles => 1, enroll => 1},
237: getdom => {anywhere => 1},
238: home => {anywhere => 1},
239: iddel => {remote => 1, enroll => 1},
240: idget => {remote => 1, enroll => 1},
241: idput => {remote => 1, domroles => 1, enroll => 1},
242: inc => {remote => 1, enroll => 1},
243: init => {anywhere => 1},
244: inst_usertypes => {remote => 1, domroles => 1, enroll => 1},
245: instemailrules => {remote => 1, domroles => 1},
246: instidrulecheck => {remote => 1, domroles => 1,},
247: instidrules => {remote => 1, domroles => 1,},
248: instrulecheck => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
249: instselfcreatecheck => {institutiononly => 1},
250: instuserrules => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1},
251: keys => {remote => 1,},
252: load => {anywhere => 1},
253: log => {anywhere => 1},
254: ls => {remote => 1, enroll => 1, content => 1,},
255: ls2 => {remote => 1, enroll => 1, content => 1,},
256: ls3 => {remote => 1, enroll => 1, content => 1,},
257: makeuser => {remote => 1, enroll => 1, domroles => 1,},
258: mkdiruserfile => {remote => 1, enroll => 1,},
259: newput => {remote => 1, enroll => 1, reqcrs => 1, domroles => 1,},
260: passwd => {remote => 1},
261: ping => {anywhere => 1},
262: pong => {anywhere => 1},
263: pushfile => {manageronly => 1},
264: put => {remote => 1, enroll => 1, domroles => 1, msg => 1, content => 1, shared => 1},
265: putdom => {remote => 1, domroles => 1,},
266: putstore => {remote => 1, enroll => 1},
267: queryreply => {anywhere => 1},
268: querysend => {anywhere => 1},
269: querysend_activitylog => {remote => 1},
270: querysend_allusers => {remote => 1, domroles => 1},
271: querysend_courselog => {remote => 1},
272: querysend_fetchenrollment => {remote => 1},
273: querysend_getinstuser => {remote => 1},
274: querysend_getmultinstusers => {remote => 1},
275: querysend_instdirsearch => {remote => 1, domroles => 1, coaurem => 1},
276: querysend_institutionalphotos => {remote => 1},
277: querysend_portfolio_metadata => {remote => 1, content => 1},
278: querysend_userlog => {remote => 1, domroles => 1},
279: querysend_usersearch => {remote => 1, enroll => 1, coaurem => 1},
280: quit => {anywhere => 1},
281: readlonnetglobal => {institutiononly => 1},
282: reinit => {manageronly => 1}, #not used currently
283: removeuserfile => {remote => 1, enroll => 1},
284: renameuserfile => {remote => 1,},
285: restore => {remote => 1, enroll => 1, reqcrs => 1,},
286: rolesdel => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
287: rolesput => {remote => 1, enroll => 1, domroles => 1, coaurem => 1},
288: servercerts => {institutiononly => 1},
289: serverdistarch => {anywhere => 1},
290: serverhomeID => {anywhere => 1},
291: serverloncaparev => {anywhere => 1},
292: servertimezone => {remote => 1, enroll => 1},
293: setannounce => {remote => 1, domroles => 1},
294: sethost => {anywhere => 1},
295: store => {remote => 1, enroll => 1, reqcrs => 1,},
296: studentphoto => {remote => 1, enroll => 1},
297: sub => {content => 1,},
298: tmpdel => {anywhere => 1},
299: tmpget => {anywhere => 1},
300: tmpput => {anywhere => 1},
301: tokenauthuserfile => {anywhere => 1},
302: unsub => {content => 1,},
303: update => {shared => 1},
304: updateclickers => {remote => 1},
305: userhassession => {anywhere => 1},
306: userload => {anywhere => 1},
307: version => {anywhere => 1}, #not used
308: );
309:
310: #
311: # Statistics that are maintained and dislayed in the status line.
312: #
313: my $Transactions = 0; # Number of attempted transactions.
314: my $Failures = 0; # Number of transcations failed.
315:
316: # ResetStatistics:
317: # Resets the statistics counters:
318: #
319: sub ResetStatistics {
320: $Transactions = 0;
321: $Failures = 0;
322: }
323:
324: #------------------------------------------------------------------------
325: #
326: # LocalConnection
327: # Completes the formation of a locally authenticated connection.
328: # This function will ensure that the 'remote' client is really the
329: # local host. If not, the connection is closed, and the function fails.
330: # If so, initcmd is parsed for the name of a file containing the
331: # IDEA session key. The fie is opened, read, deleted and the session
332: # key returned to the caller.
333: #
334: # Parameters:
335: # $Socket - Socket open on client.
336: # $initcmd - The full text of the init command.
337: #
338: # Returns:
339: # IDEA session key on success.
340: # undef on failure.
341: #
342: sub LocalConnection {
343: my ($Socket, $initcmd) = @_;
344: Debug("Attempting local connection: $initcmd client: $clientip");
345: if($clientip ne "127.0.0.1") {
346: &logthis('<font color="red"> LocalConnection rejecting non local: '
347: ."$clientip ne 127.0.0.1 </font>");
348: close $Socket;
349: return undef;
350: } else {
351: chomp($initcmd); # Get rid of \n in filename.
352: my ($init, $type, $name) = split(/:/, $initcmd);
353: Debug(" Init command: $init $type $name ");
354:
355: # Require that $init = init, and $type = local: Otherwise
356: # the caller is insane:
357:
358: if(($init ne "init") && ($type ne "local")) {
359: &logthis('<font color = "red"> LocalConnection: caller is insane! '
360: ."init = $init, and type = $type </font>");
361: close($Socket);;
362: return undef;
363:
364: }
365: # Now get the key filename:
366:
367: my $IDEAKey = lonlocal::ReadKeyFile($name);
368: return $IDEAKey;
369: }
370: }
371: #------------------------------------------------------------------------------
372: #
373: # SSLConnection
374: # Completes the formation of an ssh authenticated connection. The
375: # socket is promoted to an ssl socket. If this promotion and the associated
376: # certificate exchange are successful, the IDEA key is generated and sent
377: # to the remote peer via the SSL tunnel. The IDEA key is also returned to
378: # the caller after the SSL tunnel is torn down.
379: #
380: # Parameters:
381: # Name Type Purpose
382: # $Socket IO::Socket::INET Plaintext socket.
383: #
384: # Returns:
385: # IDEA key on success.
386: # undef on failure.
387: #
388: sub SSLConnection {
389: my $Socket = shift;
390:
391: Debug("SSLConnection: ");
392: my $KeyFile = lonssl::KeyFile();
393: if(!$KeyFile) {
394: my $err = lonssl::LastError();
395: &logthis("<font color=\"red\"> CRITICAL"
396: ."Can't get key file $err </font>");
397: return undef;
398: }
399: my ($CACertificate,
400: $Certificate) = lonssl::CertificateFile();
401:
402:
403: # If any of the key, certificate or certificate authority
404: # certificate filenames are not defined, this can't work.
405:
406: if((!$Certificate) || (!$CACertificate)) {
407: my $err = lonssl::LastError();
408: &logthis("<font color=\"red\"> CRITICAL"
409: ."Can't get certificates: $err </font>");
410:
411: return undef;
412: }
413: Debug("Key: $KeyFile CA: $CACertificate Cert: $Certificate");
414:
415: # Indicate to our peer that we can procede with
416: # a transition to ssl authentication:
417:
418: print $Socket "ok:ssl\n";
419:
420: Debug("Approving promotion -> ssl");
421: # And do so:
422:
423: my $SSLSocket = lonssl::PromoteServerSocket($Socket,
424: $CACertificate,
425: $Certificate,
426: $KeyFile);
427: if(! ($SSLSocket) ) { # SSL socket promotion failed.
428: my $err = lonssl::LastError();
429: &logthis("<font color=\"red\"> CRITICAL "
430: ."SSL Socket promotion failed: $err </font>");
431: return undef;
432: }
433: Debug("SSL Promotion successful");
434:
435: #
436: # The only thing we'll use the socket for is to send the IDEA key
437: # to the peer:
438:
439: my $Key = lonlocal::CreateCipherKey();
440: print $SSLSocket "$Key\n";
441:
442: lonssl::Close($SSLSocket);
443:
444: Debug("Key exchange complete: $Key");
445:
446: return $Key;
447: }
448: #
449: # InsecureConnection:
450: # If insecure connections are allowd,
451: # exchange a challenge with the client to 'validate' the
452: # client (not really, but that's the protocol):
453: # We produce a challenge string that's sent to the client.
454: # The client must then echo the challenge verbatim to us.
455: #
456: # Parameter:
457: # Socket - Socket open on the client.
458: # Returns:
459: # 1 - success.
460: # 0 - failure (e.g.mismatch or insecure not allowed).
461: #
462: sub InsecureConnection {
463: my $Socket = shift;
464:
465: # Don't even start if insecure connections are not allowed.
466: # return 0 if Insecure connections not allowed.
467: #
468: if (ref($secureconf{'connfrom'}) eq 'HASH') {
469: if ($clientsamedom) {
470: if ($secureconf{'connfrom'}{'dom'} eq 'req') {
471: return 0;
472: }
473: } elsif ($clientsameinst) {
474: if ($secureconf{'connfrom'}{'intdom'} eq 'req') {
475: return 0;
476: }
477: } else {
478: if ($secureconf{'connfrom'}{'other'} eq 'req') {
479: return 0;
480: }
481: }
482: } elsif (!$perlvar{londAllowInsecure}) {
483: return 0;
484: }
485:
486: # Fabricate a challenge string and send it..
487:
488: my $challenge = "$$".time; # pid + time.
489: print $Socket "$challenge\n";
490: &status("Waiting for challenge reply");
491:
492: my $answer = <$Socket>;
493: $answer =~s/\W//g;
494: if($challenge eq $answer) {
495: return 1;
496: } else {
497: logthis("<font color='blue'>WARNING client did not respond to challenge</font>");
498: &status("No challenge reqply");
499: return 0;
500: }
501:
502:
503: }
504: #
505: # Safely execute a command (as long as it's not a shel command and doesn
506: # not require/rely on shell escapes. The function operates by doing a
507: # a pipe based fork and capturing stdout and stderr from the pipe.
508: #
509: # Formal Parameters:
510: # $line - A line of text to be executed as a command.
511: # Returns:
512: # The output from that command. If the output is multiline the caller
513: # must know how to split up the output.
514: #
515: #
516: sub execute_command {
517: my ($line) = @_;
518: my @words = split(/\s/, $line); # Bust the command up into words.
519: my $output = "";
520:
521: my $pid = open(CHILD, "-|");
522:
523: if($pid) { # Parent process
524: Debug("In parent process for execute_command");
525: my @data = <CHILD>; # Read the child's outupt...
526: close CHILD;
527: foreach my $output_line (@data) {
528: Debug("Adding $output_line");
529: $output .= $output_line; # Presumably has a \n on it.
530: }
531:
532: } else { # Child process
533: close (STDERR);
534: open (STDERR, ">&STDOUT");# Combine stderr, and stdout...
535: exec(@words); # won't return.
536: }
537: return $output;
538: }
539:
540:
541: # GetCertificate: Given a transaction that requires a certificate,
542: # this function will extract the certificate from the transaction
543: # request. Note that at this point, the only concept of a certificate
544: # is the hostname to which we are connected.
545: #
546: # Parameter:
547: # request - The request sent by our client (this parameterization may
548: # need to change when we really use a certificate granting
549: # authority.
550: #
551: sub GetCertificate {
552: my $request = shift;
553:
554: return $clientip;
555: }
556:
557: #
558: # Return true if client is a manager.
559: #
560: sub isManager {
561: return (($ConnectionType eq "manager") || ($ConnectionType eq "both"));
562: }
563: #
564: # Return tru if client can do client functions
565: #
566: sub isClient {
567: return (($ConnectionType eq "client") || ($ConnectionType eq "both"));
568: }
569:
570:
571: #
572: # ReadManagerTable: Reads in the current manager table. For now this is
573: # done on each manager authentication because:
574: # - These authentications are not frequent
575: # - This allows dynamic changes to the manager table
576: # without the need to signal to the lond.
577: #
578: sub ReadManagerTable {
579:
580: &Debug("Reading manager table");
581: # Clean out the old table first..
582:
583: foreach my $key (keys %managers) {
584: delete $managers{$key};
585: }
586:
587: my $tablename = $perlvar{'lonTabDir'}."/managers.tab";
588: if (!open (MANAGERS, $tablename)) {
589: my $hostname = &Apache::lonnet::hostname($perlvar{'lonHostID'});
590: if (&Apache::lonnet::is_LC_dns($hostname)) {
591: &logthis('<font color="red">No manager table. Nobody can manage!!</font>');
592: }
593: return;
594: }
595: while(my $host = <MANAGERS>) {
596: chomp($host);
597: if ($host =~ "^#") { # Comment line.
598: next;
599: }
600: if (!defined &Apache::lonnet::get_host_ip($host)) { # This is a non cluster member
601: # The entry is of the form:
602: # cluname:hostname
603: # cluname - A 'cluster hostname' is needed in order to negotiate
604: # the host key.
605: # hostname- The dns name of the host.
606: #
607: my($cluname, $dnsname) = split(/:/, $host);
608:
609: my $ip = gethostbyname($dnsname);
610: if(defined($ip)) { # bad names don't deserve entry.
611: my $hostip = inet_ntoa($ip);
612: $managers{$hostip} = $cluname;
613: logthis('<font color="green"> registering manager '.
614: "$dnsname as $cluname with $hostip </font>\n");
615: }
616: } else {
617: logthis('<font color="green"> existing host'." $host</font>\n");
618: $managers{&Apache::lonnet::get_host_ip($host)} = $host; # Use info from cluster tab if cluster memeber
619: }
620: }
621: }
622:
623: #
624: # ValidManager: Determines if a given certificate represents a valid manager.
625: # in this primitive implementation, the 'certificate' is
626: # just the connecting loncapa client name. This is checked
627: # against a valid client list in the configuration.
628: #
629: #
630: sub ValidManager {
631: my $certificate = shift;
632:
633: return isManager;
634: }
635: #
636: # CopyFile: Called as part of the process of installing a
637: # new configuration file. This function copies an existing
638: # file to a backup file.
639: # Parameters:
640: # oldfile - Name of the file to backup.
641: # newfile - Name of the backup file.
642: # Return:
643: # 0 - Failure (errno has failure reason).
644: # 1 - Success.
645: #
646: sub CopyFile {
647:
648: my ($oldfile, $newfile) = @_;
649:
650: if (! copy($oldfile,$newfile)) {
651: return 0;
652: }
653: chmod(0660, $newfile);
654: return 1;
655: }
656: #
657: # Host files are passed out with externally visible host IPs.
658: # If, for example, we are behind a fire-wall or NAT host, our
659: # internally visible IP may be different than the externally
660: # visible IP. Therefore, we always adjust the contents of the
661: # host file so that the entry for ME is the IP that we believe
662: # we have. At present, this is defined as the entry that
663: # DNS has for us. If by some chance we are not able to get a
664: # DNS translation for us, then we assume that the host.tab file
665: # is correct.
666: # BUGBUGBUG - in the future, we really should see if we can
667: # easily query the interface(s) instead.
668: # Parameter(s):
669: # contents - The contents of the host.tab to check.
670: # Returns:
671: # newcontents - The adjusted contents.
672: #
673: #
674: sub AdjustHostContents {
675: my $contents = shift;
676: my $adjusted;
677: my $me = $perlvar{'lonHostID'};
678:
679: foreach my $line (split(/\n/,$contents)) {
680: if(!(($line eq "") || ($line =~ /^ *\#/) || ($line =~ /^ *$/) ||
681: ($line =~ /^\s*\^/))) {
682: chomp($line);
683: my ($id,$domain,$role,$name,$ip,$maxcon,$idleto,$mincon)=split(/:/,$line);
684: if ($id eq $me) {
685: my $ip = gethostbyname($name);
686: my $ipnew = inet_ntoa($ip);
687: $ip = $ipnew;
688: # Reconstruct the host line and append to adjusted:
689:
690: my $newline = "$id:$domain:$role:$name:$ip";
691: if($maxcon ne "") { # Not all hosts have loncnew tuning params
692: $newline .= ":$maxcon:$idleto:$mincon";
693: }
694: $adjusted .= $newline."\n";
695:
696: } else { # Not me, pass unmodified.
697: $adjusted .= $line."\n";
698: }
699: } else { # Blank or comment never re-written.
700: $adjusted .= $line."\n"; # Pass blanks and comments as is.
701: }
702: }
703: return $adjusted;
704: }
705: #
706: # InstallFile: Called to install an administrative file:
707: # - The file is created int a temp directory called <name>.tmp
708: # - lcinstall file is called to install the file.
709: # since the web app has no direct write access to the table directory
710: #
711: # Parameters:
712: # Name of the file
713: # File Contents.
714: # Return:
715: # nonzero - success.
716: # 0 - failure and $! has an errno.
717: # Assumptions:
718: # File installtion is a relatively infrequent
719: #
720: sub InstallFile {
721:
722: my ($Filename, $Contents) = @_;
723: # my $TempFile = $Filename.".tmp";
724: my $exedir = $perlvar{'lonDaemons'};
725: my $tmpdir = $exedir.'/tmp/';
726: my $TempFile = $tmpdir."TempTableFile.tmp";
727:
728: # Open the file for write:
729:
730: my $fh = IO::File->new("> $TempFile"); # Write to temp.
731: if(!(defined $fh)) {
732: &logthis('<font color="red"> Unable to create '.$TempFile."</font>");
733: return 0;
734: }
735: # write the contents of the file:
736:
737: print $fh ($Contents);
738: $fh->close; # In case we ever have a filesystem w. locking
739:
740: chmod(0664, $TempFile); # Everyone can write it.
741:
742: # Use lcinstall file to put the file in the table directory...
743:
744: &Debug("Opening pipe to $exedir/lcinstallfile $TempFile $Filename");
745: my $pf = IO::File->new("| $exedir/lcinstallfile $TempFile $Filename > $exedir/logs/lcinstallfile.log");
746: close $pf;
747: my $err = $?;
748: &Debug("Status is $err");
749: if ($err != 0) {
750: my $msg = $err;
751: if ($err < @installerrors) {
752: $msg = $installerrors[$err];
753: }
754: &logthis("Install failed for table file $Filename : $msg");
755: return 0;
756: }
757:
758: # Remove the temp file:
759:
760: unlink($TempFile);
761:
762: return 1;
763: }
764:
765:
766: #
767: # ConfigFileFromSelector: converts a configuration file selector
768: # into a configuration file pathname.
769: # Supports the following file selectors:
770: # hosts, domain, dns_hosts, dns_domain
771: #
772: #
773: # Parameters:
774: # selector - Configuration file selector.
775: # Returns:
776: # Full path to the file or undef if the selector is invalid.
777: #
778: sub ConfigFileFromSelector {
779: my $selector = shift;
780: my $tablefile;
781:
782: my $tabledir = $perlvar{'lonTabDir'}.'/';
783: if (($selector eq "hosts") || ($selector eq "domain") ||
784: ($selector eq "dns_hosts") || ($selector eq "dns_domain")) {
785: $tablefile = $tabledir.$selector.'.tab';
786: }
787: return $tablefile;
788: }
789: #
790: # PushFile: Called to do an administrative push of a file.
791: # - Ensure the file being pushed is one we support.
792: # - Backup the old file to <filename.saved>
793: # - Separate the contents of the new file out from the
794: # rest of the request.
795: # - Write the new file.
796: # Parameter:
797: # Request - The entire user request. This consists of a : separated
798: # string pushfile:tablename:contents.
799: # NOTE: The contents may have :'s in it as well making things a bit
800: # more interesting... but not much.
801: # Returns:
802: # String to send to client ("ok" or "refused" if bad file).
803: #
804: sub PushFile {
805: my $request = shift;
806: my ($command, $filename, $contents) = split(":", $request, 3);
807: &Debug("PushFile");
808:
809: # At this point in time, pushes for only the following tables are
810: # supported:
811: # hosts.tab ($filename eq host).
812: # domain.tab ($filename eq domain).
813: # dns_hosts.tab ($filename eq dns_host).
814: # dns_domain.tab ($filename eq dns_domain).
815: # Construct the destination filename or reject the request.
816: #
817: # lonManage is supposed to ensure this, however this session could be
818: # part of some elaborate spoof that managed somehow to authenticate.
819: #
820:
821:
822: my $tablefile = ConfigFileFromSelector($filename);
823: if(! (defined $tablefile)) {
824: return "refused";
825: }
826:
827: # If the file being pushed is the host file, we adjust the entry for ourself so that the
828: # IP will be our current IP as looked up in dns. Note this is only 99% good as it's possible
829: # to conceive of conditions where we don't have a DNS entry locally. This is possible in a
830: # network sense but it doesn't make much sense in a LonCAPA sense so we ignore (for now)
831: # that possibilty.
832:
833: if($filename eq "host") {
834: $contents = AdjustHostContents($contents);
835: } elsif ($filename eq 'dns_host' || $filename eq 'dns_domain') {
836: if ($contents eq '') {
837: &logthis('<font color="red"> Pushfile: unable to install '
838: .$tablefile." - no data received from push. </font>");
839: return 'error: push had no data';
840: }
841: if (&Apache::lonnet::get_host_ip($clientname)) {
842: my $clienthost = &Apache::lonnet::hostname($clientname);
843: if ($managers{$clientip} eq $clientname) {
844: my $clientprotocol = $Apache::lonnet::protocol{$clientname};
845: $clientprotocol = 'http' if ($clientprotocol ne 'https');
846: my $url = '/adm/'.$filename;
847: $url =~ s{_}{/};
848: my $request=new HTTP::Request('GET',"$clientprotocol://$clienthost$url");
849: my $response = LONCAPA::LWPReq::makerequest($clientname,$request,'',\%perlvar,60,0);
850: if ($response->is_error()) {
851: &logthis('<font color="red"> Pushfile: unable to install '
852: .$tablefile." - error attempting to pull data. </font>");
853: return 'error: pull failed';
854: } else {
855: my $result = $response->content;
856: chomp($result);
857: unless ($result eq $contents) {
858: &logthis('<font color="red"> Pushfile: unable to install '
859: .$tablefile." - pushed data and pulled data differ. </font>");
860: my $pushleng = length($contents);
861: my $pullleng = length($result);
862: if ($pushleng != $pullleng) {
863: return "error: $pushleng vs $pullleng bytes";
864: } else {
865: return "error: mismatch push and pull";
866: }
867: }
868: }
869: }
870: }
871: }
872:
873: # Install the new file:
874:
875: &logthis("Installing new $tablefile contents:\n$contents");
876: if(!InstallFile($tablefile, $contents)) {
877: &logthis('<font color="red"> Pushfile: unable to install '
878: .$tablefile." $! </font>");
879: return "error:$!";
880: } else {
881: &logthis('<font color="green"> Installed new '.$tablefile
882: ." - transaction by: $clientname ($clientip)</font>");
883: my $adminmail = $perlvar{'lonAdmEMail'};
884: my $admindom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
885: if ($admindom ne '') {
886: my %domconfig =
887: &Apache::lonnet::get_dom('configuration',['contacts'],$admindom);
888: if (ref($domconfig{'contacts'}) eq 'HASH') {
889: if ($domconfig{'contacts'}{'adminemail'} ne '') {
890: $adminmail = $domconfig{'contacts'}{'adminemail'};
891: }
892: }
893: }
894: if ($adminmail =~ /^[^\@]+\@[^\@]+$/) {
895: my $msg = new Mail::Send;
896: $msg->to($adminmail);
897: $msg->subject('LON-CAPA DNS update on '.$perlvar{'lonHostID'});
898: $msg->add('Content-type','text/plain; charset=UTF-8');
899: if (my $fh = $msg->open()) {
900: print $fh 'Update to '.$tablefile.' from Cluster Manager '.
901: "$clientname ($clientip)\n";
902: $fh->close;
903: }
904: }
905: }
906:
907: # Indicate success:
908:
909: return "ok";
910:
911: }
912:
913: #
914: # Called to re-init either lonc or lond.
915: #
916: # Parameters:
917: # request - The full request by the client. This is of the form
918: # reinit:<process>
919: # where <process> is allowed to be either of
920: # lonc or lond
921: #
922: # Returns:
923: # The string to be sent back to the client either:
924: # ok - Everything worked just fine.
925: # error:why - There was a failure and why describes the reason.
926: #
927: #
928: sub ReinitProcess {
929: my $request = shift;
930:
931:
932: # separate the request (reinit) from the process identifier and
933: # validate it producing the name of the .pid file for the process.
934: #
935: #
936: my ($junk, $process) = split(":", $request);
937: my $processpidfile = $perlvar{'lonDaemons'}.'/logs/';
938: if($process eq 'lonc') {
939: $processpidfile = $processpidfile."lonc.pid";
940: if (!open(PIDFILE, "< $processpidfile")) {
941: return "error:Open failed for $processpidfile";
942: }
943: my $loncpid = <PIDFILE>;
944: close(PIDFILE);
945: logthis('<font color="red"> Reinitializing lonc pid='.$loncpid
946: ."</font>");
947: kill("USR2", $loncpid);
948: } elsif ($process eq 'lond') {
949: logthis('<font color="red"> Reinitializing self (lond) </font>');
950: &UpdateHosts; # Lond is us!!
951: } else {
952: &logthis('<font color="yellow" Invalid reinit request for '.$process
953: ."</font>");
954: return "error:Invalid process identifier $process";
955: }
956: return 'ok';
957: }
958: # Validate a line in a configuration file edit script:
959: # Validation includes:
960: # - Ensuring the command is valid.
961: # - Ensuring the command has sufficient parameters
962: # Parameters:
963: # scriptline - A line to validate (\n has been stripped for what it's worth).
964: #
965: # Return:
966: # 0 - Invalid scriptline.
967: # 1 - Valid scriptline
968: # NOTE:
969: # Only the command syntax is checked, not the executability of the
970: # command.
971: #
972: sub isValidEditCommand {
973: my $scriptline = shift;
974:
975: # Line elements are pipe separated:
976:
977: my ($command, $key, $newline) = split(/\|/, $scriptline);
978: &logthis('<font color="green"> isValideditCommand checking: '.
979: "Command = '$command', Key = '$key', Newline = '$newline' </font>\n");
980:
981: if ($command eq "delete") {
982: #
983: # key with no newline.
984: #
985: if( ($key eq "") || ($newline ne "")) {
986: return 0; # Must have key but no newline.
987: } else {
988: return 1; # Valid syntax.
989: }
990: } elsif ($command eq "replace") {
991: #
992: # key and newline:
993: #
994: if (($key eq "") || ($newline eq "")) {
995: return 0;
996: } else {
997: return 1;
998: }
999: } elsif ($command eq "append") {
1000: if (($key ne "") && ($newline eq "")) {
1001: return 1;
1002: } else {
1003: return 0;
1004: }
1005: } else {
1006: return 0; # Invalid command.
1007: }
1008: return 0; # Should not get here!!!
1009: }
1010: #
1011: # ApplyEdit - Applies an edit command to a line in a configuration
1012: # file. It is the caller's responsiblity to validate the
1013: # edit line.
1014: # Parameters:
1015: # $directive - A single edit directive to apply.
1016: # Edit directives are of the form:
1017: # append|newline - Appends a new line to the file.
1018: # replace|key|newline - Replaces the line with key value 'key'
1019: # delete|key - Deletes the line with key value 'key'.
1020: # $editor - A config file editor object that contains the
1021: # file being edited.
1022: #
1023: sub ApplyEdit {
1024:
1025: my ($directive, $editor) = @_;
1026:
1027: # Break the directive down into its command and its parameters
1028: # (at most two at this point. The meaning of the parameters, if in fact
1029: # they exist depends on the command).
1030:
1031: my ($command, $p1, $p2) = split(/\|/, $directive);
1032:
1033: if($command eq "append") {
1034: $editor->Append($p1); # p1 - key p2 null.
1035: } elsif ($command eq "replace") {
1036: $editor->ReplaceLine($p1, $p2); # p1 - key p2 = newline.
1037: } elsif ($command eq "delete") {
1038: $editor->DeleteLine($p1); # p1 - key p2 null.
1039: } else { # Should not get here!!!
1040: die "Invalid command given to ApplyEdit $command"
1041: }
1042: }
1043: #
1044: # AdjustOurHost:
1045: # Adjusts a host file stored in a configuration file editor object
1046: # for the true IP address of this host. This is necessary for hosts
1047: # that live behind a firewall.
1048: # Those hosts have a publicly distributed IP of the firewall, but
1049: # internally must use their actual IP. We assume that a given
1050: # host only has a single IP interface for now.
1051: # Formal Parameters:
1052: # editor - The configuration file editor to adjust. This
1053: # editor is assumed to contain a hosts.tab file.
1054: # Strategy:
1055: # - Figure out our hostname.
1056: # - Lookup the entry for this host.
1057: # - Modify the line to contain our IP
1058: # - Do a replace for this host.
1059: sub AdjustOurHost {
1060: my $editor = shift;
1061:
1062: # figure out who I am.
1063:
1064: my $myHostName = $perlvar{'lonHostID'}; # LonCAPA hostname.
1065:
1066: # Get my host file entry.
1067:
1068: my $ConfigLine = $editor->Find($myHostName);
1069: if(! (defined $ConfigLine)) {
1070: die "AdjustOurHost - no entry for me in hosts file $myHostName";
1071: }
1072: # figure out my IP:
1073: # Use the config line to get my hostname.
1074: # Use gethostbyname to translate that into an IP address.
1075: #
1076: my ($id,$domain,$role,$name,$maxcon,$idleto,$mincon) = split(/:/,$ConfigLine);
1077: #
1078: # Reassemble the config line from the elements in the list.
1079: # Note that if the loncnew items were not present before, they will
1080: # be now even if they would be empty
1081: #
1082: my $newConfigLine = $id;
1083: foreach my $item ($domain, $role, $name, $maxcon, $idleto, $mincon) {
1084: $newConfigLine .= ":".$item;
1085: }
1086: # Replace the line:
1087:
1088: $editor->ReplaceLine($id, $newConfigLine);
1089:
1090: }
1091: #
1092: # ReplaceConfigFile:
1093: # Replaces a configuration file with the contents of a
1094: # configuration file editor object.
1095: # This is done by:
1096: # - Copying the target file to <filename>.old
1097: # - Writing the new file to <filename>.tmp
1098: # - Moving <filename.tmp> -> <filename>
1099: # This laborious process ensures that the system is never without
1100: # a configuration file that's at least valid (even if the contents
1101: # may be dated).
1102: # Parameters:
1103: # filename - Name of the file to modify... this is a full path.
1104: # editor - Editor containing the file.
1105: #
1106: sub ReplaceConfigFile {
1107:
1108: my ($filename, $editor) = @_;
1109:
1110: CopyFile ($filename, $filename.".old");
1111:
1112: my $contents = $editor->Get(); # Get the contents of the file.
1113:
1114: InstallFile($filename, $contents);
1115: }
1116: #
1117: #
1118: # Called to edit a configuration table file
1119: # Parameters:
1120: # request - The entire command/request sent by lonc or lonManage
1121: # Return:
1122: # The reply to send to the client.
1123: #
1124: sub EditFile {
1125: my $request = shift;
1126:
1127: # Split the command into it's pieces: edit:filetype:script
1128:
1129: my ($cmd, $filetype, $script) = split(/:/, $request,3); # : in script
1130:
1131: # Check the pre-coditions for success:
1132:
1133: if($cmd != "edit") { # Something is amiss afoot alack.
1134: return "error:edit request detected, but request != 'edit'\n";
1135: }
1136: if( ($filetype ne "hosts") &&
1137: ($filetype ne "domain")) {
1138: return "error:edit requested with invalid file specifier: $filetype \n";
1139: }
1140:
1141: # Split the edit script and check it's validity.
1142:
1143: my @scriptlines = split(/\n/, $script); # one line per element.
1144: my $linecount = scalar(@scriptlines);
1145: for(my $i = 0; $i < $linecount; $i++) {
1146: chomp($scriptlines[$i]);
1147: if(!isValidEditCommand($scriptlines[$i])) {
1148: return "error:edit with bad script line: '$scriptlines[$i]' \n";
1149: }
1150: }
1151:
1152: # Execute the edit operation.
1153: # - Create a config file editor for the appropriate file and
1154: # - execute each command in the script:
1155: #
1156: my $configfile = ConfigFileFromSelector($filetype);
1157: if (!(defined $configfile)) {
1158: return "refused\n";
1159: }
1160: my $editor = ConfigFileEdit->new($configfile);
1161:
1162: for (my $i = 0; $i < $linecount; $i++) {
1163: ApplyEdit($scriptlines[$i], $editor);
1164: }
1165: # If the file is the host file, ensure that our host is
1166: # adjusted to have our ip:
1167: #
1168: if($filetype eq "host") {
1169: AdjustOurHost($editor);
1170: }
1171: # Finally replace the current file with our file.
1172: #
1173: ReplaceConfigFile($configfile, $editor);
1174:
1175: return "ok\n";
1176: }
1177:
1178: # read_profile
1179: #
1180: # Returns a set of specific entries from a user's profile file.
1181: # this is a utility function that is used by both get_profile_entry and
1182: # get_profile_entry_encrypted.
1183: #
1184: # Parameters:
1185: # udom - Domain in which the user exists.
1186: # uname - User's account name (loncapa account)
1187: # namespace - The profile namespace to open.
1188: # what - A set of & separated queries.
1189: # Returns:
1190: # If all ok: - The string that needs to be shipped back to the user.
1191: # If failure - A string that starts with error: followed by the failure
1192: # reason.. note that this probabyl gets shipped back to the
1193: # user as well.
1194: #
1195: sub read_profile {
1196: my ($udom, $uname, $namespace, $what) = @_;
1197:
1198: my $hashref = &tie_user_hash($udom, $uname, $namespace,
1199: &GDBM_READER());
1200: if ($hashref) {
1201: my @queries=split(/\&/,$what);
1202: if ($namespace eq 'roles') {
1203: @queries = map { &unescape($_); } @queries;
1204: }
1205: my $qresult='';
1206:
1207: for (my $i=0;$i<=$#queries;$i++) {
1208: $qresult.="$hashref->{$queries[$i]}&"; # Presumably failure gives empty string.
1209: }
1210: $qresult=~s/\&$//; # Remove trailing & from last lookup.
1211: if (&untie_user_hash($hashref)) {
1212: return $qresult;
1213: } else {
1214: return "error: ".($!+0)." untie (GDBM) Failed";
1215: }
1216: } else {
1217: if ($!+0 == 2) {
1218: return "error:No such file or GDBM reported bad block error";
1219: } else {
1220: return "error: ".($!+0)." tie (GDBM) Failed";
1221: }
1222: }
1223:
1224: }
1225: #--------------------- Request Handlers --------------------------------------------
1226: #
1227: # By convention each request handler registers itself prior to the sub
1228: # declaration:
1229: #
1230:
1231: #++
1232: #
1233: # Handles ping requests.
1234: # Parameters:
1235: # $cmd - the actual keyword that invoked us.
1236: # $tail - the tail of the request that invoked us.
1237: # $replyfd- File descriptor connected to the client
1238: # Implicit Inputs:
1239: # $currenthostid - Global variable that carries the name of the host we are
1240: # known as.
1241: # Returns:
1242: # 1 - Ok to continue processing.
1243: # 0 - Program should exit.
1244: # Side effects:
1245: # Reply information is sent to the client.
1246: sub ping_handler {
1247: my ($cmd, $tail, $client) = @_;
1248: Debug("$cmd $tail $client .. $currenthostid:");
1249:
1250: Reply( $client,\$currenthostid,"$cmd:$tail");
1251:
1252: return 1;
1253: }
1254: ®ister_handler("ping", \&ping_handler, 0, 1, 1); # Ping unencoded, client or manager.
1255:
1256: #++
1257: #
1258: # Handles pong requests. Pong replies with our current host id, and
1259: # the results of a ping sent to us via our lonc.
1260: #
1261: # Parameters:
1262: # $cmd - the actual keyword that invoked us.
1263: # $tail - the tail of the request that invoked us.
1264: # $replyfd- File descriptor connected to the client
1265: # Implicit Inputs:
1266: # $currenthostid - Global variable that carries the name of the host we are
1267: # connected to.
1268: # Returns:
1269: # 1 - Ok to continue processing.
1270: # 0 - Program should exit.
1271: # Side effects:
1272: # Reply information is sent to the client.
1273: sub pong_handler {
1274: my ($cmd, $tail, $replyfd) = @_;
1275:
1276: my $reply=&Apache::lonnet::reply("ping",$clientname);
1277: &Reply( $replyfd, "$currenthostid:$reply\n", "$cmd:$tail");
1278: return 1;
1279: }
1280: ®ister_handler("pong", \&pong_handler, 0, 1, 1); # Pong unencoded, client or manager
1281:
1282: #++
1283: # Called to establish an encrypted session key with the remote client.
1284: # Note that with secure lond, in most cases this function is never
1285: # invoked. Instead, the secure session key is established either
1286: # via a local file that's locked down tight and only lives for a short
1287: # time, or via an ssl tunnel...and is generated from a bunch-o-random
1288: # bits from /dev/urandom, rather than the predictable pattern used by
1289: # by this sub. This sub is only used in the old-style insecure
1290: # key negotiation.
1291: # Parameters:
1292: # $cmd - the actual keyword that invoked us.
1293: # $tail - the tail of the request that invoked us.
1294: # $replyfd- File descriptor connected to the client
1295: # Implicit Inputs:
1296: # $currenthostid - Global variable that carries the name of the host
1297: # known as.
1298: # $clientname - Global variable that carries the name of the host we're connected to.
1299: # Returns:
1300: # 1 - Ok to continue processing.
1301: # 0 - Program should exit.
1302: # Implicit Outputs:
1303: # Reply information is sent to the client.
1304: # $cipher is set with a reference to a new IDEA encryption object.
1305: #
1306: sub establish_key_handler {
1307: my ($cmd, $tail, $replyfd) = @_;
1308:
1309: my $buildkey=time.$$.int(rand 100000);
1310: $buildkey=~tr/1-6/A-F/;
1311: $buildkey=int(rand 100000).$buildkey.int(rand 100000);
1312: my $key=$currenthostid.$clientname;
1313: $key=~tr/a-z/A-Z/;
1314: $key=~tr/G-P/0-9/;
1315: $key=~tr/Q-Z/0-9/;
1316: $key=$key.$buildkey.$key.$buildkey.$key.$buildkey;
1317: $key=substr($key,0,32);
1318: my $cipherkey=pack("H32",$key);
1319: $cipher=new IDEA $cipherkey;
1320: &Reply($replyfd, \$buildkey, "$cmd:$tail");
1321:
1322: return 1;
1323:
1324: }
1325: ®ister_handler("ekey", \&establish_key_handler, 0, 1,1);
1326:
1327: # Handler for the load command. Returns the current system load average
1328: # to the requestor.
1329: #
1330: # Parameters:
1331: # $cmd - the actual keyword that invoked us.
1332: # $tail - the tail of the request that invoked us.
1333: # $replyfd- File descriptor connected to the client
1334: # Implicit Inputs:
1335: # $currenthostid - Global variable that carries the name of the host
1336: # known as.
1337: # $clientname - Global variable that carries the name of the host we're connected to.
1338: # Returns:
1339: # 1 - Ok to continue processing.
1340: # 0 - Program should exit.
1341: # Side effects:
1342: # Reply information is sent to the client.
1343: sub load_handler {
1344: my ($cmd, $tail, $replyfd) = @_;
1345:
1346:
1347:
1348: # Get the load average from /proc/loadavg and calculate it as a percentage of
1349: # the allowed load limit as set by the perl global variable lonLoadLim
1350:
1351: my $loadavg;
1352: my $loadfile=IO::File->new('/proc/loadavg');
1353:
1354: $loadavg=<$loadfile>;
1355: $loadavg =~ s/\s.*//g; # Extract the first field only.
1356:
1357: my $loadpercent=100*$loadavg/$perlvar{'lonLoadLim'};
1358:
1359: &Reply( $replyfd, \$loadpercent, "$cmd:$tail");
1360:
1361: return 1;
1362: }
1363: ®ister_handler("load", \&load_handler, 0, 1, 0);
1364:
1365: #
1366: # Process the userload request. This sub returns to the client the current
1367: # user load average. It can be invoked either by clients or managers.
1368: #
1369: # Parameters:
1370: # $cmd - the actual keyword that invoked us.
1371: # $tail - the tail of the request that invoked us.
1372: # $replyfd- File descriptor connected to the client
1373: # Implicit Inputs:
1374: # $currenthostid - Global variable that carries the name of the host
1375: # known as.
1376: # $clientname - Global variable that carries the name of the host we're connected to.
1377: # Returns:
1378: # 1 - Ok to continue processing.
1379: # 0 - Program should exit
1380: # Implicit inputs:
1381: # whatever the userload() function requires.
1382: # Implicit outputs:
1383: # the reply is written to the client.
1384: #
1385: sub user_load_handler {
1386: my ($cmd, $tail, $replyfd) = @_;
1387:
1388: my $userloadpercent=&Apache::lonnet::userload();
1389: &Reply($replyfd, \$userloadpercent, "$cmd:$tail");
1390:
1391: return 1;
1392: }
1393: ®ister_handler("userload", \&user_load_handler, 0, 1, 0);
1394:
1395: # Process a request for the authorization type of a user:
1396: # (userauth).
1397: #
1398: # Parameters:
1399: # $cmd - the actual keyword that invoked us.
1400: # $tail - the tail of the request that invoked us.
1401: # $replyfd- File descriptor connected to the client
1402: # Returns:
1403: # 1 - Ok to continue processing.
1404: # 0 - Program should exit
1405: # Implicit outputs:
1406: # The user authorization type is written to the client.
1407: #
1408: sub user_authorization_type {
1409: my ($cmd, $tail, $replyfd) = @_;
1410:
1411: my $userinput = "$cmd:$tail";
1412:
1413: # Pull the domain and username out of the command tail.
1414: # and call get_auth_type to determine the authentication type.
1415:
1416: my ($udom,$uname)=split(/:/,$tail);
1417: my $result = &get_auth_type($udom, $uname);
1418: if($result eq "nouser") {
1419: &Failure( $replyfd, "unknown_user\n", $userinput);
1420: } else {
1421: #
1422: # We only want to pass the second field from get_auth_type
1423: # for ^krb.. otherwise we'll be handing out the encrypted
1424: # password for internals e.g.
1425: #
1426: my ($type,$otherinfo) = split(/:/,$result);
1427: if($type =~ /^krb/) {
1428: $type = $result;
1429: } else {
1430: $type .= ':';
1431: }
1432: &Reply( $replyfd, \$type, $userinput);
1433: }
1434:
1435: return 1;
1436: }
1437: ®ister_handler("currentauth", \&user_authorization_type, 1, 1, 0);
1438:
1439: # Process a request by a manager to push a hosts or domain table
1440: # to us. We pick apart the command and pass it on to the subs
1441: # that already exist to do this.
1442: #
1443: # Parameters:
1444: # $cmd - the actual keyword that invoked us.
1445: # $tail - the tail of the request that invoked us.
1446: # $client - File descriptor connected to the client
1447: # Returns:
1448: # 1 - Ok to continue processing.
1449: # 0 - Program should exit
1450: # Implicit Output:
1451: # a reply is written to the client.
1452: sub push_file_handler {
1453: my ($cmd, $tail, $client) = @_;
1454: &Debug("In push file handler");
1455: my $userinput = "$cmd:$tail";
1456:
1457: # At this time we only know that the IP of our partner is a valid manager
1458: # the code below is a hook to do further authentication (e.g. to resolve
1459: # spoofing).
1460:
1461: my $cert = &GetCertificate($userinput);
1462: if(&ValidManager($cert)) {
1463: &Debug("Valid manager: $client");
1464:
1465: # Now presumably we have the bona fides of both the peer host and the
1466: # process making the request.
1467:
1468: my $reply = &PushFile($userinput);
1469: &Reply($client, \$reply, $userinput);
1470:
1471: } else {
1472: &logthis("push_file_handler $client is not valid");
1473: &Failure( $client, "refused\n", $userinput);
1474: }
1475: return 1;
1476: }
1477: ®ister_handler("pushfile", \&push_file_handler, 1, 0, 1);
1478:
1479: # The du_handler routine should be considered obsolete and is retained
1480: # for communication with legacy servers. Please see the du2_handler.
1481: #
1482: # du - list the disk usage of a directory recursively.
1483: #
1484: # note: stolen code from the ls file handler
1485: # under construction by Rick Banghart
1486: # .
1487: # Parameters:
1488: # $cmd - The command that dispatched us (du).
1489: # $ududir - The directory path to list... I'm not sure what this
1490: # is relative as things like ls:. return e.g.
1491: # no_such_dir.
1492: # $client - Socket open on the client.
1493: # Returns:
1494: # 1 - indicating that the daemon should not disconnect.
1495: # Side Effects:
1496: # The reply is written to $client.
1497: #
1498: sub du_handler {
1499: my ($cmd, $ududir, $client) = @_;
1500: ($ududir) = split(/:/,$ududir); # Make 'telnet' testing easier.
1501: my $userinput = "$cmd:$ududir";
1502:
1503: if ($ududir=~/\.\./ || $ududir!~m|^/home/httpd/|) {
1504: &Failure($client,"refused\n","$cmd:$ududir");
1505: return 1;
1506: }
1507: # Since $ududir could have some nasties in it,
1508: # we will require that ududir is a valid
1509: # directory. Just in case someone tries to
1510: # slip us a line like .;(cd /home/httpd rm -rf*)
1511: # etc.
1512: #
1513: if (-d $ududir) {
1514: my $total_size=0;
1515: my $code=sub {
1516: if ($_=~/\.\d+\./) { return;}
1517: if ($_=~/\.meta$/) { return;}
1518: if (-d $_) { return;}
1519: $total_size+=(stat($_))[7];
1520: };
1521: chdir($ududir);
1522: find($code,$ududir);
1523: $total_size=int($total_size/1024);
1524: &Reply($client,\$total_size,"$cmd:$ududir");
1525: } else {
1526: &Failure($client, "bad_directory:$ududir\n","$cmd:$ududir");
1527: }
1528: return 1;
1529: }
1530: ®ister_handler("du", \&du_handler, 0, 1, 0);
1531:
1532: # Please also see the du_handler, which is obsoleted by du2.
1533: # du2_handler differs from du_handler in that required path to directory
1534: # provided by &propath() is prepended in the handler instead of on the
1535: # client side.
1536: #
1537: # du2 - list the disk usage of a directory recursively.
1538: #
1539: # Parameters:
1540: # $cmd - The command that dispatched us (du).
1541: # $tail - The tail of the request that invoked us.
1542: # $tail is a : separated list of the following:
1543: # - $ududir - directory path to list (before prepending)
1544: # - $getpropath = 1 if &propath() should prepend
1545: # - $uname - username to use for &propath or user dir
1546: # - $udom - domain to use for &propath or user dir
1547: # All are escaped.
1548: # $client - Socket open on the client.
1549: # Returns:
1550: # 1 - indicating that the daemon should not disconnect.
1551: # Side Effects:
1552: # The reply is written to $client.
1553: #
1554:
1555: sub du2_handler {
1556: my ($cmd, $tail, $client) = @_;
1557: my ($ududir,$getpropath,$uname,$udom) = map { &unescape($_) } (split(/:/, $tail));
1558: my $userinput = "$cmd:$tail";
1559: if (($ududir=~/\.\./) || (($ududir!~m|^/home/httpd/|) && (!$getpropath))) {
1560: &Failure($client,"refused\n","$cmd:$tail");
1561: return 1;
1562: }
1563: if ($getpropath) {
1564: if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
1565: $ududir = &propath($udom,$uname).'/'.$ududir;
1566: } else {
1567: &Failure($client,"refused\n","$cmd:$tail");
1568: return 1;
1569: }
1570: }
1571: # Since $ududir could have some nasties in it,
1572: # we will require that ududir is a valid
1573: # directory. Just in case someone tries to
1574: # slip us a line like .;(cd /home/httpd rm -rf*)
1575: # etc.
1576: #
1577: if (-d $ududir) {
1578: my $total_size=0;
1579: my $code=sub {
1580: if ($_=~/\.\d+\./) { return;}
1581: if ($_=~/\.meta$/) { return;}
1582: if (-d $_) { return;}
1583: $total_size+=(stat($_))[7];
1584: };
1585: chdir($ududir);
1586: find($code,$ududir);
1587: $total_size=int($total_size/1024);
1588: &Reply($client,\$total_size,"$cmd:$ududir");
1589: } else {
1590: &Failure($client, "bad_directory:$ududir\n","$cmd:$tail");
1591: }
1592: return 1;
1593: }
1594: ®ister_handler("du2", \&du2_handler, 0, 1, 0);
1595:
1596: #
1597: # The ls_handler routine should be considered obsolete and is retained
1598: # for communication with legacy servers. Please see the ls3_handler.
1599: #
1600: # ls - list the contents of a directory. For each file in the
1601: # selected directory the filename followed by the full output of
1602: # the stat function is returned. The returned info for each
1603: # file are separated by ':'. The stat fields are separated by &'s.
1604: #
1605: # If the requested path contains /../ or is:
1606: #
1607: # 1. for a directory, and the path does not begin with one of:
1608: # (a) /home/httpd/html/res/<domain>
1609: # (b) /home/httpd/html/userfiles/
1610: # (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1611: # or is:
1612: #
1613: # 2. for a file, and the path (after prepending) does not begin with one of:
1614: # (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
1615: # (b) /home/httpd/html/res/<domain>/<username>/
1616: # (c) /home/httpd/html/userfiles/<domain>/<username>/
1617: #
1618: # the response will be "refused".
1619: #
1620: # Parameters:
1621: # $cmd - The command that dispatched us (ls).
1622: # $ulsdir - The directory path to list... I'm not sure what this
1623: # is relative as things like ls:. return e.g.
1624: # no_such_dir.
1625: # $client - Socket open on the client.
1626: # Returns:
1627: # 1 - indicating that the daemon should not disconnect.
1628: # Side Effects:
1629: # The reply is written to $client.
1630: #
1631: sub ls_handler {
1632: # obsoleted by ls2_handler
1633: my ($cmd, $ulsdir, $client) = @_;
1634:
1635: my $userinput = "$cmd:$ulsdir";
1636:
1637: my $obs;
1638: my $rights;
1639: my $ulsout='';
1640: my $ulsfn;
1641: if ($ulsdir =~m{/\.\./}) {
1642: &Failure($client,"refused\n",$userinput);
1643: return 1;
1644: }
1645: if (-e $ulsdir) {
1646: if(-d $ulsdir) {
1647: unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
1648: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1649: &Failure($client,"refused\n",$userinput);
1650: return 1;
1651: }
1652: if (opendir(LSDIR,$ulsdir)) {
1653: while ($ulsfn=readdir(LSDIR)) {
1654: undef($obs);
1655: undef($rights);
1656: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1657: #We do some obsolete checking here
1658: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1659: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1660: my @obsolete=<FILE>;
1661: foreach my $obsolete (@obsolete) {
1662: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1663: if($obsolete =~ m|(<copyright>)(default)|) { $rights = 1; }
1664: }
1665: }
1666: $ulsout.=$ulsfn.'&'.join('&',@ulsstats);
1667: if($obs eq '1') { $ulsout.="&1"; }
1668: else { $ulsout.="&0"; }
1669: if($rights eq '1') { $ulsout.="&1:"; }
1670: else { $ulsout.="&0:"; }
1671: }
1672: closedir(LSDIR);
1673: }
1674: } else {
1675: unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
1676: ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1677: &Failure($client,"refused\n",$userinput);
1678: return 1;
1679: }
1680: my @ulsstats=stat($ulsdir);
1681: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1682: }
1683: } else {
1684: $ulsout='no_such_dir';
1685: }
1686: if ($ulsout eq '') { $ulsout='empty'; }
1687: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1688:
1689: return 1;
1690:
1691: }
1692: ®ister_handler("ls", \&ls_handler, 0, 1, 0);
1693:
1694: # The ls2_handler routine should be considered obsolete and is retained
1695: # for communication with legacy servers. Please see the ls3_handler.
1696: # Please also see the ls_handler, which was itself obsoleted by ls2.
1697: # ls2_handler differs from ls_handler in that it escapes its return
1698: # values before concatenating them together with ':'s.
1699: #
1700: # ls2 - list the contents of a directory. For each file in the
1701: # selected directory the filename followed by the full output of
1702: # the stat function is returned. The returned info for each
1703: # file are separated by ':'. The stat fields are separated by &'s.
1704: #
1705: # If the requested path contains /../ or is:
1706: #
1707: # 1. for a directory, and the path does not begin with one of:
1708: # (a) /home/httpd/html/res/<domain>
1709: # (b) /home/httpd/html/userfiles/
1710: # (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1711: # or is:
1712: #
1713: # 2. for a file, and the path (after prepending) does not begin with one of:
1714: # (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
1715: # (b) /home/httpd/html/res/<domain>/<username>/
1716: # (c) /home/httpd/html/userfiles/<domain>/<username>/
1717: #
1718: # the response will be "refused".
1719: #
1720: # Parameters:
1721: # $cmd - The command that dispatched us (ls).
1722: # $ulsdir - The directory path to list... I'm not sure what this
1723: # is relative as things like ls:. return e.g.
1724: # no_such_dir.
1725: # $client - Socket open on the client.
1726: # Returns:
1727: # 1 - indicating that the daemon should not disconnect.
1728: # Side Effects:
1729: # The reply is written to $client.
1730: #
1731: sub ls2_handler {
1732: my ($cmd, $ulsdir, $client) = @_;
1733:
1734: my $userinput = "$cmd:$ulsdir";
1735:
1736: my $obs;
1737: my $rights;
1738: my $ulsout='';
1739: my $ulsfn;
1740: if ($ulsdir =~m{/\.\./}) {
1741: &Failure($client,"refused\n",$userinput);
1742: return 1;
1743: }
1744: if (-e $ulsdir) {
1745: if(-d $ulsdir) {
1746: unless (($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
1747: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles})) {
1748: &Failure($client,"refused\n","$userinput");
1749: return 1;
1750: }
1751: if (opendir(LSDIR,$ulsdir)) {
1752: while ($ulsfn=readdir(LSDIR)) {
1753: undef($obs);
1754: undef($rights);
1755: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1756: #We do some obsolete checking here
1757: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1758: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1759: my @obsolete=<FILE>;
1760: foreach my $obsolete (@obsolete) {
1761: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1762: if($obsolete =~ m|(<copyright>)(default)|) {
1763: $rights = 1;
1764: }
1765: }
1766: }
1767: my $tmp = $ulsfn.'&'.join('&',@ulsstats);
1768: if ($obs eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1769: if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1770: $ulsout.= &escape($tmp).':';
1771: }
1772: closedir(LSDIR);
1773: }
1774: } else {
1775: unless (($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
1776: ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/})) {
1777: &Failure($client,"refused\n",$userinput);
1778: return 1;
1779: }
1780: my @ulsstats=stat($ulsdir);
1781: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1782: }
1783: } else {
1784: $ulsout='no_such_dir';
1785: }
1786: if ($ulsout eq '') { $ulsout='empty'; }
1787: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1788: return 1;
1789: }
1790: ®ister_handler("ls2", \&ls2_handler, 0, 1, 0);
1791: #
1792: # ls3 - list the contents of a directory. For each file in the
1793: # selected directory the filename followed by the full output of
1794: # the stat function is returned. The returned info for each
1795: # file are separated by ':'. The stat fields are separated by &'s.
1796: #
1797: # If the requested path (after prepending) contains /../ or is:
1798: #
1799: # 1. for a directory, and the path does not begin with one of:
1800: # (a) /home/httpd/html/res/<domain>
1801: # (b) /home/httpd/html/userfiles/
1802: # (c) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/userfiles
1803: # (d) /home/httpd/html/priv/<domain> and client is the homeserver
1804: #
1805: # or is:
1806: #
1807: # 2. for a file, and the path (after prepending) does not begin with one of:
1808: # (a) /home/httpd/lonUsers/<domain>/<1>/<2>/<3>/<username>/
1809: # (b) /home/httpd/html/res/<domain>/<username>/
1810: # (c) /home/httpd/html/userfiles/<domain>/<username>/
1811: # (d) /home/httpd/html/priv/<domain>/<username>/ and client is the homeserver
1812: #
1813: # the response will be "refused".
1814: #
1815: # Parameters:
1816: # $cmd - The command that dispatched us (ls).
1817: # $tail - The tail of the request that invoked us.
1818: # $tail is a : separated list of the following:
1819: # - $ulsdir - directory path to list (before prepending)
1820: # - $getpropath = 1 if &propath() should prepend
1821: # - $getuserdir = 1 if path to user dir in lonUsers should
1822: # prepend
1823: # - $alternate_root - path to prepend
1824: # - $uname - username to use for &propath or user dir
1825: # - $udom - domain to use for &propath or user dir
1826: # All of these except $getpropath and &getuserdir are escaped.
1827: # no_such_dir.
1828: # $client - Socket open on the client.
1829: # Returns:
1830: # 1 - indicating that the daemon should not disconnect.
1831: # Side Effects:
1832: # The reply is written to $client.
1833: #
1834:
1835: sub ls3_handler {
1836: my ($cmd, $tail, $client) = @_;
1837: my $userinput = "$cmd:$tail";
1838: my ($ulsdir,$getpropath,$getuserdir,$alternate_root,$uname,$udom) =
1839: split(/:/,$tail);
1840: if (defined($ulsdir)) {
1841: $ulsdir = &unescape($ulsdir);
1842: }
1843: if (defined($alternate_root)) {
1844: $alternate_root = &unescape($alternate_root);
1845: }
1846: if (defined($uname)) {
1847: $uname = &unescape($uname);
1848: }
1849: if (defined($udom)) {
1850: $udom = &unescape($udom);
1851: }
1852:
1853: my $dir_root = $perlvar{'lonDocRoot'};
1854: if (($getpropath) || ($getuserdir)) {
1855: if (($uname =~ /^$LONCAPA::match_name$/) && ($udom =~ /^$LONCAPA::match_domain$/)) {
1856: $dir_root = &propath($udom,$uname);
1857: $dir_root =~ s/\/$//;
1858: } else {
1859: &Failure($client,"refused\n",$userinput);
1860: return 1;
1861: }
1862: } elsif ($alternate_root ne '') {
1863: $dir_root = $alternate_root;
1864: }
1865: if (($dir_root ne '') && ($dir_root ne '/')) {
1866: if ($ulsdir =~ /^\//) {
1867: $ulsdir = $dir_root.$ulsdir;
1868: } else {
1869: $ulsdir = $dir_root.'/'.$ulsdir;
1870: }
1871: }
1872: if ($ulsdir =~m{/\.\./}) {
1873: &Failure($client,"refused\n",$userinput);
1874: return 1;
1875: }
1876: my $islocal;
1877: my @machine_ids = &Apache::lonnet::current_machine_ids();
1878: if (grep(/^\Q$clientname\E$/,@machine_ids)) {
1879: $islocal = 1;
1880: }
1881: my $obs;
1882: my $rights;
1883: my $ulsout='';
1884: my $ulsfn;
1885: if (-e $ulsdir) {
1886: if(-d $ulsdir) {
1887: unless (($getpropath) || ($getuserdir) ||
1888: ($ulsdir =~ m{^/home/httpd/html/(res/$LONCAPA::match_domain|userfiles/)}) ||
1889: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/userfiles}) ||
1890: (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain}) && ($islocal))) {
1891: &Failure($client,"refused\n",$userinput);
1892: return 1;
1893: }
1894: if (opendir(LSDIR,$ulsdir)) {
1895: while ($ulsfn=readdir(LSDIR)) {
1896: undef($obs);
1897: undef($rights);
1898: my @ulsstats=stat($ulsdir.'/'.$ulsfn);
1899: #We do some obsolete checking here
1900: if(-e $ulsdir.'/'.$ulsfn.".meta") {
1901: open(FILE, $ulsdir.'/'.$ulsfn.".meta");
1902: my @obsolete=<FILE>;
1903: foreach my $obsolete (@obsolete) {
1904: if($obsolete =~ m/(<obsolete>)(on|1)/) { $obs = 1; }
1905: if($obsolete =~ m|(<copyright>)(default)|) {
1906: $rights = 1;
1907: }
1908: }
1909: }
1910: my $tmp = $ulsfn.'&'.join('&',@ulsstats);
1911: if ($obs eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1912: if ($rights eq '1') { $tmp.="&1"; } else { $tmp.="&0"; }
1913: $ulsout.= &escape($tmp).':';
1914: }
1915: closedir(LSDIR);
1916: }
1917: } else {
1918: unless (($getpropath) || ($getuserdir) ||
1919: ($ulsdir =~ m{^/home/httpd/lonUsers/$LONCAPA::match_domain(?:/[\w\-.@]){3}/$LONCAPA::match_name/}) ||
1920: ($ulsdir =~ m{^/home/httpd/html/(?:res|userfiles)/$LONCAPA::match_domain/$LONCAPA::match_name/}) ||
1921: (($ulsdir =~ m{^/home/httpd/html/priv/$LONCAPA::match_domain/$LONCAPA::match_name/}) && ($islocal))) {
1922: &Failure($client,"refused\n",$userinput);
1923: return 1;
1924: }
1925: my @ulsstats=stat($ulsdir);
1926: $ulsout.=$ulsfn.'&'.join('&',@ulsstats).':';
1927: }
1928: } else {
1929: $ulsout='no_such_dir';
1930: }
1931: if ($ulsout eq '') { $ulsout='empty'; }
1932: &Reply($client, \$ulsout, $userinput); # This supports debug logging.
1933: return 1;
1934: }
1935: ®ister_handler("ls3", \&ls3_handler, 0, 1, 0);
1936:
1937: sub read_lonnet_global {
1938: my ($cmd,$tail,$client) = @_;
1939: my $userinput = "$cmd:$tail";
1940: my $requested = &Apache::lonnet::thaw_unescape($tail);
1941: my $result;
1942: my %packagevars = (
1943: spareid => \%Apache::lonnet::spareid,
1944: perlvar => \%Apache::lonnet::perlvar,
1945: );
1946: my %limit_to = (
1947: perlvar => {
1948: lonOtherAuthen => 1,
1949: lonBalancer => 1,
1950: lonVersion => 1,
1951: lonAdmEMail => 1,
1952: lonSupportEMail => 1,
1953: lonSysEMail => 1,
1954: lonHostID => 1,
1955: lonRole => 1,
1956: lonDefDomain => 1,
1957: lonLoadLim => 1,
1958: lonUserLoadLim => 1,
1959: }
1960: );
1961: if (ref($requested) eq 'HASH') {
1962: foreach my $what (keys(%{$requested})) {
1963: my $response;
1964: my $items = {};
1965: if (exists($packagevars{$what})) {
1966: if (ref($limit_to{$what}) eq 'HASH') {
1967: foreach my $varname (keys(%{$packagevars{$what}})) {
1968: if ($limit_to{$what}{$varname}) {
1969: $items->{$varname} = $packagevars{$what}{$varname};
1970: }
1971: }
1972: } else {
1973: $items = $packagevars{$what};
1974: }
1975: if ($what eq 'perlvar') {
1976: if (!exists($packagevars{$what}{'lonBalancer'})) {
1977: if ($dist =~ /^(centos|rhes|fedora|scientific)/) {
1978: my $othervarref=LONCAPA::Configuration::read_conf('httpd.conf');
1979: if (ref($othervarref) eq 'HASH') {
1980: $items->{'lonBalancer'} = $othervarref->{'lonBalancer'};
1981: }
1982: }
1983: }
1984: }
1985: $response = &Apache::lonnet::freeze_escape($items);
1986: }
1987: $result .= &escape($what).'='.$response.'&';
1988: }
1989: }
1990: $result =~ s/\&$//;
1991: &Reply($client,\$result,$userinput);
1992: return 1;
1993: }
1994: ®ister_handler("readlonnetglobal", \&read_lonnet_global, 0, 1, 0);
1995:
1996: sub server_devalidatecache_handler {
1997: my ($cmd,$tail,$client) = @_;
1998: my $userinput = "$cmd:$tail";
1999: my $items = &unescape($tail);
2000: my @cached = split(/\&/,$items);
2001: foreach my $key (@cached) {
2002: if ($key =~ /:/) {
2003: my ($name,$id) = map { &unescape($_); } split(/:/,$key);
2004: &Apache::lonnet::devalidate_cache_new($name,$id);
2005: }
2006: }
2007: my $result = 'ok';
2008: &Reply($client,\$result,$userinput);
2009: return 1;
2010: }
2011: ®ister_handler("devalidatecache", \&server_devalidatecache_handler, 0, 1, 0);
2012:
2013: sub server_timezone_handler {
2014: my ($cmd,$tail,$client) = @_;
2015: my $userinput = "$cmd:$tail";
2016: my $timezone;
2017: my $clockfile = '/etc/sysconfig/clock'; # Fedora/CentOS/SuSE
2018: my $tzfile = '/etc/timezone'; # Debian/Ubuntu
2019: if (-e $clockfile) {
2020: if (open(my $fh,"<$clockfile")) {
2021: while (<$fh>) {
2022: next if (/^[\#\s]/);
2023: if (/^(?:TIME)?ZONE\s*=\s*['"]?\s*([\w\/]+)/) {
2024: $timezone = $1;
2025: last;
2026: }
2027: }
2028: close($fh);
2029: }
2030: } elsif (-e $tzfile) {
2031: if (open(my $fh,"<$tzfile")) {
2032: $timezone = <$fh>;
2033: close($fh);
2034: chomp($timezone);
2035: if ($timezone =~ m{^Etc/(\w+)$}) {
2036: $timezone = $1;
2037: }
2038: }
2039: }
2040: &Reply($client,\$timezone,$userinput); # This supports debug logging.
2041: return 1;
2042: }
2043: ®ister_handler("servertimezone", \&server_timezone_handler, 0, 1, 0);
2044:
2045: sub server_loncaparev_handler {
2046: my ($cmd,$tail,$client) = @_;
2047: my $userinput = "$cmd:$tail";
2048: &Reply($client,\$perlvar{'lonVersion'},$userinput);
2049: return 1;
2050: }
2051: ®ister_handler("serverloncaparev", \&server_loncaparev_handler, 0, 1, 0);
2052:
2053: sub server_homeID_handler {
2054: my ($cmd,$tail,$client) = @_;
2055: my $userinput = "$cmd:$tail";
2056: &Reply($client,\$perlvar{'lonHostID'},$userinput);
2057: return 1;
2058: }
2059: ®ister_handler("serverhomeID", \&server_homeID_handler, 0, 1, 0);
2060:
2061: sub server_distarch_handler {
2062: my ($cmd,$tail,$client) = @_;
2063: my $userinput = "$cmd:$tail";
2064: my $reply = &distro_and_arch();
2065: &Reply($client,\$reply,$userinput);
2066: return 1;
2067: }
2068: ®ister_handler("serverdistarch", \&server_distarch_handler, 0, 1, 0);
2069:
2070: sub server_certs_handler {
2071: my ($cmd,$tail,$client) = @_;
2072: my $userinput = "$cmd:$tail";
2073: my $result;
2074: my $result = &LONCAPA::Lond::server_certs(\%perlvar);
2075: &Reply($client,\$result,$userinput);
2076: return;
2077: }
2078: ®ister_handler("servercerts", \&server_certs_handler, 0, 1, 0);
2079:
2080: # Process a reinit request. Reinit requests that either
2081: # lonc or lond be reinitialized so that an updated
2082: # host.tab or domain.tab can be processed.
2083: #
2084: # Parameters:
2085: # $cmd - the actual keyword that invoked us.
2086: # $tail - the tail of the request that invoked us.
2087: # $client - File descriptor connected to the client
2088: # Returns:
2089: # 1 - Ok to continue processing.
2090: # 0 - Program should exit
2091: # Implicit output:
2092: # a reply is sent to the client.
2093: #
2094: sub reinit_process_handler {
2095: my ($cmd, $tail, $client) = @_;
2096:
2097: my $userinput = "$cmd:$tail";
2098:
2099: my $cert = &GetCertificate($userinput);
2100: if(&ValidManager($cert)) {
2101: chomp($userinput);
2102: my $reply = &ReinitProcess($userinput);
2103: &Reply( $client, \$reply, $userinput);
2104: } else {
2105: &Failure( $client, "refused\n", $userinput);
2106: }
2107: return 1;
2108: }
2109: ®ister_handler("reinit", \&reinit_process_handler, 1, 0, 1);
2110:
2111: # Process the editing script for a table edit operation.
2112: # the editing operation must be encrypted and requested by
2113: # a manager host.
2114: #
2115: # Parameters:
2116: # $cmd - the actual keyword that invoked us.
2117: # $tail - the tail of the request that invoked us.
2118: # $client - File descriptor connected to the client
2119: # Returns:
2120: # 1 - Ok to continue processing.
2121: # 0 - Program should exit
2122: # Implicit output:
2123: # a reply is sent to the client.
2124: #
2125: sub edit_table_handler {
2126: my ($command, $tail, $client) = @_;
2127:
2128: my $userinput = "$command:$tail";
2129:
2130: my $cert = &GetCertificate($userinput);
2131: if(&ValidManager($cert)) {
2132: my($filetype, $script) = split(/:/, $tail);
2133: if (($filetype eq "hosts") ||
2134: ($filetype eq "domain")) {
2135: if($script ne "") {
2136: &Reply($client, # BUGBUG - EditFile
2137: &EditFile($userinput), # could fail.
2138: $userinput);
2139: } else {
2140: &Failure($client,"refused\n",$userinput);
2141: }
2142: } else {
2143: &Failure($client,"refused\n",$userinput);
2144: }
2145: } else {
2146: &Failure($client,"refused\n",$userinput);
2147: }
2148: return 1;
2149: }
2150: ®ister_handler("edit", \&edit_table_handler, 1, 0, 1);
2151:
2152: #
2153: # Authenticate a user against the LonCAPA authentication
2154: # database. Note that there are several authentication
2155: # possibilities:
2156: # - unix - The user can be authenticated against the unix
2157: # password file.
2158: # - internal - The user can be authenticated against a purely
2159: # internal per user password file.
2160: # - kerberos - The user can be authenticated against either a kerb4 or kerb5
2161: # ticket granting authority.
2162: # - user - The person tailoring LonCAPA can supply a user authentication
2163: # mechanism that is per system.
2164: #
2165: # Parameters:
2166: # $cmd - The command that got us here.
2167: # $tail - Tail of the command (remaining parameters).
2168: # $client - File descriptor connected to client.
2169: # Returns
2170: # 0 - Requested to exit, caller should shut down.
2171: # 1 - Continue processing.
2172: # Implicit inputs:
2173: # The authentication systems describe above have their own forms of implicit
2174: # input into the authentication process that are described above.
2175: #
2176: sub authenticate_handler {
2177: my ($cmd, $tail, $client) = @_;
2178:
2179:
2180: # Regenerate the full input line
2181:
2182: my $userinput = $cmd.":".$tail;
2183:
2184: # udom - User's domain.
2185: # uname - Username.
2186: # upass - User's password.
2187: # checkdefauth - Pass to validate_user() to try authentication
2188: # with default auth type(s) if no user account.
2189: # clientcancheckhost - Passed by clients with functionality in lonauth.pm
2190: # to check if session can be hosted.
2191:
2192: my ($udom, $uname, $upass, $checkdefauth, $clientcancheckhost)=split(/:/,$tail);
2193: &Debug(" Authenticate domain = $udom, user = $uname, password = $upass, checkdefauth = $checkdefauth");
2194: chomp($upass);
2195: $upass=&unescape($upass);
2196:
2197: my $pwdcorrect = &validate_user($udom,$uname,$upass,$checkdefauth);
2198: if($pwdcorrect) {
2199: my $canhost = 1;
2200: unless ($clientcancheckhost) {
2201: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
2202: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
2203: my @intdoms;
2204: my $internet_names = &Apache::lonnet::get_internet_names($clientname);
2205: if (ref($internet_names) eq 'ARRAY') {
2206: @intdoms = @{$internet_names};
2207: }
2208: unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
2209: my ($remote,$hosted);
2210: my $remotesession = &get_usersession_config($udom,'remotesession');
2211: if (ref($remotesession) eq 'HASH') {
2212: $remote = $remotesession->{'remote'};
2213: }
2214: my $hostedsession = &get_usersession_config($clienthomedom,'hostedsession');
2215: if (ref($hostedsession) eq 'HASH') {
2216: $hosted = $hostedsession->{'hosted'};
2217: }
2218: $canhost = &Apache::lonnet::can_host_session($udom,$clientname,
2219: $clientversion,
2220: $remote,$hosted);
2221: }
2222: }
2223: if ($canhost) {
2224: &Reply( $client, "authorized\n", $userinput);
2225: } else {
2226: &Reply( $client, "not_allowed_to_host\n", $userinput);
2227: }
2228: #
2229: # Bad credentials: Failed to authorize
2230: #
2231: } else {
2232: &Failure( $client, "non_authorized\n", $userinput);
2233: }
2234:
2235: return 1;
2236: }
2237: ®ister_handler("auth", \&authenticate_handler, 1, 1, 0);
2238:
2239: #
2240: # Change a user's password. Note that this function is complicated by
2241: # the fact that a user may be authenticated in more than one way:
2242: # At present, we are not able to change the password for all types of
2243: # authentication methods. Only for:
2244: # unix - unix password or shadow passoword style authentication.
2245: # local - Locally written authentication mechanism.
2246: # For now, kerb4 and kerb5 password changes are not supported and result
2247: # in an error.
2248: # FUTURE WORK:
2249: # Support kerberos passwd changes?
2250: # Parameters:
2251: # $cmd - The command that got us here.
2252: # $tail - Tail of the command (remaining parameters).
2253: # $client - File descriptor connected to client.
2254: # Returns
2255: # 0 - Requested to exit, caller should shut down.
2256: # 1 - Continue processing.
2257: # Implicit inputs:
2258: # The authentication systems describe above have their own forms of implicit
2259: # input into the authentication process that are described above.
2260: sub change_password_handler {
2261: my ($cmd, $tail, $client) = @_;
2262:
2263: my $userinput = $cmd.":".$tail; # Reconstruct client's string.
2264:
2265: #
2266: # udom - user's domain.
2267: # uname - Username.
2268: # upass - Current password.
2269: # npass - New password.
2270: # context - Context in which this was called
2271: # (preferences or reset_by_email).
2272: # lonhost - HostID of server where request originated
2273:
2274: my ($udom,$uname,$upass,$npass,$context,$lonhost)=split(/:/,$tail);
2275:
2276: $upass=&unescape($upass);
2277: $npass=&unescape($npass);
2278: &Debug("Trying to change password for $uname");
2279:
2280: # First require that the user can be authenticated with their
2281: # old password unless context was 'reset_by_email':
2282:
2283: my ($validated,$failure);
2284: if ($context eq 'reset_by_email') {
2285: if ($lonhost eq '') {
2286: $failure = 'invalid_client';
2287: } else {
2288: $validated = 1;
2289: }
2290: } else {
2291: $validated = &validate_user($udom, $uname, $upass);
2292: }
2293: if($validated) {
2294: my $realpasswd = &get_auth_type($udom, $uname); # Defined since authd.
2295:
2296: my ($howpwd,$contentpwd)=split(/:/,$realpasswd);
2297: if ($howpwd eq 'internal') {
2298: &Debug("internal auth");
2299: my $ncpass = &hash_passwd($udom,$npass);
2300: if(&rewrite_password_file($udom, $uname, "internal:$ncpass")) {
2301: my $msg="Result of password change for $uname: pwchange_success";
2302: if ($lonhost) {
2303: $msg .= " - request originated from: $lonhost";
2304: }
2305: &logthis($msg);
2306: &update_passwd_history($uname,$udom,$howpwd,$context);
2307: &Reply($client, "ok\n", $userinput);
2308: } else {
2309: &logthis("Unable to open $uname passwd "
2310: ."to change password");
2311: &Failure( $client, "non_authorized\n",$userinput);
2312: }
2313: } elsif ($howpwd eq 'unix' && $context ne 'reset_by_email') {
2314: my $result = &change_unix_password($uname, $npass);
2315: if ($result eq 'ok') {
2316: &update_passwd_history($uname,$udom,$howpwd,$context);
2317: }
2318: &logthis("Result of password change for $uname: ".
2319: $result);
2320: &Reply($client, \$result, $userinput);
2321: } else {
2322: # this just means that the current password mode is not
2323: # one we know how to change (e.g the kerberos auth modes or
2324: # locally written auth handler).
2325: #
2326: &Failure( $client, "auth_mode_error\n", $userinput);
2327: }
2328:
2329: } else {
2330: if ($failure eq '') {
2331: $failure = 'non_authorized';
2332: }
2333: &Failure( $client, "$failure\n", $userinput);
2334: }
2335:
2336: return 1;
2337: }
2338: ®ister_handler("passwd", \&change_password_handler, 1, 1, 0);
2339:
2340: sub hash_passwd {
2341: my ($domain,$plainpass,@rest) = @_;
2342: my ($salt,$cost);
2343: if (@rest) {
2344: $cost = $rest[0];
2345: # salt is first 22 characters, base-64 encoded by bcrypt
2346: my $plainsalt = substr($rest[1],0,22);
2347: $salt = Crypt::Eksblowfish::Bcrypt::de_base64($plainsalt);
2348: } else {
2349: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
2350: my $defaultcost = $domdefaults{'intauth_cost'};
2351: if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
2352: $cost = 10;
2353: } else {
2354: $cost = $defaultcost;
2355: }
2356: # Generate random 16-octet base64 salt
2357: $salt = "";
2358: $salt .= pack("C", int rand(256)) for 1..16;
2359: }
2360: my $hash = &Crypt::Eksblowfish::Bcrypt::bcrypt_hash({
2361: key_nul => 1,
2362: cost => $cost,
2363: salt => $salt,
2364: }, Digest::SHA::sha512(Encode::encode('UTF-8',$plainpass)));
2365:
2366: my $result = join("!", "", "bcrypt", sprintf("%02d",$cost),
2367: &Crypt::Eksblowfish::Bcrypt::en_base64($salt).
2368: &Crypt::Eksblowfish::Bcrypt::en_base64($hash));
2369: return $result;
2370: }
2371:
2372: #
2373: # Create a new user. User in this case means a lon-capa user.
2374: # The user must either already exist in some authentication realm
2375: # like kerberos or the /etc/passwd. If not, a user completely local to
2376: # this loncapa system is created.
2377: #
2378: # Parameters:
2379: # $cmd - The command that got us here.
2380: # $tail - Tail of the command (remaining parameters).
2381: # $client - File descriptor connected to client.
2382: # Returns
2383: # 0 - Requested to exit, caller should shut down.
2384: # 1 - Continue processing.
2385: # Implicit inputs:
2386: # The authentication systems describe above have their own forms of implicit
2387: # input into the authentication process that are described above.
2388: sub add_user_handler {
2389:
2390: my ($cmd, $tail, $client) = @_;
2391:
2392:
2393: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
2394: my $userinput = $cmd.":".$tail; # Reconstruct the full request line.
2395:
2396: &Debug("cmd =".$cmd." $udom =".$udom." uname=".$uname);
2397:
2398:
2399: if($udom eq $currentdomainid) { # Reject new users for other domains...
2400:
2401: my $oldumask=umask(0077);
2402: chomp($npass);
2403: $npass=&unescape($npass);
2404: my $passfilename = &password_path($udom, $uname);
2405: &Debug("Password file created will be:".$passfilename);
2406: if (-e $passfilename) {
2407: &Failure( $client, "already_exists\n", $userinput);
2408: } else {
2409: my $fperror='';
2410: if (!&mkpath($passfilename)) {
2411: $fperror="error: ".($!+0)." mkdir failed while attempting "
2412: ."makeuser";
2413: }
2414: unless ($fperror) {
2415: my $result=&make_passwd_file($uname,$udom,$umode,$npass,
2416: $passfilename,'makeuser');
2417: &Reply($client,\$result, $userinput); #BUGBUG - could be fail
2418: } else {
2419: &Failure($client, \$fperror, $userinput);
2420: }
2421: }
2422: umask($oldumask);
2423: } else {
2424: &Failure($client, "not_right_domain\n",
2425: $userinput); # Even if we are multihomed.
2426:
2427: }
2428: return 1;
2429:
2430: }
2431: ®ister_handler("makeuser", \&add_user_handler, 1, 1, 0);
2432:
2433: #
2434: # Change the authentication method of a user. Note that this may
2435: # also implicitly change the user's password if, for example, the user is
2436: # joining an existing authentication realm. Known authentication realms at
2437: # this time are:
2438: # internal - Purely internal password file (only loncapa knows this user)
2439: # local - Institutionally written authentication module.
2440: # unix - Unix user (/etc/passwd with or without /etc/shadow).
2441: # kerb4 - kerberos version 4
2442: # kerb5 - kerberos version 5
2443: #
2444: # Parameters:
2445: # $cmd - The command that got us here.
2446: # $tail - Tail of the command (remaining parameters).
2447: # $client - File descriptor connected to client.
2448: # Returns
2449: # 0 - Requested to exit, caller should shut down.
2450: # 1 - Continue processing.
2451: # Implicit inputs:
2452: # The authentication systems describe above have their own forms of implicit
2453: # input into the authentication process that are described above.
2454: # NOTE:
2455: # This is also used to change the authentication credential values (e.g. passwd).
2456: #
2457: #
2458: sub change_authentication_handler {
2459:
2460: my ($cmd, $tail, $client) = @_;
2461:
2462: my $userinput = "$cmd:$tail"; # Reconstruct user input.
2463:
2464: my ($udom,$uname,$umode,$npass)=split(/:/,$tail);
2465: &Debug("cmd = ".$cmd." domain= ".$udom."uname =".$uname." umode= ".$umode);
2466: if ($udom ne $currentdomainid) {
2467: &Failure( $client, "not_right_domain\n", $client);
2468: } else {
2469:
2470: chomp($npass);
2471:
2472: $npass=&unescape($npass);
2473: my $oldauth = &get_auth_type($udom, $uname); # Get old auth info.
2474: my $passfilename = &password_path($udom, $uname);
2475: if ($passfilename) { # Not allowed to create a new user!!
2476: # If just changing the unix passwd. need to arrange to run
2477: # passwd since otherwise make_passwd_file will fail as
2478: # creation of unix authenticated users is no longer supported
2479: # except from the command line, when running make_domain_coordinator.pl
2480:
2481: if(($oldauth =~/^unix/) && ($umode eq "unix")) {
2482: my $result = &change_unix_password($uname, $npass);
2483: &logthis("Result of password change for $uname: ".$result);
2484: if ($result eq "ok") {
2485: &update_passwd_history($uname,$udom,$umode,'changeuserauth');
2486: &Reply($client, \$result);
2487: } else {
2488: &Failure($client, \$result);
2489: }
2490: } else {
2491: my $result=&make_passwd_file($uname,$udom,$umode,$npass,
2492: $passfilename,'changeuserauth');
2493: #
2494: # If the current auth mode is internal, and the old auth mode was
2495: # unix, or krb*, and the user is an author for this domain,
2496: # re-run manage_permissions for that role in order to be able
2497: # to take ownership of the construction space back to www:www
2498: #
2499:
2500:
2501: &Reply($client, \$result, $userinput);
2502: }
2503:
2504:
2505: } else {
2506: &Failure($client, "non_authorized\n", $userinput); # Fail the user now.
2507: }
2508: }
2509: return 1;
2510: }
2511: ®ister_handler("changeuserauth", \&change_authentication_handler, 1,1, 0);
2512:
2513: sub update_passwd_history {
2514: my ($uname,$udom,$umode,$context) = @_;
2515: my $proname=&propath($udom,$uname);
2516: my $now = time;
2517: if (open(my $fh,">>$proname/passwd.log")) {
2518: print $fh "$now:$umode:$context\n";
2519: close($fh);
2520: }
2521: return;
2522: }
2523:
2524: #
2525: # Determines if this is the home server for a user. The home server
2526: # for a user will have his/her lon-capa passwd file. Therefore all we need
2527: # to do is determine if this file exists.
2528: #
2529: # Parameters:
2530: # $cmd - The command that got us here.
2531: # $tail - Tail of the command (remaining parameters).
2532: # $client - File descriptor connected to client.
2533: # Returns
2534: # 0 - Requested to exit, caller should shut down.
2535: # 1 - Continue processing.
2536: # Implicit inputs:
2537: # The authentication systems describe above have their own forms of implicit
2538: # input into the authentication process that are described above.
2539: #
2540: sub is_home_handler {
2541: my ($cmd, $tail, $client) = @_;
2542:
2543: my $userinput = "$cmd:$tail";
2544:
2545: my ($udom,$uname)=split(/:/,$tail);
2546: chomp($uname);
2547: my $passfile = &password_filename($udom, $uname);
2548: if($passfile) {
2549: &Reply( $client, "found\n", $userinput);
2550: } else {
2551: &Failure($client, "not_found\n", $userinput);
2552: }
2553: return 1;
2554: }
2555: ®ister_handler("home", \&is_home_handler, 0,1,0);
2556:
2557: #
2558: # Process an update request for a resource.
2559: # A resource has been modified that we hold a subscription to.
2560: # If the resource is not local, then we must update, or at least invalidate our
2561: # cached copy of the resource.
2562: # Parameters:
2563: # $cmd - The command that got us here.
2564: # $tail - Tail of the command (remaining parameters).
2565: # $client - File descriptor connected to client.
2566: # Returns
2567: # 0 - Requested to exit, caller should shut down.
2568: # 1 - Continue processing.
2569: # Implicit inputs:
2570: # The authentication systems describe above have their own forms of implicit
2571: # input into the authentication process that are described above.
2572: #
2573: sub update_resource_handler {
2574:
2575: my ($cmd, $tail, $client) = @_;
2576:
2577: my $userinput = "$cmd:$tail";
2578:
2579: my $fname= $tail; # This allows interactive testing
2580:
2581:
2582: my $ownership=ishome($fname);
2583: if ($ownership eq 'not_owner') {
2584: if (-e $fname) {
2585: # Delete preview file, if exists
2586: unlink("$fname.tmp");
2587: # Get usage stats
2588: my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
2589: $atime,$mtime,$ctime,$blksize,$blocks)=stat($fname);
2590: my $now=time;
2591: my $since=$now-$atime;
2592: # If the file has not been used within lonExpire seconds,
2593: # unsubscribe from it and delete local copy
2594: if ($since>$perlvar{'lonExpire'}) {
2595: my $reply=&Apache::lonnet::reply("unsub:$fname","$clientname");
2596: &devalidate_meta_cache($fname);
2597: unlink("$fname");
2598: unlink("$fname.meta");
2599: } else {
2600: # Yes, this is in active use. Get a fresh copy. Since it might be in
2601: # very active use and huge (like a movie), copy it to "in.transfer" filename first.
2602: my $transname="$fname.in.transfer";
2603: my $remoteurl=&Apache::lonnet::reply("sub:$fname","$clientname");
2604: my $response;
2605: # FIXME: cannot replicate files that take more than two minutes to transfer -- needs checking now 1200s timeout used
2606: # for LWP request.
2607: my $request=new HTTP::Request('GET',"$remoteurl");
2608: $response=&LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,0,1);
2609: if ($response->is_error()) {
2610: # FIXME: we should probably clean up here instead of just whine
2611: unlink($transname);
2612: my $message=$response->status_line;
2613: &logthis("LWP GET: $message for $fname ($remoteurl)");
2614: } else {
2615: if ($remoteurl!~/\.meta$/) {
2616: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2617: my $mresponse = &LONCAPA::LWPReq::makerequest($clientname,$mrequest,$fname.'.meta',\%perlvar,120,0,1);
2618: if ($mresponse->is_error()) {
2619: unlink($fname.'.meta');
2620: }
2621: }
2622: # we successfully transfered, copy file over to real name
2623: rename($transname,$fname);
2624: &devalidate_meta_cache($fname);
2625: }
2626: }
2627: &Reply( $client, "ok\n", $userinput);
2628: } else {
2629: &Failure($client, "not_found\n", $userinput);
2630: }
2631: } else {
2632: &Failure($client, "rejected\n", $userinput);
2633: }
2634: return 1;
2635: }
2636: ®ister_handler("update", \&update_resource_handler, 0 ,1, 0);
2637:
2638: sub devalidate_meta_cache {
2639: my ($url) = @_;
2640: use Cache::Memcached;
2641: my $memcache = new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
2642: $url = &Apache::lonnet::declutter($url);
2643: $url =~ s-\.meta$--;
2644: my $id = &escape('meta:'.$url);
2645: $memcache->delete($id);
2646: }
2647:
2648: #
2649: # Fetch a user file from a remote server to the user's home directory
2650: # userfiles subdir.
2651: # Parameters:
2652: # $cmd - The command that got us here.
2653: # $tail - Tail of the command (remaining parameters).
2654: # $client - File descriptor connected to client.
2655: # Returns
2656: # 0 - Requested to exit, caller should shut down.
2657: # 1 - Continue processing.
2658: #
2659: sub fetch_user_file_handler {
2660:
2661: my ($cmd, $tail, $client) = @_;
2662:
2663: my $userinput = "$cmd:$tail";
2664: my $fname = $tail;
2665: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2666: my $udir=&propath($udom,$uname).'/userfiles';
2667: unless (-e $udir) {
2668: mkdir($udir,0770);
2669: }
2670: Debug("fetch user file for $fname");
2671: if (-e $udir) {
2672: $ufile=~s/^[\.\~]+//;
2673:
2674: # IF necessary, create the path right down to the file.
2675: # Note that any regular files in the way of this path are
2676: # wiped out to deal with some earlier folly of mine.
2677:
2678: if (!&mkpath($udir.'/'.$ufile)) {
2679: &Failure($client, "unable_to_create\n", $userinput);
2680: }
2681:
2682: my $destname=$udir.'/'.$ufile;
2683: my $transname=$udir.'/'.$ufile.'.in.transit';
2684: my $clientprotocol=$Apache::lonnet::protocol{$clientname};
2685: $clientprotocol = 'http' if ($clientprotocol ne 'https');
2686: my $clienthost = &Apache::lonnet::hostname($clientname);
2687: my $remoteurl=$clientprotocol.'://'.$clienthost.'/userfiles/'.$fname;
2688: my $response;
2689: Debug("Remote URL : $remoteurl Transfername $transname Destname: $destname");
2690: my $request=new HTTP::Request('GET',"$remoteurl");
2691: my $verifycert = 1;
2692: my @machine_ids = &Apache::lonnet::current_machine_ids();
2693: if (grep(/^\Q$clientname\E$/,@machine_ids)) {
2694: $verifycert = 0;
2695: }
2696: $response = &LONCAPA::LWPReq::makerequest($clientname,$request,$transname,\%perlvar,1200,$verifycert);
2697: if ($response->is_error()) {
2698: unlink($transname);
2699: my $message=$response->status_line;
2700: &logthis("LWP GET: $message for $fname ($remoteurl)");
2701: &Failure($client, "failed\n", $userinput);
2702: } else {
2703: Debug("Renaming $transname to $destname");
2704: if (!rename($transname,$destname)) {
2705: &logthis("Unable to move $transname to $destname");
2706: unlink($transname);
2707: &Failure($client, "failed\n", $userinput);
2708: } else {
2709: if ($fname =~ /^default.+\.(page|sequence)$/) {
2710: my ($major,$minor) = split(/\./,$clientversion);
2711: if (($major < 2) || ($major == 2 && $minor < 11)) {
2712: my $now = time;
2713: &Apache::lonnet::do_cache_new('crschange',$udom.'_'.$uname,$now,600);
2714: my $key = &escape('internal.contentchange');
2715: my $what = "$key=$now";
2716: my $hashref = &tie_user_hash($udom,$uname,'environment',
2717: &GDBM_WRCREAT(),"P",$what);
2718: if ($hashref) {
2719: $hashref->{$key}=$now;
2720: if (!&untie_user_hash($hashref)) {
2721: &logthis("error: ".($!+0)." untie (GDBM) failed ".
2722: "when updating internal.contentchange");
2723: }
2724: }
2725: }
2726: }
2727: &Reply($client, "ok\n", $userinput);
2728: }
2729: }
2730: } else {
2731: &Failure($client, "not_home\n", $userinput);
2732: }
2733: return 1;
2734: }
2735: ®ister_handler("fetchuserfile", \&fetch_user_file_handler, 0, 1, 0);
2736:
2737: #
2738: # Remove a file from a user's home directory userfiles subdirectory.
2739: # Parameters:
2740: # cmd - the Lond request keyword that got us here.
2741: # tail - the part of the command past the keyword.
2742: # client- File descriptor connected with the client.
2743: #
2744: # Returns:
2745: # 1 - Continue processing.
2746: sub remove_user_file_handler {
2747: my ($cmd, $tail, $client) = @_;
2748:
2749: my ($fname) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2750:
2751: my ($udom,$uname,$ufile) = ($fname =~ m|^([^/]+)/([^/]+)/(.+)$|);
2752: if ($ufile =~m|/\.\./|) {
2753: # any files paths with /../ in them refuse
2754: # to deal with
2755: &Failure($client, "refused\n", "$cmd:$tail");
2756: } else {
2757: my $udir = &propath($udom,$uname);
2758: if (-e $udir) {
2759: my $file=$udir.'/userfiles/'.$ufile;
2760: if (-e $file) {
2761: #
2762: # If the file is a regular file unlink is fine...
2763: # However it's possible the client wants a dir
2764: # removed, in which case rmdir is more appropriate.
2765: # Note: rmdir will only remove an empty directory.
2766: #
2767: if (-f $file){
2768: unlink($file);
2769: # for html files remove the associated .bak file
2770: # which may have been created by the editor.
2771: if ($ufile =~ m{^((docs|supplemental)/(?:\d+|default)/\d+(?:|/.+)/)[^/]+\.x?html?$}i) {
2772: my $path = $1;
2773: if (-e $file.'.bak') {
2774: unlink($file.'.bak');
2775: }
2776: }
2777: } elsif(-d $file) {
2778: rmdir($file);
2779: }
2780: if (-e $file) {
2781: # File is still there after we deleted it ?!?
2782:
2783: &Failure($client, "failed\n", "$cmd:$tail");
2784: } else {
2785: &Reply($client, "ok\n", "$cmd:$tail");
2786: }
2787: } else {
2788: &Failure($client, "not_found\n", "$cmd:$tail");
2789: }
2790: } else {
2791: &Failure($client, "not_home\n", "$cmd:$tail");
2792: }
2793: }
2794: return 1;
2795: }
2796: ®ister_handler("removeuserfile", \&remove_user_file_handler, 0,1,0);
2797:
2798: #
2799: # make a directory in a user's home directory userfiles subdirectory.
2800: # Parameters:
2801: # cmd - the Lond request keyword that got us here.
2802: # tail - the part of the command past the keyword.
2803: # client- File descriptor connected with the client.
2804: #
2805: # Returns:
2806: # 1 - Continue processing.
2807: sub mkdir_user_file_handler {
2808: my ($cmd, $tail, $client) = @_;
2809:
2810: my ($dir) = split(/:/, $tail); # Get rid of any tailing :'s lonc may have sent.
2811: $dir=&unescape($dir);
2812: my ($udom,$uname,$ufile) = ($dir =~ m|^([^/]+)/([^/]+)/(.+)$|);
2813: if ($ufile =~m|/\.\./|) {
2814: # any files paths with /../ in them refuse
2815: # to deal with
2816: &Failure($client, "refused\n", "$cmd:$tail");
2817: } else {
2818: my $udir = &propath($udom,$uname);
2819: if (-e $udir) {
2820: my $newdir=$udir.'/userfiles/'.$ufile.'/';
2821: if (!&mkpath($newdir)) {
2822: &Failure($client, "failed\n", "$cmd:$tail");
2823: }
2824: &Reply($client, "ok\n", "$cmd:$tail");
2825: } else {
2826: &Failure($client, "not_home\n", "$cmd:$tail");
2827: }
2828: }
2829: return 1;
2830: }
2831: ®ister_handler("mkdiruserfile", \&mkdir_user_file_handler, 0,1,0);
2832:
2833: #
2834: # rename a file in a user's home directory userfiles subdirectory.
2835: # Parameters:
2836: # cmd - the Lond request keyword that got us here.
2837: # tail - the part of the command past the keyword.
2838: # client- File descriptor connected with the client.
2839: #
2840: # Returns:
2841: # 1 - Continue processing.
2842: sub rename_user_file_handler {
2843: my ($cmd, $tail, $client) = @_;
2844:
2845: my ($udom,$uname,$old,$new) = split(/:/, $tail);
2846: $old=&unescape($old);
2847: $new=&unescape($new);
2848: if ($new =~m|/\.\./| || $old =~m|/\.\./|) {
2849: # any files paths with /../ in them refuse to deal with
2850: &Failure($client, "refused\n", "$cmd:$tail");
2851: } else {
2852: my $udir = &propath($udom,$uname);
2853: if (-e $udir) {
2854: my $oldfile=$udir.'/userfiles/'.$old;
2855: my $newfile=$udir.'/userfiles/'.$new;
2856: if (-e $newfile) {
2857: &Failure($client, "exists\n", "$cmd:$tail");
2858: } elsif (! -e $oldfile) {
2859: &Failure($client, "not_found\n", "$cmd:$tail");
2860: } else {
2861: if (!rename($oldfile,$newfile)) {
2862: &Failure($client, "failed\n", "$cmd:$tail");
2863: } else {
2864: &Reply($client, "ok\n", "$cmd:$tail");
2865: }
2866: }
2867: } else {
2868: &Failure($client, "not_home\n", "$cmd:$tail");
2869: }
2870: }
2871: return 1;
2872: }
2873: ®ister_handler("renameuserfile", \&rename_user_file_handler, 0,1,0);
2874:
2875: #
2876: # Checks if the specified user has an active session on the server
2877: # return ok if so, not_found if not
2878: #
2879: # Parameters:
2880: # cmd - The request keyword that dispatched to tus.
2881: # tail - The tail of the request (colon separated parameters).
2882: # client - Filehandle open on the client.
2883: # Return:
2884: # 1.
2885: sub user_has_session_handler {
2886: my ($cmd, $tail, $client) = @_;
2887:
2888: my ($udom, $uname) = map { &unescape($_) } (split(/:/, $tail));
2889:
2890: opendir(DIR,$perlvar{'lonIDsDir'});
2891: my $filename;
2892: while ($filename=readdir(DIR)) {
2893: last if ($filename=~/^\Q$uname\E_\d+_\Q$udom\E_/);
2894: }
2895: if ($filename) {
2896: &Reply($client, "ok\n", "$cmd:$tail");
2897: } else {
2898: &Failure($client, "not_found\n", "$cmd:$tail");
2899: }
2900: return 1;
2901:
2902: }
2903: ®ister_handler("userhassession", \&user_has_session_handler, 0,1,0);
2904:
2905: #
2906: # Authenticate access to a user file by checking that the token the user's
2907: # passed also exists in their session file
2908: #
2909: # Parameters:
2910: # cmd - The request keyword that dispatched to tus.
2911: # tail - The tail of the request (colon separated parameters).
2912: # client - Filehandle open on the client.
2913: # Return:
2914: # 1.
2915: sub token_auth_user_file_handler {
2916: my ($cmd, $tail, $client) = @_;
2917:
2918: my ($fname, $session) = split(/:/, $tail);
2919:
2920: chomp($session);
2921: my $reply="non_auth";
2922: my $file = $perlvar{'lonIDsDir'}.'/'.$session.'.id';
2923: if (open(ENVIN,"$file")) {
2924: flock(ENVIN,LOCK_SH);
2925: tie(my %disk_env,'GDBM_File',"$file",&GDBM_READER(),0640);
2926: if (exists($disk_env{"userfile.$fname"})) {
2927: $reply="ok";
2928: } else {
2929: foreach my $envname (keys(%disk_env)) {
2930: if ($envname=~ m|^userfile\.\Q$fname\E|) {
2931: $reply="ok";
2932: last;
2933: }
2934: }
2935: }
2936: untie(%disk_env);
2937: close(ENVIN);
2938: &Reply($client, \$reply, "$cmd:$tail");
2939: } else {
2940: &Failure($client, "invalid_token\n", "$cmd:$tail");
2941: }
2942: return 1;
2943:
2944: }
2945: ®ister_handler("tokenauthuserfile", \&token_auth_user_file_handler, 0,1,0);
2946:
2947: #
2948: # Unsubscribe from a resource.
2949: #
2950: # Parameters:
2951: # $cmd - The command that got us here.
2952: # $tail - Tail of the command (remaining parameters).
2953: # $client - File descriptor connected to client.
2954: # Returns
2955: # 0 - Requested to exit, caller should shut down.
2956: # 1 - Continue processing.
2957: #
2958: sub unsubscribe_handler {
2959: my ($cmd, $tail, $client) = @_;
2960:
2961: my $userinput= "$cmd:$tail";
2962:
2963: my ($fname) = split(/:/,$tail); # Split in case there's extrs.
2964:
2965: &Debug("Unsubscribing $fname");
2966: if (-e $fname) {
2967: &Debug("Exists");
2968: &Reply($client, &unsub($fname,$clientip), $userinput);
2969: } else {
2970: &Failure($client, "not_found\n", $userinput);
2971: }
2972: return 1;
2973: }
2974: ®ister_handler("unsub", \&unsubscribe_handler, 0, 1, 0);
2975:
2976: # Subscribe to a resource
2977: #
2978: # Parameters:
2979: # $cmd - The command that got us here.
2980: # $tail - Tail of the command (remaining parameters).
2981: # $client - File descriptor connected to client.
2982: # Returns
2983: # 0 - Requested to exit, caller should shut down.
2984: # 1 - Continue processing.
2985: #
2986: sub subscribe_handler {
2987: my ($cmd, $tail, $client)= @_;
2988:
2989: my $userinput = "$cmd:$tail";
2990:
2991: &Reply( $client, &subscribe($userinput,$clientip), $userinput);
2992:
2993: return 1;
2994: }
2995: ®ister_handler("sub", \&subscribe_handler, 0, 1, 0);
2996:
2997: #
2998: # Determine the latest version of a resource (it looks for the highest
2999: # past version and then returns that +1)
3000: #
3001: # Parameters:
3002: # $cmd - The command that got us here.
3003: # $tail - Tail of the command (remaining parameters).
3004: # (Should consist of an absolute path to a file)
3005: # $client - File descriptor connected to client.
3006: # Returns
3007: # 0 - Requested to exit, caller should shut down.
3008: # 1 - Continue processing.
3009: #
3010: sub current_version_handler {
3011: my ($cmd, $tail, $client) = @_;
3012:
3013: my $userinput= "$cmd:$tail";
3014:
3015: my $fname = $tail;
3016: &Reply( $client, ¤tversion($fname)."\n", $userinput);
3017: return 1;
3018:
3019: }
3020: ®ister_handler("currentversion", \¤t_version_handler, 0, 1, 0);
3021:
3022: # Make an entry in a user's activity log.
3023: #
3024: # Parameters:
3025: # $cmd - The command that got us here.
3026: # $tail - Tail of the command (remaining parameters).
3027: # $client - File descriptor connected to client.
3028: # Returns
3029: # 0 - Requested to exit, caller should shut down.
3030: # 1 - Continue processing.
3031: #
3032: sub activity_log_handler {
3033: my ($cmd, $tail, $client) = @_;
3034:
3035:
3036: my $userinput= "$cmd:$tail";
3037:
3038: my ($udom,$uname,$what)=split(/:/,$tail);
3039: chomp($what);
3040: my $proname=&propath($udom,$uname);
3041: my $now=time;
3042: my $hfh;
3043: if ($hfh=IO::File->new(">>$proname/activity.log")) {
3044: print $hfh "$now:$clientname:$what\n";
3045: &Reply( $client, "ok\n", $userinput);
3046: } else {
3047: &Failure($client, "error: ".($!+0)." IO::File->new Failed "
3048: ."while attempting log\n",
3049: $userinput);
3050: }
3051:
3052: return 1;
3053: }
3054: ®ister_handler("log", \&activity_log_handler, 0, 1, 0);
3055:
3056: #
3057: # Put a namespace entry in a user profile hash.
3058: # My druthers would be for this to be an encrypted interaction too.
3059: # anything that might be an inadvertent covert channel about either
3060: # user authentication or user personal information....
3061: #
3062: # Parameters:
3063: # $cmd - The command that got us here.
3064: # $tail - Tail of the command (remaining parameters).
3065: # $client - File descriptor connected to client.
3066: # Returns
3067: # 0 - Requested to exit, caller should shut down.
3068: # 1 - Continue processing.
3069: #
3070: sub put_user_profile_entry {
3071: my ($cmd, $tail, $client) = @_;
3072:
3073: my $userinput = "$cmd:$tail";
3074:
3075: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
3076: if ($namespace ne 'roles') {
3077: chomp($what);
3078: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3079: &GDBM_WRCREAT(),"P",$what);
3080: if($hashref) {
3081: my @pairs=split(/\&/,$what);
3082: foreach my $pair (@pairs) {
3083: my ($key,$value)=split(/=/,$pair);
3084: $hashref->{$key}=$value;
3085: }
3086: if (&untie_user_hash($hashref)) {
3087: &Reply( $client, "ok\n", $userinput);
3088: } else {
3089: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3090: "while attempting put\n",
3091: $userinput);
3092: }
3093: } else {
3094: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3095: "while attempting put\n", $userinput);
3096: }
3097: } else {
3098: &Failure( $client, "refused\n", $userinput);
3099: }
3100:
3101: return 1;
3102: }
3103: ®ister_handler("put", \&put_user_profile_entry, 0, 1, 0);
3104:
3105: # Put a piece of new data in hash, returns error if entry already exists
3106: # Parameters:
3107: # $cmd - The command that got us here.
3108: # $tail - Tail of the command (remaining parameters).
3109: # $client - File descriptor connected to client.
3110: # Returns
3111: # 0 - Requested to exit, caller should shut down.
3112: # 1 - Continue processing.
3113: #
3114: sub newput_user_profile_entry {
3115: my ($cmd, $tail, $client) = @_;
3116:
3117: my $userinput = "$cmd:$tail";
3118:
3119: my ($udom,$uname,$namespace,$what) =split(/:/,$tail,4);
3120: if ($namespace eq 'roles') {
3121: &Failure( $client, "refused\n", $userinput);
3122: return 1;
3123: }
3124:
3125: chomp($what);
3126:
3127: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3128: &GDBM_WRCREAT(),"N",$what);
3129: if(!$hashref) {
3130: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3131: "while attempting put\n", $userinput);
3132: return 1;
3133: }
3134:
3135: my @pairs=split(/\&/,$what);
3136: foreach my $pair (@pairs) {
3137: my ($key,$value)=split(/=/,$pair);
3138: if (exists($hashref->{$key})) {
3139: if (!&untie_user_hash($hashref)) {
3140: &logthis("error: ".($!+0)." untie (GDBM) failed ".
3141: "while attempting newput - early out as key exists");
3142: }
3143: &Failure($client, "key_exists: ".$key."\n",$userinput);
3144: return 1;
3145: }
3146: }
3147:
3148: foreach my $pair (@pairs) {
3149: my ($key,$value)=split(/=/,$pair);
3150: $hashref->{$key}=$value;
3151: }
3152:
3153: if (&untie_user_hash($hashref)) {
3154: &Reply( $client, "ok\n", $userinput);
3155: } else {
3156: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3157: "while attempting put\n",
3158: $userinput);
3159: }
3160: return 1;
3161: }
3162: ®ister_handler("newput", \&newput_user_profile_entry, 0, 1, 0);
3163:
3164: #
3165: # Increment a profile entry in the user history file.
3166: # The history contains keyword value pairs. In this case,
3167: # The value itself is a pair of numbers. The first, the current value
3168: # the second an increment that this function applies to the current
3169: # value.
3170: #
3171: # Parameters:
3172: # $cmd - The command that got us here.
3173: # $tail - Tail of the command (remaining parameters).
3174: # $client - File descriptor connected to client.
3175: # Returns
3176: # 0 - Requested to exit, caller should shut down.
3177: # 1 - Continue processing.
3178: #
3179: sub increment_user_value_handler {
3180: my ($cmd, $tail, $client) = @_;
3181:
3182: my $userinput = "$cmd:$tail";
3183:
3184: my ($udom,$uname,$namespace,$what) =split(/:/,$tail);
3185: if ($namespace ne 'roles') {
3186: chomp($what);
3187: my $hashref = &tie_user_hash($udom, $uname,
3188: $namespace, &GDBM_WRCREAT(),
3189: "P",$what);
3190: if ($hashref) {
3191: my @pairs=split(/\&/,$what);
3192: foreach my $pair (@pairs) {
3193: my ($key,$value)=split(/=/,$pair);
3194: $value = &unescape($value);
3195: # We could check that we have a number...
3196: if (! defined($value) || $value eq '') {
3197: $value = 1;
3198: }
3199: $hashref->{$key}+=$value;
3200: if ($namespace eq 'nohist_resourcetracker') {
3201: if ($hashref->{$key} < 0) {
3202: $hashref->{$key} = 0;
3203: }
3204: }
3205: }
3206: if (&untie_user_hash($hashref)) {
3207: &Reply( $client, "ok\n", $userinput);
3208: } else {
3209: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
3210: "while attempting inc\n", $userinput);
3211: }
3212: } else {
3213: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3214: "while attempting inc\n", $userinput);
3215: }
3216: } else {
3217: &Failure($client, "refused\n", $userinput);
3218: }
3219:
3220: return 1;
3221: }
3222: ®ister_handler("inc", \&increment_user_value_handler, 0, 1, 0);
3223:
3224: #
3225: # Put a new role for a user. Roles are LonCAPA's packaging of permissions.
3226: # Each 'role' a user has implies a set of permissions. Adding a new role
3227: # for a person grants the permissions packaged with that role
3228: # to that user when the role is selected.
3229: #
3230: # Parameters:
3231: # $cmd - The command string (rolesput).
3232: # $tail - The remainder of the request line. For rolesput this
3233: # consists of a colon separated list that contains:
3234: # The domain and user that is granting the role (logged).
3235: # The domain and user that is getting the role.
3236: # The roles being granted as a set of & separated pairs.
3237: # each pair a key value pair.
3238: # $client - File descriptor connected to the client.
3239: # Returns:
3240: # 0 - If the daemon should exit
3241: # 1 - To continue processing.
3242: #
3243: #
3244: sub roles_put_handler {
3245: my ($cmd, $tail, $client) = @_;
3246:
3247: my $userinput = "$cmd:$tail";
3248:
3249: my ( $exedom, $exeuser, $udom, $uname, $what) = split(/:/,$tail);
3250:
3251:
3252: my $namespace='roles';
3253: chomp($what);
3254: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3255: &GDBM_WRCREAT(), "P",
3256: "$exedom:$exeuser:$what");
3257: #
3258: # Log the attempt to set a role. The {}'s here ensure that the file
3259: # handle is open for the minimal amount of time. Since the flush
3260: # is done on close this improves the chances the log will be an un-
3261: # corrupted ordered thing.
3262: if ($hashref) {
3263: my $pass_entry = &get_auth_type($udom, $uname);
3264: my ($auth_type,$pwd) = split(/:/, $pass_entry);
3265: $auth_type = $auth_type.":";
3266: my @pairs=split(/\&/,$what);
3267: foreach my $pair (@pairs) {
3268: my ($key,$value)=split(/=/,$pair);
3269: &manage_permissions($key, $udom, $uname,
3270: $auth_type);
3271: $hashref->{$key}=$value;
3272: }
3273: if (&untie_user_hash($hashref)) {
3274: &Reply($client, "ok\n", $userinput);
3275: } else {
3276: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3277: "while attempting rolesput\n", $userinput);
3278: }
3279: } else {
3280: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3281: "while attempting rolesput\n", $userinput);
3282: }
3283: return 1;
3284: }
3285: ®ister_handler("rolesput", \&roles_put_handler, 1,1,0); # Encoded client only.
3286:
3287: #
3288: # Deletes (removes) a role for a user. This is equivalent to removing
3289: # a permissions package associated with the role from the user's profile.
3290: #
3291: # Parameters:
3292: # $cmd - The command (rolesdel)
3293: # $tail - The remainder of the request line. This consists
3294: # of:
3295: # The domain and user requesting the change (logged)
3296: # The domain and user being changed.
3297: # The roles being revoked. These are shipped to us
3298: # as a bunch of & separated role name keywords.
3299: # $client - The file handle open on the client.
3300: # Returns:
3301: # 1 - Continue processing
3302: # 0 - Exit.
3303: #
3304: sub roles_delete_handler {
3305: my ($cmd, $tail, $client) = @_;
3306:
3307: my $userinput = "$cmd:$tail";
3308:
3309: my ($exedom,$exeuser,$udom,$uname,$what)=split(/:/,$tail);
3310: &Debug("cmd = ".$cmd." exedom= ".$exedom."user = ".$exeuser." udom=".$udom.
3311: "what = ".$what);
3312: my $namespace='roles';
3313: chomp($what);
3314: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3315: &GDBM_WRCREAT(), "D",
3316: "$exedom:$exeuser:$what");
3317:
3318: if ($hashref) {
3319: my @rolekeys=split(/\&/,$what);
3320:
3321: foreach my $key (@rolekeys) {
3322: delete $hashref->{$key};
3323: }
3324: if (&untie_user_hash($hashref)) {
3325: &Reply($client, "ok\n", $userinput);
3326: } else {
3327: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3328: "while attempting rolesdel\n", $userinput);
3329: }
3330: } else {
3331: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3332: "while attempting rolesdel\n", $userinput);
3333: }
3334:
3335: return 1;
3336: }
3337: ®ister_handler("rolesdel", \&roles_delete_handler, 1,1, 0); # Encoded client only
3338:
3339: # Unencrypted get from a user's profile database. See
3340: # GetProfileEntryEncrypted for a version that does end-to-end encryption.
3341: # This function retrieves a keyed item from a specific named database in the
3342: # user's directory.
3343: #
3344: # Parameters:
3345: # $cmd - Command request keyword (get).
3346: # $tail - Tail of the command. This is a colon separated list
3347: # consisting of the domain and username that uniquely
3348: # identifies the profile,
3349: # The 'namespace' which selects the gdbm file to
3350: # do the lookup in,
3351: # & separated list of keys to lookup. Note that
3352: # the values are returned as an & separated list too.
3353: # $client - File descriptor open on the client.
3354: # Returns:
3355: # 1 - Continue processing.
3356: # 0 - Exit.
3357: #
3358: sub get_profile_entry {
3359: my ($cmd, $tail, $client) = @_;
3360:
3361: my $userinput= "$cmd:$tail";
3362:
3363: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
3364: chomp($what);
3365:
3366:
3367: my $replystring = read_profile($udom, $uname, $namespace, $what);
3368: my ($first) = split(/:/,$replystring);
3369: if($first ne "error") {
3370: &Reply($client, \$replystring, $userinput);
3371: } else {
3372: &Failure($client, $replystring." while attempting get\n", $userinput);
3373: }
3374: return 1;
3375:
3376:
3377: }
3378: ®ister_handler("get", \&get_profile_entry, 0,1,0);
3379:
3380: #
3381: # Process the encrypted get request. Note that the request is sent
3382: # in clear, but the reply is encrypted. This is a small covert channel:
3383: # information about the sensitive keys is given to the snooper. Just not
3384: # information about the values of the sensitive key. Hmm if I wanted to
3385: # know these I'd snoop for the egets. Get the profile item names from them
3386: # and then issue a get for them since there's no enforcement of the
3387: # requirement of an encrypted get for particular profile items. If I
3388: # were re-doing this, I'd force the request to be encrypted as well as the
3389: # reply. I'd also just enforce encrypted transactions for all gets since
3390: # that would prevent any covert channel snooping.
3391: #
3392: # Parameters:
3393: # $cmd - Command keyword of request (eget).
3394: # $tail - Tail of the command. See GetProfileEntry
3395: # for more information about this.
3396: # $client - File open on the client.
3397: # Returns:
3398: # 1 - Continue processing
3399: # 0 - server should exit.
3400: sub get_profile_entry_encrypted {
3401: my ($cmd, $tail, $client) = @_;
3402:
3403: my $userinput = "$cmd:$tail";
3404:
3405: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
3406: chomp($what);
3407: my $qresult = read_profile($udom, $uname, $namespace, $what);
3408: my ($first) = split(/:/, $qresult);
3409: if($first ne "error") {
3410:
3411: if ($cipher) {
3412: my $cmdlength=length($qresult);
3413: $qresult.=" ";
3414: my $encqresult='';
3415: for(my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
3416: $encqresult.= unpack("H16",
3417: $cipher->encrypt(substr($qresult,
3418: $encidx,
3419: 8)));
3420: }
3421: &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
3422: } else {
3423: &Failure( $client, "error:no_key\n", $userinput);
3424: }
3425: } else {
3426: &Failure($client, "$qresult while attempting eget\n", $userinput);
3427:
3428: }
3429:
3430: return 1;
3431: }
3432: ®ister_handler("eget", \&get_profile_entry_encrypted, 0, 1, 0);
3433:
3434: #
3435: # Deletes a key in a user profile database.
3436: #
3437: # Parameters:
3438: # $cmd - Command keyword (del).
3439: # $tail - Command tail. IN this case a colon
3440: # separated list containing:
3441: # The domain and user that identifies uniquely
3442: # the identity of the user.
3443: # The profile namespace (name of the profile
3444: # database file).
3445: # & separated list of keywords to delete.
3446: # $client - File open on client socket.
3447: # Returns:
3448: # 1 - Continue processing
3449: # 0 - Exit server.
3450: #
3451: #
3452: sub delete_profile_entry {
3453: my ($cmd, $tail, $client) = @_;
3454:
3455: my $userinput = "cmd:$tail";
3456:
3457: my ($udom,$uname,$namespace,$what) = split(/:/,$tail);
3458: chomp($what);
3459: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3460: &GDBM_WRCREAT(),
3461: "D",$what);
3462: if ($hashref) {
3463: my @keys=split(/\&/,$what);
3464: foreach my $key (@keys) {
3465: delete($hashref->{$key});
3466: }
3467: if (&untie_user_hash($hashref)) {
3468: &Reply($client, "ok\n", $userinput);
3469: } else {
3470: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3471: "while attempting del\n", $userinput);
3472: }
3473: } else {
3474: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3475: "while attempting del\n", $userinput);
3476: }
3477: return 1;
3478: }
3479: ®ister_handler("del", \&delete_profile_entry, 0, 1, 0);
3480:
3481: #
3482: # List the set of keys that are defined in a profile database file.
3483: # A successful reply from this will contain an & separated list of
3484: # the keys.
3485: # Parameters:
3486: # $cmd - Command request (keys).
3487: # $tail - Remainder of the request, a colon separated
3488: # list containing domain/user that identifies the
3489: # user being queried, and the database namespace
3490: # (database filename essentially).
3491: # $client - File open on the client.
3492: # Returns:
3493: # 1 - Continue processing.
3494: # 0 - Exit the server.
3495: #
3496: sub get_profile_keys {
3497: my ($cmd, $tail, $client) = @_;
3498:
3499: my $userinput = "$cmd:$tail";
3500:
3501: my ($udom,$uname,$namespace)=split(/:/,$tail);
3502: my $qresult='';
3503: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3504: &GDBM_READER());
3505: if ($hashref) {
3506: foreach my $key (keys %$hashref) {
3507: $qresult.="$key&";
3508: }
3509: if (&untie_user_hash($hashref)) {
3510: $qresult=~s/\&$//;
3511: &Reply($client, \$qresult, $userinput);
3512: } else {
3513: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3514: "while attempting keys\n", $userinput);
3515: }
3516: } else {
3517: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3518: "while attempting keys\n", $userinput);
3519: }
3520:
3521: return 1;
3522: }
3523: ®ister_handler("keys", \&get_profile_keys, 0, 1, 0);
3524:
3525: #
3526: # Dump the contents of a user profile database.
3527: # Note that this constitutes a very large covert channel too since
3528: # the dump will return sensitive information that is not encrypted.
3529: # The naive security assumption is that the session negotiation ensures
3530: # our client is trusted and I don't believe that's assured at present.
3531: # Sure want badly to go to ssl or tls. Of course if my peer isn't really
3532: # a LonCAPA node they could have negotiated an encryption key too so >sigh<.
3533: #
3534: # Parameters:
3535: # $cmd - The command request keyword (currentdump).
3536: # $tail - Remainder of the request, consisting of a colon
3537: # separated list that has the domain/username and
3538: # the namespace to dump (database file).
3539: # $client - file open on the remote client.
3540: # Returns:
3541: # 1 - Continue processing.
3542: # 0 - Exit the server.
3543: #
3544: sub dump_profile_database {
3545: my ($cmd, $tail, $client) = @_;
3546:
3547: my $res = LONCAPA::Lond::dump_profile_database($tail);
3548:
3549: if ($res =~ /^error:/) {
3550: Failure($client, \$res, "$cmd:$tail");
3551: } else {
3552: Reply($client, \$res, "$cmd:$tail");
3553: }
3554:
3555: return 1;
3556:
3557: #TODO remove
3558: my $userinput = "$cmd:$tail";
3559:
3560: my ($udom,$uname,$namespace) = split(/:/,$tail);
3561: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3562: &GDBM_READER());
3563: if ($hashref) {
3564: # Structure of %data:
3565: # $data{$symb}->{$parameter}=$value;
3566: # $data{$symb}->{'v.'.$parameter}=$version;
3567: # since $parameter will be unescaped, we do not
3568: # have to worry about silly parameter names...
3569:
3570: my $qresult='';
3571: my %data = (); # A hash of anonymous hashes..
3572: while (my ($key,$value) = each(%$hashref)) {
3573: my ($v,$symb,$param) = split(/:/,$key);
3574: next if ($v eq 'version' || $symb eq 'keys');
3575: next if (exists($data{$symb}) &&
3576: exists($data{$symb}->{$param}) &&
3577: $data{$symb}->{'v.'.$param} > $v);
3578: $data{$symb}->{$param}=$value;
3579: $data{$symb}->{'v.'.$param}=$v;
3580: }
3581: if (&untie_user_hash($hashref)) {
3582: while (my ($symb,$param_hash) = each(%data)) {
3583: while(my ($param,$value) = each (%$param_hash)){
3584: next if ($param =~ /^v\./); # Ignore versions...
3585: #
3586: # Just dump the symb=value pairs separated by &
3587: #
3588: $qresult.=$symb.':'.$param.'='.$value.'&';
3589: }
3590: }
3591: chop($qresult);
3592: &Reply($client , \$qresult, $userinput);
3593: } else {
3594: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
3595: "while attempting currentdump\n", $userinput);
3596: }
3597: } else {
3598: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3599: "while attempting currentdump\n", $userinput);
3600: }
3601:
3602: return 1;
3603: }
3604: ®ister_handler("currentdump", \&dump_profile_database, 0, 1, 0);
3605:
3606: #
3607: # Dump a profile database with an optional regular expression
3608: # to match against the keys. In this dump, no effort is made
3609: # to separate symb from version information. Presumably the
3610: # databases that are dumped by this command are of a different
3611: # structure. Need to look at this and improve the documentation of
3612: # both this and the currentdump handler.
3613: # Parameters:
3614: # $cmd - The command keyword.
3615: # $tail - All of the characters after the $cmd:
3616: # These are expected to be a colon
3617: # separated list containing:
3618: # domain/user - identifying the user.
3619: # namespace - identifying the database.
3620: # regexp - optional regular expression
3621: # that is matched against
3622: # database keywords to do
3623: # selective dumps.
3624: # range - optional range of entries
3625: # e.g., 10-20 would return the
3626: # 10th to 19th items, etc.
3627: # $client - Channel open on the client.
3628: # Returns:
3629: # 1 - Continue processing.
3630: # Side effects:
3631: # response is written to $client.
3632: #
3633: sub dump_with_regexp {
3634: my ($cmd, $tail, $client) = @_;
3635:
3636: my $res = LONCAPA::Lond::dump_with_regexp($tail, $clientversion);
3637:
3638: if ($res =~ /^error:/) {
3639: Failure($client, \$res, "$cmd:$tail");
3640: } else {
3641: Reply($client, \$res, "$cmd:$tail");
3642: }
3643:
3644: return 1;
3645: }
3646: ®ister_handler("dump", \&dump_with_regexp, 0, 1, 0);
3647:
3648: # Store a set of key=value pairs associated with a versioned name.
3649: #
3650: # Parameters:
3651: # $cmd - Request command keyword.
3652: # $tail - Tail of the request. This is a colon
3653: # separated list containing:
3654: # domain/user - User and authentication domain.
3655: # namespace - Name of the database being modified
3656: # rid - Resource keyword to modify.
3657: # what - new value associated with rid.
3658: # laststore - (optional) version=timestamp
3659: # for most recent transaction for rid
3660: # in namespace, when cstore was called
3661: #
3662: # $client - Socket open on the client.
3663: #
3664: #
3665: # Returns:
3666: # 1 (keep on processing).
3667: # Side-Effects:
3668: # Writes to the client
3669: # Successful storage will cause either 'ok', or, if $laststore was included
3670: # in the tail of the request, and the version number for the last transaction
3671: # is larger than the version in $laststore, delay:$numtrans , where $numtrans
3672: # is the number of store evevnts recorded for rid in namespace since
3673: # lonnet::store() was called by the client.
3674: #
3675: sub store_handler {
3676: my ($cmd, $tail, $client) = @_;
3677:
3678: my $userinput = "$cmd:$tail";
3679: chomp($tail);
3680: my ($udom,$uname,$namespace,$rid,$what,$laststore) =split(/:/,$tail);
3681: if ($namespace ne 'roles') {
3682:
3683: my @pairs=split(/\&/,$what);
3684: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3685: &GDBM_WRCREAT(), "S",
3686: "$rid:$what");
3687: if ($hashref) {
3688: my $now = time;
3689: my $numtrans;
3690: if ($laststore) {
3691: my ($previousversion,$previoustime) = split(/\=/,$laststore);
3692: my ($lastversion,$lasttime) = (0,0);
3693: $lastversion = $hashref->{"version:$rid"};
3694: if ($lastversion) {
3695: $lasttime = $hashref->{"$lastversion:$rid:timestamp"};
3696: }
3697: if (($previousversion) && ($previousversion !~ /\D/)) {
3698: if (($lastversion > $previousversion) && ($lasttime >= $previoustime)) {
3699: $numtrans = $lastversion - $previousversion;
3700: }
3701: } elsif ($lastversion) {
3702: $numtrans = $lastversion;
3703: }
3704: if ($numtrans) {
3705: $numtrans =~ s/D//g;
3706: }
3707: }
3708: $hashref->{"version:$rid"}++;
3709: my $version=$hashref->{"version:$rid"};
3710: my $allkeys='';
3711: foreach my $pair (@pairs) {
3712: my ($key,$value)=split(/=/,$pair);
3713: $allkeys.=$key.':';
3714: $hashref->{"$version:$rid:$key"}=$value;
3715: }
3716: $hashref->{"$version:$rid:timestamp"}=$now;
3717: $allkeys.='timestamp';
3718: $hashref->{"$version:keys:$rid"}=$allkeys;
3719: if (&untie_user_hash($hashref)) {
3720: my $msg = 'ok';
3721: if ($numtrans) {
3722: $msg = 'delay:'.$numtrans;
3723: }
3724: &Reply($client, "$msg\n", $userinput);
3725: } else {
3726: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3727: "while attempting store\n", $userinput);
3728: }
3729: } else {
3730: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3731: "while attempting store\n", $userinput);
3732: }
3733: } else {
3734: &Failure($client, "refused\n", $userinput);
3735: }
3736:
3737: return 1;
3738: }
3739: ®ister_handler("store", \&store_handler, 0, 1, 0);
3740:
3741: # Modify a set of key=value pairs associated with a versioned name.
3742: #
3743: # Parameters:
3744: # $cmd - Request command keyword.
3745: # $tail - Tail of the request. This is a colon
3746: # separated list containing:
3747: # domain/user - User and authentication domain.
3748: # namespace - Name of the database being modified
3749: # rid - Resource keyword to modify.
3750: # v - Version item to modify
3751: # what - new value associated with rid.
3752: #
3753: # $client - Socket open on the client.
3754: #
3755: #
3756: # Returns:
3757: # 1 (keep on processing).
3758: # Side-Effects:
3759: # Writes to the client
3760: sub putstore_handler {
3761: my ($cmd, $tail, $client) = @_;
3762:
3763: my $userinput = "$cmd:$tail";
3764:
3765: my ($udom,$uname,$namespace,$rid,$v,$what) =split(/:/,$tail);
3766: if ($namespace ne 'roles') {
3767:
3768: chomp($what);
3769: my $hashref = &tie_user_hash($udom, $uname, $namespace,
3770: &GDBM_WRCREAT(), "M",
3771: "$rid:$v:$what");
3772: if ($hashref) {
3773: my $now = time;
3774: my %data = &hash_extract($what);
3775: my @allkeys;
3776: while (my($key,$value) = each(%data)) {
3777: push(@allkeys,$key);
3778: $hashref->{"$v:$rid:$key"} = $value;
3779: }
3780: my $allkeys = join(':',@allkeys);
3781: $hashref->{"$v:keys:$rid"}=$allkeys;
3782:
3783: if (&untie_user_hash($hashref)) {
3784: &Reply($client, "ok\n", $userinput);
3785: } else {
3786: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3787: "while attempting store\n", $userinput);
3788: }
3789: } else {
3790: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
3791: "while attempting store\n", $userinput);
3792: }
3793: } else {
3794: &Failure($client, "refused\n", $userinput);
3795: }
3796:
3797: return 1;
3798: }
3799: ®ister_handler("putstore", \&putstore_handler, 0, 1, 0);
3800:
3801: sub hash_extract {
3802: my ($str)=@_;
3803: my %hash;
3804: foreach my $pair (split(/\&/,$str)) {
3805: my ($key,$value)=split(/=/,$pair);
3806: $hash{$key}=$value;
3807: }
3808: return (%hash);
3809: }
3810: sub hash_to_str {
3811: my ($hash_ref)=@_;
3812: my $str;
3813: foreach my $key (keys(%$hash_ref)) {
3814: $str.=$key.'='.$hash_ref->{$key}.'&';
3815: }
3816: $str=~s/\&$//;
3817: return $str;
3818: }
3819:
3820: #
3821: # Dump out all versions of a resource that has key=value pairs associated
3822: # with it for each version. These resources are built up via the store
3823: # command.
3824: #
3825: # Parameters:
3826: # $cmd - Command keyword.
3827: # $tail - Remainder of the request which consists of:
3828: # domain/user - User and auth. domain.
3829: # namespace - name of resource database.
3830: # rid - Resource id.
3831: # $client - socket open on the client.
3832: #
3833: # Returns:
3834: # 1 indicating the caller should not yet exit.
3835: # Side-effects:
3836: # Writes a reply to the client.
3837: # The reply is a string of the following shape:
3838: # version=current&version:keys=k1:k2...&1:k1=v1&1:k2=v2...
3839: # Where the 1 above represents version 1.
3840: # this continues for all pairs of keys in all versions.
3841: #
3842: #
3843: #
3844: #
3845: sub restore_handler {
3846: my ($cmd, $tail, $client) = @_;
3847:
3848: my $userinput = "$cmd:$tail"; # Only used for logging purposes.
3849: my ($udom,$uname,$namespace,$rid) = split(/:/,$tail);
3850: $namespace=~s/\//\_/g;
3851: $namespace = &LONCAPA::clean_username($namespace);
3852:
3853: chomp($rid);
3854: my $qresult='';
3855: my $hashref = &tie_user_hash($udom, $uname, $namespace, &GDBM_READER());
3856: if ($hashref) {
3857: my $version=$hashref->{"version:$rid"};
3858: $qresult.="version=$version&";
3859: my $scope;
3860: for ($scope=1;$scope<=$version;$scope++) {
3861: my $vkeys=$hashref->{"$scope:keys:$rid"};
3862: my @keys=split(/:/,$vkeys);
3863: my $key;
3864: $qresult.="$scope:keys=$vkeys&";
3865: foreach $key (@keys) {
3866: $qresult.="$scope:$key=".$hashref->{"$scope:$rid:$key"}."&";
3867: }
3868: }
3869: if (&untie_user_hash($hashref)) {
3870: $qresult=~s/\&$//;
3871: &Reply( $client, \$qresult, $userinput);
3872: } else {
3873: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
3874: "while attempting restore\n", $userinput);
3875: }
3876: } else {
3877: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
3878: "while attempting restore\n", $userinput);
3879: }
3880:
3881: return 1;
3882:
3883:
3884: }
3885: ®ister_handler("restore", \&restore_handler, 0,1,0);
3886:
3887: #
3888: # Add a chat message to a synchronous discussion board.
3889: #
3890: # Parameters:
3891: # $cmd - Request keyword.
3892: # $tail - Tail of the command. A colon separated list
3893: # containing:
3894: # cdom - Domain on which the chat board lives
3895: # cnum - Course containing the chat board.
3896: # newpost - Body of the posting.
3897: # group - Optional group, if chat board is only
3898: # accessible in a group within the course
3899: # $client - Socket open on the client.
3900: # Returns:
3901: # 1 - Indicating caller should keep on processing.
3902: #
3903: # Side-effects:
3904: # writes a reply to the client.
3905: #
3906: #
3907: sub send_chat_handler {
3908: my ($cmd, $tail, $client) = @_;
3909:
3910:
3911: my $userinput = "$cmd:$tail";
3912:
3913: my ($cdom,$cnum,$newpost,$group)=split(/\:/,$tail);
3914: &chat_add($cdom,$cnum,$newpost,$group);
3915: &Reply($client, "ok\n", $userinput);
3916:
3917: return 1;
3918: }
3919: ®ister_handler("chatsend", \&send_chat_handler, 0, 1, 0);
3920:
3921: #
3922: # Retrieve the set of chat messages from a discussion board.
3923: #
3924: # Parameters:
3925: # $cmd - Command keyword that initiated the request.
3926: # $tail - Remainder of the request after the command
3927: # keyword. In this case a colon separated list of
3928: # chat domain - Which discussion board.
3929: # chat id - Discussion thread(?)
3930: # domain/user - Authentication domain and username
3931: # of the requesting person.
3932: # group - Optional course group containing
3933: # the board.
3934: # $client - Socket open on the client program.
3935: # Returns:
3936: # 1 - continue processing
3937: # Side effects:
3938: # Response is written to the client.
3939: #
3940: sub retrieve_chat_handler {
3941: my ($cmd, $tail, $client) = @_;
3942:
3943:
3944: my $userinput = "$cmd:$tail";
3945:
3946: my ($cdom,$cnum,$udom,$uname,$group)=split(/\:/,$tail);
3947: my $reply='';
3948: foreach (&get_chat($cdom,$cnum,$udom,$uname,$group)) {
3949: $reply.=&escape($_).':';
3950: }
3951: $reply=~s/\:$//;
3952: &Reply($client, \$reply, $userinput);
3953:
3954:
3955: return 1;
3956: }
3957: ®ister_handler("chatretr", \&retrieve_chat_handler, 0, 1, 0);
3958:
3959: #
3960: # Initiate a query of an sql database. SQL query repsonses get put in
3961: # a file for later retrieval. This prevents sql query results from
3962: # bottlenecking the system. Note that with loncnew, perhaps this is
3963: # less of an issue since multiple outstanding requests can be concurrently
3964: # serviced.
3965: #
3966: # Parameters:
3967: # $cmd - Command keyword that initiated the request.
3968: # $tail - Remainder of the command after the keyword.
3969: # For this function, this consists of a query and
3970: # 3 arguments that are self-documentingly labelled
3971: # in the original arg1, arg2, arg3.
3972: # $client - Socket open on the client.
3973: # Return:
3974: # 1 - Indicating processing should continue.
3975: # Side-effects:
3976: # a reply is written to $client.
3977: #
3978: sub send_query_handler {
3979: my ($cmd, $tail, $client) = @_;
3980:
3981: my $userinput = "$cmd:$tail";
3982:
3983: my ($query,$arg1,$arg2,$arg3)=split(/\:/,$tail);
3984: $query=~s/\n*$//g;
3985: if (($query eq 'usersearch') || ($query eq 'instdirsearch')) {
3986: my $usersearchconf = &get_usersearch_config($currentdomainid,'directorysrch');
3987: my $earlyout;
3988: if (ref($usersearchconf) eq 'HASH') {
3989: if ($currentdomainid eq $clienthomedom) {
3990: if ($query eq 'usersearch') {
3991: if ($usersearchconf->{'lcavailable'} eq '0') {
3992: $earlyout = 1;
3993: }
3994: } else {
3995: if ($usersearchconf->{'available'} eq '0') {
3996: $earlyout = 1;
3997: }
3998: }
3999: } else {
4000: if ($query eq 'usersearch') {
4001: if ($usersearchconf->{'lclocalonly'}) {
4002: $earlyout = 1;
4003: }
4004: } else {
4005: if ($usersearchconf->{'localonly'}) {
4006: $earlyout = 1;
4007: }
4008: }
4009: }
4010: }
4011: if ($earlyout) {
4012: &Reply($client, "query_not_authorized\n");
4013: return 1;
4014: }
4015: }
4016: &Reply($client, "". &sql_reply("$clientname\&$query".
4017: "\&$arg1"."\&$arg2"."\&$arg3")."\n",
4018: $userinput);
4019:
4020: return 1;
4021: }
4022: ®ister_handler("querysend", \&send_query_handler, 0, 1, 0);
4023:
4024: #
4025: # Add a reply to an sql query. SQL queries are done asyncrhonously.
4026: # The query is submitted via a "querysend" transaction.
4027: # There it is passed on to the lonsql daemon, queued and issued to
4028: # mysql.
4029: # This transaction is invoked when the sql transaction is complete
4030: # it stores the query results in flie and indicates query completion.
4031: # presumably local software then fetches this response... I'm guessing
4032: # the sequence is: lonc does a querysend, we ask lonsql to do it.
4033: # lonsql on completion of the query interacts with the lond of our
4034: # client to do a query reply storing two files:
4035: # - id - The results of the query.
4036: # - id.end - Indicating the transaction completed.
4037: # NOTE: id is a unique id assigned to the query and querysend time.
4038: # Parameters:
4039: # $cmd - Command keyword that initiated this request.
4040: # $tail - Remainder of the tail. In this case that's a colon
4041: # separated list containing the query Id and the
4042: # results of the query.
4043: # $client - Socket open on the client.
4044: # Return:
4045: # 1 - Indicating that we should continue processing.
4046: # Side effects:
4047: # ok written to the client.
4048: #
4049: sub reply_query_handler {
4050: my ($cmd, $tail, $client) = @_;
4051:
4052:
4053: my $userinput = "$cmd:$tail";
4054:
4055: my ($id,$reply)=split(/:/,$tail);
4056: my $store;
4057: my $execdir=$perlvar{'lonDaemons'};
4058: if ($store=IO::File->new(">$execdir/tmp/$id")) {
4059: $reply=~s/\&/\n/g;
4060: print $store $reply;
4061: close $store;
4062: my $store2=IO::File->new(">$execdir/tmp/$id.end");
4063: print $store2 "done\n";
4064: close $store2;
4065: &Reply($client, "ok\n", $userinput);
4066: } else {
4067: &Failure($client, "error: ".($!+0)
4068: ." IO::File->new Failed ".
4069: "while attempting queryreply\n", $userinput);
4070: }
4071:
4072:
4073: return 1;
4074: }
4075: ®ister_handler("queryreply", \&reply_query_handler, 0, 1, 0);
4076:
4077: #
4078: # Process the courseidput request. Not quite sure what this means
4079: # at the system level sense. It appears a gdbm file in the
4080: # /home/httpd/lonUsers/$domain/nohist_courseids is tied and
4081: # a set of entries made in that database.
4082: #
4083: # Parameters:
4084: # $cmd - The command keyword that initiated this request.
4085: # $tail - Tail of the command. In this case consists of a colon
4086: # separated list contaning the domain to apply this to and
4087: # an ampersand separated list of keyword=value pairs.
4088: # Each value is a colon separated list that includes:
4089: # description, institutional code and course owner.
4090: # For backward compatibility with versions included
4091: # in LON-CAPA 1.1.X (and earlier) and 1.2.X, institutional
4092: # code and/or course owner are preserved from the existing
4093: # record when writing a new record in response to 1.1 or
4094: # 1.2 implementations of lonnet::flushcourselogs().
4095: #
4096: # $client - Socket open on the client.
4097: # Returns:
4098: # 1 - indicating that processing should continue
4099: #
4100: # Side effects:
4101: # reply is written to the client.
4102: #
4103: sub put_course_id_handler {
4104: my ($cmd, $tail, $client) = @_;
4105:
4106:
4107: my $userinput = "$cmd:$tail";
4108:
4109: my ($udom, $what) = split(/:/, $tail,2);
4110: chomp($what);
4111: my $now=time;
4112: my @pairs=split(/\&/,$what);
4113:
4114: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
4115: if ($hashref) {
4116: foreach my $pair (@pairs) {
4117: my ($key,$courseinfo) = split(/=/,$pair,2);
4118: $courseinfo =~ s/=/:/g;
4119: if (defined($hashref->{$key})) {
4120: my $value = &Apache::lonnet::thaw_unescape($hashref->{$key});
4121: if (ref($value) eq 'HASH') {
4122: my @items = ('description','inst_code','owner','type');
4123: my @new_items = split(/:/,$courseinfo,-1);
4124: my %storehash;
4125: for (my $i=0; $i<@new_items; $i++) {
4126: $storehash{$items[$i]} = &unescape($new_items[$i]);
4127: }
4128: $hashref->{$key} =
4129: &Apache::lonnet::freeze_escape(\%storehash);
4130: my $unesc_key = &unescape($key);
4131: $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
4132: next;
4133: }
4134: }
4135: my @current_items = split(/:/,$hashref->{$key},-1);
4136: shift(@current_items); # remove description
4137: pop(@current_items); # remove last access
4138: my $numcurrent = scalar(@current_items);
4139: if ($numcurrent > 3) {
4140: $numcurrent = 3;
4141: }
4142: my @new_items = split(/:/,$courseinfo,-1);
4143: my $numnew = scalar(@new_items);
4144: if ($numcurrent > 0) {
4145: if ($numnew <= $numcurrent) { # flushcourselogs() from pre 2.2
4146: for (my $j=$numcurrent-$numnew; $j>=0; $j--) {
4147: $courseinfo .= ':'.$current_items[$numcurrent-$j-1];
4148: }
4149: }
4150: }
4151: $hashref->{$key}=$courseinfo.':'.$now;
4152: }
4153: if (&untie_domain_hash($hashref)) {
4154: &Reply( $client, "ok\n", $userinput);
4155: } else {
4156: &Failure($client, "error: ".($!+0)
4157: ." untie(GDBM) Failed ".
4158: "while attempting courseidput\n", $userinput);
4159: }
4160: } else {
4161: &Failure($client, "error: ".($!+0)
4162: ." tie(GDBM) Failed ".
4163: "while attempting courseidput\n", $userinput);
4164: }
4165:
4166: return 1;
4167: }
4168: ®ister_handler("courseidput", \&put_course_id_handler, 0, 1, 0);
4169:
4170: sub put_course_id_hash_handler {
4171: my ($cmd, $tail, $client) = @_;
4172: my $userinput = "$cmd:$tail";
4173: my ($udom,$mode,$what) = split(/:/, $tail,3);
4174: chomp($what);
4175: my $now=time;
4176: my @pairs=split(/\&/,$what);
4177: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
4178: if ($hashref) {
4179: foreach my $pair (@pairs) {
4180: my ($key,$value)=split(/=/,$pair);
4181: my $unesc_key = &unescape($key);
4182: if ($mode ne 'timeonly') {
4183: if (!defined($hashref->{&escape('lasttime:'.$unesc_key)})) {
4184: my $curritems = &Apache::lonnet::thaw_unescape($key);
4185: if (ref($curritems) ne 'HASH') {
4186: my @current_items = split(/:/,$hashref->{$key},-1);
4187: my $lasttime = pop(@current_items);
4188: $hashref->{&escape('lasttime:'.$unesc_key)} = $lasttime;
4189: } else {
4190: $hashref->{&escape('lasttime:'.$unesc_key)} = '';
4191: }
4192: }
4193: $hashref->{$key} = $value;
4194: }
4195: if ($mode ne 'notime') {
4196: $hashref->{&escape('lasttime:'.$unesc_key)} = $now;
4197: }
4198: }
4199: if (&untie_domain_hash($hashref)) {
4200: &Reply($client, "ok\n", $userinput);
4201: } else {
4202: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4203: "while attempting courseidputhash\n", $userinput);
4204: }
4205: } else {
4206: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4207: "while attempting courseidputhash\n", $userinput);
4208: }
4209: return 1;
4210: }
4211: ®ister_handler("courseidputhash", \&put_course_id_hash_handler, 0, 1, 0);
4212:
4213: # Retrieves the value of a course id resource keyword pattern
4214: # defined since a starting date. Both the starting date and the
4215: # keyword pattern are optional. If the starting date is not supplied it
4216: # is treated as the beginning of time. If the pattern is not found,
4217: # it is treatred as "." matching everything.
4218: #
4219: # Parameters:
4220: # $cmd - Command keyword that resulted in us being dispatched.
4221: # $tail - The remainder of the command that, in this case, consists
4222: # of a colon separated list of:
4223: # domain - The domain in which the course database is
4224: # defined.
4225: # since - Optional parameter describing the minimum
4226: # time of definition(?) of the resources that
4227: # will match the dump.
4228: # description - regular expression that is used to filter
4229: # the dump. Only keywords matching this regexp
4230: # will be used.
4231: # institutional code - optional supplied code to filter
4232: # the dump. Only courses with an institutional code
4233: # that match the supplied code will be returned.
4234: # owner - optional supplied username and domain of owner to
4235: # filter the dump. Only courses for which the course
4236: # owner matches the supplied username and/or domain
4237: # will be returned. Pre-2.2.0 legacy entries from
4238: # nohist_courseiddump will only contain usernames.
4239: # type - optional parameter for selection
4240: # regexp_ok - if 1 or -1 allow the supplied institutional code
4241: # filter to behave as a regular expression:
4242: # 1 will not exclude the course if the instcode matches the RE
4243: # -1 will exclude the course if the instcode matches the RE
4244: # rtn_as_hash - whether to return the information available for
4245: # each matched item as a frozen hash of all
4246: # key, value pairs in the item's hash, or as a
4247: # colon-separated list of (in order) description,
4248: # institutional code, and course owner.
4249: # selfenrollonly - filter by courses allowing self-enrollment
4250: # now or in the future (selfenrollonly = 1).
4251: # catfilter - filter by course category, assigned to a course
4252: # using manually defined categories (i.e., not
4253: # self-cataloging based on on institutional code).
4254: # showhidden - include course in results even if course
4255: # was set to be excluded from course catalog (DC only).
4256: # caller - if set to 'coursecatalog', courses set to be hidden
4257: # from course catalog will be excluded from results (unless
4258: # overridden by "showhidden".
4259: # cloner - escaped username:domain of course cloner (if picking course to
4260: # clone).
4261: # cc_clone_list - escaped comma separated list of courses for which
4262: # course cloner has active CC role (and so can clone
4263: # automatically).
4264: # cloneonly - filter by courses for which cloner has rights to clone.
4265: # createdbefore - include courses for which creation date preceeded this date.
4266: # createdafter - include courses for which creation date followed this date.
4267: # creationcontext - include courses created in specified context
4268: #
4269: # domcloner - flag to indicate if user can create CCs in course's domain.
4270: # If so, ability to clone course is automatic.
4271: # hasuniquecode - filter by courses for which a six character unique code has
4272: # been set.
4273: #
4274: # $client - The socket open on the client.
4275: # Returns:
4276: # 1 - Continue processing.
4277: # Side Effects:
4278: # a reply is written to $client.
4279: sub dump_course_id_handler {
4280: my ($cmd, $tail, $client) = @_;
4281:
4282: my $res = LONCAPA::Lond::dump_course_id_handler($tail);
4283: if ($res =~ /^error:/) {
4284: Failure($client, \$res, "$cmd:$tail");
4285: } else {
4286: Reply($client, \$res, "$cmd:$tail");
4287: }
4288:
4289: return 1;
4290:
4291: #TODO remove
4292: my $userinput = "$cmd:$tail";
4293:
4294: my ($udom,$since,$description,$instcodefilter,$ownerfilter,$coursefilter,
4295: $typefilter,$regexp_ok,$rtn_as_hash,$selfenrollonly,$catfilter,$showhidden,
4296: $caller,$cloner,$cc_clone_list,$cloneonly,$createdbefore,$createdafter,
4297: $creationcontext,$domcloner,$hasuniquecode) =split(/:/,$tail);
4298: my $now = time;
4299: my ($cloneruname,$clonerudom,%cc_clone);
4300: if (defined($description)) {
4301: $description=&unescape($description);
4302: } else {
4303: $description='.';
4304: }
4305: if (defined($instcodefilter)) {
4306: $instcodefilter=&unescape($instcodefilter);
4307: } else {
4308: $instcodefilter='.';
4309: }
4310: my ($ownerunamefilter,$ownerdomfilter);
4311: if (defined($ownerfilter)) {
4312: $ownerfilter=&unescape($ownerfilter);
4313: if ($ownerfilter ne '.' && defined($ownerfilter)) {
4314: if ($ownerfilter =~ /^([^:]*):([^:]*)$/) {
4315: $ownerunamefilter = $1;
4316: $ownerdomfilter = $2;
4317: } else {
4318: $ownerunamefilter = $ownerfilter;
4319: $ownerdomfilter = '';
4320: }
4321: }
4322: } else {
4323: $ownerfilter='.';
4324: }
4325:
4326: if (defined($coursefilter)) {
4327: $coursefilter=&unescape($coursefilter);
4328: } else {
4329: $coursefilter='.';
4330: }
4331: if (defined($typefilter)) {
4332: $typefilter=&unescape($typefilter);
4333: } else {
4334: $typefilter='.';
4335: }
4336: if (defined($regexp_ok)) {
4337: $regexp_ok=&unescape($regexp_ok);
4338: }
4339: if (defined($catfilter)) {
4340: $catfilter=&unescape($catfilter);
4341: }
4342: if (defined($cloner)) {
4343: $cloner = &unescape($cloner);
4344: ($cloneruname,$clonerudom) = ($cloner =~ /^($LONCAPA::match_username):($LONCAPA::match_domain)$/);
4345: }
4346: if (defined($cc_clone_list)) {
4347: $cc_clone_list = &unescape($cc_clone_list);
4348: my @cc_cloners = split('&',$cc_clone_list);
4349: foreach my $cid (@cc_cloners) {
4350: my ($clonedom,$clonenum) = split(':',$cid);
4351: next if ($clonedom ne $udom);
4352: $cc_clone{$clonedom.'_'.$clonenum} = 1;
4353: }
4354: }
4355: if ($createdbefore ne '') {
4356: $createdbefore = &unescape($createdbefore);
4357: } else {
4358: $createdbefore = 0;
4359: }
4360: if ($createdafter ne '') {
4361: $createdafter = &unescape($createdafter);
4362: } else {
4363: $createdafter = 0;
4364: }
4365: if ($creationcontext ne '') {
4366: $creationcontext = &unescape($creationcontext);
4367: } else {
4368: $creationcontext = '.';
4369: }
4370: unless ($hasuniquecode) {
4371: $hasuniquecode = '.';
4372: }
4373: my $unpack = 1;
4374: if ($description eq '.' && $instcodefilter eq '.' && $ownerfilter eq '.' &&
4375: $typefilter eq '.') {
4376: $unpack = 0;
4377: }
4378: if (!defined($since)) { $since=0; }
4379: my $qresult='';
4380: my $hashref = &tie_domain_hash($udom, "nohist_courseids", &GDBM_WRCREAT());
4381: if ($hashref) {
4382: while (my ($key,$value) = each(%$hashref)) {
4383: my ($unesc_key,$lasttime_key,$lasttime,$is_hash,%val,
4384: %unesc_val,$selfenroll_end,$selfenroll_types,$created,
4385: $context);
4386: $unesc_key = &unescape($key);
4387: if ($unesc_key =~ /^lasttime:/) {
4388: next;
4389: } else {
4390: $lasttime_key = &escape('lasttime:'.$unesc_key);
4391: }
4392: if ($hashref->{$lasttime_key} ne '') {
4393: $lasttime = $hashref->{$lasttime_key};
4394: next if ($lasttime<$since);
4395: }
4396: my ($canclone,$valchange);
4397: my $items = &Apache::lonnet::thaw_unescape($value);
4398: if (ref($items) eq 'HASH') {
4399: if ($hashref->{$lasttime_key} eq '') {
4400: next if ($since > 1);
4401: }
4402: $is_hash = 1;
4403: if ($domcloner) {
4404: $canclone = 1;
4405: } elsif (defined($clonerudom)) {
4406: if ($items->{'cloners'}) {
4407: my @cloneable = split(',',$items->{'cloners'});
4408: if (@cloneable) {
4409: if (grep(/^\*$/,@cloneable)) {
4410: $canclone = 1;
4411: } elsif (grep(/^\*:\Q$clonerudom\E$/,@cloneable)) {
4412: $canclone = 1;
4413: } elsif (grep(/^\Q$cloneruname\E:\Q$clonerudom\E$/,@cloneable)) {
4414: $canclone = 1;
4415: }
4416: }
4417: unless ($canclone) {
4418: if ($cloneruname ne '' && $clonerudom ne '') {
4419: if ($cc_clone{$unesc_key}) {
4420: $canclone = 1;
4421: $items->{'cloners'} .= ','.$cloneruname.':'.
4422: $clonerudom;
4423: $valchange = 1;
4424: }
4425: }
4426: }
4427: } elsif (defined($cloneruname)) {
4428: if ($cc_clone{$unesc_key}) {
4429: $canclone = 1;
4430: $items->{'cloners'} = $cloneruname.':'.$clonerudom;
4431: $valchange = 1;
4432: }
4433: unless ($canclone) {
4434: if ($items->{'owner'} =~ /:/) {
4435: if ($items->{'owner'} eq $cloner) {
4436: $canclone = 1;
4437: }
4438: } elsif ($cloner eq $items->{'owner'}.':'.$udom) {
4439: $canclone = 1;
4440: }
4441: if ($canclone) {
4442: $items->{'cloners'} = $cloneruname.':'.$clonerudom;
4443: $valchange = 1;
4444: }
4445: }
4446: }
4447: }
4448: if ($unpack || !$rtn_as_hash) {
4449: $unesc_val{'descr'} = $items->{'description'};
4450: $unesc_val{'inst_code'} = $items->{'inst_code'};
4451: $unesc_val{'owner'} = $items->{'owner'};
4452: $unesc_val{'type'} = $items->{'type'};
4453: $unesc_val{'cloners'} = $items->{'cloners'};
4454: $unesc_val{'created'} = $items->{'created'};
4455: $unesc_val{'context'} = $items->{'context'};
4456: }
4457: $selfenroll_types = $items->{'selfenroll_types'};
4458: $selfenroll_end = $items->{'selfenroll_end_date'};
4459: $created = $items->{'created'};
4460: $context = $items->{'context'};
4461: if ($hasuniquecode ne '.') {
4462: next unless ($items->{'uniquecode'});
4463: }
4464: if ($selfenrollonly) {
4465: next if (!$selfenroll_types);
4466: if (($selfenroll_end > 0) && ($selfenroll_end <= $now)) {
4467: next;
4468: }
4469: }
4470: if ($creationcontext ne '.') {
4471: next if (($context ne '') && ($context ne $creationcontext));
4472: }
4473: if ($createdbefore > 0) {
4474: next if (($created eq '') || ($created > $createdbefore));
4475: }
4476: if ($createdafter > 0) {
4477: next if (($created eq '') || ($created <= $createdafter));
4478: }
4479: if ($catfilter ne '') {
4480: next if ($items->{'categories'} eq '');
4481: my @categories = split('&',$items->{'categories'});
4482: next if (@categories == 0);
4483: my @subcats = split('&',$catfilter);
4484: my $matchcat = 0;
4485: foreach my $cat (@categories) {
4486: if (grep(/^\Q$cat\E$/,@subcats)) {
4487: $matchcat = 1;
4488: last;
4489: }
4490: }
4491: next if (!$matchcat);
4492: }
4493: if ($caller eq 'coursecatalog') {
4494: if ($items->{'hidefromcat'} eq 'yes') {
4495: next if !$showhidden;
4496: }
4497: }
4498: } else {
4499: next if ($catfilter ne '');
4500: next if ($selfenrollonly);
4501: next if ($createdbefore || $createdafter);
4502: next if ($creationcontext ne '.');
4503: if ((defined($clonerudom)) && (defined($cloneruname))) {
4504: if ($cc_clone{$unesc_key}) {
4505: $canclone = 1;
4506: $val{'cloners'} = &escape($cloneruname.':'.$clonerudom);
4507: }
4508: }
4509: $is_hash = 0;
4510: my @courseitems = split(/:/,$value);
4511: $lasttime = pop(@courseitems);
4512: if ($hashref->{$lasttime_key} eq '') {
4513: next if ($lasttime<$since);
4514: }
4515: ($val{'descr'},$val{'inst_code'},$val{'owner'},$val{'type'}) = @courseitems;
4516: }
4517: if ($cloneonly) {
4518: next unless ($canclone);
4519: }
4520: my $match = 1;
4521: if ($description ne '.') {
4522: if (!$is_hash) {
4523: $unesc_val{'descr'} = &unescape($val{'descr'});
4524: }
4525: if (eval{$unesc_val{'descr'} !~ /\Q$description\E/i}) {
4526: $match = 0;
4527: }
4528: }
4529: if ($instcodefilter ne '.') {
4530: if (!$is_hash) {
4531: $unesc_val{'inst_code'} = &unescape($val{'inst_code'});
4532: }
4533: if ($regexp_ok == 1) {
4534: if (eval{$unesc_val{'inst_code'} !~ /$instcodefilter/}) {
4535: $match = 0;
4536: }
4537: } elsif ($regexp_ok == -1) {
4538: if (eval{$unesc_val{'inst_code'} =~ /$instcodefilter/}) {
4539: $match = 0;
4540: }
4541: } else {
4542: if (eval{$unesc_val{'inst_code'} !~ /\Q$instcodefilter\E/i}) {
4543: $match = 0;
4544: }
4545: }
4546: }
4547: if ($ownerfilter ne '.') {
4548: if (!$is_hash) {
4549: $unesc_val{'owner'} = &unescape($val{'owner'});
4550: }
4551: if (($ownerunamefilter ne '') && ($ownerdomfilter ne '')) {
4552: if ($unesc_val{'owner'} =~ /:/) {
4553: if (eval{$unesc_val{'owner'} !~
4554: /\Q$ownerunamefilter\E:\Q$ownerdomfilter\E$/i}) {
4555: $match = 0;
4556: }
4557: } else {
4558: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
4559: $match = 0;
4560: }
4561: }
4562: } elsif ($ownerunamefilter ne '') {
4563: if ($unesc_val{'owner'} =~ /:/) {
4564: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E:[^:]+$/i}) {
4565: $match = 0;
4566: }
4567: } else {
4568: if (eval{$unesc_val{'owner'} !~ /\Q$ownerunamefilter\E/i}) {
4569: $match = 0;
4570: }
4571: }
4572: } elsif ($ownerdomfilter ne '') {
4573: if ($unesc_val{'owner'} =~ /:/) {
4574: if (eval{$unesc_val{'owner'} !~ /^[^:]+:\Q$ownerdomfilter\E/}) {
4575: $match = 0;
4576: }
4577: } else {
4578: if ($ownerdomfilter ne $udom) {
4579: $match = 0;
4580: }
4581: }
4582: }
4583: }
4584: if ($coursefilter ne '.') {
4585: if (eval{$unesc_key !~ /^$udom(_)\Q$coursefilter\E$/}) {
4586: $match = 0;
4587: }
4588: }
4589: if ($typefilter ne '.') {
4590: if (!$is_hash) {
4591: $unesc_val{'type'} = &unescape($val{'type'});
4592: }
4593: if ($unesc_val{'type'} eq '') {
4594: if ($typefilter ne 'Course') {
4595: $match = 0;
4596: }
4597: } else {
4598: if (eval{$unesc_val{'type'} !~ /^\Q$typefilter\E$/}) {
4599: $match = 0;
4600: }
4601: }
4602: }
4603: if ($match == 1) {
4604: if ($rtn_as_hash) {
4605: if ($is_hash) {
4606: if ($valchange) {
4607: my $newvalue = &Apache::lonnet::freeze_escape($items);
4608: $qresult.=$key.'='.$newvalue.'&';
4609: } else {
4610: $qresult.=$key.'='.$value.'&';
4611: }
4612: } else {
4613: my %rtnhash = ( 'description' => &unescape($val{'descr'}),
4614: 'inst_code' => &unescape($val{'inst_code'}),
4615: 'owner' => &unescape($val{'owner'}),
4616: 'type' => &unescape($val{'type'}),
4617: 'cloners' => &unescape($val{'cloners'}),
4618: );
4619: my $items = &Apache::lonnet::freeze_escape(\%rtnhash);
4620: $qresult.=$key.'='.$items.'&';
4621: }
4622: } else {
4623: if ($is_hash) {
4624: $qresult .= $key.'='.&escape($unesc_val{'descr'}).':'.
4625: &escape($unesc_val{'inst_code'}).':'.
4626: &escape($unesc_val{'owner'}).'&';
4627: } else {
4628: $qresult .= $key.'='.$val{'descr'}.':'.$val{'inst_code'}.
4629: ':'.$val{'owner'}.'&';
4630: }
4631: }
4632: }
4633: }
4634: if (&untie_domain_hash($hashref)) {
4635: chop($qresult);
4636: &Reply($client, \$qresult, $userinput);
4637: } else {
4638: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4639: "while attempting courseiddump\n", $userinput);
4640: }
4641: } else {
4642: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4643: "while attempting courseiddump\n", $userinput);
4644: }
4645: return 1;
4646: }
4647: ®ister_handler("courseiddump", \&dump_course_id_handler, 0, 1, 0);
4648:
4649: sub course_lastaccess_handler {
4650: my ($cmd, $tail, $client) = @_;
4651: my $userinput = "$cmd:$tail";
4652: my ($cdom,$cnum) = split(':',$tail);
4653: my (%lastaccess,$qresult);
4654: my $hashref = &tie_domain_hash($cdom, "nohist_courseids", &GDBM_WRCREAT());
4655: if ($hashref) {
4656: while (my ($key,$value) = each(%$hashref)) {
4657: my ($unesc_key,$lasttime);
4658: $unesc_key = &unescape($key);
4659: if ($cnum) {
4660: next unless ($unesc_key =~ /\Q$cdom\E_\Q$cnum\E$/);
4661: }
4662: if ($unesc_key =~ /^lasttime:($LONCAPA::match_domain\_$LONCAPA::match_courseid)/) {
4663: $lastaccess{$1} = $value;
4664: } else {
4665: my $items = &Apache::lonnet::thaw_unescape($value);
4666: if (ref($items) eq 'HASH') {
4667: unless ($lastaccess{$unesc_key}) {
4668: $lastaccess{$unesc_key} = '';
4669: }
4670: } else {
4671: my @courseitems = split(':',$value);
4672: $lastaccess{$unesc_key} = pop(@courseitems);
4673: }
4674: }
4675: }
4676: foreach my $cid (sort(keys(%lastaccess))) {
4677: $qresult.=&escape($cid).'='.$lastaccess{$cid}.'&';
4678: }
4679: if (&untie_domain_hash($hashref)) {
4680: if ($qresult) {
4681: chop($qresult);
4682: }
4683: &Reply($client, \$qresult, $userinput);
4684: } else {
4685: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4686: "while attempting lastacourseaccess\n", $userinput);
4687: }
4688: } else {
4689: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4690: "while attempting lastcourseaccess\n", $userinput);
4691: }
4692: return 1;
4693: }
4694: ®ister_handler("courselastaccess",\&course_lastaccess_handler, 0, 1, 0);
4695:
4696: #
4697: # Puts an unencrypted entry in a namespace db file at the domain level
4698: #
4699: # Parameters:
4700: # $cmd - The command that got us here.
4701: # $tail - Tail of the command (remaining parameters).
4702: # $client - File descriptor connected to client.
4703: # Returns
4704: # 0 - Requested to exit, caller should shut down.
4705: # 1 - Continue processing.
4706: # Side effects:
4707: # reply is written to $client.
4708: #
4709: sub put_domain_handler {
4710: my ($cmd,$tail,$client) = @_;
4711:
4712: my $userinput = "$cmd:$tail";
4713:
4714: my ($udom,$namespace,$what) =split(/:/,$tail,3);
4715: chomp($what);
4716: my @pairs=split(/\&/,$what);
4717: my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_WRCREAT(),
4718: "P", $what);
4719: if ($hashref) {
4720: foreach my $pair (@pairs) {
4721: my ($key,$value)=split(/=/,$pair);
4722: $hashref->{$key}=$value;
4723: }
4724: if (&untie_domain_hash($hashref)) {
4725: &Reply($client, "ok\n", $userinput);
4726: } else {
4727: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4728: "while attempting putdom\n", $userinput);
4729: }
4730: } else {
4731: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4732: "while attempting putdom\n", $userinput);
4733: }
4734:
4735: return 1;
4736: }
4737: ®ister_handler("putdom", \&put_domain_handler, 0, 1, 0);
4738:
4739: # Updates one or more entries in clickers.db file at the domain level
4740: #
4741: # Parameters:
4742: # $cmd - The command that got us here.
4743: # $tail - Tail of the command (remaining parameters).
4744: # In this case a colon separated list containing:
4745: # (a) the domain for which we are updating the entries,
4746: # (b) the action required -- add or del -- and
4747: # (c) a &-separated list of entries to add or delete.
4748: # $client - File descriptor connected to client.
4749: # Returns
4750: # 1 - Continue processing.
4751: # 0 - Requested to exit, caller should shut down.
4752: # Side effects:
4753: # reply is written to $client.
4754: #
4755:
4756:
4757: sub update_clickers {
4758: my ($cmd, $tail, $client) = @_;
4759:
4760: my $userinput = "$cmd:$tail";
4761: my ($udom,$action,$what) =split(/:/,$tail,3);
4762: chomp($what);
4763:
4764: my $hashref = &tie_domain_hash($udom, "clickers", &GDBM_WRCREAT(),
4765: "U","$action:$what");
4766:
4767: if (!$hashref) {
4768: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4769: "while attempting updateclickers\n", $userinput);
4770: return 1;
4771: }
4772:
4773: my @pairs=split(/\&/,$what);
4774: foreach my $pair (@pairs) {
4775: my ($key,$value)=split(/=/,$pair);
4776: if ($action eq 'add') {
4777: if (exists($hashref->{$key})) {
4778: my @newvals = split(/,/,&unescape($value));
4779: my @currvals = split(/,/,&unescape($hashref->{$key}));
4780: my @merged = sort(keys(%{{map { $_ => 1 } (@newvals,@currvals)}}));
4781: $hashref->{$key}=&escape(join(',',@merged));
4782: } else {
4783: $hashref->{$key}=$value;
4784: }
4785: } elsif ($action eq 'del') {
4786: if (exists($hashref->{$key})) {
4787: my %current;
4788: map { $current{$_} = 1; } split(/,/,&unescape($hashref->{$key}));
4789: map { delete($current{$_}); } split(/,/,&unescape($value));
4790: if (keys(%current)) {
4791: $hashref->{$key}=&escape(join(',',sort(keys(%current))));
4792: } else {
4793: delete($hashref->{$key});
4794: }
4795: }
4796: }
4797: }
4798: if (&untie_user_hash($hashref)) {
4799: &Reply( $client, "ok\n", $userinput);
4800: } else {
4801: &Failure($client, "error: ".($!+0)." untie(GDBM) failed ".
4802: "while attempting put\n",
4803: $userinput);
4804: }
4805: return 1;
4806: }
4807: ®ister_handler("updateclickers", \&update_clickers, 0, 1, 0);
4808:
4809:
4810: # Deletes one or more entries in a namespace db file at the domain level
4811: #
4812: # Parameters:
4813: # $cmd - The command that got us here.
4814: # $tail - Tail of the command (remaining parameters).
4815: # In this case a colon separated list containing:
4816: # (a) the domain for which we are deleting the entries,
4817: # (b) &-separated list of keys to delete.
4818: # $client - File descriptor connected to client.
4819: # Returns
4820: # 1 - Continue processing.
4821: # 0 - Requested to exit, caller should shut down.
4822: # Side effects:
4823: # reply is written to $client.
4824: #
4825:
4826: sub del_domain_handler {
4827: my ($cmd,$tail,$client) = @_;
4828:
4829: my $userinput = "$cmd:$tail";
4830:
4831: my ($udom,$namespace,$what)=split(/:/,$tail,3);
4832: chomp($what);
4833: my $hashref = &tie_domain_hash($udom,$namespace,&GDBM_WRCREAT(),
4834: "D", $what);
4835: if ($hashref) {
4836: my @keys=split(/\&/,$what);
4837: foreach my $key (@keys) {
4838: delete($hashref->{$key});
4839: }
4840: if (&untie_user_hash($hashref)) {
4841: &Reply($client, "ok\n", $userinput);
4842: } else {
4843: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4844: "while attempting deldom\n", $userinput);
4845: }
4846: } else {
4847: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4848: "while attempting deldom\n", $userinput);
4849: }
4850: return 1;
4851: }
4852: ®ister_handler("deldom", \&del_domain_handler, 0, 1, 0);
4853:
4854:
4855: # Unencrypted get from the namespace database file at the domain level.
4856: # This function retrieves a keyed item from a specific named database in the
4857: # domain directory.
4858: #
4859: # Parameters:
4860: # $cmd - Command request keyword (get).
4861: # $tail - Tail of the command. This is a colon separated list
4862: # consisting of the domain and the 'namespace'
4863: # which selects the gdbm file to do the lookup in,
4864: # & separated list of keys to lookup. Note that
4865: # the values are returned as an & separated list too.
4866: # $client - File descriptor open on the client.
4867: # Returns:
4868: # 1 - Continue processing.
4869: # 0 - Exit.
4870: # Side effects:
4871: # reply is written to $client.
4872: #
4873:
4874: sub get_domain_handler {
4875: my ($cmd, $tail, $client) = @_;
4876:
4877:
4878: my $userinput = "$cmd:$tail";
4879:
4880: my ($udom,$namespace,$what)=split(/:/,$tail,3);
4881: chomp($what);
4882: if ($namespace =~ /^enc/) {
4883: &Failure( $client, "refused\n", $userinput);
4884: } else {
4885: my @queries=split(/\&/,$what);
4886: my $qresult='';
4887: my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
4888: if ($hashref) {
4889: for (my $i=0;$i<=$#queries;$i++) {
4890: $qresult.="$hashref->{$queries[$i]}&";
4891: }
4892: if (&untie_domain_hash($hashref)) {
4893: $qresult=~s/\&$//;
4894: &Reply($client, \$qresult, $userinput);
4895: } else {
4896: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
4897: "while attempting getdom\n",$userinput);
4898: }
4899: } else {
4900: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4901: "while attempting getdom\n",$userinput);
4902: }
4903: }
4904:
4905: return 1;
4906: }
4907: ®ister_handler("getdom", \&get_domain_handler, 0, 1, 0);
4908:
4909: sub encrypted_get_domain_handler {
4910: my ($cmd, $tail, $client) = @_;
4911:
4912: my $userinput = "$cmd:$tail";
4913:
4914: my ($udom,$namespace,$what)=split(/:/,$tail,3);
4915: chomp($what);
4916: my @queries=split(/\&/,$what);
4917: my $qresult='';
4918: my $hashref = &tie_domain_hash($udom, "$namespace", &GDBM_READER());
4919: if ($hashref) {
4920: for (my $i=0;$i<=$#queries;$i++) {
4921: $qresult.="$hashref->{$queries[$i]}&";
4922: }
4923: if (&untie_domain_hash($hashref)) {
4924: $qresult=~s/\&$//;
4925: if ($cipher) {
4926: my $cmdlength=length($qresult);
4927: $qresult.=" ";
4928: my $encqresult='';
4929: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
4930: $encqresult.= unpack("H16",
4931: $cipher->encrypt(substr($qresult,
4932: $encidx,
4933: 8)));
4934: }
4935: &Reply( $client, "enc:$cmdlength:$encqresult\n", $userinput);
4936: } else {
4937: &Failure( $client, "error:no_key\n", $userinput);
4938: }
4939: } else {
4940: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
4941: "while attempting egetdom\n",$userinput);
4942: }
4943: } else {
4944: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
4945: "while attempting egetdom\n",$userinput);
4946: }
4947: return 1;
4948: }
4949: ®ister_handler("egetdom", \&encrypted_get_domain_handler, 1, 1, 0);
4950:
4951: #
4952: # Puts an id to a domains id database.
4953: #
4954: # Parameters:
4955: # $cmd - The command that triggered us.
4956: # $tail - Remainder of the request other than the command. This is a
4957: # colon separated list containing:
4958: # $domain - The domain for which we are writing the id.
4959: # $pairs - The id info to write... this is and & separated list
4960: # of keyword=value.
4961: # $client - Socket open on the client.
4962: # Returns:
4963: # 1 - Continue processing.
4964: # Side effects:
4965: # reply is written to $client.
4966: #
4967: sub put_id_handler {
4968: my ($cmd,$tail,$client) = @_;
4969:
4970:
4971: my $userinput = "$cmd:$tail";
4972:
4973: my ($udom,$what)=split(/:/,$tail);
4974: chomp($what);
4975: my @pairs=split(/\&/,$what);
4976: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
4977: "P", $what);
4978: if ($hashref) {
4979: foreach my $pair (@pairs) {
4980: my ($key,$value)=split(/=/,$pair);
4981: $hashref->{$key}=$value;
4982: }
4983: if (&untie_domain_hash($hashref)) {
4984: &Reply($client, "ok\n", $userinput);
4985: } else {
4986: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
4987: "while attempting idput\n", $userinput);
4988: }
4989: } else {
4990: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
4991: "while attempting idput\n", $userinput);
4992: }
4993:
4994: return 1;
4995: }
4996: ®ister_handler("idput", \&put_id_handler, 0, 1, 0);
4997:
4998: #
4999: # Retrieves a set of id values from the id database.
5000: # Returns an & separated list of results, one for each requested id to the
5001: # client.
5002: #
5003: # Parameters:
5004: # $cmd - Command keyword that caused us to be dispatched.
5005: # $tail - Tail of the command. Consists of a colon separated:
5006: # domain - the domain whose id table we dump
5007: # ids Consists of an & separated list of
5008: # id keywords whose values will be fetched.
5009: # nonexisting keywords will have an empty value.
5010: # $client - Socket open on the client.
5011: #
5012: # Returns:
5013: # 1 - indicating processing should continue.
5014: # Side effects:
5015: # An & separated list of results is written to $client.
5016: #
5017: sub get_id_handler {
5018: my ($cmd, $tail, $client) = @_;
5019:
5020:
5021: my $userinput = "$client:$tail";
5022:
5023: my ($udom,$what)=split(/:/,$tail);
5024: chomp($what);
5025: my @queries=split(/\&/,$what);
5026: my $qresult='';
5027: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_READER());
5028: if ($hashref) {
5029: for (my $i=0;$i<=$#queries;$i++) {
5030: $qresult.="$hashref->{$queries[$i]}&";
5031: }
5032: if (&untie_domain_hash($hashref)) {
5033: $qresult=~s/\&$//;
5034: &Reply($client, \$qresult, $userinput);
5035: } else {
5036: &Failure( $client, "error: ".($!+0)." untie(GDBM) Failed ".
5037: "while attempting idget\n",$userinput);
5038: }
5039: } else {
5040: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5041: "while attempting idget\n",$userinput);
5042: }
5043:
5044: return 1;
5045: }
5046: ®ister_handler("idget", \&get_id_handler, 0, 1, 0);
5047:
5048: # Deletes one or more ids in a domain's id database.
5049: #
5050: # Parameters:
5051: # $cmd - Command keyword (iddel).
5052: # $tail - Command tail. In this case a colon
5053: # separated list containing:
5054: # The domain for which we are deleting the id(s).
5055: # &-separated list of id(s) to delete.
5056: # $client - File open on client socket.
5057: # Returns:
5058: # 1 - Continue processing
5059: # 0 - Exit server.
5060: #
5061: #
5062:
5063: sub del_id_handler {
5064: my ($cmd,$tail,$client) = @_;
5065:
5066: my $userinput = "$cmd:$tail";
5067:
5068: my ($udom,$what)=split(/:/,$tail);
5069: chomp($what);
5070: my $hashref = &tie_domain_hash($udom, "ids", &GDBM_WRCREAT(),
5071: "D", $what);
5072: if ($hashref) {
5073: my @keys=split(/\&/,$what);
5074: foreach my $key (@keys) {
5075: delete($hashref->{$key});
5076: }
5077: if (&untie_user_hash($hashref)) {
5078: &Reply($client, "ok\n", $userinput);
5079: } else {
5080: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5081: "while attempting iddel\n", $userinput);
5082: }
5083: } else {
5084: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5085: "while attempting iddel\n", $userinput);
5086: }
5087: return 1;
5088: }
5089: ®ister_handler("iddel", \&del_id_handler, 0, 1, 0);
5090:
5091: #
5092: # Puts broadcast e-mail sent by Domain Coordinator in nohist_dcmail database
5093: #
5094: # Parameters
5095: # $cmd - Command keyword that caused us to be dispatched.
5096: # $tail - Tail of the command. Consists of a colon separated:
5097: # domain - the domain whose dcmail we are recording
5098: # email Consists of key=value pair
5099: # where key is unique msgid
5100: # and value is message (in XML)
5101: # $client - Socket open on the client.
5102: #
5103: # Returns:
5104: # 1 - indicating processing should continue.
5105: # Side effects
5106: # reply is written to $client.
5107: #
5108: sub put_dcmail_handler {
5109: my ($cmd,$tail,$client) = @_;
5110: my $userinput = "$cmd:$tail";
5111:
5112:
5113: my ($udom,$what)=split(/:/,$tail);
5114: chomp($what);
5115: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
5116: if ($hashref) {
5117: my ($key,$value)=split(/=/,$what);
5118: $hashref->{$key}=$value;
5119: }
5120: if (&untie_domain_hash($hashref)) {
5121: &Reply($client, "ok\n", $userinput);
5122: } else {
5123: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5124: "while attempting dcmailput\n", $userinput);
5125: }
5126: return 1;
5127: }
5128: ®ister_handler("dcmailput", \&put_dcmail_handler, 0, 1, 0);
5129:
5130: #
5131: # Retrieves broadcast e-mail from nohist_dcmail database
5132: # Returns to client an & separated list of key=value pairs,
5133: # where key is msgid and value is message information.
5134: #
5135: # Parameters
5136: # $cmd - Command keyword that caused us to be dispatched.
5137: # $tail - Tail of the command. Consists of a colon separated:
5138: # domain - the domain whose dcmail table we dump
5139: # startfilter - beginning of time window
5140: # endfilter - end of time window
5141: # sendersfilter - & separated list of username:domain
5142: # for senders to search for.
5143: # $client - Socket open on the client.
5144: #
5145: # Returns:
5146: # 1 - indicating processing should continue.
5147: # Side effects
5148: # reply (& separated list of msgid=messageinfo pairs) is
5149: # written to $client.
5150: #
5151: sub dump_dcmail_handler {
5152: my ($cmd, $tail, $client) = @_;
5153:
5154: my $userinput = "$cmd:$tail";
5155: my ($udom,$startfilter,$endfilter,$sendersfilter) = split(/:/,$tail);
5156: chomp($sendersfilter);
5157: my @senders = ();
5158: if (defined($startfilter)) {
5159: $startfilter=&unescape($startfilter);
5160: } else {
5161: $startfilter='.';
5162: }
5163: if (defined($endfilter)) {
5164: $endfilter=&unescape($endfilter);
5165: } else {
5166: $endfilter='.';
5167: }
5168: if (defined($sendersfilter)) {
5169: $sendersfilter=&unescape($sendersfilter);
5170: @senders = map { &unescape($_) } split(/\&/,$sendersfilter);
5171: }
5172:
5173: my $qresult='';
5174: my $hashref = &tie_domain_hash($udom, "nohist_dcmail", &GDBM_WRCREAT());
5175: if ($hashref) {
5176: while (my ($key,$value) = each(%$hashref)) {
5177: my $match = 1;
5178: my ($timestamp,$subj,$uname,$udom) =
5179: split(/:/,&unescape(&unescape($key)),5); # yes, twice really
5180: $subj = &unescape($subj);
5181: unless ($startfilter eq '.' || !defined($startfilter)) {
5182: if ($timestamp < $startfilter) {
5183: $match = 0;
5184: }
5185: }
5186: unless ($endfilter eq '.' || !defined($endfilter)) {
5187: if ($timestamp > $endfilter) {
5188: $match = 0;
5189: }
5190: }
5191: unless (@senders < 1) {
5192: unless (grep/^$uname:$udom$/,@senders) {
5193: $match = 0;
5194: }
5195: }
5196: if ($match == 1) {
5197: $qresult.=$key.'='.$value.'&';
5198: }
5199: }
5200: if (&untie_domain_hash($hashref)) {
5201: chop($qresult);
5202: &Reply($client, \$qresult, $userinput);
5203: } else {
5204: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5205: "while attempting dcmaildump\n", $userinput);
5206: }
5207: } else {
5208: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5209: "while attempting dcmaildump\n", $userinput);
5210: }
5211: return 1;
5212: }
5213:
5214: ®ister_handler("dcmaildump", \&dump_dcmail_handler, 0, 1, 0);
5215:
5216: #
5217: # Puts domain roles in nohist_domainroles database
5218: #
5219: # Parameters
5220: # $cmd - Command keyword that caused us to be dispatched.
5221: # $tail - Tail of the command. Consists of a colon separated:
5222: # domain - the domain whose roles we are recording
5223: # role - Consists of key=value pair
5224: # where key is unique role
5225: # and value is start/end date information
5226: # $client - Socket open on the client.
5227: #
5228: # Returns:
5229: # 1 - indicating processing should continue.
5230: # Side effects
5231: # reply is written to $client.
5232: #
5233:
5234: sub put_domainroles_handler {
5235: my ($cmd,$tail,$client) = @_;
5236:
5237: my $userinput = "$cmd:$tail";
5238: my ($udom,$what)=split(/:/,$tail);
5239: chomp($what);
5240: my @pairs=split(/\&/,$what);
5241: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
5242: if ($hashref) {
5243: foreach my $pair (@pairs) {
5244: my ($key,$value)=split(/=/,$pair);
5245: $hashref->{$key}=$value;
5246: }
5247: if (&untie_domain_hash($hashref)) {
5248: &Reply($client, "ok\n", $userinput);
5249: } else {
5250: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5251: "while attempting domroleput\n", $userinput);
5252: }
5253: } else {
5254: &Failure( $client, "error: ".($!+0)." tie(GDBM) Failed ".
5255: "while attempting domroleput\n", $userinput);
5256: }
5257:
5258: return 1;
5259: }
5260:
5261: ®ister_handler("domroleput", \&put_domainroles_handler, 0, 1, 0);
5262:
5263: #
5264: # Retrieves domain roles from nohist_domainroles database
5265: # Returns to client an & separated list of key=value pairs,
5266: # where key is role and value is start and end date information.
5267: #
5268: # Parameters
5269: # $cmd - Command keyword that caused us to be dispatched.
5270: # $tail - Tail of the command. Consists of a colon separated:
5271: # domain - the domain whose domain roles table we dump
5272: # $client - Socket open on the client.
5273: #
5274: # Returns:
5275: # 1 - indicating processing should continue.
5276: # Side effects
5277: # reply (& separated list of role=start/end info pairs) is
5278: # written to $client.
5279: #
5280: sub dump_domainroles_handler {
5281: my ($cmd, $tail, $client) = @_;
5282:
5283: my $userinput = "$cmd:$tail";
5284: my ($udom,$startfilter,$endfilter,$rolesfilter) = split(/:/,$tail);
5285: chomp($rolesfilter);
5286: my @roles = ();
5287: if (defined($startfilter)) {
5288: $startfilter=&unescape($startfilter);
5289: } else {
5290: $startfilter='.';
5291: }
5292: if (defined($endfilter)) {
5293: $endfilter=&unescape($endfilter);
5294: } else {
5295: $endfilter='.';
5296: }
5297: if (defined($rolesfilter)) {
5298: $rolesfilter=&unescape($rolesfilter);
5299: @roles = split(/\&/,$rolesfilter);
5300: }
5301:
5302: my $hashref = &tie_domain_hash($udom, "nohist_domainroles", &GDBM_WRCREAT());
5303: if ($hashref) {
5304: my $qresult = '';
5305: while (my ($key,$value) = each(%$hashref)) {
5306: my $match = 1;
5307: my ($end,$start) = split(/:/,&unescape($value));
5308: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,&unescape($key));
5309: unless (@roles < 1) {
5310: unless (grep/^\Q$trole\E$/,@roles) {
5311: $match = 0;
5312: next;
5313: }
5314: }
5315: unless ($startfilter eq '.' || !defined($startfilter)) {
5316: if ((defined($start)) && ($start >= $startfilter)) {
5317: $match = 0;
5318: next;
5319: }
5320: }
5321: unless ($endfilter eq '.' || !defined($endfilter)) {
5322: if ((defined($end)) && (($end > 0) && ($end <= $endfilter))) {
5323: $match = 0;
5324: next;
5325: }
5326: }
5327: if ($match == 1) {
5328: $qresult.=$key.'='.$value.'&';
5329: }
5330: }
5331: if (&untie_domain_hash($hashref)) {
5332: chop($qresult);
5333: &Reply($client, \$qresult, $userinput);
5334: } else {
5335: &Failure($client, "error: ".($!+0)." untie(GDBM) Failed ".
5336: "while attempting domrolesdump\n", $userinput);
5337: }
5338: } else {
5339: &Failure($client, "error: ".($!+0)." tie(GDBM) Failed ".
5340: "while attempting domrolesdump\n", $userinput);
5341: }
5342: return 1;
5343: }
5344:
5345: ®ister_handler("domrolesdump", \&dump_domainroles_handler, 0, 1, 0);
5346:
5347:
5348: # Process the tmpput command I'm not sure what this does.. Seems to
5349: # create a file in the lonDaemons/tmp directory of the form $id.tmp
5350: # where Id is the client's ip concatenated with a sequence number.
5351: # The file will contain some value that is passed in. Is this e.g.
5352: # a login token?
5353: #
5354: # Parameters:
5355: # $cmd - The command that got us dispatched.
5356: # $tail - The remainder of the request following $cmd:
5357: # In this case this will be the contents of the file.
5358: # $client - Socket connected to the client.
5359: # Returns:
5360: # 1 indicating processing can continue.
5361: # Side effects:
5362: # A file is created in the local filesystem.
5363: # A reply is sent to the client.
5364: sub tmp_put_handler {
5365: my ($cmd, $what, $client) = @_;
5366:
5367: my $userinput = "$cmd:$what"; # Reconstruct for logging.
5368:
5369: my ($record,$context) = split(/:/,$what);
5370: if ($context ne '') {
5371: chomp($context);
5372: $context = &unescape($context);
5373: }
5374: my ($id,$store);
5375: $tmpsnum++;
5376: if (($context eq 'resetpw') || ($context eq 'createaccount')) {
5377: $id = &md5_hex(&md5_hex(time.{}.rand().$$));
5378: } else {
5379: $id = $$.'_'.$clientip.'_'.$tmpsnum;
5380: }
5381: $id=~s/\W/\_/g;
5382: $record=~s/\n//g;
5383: my $execdir=$perlvar{'lonDaemons'};
5384: if ($store=IO::File->new(">$execdir/tmp/$id.tmp")) {
5385: print $store $record;
5386: close $store;
5387: &Reply($client, \$id, $userinput);
5388: } else {
5389: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
5390: "while attempting tmpput\n", $userinput);
5391: }
5392: return 1;
5393:
5394: }
5395: ®ister_handler("tmpput", \&tmp_put_handler, 0, 1, 0);
5396:
5397: # Processes the tmpget command. This command returns the contents
5398: # of a temporary resource file(?) created via tmpput.
5399: #
5400: # Paramters:
5401: # $cmd - Command that got us dispatched.
5402: # $id - Tail of the command, contain the id of the resource
5403: # we want to fetch.
5404: # $client - socket open on the client.
5405: # Return:
5406: # 1 - Inidcating processing can continue.
5407: # Side effects:
5408: # A reply is sent to the client.
5409: #
5410: sub tmp_get_handler {
5411: my ($cmd, $id, $client) = @_;
5412:
5413: my $userinput = "$cmd:$id";
5414:
5415:
5416: $id=~s/\W/\_/g;
5417: my $store;
5418: my $execdir=$perlvar{'lonDaemons'};
5419: if ($store=IO::File->new("$execdir/tmp/$id.tmp")) {
5420: my $reply=<$store>;
5421: &Reply( $client, \$reply, $userinput);
5422: close $store;
5423: } else {
5424: &Failure( $client, "error: ".($!+0)."IO::File->new Failed ".
5425: "while attempting tmpget\n", $userinput);
5426: }
5427:
5428: return 1;
5429: }
5430: ®ister_handler("tmpget", \&tmp_get_handler, 0, 1, 0);
5431:
5432: #
5433: # Process the tmpdel command. This command deletes a temp resource
5434: # created by the tmpput command.
5435: #
5436: # Parameters:
5437: # $cmd - Command that got us here.
5438: # $id - Id of the temporary resource created.
5439: # $client - socket open on the client process.
5440: #
5441: # Returns:
5442: # 1 - Indicating processing should continue.
5443: # Side Effects:
5444: # A file is deleted
5445: # A reply is sent to the client.
5446: sub tmp_del_handler {
5447: my ($cmd, $id, $client) = @_;
5448:
5449: my $userinput= "$cmd:$id";
5450:
5451: chomp($id);
5452: $id=~s/\W/\_/g;
5453: my $execdir=$perlvar{'lonDaemons'};
5454: if (unlink("$execdir/tmp/$id.tmp")) {
5455: &Reply($client, "ok\n", $userinput);
5456: } else {
5457: &Failure( $client, "error: ".($!+0)."Unlink tmp Failed ".
5458: "while attempting tmpdel\n", $userinput);
5459: }
5460:
5461: return 1;
5462:
5463: }
5464: ®ister_handler("tmpdel", \&tmp_del_handler, 0, 1, 0);
5465:
5466: #
5467: # Processes the setannounce command. This command
5468: # creates a file named announce.txt in the top directory of
5469: # the documentn root and sets its contents. The announce.txt file is
5470: # printed in its entirety at the LonCAPA login page. Note:
5471: # once the announcement.txt fileis created it cannot be deleted.
5472: # However, setting the contents of the file to empty removes the
5473: # announcement from the login page of loncapa so who cares.
5474: #
5475: # Parameters:
5476: # $cmd - The command that got us dispatched.
5477: # $announcement - The text of the announcement.
5478: # $client - Socket open on the client process.
5479: # Retunrns:
5480: # 1 - Indicating request processing should continue
5481: # Side Effects:
5482: # The file {DocRoot}/announcement.txt is created.
5483: # A reply is sent to $client.
5484: #
5485: sub set_announce_handler {
5486: my ($cmd, $announcement, $client) = @_;
5487:
5488: my $userinput = "$cmd:$announcement";
5489:
5490: chomp($announcement);
5491: $announcement=&unescape($announcement);
5492: if (my $store=IO::File->new('>'.$perlvar{'lonDocRoot'}.
5493: '/announcement.txt')) {
5494: print $store $announcement;
5495: close $store;
5496: &Reply($client, "ok\n", $userinput);
5497: } else {
5498: &Failure($client, "error: ".($!+0)."\n", $userinput);
5499: }
5500:
5501: return 1;
5502: }
5503: ®ister_handler("setannounce", \&set_announce_handler, 0, 1, 0);
5504:
5505: #
5506: # Return the version of the daemon. This can be used to determine
5507: # the compatibility of cross version installations or, alternatively to
5508: # simply know who's out of date and who isn't. Note that the version
5509: # is returned concatenated with the tail.
5510: # Parameters:
5511: # $cmd - the request that dispatched to us.
5512: # $tail - Tail of the request (client's version?).
5513: # $client - Socket open on the client.
5514: #Returns:
5515: # 1 - continue processing requests.
5516: # Side Effects:
5517: # Replies with version to $client.
5518: sub get_version_handler {
5519: my ($cmd, $tail, $client) = @_;
5520:
5521: my $userinput = $cmd.$tail;
5522:
5523: &Reply($client, &version($userinput)."\n", $userinput);
5524:
5525:
5526: return 1;
5527: }
5528: ®ister_handler("version", \&get_version_handler, 0, 1, 0);
5529:
5530: # Set the current host and domain. This is used to support
5531: # multihomed systems. Each IP of the system, or even separate daemons
5532: # on the same IP can be treated as handling a separate lonCAPA virtual
5533: # machine. This command selects the virtual lonCAPA. The client always
5534: # knows the right one since it is lonc and it is selecting the domain/system
5535: # from the hosts.tab file.
5536: # Parameters:
5537: # $cmd - Command that dispatched us.
5538: # $tail - Tail of the command (domain/host requested).
5539: # $socket - Socket open on the client.
5540: #
5541: # Returns:
5542: # 1 - Indicates the program should continue to process requests.
5543: # Side-effects:
5544: # The default domain/system context is modified for this daemon.
5545: # a reply is sent to the client.
5546: #
5547: sub set_virtual_host_handler {
5548: my ($cmd, $tail, $socket) = @_;
5549:
5550: my $userinput ="$cmd:$tail";
5551:
5552: &Reply($client, &sethost($userinput)."\n", $userinput);
5553:
5554:
5555: return 1;
5556: }
5557: ®ister_handler("sethost", \&set_virtual_host_handler, 0, 1, 0);
5558:
5559: # Process a request to exit:
5560: # - "bye" is sent to the client.
5561: # - The client socket is shutdown and closed.
5562: # - We indicate to the caller that we should exit.
5563: # Formal Parameters:
5564: # $cmd - The command that got us here.
5565: # $tail - Tail of the command (empty).
5566: # $client - Socket open on the tail.
5567: # Returns:
5568: # 0 - Indicating the program should exit!!
5569: #
5570: sub exit_handler {
5571: my ($cmd, $tail, $client) = @_;
5572:
5573: my $userinput = "$cmd:$tail";
5574:
5575: &logthis("Client $clientip ($clientname) hanging up: $userinput");
5576: &Reply($client, "bye\n", $userinput);
5577: $client->shutdown(2); # shutdown the socket forcibly.
5578: $client->close();
5579:
5580: return 0;
5581: }
5582: ®ister_handler("exit", \&exit_handler, 0,1,1);
5583: ®ister_handler("init", \&exit_handler, 0,1,1);
5584: ®ister_handler("quit", \&exit_handler, 0,1,1);
5585:
5586: # Determine if auto-enrollment is enabled.
5587: # Note that the original had what I believe to be a defect.
5588: # The original returned 0 if the requestor was not a registerd client.
5589: # It should return "refused".
5590: # Formal Parameters:
5591: # $cmd - The command that invoked us.
5592: # $tail - The tail of the command (Extra command parameters.
5593: # $client - The socket open on the client that issued the request.
5594: # Returns:
5595: # 1 - Indicating processing should continue.
5596: #
5597: sub enrollment_enabled_handler {
5598: my ($cmd, $tail, $client) = @_;
5599: my $userinput = $cmd.":".$tail; # For logging purposes.
5600:
5601:
5602: my ($cdom) = split(/:/, $tail, 2); # Domain we're asking about.
5603:
5604: my $outcome = &localenroll::run($cdom);
5605: &Reply($client, \$outcome, $userinput);
5606:
5607: return 1;
5608: }
5609: ®ister_handler("autorun", \&enrollment_enabled_handler, 0, 1, 0);
5610:
5611: #
5612: # Validate an institutional code used for a LON-CAPA course.
5613: #
5614: # Formal Parameters:
5615: # $cmd - The command request that got us dispatched.
5616: # $tail - The tail of the command. In this case,
5617: # this is a colon separated set of words that will be split
5618: # into:
5619: # $dom - The domain for which the check of
5620: # institutional course code will occur.
5621: #
5622: # $instcode - The institutional code for the course
5623: # being requested, or validated for rights
5624: # to request.
5625: #
5626: # $owner - The course requestor (who will be the
5627: # course owner, in the form username:domain
5628: #
5629: # $client - Socket open on the client.
5630: # Returns:
5631: # 1 - Indicating processing should continue.
5632: #
5633: sub validate_instcode_handler {
5634: my ($cmd, $tail, $client) = @_;
5635: my $userinput = "$cmd:$tail";
5636: my ($dom,$instcode,$owner) = split(/:/, $tail);
5637: $instcode = &unescape($instcode);
5638: $owner = &unescape($owner);
5639: my ($outcome,$description,$credits) =
5640: &localenroll::validate_instcode($dom,$instcode,$owner);
5641: my $result = &escape($outcome).'&'.&escape($description).'&'.
5642: &escape($credits);
5643: &Reply($client, \$result, $userinput);
5644:
5645: return 1;
5646: }
5647: ®ister_handler("autovalidateinstcode", \&validate_instcode_handler, 0, 1, 0);
5648:
5649: # Get the official sections for which auto-enrollment is possible.
5650: # Since the admin people won't know about 'unofficial sections'
5651: # we cannot auto-enroll on them.
5652: # Formal Parameters:
5653: # $cmd - The command request that got us dispatched here.
5654: # $tail - The remainder of the request. In our case this
5655: # will be split into:
5656: # $coursecode - The course name from the admin point of view.
5657: # $cdom - The course's domain(?).
5658: # $client - Socket open on the client.
5659: # Returns:
5660: # 1 - Indiciting processing should continue.
5661: #
5662: sub get_sections_handler {
5663: my ($cmd, $tail, $client) = @_;
5664: my $userinput = "$cmd:$tail";
5665:
5666: my ($coursecode, $cdom) = split(/:/, $tail);
5667: my @secs = &localenroll::get_sections($coursecode,$cdom);
5668: my $seclist = &escape(join(':',@secs));
5669:
5670: &Reply($client, \$seclist, $userinput);
5671:
5672:
5673: return 1;
5674: }
5675: ®ister_handler("autogetsections", \&get_sections_handler, 0, 1, 0);
5676:
5677: # Validate the owner of a new course section.
5678: #
5679: # Formal Parameters:
5680: # $cmd - Command that got us dispatched.
5681: # $tail - the remainder of the command. For us this consists of a
5682: # colon separated string containing:
5683: # $inst - Course Id from the institutions point of view.
5684: # $owner - Proposed owner of the course.
5685: # $cdom - Domain of the course (from the institutions
5686: # point of view?)..
5687: # $client - Socket open on the client.
5688: #
5689: # Returns:
5690: # 1 - Processing should continue.
5691: #
5692: sub validate_course_owner_handler {
5693: my ($cmd, $tail, $client) = @_;
5694: my $userinput = "$cmd:$tail";
5695: my ($inst_course_id, $owner, $cdom, $coowners) = split(/:/, $tail);
5696:
5697: $owner = &unescape($owner);
5698: $coowners = &unescape($coowners);
5699: my $outcome = &localenroll::new_course($inst_course_id,$owner,$cdom,$coowners);
5700: &Reply($client, \$outcome, $userinput);
5701:
5702:
5703:
5704: return 1;
5705: }
5706: ®ister_handler("autonewcourse", \&validate_course_owner_handler, 0, 1, 0);
5707:
5708: #
5709: # Validate a course section in the official schedule of classes
5710: # from the institutions point of view (part of autoenrollment).
5711: #
5712: # Formal Parameters:
5713: # $cmd - The command request that got us dispatched.
5714: # $tail - The tail of the command. In this case,
5715: # this is a colon separated set of words that will be split
5716: # into:
5717: # $inst_course_id - The course/section id from the
5718: # institutions point of view.
5719: # $cdom - The domain from the institutions
5720: # point of view.
5721: # $client - Socket open on the client.
5722: # Returns:
5723: # 1 - Indicating processing should continue.
5724: #
5725: sub validate_course_section_handler {
5726: my ($cmd, $tail, $client) = @_;
5727: my $userinput = "$cmd:$tail";
5728: my ($inst_course_id, $cdom) = split(/:/, $tail);
5729:
5730: my $outcome=&localenroll::validate_courseID($inst_course_id,$cdom);
5731: &Reply($client, \$outcome, $userinput);
5732:
5733:
5734: return 1;
5735: }
5736: ®ister_handler("autovalidatecourse", \&validate_course_section_handler, 0, 1, 0);
5737:
5738: #
5739: # Validate course owner's access to enrollment data for specific class section.
5740: #
5741: #
5742: # Formal Parameters:
5743: # $cmd - The command request that got us dispatched.
5744: # $tail - The tail of the command. In this case this is a colon separated
5745: # set of words that will be split into:
5746: # $inst_class - Institutional code for the specific class section
5747: # $courseowner - The escaped username:domain of the course owner
5748: # $cdom - The domain of the course from the institution's
5749: # point of view.
5750: # $client - The socket open on the client.
5751: # Returns:
5752: # 1 - continue processing.
5753: #
5754:
5755: sub validate_class_access_handler {
5756: my ($cmd, $tail, $client) = @_;
5757: my $userinput = "$cmd:$tail";
5758: my ($inst_class,$ownerlist,$cdom) = split(/:/, $tail);
5759: my $owners = &unescape($ownerlist);
5760: my $outcome;
5761: eval {
5762: local($SIG{__DIE__})='DEFAULT';
5763: $outcome=&localenroll::check_section($inst_class,$owners,$cdom);
5764: };
5765: &Reply($client,\$outcome, $userinput);
5766:
5767: return 1;
5768: }
5769: ®ister_handler("autovalidateclass_sec", \&validate_class_access_handler, 0, 1, 0);
5770:
5771: #
5772: # Create a password for a new LON-CAPA user added by auto-enrollment.
5773: # Only used for case where authentication method for new user is localauth
5774: #
5775: # Formal Parameters:
5776: # $cmd - The command request that got us dispatched.
5777: # $tail - The tail of the command. In this case this is a colon separated
5778: # set of words that will be split into:
5779: # $authparam - An authentication parameter (localauth parameter).
5780: # $cdom - The domain of the course from the institution's
5781: # point of view.
5782: # $client - The socket open on the client.
5783: # Returns:
5784: # 1 - continue processing.
5785: #
5786: sub create_auto_enroll_password_handler {
5787: my ($cmd, $tail, $client) = @_;
5788: my $userinput = "$cmd:$tail";
5789:
5790: my ($authparam, $cdom) = split(/:/, $userinput);
5791:
5792: my ($create_passwd,$authchk);
5793: ($authparam,
5794: $create_passwd,
5795: $authchk) = &localenroll::create_password($authparam,$cdom);
5796:
5797: &Reply($client, &escape($authparam.':'.$create_passwd.':'.$authchk)."\n",
5798: $userinput);
5799:
5800:
5801: return 1;
5802: }
5803: ®ister_handler("autocreatepassword", \&create_auto_enroll_password_handler,
5804: 0, 1, 0);
5805:
5806: sub auto_export_grades_handler {
5807: my ($cmd, $tail, $client) = @_;
5808: my $userinput = "$cmd:$tail";
5809: my ($cdom,$cnum,$info,$data) = split(/:/,$tail);
5810: my $inforef = &Apache::lonnet::thaw_unescape($info);
5811: my $dataref = &Apache::lonnet::thaw_unescape($data);
5812: my ($outcome,$result);;
5813: eval {
5814: local($SIG{__DIE__})='DEFAULT';
5815: my %rtnhash;
5816: $outcome=&localenroll::export_grades($cdom,$cnum,$inforef,$dataref,\%rtnhash);
5817: if ($outcome eq 'ok') {
5818: foreach my $key (keys(%rtnhash)) {
5819: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
5820: }
5821: $result =~ s/\&$//;
5822: }
5823: };
5824: if (!$@) {
5825: if ($outcome eq 'ok') {
5826: if ($cipher) {
5827: my $cmdlength=length($result);
5828: $result.=" ";
5829: my $encresult='';
5830: for (my $encidx=0;$encidx<=$cmdlength;$encidx+=8) {
5831: $encresult.= unpack("H16",
5832: $cipher->encrypt(substr($result,
5833: $encidx,
5834: 8)));
5835: }
5836: &Reply( $client, "enc:$cmdlength:$encresult\n", $userinput);
5837: } else {
5838: &Failure( $client, "error:no_key\n", $userinput);
5839: }
5840: } else {
5841: &Reply($client, "$outcome\n", $userinput);
5842: }
5843: } else {
5844: &Failure($client,"export_error\n",$userinput);
5845: }
5846: return 1;
5847: }
5848: ®ister_handler("autoexportgrades", \&auto_export_grades_handler,
5849: 1, 1, 0);
5850:
5851: # Retrieve and remove temporary files created by/during autoenrollment.
5852: #
5853: # Formal Parameters:
5854: # $cmd - The command that got us dispatched.
5855: # $tail - The tail of the command. In our case this is a colon
5856: # separated list that will be split into:
5857: # $filename - The name of the file to retrieve.
5858: # The filename is given as a path relative to
5859: # the LonCAPA temp file directory.
5860: # $client - Socket open on the client.
5861: #
5862: # Returns:
5863: # 1 - Continue processing.
5864: sub retrieve_auto_file_handler {
5865: my ($cmd, $tail, $client) = @_;
5866: my $userinput = "cmd:$tail";
5867:
5868: my ($filename) = split(/:/, $tail);
5869:
5870: my $source = $perlvar{'lonDaemons'}.'/tmp/'.$filename;
5871:
5872: if ($filename =~m{/\.\./}) {
5873: &Failure($client, "refused\n", $userinput);
5874: } elsif ($filename !~ /^$LONCAPA::match_domain\_$LONCAPA::match_courseid\_.+_classlist\.xml$/) {
5875: &Failure($client, "refused\n", $userinput);
5876: } elsif ( (-e $source) && ($filename ne '') ) {
5877: my $reply = '';
5878: if (open(my $fh,$source)) {
5879: while (<$fh>) {
5880: chomp($_);
5881: $_ =~ s/^\s+//g;
5882: $_ =~ s/\s+$//g;
5883: $reply .= $_;
5884: }
5885: close($fh);
5886: &Reply($client, &escape($reply)."\n", $userinput);
5887:
5888: # Does this have to be uncommented??!? (RF).
5889: #
5890: # unlink($source);
5891: } else {
5892: &Failure($client, "error\n", $userinput);
5893: }
5894: } else {
5895: &Failure($client, "error\n", $userinput);
5896: }
5897:
5898:
5899: return 1;
5900: }
5901: ®ister_handler("autoretrieve", \&retrieve_auto_file_handler, 0,1,0);
5902:
5903: sub crsreq_checks_handler {
5904: my ($cmd, $tail, $client) = @_;
5905: my $userinput = "$cmd:$tail";
5906: my $dom = $tail;
5907: my $result;
5908: my @reqtypes = ('official','unofficial','community','textbook','placement');
5909: eval {
5910: local($SIG{__DIE__})='DEFAULT';
5911: my %validations;
5912: my $response = &localenroll::crsreq_checks($dom,\@reqtypes,
5913: \%validations);
5914: if ($response eq 'ok') {
5915: foreach my $key (keys(%validations)) {
5916: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($validations{$key}).'&';
5917: }
5918: $result =~ s/\&$//;
5919: } else {
5920: $result = 'error';
5921: }
5922: };
5923: if (!$@) {
5924: &Reply($client, \$result, $userinput);
5925: } else {
5926: &Failure($client,"unknown_cmd\n",$userinput);
5927: }
5928: return 1;
5929: }
5930: ®ister_handler("autocrsreqchecks", \&crsreq_checks_handler, 0, 1, 0);
5931:
5932: sub validate_crsreq_handler {
5933: my ($cmd, $tail, $client) = @_;
5934: my $userinput = "$cmd:$tail";
5935: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$customdata) = split(/:/, $tail);
5936: $instcode = &unescape($instcode);
5937: $owner = &unescape($owner);
5938: $crstype = &unescape($crstype);
5939: $inststatuslist = &unescape($inststatuslist);
5940: $instcode = &unescape($instcode);
5941: $instseclist = &unescape($instseclist);
5942: my $custominfo = &Apache::lonnet::thaw_unescape($customdata);
5943: my $outcome;
5944: eval {
5945: local($SIG{__DIE__})='DEFAULT';
5946: $outcome = &localenroll::validate_crsreq($dom,$owner,$crstype,
5947: $inststatuslist,$instcode,
5948: $instseclist,$custominfo);
5949: };
5950: if (!$@) {
5951: &Reply($client, \$outcome, $userinput);
5952: } else {
5953: &Failure($client,"unknown_cmd\n",$userinput);
5954: }
5955: return 1;
5956: }
5957: ®ister_handler("autocrsreqvalidation", \&validate_crsreq_handler, 0, 1, 0);
5958:
5959: sub crsreq_update_handler {
5960: my ($cmd, $tail, $client) = @_;
5961: my $userinput = "$cmd:$tail";
5962: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,$code,
5963: $accessstart,$accessend,$infohashref) =
5964: split(/:/, $tail);
5965: $crstype = &unescape($crstype);
5966: $action = &unescape($action);
5967: $ownername = &unescape($ownername);
5968: $ownerdomain = &unescape($ownerdomain);
5969: $fullname = &unescape($fullname);
5970: $title = &unescape($title);
5971: $code = &unescape($code);
5972: $accessstart = &unescape($accessstart);
5973: $accessend = &unescape($accessend);
5974: my $incoming = &Apache::lonnet::thaw_unescape($infohashref);
5975: my ($result,$outcome);
5976: eval {
5977: local($SIG{__DIE__})='DEFAULT';
5978: my %rtnhash;
5979: $outcome = &localenroll::crsreq_updates($cdom,$cnum,$crstype,$action,
5980: $ownername,$ownerdomain,$fullname,
5981: $title,$code,$accessstart,$accessend,
5982: $incoming,\%rtnhash);
5983: if ($outcome eq 'ok') {
5984: my @posskeys = qw(createdweb createdmsg createdcustomized createdactions queuedweb queuedmsg formitems reviewweb validationjs onload javascript);
5985: foreach my $key (keys(%rtnhash)) {
5986: if (grep(/^\Q$key\E/,@posskeys)) {
5987: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rtnhash{$key}).'&';
5988: }
5989: }
5990: $result =~ s/\&$//;
5991: }
5992: };
5993: if (!$@) {
5994: if ($outcome eq 'ok') {
5995: &Reply($client, \$result, $userinput);
5996: } else {
5997: &Reply($client, "format_error\n", $userinput);
5998: }
5999: } else {
6000: &Failure($client,"unknown_cmd\n",$userinput);
6001: }
6002: return 1;
6003: }
6004: ®ister_handler("autocrsrequpdate", \&crsreq_update_handler, 0, 1, 0);
6005:
6006: #
6007: # Read and retrieve institutional code format (for support form).
6008: # Formal Parameters:
6009: # $cmd - Command that dispatched us.
6010: # $tail - Tail of the command. In this case it conatins
6011: # the course domain and the coursename.
6012: # $client - Socket open on the client.
6013: # Returns:
6014: # 1 - Continue processing.
6015: #
6016: sub get_institutional_code_format_handler {
6017: my ($cmd, $tail, $client) = @_;
6018: my $userinput = "$cmd:$tail";
6019:
6020: my $reply;
6021: my($cdom,$course) = split(/:/,$tail);
6022: my @pairs = split/\&/,$course;
6023: my %instcodes = ();
6024: my %codes = ();
6025: my @codetitles = ();
6026: my %cat_titles = ();
6027: my %cat_order = ();
6028: foreach (@pairs) {
6029: my ($key,$value) = split/=/,$_;
6030: $instcodes{&unescape($key)} = &unescape($value);
6031: }
6032: my $formatreply = &localenroll::instcode_format($cdom,
6033: \%instcodes,
6034: \%codes,
6035: \@codetitles,
6036: \%cat_titles,
6037: \%cat_order);
6038: if ($formatreply eq 'ok') {
6039: my $codes_str = &Apache::lonnet::hash2str(%codes);
6040: my $codetitles_str = &Apache::lonnet::array2str(@codetitles);
6041: my $cat_titles_str = &Apache::lonnet::hash2str(%cat_titles);
6042: my $cat_order_str = &Apache::lonnet::hash2str(%cat_order);
6043: &Reply($client,
6044: $codes_str.':'.$codetitles_str.':'.$cat_titles_str.':'
6045: .$cat_order_str."\n",
6046: $userinput);
6047: } else {
6048: # this else branch added by RF since if not ok, lonc will
6049: # hang waiting on reply until timeout.
6050: #
6051: &Reply($client, "format_error\n", $userinput);
6052: }
6053:
6054: return 1;
6055: }
6056: ®ister_handler("autoinstcodeformat",
6057: \&get_institutional_code_format_handler,0,1,0);
6058:
6059: sub get_institutional_defaults_handler {
6060: my ($cmd, $tail, $client) = @_;
6061: my $userinput = "$cmd:$tail";
6062:
6063: my $dom = $tail;
6064: my %defaults_hash;
6065: my @code_order;
6066: my $outcome;
6067: eval {
6068: local($SIG{__DIE__})='DEFAULT';
6069: $outcome = &localenroll::instcode_defaults($dom,\%defaults_hash,
6070: \@code_order);
6071: };
6072: if (!$@) {
6073: if ($outcome eq 'ok') {
6074: my $result='';
6075: while (my ($key,$value) = each(%defaults_hash)) {
6076: $result.=&escape($key).'='.&escape($value).'&';
6077: }
6078: $result .= 'code_order='.&escape(join('&',@code_order));
6079: &Reply($client,\$result,$userinput);
6080: } else {
6081: &Reply($client,"error\n", $userinput);
6082: }
6083: } else {
6084: &Failure($client,"unknown_cmd\n",$userinput);
6085: }
6086: }
6087: ®ister_handler("autoinstcodedefaults",
6088: \&get_institutional_defaults_handler,0,1,0);
6089:
6090: sub get_possible_instcodes_handler {
6091: my ($cmd, $tail, $client) = @_;
6092: my $userinput = "$cmd:$tail";
6093:
6094: my $reply;
6095: my $cdom = $tail;
6096: my (@codetitles,%cat_titles,%cat_order,@code_order);
6097: my $formatreply = &localenroll::possible_instcodes($cdom,
6098: \@codetitles,
6099: \%cat_titles,
6100: \%cat_order,
6101: \@code_order);
6102: if ($formatreply eq 'ok') {
6103: my $result = join('&',map {&escape($_);} (@codetitles)).':';
6104: $result .= join('&',map {&escape($_);} (@code_order)).':';
6105: foreach my $key (keys(%cat_titles)) {
6106: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_titles{$key}).'&';
6107: }
6108: $result =~ s/\&$//;
6109: $result .= ':';
6110: foreach my $key (keys(%cat_order)) {
6111: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($cat_order{$key}).'&';
6112: }
6113: $result =~ s/\&$//;
6114: &Reply($client,\$result,$userinput);
6115: } else {
6116: &Reply($client, "format_error\n", $userinput);
6117: }
6118: return 1;
6119: }
6120: ®ister_handler("autopossibleinstcodes",
6121: \&get_possible_instcodes_handler,0,1,0);
6122:
6123: sub get_institutional_user_rules {
6124: my ($cmd, $tail, $client) = @_;
6125: my $userinput = "$cmd:$tail";
6126: my $dom = &unescape($tail);
6127: my (%rules_hash,@rules_order);
6128: my $outcome;
6129: eval {
6130: local($SIG{__DIE__})='DEFAULT';
6131: $outcome = &localenroll::username_rules($dom,\%rules_hash,\@rules_order);
6132: };
6133: if (!$@) {
6134: if ($outcome eq 'ok') {
6135: my $result;
6136: foreach my $key (keys(%rules_hash)) {
6137: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6138: }
6139: $result =~ s/\&$//;
6140: $result .= ':';
6141: if (@rules_order > 0) {
6142: foreach my $item (@rules_order) {
6143: $result .= &escape($item).'&';
6144: }
6145: }
6146: $result =~ s/\&$//;
6147: &Reply($client,\$result,$userinput);
6148: } else {
6149: &Reply($client,"error\n", $userinput);
6150: }
6151: } else {
6152: &Failure($client,"unknown_cmd\n",$userinput);
6153: }
6154: }
6155: ®ister_handler("instuserrules",\&get_institutional_user_rules,0,1,0);
6156:
6157: sub get_institutional_id_rules {
6158: my ($cmd, $tail, $client) = @_;
6159: my $userinput = "$cmd:$tail";
6160: my $dom = &unescape($tail);
6161: my (%rules_hash,@rules_order);
6162: my $outcome;
6163: eval {
6164: local($SIG{__DIE__})='DEFAULT';
6165: $outcome = &localenroll::id_rules($dom,\%rules_hash,\@rules_order);
6166: };
6167: if (!$@) {
6168: if ($outcome eq 'ok') {
6169: my $result;
6170: foreach my $key (keys(%rules_hash)) {
6171: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6172: }
6173: $result =~ s/\&$//;
6174: $result .= ':';
6175: if (@rules_order > 0) {
6176: foreach my $item (@rules_order) {
6177: $result .= &escape($item).'&';
6178: }
6179: }
6180: $result =~ s/\&$//;
6181: &Reply($client,\$result,$userinput);
6182: } else {
6183: &Reply($client,"error\n", $userinput);
6184: }
6185: } else {
6186: &Failure($client,"unknown_cmd\n",$userinput);
6187: }
6188: }
6189: ®ister_handler("instidrules",\&get_institutional_id_rules,0,1,0);
6190:
6191: sub get_institutional_selfcreate_rules {
6192: my ($cmd, $tail, $client) = @_;
6193: my $userinput = "$cmd:$tail";
6194: my $dom = &unescape($tail);
6195: my (%rules_hash,@rules_order);
6196: my $outcome;
6197: eval {
6198: local($SIG{__DIE__})='DEFAULT';
6199: $outcome = &localenroll::selfcreate_rules($dom,\%rules_hash,\@rules_order);
6200: };
6201: if (!$@) {
6202: if ($outcome eq 'ok') {
6203: my $result;
6204: foreach my $key (keys(%rules_hash)) {
6205: $result .= &escape($key).'='.&Apache::lonnet::freeze_escape($rules_hash{$key}).'&';
6206: }
6207: $result =~ s/\&$//;
6208: $result .= ':';
6209: if (@rules_order > 0) {
6210: foreach my $item (@rules_order) {
6211: $result .= &escape($item).'&';
6212: }
6213: }
6214: $result =~ s/\&$//;
6215: &Reply($client,\$result,$userinput);
6216: } else {
6217: &Reply($client,"error\n", $userinput);
6218: }
6219: } else {
6220: &Failure($client,"unknown_cmd\n",$userinput);
6221: }
6222: }
6223: ®ister_handler("instemailrules",\&get_institutional_selfcreate_rules,0,1,0);
6224:
6225:
6226: sub institutional_username_check {
6227: my ($cmd, $tail, $client) = @_;
6228: my $userinput = "$cmd:$tail";
6229: my %rulecheck;
6230: my $outcome;
6231: my ($udom,$uname,@rules) = split(/:/,$tail);
6232: $udom = &unescape($udom);
6233: $uname = &unescape($uname);
6234: @rules = map {&unescape($_);} (@rules);
6235: eval {
6236: local($SIG{__DIE__})='DEFAULT';
6237: $outcome = &localenroll::username_check($udom,$uname,\@rules,\%rulecheck);
6238: };
6239: if (!$@) {
6240: if ($outcome eq 'ok') {
6241: my $result='';
6242: foreach my $key (keys(%rulecheck)) {
6243: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
6244: }
6245: &Reply($client,\$result,$userinput);
6246: } else {
6247: &Reply($client,"error\n", $userinput);
6248: }
6249: } else {
6250: &Failure($client,"unknown_cmd\n",$userinput);
6251: }
6252: }
6253: ®ister_handler("instrulecheck",\&institutional_username_check,0,1,0);
6254:
6255: sub institutional_id_check {
6256: my ($cmd, $tail, $client) = @_;
6257: my $userinput = "$cmd:$tail";
6258: my %rulecheck;
6259: my $outcome;
6260: my ($udom,$id,@rules) = split(/:/,$tail);
6261: $udom = &unescape($udom);
6262: $id = &unescape($id);
6263: @rules = map {&unescape($_);} (@rules);
6264: eval {
6265: local($SIG{__DIE__})='DEFAULT';
6266: $outcome = &localenroll::id_check($udom,$id,\@rules,\%rulecheck);
6267: };
6268: if (!$@) {
6269: if ($outcome eq 'ok') {
6270: my $result='';
6271: foreach my $key (keys(%rulecheck)) {
6272: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
6273: }
6274: &Reply($client,\$result,$userinput);
6275: } else {
6276: &Reply($client,"error\n", $userinput);
6277: }
6278: } else {
6279: &Failure($client,"unknown_cmd\n",$userinput);
6280: }
6281: }
6282: ®ister_handler("instidrulecheck",\&institutional_id_check,0,1,0);
6283:
6284: sub institutional_selfcreate_check {
6285: my ($cmd, $tail, $client) = @_;
6286: my $userinput = "$cmd:$tail";
6287: my %rulecheck;
6288: my $outcome;
6289: my ($udom,$email,@rules) = split(/:/,$tail);
6290: $udom = &unescape($udom);
6291: $email = &unescape($email);
6292: @rules = map {&unescape($_);} (@rules);
6293: eval {
6294: local($SIG{__DIE__})='DEFAULT';
6295: $outcome = &localenroll::selfcreate_check($udom,$email,\@rules,\%rulecheck);
6296: };
6297: if (!$@) {
6298: if ($outcome eq 'ok') {
6299: my $result='';
6300: foreach my $key (keys(%rulecheck)) {
6301: $result.=&escape($key).'='.&Apache::lonnet::freeze_escape($rulecheck{$key}).'&';
6302: }
6303: &Reply($client,\$result,$userinput);
6304: } else {
6305: &Reply($client,"error\n", $userinput);
6306: }
6307: } else {
6308: &Failure($client,"unknown_cmd\n",$userinput);
6309: }
6310: }
6311: ®ister_handler("instselfcreatecheck",\&institutional_selfcreate_check,0,1,0);
6312:
6313: # Get domain specific conditions for import of student photographs to a course
6314: #
6315: # Retrieves information from photo_permission subroutine in localenroll.
6316: # Returns outcome (ok) if no processing errors, and whether course owner is
6317: # required to accept conditions of use (yes/no).
6318: #
6319: #
6320: sub photo_permission_handler {
6321: my ($cmd, $tail, $client) = @_;
6322: my $userinput = "$cmd:$tail";
6323: my $cdom = $tail;
6324: my ($perm_reqd,$conditions);
6325: my $outcome;
6326: eval {
6327: local($SIG{__DIE__})='DEFAULT';
6328: $outcome = &localenroll::photo_permission($cdom,\$perm_reqd,
6329: \$conditions);
6330: };
6331: if (!$@) {
6332: &Reply($client, &escape($outcome.':'.$perm_reqd.':'. $conditions)."\n",
6333: $userinput);
6334: } else {
6335: &Failure($client,"unknown_cmd\n",$userinput);
6336: }
6337: return 1;
6338: }
6339: ®ister_handler("autophotopermission",\&photo_permission_handler,0,1,0);
6340:
6341: #
6342: # Checks if student photo is available for a user in the domain, in the user's
6343: # directory (in /userfiles/internal/studentphoto.jpg).
6344: # Uses localstudentphoto:fetch() to ensure there is an up to date copy of
6345: # the student's photo.
6346:
6347: sub photo_check_handler {
6348: my ($cmd, $tail, $client) = @_;
6349: my $userinput = "$cmd:$tail";
6350: my ($udom,$uname,$pid) = split(/:/,$tail);
6351: $udom = &unescape($udom);
6352: $uname = &unescape($uname);
6353: $pid = &unescape($pid);
6354: my $path=&propath($udom,$uname).'/userfiles/internal/';
6355: if (!-e $path) {
6356: &mkpath($path);
6357: }
6358: my $response;
6359: my $result = &localstudentphoto::fetch($udom,$uname,$pid,\$response);
6360: $result .= ':'.$response;
6361: &Reply($client, &escape($result)."\n",$userinput);
6362: return 1;
6363: }
6364: ®ister_handler("autophotocheck",\&photo_check_handler,0,1,0);
6365:
6366: #
6367: # Retrieve information from localenroll about whether to provide a button
6368: # for users who have enbled import of student photos to initiate an
6369: # update of photo files for registered students. Also include
6370: # comment to display alongside button.
6371:
6372: sub photo_choice_handler {
6373: my ($cmd, $tail, $client) = @_;
6374: my $userinput = "$cmd:$tail";
6375: my $cdom = &unescape($tail);
6376: my ($update,$comment);
6377: eval {
6378: local($SIG{__DIE__})='DEFAULT';
6379: ($update,$comment) = &localenroll::manager_photo_update($cdom);
6380: };
6381: if (!$@) {
6382: &Reply($client,&escape($update).':'.&escape($comment)."\n",$userinput);
6383: } else {
6384: &Failure($client,"unknown_cmd\n",$userinput);
6385: }
6386: return 1;
6387: }
6388: ®ister_handler("autophotochoice",\&photo_choice_handler,0,1,0);
6389:
6390: #
6391: # Gets a student's photo to exist (in the correct image type) in the user's
6392: # directory.
6393: # Formal Parameters:
6394: # $cmd - The command request that got us dispatched.
6395: # $tail - A colon separated set of words that will be split into:
6396: # $domain - student's domain
6397: # $uname - student username
6398: # $type - image type desired
6399: # $client - The socket open on the client.
6400: # Returns:
6401: # 1 - continue processing.
6402:
6403: sub student_photo_handler {
6404: my ($cmd, $tail, $client) = @_;
6405: my ($domain,$uname,$ext,$type) = split(/:/, $tail);
6406:
6407: my $path=&propath($domain,$uname). '/userfiles/internal/';
6408: my $filename = 'studentphoto.'.$ext;
6409: if ($type eq 'thumbnail') {
6410: $filename = 'studentphoto_tn.'.$ext;
6411: }
6412: if (-e $path.$filename) {
6413: &Reply($client,"ok\n","$cmd:$tail");
6414: return 1;
6415: }
6416: &mkpath($path);
6417: my $file;
6418: if ($type eq 'thumbnail') {
6419: eval {
6420: local($SIG{__DIE__})='DEFAULT';
6421: $file=&localstudentphoto::fetch_thumbnail($domain,$uname);
6422: };
6423: } else {
6424: $file=&localstudentphoto::fetch($domain,$uname);
6425: }
6426: if (!$file) {
6427: &Failure($client,"unavailable\n","$cmd:$tail");
6428: return 1;
6429: }
6430: if (!-e $path.$filename) { &convert_photo($file,$path.$filename); }
6431: if (-e $path.$filename) {
6432: &Reply($client,"ok\n","$cmd:$tail");
6433: return 1;
6434: }
6435: &Failure($client,"unable_to_convert\n","$cmd:$tail");
6436: return 1;
6437: }
6438: ®ister_handler("studentphoto", \&student_photo_handler, 0, 1, 0);
6439:
6440: sub inst_usertypes_handler {
6441: my ($cmd, $domain, $client) = @_;
6442: my $res;
6443: my $userinput = $cmd.":".$domain; # For logging purposes.
6444: my (%typeshash,@order,$result);
6445: eval {
6446: local($SIG{__DIE__})='DEFAULT';
6447: $result=&localenroll::inst_usertypes($domain,\%typeshash,\@order);
6448: };
6449: if ($result eq 'ok') {
6450: if (keys(%typeshash) > 0) {
6451: foreach my $key (keys(%typeshash)) {
6452: $res.=&escape($key).'='.&escape($typeshash{$key}).'&';
6453: }
6454: }
6455: $res=~s/\&$//;
6456: $res .= ':';
6457: if (@order > 0) {
6458: foreach my $item (@order) {
6459: $res .= &escape($item).'&';
6460: }
6461: }
6462: $res=~s/\&$//;
6463: }
6464: &Reply($client, \$res, $userinput);
6465: return 1;
6466: }
6467: ®ister_handler("inst_usertypes", \&inst_usertypes_handler, 0, 1, 0);
6468:
6469: # mkpath makes all directories for a file, expects an absolute path with a
6470: # file or a trailing / if just a dir is passed
6471: # returns 1 on success 0 on failure
6472: sub mkpath {
6473: my ($file)=@_;
6474: my @parts=split(/\//,$file,-1);
6475: my $now=$parts[0].'/'.$parts[1].'/'.$parts[2];
6476: for (my $i=3;$i<= ($#parts-1);$i++) {
6477: $now.='/'.$parts[$i];
6478: if (!-e $now) {
6479: if (!mkdir($now,0770)) { return 0; }
6480: }
6481: }
6482: return 1;
6483: }
6484:
6485: #---------------------------------------------------------------
6486: #
6487: # Getting, decoding and dispatching requests:
6488: #
6489: #
6490: # Get a Request:
6491: # Gets a Request message from the client. The transaction
6492: # is defined as a 'line' of text. We remove the new line
6493: # from the text line.
6494: #
6495: sub get_request {
6496: my $input = <$client>;
6497: chomp($input);
6498:
6499: &Debug("get_request: Request = $input\n");
6500:
6501: &status('Processing '.$clientname.':'.$input);
6502:
6503: return $input;
6504: }
6505: #---------------------------------------------------------------
6506: #
6507: # Process a request. This sub should shrink as each action
6508: # gets farmed out into a separat sub that is registered
6509: # with the dispatch hash.
6510: #
6511: # Parameters:
6512: # user_input - The request received from the client (lonc).
6513: #
6514: # Returns:
6515: # true to keep processing, false if caller should exit.
6516: #
6517: sub process_request {
6518: my ($userinput) = @_; # Easier for now to break style than to
6519: # fix all the userinput -> user_input.
6520: my $wasenc = 0; # True if request was encrypted.
6521: # ------------------------------------------------------------ See if encrypted
6522: # for command
6523: # sethost:<server>
6524: # <command>:<args>
6525: # we just send it to the processor
6526: # for
6527: # sethost:<server>:<command>:<args>
6528: # we do the implict set host and then do the command
6529: if ($userinput =~ /^sethost:/) {
6530: (my $cmd,my $newid,$userinput) = split(':',$userinput,3);
6531: if (defined($userinput)) {
6532: &sethost("$cmd:$newid");
6533: } else {
6534: $userinput = "$cmd:$newid";
6535: }
6536: }
6537:
6538: if ($userinput =~ /^enc/) {
6539: $userinput = decipher($userinput);
6540: $wasenc=1;
6541: if(!$userinput) { # Cipher not defined.
6542: &Failure($client, "error: Encrypted data without negotated key\n");
6543: return 0;
6544: }
6545: }
6546: Debug("process_request: $userinput\n");
6547:
6548: #
6549: # The 'correct way' to add a command to lond is now to
6550: # write a sub to execute it and Add it to the command dispatch
6551: # hash via a call to register_handler.. The comments to that
6552: # sub should give you enough to go on to show how to do this
6553: # along with the examples that are building up as this code
6554: # is getting refactored. Until all branches of the
6555: # if/elseif monster below have been factored out into
6556: # separate procesor subs, if the dispatch hash is missing
6557: # the command keyword, we will fall through to the remainder
6558: # of the if/else chain below in order to keep this thing in
6559: # working order throughout the transmogrification.
6560:
6561: my ($command, $tail) = split(/:/, $userinput, 2);
6562: chomp($command);
6563: chomp($tail);
6564: $tail =~ s/(\r)//; # This helps people debugging with e.g. telnet.
6565: $command =~ s/(\r)//; # And this too for parameterless commands.
6566: if(!$tail) {
6567: $tail =""; # defined but blank.
6568: }
6569:
6570: &Debug("Command received: $command, encoded = $wasenc");
6571:
6572: if(defined $Dispatcher{$command}) {
6573:
6574: my $dispatch_info = $Dispatcher{$command};
6575: my $handler = $$dispatch_info[0];
6576: my $need_encode = $$dispatch_info[1];
6577: my $client_types = $$dispatch_info[2];
6578: Debug("Matched dispatch hash: mustencode: $need_encode "
6579: ."ClientType $client_types");
6580:
6581: # Validate the request:
6582:
6583: my $ok = 1;
6584: my $requesterprivs = 0;
6585: if(&isClient()) {
6586: $requesterprivs |= $CLIENT_OK;
6587: }
6588: if(&isManager()) {
6589: $requesterprivs |= $MANAGER_OK;
6590: }
6591: if($need_encode && (!$wasenc)) {
6592: Debug("Must encode but wasn't: $need_encode $wasenc");
6593: $ok = 0;
6594: }
6595: if(($client_types & $requesterprivs) == 0) {
6596: Debug("Client not privileged to do this operation");
6597: $ok = 0;
6598: }
6599: if ($ok) {
6600: my $realcommand = $command;
6601: if ($command eq 'querysend') {
6602: my ($query,$rest)=split(/\:/,$tail,2);
6603: $query=~s/\n*$//g;
6604: my @possqueries =
6605: qw(userlog courselog fetchenrollment institutionalphotos usersearch instdirsearch getinstuser getmultinstusers);
6606: if (grep(/^\Q$query\E$/,@possqueries)) {
6607: $command .= '_'.$query;
6608: } elsif ($query eq 'prepare activity log') {
6609: $command .= '_activitylog';
6610: }
6611: }
6612: if (ref($trust{$command}) eq 'HASH') {
6613: my $donechecks;
6614: if ($trust{$command}{'anywhere'}) {
6615: $donechecks = 1;
6616: } elsif ($trust{$command}{'manageronly'}) {
6617: unless (&isManager()) {
6618: $ok = 0;
6619: }
6620: $donechecks = 1;
6621: } elsif ($trust{$command}{'institutiononly'}) {
6622: unless ($clientsameinst) {
6623: $ok = 0;
6624: }
6625: $donechecks = 1;
6626: } elsif ($clientsameinst) {
6627: $donechecks = 1;
6628: }
6629: unless ($donechecks) {
6630: foreach my $rule (keys(%{$trust{$command}})) {
6631: next if ($rule eq 'remote');
6632: if ($trust{$command}{$rule}) {
6633: if ($clientprohibited{$rule}) {
6634: $ok = 0;
6635: } else {
6636: $ok = 1;
6637: $donechecks = 1;
6638: last;
6639: }
6640: }
6641: }
6642: }
6643: unless ($donechecks) {
6644: if ($trust{$command}{'remote'}) {
6645: if ($clientremoteok) {
6646: $ok = 1;
6647: } else {
6648: $ok = 0;
6649: }
6650: }
6651: }
6652: }
6653: $command = $realcommand;
6654: }
6655:
6656: if($ok) {
6657: Debug("Dispatching to handler $command $tail");
6658: my $keep_going = &$handler($command, $tail, $client);
6659: return $keep_going;
6660: } else {
6661: Debug("Refusing to dispatch because client did not match requirements");
6662: Failure($client, "refused\n", $userinput);
6663: return 1;
6664: }
6665: }
6666:
6667: print $client "unknown_cmd\n";
6668: # -------------------------------------------------------------------- complete
6669: Debug("process_request - returning 1");
6670: return 1;
6671: }
6672: #
6673: # Decipher encoded traffic
6674: # Parameters:
6675: # input - Encoded data.
6676: # Returns:
6677: # Decoded data or undef if encryption key was not yet negotiated.
6678: # Implicit input:
6679: # cipher - This global holds the negotiated encryption key.
6680: #
6681: sub decipher {
6682: my ($input) = @_;
6683: my $output = '';
6684:
6685:
6686: if($cipher) {
6687: my($enc, $enclength, $encinput) = split(/:/, $input);
6688: for(my $encidx = 0; $encidx < length($encinput); $encidx += 16) {
6689: $output .=
6690: $cipher->decrypt(pack("H16", substr($encinput, $encidx, 16)));
6691: }
6692: return substr($output, 0, $enclength);
6693: } else {
6694: return undef;
6695: }
6696: }
6697:
6698: #
6699: # Register a command processor. This function is invoked to register a sub
6700: # to process a request. Once registered, the ProcessRequest sub can automatically
6701: # dispatch requests to an appropriate sub, and do the top level validity checking
6702: # as well:
6703: # - Is the keyword recognized.
6704: # - Is the proper client type attempting the request.
6705: # - Is the request encrypted if it has to be.
6706: # Parameters:
6707: # $request_name - Name of the request being registered.
6708: # This is the command request that will match
6709: # against the hash keywords to lookup the information
6710: # associated with the dispatch information.
6711: # $procedure - Reference to a sub to call to process the request.
6712: # All subs get called as follows:
6713: # Procedure($cmd, $tail, $replyfd, $key)
6714: # $cmd - the actual keyword that invoked us.
6715: # $tail - the tail of the request that invoked us.
6716: # $replyfd- File descriptor connected to the client
6717: # $must_encode - True if the request must be encoded to be good.
6718: # $client_ok - True if it's ok for a client to request this.
6719: # $manager_ok - True if it's ok for a manager to request this.
6720: # Side effects:
6721: # - On success, the Dispatcher hash has an entry added for the key $RequestName
6722: # - On failure, the program will die as it's a bad internal bug to try to
6723: # register a duplicate command handler.
6724: #
6725: sub register_handler {
6726: my ($request_name,$procedure,$must_encode, $client_ok,$manager_ok) = @_;
6727:
6728: # Don't allow duplication#
6729:
6730: if (defined $Dispatcher{$request_name}) {
6731: die "Attempting to define a duplicate request handler for $request_name\n";
6732: }
6733: # Build the client type mask:
6734:
6735: my $client_type_mask = 0;
6736: if($client_ok) {
6737: $client_type_mask |= $CLIENT_OK;
6738: }
6739: if($manager_ok) {
6740: $client_type_mask |= $MANAGER_OK;
6741: }
6742:
6743: # Enter the hash:
6744:
6745: my @entry = ($procedure, $must_encode, $client_type_mask);
6746:
6747: $Dispatcher{$request_name} = \@entry;
6748:
6749: }
6750:
6751:
6752: #------------------------------------------------------------------
6753:
6754:
6755:
6756:
6757: #
6758: # Convert an error return code from lcpasswd to a string value.
6759: #
6760: sub lcpasswdstrerror {
6761: my $ErrorCode = shift;
6762: if(($ErrorCode < 0) || ($ErrorCode > $lastpwderror)) {
6763: return "lcpasswd Unrecognized error return value ".$ErrorCode;
6764: } else {
6765: return $passwderrors[$ErrorCode];
6766: }
6767: }
6768:
6769: # grabs exception and records it to log before exiting
6770: sub catchexception {
6771: my ($error)=@_;
6772: $SIG{'QUIT'}='DEFAULT';
6773: $SIG{__DIE__}='DEFAULT';
6774: &status("Catching exception");
6775: &logthis("<font color='red'>CRITICAL: "
6776: ."ABNORMAL EXIT. Child $$ for server ".$perlvar{'lonHostID'}." died through "
6777: ."a crash with this error msg->[$error]</font>");
6778: &logthis('Famous last words: '.$status.' - '.$lastlog);
6779: if ($client) { print $client "error: $error\n"; }
6780: $server->close();
6781: die($error);
6782: }
6783: sub timeout {
6784: &status("Handling Timeout");
6785: &logthis("<font color='red'>CRITICAL: TIME OUT ".$$."</font>");
6786: &catchexception('Timeout');
6787: }
6788: # -------------------------------- Set signal handlers to record abnormal exits
6789:
6790:
6791: $SIG{'QUIT'}=\&catchexception;
6792: $SIG{__DIE__}=\&catchexception;
6793:
6794: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
6795: &status("Read loncapa.conf and loncapa_apache.conf");
6796: my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
6797: %perlvar=%{$perlvarref};
6798: undef $perlvarref;
6799:
6800: # ----------------------------- Make sure this process is running from user=www
6801: my $wwwid=getpwnam('www');
6802: if ($wwwid!=$<) {
6803: my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
6804: my $subj="LON: $currenthostid User ID mismatch";
6805: system("echo 'User ID mismatch. lond must be run as user www.' |\
6806: mailto $emailto -s '$subj' > /dev/null");
6807: exit 1;
6808: }
6809:
6810: # --------------------------------------------- Check if other instance running
6811:
6812: my $pidfile="$perlvar{'lonDaemons'}/logs/lond.pid";
6813:
6814: if (-e $pidfile) {
6815: my $lfh=IO::File->new("$pidfile");
6816: my $pide=<$lfh>;
6817: chomp($pide);
6818: if (kill 0 => $pide) { die "already running"; }
6819: }
6820:
6821: # ------------------------------------------------------------- Read hosts file
6822:
6823:
6824:
6825: # establish SERVER socket, bind and listen.
6826: $server = IO::Socket::INET->new(LocalPort => $perlvar{'londPort'},
6827: Type => SOCK_STREAM,
6828: Proto => 'tcp',
6829: ReuseAddr => 1,
6830: Listen => 10 )
6831: or die "making socket: $@\n";
6832:
6833: # --------------------------------------------------------- Do global variables
6834:
6835: # global variables
6836:
6837: my %children = (); # keys are current child process IDs
6838:
6839: sub REAPER { # takes care of dead children
6840: $SIG{CHLD} = \&REAPER;
6841: &status("Handling child death");
6842: my $pid;
6843: do {
6844: $pid = waitpid(-1,&WNOHANG());
6845: if (defined($children{$pid})) {
6846: &logthis("Child $pid died");
6847: delete($children{$pid});
6848: } elsif ($pid > 0) {
6849: &logthis("Unknown Child $pid died");
6850: }
6851: } while ( $pid > 0 );
6852: foreach my $child (keys(%children)) {
6853: $pid = waitpid($child,&WNOHANG());
6854: if ($pid > 0) {
6855: &logthis("Child $child - $pid looks like we missed it's death");
6856: delete($children{$pid});
6857: }
6858: }
6859: &status("Finished Handling child death");
6860: }
6861:
6862: sub HUNTSMAN { # signal handler for SIGINT
6863: &status("Killing children (INT)");
6864: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
6865: kill 'INT' => keys %children;
6866: &logthis("Free socket: ".shutdown($server,2)); # free up socket
6867: my $execdir=$perlvar{'lonDaemons'};
6868: unlink("$execdir/logs/lond.pid");
6869: &logthis("<font color='red'>CRITICAL: Shutting down</font>");
6870: &status("Done killing children");
6871: exit; # clean up with dignity
6872: }
6873:
6874: sub HUPSMAN { # signal handler for SIGHUP
6875: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
6876: &status("Killing children for restart (HUP)");
6877: kill 'INT' => keys %children;
6878: &logthis("Free socket: ".shutdown($server,2)); # free up socket
6879: &logthis("<font color='red'>CRITICAL: Restarting</font>");
6880: my $execdir=$perlvar{'lonDaemons'};
6881: unlink("$execdir/logs/lond.pid");
6882: &status("Restarting self (HUP)");
6883: exec("$execdir/lond"); # here we go again
6884: }
6885:
6886: #
6887: # Reload the Apache daemon's state.
6888: # This is done by invoking /home/httpd/perl/apachereload
6889: # a setuid perl script that can be root for us to do this job.
6890: #
6891: sub ReloadApache {
6892: # --------------------------- Handle case of another apachereload process (locking)
6893: if (&LONCAPA::try_to_lock('/tmp/lock_apachereload')) {
6894: my $execdir = $perlvar{'lonDaemons'};
6895: my $script = $execdir."/apachereload";
6896: system($script);
6897: unlink('/tmp/lock_apachereload'); # Remove the lock file.
6898: }
6899: }
6900:
6901: #
6902: # Called in response to a USR2 signal.
6903: # - Reread hosts.tab
6904: # - All children connected to hosts that were removed from hosts.tab
6905: # are killed via SIGINT
6906: # - All children connected to previously existing hosts are sent SIGUSR1
6907: # - Our internal hosts hash is updated to reflect the new contents of
6908: # hosts.tab causing connections from hosts added to hosts.tab to
6909: # now be honored.
6910: #
6911: sub UpdateHosts {
6912: &status("Reload hosts.tab");
6913: logthis('<font color="blue"> Updating connections </font>');
6914: #
6915: # The %children hash has the set of IP's we currently have children
6916: # on. These need to be matched against records in the hosts.tab
6917: # Any ip's no longer in the table get killed off they correspond to
6918: # either dropped or changed hosts. Note that the re-read of the table
6919: # will take care of new and changed hosts as connections come into being.
6920:
6921: &Apache::lonnet::reset_hosts_info();
6922: my %active;
6923:
6924: foreach my $child (keys(%children)) {
6925: my $childip = $children{$child};
6926: if ($childip ne '127.0.0.1'
6927: && !defined(&Apache::lonnet::get_hosts_from_ip($childip))) {
6928: logthis('<font color="blue"> UpdateHosts killing child '
6929: ." $child for ip $childip </font>");
6930: kill('INT', $child);
6931: } else {
6932: $active{$child} = $childip;
6933: logthis('<font color="green"> keeping child for ip '
6934: ." $childip (pid=$child) </font>");
6935: }
6936: }
6937:
6938: my %oldconf = %secureconf;
6939: my %connchange;
6940: if (lonssl::Read_Connect_Config(\%secureconf,\%perlvar) eq 'ok') {
6941: logthis('<font color="blue"> Reloaded SSL connection rules </font>');
6942: } else {
6943: logthis('<font color="yellow"> Failed to reload SSL connection rules </font>');
6944: }
6945: if ((ref($oldconf{'connfrom'}) eq 'HASH') && (ref($secureconf{'connfrom'}) eq 'HASH')) {
6946: foreach my $type ('dom','intdom','other') {
6947: if ((($oldconf{'connfrom'}{$type} eq 'no') && ($secureconf{'connfrom'}{$type} eq 'req')) ||
6948: (($oldconf{'connfrom'}{$type} eq 'req') && ($secureconf{'connfrom'}{$type} eq 'no'))) {
6949: $connchange{$type} = 1;
6950: }
6951: }
6952: }
6953: if (keys(%connchange)) {
6954: foreach my $child (keys(%active)) {
6955: my $childip = $active{$child};
6956: if ($childip ne '127.0.0.1') {
6957: my $childhostname = gethostbyaddr(Socket::inet_aton($childip),AF_INET);
6958: if ($childhostname ne '') {
6959: my $childlonhost = &Apache::lonnet::get_server_homeID($childhostname);
6960: my ($samedom,$sameinst) = &set_client_info($childlonhost);
6961: if ($samedom) {
6962: if ($connchange{'dom'}) {
6963: logthis('<font color="blue"> UpdateHosts killing child '
6964: ." $child for ip $childip </font>");
6965: kill('INT', $child);
6966: }
6967: } elsif ($sameinst) {
6968: if ($connchange{'intdom'}) {
6969: logthis('<font color="blue"> UpdateHosts killing child '
6970: ." $child for ip $childip </font>");
6971: kill('INT', $child);
6972: }
6973: } else {
6974: if ($connchange{'other'}) {
6975: logthis('<font color="blue"> UpdateHosts killing child '
6976: ." $child for ip $childip </font>");
6977: kill('INT', $child);
6978: }
6979: }
6980: }
6981: }
6982: }
6983: }
6984: ReloadApache;
6985: &status("Finished reloading hosts.tab");
6986: }
6987:
6988: sub checkchildren {
6989: &status("Checking on the children (sending signals)");
6990: &initnewstatus();
6991: &logstatus();
6992: &logthis('Going to check on the children');
6993: my $docdir=$perlvar{'lonDocRoot'};
6994: foreach (sort keys %children) {
6995: #sleep 1;
6996: unless (kill 'USR1' => $_) {
6997: &logthis ('Child '.$_.' is dead');
6998: &logstatus($$.' is dead');
6999: delete($children{$_});
7000: }
7001: }
7002: sleep 5;
7003: $SIG{ALRM} = sub { Debug("timeout");
7004: die "timeout"; };
7005: $SIG{__DIE__} = 'DEFAULT';
7006: &status("Checking on the children (waiting for reports)");
7007: foreach (sort keys %children) {
7008: unless (-e "$docdir/lon-status/londchld/$_.txt") {
7009: eval {
7010: alarm(300);
7011: &logthis('Child '.$_.' did not respond');
7012: kill 9 => $_;
7013: #$emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
7014: #$subj="LON: $currenthostid killed lond process $_";
7015: #my $result=`echo 'Killed lond process $_.' | mailto $emailto -s '$subj' > /dev/null`;
7016: #$execdir=$perlvar{'lonDaemons'};
7017: #$result=`/bin/cp $execdir/logs/lond.log $execdir/logs/lond.log.$_`;
7018: delete($children{$_});
7019: alarm(0);
7020: }
7021: }
7022: }
7023: $SIG{ALRM} = 'DEFAULT';
7024: $SIG{__DIE__} = \&catchexception;
7025: &status("Finished checking children");
7026: &logthis('Finished Checking children');
7027: }
7028:
7029: # --------------------------------------------------------------------- Logging
7030:
7031: sub logthis {
7032: my $message=shift;
7033: my $execdir=$perlvar{'lonDaemons'};
7034: my $fh=IO::File->new(">>$execdir/logs/lond.log");
7035: my $now=time;
7036: my $local=localtime($now);
7037: $lastlog=$local.': '.$message;
7038: print $fh "$local ($$): $message\n";
7039: }
7040:
7041: # ------------------------- Conditional log if $DEBUG true.
7042: sub Debug {
7043: my $message = shift;
7044: if($DEBUG) {
7045: &logthis($message);
7046: }
7047: }
7048:
7049: #
7050: # Sub to do replies to client.. this gives a hook for some
7051: # debug tracing too:
7052: # Parameters:
7053: # fd - File open on client.
7054: # reply - Text to send to client.
7055: # request - Original request from client.
7056: #
7057: #NOTE $reply must be terminated by exactly *one* \n. If $reply is a reference
7058: #this is done automatically ($$reply must not contain any \n in this case).
7059: #If $reply is a string the caller has to ensure this.
7060: sub Reply {
7061: my ($fd, $reply, $request) = @_;
7062: if (ref($reply)) {
7063: print $fd $$reply;
7064: print $fd "\n";
7065: if ($DEBUG) { Debug("Request was $request Reply was $$reply"); }
7066: } else {
7067: print $fd $reply;
7068: if ($DEBUG) { Debug("Request was $request Reply was $reply"); }
7069: }
7070: $Transactions++;
7071: }
7072:
7073:
7074: #
7075: # Sub to report a failure.
7076: # This function:
7077: # - Increments the failure statistic counters.
7078: # - Invokes Reply to send the error message to the client.
7079: # Parameters:
7080: # fd - File descriptor open on the client
7081: # reply - Reply text to emit.
7082: # request - The original request message (used by Reply
7083: # to debug if that's enabled.
7084: # Implicit outputs:
7085: # $Failures- The number of failures is incremented.
7086: # Reply (invoked here) sends a message to the
7087: # client:
7088: #
7089: sub Failure {
7090: my $fd = shift;
7091: my $reply = shift;
7092: my $request = shift;
7093:
7094: $Failures++;
7095: Reply($fd, $reply, $request); # That's simple eh?
7096: }
7097: # ------------------------------------------------------------------ Log status
7098:
7099: sub logstatus {
7100: &status("Doing logging");
7101: my $docdir=$perlvar{'lonDocRoot'};
7102: {
7103: my $fh=IO::File->new(">$docdir/lon-status/londchld/$$.txt");
7104: print $fh $status."\n".$lastlog."\n".time."\n$keymode";
7105: $fh->close();
7106: }
7107: &status("Finished $$.txt");
7108: {
7109: open(LOG,">>$docdir/lon-status/londstatus.txt");
7110: flock(LOG,LOCK_EX);
7111: print LOG $$."\t".$clientname."\t".$currenthostid."\t"
7112: .$status."\t".$lastlog."\t $keymode\n";
7113: flock(LOG,LOCK_UN);
7114: close(LOG);
7115: }
7116: &status("Finished logging");
7117: }
7118:
7119: sub initnewstatus {
7120: my $docdir=$perlvar{'lonDocRoot'};
7121: my $fh=IO::File->new(">$docdir/lon-status/londstatus.txt");
7122: my $now=time();
7123: my $local=localtime($now);
7124: print $fh "LOND status $local - parent $$\n\n";
7125: opendir(DIR,"$docdir/lon-status/londchld");
7126: while (my $filename=readdir(DIR)) {
7127: unlink("$docdir/lon-status/londchld/$filename");
7128: }
7129: closedir(DIR);
7130: }
7131:
7132: # -------------------------------------------------------------- Status setting
7133:
7134: sub status {
7135: my $what=shift;
7136: my $now=time;
7137: my $local=localtime($now);
7138: $status=$local.': '.$what;
7139: $0='lond: '.$what.' '.$local;
7140: }
7141:
7142: # -------------------------------------------------------------- Talk to lonsql
7143:
7144: sub sql_reply {
7145: my ($cmd)=@_;
7146: my $answer=&sub_sql_reply($cmd);
7147: if ($answer eq 'con_lost') { $answer=&sub_sql_reply($cmd); }
7148: return $answer;
7149: }
7150:
7151: sub sub_sql_reply {
7152: my ($cmd)=@_;
7153: my $unixsock="mysqlsock";
7154: my $peerfile="$perlvar{'lonSockDir'}/$unixsock";
7155: my $sclient=IO::Socket::UNIX->new(Peer =>"$peerfile",
7156: Type => SOCK_STREAM,
7157: Timeout => 10)
7158: or return "con_lost";
7159: print $sclient "$cmd:$currentdomainid\n";
7160: my $answer=<$sclient>;
7161: chomp($answer);
7162: if (!$answer) { $answer="con_lost"; }
7163: return $answer;
7164: }
7165:
7166: # --------------------------------------- Is this the home server of an author?
7167:
7168: sub ishome {
7169: my $author=shift;
7170: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
7171: my ($udom,$uname)=split(/\//,$author);
7172: my $proname=propath($udom,$uname);
7173: if (-e $proname) {
7174: return 'owner';
7175: } else {
7176: return 'not_owner';
7177: }
7178: }
7179:
7180: # ======================================================= Continue main program
7181: # ---------------------------------------------------- Fork once and dissociate
7182:
7183: my $fpid=fork;
7184: exit if $fpid;
7185: die "Couldn't fork: $!" unless defined ($fpid);
7186:
7187: POSIX::setsid() or die "Can't start new session: $!";
7188:
7189: # ------------------------------------------------------- Write our PID on disk
7190:
7191: my $execdir=$perlvar{'lonDaemons'};
7192: open (PIDSAVE,">$execdir/logs/lond.pid");
7193: print PIDSAVE "$$\n";
7194: close(PIDSAVE);
7195: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
7196: &status('Starting');
7197:
7198:
7199:
7200: # ----------------------------------------------------- Install signal handlers
7201:
7202:
7203: $SIG{CHLD} = \&REAPER;
7204: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
7205: $SIG{HUP} = \&HUPSMAN;
7206: $SIG{USR1} = \&checkchildren;
7207: $SIG{USR2} = \&UpdateHosts;
7208:
7209: # Read the host hashes:
7210: &Apache::lonnet::load_hosts_tab();
7211: my %iphost = &Apache::lonnet::get_iphost(1);
7212:
7213: $dist=`$perlvar{'lonDaemons'}/distprobe`;
7214:
7215: my $arch = `uname -i`;
7216: chomp($arch);
7217: if ($arch eq 'unknown') {
7218: $arch = `uname -m`;
7219: chomp($arch);
7220: }
7221:
7222: unless (lonssl::Read_Connect_Config(\%secureconf,\%perlvar) eq 'ok') {
7223: &logthis('<font color="blue">No connectionrules table. Will fallback to loncapa.conf</font>');
7224: }
7225:
7226: # --------------------------------------------------------------
7227: # Accept connections. When a connection comes in, it is validated
7228: # and if good, a child process is created to process transactions
7229: # along the connection.
7230:
7231: while (1) {
7232: &status('Starting accept');
7233: $client = $server->accept() or next;
7234: &status('Accepted '.$client.' off to spawn');
7235: make_new_child($client);
7236: &status('Finished spawning');
7237: }
7238:
7239: sub make_new_child {
7240: my $pid;
7241: # my $cipher; # Now global
7242: my $sigset;
7243:
7244: $client = shift;
7245: &status('Starting new child '.$client);
7246: &logthis('<font color="green"> Attempting to start child ('.$client.
7247: ")</font>");
7248: # block signal for fork
7249: $sigset = POSIX::SigSet->new(SIGINT);
7250: sigprocmask(SIG_BLOCK, $sigset)
7251: or die "Can't block SIGINT for fork: $!\n";
7252:
7253: die "fork: $!" unless defined ($pid = fork);
7254:
7255: $client->sockopt(SO_KEEPALIVE, 1); # Enable monitoring of
7256: # connection liveness.
7257:
7258: #
7259: # Figure out who we're talking to so we can record the peer in
7260: # the pid hash.
7261: #
7262: my $caller = getpeername($client);
7263: my ($port,$iaddr);
7264: if (defined($caller) && length($caller) > 0) {
7265: ($port,$iaddr)=unpack_sockaddr_in($caller);
7266: } else {
7267: &logthis("Unable to determine who caller was, getpeername returned nothing");
7268: }
7269: if (defined($iaddr)) {
7270: $clientip = inet_ntoa($iaddr);
7271: Debug("Connected with $clientip");
7272: } else {
7273: &logthis("Unable to determine clientip");
7274: $clientip='Unavailable';
7275: }
7276:
7277: if ($pid) {
7278: # Parent records the child's birth and returns.
7279: sigprocmask(SIG_UNBLOCK, $sigset)
7280: or die "Can't unblock SIGINT for fork: $!\n";
7281: $children{$pid} = $clientip;
7282: &status('Started child '.$pid);
7283: close($client);
7284: return;
7285: } else {
7286: # Child can *not* return from this subroutine.
7287: $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before
7288: $SIG{CHLD} = 'DEFAULT'; #make this default so that pwauth returns
7289: #don't get intercepted
7290: $SIG{USR1}= \&logstatus;
7291: $SIG{ALRM}= \&timeout;
7292: #
7293: # Block sigpipe as it gets thrownon socket disconnect and we want to
7294: # deal with that as a read faiure instead.
7295: #
7296: my $blockset = POSIX::SigSet->new(SIGPIPE);
7297: sigprocmask(SIG_BLOCK, $blockset);
7298:
7299: $lastlog='Forked ';
7300: $status='Forked';
7301:
7302: # unblock signals
7303: sigprocmask(SIG_UNBLOCK, $sigset)
7304: or die "Can't unblock SIGINT for fork: $!\n";
7305:
7306: # my $tmpsnum=0; # Now global
7307: #---------------------------------------------------- kerberos 5 initialization
7308: &Authen::Krb5::init_context();
7309:
7310: my $no_ets;
7311: if ($dist =~ /^(?:centos|rhes|scientific)(\d+)$/) {
7312: if ($1 >= 7) {
7313: $no_ets = 1;
7314: }
7315: } elsif ($dist =~ /^suse(\d+\.\d+)$/) {
7316: if (($1 eq '9.3') || ($1 >= 12.2)) {
7317: $no_ets = 1;
7318: }
7319: } elsif ($dist =~ /^sles(\d+)$/) {
7320: if ($1 > 11) {
7321: $no_ets = 1;
7322: }
7323: } elsif ($dist =~ /^fedora(\d+)$/) {
7324: if ($1 < 7) {
7325: $no_ets = 1;
7326: }
7327: }
7328: unless ($no_ets) {
7329: &Authen::Krb5::init_ets();
7330: }
7331:
7332: &status('Accepted connection');
7333: # =============================================================================
7334: # do something with the connection
7335: # -----------------------------------------------------------------------------
7336: # see if we know client and 'check' for spoof IP by ineffective challenge
7337:
7338: my $outsideip=$clientip;
7339: if ($clientip eq '127.0.0.1') {
7340: $outsideip=&Apache::lonnet::get_host_ip($perlvar{'lonHostID'});
7341: }
7342: &ReadManagerTable();
7343: my $clientrec=defined(&Apache::lonnet::get_hosts_from_ip($outsideip));
7344: my $ismanager=($managers{$outsideip} ne undef);
7345: $clientname = "[unknown]";
7346: if($clientrec) { # Establish client type.
7347: $ConnectionType = "client";
7348: $clientname = (&Apache::lonnet::get_hosts_from_ip($outsideip))[-1];
7349: if($ismanager) {
7350: $ConnectionType = "both";
7351: }
7352: } else {
7353: $ConnectionType = "manager";
7354: $clientname = $managers{$outsideip};
7355: }
7356: my ($clientok,$clientinfoset);
7357:
7358: if ($clientrec || $ismanager) {
7359: &status("Waiting for init from $clientip $clientname");
7360: &logthis('<font color="yellow">INFO: Connection, '.
7361: $clientip.
7362: " ($clientname) connection type = $ConnectionType </font>" );
7363: &status("Connecting $clientip ($clientname))");
7364: my $remotereq=<$client>;
7365: chomp($remotereq);
7366: Debug("Got init: $remotereq");
7367:
7368: if ($remotereq =~ /^init/) {
7369: &sethost("sethost:$perlvar{'lonHostID'}");
7370: #
7371: # If the remote is attempting a local init... give that a try:
7372: #
7373: (my $i, my $inittype, $clientversion) = split(/:/, $remotereq);
7374: # For LON-CAPA 2.9, the client session will have sent its LON-CAPA
7375: # version when initiating the connection. For LON-CAPA 2.8 and older,
7376: # the version is retrieved from the global %loncaparevs in lonnet.pm.
7377: # $clientversion contains path to keyfile if $inittype eq 'local'
7378: # it's overridden below in this case
7379: $clientversion ||= $Apache::lonnet::loncaparevs{$clientname};
7380:
7381: # If the connection type is ssl, but I didn't get my
7382: # certificate files yet, then I'll drop back to
7383: # insecure (if allowed).
7384:
7385: if ($inittype eq "ssl") {
7386: my $context;
7387: if ($clientsamedom) {
7388: $context = 'dom';
7389: if ($secureconf{'connfrom'}{'dom'} eq 'no') {
7390: $inittype = "";
7391: }
7392: } elsif ($clientsameinst) {
7393: $context = 'intdom';
7394: if ($secureconf{'connfrom'}{'intdom'} eq 'no') {
7395: $inittype = "";
7396: }
7397: } else {
7398: $context = 'other';
7399: if ($secureconf{'connfrom'}{'other'} eq 'no') {
7400: $inittype = "";
7401: }
7402: }
7403: if ($inittype eq '') {
7404: &logthis("<font color=\"blue\"> Domain config set "
7405: ."to no ssl for $clientname (context: $context)"
7406: ." -- trying insecure auth</font>");
7407: }
7408: }
7409:
7410: if($inittype eq "ssl") {
7411: my ($ca, $cert) = lonssl::CertificateFile;
7412: my $kfile = lonssl::KeyFile;
7413: if((!$ca) ||
7414: (!$cert) ||
7415: (!$kfile)) {
7416: $inittype = ""; # This forces insecure attempt.
7417: &logthis("<font color=\"blue\"> Certificates not "
7418: ."installed -- trying insecure auth</font>");
7419: } else { # SSL certificates are in place so
7420: } # Leave the inittype alone.
7421: }
7422:
7423: if($inittype eq "local") {
7424: $clientversion = $perlvar{'lonVersion'};
7425: my $key = LocalConnection($client, $remotereq);
7426: if($key) {
7427: Debug("Got local key $key");
7428: $clientok = 1;
7429: my $cipherkey = pack("H32", $key);
7430: $cipher = new IDEA($cipherkey);
7431: print $client "ok:local\n";
7432: &logthis('<font color="green">'
7433: . "Successful local authentication </font>");
7434: $keymode = "local"
7435: } else {
7436: Debug("Failed to get local key");
7437: $clientok = 0;
7438: shutdown($client, 3);
7439: close $client;
7440: }
7441: } elsif ($inittype eq "ssl") {
7442: my $key = SSLConnection($client,$clientname);
7443: if ($key) {
7444: $clientok = 1;
7445: my $cipherkey = pack("H32", $key);
7446: $cipher = new IDEA($cipherkey);
7447: &logthis('<font color="green">'
7448: ."Successfull ssl authentication with $clientname </font>");
7449: $keymode = "ssl";
7450:
7451: } else {
7452: $clientok = 0;
7453: close $client;
7454: }
7455:
7456: } else {
7457: $clientinfoset = &set_client_info();
7458: my $ok = InsecureConnection($client);
7459: if($ok) {
7460: $clientok = 1;
7461: &logthis('<font color="green">'
7462: ."Successful insecure authentication with $clientname </font>");
7463: print $client "ok\n";
7464: $keymode = "insecure";
7465: } else {
7466: &logthis('<font color="yellow">'
7467: ."Attempted insecure connection disallowed </font>");
7468: close $client;
7469: $clientok = 0;
7470: }
7471: }
7472: } else {
7473: &logthis(
7474: "<font color='blue'>WARNING: "
7475: ."$clientip failed to initialize: >$remotereq< </font>");
7476: &status('No init '.$clientip);
7477: }
7478: } else {
7479: &logthis(
7480: "<font color='blue'>WARNING: Unknown client $clientip</font>");
7481: &status('Hung up on '.$clientip);
7482: }
7483:
7484: if ($clientok) {
7485: # ---------------- New known client connecting, could mean machine online again
7486: if (&Apache::lonnet::get_host_ip($currenthostid) ne $clientip
7487: && $clientip ne '127.0.0.1') {
7488: &Apache::lonnet::reconlonc($clientname);
7489: }
7490: &logthis("<font color='green'>Established connection: $clientname</font>");
7491: &status('Will listen to '.$clientname);
7492: # ------------------------------------------------------------ Process requests
7493: my $keep_going = 1;
7494: my $user_input;
7495: unless ($clientinfoset) {
7496: $clientinfoset = &set_client_info();
7497: }
7498: $clientremoteok = 0;
7499: unless ($clientsameinst) {
7500: $clientremoteok = 1;
7501: my $defdom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
7502: %clientprohibited = &get_prohibited($defdom);
7503: if ($clientintdom) {
7504: my $remsessconf = &get_usersession_config($defdom,'remotesession');
7505: if (ref($remsessconf) eq 'HASH') {
7506: if (ref($remsessconf->{'remote'}) eq 'HASH') {
7507: if (ref($remsessconf->{'remote'}->{'excludedomain'}) eq 'ARRAY') {
7508: if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'excludedomain'}})) {
7509: $clientremoteok = 0;
7510: }
7511: }
7512: if (ref($remsessconf->{'remote'}->{'includedomain'}) eq 'ARRAY') {
7513: if (grep(/^\Q$clientintdom\E$/,@{$remsessconf->{'remote'}->{'includedomain'}})) {
7514: $clientremoteok = 1;
7515: } else {
7516: $clientremoteok = 0;
7517: }
7518: }
7519: }
7520: }
7521: }
7522: }
7523: while(($user_input = get_request) && $keep_going) {
7524: alarm(120);
7525: Debug("Main: Got $user_input\n");
7526: $keep_going = &process_request($user_input);
7527: alarm(0);
7528: &status('Listening to '.$clientname." ($keymode)");
7529: }
7530:
7531: # --------------------------------------------- client unknown or fishy, refuse
7532: } else {
7533: print $client "refused\n";
7534: $client->close();
7535: &logthis("<font color='blue'>WARNING: "
7536: ."Rejected client $clientip, closing connection</font>");
7537: }
7538: }
7539:
7540: # =============================================================================
7541:
7542: &logthis("<font color='red'>CRITICAL: "
7543: ."Disconnect from $clientip ($clientname)</font>");
7544:
7545:
7546: # this exit is VERY important, otherwise the child will become
7547: # a producer of more and more children, forking yourself into
7548: # process death.
7549: exit;
7550:
7551: }
7552:
7553: #
7554: # Used to determine if a particular client is from the same domain
7555: # as the current server, or from the same internet domain.
7556: #
7557: # Optional input -- the client to check for domain and internet domain.
7558: # If not specified, defaults to the package variable: $clientname
7559: #
7560: # If called in array context will not set package variables, but will
7561: # instead return an array of two values - (a) true if client is in the
7562: # same domain as the server, and (b) true if client is in the same internet
7563: # domain.
7564: #
7565: # If called in scalar context, sets package variables for current client:
7566: #
7567: # $clienthomedom - LonCAPA domain of homeID for client.
7568: # $clientsamedom - LonCAPA domain same for this host and client.
7569: # $clientintdom - LonCAPA "internet domain" for client.
7570: # $clientsameinst - LonCAPA "internet domain" same for this host & client.
7571: #
7572: # returns 1 to indicate package variables have been set for current client.
7573: #
7574:
7575: sub set_client_info {
7576: my ($lonhost) = @_;
7577: $lonhost ||= $clientname;
7578: my $clienthost = &Apache::lonnet::hostname($lonhost);
7579: my $clientserverhomeID = &Apache::lonnet::get_server_homeID($clienthost);
7580: my $homedom = &Apache::lonnet::host_domain($clientserverhomeID);
7581: my $samedom = 0;
7582: if ($perlvar{'lonDefDom'} eq $homedom) {
7583: $samedom = 1;
7584: }
7585: my $intdom = &Apache::lonnet::internet_dom($clientserverhomeID);
7586: my $sameinst = 0;
7587: if ($intdom ne '') {
7588: my $internet_names = &Apache::lonnet::get_internet_names($currenthostid);
7589: if (ref($internet_names) eq 'ARRAY') {
7590: if (grep(/^\Q$intdom\E$/,@{$internet_names})) {
7591: $sameinst = 1;
7592: }
7593: }
7594: }
7595: if (wantarray) {
7596: return ($samedom,$sameinst);
7597: } else {
7598: $clienthomedom = $homedom;
7599: $clientsamedom = $samedom;
7600: $clientintdom = $intdom;
7601: $clientsameinst = $sameinst;
7602: return 1;
7603: }
7604: }
7605:
7606: #
7607: # Determine if a user is an author for the indicated domain.
7608: #
7609: # Parameters:
7610: # domain - domain to check in .
7611: # user - Name of user to check.
7612: #
7613: # Return:
7614: # 1 - User is an author for domain.
7615: # 0 - User is not an author for domain.
7616: sub is_author {
7617: my ($domain, $user) = @_;
7618:
7619: &Debug("is_author: $user @ $domain");
7620:
7621: my $hashref = &tie_user_hash($domain, $user, "roles",
7622: &GDBM_READER());
7623:
7624: # Author role should show up as a key /domain/_au
7625:
7626: my $value;
7627: if ($hashref) {
7628:
7629: my $key = "/$domain/_au";
7630: if (defined($hashref)) {
7631: $value = $hashref->{$key};
7632: if(!untie_user_hash($hashref)) {
7633: return 'error: ' . ($!+0)." untie (GDBM) Failed";
7634: }
7635: }
7636:
7637: if(defined($value)) {
7638: &Debug("$user @ $domain is an author");
7639: }
7640: } else {
7641: return 'error: '.($!+0)." tie (GDBM) Failed";
7642: }
7643:
7644: return defined($value);
7645: }
7646: #
7647: # Checks to see if the input roleput request was to set
7648: # an author role. If so, creates construction space
7649: # Parameters:
7650: # request - The request sent to the rolesput subchunk.
7651: # We're looking for /domain/_au
7652: # domain - The domain in which the user is having roles doctored.
7653: # user - Name of the user for which the role is being put.
7654: # authtype - The authentication type associated with the user.
7655: #
7656: sub manage_permissions {
7657: my ($request, $domain, $user, $authtype) = @_;
7658: # See if the request is of the form /$domain/_au
7659: if($request =~ /^(\/\Q$domain\E\/_au)$/) { # It's an author rolesput...
7660: my $path=$perlvar{'lonDocRoot'}."/priv/$domain";
7661: unless (-e $path) {
7662: mkdir($path);
7663: }
7664: unless (-e $path.'/'.$user) {
7665: mkdir($path.'/'.$user);
7666: }
7667: }
7668: }
7669:
7670:
7671: #
7672: # Return the full path of a user password file, whether it exists or not.
7673: # Parameters:
7674: # domain - Domain in which the password file lives.
7675: # user - name of the user.
7676: # Returns:
7677: # Full passwd path:
7678: #
7679: sub password_path {
7680: my ($domain, $user) = @_;
7681: return &propath($domain, $user).'/passwd';
7682: }
7683:
7684: # Password Filename
7685: # Returns the path to a passwd file given domain and user... only if
7686: # it exists.
7687: # Parameters:
7688: # domain - Domain in which to search.
7689: # user - username.
7690: # Returns:
7691: # - If the password file exists returns its path.
7692: # - If the password file does not exist, returns undefined.
7693: #
7694: sub password_filename {
7695: my ($domain, $user) = @_;
7696:
7697: Debug ("PasswordFilename called: dom = $domain user = $user");
7698:
7699: my $path = &password_path($domain, $user);
7700: Debug("PasswordFilename got path: $path");
7701: if(-e $path) {
7702: return $path;
7703: } else {
7704: return undef;
7705: }
7706: }
7707:
7708: #
7709: # Rewrite the contents of the user's passwd file.
7710: # Parameters:
7711: # domain - domain of the user.
7712: # name - User's name.
7713: # contents - New contents of the file.
7714: # saveold - (optional). If true save old file in a passwd.bak file.
7715: # Returns:
7716: # 0 - Failed.
7717: # 1 - Success.
7718: #
7719: sub rewrite_password_file {
7720: my ($domain, $user, $contents, $saveold) = @_;
7721:
7722: my $file = &password_filename($domain, $user);
7723: if (defined $file) {
7724: if ($saveold) {
7725: my $bakfile = $file.'.bak';
7726: if (CopyFile($file,$bakfile)) {
7727: chmod(0400,$bakfile);
7728: &logthis("Old password saved in passwd.bak for internally authenticated user: $user:$domain");
7729: } else {
7730: &logthis("Failed to save old password in passwd.bak for internally authenticated user: $user:$domain");
7731: }
7732: }
7733: my $pf = IO::File->new(">$file");
7734: if($pf) {
7735: print $pf "$contents\n";
7736: return 1;
7737: } else {
7738: return 0;
7739: }
7740: } else {
7741: return 0;
7742: }
7743:
7744: }
7745:
7746: #
7747: # get_auth_type - Determines the authorization type of a user in a domain.
7748:
7749: # Returns the authorization type or nouser if there is no such user.
7750: #
7751: sub get_auth_type {
7752: my ($domain, $user) = @_;
7753:
7754: Debug("get_auth_type( $domain, $user ) \n");
7755: my $proname = &propath($domain, $user);
7756: my $passwdfile = "$proname/passwd";
7757: if( -e $passwdfile ) {
7758: my $pf = IO::File->new($passwdfile);
7759: my $realpassword = <$pf>;
7760: chomp($realpassword);
7761: Debug("Password info = $realpassword\n");
7762: my ($authtype, $contentpwd) = split(/:/, $realpassword);
7763: Debug("Authtype = $authtype, content = $contentpwd\n");
7764: return "$authtype:$contentpwd";
7765: } else {
7766: Debug("Returning nouser");
7767: return "nouser";
7768: }
7769: }
7770:
7771: #
7772: # Validate a user given their domain, name and password. This utility
7773: # function is used by both AuthenticateHandler and ChangePasswordHandler
7774: # to validate the login credentials of a user.
7775: # Parameters:
7776: # $domain - The domain being logged into (this is required due to
7777: # the capability for multihomed systems.
7778: # $user - The name of the user being validated.
7779: # $password - The user's propoposed password.
7780: #
7781: # Returns:
7782: # 1 - The domain,user,pasword triplet corresponds to a valid
7783: # user.
7784: # 0 - The domain,user,password triplet is not a valid user.
7785: #
7786: sub validate_user {
7787: my ($domain, $user, $password, $checkdefauth) = @_;
7788:
7789: # Why negative ~pi you may well ask? Well this function is about
7790: # authentication, and therefore very important to get right.
7791: # I've initialized the flag that determines whether or not I've
7792: # validated correctly to a value it's not supposed to get.
7793: # At the end of this function. I'll ensure that it's not still that
7794: # value so we don't just wind up returning some accidental value
7795: # as a result of executing an unforseen code path that
7796: # did not set $validated. At the end of valid execution paths,
7797: # validated shoule be 1 for success or 0 for failuer.
7798:
7799: my $validated = -3.14159;
7800:
7801: # How we authenticate is determined by the type of authentication
7802: # the user has been assigned. If the authentication type is
7803: # "nouser", the user does not exist so we will return 0.
7804:
7805: my $contents = &get_auth_type($domain, $user);
7806: my ($howpwd, $contentpwd) = split(/:/, $contents);
7807:
7808: my $null = pack("C",0); # Used by kerberos auth types.
7809:
7810: if ($howpwd eq 'nouser') {
7811: if ($checkdefauth) {
7812: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
7813: if ($domdefaults{'auth_def'} eq 'localauth') {
7814: $howpwd = $domdefaults{'auth_def'};
7815: $contentpwd = $domdefaults{'auth_arg_def'};
7816: } elsif ((($domdefaults{'auth_def'} eq 'krb4') ||
7817: ($domdefaults{'auth_def'} eq 'krb5')) &&
7818: ($domdefaults{'auth_arg_def'} ne '')) {
7819: $howpwd = $domdefaults{'auth_def'};
7820: $contentpwd = $domdefaults{'auth_arg_def'};
7821: }
7822: }
7823: }
7824: if ($howpwd ne 'nouser') {
7825: if($howpwd eq "internal") { # Encrypted is in local password file.
7826: if (length($contentpwd) == 13) {
7827: $validated = (crypt($password,$contentpwd) eq $contentpwd);
7828: if ($validated) {
7829: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
7830: if ($domdefaults{'intauth_switch'}) {
7831: my $ncpass = &hash_passwd($domain,$password);
7832: my $saveold;
7833: if ($domdefaults{'intauth_switch'} == 2) {
7834: $saveold = 1;
7835: }
7836: if (&rewrite_password_file($domain,$user,"$howpwd:$ncpass",$saveold)) {
7837: &update_passwd_history($user,$domain,$howpwd,'conversion');
7838: &logthis("Validated password hashed with bcrypt for $user:$domain");
7839: }
7840: }
7841: }
7842: } else {
7843: $validated = &check_internal_passwd($password,$contentpwd,$domain,$user);
7844: }
7845: }
7846: elsif ($howpwd eq "unix") { # User is a normal unix user.
7847: $contentpwd = (getpwnam($user))[1];
7848: if($contentpwd) {
7849: if($contentpwd eq 'x') { # Shadow password file...
7850: my $pwauth_path = "/usr/local/sbin/pwauth";
7851: open PWAUTH, "|$pwauth_path" or
7852: die "Cannot invoke authentication";
7853: print PWAUTH "$user\n$password\n";
7854: close PWAUTH;
7855: $validated = ! $?;
7856:
7857: } else { # Passwords in /etc/passwd.
7858: $validated = (crypt($password,
7859: $contentpwd) eq $contentpwd);
7860: }
7861: } else {
7862: $validated = 0;
7863: }
7864: } elsif ($howpwd eq "krb4") { # user is in kerberos 4 auth. domain.
7865: my $checkwithkrb5 = 0;
7866: if ($dist =~/^fedora(\d+)$/) {
7867: if ($1 > 11) {
7868: $checkwithkrb5 = 1;
7869: }
7870: } elsif ($dist =~ /^suse([\d.]+)$/) {
7871: if ($1 > 11.1) {
7872: $checkwithkrb5 = 1;
7873: }
7874: }
7875: if ($checkwithkrb5) {
7876: $validated = &krb5_authen($password,$null,$user,$contentpwd);
7877: } else {
7878: $validated = &krb4_authen($password,$null,$user,$contentpwd);
7879: }
7880: } elsif ($howpwd eq "krb5") { # User is in kerberos 5 auth. domain.
7881: $validated = &krb5_authen($password,$null,$user,$contentpwd);
7882: } elsif ($howpwd eq "localauth") {
7883: # Authenticate via installation specific authentcation method:
7884: $validated = &localauth::localauth($user,
7885: $password,
7886: $contentpwd,
7887: $domain);
7888: if ($validated < 0) {
7889: &logthis("localauth for $contentpwd $user:$domain returned a $validated");
7890: $validated = 0;
7891: }
7892: } else { # Unrecognized auth is also bad.
7893: $validated = 0;
7894: }
7895: } else {
7896: $validated = 0;
7897: }
7898: #
7899: # $validated has the correct stat of the authentication:
7900: #
7901:
7902: unless ($validated != -3.14159) {
7903: # I >really really< want to know if this happens.
7904: # since it indicates that user authentication is badly
7905: # broken in some code path.
7906: #
7907: die "ValidateUser - failed to set the value of validated $domain, $user $password";
7908: }
7909: return $validated;
7910: }
7911:
7912: sub check_internal_passwd {
7913: my ($plainpass,$stored,$domain,$user) = @_;
7914: my (undef,$method,@rest) = split(/!/,$stored);
7915: if ($method eq 'bcrypt') {
7916: my $result = &hash_passwd($domain,$plainpass,@rest);
7917: if ($result ne $stored) {
7918: return 0;
7919: }
7920: my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
7921: if ($domdefaults{'intauth_check'}) {
7922: # Upgrade to a larger number of rounds if necessary
7923: my $defaultcost = $domdefaults{'intauth_cost'};
7924: if (($defaultcost eq '') || ($defaultcost =~ /D/)) {
7925: $defaultcost = 10;
7926: }
7927: if (int($rest[0])<int($defaultcost)) {
7928: if ($domdefaults{'intauth_check'} == 1) {
7929: my $ncpass = &hash_passwd($domain,$plainpass);
7930: if (&rewrite_password_file($domain,$user,"internal:$ncpass")) {
7931: &update_passwd_history($user,$domain,'internal','update cost');
7932: &logthis("Validated password hashed with bcrypt for $user:$domain");
7933: }
7934: return 1;
7935: } elsif ($domdefaults{'intauth_check'} == 2) {
7936: return 0;
7937: }
7938: }
7939: } else {
7940: return 1;
7941: }
7942: }
7943: return 0;
7944: }
7945:
7946: sub get_last_authchg {
7947: my ($domain,$user) = @_;
7948: my $lastmod;
7949: my $logname = &propath($domain,$user).'/passwd.log';
7950: if (-e "$logname") {
7951: $lastmod = (stat("$logname"))[9];
7952: }
7953: return $lastmod;
7954: }
7955:
7956: sub krb4_authen {
7957: my ($password,$null,$user,$contentpwd) = @_;
7958: my $validated = 0;
7959: if (!($password =~ /$null/) ) { # Null password not allowed.
7960: eval {
7961: require Authen::Krb4;
7962: };
7963: if (!$@) {
7964: my $k4error = &Authen::Krb4::get_pw_in_tkt($user,
7965: "",
7966: $contentpwd,,
7967: 'krbtgt',
7968: $contentpwd,
7969: 1,
7970: $password);
7971: if(!$k4error) {
7972: $validated = 1;
7973: } else {
7974: $validated = 0;
7975: &logthis('krb4: '.$user.', '.$contentpwd.', '.
7976: &Authen::Krb4::get_err_txt($Authen::Krb4::error));
7977: }
7978: } else {
7979: $validated = krb5_authen($password,$null,$user,$contentpwd);
7980: }
7981: }
7982: return $validated;
7983: }
7984:
7985: sub krb5_authen {
7986: my ($password,$null,$user,$contentpwd) = @_;
7987: my $validated = 0;
7988: if(!($password =~ /$null/)) { # Null password not allowed.
7989: my $krbclient = &Authen::Krb5::parse_name($user.'@'
7990: .$contentpwd);
7991: my $krbservice = "krbtgt/".$contentpwd."\@".$contentpwd;
7992: my $krbserver = &Authen::Krb5::parse_name($krbservice);
7993: my $credentials= &Authen::Krb5::cc_default();
7994: $credentials->initialize(&Authen::Krb5::parse_name($user.'@'
7995: .$contentpwd));
7996: my $krbreturn;
7997: if (exists(&Authen::Krb5::get_init_creds_password)) {
7998: $krbreturn =
7999: &Authen::Krb5::get_init_creds_password($krbclient,$password,
8000: $krbservice);
8001: $validated = (ref($krbreturn) eq 'Authen::Krb5::Creds');
8002: } else {
8003: $krbreturn =
8004: &Authen::Krb5::get_in_tkt_with_password($krbclient,$krbserver,
8005: $password,$credentials);
8006: $validated = ($krbreturn == 1);
8007: }
8008: if (!$validated) {
8009: &logthis('krb5: '.$user.', '.$contentpwd.', '.
8010: &Authen::Krb5::error());
8011: }
8012: }
8013: return $validated;
8014: }
8015:
8016: sub addline {
8017: my ($fname,$hostid,$ip,$newline)=@_;
8018: my $contents;
8019: my $found=0;
8020: my $expr='^'.quotemeta($hostid).':'.quotemeta($ip).':';
8021: my $sh;
8022: if ($sh=IO::File->new("$fname.subscription")) {
8023: while (my $subline=<$sh>) {
8024: if ($subline !~ /$expr/) {$contents.= $subline;} else {$found=1;}
8025: }
8026: $sh->close();
8027: }
8028: $sh=IO::File->new(">$fname.subscription");
8029: if ($contents) { print $sh $contents; }
8030: if ($newline) { print $sh $newline; }
8031: $sh->close();
8032: return $found;
8033: }
8034:
8035: sub get_chat {
8036: my ($cdom,$cname,$udom,$uname,$group)=@_;
8037:
8038: my @entries=();
8039: my $namespace = 'nohist_chatroom';
8040: my $namespace_inroom = 'nohist_inchatroom';
8041: if ($group ne '') {
8042: $namespace .= '_'.$group;
8043: $namespace_inroom .= '_'.$group;
8044: }
8045: my $hashref = &tie_user_hash($cdom, $cname, $namespace,
8046: &GDBM_READER());
8047: if ($hashref) {
8048: @entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
8049: &untie_user_hash($hashref);
8050: }
8051: my @participants=();
8052: my $cutoff=time-60;
8053: $hashref = &tie_user_hash($cdom, $cname, $namespace_inroom,
8054: &GDBM_WRCREAT());
8055: if ($hashref) {
8056: $hashref->{$uname.':'.$udom}=time;
8057: foreach my $user (sort(keys(%$hashref))) {
8058: if ($hashref->{$user}>$cutoff) {
8059: push(@participants, 'active_participant:'.$user);
8060: }
8061: }
8062: &untie_user_hash($hashref);
8063: }
8064: return (@participants,@entries);
8065: }
8066:
8067: sub chat_add {
8068: my ($cdom,$cname,$newchat,$group)=@_;
8069: my @entries=();
8070: my $time=time;
8071: my $namespace = 'nohist_chatroom';
8072: my $logfile = 'chatroom.log';
8073: if ($group ne '') {
8074: $namespace .= '_'.$group;
8075: $logfile = 'chatroom_'.$group.'.log';
8076: }
8077: my $hashref = &tie_user_hash($cdom, $cname, $namespace,
8078: &GDBM_WRCREAT());
8079: if ($hashref) {
8080: @entries=map { $_.':'.$hashref->{$_} } sort(keys(%$hashref));
8081: my ($lastid)=($entries[$#entries]=~/^(\w+)\:/);
8082: my ($thentime,$idnum)=split(/\_/,$lastid);
8083: my $newid=$time.'_000000';
8084: if ($thentime==$time) {
8085: $idnum=~s/^0+//;
8086: $idnum++;
8087: $idnum=substr('000000'.$idnum,-6,6);
8088: $newid=$time.'_'.$idnum;
8089: }
8090: $hashref->{$newid}=$newchat;
8091: my $expired=$time-3600;
8092: foreach my $comment (keys(%$hashref)) {
8093: my ($thistime) = ($comment=~/(\d+)\_/);
8094: if ($thistime<$expired) {
8095: delete $hashref->{$comment};
8096: }
8097: }
8098: {
8099: my $proname=&propath($cdom,$cname);
8100: if (open(CHATLOG,">>$proname/$logfile")) {
8101: print CHATLOG ("$time:".&unescape($newchat)."\n");
8102: }
8103: close(CHATLOG);
8104: }
8105: &untie_user_hash($hashref);
8106: }
8107: }
8108:
8109: sub unsub {
8110: my ($fname,$clientip)=@_;
8111: my $result;
8112: my $unsubs = 0; # Number of successful unsubscribes:
8113:
8114:
8115: # An old way subscriptions were handled was to have a
8116: # subscription marker file:
8117:
8118: Debug("Attempting unlink of $fname.$clientname");
8119: if (unlink("$fname.$clientname")) {
8120: $unsubs++; # Successful unsub via marker file.
8121: }
8122:
8123: # The more modern way to do it is to have a subscription list
8124: # file:
8125:
8126: if (-e "$fname.subscription") {
8127: my $found=&addline($fname,$clientname,$clientip,'');
8128: if ($found) {
8129: $unsubs++;
8130: }
8131: }
8132:
8133: # If either or both of these mechanisms succeeded in unsubscribing a
8134: # resource we can return ok:
8135:
8136: if($unsubs) {
8137: $result = "ok\n";
8138: } else {
8139: $result = "not_subscribed\n";
8140: }
8141:
8142: return $result;
8143: }
8144:
8145: sub currentversion {
8146: my $fname=shift;
8147: my $version=-1;
8148: my $ulsdir='';
8149: if ($fname=~/^(.+)\/[^\/]+$/) {
8150: $ulsdir=$1;
8151: }
8152: my ($fnamere1,$fnamere2);
8153: # remove version if already specified
8154: $fname=~s/\.\d+\.(\w+(?:\.meta)*)$/\.$1/;
8155: # get the bits that go before and after the version number
8156: if ( $fname=~/^(.*\.)(\w+(?:\.meta)*)$/ ) {
8157: $fnamere1=$1;
8158: $fnamere2='.'.$2;
8159: }
8160: if (-e $fname) { $version=1; }
8161: if (-e $ulsdir) {
8162: if(-d $ulsdir) {
8163: if (opendir(LSDIR,$ulsdir)) {
8164: my $ulsfn;
8165: while ($ulsfn=readdir(LSDIR)) {
8166: # see if this is a regular file (ignore links produced earlier)
8167: my $thisfile=$ulsdir.'/'.$ulsfn;
8168: unless (-l $thisfile) {
8169: if ($thisfile=~/\Q$fnamere1\E(\d+)\Q$fnamere2\E$/) {
8170: if ($1>$version) { $version=$1; }
8171: }
8172: }
8173: }
8174: closedir(LSDIR);
8175: $version++;
8176: }
8177: }
8178: }
8179: return $version;
8180: }
8181:
8182: sub thisversion {
8183: my $fname=shift;
8184: my $version=-1;
8185: if ($fname=~/\.(\d+)\.\w+(?:\.meta)*$/) {
8186: $version=$1;
8187: }
8188: return $version;
8189: }
8190:
8191: sub subscribe {
8192: my ($userinput,$clientip)=@_;
8193: my $result;
8194: my ($cmd,$fname)=split(/:/,$userinput,2);
8195: my $ownership=&ishome($fname);
8196: if ($ownership eq 'owner') {
8197: # explitly asking for the current version?
8198: unless (-e $fname) {
8199: my $currentversion=¤tversion($fname);
8200: if (&thisversion($fname)==$currentversion) {
8201: if ($fname=~/^(.+)\.\d+\.(\w+(?:\.meta)*)$/) {
8202: my $root=$1;
8203: my $extension=$2;
8204: symlink($root.'.'.$extension,
8205: $root.'.'.$currentversion.'.'.$extension);
8206: unless ($extension=~/\.meta$/) {
8207: symlink($root.'.'.$extension.'.meta',
8208: $root.'.'.$currentversion.'.'.$extension.'.meta');
8209: }
8210: }
8211: }
8212: }
8213: if (-e $fname) {
8214: if (-d $fname) {
8215: $result="directory\n";
8216: } else {
8217: if (-e "$fname.$clientname") {&unsub($fname,$clientip);}
8218: my $now=time;
8219: my $found=&addline($fname,$clientname,$clientip,
8220: "$clientname:$clientip:$now\n");
8221: if ($found) { $result="$fname\n"; }
8222: # if they were subscribed to only meta data, delete that
8223: # subscription, when you subscribe to a file you also get
8224: # the metadata
8225: unless ($fname=~/\.meta$/) { &unsub("$fname.meta",$clientip); }
8226: $fname=~s/\/home\/httpd\/html\/res/raw/;
8227: my $protocol = $Apache::lonnet::protocol{$perlvar{'lonHostID'}};
8228: $protocol = 'http' if ($protocol ne 'https');
8229: $fname=$protocol.'://'.&Apache::lonnet::hostname($perlvar{'lonHostID'})."/".$fname;
8230: $result="$fname\n";
8231: }
8232: } else {
8233: $result="not_found\n";
8234: }
8235: } else {
8236: $result="rejected\n";
8237: }
8238: return $result;
8239: }
8240: # Change the passwd of a unix user. The caller must have
8241: # first verified that the user is a loncapa user.
8242: #
8243: # Parameters:
8244: # user - Unix user name to change.
8245: # pass - New password for the user.
8246: # Returns:
8247: # ok - if success
8248: # other - Some meaningfule error message string.
8249: # NOTE:
8250: # invokes a setuid script to change the passwd.
8251: sub change_unix_password {
8252: my ($user, $pass) = @_;
8253:
8254: &Debug("change_unix_password");
8255: my $execdir=$perlvar{'lonDaemons'};
8256: &Debug("Opening lcpasswd pipeline");
8257: my $pf = IO::File->new("|$execdir/lcpasswd > "
8258: ."$perlvar{'lonDaemons'}"
8259: ."/logs/lcpasswd.log");
8260: print $pf "$user\n$pass\n$pass\n";
8261: close $pf;
8262: my $err = $?;
8263: return ($err < @passwderrors) ? $passwderrors[$err] :
8264: "pwchange_falure - unknown error";
8265:
8266:
8267: }
8268:
8269:
8270: sub make_passwd_file {
8271: my ($uname,$udom,$umode,$npass,$passfilename,$action)=@_;
8272: my $result="ok";
8273: if ($umode eq 'krb4' or $umode eq 'krb5') {
8274: {
8275: my $pf = IO::File->new(">$passfilename");
8276: if ($pf) {
8277: print $pf "$umode:$npass\n";
8278: &update_passwd_history($uname,$udom,$umode,$action);
8279: } else {
8280: $result = "pass_file_failed_error";
8281: }
8282: }
8283: } elsif ($umode eq 'internal') {
8284: my $ncpass = &hash_passwd($udom,$npass);
8285: {
8286: &Debug("Creating internal auth");
8287: my $pf = IO::File->new(">$passfilename");
8288: if($pf) {
8289: print $pf "internal:$ncpass\n";
8290: &update_passwd_history($uname,$udom,$umode,$action);
8291: } else {
8292: $result = "pass_file_failed_error";
8293: }
8294: }
8295: } elsif ($umode eq 'localauth') {
8296: {
8297: my $pf = IO::File->new(">$passfilename");
8298: if($pf) {
8299: print $pf "localauth:$npass\n";
8300: &update_passwd_history($uname,$udom,$umode,$action);
8301: } else {
8302: $result = "pass_file_failed_error";
8303: }
8304: }
8305: } elsif ($umode eq 'unix') {
8306: &logthis(">>>Attempt to create unix account blocked -- unix auth not available for new users.");
8307: $result="no_new_unix_accounts";
8308: } elsif ($umode eq 'none') {
8309: {
8310: my $pf = IO::File->new("> $passfilename");
8311: if($pf) {
8312: print $pf "none:\n";
8313: } else {
8314: $result = "pass_file_failed_error";
8315: }
8316: }
8317: } else {
8318: $result="auth_mode_error";
8319: }
8320: return $result;
8321: }
8322:
8323: sub convert_photo {
8324: my ($start,$dest)=@_;
8325: system("convert $start $dest");
8326: }
8327:
8328: sub sethost {
8329: my ($remotereq) = @_;
8330: my (undef,$hostid)=split(/:/,$remotereq);
8331: # ignore sethost if we are already correct
8332: if ($hostid eq $currenthostid) {
8333: return 'ok';
8334: }
8335:
8336: if (!defined($hostid)) { $hostid=$perlvar{'lonHostID'}; }
8337: if (&Apache::lonnet::get_host_ip($perlvar{'lonHostID'})
8338: eq &Apache::lonnet::get_host_ip($hostid)) {
8339: $currenthostid =$hostid;
8340: $currentdomainid=&Apache::lonnet::host_domain($hostid);
8341: # &logthis("Setting hostid to $hostid, and domain to $currentdomainid");
8342: } else {
8343: &logthis("Requested host id $hostid not an alias of ".
8344: $perlvar{'lonHostID'}." refusing connection");
8345: return 'unable_to_set';
8346: }
8347: return 'ok';
8348: }
8349:
8350: sub version {
8351: my ($userinput)=@_;
8352: $remoteVERSION=(split(/:/,$userinput))[1];
8353: return "version:$VERSION";
8354: }
8355:
8356: sub get_usersession_config {
8357: my ($dom,$name) = @_;
8358: my ($usersessionconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
8359: if (defined($cached)) {
8360: return $usersessionconf;
8361: } else {
8362: my %domconfig = &Apache::lonnet::get_dom('configuration',['usersessions'],$dom);
8363: &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'usersessions'},3600);
8364: return $domconfig{'usersessions'};
8365: }
8366: return;
8367: }
8368:
8369: sub get_usersearch_config {
8370: my ($dom,$name) = @_;
8371: my ($usersearchconf,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
8372: if (defined($cached)) {
8373: return $usersearchconf;
8374: } else {
8375: my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$dom);
8376: &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'directorysrch'},600);
8377: return $domconfig{'directorysrch'};
8378: }
8379: return;
8380: }
8381:
8382: sub get_prohibited {
8383: my ($dom) = @_;
8384: my $name = 'trust';
8385: my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new($name,$dom);
8386: unless (defined($cached)) {
8387: my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$dom);
8388: &Apache::lonnet::do_cache_new($name,$dom,$domconfig{'trust'},3600);
8389: $trustconfig = $domconfig{'trust'};
8390: }
8391: my %prohibited;
8392: if (ref($trustconfig)) {
8393: foreach my $prefix (keys(%{$trustconfig})) {
8394: if (ref($trustconfig->{$prefix}) eq 'HASH') {
8395: my $reject;
8396: if (ref($trustconfig->{$prefix}->{'exc'}) eq 'ARRAY') {
8397: if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'exc'}})) {
8398: $reject = 1;
8399: }
8400: }
8401: if (ref($trustconfig->{$prefix}->{'inc'}) eq 'ARRAY') {
8402: if (grep(/^\Q$clientintdom\E$/,@{$trustconfig->{$prefix}->{'inc'}})) {
8403: $reject = 0;
8404: } else {
8405: $reject = 1;
8406: }
8407: }
8408: if ($reject) {
8409: $prohibited{$prefix} = 1;
8410: }
8411: }
8412: }
8413: }
8414: return %prohibited;
8415: }
8416:
8417: sub distro_and_arch {
8418: return $dist.':'.$arch;
8419: }
8420:
8421: # ----------------------------------- POD (plain old documentation, CPAN style)
8422:
8423: =head1 NAME
8424:
8425: lond - "LON Daemon" Server (port "LOND" 5663)
8426:
8427: =head1 SYNOPSIS
8428:
8429: Usage: B<lond>
8430:
8431: Should only be run as user=www. This is a command-line script which
8432: is invoked by B<loncron>. There is no expectation that a typical user
8433: will manually start B<lond> from the command-line. (In other words,
8434: DO NOT START B<lond> YOURSELF.)
8435:
8436: =head1 DESCRIPTION
8437:
8438: There are two characteristics associated with the running of B<lond>,
8439: PROCESS MANAGEMENT (starting, stopping, handling child processes)
8440: and SERVER-SIDE ACTIVITIES (password authentication, user creation,
8441: subscriptions, etc). These are described in two large
8442: sections below.
8443:
8444: B<PROCESS MANAGEMENT>
8445:
8446: Preforker - server who forks first. Runs as a daemon. HUPs.
8447: Uses IDEA encryption
8448:
8449: B<lond> forks off children processes that correspond to the other servers
8450: in the network. Management of these processes can be done at the
8451: parent process level or the child process level.
8452:
8453: B<logs/lond.log> is the location of log messages.
8454:
8455: The process management is now explained in terms of linux shell commands,
8456: subroutines internal to this code, and signal assignments:
8457:
8458: =over 4
8459:
8460: =item *
8461:
8462: PID is stored in B<logs/lond.pid>
8463:
8464: This is the process id number of the parent B<lond> process.
8465:
8466: =item *
8467:
8468: SIGTERM and SIGINT
8469:
8470: Parent signal assignment:
8471: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
8472:
8473: Child signal assignment:
8474: $SIG{INT} = 'DEFAULT'; (and SIGTERM is DEFAULT also)
8475: (The child dies and a SIGALRM is sent to parent, awaking parent from slumber
8476: to restart a new child.)
8477:
8478: Command-line invocations:
8479: B<kill> B<-s> SIGTERM I<PID>
8480: B<kill> B<-s> SIGINT I<PID>
8481:
8482: Subroutine B<HUNTSMAN>:
8483: This is only invoked for the B<lond> parent I<PID>.
8484: This kills all the children, and then the parent.
8485: The B<lonc.pid> file is cleared.
8486:
8487: =item *
8488:
8489: SIGHUP
8490:
8491: Current bug:
8492: This signal can only be processed the first time
8493: on the parent process. Subsequent SIGHUP signals
8494: have no effect.
8495:
8496: Parent signal assignment:
8497: $SIG{HUP} = \&HUPSMAN;
8498:
8499: Child signal assignment:
8500: none (nothing happens)
8501:
8502: Command-line invocations:
8503: B<kill> B<-s> SIGHUP I<PID>
8504:
8505: Subroutine B<HUPSMAN>:
8506: This is only invoked for the B<lond> parent I<PID>,
8507: This kills all the children, and then the parent.
8508: The B<lond.pid> file is cleared.
8509:
8510: =item *
8511:
8512: SIGUSR1
8513:
8514: Parent signal assignment:
8515: $SIG{USR1} = \&USRMAN;
8516:
8517: Child signal assignment:
8518: $SIG{USR1}= \&logstatus;
8519:
8520: Command-line invocations:
8521: B<kill> B<-s> SIGUSR1 I<PID>
8522:
8523: Subroutine B<USRMAN>:
8524: When invoked for the B<lond> parent I<PID>,
8525: SIGUSR1 is sent to all the children, and the status of
8526: each connection is logged.
8527:
8528: =item *
8529:
8530: SIGUSR2
8531:
8532: Parent Signal assignment:
8533: $SIG{USR2} = \&UpdateHosts
8534:
8535: Child signal assignment:
8536: NONE
8537:
8538:
8539: =item *
8540:
8541: SIGCHLD
8542:
8543: Parent signal assignment:
8544: $SIG{CHLD} = \&REAPER;
8545:
8546: Child signal assignment:
8547: none
8548:
8549: Command-line invocations:
8550: B<kill> B<-s> SIGCHLD I<PID>
8551:
8552: Subroutine B<REAPER>:
8553: This is only invoked for the B<lond> parent I<PID>.
8554: Information pertaining to the child is removed.
8555: The socket port is cleaned up.
8556:
8557: =back
8558:
8559: B<SERVER-SIDE ACTIVITIES>
8560:
8561: Server-side information can be accepted in an encrypted or non-encrypted
8562: method.
8563:
8564: =over 4
8565:
8566: =item ping
8567:
8568: Query a client in the hosts.tab table; "Are you there?"
8569:
8570: =item pong
8571:
8572: Respond to a ping query.
8573:
8574: =item ekey
8575:
8576: Read in encrypted key, make cipher. Respond with a buildkey.
8577:
8578: =item load
8579:
8580: Respond with CPU load based on a computation upon /proc/loadavg.
8581:
8582: =item currentauth
8583:
8584: Reply with current authentication information (only over an
8585: encrypted channel).
8586:
8587: =item auth
8588:
8589: Only over an encrypted channel, reply as to whether a user's
8590: authentication information can be validated.
8591:
8592: =item passwd
8593:
8594: Allow for a password to be set.
8595:
8596: =item makeuser
8597:
8598: Make a user.
8599:
8600: =item changeuserauth
8601:
8602: Allow for authentication mechanism and password to be changed.
8603:
8604: =item home
8605:
8606: Respond to a question "are you the home for a given user?"
8607:
8608: =item update
8609:
8610: Update contents of a subscribed resource.
8611:
8612: =item unsubscribe
8613:
8614: The server is unsubscribing from a resource.
8615:
8616: =item subscribe
8617:
8618: The server is subscribing to a resource.
8619:
8620: =item log
8621:
8622: Place in B<logs/lond.log>
8623:
8624: =item put
8625:
8626: stores hash in namespace
8627:
8628: =item rolesput
8629:
8630: put a role into a user's environment
8631:
8632: =item get
8633:
8634: returns hash with keys from array
8635: reference filled in from namespace
8636:
8637: =item eget
8638:
8639: returns hash with keys from array
8640: reference filled in from namesp (encrypts the return communication)
8641:
8642: =item rolesget
8643:
8644: get a role from a user's environment
8645:
8646: =item del
8647:
8648: deletes keys out of array from namespace
8649:
8650: =item keys
8651:
8652: returns namespace keys
8653:
8654: =item dump
8655:
8656: dumps the complete (or key matching regexp) namespace into a hash
8657:
8658: =item store
8659:
8660: stores hash permanently
8661: for this url; hashref needs to be given and should be a \%hashname; the
8662: remaining args aren't required and if they aren't passed or are '' they will
8663: be derived from the ENV
8664:
8665: =item restore
8666:
8667: returns a hash for a given url
8668:
8669: =item querysend
8670:
8671: Tells client about the lonsql process that has been launched in response
8672: to a sent query.
8673:
8674: =item queryreply
8675:
8676: Accept information from lonsql and make appropriate storage in temporary
8677: file space.
8678:
8679: =item idput
8680:
8681: Defines usernames as corresponding to IDs. (These "IDs" are unique identifiers
8682: for each student, defined perhaps by the institutional Registrar.)
8683:
8684: =item idget
8685:
8686: Returns usernames corresponding to IDs. (These "IDs" are unique identifiers
8687: for each student, defined perhaps by the institutional Registrar.)
8688:
8689: =item iddel
8690:
8691: Deletes one or more ids in a domain's id database.
8692:
8693: =item tmpput
8694:
8695: Accept and store information in temporary space.
8696:
8697: =item tmpget
8698:
8699: Send along temporarily stored information.
8700:
8701: =item ls
8702:
8703: List part of a user's directory.
8704:
8705: =item pushtable
8706:
8707: Pushes a file in /home/httpd/lonTab directory. Currently limited to:
8708: hosts.tab and domain.tab. The old file is copied to *.tab.backup but
8709: must be restored manually in case of a problem with the new table file.
8710: pushtable requires that the request be encrypted and validated via
8711: ValidateManager. The form of the command is:
8712: enc:pushtable tablename <tablecontents> \n
8713: where pushtable, tablename and <tablecontents> will be encrypted, but \n is a
8714: cleartext newline.
8715:
8716: =item Hanging up (exit or init)
8717:
8718: What to do when a client tells the server that they (the client)
8719: are leaving the network.
8720:
8721: =item unknown command
8722:
8723: If B<lond> is sent an unknown command (not in the list above),
8724: it replys to the client "unknown_cmd".
8725:
8726:
8727: =item UNKNOWN CLIENT
8728:
8729: If the anti-spoofing algorithm cannot verify the client,
8730: the client is rejected (with a "refused" message sent
8731: to the client, and the connection is closed.
8732:
8733: =back
8734:
8735: =head1 PREREQUISITES
8736:
8737: IO::Socket
8738: IO::File
8739: Apache::File
8740: POSIX
8741: Crypt::IDEA
8742: GDBM_File
8743: Authen::Krb4
8744: Authen::Krb5
8745:
8746: =head1 COREQUISITES
8747:
8748: none
8749:
8750: =head1 OSNAMES
8751:
8752: linux
8753:
8754: =head1 SCRIPT CATEGORIES
8755:
8756: Server/Process
8757:
8758: =cut
8759:
8760:
8761: =pod
8762:
8763: =head1 LOG MESSAGES
8764:
8765: The messages below can be emitted in the lond log. This log is located
8766: in ~httpd/perl/logs/lond.log Many log messages have HTML encapsulation
8767: to provide coloring if examined from inside a web page. Some do not.
8768: Where color is used, the colors are; Red for sometihhng to get excited
8769: about and to follow up on. Yellow for something to keep an eye on to
8770: be sure it does not get worse, Green,and Blue for informational items.
8771:
8772: In the discussions below, sometimes reference is made to ~httpd
8773: when describing file locations. There isn't really an httpd
8774: user, however there is an httpd directory that gets installed in the
8775: place that user home directories go. On linux, this is usually
8776: (always?) /home/httpd.
8777:
8778:
8779: Some messages are colorless. These are usually (not always)
8780: Green/Blue color level messages.
8781:
8782: =over 2
8783:
8784: =item (Red) LocalConnection rejecting non local: <ip> ne 127.0.0.1
8785:
8786: A local connection negotiation was attempted by
8787: a host whose IP address was not 127.0.0.1.
8788: The socket is closed and the child will exit.
8789: lond has three ways to establish an encyrption
8790: key with a client:
8791:
8792: =over 2
8793:
8794: =item local
8795:
8796: The key is written and read from a file.
8797: This is only valid for connections from localhost.
8798:
8799: =item insecure
8800:
8801: The key is generated by the server and
8802: transmitted to the client.
8803:
8804: =item ssl (secure)
8805:
8806: An ssl connection is negotiated with the client,
8807: the key is generated by the server and sent to the
8808: client across this ssl connection before the
8809: ssl connectionis terminated and clear text
8810: transmission resumes.
8811:
8812: =back
8813:
8814: =item (Red) LocalConnection: caller is insane! init = <init> and type = <type>
8815:
8816: The client is local but has not sent an initialization
8817: string that is the literal "init:local" The connection
8818: is closed and the child exits.
8819:
8820: =item Red CRITICAL Can't get key file <error>
8821:
8822: SSL key negotiation is being attempted but the call to
8823: lonssl::KeyFile failed. This usually means that the
8824: configuration file is not correctly defining or protecting
8825: the directories/files lonCertificateDirectory or
8826: lonnetPrivateKey
8827: <error> is a string that describes the reason that
8828: the key file could not be located.
8829:
8830: =item (Red) CRITICAL Can't get certificates <error>
8831:
8832: SSL key negotiation failed because we were not able to retrives our certificate
8833: or the CA's certificate in the call to lonssl::CertificateFile
8834: <error> is the textual reason this failed. Usual reasons:
8835:
8836: =over 2
8837:
8838: =item Apache config file for loncapa incorrect:
8839:
8840: one of the variables
8841: lonCertificateDirectory, lonnetCertificateAuthority, or lonnetCertificate
8842: undefined or incorrect
8843:
8844: =item Permission error:
8845:
8846: The directory pointed to by lonCertificateDirectory is not readable by lond
8847:
8848: =item Permission error:
8849:
8850: Files in the directory pointed to by lonCertificateDirectory are not readable by lond.
8851:
8852: =item Installation error:
8853:
8854: Either the certificate authority file or the certificate have not
8855: been installed in lonCertificateDirectory.
8856:
8857: =item (Red) CRITICAL SSL Socket promotion failed: <err>
8858:
8859: The promotion of the connection from plaintext to SSL failed
8860: <err> is the reason for the failure. There are two
8861: system calls involved in the promotion (one of which failed),
8862: a dup to produce
8863: a second fd on the raw socket over which the encrypted data
8864: will flow and IO::SOcket::SSL->new_from_fd which creates
8865: the SSL connection on the duped fd.
8866:
8867: =item (Blue) WARNING client did not respond to challenge
8868:
8869: This occurs on an insecure (non SSL) connection negotiation request.
8870: lond generates some number from the time, the PID and sends it to
8871: the client. The client must respond by echoing this information back.
8872: If the client does not do so, that's a violation of the challenge
8873: protocols and the connection will be failed.
8874:
8875: =item (Red) No manager table. Nobody can manage!!
8876:
8877: lond has the concept of privileged hosts that
8878: can perform remote management function such
8879: as update the hosts.tab. The manager hosts
8880: are described in the
8881: ~httpd/lonTabs/managers.tab file.
8882: this message is logged if this file is missing.
8883:
8884:
8885: =item (Green) Registering manager <dnsname> as <cluster_name> with <ipaddress>
8886:
8887: Reports the successful parse and registration
8888: of a specific manager.
8889:
8890: =item Green existing host <clustername:dnsname>
8891:
8892: The manager host is already defined in the hosts.tab
8893: the information in that table, rather than the info in the
8894: manager table will be used to determine the manager's ip.
8895:
8896: =item (Red) Unable to craete <filename>
8897:
8898: lond has been asked to create new versions of an administrative
8899: file (by a manager). When this is done, the new file is created
8900: in a temp file and then renamed into place so that there are always
8901: usable administrative files, even if the update fails. This failure
8902: message means that the temp file could not be created.
8903: The update is abandoned, and the old file is available for use.
8904:
8905: =item (Green) CopyFile from <oldname> to <newname> failed
8906:
8907: In an update of administrative files, the copy of the existing file to a
8908: backup file failed. The installation of the new file may still succeed,
8909: but there will not be a back up file to rever to (this should probably
8910: be yellow).
8911:
8912: =item (Green) Pushfile: backed up <oldname> to <newname>
8913:
8914: See above, the backup of the old administrative file succeeded.
8915:
8916: =item (Red) Pushfile: Unable to install <filename> <reason>
8917:
8918: The new administrative file could not be installed. In this case,
8919: the old administrative file is still in use.
8920:
8921: =item (Green) Installed new < filename>.
8922:
8923: The new administrative file was successfullly installed.
8924:
8925: =item (Red) Reinitializing lond pid=<pid>
8926:
8927: The lonc child process <pid> will be sent a USR2
8928: signal.
8929:
8930: =item (Red) Reinitializing self
8931:
8932: We've been asked to re-read our administrative files,and
8933: are doing so.
8934:
8935: =item (Yellow) error:Invalid process identifier <ident>
8936:
8937: A reinit command was received, but the target part of the
8938: command was not valid. It must be either
8939: 'lond' or 'lonc' but was <ident>
8940:
8941: =item (Green) isValideditCommand checking: Command = <command> Key = <key> newline = <newline>
8942:
8943: Checking to see if lond has been handed a valid edit
8944: command. It is possible the edit command is not valid
8945: in that case there are no log messages to indicate that.
8946:
8947: =item Result of password change for <username> pwchange_success
8948:
8949: The password for <username> was
8950: successfully changed.
8951:
8952: =item Unable to open <user> passwd to change password
8953:
8954: Could not rewrite the
8955: internal password file for a user
8956:
8957: =item Result of password change for <user> : <result>
8958:
8959: A unix password change for <user> was attempted
8960: and the pipe returned <result>
8961:
8962: =item LWP GET: <message> for <fname> (<remoteurl>)
8963:
8964: The lightweight process fetch for a resource failed
8965: with <message> the local filename that should
8966: have existed/been created was <fname> the
8967: corresponding URI: <remoteurl> This is emitted in several
8968: places.
8969:
8970: =item Unable to move <transname> to <destname>
8971:
8972: From fetch_user_file_handler - the user file was replicated but could not
8973: be mv'd to its final location.
8974:
8975: =item Looking for <domain> <username>
8976:
8977: From user_has_session_handler - This should be a Debug call instead
8978: it indicates lond is about to check whether the specified user has a
8979: session active on the specified domain on the local host.
8980:
8981: =item Client <ip> (<name>) hanging up: <input>
8982:
8983: lond has been asked to exit by its client. The <ip> and <name> identify the
8984: client systemand <input> is the full exit command sent to the server.
8985:
8986: =item Red CRITICAL: ABNORMAL EXIT. child <pid> for server <hostname> died through a crass with this error->[<message>].
8987:
8988: A lond child terminated. NOte that this termination can also occur when the
8989: child receives the QUIT or DIE signals. <pid> is the process id of the child,
8990: <hostname> the host lond is working for, and <message> the reason the child died
8991: to the best of our ability to get it (I would guess that any numeric value
8992: represents and errno value). This is immediately followed by
8993:
8994: =item Famous last words: Catching exception - <log>
8995:
8996: Where log is some recent information about the state of the child.
8997:
8998: =item Red CRITICAL: TIME OUT <pid>
8999:
9000: Some timeout occured for server <pid>. THis is normally a timeout on an LWP
9001: doing an HTTP::GET.
9002:
9003: =item child <pid> died
9004:
9005: The reaper caught a SIGCHILD for the lond child process <pid>
9006: This should be modified to also display the IP of the dying child
9007: $children{$pid}
9008:
9009: =item Unknown child 0 died
9010: A child died but the wait for it returned a pid of zero which really should not
9011: ever happen.
9012:
9013: =item Child <which> - <pid> looks like we missed it's death
9014:
9015: When a sigchild is received, the reaper process checks all children to see if they are
9016: alive. If children are dying quite quickly, the lack of signal queuing can mean
9017: that a signal hearalds the death of more than one child. If so this message indicates
9018: which other one died. <which> is the ip of a dead child
9019:
9020: =item Free socket: <shutdownretval>
9021:
9022: The HUNTSMAN sub was called due to a SIGINT in a child process. The socket is being shutdown.
9023: for whatever reason, <shutdownretval> is printed but in fact shutdown() is not documented
9024: to return anything. This is followed by:
9025:
9026: =item Red CRITICAL: Shutting down
9027:
9028: Just prior to exit.
9029:
9030: =item Free socket: <shutdownretval>
9031:
9032: The HUPSMAN sub was called due to a SIGHUP. all children get killsed, and lond execs itself.
9033: This is followed by:
9034:
9035: =item (Red) CRITICAL: Restarting
9036:
9037: lond is about to exec itself to restart.
9038:
9039: =item (Blue) Updating connections
9040:
9041: (In response to a USR2). All the children (except the one for localhost)
9042: are about to be killed, the hosts tab reread, and Apache reloaded via apachereload.
9043:
9044: =item (Blue) UpdateHosts killing child <pid> for ip <ip>
9045:
9046: Due to USR2 as above.
9047:
9048: =item (Green) keeping child for ip <ip> (pid = <pid>)
9049:
9050: In response to USR2 as above, the child indicated is not being restarted because
9051: it's assumed that we'll always need a child for the localhost.
9052:
9053:
9054: =item Going to check on the children
9055:
9056: Parent is about to check on the health of the child processes.
9057: Note that this is in response to a USR1 sent to the parent lond.
9058: there may be one or more of the next two messages:
9059:
9060: =item <pid> is dead
9061:
9062: A child that we have in our child hash as alive has evidently died.
9063:
9064: =item Child <pid> did not respond
9065:
9066: In the health check the child <pid> did not update/produce a pid_.txt
9067: file when sent it's USR1 signal. That process is killed with a 9 signal, as it's
9068: assumed to be hung in some un-fixable way.
9069:
9070: =item Finished checking children
9071:
9072: Master processs's USR1 processing is cojmplete.
9073:
9074: =item (Red) CRITICAL: ------- Starting ------
9075:
9076: (There are more '-'s on either side). Lond has forked itself off to
9077: form a new session and is about to start actual initialization.
9078:
9079: =item (Green) Attempting to start child (<client>)
9080:
9081: Started a new child process for <client>. Client is IO::Socket object
9082: connected to the child. This was as a result of a TCP/IP connection from a client.
9083:
9084: =item Unable to determine who caller was, getpeername returned nothing
9085:
9086: In child process initialization. either getpeername returned undef or
9087: a zero sized object was returned. Processing continues, but in my opinion,
9088: this should be cause for the child to exit.
9089:
9090: =item Unable to determine clientip
9091:
9092: In child process initialization. The peer address from getpeername was not defined.
9093: The client address is stored as "Unavailable" and processing continues.
9094:
9095: =item (Yellow) INFO: Connection <ip> <name> connection type = <type>
9096:
9097: In child initialization. A good connectionw as received from <ip>.
9098:
9099: =over 2
9100:
9101: =item <name>
9102:
9103: is the name of the client from hosts.tab.
9104:
9105: =item <type>
9106:
9107: Is the connection type which is either
9108:
9109: =over 2
9110:
9111: =item manager
9112:
9113: The connection is from a manager node, not in hosts.tab
9114:
9115: =item client
9116:
9117: the connection is from a non-manager in the hosts.tab
9118:
9119: =item both
9120:
9121: The connection is from a manager in the hosts.tab.
9122:
9123: =back
9124:
9125: =back
9126:
9127: =item (Blue) Certificates not installed -- trying insecure auth
9128:
9129: One of the certificate file, key file or
9130: certificate authority file could not be found for a client attempting
9131: SSL connection intiation. COnnection will be attemptied in in-secure mode.
9132: (this would be a system with an up to date lond that has not gotten a
9133: certificate from us).
9134:
9135: =item (Green) Successful local authentication
9136:
9137: A local connection successfully negotiated the encryption key.
9138: In this case the IDEA key is in a file (that is hopefully well protected).
9139:
9140: =item (Green) Successful ssl authentication with <client>
9141:
9142: The client (<client> is the peer's name in hosts.tab), has successfully
9143: negotiated an SSL connection with this child process.
9144:
9145: =item (Green) Successful insecure authentication with <client>
9146:
9147:
9148: The client has successfully negotiated an insecure connection withthe child process.
9149:
9150: =item (Yellow) Attempted insecure connection disallowed
9151:
9152: The client attempted and failed to successfully negotiate a successful insecure
9153: connection. This can happen either because the variable londAllowInsecure is false
9154: or undefined, or becuse the child did not successfully echo back the challenge
9155: string.
9156:
9157:
9158: =back
9159:
9160: =back
9161:
9162:
9163: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>