Now (apparent) apparently working
[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 #
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 QSL;
36 use DB_File;
37 use VE7CC;
38 use DXXml;
39 use AsyncMsg;
40
41 use strict;
42 use vars qw(%Cache %cmd_cache $errstr %aliases $scriptbase %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 $maxbadcount = 3;                               # no of bad words allowed before disconnection
51 $msgpolltime = 3600;                    # the time between polls for new messages 
52 $cmdimportdir = "$main::root/cmd_import"; # the base directory for importing command scripts 
53                                           # this does not exist as default, you need to create it manually
54 #
55
56 #
57 # obtain a new connection this is derived from dxchannel
58 #
59
60 sub new 
61 {
62         my $self = DXChannel::alloc(@_);
63
64         # routing, this must go out here to prevent race condx
65         my $pkg = shift;
66         my $call = shift;
67 #       my @rout = $main::routeroot->add_user($call, Route::here(1));
68         DXProt::_add_thingy($main::routeroot, [$call, 0, 0, 1, undef, undef, $self->{conn}->peerhost], );
69
70         # ALWAYS output the user
71         my $ref = Route::User::get($call);
72         if ($ref) {
73                 $main::me->route_pc16($main::mycall, undef, $main::routeroot, $ref);
74                 $main::me->route_pc92a($main::mycall, undef, $main::routeroot, $ref) unless $DXProt::pc92_slug_changes;
75         }
76
77         return $self;
78 }
79
80 # this is how a a connection starts, you get a hello message and the motd with
81 # possibly some other messages asking you to set various things up if you are
82 # new (or nearly new and slacking) user.
83
84 sub start
85
86         my ($self, $line, $sort) = @_;
87         my $user = $self->{user};
88         my $call = $self->{call};
89         my $name = $user->{name};
90         
91         # log it
92         my $host = $self->{conn}->peerhost;
93         $host ||= "AGW Port #$self->{conn}->{agwport}" if exists $self->{conn}->{agwport};
94         $host ||= "unknown";
95         $self->{hostname} = $host;
96         LogDbg('DXCommand', "$call connected from $host");
97
98         $self->{name} = $name ? $name : $call;
99         $self->send($self->msg('l2',$self->{name}));
100         $self->state('prompt');         # a bit of room for further expansion, passwords etc
101         $self->{priv} = $user->priv || 0;
102         $self->{lang} = $user->lang || $main::lang || 'en';
103         my $pagelth = $user->pagelth;
104         $pagelth = $default_pagelth unless defined $pagelth;
105         $self->{pagelth} = $pagelth;
106         ($self->{width}) = $line =~ /width=(\d+)/; $line =~ s/\s*width=\d+\s*//;
107         $self->{width} = 80 unless $self->{width} && $self->{width} > 80;
108         $self->{consort} = $line;       # save the connection type
109         
110         # set some necessary flags on the user if they are connecting
111         $self->{beep} = $user->wantbeep;
112         $self->{ann} = $user->wantann;
113         $self->{wwv} = $user->wantwwv;
114         $self->{wcy} = $user->wantwcy;
115         $self->{talk} = $user->wanttalk;
116         $self->{wx} = $user->wantwx;
117         $self->{dx} = $user->wantdx;
118         $self->{logininfo} = $user->wantlogininfo;
119         $self->{ann_talk} = $user->wantann_talk;
120         $self->{here} = 1;
121         $self->{prompt} = $user->prompt if $user->prompt;
122         $self->{lastmsgpoll} = 0;
123
124         # sort out new dx spot stuff
125         $user->wantdxcq(0) unless defined $user->{wantdxcq};
126         $user->wantdxitu(0) unless defined $user->{wantdxitu};  
127         $user->wantusstate(0) unless defined $user->{wantusstate};
128
129         # sort out registration (who wanted 2???) Note registration *could* be used even when reqreg == 0
130         if ($main::reqreg == 2) {
131                 $self->{registered} = !$user->registered;
132         } else {
133                 $self->{registered} = $user->registered;
134         }
135
136         # establish slug queue, if required
137     $self->{sluggedpcs} = [];
138     $self->{isslugged} = $DXProt::pc92_slug_changes + $DXProt::last_pc92_slug + 5 if $DXProt::pc92_slug_changes;
139     $self->{isslugged} = 0 if $self->{priv} > 0 || $user->registered || $user->homenode eq $main::mycall;
140
141         # send the relevant MOTD
142         $self->send_motd;
143
144         # sort out privilege reduction
145         $self->{priv} = 0 unless $self->{hostname} eq '127.0.0.1' || $self->{hostname} eq '::1' || $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->parents) {
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' || $self->{state} eq 'chat') {
303                 if ($cmdline =~ m{^(?:/EX|/ABORT)}i) {
304                         for (@{$self->{talklist}}) {
305                                 if ($self->{state} eq 'talk') {
306                                         $self->send_talks($_,  $self->msg('talkend'));
307                                 } else {
308                                         $self->local_send('C', $self->msg('chatend', $_));
309                                 }
310                         }
311                         $self->state('prompt');
312                         delete $self->{talklist};
313                 } elsif ($cmdline =~ m|^/+\w+|) {
314                         $cmdline =~ s|^/||;
315                         my $sendit = $cmdline =~ s|^/+||;
316                         my @in = $self->run_cmd($cmdline);
317                         $self->send_ans(@in);
318                         if ($sendit && $self->{talklist} && @{$self->{talklist}}) {
319                                 foreach my $l (@in) {
320                                         my @bad;
321                                         if (@bad = BadWords::check($l)) {
322                                                 $self->badcount(($self->badcount||0) + @bad);
323                                                 LogDbg('DXCommand', "$self->{call} swore: $l with words:" . join(',', @bad) . ")");
324                                         } else {
325                                                 for (@{$self->{talklist}}) {
326                                                         if ($self->{state} eq 'talk') {
327                                                                 $self->send_talks($_, $l);
328                                                         } else {
329                                                                 send_chats($self, $_, $l)
330                                                         }
331                                                 }
332                                         }
333                                 }
334                         }
335                         $self->send($self->{state} eq 'talk' ? $self->talk_prompt : $self->chat_prompt);
336                 } elsif ($self->{talklist} && @{$self->{talklist}}) {
337                         # send what has been said to whoever is in this person's talk list
338                         my @bad;
339                         if (@bad = BadWords::check($cmdline)) {
340                                 $self->badcount(($self->badcount||0) + @bad);
341                                 LogDbg('DXCommand', "$self->{call} swore: $cmdline with words:" . join(',', @bad) . ")");
342                         } else {
343                                 for (@{$self->{talklist}}) {
344                                         if ($self->{state} eq 'talk') {
345                                                 $self->send_talks($_, $rawline);
346                                         } else {
347                                                 send_chats($self, $_, $rawline);
348                                         }
349                                 }
350                         }
351                         $self->send($self->talk_prompt) if $self->{state} eq 'talk';
352                         $self->send($self->chat_prompt) if $self->{state} eq 'chat';
353                 } else {
354                         # for safety
355                         $self->state('prompt');
356                 }
357         } elsif (my $func = $self->{func}) {
358                 no strict 'refs';
359                 my @ans;
360                 if (ref $self->{edit}) {
361                         eval { @ans = $self->{edit}->$func($self, $rawline)};
362                 } else {
363                         eval {  @ans = &{$self->{func}}($self, $rawline) };
364                 }
365                 if ($@) {
366                         $self->send_ans("Syserr: on stored func $self->{func}", $@);
367                         delete $self->{func};
368                         $self->state('prompt');
369                         undef $@;
370                 }
371                 $self->send_ans(@ans);
372         } else {
373                 $self->send_ans(run_cmd($self, $cmdline));
374         } 
375
376         # check for excessive swearing
377         if ($self->{badcount} && $self->{badcount} >= $maxbadcount) {
378                 LogDbg('DXCommand', "$self->{call} logged out for excessive swearing");
379                 $self->disconnect;
380                 return;
381         }
382
383         # send a prompt only if we are in a prompt state
384         $self->prompt() if $self->{state} =~ /^prompt/o;
385 }
386
387 # send out the talk messages taking into account vias and connectivity
388 sub send_talks
389 {
390         my ($self, $ent, $line) = @_;
391         
392         my ($to, $via) = $ent =~ /(\S+)>(\S+)/;
393         $to = $ent unless $to;
394         my $call = $via && $via ne '*' ? $via : $to;
395         my $clref = Route::get($call);
396         my $dxchan = $clref->dxchan if $clref;
397         if ($dxchan) {
398                 $dxchan->talk($self->{call}, $to, undef, $line);
399         } else {
400                 $self->send($self->msg('disc2', $via ? $via : $to));
401                 my @l = grep { $_ ne $ent } @{$self->{talklist}};
402                 if (@l) {
403                         $self->{talklist} = \@l;
404                 } else {
405                         delete $self->{talklist};
406                         $self->state('prompt');
407                 }
408         }
409 }
410
411 sub send_chats
412 {
413         my $self = shift;
414         my $target = shift;
415         my $text = shift;
416
417         my $msgid = DXProt::nextchatmsgid();
418         $text = "#$msgid $text";
419         $main::me->normal(DXProt::pc93($target, $self->{call}, undef, $text));
420 }
421
422 sub special_prompt
423 {
424         my $self = shift;
425         my $prompt = shift;
426         my @call;
427         for (@{$self->{talklist}}) {
428                 my ($to, $via) = /(\S+)>(\S+)/;
429                 $to = $_ unless $to;
430                 push @call, $to;
431         }
432         return $self->msg($prompt, join(',', @call));
433 }
434
435 sub talk_prompt
436 {
437         my $self = shift;
438         return $self->special_prompt('talkprompt');
439 }
440
441 sub chat_prompt
442 {
443         my $self = shift;
444         return $self->special_prompt('chatprompt');
445 }
446
447 #
448 # send a load of stuff to a command user with page prompting
449 # and stuff
450 #
451
452 sub send_ans
453 {
454         my $self = shift;
455         
456         if ($self->{pagelth} && @_ > $self->{pagelth}) {
457                 my $i;
458                 for ($i = $self->{pagelth}; $i-- > 0; ) {
459                         my $line = shift @_;
460                         $line =~ s/\s+$//o;     # why am having to do this? 
461                         $self->send($line);
462                 }
463                 $self->{pagedata} =  [ @_ ];
464                 $self->state('page');
465                 $self->send($self->msg('page', scalar @_));
466         } else {
467                 for (@_) {
468                         if (defined $_) {
469                                 $self->send($_);
470                         } else {
471                                 $self->send('');
472                         }
473                 }
474         } 
475 }
476
477
478 # this is the thing that runs the command, it is done like this for the 
479 # benefit of remote command execution
480 #
481
482 sub run_cmd
483 {
484         my $self = shift;
485         my $user = $self->{user};
486         my $call = $self->{call};
487         my $cmdline = shift;
488         my @ans;
489         
490         return () if length $cmdline == 0;
491         
492         # split the command line up into parts, the first part is the command
493         my ($cmd, $args) = split /\s+/, $cmdline, 2;
494         $args = "" unless defined $args;
495                 
496         if ($cmd) {
497
498                 # check cmd
499                 if ($cmd =~ m|^/| || $cmd =~ m|[^-?\w/]|) {
500                         LogDbg('DXCommand', "cmd: invalid characters in '$cmd'");
501                         return $self->_error_out('e1');
502                 }
503
504                 # strip out // on command only
505                 $cmd =~ s|//|/|g;
506                                         
507                 my ($path, $fcmd);
508                         
509                 dbg("cmd: $cmd") if isdbg('command');
510                         
511                 # alias it if possible
512                 my $acmd = CmdAlias::get_cmd($cmd);
513                 if ($acmd) {
514                         ($cmd, $args) = split /\s+/, "$acmd $args", 2;
515                         $args = "" unless defined $args;
516                         dbg("cmd: aliased $cmd $args") if isdbg('command');
517                 }
518                         
519                 # first expand out the entry to a command
520                 ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
521                 ($path, $fcmd) = search($main::cmd, $cmd, "pl") unless $path && $fcmd;
522
523                 if ($path && $cmd) {
524                         dbg("cmd: path $cmd cmd: $fcmd") if isdbg('command');
525                         
526                         my $package = find_cmd_name($path, $fcmd);
527                         return ($@) if $@;
528                                 
529                         if ($package && $self->can("${package}::handle")) {
530                                 no strict 'refs';
531                                 dbg("cmd: package $package") if isdbg('command');
532                                 eval { @ans = &{"${package}::handle"}($self, $args) };
533                                 return (DXDebug::shortmess($@)) if $@;
534                         } else {
535                                 dbg("cmd: $package not present") if isdbg('command');
536                                 return $self->_error_out('e1');
537                         }
538                 } else {
539                         dbg("cmd: $cmd not found") if isdbg('command');
540                         return $self->_error_out('e1');
541                 }
542         }
543         
544         my $ok = shift @ans;
545         if ($ok) {
546                 delete $self->{errors};
547         } else {
548                 if (++$self->{errors} > $DXChannel::maxerrors) {
549                         $self->send($self->msg('e26'));
550                         $self->disconnect;
551                         return ();
552                 }
553         }
554         return map {s/([^\s])\s+$/$1/; $_} @ans;
555 }
556
557 #
558 # This is called from inside the main cluster processing loop and is used
559 # for despatching commands that are doing some long processing job
560 #
561 sub process
562 {
563         my $t = time;
564         my @dxchan = DXChannel::get_all();
565         my $dxchan;
566         
567         foreach $dxchan (@dxchan) {
568                 next unless $dxchan->is_user;  
569         
570                 # send a outstanding message prompt if required
571                 if ($t >= $dxchan->lastmsgpoll + $msgpolltime) {
572                         $dxchan->send($dxchan->msg('m9')) if DXMsg::for_me($dxchan->call);
573                         $dxchan->{lastmsgpoll} = $t;
574                 }
575                 
576                 # send a prompt if no activity out on this channel
577                 if ($t >= $dxchan->t + $main::user_interval) {
578                         $dxchan->prompt() if $dxchan->{state} =~ /^prompt/o;
579                         $dxchan->t($t);
580                 }
581
582                 if ($dxchan->{isslugged} && $main::systime > $dxchan->{isslugged}) {
583                         foreach my $ref (@{$dxchan->{sluggedpcs}}) {
584                                 if ($ref->[0] == 61) {
585                                         Spot::add(@{$ref->[2]});
586                                         DXProt::send_dx_spot($dxchan, $ref->[1], @{$ref->[2]});
587                                 }
588                         }
589
590                         $dxchan->{isslugged} = 0;
591                         $dxchan->{sluggedpcs} = [];
592                 }
593         }
594
595         while (my ($k, $v) = each %nothereslug) {
596                 if ($main::systime >= $v + 300) {
597                         delete $nothereslug{$k};
598                 }
599         }
600
601         import_cmd();
602 }
603
604 #
605 # finish up a user context
606 #
607 sub disconnect
608 {
609         my $self = shift;
610         my $call = $self->call;
611
612         return if $self->{disconnecting}++;
613
614         delete $self->{senddbg};
615
616         my $uref = Route::User::get($call);
617         my @rout;
618         if ($uref) {
619 #               @rout = $main::routeroot->del_user($uref);
620                 @rout = DXProt::_del_thingy($main::routeroot, [$call, 0]);
621
622                 dbg("B/C PC17 on $main::mycall for: $call") if isdbg('route');
623
624                 # issue a pc17 to everybody interested
625                 $main::me->route_pc17($main::mycall, undef, $main::routeroot, $uref);
626                 $main::me->route_pc92d($main::mycall, undef, $main::routeroot, $uref) unless $DXProt::pc92_slug_changes;
627         } else {
628                 confess "trying to disconnect a non existant user $call";
629         }
630
631         # I was the last node visited
632     $self->user->node($main::mycall);
633                 
634         # send info to all logged in thingies
635         $self->tell_login('logoutu');
636         $self->tell_buddies('logoutb');
637
638         LogDbg('DXCommand', "$call disconnected");
639
640         $self->SUPER::disconnect;
641 }
642
643 #
644 # short cut to output a prompt
645 #
646
647 sub prompt
648 {
649         my $self = shift;
650
651         return if $self->{gtk};         # 'cos prompts are not a concept that applies here
652         
653         my $call = $self->call;
654         my $date = cldate($main::systime);
655         my $time = ztime($main::systime);
656         my $prompt = $self->{prompt} || $self->msg('pr');
657
658         $call = "($call)" unless $self->here;
659         $prompt =~ s/\%C/$call/g;
660         $prompt =~ s/\%D/$date/g;
661         $prompt =~ s/\%T/$time/g;
662         $prompt =~ s/\%M/$main::mycall/g;
663         
664         $self->send($prompt);
665 }
666
667 # broadcast a message to all users [except those mentioned after buffer]
668 sub broadcast
669 {
670         my $pkg = shift;                        # ignored
671         my $s = shift;                          # the line to be rebroadcast
672         
673     foreach my $dxchan (DXChannel::get_all()) {
674                 next unless $dxchan->{sort} eq 'U'; # only interested in user channels  
675                 next if grep $dxchan == $_, @_;
676                 $dxchan->send($s);                      # send it
677         }
678 }
679
680 # gimme all the users
681 sub get_all
682 {
683         return grep {$_->{sort} eq 'U'} DXChannel::get_all();
684 }
685
686 # run a script for this user
687 sub run_script
688 {
689         my $self = shift;
690         my $silent = shift || 0;
691         
692 }
693
694 #
695 # search for the command in the cache of short->long form commands
696 #
697
698 sub search
699 {
700         my ($path, $short_cmd, $suffix) = @_;
701         my ($apath, $acmd);
702         
703         # commands are lower case
704         $short_cmd = lc $short_cmd;
705         dbg("command: $path $short_cmd\n") if isdbg('command');
706
707         # do some checking for funny characters
708         return () if $short_cmd =~ /\/$/;
709
710         # return immediately if we have it
711         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
712         if ($apath && $acmd) {
713                 dbg("cached $short_cmd = ($apath, $acmd)\n") if isdbg('command');
714                 return ($apath, $acmd);
715         }
716         
717         # if not guess
718         my @parts = split '/', $short_cmd;
719         my $dirfn;
720         my $curdir = $path;
721         
722         while (my $p = shift @parts) {
723                 opendir(D, $curdir) or confess "can't open $curdir $!";
724                 my @ls = readdir D;
725                 closedir D;
726
727                 # if this isn't the last part
728                 if (@parts) {
729                         my $found;
730                         foreach my $l (sort @ls) {
731                                 next if $l =~ /^\./;
732                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
733                                         dbg("got dir: $curdir/$l\n") if isdbg('command');
734                                         $dirfn .= "$l/";
735                                         $curdir .= "/$l";
736                                         $found++;
737                                         last;
738                                 }
739                         }
740                         # only proceed if we find the directory asked for
741                         return () unless $found;
742                 } else {
743                         foreach my $l (sort @ls) {
744                                 next if $l =~ /^\./;
745                                 next unless $l =~ /\.$suffix$/;
746                                 if ($p eq substr($l, 0, length $p)) {
747                                         $l =~ s/\.$suffix$//;
748                                         $dirfn = "" unless $dirfn;
749                                         $cmd_cache{$short_cmd} = join(',', ($path, "$dirfn$l")); # cache it
750                                         dbg("got path: $path cmd: $dirfn$l\n") if isdbg('command');
751                                         return ($path, "$dirfn$l");
752                                 }
753                         }
754                 }
755         }
756
757         return ();  
758 }  
759
760 # clear the command name cache
761 sub clear_cmd_cache
762 {
763         no strict 'refs';
764         
765         for my $k (keys %Cache) {
766                 unless ($k =~ /cmd_cache/) {
767                         dbg("Undefining cmd $k") if isdbg('command');
768                         undef $DXCommandmode::{"${k}::"};
769                 }
770         }
771         %cmd_cache = ();
772         %Cache = ( cmd_clear_cmd_cache  => $Cache{cmd_clear_cmd_cache} );
773 }
774
775 #
776 # the persistant execution of things from the command directories
777 #
778 #
779 # This allows perl programs to call functions dynamically
780
781 # This has been nicked directly from the perlembed pages
782 #
783 #require Devel::Symdump;  
784
785 sub valid_package_name {
786         my $string = shift;
787         $string =~ s|([^A-Za-z0-9_/])|sprintf("_%2x",unpack("C",$1))|eg;
788         
789         $string =~ s|/|_|g;
790         return "cmd_$string";
791 }
792
793
794 # this bit of magic finds a command in the offered directory
795 sub find_cmd_name {
796         my $path = shift;
797         my $cmdname = shift;
798         my $package = valid_package_name($cmdname);
799         my $filename = "$path/$cmdname.pl";
800         my $mtime = -M $filename;
801         
802         # return if we can't find it
803         $errstr = undef;
804         unless (defined $mtime) {
805                 $errstr = DXM::msg('e1');
806                 return undef;
807         }
808         
809         if(exists $Cache{$package} && exists $Cache{$package}->{mtime} && $Cache{$package}->{mtime} <= $mtime) {
810                 #we have compiled this subroutine already,
811                 #it has not been updated on disk, nothing left to do
812                 #print STDERR "already compiled $package->handler\n";
813                 ;
814         } else {
815
816                 my $sub = readfilestr($filename);
817                 unless ($sub) {
818                         $errstr = "Syserr: can't open '$filename' $!";
819                         return undef;
820                 };
821                 
822                 #wrap the code into a subroutine inside our unique package
823                 my $eval = qq(package DXCommandmode::$package; use POSIX qw{:math_h}; use DXLog; use DXDebug; use DXUser; use DXUtil; our \@ISA = qw{DXCommandmode}; );
824
825
826                 if ($sub =~ m|\s*sub\s+handle\n|) {
827                         $eval .= $sub;
828                 } else {
829                         $eval .= qq(sub handle { $sub });
830                 }
831                 
832                 if (isdbg('eval')) {
833                         my @list = split /\n/, $eval;
834                         my $line;
835                         for (@list) {
836                                 dbg($_ . "\n") if isdbg('eval');
837                         }
838                 }
839                 
840                 # get rid of any existing sub and try to compile the new one
841                 no strict 'refs';
842
843                 if (exists $Cache{$package}) {
844                         dbg("find_cmd_name: Redefining $package") if isdbg('command');
845                         undef $DXCommandmode::{"${package}::"};
846                         delete $Cache{$package};
847                 } else {
848                         dbg("find_cmd_name: Defining $package") if isdbg('command');
849                 }
850
851                 eval $eval;
852
853                 $Cache{$package} = {mtime => $mtime } unless $@;
854         }
855
856         return "DXCommandmode::$package";
857 }
858
859 sub send
860 {
861         my $self = shift;
862         if ($self->{gtk}) {
863                 for (@_) {
864                         $self->SUPER::send(dd(['cmd',$_]));
865                 }
866         } else {
867                 $self->SUPER::send(@_);
868         }
869 }
870
871 sub local_send
872 {
873         my ($self, $let, $buf) = @_;
874         if ($self->{state} eq 'prompt' || $self->{state} eq 'talk' || $self->{state} eq 'chat') {
875                 if ($self->{enhanced}) {
876                         $self->send_later($let, $buf);
877                 } else {
878                         $self->send($buf);
879                 }
880         } else {
881                 $self->delay($buf);
882         }
883 }
884
885 # send a talk message here
886 sub talk
887 {
888         my ($self, $from, $to, $via, $line, $onode) = @_;
889         $line =~ s/\\5E/\^/g;
890         if ($self->{talk}) {
891                 if ($self->{gtk}) {
892                         $self->local_send('T', dd(['talk',$to,$from,$via,$line]));
893                 } else {
894                         $self->local_send('T', "$to de $from: $line");
895                 }
896         }
897         Log('talk', $to, $from, '<' . ($onode || '*'), $line);
898         # send a 'not here' message if required
899         unless ($self->{here} && $from ne $to) {
900                 my $key = "$to$from";
901                 unless (exists $nothereslug{$key}) {
902                         my ($ref, $dxchan);
903                         if (($ref = Route::get($from)) && ($dxchan = $ref->dxchan)) {
904                                 my $name = $self->user->name || $to;
905                                 my $s = $self->user->nothere || $dxchan->msg('nothere', $name);
906                                 $nothereslug{$key} = $main::systime;
907                                 $dxchan->talk($to, $from, undef, $s);
908                         }
909                 }
910         }
911 }
912
913 # send an announce
914 sub announce
915 {
916         my $self = shift;
917         my $line = shift;
918         my $isolate = shift;
919         my $to = shift;
920         my $target = shift;
921         my $text = shift;
922         my ($filter, $hops);
923
924         if (!$self->{ann_talk} && $to ne $self->{call}) {
925                 my $call = AnnTalk::is_talk_candidate($_[0], $text);
926                 return if $call;
927         }
928
929         if ($self->{annfilter}) {
930                 ($filter, $hops) = $self->{annfilter}->it(@_ );
931                 return unless $filter;
932         }
933
934         unless ($self->{ann}) {
935                 return if $_[0] ne $main::myalias && $_[0] ne $main::mycall;
936         }
937         return if $target eq 'SYSOP' && $self->{priv} < 5;
938         my $buf;
939         if ($self->{gtk}) {
940                 $buf = dd(['ann', $to, $target, $text, @_])
941         } else {
942                 $buf = "$to$target de $_[0]: $text";
943                 $buf =~ s/\%5E/^/g;
944                 $buf .= "\a\a" if $self->{beep};
945         }
946         $self->local_send($target eq 'WX' ? 'W' : 'N', $buf);
947 }
948
949 # send a chat
950 sub chat
951 {
952         my $self = shift;
953         my $line = shift;
954         my $isolate = shift;
955         my $target = shift;
956         my $to = shift;
957         my $text = shift;
958         my ($filter, $hops);
959
960         return unless grep uc $_ eq $target, @{$self->{user}->{group}};
961         
962         $text =~ s/^\#\d+ //;
963         my $buf;
964         if ($self->{gtk}) {
965                 $buf = dd(['chat', $to, $target, $text, @_])
966         } else {
967                 $buf = "$target de $_[0]: $text";
968                 $buf =~ s/\%5E/^/g;
969                 $buf .= "\a\a" if $self->{beep};
970         }
971         $self->local_send('C', $buf);
972 }
973
974 sub format_dx_spot
975 {
976         my $self = shift;
977
978         my $t = ztime($_[2]);
979         my $loc = '';
980         my ($slot1, $slot2) = ('', '');
981         
982         my $clth = 30 + $self->{width} - 80;    # allow comment to grow according the screen width 
983         my $comment = substr (($_[3] || ''), 0, $clth);
984         $comment =~ s/\t/ /g;
985         $comment .= ' ' x ($clth - (length($comment)));
986
987         if (!$slot1 && $self->{user}->wantgrid) {
988                 my $ref = DXUser::get_current($_[1]);
989                 if ($ref && $ref->qra) {
990                         $slot1 = ' ' . substr($ref->qra, 0, 4);
991                 }
992         }
993         if (!$slot1 && $self->{user}->wantusstate) {
994                 $slot1 = " $_[12]" if $_[12];
995         }
996         unless ($slot1) {
997                 if ($self->{user}->wantdxitu) {
998                         $slot1 = sprintf(" %2d", $_[8]) if defined $_[8]; 
999                 } elsif ($self->{user}->wantdxcq) {
1000                         $slot1 = sprintf(" %2d", $_[9]) if defined $_[9];
1001                 }
1002         }
1003         $comment = substr($comment, 0,  $clth-length($slot1)) . $slot1 if $slot1;
1004         
1005     if (!$slot2 && $self->{user}->wantgrid) {
1006                 my $origin = $_[4];
1007                 $origin =~ s/-#$//;                     # sigh......
1008                 my $ref = DXUser::get_current($origin);
1009                 if ($ref && $ref->qra) {
1010                         $slot2 = ' ' . substr($ref->qra, 0, 4);
1011                 }
1012         }
1013         if (!$slot2 && $self->{user}->wantusstate) {
1014                 $slot2 = " $_[13]" if $_[13];
1015         }
1016         unless ($slot2) {
1017                 if ($self->{user}->wantdxitu) {
1018                         $slot2 = sprintf(" %2d", $_[10]) if defined $_[10]; 
1019                 } elsif ($self->{user}->wantdxcq) {
1020                         $slot2 = sprintf(" %2d", $_[11]) if defined $_[11]; 
1021                 }
1022         }
1023
1024         return sprintf "DX de %-8.8s%10.1f  %-12.12s %-s $t$slot2", "$_[4]:", $_[0], $_[1], $comment;
1025 }
1026
1027 # send a dx spot
1028 sub dx_spot
1029 {
1030         my $self = shift;
1031         my $line = shift;
1032         my $isolate = shift;
1033         return unless $self->{dx};
1034
1035         my ($filter, $hops);
1036
1037         if ($self->{spotsfilter}) {
1038                 ($filter, $hops) = $self->{spotsfilter}->it(@_ );
1039                 return unless $filter;
1040         }
1041
1042         dbg('spot: "' . join('","', @_) . '"') if isdbg('dxspot');
1043
1044         my $buf;
1045         if ($self->{ve7cc}) {
1046                 $buf = VE7CC::dx_spot($self, @_);
1047         } elsif ($self->{gtk}) {
1048                 my ($dxloc, $byloc);
1049
1050                 my $ref = DXUser::get_current($_[4]);
1051                 if ($ref) {
1052                         $byloc = $ref->qra;
1053                         $byloc = substr($byloc, 0, 4) if $byloc;
1054                 }
1055
1056                 my $spot = $_[1];
1057                 $spot =~ s|/\w{1,4}$||;
1058                 $ref = DXUser::get_current($spot);
1059                 if ($ref) {
1060                         $dxloc = $ref->qra;
1061                         $dxloc = substr($dxloc, 0, 4) if $dxloc;
1062                 }
1063                 $buf = dd(['dx', @_, ($dxloc||''), ($byloc||'')]);
1064                 
1065         } else {
1066                 $buf = $self->format_dx_spot(@_);
1067                 $buf .= "\a\a" if $self->{beep};
1068                 $buf =~ s/\%5E/^/g;
1069         }
1070
1071         $self->local_send('X', $buf);
1072 }
1073
1074 sub wwv
1075 {
1076         my $self = shift;
1077         my $line = shift;
1078         my $isolate = shift;
1079         my ($filter, $hops);
1080
1081         return unless $self->{wwv};
1082         
1083         if ($self->{wwvfilter}) {
1084                 ($filter, $hops) = $self->{wwvfilter}->it(@_[7..$#_] );
1085                 return unless $filter;
1086         }
1087
1088         my $buf;
1089         if ($self->{gtk}) {
1090                 $buf = dd(['wwv', @_])
1091         } else {
1092                 $buf = "WWV de $_[6] <$_[1]>:   SFI=$_[2], A=$_[3], K=$_[4], $_[5]";
1093                 $buf .= "\a\a" if $self->{beep};
1094         }
1095         
1096         $self->local_send('V', $buf);
1097 }
1098
1099 sub wcy
1100 {
1101         my $self = shift;
1102         my $line = shift;
1103         my $isolate = shift;
1104         my ($filter, $hops);
1105
1106         return unless $self->{wcy};
1107         
1108         if ($self->{wcyfilter}) {
1109                 ($filter, $hops) = $self->{wcyfilter}->it(@_ );
1110                 return unless $filter;
1111         }
1112
1113         my $buf;
1114         if ($self->{gtk}) {
1115                 $buf = dd(['wcy', @_])
1116         } else {
1117                 $buf = "WCY de $_[10] <$_[1]> : K=$_[4] expK=$_[5] A=$_[3] R=$_[6] SFI=$_[2] SA=$_[7] GMF=$_[8] Au=$_[9]";
1118                 $buf .= "\a\a" if $self->{beep};
1119         }
1120         $self->local_send('Y', $buf);
1121 }
1122
1123 # broadcast debug stuff to all interested parties
1124 sub broadcast_debug
1125 {
1126         my $s = shift;                          # the line to be rebroadcast
1127         
1128         foreach my $dxchan (DXChannel::get_all) {
1129                 next unless $dxchan->{enhanced} && $dxchan->{senddbg};
1130                 if ($dxchan->{gtk}) {
1131                         $dxchan->send_later('L', dd(['db', $s]));
1132                 } else {
1133                         $dxchan->send_later('L', $s);
1134                 }
1135         }
1136 }
1137
1138 sub do_entry_stuff
1139 {
1140         my $self = shift;
1141         my $line = shift;
1142         my @out;
1143         
1144         if ($self->state eq 'enterbody') {
1145                 my $loc = $self->{loc} || confess "local var gone missing" ;
1146                 if ($line eq "\032" || $line eq '%1A' || uc $line eq "/EX") {
1147                         no strict 'refs';
1148                         push @out, &{$loc->{endaction}}($self);          # like this for < 5.8.0
1149                         $self->func(undef);
1150                         $self->state('prompt');
1151                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
1152                         push @out, $self->msg('m10');
1153                         delete $loc->{lines};
1154                         delete $self->{loc};
1155                         $self->func(undef);
1156                         $self->state('prompt');
1157                 } else {
1158                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
1159                         # i.e. it ain't and end or abort, therefore store the line
1160                 }
1161         } else {
1162                 confess "Invalid state $self->{state}";
1163         }
1164         return @out;
1165 }
1166
1167 sub store_startup_script
1168 {
1169         my $self = shift;
1170         my $loc = $self->{loc} || confess "local var gone missing" ;
1171         my @out;
1172         my $call = $loc->{call} || confess "callsign gone missing";
1173         confess "lines array gone missing" unless ref $loc->{lines};
1174         my $r = Script::store($call, $loc->{lines});
1175         if (defined $r) {
1176                 if ($r) {
1177                         push @out, $self->msg('m19', $call, $r);
1178                 } else {
1179                         push @out, $self->msg('m20', $call);
1180                 }
1181         } else {
1182                 push @out, "error opening startup script $call $!";
1183         } 
1184         return @out;
1185 }
1186
1187 # Import any commands contained in any files in import_cmd directory
1188 #
1189 # If the filename has a recogisable callsign as some delimited part
1190 # of it, then this is the user the command will be run as. 
1191 #
1192 sub import_cmd
1193 {
1194         # are there any to do in this directory?
1195         return unless -d $cmdimportdir;
1196         unless (opendir(DIR, $cmdimportdir)) {
1197                 LogDbg('err', "can\'t open $cmdimportdir $!");
1198                 return;
1199         } 
1200
1201         my @names = readdir(DIR);
1202         closedir(DIR);
1203         my $name;
1204         foreach $name (@names) {
1205                 next if $name =~ /^\./;
1206
1207                 my $s = Script->new($name, $cmdimportdir);
1208                 if ($s) {
1209                         LogDbg('DXCommand', "Run import cmd file $name");
1210                         my @cat = split /[^A-Za-z0-9]+/, $name;
1211                         my ($call) = grep {is_callsign(uc $_)} @cat;
1212                         $call ||= $main::mycall;
1213                         $call = uc $call;
1214                         my @out;
1215                         
1216                         
1217                         $s->inscript(0);        # switch off script checks
1218                         
1219                         if ($call eq $main::mycall) {
1220                                 @out = $s->run($main::me, 1);
1221                         } else {
1222                                 my $dxchan = DXChannel::get($call);
1223                             if ($dxchan) {
1224                                         @out = $s->run($dxchan, 1);
1225                                 } else {
1226                                         my $u = DXUser::get($call);
1227                                         if ($u) {
1228                                                 $dxchan = $main::me;
1229                                                 my $old = $dxchan->{call};
1230                                                 my $priv = $dxchan->{priv};
1231                                                 my $user = $dxchan->{user};
1232                                                 $dxchan->{call} = $call;
1233                                                 $dxchan->{priv} = $u->priv;
1234                                                 $dxchan->{user} = $u;
1235                                                 @out = $s->run($dxchan, 1);
1236                                                 $dxchan->{call} = $old;
1237                                                 $dxchan->{priv} = $priv;
1238                                                 $dxchan->{user} = $user;
1239                                         } else {
1240                                                 LogDbg('err', "Trying to run import cmd for non-existant user $call");
1241                                         }
1242                                 }
1243                         }
1244                         $s->erase;
1245                         for (@out) {
1246                                 LogDbg('DXCommand', "Import cmd $name/$call: $_");
1247                         }
1248                 } else {
1249                         LogDbg('err', "Failed to open $cmdimportdir/$name $!");
1250                         unlink "$cmdimportdir/$name";
1251                 }
1252         }
1253 }
1254
1255 sub print_find_reply
1256 {
1257         my ($self, $node, $target, $flag, $ms) = @_;
1258         my $sort = $flag == 2 ? "External" : "Local";
1259         $self->send("$sort $target found at $node in $ms ms" );
1260 }
1261
1262 # send the most relevant motd
1263 sub send_motd
1264 {
1265         my $self = shift;
1266         my $motd;
1267
1268         unless ($self->registered) {
1269                 $motd = "${main::motd}_nor_$self->{lang}";
1270                 $motd = "${main::motd}_nor" unless -e $motd;
1271         }
1272         $motd = "${main::motd}_$self->{lang}" unless $motd && -e $motd;
1273         $motd = $main::motd unless $motd && -e $motd;
1274         if ($self->conn->ax25) {
1275                 if ($motd) {
1276                         $motd = "${motd}_ax25" if -e "${motd}_ax25";
1277                 } else {
1278                         $motd = "${main::motd}_ax25" if -e "${main::motd}_ax25";
1279                 }
1280         }
1281         $self->send_file($motd) if -e $motd;
1282 }
1283
1284
1285 1;
1286 __END__