allow out going frames :-)
[spider.git] / perl / AGWMsg.pm
1 #
2 # This class is the internal subclass that deals with AGW Engine connections
3 #
4 # The complication here is that there only one 'real' (and from the node's point
5 # of view, invisible) IP connection. This connection then has multiplexed 
6 # connections passed down it, a la BPQ native host ports (but not as nicely).
7 #
8 # It is a shame that the author has chosen an inherently dangerous binary format
9 # which is non-framed and has the potential for getting out of sync and not
10 # being able to recover. Relying on length fields is recipe for disaster (esp.
11 # for him!). DoS attacks are a wonderful thing....
12 #
13 # Also making the user handle the distinction between a level 2 and 4 connection
14 # and especially Digis, in the way that he has, is a bit of a cop out! If I can
15 # be arsed to do anything other than straight ax25 connects then it will only
16 # because I have the 'power of perl' available that avoids me getting 
17 # terminally bored sorting out other people's sloppyness.
18 #
19 # $Id$
20 #
21 # Copyright (c) 2001 - Dirk Koopman G1TLH
22 #
23
24 package AGWMsg;
25
26 use strict;
27 use IO::Socket;
28 use Msg;
29 use AGWConnect;
30 use DXDebug;
31
32 use vars qw(@ISA $sock @outqueue $send_offset $inmsg $rproc);
33
34 @ISA = qw(Msg ExtMsg);
35 $sock = undef;
36 @outqueue = ();
37 $send_offset = 0;
38 $inmsg = '';
39 $rproc = undef;
40
41 sub init
42 {
43         return unless $enable;
44         $rproc = shift;
45         
46         finish();
47         dbg('err', "AGW initialising and connecting to $addr/$port ...");
48         $sock = IO::Socket::INET->new(PeerAddr => $addr, PeerPort => $port, Proto=>'tcp');
49         unless ($sock) {
50                 dbg('err', "Cannot connect to AGW Engine at $addr/$port $!");
51                 return;
52         }
53         Msg::blocking($sock, 0);
54         Msg::set_event_handler($sock, read=>\&_rcv, error=>\&_error);
55         
56         # send a P frame for the login if required
57         if ($login) {
58                 my $data = pack "a255 a255", $login, $passwd;
59                 _sendf('P', undef, undef, undef, undef, $data);
60         }
61
62         # send:
63         # R frame for the release number
64         # G frame to ask for ports
65         # X frame to say who we are
66         _sendf('R');
67         _sendf('G');
68         _sendf('X', $main::mycall);
69         if ($monitor) {
70                 _sendf('m')
71         }
72 }
73
74 sub finish
75 {
76         if ($sock) {
77                 dbg('err', "AGW ending...");
78                 for (values %Msg::conns) {
79                         next unless $_->isa('AGWMsg');
80                         $_->disconnect;
81                 }
82                 # say we are going
83                 _sendf('x', $main::mycall);
84                 Msg->sleep(2);
85                 Msg::set_event_handler($sock, read=>undef, write=>undef, error=>undef);
86                 $sock->close;
87         }
88 }
89
90 sub _sendf
91 {
92         my $sort = shift || confess "need a valid AGW command letter";
93         my $from = shift || '';
94         my $to   = shift || '';
95         my $port = shift || 0;
96         my $pid  = shift || 0;
97         my $data = shift || '';
98         my $len  = 0;
99         
100         $len = length $data; 
101         dbg('agw', "AGW sendf: $sort '${from}'->'${to}' port: $port pid: $pid \"$data\"");
102         push @outqueue, pack('C x3 a1 x1 C x1 a10 a10 V x4 a*', $port, $sort, $pid, $from, $to, $len, $data);
103         Msg::set_event_handler($sock, write=>\&_send);
104 }
105
106 sub _send 
107 {
108     return unless $sock;
109
110     # If $flush is set, set the socket to blocking, and send all
111     # messages in the queue - return only if there's an error
112     # If $flush is 0 (deferred mode) make the socket non-blocking, and
113     # return to the event loop only after every message, or if it
114     # is likely to block in the middle of a message.
115
116     my $offset = $send_offset;
117
118     while (@outqueue) {
119         my $msg            = $outqueue[0];
120                 my $mlth           = length($msg);
121         my $bytes_to_write = $mlth - $offset;
122         my $bytes_written  = 0;
123                 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
124         while ($bytes_to_write > 0) {
125             $bytes_written = syswrite ($sock, $msg,
126                                        $bytes_to_write, $offset);
127             if (!defined($bytes_written)) {
128                 if (Msg::_err_will_block($!)) {
129                     # Should happen only in deferred mode. Record how
130                     # much we have already sent.
131                     $send_offset = $offset;
132                     # Event handler should already be set, so we will
133                     # be called back eventually, and will resume sending
134                     return 1;
135                 } else {    # Uh, oh
136                                         _error();
137                     return 0; # fail. Message remains in queue ..
138                 }
139             }
140             $offset         += $bytes_written;
141             $bytes_to_write -= $bytes_written;
142         }
143         $send_offset = $offset = 0;
144         shift @outqueue;
145         last;  # Go back to select and wait
146                        # for it to fire again.
147     }
148
149     # Call me back if queue has not been drained.
150     if (@outqueue) {
151         Msg::set_event_handler ($sock, write => \&_send);
152     } else {
153         Msg::set_event_handler ($sock, write => undef);
154     }
155     1;  # Success
156 }
157
158 sub _rcv {                     # Complement to _send
159     return unless $sock;
160     my ($msg, $offset, $bytes_read);
161
162         $bytes_read = sysread ($sock, $msg, 1024, 0);
163         if (defined ($bytes_read)) {
164                 if ($bytes_read > 0) {
165                         $inmsg .= $msg;
166                 } 
167         } else {
168                 if (Msg::_err_will_block($!)) {
169                         return; 
170                 } else {
171                         $bytes_read = 0;
172                 }
173     }
174
175 FINISH:
176     if (defined $bytes_read && $bytes_read == 0) {
177                 finish();
178     } else {
179                 _decode() if length $inmsg > 36;
180         }
181 }
182
183 sub _error
184 {
185         dbg('agw', "error on AGW connection $addr/$port $!");
186         Msg::set_event_handler($sock, read=>undef, write=>undef, error=>undef);
187         $sock = undef;
188         for (values %Msg::conns) {
189                 next unless $_->isa('AGWMsg');
190                 $_->disconnect;
191         }
192 }
193
194 sub _decode
195 {
196         return unless $sock;
197
198         # we have at least 36 bytes of data (ugh!)
199         my ($port, $sort, $pid, $from, $to, $len) = unpack('C x3 a1 x1 C x1 a10 a10 V x4', $inmsg);
200         my $data;
201
202         # do a sanity check on the length
203         if ($len > 2000) {
204                 dbg('err', "AGW: invalid length $len > 2000 received ($sort $port $pid '$from'->'$to')");
205                 finish();
206                 return;
207         }
208         if ($len == 0){
209                 if (length $inmsg > 36) {
210                         $inmsg = substr($inmsg, 36);
211                 } else {
212                         $inmsg = '';
213                 }
214         } elsif (length $inmsg > $len + 36) {
215                 $data = substr($inmsg, 36, $len);
216                 $inmsg = substr($inmsg, $len + 36);
217         } elsif (length $inmsg == $len + 36) {
218                 $data = substr($inmsg, 36);
219                 $inmsg = '';
220         } else {
221                 # we don't have enough data or something
222                 # or we have screwed up
223                 return;
224         }
225
226         $data = '' unless defined $data;
227         if ($sort eq 'D') {
228                 $data =~ s/\cR//g;
229                 dbg('agw', "AGW Data In port: $port pid: $pid '$from'->'$to' length: $len \"$data\"");
230                 my $conn = Msg->conns($from eq $main::mycall ? $to : $from);
231                 if ($conn) {
232                         if ($conn->{state} eq 'WC') {
233                                 if (exists $conn->{cmd}) {
234                                         if (@{$conn->{cmd}}) {
235                                                 dbg('connect', $conn->{msg});
236                                                 $conn->_docmd($conn->{msg});
237                                         }
238                                 }
239                                 if ($conn->{state} eq 'WC' && exists $conn->{cmd} && @{$conn->{cmd}} == 0) {
240                                         $conn->to_connected($conn->{call}, 'O', $conn->{csort});
241                                 }
242                         } else {
243                                 &{$conn->{rproc}}($conn, "I$conn->{call}|$data");
244                         }
245                 } else {
246                         dbg('err', "AGW error Unsolicited Data!");
247                 }
248         } elsif ($sort eq 'I' || $sort eq 'S' || $sort eq 'U' || $sort eq 'M') {
249                 dbg('agw', "AGW Monitor \"$data\"");
250         } elsif ($sort eq 'C') {
251                 dbg('agw', "AGW Connect port: $port pid: $pid '$from'->'$to'");
252                 my $call = $from eq $main::mycall ? $to : $from;
253                 my $conn = Msg->conns($call);
254                 if ($conn) {
255                         if ($conn->{state} eq 'WC') {
256                                 if (exists $conn->{cmd} && @{$conn->{cmd}}) {
257                                         $conn->_docmd($data);
258                                         if ($conn->{state} eq 'WC' && exists $conn->{cmd} &&  @{$conn->{cmd}} == 0) {
259                                                 $conn->to_connected($conn->{call}, 'O', $conn->{csort});
260                                         }
261                                 }
262                         }
263                 } else {
264                         $conn = AGWMsg->new($rproc);
265                         $conn->{agwpid} = $pid;
266                         $conn->{agwport} = $port;
267                         $conn->{lineend} = "\cR";
268                         $conn->to_connected($call, 'A', $conn->{csort} = 'ax25');
269                 }
270         } elsif ($sort eq 'd') {
271                 dbg('agw', "AGW '$from'->'$to' Disconnected");
272                 my $conn = Msg->conns($from eq $main::mycall ? $to : $from);
273                 $conn->in_disconnect if $conn;
274         } elsif ($sort eq 'y') {
275                 my ($frames) = unpack "V", $data;
276                 dbg('agw', "AGW Frames Outstanding on port $port = $frames");
277                 my $conn = Msg->conns($from);
278                 $conn->{oframes} = $frames if $conn;
279         } elsif ($sort eq 'Y') {
280                 my ($frames) = unpack "V", $data;
281                 dbg('agw', "AGW Frames Outstanding on circuit '$from'->'$to' = $frames");
282                 my $conn = Msg->conns($from eq $main::mycall ? $to : $from);
283                 $conn->{oframes} = $frames if $conn;
284         } elsif ($sort eq 'X') {
285                 my ($r) = unpack "C", $data;
286                 $r = $r ? "Successful" : "Failed";
287                 dbg('err', "AGW Register $from $r");
288                 finish() unless $r;
289         } elsif ($sort eq 'R') {
290                 my ($major, $minor) = unpack "v x2 v x2", $data;
291                 dbg('agw', "AGW Version $major.$minor");
292         } elsif ($sort eq 'G') {
293                 my @ports = split /;/, $data;
294                 dbg('agw', "AGW $ports[0] Ports available");
295                 my $n = shift @ports;
296                 pop @ports while @ports > $n;
297                 for (@ports) {
298                         next unless $_;
299                         dbg('agw', "AGW Port: $_");
300                 }
301         } else {
302                 dbg('agw', "AGW decode $sort port: $port pid: $pid '$from'->'$to' length: $len \"$data\"");
303         }
304 }
305
306 sub in_disconnect
307 {
308         my $conn = shift;
309         $conn->SUPER->disconnect;
310 }
311
312 sub disconnect
313 {
314         my $conn = shift;
315         _sendf('d', $main::mycall, $conn->{call}, $conn->{agwport});
316         $conn->SUPER->disconnect;
317 }
318
319 sub enqueue
320 {
321         my ($conn, $msg) = @_;
322         if ($msg =~ /^[D]/) {
323                 $msg =~ s/^[-\w]+\|//;
324                 _sendf('D', $main::mycall, $conn->{call}, $conn->{agwport}, $conn->{agwpid}, $msg . $conn->{lineend});
325         }
326 }
327 1;
328