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