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