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