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