remove any leading ::ffff: on ipv4 addresses
[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 #
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 DXProtVars;
19 use DXCommandmode;
20 use DXLog;
21 use Spot;
22 use DXProtout;
23 use DXDebug;
24 use Filter;
25 use Local;
26 use DXDb;
27 use AnnTalk;
28 use Geomag;
29 use WCY;
30 use BadWords;
31 use DXHash;
32 use Route;
33 use Route::Node;
34 use Script;
35 use DXProtHandle;
36
37 use Time::HiRes qw(gettimeofday tv_interval);
38 use Mojo::IOLoop::Subprocess;
39
40 use strict;
41
42 use vars qw($pc11_max_age $pc23_max_age $last_pc50 $eph_restime $eph_info_restime $eph_pc34_restime
43                         $last_hour $last10 %eph  %pings %rcmds $ann_to_talk
44                         $pingint $obscount %pc19list $chatdupeage $chatimportfn
45                         $pc19_version $myprot_version
46                         %nodehops $baddx $badspotter $badnode $censorpc
47                         $allowzero $decode_dk0wcy $send_opernam @checklist
48                         $eph_pc15_restime $pc92_update_period $pc92_obs_timeout
49                         %pc92_find $pc92_find_timeout $pc92_short_update_period
50                         $next_pc92_obs_timeout $pc92_slug_changes $last_pc92_slug
51                         $pc92_extnode_update_period $pc50_interval
52                         $pc92_keepalive_period
53                    );
54
55 $pc11_max_age = 1*3600;                 # the maximum age for an incoming 'real-time' pc11
56 $pc23_max_age = 1*3600;                 # the maximum age for an incoming 'real-time' pc23
57
58 $last_hour = time;                              # last time I did an hourly periodic update
59 %rcmds = ();                    # outstanding rcmd requests outbound
60 %nodehops = ();                 # node specific hop control
61 %pc19list = ();                                 # list of outstanding PC19s that haven't had PC16s on them
62
63 $censorpc = 1;                                  # Do a BadWords::check on text fields and reject things
64                                                                 # loads of 'bad things'
65 $baddx = new DXHash "baddx";
66 $badspotter = new DXHash "badspotter";
67 $badnode = new DXHash "badnode";
68 $last10 = $last_pc50 = time;
69 $ann_to_talk = 1;
70 $eph_restime = 60;
71 $eph_info_restime = 18*60*60;
72 $eph_pc15_restime = 6*60;
73 $eph_pc34_restime = 30;
74 $pingint = 5*60;
75 $obscount = 2;
76 $chatdupeage = 20 * 60;
77 $chatimportfn = "$main::root/chat_import";
78 $pc19_version = 5455;                   # the visible version no for outgoing PC19s generated from pc59
79 $pc92_update_period = 4*60*60;  # the period between outgoing PC92 C updates
80 $pc92_short_update_period = 15*60; # shorten the update period after a connection or start up
81 $pc92_extnode_update_period = 1*60*60; # the update period for external nodes
82 $pc92_keepalive_period = 1*60*60;       # frequency of PC92 K (keepalive) records
83 %pc92_find = ();                                # outstanding pc92 find operations
84 $pc92_find_timeout = 30;                # maximum time to wait for a reply
85
86
87 @checklist =
88 (
89  [ qw(i c c m bp bc c) ],                       # pc10
90  [ qw(i f m d t m c c h) ],             # pc11
91  [ qw(i c bm m bm bm p h) ],            # pc12
92  [ qw(i c h) ],                                 #
93  [ qw(i c h) ],                                 #
94  [ qw(i c m h) ],                                       #
95  undef ,                                                # pc16 has to be validated manually
96  [ qw(i c c h) ],                                       # pc17
97  [ qw(i m n) ],                                 # pc18
98  undef ,                                                # pc19 has to be validated manually
99  undef ,                                                # pc20 no validation
100  [ qw(i c m h) ],                                       # pc21
101  undef ,                                                # pc22 no validation
102  [ qw(i d n n n n m c c h) ],           # pc23
103  [ qw(i c p h) ],                                       # pc24
104  [ qw(i c c n n) ],                             # pc25
105  [ qw(i f m d t m c c bc) ],            # pc26
106  [ qw(i d n n n n m c c bc) ],  # pc27
107  [ qw(i c c m c d t p m bp n p bp bc) ], # pc28
108  [ qw(i c c n m) ],                             # pc29
109  [ qw(i c c n) ],                                       # pc30
110  [ qw(i c c n) ],                                       # pc31
111  [ qw(i c c n) ],                                       # pc32
112  [ qw(i c c n) ],                                       # pc33
113  [ qw(i c c m) ],                                       # pc34
114  [ qw(i c c m) ],                                       # pc35
115  [ qw(i c c m) ],                                       # pc36
116  [ qw(i c c n m) ],                             # pc37
117  undef,                                                 # pc38 not interested
118  [ qw(i c m) ],                                 # pc39
119  [ qw(i c c m p n) ],                           # pc40
120  [ qw(i c n m h) ],                             # pc41
121  [ qw(i c c n) ],                                       # pc42
122  undef,                                                 # pc43 don't handle it
123  [ qw(i c c n m m c) ],                 # pc44
124  [ qw(i c c n m) ],                             # pc45
125  [ qw(i c c n) ],                                       # pc46
126  undef,                                                 # pc47
127  undef,                                                 # pc48
128  [ qw(i c m h) ],                                       # pc49
129  [ qw(i c n h) ],                                       # pc50
130  [ qw(i c c n) ],                                       # pc51
131  undef,
132  undef,
133  undef,
134  undef,
135  undef,
136  undef,
137  undef,
138  undef,
139  undef,                                                 # pc60
140  [ qw(i f m d t m c c a h) ],           # pc61
141  undef,
142  undef,
143  undef,
144  undef,
145  undef,
146  undef,
147  undef,
148  undef,
149  undef,                                                 # pc70
150  undef,
151  undef,
152  [ qw(i d n n n n n n m m m c c h) ],   # pc73
153  undef,
154  undef,
155  undef,
156  undef,
157  undef,
158  undef,
159  undef,                                                 # pc80
160  undef,
161  undef,
162  undef,
163  [ qw(i c c c m) ],                             # pc84
164  [ qw(i c c c m) ],                             # pc85
165  undef,
166  undef,
167  undef,
168  undef,
169  undef,                                                 # pc90
170  undef,
171  [ qw(i c f l)],                                # pc92
172  [ qw(i c f *m c *c m)],                                        # pc93
173 );
174
175 # use the entry in the check list to check the field list presented
176 # return OK if line NOT in check list (for now)
177 sub check
178 {
179         my $n = shift;
180         my $pc = shift;
181         
182         $n -= 10;
183         return 0 if $n < 0 || $n > @checklist;
184         my $ref = $checklist[$n];
185         return 0 unless ref $ref;
186
187         my $i;
188         for ($i = 1; $i < @$ref; $i++) {
189                 my ($blank, $act) = $$ref[$i] =~ /^(b?)(\w)$/;
190                 return 0 unless $act;
191                 next if $blank eq 'b' && $pc->[$i] =~ /^[ \*]$/;
192                 next if $blank eq '*' && $pc->[$i] =~ /^\*$/;
193                 if ($act eq 'c') {
194                         return $i unless is_callsign($pc->[$i]);
195                 } elsif ($act eq 'i') {
196                         ;                                       # do nothing
197                 } elsif ($act eq 'm') {
198                         return $i unless is_pctext($pc->[$i]);
199                 } elsif ($act eq 'p') {
200                         return $i unless is_pcflag($pc->[$i]);
201                 } elsif ($act eq 'f') {
202                         return $i unless is_freq($pc->[$i]);
203                 } elsif ($act eq 'n') {
204                         return $i unless $pc->[$i] =~ /^[\d ]+$/;
205                 } elsif ($act eq 'h') {
206                         return $i unless $pc->[$i] =~ /^H\d\d?$/;
207                 } elsif ($act eq 'd') {
208                         return $i unless $pc->[$i] =~ /^\s*\d+-\w\w\w-[12][90]\d\d$/;
209                 } elsif ($act eq 't') {
210                         return $i unless $pc->[$i] =~ /^[012]\d[012345]\dZ$/;
211                 } elsif ($act eq 'l') {
212                         return $i unless $pc->[$i] =~ /^[A-Z]$/;
213                 } elsif ($act eq 'a') {
214                         return $i unless is_ipaddr($pc->[$i]);
215                 }
216         }
217         return 0;
218 }
219
220 sub update_pc92_next
221 {
222         my $self = shift;
223         my $period = shift || ($self->{do_pc9x} ? $pc92_update_period : $pc92_extnode_update_period);
224         $self->{next_pc92_update} = $main::systime + $period - int rand($period / 4);
225         dbg("ROUTE: update_pc92_next: $self->{call} " . atime($self->{next_pc92_update})) if isdbg('obscount');
226 }
227
228 sub update_pc92_keepalive
229 {
230         my $self = shift;
231         my $period = shift || $pc92_keepalive_period;
232         $self->{next_pc92_keepalive} = $main::systime + $period - int rand($period / 4);
233         dbg("ROUTE: update_pc92_keepalive: $self->{call} " . atime($self->{next_pc92_keepalive})) if isdbg('obscount');
234 }
235
236 sub init
237 {
238         my $fn = localdata("hop_table.pl");
239         do $fn if -e $fn;
240         confess $@ if $@;
241
242         my $user = DXUser::get($main::mycall);
243         die "User $main::mycall not setup or disappeared RTFM" unless $user;
244
245         $myprot_version += $main::version*100;
246         $main::me = DXProt->new($main::mycall, 0, $user);
247         $main::me->{here} = 1;
248         $main::me->{state} = "indifferent";
249         $main::me->{sort} = 'S';    # S for spider
250         $main::me->{priv} = 9;
251         $main::me->{metric} = 0;
252         $main::me->{pingave} = 0;
253         $main::me->{registered} = 1;
254         $main::me->{version} = $main::version;
255         $main::me->{build} = $main::build;
256         $main::me->{do_pc9x} = 1;
257         $main::me->update_pc92_next($pc92_short_update_period);
258         $main::me->update_pc92_keepalive;
259 }
260
261 #
262 # obtain a new connection this is derived from dxchannel
263 #
264
265 sub new
266 {
267         my $self = DXChannel::alloc(@_);
268
269         # add this node to the table, the values get filled in later
270         my $pkg = shift;
271         my $call = shift;
272
273         # if we have an entry already, then send a PC21 to all connect
274         # old style connections, because we are about to get the real deal
275         if (my $ref = Route::Node::get($call)) {
276                 dbg("ROUTE: $call is already in the routing table, deleting") if isdbg('route');
277                 my @rout = $ref->delete;
278                 $self->route_pc21($main::mycall, undef, @rout) if @rout;
279         }
280         $main::routeroot->add($call, '5000', Route::here(1), $self->{conn}->peerhost) if $call ne $main::mycall;
281
282         return $self;
283 }
284
285 # this is how a pc connection starts (for an incoming connection)
286 # issue a PC38 followed by a PC18, then wait for a PC20 (remembering
287 # all the crap that comes between).
288 sub start
289 {
290         my ($self, $line, $sort) = @_;
291         my $call = $self->{call};
292         my $user = $self->{user};
293
294         # log it
295         my $host = $self->{conn}->peerhost;
296         $host ||= "AGW Port #$self->{conn}->{agwport}" if exists $self->{conn}->{agwport};
297         $host ||= "unknown";
298         $self->{hostname} = $host if is_ipaddr($host);
299
300         Log('DXProt', "$call connected from $host");
301
302         # remember type of connection
303         $self->{consort} = $line;
304         $self->{outbound} = $sort eq 'O';
305         my $priv = $user->priv;
306         $priv = $user->priv(1) unless defined $priv;
307         $self->{priv} = $priv;     # other clusters can always be 'normal' users
308         $self->{lang} = $user->lang || 'en';
309         $self->{isolate} = $user->{isolate};
310         $self->{consort} = $line;       # save the connection type
311         $self->{here} = 1;
312         $self->{width} = 80;
313
314         # sort out registration
315         $self->{registered} = 1;
316
317         # get the output filters
318         $self->{spotsfilter} = Filter::read_in('spots', $call, 0) || Filter::read_in('spots', 'node_default', 0);
319         $self->{wwvfilter} = Filter::read_in('wwv', $call, 0) || Filter::read_in('wwv', 'node_default', 0);
320         $self->{wcyfilter} = Filter::read_in('wcy', $call, 0) || Filter::read_in('wcy', 'node_default', 0);
321         $self->{annfilter} = Filter::read_in('ann', $call, 0) || Filter::read_in('ann', 'node_default', 0) ;
322         $self->{routefilter} = Filter::read_in('route', $call, 0) || Filter::read_in('route', 'node_default', 0) unless $self->{isolate};
323         $self->{pc92filter} = Filter::read_in('pc92', $call, 0) || Filter::read_in('pc92', 'node_default', 0) unless $self->{isolate} ;
324
325
326         # get the INPUT filters (these only pertain to Clusters)
327         $self->{inspotsfilter} = Filter::read_in('spots', $call, 1) || Filter::read_in('spots', 'node_default', 1);
328         $self->{inwwvfilter} = Filter::read_in('wwv', $call, 1) || Filter::read_in('wwv', 'node_default', 1);
329         $self->{inwcyfilter} = Filter::read_in('wcy', $call, 1) || Filter::read_in('wcy', 'node_default', 1);
330         $self->{inannfilter} = Filter::read_in('ann', $call, 1) || Filter::read_in('ann', 'node_default', 1);
331         $self->{inroutefilter} = Filter::read_in('route', $call, 1) || Filter::read_in('route', 'node_default', 1) unless $self->{isolate};
332         $self->{inpc92filter} = Filter::read_in('pc92', $call, 0) || Filter::read_in('pc92', 'node_default', 0) unless $self->{isolate} ;
333
334
335         # set unbuffered and no echo
336         $self->send_now('B',"0");
337         $self->send_now('E',"0");
338         $self->conn->echo(0) if $self->conn->can('echo');
339
340         # ping neighbour node stuff
341         my $ping = $user->pingint;
342         $ping = $pingint unless defined $ping;
343         $self->{pingint} = $ping;
344         $self->{nopings} = $user->nopings || $obscount;
345         $self->{pingtime} = [ ];
346         $self->{pingave} = 999;
347         $self->{metric} ||= 100;
348         $self->{lastping} = $main::systime;
349
350         # send initialisation string
351         unless ($self->{outbound}) {
352                 $self->sendinit;
353         }
354
355         $self->state('init');
356         $self->{pc50_t} = $main::systime;
357
358         # send info to all logged in thingies
359         $self->tell_login('loginn');
360
361         # run a script send the output to the debug file
362         my $script = new Script(lc $call) || new Script('node_default');
363         $script->run($self) if $script;
364
365         # set up a config broadcast "quite soon" to converge tables quicker
366         $main::me->update_pc92_next($pc92_short_update_period);
367         $self->update_pc92_next($pc92_short_update_period);
368
369         # set next keepalive time
370         $self->update_pc92_keepalive;
371 }
372
373 #
374 # send outgoing 'challenge'
375 #
376
377 sub sendinit
378 {
379         my $self = shift;
380         $self->send(pc18(($self->{isolate} || !$self->user->wantpc9x) ? "" : " pc9x"));
381 }
382
383 #
384 # This is the normal pcxx despatcher
385 #
386 sub normal
387 {
388         my ($self, $line) = @_;
389
390         if ($line =~ '^<\w+\s' && $main::do_xml) {
391                 DXXml::normal($self, $line);
392                 return;
393         }
394
395         my @field = split /\^/, $line;
396         return unless @field;
397
398         pop @field if $field[-1] eq '~';
399
400 #       print join(',', @field), "\n";
401
402
403         # process PC frames, this will fail unless the frame starts PCnn
404         my ($pcno) = $field[0] =~ /^PC(\d\d)/; # just get the number
405         unless (defined $pcno && $pcno >= 10 && $pcno <= 99) {
406                 dbg("PCPROT: unknown protocol") if isdbg('chanerr');
407                 return;
408         }
409
410         # check for and dump bad protocol messages
411         my $n = check($pcno, \@field);
412         if ($n) {
413                 dbg("PCPROT: bad field $n, dumped (" . parray($checklist[$pcno-10]) . ")") if isdbg('chanerr');
414                 return;
415         }
416
417         # modify the hop count here
418         if ($self != $main::me) {
419                 if (my ($hops, $trail) = $line =~ /\^H(\d+)(\^?\~?)?$/) {
420                         $trail ||= '';
421                         $hops--;
422                         return if $hops < 0;
423                         $line =~ s/\^H(\d+)(\^?\~?)?$/sprintf('^H%d%s', $hops, $trail)/e;
424                         $field[-1] = "H$hops";
425                 }
426         }
427
428         if (defined &Local::pcprot) {
429                 my $r;
430                 eval { $r = Local::pcprot($self, $pcno, $line, @field); };
431                 return if $r;                   # i.e don't process it
432         }
433
434         # send it out for processing
435         my $origin = $self->{call};
436         no strict 'subs';
437         my $sub = "handle_$pcno";
438
439         if ($self->can($sub)) {
440                 $self->$sub($pcno, $line, $origin, \@field);
441         } else {
442                 $self->handle_default($pcno, $line, $origin, \@field);
443         }
444 }
445
446 #
447 # This is called from inside the main cluster processing loop and is used
448 # for despatching commands that are doing some long processing job
449 #
450 sub process
451 {
452         my $t = time;
453         my @dxchan = DXChannel::get_all();
454         my $dxchan;
455         my $pc50s;
456
457         # every ten seconds
458         if ($t - $last10 >= 10) {
459                 # clean out ephemera
460
461                 eph_clean();
462                 import_chat();
463
464                 $last10 = $t;
465
466                 # send out a pc50 on EVERY channel all at once
467                 if ($t >= $last_pc50 + $pc50_interval) {
468                         $pc50s = pc50($main::me, scalar DXChannel::get_all_users);
469                         eph_dup($pc50s);
470                         $last_pc50 = $t;
471                 }
472
473                 foreach $dxchan (@dxchan) {
474                         next unless $dxchan->is_node;
475                         next if $dxchan == $main::me;
476
477                         # send the pc50
478                         $dxchan->send($pc50s) if !$dxchan->{do_pc9x} && $pc50s;
479
480                         # send a ping out on this channel
481                         if ($dxchan->{pingint} && $t >= $dxchan->{pingint} + $dxchan->{lastping}) {
482                                 if ($dxchan->{nopings} <= 0) {
483                                         dbg("ROUTE: $dxchan->{call} disconnected on ping obscount") if isdbg('obscount');
484                                         $dxchan->disconnect;
485                                 } else {
486                                         DXXml::Ping::add($main::me, $dxchan->call);
487                                         $dxchan->{nopings} -= 1;
488                                         $dxchan->{lastping} = $t;
489                                         $dxchan->{lastping} += $dxchan->{pingint} / 2 unless @{$dxchan->{pingtime}};
490                                         dbg("ROUTE: $dxchan->{call} ping obscount = $dxchan->{nopings}") if isdbg('obscount');
491                                 }
492                         }
493                 }
494
495                 clean_pc92_find();
496
497                 # send out config broadcasts
498                 foreach $dxchan (@dxchan) {
499                         next unless $dxchan->is_node;
500
501                         # send out a PC92 config record if required for me and
502                         # all my non pc9x dependent nodes. But for dependent nodes we only do
503                         # this if we have not seen any from anyone else for at least half
504                         # of one update period. This should stop quite a bit of excess C
505                         # records. Someone will win, it does not really matter who, because
506                         # we always believe "us".
507                         if ($main::systime >= $dxchan->{next_pc92_update}) {
508                                 if ($dxchan == $main::me || !$dxchan->{do_pc9x}) {
509                                         dbg("ROUTE: pc92 broadcast candidate: $dxchan->{call}") if isdbg('obscount');
510                                         my $ref = Route::Node::get($dxchan->{call});
511                                         if ($dxchan == $main::me || ($ref && ($ref->measure_pc9x_t($main::systime-$main::systime_daystart)) >= $pc92_extnode_update_period/2)) {
512                                                 $dxchan->broadcast_pc92_update($dxchan->{call});
513                                         } else {
514                                                 $dxchan->update_pc92_next;
515                                         }
516                                 } else {
517                                         $dxchan->update_pc92_next; # this won't actually do anything, it's just to be tidy
518                                 }
519                         }
520                 }
521
522                 # do the keepalive for me, if required
523                 if ($main::systime >= $main::me->{next_pc92_keepalive}) {
524                         time_out_pc92_routes();
525                         $main::me->broadcast_pc92_keepalive($main::mycall);
526                 }
527
528                 if ($pc92_slug_changes && $main::systime >= $last_pc92_slug + $pc92_slug_changes) {
529                         my ($add, $del) = gen_pc92_changes();
530                         $main::me->route_pc92d($main::mycall, undef, $main::routeroot, @$del) if @$del;
531                         $main::me->route_pc92a($main::mycall, undef, $main::routeroot, @$add) if @$add;
532                         clear_pc92_changes();
533                 }
534         }
535
536         if ($main::systime - 3600 > $last_hour) {
537                 $last_hour = $main::systime;
538         }
539 }
540
541 #
542 # finish up a pc context
543 #
544
545 #
546 # some active measures
547 #
548
549
550 sub send_dx_spot
551 {
552         my $self = shift;
553         my $line = shift;
554         my @dxchan = DXChannel::get_all();
555         my $dxchan;
556         my $pc11;
557
558         # send it if it isn't the except list and isn't isolated and still has a hop count
559         # taking into account filtering and so on
560         foreach $dxchan (@dxchan) {
561                 next if $dxchan == $main::me;
562                 next if $dxchan == $self && $self->is_node;
563                 if ($line =~ /PC61/ && !($dxchan->is_spider || $dxchan->is_user)) {
564                         unless ($pc11) {
565                                 my @f = split /\^/, $line;
566                                 $pc11 = join '^', 'PC11', @f[1..7,9];
567                         }
568                         $dxchan->dx_spot($pc11, $self->{isolate}, @_, $self->{call});
569                 } else {
570                         $dxchan->dx_spot($line, $self->{isolate}, @_, $self->{call});
571                 }
572         }
573 }
574
575 sub dx_spot
576 {
577         my $self = shift;
578         my $line = shift;
579         my $isolate = shift;
580         my ($filter, $hops);
581
582         if ($self->{spotsfilter}) {
583                 ($filter, $hops) = $self->{spotsfilter}->it(@_);
584                 return unless $filter;
585         }
586         send_prot_line($self, $filter, $hops, $isolate, $line);
587 }
588
589 sub send_prot_line
590 {
591         my ($self, $filter, $hops, $isolate, $line) = @_;
592         my $routeit;
593
594
595         if ($hops) {
596                 $routeit = $line;
597                 $routeit =~ s/\^H\d+\^\~$/\^H$hops\^\~/;
598         } else {
599                 $routeit = adjust_hops($self, $line);  # adjust its hop count by node name
600                 return unless $routeit;
601         }
602         if ($filter) {
603                 $self->send($routeit);
604         } else {
605                 $self->send($routeit) unless $self->{isolate} || $isolate;
606         }
607 }
608
609
610 sub send_wwv_spot
611 {
612         my $self = shift;
613         my $line = shift;
614         my @dxchan = DXChannel::get_all();
615         my $dxchan;
616         my @dxcc = ((Prefix::cty_data($_[6]))[0..2], (Prefix::cty_data($_[7]))[0..2]);
617
618         # send it if it isn't the except list and isn't isolated and still has a hop count
619         # taking into account filtering and so on
620         foreach $dxchan (@dxchan) {
621                 next if $dxchan == $main::me;
622                 next if $dxchan == $self && $self->is_node;
623                 my $routeit;
624                 my ($filter, $hops);
625
626                 $dxchan->wwv($line, $self->{isolate}, @_, $self->{call}, @dxcc);
627         }
628 }
629
630 sub wwv
631 {
632         my $self = shift;
633         my $line = shift;
634         my $isolate = shift;
635         my ($filter, $hops);
636
637         if ($self->{wwvfilter}) {
638                 ($filter, $hops) = $self->{wwvfilter}->it(@_[7..$#_]);
639                 return unless $filter;
640         }
641         send_prot_line($self, $filter, $hops, $isolate, $line)
642 }
643
644 sub send_wcy_spot
645 {
646         my $self = shift;
647         my $line = shift;
648         my @dxchan = DXChannel::get_all();
649         my $dxchan;
650         my @dxcc = ((Prefix::cty_data($_[10]))[0..2], (Prefix::cty_data($_[11]))[0..2]);
651
652         # send it if it isn't the except list and isn't isolated and still has a hop count
653         # taking into account filtering and so on
654         foreach $dxchan (@dxchan) {
655                 next if $dxchan == $main::me;
656                 next if $dxchan == $self;
657
658                 $dxchan->wcy($line, $self->{isolate}, @_, $self->{call}, @dxcc);
659         }
660 }
661
662 sub wcy
663 {
664         my $self = shift;
665         my $line = shift;
666         my $isolate = shift;
667         my ($filter, $hops);
668
669         if ($self->{wcyfilter}) {
670                 ($filter, $hops) = $self->{wcyfilter}->it(@_);
671                 return unless $filter;
672         }
673         send_prot_line($self, $filter, $hops, $isolate, $line) if $self->is_clx || $self->is_spider || $self->is_dxnet;
674 }
675
676 # send an announce
677 sub send_announce
678 {
679         my $self = shift;
680         my $from_pc9x = shift;
681         my $line = shift;
682         my @dxchan = DXChannel::get_all();
683         my $dxchan;
684         my $target = $_[6];
685         my $to = 'To ';
686         my $text = unpad($_[2]);
687         my $from = $_[0];
688
689         if ($_[3] eq '*') {     # sysops
690                 $target = "SYSOP";
691         } elsif ($_[3] gt ' ') { # speciality list handling
692                 my ($name) = split /\./, $_[3];
693                 $target = "$name"; # put the rest in later (if bothered)
694         }
695
696         if ($_[5] eq '1') {
697                 $target = "WX";
698                 $to = '';
699         }
700         $target = "ALL" if !$target;
701
702
703         # obtain country codes etc
704         my @a = Prefix::cty_data($from);
705         my @b = Prefix::cty_data($_[4]);
706         if ($self->{inannfilter}) {
707                 my ($filter, $hops) =
708                         $self->{inannfilter}->it(@_, $self->{call},
709                                                                          @a[0..2],
710                                                                          @b[0..2], $a[3], $b[3]);
711                 unless ($filter) {
712                         dbg("PCPROT: Rejected by input announce filter") if isdbg('chanerr');
713                         return;
714                 }
715         }
716
717         # the sysop ('*') thing is an attempt to minimise the damage caused by non-updated PC93 generators
718         if (AnnTalk::dup($from, $target, $_[2]) || ($_[3] eq '*' && AnnTalk::dup($from, 'ALL', $_[2]))) {
719                 my $dxchan = DXChannel::get($from);
720                 if ($self == $main::me && $dxchan && $dxchan->is_user) {
721                         if ($dxchan->priv < 5) {
722                                 $dxchan->send($dxchan->msg('dup'));
723                                 return;
724                         }
725                 } else {
726                         dbg("PCPROT: Duplicate Announce ignored") if isdbg('chanerr');
727                         return;
728                 }
729         }
730
731         Log('ann', $target, $from, $text);
732
733         # send it if it isn't the except list and isn't isolated and still has a hop count
734         # taking into account filtering and so on
735         foreach $dxchan (@dxchan) {
736                 next if $dxchan == $main::me;
737                 next if $dxchan == $self && $self->is_node;
738                 next if $from_pc9x && $dxchan->{do_pc9x};
739                 next if $target eq 'LOCAL' && $dxchan->is_node;
740                 $dxchan->announce($line, $self->{isolate}, $to, $target, $text, @_, $self->{call},
741                                                   @a[0..2], @b[0..2]);
742         }
743 }
744
745 my $msgid = int rand(1000);
746
747 sub nextchatmsgid
748 {
749         $msgid++;
750         $msgid = 1 if $msgid > 999;
751         return $msgid;
752 }
753
754 # send a chat line
755 sub send_chat
756 {
757         my $self = shift;
758         my $from_pc9x = shift;
759         my $line = shift;
760         my @dxchan = DXChannel::get_all();
761         my $dxchan;
762         my $target = $_[3];
763         my $text = unpad($_[2]);
764         my $ak1a_line;
765         my $from = $_[0];
766
767         # munge the group and recast the line if required
768         if ($target =~ s/\.LST$//) {
769                 $ak1a_line = $line;
770         }
771
772         # obtain country codes etc
773         my @a = Prefix::cty_data($from);
774         my @b = Prefix::cty_data($_[4]);
775         if ($self->{inannfilter}) {
776                 my ($filter, $hops) =
777                         $self->{inannfilter}->it(@_, $self->{call},
778                                                                          @a[0..2],
779                                                                          @b[0..2], $a[3], $b[3]);
780                 unless ($filter) {
781                         dbg("PCPROT: Rejected by input announce filter") if isdbg('chanerr');
782                         return;
783                 }
784         }
785
786         if (AnnTalk::dup($from, $target, $_[2], $main::systime + $chatdupeage)) {
787                 my $dxchan = DXChannel::get($from);
788                 if ($self == $main::me && $dxchan && $dxchan->is_user) {
789                         if ($dxchan->priv < 5) {
790                                 $dxchan->send($dxchan->msg('dup'));
791                                 return;
792                         }
793                 } else {
794                         dbg("PCPROT: Duplicate Announce ignored") if isdbg('chanerr');
795                         return;
796                 }
797         }
798
799
800         Log('chat', $target, $from, $text);
801
802         # send it if it isn't the except list and isn't isolated and still has a hop count
803         # taking into account filtering and so on
804         foreach $dxchan (@dxchan) {
805                 if ($dxchan->is_node) {
806                         next if $dxchan == $main::me;
807                         next if $dxchan == $self;
808                         next if $from_pc9x && $dxchan->do_pc9x;
809                         next unless $dxchan->is_spider && $dxchan->do_pc9x;
810                         next if $target eq 'LOCAL';
811                 }
812
813                 $dxchan->chat($line, $self->{isolate}, $target, $_[1],
814                                           $text, @_, $self->{call}, @a[0..2], @b[0..2]);
815         }
816 }
817
818 sub announce
819 {
820         my $self = shift;
821         my $line = shift;
822         my $isolate = shift;
823         my $to = shift;
824         my $target = shift;
825         my $text = shift;
826         my ($filter, $hops);
827
828         if ($self->{annfilter}) {
829                 ($filter, $hops) = $self->{annfilter}->it(@_);
830                 return unless $filter;
831         }
832         send_prot_line($self, $filter, $hops, $isolate, $line) unless $_[1] eq $main::mycall;
833 }
834
835 sub chat
836 {
837         my $self = shift;
838         my $line = shift;
839         my $isolate = shift;
840         my $to = shift;
841         my $target = shift;
842         my $text = shift;
843         my ($filter, $hops);
844
845         if ($self->{annfilter}) {
846                 ($filter, $hops) = $self->{annfilter}->it(@_);
847                 return unless $filter;
848         }
849         if (($self->is_spider || $self->is_ak1a) && $_[1] ne $main::mycall) {
850                 send_prot_line($self, $filter, $hops, $isolate, $line);
851         }
852 }
853
854
855 sub send_local_config
856 {
857         my $self = shift;
858
859         dbg('DXProt::send_local_config') if isdbg('trace');
860
861         # send our nodes
862         my $node;
863         my @nodes;
864         my @localnodes;
865         my @remotenodes;
866
867         if ($self->{isolate}) {
868                 dbg("send_local_config: isolated");
869                 @localnodes = ( $main::routeroot );
870                 $self->send_route($main::mycall, \&pc19, 1, $main::routeroot);
871         } elsif ($self->{do_pc9x}) {
872                 dbg("send_local_config: doing pc9x");
873                 my $node = Route::Node::get($self->{call});
874 #               $self->send_last_pc92_config($main::routeroot);
875 #               $self->send(pc92a($main::routeroot, $node)) unless $main::routeroot->last_PC92C =~ /$self->{call}/;
876                 $self->send(pc92a($main::routeroot, $node));
877                 $self->send(pc92k($main::routeroot));
878         } else {
879                 # create a list of all the nodes that are not connected to this connection
880                 # and are not themselves isolated, this to make sure that isolated nodes
881                 # don't appear outside of this node
882
883                 dbg("send_local_config: traditional");
884
885                 # send locally connected nodes
886                 my @dxchan = grep { $_->call ne $main::mycall && $_ != $self && !$_->{isolate} } DXChannel::get_all_nodes();
887                 @localnodes = map { my $r = Route::Node::get($_->{call}); $r ? $r : () } @dxchan if @dxchan;
888                 $self->send_route($main::mycall, \&pc19, scalar(@localnodes)+1, $main::routeroot, @localnodes);
889
890                 my $node;
891                 my @rawintcalls = map { $_->nodes } @localnodes if @localnodes;
892                 my @intcalls;
893                 foreach $node (@rawintcalls) {
894                         push @intcalls, $node if grep $_ && $node != $_, @intcalls;
895                 }
896                 my $ref = Route::Node::get($self->{call});
897                 my @rnodes = $ref->nodes;
898                 foreach $node (@intcalls) {
899                         push @remotenodes, Route::Node::get($node) if grep $_ && $node != $_, @rnodes, @remotenodes;
900                 }
901                 $self->send_route($main::mycall, \&pc19, scalar(@remotenodes), @remotenodes);
902         }
903
904         # get all the users connected on the above nodes and send them out
905         unless ($self->{do_pc9x}) {
906                 foreach $node ($main::routeroot, @localnodes, @remotenodes) {
907                         if ($node) {
908                                 my @rout = map {my $r = Route::User::get($_); $r ? ($r) : ()} $node->users;
909                                 $self->send_route($main::mycall, \&pc16, 1, $node, @rout) if @rout && $self->user->wantsendpc16;
910                         } else {
911                                 dbg("sent a null value") if isdbg('chanerr');
912                         }
913                 }
914         }
915 }
916
917 sub gen_my_pc92_config
918 {
919         my $node = shift;
920
921         if ($node->{call} eq $main::mycall) {
922                 clear_pc92_changes();           # remove any slugged data, we are generating it as now
923                 my @dxchan = grep { $_->call ne $main::mycall && !$_->{isolate} } DXChannel::get_all();
924                 dbg("ROUTE: all dxchan: " . join(',', map{$_->{call}} @dxchan)) if isdbg('routelow');
925                 my @localnodes = map { my $r = Route::get($_->{call}); $r ? $r : () } @dxchan;
926                 dbg("ROUTE: localnodes: " . join(',', map{$_->{call}} @localnodes)) if isdbg('routelow');
927                 return pc92c($node, @localnodes);
928         } else {
929                 my @rout = map {my $r = Route::User::get($_); $r ? ($r) : ()} $node->users;
930                 return pc92c($node, @rout);
931         }
932 }
933
934 sub send_last_pc92_config
935 {
936         my $self = shift;
937         my $node = shift;
938         if (my $l = $node->last_PC92C) {
939                 $self->send($l);
940         } else {
941                 $self->send_pc92_config($node);
942         }
943 }
944
945 sub send_pc92_config
946 {
947         my $self = shift;
948         my $node = shift;
949
950         dbg('DXProt::send_pc92_config') if isdbg('trace');
951
952         $node->last_PC92C(gen_my_pc92_config($node));
953         $self->send($node->last_PC92C);
954 }
955
956 sub broadcast_pc92_update
957 {
958         my $self = shift;
959         my $call = shift;
960
961         dbg("ROUTE: broadcast_pc92_update $call") if isdbg('obscount');
962
963         my $nref = Route::Node::get($call);
964         unless ($nref) {
965                 cluck("ERROR: broadcast_pc92_update - Route::Node $call disappeared");
966                 $self->update_pc92_next;
967                 return;
968         }
969         my $l = $nref->last_PC92C(gen_my_pc92_config($nref));
970         $nref->lastid(last_pc9x_id());
971         $main::me->broadcast_route_pc9x($main::mycall, undef, $l, 0);
972         $self->update_pc92_next;
973 }
974
975 sub broadcast_pc92_keepalive
976 {
977         my $self = shift;
978         my $call = shift;
979
980         dbg("ROUTE: broadcast_pc92_keepalive $call") if isdbg('obscount');
981
982         my $nref = Route::Node::get($call);
983         unless ($nref) {
984                 cluck("ERROR: broadcast_pc92_keepalive - Route::Node $call disappeared");
985                 $self->update_pc92_keepalive;
986                 return;
987         }
988         my $l = pc92k($nref);
989         $nref->lastid(last_pc9x_id());
990         $main::me->broadcast_route_pc9x($main::mycall, undef, $l, 0);
991         $self->update_pc92_keepalive;
992 }
993
994 sub time_out_pc92_routes
995 {
996         my @nodes = grep {$_->call ne $main::mycall && ($_->do_pc9x || $_->via_pc92)} Route::Node::get_all();
997         my @rdel;
998         foreach my $n (@nodes) {
999                 my $o = $n->dec_obs;
1000                 if ($o <= 0) {
1001                         if (my $dxchan = DXChannel::get($n->call)) {
1002                                 dbg("ROUTE: disconnecting local pc92 $dxchan->{call} on obscount") if isdbg('obscount');
1003                                 $dxchan->disconnect;
1004                                 next;
1005                         }
1006                         my @parents = map {Route::Node::get($_)} $n->parents;
1007                         for (@parents) {
1008                                 if ($_) {
1009                                         dbg("ROUTE: deleting pc92 $_->{call} from $n->{call} on obscount")  if isdbg('obscount');
1010                                         push @rdel, $n->del($_);
1011                                 }
1012                         }
1013                 } else {
1014                         dbg("ROUTE: obscount on $n->{call} now $o") if isdbg('obscount');
1015                 }
1016         }
1017         for (@rdel) {
1018                 $main::me->route_pc21($main::mycall, undef, $_) if $_;
1019         }
1020 }
1021
1022 #
1023 # route a message down an appropriate interface for a callsign
1024 #
1025 # is called route(to, pcline);
1026 #
1027
1028 sub route
1029 {
1030         my ($self, $call, $line) = @_;
1031
1032         if (ref $self && $call eq $self->{call}) {
1033                 dbg("PCPROT: Trying to route back to source, dropped") if isdbg('chanerr');
1034                 return;
1035         }
1036
1037         # always send it down the local interface if available
1038         my $dxchan = DXChannel::get($call);
1039         if ($dxchan) {
1040                 dbg("route: $call -> $dxchan->{call} direct" ) if isdbg('route');
1041         } else {
1042                 my $cl = Route::get($call);
1043                 $dxchan = $cl->dxchan if $cl;
1044                 if (ref $dxchan) {
1045                         if (ref $self && $dxchan eq $self) {
1046                                 dbg("PCPROT: Trying to route back to source, dropped") if isdbg('chanerr');
1047                                 return;
1048                         }
1049                         dbg("route: $call -> $dxchan->{call} using normal route" ) if isdbg('route');
1050                 }
1051         }
1052
1053         if ($dxchan) {
1054                 my $routeit = adjust_hops($dxchan, $line);   # adjust its hop count by node name
1055                 if ($routeit) {
1056                         $dxchan->send($routeit) unless $dxchan == $main::me;
1057                 }
1058         } else {
1059                 dbg("PCPROT: No route available, dropped") if isdbg('chanerr');
1060         }
1061 }
1062
1063 #
1064 # obtain the hops from the list for this callsign and pc no
1065 #
1066
1067 sub get_hops
1068 {
1069         my $pcno = shift;
1070         my $hops = $DXProt::hopcount{$pcno};
1071         $hops = $DXProt::def_hopcount if !$hops;
1072         return "H$hops";
1073 }
1074
1075 #
1076 # adjust the hop count on a per node basis using the user loadable
1077 # hop table if available or else decrement an existing one
1078 #
1079
1080 sub adjust_hops
1081 {
1082         my $self = shift;
1083         my $s = shift;
1084         my $call = $self->{call};
1085         my $hops;
1086
1087         if (($hops) = $s =~ /\^H([-\d]+)\^?~?$/o) {
1088                 my ($pcno) = $s =~ /^PC(\d\d)/o;
1089                 confess "$call called adjust_hops with '$s'" unless $pcno;
1090                 my $ref = $nodehops{$call} if %nodehops;
1091                 if ($ref) {
1092                         my $newhops = $ref->{$pcno};
1093                         return "" if defined $newhops && $newhops == 0;
1094                         $newhops = $ref->{default} unless $newhops;
1095                         return "" if defined $newhops && $newhops == 0;
1096                         $newhops = $hops unless $newhops;
1097                         return "" unless $newhops > 0;
1098                         $s =~ s/\^H(\d+)(\^~?)$/\^H$newhops$2/ if $newhops != $hops;
1099                 } else {
1100                         return "" unless $hops > 0;
1101                 }
1102         }
1103         return $s;
1104 }
1105
1106 #
1107 # load hop tables
1108 #
1109 sub load_hops
1110 {
1111         my $self = shift;
1112         return $self->msg('lh1') unless -e "$main::data/hop_table.pl";
1113         do "$main::data/hop_table.pl";
1114         return $@ if $@;
1115         return ();
1116 }
1117
1118 sub process_rcmd
1119 {
1120         my ($self, $tonode, $fromnode, $user, $cmd) = @_;
1121
1122         if ($tonode eq $main::mycall) {
1123                 my $ref = DXUser::get_current($fromnode);
1124                 unless ($ref && UNIVERSAL::isa($ref, 'DXUser')) {
1125                         dbg("DXProt process_rcmd: user $fromnode isn't a reference (check user_asc and tell G1TLH)"); 
1126                         $self->send_rcmd_reply($main::mycall, $fromnode, $user, "sorry...!");
1127                         return;
1128                 }
1129                 Log('rcmd', 'in', ($ref->{priv}||0), $fromnode, $cmd, $user);
1130                 my $cref = Route::Node::get($fromnode);
1131                 unless ($cref && UNIVERSAL::isa($cref, 'Route')) {
1132                         dbg("DXProt process_rcmd: Route $fromnode isn't a reference (tell G1TLH)"); 
1133                         $self->send_rcmd_reply($main::mycall, $fromnode, $user, "sorry...!");
1134                         return;
1135                 }
1136                 if ($cmd !~ /^\s*rcmd/i && $ref->homenode && $cref->call eq $ref->homenode) { # not allowed to relay RCMDS!
1137                         if ($ref->{priv}) {             # you have to have SOME privilege, the commands have further filtering
1138                                 $self->{remotecmd} = 1; # for the benefit of any command that needs to know
1139                                 my $oldpriv = $self->{priv};
1140                                 $self->{priv} = 1; # set a maximum privilege 
1141
1142                                 # park homenode and user for any spawned command that run_cmd may do.
1143                                 $self->{_rcmd_user} = $user;
1144                                 $self->{_rcmd_fromnode} = $fromnode;
1145                                 my @in = (DXCommandmode::run_cmd($self, $cmd));
1146                                 delete $self->{_rcmd_fromnode};
1147                                 delete $self->{_rcmd_user};
1148                                 $self->{priv} = $oldpriv;
1149                                 $self->send_rcmd_reply($main::mycall, $fromnode, $user, @in);
1150                                 delete $self->{remotecmd};
1151                         } else {
1152                                 $self->send_rcmd_reply($main::mycall, $fromnode, $user, "sorry...!");
1153                         }
1154                 } else {
1155                         $self->send_rcmd_reply($main::mycall, $fromnode, $user, "your attempt is logged, Tut tut tut...!");
1156                 }
1157         } else {
1158                 my $ref = DXUser::get_current($tonode);
1159                 if ($ref && $ref->is_clx) {
1160                         $self->route($tonode, pc84($fromnode, $tonode, $user, $cmd));
1161                 } else {
1162                         $self->route($tonode, pc34($fromnode, $tonode, $cmd));
1163                 }
1164         }
1165 }
1166
1167
1168 sub send_rcmd_reply
1169 {
1170         my $self = shift;
1171         my $tonode = shift;
1172         my $fromnode = shift;
1173         my $user = shift;
1174         while (@_) {
1175                 my $line = shift;
1176                 $line =~ s/\s*$//;
1177                 Log('rcmd', 'out', $fromnode, $line, $user);
1178                 if ($self->is_clx) {
1179                         $self->send(pc85($main::mycall, $fromnode, $user, "$main::mycall:$line"));
1180                 } else {
1181                         $self->send(pc35($main::mycall, $fromnode, "$main::mycall:$line"));
1182                 }
1183         }
1184 }
1185
1186 # Punt off a long running command into a separate process - this will be caused by an rcmd from outside
1187 #
1188 # This is called from commands to run some potentially long running
1189 # function. The process forks and then runs the function and returns
1190 # the result back to the cmd. 
1191 #
1192 # NOTE: this merely forks the current process and then runs the cmd in that (current) context.
1193 #       IT DOES NOT START UP SOME NEW PROGRAM AND RELIES ON THE FACT THAT IT IS RUNNING DXSPIDER 
1194 #       THE CURRENT CONTEXT!!
1195
1196 # call: $self->spawn_cmd($original_cmd_line, \<function>, [cb => sub{...}], [prefix => "cmd> "], [progress => 0|1], [args => [...]]);
1197 sub spawn_cmd
1198 {
1199         my $self = shift;
1200         my $line = shift;
1201         my $cmdref = shift;
1202         my $call = $self->{call};
1203         my %args = @_;
1204         my @out;
1205         
1206         my $cb = delete $args{cb};
1207         my $prefix = delete $args{prefix};
1208         my $progress = delete $args{progress};
1209         my $args = delete $args{args} || [];
1210         my $t0 = [gettimeofday];
1211
1212         # remembered from process_cmd when spawn_cmd was called thru DXCommandmode::run_cmd which was called by process_rcmd
1213         my $fromnode = $self->{_rcmd_fromnode};
1214         my $user = $self->{_rcmd_user};
1215
1216         no strict 'refs';
1217                 
1218         my $fc = Mojo::IOLoop::Subprocess->new;
1219
1220         # just behave normally if something has set the "one-shot" _nospawn in the channel
1221         return ($cmdref->(@$args)) if $self->{_nospawn};
1222
1223         #       $fc->serializer(\&encode_json);
1224 #       $fc->deserializer(\&decode_json);
1225         $fc->run(
1226                          sub {
1227                                  my $subpro = shift;
1228                                  if (isdbg('chan')) {
1229                                          my $s = "line: $line";
1230                                          $s .= ", args: " . join(', ', @$args) if $args && @$args;
1231                                  }
1232
1233                                  my @res = $cmdref->(@$args);
1234 #                                diffms("by $call 1", $line, $t0, scalar @res) if isdbg('chan');
1235                                  return @res;
1236                          },
1237 #                        $args,
1238                          sub {
1239                                  my ($fc, $err, @res) = @_; 
1240                                  my $self = DXChannel::get($call);
1241                                  return unless $self;
1242
1243                                  if ($err) {
1244                                          my $s = "DXCommand::spawn_cmd: call $call error $err";
1245                                          dbg($s) if isdbg('chan');
1246                                          if ($fromnode && $user) {
1247                                                  $self->send_rcmd_reply($main::mycall, $fromnode, $user, $s);
1248                                          } else {
1249                                                  $self->send($s);
1250                                          }
1251                                          return;
1252                                  }
1253                                  if ($cb) {
1254                                          # transform output if required
1255                                          @res = $cb->($self, @res);
1256                                  }
1257                                  if (@res) {
1258                                          if ($fromnode && $user) {
1259                                                  $self->send_rcmd_reply($main::mycall, $fromnode, $user, @res);
1260                                          } else {
1261                                                  $self->send(@res);
1262                                          }
1263                                  }
1264                                  diffms("rcmd from $user on $call", $line, $t0, scalar @res) if isdbg('chan');
1265                          });
1266         
1267         return @out;
1268 }
1269
1270 sub process_rcmd_reply
1271 {
1272         my ($self, $tonode, $fromnode, $user, $line) = @_;
1273         if ($tonode eq $main::mycall) {
1274                 my $s = $rcmds{$fromnode};
1275                 if ($s) {
1276                         my $dxchan = DXChannel::get($s->{call});
1277                         my $ref = $user eq $tonode ? $dxchan : (DXChannel::get($user) || $dxchan);
1278                         $ref->send($line) if $ref;
1279                         delete $rcmds{$fromnode} if !$dxchan;
1280                 } else {
1281                         # send unsolicited ones to the sysop
1282                         my $dxchan = DXChannel::get($main::myalias);
1283                         $dxchan->send($line) if $dxchan;
1284                 }
1285         } else {
1286                 my $ref = DXUser::get_current($tonode);
1287                 if ($ref && $ref->is_clx) {
1288                         $self->route($tonode, pc85($fromnode, $tonode, $user, $line));
1289                 } else {
1290                         $self->route($tonode, pc35($fromnode, $tonode, $line));
1291                 }
1292         }
1293 }
1294
1295
1296
1297 # add a rcmd request to the rcmd queues
1298 sub addrcmd
1299 {
1300         my ($self, $to, $cmd) = @_;
1301
1302         my $r = {};
1303         $r->{call} = $self->{call};
1304         $r->{t} = $main::systime;
1305         $r->{cmd} = $cmd;
1306         $rcmds{$to} = $r;
1307
1308         my $ref = Route::Node::get($to);
1309         my $dxchan = $ref->dxchan;
1310         if ($dxchan && $dxchan->is_clx) {
1311                 route(undef, $to, pc84($main::mycall, $to, $self->{call}, $cmd));
1312         } else {
1313                 route(undef, $to, pc34($main::mycall, $to, $cmd));
1314         }
1315 }
1316
1317 sub disconnect
1318 {
1319         my $self = shift;
1320         my $pc39flag = shift || 0;
1321         my $call = $self->call;
1322
1323         return if $self->{disconnecting}++;
1324
1325         unless ($pc39flag == 1) {
1326                 $self->send_now("D", DXProt::pc39($main::mycall, $self->msg('disc1', "System Op")));
1327         }
1328
1329         # get rid of any PC16/17/19
1330         eph_del_regex("^PC1[679]*$call");
1331
1332         # do routing stuff, remove me from routing table
1333         my $node = Route::Node::get($call);
1334
1335         Route::delete_interface($call);
1336
1337         # unbusy and stop and outgoing mail
1338         my $mref = DXMsg::get_busy($call);
1339         $mref->stop_msg($call) if $mref;
1340
1341         # remove outstanding pings
1342         delete $pings{$call};
1343
1344         # I was the last node visited
1345     $self->user->node($main::mycall);
1346
1347         # send info to all logged in thingies
1348         $self->tell_login('logoutn');
1349
1350         Log('DXProt', $call . " Disconnected");
1351
1352         $self->SUPER::disconnect;
1353
1354         # here we determine what needs to go out of the routing table
1355         my @rout;
1356         if ($node && $pc39flag != 2) {
1357                 dbg('%Route::Node::List = ' . join(',', sort keys %Route::Node::list)) if isdbg('routedisc');
1358
1359                 @rout = $node->del($main::routeroot);
1360
1361                 dbg('@rout = ' . join(',', sort map {$_->call} @rout)) if isdbg('routedisc');
1362
1363                 # now we need to see what can't be routed anymore and came
1364                 # in via this node (probably).
1365                 my $n = 0;
1366                 while ($n != @rout) {
1367                         $n = @rout;
1368                         for (Route::Node::get_all()) {
1369                                 unless ($_->dxchan) {
1370                                         push @rout, $_->delete;
1371                                 }
1372                         }
1373                         dbg('@rout = ' . join(',', sort map {$_->call} @rout)) if isdbg('routedisc');
1374                 }
1375
1376                 dbg('%Route::Node::List = ' . join(',', sort keys %Route::Node::list)) if isdbg('routedisc');
1377
1378                 # and all my ephemera as well
1379                 for (@rout) {
1380                         my $c = $_->call;
1381                         eph_del_regex("^PC1[679].*$c");
1382                 }
1383         }
1384
1385         # broadcast to all other nodes that all the nodes connected to via me are gone
1386         unless ($pc39flag == 2)  {
1387                 $self->route_pc21($main::mycall, undef, @rout) if @rout;
1388                 $self->route_pc92d($main::mycall, undef, $main::routeroot, $node) if $node;
1389         }
1390 }
1391
1392
1393 #
1394 # send a talk message to this thingy
1395 #
1396 sub talk
1397 {
1398         my ($self, $from, $to, $via, $line, $origin) = @_;
1399
1400         if ($self->{do_pc9x}) {
1401                 $self->send(pc93($to, $from, $via, $line));
1402         } else {
1403                 $self->send(pc10($from, $to, $via, $line, $origin));
1404         }
1405         Log('talk', $to, $from, '>' . ($via || $origin || $self->call), $line) unless $origin && $origin ne $main::mycall;
1406 }
1407
1408 # send it if it isn't the except list and isn't isolated and still has a hop count
1409 # taking into account filtering and so on
1410
1411 sub send_route
1412 {
1413         my $self = shift;
1414         my $origin = shift;
1415         my $generate = shift;
1416         my $no = shift;     # the no of things to filter on
1417         my $routeit;
1418         my ($filter, $hops);
1419         my @rin;
1420
1421         for (; @_ && $no; $no--) {
1422                 my $r = shift;
1423
1424                 # don't send messages with $self's call in back to them
1425                 if ($r->call eq $self->{call}) {
1426                         dbg("PCPROT: trying to send $self->{call} back itself") if isdbg('chanerr');
1427                         next;
1428                 }
1429
1430                 if (!$self->{isolate} && $self->{routefilter}) {
1431                         $filter = undef;
1432                         if ($r) {
1433                                 ($filter, $hops) = $self->{routefilter}->it($self->{call}, $self->{dxcc}, $self->{itu}, $self->{cq}, $r->call, $r->dxcc, $r->itu, $r->cq, $self->{state}, $r->{state});
1434                                 if ($filter) {
1435                                         push @rin, $r;
1436                                 } else {
1437                                         dbg("PCPROT: $self->{call}/" . $r->call . " rejected by output filter") if isdbg('filter');
1438                                 }
1439                         } else {
1440                                 dbg("was sent a null value") if isdbg('chanerr');
1441                         }
1442                 } else {
1443                         push @rin, $r unless $self->{isolate} && $r->call ne $main::mycall;
1444                 }
1445         }
1446         if (@rin) {
1447                 foreach my $line (&$generate(@rin, @_)) {
1448                         if ($hops) {
1449                                 $routeit = $line;
1450                                 $routeit =~ s/\^H\d+\^\~$/\^H$hops\^\~/;
1451                         } else {
1452                                 $routeit = adjust_hops($self, $line);  # adjust its hop count by node name
1453                                 next unless $routeit;
1454                         }
1455
1456                         $self->send($routeit);
1457                 }
1458         }
1459 }
1460
1461 # broadcast everywhere
1462 sub broadcast_route
1463 {
1464         my $self = shift;
1465         my $origin = shift;
1466         my $generate = shift;
1467         my $line = shift;
1468         my @dxchan = DXChannel::get_all_nodes();
1469         my $dxchan;
1470
1471         if ($line) {
1472                 $line =~ /\^H(\d+)\^?\~?$/;
1473                 return unless $1 > 0;
1474         }
1475         unless ($self->{isolate}) {
1476                 foreach $dxchan (@dxchan) {
1477                         next if $dxchan == $self || $dxchan == $main::me;
1478                         next if $origin eq $dxchan->{call};     # don't route some from this call back again.
1479                         next unless $dxchan->isa('DXProt');
1480
1481                         $dxchan->send_route($origin, $generate, @_);
1482                 }
1483         }
1484 }
1485
1486 # broadcast to non-pc9x nodes
1487 sub broadcast_route_nopc9x
1488 {
1489         my $self = shift;
1490         my $origin = shift;
1491         my $generate = shift;
1492         my $line = shift;
1493         my @dxchan = DXChannel::get_all_nodes();
1494         my $dxchan;
1495
1496         if ($line) {
1497                 $line =~ /\^H(\d+)\^?\~?$/;
1498                 return unless $1 > 0;
1499         }
1500         unless ($self->{isolate}) {
1501                 foreach $dxchan (@dxchan) {
1502                         next if $dxchan == $self || $dxchan == $main::me;
1503                         next if $origin eq $dxchan->{call};     # don't route some from this call back again.
1504                         next unless $dxchan->isa('DXProt');
1505                         next if $dxchan->{do_pc9x};
1506                         if ($generate == \&pc16 || $generate==\&pc17) {
1507                                 next unless $dxchan->user->wantsendpc16;
1508                         }
1509                         $dxchan->send_route($origin, $generate, @_);
1510                 }
1511         }
1512 }
1513
1514 # this is only used for next door nodes on init
1515 sub send_route_pc92
1516 {
1517         my $self = shift;
1518
1519         return unless $self->{do_pc9x};
1520
1521         my $origin = shift;
1522         my $generate = shift;
1523         my $no = shift;     # the no of things to filter on
1524         my $line;
1525
1526         $line = &$generate(@_);
1527         $self->send($line);
1528 }
1529
1530 # broadcast only to pc9x nodes
1531 sub broadcast_route_pc9x
1532 {
1533         my $self = shift;
1534         my $origin = shift;
1535         my $generate = shift;
1536         my $line = shift;
1537         my $no = shift;
1538         my @dxchan = DXChannel::get_all_nodes();
1539         my $dxchan;
1540
1541         if ($origin eq $main::mycall && $generate && !$line) {
1542                 $line = &$generate(@_);
1543         }
1544
1545         $line =~ /\^H(\d+)\^\~?$/;
1546         unless ($1 > 0 && $self->{isolate}) {
1547                 foreach $dxchan (@dxchan) {
1548                         next if $dxchan == $self || $dxchan == $main::me;
1549                         next if $origin eq $dxchan->{call};     # don't route some from this call back again.
1550                         next unless $dxchan->isa('DXProt');
1551                         next unless $dxchan->{do_pc9x};
1552
1553                         $dxchan->send($line);
1554                 }
1555         }
1556 }
1557
1558 sub route_pc16
1559 {
1560         my $self = shift;
1561         return unless $self->user->wantpc16;
1562         my $origin = shift;
1563         my $line = shift;
1564         broadcast_route_nopc9x($self, $origin, \&pc16, $line, 1, @_);
1565 }
1566
1567 sub route_pc17
1568 {
1569         my $self = shift;
1570         return unless $self->user->wantpc16;
1571         my $origin = shift;
1572         my $line = shift;
1573         broadcast_route_nopc9x($self, $origin, \&pc17, $line, 1, @_);
1574 }
1575
1576 sub route_pc19
1577 {
1578         my $self = shift;
1579         my $origin = shift;
1580         my $line = shift;
1581         broadcast_route_nopc9x($self, $origin, \&pc19, $line, scalar @_, @_);
1582 }
1583
1584 sub route_pc21
1585 {
1586         my $self = shift;
1587         my $origin = shift;
1588         my $line = shift;
1589         broadcast_route_nopc9x($self, $origin, \&pc21, $line, scalar @_, @_);
1590 }
1591
1592 sub route_pc24
1593 {
1594         my $self = shift;
1595         my $origin = shift;
1596         my $line = shift;
1597         broadcast_route($self, $origin, \&pc24, $line, 1, @_);
1598 }
1599
1600 sub route_pc41
1601 {
1602         my $self = shift;
1603         my $origin = shift;
1604         my $line = shift;
1605         broadcast_route($self, $origin, \&pc41, $line, 1, @_);
1606 }
1607
1608 # this is probably obsolete now
1609 sub route_pc50
1610 {
1611         my $self = shift;
1612         my $origin = shift;
1613         my $line = shift;
1614
1615         broadcast_route($self, $origin, \&pc50, $line, 1, @_);
1616 }
1617
1618 sub route_pc92c
1619 {
1620         my $self = shift;
1621         my $origin = shift;
1622         my $line = shift;
1623         broadcast_route_pc9x($self, $origin, \&pc92c, $line, 1, @_);
1624 }
1625
1626 sub route_pc92a
1627 {
1628         my $self = shift;
1629         my $origin = shift;
1630         my $line = shift;
1631         broadcast_route_pc9x($self, $origin, \&pc92a, $line, 1, @_);
1632 }
1633
1634 sub route_pc92d
1635 {
1636         my $self = shift;
1637         my $origin = shift;
1638         my $line = shift;
1639         broadcast_route_pc9x($self, $origin, \&pc92d, $line, 1, @_);
1640 }
1641
1642 sub in_filter_route
1643 {
1644         my $self = shift;
1645         my $r = shift;
1646         my ($filter, $hops) = (1, 1);
1647
1648         if ($self->{inroutefilter}) {
1649                 ($filter, $hops) = $self->{inroutefilter}->it($self->{call}, $self->{dxcc}, $self->{itu}, $self->{cq}, $r->call, $r->dxcc, $r->itu, $r->cq, $self->state, $r->state);
1650                 dbg("PCPROT: $self->{call}/" . $r->call . ' rejected by in_filter_route') if !$filter && isdbg('chanerr');
1651         }
1652         return $filter;
1653 }
1654
1655 sub eph_dup
1656 {
1657         my $s = shift;
1658         my $t = shift || $eph_restime;
1659         my $r;
1660
1661         # chop the end off
1662         $s =~ s/\^H\d\d?\^?\~?$//;
1663         $r = 1 if exists $eph{$s};    # pump up the dup if it keeps circulating
1664         $eph{$s} = $main::systime + $t;
1665         dbg("PCPROT: emphemeral duplicate") if $r && isdbg('chanerr');
1666         return $r;
1667 }
1668
1669 sub eph_del_regex
1670 {
1671         my $regex = shift;
1672         my ($key, $val);
1673         while (($key, $val) = each %eph) {
1674                 if ($key =~ m{$regex}) {
1675                         delete $eph{$key};
1676                 }
1677         }
1678 }
1679
1680 sub eph_clean
1681 {
1682         my ($key, $val);
1683
1684         while (($key, $val) = each %eph) {
1685                 if ($main::systime >= $val) {
1686                         delete $eph{$key};
1687                 }
1688         }
1689 }
1690
1691 sub eph_list
1692 {
1693         my ($key, $val);
1694         my @out;
1695
1696         while (($key, $val) = each %eph) {
1697                 push @out, $key, $val;
1698         }
1699         return @out;
1700 }
1701
1702 sub run_cmd
1703 {
1704         goto &DXCommandmode::run_cmd;
1705 }
1706
1707
1708 # import any msgs in the chat directory
1709 # the messages are sent to the chat group which forms the
1710 # the first part of the name (eg: solar.1243.txt would be
1711 # sent to chat group SOLAR)
1712 #
1713 # Each message found is sent: one non-blank line to one chat
1714 # message. So 4 lines = 4 chat messages.
1715 #
1716 # The special name LOCAL is for local users ANN
1717 # The special name ALL is for ANN/FULL
1718 # The special name SYSOP is for ANN/SYSOP
1719 #
1720 sub import_chat
1721 {
1722         # are there any to do in this directory?
1723         return unless -d $chatimportfn;
1724         unless (opendir(DIR, $chatimportfn)) {
1725                 dbg("can\'t open $chatimportfn $!") if isdbg('msg');
1726                 Log('msg', "can\'t open $chatimportfn $!");
1727                 return;
1728         }
1729
1730         my @names = readdir(DIR);
1731         closedir(DIR);
1732         my $name;
1733         foreach $name (@names) {
1734                 next if $name =~ /^\./;
1735                 my $splitit = $name =~ /^split/;
1736                 my $fn = "$chatimportfn/$name";
1737                 next unless -f $fn;
1738                 unless (open(MSG, $fn)) {
1739                         dbg("can\'t open import file $fn $!") if isdbg('msg');
1740                         Log('msg', "can\'t open import file $fn $!");
1741                         unlink($fn);
1742                         next;
1743                 }
1744                 my @msg = map { s/\r?\n$//; $_ } <MSG>;
1745                 close(MSG);
1746                 unlink($fn);
1747
1748                 my @cat = split /\./, $name;
1749                 my $target = uc $cat[0];
1750
1751                 foreach my $text (@msg) {
1752                         next unless $text && $text !~ /^\s*#/;
1753                         if ($target eq 'ALL' || $target eq 'LOCAL' || $target eq 'SYSOP' || $target eq 'WX') {
1754                                 my $sysop = uc $target eq 'SYSOP' ? '*' : ' ';
1755                                 my $wx = uc $target eq 'WX' ? '1' : '0';
1756                                 my $via = $target;
1757                                 $via = '*' if $target eq 'ALL' || $target eq 'SYSOP';
1758                                 Log('ann', $target, $main::mycall, $text);
1759                                 $main::me->normal(DXProt::pc93($target, $main::mycall, $via, $text));
1760                         } else {
1761                                 DXCommandmode::send_chats($main::me, $target, $text);
1762                         }
1763                 }
1764         }
1765 }
1766
1767 # start a pc92 find operation
1768 sub start_pc92_find
1769 {
1770         my $dxchan = shift;
1771         my $target = shift;
1772         my $key = "$dxchan->{call}|$target";
1773         if ($pc92_find{$key}) {
1774
1775         }
1776 }
1777
1778 # function (not method) to handle pc92 find returns
1779 sub handle_pc92_find_reply
1780 {
1781         my ($dxchan, $node, $from, $target, $flag, $ms) = @_;
1782
1783         $dxchan->print_pc92_find_reply($node, $target, $flag, $ms) if $dxchan->can('print_pc92_find_return');
1784 }
1785
1786 sub clean_pc92_find
1787 {
1788
1789 }
1790
1791
1792
1793 1;
1794 __END__