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