added a check that connect ip addresses resolve
[spider.git] / perl / Msg.pm
1 #
2 # This has been taken from the 'Advanced Perl Programming' book by Sriram Srinivasan 
3 #
4 # I am presuming that the code is distributed on the same basis as perl itself.
5 #
6 # I have modified it to suit my devious purposes (Dirk Koopman G1TLH)
7 #
8 # $Id$
9 #
10
11 package Msg;
12
13 use strict;
14
15 use vars qw($VERSION $BRANCH);
16 $VERSION = sprintf( "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/ );
17 $BRANCH = sprintf( "%d.%03d", q$Revision$ =~ /\d+\.\d+\.(\d+)\.(\d+)/  || (0,0));
18 $main::build += $VERSION;
19 $main::branch += $BRANCH;
20
21 use IO::Select;
22 use IO::Socket;
23 use DXDebug;
24 use Timer;
25
26 use vars qw(%rd_callbacks %wt_callbacks %er_callbacks $rd_handles $wt_handles $er_handles $now %conns $noconns $blocking_supported $cnum);
27
28 %rd_callbacks = ();
29 %wt_callbacks = ();
30 %er_callbacks = ();
31 $rd_handles   = IO::Select->new();
32 $wt_handles   = IO::Select->new();
33 $er_handles   = IO::Select->new();
34
35 $now = time;
36
37 BEGIN {
38     # Checks if blocking is supported
39     eval {
40                 local $^W;
41         require POSIX; POSIX->import(qw(O_NONBLOCK F_SETFL F_GETFL))
42     };
43         if ($@ || $main::is_win) {
44 #               print STDERR "POSIX Blocking *** NOT *** supported $@\n";
45                 $blocking_supported = 0;
46         } else {
47                 $blocking_supported = 1;
48 #               print STDERR "POSIX Blocking enabled\n";
49         }
50
51
52         # import as many of these errno values as are available
53         eval {
54                 local $^W;
55                 require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
56         };
57
58         unless ($^O eq 'MSWin32') {
59                 if ($] >= 5.6) {
60                         eval {
61                                 local $^W;
62                                 require Socket; Socket->import(qw(IPPROTO_TCP TCP_NODELAY));
63                         };
64                 } else {
65                         dbg("IPPROTO_TCP and TCP_NODELAY manually defined");
66                         eval 'sub IPPROTO_TCP {     6 };';
67                         eval 'sub TCP_NODELAY {     1 };';
68                 }
69         }
70         # http://support.microsoft.com/support/kb/articles/Q150/5/37.asp
71         # defines EINPROGRESS as 10035.  We provide it here because some
72         # Win32 users report POSIX::EINPROGRESS is not vendor-supported.
73         if ($^O eq 'MSWin32') { 
74                 eval '*EINPROGRESS = sub { 10036 };';
75                 eval '*EWOULDBLOCK = *EAGAIN = sub { 10035 };';
76                 eval '*F_GETFL     = sub {     0 };';
77                 eval '*F_SETFL     = sub {     0 };';
78                 eval '*IPPROTO_TCP     = sub {     6 };';
79                 eval '*TCP_NODELAY     = sub {     1 };';
80                 $blocking_supported = 0;   # it appears that this DOESN'T work :-(
81         } 
82 }
83
84 my $w = $^W;
85 $^W = 0;
86 my $eagain = eval {EAGAIN()};
87 my $einprogress = eval {EINPROGRESS()};
88 my $ewouldblock = eval {EWOULDBLOCK()};
89 $^W = $w;
90 $cnum = 0;
91
92
93 #
94 #-----------------------------------------------------------------
95 # Generalised initializer
96
97 sub new
98 {
99     my ($pkg, $rproc) = @_;
100         my $obj = ref($pkg);
101         my $class = $obj || $pkg;
102
103     my $conn = {
104         rproc => $rproc,
105                 inqueue => [],
106                 outqueue => [],
107                 state => 0,
108                 lineend => "\r\n",
109                 csort => 'telnet',
110                 timeval => 60,
111                 blocking => 0,
112                 cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
113     };
114
115         $noconns++;
116         
117         dbg("Connection created ($noconns)") if isdbg('connll');
118         return bless $conn, $class;
119 }
120
121 sub set_error
122 {
123         my $conn = shift;
124         my $callback = shift;
125         $conn->{eproc} = $callback;
126         set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
127 }
128
129 sub set_rproc
130 {
131         my $conn = shift;
132         my $callback = shift;
133         $conn->{rproc} = $callback;
134 }
135
136 sub blocking
137 {
138         return unless $blocking_supported;
139
140         # Make the handle stop blocking, the Windows way.
141         if ($main::is_win) { 
142           # 126 is FIONBIO (some docs say 0x7F << 16)
143                 ioctl( $_[0],
144                            0x80000000 | (4 << 16) | (ord('f') << 8) | 126,
145                            "$_[1]"
146                          );
147         } else {
148                 my $flags = fcntl ($_[0], F_GETFL, 0);
149                 if ($_[1]) {
150                         $flags &= ~O_NONBLOCK;
151                 } else {
152                         $flags |= O_NONBLOCK;
153                 }
154                 fcntl ($_[0], F_SETFL, $flags);
155         }
156 }
157
158 # save it
159 sub conns
160 {
161         my $pkg = shift;
162         my $call = shift;
163         my $ref;
164         
165         if (ref $pkg) {
166                 $call = $pkg->{call} unless $call;
167                 return undef unless $call;
168                 dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
169                 delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call; 
170                 $pkg->{call} = $call;
171                 $ref = $conns{$call} = $pkg;
172                 dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
173         } else {
174                 $ref = $conns{$call};
175         }
176         return $ref;
177 }
178
179 # this is only called by any dependent processes going away unexpectedly
180 sub pid_gone
181 {
182         my ($pkg, $pid) = @_;
183         
184         my @pid = grep {$_->{pid} == $pid} values %conns;
185         foreach my $p (@pid) {
186                 &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
187                 $p->disconnect;
188         }
189 }
190
191 #-----------------------------------------------------------------
192 # Send side routines
193 sub connect {
194     my ($pkg, $to_host, $to_port, $rproc) = @_;
195
196     # Create a connection end-point object
197     my $conn = $pkg;
198         unless (ref $pkg) {
199                 $conn = $pkg->new($rproc);
200         }
201         $conn->{peerhost} = $to_host;
202         $conn->{peerport} = $to_port;
203         $conn->{sort} = 'Outgoing';
204         
205     # Create a new internet socket
206     my $sock = IO::Socket::INET->new();
207     return undef unless $sock;
208         
209         my $proto = getprotobyname('tcp');
210         $sock->socket(AF_INET, SOCK_STREAM, $proto) or return undef;
211         
212         blocking($sock, 0);
213         $conn->{blocking} = 0;
214
215         # does the host resolve?
216         my $ip = gethostbyname($to_host);
217         return undef unless $ip;
218         
219 #       my $r = $sock->connect($to_port, $ip);
220         my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
221         return undef unless $r || _err_will_block($!);
222         
223         $conn->{sock} = $sock;
224     
225     if ($conn->{rproc}) {
226         my $callback = sub {$conn->_rcv};
227         set_event_handler ($sock, read => $callback);
228     }
229     return $conn;
230 }
231
232 sub disconnect {
233     my $conn = shift;
234         return if exists $conn->{disconnecting};
235
236         $conn->{disconnecting} = 1;
237     my $sock = delete $conn->{sock};
238         $conn->{state} = 'E';
239         $conn->{timeout}->del if $conn->{timeout};
240
241         # be careful to delete the correct one
242         my $call;
243         if ($call = $conn->{call}) {
244                 my $ref = $conns{$call};
245                 delete $conns{$call} if $ref && $ref == $conn;
246         }
247         $call ||= 'unallocated';
248         dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
249         
250         # get rid of any references
251         for (keys %$conn) {
252                 if (ref($conn->{$_})) {
253                         delete $conn->{$_};
254                 }
255         }
256
257         if (defined($sock)) {
258                 set_event_handler ($sock, read => undef, write => undef, error => undef);
259                 shutdown($sock, 3);
260                 close($sock);
261         }
262         
263         unless ($main::is_win) {
264                 kill 'TERM', $conn->{pid} if exists $conn->{pid};
265         }
266
267 }
268
269 sub send_now {
270     my ($conn, $msg) = @_;
271     $conn->enqueue($msg);
272     $conn->_send (1); # 1 ==> flush
273 }
274
275 sub send_later {
276     my ($conn, $msg) = @_;
277     $conn->enqueue($msg);
278     my $sock = $conn->{sock};
279     return unless defined($sock);
280     set_event_handler ($sock, write => sub {$conn->_send(0)});
281 }
282
283 sub enqueue {
284     my $conn = shift;
285     push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
286 }
287
288 sub _send {
289     my ($conn, $flush) = @_;
290     my $sock = $conn->{sock};
291     return unless defined($sock);
292     my $rq = $conn->{outqueue};
293
294     # If $flush is set, set the socket to blocking, and send all
295     # messages in the queue - return only if there's an error
296     # If $flush is 0 (deferred mode) make the socket non-blocking, and
297     # return to the event loop only after every message, or if it
298     # is likely to block in the middle of a message.
299
300         if ($conn->{blocking} != $flush) {
301                 blocking($sock, $flush);
302                 $conn->{blocking} = $flush;
303         }
304     my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
305
306     while (@$rq) {
307         my $msg            = $rq->[0];
308                 my $mlth           = length($msg);
309         my $bytes_to_write = $mlth - $offset;
310         my $bytes_written  = 0;
311                 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
312         while ($bytes_to_write > 0) {
313             $bytes_written = syswrite ($sock, $msg,
314                                        $bytes_to_write, $offset);
315             if (!defined($bytes_written)) {
316                 if (_err_will_block($!)) {
317                     # Should happen only in deferred mode. Record how
318                     # much we have already sent.
319                     $conn->{send_offset} = $offset;
320                     # Event handler should already be set, so we will
321                     # be called back eventually, and will resume sending
322                     return 1;
323                 } else {    # Uh, oh
324                                         &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
325                                         $conn->disconnect;
326                     return 0; # fail. Message remains in queue ..
327                 }
328             } elsif (isdbg('raw')) {
329                                 my $call = $conn->{call} || 'none';
330                                 dbgdump('raw', "$call send $bytes_written: ", $msg);
331                         }
332             $offset         += $bytes_written;
333             $bytes_to_write -= $bytes_written;
334         }
335         delete $conn->{send_offset};
336         $offset = 0;
337         shift @$rq;
338         #last unless $flush; # Go back to select and wait
339                             # for it to fire again.
340     }
341     # Call me back if queue has not been drained.
342     unless (@$rq) {
343         set_event_handler ($sock, write => undef);
344                 if (exists $conn->{close_on_empty}) {
345                         &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
346                         $conn->disconnect; 
347                 }
348     }
349     1;  # Success
350 }
351
352 sub dup_sock
353 {
354         my $conn = shift;
355         my $oldsock = $conn->{sock};
356         my $rc = $rd_callbacks{$oldsock};
357         my $wc = $wt_callbacks{$oldsock};
358         my $ec = $er_callbacks{$oldsock};
359         my $sock = $oldsock->new_from_fd($oldsock, "w+");
360         if ($sock) {
361                 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
362                 $conn->{sock} = $sock;
363                 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
364                 $oldsock->close;
365         }
366 }
367
368 sub _err_will_block {
369         return 0 unless $blocking_supported;
370         return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
371 }
372
373 sub close_on_empty
374 {
375         my $conn = shift;
376         $conn->{close_on_empty} = 1;
377 }
378
379 #-----------------------------------------------------------------
380 # Receive side routines
381
382 sub new_server {
383     @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
384     my ($pkg, $my_host, $my_port, $login_proc) = @_;
385         my $self = $pkg->new($login_proc);
386         
387     $self->{sock} = IO::Socket::INET->new (
388                                           LocalAddr => "$my_host:$my_port",
389 #                                          LocalPort => $my_port,
390                                           Listen    => SOMAXCONN,
391                                           Proto     => 'tcp',
392                                           Reuse => 1);
393     die "Could not create socket: $! \n" unless $self->{sock};
394     set_event_handler ($self->{sock}, read => sub { $self->new_client }  );
395         return $self;
396 }
397
398
399 sub nolinger
400 {
401         my $conn = shift;
402
403         unless ($main::is_win) {
404                 if (isdbg('sock')) {
405                         my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER); 
406                         my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
407                         my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
408                         dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
409                 }
410                 
411                 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
412                 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
413                 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
414                 $conn->{sock}->autoflush(0);
415
416                 if (isdbg('sock')) {
417                         my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER); 
418                         my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
419                         my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
420                         dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
421                 }
422         } 
423 }
424
425 sub dequeue
426 {
427         my $conn = shift;
428
429         if ($conn->{msg} =~ /\n/) {
430                 my @lines = split /\r?\n/, $conn->{msg};
431                 if ($conn->{msg} =~ /\n$/) {
432                         delete $conn->{msg};
433                 } else {
434                         $conn->{msg} = pop @lines;
435                 }
436                 for (@lines) {
437                         &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
438                 }
439         }
440 }
441
442 sub _rcv {                     # Complement to _send
443     my $conn = shift; # $rcv_now complement of $flush
444     # Find out how much has already been received, if at all
445     my ($msg, $offset, $bytes_to_read, $bytes_read);
446     my $sock = $conn->{sock};
447     return unless defined($sock);
448
449         my @lines;
450         if ($conn->{blocking}) {
451                 blocking($sock, 0);
452                 $conn->{blocking} = 0;
453         }
454         $bytes_read = sysread ($sock, $msg, 1024, 0);
455         if (defined ($bytes_read)) {
456                 if ($bytes_read > 0) {
457                         if (isdbg('raw')) {
458                                 my $call = $conn->{call} || 'none';
459                                 dbgdump('raw', "$call read $bytes_read: ", $msg);
460                         }
461                         if ($conn->{echo}) {
462                                 my @ch = split //, $msg;
463                                 my $out;
464                                 for (@ch) {
465                                         if (/[\cH\x7f]/) {
466                                                 $out .= "\cH \cH";
467                                                 $conn->{msg} =~ s/.$//;
468                                         } else {
469                                                 $out .= $_;
470                                                 $conn->{msg} .= $_;
471                                         }
472                                 }
473                                 if (defined $out) {
474                                         set_event_handler ($sock, write => sub{$conn->_send(0)});
475                                         push @{$conn->{outqueue}}, $out;
476                                 }
477                         } else {
478                                 $conn->{msg} .= $msg;
479                         }
480                 } 
481         } else {
482                 if (_err_will_block($!)) {
483                         return ; 
484                 } else {
485                         $bytes_read = 0;
486                 }
487     }
488
489 FINISH:
490     if (defined $bytes_read && $bytes_read == 0) {
491                 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
492                 $conn->disconnect;
493     } else {
494                 unless ($conn->{disable_read}) {
495                         $conn->dequeue if exists $conn->{msg};
496                 }
497         }
498 }
499
500 sub new_client {
501         my $server_conn = shift;
502     my $sock = $server_conn->{sock}->accept();
503         if ($sock) {
504                 my $conn = $server_conn->new($server_conn->{rproc});
505                 $conn->{sock} = $sock;
506                 blocking($sock, 0);
507                 $conn->nolinger;
508                 $conn->{blocking} = 0;
509                 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
510                 $conn->{sort} = 'Incoming';
511                 if ($eproc) {
512                         $conn->{eproc} = $eproc;
513                         set_event_handler ($sock, error => $eproc);
514                 }
515                 if ($rproc) {
516                         $conn->{rproc} = $rproc;
517                         my $callback = sub {$conn->_rcv};
518                         set_event_handler ($sock, read => $callback);
519                 } else {  # Login failed
520                         &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
521                         $conn->disconnect();
522                 }
523         } else {
524                 dbg("Msg: error on accept ($!)") if isdbg('err');
525         }
526 }
527
528 sub close_server
529 {
530         my $conn = shift;
531         set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
532         $conn->{sock}->close;
533 }
534
535 # close all clients (this is for forking really)
536 sub close_all_clients
537 {
538         foreach my $conn (values %conns) {
539                 $conn->disconnect;
540         }
541 }
542
543 sub disable_read
544 {
545         my $conn = shift;
546         set_event_handler ($conn->{sock}, read => undef);
547         return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
548 }
549
550 #
551 #----------------------------------------------------
552 # Event loop routines used by both client and server
553
554 sub set_event_handler {
555     shift unless ref($_[0]); # shift if first arg is package name
556     my ($handle, %args) = @_;
557     my $callback;
558     if (exists $args{'write'}) {
559         $callback = $args{'write'};
560         if ($callback) {
561             $wt_callbacks{$handle} = $callback;
562             $wt_handles->add($handle);
563         } else {
564             delete $wt_callbacks{$handle};
565             $wt_handles->remove($handle);
566         }
567     }
568     if (exists $args{'read'}) {
569         $callback = $args{'read'};
570         if ($callback) {
571             $rd_callbacks{$handle} = $callback;
572             $rd_handles->add($handle);
573         } else {
574             delete $rd_callbacks{$handle};
575             $rd_handles->remove($handle);
576        }
577     }
578     if (exists $args{'error'}) {
579         $callback = $args{'error'};
580         if ($callback) {
581             $er_callbacks{$handle} = $callback;
582             $er_handles->add($handle);
583         } else {
584             delete $er_callbacks{$handle};
585             $er_handles->remove($handle);
586        }
587     }
588 }
589
590 sub event_loop {
591     my ($pkg, $loop_count, $timeout, $wronly) = @_; # event_loop(1) to process events once
592     my ($conn, $r, $w, $e, $rset, $wset, $eset);
593     while (1) {
594  
595        # Quit the loop if no handles left to process
596                 if ($wronly) {
597                         last unless $wt_handles->count();
598         
599                         ($rset, $wset, $eset) = IO::Select->select(undef, $wt_handles, undef, $timeout);
600                         
601                         foreach $w (@$wset) {
602                                 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
603                         }
604                 } else {
605                         
606                         last unless ($rd_handles->count() || $wt_handles->count());
607         
608                         ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
609                         
610                         foreach $e (@$eset) {
611                                 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
612                         }
613                         foreach $r (@$rset) {
614                                 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
615                         }
616                         foreach $w (@$wset) {
617                                 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
618                         }
619                 }
620
621                 Timer::handler;
622                 
623         if (defined($loop_count)) {
624             last unless --$loop_count;
625         }
626     }
627 }
628
629 sub sleep
630 {
631         my ($pkg, $interval) = @_;
632         my $now = time;
633         while (time - $now < $interval) {
634                 $pkg->event_loop(10, 0.01);
635         }
636 }
637
638 sub DESTROY
639 {
640         my $conn = shift;
641         my $call = $conn->{call} || 'unallocated';
642         my $host = $conn->{peerhost} || '';
643         my $port = $conn->{peerport} || '';
644         dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');
645         $noconns--;
646 }
647
648 1;
649
650 __END__
651