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