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