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