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