3 # This module impliments the user facing command mode for a dx cluster
5 # Copyright (c) 1998 Dirk Koopman G1TLH
10 package DXCommandmode;
18 use POSIX qw(:math_h);
43 use Time::HiRes qw(gettimeofday tv_interval);
51 use vars qw(%Cache %cmd_cache $errstr %aliases $scriptbase %nothereslug
52 $maxbadcount $msgpolltime $default_pagelth $cmdimportdir $users $maxusers
56 %Cache = (); # cache of dynamically loaded routine's mod times
57 %cmd_cache = (); # cache of short names
58 $errstr = (); # error string from eval
59 %aliases = (); # aliases for (parts of) commands
60 $scriptbase = "$main::root/scripts"; # the place where all users start scripts go
61 $maxbadcount = 3; # no of bad words allowed before disconnection
62 $msgpolltime = 3600; # the time between polls for new messages
63 $cmdimportdir = "$main::root/cmd_import"; # the base directory for importing command scripts
64 # this does not exist as default, you need to create it manually
65 $users = 0; # no of users on this node currently
66 $maxusers = 0; # max no users on this node for this run
68 $maxcmdlth = 512; # max length of incoming cmd line (including the command and any arguments
71 # obtain a new connection this is derived from dxchannel
76 my $self = DXChannel::alloc(@_);
78 # routing, this must go out here to prevent race condx
81 # my @rout = $main::routeroot->add_user($call, Route::here(1));
82 my $ipaddr = alias_localhost($self->hostname);
83 DXProt::_add_thingy($main::routeroot, [$call, 0, 0, 1, undef, undef, $ipaddr], );
85 # ALWAYS output the user (except if the updates not enabled)
86 my $ref = Route::User::get($call);
88 $main::me->route_pc16($main::mycall, undef, $main::routeroot, $ref);
89 $main::me->route_pc92a($main::mycall, undef, $main::routeroot, $ref) unless $DXProt::pc92_slug_changes || ! $DXProt::pc92_ad_enable;
95 # this is how a a connection starts, you get a hello message and the motd with
96 # possibly some other messages asking you to set various things up if you are
97 # new (or nearly new and slacking) user.
101 my ($self, $line, $sort) = @_;
102 my $user = $self->{user};
103 my $call = $self->{call};
104 my $name = $user->{name};
107 my $host = $self->{conn}->peerhost;
108 $host ||= "AGW Port #$self->{conn}->{agwport}" if exists $self->{conn}->{agwport};
110 $self->{hostname} = $host;
112 $self->{name} = $name ? $name : $call;
113 $self->send($self->msg('l2',$self->{name}));
114 $self->send("Capabilities: ve7cc rbn");
115 $self->state('prompt'); # a bit of room for further expansion, passwords etc
116 $self->{priv} = $user->priv || 0;
117 $self->{lang} = $user->lang || $main::lang || 'en';
118 my $pagelth = $user->pagelth;
119 $pagelth = $default_pagelth unless defined $pagelth;
120 $self->{pagelth} = $pagelth;
121 ($self->{width}) = $line =~ /\s*width=(\d+)/; $line =~ s/\s*width=\d+//;
122 $self->{enhanced} = $line =~ /\s+enhanced/; $line =~ s/\s*enhanced//;
123 if ($line =~ /host=/) {
124 my ($h) = $line =~ /host=(\d+\.\d+\.\d+\.\d+)/;
125 $line =~ s/\s*host=\d+\.\d+\.\d+\.\d+// if $h;
127 ($h) = $line =~ /host=([\da..fA..F:]+)/;
128 $line =~ s/\s*host=[\da..fA..F:]+// if $h;
130 $self->{hostname} = $h if $h;
132 $self->{width} = 80 unless $self->{width} && $self->{width} > 80;
133 $self->{consort} = $line; # save the connection type
135 LogDbg('DXCommand', "$call connected from $self->{hostname} cols $self->{width}" . ($self->{enhanced}?" enhanced":''));
137 # set some necessary flags on the user if they are connecting
138 $self->{beep} = $user->wantbeep;
139 $self->{ann} = $user->wantann;
140 $self->{wwv} = $user->wantwwv;
141 $self->{wcy} = $user->wantwcy;
142 $self->{talk} = $user->wanttalk;
143 $self->{wx} = $user->wantwx;
144 $self->{dx} = $user->wantdx;
145 $self->{logininfo} = $user->wantlogininfo;
146 $self->{ann_talk} = $user->wantann_talk;
147 $self->{wantrbn} = $user->wantrbn;
149 $self->{prompt} = $user->prompt if $user->prompt;
150 $self->{lastmsgpoll} = 0;
151 $self->{rbnseeme} = $user->rbnseeme;
152 RBN::add_seeme($call) if $self->{rbnseeme};
154 # sort out new dx spot stuff
155 $user->wantdxcq(0) unless defined $user->{wantdxcq};
156 $user->wantdxitu(0) unless defined $user->{wantdxitu};
157 $user->wantusstate(0) unless defined $user->{wantusstate};
159 # sort out registration
160 if ($main::reqreg == 2) {
161 $self->{registered} = !$user->registered;
163 $self->{registered} = $user->registered;
166 # establish slug queue, if required
167 $self->{sluggedpcs} = [];
168 $self->{isslugged} = $DXProt::pc92_slug_changes + $DXProt::last_pc92_slug + 5 if $DXProt::pc92_slug_changes;
169 $self->{isslugged} = 0 if $self->{priv} || $user->registered || ($user->homenode && $user->homenode eq $main::mycall);
171 # send the relevant MOTD
174 # sort out privilege reduction
175 $self->{priv} = 0 unless $self->{hostname} eq '127.0.0.1' || $self->conn->peerhost eq '127.0.0.1' || $self->{hostname} eq '::1' || $self->conn->{usedpasswd};
179 $nossid =~ s/-\d+$//;
181 $self->{spotsfilter} = Filter::read_in('spots', $call, 0)
182 || Filter::read_in('spots', $nossid, 0)
183 || Filter::read_in('spots', 'user_default', 0);
184 $self->{wwvfilter} = Filter::read_in('wwv', $call, 0)
185 || Filter::read_in('wwv', $nossid, 0)
186 || Filter::read_in('wwv', 'user_default', 0);
187 $self->{wcyfilter} = Filter::read_in('wcy', $call, 0)
188 || Filter::read_in('wcy', $nossid, 0)
189 || Filter::read_in('wcy', 'user_default', 0);
190 $self->{annfilter} = Filter::read_in('ann', $call, 0)
191 || Filter::read_in('ann', $nossid, 0)
192 || Filter::read_in('ann', 'user_default', 0) ;
193 $self->{rbnfilter} = Filter::read_in('rbn', $call, 0)
194 || Filter::read_in('rbn', $nossid, 0)
195 || Filter::read_in('rbn', 'user_default', 0);
197 # clean up qra locators
198 my $qra = $user->qra;
199 $qra = undef if ($qra && !DXBearing::is_qra($qra));
201 my $lat = $user->lat;
202 my $long = $user->long;
203 $user->qra(DXBearing::lltoqra($lat, $long)) if (defined $lat && defined $long);
207 my $echo = $user->wantecho;
209 $self->send_now('E', "0");
210 $self->send($self->msg('echow'));
211 $self->conn->echo($echo) if $self->conn->can('echo');
214 $self->tell_login('loginu');
215 $self->tell_buddies('loginb');
217 # is this a bad ip address?
218 if (is_ipaddr($self->{hostname})) {
219 $self->{badip} = DXCIDR::find($self->{hostname});
222 # do we need to send a forward/opernam?
223 my $lastoper = $user->lastoper || 0;
224 my $homenode = $user->homenode || "";
225 if ($homenode eq $main::mycall && $main::systime >= $lastoper + $DXUser::lastoperinterval) {
226 run_cmd($main::me, "forward/opernam $call");
227 $user->lastoper($main::systime + ((int rand(10)) * 86400));
230 # run a script send the output to the punter
231 my $script = new Script(lc $call) || new Script('user_default');
232 $script->run($self) if $script;
235 $self->send($self->run_cmd("show/cluster"));
237 # send prompts for qth, name and things
238 $self->send($self->msg('namee1')) if !$user->name;
239 $self->send($self->msg('qthe1')) if !$user->qth;
240 $self->send($self->msg('qll')) if !$user->qra || (!$user->lat && !$user->long);
241 $self->send($self->msg('hnodee1')) if !$user->qth;
242 $self->send($self->msg('m9')) if DXMsg::for_me($call);
244 # send out any buddy messages for other people that are online
245 foreach my $call (@{$user->buddies}) {
246 my $ref = Route::User::get($call);
248 foreach my $node ($ref->parents) {
249 $self->send($self->msg($node eq $main::mycall ? 'loginb' : 'loginbn', $call, $node));
254 $self->lastmsgpoll($main::systime);
255 $self->{user_interval} = $self->user->user_interval || $main::user_interval; # allow user to change idle time between prompts
260 # This is the normal command prompt driver
270 # save this for them's that need it
271 my $rawline = $cmdline;
273 # remove leading and trailing spaces
274 $cmdline =~ s/^\s*(.*)\s*$/$1/;
276 if ($self->{state} eq 'page') {
277 my $i = $self->{pagelth}-5;
278 my $ref = $self->{pagedata};
281 # abort if we get a line starting in with a
282 if ($cmdline =~ /^a/io) {
287 # send a tranche of data
288 for (; $i > 0 && @$ref; --$i) {
289 my $line = shift @$ref;
290 $line =~ s/\s+$//o; # why am having to do this?
294 # reset state if none or else chuck out an intermediate prompt
296 $tot -= $self->{pagelth};
297 $self->send($self->msg('page', $tot));
299 $self->state('prompt');
301 } elsif ($self->{state} eq 'sysop') {
302 my $passwd = $self->{user}->passwd;
304 my @pw = grep {$_ !~ /\s/} split //, $passwd;
305 my @l = @{$self->{passwd}};
306 my $str = "$pw[$l[0]].*$pw[$l[1]].*$pw[$l[2]].*$pw[$l[3]].*$pw[$l[4]]";
307 if ($cmdline =~ /$str/) {
308 $self->{priv} = $self->{user}->priv;
310 $self->send($self->msg('sorry'));
313 $self->send($self->msg('sorry'));
315 $self->state('prompt');
316 } elsif ($self->{state} eq 'passwd') {
317 my $passwd = $self->{user}->passwd;
318 if ($passwd && $cmdline eq $passwd) {
319 $self->send($self->msg('pw1'));
320 $self->state('passwd1');
322 $self->conn->{echo} = $self->conn->{decho};
323 delete $self->conn->{decho};
324 $self->send($self->msg('sorry'));
325 $self->state('prompt');
327 } elsif ($self->{state} eq 'passwd1') {
328 $self->{passwd} = $cmdline;
329 $self->send($self->msg('pw2'));
330 $self->state('passwd2');
331 } elsif ($self->{state} eq 'passwd2') {
332 if ($cmdline eq $self->{passwd}) {
333 $self->{user}->passwd($cmdline);
334 $self->send($self->msg('pw3'));
336 $self->send($self->msg('pw4'));
338 $self->conn->{echo} = $self->conn->{decho};
339 delete $self->conn->{decho};
340 $self->state('prompt');
341 } elsif ($self->{state} eq 'talk' || $self->{state} eq 'chat') {
342 if ($cmdline =~ m{^(?:/EX|/ABORT)}i) {
343 for (@{$self->{talklist}}) {
344 if ($self->{state} eq 'talk') {
345 $self->send_talks($_, $self->msg('talkend'));
347 $self->local_send('C', $self->msg('chatend', $_));
350 $self->state('prompt');
351 delete $self->{talklist};
352 } elsif ($cmdline =~ m|^[/\w\\]+|) {
354 my $sendit = $cmdline =~ s|^/+||;
355 if (@bad = BadWords::check($cmdline)) {
356 $self->badcount(($self->badcount||0) + @bad);
357 LogDbg('DXCommand', "$self->{call} swore: '$cmdline' with badwords: '" . join(',', @bad) . "'");
359 my @cmd = split /\s*\\n\s*/, $cmdline;
360 foreach my $l (@cmd) {
361 my @in = $self->run_cmd($l);
362 $self->send_ans(@in);
363 if ($sendit && $self->{talklist} && @{$self->{talklist}}) {
364 foreach my $l (@in) {
365 for (@{$self->{talklist}}) {
366 if ($self->{state} eq 'talk') {
367 $self->send_talks($_, $l);
370 send_chats($self, $_, $l)
377 $self->send($self->{state} eq 'talk' ? $self->talk_prompt : $self->chat_prompt);
378 } elsif ($self->{talklist} && @{$self->{talklist}}) {
379 # send what has been said to whoever is in this person's talk list
380 if (@bad = BadWords::check($cmdline)) {
381 $self->badcount(($self->badcount||0) + @bad);
382 LogDbg('DXCommand', "$self->{call} swore: '$cmdline' with badwords: '" . join(',', @bad) . "'");
384 for (@{$self->{talklist}}) {
385 if ($self->{state} eq 'talk') {
386 $self->send_talks($_, $rawline);
388 send_chats($self, $_, $rawline);
392 $self->send($self->talk_prompt) if $self->{state} eq 'talk';
393 $self->send($self->chat_prompt) if $self->{state} eq 'chat';
396 $self->state('prompt');
398 } elsif (my $func = $self->{func}) {
401 if (ref $self->{edit}) {
402 eval { @ans = $self->{edit}->$func($self, $rawline)};
404 eval { @ans = &{$self->{func}}($self, $rawline) };
407 $self->send_ans("Syserr: on stored func $self->{func}", $@);
408 delete $self->{func};
409 $self->state('prompt');
412 $self->send_ans(@ans);
414 # if (@bad = BadWords::check($cmdline)) {
415 # $self->badcount(($self->badcount||0) + @bad);
416 # LogDbg('DXCommand', "$self->{call} swore: '$cmdline' with badwords: '" . join(',', @bad) . "'");
418 my @cmd = split /\s*\\n\s*/, $cmdline;
419 foreach my $l (@cmd) {
420 $self->send_ans(run_cmd($self, $l));
425 # check for excessive swearing
426 if ($maxbadcount && $self->{badcount} && $self->{badcount} >= $maxbadcount) {
427 LogDbg('DXCommand', "$self->{call} logged out for excessive swearing");
432 # send a prompt only if we are in a prompt state
433 $self->prompt() if $self->{state} =~ /^prompt/o;
436 # send out the talk messages taking into account vias and connectivity
439 my ($self, $ent, $line) = @_;
441 my ($to, $via) = $ent =~ /(\S+)>(\S+)/;
442 $to = $ent unless $to;
443 my $call = $via && $via ne '*' ? $via : $to;
444 my $clref = Route::get($call);
445 my $dxchan = $clref->dxchan if $clref;
447 $dxchan->talk($self->{call}, $to, undef, $line);
449 $self->send($self->msg('disc2', $via ? $via : $to));
450 my @l = grep { $_ ne $ent } @{$self->{talklist}};
452 $self->{talklist} = \@l;
454 delete $self->{talklist};
455 $self->state('prompt');
466 my $msgid = DXProt::nextchatmsgid();
467 $text = "#$msgid $text";
468 my $ipaddr = alias_localhost($self->hostname || '127.0.0.1');
469 $main::me->normal(DXProt::pc93($target, $self->{call}, undef, $text, undef, $ipaddr));
477 for (@{$self->{talklist}}) {
478 my ($to, $via) = /(\S+)>(\S+)/;
482 return $self->msg($prompt, join(',', @call));
488 return $self->special_prompt('talkprompt');
494 return $self->special_prompt('chatprompt');
498 # send a load of stuff to a command user with page prompting
506 if ($self->{pagelth} && @_ > $self->{pagelth}) {
508 for ($i = $self->{pagelth}; $i-- > 0; ) {
510 $line =~ s/\s+$//o; # why am having to do this?
513 $self->{pagedata} = [ @_ ];
514 $self->state('page');
515 $self->send($self->msg('page', scalar @_));
528 # this is the thing that preps for running the command, it is done like this for the
529 # benefit of remote command execution
535 my $user = $self->{user};
536 my $call = $self->{call};
540 return () if length $cmdline == 0;
542 # split the command line up into parts, the first part is the command
543 my ($cmd, $args) = split /\s+/, $cmdline, 2;
544 $args = "" unless defined $args;
548 # strip out // on command only
551 # check for length of whole command line and any invalid characters
552 if (length $cmdline > $maxcmdlth || $cmd =~ m|\.| || $cmd !~ m|^\w+(?:/\w+){0,1}(?:/\d+)?$|) {
553 LogDbg('DXCommand', "cmd: $self->{call} - invalid characters in '$cmd'");
554 return $self->_error_out('e40');
559 dbg("cmd: $cmd") if isdbg('command');
561 # alias it if possible
562 my $acmd = CmdAlias::get_cmd($cmd);
564 ($cmd, $args) = split /\s+/, "$acmd $args", 2;
565 $args = "" unless defined $args;
566 dbg("cmd: aliased $cmd $args") if isdbg('command');
569 # first expand out the entry to a command
570 ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
571 ($path, $fcmd) = search($main::cmd, $cmd, "pl") unless $path && $fcmd;
574 dbg("cmd: path $cmd cmd: $fcmd") if isdbg('command');
576 my $package = find_cmd_name($path, $fcmd);
579 if ($package && $self->can("${package}::handle")) {
581 dbg("cmd: package $package") if isdbg('command');
582 # Log('cmd', "$self->{call} on $self->{hostname} : '$cmd $args'");
583 my $t0 = [gettimeofday];
584 eval { @ans = &{"${package}::handle"}($self, $args) };
586 DXDebug::dbgprintring(25);
587 return (DXDebug::shortmess($@));
589 if (isdbg('progress')) {
590 my $msecs = _diffms($t0);
591 my $s = "CMD: '$cmd $args' by $call ip: $self->{hostname} ${msecs}mS";
592 dbg($s) if $cmd !~ /^(?:echo|blank)/ || isdbg('echo'); # cut down a bit on HRD and other clients' noise
595 dbg("cmd: $package not present") if isdbg('command');
596 return $self->_error_out('e1');
599 LogDbg('DXCommand', "$self->{call} cmd: '$cmd' not found");
600 return $self->_error_out('e1');
606 delete $self->{errors};
608 if ($self != $main::me && ++$self->{errors} > $DXChannel::maxerrors) {
609 $self->send($self->msg('e26'));
614 return map {s/([^\s])\s+$/$1/; $_} @ans;
618 # This is called from inside the main cluster processing loop and is used
619 # for despatching commands that are doing some long processing job
624 my @dxchan = DXChannel::get_all();
628 foreach $dxchan (@dxchan) {
629 next unless $dxchan->is_user;
631 # send a outstanding message prompt if required
632 if ($t >= $dxchan->lastmsgpoll + $msgpolltime) {
633 $dxchan->send($dxchan->msg('m9')) if DXMsg::for_me($dxchan->call);
634 $dxchan->lastmsgpoll($t);
637 # send a prompt if no activity out on this channel
638 if ($t >= $dxchan->t + $dxchan->{user_interval}) {
639 $dxchan->prompt() if $dxchan->{state} =~ /^prompt/o;
643 $maxusers = $users if $users > $maxusers;
645 if ($dxchan->{isslugged} && $main::systime > $dxchan->{isslugged}) {
646 foreach my $ref (@{$dxchan->{sluggedpcs}}) {
647 if ($ref->[0] == 61) {
648 Spot::add(@{$ref->[2]});
649 DXProt::send_dx_spot($dxchan, $ref->[1], @{$ref->[2]});
653 $dxchan->{isslugged} = 0;
654 $dxchan->{sluggedpcs} = [];
662 # finish up a user context
667 my $call = $self->call;
669 return if $self->{disconnecting}++;
671 delete $self->{senddbg};
672 RBN::del_seeme($call);
674 my $uref = Route::User::get($call);
677 # @rout = $main::routeroot->del_user($uref);
678 @rout = DXProt::_del_thingy($main::routeroot, [$call, 0]);
680 # dbg("B/C PC17 on $main::mycall for: $call") if isdbg('route');
682 # issue a pc17 to everybody interested
683 $main::me->route_pc17($main::mycall, undef, $main::routeroot, $uref);
684 $main::me->route_pc92d($main::mycall, undef, $main::routeroot, $uref) unless $DXProt::pc92_slug_changes || ! $DXProt::pc92_ad_enable;
686 confess "trying to disconnect a non existant user $call";
689 # I was the last node visited
690 $self->user->node($main::mycall);
692 # send info to all logged in thingies
693 $self->tell_login('logoutu');
694 $self->tell_buddies('logoutb');
696 LogDbg('DXCommand', "$call disconnected");
698 $self->SUPER::disconnect;
702 # short cut to output a prompt
709 return if $self->{gtk}; # 'cos prompts are not a concept that applies here
711 my $call = $self->call;
712 my $date = cldate($main::systime);
713 my $time = ztime($main::systime);
714 my $prompt = $self->{prompt} || $self->msg('pr');
716 $call = "($call)" unless $self->here;
717 $prompt =~ s/\%C/$call/g;
718 $prompt =~ s/\%D/$date/g;
719 $prompt =~ s/\%T/$time/g;
720 $prompt =~ s/\%M/$main::mycall/g;
722 $self->send($prompt);
725 # broadcast a message to all users [except those mentioned after buffer]
728 my $pkg = shift; # ignored
729 my $s = shift; # the line to be rebroadcast
731 foreach my $dxchan (DXChannel::get_all()) {
732 next unless $dxchan->is_user; # only interested in user channels
733 next if grep $dxchan == $_, @_;
734 $dxchan->send($s); # send it
738 # gimme all the users
741 goto &DXChannel::get_all_users;
744 # run a script for this user
748 my $silent = shift || 0;
753 # search for the command in the cache of short->long form commands
758 my ($path, $short_cmd, $suffix) = @_;
761 # commands are lower case
762 $short_cmd = lc $short_cmd;
763 dbg("command: $path $short_cmd\n") if isdbg('command');
765 # do some checking for funny characters
766 return () if $short_cmd =~ /\/$/;
768 # return immediately if we have it
769 ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
770 if ($apath && $acmd) {
771 dbg("cached $short_cmd = ($apath, $acmd)\n") if isdbg('command');
772 return ($apath, $acmd);
776 my @parts = split '/', $short_cmd;
780 while (my $p = shift @parts) {
781 opendir(D, $curdir) or confess "can't open $curdir $!";
785 # if this isn't the last part
788 foreach my $l (sort @ls) {
790 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
791 dbg("got dir: $curdir/$l\n") if isdbg('command');
798 # only proceed if we find the directory asked for
799 return () unless $found;
801 foreach my $l (sort @ls) {
803 next unless $l =~ /\.$suffix$/;
804 if ($p eq substr($l, 0, length $p)) {
805 $l =~ s/\.$suffix$//;
806 $dirfn = "" unless $dirfn;
807 $cmd_cache{$short_cmd} = join(',', ($path, "$dirfn$l")); # cache it
808 dbg("got path: $path cmd: $dirfn$l\n") if isdbg('command');
809 return ($path, "$dirfn$l");
818 # clear the command name cache
823 for my $k (keys %Cache) {
824 unless ($k =~ /cmd_cache/) {
825 dbg("Undefining cmd $k") if isdbg('command');
826 undef $DXCommandmode::{"${k}::"};
830 %Cache = ( cmd_clear_cmd_cache => $Cache{cmd_clear_cmd_cache} );
834 # the persistant execution of things from the command directories
837 # This allows perl programs to call functions dynamically
839 # This has been nicked directly from the perlembed pages
841 #require Devel::Symdump;
843 sub valid_package_name {
845 $string =~ s|([^A-Za-z0-9_/])|sprintf("_%2x",unpack("C",$1))|eg;
848 return "cmd_$string";
852 # this bit of magic finds a command in the offered directory
856 my $package = valid_package_name($cmdname);
857 my $filename = "$path/$cmdname.pl";
858 my $mtime = -M $filename;
860 # return if we can't find it
862 unless (defined $mtime) {
863 $errstr = DXM::msg('e1');
867 if(exists $Cache{$package} && exists $Cache{$package}->{mtime} && $Cache{$package}->{mtime} <= $mtime) {
868 #we have compiled this subroutine already,
869 #it has not been updated on disk, nothing left to do
870 #print STDERR "already compiled $package->handler\n";
871 dbg("find_cmd_name: $package cached") if isdbg('command');
874 my $sub = readfilestr($filename);
876 $errstr = "Syserr: can't open '$filename' $!";
880 #wrap the code into a subroutine inside our unique package
881 my $eval = qq(package DXCommandmode::$package; use 5.10.1; use POSIX qw{:math_h}; use DXLog; use DXDebug; use DXUser; use DXUtil; our \@ISA = qw{DXCommandmode}; );
884 if ($sub =~ m|\s*sub\s+handle\n|) {
887 $eval .= qq(sub handle { $sub });
891 my @list = split /\n/, $eval;
893 dbg($_ . "\n") if isdbg('eval');
897 # get rid of any existing sub and try to compile the new one
900 if (exists $Cache{$package}) {
901 dbg("find_cmd_name: Redefining $package") if isdbg('command');
902 undef $DXCommandmode::{"${package}::"};
903 delete $Cache{$package};
905 dbg("find_cmd_name: Defining $package") if isdbg('command');
910 $Cache{$package} = {mtime => $mtime } unless $@;
913 return "DXCommandmode::$package";
921 $self->SUPER::send(dd(['cmd',$_]));
924 $self->SUPER::send(@_);
930 my ($self, $let, $buf) = @_;
931 if ($self->{state} eq 'prompt' || $self->{state} eq 'talk' || $self->{state} eq 'chat') {
932 if ($self->{enhanced}) {
933 $self->send_later($let, $buf);
942 # send a talk message here
945 my ($self, $from, $to, $via, $line, $onode) = @_;
946 $line =~ s/\\5E/\^/g;
949 $self->local_send('T', dd(['talk',$to,$from,$via,$line]));
951 $self->local_send('T', "$to de $from: $line");
954 Log('talk', $to, $from, '<' . ($onode || '*'), $line);
955 # send a 'not here' message if required
956 unless ($self->{here} && $from ne $to) {
957 my $key = "$to$from";
958 unless (exists $nothereslug{$key}) {
960 if (($ref = Route::get($from)) && ($dxchan = $ref->dxchan)) {
961 my $name = $self->user->name || $to;
962 my $s = $self->user->nothere || $dxchan->msg('nothere', $name);
963 $nothereslug{$key} = $main::systime;
964 $dxchan->talk($to, $from, undef, $s);
981 if (!$self->{ann_talk} && $to ne $self->{call}) {
982 my $call = AnnTalk::is_talk_candidate($_[0], $text);
986 if ($self->{annfilter}) {
987 ($filter, $hops) = $self->{annfilter}->it(@_ );
988 return unless $filter;
991 unless ($self->{ann}) {
992 return if $_[0] ne $main::myalias && $_[0] ne $main::mycall;
994 return if $target eq 'SYSOP' && $self->{priv} < 5;
997 $buf = dd(['ann', $to, $target, $text, @_])
999 $buf = "$to$target de $_[0]: $text";
1000 #$buf =~ s/\%5E/^/g;
1001 $buf .= "\a\a" if $self->{beep};
1003 $self->local_send($target eq 'WX' ? 'W' : 'N', $buf);
1011 my $isolate = shift;
1015 my ($filter, $hops);
1017 return unless grep uc $_ eq $target, @{$self->{user}->{group}};
1019 $text =~ s/^\#\d+ //;
1022 $buf = dd(['chat', $to, $target, $text, @_])
1024 $buf = "$target de $_[0]: $text";
1025 #$buf =~ s/\%5E/^/g;
1026 $buf .= "\a\a" if $self->{beep};
1028 $self->local_send('C', $buf);
1035 my $t = ztime($_[2]);
1036 my ($slot1, $slot2) = ('', '');
1038 my $clth = 30 + $self->{width} - 80; # allow comment to grow according the screen width
1041 my $comment = substr (($c || ''), 0, $clth);
1042 $comment .= ' ' x ($clth - (length($comment)));
1044 if ($self->{user}) { # to allow the standalone program 'showdx' to work
1045 if (!$slot1 && $self->{user}->wantgrid) {
1046 my $ref = DXUser::get_current($_[1]);
1047 if ($ref && $ref->qra) {
1048 $slot1 = ' ' . substr($ref->qra, 0, 4);
1051 if (!$slot1 && $self->{user}->wantusstate) {
1052 $slot1 = " $_[12]" if $_[12];
1055 if ($self->{user}->wantdxitu) {
1056 $slot1 = sprintf(" %2d", $_[8]) if defined $_[8];
1058 elsif ($self->{user}->wantdxcq) {
1059 $slot1 = sprintf(" %2d", $_[9]) if defined $_[9];
1062 $comment = substr($comment, 0, $clth-length($slot1)) . $slot1 if $slot1;
1064 if (!$slot2 && $self->{user}->wantgrid) {
1066 $origin =~ s/-#$//; # sigh......
1067 my $ref = DXUser::get_current($origin);
1068 if ($ref && $ref->qra) {
1069 $slot2 = ' ' . substr($ref->qra, 0, 4);
1072 if (!$slot2 && $self->{user}->wantusstate) {
1073 $slot2 = " $_[13]" if $_[13];
1076 if ($self->{user}->wantdxitu) {
1077 $slot2 = sprintf(" %2d", $_[10]) if defined $_[10];
1079 elsif ($self->{user}->wantdxcq) {
1080 $slot2 = sprintf(" %2d", $_[11]) if defined $_[11];
1085 my $o = sprintf("%-9s", $_[4] . ':');
1086 my $qrg = sprintf "%8.1f", $_[0];
1087 if (length $qrg >= 9) {
1088 while (length($o)+length($qrg) > 17 && $o =~ / $/) {
1092 my $spot = sprintf "%-12s", $_[1];
1093 my $front = "DX de $o $qrg $spot";
1094 while (length($front) > 38 && $front =~ / $/) {
1099 return sprintf "$front %-s $t$slot2", $comment;
1108 my $isolate = shift;
1109 return unless $self->{dx};
1111 my ($filter, $hops);
1113 if ($self->{spotsfilter}) {
1114 ($filter, $hops) = $self->{spotsfilter}->it(@_ );
1115 return unless $filter;
1118 dbg('spot: "' . join('","', @_) . '"') if isdbg('dxspot');
1121 if ($self->{ve7cc}) {
1122 $buf = VE7CC::dx_spot($self, @_);
1123 } elsif ($self->{gtk}) {
1124 my ($dxloc, $byloc);
1126 my $ref = DXUser::get_current($_[4]);
1129 $byloc = substr($byloc, 0, 4) if $byloc;
1133 $spot =~ s|/\w{1,4}$||;
1134 $ref = DXUser::get_current($spot);
1137 $dxloc = substr($dxloc, 0, 4) if $dxloc;
1139 $buf = dd(['dx', @_, ($dxloc||''), ($byloc||'')]);
1142 $buf = $self->format_dx_spot(@_);
1143 $buf .= "\a\a" if $self->{beep};
1144 #$buf =~ s/\%5E/^/g;
1147 $self->local_send('X', $buf);
1154 my $isolate = shift;
1155 my ($filter, $hops);
1157 return unless $self->{wwv};
1159 if ($self->{wwvfilter}) {
1160 ($filter, $hops) = $self->{wwvfilter}->it(@_[7..$#_] );
1161 return unless $filter;
1166 $buf = dd(['wwv', @_])
1168 $buf = "WWV de $_[6] <$_[1]>: SFI=$_[2], A=$_[3], K=$_[4], $_[5]";
1169 $buf .= "\a\a" if $self->{beep};
1172 $self->local_send('V', $buf);
1179 my $isolate = shift;
1180 my ($filter, $hops);
1182 return unless $self->{wcy};
1184 if ($self->{wcyfilter}) {
1185 ($filter, $hops) = $self->{wcyfilter}->it(@_ );
1186 return unless $filter;
1191 $buf = dd(['wcy', @_])
1193 $buf = "WCY de $_[10] <$_[1]> : K=$_[4] expK=$_[5] A=$_[3] R=$_[6] SFI=$_[2] SA=$_[7] GMF=$_[8] Au=$_[9]";
1194 $buf .= "\a\a" if $self->{beep};
1196 $self->local_send('Y', $buf);
1199 # broadcast debug stuff to all interested parties
1202 my $s = shift; # the line to be rebroadcast
1204 foreach my $dxchan (DXChannel::get_all_users) {
1205 next unless $dxchan->{enhanced} && $dxchan->{senddbg};
1206 if ($dxchan->{gtk}) {
1207 $dxchan->send_later('L', dd(['db', $s]));
1209 $dxchan->send_later('L', $s);
1220 if ($self->state eq 'enterbody') {
1221 my $loc = $self->{loc} || confess "local var gone missing" ;
1222 if ($line eq "\032" || $line eq '%1A' || uc $line eq "/EX") {
1224 push @out, &{$loc->{endaction}}($self); # like this for < 5.8.0
1226 $self->state('prompt');
1227 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
1228 push @out, $self->msg('m10');
1229 delete $loc->{lines};
1230 delete $self->{loc};
1232 $self->state('prompt');
1234 push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
1235 # i.e. it ain't and end or abort, therefore store the line
1238 confess "Invalid state $self->{state}";
1243 sub store_startup_script
1246 my $loc = $self->{loc} || confess "local var gone missing" ;
1248 my $call = $loc->{call} || confess "callsign gone missing";
1249 confess "lines array gone missing" unless ref $loc->{lines};
1250 my $r = Script::store($call, $loc->{lines});
1253 push @out, $self->msg('m19', $call, $r);
1255 push @out, $self->msg('m20', $call);
1258 push @out, "error opening startup script $call $!";
1263 # Import any commands contained in any files in import_cmd directory
1265 # If the filename has a recogisable callsign as some delimited part
1266 # of it, then this is the user the command will be run as.
1270 # are there any to do in this directory?
1271 return unless -d $cmdimportdir;
1272 unless (opendir(DIR, $cmdimportdir)) {
1273 LogDbg('err', "can\'t open $cmdimportdir $!");
1277 my @names = readdir(DIR);
1281 return unless @names;
1283 foreach $name (@names) {
1284 next if $name =~ /^\./;
1286 my $s = Script->new($name, $cmdimportdir);
1288 LogDbg('DXCommand', "Run import cmd file $name");
1289 my @cat = split /[^A-Za-z0-9]+/, $name;
1290 my ($call) = grep {is_callsign(uc $_)} @cat;
1291 $call ||= $main::mycall;
1296 $s->inscript(0); # switch off script checks
1298 if ($call eq $main::mycall) {
1299 @out = $s->run($main::me, 1);
1301 my $dxchan = DXChannel::get($call);
1303 @out = $s->run($dxchan, 1);
1305 my $u = DXUser::get($call);
1307 $dxchan = $main::me;
1308 my $old = $dxchan->{call};
1309 my $priv = $dxchan->{priv};
1310 my $user = $dxchan->{user};
1311 $dxchan->{call} = $call;
1312 $dxchan->{priv} = $u->priv;
1313 $dxchan->{user} = $u;
1314 @out = $s->run($dxchan, 1);
1315 $dxchan->{call} = $old;
1316 $dxchan->{priv} = $priv;
1317 $dxchan->{user} = $user;
1319 LogDbg('err', "Trying to run import cmd for non-existant user $call");
1325 LogDbg('DXCommand', "Import cmd $name/$call: $_");
1328 LogDbg('err', "Failed to open $cmdimportdir/$name $!");
1329 unlink "$cmdimportdir/$name";
1334 sub print_find_reply
1336 my ($self, $node, $target, $flag, $ms) = @_;
1337 my $sort = $flag == 2 ? "External" : "Local";
1338 $self->send("$sort $target found at $node in $ms ms" );
1341 # send the most relevant motd
1347 unless ($self->isregistered) {
1348 $motd = "${main::motd}_nor_$self->{lang}";
1349 $motd = "${main::motd}_nor" unless -e $motd;
1351 $motd = "${main::motd}_$self->{lang}" unless $motd && -e $motd;
1352 $motd = $main::motd unless $motd && -e $motd;
1353 if ($self->conn->ax25) {
1355 $motd = "${motd}_ax25" if -e "${motd}_ax25";
1357 $motd = "${main::motd}_ax25" if -e "${main::motd}_ax25";
1360 $self->send_file($motd) if -e $motd;
1363 # Punt off a long running command into a separate process
1365 # This is called from commands to run some potentially long running
1366 # function. The process forks and then runs the function and returns
1367 # the result back to the cmd.
1369 # NOTE: this merely forks the current process and then runs the cmd in that (current) context.
1370 # IT DOES NOT START UP SOME NEW PROGRAM AND RELIES ON THE FACT THAT IT IS RUNNING DXSPIDER
1371 # THE CURRENT CONTEXT!!
1373 # call: $self->spawn_cmd($original_cmd_line, \<function>, [cb => sub{...}], [prefix => "cmd> "], [progress => 0|1], [args => [...]]);
1379 my $call = $self->{call};
1383 my $cb = delete $args{cb};
1384 my $prefix = delete $args{prefix};
1385 my $progress = delete $args{progress};
1386 my $args = delete $args{args} || [];
1387 my $t0 = [gettimeofday];
1391 # just behave normally if something has set the "one-shot" _nospawn in the channel
1392 if ($self->{_nospawn} || $main::is_win == 1) {
1393 eval { @out = $cmdref->(@$args); };
1395 DXDebug::dbgprintring(25);
1396 push @out, DXDebug::shortmess($@);
1401 my $fc = DXSubprocess->new;
1402 # $fc->serializer(\&encode_json);
1403 # $fc->deserializer(\&decode_json);
1407 if (isdbg('progress')) {
1408 my $s = qq{$call line: "$line"};
1409 $s .= ", args: " . join(', ', map { defined $_ ? qq{'$_'} : q{'undef'} } @$args) if $args && @$args;
1413 ++$self->{_in_sub_process};
1414 dbg "\$self->{_in_sub_process} = $self->{_in_sub_process}";
1415 @out = $cmdref->(@$args);
1416 --$self->{_in_sub_process} if $self->{_in_sub_process} > 0;
1419 DXDebug::dbgprintring(25);
1420 push @out, DXDebug::shortmess($@);
1426 my ($fc, $err, @res) = @_;
1427 my $dxchan = DXChannel::get($call);
1428 return unless $dxchan;
1431 my $s = "DXProt::spawn_cmd: call $call error $err";
1432 dbg($s) if isdbg('chan');
1437 # transform output if required
1438 @res = $cb->($dxchan, @res);
1441 if (defined $prefix) {
1442 $dxchan->send(map {"$prefix$_"} @res);
1444 $dxchan->send(@res);
1447 diffms("by $call", $line, $t0, scalar @res) if isdbg('progress');
1455 return ($users, $maxusers);
1458 # alias localhost if required. This is designed to repress all localhost and other
1459 # internal interfaces to a fixed (outside) IPv4 or IPV6 address
1462 my $hostname = shift;
1463 if ($hostname =~ /./) {
1464 return $hostname unless $main::localhost_alias_ipv4;
1465 return (grep $hostname eq $_, @main::localhost_names) ? $main::localhost_alias_ipv4 : $hostname;
1466 } elsif ($hostname =~ /:/) {
1467 return $hostname unless $main::localhost_alias_ipv6;
1468 return (grep $hostname eq $_, @main::localhost_names) ? $main::localhost_alias_ipv6 : $hostname;