Fixed console to wrap.
[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 filters
118         $self->{spotfilter} = Filter::read_in('spots', $call);
119         $self->{wwvfilter} = Filter::read_in('wwv', $call);
120         $self->{annfilter} = Filter::read_in('ann', $call);
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                         # global ann filtering on INPUT
275                         my ($filter, $hops) = Filter::it($self->{annfilter}, @field[1..6], $self->{call} ) if $self->{annfilter};
276                         if ($self->{annfilter} && !$filter) {
277                                 dbg('chan', "Rejected by filter");
278                                 return;
279                         }
280                         
281                         if ($field[2] eq '*' || $field[2] eq $main::mycall) {
282                                 
283                                 # strip leading and trailing stuff
284                                 my $text = unpad($field[3]);
285                                 my $target;
286                                 my $to = 'To ';
287                                 my @list;
288                                 
289                                 if ($field[4] eq '*') { # sysops
290                                         $target = "SYSOP";
291                                         @list = map { $_->priv >= 5 ? $_ : () } get_all_users();
292                                 } elsif ($field[4] gt ' ') { # speciality list handling
293                                         my ($name) = split /\./, $field[4]; 
294                                         $target = "$name"; # put the rest in later (if bothered) 
295                                 } 
296                                 
297                                 if ($field[6] eq '1') {
298                                         $target = "WX"; 
299                                         $to = '';
300                                 }
301                                 $target = "All" if !$target;
302                                 
303                                 if (@list > 0) {
304                                         broadcast_list("$to$target de $field[1]: $text", 'ann', undef, @list);
305                                 } else {
306                                         broadcast_users("$target de $field[1]: $text", 'ann', undef);
307                                 }
308                                 Log('ann', $target, $field[1], $text);
309                                 
310                                 if ($decode_dk0wcy && $field[1] eq $decode_dk0wcy) {
311                                         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+)/;
312                                         $alarm = ($alarm =~ /^Y/i) ? ', Aurora in DE' : ''; 
313                                         my $wwv = Geomag::update($main::systime, $hour, $sfi, $a, $k, "R=$r, Next K=$next$alarm", $decode_dk0wcy, $field[5], $r);
314                                 }
315                                 
316                                 return if $field[2] eq $main::mycall; # it's routed to me
317                         } else {
318                                 route($field[2], $line);
319                                 return;                 # only on a routed one
320                         }
321                         
322                         last SWITCH;
323                 }
324                 
325                 if ($pcno == 13) {
326                         last SWITCH;
327                 }
328                 if ($pcno == 14) {
329                         last SWITCH;
330                 }
331                 if ($pcno == 15) {
332                         last SWITCH;
333                 }
334                 
335                 if ($pcno == 16) {              # add a user
336                         my $node = DXCluster->get_exact($field[1]); 
337                         return unless $node; # ignore if havn't seen a PC19 for this one yet
338                         return unless $node->isa('DXNode');
339                         if ($node->dxchan != $self) {
340                                 dbg('chan', "LOOP: $field[1] came in on wrong channel");
341                                 return;
342                         }
343                         my $dxchan;
344                         if (($dxchan = DXChannel->get($field[1])) && $dxchan != $self) {
345                                 dbg('chan', "LOOP: $field[1] connected locally");
346                                 return;
347                         }
348                         my $i;
349                         
350                         
351                         for ($i = 2; $i < $#field; $i++) {
352                                 my ($call, $confmode, $here) = $field[$i] =~ /^(\S+) (\S) (\d)/o;
353                                 next if !$call || length $call < 3 || length $call > 8;
354                                 next if !$confmode;
355                                 $call = uc $call;
356                                 next if DXCluster->get_exact($call); # we already have this (loop?)
357                                 
358                                 $confmode = $confmode eq '*';
359                                 DXNodeuser->new($self, $node, $call, $confmode, $here);
360                                 
361                                 # add this station to the user database, if required
362                                 $call =~ s/-\d+$//o;        # remove ssid for users
363                                 my $user = DXUser->get_current($call);
364                                 $user = DXUser->new($call) if !$user;
365                                 $user->homenode($node->call) if !$user->homenode;
366                                 $user->node($node->call);
367                                 $user->lastin($main::systime) unless DXChannel->get($call);
368                                 $user->put;
369                         }
370                         
371                         # queue up any messages (look for privates only)
372                         DXMsg::queue_msg(1) if $self->state eq 'normal';     
373                         last SWITCH;
374                 }
375                 
376                 if ($pcno == 17) {              # remove a user
377                         my $node = DXCluster->get_exact($field[2]);
378                         return unless $node;
379                         return unless $node->isa('DXNode');
380                         if ($node->dxchan != $self) {
381                                 dbg('chan', "LOOP: $field[2] came in on wrong channel");
382                                 return;
383                         }
384                         my $dxchan;
385                         if (($dxchan = DXChannel->get($field[2])) && $dxchan != $self) {
386                                 dbg('chan', "LOOP: $field[2] connected locally");
387                                 return;
388                         }
389                         my $ref = DXCluster->get_exact($field[1]);
390                         $ref->del() if $ref;
391                         last SWITCH;
392                 }
393                 
394                 if ($pcno == 18) {              # link request
395                         $self->state('init');   
396
397                         # first clear out any nodes on this dxchannel
398                         my @gonenodes = map { $_->dxchan == $self ? $_ : () } DXNode::get_all();
399                         foreach my $node (@gonenodes) {
400                                 next if $node->dxchan == $DXProt::me;
401                                 broadcast_ak1a(pc21($node->call, 'Gone, re-init') , $self) unless $self->{isolate}; 
402                                 $node->del();
403                         }
404                         $self->send_local_config();
405                         $self->send(pc20());
406                         return;             # we don't pass these on
407                 }
408                 
409                 if ($pcno == 19) {              # incoming cluster list
410                         my $i;
411                         my $newline = "PC19^";
412                         for ($i = 1; $i < $#field-1; $i += 4) {
413                                 my $here = $field[$i];
414                                 my $call = uc $field[$i+1];
415                                 my $confmode = $field[$i+2];
416                                 my $ver = $field[$i+3];
417
418                                 $ver = 5400 if !$ver && $allowzero;
419                                 
420                                 # now check the call over
421                                 my $node = DXCluster->get_exact($call);
422                                 if ($node) {
423                                         my $dxchan;
424                                         if (($dxchan = DXChannel->get($call)) && $dxchan != $self) {
425                                                 dbg('chan', "LOOP: $call connected locally");
426                                         }
427                                     if ($node->dxchan != $self) {
428                                                 dbg('chan', "LOOP: $call come in on wrong channel");
429                                                 next;
430                                         }
431                                         dbg('chan', "already have $call");
432                                         next;
433                                 }
434                                 
435                                 # check for sane parameters
436                                 next if $ver < 5000; # only works with version 5 software
437                                 next if length $call < 3; # min 3 letter callsigns
438
439                                 # add it to the nodes table and outgoing line
440                                 $newline .= "$here^$call^$confmode^$ver^";
441                                 DXNode->new($self, $call, $confmode, $here, $ver);
442                                 
443                                 # unbusy and stop and outgoing mail (ie if somehow we receive another PC19 without a disconnect)
444                                 my $mref = DXMsg::get_busy($call);
445                                 $mref->stop_msg($call) if $mref;
446                                 
447                                 # add this station to the user database, if required (don't remove SSID from nodes)
448                                 my $user = DXUser->get_current($call);
449                                 if (!$user) {
450                                         $user = DXUser->new($call);
451                                         $user->sort('A');
452                                         $user->priv(1);                   # I have relented and defaulted nodes
453                                         $self->{priv} = 1;                # to user RCMDs allowed
454                                         $user->homenode($call);
455                                         $user->node($call);
456                                 }
457                                 $user->lastin($main::systime) unless DXChannel->get($call);
458                                 $user->put;
459                         }
460                         
461                         return if $newline eq "PC19^";
462
463                         # add hop count 
464                         $newline .=  get_hops(19) . "^";
465                         $line = $newline;
466                         last SWITCH;
467                 }
468                 
469                 if ($pcno == 20) {              # send local configuration
470                         $self->send_local_config();
471                         $self->send(pc22());
472                         $self->state('normal');
473                         return;
474                 }
475                 
476                 if ($pcno == 21) {              # delete a cluster from the list
477                         my $call = uc $field[1];
478                         if ($call ne $main::mycall) { # don't allow malicious buggers to disconnect me!
479                                 my $node = DXCluster->get_exact($call);
480                                 if ($node) {
481                                         if ($node->dxchan != $self) {
482                                                 dbg('chan', "LOOP: $call come in on wrong channel");
483                                                 return;
484                                         }
485                                         my $dxchan;
486                                         if (($dxchan = DXChannel->get($call)) && $dxchan != $self) {
487                                                 dbg('chan', "LOOP: $call connected locally");
488                                                 return;
489                                         }
490                                         $node->del();
491                                 } else {
492                                         dbg('chan', "$call not in table, dropped");
493                                         return;
494                                 }
495                         }
496                         last SWITCH;
497                 }
498                 
499                 if ($pcno == 22) {
500                         $self->state('normal');
501                         return;
502                 }
503                                 
504                 if ($pcno == 23 || $pcno == 27) { # WWV info
505                         
506                         # route 'foreign' pc27s 
507                         if ($pcno == 27) {
508                                 if ($field[8] ne $main::mycall) {
509                                         route($field[8], $line);
510                                         return;
511                                 }
512                         }
513
514                         # do some de-duping
515                         my $d = cltounix($field[1], sprintf("%02d18Z", $field[2]));
516                         my $sfi = unpad($field[3]);
517                         my $k = unpad($field[4]);
518                         my $i = unpad($field[5]);
519                         my ($r) = $field[6] =~ /R=(\d+)/;
520                         $r = 0 unless $r;
521                         my $dupkey = "$d.$sfi$k$i";
522                         if ($wwvdup{$dupkey}) {
523                                 dbg('chan', "Dup WWV Spot ignored\n");
524                                 return;
525                         }
526                         if (($pcno == 23 && $d < $main::systime - $pc23_max_age) || $d > $main::systime + 900 || $field[2] < 0 || $field[2] > 23) {
527                                 dbg('chan', "WWV Date ($field[1] $field[2]) out of range");
528                                 return;
529                         }
530                         $wwvdup{$dupkey} = $d;
531                         $field[6] =~ s/-\d+$//o;            # remove spotter's ssid
532                 
533                         my $wwv = Geomag::update($d, $field[2], $sfi, $k, $i, @field[6..8], $r);
534
535                         my $rep;
536                         eval {
537                                 $rep = Local::wwv($self, $field[1], $field[2], $sfi, $k, $i, @field[6..8], $r);
538                         };
539 #                       dbg('local', "Local::wwv2 error $@") if $@;
540                         return if $rep;
541
542                         # DON'T be silly and send on PC27s!
543                         return if $pcno == 27;
544
545                         # broadcast to the eager world
546                         send_wwv_spot($self, $line, $d, $field[2], $sfi, $k, $i, @field[6..8]);
547                         return;
548                 }
549                 
550                 if ($pcno == 24) {              # set here status
551                         my $call = uc $field[1];
552                         my $ref = DXCluster->get_exact($call);
553                         $ref->here($field[2]) if $ref;
554                         last SWITCH;
555                 }
556                 
557                 if ($pcno == 25) {      # merge request
558                         if ($field[1] ne $main::mycall) {
559                                 route($field[1], $line);
560                                 return;
561                         }
562                         if ($field[2] eq $main::mycall) {
563                                 dbg('chan', "Trying to merge to myself, ignored");
564                                 return;
565                         }
566
567                         Log('DXProt', "Merge request for $field[3] spots and $field[4] WWV from $field[1]");
568                         
569                         # spots
570                         if ($field[3] > 0) {
571                                 my @in = reverse Spot::search(1, undef, undef, 0, $field[3]);
572                                 my $in;
573                                 foreach $in (@in) {
574                                         $self->send(pc26(@{$in}[0..4], $field[2]));
575                                 }
576                         }
577
578                         # wwv
579                         if ($field[4] > 0) {
580                                 my @in = reverse Geomag::search(0, $field[4], time, 1);
581                                 my $in;
582                                 foreach $in (@in) {
583                                         $self->send(pc27(@{$in}[0..5], $field[2]));
584                                 }
585                         }
586                         return;
587                 }
588
589                 if (($pcno >= 28 && $pcno <= 33) || $pcno == 40 || $pcno == 42 || $pcno == 49) { # mail/file handling
590                         if ($pcno == 49 || $field[1] eq $main::mycall) {
591                                 DXMsg::process($self, $line);
592                         } else {
593                                 route($field[1], $line);
594                         }
595                         return;
596                 }
597                 
598                 if ($pcno == 34 || $pcno == 36) { # remote commands (incoming)
599                         if ($field[1] eq $main::mycall) {
600                                 my $ref = DXUser->get_current($field[2]);
601                                 my $cref = DXCluster->get($field[2]);
602                                 Log('rcmd', 'in', $ref->{priv}, $field[2], $field[3]);
603                                 unless ($field[3] =~ /rcmd/i || !$cref || !$ref || $cref->mynode->call ne $ref->homenode) {    # not allowed to relay RCMDS!
604                                         if ($ref->{priv}) {     # you have to have SOME privilege, the commands have further filtering
605                                                 $self->{remotecmd} = 1; # for the benefit of any command that needs to know
606                                                 my $oldpriv = $self->{priv};
607                                                 $self->{priv} = $ref->{priv};     # assume the user's privilege level
608                                                 my @in = (DXCommandmode::run_cmd($self, $field[3]));
609                                                 $self->{priv} = $oldpriv;
610                                                 for (@in) {
611                                                         s/\s*$//og;
612                                                         $self->send(pc35($main::mycall, $field[2], "$main::mycall:$_"));
613                                                         Log('rcmd', 'out', $field[2], $_);
614                                                 }
615                                                 delete $self->{remotecmd};
616                                         } else {
617                                                 $self->send(pc35($main::mycall, $field[2], "$main::mycall:sorry...!"));
618                                         }
619                                 } else {
620                                         $self->send(pc35($main::mycall, $field[2], "$main::mycall:your attempt is logged, Tut tut tut...!"));
621                                 }
622                         } else {
623                                 route($field[1], $line);
624                         }
625                         return;
626                 }
627                 
628                 if ($pcno == 35) {              # remote command replies
629                         if ($field[1] eq $main::mycall) {
630                                 my $s = $rcmds{$field[2]};
631                                 if ($s) {
632                                         my $dxchan = DXChannel->get($s->{call});
633                                         $dxchan->send($field[3]) if $dxchan;
634                                         delete $rcmds{$field[2]} if !$dxchan;
635                                 }
636                         } else {
637                                 route($field[1], $line);
638                         }
639                         return;
640                 }
641                 
642                 # for pc 37 see 44 onwards
643
644                 if ($pcno == 38) {              # node connected list from neighbour
645                         return;
646                 }
647                 
648                 if ($pcno == 39) {              # incoming disconnect
649                         $self->disconnect();
650                         return;
651                 }
652                 
653                 if ($pcno == 41) {              # user info
654                         # add this station to the user database, if required
655                         my $user = DXUser->get_current($field[1]);
656                         if (!$user) {
657                                 # then try without an SSID
658                                 $field[1] =~ s/-\d+$//o;
659                                 $user = DXUser->get_current($field[1]);
660                         }
661                         $user = DXUser->new($field[1]) if !$user;
662                         
663                         if ($field[2] == 1) {
664                                 $user->name($field[3]);
665                         } elsif ($field[2] == 2) {
666                                 $user->qth($field[3]);
667                         } elsif ($field[2] == 3) {
668                                 my ($lat, $long) = DXBearing::stoll($field[3]);
669                                 $user->lat($lat);
670                                 $user->long($long);
671                         } elsif ($field[2] == 4) {
672                                 $user->homenode($field[3]);
673                         }
674                         $user->put;
675                         last SWITCH;
676                 }
677                 if ($pcno == 43) {
678                         last SWITCH;
679                 }
680                 if ($pcno == 37 || $pcno == 44 || $pcno == 45 || $pcno == 46 || $pcno == 47) {
681                         if ($field[1] eq $main::mycall) {
682                                 ;
683                         } else {
684                                 route($field[1], $line);
685                         }
686                         return;
687                 }
688                 
689                 if ($pcno == 50) {              # keep alive/user list
690                         my $node = DXCluster->get_exact($field[1]);
691                         if ($node) {
692                                 return unless $node->isa('DXNode');
693                                 return unless $node->dxchan == $self;
694                                 $node->update_users($field[2]);
695                         }
696                         last SWITCH;
697                 }
698                 
699                 if ($pcno == 51) {              # incoming ping requests/answers
700                         
701                         # is it for us?
702                         if ($field[1] eq $main::mycall) {
703                                 my $flag = $field[3];
704                                 if ($flag == 1) {
705                                         $self->send(pc51($field[2], $field[1], '0'));
706                                 } else {
707                                         # it's a reply, look in the ping list for this one
708                                         my $ref = $pings{$field[2]};
709                                         if ($ref) {
710                                                 my $r = shift @$ref;
711                                                 my $dxchan = DXChannel->get($r->{call});
712                                                 $dxchan->send($dxchan->msg('pingi', $field[2], atime($main::systime), $main::systime - $r->{t})) if $dxchan;
713                                         }
714                                 }
715                                 
716                         } else {
717                                 # route down an appropriate thingy
718                                 route($field[1], $line);
719                         }
720                         return;
721                 }
722         }
723          
724          # if get here then rebroadcast the thing with its Hop count decremented (if
725          # there is one). If it has a hop count and it decrements to zero then don't
726          # rebroadcast it.
727          #
728          # NOTE - don't arrive here UNLESS YOU WANT this lump of protocol to be
729          #        REBROADCAST!!!!
730          #
731          
732         if (!$self->{isolate}) {
733                 broadcast_ak1a($line, $self); # send it to everyone but me
734         }
735 }
736
737 #
738 # This is called from inside the main cluster processing loop and is used
739 # for despatching commands that are doing some long processing job
740 #
741 sub process
742 {
743         my $t = time;
744         my @dxchan = DXChannel->get_all();
745         my $dxchan;
746         
747         foreach $dxchan (@dxchan) {
748                 next unless $dxchan->is_ak1a();
749                 next if $dxchan == $me;
750                 
751                 # send a pc50 out on this channel
752                 if ($t >= $dxchan->pc50_t + $DXProt::pc50_interval) {
753                         $dxchan->send(pc50());
754                         $dxchan->pc50_t($t);
755                 }
756         }
757         
758         my $key;
759         my $val;
760         my $cutoff;
761         if ($main::systime - 3600 > $last_hour) {
762                 $cutoff  = $main::systime - $pc11_dup_age;
763                 while (($key, $val) = each %spotdup) {
764                         delete $spotdup{$key} if $val < $cutoff;
765                 }
766                 $cutoff = $main::systime - $pc23_dup_age;
767                 while (($key, $val) = each %wwvdup) {
768                         delete $wwvdup{$key} if $val < $cutoff;
769                 }
770                 $cutoff = $main::systime - $pc12_dup_age;
771                 while (($key, $val) = each %anndup) {
772                         delete $anndup{$key} if $val < $cutoff;
773                 }
774                 $last_hour = $main::systime;
775         }
776 }
777
778 #
779 # finish up a pc context
780 #
781 sub finish
782 {
783         my $self = shift;
784         my $call = $self->call;
785         my $ref = DXCluster->get_exact($call);
786         
787         # unbusy and stop and outgoing mail
788         my $mref = DXMsg::get_busy($call);
789         $mref->stop_msg($call) if $mref;
790         
791         # broadcast to all other nodes that all the nodes connected to via me are gone
792         my @gonenodes = map { $_->dxchan == $self ? $_ : () } DXNode::get_all();
793         my $node;
794         
795         foreach $node (@gonenodes) {
796                 next if $node->call eq $call;
797                 broadcast_ak1a(pc21($node->call, 'Gone') , $self) unless $self->{isolate}; 
798                 $node->del();
799         }
800
801         # remove outstanding pings
802         delete $pings{$call};
803         
804         # now broadcast to all other ak1a nodes that I have gone
805         broadcast_ak1a(pc21($call, 'Gone.'), $self) unless $self->{isolate};
806         
807         Log('DXProt', $call . " Disconnected");
808         $ref->del() if $ref;
809 }
810
811 #
812 # some active measures
813 #
814 sub send_dx_spot
815 {
816         my $self = shift;
817         my $line = shift;
818         my @dxchan = DXChannel->get_all();
819         my $dxchan;
820         
821         # send it if it isn't the except list and isn't isolated and still has a hop count
822         # taking into account filtering and so on
823         foreach $dxchan (@dxchan) {
824                 my $routeit;
825                 my ($filter, $hops);
826
827                 if ($dxchan->{spotfilter}) {
828                     ($filter, $hops) = Filter::it($dxchan->{spotfilter}, @_, $self->{call} );
829                         next unless $filter;
830                 }
831                 
832                 if ($dxchan->is_ak1a) {
833                         next if $dxchan == $self;
834                         if ($hops) {
835                                 $routeit = $line;
836                                 $routeit =~ s/\^H\d+\^\~$/\^H$hops\^\~/;
837                         } else {
838                                 $routeit = adjust_hops($dxchan, $line);  # adjust its hop count by node name
839                                 next unless $routeit;
840                         }
841                         if ($filter) {
842                                 $dxchan->send($routeit) if $routeit;
843                         } else {
844                                 $dxchan->send($routeit) unless $dxchan->{isolate} || $self->{isolate};
845                                 
846                         }
847                 } elsif ($dxchan->is_user && $dxchan->{dx}) {
848                         my $buf = Spot::formatb($_[0], $_[1], $_[2], $_[3], $_[4]);
849                         $buf .= "\a\a" if $dxchan->{beep};
850                         if ($dxchan->{state} eq 'prompt' || $dxchan->{state} eq 'convers') {
851                                 $dxchan->send($buf) if !$hops || ($hops && $filter);
852                         } else {
853                                 $dxchan->delay($buf) if !$hops || ($hops && $filter);
854                         }
855                 }                                       
856         }
857 }
858
859 sub send_wwv_spot
860 {
861         my $self = shift;
862         my $line = shift;
863         my @dxchan = DXChannel->get_all();
864         my $dxchan;
865         
866         # send it if it isn't the except list and isn't isolated and still has a hop count
867         # taking into account filtering and so on
868         foreach $dxchan (@dxchan) {
869                 my $routeit;
870                 my ($filter, $hops) = Filter::it($dxchan->{wwvfilter}, @_, $self->{call} ) if $dxchan->{wwvfilter};
871                 if ($dxchan->is_ak1a) {
872                         next if $dxchan == $self;
873                         if ($hops) {
874                                 $routeit = $line;
875                                 $routeit =~ s/\^H\d+\^\~$/\^H$hops\^\~/;
876                         } else {
877                                 $routeit = adjust_hops($dxchan, $line);  # adjust its hop count by node name
878                                 next unless $routeit;
879                         }
880                         if ($filter) {
881                                 $dxchan->send($routeit) if $routeit;
882                         } else {
883                                 $dxchan->send($routeit) unless $dxchan->{isolate} || $self->{isolate};
884                                 
885                         }
886                 } elsif ($dxchan->is_user && $dxchan->{wwv}) {
887                         my $buf = "WWV de $_[6] <$_[1]>:   SFI=$_[2], A=$_[3], K=$_[4], $_[5]";
888                         $buf .= "\a\a" if $dxchan->{beep};
889                         if ($dxchan->{state} eq 'prompt' || $dxchan->{state} eq 'convers') {
890                                 $dxchan->send($buf) if !$hops || ($hops && $filter);
891                         } else {
892                                 $dxchan->delay($buf) if !$hops || ($hops && $filter);
893                         }
894                 }                                       
895         }
896 }
897
898 sub send_local_config
899 {
900         my $self = shift;
901         my $n;
902         my @nodes;
903         my @localnodes;
904         my @remotenodes;
905                 
906         # send our nodes
907         if ($self->{isolate}) {
908                 @localnodes = (DXCluster->get_exact($main::mycall));
909         } else {
910                 # create a list of all the nodes that are not connected to this connection
911                 # and are not themselves isolated, this to make sure that isolated nodes
912         # don't appear outside of this node
913                 @nodes = DXNode::get_all();
914                 @nodes = grep { $_->{call} ne $main::mycall } @nodes;
915                 @nodes = grep { $_->dxchan != $self } @nodes if @nodes;
916                 @nodes = grep { !$_->dxchan->{isolate} } @nodes if @nodes;
917                 @localnodes = grep { $_->dxchan->{call} eq $_->{call} } @nodes if @nodes;
918                 unshift @localnodes, DXCluster->get_exact($main::mycall);
919                 @remotenodes = grep { $_->dxchan->{call} ne $_->{call} } @nodes if @nodes;
920         }
921
922         my @s = $me->pc19(@localnodes, @remotenodes);
923         for (@s) {
924                 my $routeit = adjust_hops($self, $_);
925                 $self->send($routeit) if $routeit;
926         }
927         
928         # get all the users connected on the above nodes and send them out
929         foreach $n (@localnodes, @remotenodes) {
930                 my @users = values %{$n->list};
931                 my @s = pc16($n, @users);
932                 for (@s) {
933                         my $routeit = adjust_hops($self, $_);
934                         $self->send($routeit) if $routeit;
935                 }
936         }
937 }
938
939 #
940 # route a message down an appropriate interface for a callsign
941 #
942 # is called route(to, pcline);
943 #
944 sub route
945 {
946         my ($call, $line) = @_;
947         my $cl = DXCluster->get_exact($call);
948         if ($cl) {
949                 my $hops;
950                 my $dxchan = $cl->{dxchan};
951                 if ($dxchan) {
952                         my $routeit = adjust_hops($dxchan, $line);   # adjust its hop count by node name
953                         if ($routeit) {
954                                 $dxchan->send($routeit) if $dxchan;
955                         }
956                 }
957         }
958 }
959
960 # broadcast a message to all clusters taking into account isolation
961 # [except those mentioned after buffer]
962 sub broadcast_ak1a
963 {
964         my $s = shift;                          # the line to be rebroadcast
965         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
966         my @dxchan = get_all_ak1a();
967         my $dxchan;
968         
969         # send it if it isn't the except list and isn't isolated and still has a hop count
970         foreach $dxchan (@dxchan) {
971                 next if grep $dxchan == $_, @except;
972                 my $routeit = adjust_hops($dxchan, $s);      # adjust its hop count by node name
973                 $dxchan->send($routeit) unless $dxchan->{isolate} || !$routeit;
974         }
975 }
976
977 # broadcast a message to all clusters ignoring isolation
978 # [except those mentioned after buffer]
979 sub broadcast_all_ak1a
980 {
981         my $s = shift;                          # the line to be rebroadcast
982         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
983         my @dxchan = get_all_ak1a();
984         my $dxchan;
985         
986         # send it if it isn't the except list and isn't isolated and still has a hop count
987         foreach $dxchan (@dxchan) {
988                 next if grep $dxchan == $_, @except;
989                 my $routeit = adjust_hops($dxchan, $s);      # adjust its hop count by node name
990                 $dxchan->send($routeit);
991         }
992 }
993
994 # broadcast to all users
995 # storing the spot or whatever until it is in a state to receive it
996 sub broadcast_users
997 {
998         my $s = shift;                          # the line to be rebroadcast
999         my $sort = shift;           # the type of transmission
1000         my $fref = shift;           # a reference to an object to filter on
1001         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
1002         my @dxchan = get_all_users();
1003         my $dxchan;
1004         my @out;
1005         
1006         foreach $dxchan (@dxchan) {
1007                 next if grep $dxchan == $_, @except;
1008                 push @out, $dxchan;
1009         }
1010         broadcast_list($s, $sort, $fref, @out);
1011 }
1012
1013 # broadcast to a list of users
1014 sub broadcast_list
1015 {
1016         my $s = shift;
1017         my $sort = shift;
1018         my $fref = shift;
1019         my $dxchan;
1020         
1021         foreach $dxchan (@_) {
1022                 my $filter = 1;
1023                 
1024                 if ($sort eq 'dx') {
1025                     next unless $dxchan->{dx};
1026                         ($filter) = Filter::it($dxchan->{spotfilter}, @{$fref}) if ref $fref;
1027                         next unless $filter;
1028                 }
1029                 next if $sort eq 'ann' && !$dxchan->{ann};
1030                 next if $sort eq 'wwv' && !$dxchan->{wwv};
1031                 next if $sort eq 'wx' && !$dxchan->{wx};
1032
1033                 $s =~ s/\a//og unless $dxchan->{beep};
1034
1035                 if ($dxchan->{state} eq 'prompt' || $dxchan->{state} eq 'convers') {
1036                         $dxchan->send($s);      
1037                 } else {
1038                         $dxchan->delay($s);
1039                 }
1040         }
1041 }
1042
1043 #
1044 # gimme all the ak1a nodes
1045 #
1046 sub get_all_ak1a
1047 {
1048         my @list = DXChannel->get_all();
1049         my $ref;
1050         my @out;
1051         foreach $ref (@list) {
1052                 push @out, $ref if $ref->is_ak1a;
1053         }
1054         return @out;
1055 }
1056
1057 # return a list of all users
1058 sub get_all_users
1059 {
1060         my @list = DXChannel->get_all();
1061         my $ref;
1062         my @out;
1063         foreach $ref (@list) {
1064                 push @out, $ref if $ref->is_user;
1065         }
1066         return @out;
1067 }
1068
1069 # return a list of all user callsigns
1070 sub get_all_user_calls
1071 {
1072         my @list = DXChannel->get_all();
1073         my $ref;
1074         my @out;
1075         foreach $ref (@list) {
1076                 push @out, $ref->call if $ref->is_user;
1077         }
1078         return @out;
1079 }
1080
1081 #
1082 # obtain the hops from the list for this callsign and pc no 
1083 #
1084
1085 sub get_hops
1086 {
1087         my $pcno = shift;
1088         my $hops = $DXProt::hopcount{$pcno};
1089         $hops = $DXProt::def_hopcount if !$hops;
1090         return "H$hops";       
1091 }
1092
1093
1094 # adjust the hop count on a per node basis using the user loadable 
1095 # hop table if available or else decrement an existing one
1096 #
1097
1098 sub adjust_hops
1099 {
1100         my $self = shift;
1101         my $s = shift;
1102         my $call = $self->{call};
1103         my $hops;
1104         
1105         if (($hops) = $s =~ /\^H(\d+)\^~?$/o) {
1106                 my ($pcno) = $s =~ /^PC(\d\d)/o;
1107                 confess "$call called adjust_hops with '$s'" unless $pcno;
1108                 my $ref = $nodehops{$call} if %nodehops;
1109                 if ($ref) {
1110                         my $newhops = $ref->{$pcno};
1111                         return "" if defined $newhops && $newhops == 0;
1112                         $newhops = $ref->{default} unless $newhops;
1113                         return "" if defined $newhops && $newhops == 0;
1114                         $newhops = $hops if !$newhops;
1115                         $s =~ s/\^H(\d+)(\^~?)$/\^H$newhops$2/ if $newhops;
1116                 } else {
1117                         # simply decrement it
1118                         $hops--;
1119                         return "" if !$hops;
1120                         $s =~ s/\^H(\d+)(\^~?)$/\^H$hops$2/ if $hops;
1121                 }
1122         }
1123         return $s;
1124 }
1125
1126
1127 # load hop tables
1128 #
1129 sub load_hops
1130 {
1131         my $self = shift;
1132         return $self->msg('lh1') unless -e "$main::data/hop_table.pl";
1133         do "$main::data/hop_table.pl";
1134         return $@ if $@;
1135         return 0;
1136 }
1137
1138 # remove leading and trailing spaces from an input string
1139 sub unpad
1140 {
1141         my $s = shift;
1142         $s =~ s/^\s+|\s+$//;
1143         return $s;
1144 }
1145
1146 # add a ping request to the ping queues
1147 sub addping
1148 {
1149         my ($from, $to) = @_;
1150         my $ref = $pings{$to};
1151         $ref = $pings{$to} = [] if !$ref;
1152         my $r = {};
1153         $r->{call} = $from;
1154         $r->{t} = $main::systime;
1155         route($to, pc51($to, $main::mycall, 1));
1156         push @$ref, $r;
1157 }
1158
1159 # add a rcmd request to the rcmd queues
1160 sub addrcmd
1161 {
1162         my ($from, $to, $cmd) = @_;
1163         my $r = {};
1164         $r->{call} = $from;
1165         $r->{t} = $main::systime;
1166         $r->{cmd} = $cmd;
1167         route($to, pc34($main::mycall, $to, $cmd));
1168         $rcmds{$to} = $r;
1169 }
1170 1;
1171 __END__