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