]> dxcluster.net Git - spider.git/blob - perl/DXCommandmode.pm
add 1702 prefix cty.dat data
[spider.git] / perl / DXCommandmode.pm
1 #!/usr/bin/perl
2 #
3 # This module impliments the user facing command mode for a dx cluster
4 #
5 # Copyright (c) 1998 Dirk Koopman G1TLH
6 #
7 # $Id$
8
9
10 package DXCommandmode;
11
12 #use POSIX;
13
14 @ISA = qw(DXChannel);
15
16 use POSIX qw(:math_h);
17 use DXUtil;
18 use DXChannel;
19 use DXUser;
20 use DXVars;
21 use DXDebug;
22 use DXM;
23 use DXLog;
24 use DXLogPrint;
25 use DXBearing;
26 use CmdAlias;
27 use Filter;
28 use Minimuf;
29 use DXDb;
30 use AnnTalk;
31 use WCY;
32 use Sun;
33 use Internet;
34 use Script;
35 use Net::Telnet;
36 use QSL;
37 use DB_File;
38 use VE7CC;
39 use DXXml;
40
41 use strict;
42 use vars qw(%Cache %cmd_cache $errstr %aliases $scriptbase $maxerrors %nothereslug
43         $maxbadcount $msgpolltime $default_pagelth $cmdimportdir);
44
45 %Cache = ();                                    # cache of dynamically loaded routine's mod times
46 %cmd_cache = ();                                # cache of short names
47 $errstr = ();                                   # error string from eval
48 %aliases = ();                                  # aliases for (parts of) commands
49 $scriptbase = "$main::root/scripts"; # the place where all users start scripts go
50 $maxerrors = 20;                                # the maximum number of concurrent errors allowed before disconnection
51 $maxbadcount = 3;                               # no of bad words allowed before disconnection
52 $msgpolltime = 3600;                    # the time between polls for new messages 
53 $cmdimportdir = "$main::root/cmd_import"; # the base directory for importing command scripts 
54                                           # this does not exist as default, you need to create it manually
55                                           #
56
57 use vars qw($VERSION $BRANCH);
58 $VERSION = sprintf( "%d.%03d", q$Revision$ =~ /(\d+)\.(\d+)/ );
59 $BRANCH = sprintf( "%d.%03d", q$Revision$ =~ /\d+\.\d+\.(\d+)\.(\d+)/  || (0,0));
60 $main::build += $VERSION;
61 $main::branch += $BRANCH;
62
63 #
64 # obtain a new connection this is derived from dxchannel
65 #
66
67 sub new 
68 {
69         my $self = DXChannel::alloc(@_);
70
71         # routing, this must go out here to prevent race condx
72         my $pkg = shift;
73         my $call = shift;
74         my @rout = $main::routeroot->add_user($call, Route::here(1));
75
76         # ALWAYS output the user
77         my $ref = Route::User::get($call);
78         $main::me->route_pc16($main::mycall, undef, $main::routeroot, $ref) if $ref;
79
80         return $self;
81 }
82
83 # this is how a a connection starts, you get a hello message and the motd with
84 # possibly some other messages asking you to set various things up if you are
85 # new (or nearly new and slacking) user.
86
87 sub start
88
89         my ($self, $line, $sort) = @_;
90         my $user = $self->{user};
91         my $call = $self->{call};
92         my $name = $user->{name};
93         
94         # log it
95         my $host = $self->{conn}->{peerhost};
96         $host ||= "AGW Port #$self->{conn}->{agwport}" if exists $self->{conn}->{agwport};
97         $host ||= "unknown";
98         LogDbg('DXCommand', "$call connected from $host");
99
100         $self->{name} = $name ? $name : $call;
101         $self->send($self->msg('l2',$self->{name}));
102         $self->state('prompt');         # a bit of room for further expansion, passwords etc
103         $self->{priv} = $user->priv || 0;
104         $self->{lang} = $user->lang || $main::lang || 'en';
105         my $pagelth = $user->pagelth;
106         $pagelth = $default_pagelth unless defined $pagelth;
107         $self->{pagelth} = $pagelth;
108         ($self->{width}) = $line =~ /width=(\d+)/; $line =~ s/\s*width=\d+\s*//;
109         $self->{width} = 80 unless $self->{width} && $self->{width} > 80;
110         $self->{consort} = $line;       # save the connection type
111         
112         # set some necessary flags on the user if they are connecting
113         $self->{beep} = $user->wantbeep;
114         $self->{ann} = $user->wantann;
115         $self->{wwv} = $user->wantwwv;
116         $self->{wcy} = $user->wantwcy;
117         $self->{talk} = $user->wanttalk;
118         $self->{wx} = $user->wantwx;
119         $self->{dx} = $user->wantdx;
120         $self->{logininfo} = $user->wantlogininfo;
121         $self->{ann_talk} = $user->wantann_talk;
122         $self->{here} = 1;
123         $self->{prompt} = $user->prompt if $user->prompt;
124
125         # sort out new dx spot stuff
126         $user->wantdxcq(0) unless defined $user->{wantdxcq};
127         $user->wantdxitu(0) unless defined $user->{wantdxitu};  
128         $user->wantusstate(0) unless defined $user->{wantusstate};
129
130         # sort out registration
131         if ($main::reqreg == 1) {
132                 $self->{registered} = $user->registered;
133         } elsif ($main::reqreg == 2) {
134                 $self->{registered} = !$user->registered;
135         } else {
136                 $self->{registered} = 1;
137         }
138
139
140         # decide which motd to send
141         my $motd;
142         unless ($self->{registered}) {
143                 $motd = "${main::motd}_nor_$self->{lang}";
144                 $motd = "${main::motd}_nor" unless -e $motd;
145         }
146         $motd = "${main::motd}_$self->{lang}" unless $motd && -e $motd;
147         $motd = $main::motd unless $motd && -e $motd;
148         $self->send_file($motd) if -e $motd;
149
150         # sort out privilege reduction
151         $self->{priv} = 0 if $line =~ /^(ax|te)/ && !$self->conn->{usedpasswd};
152
153         # get the filters
154         my $nossid = $call;
155         $nossid =~ s/-\d+$//;
156         
157         $self->{spotsfilter} = Filter::read_in('spots', $call, 0) 
158                 || Filter::read_in('spots', $nossid, 0)
159                         || Filter::read_in('spots', 'user_default', 0);
160         $self->{wwvfilter} = Filter::read_in('wwv', $call, 0) 
161                 || Filter::read_in('wwv', $nossid, 0) 
162                         || Filter::read_in('wwv', 'user_default', 0);
163         $self->{wcyfilter} = Filter::read_in('wcy', $call, 0) 
164                 || Filter::read_in('wcy', $nossid, 0) 
165                         || Filter::read_in('wcy', 'user_default', 0);
166         $self->{annfilter} = Filter::read_in('ann', $call, 0) 
167                 || Filter::read_in('ann', $nossid, 0) 
168                         || Filter::read_in('ann', 'user_default', 0) ;
169
170         # clean up qra locators
171         my $qra = $user->qra;
172         $qra = undef if ($qra && !DXBearing::is_qra($qra));
173         unless ($qra) {
174                 my $lat = $user->lat;
175                 my $long = $user->long;
176                 $user->qra(DXBearing::lltoqra($lat, $long)) if (defined $lat && defined $long);  
177         }
178
179         # decide on echo
180         my $echo = $user->wantecho;
181         unless ($echo) {
182                 $self->send_now('E', "0");
183                 $self->send($self->msg('echow'));
184                 $self->conn->echo($echo) if $self->conn->can('echo');
185         }
186         
187         $self->tell_login('loginu');
188         $self->tell_buddies('loginb');
189         
190         # do we need to send a forward/opernam?
191         my $lastoper = $user->lastoper || 0;
192         my $homenode = $user->homenode || ""; 
193         if ($homenode eq $main::mycall && $main::systime >= $lastoper + $DXUser::lastoperinterval) {
194                 run_cmd($main::me, "forward/opernam $call");
195                 $user->lastoper($main::systime + ((int rand(10)) * 86400));
196         }
197
198         # run a script send the output to the punter
199         my $script = new Script(lc $call) || new Script('user_default');
200         $script->run($self) if $script;
201
202         # send cluster info
203         my $info = Route::cluster();
204         $self->send("Cluster:$info");
205
206         # send prompts for qth, name and things
207         $self->send($self->msg('namee1')) if !$user->name;
208         $self->send($self->msg('qthe1')) if !$user->qth;
209         $self->send($self->msg('qll')) if !$user->qra || (!$user->lat && !$user->long);
210         $self->send($self->msg('hnodee1')) if !$user->qth;
211         $self->send($self->msg('m9')) if DXMsg::for_me($call);
212
213         # send out any buddy messages for other people that are online
214         foreach my $call (@{$user->buddies}) {
215                 my $ref = Route::User::get($call);
216                 if ($ref) {
217                         foreach my $node (@{$ref->parent}) {
218                                 $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         } 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
604         return if $self->{gtk};         # 'cos prompts are not a concept that applies here
605         
606         my $call = $self->call;
607         my $date = cldate($main::systime);
608         my $time = ztime($main::systime);
609         my $prompt = $self->{prompt} || $self->msg('pr');
610
611         $call = "($call)" unless $self->here;
612         $prompt =~ s/\%C/$call/g;
613         $prompt =~ s/\%D/$date/g;
614         $prompt =~ s/\%T/$time/g;
615         $prompt =~ s/\%M/$main::mycall/g;
616         
617         $self->send($prompt);
618 }
619
620 # broadcast a message to all users [except those mentioned after buffer]
621 sub broadcast
622 {
623         my $pkg = shift;                        # ignored
624         my $s = shift;                          # the line to be rebroadcast
625         
626     foreach my $dxchan (DXChannel::get_all()) {
627                 next unless $dxchan->{sort} eq 'U'; # only interested in user channels  
628                 next if grep $dxchan == $_, @_;
629                 $dxchan->send($s);                      # send it
630         }
631 }
632
633 # gimme all the users
634 sub get_all
635 {
636         return grep {$_->{sort} eq 'U'} DXChannel::get_all();
637 }
638
639 # run a script for this user
640 sub run_script
641 {
642         my $self = shift;
643         my $silent = shift || 0;
644         
645 }
646
647 #
648 # search for the command in the cache of short->long form commands
649 #
650
651 sub search
652 {
653         my ($path, $short_cmd, $suffix) = @_;
654         my ($apath, $acmd);
655         
656         # commands are lower case
657         $short_cmd = lc $short_cmd;
658         dbg("command: $path $short_cmd\n") if isdbg('command');
659
660         # do some checking for funny characters
661         return () if $short_cmd =~ /\/$/;
662
663         # return immediately if we have it
664         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
665         if ($apath && $acmd) {
666                 dbg("cached $short_cmd = ($apath, $acmd)\n") if isdbg('command');
667                 return ($apath, $acmd);
668         }
669         
670         # if not guess
671         my @parts = split '/', $short_cmd;
672         my $dirfn;
673         my $curdir = $path;
674         
675         while (my $p = shift @parts) {
676                 opendir(D, $curdir) or confess "can't open $curdir $!";
677                 my @ls = readdir D;
678                 closedir D;
679
680                 # if this isn't the last part
681                 if (@parts) {
682                         my $found;
683                         foreach my $l (sort @ls) {
684                                 next if $l =~ /^\./;
685                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
686                                         dbg("got dir: $curdir/$l\n") if isdbg('command');
687                                         $dirfn .= "$l/";
688                                         $curdir .= "/$l";
689                                         $found++;
690                                         last;
691                                 }
692                         }
693                         # only proceed if we find the directory asked for
694                         return () unless $found;
695                 } else {
696                         foreach my $l (sort @ls) {
697                                 next if $l =~ /^\./;
698                                 next unless $l =~ /\.$suffix$/;
699                                 if ($p eq substr($l, 0, length $p)) {
700                                         $l =~ s/\.$suffix$//;
701                                         $dirfn = "" unless $dirfn;
702                                         $cmd_cache{$short_cmd} = join(',', ($path, "$dirfn$l")); # cache it
703                                         dbg("got path: $path cmd: $dirfn$l\n") if isdbg('command');
704                                         return ($path, "$dirfn$l");
705                                 }
706                         }
707                 }
708         }
709
710         return ();  
711 }  
712
713 # clear the command name cache
714 sub clear_cmd_cache
715 {
716         no strict 'refs';
717         
718         for (keys %Cache) {
719                 undef *{$_} unless /cmd_cache/;
720                 dbg("Undefining cmd $_") if isdbg('command');
721         }
722         %cmd_cache = ();
723         %Cache = ();
724 }
725
726 #
727 # the persistant execution of things from the command directories
728 #
729 #
730 # This allows perl programs to call functions dynamically
731
732 # This has been nicked directly from the perlembed pages
733 #
734
735 #require Devel::Symdump;  
736
737 sub valid_package_name {
738         my($string) = @_;
739         $string =~ s|([^A-Za-z0-9_/])|sprintf("_%2x",unpack("C",$1))|eg;
740         
741         $string =~ s|/|_|g;
742         return "cmd_$string";
743 }
744
745
746 # this bit of magic finds a command in the offered directory
747 sub find_cmd_name {
748         my $path = shift;
749         my $cmdname = shift;
750         my $package = valid_package_name($cmdname);
751         my $filename = "$path/$cmdname.pl";
752         my $mtime = -M $filename;
753         
754         # return if we can't find it
755         $errstr = undef;
756         unless (defined $mtime) {
757                 $errstr = DXM::msg('e1');
758                 return undef;
759         }
760         
761         if(defined $Cache{$package}->{mtime} &&$Cache{$package}->{mtime} <= $mtime) {
762                 #we have compiled this subroutine already,
763                 #it has not been updated on disk, nothing left to do
764                 #print STDERR "already compiled $package->handler\n";
765                 ;
766         } else {
767
768                 my $sub = readfilestr($filename);
769                 unless ($sub) {
770                         $errstr = "Syserr: can't open '$filename' $!";
771                         return undef;
772                 };
773                 
774                 #wrap the code into a subroutine inside our unique package
775                 my $eval = qq( sub $package { $sub } );
776                 
777                 if (isdbg('eval')) {
778                         my @list = split /\n/, $eval;
779                         my $line;
780                         for (@list) {
781                                 dbg($_ . "\n") if isdbg('eval');
782                         }
783                 }
784                 
785                 # get rid of any existing sub and try to compile the new one
786                 no strict 'refs';
787
788                 if (exists $Cache{$package}) {
789                         dbg("Redefining $package") if isdbg('command');
790                         undef *$package;
791                 } else {
792                         dbg("Defining $package") if isdbg('command');
793                 }
794                 eval $eval;
795                 
796                 $Cache{$package} = {mtime => $mtime };
797             
798         }
799
800         return $package;
801 }
802
803 sub send
804 {
805         my $self = shift;
806         if ($self->{gtk}) {
807                 for (@_) {
808                         $self->SUPER::send(dd(['cmd',$_]));
809                 }
810         } else {
811                 $self->SUPER::send(@_);
812         }
813 }
814
815 sub local_send
816 {
817         my ($self, $let, $buf) = @_;
818         if ($self->{state} eq 'prompt' || $self->{state} eq 'talk') {
819                 if ($self->{enhanced}) {
820                         $self->send_later($let, $buf);
821                 } else {
822                         $self->send($buf);
823                 }
824         } else {
825                 $self->delay($buf);
826         }
827 }
828
829 # send a talk message here
830 sub talk
831 {
832         my ($self, $from, $to, $via, $line) = @_;
833         $line =~ s/\\5E/\^/g;
834         if ($self->{talk}) {
835                 if ($self->{gtk}) {
836                         $self->local_send('T', dd(['talk',$to,$from,$via,$line]));
837                 } else {
838                         $self->local_send('T', "$to de $from: $line");
839                 }
840         }
841         Log('talk', $to, $from, $via?$via:$main::mycall, $line);
842         # send a 'not here' message if required
843         unless ($self->{here} && $from ne $to) {
844                 my $key = "$to$from";
845                 unless (exists $nothereslug{$key}) {
846                         my ($ref, $dxchan);
847                         if (($ref = Route::get($from)) && ($dxchan = $ref->dxchan)) {
848                                 my $name = $self->user->name || $to;
849                                 my $s = $self->user->nothere || $dxchan->msg('nothere', $name);
850                                 $nothereslug{$key} = $main::systime;
851                                 $dxchan->talk($to, $from, undef, $s);
852                         }
853                 }
854         }
855 }
856
857 # send an announce
858 sub announce
859 {
860         my $self = shift;
861         my $line = shift;
862         my $isolate = shift;
863         my $to = shift;
864         my $target = shift;
865         my $text = shift;
866         my ($filter, $hops);
867
868         if (!$self->{ann_talk} && $to ne $self->{call}) {
869                 my $call = AnnTalk::is_talk_candidate($_[0], $text);
870                 return if $call;
871         }
872
873         if ($self->{annfilter}) {
874                 ($filter, $hops) = $self->{annfilter}->it(@_ );
875                 return unless $filter;
876         }
877
878         unless ($self->{ann}) {
879                 return if $_[0] ne $main::myalias && $_[0] ne $main::mycall;
880         }
881         return if $target eq 'SYSOP' && $self->{priv} < 5;
882         my $buf;
883         if ($self->{gtk}) {
884                 $buf = dd(['ann', $to, $target, $text, @_])
885         } else {
886                 $buf = "$to$target de $_[0]: $text";
887                 $buf =~ s/\%5E/^/g;
888                 $buf .= "\a\a" if $self->{beep};
889         }
890         $self->local_send($target eq 'WX' ? 'W' : 'N', $buf);
891 }
892
893 # send a chat
894 sub chat
895 {
896         my $self = shift;
897         my $line = shift;
898         my $isolate = shift;
899         my $target = shift;
900         my $to = shift;
901         my $text = shift;
902         my ($filter, $hops);
903
904         return unless grep uc $_ eq $target, @{$self->{user}->{group}};
905         
906         $text =~ s/^\#\d+ //;
907         my $buf;
908         if ($self->{gtk}) {
909                 $buf = dd(['chat', $to, $target, $text, @_])
910         } else {
911                 $buf = "$target de $_[0]: $text";
912                 $buf =~ s/\%5E/^/g;
913                 $buf .= "\a\a" if $self->{beep};
914         }
915         $self->local_send('C', $buf);
916 }
917
918 sub format_dx_spot
919 {
920         my $self = shift;
921
922         my $t = ztime($_[2]);
923         my $loc = '';
924         my $clth = $self->{consort} eq 'local' ? 29 : 30;
925         my $comment = substr $_[3], 0, $clth; 
926         $comment .= ' ' x ($clth - length($comment));
927         if ($self->{user}->wantgrid) { 
928                 my $ref = DXUser->get_current($_[4]);
929                 if ($ref) {
930                         $loc = $ref->qra || '';
931                         $loc = ' ' . substr($loc, 0, 4) if $loc;
932                 }
933         }
934
935         if ($self->{user}->wantdxitu) {
936                 $loc = ' ' . sprintf("%2d", $_[10]) if defined $_[10];
937                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . sprintf("%2d", $_[8]) if defined $_[8]; 
938         } elsif ($self->{user}->wantdxcq) {
939                 $loc = ' ' . sprintf("%2d", $_[11]) if defined $_[11];
940                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . sprintf("%2d", $_[9]) if defined $_[9]; 
941         } elsif ($self->{user}->wantusstate) {
942                 $loc = ' ' . $_[13] if $_[13];
943                 $comment = substr($comment, 0,  $self->{consort} eq 'local' ? 26 : 27) . ' ' . $_[12] if $_[12]; 
944         }
945
946         return sprintf "DX de %-7.7s%11.1f  %-12.12s %-s $t$loc", "$_[4]:", $_[0], $_[1], $comment;
947 }
948
949 # send a dx spot
950 sub dx_spot
951 {
952         my $self = shift;
953         my $line = shift;
954         my $isolate = shift;
955         return unless $self->{dx};
956
957         my ($filter, $hops);
958
959         if ($self->{spotsfilter}) {
960                 ($filter, $hops) = $self->{spotsfilter}->it(@_ );
961                 return unless $filter;
962         }
963
964         dbg('spot: "' . join('","', @_) . '"') if isdbg('dxspot');
965
966         my $buf;
967         if ($self->{ve7cc}) {
968                 $buf = VE7CC::dx_spot($self, @_);
969         } elsif ($self->{gtk}) {
970                 my ($dxloc, $byloc);
971
972                 my $ref = DXUser->get_current($_[4]);
973                 if ($ref) {
974                         $byloc = $ref->qra;
975                         $byloc = substr($byloc, 0, 4) if $byloc;
976                 }
977
978                 my $spot = $_[1];
979                 $spot =~ s|/\w{1,4}$||;
980                 $ref = DXUser->get_current($spot);
981                 if ($ref) {
982                         $dxloc = $ref->qra;
983                         $dxloc = substr($dxloc, 0, 4) if $dxloc;
984                 }
985                 $buf = dd(['dx', @_, ($dxloc||''), ($byloc||'')]);
986                 
987         } else {
988                 $buf = $self->format_dx_spot(@_);
989                 $buf .= "\a\a" if $self->{beep};
990                 $buf =~ s/\%5E/^/g;
991         }
992
993         $self->local_send('X', $buf);
994 }
995
996 sub wwv
997 {
998         my $self = shift;
999         my $line = shift;
1000         my $isolate = shift;
1001         my ($filter, $hops);
1002
1003         return unless $self->{wwv};
1004         
1005         if ($self->{wwvfilter}) {
1006                 ($filter, $hops) = $self->{wwvfilter}->it(@_[7..$#_] );
1007                 return unless $filter;
1008         }
1009
1010         my $buf;
1011         if ($self->{gtk}) {
1012                 $buf = dd(['wwv', @_])
1013         } else {
1014                 $buf = "WWV de $_[6] <$_[1]>:   SFI=$_[2], A=$_[3], K=$_[4], $_[5]";
1015                 $buf .= "\a\a" if $self->{beep};
1016         }
1017         
1018         $self->local_send('V', $buf);
1019 }
1020
1021 sub wcy
1022 {
1023         my $self = shift;
1024         my $line = shift;
1025         my $isolate = shift;
1026         my ($filter, $hops);
1027
1028         return unless $self->{wcy};
1029         
1030         if ($self->{wcyfilter}) {
1031                 ($filter, $hops) = $self->{wcyfilter}->it(@_ );
1032                 return unless $filter;
1033         }
1034
1035         my $buf;
1036         if ($self->{gtk}) {
1037                 $buf = dd(['wcy', @_])
1038         } else {
1039                 $buf = "WCY de $_[10] <$_[1]> : K=$_[4] expK=$_[5] A=$_[3] R=$_[6] SFI=$_[2] SA=$_[7] GMF=$_[8] Au=$_[9]";
1040                 $buf .= "\a\a" if $self->{beep};
1041         }
1042         $self->local_send('Y', $buf);
1043 }
1044
1045 # broadcast debug stuff to all interested parties
1046 sub broadcast_debug
1047 {
1048         my $s = shift;                          # the line to be rebroadcast
1049         
1050         foreach my $dxchan (DXChannel::get_all) {
1051                 next unless $dxchan->{enhanced} && $dxchan->{senddbg};
1052                 if ($dxchan->{gtk}) {
1053                         $dxchan->send_later('L', dd(['db', $s]));
1054                 } else {
1055                         $dxchan->send_later('L', $s);
1056                 }
1057         }
1058 }
1059
1060 sub do_entry_stuff
1061 {
1062         my $self = shift;
1063         my $line = shift;
1064         my @out;
1065         
1066         if ($self->state eq 'enterbody') {
1067                 my $loc = $self->{loc} || confess "local var gone missing" ;
1068                 if ($line eq "\032" || $line eq '%1A' || uc $line eq "/EX") {
1069                         no strict 'refs';
1070                         push @out, &{$loc->{endaction}}($self);          # like this for < 5.8.0
1071                         $self->func(undef);
1072                         $self->state('prompt');
1073                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
1074                         push @out, $self->msg('m10');
1075                         delete $loc->{lines};
1076                         delete $self->{loc};
1077                         $self->func(undef);
1078                         $self->state('prompt');
1079                 } else {
1080                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
1081                         # i.e. it ain't and end or abort, therefore store the line
1082                 }
1083         } else {
1084                 confess "Invalid state $self->{state}";
1085         }
1086         return @out;
1087 }
1088
1089 sub store_startup_script
1090 {
1091         my $self = shift;
1092         my $loc = $self->{loc} || confess "local var gone missing" ;
1093         my @out;
1094         my $call = $loc->{call} || confess "callsign gone missing";
1095         confess "lines array gone missing" unless ref $loc->{lines};
1096         my $r = Script::store($call, $loc->{lines});
1097         if (defined $r) {
1098                 if ($r) {
1099                         push @out, $self->msg('m19', $call, $r);
1100                 } else {
1101                         push @out, $self->msg('m20', $call);
1102                 }
1103         } else {
1104                 push @out, "error opening startup script $call $!";
1105         } 
1106         return @out;
1107 }
1108
1109 # Import any commands contained in any files in import_cmd directory
1110 #
1111 # If the filename has a recogisable callsign as some delimited part
1112 # of it, then this is the user the command will be run as. 
1113 #
1114 sub import_cmd
1115 {
1116         # are there any to do in this directory?
1117         return unless -d $cmdimportdir;
1118         unless (opendir(DIR, $cmdimportdir)) {
1119                 LogDbg('err', "can\'t open $cmdimportdir $!");
1120                 return;
1121         } 
1122
1123         my @names = readdir(DIR);
1124         closedir(DIR);
1125         my $name;
1126         foreach $name (@names) {
1127                 next if $name =~ /^\./;
1128
1129                 my $s = Script->new($name, $cmdimportdir);
1130                 if ($s) {
1131                         LogDbg('DXCommand', "Run import cmd file $name");
1132                         my @cat = split /[^A-Za-z0-9]+/, $name;
1133                         my ($call) = grep {is_callsign(uc $_)} @cat;
1134                         $call ||= $main::mycall;
1135                         $call = uc $call;
1136                         my @out;
1137                         
1138                         
1139                         $s->inscript(0);        # switch off script checks
1140                         
1141                         if ($call eq $main::mycall) {
1142                                 @out = $s->run($main::me, 1);
1143                         } else {
1144                                 my $dxchan = DXChannel::get($call);
1145                             if ($dxchan) {
1146                                         @out = $s->run($dxchan, 1);
1147                                 } else {
1148                                         my $u = DXUser->get($call);
1149                                         if ($u) {
1150                                                 $dxchan = $main::me;
1151                                                 my $old = $dxchan->{call};
1152                                                 my $priv = $dxchan->{priv};
1153                                                 my $user = $dxchan->{user};
1154                                                 $dxchan->{call} = $call;
1155                                                 $dxchan->{priv} = $u->priv;
1156                                                 $dxchan->{user} = $u;
1157                                                 @out = $s->run($dxchan, 1);
1158                                                 $dxchan->{call} = $call;
1159                                                 $dxchan->{priv} = $priv;
1160                                                 $dxchan->{user} = $user;
1161                                         } else {
1162                                                 LogDbg('err', "Trying to run import cmd for non-existant user $call");
1163                                         }
1164                                 }
1165                         }
1166                         $s->erase;
1167                         for (@out) {
1168                                 LogDbg('DXCommand', "Import cmd $name/$call: $_");
1169                         }
1170                 } else {
1171                         LogDbg('err', "Failed to open $cmdimportdir/$name $!");
1172                         unlink "$cmdimportdir/$name";
1173                 }
1174         }
1175 }
1176 1;
1177 __END__