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