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