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