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