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