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