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