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