Annotation of loncom/LondConnection.pm, revision 1.38
1.2 albertel 1: # This module defines and implements a class that represents
2: # a connection to a lond daemon.
3: #
1.38 ! albertel 4: # $Id: LondConnection.pm,v 1.37 2005/05/27 21:49:18 albertel Exp $
1.2 albertel 5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
1.1 foxr 27: #
1.14 foxr 28:
1.1 foxr 29: package LondConnection;
30:
1.10 foxr 31: use strict;
1.1 foxr 32: use IO::Socket;
33: use IO::Socket::INET;
34: use IO::Handle;
35: use IO::File;
36: use Fcntl;
37: use POSIX;
38: use Crypt::IDEA;
1.31 foxr 39: use LONCAPA::lonlocal;
40: use LONCAPA::lonssl;
1.14 foxr 41:
1.1 foxr 42:
1.12 foxr 43:
44:
1.32 foxr 45: my $DebugLevel=0;
1.12 foxr 46: my %hostshash;
47: my %perlvar;
1.31 foxr 48: my $LocalDns = ""; # Need not be defined for managers.
49: my $InsecureOk;
1.1 foxr 50:
1.14 foxr 51: #
1.16 foxr 52: # Set debugging level
53: #
54: sub SetDebug {
55: $DebugLevel = shift;
56: }
57:
58: #
1.14 foxr 59: # The config read is done in this way to support the read of
60: # the non-default configuration file in the
61: # event we are being used outside of loncapa.
62: #
63:
64: my $ConfigRead = 0;
65:
1.1 foxr 66: # Read the configuration file for apache to get the perl
1.31 foxr 67: # variables set.
1.1 foxr 68:
1.12 foxr 69: sub ReadConfig {
1.31 foxr 70: Debug(8, "ReadConfig called");
71:
1.14 foxr 72: my $perlvarref = read_conf('loncapa.conf');
1.12 foxr 73: %perlvar = %{$perlvarref};
1.14 foxr 74: my $hoststab = read_hosts(
1.21 foxr 75: "$perlvar{lonTabDir}/hosts.tab") ||
1.14 foxr 76: die "Can't read host table!!";
1.12 foxr 77: %hostshash = %{$hoststab};
1.17 foxr 78: $ConfigRead = 1;
1.12 foxr 79:
1.31 foxr 80: my $myLonCapaName = $perlvar{lonHostID};
81: Debug(8, "My loncapa name is $myLonCapaName");
82:
83: if(defined $hostshash{$myLonCapaName}) {
84: Debug(8, "My loncapa name is in hosthash");
85: my @ConfigLine = @{$hostshash{$myLonCapaName}};
86: $LocalDns = $ConfigLine[3];
87: Debug(8, "Got local name $LocalDns");
88: }
89: $InsecureOk = $perlvar{loncAllowInsecure};
90:
91: Debug(3, "ReadConfig - LocalDNS = $LocalDns");
1.12 foxr 92: }
93:
1.15 foxr 94: #
95: # Read a foreign configuration.
96: # This sub is intended for the cases where the package
97: # will be read from outside the LonCAPA environment, in that case
98: # the client will need to explicitly provide:
99: # - A file in hosts.tab format.
100: # - Some idea of the 'lonCAPA' name of the local host (for building
101: # the encryption key).
102: #
103: # Parameters:
104: # MyHost - Name of this host as far as LonCAPA is concerned.
105: # Filename - Name of a hosts.tab formatted file that will be used
106: # to build up the hosts table.
107: #
108: sub ReadForeignConfig {
1.30 foxr 109:
110: my ($MyHost, $Filename) = @_;
1.15 foxr 111:
1.17 foxr 112: &Debug(4, "ReadForeignConfig $MyHost $Filename\n");
113:
1.15 foxr 114: $perlvar{lonHostID} = $MyHost; # Rmember my host.
115: my $hosttab = read_hosts($Filename) ||
116: die "Can't read hosts table!!";
1.17 foxr 117: %hostshash = %{$hosttab};
118: if($DebugLevel > 3) {
119: foreach my $host (keys %hostshash) {
1.31 foxr 120: print STDERR "host $host => $hostshash{$host}\n";
1.17 foxr 121: }
122: }
123: $ConfigRead = 1;
1.1 foxr 124:
1.31 foxr 125: my $myLonCapaName = $perlvar{lonHostID};
126:
127: if(defined $hostshash{$myLonCapaName}) {
128: my @ConfigLine = @{$hostshash{$myLonCapaName}};
129: $LocalDns = $ConfigLine[3];
130: }
131: $InsecureOk = $perlvar{loncAllowInsecure};
132:
133: Debug(3, "ReadForeignConfig - LocalDNS = $LocalDns");
134:
1.15 foxr 135: }
1.1 foxr 136:
137: sub Debug {
1.30 foxr 138:
139: my ($level, $message) = @_;
140:
1.1 foxr 141: if ($level < $DebugLevel) {
1.31 foxr 142: print STDERR ($message."\n");
1.1 foxr 143: }
144: }
1.3 albertel 145:
146: =pod
147:
148: =head2 Dump
149:
1.12 foxr 150: Dump the internal state of the object: For debugging purposes, to stderr.
1.3 albertel 151:
1.1 foxr 152: =cut
153:
154: sub Dump {
155: my $self = shift;
1.32 foxr 156: my $level = shift;
1.35 foxr 157: my $now = time;
158: my $local = localtime($now);
1.32 foxr 159:
1.37 albertel 160: if ($level >= $DebugLevel) {
1.32 foxr 161: return;
162: }
163:
1.35 foxr 164:
1.10 foxr 165: my $key;
166: my $value;
1.35 foxr 167: print STDERR "[ $local ] Dumping LondConnectionObject:\n";
1.37 albertel 168: print STDERR join(':',caller(1))."\n";
1.1 foxr 169: while(($key, $value) = each %$self) {
1.22 foxr 170: print STDERR "$key -> $value\n";
1.1 foxr 171: }
1.23 foxr 172: print STDERR "-------------------------------\n";
1.1 foxr 173: }
174:
175: =pod
1.3 albertel 176:
177: Local function to do a state transition. If the state transition
178: callback is defined it is called with two parameters: the self and the
179: old state.
180:
1.1 foxr 181: =cut
1.3 albertel 182:
1.1 foxr 183: sub Transition {
1.30 foxr 184:
185: my ($self, $newstate) = @_;
186:
1.1 foxr 187: my $oldstate = $self->{State};
188: $self->{State} = $newstate;
189: $self->{TimeoutRemaining} = $self->{TimeoutValue};
190: if($self->{TransitionCallback}) {
191: ($self->{TransitionCallback})->($self, $oldstate);
192: }
193: }
194:
1.3 albertel 195:
1.14 foxr 196:
1.1 foxr 197: =pod
1.3 albertel 198:
199: =head2 new
200:
201: Construct a new lond connection.
202:
203: Parameters (besides the class name) include:
204:
205: =item hostname
206:
207: host the remote lond is on. This host is a host in the hosts.tab file
208:
209: =item port
210:
211: port number the remote lond is listening on.
212:
1.1 foxr 213: =cut
1.3 albertel 214:
1.1 foxr 215: sub new {
1.30 foxr 216:
217: my ($class, $Hostname, $Port) = @_;
1.14 foxr 218:
219: if (!$ConfigRead) {
220: ReadConfig();
221: $ConfigRead = 1;
222: }
1.1 foxr 223: &Debug(4,$class."::new( ".$Hostname.",".$Port.")\n");
224:
225: # The host must map to an entry in the hosts table:
226: # We connect to the dns host that corresponds to that
227: # system and use the hostname for the encryption key
228: # negotion. In the objec these become the Host and
229: # LoncapaHim fields of the object respectively.
230: #
231: if (!exists $hostshash{$Hostname}) {
1.16 foxr 232: &Debug(8, "No Such host $Hostname");
1.1 foxr 233: return undef; # No such host!!!
234: }
235: my @ConfigLine = @{$hostshash{$Hostname}};
236: my $DnsName = $ConfigLine[3]; # 4'th item is dns of host.
237: Debug(5, "Connecting to ".$DnsName);
1.36 albertel 238: # if it is me use loopback for connection
239: if ($DnsName eq $LocalDns) { $DnsName="127.0.0.1"; }
240: Debug(8, "Connecting to $DnsName I am $LocalDns");
1.1 foxr 241: # Now create the object...
242: my $self = { Host => $DnsName,
1.24 foxr 243: LoncapaHim => $Hostname,
244: Port => $Port,
245: State => "Initialized",
1.31 foxr 246: AuthenticationMode => "",
1.24 foxr 247: TransactionRequest => "",
248: TransactionReply => "",
249: InformReadable => 0,
250: InformWritable => 0,
251: TimeoutCallback => undef,
252: TransitionCallback => undef,
253: Timeoutable => 0,
254: TimeoutValue => 30,
255: TimeoutRemaining => 0,
1.31 foxr 256: LocalKeyFile => "",
1.24 foxr 257: CipherKey => "",
258: LondVersion => "Unknown",
259: Cipher => undef};
1.1 foxr 260: bless($self, $class);
261: unless ($self->{Socket} = IO::Socket::INET->new(PeerHost => $self->{Host},
1.27 foxr 262: PeerPort => $self->{Port},
263: Type => SOCK_STREAM,
264: Proto => "tcp",
265: Timeout => 3)) {
1.36 albertel 266: Debug(8, "Error? \n$@ \n$!");
1.1 foxr 267: return undef; # Inidicates the socket could not be made.
268: }
1.31 foxr 269: my $socket = $self->{Socket}; # For local use only.
1.33 foxr 270: # If we are local, we'll first try local auth mode, otherwise, we'll try
271: # the ssl auth mode:
1.31 foxr 272:
273: my $key;
274: my $keyfile;
1.36 albertel 275: if ($DnsName eq '127.0.0.1') {
1.31 foxr 276: $self->{AuthenticationMode} = "local";
277: ($key, $keyfile) = lonlocal::CreateKeyFile();
278: Debug(8, "Local key: $key, stored in $keyfile");
279:
280: # If I can't make the key file fall back to insecure if
281: # allowed...else give up right away.
282:
283: if(!(defined $key) || !(defined $keyfile)) {
284: if($InsecureOk) {
285: $self->{AuthenticationMode} = "insecure";
286: $self->{TransactionRequest} = "init\n";
287: }
288: else {
289: $socket->close;
290: return undef;
291: }
292: }
293: $self->{TransactionRequest} = "init:local:$keyfile\n";
294: Debug(9, "Init string is init:local:$keyfile");
295: if(!$self->CreateCipher($key)) { # Nothing's going our way...
296: $socket->close;
297: return undef;
298: }
299:
1.33 foxr 300: }
1.31 foxr 301: else {
1.33 foxr 302: # Remote peer: I'd like to do ssl, but if my host key or certificates
303: # are not all installed, my only choice is insecure, if that's
304: # allowed:
305:
306: my ($ca, $cert) = lonssl::CertificateFile;
307: my $sslkeyfile = lonssl::KeyFile;
308:
309: if((defined $ca) && (defined $cert) && (defined $sslkeyfile)) {
310:
311: $self->{AuthenticationMode} = "ssl";
312: $self->{TransactionRequest} = "init:ssl\n";
313: } else {
314: if($InsecureOk) { # Allowed to do insecure:
315: $self->{AuthenticationMode} = "insecure";
316: $self->{TransactionRequest} = "init\n";
317: }
318: else { # Not allowed to do insecure...
319: $socket->close;
320: return undef;
321: }
322: }
1.31 foxr 323: }
324:
1.1 foxr 325: #
326: # We're connected. Set the state, and the events we'll accept:
327: #
328: $self->Transition("Connected");
329: $self->{InformWritable} = 1; # When socket is writable we send init
1.9 foxr 330: $self->{Timeoutable} = 1; # Timeout allowed during startup negotiation.
1.31 foxr 331:
1.1 foxr 332:
333: #
334: # Set socket to nonblocking I/O.
335: #
336: my $socket = $self->{Socket};
1.31 foxr 337: my $flags = fcntl($socket, F_GETFL,0);
338: if(!$flags) {
1.1 foxr 339: $socket->close;
340: return undef;
341: }
1.31 foxr 342: if(!fcntl($socket, F_SETFL, $flags | O_NONBLOCK)) {
1.1 foxr 343: $socket->close;
344: return undef;
345: }
346:
347: # return the object :
348:
1.31 foxr 349: Debug(9, "Initial object state: ");
1.32 foxr 350: $self->Dump(9);
1.31 foxr 351:
1.1 foxr 352: return $self;
353: }
1.3 albertel 354:
1.1 foxr 355: =pod
1.3 albertel 356:
357: =head2 Readable
358:
359: This member should be called when the Socket becomes readable. Until
360: the read completes, action is state independet. Data are accepted into
361: the TransactionReply until a newline character is received. At that
362: time actionis state dependent:
363:
364: =item Connected
365:
366: in this case we received challenge, the state changes to
367: ChallengeReceived, and we initiate a send with the challenge response.
368:
369: =item ReceivingReply
370:
371: In this case a reply has been received for a transaction, the state
372: goes to Idle and we disable write and read notification.
373:
374: =item ChallengeReeived
375:
376: we just got what should be an ok\n and the connection can now handle
377: transactions.
1.1 foxr 378:
379: =cut
1.3 albertel 380:
1.1 foxr 381: sub Readable {
382: my $self = shift;
383: my $socket = $self->{Socket};
384: my $data = '';
1.27 foxr 385: my $rv;
1.31 foxr 386: my $ConnectionMode = $self->{AuthenticationMode};
387:
1.27 foxr 388: if ($socket) {
389: eval {
390: $rv = $socket->recv($data, POSIX::BUFSIZ, 0);
391: }
392: } else {
393: $self->Transition("Disconnected");
394: return -1;
395: }
1.1 foxr 396: my $errno = $! + 0; # Force numeric context.
397:
1.8 foxr 398: unless (defined($rv) && length $data) {# Read failed,
1.1 foxr 399: if(($errno == POSIX::EWOULDBLOCK) ||
400: ($errno == POSIX::EAGAIN) ||
1.8 foxr 401: ($errno == POSIX::EINTR)) {
1.1 foxr 402: return 0;
403: }
404:
405: # Connection likely lost.
406: &Debug(4, "Connection lost");
407: $self->{TransactionRequest} = '';
408: $socket->close();
409: $self->Transition("Disconnected");
410: return -1;
411: }
412: # Append the data to the buffer. And figure out if the read is done:
413:
414: &Debug(9,"Received from host: ".$data);
415: $self->{TransactionReply} .= $data;
1.29 albertel 416: if($self->{TransactionReply} =~ m/\n$/) {
1.1 foxr 417: &Debug(8,"Readable End of line detected");
1.31 foxr 418:
419:
1.1 foxr 420: if ($self->{State} eq "Initialized") { # We received the challenge:
1.31 foxr 421: # Our init was replied to. What happens next depends both on
422: # the actual init we sent (AuthenticationMode member data)
423: # and the response:
424: # AuthenticationMode == local:
425: # Response ok: The key has been exchanged and
426: # the key file destroyed. We can jump
427: # into setting the host and requesting the
428: # Later we'll also bypass key exchange.
429: # Response digits:
430: # Old style lond. Delete the keyfile.
431: # If allowed fall back to insecure mode.
432: # else close connection and fail.
433: # Response other:
434: # Failed local auth
435: # Close connection and fail.
436: #
437: # AuthenticationMode == ssl:
438: # Response ok:ssl
439: # Response digits:
440: # Response other:
441: # Authentication mode == insecure
442: # Response digits
443: # Response other:
444:
445: my $Response = $self->{TransactionReply};
446: if($ConnectionMode eq "local") {
447: if($Response =~ /^ok:local/) { # Good local auth.
448: $self->ToVersionRequest();
449: return 0;
450: }
451: elsif ($Response =~/^[0-9]+/) { # Old style lond.
452: return $self->CompleteInsecure();
453:
454: }
455: else { # Complete flop
456: &Debug(3, "init:local : unrecognized reply");
457: $self->Transition("Disconnected");
458: $socket->close;
459: return -1;
460: }
461: }
462: elsif ($ConnectionMode eq "ssl") {
463: if($Response =~ /^ok:ssl/) { # Good ssl...
464: if($self->ExchangeKeysViaSSL()) { # Success skip to vsn stuff
465: # Need to reset to non blocking:
466:
467: my $flags = fcntl($socket, F_GETFL, 0);
468: fcntl($socket, F_SETFL, $flags | O_NONBLOCK);
469: $self->ToVersionRequest();
470: return 0;
471: }
472: else { # Failed in ssl exchange.
473: &Debug(3,"init:ssl failed key negotiation!");
474: $self->Transition("Disconnected");
475: $socket->close;
476: return -1;
477: }
478: }
479: elsif ($Response =~ /^[0-9]+/) { # Old style lond.
480: return $self->CompleteInsecure();
481: }
482: else { # Complete flop
483: }
484: }
485: elsif ($ConnectionMode eq "insecure") {
486: if($self->{TransactionReply} eq "refused\n") { # Remote doesn't have
487:
488: $self->Transition("Disconnected"); # in host tables.
489: $socket->close();
490: return -1;
491:
492: }
493: return $self->CompleteInsecure();
494: }
495: else {
496: &Debug(1,"Authentication mode incorrect");
497: die "BUG!!! LondConnection::Readable invalid authmode";
1.1 foxr 498: }
1.27 foxr 499:
1.31 foxr 500:
1.28 albertel 501: } elsif ($self->{State} eq "ChallengeReplied") {
502: if($self->{TransactionReply} ne "ok\n") {
503: $self->Transition("Disconnected");
504: $socket->close();
505: return -1;
506: }
1.31 foxr 507: $self->ToVersionRequest();
1.28 albertel 508: return 0;
1.31 foxr 509:
1.28 albertel 510: } elsif ($self->{State} eq "ReadingVersionString") {
1.38 ! albertel 511: chomp($self->{TransactionReply});
! 512: $self->{LondVersion} = $self->{TransactionReply};
1.28 albertel 513: $self->Transition("SetHost");
514: $self->{InformReadable} = 0;
515: $self->{InformWritable} = 1;
516: my $peer = $self->{LoncapaHim};
517: $self->{TransactionRequest}= "sethost:$peer\n";
518: return 0;
1.24 foxr 519: } elsif ($self->{State} eq "HostSet") { # should be ok.
1.28 albertel 520: if($self->{TransactionReply} ne "ok\n") {
521: $self->Transition("Disconnected");
522: $socket->close();
523: return -1;
524: }
1.31 foxr 525: # If the auth mode is insecure we must still
526: # exchange session keys. Otherwise,
527: # we can just transition to idle.
528:
529: if($ConnectionMode eq "insecure") {
530: $self->Transition("RequestingKey");
531: $self->{InformReadable} = 0;
532: $self->{InformWritable} = 1;
533: $self->{TransactionRequest} = "ekey\n";
534: return 0;
535: }
536: else {
537: $self->ToIdle();
538: return 0;
539: }
1.1 foxr 540: } elsif ($self->{State} eq "ReceivingKey") {
541: my $buildkey = $self->{TransactionReply};
542: my $key = $self->{LoncapaHim}.$perlvar{'lonHostID'};
543: $key=~tr/a-z/A-Z/;
544: $key=~tr/G-P/0-9/;
545: $key=~tr/Q-Z/0-9/;
1.31 foxr 546: $key =$key.$buildkey.$key.$buildkey.$key.$buildkey;
547: $key = substr($key,0,32);
548: if(!$self->CreateCipher($key)) {
1.1 foxr 549: $self->Transition("Disconnected");
550: $socket->close();
551: return -1;
552: } else {
1.31 foxr 553: $self->ToIdle();
1.1 foxr 554: return 0;
555: }
556: } elsif ($self->{State} eq "ReceivingReply") {
557:
558: # If the data are encrypted, decrypt first.
559:
560: my $answer = $self->{TransactionReply};
561: if($answer =~ /^enc\:/) {
562: $answer = $self->Decrypt($answer);
1.34 foxr 563: $self->{TransactionReply} = "$answer\n";
1.1 foxr 564: }
565:
566: # finish the transaction
567:
1.31 foxr 568: $self->ToIdle();
1.1 foxr 569: return 0;
570: } elsif ($self->{State} eq "Disconnected") { # No connection.
571: return -1;
572: } else { # Internal error: Invalid state.
573: $self->Transition("Disconnected");
574: $socket->close();
575: return -1;
576: }
577: }
578:
579: return 0;
1.27 foxr 580:
1.1 foxr 581: }
582:
583:
584: =pod
1.3 albertel 585:
586: This member should be called when the Socket becomes writable.
587:
588: The action is state independent. An attempt is made to drain the
589: contents of the TransactionRequest member. Once this is drained, we
590: mark the object as waiting for readability.
1.1 foxr 591:
592: Returns 0 if successful, or -1 if not.
1.3 albertel 593:
1.1 foxr 594: =cut
595: sub Writable {
596: my $self = shift; # Get reference to the object.
597: my $socket = $self->{Socket};
1.26 albertel 598: my $nwritten;
599: if ($socket) {
600: eval {
601: $nwritten = $socket->send($self->{TransactionRequest}, 0);
602: }
1.27 foxr 603: } else {
604: # For whatever reason, there's no longer a socket left.
605:
606:
607: $self->Transition("Disconnected");
608: return -1;
1.26 albertel 609: }
1.1 foxr 610: my $errno = $! + 0;
611: unless (defined $nwritten) {
612: if($errno != POSIX::EINTR) {
613: $self->Transition("Disconnected");
614: return -1;
615: }
616:
617: }
1.10 foxr 618: if (($nwritten >= 0) ||
1.1 foxr 619: ($errno == POSIX::EWOULDBLOCK) ||
620: ($errno == POSIX::EAGAIN) ||
621: ($errno == POSIX::EINTR) ||
622: ($errno == 0)) {
623: substr($self->{TransactionRequest}, 0, $nwritten) = ""; # rmv written part
1.27 foxr 624: if(length $self->{TransactionRequest} == 0) {
625: $self->{InformWritable} = 0;
626: $self->{InformReadable} = 1;
627: $self->{TransactionReply} = '';
628: #
629: # Figure out the next state:
630: #
631: if($self->{State} eq "Connected") {
632: $self->Transition("Initialized");
633: } elsif($self->{State} eq "ChallengeReceived") {
634: $self->Transition("ChallengeReplied");
635: } elsif($self->{State} eq "RequestingVersion") {
636: $self->Transition("ReadingVersionString");
637: } elsif ($self->{State} eq "SetHost") {
638: $self->Transition("HostSet");
639: } elsif($self->{State} eq "RequestingKey") {
640: $self->Transition("ReceivingKey");
1.24 foxr 641: # $self->{InformWritable} = 0;
642: # $self->{InformReadable} = 1;
643: # $self->{TransactionReply} = '';
1.27 foxr 644: } elsif ($self->{State} eq "SendingRequest") {
645: $self->Transition("ReceivingReply");
646: $self->{TimeoutRemaining} = $self->{TimeoutValue};
647: } elsif ($self->{State} eq "Disconnected") {
648: return -1;
649: }
650: return 0;
651: }
652: } else { # The write failed (e.g. partner disconnected).
653: $self->Transition("Disconnected");
654: $socket->close();
655: return -1;
656: }
657:
1.1 foxr 658: }
659: =pod
1.3 albertel 660:
661: =head2 Tick
662:
1.1 foxr 663: Tick is called every time unit by the event framework. It
1.3 albertel 664:
665: =item 1 decrements the remaining timeout.
666:
667: =item 2 If the timeout is zero, calls TimedOut indicating that the current operation timed out.
1.1 foxr 668:
669: =cut
670:
671: sub Tick {
672: my $self = shift;
673: $self->{TimeoutRemaining}--;
674: if ($self->{TimeoutRemaining} < 0) {
675: $self->TimedOut();
676: }
677: }
1.3 albertel 678:
1.1 foxr 679: =pod
680:
1.3 albertel 681: =head2 TimedOut
682:
683: called on a timeout. If the timeout callback is defined, it is called
684: with $self as its parameters.
685:
686: =cut
687:
1.1 foxr 688: sub TimedOut {
689:
690: my $self = shift;
691: if($self->{TimeoutCallback}) {
692: my $callback = $self->{TimeoutCallback};
693: my @args = ( $self);
694: &$callback(@args);
695: }
696: }
1.3 albertel 697:
1.1 foxr 698: =pod
1.3 albertel 699:
700: =head2 InitiateTransaction
701:
702: Called to initiate a transaction. A transaction can only be initiated
703: when the object is idle... otherwise an error is returned. A
704: transaction consists of a request to the server that will have a
705: reply. This member sets the request data in the TransactionRequest
706: member, makes the state SendingRequest and sets the data to allow a
707: timout, and to request writability notification.
708:
1.1 foxr 709: =cut
1.3 albertel 710:
1.1 foxr 711: sub InitiateTransaction {
1.30 foxr 712:
713: my ($self, $data) = @_;
1.1 foxr 714:
1.4 foxr 715: Debug(1, "initiating transaction: ".$data);
1.1 foxr 716: if($self->{State} ne "Idle") {
1.4 foxr 717: Debug(0," .. but not idle here\n");
1.1 foxr 718: return -1; # Error indicator.
719: }
720: # if the transaction is to be encrypted encrypt the data:
721:
722: if($data =~ /^encrypt\:/) {
723: $data = $self->Encrypt($data);
724: }
725:
726: # Setup the trasaction
727:
728: $self->{TransactionRequest} = $data;
729: $self->{TransactionReply} = "";
730: $self->{InformWritable} = 1;
731: $self->{InformReadable} = 0;
732: $self->{Timeoutable} = 1;
733: $self->{TimeoutRemaining} = $self->{TimeoutValue};
734: $self->Transition("SendingRequest");
735: }
736:
737:
738: =pod
1.3 albertel 739:
740: =head2 SetStateTransitionCallback
741:
742: Sets a callback for state transitions. Returns a reference to any
743: prior established callback, or undef if there was none:
744:
1.1 foxr 745: =cut
1.3 albertel 746:
1.1 foxr 747: sub SetStateTransitionCallback {
748: my $self = shift;
749: my $oldCallback = $self->{TransitionCallback};
750: $self->{TransitionCallback} = shift;
751: return $oldCallback;
752: }
1.3 albertel 753:
1.1 foxr 754: =pod
1.3 albertel 755:
756: =head2 SetTimeoutCallback
757:
758: Sets the timeout callback. Returns a reference to any prior
759: established callback or undef if there was none.
760:
1.1 foxr 761: =cut
1.3 albertel 762:
1.1 foxr 763: sub SetTimeoutCallback {
1.30 foxr 764:
765: my ($self, $callback) = @_;
766:
1.1 foxr 767: my $oldCallback = $self->{TimeoutCallback};
768: $self->{TimeoutCallback} = $callback;
769: return $oldCallback;
770: }
771:
772: =pod
1.3 albertel 773:
1.5 foxr 774: =head2 Shutdown:
775:
776: Shuts down the socket.
777:
778: =cut
779:
780: sub Shutdown {
781: my $self = shift;
782: my $socket = $self->GetSocket();
1.20 albertel 783: Debug(5,"socket is -$socket-");
784: if ($socket) {
785: # Ask lond to exit too. Non blocking so
786: # there is no cost for failure.
787: eval {
788: $socket->send("exit\n", 0);
789: $socket->shutdown(2);
790: }
791: }
1.5 foxr 792: }
793:
794: =pod
795:
1.3 albertel 796: =head2 GetState
797:
798: selector for the object state.
799:
1.1 foxr 800: =cut
1.3 albertel 801:
1.1 foxr 802: sub GetState {
803: my $self = shift;
804: return $self->{State};
805: }
1.3 albertel 806:
1.1 foxr 807: =pod
1.3 albertel 808:
809: =head2 GetSocket
810:
811: selector for the object socket.
812:
1.1 foxr 813: =cut
1.3 albertel 814:
1.1 foxr 815: sub GetSocket {
816: my $self = shift;
817: return $self->{Socket};
818: }
1.3 albertel 819:
1.5 foxr 820:
1.1 foxr 821: =pod
1.3 albertel 822:
823: =head2 WantReadable
824:
825: Return the state of the flag that indicates the object wants to be
826: called when readable.
827:
1.1 foxr 828: =cut
1.3 albertel 829:
1.1 foxr 830: sub WantReadable {
831: my $self = shift;
832:
833: return $self->{InformReadable};
834: }
1.3 albertel 835:
1.1 foxr 836: =pod
1.3 albertel 837:
838: =head2 WantWritable
839:
840: Return the state of the flag that indicates the object wants write
841: notification.
842:
1.1 foxr 843: =cut
1.3 albertel 844:
1.1 foxr 845: sub WantWritable {
846: my $self = shift;
847: return $self->{InformWritable};
848: }
1.3 albertel 849:
1.1 foxr 850: =pod
1.3 albertel 851:
852: =head2 WantTimeout
853:
854: return the state of the flag that indicates the object wants to be
855: informed of timeouts.
856:
1.1 foxr 857: =cut
1.3 albertel 858:
1.1 foxr 859: sub WantTimeout {
860: my $self = shift;
861: return $self->{Timeoutable};
862: }
863:
864: =pod
1.3 albertel 865:
866: =head2 GetReply
867:
868: Returns the reply from the last transaction.
869:
1.1 foxr 870: =cut
1.3 albertel 871:
1.1 foxr 872: sub GetReply {
873: my $self = shift;
874: return $self->{TransactionReply};
875: }
876:
877: =pod
1.3 albertel 878:
879: =head2 Encrypt
880:
881: Returns the encrypted version of the command string.
882:
883: The command input string is of the form:
884:
1.1 foxr 885: encrypt:command
1.3 albertel 886:
887: The output string can be directly sent to lond as it is of the form:
888:
1.1 foxr 889: enc:length:<encodedrequest>
1.3 albertel 890:
1.1 foxr 891: =cut
1.3 albertel 892:
1.1 foxr 893: sub Encrypt {
1.30 foxr 894:
895: my ($self, $request) = @_;
1.1 foxr 896:
897:
898: # Split the encrypt: off the request and figure out it's length.
899: # the cipher works in blocks of 8 bytes.
900:
901: my $cmd = $request;
902: $cmd =~ s/^encrypt\://; # strip off encrypt:
903: chomp($cmd); # strip off trailing \n
904: my $length=length($cmd); # Get the string length.
905: $cmd .= " "; # Pad with blanks so we can fill out a block.
906:
907: # encrypt the request in 8 byte chunks to create the encrypted
908: # output request.
909:
910: my $Encoded = '';
911: for(my $index = 0; $index <= $length; $index += 8) {
912: $Encoded .=
913: unpack("H16",
914: $self->{Cipher}->encrypt(substr($cmd,
915: $index, 8)));
916: }
917:
918: # Build up the answer as enc:length:$encrequest.
919:
920: $request = "enc:$length:$Encoded\n";
921: return $request;
922:
923:
924: }
1.3 albertel 925:
926: =pod
927:
928: =head2 Decrypt
929:
930: Decrypt a response from the server. The response is in the form:
931:
932: enc:<length>:<encrypted data>
933:
1.1 foxr 934: =cut
1.3 albertel 935:
1.1 foxr 936: sub Decrypt {
1.30 foxr 937:
938: my ($self, $encrypted) = @_;
1.1 foxr 939:
940: # Bust up the response into length, and encryptedstring:
941:
942: my ($enc, $length, $EncryptedString) = split(/:/,$encrypted);
943: chomp($EncryptedString);
944:
945: # Decode the data in 8 byte blocks. The string is encoded
946: # as hex digits so there are two characters per byte:
947:
1.10 foxr 948: my $decrypted = "";
1.1 foxr 949: for(my $index = 0; $index < length($EncryptedString);
950: $index += 16) {
951: $decrypted .= $self->{Cipher}->decrypt(
952: pack("H16",
953: substr($EncryptedString,
954: $index,
955: 16)));
956: }
957: # the answer may have trailing pads to fill out a block.
958: # $length tells us the actual length of the decrypted string:
959:
960: $decrypted = substr($decrypted, 0, $length);
1.34 foxr 961: Debug(9, "Decrypted $EncryptedString to $decrypted");
1.1 foxr 962:
963: return $decrypted;
964:
965: }
1.31 foxr 966: # ToIdle
967: # Called to transition to idle... done enough it's worth subbing
968: # off to ensure it's always done right!!
969: #
970: sub ToIdle {
971: my $self = shift;
972:
973: $self->Transition("Idle");
974: $self->{InformWritiable} = 0;
975: $self->{InformReadable} = 0;
976: $self->{Timeoutable} = 0;
977: }
978:
979: # ToVersionRequest
980: # Called to transition to "RequestVersion" also done a few times
981: # so worth subbing out.
982: #
983: sub ToVersionRequest {
984: my $self = shift;
985:
986: $self->Transition("RequestingVersion");
987: $self->{InformReadable} = 0;
988: $self->{InformWritable} = 1;
989: $self->{TransactionRequest} = "version\n";
990:
991: }
992: #
993: # CreateCipher
994: # Given a cipher key stores the key in the object context,
995: # creates the cipher object, (stores that in object context),
996: # This is done a couple of places, so it's worth factoring it out.
997: #
998: # Parameters:
999: # (self)
1000: # key - The Cipher key.
1001: #
1002: # Returns:
1003: # 0 - Failure to create IDEA cipher.
1004: # 1 - Success.
1005: #
1006: sub CreateCipher {
1007: my ($self, $key) = @_; # According to coding std.
1008:
1009: $self->{CipherKey} = $key; # Save the text key...
1010: my $packedkey = pack ("H32", $key);
1011: my $cipher = new IDEA $packedkey;
1012: if($cipher) {
1013: $self->{Cipher} = $cipher;
1014: Debug("Cipher created dumping socket: ");
1.32 foxr 1015: $self->Dump(9);
1.31 foxr 1016: return 1;
1017: }
1018: else {
1019: return 0;
1020: }
1021: }
1022: # ExchangeKeysViaSSL
1023: # Called to do cipher key exchange via SSL.
1024: # The socket is promoted to an SSL socket. If that's successful,
1025: # we read out cipher key through the socket and create an IDEA
1026: # cipher object.
1027: # Parameters:
1028: # (self)
1029: # Returns:
1030: # true - Success.
1031: # false - Failure.
1032: #
1033: # Assumptions:
1034: # 1. The ssl session setup has timeout logic built in so we don't
1035: # have to worry about DOS attacks at that stage.
1036: # 2. If the ssl session gets set up we are talking to a legitimate
1037: # lond so again we don't have to worry about DOS attacks.
1038: # All this allows us just to call
1039: sub ExchangeKeysViaSSL {
1040: my $self = shift;
1041: my $socket = $self->{Socket};
1042:
1043: # Get our signed certificate, the certificate authority's
1044: # certificate and our private key file. All of these
1045: # are needed to create the ssl connection.
1046:
1047: my ($SSLCACertificate,
1048: $SSLCertificate) = lonssl::CertificateFile();
1049: my $SSLKey = lonssl::KeyFile();
1050:
1051: # Promote our connection to ssl and read the key from lond.
1052:
1053: my $SSLSocket = lonssl::PromoteClientSocket($socket,
1054: $SSLCACertificate,
1055: $SSLCertificate,
1056: $SSLKey);
1057: if(defined $SSLSocket) {
1058: my $key = <$SSLSocket>;
1059: lonssl::Close($SSLSocket);
1060: if($key) {
1061: chomp($key); # \n is not part of the key.
1062: return $self->CreateCipher($key);
1063: }
1064: else {
1065: Debug(3, "Failed to read ssl key");
1066: return 0;
1067: }
1068: }
1069: else {
1070: # Failed!!
1071: Debug(3, "Failed to negotiate SSL connection!");
1072: return 0;
1073: }
1074: # should not get here
1075: return 0;
1076:
1077: }
1078:
1079:
1080:
1081: #
1082: # CompleteInsecure:
1083: # This function is called to initiate the completion of
1084: # insecure challenge response negotiation.
1085: # To do this, we copy the challenge string to the transaction
1086: # request, flip to writability and state transition to
1087: # ChallengeReceived..
1088: # All this is only possible if InsecureOk is true.
1089: # Parameters:
1090: # (self) - This object's context hash.
1091: # Return:
1092: # 0 - Ok to transition.
1093: # -1 - Not ok to transition (InsecureOk not ok).
1094: #
1095: sub CompleteInsecure {
1096: my $self = shift;
1097: if($InsecureOk) {
1098: $self->{AuthenticationMode} = "insecure";
1099: &Debug(8," Transition out of Initialized:insecure");
1100: $self->{TransactionRequest} = $self->{TransactionReply};
1101: $self->{InformWritable} = 1;
1102: $self->{InformReadable} = 0;
1103: $self->Transition("ChallengeReceived");
1104: $self->{TimeoutRemaining} = $self->{TimeoutValue};
1105: return 0;
1106:
1107:
1108: }
1109: else {
1110: &Debug(3, "Insecure key negotiation disabled!");
1111: my $socket = $self->{Socket};
1112: $socket->close;
1113: return -1;
1114: }
1115: }
1.1 foxr 1116:
1117: =pod
1.3 albertel 1118:
1119: =head2 GetHostIterator
1.1 foxr 1120:
1121: Returns a hash iterator to the host information. Each get from
1122: this iterator returns a reference to an array that contains
1123: information read from the hosts configuration file. Array elements
1124: are used as follows:
1125:
1.3 albertel 1126: [0] - LonCapa host name.
1127: [1] - LonCapa domain name.
1128: [2] - Loncapa role (e.g. library or access).
1129: [3] - DNS name server hostname.
1.11 foxr 1130: [4] - IP address (result of e.g. nslookup [3]).
1.3 albertel 1131: [5] - Maximum connection count.
1132: [6] - Idle timeout for reducing connection count.
1133: [7] - Minimum connection count.
1.1 foxr 1134:
1.3 albertel 1135: =cut
1.1 foxr 1136:
1137: sub GetHostIterator {
1138:
1139: return HashIterator->new(\%hostshash);
1140: }
1.14 foxr 1141:
1142: ###########################################################
1143: #
1144: # The following is an unashamed kludge that is here to
1145: # allow LondConnection to be used outside of the
1146: # loncapa environment (e.g. by lonManage).
1147: #
1148: # This is a textual inclusion of pieces of the
1149: # Configuration.pm module.
1150: #
1151:
1152:
1153: my $confdir='/etc/httpd/conf/';
1154:
1155: # ------------------- Subroutine read_conf: read LON-CAPA server configuration.
1156: # This subroutine reads PerlSetVar values out of specified web server
1157: # configuration files.
1158: sub read_conf
1159: {
1160: my (@conf_files)=@_;
1161: my %perlvar;
1162: foreach my $filename (@conf_files,'loncapa_apache.conf')
1163: {
1.21 foxr 1164: if($DebugLevel > 3) {
1.31 foxr 1165: print STDERR ("Going to read $confdir.$filename\n");
1.21 foxr 1166: }
1.14 foxr 1167: open(CONFIG,'<'.$confdir.$filename) or
1168: die("Can't read $confdir$filename");
1169: while (my $configline=<CONFIG>)
1170: {
1171: if ($configline =~ /^[^\#]*PerlSetVar/)
1172: {
1173: my ($unused,$varname,$varvalue)=split(/\s+/,$configline);
1174: chomp($varvalue);
1175: $perlvar{$varname}=$varvalue;
1176: }
1177: }
1178: close(CONFIG);
1179: }
1.21 foxr 1180: if($DebugLevel > 3) {
1.31 foxr 1181: print STDERR "Dumping perlvar:\n";
1.21 foxr 1182: foreach my $var (keys %perlvar) {
1.31 foxr 1183: print STDERR "$var = $perlvar{$var}\n";
1.21 foxr 1184: }
1185: }
1.14 foxr 1186: my $perlvarref=\%perlvar;
1.21 foxr 1187: return $perlvarref;
1188: }
1.14 foxr 1189:
1190: #---------------------- Subroutine read_hosts: Read a LON-CAPA hosts.tab
1191: # formatted configuration file.
1192: #
1.36 albertel 1193: my $RequiredCount = 4; # Required item count in hosts.tab.
1.14 foxr 1194: my $DefaultMaxCon = 5; # Default value for maximum connections.
1195: my $DefaultIdle = 1000; # Default connection idle time in seconds.
1196: my $DefaultMinCon = 0; # Default value for minimum connections.
1197:
1198: sub read_hosts {
1199: my $Filename = shift;
1200: my %HostsTab;
1201:
1.36 albertel 1202: open(CONFIG,'<'.$Filename) or die("Can't read $Filename");
1.14 foxr 1203: while (my $line = <CONFIG>) {
1.36 albertel 1204: if ($line !~ /^\s*\#/) {
1205: $line=~s/\s*$//;
1.14 foxr 1206: my @items = split(/:/, $line);
1207: if(scalar @items >= $RequiredCount) {
1208: if (scalar @items == $RequiredCount) { # Only required items:
1209: $items[$RequiredCount] = $DefaultMaxCon;
1210: }
1211: if(scalar @items == $RequiredCount + 1) { # up through maxcon.
1212: $items[$RequiredCount+1] = $DefaultIdle;
1213: }
1214: if(scalar @items == $RequiredCount + 2) { # up through idle.
1215: $items[$RequiredCount+2] = $DefaultMinCon;
1216: }
1217: {
1218: my @list = @items; # probably not needed but I'm unsure of
1219: # about the scope of item so...
1220: $HostsTab{$list[0]} = \@list;
1221: }
1222: }
1223: }
1224: }
1225: close(CONFIG);
1226: my $hostref = \%HostsTab;
1227: return ($hostref);
1228: }
1.24 foxr 1229: #
1230: # Get the version of our peer. Note that this is only well
1231: # defined if the state machine has hit the idle state at least
1232: # once (well actually if it has transitioned out of
1233: # ReadingVersionString The member data LondVersion is returned.
1234: #
1235: sub PeerVersion {
1236: my $self = shift;
1237:
1238: return $self->{LondVersion};
1239: }
1.1 foxr 1240:
1241: 1;
1242:
1243: =pod
1.3 albertel 1244:
1.1 foxr 1245: =head1 Theory
1246:
1.3 albertel 1247: The lond object is a state machine. It lives through the following states:
1248:
1249: =item Connected:
1250:
1251: a TCP connection has been formed, but the passkey has not yet been
1252: negotiated.
1253:
1254: =item Initialized:
1255:
1256: "init" sent.
1257:
1258: =item ChallengeReceived:
1259:
1260: lond sent its challenge to us.
1261:
1262: =item ChallengeReplied:
1263:
1264: We replied to lond's challenge waiting for lond's ok.
1265:
1266: =item RequestingKey:
1267:
1268: We are requesting an encryption key.
1269:
1270: =item ReceivingKey:
1271:
1272: We are receiving an encryption key.
1273:
1274: =item Idle:
1275:
1276: Connection was negotiated but no requests are active.
1277:
1278: =item SendingRequest:
1279:
1280: A request is being sent to the peer.
1281:
1282: =item ReceivingReply:
1283:
1284: Waiting for an entire reply from the peer.
1285:
1286: =item Disconnected:
1287:
1288: For whatever reason, the connection was dropped.
1289:
1290: When we need to be writing data, we have a writable event. When we
1291: need to be reading data, a readable event established. Events
1292: dispatch through the class functions Readable and Writable, and the
1293: watcher contains a reference to the associated object to allow object
1294: context to be reached.
1.1 foxr 1295:
1296: =head2 Member data.
1297:
1.3 albertel 1298: =item Host
1299:
1300: Host socket is connected to.
1301:
1302: =item Port
1303:
1304: The port the remote lond is listening on.
1305:
1306: =item Socket
1307:
1308: Socket open on the connection.
1309:
1310: =item State
1311:
1312: The current state.
1313:
1.31 foxr 1314: =item AuthenticationMode
1315:
1316: How authentication is being done. This can be any of:
1317:
1318: o local - Authenticate via a key exchanged in a file.
1319: o ssl - Authenticate via a key exchaned through a temporary ssl tunnel.
1320: o insecure - Exchange keys in an insecure manner.
1321:
1322: insecure is only allowed if the configuration parameter loncAllowInsecure
1323: is nonzero.
1324:
1.3 albertel 1325: =item TransactionRequest
1326:
1327: The request being transmitted.
1328:
1329: =item TransactionReply
1330:
1331: The reply being received from the transaction.
1332:
1333: =item InformReadable
1334:
1335: True if we want to be called when socket is readable.
1336:
1337: =item InformWritable
1338:
1339: True if we want to be informed if the socket is writable.
1340:
1341: =item Timeoutable
1342:
1343: True if the current operation is allowed to timeout.
1344:
1345: =item TimeoutValue
1346:
1347: Number of seconds in the timeout.
1348:
1349: =item TimeoutRemaining
1350:
1351: Number of seconds left in the timeout.
1352:
1353: =item CipherKey
1354:
1355: The key that was negotiated with the peer.
1356:
1357: =item Cipher
1358:
1359: The cipher obtained via the key.
1.1 foxr 1360:
1361:
1362: =head2 The following are callback like members:
1.3 albertel 1363:
1364: =item Tick:
1365:
1366: Called in response to a timer tick. Used to managed timeouts etc.
1367:
1368: =item Readable:
1369:
1370: Called when the socket becomes readable.
1371:
1372: =item Writable:
1373:
1374: Called when the socket becomes writable.
1375:
1376: =item TimedOut:
1377:
1378: Called when a timed operation timed out.
1379:
1.1 foxr 1380:
1381: =head2 The following are operational member functions.
1.3 albertel 1382:
1383: =item InitiateTransaction:
1384:
1385: Called to initiate a new transaction
1386:
1387: =item SetStateTransitionCallback:
1388:
1389: Called to establish a function that is called whenever the object goes
1390: through a state transition. This is used by The client to manage the
1391: work flow for the object.
1392:
1393: =item SetTimeoutCallback:
1394:
1395: Set a function to be called when a transaction times out. The
1396: function will be called with the object as its sole parameter.
1397:
1398: =item Encrypt:
1399:
1400: Encrypts a block of text according to the cipher negotiated with the
1401: peer (assumes the text is a command).
1402:
1403: =item Decrypt:
1404:
1405: Decrypts a block of text according to the cipher negotiated with the
1406: peer (assumes the block was a reply.
1.5 foxr 1407:
1408: =item Shutdown:
1409:
1410: Shuts off the socket.
1.1 foxr 1411:
1412: =head2 The following are selector member functions:
1413:
1.3 albertel 1414: =item GetState:
1415:
1416: Returns the current state
1417:
1418: =item GetSocket:
1419:
1420: Gets the socekt open on the connection to lond.
1421:
1422: =item WantReadable:
1423:
1424: true if the current state requires a readable event.
1425:
1426: =item WantWritable:
1427:
1428: true if the current state requires a writable event.
1429:
1430: =item WantTimeout:
1431:
1432: true if the current state requires timeout support.
1433:
1434: =item GetHostIterator:
1435:
1436: Returns an iterator into the host file hash.
1437:
1.1 foxr 1438: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>