outgoing calls on AGW engine?
[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);
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
46 sub init
47 {
48         return unless $enable;
49         $rproc = shift;
50         
51         finish();
52         dbg('err', "AGW initialising and connecting to $addr/$port ...");
53         $sock = IO::Socket::INET->new(PeerAddr => $addr, PeerPort => $port, Proto=>'tcp', Timeout => 30);
54         unless ($sock) {
55                 dbg('err', "Cannot connect to AGW Engine at $addr/$port $!");
56                 return;
57         }
58         Msg::blocking($sock, 0);
59         Msg::set_event_handler($sock, read=>\&_rcv, error=>\&_error);
60         
61         # send a P frame for the login if required
62         if ($login) {
63                 my $data = pack "a255 a255", $login, $passwd;
64                 _sendf('P', undef, undef, undef, undef, $data);
65         }
66
67         # send:
68         # R frame for the release number
69         # G frame to ask for ports
70         # X frame to say who we are
71         # optional m frame to enable monitoring
72         _sendf('R');
73         _sendf('G');
74         _sendf('X', $main::mycall);
75         _sendf('m') if $monitor;
76 }
77
78 sub finish
79 {
80         if ($sock) {
81                 dbg('err', "AGW ending...");
82                 for (values %Msg::conns) {
83                         next unless $_->isa('AGWMsg');
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 (values %Msg::conns) {
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                         if ($call =~ /^(\w+)-(\d\d?)$/) {
303                                 my $c = $1;
304                                 my $s = $2;
305                                 $s = 15 - $s;
306                                 if ($s <= 8 && $s > 0) {
307                                         $call = "${c}-${s}";
308                                 } else {
309                                         $call = $c;
310                                 }
311                         }
312                         $conn->to_connected($call, 'A', $conn->{csort} = 'ax25');
313                 }
314         } elsif ($sort eq 'd') {
315                 dbg('agw', "AGW '$from'->'$to' port: $port Disconnected");
316                 my $conn = _find($from eq $main::mycall ? $to : $from);
317                 $conn->in_disconnect if $conn;
318         } elsif ($sort eq 'y') {
319                 my ($frames) = unpack "V", $data;
320                 dbg('agwpollans', "AGW Frames Outstanding on port $port = $frames");
321                 my $conn = Msg->conns($from);
322                 $conn->{oframes} = $frames if $conn;
323         } elsif ($sort eq 'Y') {
324                 my ($frames) = unpack "V", $data;
325                 dbg('agw', "AGW Frames Outstanding on circuit '$from'->'$to' = $frames");
326                 my $conn = Msg->conns($from eq $main::mycall ? $to : $from);
327                 $conn->{oframes} = $frames if $conn;
328         } elsif ($sort eq 'H') {
329                 unless ($from =~ /^\s+$/) {
330                         my $d = unpack "Z*", $data;
331                         $d =~ s/\cM$//;
332                         dbg('agw', "AGW Heard port: $port \"$d\"");
333                 }
334         } elsif ($sort eq 'X') {
335                 my ($r) = unpack "C", $data;
336                 $r = $r ? "Successful" : "Failed";
337                 dbg('err', "AGW Register $from $r");
338                 finish() unless $r;
339         } elsif ($sort eq 'R') {
340                 my ($major, $minor) = unpack "v x2 v x2", $data;
341                 dbg('agw', "AGW Version $major.$minor");
342         } elsif ($sort eq 'G') {
343                 my @ports = split /;/, $data;
344             $noports = shift @ports || '0';
345                 dbg('agw', "AGW $noports Ports available");
346                 pop @ports while @ports > $noports;
347                 for (@ports) {
348                         next unless $_;
349                         dbg('agw', "AGW Port: $_");
350                 }
351                 for (my $i = 0; $i < $noports; $i++) {
352                         _sendf('y', undef, undef, $i );
353                 }
354         } else {
355                 my $d = unpack "Z*", $data;
356                 dbg('agw', "AGW decode $sort port: $port pid: $pid '$from'->'$to' length: $len \"$d\"");
357         }
358 }
359
360 sub _find
361 {
362         my $call = shift;
363         for (values %Msg::conns) {
364                 if ($_->isa('AGWMsg') && $call eq $_->{agwcall}) {
365                         return $_;
366                 }
367         }
368         return undef;
369 }
370
371 sub connect
372 {
373         my ($conn, $line) = @_;
374
375         my ($port, $call) = split /\s+/, $line;
376         $conn->{agwpid} = ord "\xF0";
377         $conn->{agwport} = $port - 1;
378         $conn->{lineend} = "\cM";
379         $conn->{incoming} = 0;
380         $conn->{csort} = 'ax25';
381         $conn->{agwcall} = uc $call;
382         
383         _sendf('C', $main::mycall, $conn->{agwcall}, $conn->{agwport}, $conn->{agwpid});
384         $conn->{state} = 'WC';
385         
386         return 1;
387 }
388
389 sub in_disconnect
390 {
391         my $conn = shift;
392         _sendf('d', $conn->{agwcall}, $main::mycall, $conn->{agwport}, $conn->{agwpid});
393         $conn->SUPER::disconnect;
394 }
395
396 sub disconnect
397 {
398         my $conn = shift;
399         if ($conn->{incoming}) {
400                 _sendf('d', $conn->{agwcall}, $main::mycall, $conn->{agwport}, $conn->{agwpid});
401         } else {
402                 _sendf('d', $main::mycall, $conn->{agwcall}, $conn->{agwport}, $conn->{agwpid});
403         }
404         $conn->SUPER::disconnect;
405 }
406
407 sub enqueue
408 {
409         my ($conn, $msg) = @_;
410         if ($msg =~ /^D/) {
411                 $msg =~ s/^[-\w]+\|//;
412 #               _sendf('Y', $main::mycall, $conn->{call}, $conn->{agwport}, $conn->{agwpid});
413                 _sendf('D', $main::mycall, $conn->{agwcall}, $conn->{agwport}, $conn->{agwpid}, $msg . $conn->{lineend});
414         }
415 }
416
417 sub process
418 {
419         return unless $sock;
420         if ($ypolltime && $main::systime - $lastytime >= $ypolltime) {
421                 for (my $i = 0; $i < $noports; $i++) {
422                         _sendf('y', undef, undef, $i );
423                 }
424                 $lastytime = $main::systime;
425         }
426         if ($hpolltime && $main::systime - $lasthtime >= $hpolltime) {
427                 for (my $i = 0; $i < $noports; $i++) {
428                         _sendf('H', undef, undef, $i );
429                 }
430                 $lasthtime = $main::systime;
431         }
432 }
433 1;
434