make sure nodes only get 1 copy of an announce
[spider.git] / perl / DXProt.pm
1 #!/usr/bin/perl
2 #
3 # This module impliments the protocal mode for a dx cluster
4 #
5 # Copyright (c) 1998 Dirk Koopman G1TLH
6 #
7 # $Id$
8
9
10 package DXProt;
11
12 @ISA = qw(DXChannel);
13
14 use DXUtil;
15 use DXChannel;
16 use DXUser;
17 use DXM;
18 use DXCluster;
19 use DXProtVars;
20 use DXCommandmode;
21 use DXLog;
22 use Spot;
23 use DXProtout;
24 use DXDebug;
25 use Filter;
26 use Local;
27
28 use Carp;
29
30 use strict;
31 use vars qw($me $pc11_max_age $pc23_max_age $pc11_dup_age $pc23_dup_age
32                         %spotdup %wwvdup $last_hour %pings %rcmds
33                         %nodehops @baddx $baddxfn $pc12_dup_age
34                         %anndup $allowzero $pc12_dup_lth $decode_dk0wcy);
35
36 $me = undef;                                    # the channel id for this cluster
37 $decode_dk0wcy = undef;                 # if set use this callsign to decode announces from the EU WWV data beacon
38 $pc11_max_age = 1*3600;                 # the maximum age for an incoming 'real-time' pc11
39 $pc23_max_age = 1*3600;                 # the maximum age for an incoming 'real-time' pc23
40 $pc11_dup_age = 24*3600;                # the maximum time to keep the spot dup list for
41 $pc23_dup_age = 24*3600;                # the maximum time to keep the wwv dup list for
42 $pc12_dup_age = 12*3600;                # the maximum time to keep the ann dup list for
43 $pc12_dup_lth = 72;                             # the length of ANN text to save for deduping 
44 %spotdup = ();                              # the pc11 and 26 dup hash 
45 %wwvdup = ();                               # the pc23 and 27 dup hash
46 %anndup = ();                               # the PC12 dup hash
47 $last_hour = time;                              # last time I did an hourly periodic update
48 %pings = ();                    # outstanding ping requests outbound
49 %rcmds = ();                    # outstanding rcmd requests outbound
50 %nodehops = ();                 # node specific hop control
51 @baddx = ();                    # list of illegal spotted callsigns
52
53 $baddxfn = "$main::data/baddx.pl";
54
55 sub init
56 {
57         my $user = DXUser->get($main::mycall);
58         $DXProt::myprot_version += $main::version*100;
59         $me = DXProt->new($main::mycall, 0, $user); 
60         $me->{here} = 1;
61         $me->{state} = "indifferent";
62         do "$main::data/hop_table.pl" if -e "$main::data/hop_table.pl";
63         confess $@ if $@;
64         #  $me->{sort} = 'M';    # M for me
65
66         # now prime the spot duplicates file with today's and yesterday's data
67     my @today = Julian::unixtoj(time);
68         my @spots = Spot::readfile(@today);
69         @today = Julian::sub(@today, 1);
70         push @spots, Spot::readfile(@today);
71         for (@spots) {
72                 my $dupkey = "$_->[0]$_->[1]$_->[2]$_->[3]$_->[4]";
73                 $spotdup{$dupkey} = $_->[2];
74         }
75
76         # now prime the wwv duplicates file with just this month's data
77         my @wwv = Geomag::readfile(time);
78         for (@wwv) {
79                 my $dupkey = "$_->[1].$_->[2]$_->[3]$_->[4]";
80                 $wwvdup{$dupkey} = $_->[1];
81         }
82
83         # load the baddx file
84         do "$baddxfn" if -e "$baddxfn";
85         print "$@\n" if $@;
86 }
87
88 #
89 # obtain a new connection this is derived from dxchannel
90 #
91
92 sub new 
93 {
94         my $self = DXChannel::alloc(@_);
95         $self->{'sort'} = 'A';          # in absence of how to find out what sort of an object I am
96         return $self;
97 }
98
99 # this is how a pc connection starts (for an incoming connection)
100 # issue a PC38 followed by a PC18, then wait for a PC20 (remembering
101 # all the crap that comes between).
102 sub start
103 {
104         my ($self, $line, $sort) = @_;
105         my $call = $self->{call};
106         my $user = $self->{user};
107         
108         # remember type of connection
109         $self->{consort} = $line;
110         $self->{outbound} = $sort eq 'O';
111         $self->{priv} = $user->priv;
112         $self->{lang} = $user->lang;
113         $self->{isolate} = $user->{isolate};
114         $self->{consort} = $line;       # save the connection type
115         $self->{here} = 1;
116
117         # get the INPUT filters (these only pertain to Clusters)
118         $self->{inspotfilter} = Filter::read_in('spots', $call, 1);
119         $self->{inwwvfilter} = Filter::read_in('wwv', $call, 1);
120         $self->{inannfilter} = Filter::read_in('ann', $call, 1);
121         
122         # set unbuffered and no echo
123         $self->send_now('B',"0");
124         $self->send_now('E',"0");
125         
126         # send initialisation string
127         if (!$self->{outbound}) {
128                 $self->send(pc38()) if DXNode->get_all();
129                 $self->send(pc18());
130         }
131         $self->state('init');
132         $self->pc50_t(time);
133
134         Log('DXProt', "$call connected");
135 }
136
137 #
138 # This is the normal pcxx despatcher
139 #
140 sub normal
141 {
142         my ($self, $line) = @_;
143         my @field = split /\^/, $line;
144         pop @field if $field[-1] eq '~';
145         
146 #       print join(',', @field), "\n";
147                                                 
148         # ignore any lines that don't start with PC
149         return if !$field[0] =~ /^PC/;
150         
151         # process PC frames
152         my ($pcno) = $field[0] =~ /^PC(\d\d)/; # just get the number
153         return unless $pcno;
154         return if $pcno < 10 || $pcno > 51;
155
156         # dump bad protocol messages unless it is a PC29
157         if ($line =~ /\%[0-9A-F][0-9A-F]/o && $pcno != 29) {
158                 dbg('chan', "CORRUPT protocol message - dumped");
159                 return;
160         }
161
162         # local processing 1
163         my $pcr;
164         eval {
165                 $pcr = Local::pcprot($self, $pcno, @field);
166         };
167 #       dbg('local', "Local::pcprot error $@") if $@;
168         return if $pcr;
169         
170  SWITCH: {
171                 if ($pcno == 10) {              # incoming talk
172                         
173                         # is it for me or one of mine?
174                         my $call = ($field[5] gt ' ') ? $field[5] : $field[2];
175                         if ($call eq $main::mycall || grep $_ eq $call, get_all_user_calls()) {
176                                 
177                                 # yes, it is
178                                 my $text = unpad($field[3]);
179                                 Log('talk', $call, $field[1], $field[6], $text);
180                                 $call = $main::myalias if $call eq $main::mycall;
181                                 my $ref = DXChannel->get($call);
182                                 $ref->send("$call de $field[1]: $text") if $ref && $ref->{talk};
183                         } else {
184                                 route($field[2], $line); # relay it on its way
185                         }
186                         return;
187                 }
188                 
189                 if ($pcno == 11 || $pcno == 26) { # dx spot
190
191                         # route 'foreign' pc26s 
192                         if ($pcno == 26) {
193                                 if ($field[7] ne $main::mycall) {
194                                         route($field[7], $line);
195                                         return;
196                                 }
197                         }
198                         
199                         # if this is a 'nodx' node then ignore it
200                         last SWITCH if grep $field[7] =~ /^$_/,  @DXProt::nodx_node;
201                         
202                         # convert the date to a unix date
203                         my $d = cltounix($field[3], $field[4]);
204                         # bang out (and don't pass on) if date is invalid or the spot is too old (or too young)
205                         if (!$d || ($pcno == 11 && ($d < $main::systime - $pc11_max_age || $d > $main::systime + 900))) {
206                                 dbg('chan', "Spot ignored, invalid date or out of range ($field[3] $field[4])\n");
207                                 return;
208                         }
209
210                         # strip off the leading & trailing spaces from the comment
211                         my $text = unpad($field[5]);
212                         
213                         # store it away
214                         my $spotter = $field[6];
215                         $spotter =~ s/-[\@\d]+$//o;     # strip off the ssid from the spotter
216                         
217                         # do some de-duping
218                         my $freq = $field[1] - 0;
219                         my $dupkey = "$freq$field[2]$d$text$spotter";
220                         if ($spotdup{$dupkey}) {
221                                 dbg('chan', "Duplicate Spot ignored\n");
222                                 return;
223                         }
224                         
225                         $spotdup{$dupkey} = $d;
226
227                         # is it 'baddx'
228                         if (grep $field[2] eq $_, @baddx) {
229                                 dbg('chan', "Bad DX spot, ignored");
230                                 return;
231                         }
232
233                         # are any of the crucial fields invalid?
234             if ($field[2] =~ /[a-z]/ || $field[6] =~ /[a-z]/ || $field[7] =~ /[a-z]/) {
235                                 dbg('chan', "Spot contains lower case callsigns, rejected");
236                                 return;
237                         }
238                         
239                         my @spot = Spot::add($freq, $field[2], $d, $text, $spotter, $field[7]);
240
241             #
242                         # @spot at this point contains:-
243             # freq, spotted call, time, text, spotter, spotted cc, spotters cc, orig node
244                         # then  spotted itu, spotted cq, spotters itu, spotters cq
245                         # you should be able to route on any of these
246             #
247                         
248                         # local processing 
249                         my $r;
250                         eval {
251                                 $r = Local::spot($self, @spot);
252                         };
253 #                       dbg('local', "Local::spot1 error $@") if $@;
254                         return if $r;
255
256                         # DON'T be silly and send on PC26s!
257                         return if $pcno == 26;
258
259                         # send out the filtered spots
260                         send_dx_spot($self, $line, @spot) if @spot;
261                         return;
262                 }
263                 
264                 if ($pcno == 12) {              # announces
265                         # announce duplicate checking
266                         my $text = substr(uc unpad($field[3]), 0, $pc12_dup_lth);
267                         my $dupkey = $field[1].$field[2].$text.$field[4].$field[6];
268                         if ($anndup{$dupkey}) {
269                                 dbg('chan', "Duplicate Announce ignored\n");
270                                 return;
271                         }
272                         $anndup{$dupkey} = $main::systime;
273                         
274                         if ($field[2] eq '*' || $field[2] eq $main::mycall) {
275                                 
276                                 # global ann filtering on INPUT
277                                 if ($self->{inannfilter}) {
278                                         my ($filter, $hops) = Filter::it($self->{inannfilter}, @field[1..6], $self->{call} );
279                                         unless ($filter) {
280                                                 dbg('chan', "Rejected by filter");
281                                                 return;
282                                         }
283                                 }
284
285                                 # send it
286                                 $self->send_announce($line, @field[1..6]);
287                                 
288                                 if ($decode_dk0wcy && $field[1] eq $decode_dk0wcy) {
289                                         my ($hour, $k, $next, $a, $r, $sfi, $alarm) = $field[3] =~ /^Aurora Beacon\s+(\d+)UTC,\s+Kiel\s+K=(\d+),.*ed\s+K=(\d+),\s+A=(\d+),\s+R=(\d+),\s+SFI=(\d+),.*larm:\s+(\w+)/;
290                                         $alarm = ($alarm =~ /^Y/i) ? ', Aurora in DE' : ''; 
291                                         my $wwv = Geomag::update($main::systime, $hour, $sfi, $a, $k, "R=$r, Next K=$next$alarm", $decode_dk0wcy, $field[5], $r);
292                                 }
293                                 
294                         } else {
295                                 route($field[2], $line);
296                         }
297                         
298                         return;
299                 }
300                 
301                 if ($pcno == 13) {
302                         last SWITCH;
303                 }
304                 if ($pcno == 14) {
305                         last SWITCH;
306                 }
307                 if ($pcno == 15) {
308                         last SWITCH;
309                 }
310                 
311                 if ($pcno == 16) {              # add a user
312                         my $node = DXCluster->get_exact($field[1]); 
313                         return unless $node; # ignore if havn't seen a PC19 for this one yet
314                         return unless $node->isa('DXNode');
315                         if ($node->dxchan != $self) {
316                                 dbg('chan', "LOOP: $field[1] came in on wrong channel");
317                                 return;
318                         }
319                         my $dxchan;
320                         if (($dxchan = DXChannel->get($field[1])) && $dxchan != $self) {
321                                 dbg('chan', "LOOP: $field[1] connected locally");
322                                 return;
323                         }
324                         my $i;
325                         
326                         
327                         for ($i = 2; $i < $#field; $i++) {
328                                 my ($call, $confmode, $here) = $field[$i] =~ /^(\S+) (\S) (\d)/o;
329                                 next if !$call || length $call < 3 || length $call > 8;
330                                 next if !$confmode;
331                                 $call = uc $call;
332                                 next if DXCluster->get_exact($call); # we already have this (loop?)
333                                 
334                                 $confmode = $confmode eq '*';
335                                 DXNodeuser->new($self, $node, $call, $confmode, $here);
336                                 
337                                 # add this station to the user database, if required
338                                 $call =~ s/-\d+$//o;        # remove ssid for users
339                                 my $user = DXUser->get_current($call);
340                                 $user = DXUser->new($call) if !$user;
341                                 $user->homenode($node->call) if !$user->homenode;
342                                 $user->node($node->call);
343                                 $user->lastin($main::systime) unless DXChannel->get($call);
344                                 $user->put;
345                         }
346                         
347                         # queue up any messages (look for privates only)
348                         DXMsg::queue_msg(1) if $self->state eq 'normal';     
349                         last SWITCH;
350                 }
351                 
352                 if ($pcno == 17) {              # remove a user
353                         my $node = DXCluster->get_exact($field[2]);
354                         return unless $node;
355                         return unless $node->isa('DXNode');
356                         if ($node->dxchan != $self) {
357                                 dbg('chan', "LOOP: $field[2] came in on wrong channel");
358                                 return;
359                         }
360                         my $dxchan;
361                         if (($dxchan = DXChannel->get($field[2])) && $dxchan != $self) {
362                                 dbg('chan', "LOOP: $field[2] connected locally");
363                                 return;
364                         }
365                         my $ref = DXCluster->get_exact($field[1]);
366                         $ref->del() if $ref;
367                         last SWITCH;
368                 }
369                 
370                 if ($pcno == 18) {              # link request
371                         $self->state('init');   
372
373                         # first clear out any nodes on this dxchannel
374                         my @gonenodes = map { $_->dxchan == $self ? $_ : () } DXNode::get_all();
375                         foreach my $node (@gonenodes) {
376                                 next if $node->dxchan == $DXProt::me;
377                                 broadcast_ak1a(pc21($node->call, 'Gone, re-init') , $self) unless $self->{isolate}; 
378                                 $node->del();
379                         }
380                         $self->send_local_config();
381                         $self->send(pc20());
382                         return;             # we don't pass these on
383                 }
384                 
385                 if ($pcno == 19) {              # incoming cluster list
386                         my $i;
387                         my $newline = "PC19^";
388                         for ($i = 1; $i < $#field-1; $i += 4) {
389                                 my $here = $field[$i];
390                                 my $call = uc $field[$i+1];
391                                 my $confmode = $field[$i+2];
392                                 my $ver = $field[$i+3];
393
394                                 $ver = 5400 if !$ver && $allowzero;
395                                 
396                                 # now check the call over
397                                 my $node = DXCluster->get_exact($call);
398                                 if ($node) {
399                                         my $dxchan;
400                                         if (($dxchan = DXChannel->get($call)) && $dxchan != $self) {
401                                                 dbg('chan', "LOOP: $call connected locally");
402                                         }
403                                     if ($node->dxchan != $self) {
404                                                 dbg('chan', "LOOP: $call come in on wrong channel");
405                                                 next;
406                                         }
407                                         dbg('chan', "already have $call");
408                                         next;
409                                 }
410                                 
411                                 # check for sane parameters
412                                 next if $ver < 5000; # only works with version 5 software
413                                 next if length $call < 3; # min 3 letter callsigns
414
415                                 # add it to the nodes table and outgoing line
416                                 $newline .= "$here^$call^$confmode^$ver^";
417                                 DXNode->new($self, $call, $confmode, $here, $ver);
418                                 
419                                 # unbusy and stop and outgoing mail (ie if somehow we receive another PC19 without a disconnect)
420                                 my $mref = DXMsg::get_busy($call);
421                                 $mref->stop_msg($call) if $mref;
422                                 
423                                 # add this station to the user database, if required (don't remove SSID from nodes)
424                                 my $user = DXUser->get_current($call);
425                                 if (!$user) {
426                                         $user = DXUser->new($call);
427                                         $user->sort('A');
428                                         $user->priv(1);                   # I have relented and defaulted nodes
429                                         $self->{priv} = 1;                # to user RCMDs allowed
430                                         $user->homenode($call);
431                                         $user->node($call);
432                                 }
433                                 $user->lastin($main::systime) unless DXChannel->get($call);
434                                 $user->put;
435                         }
436                         
437                         return if $newline eq "PC19^";
438
439                         # add hop count 
440                         $newline .=  get_hops(19) . "^";
441                         $line = $newline;
442                         last SWITCH;
443                 }
444                 
445                 if ($pcno == 20) {              # send local configuration
446                         $self->send_local_config();
447                         $self->send(pc22());
448                         $self->state('normal');
449                         return;
450                 }
451                 
452                 if ($pcno == 21) {              # delete a cluster from the list
453                         my $call = uc $field[1];
454                         if ($call ne $main::mycall) { # don't allow malicious buggers to disconnect me!
455                                 my $node = DXCluster->get_exact($call);
456                                 if ($node) {
457                                         if ($node->dxchan != $self) {
458                                                 dbg('chan', "LOOP: $call come in on wrong channel");
459                                                 return;
460                                         }
461                                         my $dxchan;
462                                         if (($dxchan = DXChannel->get($call)) && $dxchan != $self) {
463                                                 dbg('chan', "LOOP: $call connected locally");
464                                                 return;
465                                         }
466                                         $node->del();
467                                 } else {
468                                         dbg('chan', "$call not in table, dropped");
469                                         return;
470                                 }
471                         }
472                         last SWITCH;
473                 }
474                 
475                 if ($pcno == 22) {
476                         $self->state('normal');
477                         return;
478                 }
479                                 
480                 if ($pcno == 23 || $pcno == 27) { # WWV info
481                         
482                         # route 'foreign' pc27s 
483                         if ($pcno == 27) {
484                                 if ($field[8] ne $main::mycall) {
485                                         route($field[8], $line);
486                                         return;
487                                 }
488                         }
489
490                         # do some de-duping
491                         my $d = cltounix($field[1], sprintf("%02d18Z", $field[2]));
492                         my $sfi = unpad($field[3]);
493                         my $k = unpad($field[4]);
494                         my $i = unpad($field[5]);
495                         my ($r) = $field[6] =~ /R=(\d+)/;
496                         $r = 0 unless $r;
497                         my $dupkey = "$d.$sfi$k$i";
498                         if ($wwvdup{$dupkey}) {
499                                 dbg('chan', "Dup WWV Spot ignored\n");
500                                 return;
501                         }
502                         if (($pcno == 23 && $d < $main::systime - $pc23_max_age) || $d > $main::systime + 900 || $field[2] < 0 || $field[2] > 23) {
503                                 dbg('chan', "WWV Date ($field[1] $field[2]) out of range");
504                                 return;
505                         }
506                         $wwvdup{$dupkey} = $d;
507                         $field[6] =~ s/-\d+$//o;            # remove spotter's ssid
508                 
509                         my $wwv = Geomag::update($d, $field[2], $sfi, $k, $i, @field[6..8], $r);
510
511                         my $rep;
512                         eval {
513                                 $rep = Local::wwv($self, $field[1], $field[2], $sfi, $k, $i, @field[6..8], $r);
514                         };
515 #                       dbg('local', "Local::wwv2 error $@") if $@;
516                         return if $rep;
517
518                         # DON'T be silly and send on PC27s!
519                         return if $pcno == 27;
520
521                         # broadcast to the eager world
522                         send_wwv_spot($self, $line, $d, $field[2], $sfi, $k, $i, @field[6..8]);
523                         return;
524                 }
525                 
526                 if ($pcno == 24) {              # set here status
527                         my $call = uc $field[1];
528                         my $ref = DXCluster->get_exact($call);
529                         $ref->here($field[2]) if $ref;
530                         last SWITCH;
531                 }
532                 
533                 if ($pcno == 25) {      # merge request
534                         if ($field[1] ne $main::mycall) {
535                                 route($field[1], $line);
536                                 return;
537                         }
538                         if ($field[2] eq $main::mycall) {
539                                 dbg('chan', "Trying to merge to myself, ignored");
540                                 return;
541                         }
542
543                         Log('DXProt', "Merge request for $field[3] spots and $field[4] WWV from $field[1]");
544                         
545                         # spots
546                         if ($field[3] > 0) {
547                                 my @in = reverse Spot::search(1, undef, undef, 0, $field[3]);
548                                 my $in;
549                                 foreach $in (@in) {
550                                         $self->send(pc26(@{$in}[0..4], $field[2]));
551                                 }
552                         }
553
554                         # wwv
555                         if ($field[4] > 0) {
556                                 my @in = reverse Geomag::search(0, $field[4], time, 1);
557                                 my $in;
558                                 foreach $in (@in) {
559                                         $self->send(pc27(@{$in}[0..5], $field[2]));
560                                 }
561                         }
562                         return;
563                 }
564
565                 if (($pcno >= 28 && $pcno <= 33) || $pcno == 40 || $pcno == 42 || $pcno == 49) { # mail/file handling
566                         if ($pcno == 49 || $field[1] eq $main::mycall) {
567                                 DXMsg::process($self, $line);
568                         } else {
569                                 route($field[1], $line);
570                         }
571                         return;
572                 }
573                 
574                 if ($pcno == 34 || $pcno == 36) { # remote commands (incoming)
575                         if ($field[1] eq $main::mycall) {
576                                 my $ref = DXUser->get_current($field[2]);
577                                 my $cref = DXCluster->get($field[2]);
578                                 Log('rcmd', 'in', $ref->{priv}, $field[2], $field[3]);
579                                 unless ($field[3] =~ /rcmd/i || !$cref || !$ref || $cref->mynode->call ne $ref->homenode) {    # not allowed to relay RCMDS!
580                                         if ($ref->{priv}) {     # you have to have SOME privilege, the commands have further filtering
581                                                 $self->{remotecmd} = 1; # for the benefit of any command that needs to know
582                                                 my $oldpriv = $self->{priv};
583                                                 $self->{priv} = $ref->{priv};     # assume the user's privilege level
584                                                 my @in = (DXCommandmode::run_cmd($self, $field[3]));
585                                                 $self->{priv} = $oldpriv;
586                                                 for (@in) {
587                                                         s/\s*$//og;
588                                                         $self->send(pc35($main::mycall, $field[2], "$main::mycall:$_"));
589                                                         Log('rcmd', 'out', $field[2], $_);
590                                                 }
591                                                 delete $self->{remotecmd};
592                                         } else {
593                                                 $self->send(pc35($main::mycall, $field[2], "$main::mycall:sorry...!"));
594                                         }
595                                 } else {
596                                         $self->send(pc35($main::mycall, $field[2], "$main::mycall:your attempt is logged, Tut tut tut...!"));
597                                 }
598                         } else {
599                                 route($field[1], $line);
600                         }
601                         return;
602                 }
603                 
604                 if ($pcno == 35) {              # remote command replies
605                         if ($field[1] eq $main::mycall) {
606                                 my $s = $rcmds{$field[2]};
607                                 if ($s) {
608                                         my $dxchan = DXChannel->get($s->{call});
609                                         $dxchan->send($field[3]) if $dxchan;
610                                         delete $rcmds{$field[2]} if !$dxchan;
611                                 }
612                         } else {
613                                 route($field[1], $line);
614                         }
615                         return;
616                 }
617                 
618                 # for pc 37 see 44 onwards
619
620                 if ($pcno == 38) {              # node connected list from neighbour
621                         return;
622                 }
623                 
624                 if ($pcno == 39) {              # incoming disconnect
625                         $self->disconnect();
626                         return;
627                 }
628                 
629                 if ($pcno == 41) {              # user info
630                         # add this station to the user database, if required
631                         my $user = DXUser->get_current($field[1]);
632                         if (!$user) {
633                                 # then try without an SSID
634                                 $field[1] =~ s/-\d+$//o;
635                                 $user = DXUser->get_current($field[1]);
636                         }
637                         $user = DXUser->new($field[1]) if !$user;
638                         
639                         if ($field[2] == 1) {
640                                 $user->name($field[3]);
641                         } elsif ($field[2] == 2) {
642                                 $user->qth($field[3]);
643                         } elsif ($field[2] == 3) {
644                                 my ($lat, $long) = DXBearing::stoll($field[3]);
645                                 $user->lat($lat);
646                                 $user->long($long);
647                         } elsif ($field[2] == 4) {
648                                 $user->homenode($field[3]);
649                         }
650                         $user->put;
651                         last SWITCH;
652                 }
653                 if ($pcno == 43) {
654                         last SWITCH;
655                 }
656                 if ($pcno == 37 || $pcno == 44 || $pcno == 45 || $pcno == 46 || $pcno == 47) {
657                         if ($field[1] eq $main::mycall) {
658                                 ;
659                         } else {
660                                 route($field[1], $line);
661                         }
662                         return;
663                 }
664                 
665                 if ($pcno == 50) {              # keep alive/user list
666                         my $node = DXCluster->get_exact($field[1]);
667                         if ($node) {
668                                 return unless $node->isa('DXNode');
669                                 return unless $node->dxchan == $self;
670                                 $node->update_users($field[2]);
671                         }
672                         last SWITCH;
673                 }
674                 
675                 if ($pcno == 51) {              # incoming ping requests/answers
676                         
677                         # is it for us?
678                         if ($field[1] eq $main::mycall) {
679                                 my $flag = $field[3];
680                                 if ($flag == 1) {
681                                         $self->send(pc51($field[2], $field[1], '0'));
682                                 } else {
683                                         # it's a reply, look in the ping list for this one
684                                         my $ref = $pings{$field[2]};
685                                         if ($ref) {
686                                                 my $r = shift @$ref;
687                                                 my $dxchan = DXChannel->get($r->{call});
688                                                 $dxchan->send($dxchan->msg('pingi', $field[2], atime($main::systime), $main::systime - $r->{t})) if $dxchan;
689                                         }
690                                 }
691                                 
692                         } else {
693                                 # route down an appropriate thingy
694                                 route($field[1], $line);
695                         }
696                         return;
697                 }
698         }
699          
700          # if get here then rebroadcast the thing with its Hop count decremented (if
701          # there is one). If it has a hop count and it decrements to zero then don't
702          # rebroadcast it.
703          #
704          # NOTE - don't arrive here UNLESS YOU WANT this lump of protocol to be
705          #        REBROADCAST!!!!
706          #
707          
708         if (!$self->{isolate}) {
709                 broadcast_ak1a($line, $self); # send it to everyone but me
710         }
711 }
712
713 #
714 # This is called from inside the main cluster processing loop and is used
715 # for despatching commands that are doing some long processing job
716 #
717 sub process
718 {
719         my $t = time;
720         my @dxchan = DXChannel->get_all();
721         my $dxchan;
722         
723         foreach $dxchan (@dxchan) {
724                 next unless $dxchan->is_ak1a();
725                 next if $dxchan == $me;
726                 
727                 # send a pc50 out on this channel
728                 if ($t >= $dxchan->pc50_t + $DXProt::pc50_interval) {
729                         $dxchan->send(pc50());
730                         $dxchan->pc50_t($t);
731                 }
732         }
733         
734         my $key;
735         my $val;
736         my $cutoff;
737         if ($main::systime - 3600 > $last_hour) {
738                 $cutoff  = $main::systime - $pc11_dup_age;
739                 while (($key, $val) = each %spotdup) {
740                         delete $spotdup{$key} if $val < $cutoff;
741                 }
742                 $cutoff = $main::systime - $pc23_dup_age;
743                 while (($key, $val) = each %wwvdup) {
744                         delete $wwvdup{$key} if $val < $cutoff;
745                 }
746                 $cutoff = $main::systime - $pc12_dup_age;
747                 while (($key, $val) = each %anndup) {
748                         delete $anndup{$key} if $val < $cutoff;
749                 }
750                 $last_hour = $main::systime;
751         }
752 }
753
754 #
755 # finish up a pc context
756 #
757 sub finish
758 {
759         my $self = shift;
760         my $call = $self->call;
761         my $ref = DXCluster->get_exact($call);
762         
763         # unbusy and stop and outgoing mail
764         my $mref = DXMsg::get_busy($call);
765         $mref->stop_msg($call) if $mref;
766         
767         # broadcast to all other nodes that all the nodes connected to via me are gone
768         my @gonenodes = map { $_->dxchan == $self ? $_ : () } DXNode::get_all();
769         my $node;
770         
771         foreach $node (@gonenodes) {
772                 next if $node->call eq $call;
773                 broadcast_ak1a(pc21($node->call, 'Gone') , $self) unless $self->{isolate}; 
774                 $node->del();
775         }
776
777         # remove outstanding pings
778         delete $pings{$call};
779         
780         # now broadcast to all other ak1a nodes that I have gone
781         broadcast_ak1a(pc21($call, 'Gone.'), $self) unless $self->{isolate};
782         
783         Log('DXProt', $call . " Disconnected");
784         $ref->del() if $ref;
785 }
786
787 #
788 # some active measures
789 #
790 sub send_dx_spot
791 {
792         my $self = shift;
793         my $line = shift;
794         my @dxchan = DXChannel->get_all();
795         my $dxchan;
796         
797         # send it if it isn't the except list and isn't isolated and still has a hop count
798         # taking into account filtering and so on
799         foreach $dxchan (@dxchan) {
800                 my $routeit;
801                 my ($filter, $hops);
802
803                 if ($dxchan->{spotfilter}) {
804                     ($filter, $hops) = Filter::it($dxchan->{spotfilter}, @_, $self->{call} );
805                         next unless $filter;
806                 }
807                 
808                 if ($dxchan->is_ak1a) {
809                         next if $dxchan == $self;
810                         if ($hops) {
811                                 $routeit = $line;
812                                 $routeit =~ s/\^H\d+\^\~$/\^H$hops\^\~/;
813                         } else {
814                                 $routeit = adjust_hops($dxchan, $line);  # adjust its hop count by node name
815                                 next unless $routeit;
816                         }
817                         if ($filter) {
818                                 $dxchan->send($routeit) if $routeit;
819                         } else {
820                                 $dxchan->send($routeit) unless $dxchan->{isolate} || $self->{isolate};
821                         }
822                 } elsif ($dxchan->is_user && $dxchan->{dx}) {
823                         my $buf = Spot::formatb($_[0], $_[1], $_[2], $_[3], $_[4]);
824                         $buf .= "\a\a" if $dxchan->{beep};
825                         if ($dxchan->{state} eq 'prompt' || $dxchan->{state} eq 'convers') {
826                                 $dxchan->send($buf);
827                         } else {
828                                 $dxchan->delay($buf);
829                         }
830                 }                                       
831         }
832 }
833
834 sub send_wwv_spot
835 {
836         my $self = shift;
837         my $line = shift;
838         my @dxchan = DXChannel->get_all();
839         my $dxchan;
840         
841         # send it if it isn't the except list and isn't isolated and still has a hop count
842         # taking into account filtering and so on
843         foreach $dxchan (@dxchan) {
844                 my $routeit;
845                 my ($filter, $hops);
846
847                 if ($dxchan->{spotfilter}) {
848                          ($filter, $hops) = Filter::it($dxchan->{wwvfilter}, @_, $self->{call} );
849                          next unless $filter;
850                 }
851                 if ($dxchan->is_ak1a) {
852                         next if $dxchan == $self;
853                         if ($hops) {
854                                 $routeit = $line;
855                                 $routeit =~ s/\^H\d+\^\~$/\^H$hops\^\~/;
856                         } else {
857                                 $routeit = adjust_hops($dxchan, $line);  # adjust its hop count by node name
858                                 next unless $routeit;
859                         }
860                         if ($filter) {
861                                 $dxchan->send($routeit) if $routeit;
862                         } else {
863                                 $dxchan->send($routeit) unless $dxchan->{isolate} || $self->{isolate};
864                                 
865                         }
866                 } elsif ($dxchan->is_user && $dxchan->{wwv}) {
867                         my $buf = "WWV de $_[6] <$_[1]>:   SFI=$_[2], A=$_[3], K=$_[4], $_[5]";
868                         $buf .= "\a\a" if $dxchan->{beep};
869                         if ($dxchan->{state} eq 'prompt' || $dxchan->{state} eq 'convers') {
870                                 $dxchan->send($buf);
871                         } else {
872                                 $dxchan->delay($buf);
873                         }
874                 }                                       
875         }
876 }
877
878 # send an announce
879 sub send_announce
880 {
881         my $self = shift;
882         my $line = shift;
883         my @dxchan = DXChannel->get_all();
884         my $dxchan;
885         my $text = unpad($_[2]);
886         my $target;
887         my $to = 'To ';
888                                 
889         if ($_[3] eq '*') {     # sysops
890                 $target = "SYSOP";
891         } elsif ($_[3] gt ' ') { # speciality list handling
892                 my ($name) = split /\./, $_[3]; 
893                 $target = "$name"; # put the rest in later (if bothered) 
894         } 
895         
896         if ($_[5] eq '1') {
897                 $target = "WX"; 
898                 $to = '';
899         }
900         $target = "All" if !$target;
901         
902         Log('ann', $target, $_[0], $text);
903
904         # send it if it isn't the except list and isn't isolated and still has a hop count
905         # taking into account filtering and so on
906         foreach $dxchan (@dxchan) {
907                 my $routeit;
908                 my ($filter, $hops);
909
910                 if ($dxchan->{annfilter}) {
911                         ($filter, $hops) = Filter::it($dxchan->{annfilter}, @_, $self->{call} );
912                         next unless $filter;
913                 } 
914                 if ($dxchan->is_ak1a && $field[1] ne $main::mycall) {  # i.e not specifically routed to me
915                         next if $dxchan == $self;
916                         if ($hops) {
917                                 $routeit = $line;
918                                 $routeit =~ s/\^H\d+\^\~$/\^H$hops\^\~/;
919                         } else {
920                                 $routeit = adjust_hops($dxchan, $line);  # adjust its hop count by node name
921                                 next unless $routeit;
922                         }
923                         if ($filter) {
924                                 $dxchan->send($routeit) if $routeit;
925                         } else {
926                                 $dxchan->send($routeit) unless $dxchan->{isolate} || $self->{isolate};
927                                 
928                         }
929                 } elsif ($dxchan->is_user && $dxchan->{ann}) {
930                         next if $target eq 'SYSOP' && $dxchan->{priv} < 5;
931                         my $buf = "$to$target de $_[0]: $text";
932                         $buf .= "\a\a" if $dxchan->{beep};
933                         if ($dxchan->{state} eq 'prompt' || $dxchan->{state} eq 'convers') {
934                                 $dxchan->send($buf);
935                         } else {
936                                 $dxchan->delay($buf);
937                         }
938                 }                                       
939         }
940 }
941
942 sub send_local_config
943 {
944         my $self = shift;
945         my $n;
946         my @nodes;
947         my @localnodes;
948         my @remotenodes;
949                 
950         # send our nodes
951         if ($self->{isolate}) {
952                 @localnodes = (DXCluster->get_exact($main::mycall));
953         } else {
954                 # create a list of all the nodes that are not connected to this connection
955                 # and are not themselves isolated, this to make sure that isolated nodes
956         # don't appear outside of this node
957                 @nodes = DXNode::get_all();
958                 @nodes = grep { $_->{call} ne $main::mycall } @nodes;
959                 @nodes = grep { $_->dxchan != $self } @nodes if @nodes;
960                 @nodes = grep { !$_->dxchan->{isolate} } @nodes if @nodes;
961                 @localnodes = grep { $_->dxchan->{call} eq $_->{call} } @nodes if @nodes;
962                 unshift @localnodes, DXCluster->get_exact($main::mycall);
963                 @remotenodes = grep { $_->dxchan->{call} ne $_->{call} } @nodes if @nodes;
964         }
965
966         my @s = $me->pc19(@localnodes, @remotenodes);
967         for (@s) {
968                 my $routeit = adjust_hops($self, $_);
969                 $self->send($routeit) if $routeit;
970         }
971         
972         # get all the users connected on the above nodes and send them out
973         foreach $n (@localnodes, @remotenodes) {
974                 my @users = values %{$n->list};
975                 my @s = pc16($n, @users);
976                 for (@s) {
977                         my $routeit = adjust_hops($self, $_);
978                         $self->send($routeit) if $routeit;
979                 }
980         }
981 }
982
983 #
984 # route a message down an appropriate interface for a callsign
985 #
986 # is called route(to, pcline);
987 #
988 sub route
989 {
990         my ($call, $line) = @_;
991         my $cl = DXCluster->get_exact($call);
992         if ($cl) {
993                 my $hops;
994                 my $dxchan = $cl->{dxchan};
995                 if ($dxchan) {
996                         my $routeit = adjust_hops($dxchan, $line);   # adjust its hop count by node name
997                         if ($routeit) {
998                                 $dxchan->send($routeit) if $dxchan;
999                         }
1000                 }
1001         }
1002 }
1003
1004 # broadcast a message to all clusters taking into account isolation
1005 # [except those mentioned after buffer]
1006 sub broadcast_ak1a
1007 {
1008         my $s = shift;                          # the line to be rebroadcast
1009         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
1010         my @dxchan = get_all_ak1a();
1011         my $dxchan;
1012         
1013         # send it if it isn't the except list and isn't isolated and still has a hop count
1014         foreach $dxchan (@dxchan) {
1015                 next if grep $dxchan == $_, @except;
1016                 my $routeit = adjust_hops($dxchan, $s);      # adjust its hop count by node name
1017                 $dxchan->send($routeit) unless $dxchan->{isolate} || !$routeit;
1018         }
1019 }
1020
1021 # broadcast a message to all clusters ignoring isolation
1022 # [except those mentioned after buffer]
1023 sub broadcast_all_ak1a
1024 {
1025         my $s = shift;                          # the line to be rebroadcast
1026         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
1027         my @dxchan = get_all_ak1a();
1028         my $dxchan;
1029         
1030         # send it if it isn't the except list and isn't isolated and still has a hop count
1031         foreach $dxchan (@dxchan) {
1032                 next if grep $dxchan == $_, @except;
1033                 my $routeit = adjust_hops($dxchan, $s);      # adjust its hop count by node name
1034                 $dxchan->send($routeit);
1035         }
1036 }
1037
1038 # broadcast to all users
1039 # storing the spot or whatever until it is in a state to receive it
1040 sub broadcast_users
1041 {
1042         my $s = shift;                          # the line to be rebroadcast
1043         my $sort = shift;           # the type of transmission
1044         my $fref = shift;           # a reference to an object to filter on
1045         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
1046         my @dxchan = get_all_users();
1047         my $dxchan;
1048         my @out;
1049         
1050         foreach $dxchan (@dxchan) {
1051                 next if grep $dxchan == $_, @except;
1052                 push @out, $dxchan;
1053         }
1054         broadcast_list($s, $sort, $fref, @out);
1055 }
1056
1057 # broadcast to a list of users
1058 sub broadcast_list
1059 {
1060         my $s = shift;
1061         my $sort = shift;
1062         my $fref = shift;
1063         my $dxchan;
1064         
1065         foreach $dxchan (@_) {
1066                 my $filter = 1;
1067                 
1068                 if ($sort eq 'dx') {
1069                     next unless $dxchan->{dx};
1070                         ($filter) = Filter::it($dxchan->{spotfilter}, @{$fref}) if ref $fref;
1071                         next unless $filter;
1072                 }
1073                 next if $sort eq 'ann' && !$dxchan->{ann};
1074                 next if $sort eq 'wwv' && !$dxchan->{wwv};
1075                 next if $sort eq 'wx' && !$dxchan->{wx};
1076
1077                 $s =~ s/\a//og unless $dxchan->{beep};
1078
1079                 if ($dxchan->{state} eq 'prompt' || $dxchan->{state} eq 'convers') {
1080                         $dxchan->send($s);      
1081                 } else {
1082                         $dxchan->delay($s);
1083                 }
1084         }
1085 }
1086
1087 #
1088 # gimme all the ak1a nodes
1089 #
1090 sub get_all_ak1a
1091 {
1092         my @list = DXChannel->get_all();
1093         my $ref;
1094         my @out;
1095         foreach $ref (@list) {
1096                 push @out, $ref if $ref->is_ak1a;
1097         }
1098         return @out;
1099 }
1100
1101 # return a list of all users
1102 sub get_all_users
1103 {
1104         my @list = DXChannel->get_all();
1105         my $ref;
1106         my @out;
1107         foreach $ref (@list) {
1108                 push @out, $ref if $ref->is_user;
1109         }
1110         return @out;
1111 }
1112
1113 # return a list of all user callsigns
1114 sub get_all_user_calls
1115 {
1116         my @list = DXChannel->get_all();
1117         my $ref;
1118         my @out;
1119         foreach $ref (@list) {
1120                 push @out, $ref->call if $ref->is_user;
1121         }
1122         return @out;
1123 }
1124
1125 #
1126 # obtain the hops from the list for this callsign and pc no 
1127 #
1128
1129 sub get_hops
1130 {
1131         my $pcno = shift;
1132         my $hops = $DXProt::hopcount{$pcno};
1133         $hops = $DXProt::def_hopcount if !$hops;
1134         return "H$hops";       
1135 }
1136
1137
1138 # adjust the hop count on a per node basis using the user loadable 
1139 # hop table if available or else decrement an existing one
1140 #
1141
1142 sub adjust_hops
1143 {
1144         my $self = shift;
1145         my $s = shift;
1146         my $call = $self->{call};
1147         my $hops;
1148         
1149         if (($hops) = $s =~ /\^H(\d+)\^~?$/o) {
1150                 my ($pcno) = $s =~ /^PC(\d\d)/o;
1151                 confess "$call called adjust_hops with '$s'" unless $pcno;
1152                 my $ref = $nodehops{$call} if %nodehops;
1153                 if ($ref) {
1154                         my $newhops = $ref->{$pcno};
1155                         return "" if defined $newhops && $newhops == 0;
1156                         $newhops = $ref->{default} unless $newhops;
1157                         return "" if defined $newhops && $newhops == 0;
1158                         $newhops = $hops if !$newhops;
1159                         $s =~ s/\^H(\d+)(\^~?)$/\^H$newhops$2/ if $newhops;
1160                 } else {
1161                         # simply decrement it
1162                         $hops--;
1163                         return "" if !$hops;
1164                         $s =~ s/\^H(\d+)(\^~?)$/\^H$hops$2/ if $hops;
1165                 }
1166         }
1167         return $s;
1168 }
1169
1170
1171 # load hop tables
1172 #
1173 sub load_hops
1174 {
1175         my $self = shift;
1176         return $self->msg('lh1') unless -e "$main::data/hop_table.pl";
1177         do "$main::data/hop_table.pl";
1178         return $@ if $@;
1179         return 0;
1180 }
1181
1182 # remove leading and trailing spaces from an input string
1183 sub unpad
1184 {
1185         my $s = shift;
1186         $s =~ s/^\s+|\s+$//;
1187         return $s;
1188 }
1189
1190 # add a ping request to the ping queues
1191 sub addping
1192 {
1193         my ($from, $to) = @_;
1194         my $ref = $pings{$to};
1195         $ref = $pings{$to} = [] if !$ref;
1196         my $r = {};
1197         $r->{call} = $from;
1198         $r->{t} = $main::systime;
1199         route($to, pc51($to, $main::mycall, 1));
1200         push @$ref, $r;
1201 }
1202
1203 # add a rcmd request to the rcmd queues
1204 sub addrcmd
1205 {
1206         my ($from, $to, $cmd) = @_;
1207         my $r = {};
1208         $r->{call} = $from;
1209         $r->{t} = $main::systime;
1210         $r->{cmd} = $cmd;
1211         route($to, pc34($main::mycall, $to, $cmd));
1212         $rcmds{$to} = $r;
1213 }
1214 1;
1215 __END__