4886a7ff3ce736ef8876b887c9526fc7be462d6b
[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 = 0;                              # 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         AnnTalk::add_anncache('ann', $target, $from, $text);
742
743         # send it if it isn't the except list and isn't isolated and still has a hop count
744         # taking into account filtering and so on
745         foreach $dxchan (@dxchan) {
746                 next if $dxchan == $main::me;
747                 next if $dxchan == $self && $self->is_node;
748                 next if $from_pc9x && $dxchan->{do_pc9x};
749                 next if $target eq 'LOCAL' && $dxchan->is_node;
750                 next if $dxchan->is_rbn;
751                 $dxchan->announce($line, $self->{isolate}, $to, $target, $text, @_, $self->{call},
752                                                   @a[0..2], @b[0..2]);
753         }
754 }
755
756 my $msgid = int rand(1000);
757
758 sub nextchatmsgid
759 {
760         $msgid++;
761         $msgid = 1 if $msgid > 999;
762         return $msgid;
763 }
764
765 # send a chat line
766 sub send_chat
767 {
768         my $self = shift;
769         my $from_pc9x = shift;
770         my $line = shift;
771         my @dxchan = DXChannel::get_all();
772         my $dxchan;
773         my $target = $_[3];
774         my $text = unpad($_[2]);
775         my $ak1a_line;
776         my $from = $_[0];
777
778         # munge the group and recast the line if required
779         if ($target =~ s/\.LST$//) {
780                 $ak1a_line = $line;
781         }
782
783         # obtain country codes etc
784         my @a = Prefix::cty_data($from);
785         my @b = Prefix::cty_data($_[4]);
786         if ($self->{inannfilter}) {
787                 my ($filter, $hops) =
788                         $self->{inannfilter}->it(@_, $self->{call},
789                                                                          @a[0..2],
790                                                                          @b[0..2], $a[3], $b[3]);
791                 unless ($filter) {
792                         dbg("PCPROT: Rejected by input announce filter") if isdbg('chanerr');
793                         return;
794                 }
795         }
796
797         if (AnnTalk::dup($from, $target, $_[2], $main::systime + $chatdupeage)) {
798                 my $dxchan = DXChannel::get($from);
799                 if ($self == $main::me && $dxchan && $dxchan->is_user) {
800                         if ($dxchan->priv < 5) {
801                                 $dxchan->send($dxchan->msg('dup'));
802                                 return;
803                         }
804                 } else {
805                         dbg("PCPROT: Duplicate Announce ignored") if isdbg('chanerr');
806                         return;
807                 }
808         }
809
810
811         Log('chat', $target, $from, $text);
812
813         # send it if it isn't the except list and isn't isolated and still has a hop count
814         # taking into account filtering and so on
815         foreach $dxchan (@dxchan) {
816                 if ($dxchan->is_node) {
817                         next if $dxchan == $main::me;
818                         next if $dxchan == $self;
819                         next if $from_pc9x && $dxchan->do_pc9x;
820                         next unless $dxchan->is_spider && $dxchan->do_pc9x;
821                         next if $target eq 'LOCAL';
822                 }
823                 next if $dxchan->is_rbn;
824
825                 $dxchan->chat($line, $self->{isolate}, $target, $_[1],
826                                           $text, @_, $self->{call}, @a[0..2], @b[0..2]);
827         }
828 }
829
830 sub announce
831 {
832         my $self = shift;
833         my $line = shift;
834         my $isolate = shift;
835         my $to = shift;
836         my $target = shift;
837         my $text = shift;
838         my ($filter, $hops);
839
840         if ($self->{annfilter}) {
841                 ($filter, $hops) = $self->{annfilter}->it(@_);
842                 return unless $filter;
843         }
844         send_prot_line($self, $filter, $hops, $isolate, $line) unless $_[1] eq $main::mycall;
845 }
846
847 sub chat
848 {
849         my $self = shift;
850         my $line = shift;
851         my $isolate = shift;
852         my $to = shift;
853         my $target = shift;
854         my $text = shift;
855         my ($filter, $hops);
856
857         if ($self->{annfilter}) {
858                 ($filter, $hops) = $self->{annfilter}->it(@_);
859                 return unless $filter;
860         }
861         if (($self->is_spider || $self->is_ak1a) && $_[1] ne $main::mycall) {
862                 send_prot_line($self, $filter, $hops, $isolate, $line);
863         }
864 }
865
866
867 sub send_local_config
868 {
869         my $self = shift;
870
871         dbg('DXProt::send_local_config') if isdbg('trace');
872
873         # send our nodes
874         my $node;
875         my @nodes;
876         my @localnodes;
877         my @remotenodes;
878
879         if ($self->{isolate}) {
880                 dbg("$self->{call} send_local_config: isolated");
881                 @localnodes = ( $main::routeroot );
882                 $self->send_route($main::mycall, \&pc19, 1, $main::routeroot);
883         } elsif ($self->{do_pc9x}) {
884                 dbg("$self->{call} send_local_config: doing pc9x");
885                 my $node = Route::Node::get($self->{call});
886 #               $self->send_last_pc92_config($main::routeroot);
887 #               $self->send(pc92a($main::routeroot, $node)) unless $main::routeroot->last_PC92C =~ /$self->{call}/;
888                 $self->send(pc92a($main::routeroot, $node));
889                 $self->send(pc92k($main::routeroot));
890         } else {
891                 # create a list of all the nodes that are not connected to this connection
892                 # and are not themselves isolated, this to make sure that isolated nodes
893                 # don't appear outside of this node
894
895                 dbg("$self->{call} send_local_config: traditional");
896
897                 # send locally connected nodes
898                 my @dxchan = grep { $_->call ne $main::mycall && $_ != $self && !$_->{isolate} } DXChannel::get_all_nodes();
899                 @localnodes = map { my $r = Route::Node::get($_->{call}); $r ? $r : () } @dxchan if @dxchan;
900                 $self->send_route($main::mycall, \&pc19, scalar(@localnodes)+1, $main::routeroot, @localnodes);
901
902                 my $node;
903                 my @rawintcalls = map { $_->nodes } @localnodes if @localnodes;
904                 my @intcalls;
905                 foreach $node (@rawintcalls) {
906                         push @intcalls, $node if grep $_ && $node != $_, @intcalls;
907                 }
908                 my $ref = Route::Node::get($self->{call});
909                 my @rnodes = $ref->nodes;
910                 foreach $node (@intcalls) {
911                         push @remotenodes, Route::Node::get($node) if grep $_ && $node != $_, @rnodes, @remotenodes;
912                 }
913                 $self->send_route($main::mycall, \&pc19, scalar(@remotenodes), @remotenodes);
914         }
915
916         # get all the users connected on the above nodes and send them out
917         unless ($self->{do_pc9x}) {
918                 foreach $node ($main::routeroot, @localnodes, @remotenodes) {
919                         if ($node) {
920                                 my @rout = map {my $r = Route::User::get($_); $r ? ($r) : ()} $node->users;
921                                 $self->send_route($main::mycall, \&pc16, 1, $node, @rout) if @rout && $self->user->wantsendpc16;
922                         } else {
923                                 dbg("sent a null value") if isdbg('chanerr');
924                         }
925                 }
926         }
927 }
928
929 sub gen_my_pc92_config
930 {
931         my $node = shift;
932
933         if ($node->{call} eq $main::mycall) {
934                 clear_pc92_changes();           # remove any slugged data, we are generating it as now
935                 my @dxchan = grep { $_->call ne $main::mycall && !$_->{isolate} } DXChannel::get_all();
936                 dbg("ROUTE: all dxchan: " . join(',', map{$_->{call}} @dxchan)) if isdbg('routelow');
937                 my @localnodes = map { my $r = Route::get($_->{call}); ($_->is_node || $_->is_user) && $r ? $r : () } @dxchan;
938                 dbg("ROUTE: localnodes: " . join(',', map{$_->{call}} @localnodes)) if isdbg('routelow');
939                 return pc92c($node, @localnodes);
940         } else {
941                 my @rout = map {my $r = Route::User::get($_); $r ? ($r) : ()} $node->users;
942                 return pc92c($node, @rout);
943         }
944 }
945
946 sub send_last_pc92_config
947 {
948         my $self = shift;
949         my $node = shift;
950         if (my $l = $node->last_PC92C) {
951                 $self->send($l);
952         } else {
953                 $self->send_pc92_config($node);
954         }
955 }
956
957 sub send_pc92_config
958 {
959         my $self = shift;
960         my $node = shift;
961
962         dbg('DXProt::send_pc92_config') if isdbg('trace');
963
964         $node->last_PC92C(gen_my_pc92_config($node));
965         $self->send($node->last_PC92C);
966 }
967
968 sub broadcast_pc92_update
969 {
970         my $self = shift;
971         my $call = shift;
972
973         dbg("ROUTE: broadcast_pc92_update $call") if isdbg('obscount');
974
975         my $nref = Route::Node::get($call);
976         unless ($nref) {
977                 cluck("ERROR: broadcast_pc92_update - Route::Node $call disappeared");
978                 $self->update_pc92_next;
979                 return;
980         }
981         my $l = $nref->last_PC92C(gen_my_pc92_config($nref));
982         $nref->lastid(last_pc9x_id());
983         $main::me->broadcast_route_pc9x($main::mycall, undef, $l, 0);
984         $self->update_pc92_next;
985 }
986
987 sub broadcast_pc92_keepalive
988 {
989         my $self = shift;
990         my $call = shift;
991
992         dbg("ROUTE: broadcast_pc92_keepalive $call") if isdbg('obscount');
993
994         my $nref = Route::Node::get($call);
995         unless ($nref) {
996                 cluck("ERROR: broadcast_pc92_keepalive - Route::Node $call disappeared");
997                 $self->update_pc92_keepalive;
998                 return;
999         }
1000         my $l = pc92k($nref);
1001         $nref->lastid(last_pc9x_id());
1002         $main::me->broadcast_route_pc9x($main::mycall, undef, $l, 0);
1003         $self->update_pc92_keepalive;
1004 }
1005
1006 sub time_out_pc92_routes
1007 {
1008         my @nodes = grep {$_->call ne $main::mycall && ($_->do_pc9x || $_->via_pc92)} Route::Node::get_all();
1009         my @rdel;
1010         foreach my $n (@nodes) {
1011                 my $o = $n->dec_obs;
1012                 if ($o <= 0) {
1013                         if (my $dxchan = DXChannel::get($n->call)) {
1014                                 dbg("ROUTE: disconnecting local pc92 $dxchan->{call} on obscount") if isdbg('obscount');
1015                                 $dxchan->disconnect;
1016                                 next;
1017                         }
1018                         my @parents = map {Route::Node::get($_)} $n->parents;
1019                         for (@parents) {
1020                                 if ($_) {
1021                                         dbg("ROUTE: deleting pc92 $_->{call} from $n->{call} on obscount")  if isdbg('obscount');
1022                                         push @rdel, $n->del($_);
1023                                 }
1024                         }
1025                 } else {
1026                         dbg("ROUTE: obscount on $n->{call} now $o") if isdbg('obscount');
1027                 }
1028         }
1029         for (@rdel) {
1030                 $main::me->route_pc21($main::mycall, undef, $_) if $_;
1031         }
1032 }
1033
1034 #
1035 # route a message down an appropriate interface for a callsign
1036 #
1037 # is called route(to, pcline);
1038 #
1039
1040 sub route
1041 {
1042         my ($self, $call, $line) = @_;
1043
1044         if (ref $self && $call eq $self->{call}) {
1045                 dbg("PCPROT: Trying to route back to source, dropped") if isdbg('chanerr');
1046                 return;
1047         }
1048
1049         # always send it down the local interface if available
1050         my $dxchan = DXChannel::get($call);
1051         if ($dxchan) {
1052                 dbg("route: $call -> $dxchan->{call} direct" ) if isdbg('route');
1053         } else {
1054                 my $cl = Route::get($call);
1055                 $dxchan = $cl->dxchan if $cl;
1056                 if (ref $dxchan) {
1057                         if (ref $self && $dxchan eq $self) {
1058                                 dbg("PCPROT: Trying to route back to source, dropped") if isdbg('chanerr');
1059                                 return;
1060                         }
1061                         dbg("route: $call -> $dxchan->{call} using normal route" ) if isdbg('route');
1062                 }
1063         }
1064
1065         if ($dxchan) {
1066                 my $routeit = adjust_hops($dxchan, $line);   # adjust its hop count by node name
1067                 if ($routeit) {
1068                         $dxchan->send($routeit) unless $dxchan == $main::me;
1069                 }
1070         } else {
1071                 dbg("PCPROT: No route available, dropped") if isdbg('chanerr');
1072         }
1073 }
1074
1075 #
1076 # obtain the hops from the list for this callsign and pc no
1077 #
1078
1079 sub get_hops
1080 {
1081         my $pcno = shift;
1082         my $hops = $DXProt::hopcount{$pcno};
1083         $hops = $DXProt::def_hopcount if !$hops;
1084         return "H$hops";
1085 }
1086
1087 #
1088 # adjust the hop count on a per node basis using the user loadable
1089 # hop table if available or else decrement an existing one
1090 #
1091
1092 sub adjust_hops
1093 {
1094         my $self = shift;
1095         my $s = shift;
1096         my $call = $self->{call};
1097         my $hops;
1098
1099         if (($hops) = $s =~ /\^H([-\d]+)\^?~?$/o) {
1100                 my ($pcno) = $s =~ /^PC(\d\d)/o;
1101                 confess "$call called adjust_hops with '$s'" unless $pcno;
1102                 my $ref = $nodehops{$call} if %nodehops;
1103                 if ($ref) {
1104                         my $newhops = $ref->{$pcno};
1105                         return "" if defined $newhops && $newhops == 0;
1106                         $newhops = $ref->{default} unless $newhops;
1107                         return "" if defined $newhops && $newhops == 0;
1108                         $newhops = $hops unless $newhops;
1109                         return "" unless $newhops > 0;
1110                         $s =~ s/\^H(\d+)(\^~?)$/\^H$newhops$2/ if $newhops != $hops;
1111                 } else {
1112                         return "" unless $hops > 0;
1113                 }
1114         }
1115         return $s;
1116 }
1117
1118 #
1119 # load hop tables
1120 #
1121 sub load_hops
1122 {
1123         my $self = shift;
1124         return $self->msg('lh1') unless -e "$main::data/hop_table.pl";
1125         do "$main::data/hop_table.pl";
1126         return $@ if $@;
1127         return ();
1128 }
1129
1130 sub process_rcmd
1131 {
1132         my ($self, $tonode, $fromnode, $user, $cmd) = @_;
1133
1134         if ($tonode eq $main::mycall) {
1135                 my $ref = DXUser::get_current($fromnode);
1136                 unless ($ref && UNIVERSAL::isa($ref, 'DXUser')) {
1137                         dbg("DXProt process_rcmd: user $fromnode isn't a reference (check user_asc and tell G1TLH)"); 
1138                         $self->send_rcmd_reply($main::mycall, $fromnode, $user, "sorry...!");
1139                         return;
1140                 }
1141                 Log('rcmd', 'in', ($ref->{priv}||0), $fromnode, $cmd, $user);
1142                 my $cref = Route::Node::get($fromnode);
1143                 unless ($cref && UNIVERSAL::isa($cref, 'Route')) {
1144                         dbg("DXProt process_rcmd: Route $fromnode isn't a reference (tell G1TLH)"); 
1145                         $self->send_rcmd_reply($main::mycall, $fromnode, $user, "sorry...!");
1146                         return;
1147                 }
1148                 if ($cmd !~ /^\s*rcmd/i && $ref->homenode && $cref->call eq $ref->homenode) { # not allowed to relay RCMDS!
1149                         if ($ref->{priv}) {             # you have to have SOME privilege, the commands have further filtering
1150                                 $self->{remotecmd} = 1; # for the benefit of any command that needs to know
1151                                 my $oldpriv = $self->{priv};
1152                                 $self->{priv} = 1; # set a maximum privilege 
1153
1154                                 # park homenode and user for any spawned command that run_cmd may do.
1155                                 $self->{_rcmd_user} = $user;
1156                                 $self->{_rcmd_fromnode} = $fromnode;
1157                                 my @in = (DXCommandmode::run_cmd($self, $cmd));
1158                                 delete $self->{_rcmd_fromnode};
1159                                 delete $self->{_rcmd_user};
1160                                 $self->{priv} = $oldpriv;
1161                                 $self->send_rcmd_reply($main::mycall, $fromnode, $user, @in);
1162                                 delete $self->{remotecmd};
1163                         } else {
1164                                 $self->send_rcmd_reply($main::mycall, $fromnode, $user, "sorry...!");
1165                         }
1166                 } else {
1167                         $self->send_rcmd_reply($main::mycall, $fromnode, $user, "your attempt is logged, Tut tut tut...!");
1168                 }
1169         } else {
1170                 my $ref = DXUser::get_current($tonode);
1171                 if ($ref && $ref->is_clx) {
1172                         $self->route($tonode, pc84($fromnode, $tonode, $user, $cmd));
1173                 } else {
1174                         $self->route($tonode, pc34($fromnode, $tonode, $cmd));
1175                 }
1176         }
1177 }
1178
1179
1180 sub send_rcmd_reply
1181 {
1182         my $self = shift;
1183         my $tonode = shift;
1184         my $fromnode = shift;
1185         my $user = shift;
1186         while (@_) {
1187                 my $line = shift;
1188                 $line =~ s/\s*$//;
1189                 Log('rcmd', 'out', $fromnode, $line, $user);
1190                 if ($self->is_clx) {
1191                         $self->send(pc85($main::mycall, $fromnode, $user, "$main::mycall:$line"));
1192                 } else {
1193                         $self->send(pc35($main::mycall, $fromnode, "$main::mycall:$line"));
1194                 }
1195         }
1196 }
1197
1198 # Punt off a long running command into a separate process - this will be caused by an rcmd from outside
1199 #
1200 # This is called from commands to run some potentially long running
1201 # function. The process forks and then runs the function and returns
1202 # the result back to the cmd. 
1203 #
1204 # NOTE: this merely forks the current process and then runs the cmd in that (current) context.
1205 #       IT DOES NOT START UP SOME NEW PROGRAM AND RELIES ON THE FACT THAT IT IS RUNNING DXSPIDER 
1206 #       THE CURRENT CONTEXT!!
1207
1208 # call: $self->spawn_cmd($original_cmd_line, \<function>, [cb => sub{...}], [prefix => "cmd> "], [progress => 0|1], [args => [...]]);
1209 sub spawn_cmd
1210 {
1211         my $self = shift;
1212         my $line = shift;
1213         my $cmdref = shift;
1214         my $call = $self->{call};
1215         my %args = @_;
1216         my @out;
1217         
1218         my $cb = delete $args{cb};
1219         my $prefix = delete $args{prefix};
1220         my $progress = delete $args{progress};
1221         my $args = delete $args{args} || [];
1222         my $t0 = [gettimeofday];
1223
1224         # remembered from process_cmd when spawn_cmd was called thru DXCommandmode::run_cmd which was called by process_rcmd
1225         my $fromnode = $self->{_rcmd_fromnode};
1226         my $user = $self->{_rcmd_user};
1227
1228         no strict 'refs';
1229                 
1230         my $fc = DXSubprocess->new;
1231
1232         # just behave normally if something has set the "one-shot" _nospawn in the channel
1233         if ($self->{_nospawn}) {
1234                 eval { @out = $cmdref->(@$args); };
1235                 if ($@) {
1236                         DXDebug::dbgprintring(25);
1237                         push @out, DXDebug::shortmess($@);
1238                 }
1239                 return @out;
1240         }
1241
1242         #       $fc->serializer(\&encode_json);
1243 #       $fc->deserializer(\&decode_json);
1244         $fc->run(
1245                          sub {
1246                                  my $subpro = shift;
1247                                  if (isdbg('progress')) {
1248                                          my $s = qq{line: "$line"};
1249                                          $s .= ", args: " . join(', ', map { defined $_ ? qq{'$_'} : q{'undef'} } @$args) if $args && @$args;
1250                                          dbg($s);
1251                                  }
1252                                  eval { @out = $cmdref->(@$args); };
1253                                  if ($@) {
1254                                          DXDebug::dbgprintring(25);
1255                                          push @out, DXDebug::shortmess($@);
1256                                  }
1257                                  return @out;
1258                          },
1259 #                        $args,
1260                          sub {
1261                                  my ($fc, $err, @res) = @_; 
1262                                  my $self = DXChannel::get($call);
1263                                  return unless $self;
1264
1265                                  if ($err) {
1266                                          my $s = "DXCommand::spawn_cmd: call $call error $err";
1267                                          dbg($s) if isdbg('chan');
1268                                          if ($fromnode && $user) {
1269                                                  $self->send_rcmd_reply($main::mycall, $fromnode, $user, $s);
1270                                          } else {
1271                                                  $self->send($s);
1272                                          }
1273                                          return;
1274                                  }
1275                                  if ($cb) {
1276                                          # transform output if required
1277                                          @res = $cb->($self, @res);
1278                                  }
1279                                  if (@res) {
1280                                          if ($fromnode && $user) {
1281                                                  $self->send_rcmd_reply($main::mycall, $fromnode, $user, @res);
1282                                          } else {
1283                                                  $self->send(@res);
1284                                          }
1285                                  }
1286                                  diffms("rcmd from $user on $call", $line, $t0, scalar @res) if isdbg('progress');
1287                          });
1288         
1289         return @out;
1290 }
1291
1292 sub process_rcmd_reply
1293 {
1294         my ($self, $tonode, $fromnode, $user, $line) = @_;
1295         if ($tonode eq $main::mycall) {
1296                 my $s = $rcmds{$fromnode};
1297                 if ($s) {
1298                         my $dxchan = DXChannel::get($s->{call});
1299                         my $ref = $user eq $tonode ? $dxchan : (DXChannel::get($user) || $dxchan);
1300                         $ref->send($line) if $ref;
1301                         delete $rcmds{$fromnode} if !$dxchan;
1302                 } else {
1303                         # send unsolicited ones to the sysop
1304                         my $dxchan = DXChannel::get($main::myalias);
1305                         $dxchan->send($line) if $dxchan;
1306                 }
1307         } else {
1308                 my $ref = DXUser::get_current($tonode);
1309                 if ($ref && $ref->is_clx) {
1310                         $self->route($tonode, pc85($fromnode, $tonode, $user, $line));
1311                 } else {
1312                         $self->route($tonode, pc35($fromnode, $tonode, $line));
1313                 }
1314         }
1315 }
1316
1317
1318
1319 # add a rcmd request to the rcmd queues
1320 sub addrcmd
1321 {
1322         my ($self, $to, $cmd) = @_;
1323
1324         my $r = {};
1325         $r->{call} = $self->{call};
1326         $r->{t} = $main::systime;
1327         $r->{cmd} = $cmd;
1328         $rcmds{$to} = $r;
1329
1330         my $ref = Route::Node::get($to);
1331         my $dxchan = $ref->dxchan;
1332         if ($dxchan && $dxchan->is_clx) {
1333                 route(undef, $to, pc84($main::mycall, $to, $self->{call}, $cmd));
1334         } else {
1335                 route(undef, $to, pc34($main::mycall, $to, $cmd));
1336         }
1337 }
1338
1339 sub disconnect
1340 {
1341         my $self = shift;
1342         my $pc39flag = shift || 0;
1343         my $call = $self->call;
1344
1345         return if $self->{disconnecting}++;
1346
1347         unless ($pc39flag == 1) {
1348                 $self->send_now("D", DXProt::pc39($main::mycall, $self->msg('disc1', "System Op")));
1349         }
1350
1351         # get rid of any PC16/17/19
1352         eph_del_regex("^PC1[679]*$call");
1353
1354         # do routing stuff, remove me from routing table
1355         my $node = Route::Node::get($call);
1356
1357         Route::delete_interface($call);
1358
1359         # unbusy and stop and outgoing mail
1360         my $mref = DXMsg::get_busy($call);
1361         $mref->stop_msg($call) if $mref;
1362
1363         # remove outstanding pings
1364         delete $pings{$call};
1365
1366         # I was the last node visited
1367     $self->user->node($main::mycall);
1368
1369         # send info to all logged in thingies
1370         $self->tell_login('logoutn');
1371
1372         Log('DXProt', $call . " Disconnected");
1373
1374         $self->SUPER::disconnect;
1375
1376         # here we determine what needs to go out of the routing table
1377         my @rout;
1378         if ($node && $pc39flag != 2) {
1379                 dbg('%Route::Node::List = ' . join(',', sort keys %Route::Node::list)) if isdbg('routedisc');
1380
1381                 @rout = $node->del($main::routeroot);
1382
1383                 dbg('@rout = ' . join(',', sort map {$_->call} @rout)) if isdbg('routedisc');
1384
1385                 # now we need to see what can't be routed anymore and came
1386                 # in via this node (probably).
1387                 my $n = 0;
1388                 while ($n != @rout) {
1389                         $n = @rout;
1390                         for (Route::Node::get_all()) {
1391                                 unless ($_->dxchan) {
1392                                         push @rout, $_->delete;
1393                                 }
1394                         }
1395                         dbg('@rout = ' . join(',', sort map {$_->call} @rout)) if isdbg('routedisc');
1396                 }
1397
1398                 dbg('%Route::Node::List = ' . join(',', sort keys %Route::Node::list)) if isdbg('routedisc');
1399
1400                 # and all my ephemera as well
1401                 for (@rout) {
1402                         my $c = $_->call;
1403                         eph_del_regex("^PC1[679].*$c");
1404                 }
1405         }
1406
1407         # broadcast to all other nodes that all the nodes connected to via me are gone
1408         unless ($pc39flag == 2)  {
1409                 $self->route_pc21($main::mycall, undef, @rout) if @rout;
1410                 $self->route_pc92d($main::mycall, undef, $main::routeroot, $node) if $node;
1411         }
1412 }
1413
1414
1415 #
1416 # send a talk message to this thingy
1417 #
1418 sub talk
1419 {
1420         my ($self, $from, $to, $via, $line, $origin) = @_;
1421
1422         if ($self->{do_pc9x}) {
1423                 $self->send(pc93($to, $from, $via, $line));
1424         } else {
1425                 $self->send(pc10($from, $to, $via, $line, $origin));
1426         }
1427         Log('talk', $to, $from, '>' . ($via || $origin || $self->call), $line) unless $origin && $origin ne $main::mycall;
1428 }
1429
1430 # send it if it isn't the except list and isn't isolated and still has a hop count
1431 # taking into account filtering and so on
1432
1433 sub send_route
1434 {
1435         my $self = shift;
1436         my $origin = shift;
1437         my $generate = shift;
1438         my $no = shift;     # the no of things to filter on
1439         my $routeit;
1440         my ($filter, $hops);
1441         my @rin;
1442
1443         for (; @_ && $no; $no--) {
1444                 my $r = shift;
1445
1446                 # don't send messages with $self's call in back to them
1447                 if ($r->call eq $self->{call}) {
1448                         dbg("PCPROT: trying to send $self->{call} back itself") if isdbg('chanerr');
1449                         next;
1450                 }
1451
1452                 if (!$self->{isolate} && $self->{routefilter}) {
1453                         $filter = undef;
1454                         if ($r) {
1455                                 ($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});
1456                                 if ($filter) {
1457                                         push @rin, $r;
1458                                 } else {
1459                                         dbg("PCPROT: $self->{call}/" . $r->call . " rejected by output filter") if isdbg('filter');
1460                                 }
1461                         } else {
1462                                 dbg("was sent a null value") if isdbg('chanerr');
1463                         }
1464                 } else {
1465                         push @rin, $r unless $self->{isolate} && $r->call ne $main::mycall;
1466                 }
1467         }
1468         if (@rin) {
1469                 foreach my $line (&$generate(@rin, @_)) {
1470                         if ($hops) {
1471                                 $routeit = $line;
1472                                 $routeit =~ s/\^H\d+\^\~$/\^H$hops\^\~/;
1473                         } else {
1474                                 $routeit = adjust_hops($self, $line);  # adjust its hop count by node name
1475                                 next unless $routeit;
1476                         }
1477
1478                         $self->send($routeit);
1479                 }
1480         }
1481 }
1482
1483 # broadcast everywhere
1484 sub broadcast_route
1485 {
1486         my $self = shift;
1487         my $origin = shift;
1488         my $generate = shift;
1489         my $line = shift;
1490         my @dxchan = DXChannel::get_all_nodes();
1491         my $dxchan;
1492
1493         if ($line) {
1494                 $line =~ /\^H(\d+)\^?\~?$/;
1495                 return unless $1 > 0;
1496         }
1497         unless ($self->{isolate}) {
1498                 foreach $dxchan (@dxchan) {
1499                         next if $dxchan == $self || $dxchan == $main::me;
1500                         next if $origin eq $dxchan->{call};     # don't route some from this call back again.
1501                         next unless $dxchan->isa('DXProt');
1502
1503                         $dxchan->send_route($origin, $generate, @_);
1504                 }
1505         }
1506 }
1507
1508 # broadcast to non-pc9x nodes
1509 sub broadcast_route_nopc9x
1510 {
1511         my $self = shift;
1512         my $origin = shift;
1513         my $generate = shift;
1514         my $line = shift;
1515         my @dxchan = DXChannel::get_all_nodes();
1516         my $dxchan;
1517
1518         if ($line) {
1519                 $line =~ /\^H(\d+)\^?\~?$/;
1520                 return unless $1 > 0;
1521         }
1522         unless ($self->{isolate}) {
1523                 foreach $dxchan (@dxchan) {
1524                         next if $dxchan == $self || $dxchan == $main::me;
1525                         next if $origin eq $dxchan->{call};     # don't route some from this call back again.
1526                         next unless $dxchan->isa('DXProt');
1527                         next if $dxchan->{do_pc9x};
1528                         if ($generate == \&pc16 || $generate==\&pc17) {
1529                                 next unless $dxchan->user->wantsendpc16;
1530                         }
1531                         $dxchan->send_route($origin, $generate, @_);
1532                 }
1533         }
1534 }
1535
1536 # this is only used for next door nodes on init
1537 sub send_route_pc92
1538 {
1539         my $self = shift;
1540
1541         return unless $self->{do_pc9x};
1542
1543         my $origin = shift;
1544         my $generate = shift;
1545         my $no = shift;     # the no of things to filter on
1546         my $line;
1547
1548         $line = &$generate(@_);
1549         $self->send($line);
1550 }
1551
1552 # broadcast only to pc9x nodes
1553 sub broadcast_route_pc9x
1554 {
1555         my $self = shift;
1556         my $origin = shift;
1557         my $generate = shift;
1558         my $line = shift;
1559         my $no = shift;
1560         my @dxchan = DXChannel::get_all_nodes();
1561         my $dxchan;
1562
1563         if ($origin eq $main::mycall && $generate && !$line) {
1564                 $line = &$generate(@_);
1565         }
1566
1567         $line =~ /\^H(\d+)\^\~?$/;
1568         unless ($1 > 0 && $self->{isolate}) {
1569                 foreach $dxchan (@dxchan) {
1570                         next if $dxchan == $self || $dxchan == $main::me;
1571                         next if $origin eq $dxchan->{call};     # don't route some from this call back again.
1572                         next unless $dxchan->isa('DXProt');
1573                         next unless $dxchan->{do_pc9x};
1574
1575                         $dxchan->send($line);
1576                 }
1577         }
1578 }
1579
1580 sub route_pc16
1581 {
1582         my $self = shift;
1583         return unless $self->user->wantpc16;
1584         my $origin = shift;
1585         my $line = shift;
1586         broadcast_route_nopc9x($self, $origin, \&pc16, $line, 1, @_);
1587 }
1588
1589 sub route_pc17
1590 {
1591         my $self = shift;
1592         return unless $self->user->wantpc16;
1593         my $origin = shift;
1594         my $line = shift;
1595         broadcast_route_nopc9x($self, $origin, \&pc17, $line, 1, @_);
1596 }
1597
1598 sub route_pc19
1599 {
1600         my $self = shift;
1601         my $origin = shift;
1602         my $line = shift;
1603         broadcast_route_nopc9x($self, $origin, \&pc19, $line, scalar @_, @_);
1604 }
1605
1606 sub route_pc21
1607 {
1608         my $self = shift;
1609         my $origin = shift;
1610         my $line = shift;
1611         broadcast_route_nopc9x($self, $origin, \&pc21, $line, scalar @_, @_);
1612 }
1613
1614 sub route_pc24
1615 {
1616         my $self = shift;
1617         my $origin = shift;
1618         my $line = shift;
1619         broadcast_route($self, $origin, \&pc24, $line, 1, @_);
1620 }
1621
1622 sub route_pc41
1623 {
1624         my $self = shift;
1625         my $origin = shift;
1626         my $line = shift;
1627         broadcast_route($self, $origin, \&pc41, $line, 1, @_);
1628 }
1629
1630 # this is probably obsolete now
1631 sub route_pc50
1632 {
1633         my $self = shift;
1634         my $origin = shift;
1635         my $line = shift;
1636
1637         broadcast_route($self, $origin, \&pc50, $line, 1, @_);
1638 }
1639
1640 sub route_pc92c
1641 {
1642         my $self = shift;
1643         my $origin = shift;
1644         my $line = shift;
1645         broadcast_route_pc9x($self, $origin, \&pc92c, $line, 1, @_);
1646 }
1647
1648 sub route_pc92a
1649 {
1650         my $self = shift;
1651         my $origin = shift;
1652         my $line = shift;
1653         broadcast_route_pc9x($self, $origin, \&pc92a, $line, 1, @_);
1654 }
1655
1656 sub route_pc92d
1657 {
1658         my $self = shift;
1659         my $origin = shift;
1660         my $line = shift;
1661         broadcast_route_pc9x($self, $origin, \&pc92d, $line, 1, @_);
1662 }
1663
1664 sub in_filter_route
1665 {
1666         my $self = shift;
1667         my $r = shift;
1668         my ($filter, $hops) = (1, 1);
1669
1670         if ($self->{inroutefilter}) {
1671                 ($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);
1672                 dbg("PCPROT: $self->{call}/" . $r->call . ' rejected by in_filter_route') if !$filter && isdbg('chanerr');
1673         }
1674         return $filter;
1675 }
1676
1677 sub eph_dup
1678 {
1679         my $s = shift;
1680         my $t = shift || $eph_restime;
1681         my $r;
1682
1683         # chop the end off
1684         $s =~ s/\^H\d\d?\^?\~?$//;
1685         $r = 1 if exists $eph{$s};    # pump up the dup if it keeps circulating
1686         $eph{$s} = $main::systime + $t;
1687         dbg("PCPROT: emphemeral duplicate") if $r && isdbg('chanerr');
1688         return $r;
1689 }
1690
1691 sub eph_del_regex
1692 {
1693         my $regex = shift;
1694         my ($key, $val);
1695         while (($key, $val) = each %eph) {
1696                 if ($key =~ m{$regex}) {
1697                         delete $eph{$key};
1698                 }
1699         }
1700 }
1701
1702 sub eph_clean
1703 {
1704         my ($key, $val);
1705
1706         while (($key, $val) = each %eph) {
1707                 if ($main::systime >= $val) {
1708                         delete $eph{$key};
1709                 }
1710         }
1711 }
1712
1713 sub eph_list
1714 {
1715         my ($key, $val);
1716         my @out;
1717
1718         while (($key, $val) = each %eph) {
1719                 push @out, $key, $val;
1720         }
1721         return @out;
1722 }
1723
1724 sub run_cmd
1725 {
1726         goto &DXCommandmode::run_cmd;
1727 }
1728
1729
1730 # import any msgs in the chat directory
1731 # the messages are sent to the chat group which forms the
1732 # the first part of the name (eg: solar.1243.txt would be
1733 # sent to chat group SOLAR)
1734 #
1735 # Each message found is sent: one non-blank line to one chat
1736 # message. So 4 lines = 4 chat messages.
1737 #
1738 # The special name LOCAL is for local users ANN
1739 # The special name ALL is for ANN/FULL
1740 # The special name SYSOP is for ANN/SYSOP
1741 #
1742 sub import_chat
1743 {
1744         # are there any to do in this directory?
1745         return unless -d $chatimportfn;
1746         unless (opendir(DIR, $chatimportfn)) {
1747                 dbg("can\'t open $chatimportfn $!") if isdbg('msg');
1748                 Log('msg', "can\'t open $chatimportfn $!");
1749                 return;
1750         }
1751
1752         my @names = readdir(DIR);
1753         closedir(DIR);
1754         my $name;
1755         foreach $name (@names) {
1756                 next if $name =~ /^\./;
1757                 my $splitit = $name =~ /^split/;
1758                 my $fn = "$chatimportfn/$name";
1759                 next unless -f $fn;
1760                 unless (open(MSG, $fn)) {
1761                         dbg("can\'t open import file $fn $!") if isdbg('msg');
1762                         Log('msg', "can\'t open import file $fn $!");
1763                         unlink($fn);
1764                         next;
1765                 }
1766                 my @msg = map { s/\r?\n$//; $_ } <MSG>;
1767                 close(MSG);
1768                 unlink($fn);
1769
1770                 my @cat = split /\./, $name;
1771                 my $target = uc $cat[0];
1772
1773                 foreach my $text (@msg) {
1774                         next unless $text && $text !~ /^\s*#/;
1775                         if ($target eq 'ALL' || $target eq 'LOCAL' || $target eq 'SYSOP' || $target eq 'WX') {
1776                                 my $sysop = uc $target eq 'SYSOP' ? '*' : ' ';
1777                                 my $wx = uc $target eq 'WX' ? '1' : '0';
1778                                 my $via = $target;
1779                                 $via = '*' if $target eq 'ALL' || $target eq 'SYSOP';
1780                                 Log('ann', $target, $main::mycall, $text);
1781                                 AnnTalk::add_anncache('ann', $target, $main::mycall, $text);
1782                                 
1783                                 $main::me->normal(DXProt::pc93($target, $main::mycall, $via, $text));
1784                         } else {
1785                                 DXCommandmode::send_chats($main::me, $target, $text);
1786                         }
1787                 }
1788         }
1789 }
1790
1791 # start a pc92 find operation
1792 sub start_pc92_find
1793 {
1794         my $dxchan = shift;
1795         my $target = shift;
1796         my $key = "$dxchan->{call}|$target";
1797         if ($pc92_find{$key}) {
1798
1799         }
1800 }
1801
1802 # function (not method) to handle pc92 find returns
1803 sub handle_pc92_find_reply
1804 {
1805         my ($dxchan, $node, $from, $target, $flag, $ms) = @_;
1806
1807         $dxchan->print_pc92_find_reply($node, $target, $flag, $ms) if $dxchan->can('print_pc92_find_return');
1808 }
1809
1810 sub clean_pc92_find
1811 {
1812
1813 }
1814
1815
1816
1817 1;
1818 __END__