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