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