]> www.dxcluster.org Git - spider.git/blob - perl/DXCommandmode.pm
d5271313960a1f6f42f6142a883923aa7e9afabd
[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);
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 #
63
64 #
65 # obtain a new connection this is derived from dxchannel
66 #
67
68 sub new 
69 {
70         my $self = DXChannel::alloc(@_);
71
72         # routing, this must go out here to prevent race condx
73         my $pkg = shift;
74         my $call = shift;
75 #       my @rout = $main::routeroot->add_user($call, Route::here(1));
76         DXProt::_add_thingy($main::routeroot, [$call, 0, 0, 1, undef, undef, $self->hostname], );
77
78         # ALWAYS output the user
79         my $ref = Route::User::get($call);
80         if ($ref) {
81                 $main::me->route_pc16($main::mycall, undef, $main::routeroot, $ref);
82                 $main::me->route_pc92a($main::mycall, undef, $main::routeroot, $ref) unless $DXProt::pc92_slug_changes;
83         }
84
85         return $self;
86 }
87
88 # this is how a a connection starts, you get a hello message and the motd with
89 # possibly some other messages asking you to set various things up if you are
90 # new (or nearly new and slacking) user.
91
92 sub start
93
94         my ($self, $line, $sort) = @_;
95         my $user = $self->{user};
96         my $call = $self->{call};
97         my $name = $user->{name};
98         
99         # log it
100         my $host = $self->{conn}->peerhost;
101         $host ||= "AGW Port #$self->{conn}->{agwport}" if exists $self->{conn}->{agwport};
102         $host ||= "unknown";
103         $self->{hostname} = $host;
104
105         $self->{name} = $name ? $name : $call;
106         $self->send($self->msg('l2',$self->{name}));
107         $self->state('prompt');         # a bit of room for further expansion, passwords etc
108         $self->{priv} = $user->priv || 0;
109         $self->{lang} = $user->lang || $main::lang || 'en';
110         my $pagelth = $user->pagelth;
111         $pagelth = $default_pagelth unless defined $pagelth;
112         $self->{pagelth} = $pagelth;
113         ($self->{width}) = $line =~ /width=(\d+)/; $line =~ s/\s*width=\d+\s*//;
114         if ($line =~ /host=/) {
115                 my ($h) = $line =~ /host=(\d+\.\d+\.\d+\.\d+)/;
116                 $line =~ s/\s*host=\d+\.\d+\.\d+\.\d+// if $h;
117                 unless ($h) {
118                         ($h) = $line =~ /host=([\da..fA..F:]+)/;
119                         $line =~ s/\s*host=[\da..fA..F:]+// if $h;
120                 }
121                 $self->{hostname} = $h if $h;
122         }
123         $self->{width} = 80 unless $self->{width} && $self->{width} > 80;
124         $self->{consort} = $line;       # save the connection type
125
126         LogDbg('DXCommand', "$call connected from $self->{hostname}");
127
128         # set some necessary flags on the user if they are connecting
129         $self->{beep} = $user->wantbeep;
130         $self->{ann} = $user->wantann;
131         $self->{wwv} = $user->wantwwv;
132         $self->{wcy} = $user->wantwcy;
133         $self->{talk} = $user->wanttalk;
134         $self->{wx} = $user->wantwx;
135         $self->{dx} = $user->wantdx;
136         $self->{logininfo} = $user->wantlogininfo;
137         $self->{ann_talk} = $user->wantann_talk;
138         $self->{here} = 1;
139         $self->{prompt} = $user->prompt if $user->prompt;
140         $self->{lastmsgpoll} = 0;
141
142         # sort out new dx spot stuff
143         $user->wantdxcq(0) unless defined $user->{wantdxcq};
144         $user->wantdxitu(0) unless defined $user->{wantdxitu};  
145         $user->wantusstate(0) unless defined $user->{wantusstate};
146
147         # sort out registration
148         if ($main::reqreg == 1) {
149                 $self->{registered} = $user->registered;
150         } elsif ($main::reqreg == 2) {
151                 $self->{registered} = !$user->registered;
152         } else {
153                 $self->{registered} = 1;
154         }
155
156         # send the relevant MOTD
157         $self->send_motd;
158
159         # sort out privilege reduction
160         $self->{priv} = 0 unless $self->{hostname} eq '127.0.0.1' || $self->{hostname} eq '::1' || $self->conn->{usedpasswd};
161
162         # get the filters
163         my $nossid = $call;
164         $nossid =~ s/-\d+$//;
165         
166         $self->{spotsfilter} = Filter::read_in('spots', $call, 0) 
167                 || Filter::read_in('spots', $nossid, 0)
168                         || Filter::read_in('spots', 'user_default', 0);
169         $self->{wwvfilter} = Filter::read_in('wwv', $call, 0) 
170                 || Filter::read_in('wwv', $nossid, 0) 
171                         || Filter::read_in('wwv', 'user_default', 0);
172         $self->{wcyfilter} = Filter::read_in('wcy', $call, 0) 
173                 || Filter::read_in('wcy', $nossid, 0) 
174                         || Filter::read_in('wcy', 'user_default', 0);
175         $self->{annfilter} = Filter::read_in('ann', $call, 0) 
176                 || Filter::read_in('ann', $nossid, 0) 
177                         || Filter::read_in('ann', 'user_default', 0) ;
178
179         # clean up qra locators
180         my $qra = $user->qra;
181         $qra = undef if ($qra && !DXBearing::is_qra($qra));
182         unless ($qra) {
183                 my $lat = $user->lat;
184                 my $long = $user->long;
185                 $user->qra(DXBearing::lltoqra($lat, $long)) if (defined $lat && defined $long);  
186         }
187
188         # decide on echo
189         my $echo = $user->wantecho;
190         unless ($echo) {
191                 $self->send_now('E', "0");
192                 $self->send($self->msg('echow'));
193                 $self->conn->echo($echo) if $self->conn->can('echo');
194         }
195         
196         $self->tell_login('loginu');
197         $self->tell_buddies('loginb');
198         
199         # do we need to send a forward/opernam?
200         my $lastoper = $user->lastoper || 0;
201         my $homenode = $user->homenode || ""; 
202         if ($homenode eq $main::mycall && $main::systime >= $lastoper + $DXUser::lastoperinterval) {
203                 run_cmd($main::me, "forward/opernam $call");
204                 $user->lastoper($main::systime + ((int rand(10)) * 86400));
205         }
206
207         # run a script send the output to the punter
208         my $script = new Script(lc $call) || new Script('user_default');
209         $script->run($self) if $script;
210
211         # send cluster info
212         my $info = Route::cluster();
213         $self->send("Cluster:$info");
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                                 eval { @ans = &{"${package}::handle"}($self, $args) };
548                                 return (DXDebug::shortmess($@)) if $@;
549                         } else {
550                                 dbg("cmd: $package not present") if isdbg('command');
551                                 return $self->_error_out('e1');
552                         }
553                 } else {
554                         dbg("cmd: $cmd not found") if isdbg('command');
555                         return $self->_error_out('e1');
556                 }
557         }
558         
559         my $ok = shift @ans;
560         if ($ok) {
561                 delete $self->{errors};
562         } else {
563                 if (++$self->{errors} > $DXChannel::maxerrors) {
564                         $self->send($self->msg('e26'));
565                         $self->disconnect;
566                         return ();
567                 }
568         }
569         return map {s/([^\s])\s+$/$1/; $_} @ans;
570 }
571
572 #
573 # This is called from inside the main cluster processing loop and is used
574 # for despatching commands that are doing some long processing job
575 #
576 sub process
577 {
578         my $t = time;
579         my @dxchan = DXChannel::get_all();
580         my $dxchan;
581         
582         foreach $dxchan (@dxchan) {
583                 next unless $dxchan->is_user;  
584         
585                 # send a outstanding message prompt if required
586                 if ($t >= $dxchan->lastmsgpoll + $msgpolltime) {
587                         $dxchan->send($dxchan->msg('m9')) if DXMsg::for_me($dxchan->call);
588                         $dxchan->lastmsgpoll($t);
589                 }
590                 
591                 # send a prompt if no activity out on this channel
592                 if ($t >= $dxchan->t + $main::user_interval) {
593                         $dxchan->prompt() if $dxchan->{state} =~ /^prompt/o;
594                         $dxchan->t($t);
595                 }
596         }
597
598         while (my ($k, $v) = each %nothereslug) {
599                 if ($main::systime >= $v + 300) {
600                         delete $nothereslug{$k};
601                 }
602         }
603
604         import_cmd();
605 }
606
607 #
608 # finish up a user context
609 #
610 sub disconnect
611 {
612         my $self = shift;
613         my $call = $self->call;
614
615         return if $self->{disconnecting}++;
616
617         delete $self->{senddbg};
618
619         my $uref = Route::User::get($call);
620         my @rout;
621         if ($uref) {
622 #               @rout = $main::routeroot->del_user($uref);
623                 @rout = DXProt::_del_thingy($main::routeroot, [$call, 0]);
624
625                 dbg("B/C PC17 on $main::mycall for: $call") if isdbg('route');
626
627                 # issue a pc17 to everybody interested
628                 $main::me->route_pc17($main::mycall, undef, $main::routeroot, $uref);
629                 $main::me->route_pc92d($main::mycall, undef, $main::routeroot, $uref) unless $DXProt::pc92_slug_changes;
630         } else {
631                 confess "trying to disconnect a non existant user $call";
632         }
633
634         # I was the last node visited
635     $self->user->node($main::mycall);
636                 
637         # send info to all logged in thingies
638         $self->tell_login('logoutu');
639         $self->tell_buddies('logoutb');
640
641         LogDbg('DXCommand', "$call disconnected");
642
643         $self->SUPER::disconnect;
644 }
645
646 #
647 # short cut to output a prompt
648 #
649
650 sub prompt
651 {
652         my $self = shift;
653
654         return if $self->{gtk};         # 'cos prompts are not a concept that applies here
655         
656         my $call = $self->call;
657         my $date = cldate($main::systime);
658         my $time = ztime($main::systime);
659         my $prompt = $self->{prompt} || $self->msg('pr');
660
661         $call = "($call)" unless $self->here;
662         $prompt =~ s/\%C/$call/g;
663         $prompt =~ s/\%D/$date/g;
664         $prompt =~ s/\%T/$time/g;
665         $prompt =~ s/\%M/$main::mycall/g;
666         
667         $self->send($prompt);
668 }
669
670 # broadcast a message to all users [except those mentioned after buffer]
671 sub broadcast
672 {
673         my $pkg = shift;                        # ignored
674         my $s = shift;                          # the line to be rebroadcast
675         
676     foreach my $dxchan (DXChannel::get_all()) {
677                 next unless $dxchan->is_user; # only interested in user channels  
678                 next if grep $dxchan == $_, @_;
679                 $dxchan->send($s);                      # send it
680         }
681 }
682
683 # gimme all the users
684 sub get_all
685 {
686         return grep {$_->is_user} DXChannel::get_all();
687 }
688
689 # run a script for this user
690 sub run_script
691 {
692         my $self = shift;
693         my $silent = shift || 0;
694         
695 }
696
697 #
698 # search for the command in the cache of short->long form commands
699 #
700
701 sub search
702 {
703         my ($path, $short_cmd, $suffix) = @_;
704         my ($apath, $acmd);
705         
706         # commands are lower case
707         $short_cmd = lc $short_cmd;
708         dbg("command: $path $short_cmd\n") if isdbg('command');
709
710         # do some checking for funny characters
711         return () if $short_cmd =~ /\/$/;
712
713         # return immediately if we have it
714         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
715         if ($apath && $acmd) {
716                 dbg("cached $short_cmd = ($apath, $acmd)\n") if isdbg('command');
717                 return ($apath, $acmd);
718         }
719         
720         # if not guess
721         my @parts = split '/', $short_cmd;
722         my $dirfn;
723         my $curdir = $path;
724         
725         while (my $p = shift @parts) {
726                 opendir(D, $curdir) or confess "can't open $curdir $!";
727                 my @ls = readdir D;
728                 closedir D;
729
730                 # if this isn't the last part
731                 if (@parts) {
732                         my $found;
733                         foreach my $l (sort @ls) {
734                                 next if $l =~ /^\./;
735                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
736                                         dbg("got dir: $curdir/$l\n") if isdbg('command');
737                                         $dirfn .= "$l/";
738                                         $curdir .= "/$l";
739                                         $found++;
740                                         last;
741                                 }
742                         }
743                         # only proceed if we find the directory asked for
744                         return () unless $found;
745                 } else {
746                         foreach my $l (sort @ls) {
747                                 next if $l =~ /^\./;
748                                 next unless $l =~ /\.$suffix$/;
749                                 if ($p eq substr($l, 0, length $p)) {
750                                         $l =~ s/\.$suffix$//;
751                                         $dirfn = "" unless $dirfn;
752                                         $cmd_cache{$short_cmd} = join(',', ($path, "$dirfn$l")); # cache it
753                                         dbg("got path: $path cmd: $dirfn$l\n") if isdbg('command');
754                                         return ($path, "$dirfn$l");
755                                 }
756                         }
757                 }
758         }
759
760         return ();  
761 }  
762
763 # clear the command name cache
764 sub clear_cmd_cache
765 {
766         no strict 'refs';
767         
768         for my $k (keys %Cache) {
769                 unless ($k =~ /cmd_cache/) {
770                         dbg("Undefining cmd $k") if isdbg('command');
771                         undef $DXCommandmode::{"${k}::"};
772                 }
773         }
774         %cmd_cache = ();
775         %Cache = ( cmd_clear_cmd_cache  => $Cache{cmd_clear_cmd_cache} );
776 }
777
778 #
779 # the persistant execution of things from the command directories
780 #
781 #
782 # This allows perl programs to call functions dynamically
783
784 # This has been nicked directly from the perlembed pages
785 #
786 #require Devel::Symdump;  
787
788 sub valid_package_name {
789         my $string = shift;
790         $string =~ s|([^A-Za-z0-9_/])|sprintf("_%2x",unpack("C",$1))|eg;
791         
792         $string =~ s|/|_|g;
793         return "cmd_$string";
794 }
795
796
797 # this bit of magic finds a command in the offered directory
798 sub find_cmd_name {
799         my $path = shift;
800         my $cmdname = shift;
801         my $package = valid_package_name($cmdname);
802         my $filename = "$path/$cmdname.pl";
803         my $mtime = -M $filename;
804         
805         # return if we can't find it
806         $errstr = undef;
807         unless (defined $mtime) {
808                 $errstr = DXM::msg('e1');
809                 return undef;
810         }
811         
812         if(exists $Cache{$package} && exists $Cache{$package}->{mtime} && $Cache{$package}->{mtime} <= $mtime) {
813                 #we have compiled this subroutine already,
814                 #it has not been updated on disk, nothing left to do
815                 #print STDERR "already compiled $package->handler\n";
816                 dbg("find_cmd_name: $package cached") if isdbg('command');
817         } else {
818
819                 my $sub = readfilestr($filename);
820                 unless ($sub) {
821                         $errstr = "Syserr: can't open '$filename' $!";
822                         return undef;
823                 };
824                 
825                 #wrap the code into a subroutine inside our unique package
826                 my $eval = qq(package DXCommandmode::$package; use POSIX qw{:math_h}; use DXLog; use DXDebug; use DXUser; use DXUtil; our \@ISA = qw{DXCommandmode}; );
827
828
829                 if ($sub =~ m|\s*sub\s+handle\n|) {
830                         $eval .= $sub;
831                 } else {
832                         $eval .= qq(sub handle { $sub });
833                 }
834                 
835                 if (isdbg('eval')) {
836                         my @list = split /\n/, $eval;
837                         my $line;
838                         for (@list) {
839                                 dbg($_ . "\n") if isdbg('eval');
840                         }
841                 }
842                 
843                 # get rid of any existing sub and try to compile the new one
844                 no strict 'refs';
845
846                 if (exists $Cache{$package}) {
847                         dbg("find_cmd_name: Redefining $package") if isdbg('command');
848                         undef $DXCommandmode::{"${package}::"};
849                         delete $Cache{$package};
850                 } else {
851                         dbg("find_cmd_name: Defining $package") if isdbg('command');
852                 }
853
854                 eval $eval;
855
856                 $Cache{$package} = {mtime => $mtime } unless $@;
857         }
858
859         return "DXCommandmode::$package";
860 }
861
862 sub send
863 {
864         my $self = shift;
865         if ($self->{gtk}) {
866                 for (@_) {
867                         $self->SUPER::send(dd(['cmd',$_]));
868                 }
869         } else {
870                 $self->SUPER::send(@_);
871         }
872 }
873
874 sub local_send
875 {
876         my ($self, $let, $buf) = @_;
877         if ($self->{state} eq 'prompt' || $self->{state} eq 'talk' || $self->{state} eq 'chat') {
878                 if ($self->{enhanced}) {
879                         $self->send_later($let, $buf);
880                 } else {
881                         $self->send($buf);
882                 }
883         } else {
884                 $self->delay($buf);
885         }
886 }
887
888 # send a talk message here
889 sub talk
890 {
891         my ($self, $from, $to, $via, $line, $onode) = @_;
892         $line =~ s/\\5E/\^/g;
893         if ($self->{talk}) {
894                 if ($self->{gtk}) {
895                         $self->local_send('T', dd(['talk',$to,$from,$via,$line]));
896                 } else {
897                         $self->local_send('T', "$to de $from: $line");
898                 }
899         }
900         Log('talk', $to, $from, '<' . ($onode || '*'), $line);
901         # send a 'not here' message if required
902         unless ($self->{here} && $from ne $to) {
903                 my $key = "$to$from";
904                 unless (exists $nothereslug{$key}) {
905                         my ($ref, $dxchan);
906                         if (($ref = Route::get($from)) && ($dxchan = $ref->dxchan)) {
907                                 my $name = $self->user->name || $to;
908                                 my $s = $self->user->nothere || $dxchan->msg('nothere', $name);
909                                 $nothereslug{$key} = $main::systime;
910                                 $dxchan->talk($to, $from, undef, $s);
911                         }
912                 }
913         }
914 }
915
916 # send an announce
917 sub announce
918 {
919         my $self = shift;
920         my $line = shift;
921         my $isolate = shift;
922         my $to = shift;
923         my $target = shift;
924         my $text = shift;
925         my ($filter, $hops);
926
927         if (!$self->{ann_talk} && $to ne $self->{call}) {
928                 my $call = AnnTalk::is_talk_candidate($_[0], $text);
929                 return if $call;
930         }
931
932         if ($self->{annfilter}) {
933                 ($filter, $hops) = $self->{annfilter}->it(@_ );
934                 return unless $filter;
935         }
936
937         unless ($self->{ann}) {
938                 return if $_[0] ne $main::myalias && $_[0] ne $main::mycall;
939         }
940         return if $target eq 'SYSOP' && $self->{priv} < 5;
941         my $buf;
942         if ($self->{gtk}) {
943                 $buf = dd(['ann', $to, $target, $text, @_])
944         } else {
945                 $buf = "$to$target de $_[0]: $text";
946                 $buf =~ s/\%5E/^/g;
947                 $buf .= "\a\a" if $self->{beep};
948         }
949         $self->local_send($target eq 'WX' ? 'W' : 'N', $buf);
950 }
951
952 # send a chat
953 sub chat
954 {
955         my $self = shift;
956         my $line = shift;
957         my $isolate = shift;
958         my $target = shift;
959         my $to = shift;
960         my $text = shift;
961         my ($filter, $hops);
962
963         return unless grep uc $_ eq $target, @{$self->{user}->{group}};
964         
965         $text =~ s/^\#\d+ //;
966         my $buf;
967         if ($self->{gtk}) {
968                 $buf = dd(['chat', $to, $target, $text, @_])
969         } else {
970                 $buf = "$target de $_[0]: $text";
971                 $buf =~ s/\%5E/^/g;
972                 $buf .= "\a\a" if $self->{beep};
973         }
974         $self->local_send('C', $buf);
975 }
976
977 sub format_dx_spot
978 {
979         my $self = shift;
980
981         my $t = ztime($_[2]);
982         my $loc = '';
983         my $clth = $self->{consort} eq 'local' ? 29 : 30;
984         my $comment = substr (($_[3] || ''), 0, $clth);
985         $comment .= ' ' x ($clth - length($comment));
986         if ($self->{user}->wantgrid) {
987                 my $ref = DXUser::get_current($_[4]);
988                 if ($ref) {
989                         $loc = $ref->qra || '';
990                         $loc = ' ' . substr($loc, 0, 4) if $loc;
991                 }
992         }
993
994         if ($self->{user}->wantdxitu) {
995                 $loc = ' ' . sprintf("%2d", $_[10]) if defined $_[10];
996                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . sprintf("%2d", $_[8]) if defined $_[8]; 
997         } elsif ($self->{user}->wantdxcq) {
998                 $loc = ' ' . sprintf("%2d", $_[11]) if defined $_[11];
999                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . sprintf("%2d", $_[9]) if defined $_[9]; 
1000         } elsif ($self->{user}->wantusstate) {
1001                 $loc = ' ' . $_[13] if $_[13];
1002                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . $_[12] if $_[12]; 
1003         }
1004
1005         return sprintf "DX de %-7.7s%11.1f  %-12.12s %-s $t$loc", "$_[4]:", $_[0], $_[1], $comment;
1006 }
1007
1008 # send a dx spot
1009 sub dx_spot
1010 {
1011         my $self = shift;
1012         my $line = shift;
1013         my $isolate = shift;
1014         return unless $self->{dx};
1015
1016         my ($filter, $hops);
1017
1018         if ($self->{spotsfilter}) {
1019                 ($filter, $hops) = $self->{spotsfilter}->it(@_ );
1020                 return unless $filter;
1021         }
1022
1023         dbg('spot: "' . join('","', @_) . '"') if isdbg('dxspot');
1024
1025         my $buf;
1026         if ($self->{ve7cc}) {
1027                 $buf = VE7CC::dx_spot($self, @_);
1028         } elsif ($self->{gtk}) {
1029                 my ($dxloc, $byloc);
1030
1031                 my $ref = DXUser::get_current($_[4]);
1032                 if ($ref) {
1033                         $byloc = $ref->qra;
1034                         $byloc = substr($byloc, 0, 4) if $byloc;
1035                 }
1036
1037                 my $spot = $_[1];
1038                 $spot =~ s|/\w{1,4}$||;
1039                 $ref = DXUser::get_current($spot);
1040                 if ($ref) {
1041                         $dxloc = $ref->qra;
1042                         $dxloc = substr($dxloc, 0, 4) if $dxloc;
1043                 }
1044                 $buf = dd(['dx', @_, ($dxloc||''), ($byloc||'')]);
1045                 
1046         } else {
1047                 $buf = $self->format_dx_spot(@_);
1048                 $buf .= "\a\a" if $self->{beep};
1049                 $buf =~ s/\%5E/^/g;
1050         }
1051
1052         $self->local_send('X', $buf);
1053 }
1054
1055 sub wwv
1056 {
1057         my $self = shift;
1058         my $line = shift;
1059         my $isolate = shift;
1060         my ($filter, $hops);
1061
1062         return unless $self->{wwv};
1063         
1064         if ($self->{wwvfilter}) {
1065                 ($filter, $hops) = $self->{wwvfilter}->it(@_[7..$#_] );
1066                 return unless $filter;
1067         }
1068
1069         my $buf;
1070         if ($self->{gtk}) {
1071                 $buf = dd(['wwv', @_])
1072         } else {
1073                 $buf = "WWV de $_[6] <$_[1]>:   SFI=$_[2], A=$_[3], K=$_[4], $_[5]";
1074                 $buf .= "\a\a" if $self->{beep};
1075         }
1076         
1077         $self->local_send('V', $buf);
1078 }
1079
1080 sub wcy
1081 {
1082         my $self = shift;
1083         my $line = shift;
1084         my $isolate = shift;
1085         my ($filter, $hops);
1086
1087         return unless $self->{wcy};
1088         
1089         if ($self->{wcyfilter}) {
1090                 ($filter, $hops) = $self->{wcyfilter}->it(@_ );
1091                 return unless $filter;
1092         }
1093
1094         my $buf;
1095         if ($self->{gtk}) {
1096                 $buf = dd(['wcy', @_])
1097         } else {
1098                 $buf = "WCY de $_[10] <$_[1]> : K=$_[4] expK=$_[5] A=$_[3] R=$_[6] SFI=$_[2] SA=$_[7] GMF=$_[8] Au=$_[9]";
1099                 $buf .= "\a\a" if $self->{beep};
1100         }
1101         $self->local_send('Y', $buf);
1102 }
1103
1104 # broadcast debug stuff to all interested parties
1105 sub broadcast_debug
1106 {
1107         my $s = shift;                          # the line to be rebroadcast
1108         
1109         foreach my $dxchan (DXChannel::get_all_users) {
1110                 next unless $dxchan->{enhanced} && $dxchan->{senddbg};
1111                 if ($dxchan->{gtk}) {
1112                         $dxchan->send_later('L', dd(['db', $s]));
1113                 } else {
1114                         $dxchan->send_later('L', $s);
1115                 }
1116         }
1117 }
1118
1119 sub do_entry_stuff
1120 {
1121         my $self = shift;
1122         my $line = shift;
1123         my @out;
1124         
1125         if ($self->state eq 'enterbody') {
1126                 my $loc = $self->{loc} || confess "local var gone missing" ;
1127                 if ($line eq "\032" || $line eq '%1A' || uc $line eq "/EX") {
1128                         no strict 'refs';
1129                         push @out, &{$loc->{endaction}}($self);          # like this for < 5.8.0
1130                         $self->func(undef);
1131                         $self->state('prompt');
1132                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
1133                         push @out, $self->msg('m10');
1134                         delete $loc->{lines};
1135                         delete $self->{loc};
1136                         $self->func(undef);
1137                         $self->state('prompt');
1138                 } else {
1139                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
1140                         # i.e. it ain't and end or abort, therefore store the line
1141                 }
1142         } else {
1143                 confess "Invalid state $self->{state}";
1144         }
1145         return @out;
1146 }
1147
1148 sub store_startup_script
1149 {
1150         my $self = shift;
1151         my $loc = $self->{loc} || confess "local var gone missing" ;
1152         my @out;
1153         my $call = $loc->{call} || confess "callsign gone missing";
1154         confess "lines array gone missing" unless ref $loc->{lines};
1155         my $r = Script::store($call, $loc->{lines});
1156         if (defined $r) {
1157                 if ($r) {
1158                         push @out, $self->msg('m19', $call, $r);
1159                 } else {
1160                         push @out, $self->msg('m20', $call);
1161                 }
1162         } else {
1163                 push @out, "error opening startup script $call $!";
1164         } 
1165         return @out;
1166 }
1167
1168 # Import any commands contained in any files in import_cmd directory
1169 #
1170 # If the filename has a recogisable callsign as some delimited part
1171 # of it, then this is the user the command will be run as. 
1172 #
1173 sub import_cmd
1174 {
1175         # are there any to do in this directory?
1176         return unless -d $cmdimportdir;
1177         unless (opendir(DIR, $cmdimportdir)) {
1178                 LogDbg('err', "can\'t open $cmdimportdir $!");
1179                 return;
1180         } 
1181
1182         my @names = readdir(DIR);
1183         closedir(DIR);
1184         my $name;
1185
1186         return unless @names;
1187         
1188         foreach $name (@names) {
1189                 next if $name =~ /^\./;
1190
1191                 my $s = Script->new($name, $cmdimportdir);
1192                 if ($s) {
1193                         LogDbg('DXCommand', "Run import cmd file $name");
1194                         my @cat = split /[^A-Za-z0-9]+/, $name;
1195                         my ($call) = grep {is_callsign(uc $_)} @cat;
1196                         $call ||= $main::mycall;
1197                         $call = uc $call;
1198                         my @out;
1199                         
1200                         
1201                         $s->inscript(0);        # switch off script checks
1202                         
1203                         if ($call eq $main::mycall) {
1204                                 @out = $s->run($main::me, 1);
1205                         } else {
1206                                 my $dxchan = DXChannel::get($call);
1207                             if ($dxchan) {
1208                                         @out = $s->run($dxchan, 1);
1209                                 } else {
1210                                         my $u = DXUser::get($call);
1211                                         if ($u) {
1212                                                 $dxchan = $main::me;
1213                                                 my $old = $dxchan->{call};
1214                                                 my $priv = $dxchan->{priv};
1215                                                 my $user = $dxchan->{user};
1216                                                 $dxchan->{call} = $call;
1217                                                 $dxchan->{priv} = $u->priv;
1218                                                 $dxchan->{user} = $u;
1219                                                 @out = $s->run($dxchan, 1);
1220                                                 $dxchan->{call} = $old;
1221                                                 $dxchan->{priv} = $priv;
1222                                                 $dxchan->{user} = $user;
1223                                         } else {
1224                                                 LogDbg('err', "Trying to run import cmd for non-existant user $call");
1225                                         }
1226                                 }
1227                         }
1228                         $s->erase;
1229                         for (@out) {
1230                                 LogDbg('DXCommand', "Import cmd $name/$call: $_");
1231                         }
1232                 } else {
1233                         LogDbg('err', "Failed to open $cmdimportdir/$name $!");
1234                         unlink "$cmdimportdir/$name";
1235                 }
1236         }
1237 }
1238
1239 sub print_find_reply
1240 {
1241         my ($self, $node, $target, $flag, $ms) = @_;
1242         my $sort = $flag == 2 ? "External" : "Local";
1243         $self->send("$sort $target found at $node in $ms ms" );
1244 }
1245
1246 # send the most relevant motd
1247 sub send_motd
1248 {
1249         my $self = shift;
1250         my $motd;
1251
1252         unless ($self->{registered}) {
1253                 $motd = "${main::motd}_nor_$self->{lang}";
1254                 $motd = "${main::motd}_nor" unless -e $motd;
1255         }
1256         $motd = "${main::motd}_$self->{lang}" unless $motd && -e $motd;
1257         $motd = $main::motd unless $motd && -e $motd;
1258         if ($self->conn->ax25) {
1259                 if ($motd) {
1260                         $motd = "${motd}_ax25" if -e "${motd}_ax25";
1261                 } else {
1262                         $motd = "${main::motd}_ax25" if -e "${main::motd}_ax25";
1263                 }
1264         }
1265         $self->send_file($motd) if -e $motd;
1266 }
1267
1268 sub _diffms
1269 {
1270         return unless isdbg('chan');
1271         my $call = shift;
1272         my $line = shift;
1273         my $ta = shift;
1274         my $tb = shift || [gettimeofday];
1275
1276         my $a = int($ta->[0] * 1000) + int($ta->[1] / 1000); 
1277         my $b = int($tb->[0] * 1000) + int($tb->[1] / 1000);
1278         my $msecs = $b - $a;
1279
1280         my $s = "forkcall stats: $call '$line' ";
1281         $s .= "${msecs}mS";
1282         dbg($s);
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         return ($cmdref->(@$args)) if $self->{_nospawn};
1315         
1316         my $fc = Mojo::IOLoop::Subprocess->new;
1317 #       $fc->serializer(\&encode_json);
1318 #       $fc->deserializer(\&decode_json);
1319         $fc->run(
1320                          sub {
1321                                  my $subpro = shift;
1322                                  if (isdbg('spawn_cmd')) {
1323                                          my $s = "line: $line";
1324                                          $s .= ", args: " . join(', ', @$args) if $args && @$args;
1325                                  }
1326                                  my @res = $cmdref->(@$args);
1327                                  return @res;
1328                          },
1329 #                        $args,
1330                          sub {
1331                                  my ($fc, $err, @res) = @_; 
1332                                  my $dxchan = DXChannel::get($call);
1333                                  return unless $dxchan;
1334
1335                                  if ($err) {
1336                                          my $s = "DXCommand::spawn_cmd: call $call error $err";
1337                                          dbg($s) if isdbg('chan');
1338                                          $dxchan->send($s);
1339                                          return;
1340                                  }
1341                                  if ($cb) {
1342                                          # transform output if required
1343                                          @res = $cb->($dxchan, @res);
1344                                  }
1345                                  if (@res) {
1346                                          if (defined $prefix) {
1347                                                  $dxchan->send(map {"$prefix$_"} @res);
1348                                          } else {
1349                                                  $dxchan->send(@res);
1350                                          }
1351                                  }
1352                                  _diffms($call, $line, $t0);
1353                          });
1354         
1355         return @out;
1356 }
1357
1358 1;
1359 __END__