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