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