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