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