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