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