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