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