make sure nothing can be sent to AGW after error
[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 #
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 $noports $lastytime 
33                         $lasthtime $ypolltime $hpolltime %circuit $total_in $total_out
34                     $lastconnect $connectinterval);
35
36 @ISA = qw(Msg ExtMsg);
37 $sock = undef;
38 @outqueue = ();
39 $send_offset = 0;
40 $inmsg = '';
41 $rproc = undef;
42 $noports = 0;
43 $lastytime = $lasthtime = time;
44 $ypolltime = 10 unless defined $ypolltime;
45 $hpolltime = 300 unless defined $hpolltime;
46 %circuit = ();
47 $total_in = $total_out = 0;
48 $lastconnect = 0;
49 $connectinterval = 60;
50
51 sub init
52 {
53         return unless $enable;
54         $rproc = shift;
55         
56         finish();
57
58         dbg("AGW initialising and connecting to $addr/$port ...");
59         $sock = IO::Socket::INET->new(PeerAddr => $addr, PeerPort => $port, Proto=>'tcp', Timeout=>3);
60         $lastconnect = $main::systime;
61         unless ($sock) {
62                 dbg("Cannot connect to AGW Engine at $addr/$port $!");
63                 return;
64         }
65         Msg::blocking($sock, 0);
66         Msg::set_event_handler($sock, read=>\&_rcv, error=>\&_error);
67         
68         # send a P frame for the login if required
69         if ($login) {
70                 my $data = pack "a255 a255", $login, $passwd;
71                 _sendf('P', undef, undef, undef, undef, $data);
72         }
73
74         # send:
75         # R frame for the release number
76         # G frame to ask for ports
77         # X frame to say who we are
78         # optional m frame to enable monitoring
79         _sendf('R');
80         _sendf('G');
81         _sendf('X', $main::mycall);
82         _sendf('m') if $monitor;
83 }
84
85 my $finishing = 0;
86
87 sub finish
88 {
89         return if $finishing;
90         if ($sock) {
91                 $finishing = 1;
92                 dbg("AGW ending...");
93                 for (values %circuit) {
94                         &{$_->{eproc}}() if $_->{eproc};
95                         $_->disconnect;
96                 }
97                 # say we are going
98                 _sendf('m') if $monitor;
99                 _sendf('x', $main::mycall);
100                 Msg->sleep(2);
101                 Msg::set_event_handler($sock, read=>undef, write=>undef, error=>undef);
102                 $sock->close;
103                 $lastconnect = $main::systime;
104                 $sock = undef;
105         }
106         $finishing = 0;
107 }
108
109 sub login
110 {
111         goto &main::login;        # save some writing, this was the default
112 }
113
114 sub active
115 {
116         return $sock;
117 }
118
119 sub _sendf
120 {
121         my $sort = shift || confess "need a valid AGW command letter";
122         my $from = shift || '';
123         my $to   = shift || '';
124         my $port = shift || 0;
125         my $pid  = shift || 0;
126         my $data = shift || '';
127         my $len  = 0;
128
129         return unless $sock;
130         
131         $len = length $data; 
132         if ($sort eq 'y' || $sort eq 'H') {
133                 dbg("AGW sendf: $sort '${from}'->'${to}' port: $port pid: $pid \"$data\"") if isdbg('agwpoll');
134         } elsif ($sort eq 'D') {
135                 if (isdbg('agw')) {
136                         my $d = $data;
137                         $d =~ s/\cM$//;
138                         dbg("AGW sendf: $sort '${from}'->'${to}' port: $port pid: $pid \"$d\"") if isdbg('agw');
139                 }
140         } else {
141                 dbg("AGW sendf: $sort '${from}'->'${to}' port: $port pid: $pid \"$data\"") if isdbg('agw');
142         }
143         push @outqueue, pack('C x3 a1 x1 C x1 a10 a10 V x4 a*', $port, $sort, $pid, $from, $to, $len, $data);
144         Msg::set_event_handler($sock, write=>\&_send);
145 }
146
147 sub _send 
148 {
149     return unless $sock;
150
151     # If $flush is set, set the socket to blocking, and send all
152     # messages in the queue - return only if there's an error
153     # If $flush is 0 (deferred mode) make the socket non-blocking, and
154     # return to the event loop only after every message, or if it
155     # is likely to block in the middle of a message.
156
157     my $offset = $send_offset;
158
159     while (@outqueue) {
160         my $msg            = $outqueue[0];
161                 my $mlth           = length($msg);
162         my $bytes_to_write = $mlth - $offset;
163         my $bytes_written  = 0;
164                 confess("Negative Length! msg: '$msg' lth: $mlth offset: $offset") if $bytes_to_write < 0;
165         while ($bytes_to_write > 0) {
166             $bytes_written = syswrite ($sock, $msg,
167                                        $bytes_to_write, $offset);
168             if (!defined($bytes_written)) {
169                 if (Msg::_err_will_block($!)) {
170                     # Should happen only in deferred mode. Record how
171                     # much we have already sent.
172                     $send_offset = $offset;
173                     # Event handler should already be set, so we will
174                     # be called back eventually, and will resume sending
175                     return 1;
176                 } else {    # Uh, oh
177                                         _error();
178                     return 0; # fail. Message remains in queue ..
179                 }
180             }
181                         if (isdbg('raw')) {
182                                 dbgdump('raw', "AGW send $bytes_written: ", $msg);
183                         }
184             $total_out      += $bytes_written;
185             $offset         += $bytes_written;
186             $bytes_to_write -= $bytes_written;
187         }
188         $send_offset = $offset = 0;
189         shift @outqueue;
190         last;  # Go back to select and wait
191                        # for it to fire again.
192     }
193
194     # Call me back if queue has not been drained.
195     if (@outqueue) {
196         Msg::set_event_handler ($sock, write => \&_send);
197     } else {
198         Msg::set_event_handler ($sock, write => undef);
199     }
200     1;  # Success
201 }
202
203 sub _rcv {                     # Complement to _send
204     return unless $sock;
205     my ($msg, $offset, $bytes_read);
206
207         $bytes_read = sysread ($sock, $msg, 1024, 0);
208         if (defined ($bytes_read)) {
209                 if ($bytes_read > 0) {
210             $total_in += $bytes_read;
211                         $inmsg .= $msg;
212                         if (isdbg('raw')) {
213                                 dbgdump('raw', "AGW read $bytes_read: ", $msg);
214                         }
215                 } 
216         } else {
217                 if (Msg::_err_will_block($!)) {
218                         return;
219                 } else {
220                         _error();
221                         return;
222                 }
223     }
224
225 FINISH:
226     if (defined $bytes_read && $bytes_read == 0) {
227                 finish();
228     } else {
229                 _decode() if length $inmsg >= 36;
230         }
231 }
232
233 sub _error
234 {
235         return if $finishing;
236         $finishing++;
237         dbg("AGW connection error on $addr/$port $!");
238         Msg::set_event_handler($sock, read=>undef, write=>undef, error=>undef);
239         for (%circuit) {
240                 &{$_->{eproc}}() if $_->{eproc};
241                 $_->disconnect;
242         }
243         $sock = undef;
244         $lastconnect = $main::systime;
245         $finishing = 0;
246 }
247
248 sub _decode
249 {
250         return unless $sock;
251
252         # we have at least 36 bytes of data (ugh!)
253         while (length $inmsg >= 36) {
254                 my ($port, $sort, $pid, $from, $to, $len) = unpack('C x3 a1 x1 C x1 Z10 Z10 V x4', $inmsg);
255                 my $data;
256         
257                 # do a sanity check on the length
258                 if ($len > 2000) {
259                         dbg("AGW: invalid length $len > 2000 received ($sort $port $pid '$from'->'$to')");
260                         finish();
261                         return;
262                 }
263                 if ($len == 0){
264                         if (length $inmsg > 36) {
265                                 $inmsg = substr($inmsg, 36);
266                         } else {
267                                 $inmsg = '';
268                         }
269                 } elsif (length $inmsg > $len + 36) {
270                         $data = substr($inmsg, 36, $len);
271                         $inmsg = substr($inmsg, $len + 36);
272                 } elsif (length $inmsg == $len + 36) {
273                         $data = substr($inmsg, 36);
274                         $inmsg = '';
275                 } else {
276                         #
277                         # we don't have enough data or something
278                         # or we have screwed up
279                         #
280                         return;
281                 }
282                 
283                 $data = '' unless defined $data;
284                 if ($sort eq 'D') {
285                         my $d = unpack "Z*", $data;
286                         $d =~ s/\cM\cJ?$//;
287                         $d =~ s/^\cJ//;
288                         dbg("AGW Data In port: $port pid: $pid '$from'->'$to' length: $len \"$d\"") if isdbg('agw');
289                         my $conn = _find($from eq $main::mycall ? $to : $from);
290                         if ($conn) {
291                                 if ($conn->{state} eq 'WC') {
292                                         if (exists $conn->{cmd}) {
293                                                 if (@{$conn->{cmd}}) {
294                                                         dbg($d) if isdbg('connect');
295                                                         $conn->_docmd($d);
296                                                 }
297                                         }
298                                         if ($conn->{state} eq 'WC' && exists $conn->{cmd} && @{$conn->{cmd}} == 0) {
299                                                 $conn->to_connected($conn->{call}, 'O', $conn->{csort});
300                                         }
301                                 } else {
302                                         my @lines = split /\cM\cJ?/, $d;
303                                         push @lines, $d unless @lines;
304                                         for (@lines) {
305                                                 &{$conn->{rproc}}($conn, "I$conn->{call}|$_");
306                                         }
307                                 }
308                         } else {
309                                 dbg("AGW error Unsolicited Data!");
310                         }
311                 } elsif ($sort eq 'I' || $sort eq 'S' || $sort eq 'U' || $sort eq 'M' || $sort eq 'T') {
312                         my $d = unpack "Z*", $data;
313                         $d =~ s/^\cJ//;
314                         $d =~ s/\cM\cJ?$//;
315                         my @lines = split /\cM\cJ?/, $d;
316                         
317                         for (@lines) {
318 #                               s/([\x00-\x1f\x7f-\xff])/sprintf("%%%02X", ord($1))/eg; 
319                                 dbg("AGW Monitor port: $port \"$_\"") if isdbg('agw');
320                         }
321                 } elsif ($sort eq 'C') {
322                         my $d = unpack "Z*", $data;
323                         $d =~ s/\cM\cJ?$//;
324                         dbg("AGW Connect port: $port pid: $pid '$from'->'$to' \"$d\"") if isdbg('agw');
325                         my $call = $from eq $main::mycall ? $to : $from;
326                         my $conn = _find($call);
327                         if ($conn) {
328                                 if ($conn->{state} eq 'WC') {
329                                         if (exists $conn->{cmd} && @{$conn->{cmd}}) {
330                                                 $conn->_docmd($d);
331                                                 if ($conn->{state} eq 'WC' && exists $conn->{cmd} &&  @{$conn->{cmd}} == 0) {
332                                                         $conn->to_connected($conn->{call}, 'O', $conn->{csort});
333                                                 }
334                                         }
335                                 }
336                         } else {
337                                 $conn = AGWMsg->new($rproc);
338                                 $conn->{agwpid} = $pid;
339                                 $conn->{agwport} = $port;
340                                 $conn->{lineend} = "\cM";
341                                 $conn->{incoming} = 1;
342                                 $conn->{agwcall} = $call;
343                                 $circuit{$call} = $conn;
344                                 if (my ($c, $s) = $call =~ /^(\w+)-(\d\d?)$/) {
345                                         $s = 15 - $s if $s > 8;
346                                         $call = $s > 0 ? "${c}-${s}" : $c;
347                                 }
348                                 $conn->to_connected($call, 'A', $conn->{csort} = 'ax25');
349                         }
350                 } elsif ($sort eq 'd') {
351                         my $d = unpack "Z*", $data;
352                         $d =~ s/\cM\cJ?$//;
353                         dbg("AGW '$from'->'$to' port: $port Disconnected ($d)") if isdbg('agw');
354                         my $conn = _find($from eq $main::mycall ? $to : $from);
355                         if ($conn) {
356                                 &{$conn->{eproc}}() if $conn->{eproc};
357                                 $conn->in_disconnect;
358                         }
359                 } elsif ($sort eq 'y') {
360                         my ($frames) = unpack "V", $data;
361                         dbg("AGW Frames Outstanding on port $port = $frames") if isdbg('agwpollans');
362                         my $conn = _find($from);
363                         $conn->{oframes} = $frames if $conn;
364                 } elsif ($sort eq 'Y') {
365                         my ($frames) = unpack "V", $data;
366                         dbg("AGW Frames Outstanding on circuit '$from'->'$to' = $frames") if isdbg('agw');
367                         my $conn = _find($from eq $main::mycall ? $to : $from);
368                         $conn->{oframes} = $frames if $conn;
369                 } elsif ($sort eq 'H') {
370                         unless ($from =~ /^\s+$/) {
371                                 my $d = unpack "Z*", $data;
372                                 $d =~ s/\cM\cJ?$//;
373                                 dbg("AGW Heard port: $port \"$d\"") if isdbg('agw');
374                         }
375                 } elsif ($sort eq 'X') {
376                         my ($r) = unpack "C", $data;
377                         $r = $r ? "Successful" : "Failed";
378                         dbg("AGW Register $from $r");
379                         finish() unless $r;
380                 } elsif ($sort eq 'R') {
381                         my ($major, $minor) = unpack "v x2 v x2", $data;
382                         dbg("AGW Version $major.$minor") if isdbg('agw');
383                 } elsif ($sort eq 'G') {
384                         my @ports = split /;/, $data;
385                         $noports = shift @ports || '0';
386                         dbg("AGW $noports Ports available") if isdbg('agw');
387                         pop @ports while @ports > $noports;
388                         for (@ports) {
389                                 next unless $_;
390                                 dbg("AGW Port: $_") if isdbg('agw');
391                         }
392                         for (my $i = 0; $i < $noports; $i++) {
393                                 _sendf('y', undef, undef, $i);
394                                 _sendf('g', undef, undef, $i);
395                         }
396                 } else {
397                         my $d = unpack "Z*", $data;
398                         dbg("AGW decode $sort port: $port pid: $pid '$from'->'$to' length: $len \"$d\"") if isdbg('agw');
399                 }
400         }
401 }
402
403 sub _find
404 {
405         my $call = shift;
406         return $circuit{$call};
407 }
408
409 sub connect
410 {
411         my ($conn, $line) = @_;
412         
413         my ($port, $call) = split /\s+/, $line;
414         $conn->{agwpid} = ord "\xF0";
415         $conn->{agwport} = $port - 1;
416         $conn->{lineend} = "\cM";
417         $conn->{incoming} = 0;
418         $conn->{csort} = 'ax25';
419         $conn->{agwcall} = uc $call;
420         $circuit{$conn->{agwcall}} = $conn; 
421         
422         _sendf('C', $main::mycall, $conn->{agwcall}, $conn->{agwport}, $conn->{agwpid});
423         $conn->{state} = 'WC';
424         
425         return 1;
426 }
427
428 sub in_disconnect
429 {
430         my $conn = shift;
431         delete $circuit{$conn->{agwcall}}; 
432         $conn->SUPER::disconnect;
433 }
434
435 sub disconnect
436 {
437         my $conn = shift;
438         delete $circuit{$conn->{agwcall}}; 
439         if ($conn->{incoming}) {
440                 _sendf('d', $conn->{agwcall}, $main::mycall, $conn->{agwport}, $conn->{agwpid});
441         } else {
442                 _sendf('d', $main::mycall, $conn->{agwcall}, $conn->{agwport}, $conn->{agwpid});
443         }
444         $conn->SUPER::disconnect;
445 }
446
447 sub enqueue
448 {
449         my ($conn, $msg) = @_;
450         if ($msg =~ /^D/) {
451                 $msg =~ s/^[-\w]+\|//;
452 #               _sendf('Y', $main::mycall, $conn->{call}, $conn->{agwport}, $conn->{agwpid});
453                 _sendf('D', $main::mycall, $conn->{agwcall}, $conn->{agwport}, $conn->{agwpid}, $msg . $conn->{lineend});
454                 my $len = length($msg) + 1; 
455                 dbg("AGW Data Out port: $conn->{agwport} pid: $conn->{agwpid} '$main::mycall'->'$conn->{agwcall}' length: $len \"$msg\"") if isdbg('agw');
456         }
457 }
458
459 sub process
460 {
461         # try to reconnect to AGW if we could not previously or there was an error
462         if ($enable && !$sock && $main::systime >= $lastconnect + $connectinterval) {
463                 init();
464         }
465         return unless $sock;
466
467         if ($ypolltime && $main::systime - $lastytime >= $ypolltime) {
468                 for (my $i = 0; $i < $noports; $i++) {
469                         _sendf('y', undef, undef, $i );
470                 }
471                 $lastytime = $main::systime;
472         }
473         if ($hpolltime && $main::systime - $lasthtime >= $hpolltime) {
474                 for (my $i = 0; $i < $noports; $i++) {
475                         _sendf('H', undef, undef, $i );
476                 }
477                 $lasthtime = $main::systime;
478         }
479 }
480
481 1;
482