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