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