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