1. put some extra checks and balances in to message send routine in Msg.pm to
[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 require Exporter;
14 @ISA = qw(Exporter);
15
16 use strict;
17 use IO::Select;
18 use IO::Socket;
19 use Carp;
20
21 use vars qw (%rd_callbacks %wt_callbacks $rd_handles $wt_handles);
22
23 %rd_callbacks = ();
24 %wt_callbacks = ();
25 $rd_handles   = IO::Select->new();
26 $wt_handles   = IO::Select->new();
27 my $blocking_supported = 0;
28
29 BEGIN {
30     # Checks if blocking is supported
31     eval {
32         require POSIX; POSIX->import(qw (F_SETFL O_NONBLOCK EAGAIN));
33     };
34     $blocking_supported = 1 unless $@;
35 }
36
37 #-----------------------------------------------------------------
38 # Send side routines
39 sub connect {
40     my ($pkg, $to_host, $to_port,$rcvd_notification_proc) = @_;
41     
42     # Create a new internet socket
43     
44     my $sock = IO::Socket::INET->new (
45                                       PeerAddr => $to_host,
46                                       PeerPort => $to_port,
47                                       Proto    => 'tcp',
48                                       Reuse    => 1);
49
50     return undef unless $sock;
51
52     # Create a connection end-point object
53     my $conn = {
54         sock                   => $sock,
55         rcvd_notification_proc => $rcvd_notification_proc,
56     };
57     
58     if ($rcvd_notification_proc) {
59         my $callback = sub {_rcv($conn, 0)};
60         set_event_handler ($sock, "read" => $callback);
61     }
62     return bless $conn, $pkg;
63 }
64
65 sub disconnect {
66     my $conn = shift;
67     my $sock = delete $conn->{sock};
68     return unless defined($sock);
69     set_event_handler ($sock, "read" => undef, "write" => undef);
70     shutdown($sock, 3);
71         close($sock);
72 }
73
74 sub send_now {
75     my ($conn, $msg) = @_;
76     _enqueue ($conn, $msg);
77     $conn->_send (1); # 1 ==> flush
78 }
79
80 sub send_later {
81     my ($conn, $msg) = @_;
82     _enqueue($conn, $msg);
83     my $sock = $conn->{sock};
84     return unless defined($sock);
85     set_event_handler ($sock, "write" => sub {$conn->_send(0)});
86 }
87
88 sub _enqueue {
89     my ($conn, $msg) = @_;
90     # prepend length (encoded as network long)
91     my $len = length($msg);
92     $msg = pack ('N', $len) . $msg; 
93     push (@{$conn->{queue}}, $msg);
94 }
95
96 sub _send {
97     my ($conn, $flush) = @_;
98     my $sock = $conn->{sock};
99     return unless defined($sock);
100     my ($rq) = $conn->{queue};
101
102     # If $flush is set, set the socket to blocking, and send all
103     # messages in the queue - return only if there's an error
104     # If $flush is 0 (deferred mode) make the socket non-blocking, and
105     # return to the event loop only after every message, or if it
106     # is likely to block in the middle of a message.
107
108     $flush ? $conn->set_blocking() : $conn->set_non_blocking();
109     my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
110
111     while (@$rq) {
112         my $msg            = $rq->[0];
113                 my $mlth           = length($msg);
114         my $bytes_to_write = $mlth - $offset;
115         my $bytes_written  = 0;
116                 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
117         while ($bytes_to_write > 0) {
118             $bytes_written = syswrite ($sock, $msg,
119                                        $bytes_to_write, $offset);
120             if (!defined($bytes_written)) {
121                 if (_err_will_block($!)) {
122                     # Should happen only in deferred mode. Record how
123                     # much we have already sent.
124                     $conn->{send_offset} = $offset;
125                     # Event handler should already be set, so we will
126                     # be called back eventually, and will resume sending
127                     return 1;
128                 } else {    # Uh, oh
129                                         delete $conn->{send_offset};
130                     $conn->handle_send_err($!);
131                     return 0; # fail. Message remains in queue ..
132                 }
133             }
134             $offset         += $bytes_written;
135             $bytes_to_write -= $bytes_written;
136         }
137         delete $conn->{send_offset};
138         $offset = 0;
139         shift @$rq;
140         last unless $flush; # Go back to select and wait
141                             # for it to fire again.
142     }
143     # Call me back if queue has not been drained.
144     if (@$rq) {
145         set_event_handler ($sock, "write" => sub {$conn->_send(0)});
146     } else {
147         set_event_handler ($sock, "write" => undef);
148     }
149     1;  # Success
150 }
151
152 sub _err_will_block {
153     if ($blocking_supported) {
154         return ($_[0] == EAGAIN());
155     }
156     return 0;
157 }
158 sub set_non_blocking {                        # $conn->set_blocking
159     if ($blocking_supported) {
160         # preserve other fcntl flags
161         my $flags = fcntl ($_[0], F_GETFL(), 0);
162         fcntl ($_[0], F_SETFL(), $flags | O_NONBLOCK());
163     }
164 }
165 sub set_blocking {
166     if ($blocking_supported) {
167         my $flags = fcntl ($_[0], F_GETFL(), 0);
168         $flags  &= ~O_NONBLOCK(); # Clear blocking, but preserve other flags
169         fcntl ($_[0], F_SETFL(), $flags);
170     }
171 }
172
173 sub handle_send_err {
174    # For more meaningful handling of send errors, subclass Msg and
175    # rebless $conn.  
176    my ($conn, $err_msg) = @_;
177    warn "Error while sending: $err_msg \n";
178    set_event_handler ($conn->{sock}, "write" => undef);
179 }
180
181 #-----------------------------------------------------------------
182 # Receive side routines
183
184 my ($g_login_proc,$g_pkg);
185 my $main_socket = 0;
186 sub new_server {
187     @_ == 4 || die "Msg->new_server (myhost, myport, login_proc)\n";
188     my ($pkg, $my_host, $my_port, $login_proc) = @_;
189     
190     $main_socket = IO::Socket::INET->new (
191                                           LocalAddr => $my_host,
192                                           LocalPort => $my_port,
193                                           Listen    => 5,
194                                           Proto     => 'tcp',
195                                           Reuse     => 1);
196     die "Could not create socket: $! \n" unless $main_socket;
197     set_event_handler ($main_socket, "read" => \&_new_client);
198     $g_login_proc = $login_proc; $g_pkg = $pkg;
199 }
200
201 sub rcv_now {
202     my ($conn) = @_;
203     my ($msg, $err) = _rcv ($conn, 1); # 1 ==> rcv now
204     return wantarray ? ($msg, $err) : $msg;
205 }
206
207 sub _rcv {                     # Complement to _send
208     my ($conn, $rcv_now) = @_; # $rcv_now complement of $flush
209     # Find out how much has already been received, if at all
210     my ($msg, $offset, $bytes_to_read, $bytes_read);
211     my $sock = $conn->{sock};
212     return unless defined($sock);
213     if (exists $conn->{msg}) {
214         $msg           = $conn->{msg};
215         $offset        = length($msg) - 1;  # sysread appends to it.
216         $bytes_to_read = $conn->{bytes_to_read};
217         delete $conn->{'msg'};              # have made a copy
218     } else {
219         # The typical case ...
220         $msg           = "";                # Otherwise -w complains 
221         $offset        = 0 ;  
222         $bytes_to_read = 0 ;                # Will get set soon
223     }
224     # We want to read the message length in blocking mode. Quite
225     # unlikely that we'll get blocked too long reading 4 bytes
226     if (!$bytes_to_read)  {                 # Get new length 
227         my $buf;
228         $conn->set_blocking();
229         $bytes_read = sysread($sock, $buf, 4);
230         if ($! || ($bytes_read != 4)) {
231             goto FINISH;
232         }
233         $bytes_to_read = unpack ('N', $buf);
234     }
235     $conn->set_non_blocking() unless $rcv_now;
236     while ($bytes_to_read) {
237         $bytes_read = sysread ($sock, $msg, $bytes_to_read, $offset);
238         if (defined ($bytes_read)) {
239             if ($bytes_read == 0) {
240                 last;
241             }
242             $bytes_to_read -= $bytes_read;
243             $offset        += $bytes_read;
244         } else {
245             if (_err_will_block($!)) {
246                 # Should come here only in non-blocking mode
247                 $conn->{msg}           = $msg;
248                 $conn->{bytes_to_read} = $bytes_to_read;
249                 return ;   # .. _rcv will be called later
250                            # when socket is readable again
251             } else {
252                 last;
253             }
254         }
255     }
256
257   FINISH:
258     if (length($msg) == 0) {
259         $conn->disconnect();
260     }
261     if ($rcv_now) {
262         return ($msg, $!);
263     } else {
264         &{$conn->{rcvd_notification_proc}}($conn, $msg, $!);
265     }
266 }
267
268 sub _new_client {
269     my $sock = $main_socket->accept();
270     my $conn = bless {
271         'sock' =>  $sock,
272         'state' => 'connected'
273     }, $g_pkg;
274     my $rcvd_notification_proc =
275         &$g_login_proc ($conn, $sock->peerhost(), $sock->peerport());
276     if ($rcvd_notification_proc) {
277         $conn->{rcvd_notification_proc} = $rcvd_notification_proc;
278         my $callback = sub {_rcv($conn,0)};
279         set_event_handler ($sock, "read" => $callback);
280     } else {  # Login failed
281         $conn->disconnect();
282     }
283 }
284
285 sub close_server
286 {
287         set_event_handler ($main_socket, "read" => undef);
288         $main_socket->close;
289         $main_socket = 0;
290 }
291
292 #----------------------------------------------------
293 # Event loop routines used by both client and server
294
295 sub set_event_handler {
296     shift unless ref($_[0]); # shift if first arg is package name
297     my ($handle, %args) = @_;
298     my $callback;
299     if (exists $args{'write'}) {
300         $callback = $args{'write'};
301         if ($callback) {
302             $wt_callbacks{$handle} = $callback;
303             $wt_handles->add($handle);
304         } else {
305             delete $wt_callbacks{$handle};
306             $wt_handles->remove($handle);
307         }
308     }
309     if (exists $args{'read'}) {
310         $callback = $args{'read'};
311         if ($callback) {
312             $rd_callbacks{$handle} = $callback;
313             $rd_handles->add($handle);
314         } else {
315             delete $rd_callbacks{$handle};
316             $rd_handles->remove($handle);
317        }
318     }
319 }
320
321 sub event_loop {
322     my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
323     my ($conn, $r, $w, $rset, $wset);
324     while (1) {
325         # Quit the loop if no handles left to process
326         last unless ($rd_handles->count() || $wt_handles->count());
327         ($rset, $wset) =
328             IO::Select->select ($rd_handles, $wt_handles, undef, $timeout);
329         foreach $r (@$rset) {
330             &{$rd_callbacks{$r}} ($r) if exists $rd_callbacks{$r};
331         }
332         foreach $w (@$wset) {
333             &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
334         }
335         if (defined($loop_count)) {
336             last unless --$loop_count;
337         }
338     }
339 }
340
341 1;
342
343 __END__
344