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