]> dxcluster.net Git - spider.git/blob - perl/DXCommandmode.pm
fiddle with pc20/22 some more
[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, $BRANCH) = dxver(q$Revision$);
59
60 #
61 # obtain a new connection this is derived from dxchannel
62 #
63
64 sub new 
65 {
66         my $self = DXChannel::alloc(@_);
67
68         # routing, this must go out here to prevent race condx
69         my $pkg = shift;
70         my $call = shift;
71         my @rout = $main::routeroot->add_user($call, Route::here(1));
72
73         # ALWAYS output the user
74         my $ref = Route::User::get($call);
75         if ($ref) {
76                 $main::me->route_pc16($main::mycall, undef, $main::routeroot, $ref);
77                 $main::me->route_pc92a($main::mycall, undef, $main::routeroot, $ref);
78         }
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                                 $self->send($self->msg($node eq $main::mycall ? 'loginb' : 'loginbn', $call, $node));
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                 $main::me->route_pc92d($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
605         return if $self->{gtk};         # 'cos prompts are not a concept that applies here
606         
607         my $call = $self->call;
608         my $date = cldate($main::systime);
609         my $time = ztime($main::systime);
610         my $prompt = $self->{prompt} || $self->msg('pr');
611
612         $call = "($call)" unless $self->here;
613         $prompt =~ s/\%C/$call/g;
614         $prompt =~ s/\%D/$date/g;
615         $prompt =~ s/\%T/$time/g;
616         $prompt =~ s/\%M/$main::mycall/g;
617         
618         $self->send($prompt);
619 }
620
621 # broadcast a message to all users [except those mentioned after buffer]
622 sub broadcast
623 {
624         my $pkg = shift;                        # ignored
625         my $s = shift;                          # the line to be rebroadcast
626         
627     foreach my $dxchan (DXChannel::get_all()) {
628                 next unless $dxchan->{sort} eq 'U'; # only interested in user channels  
629                 next if grep $dxchan == $_, @_;
630                 $dxchan->send($s);                      # send it
631         }
632 }
633
634 # gimme all the users
635 sub get_all
636 {
637         return grep {$_->{sort} eq 'U'} DXChannel::get_all();
638 }
639
640 # run a script for this user
641 sub run_script
642 {
643         my $self = shift;
644         my $silent = shift || 0;
645         
646 }
647
648 #
649 # search for the command in the cache of short->long form commands
650 #
651
652 sub search
653 {
654         my ($path, $short_cmd, $suffix) = @_;
655         my ($apath, $acmd);
656         
657         # commands are lower case
658         $short_cmd = lc $short_cmd;
659         dbg("command: $path $short_cmd\n") if isdbg('command');
660
661         # do some checking for funny characters
662         return () if $short_cmd =~ /\/$/;
663
664         # return immediately if we have it
665         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
666         if ($apath && $acmd) {
667                 dbg("cached $short_cmd = ($apath, $acmd)\n") if isdbg('command');
668                 return ($apath, $acmd);
669         }
670         
671         # if not guess
672         my @parts = split '/', $short_cmd;
673         my $dirfn;
674         my $curdir = $path;
675         
676         while (my $p = shift @parts) {
677                 opendir(D, $curdir) or confess "can't open $curdir $!";
678                 my @ls = readdir D;
679                 closedir D;
680
681                 # if this isn't the last part
682                 if (@parts) {
683                         my $found;
684                         foreach my $l (sort @ls) {
685                                 next if $l =~ /^\./;
686                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
687                                         dbg("got dir: $curdir/$l\n") if isdbg('command');
688                                         $dirfn .= "$l/";
689                                         $curdir .= "/$l";
690                                         $found++;
691                                         last;
692                                 }
693                         }
694                         # only proceed if we find the directory asked for
695                         return () unless $found;
696                 } else {
697                         foreach my $l (sort @ls) {
698                                 next if $l =~ /^\./;
699                                 next unless $l =~ /\.$suffix$/;
700                                 if ($p eq substr($l, 0, length $p)) {
701                                         $l =~ s/\.$suffix$//;
702                                         $dirfn = "" unless $dirfn;
703                                         $cmd_cache{$short_cmd} = join(',', ($path, "$dirfn$l")); # cache it
704                                         dbg("got path: $path cmd: $dirfn$l\n") if isdbg('command');
705                                         return ($path, "$dirfn$l");
706                                 }
707                         }
708                 }
709         }
710
711         return ();  
712 }  
713
714 # clear the command name cache
715 sub clear_cmd_cache
716 {
717         no strict 'refs';
718         
719         for (keys %Cache) {
720                 undef *{$_} unless /cmd_cache/;
721                 dbg("Undefining cmd $_") if isdbg('command');
722         }
723         %cmd_cache = ();
724         %Cache = ();
725 }
726
727 #
728 # the persistant execution of things from the command directories
729 #
730 #
731 # This allows perl programs to call functions dynamically
732
733 # This has been nicked directly from the perlembed pages
734 #
735
736 #require Devel::Symdump;  
737
738 sub valid_package_name {
739         my($string) = @_;
740         $string =~ s|([^A-Za-z0-9_/])|sprintf("_%2x",unpack("C",$1))|eg;
741         
742         $string =~ s|/|_|g;
743         return "cmd_$string";
744 }
745
746
747 # this bit of magic finds a command in the offered directory
748 sub find_cmd_name {
749         my $path = shift;
750         my $cmdname = shift;
751         my $package = valid_package_name($cmdname);
752         my $filename = "$path/$cmdname.pl";
753         my $mtime = -M $filename;
754         
755         # return if we can't find it
756         $errstr = undef;
757         unless (defined $mtime) {
758                 $errstr = DXM::msg('e1');
759                 return undef;
760         }
761         
762         if(defined $Cache{$package}->{mtime} &&$Cache{$package}->{mtime} <= $mtime) {
763                 #we have compiled this subroutine already,
764                 #it has not been updated on disk, nothing left to do
765                 #print STDERR "already compiled $package->handler\n";
766                 ;
767         } else {
768
769                 my $sub = readfilestr($filename);
770                 unless ($sub) {
771                         $errstr = "Syserr: can't open '$filename' $!";
772                         return undef;
773                 };
774                 
775                 #wrap the code into a subroutine inside our unique package
776                 my $eval = qq( sub $package { $sub } );
777                 
778                 if (isdbg('eval')) {
779                         my @list = split /\n/, $eval;
780                         my $line;
781                         for (@list) {
782                                 dbg($_ . "\n") if isdbg('eval');
783                         }
784                 }
785                 
786                 # get rid of any existing sub and try to compile the new one
787                 no strict 'refs';
788
789                 if (exists $Cache{$package}) {
790                         dbg("Redefining $package") if isdbg('command');
791                         undef *$package;
792                 } else {
793                         dbg("Defining $package") if isdbg('command');
794                 }
795                 eval $eval;
796                 
797                 $Cache{$package} = {mtime => $mtime };
798             
799         }
800
801         return $package;
802 }
803
804 sub send
805 {
806         my $self = shift;
807         if ($self->{gtk}) {
808                 for (@_) {
809                         $self->SUPER::send(dd(['cmd',$_]));
810                 }
811         } else {
812                 $self->SUPER::send(@_);
813         }
814 }
815
816 sub local_send
817 {
818         my ($self, $let, $buf) = @_;
819         if ($self->{state} eq 'prompt' || $self->{state} eq 'talk') {
820                 if ($self->{enhanced}) {
821                         $self->send_later($let, $buf);
822                 } else {
823                         $self->send($buf);
824                 }
825         } else {
826                 $self->delay($buf);
827         }
828 }
829
830 # send a talk message here
831 sub talk
832 {
833         my ($self, $from, $to, $via, $line) = @_;
834         $line =~ s/\\5E/\^/g;
835         if ($self->{talk}) {
836                 if ($self->{gtk}) {
837                         $self->local_send('T', dd(['talk',$to,$from,$via,$line]));
838                 } else {
839                         $self->local_send('T', "$to de $from: $line");
840                 }
841         }
842         Log('talk', $to, $from, $via?$via:$main::mycall, $line);
843         # send a 'not here' message if required
844         unless ($self->{here} && $from ne $to) {
845                 my $key = "$to$from";
846                 unless (exists $nothereslug{$key}) {
847                         my ($ref, $dxchan);
848                         if (($ref = Route::get($from)) && ($dxchan = $ref->dxchan)) {
849                                 my $name = $self->user->name || $to;
850                                 my $s = $self->user->nothere || $dxchan->msg('nothere', $name);
851                                 $nothereslug{$key} = $main::systime;
852                                 $dxchan->talk($to, $from, undef, $s);
853                         }
854                 }
855         }
856 }
857
858 # send an announce
859 sub announce
860 {
861         my $self = shift;
862         my $line = shift;
863         my $isolate = shift;
864         my $to = shift;
865         my $target = shift;
866         my $text = shift;
867         my ($filter, $hops);
868
869         if (!$self->{ann_talk} && $to ne $self->{call}) {
870                 my $call = AnnTalk::is_talk_candidate($_[0], $text);
871                 return if $call;
872         }
873
874         if ($self->{annfilter}) {
875                 ($filter, $hops) = $self->{annfilter}->it(@_ );
876                 return unless $filter;
877         }
878
879         unless ($self->{ann}) {
880                 return if $_[0] ne $main::myalias && $_[0] ne $main::mycall;
881         }
882         return if $target eq 'SYSOP' && $self->{priv} < 5;
883         my $buf;
884         if ($self->{gtk}) {
885                 $buf = dd(['ann', $to, $target, $text, @_])
886         } else {
887                 $buf = "$to$target de $_[0]: $text";
888                 $buf =~ s/\%5E/^/g;
889                 $buf .= "\a\a" if $self->{beep};
890         }
891         $self->local_send($target eq 'WX' ? 'W' : 'N', $buf);
892 }
893
894 # send a chat
895 sub chat
896 {
897         my $self = shift;
898         my $line = shift;
899         my $isolate = shift;
900         my $target = shift;
901         my $to = shift;
902         my $text = shift;
903         my ($filter, $hops);
904
905         return unless grep uc $_ eq $target, @{$self->{user}->{group}};
906         
907         $text =~ s/^\#\d+ //;
908         my $buf;
909         if ($self->{gtk}) {
910                 $buf = dd(['chat', $to, $target, $text, @_])
911         } else {
912                 $buf = "$target de $_[0]: $text";
913                 $buf =~ s/\%5E/^/g;
914                 $buf .= "\a\a" if $self->{beep};
915         }
916         $self->local_send('C', $buf);
917 }
918
919 sub format_dx_spot
920 {
921         my $self = shift;
922
923         my $t = ztime($_[2]);
924         my $loc = '';
925         my $clth = $self->{consort} eq 'local' ? 29 : 30;
926         my $comment = substr $_[3], 0, $clth; 
927         $comment .= ' ' x ($clth - length($comment));
928         if ($self->{user}->wantgrid) { 
929                 my $ref = DXUser->get_current($_[4]);
930                 if ($ref) {
931                         $loc = $ref->qra || '';
932                         $loc = ' ' . substr($loc, 0, 4) if $loc;
933                 }
934         }
935
936         if ($self->{user}->wantdxitu) {
937                 $loc = ' ' . sprintf("%2d", $_[10]) if defined $_[10];
938                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . sprintf("%2d", $_[8]) if defined $_[8]; 
939         } elsif ($self->{user}->wantdxcq) {
940                 $loc = ' ' . sprintf("%2d", $_[11]) if defined $_[11];
941                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . sprintf("%2d", $_[9]) if defined $_[9]; 
942         } elsif ($self->{user}->wantusstate) {
943                 $loc = ' ' . $_[13] if $_[13];
944                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . $_[12] if $_[12]; 
945         }
946
947         return sprintf "DX de %-7.7s%11.1f  %-12.12s %-s $t$loc", "$_[4]:", $_[0], $_[1], $comment;
948 }
949
950 # send a dx spot
951 sub dx_spot
952 {
953         my $self = shift;
954         my $line = shift;
955         my $isolate = shift;
956         return unless $self->{dx};
957
958         my ($filter, $hops);
959
960         if ($self->{spotsfilter}) {
961                 ($filter, $hops) = $self->{spotsfilter}->it(@_ );
962                 return unless $filter;
963         }
964
965         dbg('spot: "' . join('","', @_) . '"') if isdbg('dxspot');
966
967         my $buf;
968         if ($self->{ve7cc}) {
969                 $buf = VE7CC::dx_spot($self, @_);
970         } elsif ($self->{gtk}) {
971                 my ($dxloc, $byloc);
972
973                 my $ref = DXUser->get_current($_[4]);
974                 if ($ref) {
975                         $byloc = $ref->qra;
976                         $byloc = substr($byloc, 0, 4) if $byloc;
977                 }
978
979                 my $spot = $_[1];
980                 $spot =~ s|/\w{1,4}$||;
981                 $ref = DXUser->get_current($spot);
982                 if ($ref) {
983                         $dxloc = $ref->qra;
984                         $dxloc = substr($dxloc, 0, 4) if $dxloc;
985                 }
986                 $buf = dd(['dx', @_, ($dxloc||''), ($byloc||'')]);
987                 
988         } else {
989                 $buf = $self->format_dx_spot(@_);
990                 $buf .= "\a\a" if $self->{beep};
991                 $buf =~ s/\%5E/^/g;
992         }
993
994         $self->local_send('X', $buf);
995 }
996
997 sub wwv
998 {
999         my $self = shift;
1000         my $line = shift;
1001         my $isolate = shift;
1002         my ($filter, $hops);
1003
1004         return unless $self->{wwv};
1005         
1006         if ($self->{wwvfilter}) {
1007                 ($filter, $hops) = $self->{wwvfilter}->it(@_[7..$#_] );
1008                 return unless $filter;
1009         }
1010
1011         my $buf;
1012         if ($self->{gtk}) {
1013                 $buf = dd(['wwv', @_])
1014         } else {
1015                 $buf = "WWV de $_[6] <$_[1]>:   SFI=$_[2], A=$_[3], K=$_[4], $_[5]";
1016                 $buf .= "\a\a" if $self->{beep};
1017         }
1018         
1019         $self->local_send('V', $buf);
1020 }
1021
1022 sub wcy
1023 {
1024         my $self = shift;
1025         my $line = shift;
1026         my $isolate = shift;
1027         my ($filter, $hops);
1028
1029         return unless $self->{wcy};
1030         
1031         if ($self->{wcyfilter}) {
1032                 ($filter, $hops) = $self->{wcyfilter}->it(@_ );
1033                 return unless $filter;
1034         }
1035
1036         my $buf;
1037         if ($self->{gtk}) {
1038                 $buf = dd(['wcy', @_])
1039         } else {
1040                 $buf = "WCY de $_[10] <$_[1]> : K=$_[4] expK=$_[5] A=$_[3] R=$_[6] SFI=$_[2] SA=$_[7] GMF=$_[8] Au=$_[9]";
1041                 $buf .= "\a\a" if $self->{beep};
1042         }
1043         $self->local_send('Y', $buf);
1044 }
1045
1046 # broadcast debug stuff to all interested parties
1047 sub broadcast_debug
1048 {
1049         my $s = shift;                          # the line to be rebroadcast
1050         
1051         foreach my $dxchan (DXChannel::get_all) {
1052                 next unless $dxchan->{enhanced} && $dxchan->{senddbg};
1053                 if ($dxchan->{gtk}) {
1054                         $dxchan->send_later('L', dd(['db', $s]));
1055                 } else {
1056                         $dxchan->send_later('L', $s);
1057                 }
1058         }
1059 }
1060
1061 sub do_entry_stuff
1062 {
1063         my $self = shift;
1064         my $line = shift;
1065         my @out;
1066         
1067         if ($self->state eq 'enterbody') {
1068                 my $loc = $self->{loc} || confess "local var gone missing" ;
1069                 if ($line eq "\032" || $line eq '%1A' || uc $line eq "/EX") {
1070                         no strict 'refs';
1071                         push @out, &{$loc->{endaction}}($self);          # like this for < 5.8.0
1072                         $self->func(undef);
1073                         $self->state('prompt');
1074                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
1075                         push @out, $self->msg('m10');
1076                         delete $loc->{lines};
1077                         delete $self->{loc};
1078                         $self->func(undef);
1079                         $self->state('prompt');
1080                 } else {
1081                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
1082                         # i.e. it ain't and end or abort, therefore store the line
1083                 }
1084         } else {
1085                 confess "Invalid state $self->{state}";
1086         }
1087         return @out;
1088 }
1089
1090 sub store_startup_script
1091 {
1092         my $self = shift;
1093         my $loc = $self->{loc} || confess "local var gone missing" ;
1094         my @out;
1095         my $call = $loc->{call} || confess "callsign gone missing";
1096         confess "lines array gone missing" unless ref $loc->{lines};
1097         my $r = Script::store($call, $loc->{lines});
1098         if (defined $r) {
1099                 if ($r) {
1100                         push @out, $self->msg('m19', $call, $r);
1101                 } else {
1102                         push @out, $self->msg('m20', $call);
1103                 }
1104         } else {
1105                 push @out, "error opening startup script $call $!";
1106         } 
1107         return @out;
1108 }
1109
1110 # Import any commands contained in any files in import_cmd directory
1111 #
1112 # If the filename has a recogisable callsign as some delimited part
1113 # of it, then this is the user the command will be run as. 
1114 #
1115 sub import_cmd
1116 {
1117         # are there any to do in this directory?
1118         return unless -d $cmdimportdir;
1119         unless (opendir(DIR, $cmdimportdir)) {
1120                 LogDbg('err', "can\'t open $cmdimportdir $!");
1121                 return;
1122         } 
1123
1124         my @names = readdir(DIR);
1125         closedir(DIR);
1126         my $name;
1127         foreach $name (@names) {
1128                 next if $name =~ /^\./;
1129
1130                 my $s = Script->new($name, $cmdimportdir);
1131                 if ($s) {
1132                         LogDbg('DXCommand', "Run import cmd file $name");
1133                         my @cat = split /[^A-Za-z0-9]+/, $name;
1134                         my ($call) = grep {is_callsign(uc $_)} @cat;
1135                         $call ||= $main::mycall;
1136                         $call = uc $call;
1137                         my @out;
1138                         
1139                         
1140                         $s->inscript(0);        # switch off script checks
1141                         
1142                         if ($call eq $main::mycall) {
1143                                 @out = $s->run($main::me, 1);
1144                         } else {
1145                                 my $dxchan = DXChannel::get($call);
1146                             if ($dxchan) {
1147                                         @out = $s->run($dxchan, 1);
1148                                 } else {
1149                                         my $u = DXUser->get($call);
1150                                         if ($u) {
1151                                                 $dxchan = $main::me;
1152                                                 my $old = $dxchan->{call};
1153                                                 my $priv = $dxchan->{priv};
1154                                                 my $user = $dxchan->{user};
1155                                                 $dxchan->{call} = $call;
1156                                                 $dxchan->{priv} = $u->priv;
1157                                                 $dxchan->{user} = $u;
1158                                                 @out = $s->run($dxchan, 1);
1159                                                 $dxchan->{call} = $call;
1160                                                 $dxchan->{priv} = $priv;
1161                                                 $dxchan->{user} = $user;
1162                                         } else {
1163                                                 LogDbg('err', "Trying to run import cmd for non-existant user $call");
1164                                         }
1165                                 }
1166                         }
1167                         $s->erase;
1168                         for (@out) {
1169                                 LogDbg('DXCommand', "Import cmd $name/$call: $_");
1170                         }
1171                 } else {
1172                         LogDbg('err', "Failed to open $cmdimportdir/$name $!");
1173                         unlink "$cmdimportdir/$name";
1174                 }
1175         }
1176 }
1177 1;
1178 __END__