took out limit on msglength (ie 0 length messages are allowed)
[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 $bytes_to_write = length($msg) - $offset;
114         my $bytes_written  = 0;
115         while ($bytes_to_write) {
116             $bytes_written = syswrite ($sock, $msg,
117                                        $bytes_to_write, $offset);
118             if (!defined($bytes_written)) {
119                 if (_err_will_block($!)) {
120                     # Should happen only in deferred mode. Record how
121                     # much we have already sent.
122                     $conn->{send_offset} = $offset;
123                     # Event handler should already be set, so we will
124                     # be called back eventually, and will resume sending
125                     return 1;
126                 } else {    # Uh, oh
127                     $conn->handle_send_err($!);
128                     return 0; # fail. Message remains in queue ..
129                 }
130             }
131             $offset         += $bytes_written;
132             $bytes_to_write -= $bytes_written;
133         }
134         delete $conn->{send_offset};
135         $offset = 0;
136         shift @$rq;
137         last unless $flush; # Go back to select and wait
138                             # for it to fire again.
139     }
140     # Call me back if queue has not been drained.
141     if (@$rq) {
142         set_event_handler ($sock, "write" => sub {$conn->_send(0)});
143     } else {
144         set_event_handler ($sock, "write" => undef);
145     }
146     1;  # Success
147 }
148
149 sub _err_will_block {
150     if ($blocking_supported) {
151         return ($_[0] == EAGAIN());
152     }
153     return 0;
154 }
155 sub set_non_blocking {                        # $conn->set_blocking
156     if ($blocking_supported) {
157         # preserve other fcntl flags
158         my $flags = fcntl ($_[0], F_GETFL(), 0);
159         fcntl ($_[0], F_SETFL(), $flags | O_NONBLOCK());
160     }
161 }
162 sub set_blocking {
163     if ($blocking_supported) {
164         my $flags = fcntl ($_[0], F_GETFL(), 0);
165         $flags  &= ~O_NONBLOCK(); # Clear blocking, but preserve other flags
166         fcntl ($_[0], F_SETFL(), $flags);
167     }
168 }
169
170 sub handle_send_err {
171    # For more meaningful handling of send errors, subclass Msg and
172    # rebless $conn.  
173    my ($conn, $err_msg) = @_;
174    warn "Error while sending: $err_msg \n";
175    set_event_handler ($conn->{sock}, "write" => undef);
176 }
177
178 #-----------------------------------------------------------------
179 # Receive side routines
180
181 my ($g_login_proc,$g_pkg);
182 my $main_socket = 0;
183 sub new_server {
184     @_ == 4 || die "Msg->new_server (myhost, myport, login_proc)\n";
185     my ($pkg, $my_host, $my_port, $login_proc) = @_;
186     
187     $main_socket = IO::Socket::INET->new (
188                                           LocalAddr => $my_host,
189                                           LocalPort => $my_port,
190                                           Listen    => 5,
191                                           Proto     => 'tcp',
192                                           Reuse     => 1);
193     die "Could not create socket: $! \n" unless $main_socket;
194     set_event_handler ($main_socket, "read" => \&_new_client);
195     $g_login_proc = $login_proc; $g_pkg = $pkg;
196 }
197
198 sub rcv_now {
199     my ($conn) = @_;
200     my ($msg, $err) = _rcv ($conn, 1); # 1 ==> rcv now
201     return wantarray ? ($msg, $err) : $msg;
202 }
203
204 sub _rcv {                     # Complement to _send
205     my ($conn, $rcv_now) = @_; # $rcv_now complement of $flush
206     # Find out how much has already been received, if at all
207     my ($msg, $offset, $bytes_to_read, $bytes_read);
208     my $sock = $conn->{sock};
209     return unless defined($sock);
210     if (exists $conn->{msg}) {
211         $msg           = $conn->{msg};
212         $offset        = length($msg) - 1;  # sysread appends to it.
213         $bytes_to_read = $conn->{bytes_to_read};
214         delete $conn->{'msg'};              # have made a copy
215     } else {
216         # The typical case ...
217         $msg           = "";                # Otherwise -w complains 
218         $offset        = 0 ;  
219         $bytes_to_read = 0 ;                # Will get set soon
220     }
221     # We want to read the message length in blocking mode. Quite
222     # unlikely that we'll get blocked too long reading 4 bytes
223     if (!$bytes_to_read)  {                 # Get new length 
224         my $buf;
225         $conn->set_blocking();
226         $bytes_read = sysread($sock, $buf, 4);
227         if ($! || ($bytes_read != 4)) {
228             goto FINISH;
229         }
230         $bytes_to_read = unpack ('N', $buf);
231     }
232     $conn->set_non_blocking() unless $rcv_now;
233     while ($bytes_to_read) {
234         $bytes_read = sysread ($sock, $msg, $bytes_to_read, $offset);
235         if (defined ($bytes_read)) {
236             if ($bytes_read == 0) {
237                 last;
238             }
239             $bytes_to_read -= $bytes_read;
240             $offset        += $bytes_read;
241         } else {
242             if (_err_will_block($!)) {
243                 # Should come here only in non-blocking mode
244                 $conn->{msg}           = $msg;
245                 $conn->{bytes_to_read} = $bytes_to_read;
246                 return ;   # .. _rcv will be called later
247                            # when socket is readable again
248             } else {
249                 last;
250             }
251         }
252     }
253
254   FINISH:
255     if (length($msg) == 0) {
256         $conn->disconnect();
257     }
258     if ($rcv_now) {
259         return ($msg, $!);
260     } else {
261         &{$conn->{rcvd_notification_proc}}($conn, $msg, $!);
262     }
263 }
264
265 sub _new_client {
266     my $sock = $main_socket->accept();
267     my $conn = bless {
268         'sock' =>  $sock,
269         'state' => 'connected'
270     }, $g_pkg;
271     my $rcvd_notification_proc =
272         &$g_login_proc ($conn, $sock->peerhost(), $sock->peerport());
273     if ($rcvd_notification_proc) {
274         $conn->{rcvd_notification_proc} = $rcvd_notification_proc;
275         my $callback = sub {_rcv($conn,0)};
276         set_event_handler ($sock, "read" => $callback);
277     } else {  # Login failed
278         $conn->disconnect();
279     }
280 }
281
282 sub close_server
283 {
284         set_event_handler ($main_socket, "read" => undef);
285         $main_socket->close;
286         $main_socket = 0;
287 }
288
289 #----------------------------------------------------
290 # Event loop routines used by both client and server
291
292 sub set_event_handler {
293     shift unless ref($_[0]); # shift if first arg is package name
294     my ($handle, %args) = @_;
295     my $callback;
296     if (exists $args{'write'}) {
297         $callback = $args{'write'};
298         if ($callback) {
299             $wt_callbacks{$handle} = $callback;
300             $wt_handles->add($handle);
301         } else {
302             delete $wt_callbacks{$handle};
303             $wt_handles->remove($handle);
304         }
305     }
306     if (exists $args{'read'}) {
307         $callback = $args{'read'};
308         if ($callback) {
309             $rd_callbacks{$handle} = $callback;
310             $rd_handles->add($handle);
311         } else {
312             delete $rd_callbacks{$handle};
313             $rd_handles->remove($handle);
314        }
315     }
316 }
317
318 sub event_loop {
319     my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
320     my ($conn, $r, $w, $rset, $wset);
321     while (1) {
322         # Quit the loop if no handles left to process
323         last unless ($rd_handles->count() || $wt_handles->count());
324         ($rset, $wset) =
325             IO::Select->select ($rd_handles, $wt_handles, undef, $timeout);
326         foreach $r (@$rset) {
327             &{$rd_callbacks{$r}} ($r) if exists $rd_callbacks{$r};
328         }
329         foreach $w (@$wset) {
330             &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
331         }
332         if (defined($loop_count)) {
333             last unless --$loop_count;
334         }
335     }
336 }
337
338 1;
339
340 __END__
341