first cut at outgoing ax25 / external 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 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         unless ($^O =~ /^MS/i) {
171                 kill 'TERM', $conn->{pid} if exists $conn->{pid};
172         }
173
174         # get rid of any references
175         for (keys %$conn) {
176                 if (ref($conn->{$_})) {
177                         delete $conn->{$_};
178                 }
179         }
180
181         return unless defined($sock);
182     set_event_handler ($sock, read => undef, write => undef, error => undef);
183     shutdown($sock, 3);
184         close($sock);
185 }
186
187 sub send_now {
188     my ($conn, $msg) = @_;
189     $conn->enqueue($msg);
190     $conn->_send (1); # 1 ==> flush
191 }
192
193 sub send_later {
194     my ($conn, $msg) = @_;
195     $conn->enqueue($msg);
196     my $sock = $conn->{sock};
197     return unless defined($sock);
198     set_event_handler ($sock, write => sub {$conn->_send(0)});
199 }
200
201 sub enqueue {
202     my $conn = shift;
203     push (@{$conn->{outqueue}}, defined $_[0] ? $_[0] : '');
204 }
205
206 sub _send {
207     my ($conn, $flush) = @_;
208     my $sock = $conn->{sock};
209     return unless defined($sock);
210     my $rq = $conn->{outqueue};
211
212     # If $flush is set, set the socket to blocking, and send all
213     # messages in the queue - return only if there's an error
214     # If $flush is 0 (deferred mode) make the socket non-blocking, and
215     # return to the event loop only after every message, or if it
216     # is likely to block in the middle of a message.
217
218         blocking($sock, $flush);
219     my $offset = (exists $conn->{send_offset}) ? $conn->{send_offset} : 0;
220
221     while (@$rq) {
222         my $msg            = $rq->[0];
223                 my $mlth           = length($msg);
224         my $bytes_to_write = $mlth - $offset;
225         my $bytes_written  = 0;
226                 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
227         while ($bytes_to_write > 0) {
228             $bytes_written = syswrite ($sock, $msg,
229                                        $bytes_to_write, $offset);
230             if (!defined($bytes_written)) {
231                 if (_err_will_block($!)) {
232                     # Should happen only in deferred mode. Record how
233                     # much we have already sent.
234                     $conn->{send_offset} = $offset;
235                     # Event handler should already be set, so we will
236                     # be called back eventually, and will resume sending
237                     return 1;
238                 } else {    # Uh, oh
239                                         &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
240                                         $conn->disconnect;
241                     return 0; # fail. Message remains in queue ..
242                 }
243             }
244             $offset         += $bytes_written;
245             $bytes_to_write -= $bytes_written;
246         }
247         delete $conn->{send_offset};
248         $offset = 0;
249         shift @$rq;
250         last unless $flush; # Go back to select and wait
251                             # for it to fire again.
252     }
253     # Call me back if queue has not been drained.
254     if (@$rq) {
255         set_event_handler ($sock, write => sub {$conn->_send(0)});
256     } else {
257         set_event_handler ($sock, write => undef);
258                 if (exists $conn->{close_on_empty}) {
259                         &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
260                         $conn->disconnect; 
261                 }
262     }
263     1;  # Success
264 }
265
266 sub _err_will_block {
267         return ($_[0] == EAGAIN || $_[0] == EWOULDBLOCK || $_[0] == EINPROGRESS);
268 }
269
270 sub close_on_empty
271 {
272         my $conn = shift;
273         $conn->{close_on_empty} = 1;
274 }
275
276 #-----------------------------------------------------------------
277 # Receive side routines
278
279 sub new_server {
280     @_ == 4 || die "Msg->new_server (myhost, myport, login_proc\n";
281     my ($pkg, $my_host, $my_port, $login_proc) = @_;
282         my $self = $pkg->new($login_proc);
283         
284     $self->{sock} = IO::Socket::INET->new (
285                                           LocalAddr => $my_host,
286                                           LocalPort => $my_port,
287                                           Listen    => SOMAXCONN,
288                                           Proto     => 'tcp',
289                                           Reuse     => 1);
290     die "Could not create socket: $! \n" unless $self->{sock};
291     set_event_handler ($self->{sock}, read => sub { $self->new_client }  );
292         return $self;
293 }
294
295 sub dequeue
296 {
297         my $conn = shift;
298
299         if ($conn->{msg} =~ /\n/) {
300                 my @lines = split /\r?\n/, $conn->{msg};
301                 if ($conn->{msg} =~ /\n$/) {
302                         delete $conn->{msg};
303                 } else {
304                         $conn->{msg} = pop @lines;
305                 }
306                 for (@lines) {
307                         &{$conn->{rproc}}($conn, defined $_ ? $_ : '');
308                 }
309         }
310 }
311
312 sub _rcv {                     # Complement to _send
313     my $conn = shift; # $rcv_now complement of $flush
314     # Find out how much has already been received, if at all
315     my ($msg, $offset, $bytes_to_read, $bytes_read);
316     my $sock = $conn->{sock};
317     return unless defined($sock);
318
319         my @lines;
320         blocking($sock, 0);
321         $bytes_read = sysread ($sock, $msg, 1024, 0);
322         if (defined ($bytes_read)) {
323                 if ($bytes_read > 0) {
324                         $conn->{msg} .= $msg;
325                 } 
326         } else {
327                 if (_err_will_block($!)) {
328                         return ; 
329                 } else {
330                         $bytes_read = 0;
331                 }
332     }
333
334 FINISH:
335     if (defined $bytes_read && $bytes_read == 0) {
336                 &{$conn->{eproc}}($conn, $!) if exists $conn->{eproc};
337                 $conn->disconnect;
338     } else {
339                 $conn->dequeue if exists $conn->{msg};
340         }
341 }
342
343 sub new_client {
344         my $server_conn = shift;
345     my $sock = $server_conn->{sock}->accept();
346     my $conn = $server_conn->new($server_conn->{rproc});
347         $conn->{sock} = $sock;
348     my ($rproc, $eproc) = &{$server_conn->{rproc}} ($conn, $conn->{peerhost} = $sock->peerhost(), $conn->{peerport} = $sock->peerport());
349         $conn->{sort} = 'Incoming';
350         if ($eproc) {
351                 $conn->{eproc} = $eproc;
352         set_event_handler ($sock, error => $eproc);
353         }
354     if ($rproc) {
355         $conn->{rproc} = $rproc;
356         my $callback = sub {$conn->_rcv};
357         set_event_handler ($sock, read => $callback);
358     } else {  # Login failed
359                 &{$conn->{eproc}}($conn, undef) if exists $conn->{eproc};
360         $conn->disconnect();
361     }
362 }
363
364 sub close_server
365 {
366         my $conn = shift;
367         set_event_handler ($conn->{sock}, read => undef, write => undef, error => undef );
368         $conn->{sock}->close;
369 }
370
371 # close all clients (this is for forking really)
372 sub close_all_clients
373 {
374         for (values %conns) {
375                 $_->disconnect;
376         }
377 }
378
379 #----------------------------------------------------
380 # Event loop routines used by both client and server
381
382 sub set_event_handler {
383     shift unless ref($_[0]); # shift if first arg is package name
384     my ($handle, %args) = @_;
385     my $callback;
386     if (exists $args{'write'}) {
387         $callback = $args{'write'};
388         if ($callback) {
389             $wt_callbacks{$handle} = $callback;
390             $wt_handles->add($handle);
391         } else {
392             delete $wt_callbacks{$handle};
393             $wt_handles->remove($handle);
394         }
395     }
396     if (exists $args{'read'}) {
397         $callback = $args{'read'};
398         if ($callback) {
399             $rd_callbacks{$handle} = $callback;
400             $rd_handles->add($handle);
401         } else {
402             delete $rd_callbacks{$handle};
403             $rd_handles->remove($handle);
404        }
405     }
406     if (exists $args{'error'}) {
407         $callback = $args{'error'};
408         if ($callback) {
409             $er_callbacks{$handle} = $callback;
410             $er_handles->add($handle);
411         } else {
412             delete $er_callbacks{$handle};
413             $er_handles->remove($handle);
414        }
415     }
416 }
417
418 sub event_loop {
419     my ($pkg, $loop_count, $timeout) = @_; # event_loop(1) to process events once
420     my ($conn, $r, $w, $e, $rset, $wset, $eset);
421     while (1) {
422  
423        # Quit the loop if no handles left to process
424         last unless ($rd_handles->count() || $wt_handles->count());
425         
426                 ($rset, $wset) = IO::Select->select($rd_handles, $wt_handles, $er_handles, $timeout);
427                 
428         foreach $e (@$eset) {
429             &{$er_callbacks{$e}}($e) if exists $er_callbacks{$e};
430         }
431         foreach $r (@$rset) {
432             &{$rd_callbacks{$r}}($r) if exists $rd_callbacks{$r};
433         }
434         foreach $w (@$wset) {
435             &{$wt_callbacks{$w}}($w) if exists $wt_callbacks{$w};
436         }
437
438                 Timer::handler;
439                 
440         if (defined($loop_count)) {
441             last unless --$loop_count;
442         }
443     }
444 }
445
446 sub DESTROY
447 {
448         my $conn = shift;
449         my $call = $conn->{call} || 'unallocated';
450         dbg('connll', "Connection $call being destroyed ($noconns)");
451         $noconns--;
452 }
453
454 1;
455
456 __END__
457