add RBN filtering
[spider.git] / perl / DXCommandmode.pm
1 #!/usr/bin/perl
2 #
3 # This module impliments the user facing command mode for a dx cluster
4 #
5 # Copyright (c) 1998 Dirk Koopman G1TLH
6 #
7 #
8
9
10 package DXCommandmode;
11
12 #use POSIX;
13
14 @ISA = qw(DXChannel);
15
16 use 5.10.1;
17
18 use POSIX qw(:math_h);
19 use DXUtil;
20 use DXChannel;
21 use DXUser;
22 use DXVars;
23 use DXDebug;
24 use DXM;
25 use DXLog;
26 use DXLogPrint;
27 use DXBearing;
28 use CmdAlias;
29 use Filter;
30 use Minimuf;
31 use DXDb;
32 use AnnTalk;
33 use WCY;
34 use Sun;
35 use Internet;
36 use Script;
37 use QSL;
38 use DB_File;
39 use VE7CC;
40 use DXXml;
41 use AsyncMsg;
42 use JSON;
43 use Time::HiRes qw(gettimeofday tv_interval);
44
45 use Mojo::IOLoop;
46 use DXSubprocess;
47 use Mojo::UserAgent;
48
49 use strict;
50 use vars qw(%Cache %cmd_cache $errstr %aliases $scriptbase %nothereslug
51         $maxbadcount $msgpolltime $default_pagelth $cmdimportdir $users $maxusers);
52
53 %Cache = ();                                    # cache of dynamically loaded routine's mod times
54 %cmd_cache = ();                                # cache of short names
55 $errstr = ();                                   # error string from eval
56 %aliases = ();                                  # aliases for (parts of) commands
57 $scriptbase = "$main::root/scripts"; # the place where all users start scripts go
58 $maxbadcount = 3;                               # no of bad words allowed before disconnection
59 $msgpolltime = 3600;                    # the time between polls for new messages 
60 $cmdimportdir = "$main::root/cmd_import"; # the base directory for importing command scripts 
61                                           # this does not exist as default, you need to create it manually
62 $users = 0;                                       # no of users on this node currently
63 $maxusers = 0;                            # max no users on this node for this run
64
65 #
66 # obtain a new connection this is derived from dxchannel
67 #
68
69 sub new 
70 {
71         my $self = DXChannel::alloc(@_);
72
73         # routing, this must go out here to prevent race condx
74         my $pkg = shift;
75         my $call = shift;
76 #       my @rout = $main::routeroot->add_user($call, Route::here(1));
77         DXProt::_add_thingy($main::routeroot, [$call, 0, 0, 1, undef, undef, $self->hostname], );
78
79         # ALWAYS output the user
80         my $ref = Route::User::get($call);
81         if ($ref) {
82                 $main::me->route_pc16($main::mycall, undef, $main::routeroot, $ref);
83                 $main::me->route_pc92a($main::mycall, undef, $main::routeroot, $ref) unless $DXProt::pc92_slug_changes;
84         }
85
86         return $self;
87 }
88
89 # this is how a a connection starts, you get a hello message and the motd with
90 # possibly some other messages asking you to set various things up if you are
91 # new (or nearly new and slacking) user.
92
93 sub start
94
95         my ($self, $line, $sort) = @_;
96         my $user = $self->{user};
97         my $call = $self->{call};
98         my $name = $user->{name};
99         
100         # log it
101         my $host = $self->{conn}->peerhost;
102         $host ||= "AGW Port #$self->{conn}->{agwport}" if exists $self->{conn}->{agwport};
103         $host ||= "unknown";
104         $self->{hostname} = $host;
105
106         $self->{name} = $name ? $name : $call;
107         $self->send($self->msg('l2',$self->{name}));
108         $self->state('prompt');         # a bit of room for further expansion, passwords etc
109         $self->{priv} = $user->priv || 0;
110         $self->{lang} = $user->lang || $main::lang || 'en';
111         my $pagelth = $user->pagelth;
112         $pagelth = $default_pagelth unless defined $pagelth;
113         $self->{pagelth} = $pagelth;
114         ($self->{width}) = $line =~ /width=(\d+)/; $line =~ s/\s*width=\d+\s*//;
115         if ($line =~ /host=/) {
116                 my ($h) = $line =~ /host=(\d+\.\d+\.\d+\.\d+)/;
117                 $line =~ s/\s*host=\d+\.\d+\.\d+\.\d+// if $h;
118                 unless ($h) {
119                         ($h) = $line =~ /host=([\da..fA..F:]+)/;
120                         $line =~ s/\s*host=[\da..fA..F:]+// if $h;
121                 }
122                 $self->{hostname} = $h if $h;
123         }
124         $self->{width} = 80 unless $self->{width} && $self->{width} > 80;
125         $self->{consort} = $line;       # save the connection type
126
127         LogDbg('DXCommand', "$call connected from $self->{hostname}");
128
129         # set some necessary flags on the user if they are connecting
130         $self->{beep} = $user->wantbeep;
131         $self->{ann} = $user->wantann;
132         $self->{wwv} = $user->wantwwv;
133         $self->{wcy} = $user->wantwcy;
134         $self->{talk} = $user->wanttalk;
135         $self->{wx} = $user->wantwx;
136         $self->{dx} = $user->wantdx;
137         $self->{logininfo} = $user->wantlogininfo;
138         $self->{ann_talk} = $user->wantann_talk;
139         $self->{here} = 1;
140         $self->{prompt} = $user->prompt if $user->prompt;
141         $self->{lastmsgpoll} = 0;
142
143         # sort out new dx spot stuff
144         $user->wantdxcq(0) unless defined $user->{wantdxcq};
145         $user->wantdxitu(0) unless defined $user->{wantdxitu};  
146         $user->wantusstate(0) unless defined $user->{wantusstate};
147
148         # sort out registration
149         if ($main::reqreg == 1) {
150                 $self->{registered} = $user->registered;
151         } elsif ($main::reqreg == 2) {
152                 $self->{registered} = !$user->registered;
153         } else {
154                 $self->{registered} = 1;
155         }
156
157         # send the relevant MOTD
158         $self->send_motd;
159
160         # sort out privilege reduction
161         $self->{priv} = 0 unless $self->{hostname} eq '127.0.0.1' || $self->{hostname} eq '::1' || $self->conn->{usedpasswd};
162
163         # get the filters
164         my $nossid = $call;
165         $nossid =~ s/-\d+$//;
166         
167         $self->{spotsfilter} = Filter::read_in('spots', $call, 0) 
168                 || Filter::read_in('spots', $nossid, 0)
169                         || Filter::read_in('spots', 'user_default', 0);
170         $self->{wwvfilter} = Filter::read_in('wwv', $call, 0) 
171                 || Filter::read_in('wwv', $nossid, 0) 
172                         || Filter::read_in('wwv', 'user_default', 0);
173         $self->{wcyfilter} = Filter::read_in('wcy', $call, 0) 
174                 || Filter::read_in('wcy', $nossid, 0) 
175                         || Filter::read_in('wcy', 'user_default', 0);
176         $self->{annfilter} = Filter::read_in('ann', $call, 0) 
177                 || Filter::read_in('ann', $nossid, 0) 
178                         || Filter::read_in('ann', 'user_default', 0) ;
179         $self->{rbnfilter} = Filter::read_in('rbn', $call, 0) 
180                 || Filter::read_in('rbn', $nossid, 0)
181                         || Filter::read_in('rbn', 'user_default', 0);
182
183         # clean up qra locators
184         my $qra = $user->qra;
185         $qra = undef if ($qra && !DXBearing::is_qra($qra));
186         unless ($qra) {
187                 my $lat = $user->lat;
188                 my $long = $user->long;
189                 $user->qra(DXBearing::lltoqra($lat, $long)) if (defined $lat && defined $long);  
190         }
191
192         # decide on echo
193         my $echo = $user->wantecho;
194         unless ($echo) {
195                 $self->send_now('E', "0");
196                 $self->send($self->msg('echow'));
197                 $self->conn->echo($echo) if $self->conn->can('echo');
198         }
199         
200         $self->tell_login('loginu');
201         $self->tell_buddies('loginb');
202         
203         # do we need to send a forward/opernam?
204         my $lastoper = $user->lastoper || 0;
205         my $homenode = $user->homenode || ""; 
206         if ($homenode eq $main::mycall && $main::systime >= $lastoper + $DXUser::lastoperinterval) {
207                 run_cmd($main::me, "forward/opernam $call");
208                 $user->lastoper($main::systime + ((int rand(10)) * 86400));
209         }
210
211         # run a script send the output to the punter
212         my $script = new Script(lc $call) || new Script('user_default');
213         $script->run($self) if $script;
214
215         # send cluster info
216         $self->send($self->run_cmd("show/cluster"));
217
218         # send prompts for qth, name and things
219         $self->send($self->msg('namee1')) if !$user->name;
220         $self->send($self->msg('qthe1')) if !$user->qth;
221         $self->send($self->msg('qll')) if !$user->qra || (!$user->lat && !$user->long);
222         $self->send($self->msg('hnodee1')) if !$user->qth;
223         $self->send($self->msg('m9')) if DXMsg::for_me($call);
224
225         # send out any buddy messages for other people that are online
226         foreach my $call (@{$user->buddies}) {
227                 my $ref = Route::User::get($call);
228                 if ($ref) {
229                         foreach my $node ($ref->parents) {
230                                 $self->send($self->msg($node eq $main::mycall ? 'loginb' : 'loginbn', $call, $node));
231                         } 
232                 }
233         }
234
235         $self->lastmsgpoll($main::systime);
236         $self->prompt;
237 }
238
239 #
240 # This is the normal command prompt driver
241 #
242
243 sub normal
244 {
245         my $self = shift;
246         my $cmdline = shift;
247         my @ans;
248
249         # save this for them's that need it
250         my $rawline = $cmdline;
251         
252         # remove leading and trailing spaces
253         $cmdline =~ s/^\s*(.*)\s*$/$1/;
254         
255         if ($self->{state} eq 'page') {
256                 my $i = $self->{pagelth};
257                 my $ref = $self->{pagedata};
258                 my $tot = @$ref;
259                 
260                 # abort if we get a line starting in with a
261                 if ($cmdline =~ /^a/io) {
262                         undef $ref;
263                         $i = 0;
264                 }
265         
266                 # send a tranche of data
267                 while ($i-- > 0 && @$ref) {
268                         my $line = shift @$ref;
269                         $line =~ s/\s+$//o;     # why am having to do this? 
270                         $self->send($line);
271                 }
272                 
273                 # reset state if none or else chuck out an intermediate prompt
274                 if ($ref && @$ref) {
275                         $tot -= $self->{pagelth};
276                         $self->send($self->msg('page', $tot));
277                 } else {
278                         $self->state('prompt');
279                 }
280         } elsif ($self->{state} eq 'sysop') {
281                 my $passwd = $self->{user}->passwd;
282                 if ($passwd) {
283                         my @pw = grep {$_ !~ /\s/} split //, $passwd;
284                         my @l = @{$self->{passwd}};
285                         my $str = "$pw[$l[0]].*$pw[$l[1]].*$pw[$l[2]].*$pw[$l[3]].*$pw[$l[4]]";
286                         if ($cmdline =~ /$str/) {
287                                 $self->{priv} = $self->{user}->priv;
288                         } else {
289                                 $self->send($self->msg('sorry'));
290                         }
291                 } else {
292                         $self->send($self->msg('sorry'));
293                 }
294                 $self->state('prompt');
295         } elsif ($self->{state} eq 'passwd') {
296                 my $passwd = $self->{user}->passwd;
297                 if ($passwd && $cmdline eq $passwd) {
298                         $self->send($self->msg('pw1'));
299                         $self->state('passwd1');
300                 } else {
301                         $self->conn->{echo} = $self->conn->{decho};
302                         delete $self->conn->{decho};
303                         $self->send($self->msg('sorry'));
304                         $self->state('prompt');
305                 }
306         } elsif ($self->{state} eq 'passwd1') {
307                 $self->{passwd} = $cmdline;
308                 $self->send($self->msg('pw2'));
309                 $self->state('passwd2');
310         } elsif ($self->{state} eq 'passwd2') {
311                 if ($cmdline eq $self->{passwd}) {
312                         $self->{user}->passwd($cmdline);
313                         $self->send($self->msg('pw3'));
314                 } else {
315                         $self->send($self->msg('pw4'));
316                 }
317                 $self->conn->{echo} = $self->conn->{decho};
318                 delete $self->conn->{decho};
319                 $self->state('prompt');
320         } elsif ($self->{state} eq 'talk' || $self->{state} eq 'chat') {
321                 if ($cmdline =~ m{^(?:/EX|/ABORT)}i) {
322                         for (@{$self->{talklist}}) {
323                                 if ($self->{state} eq 'talk') {
324                                         $self->send_talks($_,  $self->msg('talkend'));
325                                 } else {
326                                         $self->local_send('C', $self->msg('chatend', $_));
327                                 }
328                         }
329                         $self->state('prompt');
330                         delete $self->{talklist};
331                 } elsif ($cmdline =~ m|^/+\w+|) {
332                         $cmdline =~ s|^/||;
333                         my $sendit = $cmdline =~ s|^/+||;
334                         my @in = $self->run_cmd($cmdline);
335                         $self->send_ans(@in);
336                         if ($sendit && $self->{talklist} && @{$self->{talklist}}) {
337                                 foreach my $l (@in) {
338                                         my @bad;
339                                         if (@bad = BadWords::check($l)) {
340                                                 $self->badcount(($self->badcount||0) + @bad);
341                                                 LogDbg('DXCommand', "$self->{call} swore: $l with words:" . join(',', @bad) . ")");
342                                         } else {
343                                                 for (@{$self->{talklist}}) {
344                                                         if ($self->{state} eq 'talk') {
345                                                                 $self->send_talks($_, $l);
346                                                         } else {
347                                                                 send_chats($self, $_, $l)
348                                                         }
349                                                 }
350                                         }
351                                 }
352                         }
353                         $self->send($self->{state} eq 'talk' ? $self->talk_prompt : $self->chat_prompt);
354                 } elsif ($self->{talklist} && @{$self->{talklist}}) {
355                         # send what has been said to whoever is in this person's talk list
356                         my @bad;
357                         if (@bad = BadWords::check($cmdline)) {
358                                 $self->badcount(($self->badcount||0) + @bad);
359                                 LogDbg('DXCommand', "$self->{call} swore: $cmdline with words:" . join(',', @bad) . ")");
360                         } else {
361                                 for (@{$self->{talklist}}) {
362                                         if ($self->{state} eq 'talk') {
363                                                 $self->send_talks($_, $rawline);
364                                         } else {
365                                                 send_chats($self, $_, $rawline);
366                                         }
367                                 }
368                         }
369                         $self->send($self->talk_prompt) if $self->{state} eq 'talk';
370                         $self->send($self->chat_prompt) if $self->{state} eq 'chat';
371                 } else {
372                         # for safety
373                         $self->state('prompt');
374                 }
375         } elsif (my $func = $self->{func}) {
376                 no strict 'refs';
377                 my @ans;
378                 if (ref $self->{edit}) {
379                         eval { @ans = $self->{edit}->$func($self, $rawline)};
380                 } else {
381                         eval {  @ans = &{$self->{func}}($self, $rawline) };
382                 }
383                 if ($@) {
384                         $self->send_ans("Syserr: on stored func $self->{func}", $@);
385                         delete $self->{func};
386                         $self->state('prompt');
387                         undef $@;
388                 }
389                 $self->send_ans(@ans);
390         } else {
391                 $self->send_ans(run_cmd($self, $cmdline));
392         } 
393
394         # check for excessive swearing
395         if ($self->{badcount} && $self->{badcount} >= $maxbadcount) {
396                 LogDbg('DXCommand', "$self->{call} logged out for excessive swearing");
397                 $self->disconnect;
398                 return;
399         }
400
401         # send a prompt only if we are in a prompt state
402         $self->prompt() if $self->{state} =~ /^prompt/o;
403 }
404
405 # send out the talk messages taking into account vias and connectivity
406 sub send_talks
407 {
408         my ($self, $ent, $line) = @_;
409         
410         my ($to, $via) = $ent =~ /(\S+)>(\S+)/;
411         $to = $ent unless $to;
412         my $call = $via && $via ne '*' ? $via : $to;
413         my $clref = Route::get($call);
414         my $dxchan = $clref->dxchan if $clref;
415         if ($dxchan) {
416                 $dxchan->talk($self->{call}, $to, undef, $line);
417         } else {
418                 $self->send($self->msg('disc2', $via ? $via : $to));
419                 my @l = grep { $_ ne $ent } @{$self->{talklist}};
420                 if (@l) {
421                         $self->{talklist} = \@l;
422                 } else {
423                         delete $self->{talklist};
424                         $self->state('prompt');
425                 }
426         }
427 }
428
429 sub send_chats
430 {
431         my $self = shift;
432         my $target = shift;
433         my $text = shift;
434
435         my $msgid = DXProt::nextchatmsgid();
436         $text = "#$msgid $text";
437         $main::me->normal(DXProt::pc93($target, $self->{call}, undef, $text));
438 }
439
440 sub special_prompt
441 {
442         my $self = shift;
443         my $prompt = shift;
444         my @call;
445         for (@{$self->{talklist}}) {
446                 my ($to, $via) = /(\S+)>(\S+)/;
447                 $to = $_ unless $to;
448                 push @call, $to;
449         }
450         return $self->msg($prompt, join(',', @call));
451 }
452
453 sub talk_prompt
454 {
455         my $self = shift;
456         return $self->special_prompt('talkprompt');
457 }
458
459 sub chat_prompt
460 {
461         my $self = shift;
462         return $self->special_prompt('chatprompt');
463 }
464
465 #
466 # send a load of stuff to a command user with page prompting
467 # and stuff
468 #
469
470 sub send_ans
471 {
472         my $self = shift;
473         
474         if ($self->{pagelth} && @_ > $self->{pagelth}) {
475                 my $i;
476                 for ($i = $self->{pagelth}; $i-- > 0; ) {
477                         my $line = shift @_;
478                         $line =~ s/\s+$//o;     # why am having to do this? 
479                         $self->send($line);
480                 }
481                 $self->{pagedata} =  [ @_ ];
482                 $self->state('page');
483                 $self->send($self->msg('page', scalar @_));
484         } else {
485                 for (@_) {
486                         if (defined $_) {
487                                 $self->send($_);
488                         } else {
489                                 $self->send('');
490                         }
491                 }
492         } 
493 }
494
495
496 # this is the thing that preps for running the command, it is done like this for the 
497 # benefit of remote command execution
498 #
499
500 sub run_cmd
501 {
502         my $self = shift;
503         my $user = $self->{user};
504         my $call = $self->{call};
505         my $cmdline = shift;
506         my @ans;
507         
508         return () if length $cmdline == 0;
509         
510         # split the command line up into parts, the first part is the command
511         my ($cmd, $args) = split /\s+/, $cmdline, 2;
512         $args = "" unless defined $args;
513                 
514         if ($cmd) {
515
516                 # check cmd
517                 if ($cmd =~ m|^/| || $cmd =~ m|[^-?\w/]|) {
518                         LogDbg('DXCommand', "cmd: invalid characters in '$cmd'");
519                         return $self->_error_out('e1');
520                 }
521
522                 # strip out // on command only
523                 $cmd =~ s|//|/|g;
524                                         
525                 my ($path, $fcmd);
526                         
527                 dbg("cmd: $cmd") if isdbg('command');
528                         
529                 # alias it if possible
530                 my $acmd = CmdAlias::get_cmd($cmd);
531                 if ($acmd) {
532                         ($cmd, $args) = split /\s+/, "$acmd $args", 2;
533                         $args = "" unless defined $args;
534                         dbg("cmd: aliased $cmd $args") if isdbg('command');
535                 }
536                         
537                 # first expand out the entry to a command
538                 ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
539                 ($path, $fcmd) = search($main::cmd, $cmd, "pl") unless $path && $fcmd;
540
541                 if ($path && $cmd) {
542                         dbg("cmd: path $cmd cmd: $fcmd") if isdbg('command');
543                         
544                         my $package = find_cmd_name($path, $fcmd);
545                         return ($@) if $@;
546                                 
547                         if ($package && $self->can("${package}::handle")) {
548                                 no strict 'refs';
549                                 dbg("cmd: package $package") if isdbg('command');
550                                 my $t0 = [gettimeofday];
551                                 eval { @ans = &{"${package}::handle"}($self, $args) };
552                                 if ($@) {
553                                         DXDebug::dbgprintring(25);
554                                         return (DXDebug::shortmess($@));
555                                 }
556                                 if (isdbg('progress')) {
557                                         my $msecs = _diffms($t0);
558                                         my $s = "CMD: '$cmd $args' by $call ip: $self->{hostname} ${msecs}mS";
559                                         dbg($s) if $cmd !~ /^(?:echo|blank)/ || isdbg('echo');     # cut down a bit on HRD and other clients' noise
560                                 }
561                         } else {
562                                 dbg("cmd: $package not present") if isdbg('command');
563                                 return $self->_error_out('e1');
564                         }
565                 } else {
566                         dbg("cmd: $cmd not found") if isdbg('command');
567                         return $self->_error_out('e1');
568                 }
569         }
570         
571         my $ok = shift @ans;
572         if ($ok) {
573                 delete $self->{errors};
574         } else {
575                 if (++$self->{errors} > $DXChannel::maxerrors) {
576                         $self->send($self->msg('e26'));
577                         $self->disconnect;
578                         return ();
579                 }
580         }
581         return map {s/([^\s])\s+$/$1/; $_} @ans;
582 }
583
584 #
585 # This is called from inside the main cluster processing loop and is used
586 # for despatching commands that are doing some long processing job
587 #
588 sub process
589 {
590         my $t = time;
591         my @dxchan = DXChannel::get_all();
592         my $dxchan;
593
594         $users = 0;
595         foreach $dxchan (@dxchan) {
596                 next unless $dxchan->is_user;  
597         
598                 # send a outstanding message prompt if required
599                 if ($t >= $dxchan->lastmsgpoll + $msgpolltime) {
600                         $dxchan->send($dxchan->msg('m9')) if DXMsg::for_me($dxchan->call);
601                         $dxchan->lastmsgpoll($t);
602                 }
603                 
604                 # send a prompt if no activity out on this channel
605                 if ($t >= $dxchan->t + $main::user_interval) {
606                         $dxchan->prompt() if $dxchan->{state} =~ /^prompt/o;
607                         $dxchan->t($t);
608                 }
609                 ++$users;
610                 $maxusers = $users if $users > $maxusers;
611         }
612
613         while (my ($k, $v) = each %nothereslug) {
614                 if ($main::systime >= $v + 300) {
615                         delete $nothereslug{$k};
616                 }
617         }
618
619         import_cmd();
620 }
621
622 #
623 # finish up a user context
624 #
625 sub disconnect
626 {
627         my $self = shift;
628         my $call = $self->call;
629
630         return if $self->{disconnecting}++;
631
632         delete $self->{senddbg};
633
634         my $uref = Route::User::get($call);
635         my @rout;
636         if ($uref) {
637 #               @rout = $main::routeroot->del_user($uref);
638                 @rout = DXProt::_del_thingy($main::routeroot, [$call, 0]);
639
640                 dbg("B/C PC17 on $main::mycall for: $call") if isdbg('route');
641
642                 # issue a pc17 to everybody interested
643                 $main::me->route_pc17($main::mycall, undef, $main::routeroot, $uref);
644                 $main::me->route_pc92d($main::mycall, undef, $main::routeroot, $uref) unless $DXProt::pc92_slug_changes;
645         } else {
646                 confess "trying to disconnect a non existant user $call";
647         }
648
649         # I was the last node visited
650     $self->user->node($main::mycall);
651                 
652         # send info to all logged in thingies
653         $self->tell_login('logoutu');
654         $self->tell_buddies('logoutb');
655
656         LogDbg('DXCommand', "$call disconnected");
657
658         $self->SUPER::disconnect;
659 }
660
661 #
662 # short cut to output a prompt
663 #
664
665 sub prompt
666 {
667         my $self = shift;
668
669         return if $self->{gtk};         # 'cos prompts are not a concept that applies here
670         
671         my $call = $self->call;
672         my $date = cldate($main::systime);
673         my $time = ztime($main::systime);
674         my $prompt = $self->{prompt} || $self->msg('pr');
675
676         $call = "($call)" unless $self->here;
677         $prompt =~ s/\%C/$call/g;
678         $prompt =~ s/\%D/$date/g;
679         $prompt =~ s/\%T/$time/g;
680         $prompt =~ s/\%M/$main::mycall/g;
681         
682         $self->send($prompt);
683 }
684
685 # broadcast a message to all users [except those mentioned after buffer]
686 sub broadcast
687 {
688         my $pkg = shift;                        # ignored
689         my $s = shift;                          # the line to be rebroadcast
690         
691     foreach my $dxchan (DXChannel::get_all()) {
692                 next unless $dxchan->is_user; # only interested in user channels  
693                 next if grep $dxchan == $_, @_;
694                 $dxchan->send($s);                      # send it
695         }
696 }
697
698 # gimme all the users
699 sub get_all
700 {
701         goto &DXChannel::get_all_users;
702 }
703
704 # run a script for this user
705 sub run_script
706 {
707         my $self = shift;
708         my $silent = shift || 0;
709         
710 }
711
712 #
713 # search for the command in the cache of short->long form commands
714 #
715
716 sub search
717 {
718         my ($path, $short_cmd, $suffix) = @_;
719         my ($apath, $acmd);
720         
721         # commands are lower case
722         $short_cmd = lc $short_cmd;
723         dbg("command: $path $short_cmd\n") if isdbg('command');
724
725         # do some checking for funny characters
726         return () if $short_cmd =~ /\/$/;
727
728         # return immediately if we have it
729         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
730         if ($apath && $acmd) {
731                 dbg("cached $short_cmd = ($apath, $acmd)\n") if isdbg('command');
732                 return ($apath, $acmd);
733         }
734         
735         # if not guess
736         my @parts = split '/', $short_cmd;
737         my $dirfn;
738         my $curdir = $path;
739         
740         while (my $p = shift @parts) {
741                 opendir(D, $curdir) or confess "can't open $curdir $!";
742                 my @ls = readdir D;
743                 closedir D;
744
745                 # if this isn't the last part
746                 if (@parts) {
747                         my $found;
748                         foreach my $l (sort @ls) {
749                                 next if $l =~ /^\./;
750                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
751                                         dbg("got dir: $curdir/$l\n") if isdbg('command');
752                                         $dirfn .= "$l/";
753                                         $curdir .= "/$l";
754                                         $found++;
755                                         last;
756                                 }
757                         }
758                         # only proceed if we find the directory asked for
759                         return () unless $found;
760                 } else {
761                         foreach my $l (sort @ls) {
762                                 next if $l =~ /^\./;
763                                 next unless $l =~ /\.$suffix$/;
764                                 if ($p eq substr($l, 0, length $p)) {
765                                         $l =~ s/\.$suffix$//;
766                                         $dirfn = "" unless $dirfn;
767                                         $cmd_cache{$short_cmd} = join(',', ($path, "$dirfn$l")); # cache it
768                                         dbg("got path: $path cmd: $dirfn$l\n") if isdbg('command');
769                                         return ($path, "$dirfn$l");
770                                 }
771                         }
772                 }
773         }
774
775         return ();  
776 }  
777
778 # clear the command name cache
779 sub clear_cmd_cache
780 {
781         no strict 'refs';
782         
783         for my $k (keys %Cache) {
784                 unless ($k =~ /cmd_cache/) {
785                         dbg("Undefining cmd $k") if isdbg('command');
786                         undef $DXCommandmode::{"${k}::"};
787                 }
788         }
789         %cmd_cache = ();
790         %Cache = ( cmd_clear_cmd_cache  => $Cache{cmd_clear_cmd_cache} );
791 }
792
793 #
794 # the persistant execution of things from the command directories
795 #
796 #
797 # This allows perl programs to call functions dynamically
798
799 # This has been nicked directly from the perlembed pages
800 #
801 #require Devel::Symdump;  
802
803 sub valid_package_name {
804         my $string = shift;
805         $string =~ s|([^A-Za-z0-9_/])|sprintf("_%2x",unpack("C",$1))|eg;
806         
807         $string =~ s|/|_|g;
808         return "cmd_$string";
809 }
810
811
812 # this bit of magic finds a command in the offered directory
813 sub find_cmd_name {
814         my $path = shift;
815         my $cmdname = shift;
816         my $package = valid_package_name($cmdname);
817         my $filename = "$path/$cmdname.pl";
818         my $mtime = -M $filename;
819         
820         # return if we can't find it
821         $errstr = undef;
822         unless (defined $mtime) {
823                 $errstr = DXM::msg('e1');
824                 return undef;
825         }
826         
827         if(exists $Cache{$package} && exists $Cache{$package}->{mtime} && $Cache{$package}->{mtime} <= $mtime) {
828                 #we have compiled this subroutine already,
829                 #it has not been updated on disk, nothing left to do
830                 #print STDERR "already compiled $package->handler\n";
831                 dbg("find_cmd_name: $package cached") if isdbg('command');
832         } else {
833
834                 my $sub = readfilestr($filename);
835                 unless ($sub) {
836                         $errstr = "Syserr: can't open '$filename' $!";
837                         return undef;
838                 };
839                 
840                 #wrap the code into a subroutine inside our unique package
841                 my $eval = qq(package DXCommandmode::$package; use 5.10.1; use POSIX qw{:math_h}; use DXLog; use DXDebug; use DXUser; use DXUtil; our \@ISA = qw{DXCommandmode}; );
842
843
844                 if ($sub =~ m|\s*sub\s+handle\n|) {
845                         $eval .= $sub;
846                 } else {
847                         $eval .= qq(sub handle { $sub });
848                 }
849                 
850                 if (isdbg('eval')) {
851                         my @list = split /\n/, $eval;
852                         my $line;
853                         for (@list) {
854                                 dbg($_ . "\n") if isdbg('eval');
855                         }
856                 }
857                 
858                 # get rid of any existing sub and try to compile the new one
859                 no strict 'refs';
860
861                 if (exists $Cache{$package}) {
862                         dbg("find_cmd_name: Redefining $package") if isdbg('command');
863                         undef $DXCommandmode::{"${package}::"};
864                         delete $Cache{$package};
865                 } else {
866                         dbg("find_cmd_name: Defining $package") if isdbg('command');
867                 }
868
869                 eval $eval;
870
871                 $Cache{$package} = {mtime => $mtime } unless $@;
872         }
873
874         return "DXCommandmode::$package";
875 }
876
877 sub send
878 {
879         my $self = shift;
880         if ($self->{gtk}) {
881                 for (@_) {
882                         $self->SUPER::send(dd(['cmd',$_]));
883                 }
884         } else {
885                 $self->SUPER::send(@_);
886         }
887 }
888
889 sub local_send
890 {
891         my ($self, $let, $buf) = @_;
892         if ($self->{state} eq 'prompt' || $self->{state} eq 'talk' || $self->{state} eq 'chat') {
893                 if ($self->{enhanced}) {
894                         $self->send_later($let, $buf);
895                 } else {
896                         $self->send($buf);
897                 }
898         } else {
899                 $self->delay($buf);
900         }
901 }
902
903 # send a talk message here
904 sub talk
905 {
906         my ($self, $from, $to, $via, $line, $onode) = @_;
907         $line =~ s/\\5E/\^/g;
908         if ($self->{talk}) {
909                 if ($self->{gtk}) {
910                         $self->local_send('T', dd(['talk',$to,$from,$via,$line]));
911                 } else {
912                         $self->local_send('T', "$to de $from: $line");
913                 }
914         }
915         Log('talk', $to, $from, '<' . ($onode || '*'), $line);
916         # send a 'not here' message if required
917         unless ($self->{here} && $from ne $to) {
918                 my $key = "$to$from";
919                 unless (exists $nothereslug{$key}) {
920                         my ($ref, $dxchan);
921                         if (($ref = Route::get($from)) && ($dxchan = $ref->dxchan)) {
922                                 my $name = $self->user->name || $to;
923                                 my $s = $self->user->nothere || $dxchan->msg('nothere', $name);
924                                 $nothereslug{$key} = $main::systime;
925                                 $dxchan->talk($to, $from, undef, $s);
926                         }
927                 }
928         }
929 }
930
931 # send an announce
932 sub announce
933 {
934         my $self = shift;
935         my $line = shift;
936         my $isolate = shift;
937         my $to = shift;
938         my $target = shift;
939         my $text = shift;
940         my ($filter, $hops);
941
942         if (!$self->{ann_talk} && $to ne $self->{call}) {
943                 my $call = AnnTalk::is_talk_candidate($_[0], $text);
944                 return if $call;
945         }
946
947         if ($self->{annfilter}) {
948                 ($filter, $hops) = $self->{annfilter}->it(@_ );
949                 return unless $filter;
950         }
951
952         unless ($self->{ann}) {
953                 return if $_[0] ne $main::myalias && $_[0] ne $main::mycall;
954         }
955         return if $target eq 'SYSOP' && $self->{priv} < 5;
956         my $buf;
957         if ($self->{gtk}) {
958                 $buf = dd(['ann', $to, $target, $text, @_])
959         } else {
960                 $buf = "$to$target de $_[0]: $text";
961                 $buf =~ s/\%5E/^/g;
962                 $buf .= "\a\a" if $self->{beep};
963         }
964         $self->local_send($target eq 'WX' ? 'W' : 'N', $buf);
965 }
966
967 # send a chat
968 sub chat
969 {
970         my $self = shift;
971         my $line = shift;
972         my $isolate = shift;
973         my $target = shift;
974         my $to = shift;
975         my $text = shift;
976         my ($filter, $hops);
977
978         return unless grep uc $_ eq $target, @{$self->{user}->{group}};
979         
980         $text =~ s/^\#\d+ //;
981         my $buf;
982         if ($self->{gtk}) {
983                 $buf = dd(['chat', $to, $target, $text, @_])
984         } else {
985                 $buf = "$target de $_[0]: $text";
986                 $buf =~ s/\%5E/^/g;
987                 $buf .= "\a\a" if $self->{beep};
988         }
989         $self->local_send('C', $buf);
990 }
991
992 sub format_dx_spot
993 {
994         my $self = shift;
995
996         my $t = ztime($_[2]);
997         my $loc = '';
998         my $clth = $self->{consort} eq 'local' ? 29 : 30;
999         my $comment = substr (($_[3] || ''), 0, $clth);
1000         $comment .= ' ' x ($clth - (length($comment)));
1001         if ($self->{user}->wantgrid) {
1002                 my $ref = DXUser::get_current($_[1]);
1003                 if ($ref && $ref->qra) {
1004                         $loc = ' ' . substr($ref->qra, 0, 4);
1005                         $comment = substr $comment, 0,  ($clth - (length($comment)+length($loc)));
1006                         $comment .= $loc;
1007                         $loc = '';
1008                 }
1009         }
1010         
1011         if ($self->{user}->wantgrid) {
1012                 my $ref = DXUser::get_current($_[4]);
1013                 if ($ref && $ref->qra) {
1014                         $loc = ' ' . substr($ref->qra, 0, 4);
1015                 }
1016         }
1017
1018         if ($self->{user}->wantdxitu) {
1019                 $loc = ' ' . sprintf("%2d", $_[10]) if defined $_[10];
1020                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . sprintf("%2d", $_[8]) if defined $_[8]; 
1021         } elsif ($self->{user}->wantdxcq) {
1022                 $loc = ' ' . sprintf("%2d", $_[11]) if defined $_[11];
1023                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . sprintf("%2d", $_[9]) if defined $_[9]; 
1024         } elsif ($self->{user}->wantusstate) {
1025                 $loc = ' ' . $_[13] if $_[13];
1026                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . $_[12] if $_[12]; 
1027         }
1028
1029         return sprintf "DX de %-7.7s%11.1f  %-12.12s %-s $t$loc", "$_[4]:", $_[0], $_[1], $comment;
1030 }
1031
1032 # send a dx spot
1033 sub dx_spot
1034 {
1035         my $self = shift;
1036         my $line = shift;
1037         my $isolate = shift;
1038         return unless $self->{dx};
1039
1040         my ($filter, $hops);
1041
1042         if ($self->{spotsfilter}) {
1043                 ($filter, $hops) = $self->{spotsfilter}->it(@_ );
1044                 return unless $filter;
1045         }
1046
1047         dbg('spot: "' . join('","', @_) . '"') if isdbg('dxspot');
1048
1049         my $buf;
1050         if ($self->{ve7cc}) {
1051                 $buf = VE7CC::dx_spot($self, @_);
1052         } elsif ($self->{gtk}) {
1053                 my ($dxloc, $byloc);
1054
1055                 my $ref = DXUser::get_current($_[4]);
1056                 if ($ref) {
1057                         $byloc = $ref->qra;
1058                         $byloc = substr($byloc, 0, 4) if $byloc;
1059                 }
1060
1061                 my $spot = $_[1];
1062                 $spot =~ s|/\w{1,4}$||;
1063                 $ref = DXUser::get_current($spot);
1064                 if ($ref) {
1065                         $dxloc = $ref->qra;
1066                         $dxloc = substr($dxloc, 0, 4) if $dxloc;
1067                 }
1068                 $buf = dd(['dx', @_, ($dxloc||''), ($byloc||'')]);
1069                 
1070         } else {
1071                 $buf = $self->format_dx_spot(@_);
1072                 $buf .= "\a\a" if $self->{beep};
1073                 $buf =~ s/\%5E/^/g;
1074         }
1075
1076         $self->local_send('X', $buf);
1077 }
1078
1079 sub wwv
1080 {
1081         my $self = shift;
1082         my $line = shift;
1083         my $isolate = shift;
1084         my ($filter, $hops);
1085
1086         return unless $self->{wwv};
1087         
1088         if ($self->{wwvfilter}) {
1089                 ($filter, $hops) = $self->{wwvfilter}->it(@_[7..$#_] );
1090                 return unless $filter;
1091         }
1092
1093         my $buf;
1094         if ($self->{gtk}) {
1095                 $buf = dd(['wwv', @_])
1096         } else {
1097                 $buf = "WWV de $_[6] <$_[1]>:   SFI=$_[2], A=$_[3], K=$_[4], $_[5]";
1098                 $buf .= "\a\a" if $self->{beep};
1099         }
1100         
1101         $self->local_send('V', $buf);
1102 }
1103
1104 sub wcy
1105 {
1106         my $self = shift;
1107         my $line = shift;
1108         my $isolate = shift;
1109         my ($filter, $hops);
1110
1111         return unless $self->{wcy};
1112         
1113         if ($self->{wcyfilter}) {
1114                 ($filter, $hops) = $self->{wcyfilter}->it(@_ );
1115                 return unless $filter;
1116         }
1117
1118         my $buf;
1119         if ($self->{gtk}) {
1120                 $buf = dd(['wcy', @_])
1121         } else {
1122                 $buf = "WCY de $_[10] <$_[1]> : K=$_[4] expK=$_[5] A=$_[3] R=$_[6] SFI=$_[2] SA=$_[7] GMF=$_[8] Au=$_[9]";
1123                 $buf .= "\a\a" if $self->{beep};
1124         }
1125         $self->local_send('Y', $buf);
1126 }
1127
1128 # broadcast debug stuff to all interested parties
1129 sub broadcast_debug
1130 {
1131         my $s = shift;                          # the line to be rebroadcast
1132         
1133         foreach my $dxchan (DXChannel::get_all_users) {
1134                 next unless $dxchan->{enhanced} && $dxchan->{senddbg};
1135                 if ($dxchan->{gtk}) {
1136                         $dxchan->send_later('L', dd(['db', $s]));
1137                 } else {
1138                         $dxchan->send_later('L', $s);
1139                 }
1140         }
1141 }
1142
1143 sub do_entry_stuff
1144 {
1145         my $self = shift;
1146         my $line = shift;
1147         my @out;
1148         
1149         if ($self->state eq 'enterbody') {
1150                 my $loc = $self->{loc} || confess "local var gone missing" ;
1151                 if ($line eq "\032" || $line eq '%1A' || uc $line eq "/EX") {
1152                         no strict 'refs';
1153                         push @out, &{$loc->{endaction}}($self);          # like this for < 5.8.0
1154                         $self->func(undef);
1155                         $self->state('prompt');
1156                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
1157                         push @out, $self->msg('m10');
1158                         delete $loc->{lines};
1159                         delete $self->{loc};
1160                         $self->func(undef);
1161                         $self->state('prompt');
1162                 } else {
1163                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
1164                         # i.e. it ain't and end or abort, therefore store the line
1165                 }
1166         } else {
1167                 confess "Invalid state $self->{state}";
1168         }
1169         return @out;
1170 }
1171
1172 sub store_startup_script
1173 {
1174         my $self = shift;
1175         my $loc = $self->{loc} || confess "local var gone missing" ;
1176         my @out;
1177         my $call = $loc->{call} || confess "callsign gone missing";
1178         confess "lines array gone missing" unless ref $loc->{lines};
1179         my $r = Script::store($call, $loc->{lines});
1180         if (defined $r) {
1181                 if ($r) {
1182                         push @out, $self->msg('m19', $call, $r);
1183                 } else {
1184                         push @out, $self->msg('m20', $call);
1185                 }
1186         } else {
1187                 push @out, "error opening startup script $call $!";
1188         } 
1189         return @out;
1190 }
1191
1192 # Import any commands contained in any files in import_cmd directory
1193 #
1194 # If the filename has a recogisable callsign as some delimited part
1195 # of it, then this is the user the command will be run as. 
1196 #
1197 sub import_cmd
1198 {
1199         # are there any to do in this directory?
1200         return unless -d $cmdimportdir;
1201         unless (opendir(DIR, $cmdimportdir)) {
1202                 LogDbg('err', "can\'t open $cmdimportdir $!");
1203                 return;
1204         } 
1205
1206         my @names = readdir(DIR);
1207         closedir(DIR);
1208         my $name;
1209
1210         return unless @names;
1211         
1212         foreach $name (@names) {
1213                 next if $name =~ /^\./;
1214
1215                 my $s = Script->new($name, $cmdimportdir);
1216                 if ($s) {
1217                         LogDbg('DXCommand', "Run import cmd file $name");
1218                         my @cat = split /[^A-Za-z0-9]+/, $name;
1219                         my ($call) = grep {is_callsign(uc $_)} @cat;
1220                         $call ||= $main::mycall;
1221                         $call = uc $call;
1222                         my @out;
1223                         
1224                         
1225                         $s->inscript(0);        # switch off script checks
1226                         
1227                         if ($call eq $main::mycall) {
1228                                 @out = $s->run($main::me, 1);
1229                         } else {
1230                                 my $dxchan = DXChannel::get($call);
1231                             if ($dxchan) {
1232                                         @out = $s->run($dxchan, 1);
1233                                 } else {
1234                                         my $u = DXUser::get($call);
1235                                         if ($u) {
1236                                                 $dxchan = $main::me;
1237                                                 my $old = $dxchan->{call};
1238                                                 my $priv = $dxchan->{priv};
1239                                                 my $user = $dxchan->{user};
1240                                                 $dxchan->{call} = $call;
1241                                                 $dxchan->{priv} = $u->priv;
1242                                                 $dxchan->{user} = $u;
1243                                                 @out = $s->run($dxchan, 1);
1244                                                 $dxchan->{call} = $old;
1245                                                 $dxchan->{priv} = $priv;
1246                                                 $dxchan->{user} = $user;
1247                                         } else {
1248                                                 LogDbg('err', "Trying to run import cmd for non-existant user $call");
1249                                         }
1250                                 }
1251                         }
1252                         $s->erase;
1253                         for (@out) {
1254                                 LogDbg('DXCommand', "Import cmd $name/$call: $_");
1255                         }
1256                 } else {
1257                         LogDbg('err', "Failed to open $cmdimportdir/$name $!");
1258                         unlink "$cmdimportdir/$name";
1259                 }
1260         }
1261 }
1262
1263 sub print_find_reply
1264 {
1265         my ($self, $node, $target, $flag, $ms) = @_;
1266         my $sort = $flag == 2 ? "External" : "Local";
1267         $self->send("$sort $target found at $node in $ms ms" );
1268 }
1269
1270 # send the most relevant motd
1271 sub send_motd
1272 {
1273         my $self = shift;
1274         my $motd;
1275
1276         unless ($self->{registered}) {
1277                 $motd = "${main::motd}_nor_$self->{lang}";
1278                 $motd = "${main::motd}_nor" unless -e $motd;
1279         }
1280         $motd = "${main::motd}_$self->{lang}" unless $motd && -e $motd;
1281         $motd = $main::motd unless $motd && -e $motd;
1282         if ($self->conn->ax25) {
1283                 if ($motd) {
1284                         $motd = "${motd}_ax25" if -e "${motd}_ax25";
1285                 } else {
1286                         $motd = "${main::motd}_ax25" if -e "${main::motd}_ax25";
1287                 }
1288         }
1289         $self->send_file($motd) if -e $motd;
1290 }
1291
1292
1293 # Punt off a long running command into a separate process
1294 #
1295 # This is called from commands to run some potentially long running
1296 # function. The process forks and then runs the function and returns
1297 # the result back to the cmd. 
1298 #
1299 # NOTE: this merely forks the current process and then runs the cmd in that (current) context.
1300 #       IT DOES NOT START UP SOME NEW PROGRAM AND RELIES ON THE FACT THAT IT IS RUNNING DXSPIDER 
1301 #       THE CURRENT CONTEXT!!
1302
1303 # call: $self->spawn_cmd($original_cmd_line, \<function>, [cb => sub{...}], [prefix => "cmd> "], [progress => 0|1], [args => [...]]);
1304 sub spawn_cmd
1305 {
1306         my $self = shift;
1307         my $line = shift;
1308         my $cmdref = shift;
1309         my $call = $self->{call};
1310         my %args = @_;
1311         my @out;
1312         
1313         my $cb = delete $args{cb};
1314         my $prefix = delete $args{prefix};
1315         my $progress = delete $args{progress};
1316         my $args = delete $args{args} || [];
1317         my $t0 = [gettimeofday];
1318
1319         no strict 'refs';
1320
1321         # just behave normally if something has set the "one-shot" _nospawn in the channel
1322         if ($self->{_nospawn}) {
1323                 eval { @out = $cmdref->(@$args); };
1324                 if ($@) {
1325                         DXDebug::dbgprintring(25);
1326                         push @out, DXDebug::shortmess($@);
1327                 }
1328                 return @out;
1329         }
1330         
1331         my $fc = DXSubprocess->new;
1332 #       $fc->serializer(\&encode_json);
1333 #       $fc->deserializer(\&decode_json);
1334         $fc->run(
1335                          sub {
1336                                  my $subpro = shift;
1337                                  if (isdbg('progress')) {
1338                                          my $s = qq{line: "$line"};
1339                                          $s .= ", args: " . join(', ', map { defined $_ ? qq{'$_'} : q{'undef'} } @$args) if $args && @$args;
1340                                          dbg($s);
1341                                  }
1342                                  eval { @out = $cmdref->(@$args); };
1343                                  if ($@) {
1344                                          DXDebug::dbgprintring(25);
1345                                          push @out, DXDebug::shortmess($@);
1346                                  }
1347                                  return @out;
1348                          },
1349 #                        $args,
1350                          sub {
1351                                  my ($fc, $err, @res) = @_; 
1352                                  my $dxchan = DXChannel::get($call);
1353                                  return unless $dxchan;
1354
1355                                  if ($err) {
1356                                          my $s = "DXProt::spawn_cmd: call $call error $err";
1357                                          dbg($s) if isdbg('chan');
1358                                          $dxchan->send($s);
1359                                          return;
1360                                  }
1361                                  if ($cb) {
1362                                          # transform output if required
1363                                          @res = $cb->($dxchan, @res);
1364                                  }
1365                                  if (@res) {
1366                                          if (defined $prefix) {
1367                                                  $dxchan->send(map {"$prefix$_"} @res);
1368                                          } else {
1369                                                  $dxchan->send(@res);
1370                                          }
1371                                  }
1372                                  diffms("by $call", $line, $t0, scalar @res) if isdbg('progress');
1373                          });
1374         
1375         return @out;
1376 }
1377
1378 sub user_count
1379 {
1380         return ($users, $maxusers);
1381 }
1382 1;
1383 __END__