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