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