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