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