remove warnings from $BRANCH lines for 5.8.0
[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         my $ip = gethostbyname($to_host);
216 #       my $r = $sock->connect($to_port, $ip);
217         my $r = connect($sock, pack_sockaddr_in($to_port, $ip));
218         return undef unless $r || _err_will_block($!);
219         
220         $conn->{sock} = $sock;
221     
222     if ($conn->{rproc}) {
223         my $callback = sub {$conn->_rcv};
224         set_event_handler ($sock, read => $callback);
225     }
226     return $conn;
227 }
228
229 sub disconnect {
230     my $conn = shift;
231         return if exists $conn->{disconnecting};
232
233         $conn->{disconnecting} = 1;
234     my $sock = delete $conn->{sock};
235         $conn->{state} = 'E';
236         $conn->{timeout}->del if $conn->{timeout};
237
238         # be careful to delete the correct one
239         my $call;
240         if ($call = $conn->{call}) {
241                 my $ref = $conns{$call};
242                 delete $conns{$call} if $ref && $ref == $conn;
243         }
244         $call ||= 'unallocated';
245         dbg("Connection $conn->{cnum} $call disconnected") if isdbg('connll');
246         
247         # get rid of any references
248         for (keys %$conn) {
249                 if (ref($conn->{$_})) {
250                         delete $conn->{$_};
251                 }
252         }
253
254         if (defined($sock)) {
255                 set_event_handler ($sock, read => undef, write => undef, error => undef);
256                 shutdown($sock, 3);
257                 close($sock);
258         }
259         
260         unless ($main::is_win) {
261                 kill 'TERM', $conn->{pid} if exists $conn->{pid};
262         }
263
264 }
265
266 sub send_now {
267     my ($conn, $msg) = @_;
268     $conn->enqueue($msg);
269     $conn->_send (1); # 1 ==> flush
270 }
271
272 sub send_later {
273     my ($conn, $msg) = @_;
274     $conn->enqueue($msg);
275     my $sock = $conn->{sock};
276     return unless defined($sock);
277     set_event_handler ($sock, write => sub {$conn->_send(0)});
278 }
279
280 sub enqueue {
281     my $conn = shift;
282     push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
283 }
284
285 sub _send {
286     my ($conn, $flush) = @_;
287     my $sock = $conn->{sock};
288     return unless defined($sock);
289     my $rq = $conn->{outqueue};
290
291     # If $flush is set, set the socket to blocking, and send all
292     # messages in the queue - return only if there's an error
293     # If $flush is 0 (deferred mode) make the socket non-blocking, and
294     # return to the event loop only after every message, or if it
295     # is likely to block in the middle of a message.
296
297         if ($conn->{blocking} != $flush) {
298                 blocking($sock, $flush);
299                 $conn->{blocking} = $flush;
300         }
301     my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
302
303     while (@$rq) {
304         my $msg            = $rq->[0];
305                 my $mlth           = length($msg);
306         my $bytes_to_write = $mlth - $offset;
307         my $bytes_written  = 0;
308                 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
309         while ($bytes_to_write > 0) {
310             $bytes_written = syswrite ($sock, $msg,
311                                        $bytes_to_write, $offset);
312             if (!defined($bytes_written)) {
313                 if (_err_will_block($!)) {
314                     # Should happen only in deferred mode. Record how
315                     # much we have already sent.
316                     $conn->{send_offset} = $offset;
317                     # Event handler should already be set, so we will
318                     # be called back eventually, and will resume sending
319                     return 1;
320                 } else {    # Uh, oh
321                                         &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
322                                         $conn->disconnect;
323                     return 0; # fail. Message remains in queue ..
324                 }
325             } elsif (isdbg('raw')) {
326                                 my $call = $conn->{call} || 'none';
327                                 dbgdump('raw', "$call send $bytes_written: ", $msg);
328                         }
329             $offset         += $bytes_written;
330             $bytes_to_write -= $bytes_written;
331         }
332         delete $conn->{send_offset};
333         $offset = 0;
334         shift @$rq;
335         #last unless $flush; # Go back to select and wait
336                             # for it to fire again.
337     }
338     # Call me back if queue has not been drained.
339     unless (@$rq) {
340         set_event_handler ($sock, write => undef);
341                 if (exists $conn->{close_on_empty}) {
342                         &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
343                         $conn->disconnect; 
344                 }
345     }
346     1;  # Success
347 }
348
349 sub dup_sock
350 {
351         my $conn = shift;
352         my $oldsock = $conn->{sock};
353         my $rc = $rd_callbacks{$oldsock};
354         my $wc = $wt_callbacks{$oldsock};
355         my $ec = $er_callbacks{$oldsock};
356         my $sock = $oldsock->new_from_fd($oldsock, "w+");
357         if ($sock) {
358                 set_event_handler($oldsock, read=>undef, write=>undef, error=>undef);
359                 $conn->{sock} = $sock;
360                 set_event_handler($sock, read=>$rc, write=>$wc, error=>$ec);
361                 $oldsock->close;
362         }
363 }
364
365 sub _err_will_block {
366         return 0 unless $blocking_supported;
367         return ($_[0] == $eagain || $_[0] == $ewouldblock || $_[0] == $einprogress);
368 }
369
370 sub close_on_empty
371 {
372         my $conn = shift;
373         $conn->{close_on_empty} = 1;
374 }
375
376 #-----------------------------------------------------------------
377 # Receive side routines
378
379 sub new_server {
380     @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
381     my ($pkg, $my_host, $my_port, $login_proc) = @_;
382         my $self = $pkg->new($login_proc);
383         
384     $self->{sock} = IO::Socket::INET->new (
385                                           LocalAddr => "$my_host:$my_port",
386 #                                          LocalPort => $my_port,
387                                           Listen    => SOMAXCONN,
388                                           Proto     => 'tcp',
389                                           Reuse => 1);
390     die "Could not create socket: $! \n" unless $self->{sock};
391     set_event_handler ($self->{sock}, read => sub { $self->new_client }  );
392         return $self;
393 }
394
395
396 sub nolinger
397 {
398         my $conn = shift;
399
400         unless ($main::is_win) {
401                 if (isdbg('sock')) {
402                         my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER); 
403                         my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
404                         my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
405                         dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
406                 }
407                 
408                 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE, 1)} or dbg("setsockopt keepalive: $!");
409                 eval {setsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER, pack("ll", 0, 0))} or dbg("setsockopt linger: $!");
410                 eval {setsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY, 1)} or eval {setsockopt($conn->{sock}, SOL_SOCKET, TCP_NODELAY, 1)} or dbg("setsockopt tcp_nodelay: $!");
411                 $conn->{sock}->autoflush(0);
412
413                 if (isdbg('sock')) {
414                         my ($l, $t) = unpack "ll", getsockopt($conn->{sock}, SOL_SOCKET, SO_LINGER); 
415                         my $k = unpack 'l', getsockopt($conn->{sock}, SOL_SOCKET, SO_KEEPALIVE);
416                         my $n = $main::is_win ? 0 : unpack "l", getsockopt($conn->{sock}, IPPROTO_TCP, TCP_NODELAY);
417                         dbg("Linger is: $l $t, keepalive: $k, nagle: $n");
418                 }
419         } 
420 }
421
422 sub dequeue
423 {
424         my $conn = shift;
425
426         if ($conn->{msg} =~ /\n/) {
427                 my @lines = split /\r?\n/, $conn->{msg};
428                 if ($conn->{msg} =~ /\n$/) {
429                         delete $conn->{msg};
430                 } else {
431                         $conn->{msg} = pop @lines;
432                 }
433                 for (@lines) {
434                         &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
435                 }
436         }
437 }
438
439 sub _rcv {                     # Complement to _send
440     my $conn = shift; # $rcv_now complement of $flush
441     # Find out how much has already been received, if at all
442     my ($msg, $offset, $bytes_to_read, $bytes_read);
443     my $sock = $conn->{sock};
444     return unless defined($sock);
445
446         my @lines;
447         if ($conn->{blocking}) {
448                 blocking($sock, 0);
449                 $conn->{blocking} = 0;
450         }
451         $bytes_read = sysread ($sock, $msg, 1024, 0);
452         if (defined ($bytes_read)) {
453                 if ($bytes_read > 0) {
454                         if (isdbg('raw')) {
455                                 my $call = $conn->{call} || 'none';
456                                 dbgdump('raw', "$call read $bytes_read: ", $msg);
457                         }
458                         if ($conn->{echo}) {
459                                 my @ch = split //, $msg;
460                                 my $out;
461                                 for (@ch) {
462                                         if (/[\cH\x7f]/) {
463                                                 $out .= "\cH \cH";
464                                                 $conn->{msg} =~ s/.$//;
465                                         } else {
466                                                 $out .= $_;
467                                                 $conn->{msg} .= $_;
468                                         }
469                                 }
470                                 if (defined $out) {
471                                         set_event_handler ($sock, write => sub{$conn->_send(0)});
472                                         push @{$conn->{outqueue}}, $out;
473                                 }
474                         } else {
475                                 $conn->{msg} .= $msg;
476                         }
477                 } 
478         } else {
479                 if (_err_will_block($!)) {
480                         return ; 
481                 } else {
482                         $bytes_read = 0;
483                 }
484     }
485
486 FINISH:
487     if (defined $bytes_read && $bytes_read == 0) {
488                 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
489                 $conn->disconnect;
490     } else {
491                 unless ($conn->{disable_read}) {
492                         $conn->dequeue if exists $conn->{msg};
493                 }
494         }
495 }
496
497 sub new_client {
498         my $server_conn = shift;
499     my $sock = $server_conn->{sock}->accept();
500         if ($sock) {
501                 my $conn = $server_conn->new($server_conn->{rproc});
502                 $conn->{sock} = $sock;
503                 blocking($sock, 0);
504                 $conn->nolinger;
505                 $conn->{blocking} = 0;
506                 my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
507                 $conn->{sort} = 'Incoming';
508                 if ($eproc) {
509                         $conn->{eproc} = $eproc;
510                         set_event_handler ($sock, error => $eproc);
511                 }
512                 if ($rproc) {
513                         $conn->{rproc} = $rproc;
514                         my $callback = sub {$conn->_rcv};
515                         set_event_handler ($sock, read => $callback);
516                 } else {  # Login failed
517                         &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
518                         $conn->disconnect();
519                 }
520         } else {
521                 dbg("Msg: error on accept ($!)") if isdbg('err');
522         }
523 }
524
525 sub close_server
526 {
527         my $conn = shift;
528         set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
529         $conn->{sock}->close;
530 }
531
532 # close all clients (this is for forking really)
533 sub close_all_clients
534 {
535         foreach my $conn (values %conns) {
536                 $conn->disconnect;
537         }
538 }
539
540 sub disable_read
541 {
542         my $conn = shift;
543         set_event_handler ($conn->{sock}, read => undef);
544         return $_[0] ? $conn->{disable_read} = $_[0] : $_[0];
545 }
546
547 #
548 #----------------------------------------------------
549 # Event loop routines used by both client and server
550
551 sub set_event_handler {
552     shift unless ref($_[0]); # shift if first arg is package name
553     my ($handle, %args) = @_;
554     my $callback;
555     if (exists $args{'write'}) {
556         $callback = $args{'write'};
557         if ($callback) {
558             $wt_callbacks{$handle} = $callback;
559             $wt_handles->add($handle);
560         } else {
561             delete $wt_callbacks{$handle};
562             $wt_handles->remove($handle);
563         }
564     }
565     if (exists $args{'read'}) {
566         $callback = $args{'read'};
567         if ($callback) {
568             $rd_callbacks{$handle} = $callback;
569             $rd_handles->add($handle);
570         } else {
571             delete $rd_callbacks{$handle};
572             $rd_handles->remove($handle);
573        }
574     }
575     if (exists $args{'error'}) {
576         $callback = $args{'error'};
577         if ($callback) {
578             $er_callbacks{$handle} = $callback;
579             $er_handles->add($handle);
580         } else {
581             delete $er_callbacks{$handle};
582             $er_handles->remove($handle);
583        }
584     }
585 }
586
587 sub event_loop {
588     my ($pkg, $loop_count, $timeout, $wronly) = @_; # event_loop(1) to process events once
589     my ($conn, $r, $w, $e, $rset, $wset, $eset);
590     while (1) {
591  
592        # Quit the loop if no handles left to process
593                 if ($wronly) {
594                         last unless $wt_handles->count();
595         
596                         ($rset, $wset, $eset) = IO::Select->select(undef, $wt_handles, undef, $timeout);
597                         
598                         foreach $w (@$wset) {
599                                 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
600                         }
601                 } else {
602                         
603                         last unless ($rd_handles->count() || $wt_handles->count());
604         
605                         ($rset, $wset, $eset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
606                         
607                         foreach $e (@$eset) {
608                                 &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
609                         }
610                         foreach $r (@$rset) {
611                                 &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
612                         }
613                         foreach $w (@$wset) {
614                                 &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
615                         }
616                 }
617
618                 Timer::handler;
619                 
620         if (defined($loop_count)) {
621             last unless --$loop_count;
622         }
623     }
624 }
625
626 sub sleep
627 {
628         my ($pkg, $interval) = @_;
629         my $now = time;
630         while (time - $now < $interval) {
631                 $pkg->event_loop(10, 0.01);
632         }
633 }
634
635 sub DESTROY
636 {
637         my $conn = shift;
638         my $call = $conn->{call} || 'unallocated';
639         my $host = $conn->{peerhost} || '';
640         my $port = $conn->{peerport} || '';
641         dbg("Connection $conn->{cnum} $call [$host $port] being destroyed") if isdbg('connll');
642         $noconns--;
643 }
644
645 1;
646
647 __END__
648