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