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