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