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