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