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