2c49fabe07cb7422ef8536efb981a5fce5c980c5
[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 (except if the updates not enabled)
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 || ! $DXProt::pc92_ad_enable;
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         my $ipaddr = alias_localhost($self->hostname || '127.0.0.1');
458         $main::me->normal(DXProt::pc93($target, $self->{call}, undef, $text, undef, $ipaddr));
459 }
460
461 sub special_prompt
462 {
463         my $self = shift;
464         my $prompt = shift;
465         my @call;
466         for (@{$self->{talklist}}) {
467                 my ($to, $via) = /(\S+)>(\S+)/;
468                 $to = $_ unless $to;
469                 push @call, $to;
470         }
471         return $self->msg($prompt, join(',', @call));
472 }
473
474 sub talk_prompt
475 {
476         my $self = shift;
477         return $self->special_prompt('talkprompt');
478 }
479
480 sub chat_prompt
481 {
482         my $self = shift;
483         return $self->special_prompt('chatprompt');
484 }
485
486 #
487 # send a load of stuff to a command user with page prompting
488 # and stuff
489 #
490
491 sub send_ans
492 {
493         my $self = shift;
494         
495         if ($self->{pagelth} && @_ > $self->{pagelth}) {
496                 my $i;
497                 for ($i = $self->{pagelth}; $i-- > 0; ) {
498                         my $line = shift @_;
499                         $line =~ s/\s+$//o;     # why am having to do this? 
500                         $self->send($line);
501                 }
502                 $self->{pagedata} =  [ @_ ];
503                 $self->state('page');
504                 $self->send($self->msg('page', scalar @_));
505         } else {
506                 for (@_) {
507                         if (defined $_) {
508                                 $self->send($_);
509                         } else {
510                                 $self->send('');
511                         }
512                 }
513         } 
514 }
515
516
517 # this is the thing that preps for running the command, it is done like this for the 
518 # benefit of remote command execution
519 #
520
521 sub run_cmd
522 {
523         my $self = shift;
524         my $user = $self->{user};
525         my $call = $self->{call};
526         my $cmdline = shift;
527         my @ans;
528         
529         return () if length $cmdline == 0;
530         
531         # split the command line up into parts, the first part is the command
532         my ($cmd, $args) = split /\s+/, $cmdline, 2;
533         $args = "" unless defined $args;
534                 
535         if ($cmd) {
536
537                 # check cmd
538                 if ($cmd =~ m|^/| || $cmd =~ m|[^-?\w/]|) {
539                         LogDbg('DXCommand', "cmd: $self->{call} - invalid characters in '$cmd'");
540                         return $self->_error_out('e1');
541                 }
542
543                 # strip out // on command only
544                 $cmd =~ s|//|/|g;
545                                         
546                 my ($path, $fcmd);
547                         
548                 dbg("cmd: $cmd") if isdbg('command');
549                         
550                 # alias it if possible
551                 my $acmd = CmdAlias::get_cmd($cmd);
552                 if ($acmd) {
553                         ($cmd, $args) = split /\s+/, "$acmd $args", 2;
554                         $args = "" unless defined $args;
555                         dbg("cmd: aliased $cmd $args") if isdbg('command');
556                 }
557                         
558                 # first expand out the entry to a command
559                 ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
560                 ($path, $fcmd) = search($main::cmd, $cmd, "pl") unless $path && $fcmd;
561
562                 if ($path && $cmd) {
563                         dbg("cmd: path $cmd cmd: $fcmd") if isdbg('command');
564                         
565                         my $package = find_cmd_name($path, $fcmd);
566                         return ($@) if $@;
567                                 
568                         if ($package && $self->can("${package}::handle")) {
569                                 no strict 'refs';
570                                 dbg("cmd: package $package") if isdbg('command');
571 #                               Log('cmd', "$self->{call} on $self->{hostname} : '$cmd $args'");
572                                 my $t0 = [gettimeofday];
573                                 eval { @ans = &{"${package}::handle"}($self, $args) };
574                                 if ($@) {
575                                         DXDebug::dbgprintring(25);
576                                         return (DXDebug::shortmess($@));
577                                 }
578                                 if (isdbg('progress')) {
579                                         my $msecs = _diffms($t0);
580                                         my $s = "CMD: '$cmd $args' by $call ip: $self->{hostname} ${msecs}mS";
581                                         dbg($s) if $cmd !~ /^(?:echo|blank)/ || isdbg('echo');     # cut down a bit on HRD and other clients' noise
582                                 }
583                         } else {
584                                 dbg("cmd: $package not present") if isdbg('command');
585                                 return $self->_error_out('e1');
586                         }
587                 } else {
588                         dbg("cmd: $cmd not found") if isdbg('command');
589                         return $self->_error_out('e1');
590                 }
591         }
592         
593         my $ok = shift @ans;
594         if ($ok) {
595                 delete $self->{errors};
596         } else {
597                 if (++$self->{errors} > $DXChannel::maxerrors) {
598                         $self->send($self->msg('e26'));
599                         $self->disconnect;
600                         return ();
601                 }
602         }
603         return map {s/([^\s])\s+$/$1/; $_} @ans;
604 }
605
606 #
607 # This is called from inside the main cluster processing loop and is used
608 # for despatching commands that are doing some long processing job
609 #
610 sub process
611 {
612         my $t = time;
613         my @dxchan = DXChannel::get_all();
614         my $dxchan;
615
616         $users = 0;
617         foreach $dxchan (@dxchan) {
618                 next unless $dxchan->is_user;  
619         
620                 # send a outstanding message prompt if required
621                 if ($t >= $dxchan->lastmsgpoll + $msgpolltime) {
622                         $dxchan->send($dxchan->msg('m9')) if DXMsg::for_me($dxchan->call);
623                         $dxchan->lastmsgpoll($t);
624                 }
625                 
626                 # send a prompt if no activity out on this channel
627                 if ($t >= $dxchan->t + $main::user_interval) {
628                         $dxchan->prompt() if $dxchan->{state} =~ /^prompt/o;
629                         $dxchan->t($t);
630                 }
631                 ++$users;
632                 $maxusers = $users if $users > $maxusers;
633
634                 if ($dxchan->{isslugged} && $main::systime > $dxchan->{isslugged}) {
635                         foreach my $ref (@{$dxchan->{sluggedpcs}}) {
636                                 if ($ref->[0] == 61) {
637                                         Spot::add(@{$ref->[2]});
638                                         DXProt::send_dx_spot($dxchan, $ref->[1], @{$ref->[2]});
639                                 }
640                         }
641
642                         $dxchan->{isslugged} = 0;
643                         $dxchan->{sluggedpcs} = [];
644                 }
645         }
646
647         import_cmd();
648 }
649
650 #
651 # finish up a user context
652 #
653 sub disconnect
654 {
655         my $self = shift;
656         my $call = $self->call;
657
658         return if $self->{disconnecting}++;
659
660         delete $self->{senddbg};
661         RBN::del_seeme($call);
662
663         my $uref = Route::User::get($call);
664         my @rout;
665         if ($uref) {
666 #               @rout = $main::routeroot->del_user($uref);
667                 @rout = DXProt::_del_thingy($main::routeroot, [$call, 0]);
668
669                 # dbg("B/C PC17 on $main::mycall for: $call") if isdbg('route');
670
671                 # issue a pc17 to everybody interested
672                 $main::me->route_pc17($main::mycall, undef, $main::routeroot, $uref);
673                 $main::me->route_pc92d($main::mycall, undef, $main::routeroot, $uref) unless $DXProt::pc92_slug_changes || ! $DXProt::pc92_ad_enable;
674         } else {
675                 confess "trying to disconnect a non existant user $call";
676         }
677
678         # I was the last node visited
679     $self->user->node($main::mycall);
680                 
681         # send info to all logged in thingies
682         $self->tell_login('logoutu');
683         $self->tell_buddies('logoutb');
684
685         LogDbg('DXCommand', "$call disconnected");
686
687         $self->SUPER::disconnect;
688 }
689
690 #
691 # short cut to output a prompt
692 #
693
694 sub prompt
695 {
696         my $self = shift;
697
698         return if $self->{gtk};         # 'cos prompts are not a concept that applies here
699         
700         my $call = $self->call;
701         my $date = cldate($main::systime);
702         my $time = ztime($main::systime);
703         my $prompt = $self->{prompt} || $self->msg('pr');
704
705         $call = "($call)" unless $self->here;
706         $prompt =~ s/\%C/$call/g;
707         $prompt =~ s/\%D/$date/g;
708         $prompt =~ s/\%T/$time/g;
709         $prompt =~ s/\%M/$main::mycall/g;
710         
711         $self->send($prompt);
712 }
713
714 # broadcast a message to all users [except those mentioned after buffer]
715 sub broadcast
716 {
717         my $pkg = shift;                        # ignored
718         my $s = shift;                          # the line to be rebroadcast
719         
720     foreach my $dxchan (DXChannel::get_all()) {
721                 next unless $dxchan->is_user; # only interested in user channels  
722                 next if grep $dxchan == $_, @_;
723                 $dxchan->send($s);                      # send it
724         }
725 }
726
727 # gimme all the users
728 sub get_all
729 {
730         goto &DXChannel::get_all_users;
731 }
732
733 # run a script for this user
734 sub run_script
735 {
736         my $self = shift;
737         my $silent = shift || 0;
738         
739 }
740
741 #
742 # search for the command in the cache of short->long form commands
743 #
744
745 sub search
746 {
747         my ($path, $short_cmd, $suffix) = @_;
748         my ($apath, $acmd);
749         
750         # commands are lower case
751         $short_cmd = lc $short_cmd;
752         dbg("command: $path $short_cmd\n") if isdbg('command');
753
754         # do some checking for funny characters
755         return () if $short_cmd =~ /\/$/;
756
757         # return immediately if we have it
758         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
759         if ($apath && $acmd) {
760                 dbg("cached $short_cmd = ($apath, $acmd)\n") if isdbg('command');
761                 return ($apath, $acmd);
762         }
763         
764         # if not guess
765         my @parts = split '/', $short_cmd;
766         my $dirfn;
767         my $curdir = $path;
768         
769         while (my $p = shift @parts) {
770                 opendir(D, $curdir) or confess "can't open $curdir $!";
771                 my @ls = readdir D;
772                 closedir D;
773
774                 # if this isn't the last part
775                 if (@parts) {
776                         my $found;
777                         foreach my $l (sort @ls) {
778                                 next if $l =~ /^\./;
779                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
780                                         dbg("got dir: $curdir/$l\n") if isdbg('command');
781                                         $dirfn .= "$l/";
782                                         $curdir .= "/$l";
783                                         $found++;
784                                         last;
785                                 }
786                         }
787                         # only proceed if we find the directory asked for
788                         return () unless $found;
789                 } else {
790                         foreach my $l (sort @ls) {
791                                 next if $l =~ /^\./;
792                                 next unless $l =~ /\.$suffix$/;
793                                 if ($p eq substr($l, 0, length $p)) {
794                                         $l =~ s/\.$suffix$//;
795                                         $dirfn = "" unless $dirfn;
796                                         $cmd_cache{$short_cmd} = join(',', ($path, "$dirfn$l")); # cache it
797                                         dbg("got path: $path cmd: $dirfn$l\n") if isdbg('command');
798                                         return ($path, "$dirfn$l");
799                                 }
800                         }
801                 }
802         }
803
804         return ();  
805 }  
806
807 # clear the command name cache
808 sub clear_cmd_cache
809 {
810         no strict 'refs';
811         
812         for my $k (keys %Cache) {
813                 unless ($k =~ /cmd_cache/) {
814                         dbg("Undefining cmd $k") if isdbg('command');
815                         undef $DXCommandmode::{"${k}::"};
816                 }
817         }
818         %cmd_cache = ();
819         %Cache = ( cmd_clear_cmd_cache  => $Cache{cmd_clear_cmd_cache} );
820 }
821
822 #
823 # the persistant execution of things from the command directories
824 #
825 #
826 # This allows perl programs to call functions dynamically
827
828 # This has been nicked directly from the perlembed pages
829 #
830 #require Devel::Symdump;  
831
832 sub valid_package_name {
833         my $string = shift;
834         $string =~ s|([^A-Za-z0-9_/])|sprintf("_%2x",unpack("C",$1))|eg;
835         
836         $string =~ s|/|_|g;
837         return "cmd_$string";
838 }
839
840
841 # this bit of magic finds a command in the offered directory
842 sub find_cmd_name {
843         my $path = shift;
844         my $cmdname = shift;
845         my $package = valid_package_name($cmdname);
846         my $filename = "$path/$cmdname.pl";
847         my $mtime = -M $filename;
848         
849         # return if we can't find it
850         $errstr = undef;
851         unless (defined $mtime) {
852                 $errstr = DXM::msg('e1');
853                 return undef;
854         }
855         
856         if(exists $Cache{$package} && exists $Cache{$package}->{mtime} && $Cache{$package}->{mtime} <= $mtime) {
857                 #we have compiled this subroutine already,
858                 #it has not been updated on disk, nothing left to do
859                 #print STDERR "already compiled $package->handler\n";
860                 dbg("find_cmd_name: $package cached") if isdbg('command');
861         } else {
862
863                 my $sub = readfilestr($filename);
864                 unless ($sub) {
865                         $errstr = "Syserr: can't open '$filename' $!";
866                         return undef;
867                 };
868                 
869                 #wrap the code into a subroutine inside our unique package
870                 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}; );
871
872
873                 if ($sub =~ m|\s*sub\s+handle\n|) {
874                         $eval .= $sub;
875                 } else {
876                         $eval .= qq(sub handle { $sub });
877                 }
878                 
879                 if (isdbg('eval')) {
880                         my @list = split /\n/, $eval;
881                         my $line;
882                         for (@list) {
883                                 dbg($_ . "\n") if isdbg('eval');
884                         }
885                 }
886                 
887                 # get rid of any existing sub and try to compile the new one
888                 no strict 'refs';
889
890                 if (exists $Cache{$package}) {
891                         dbg("find_cmd_name: Redefining $package") if isdbg('command');
892                         undef $DXCommandmode::{"${package}::"};
893                         delete $Cache{$package};
894                 } else {
895                         dbg("find_cmd_name: Defining $package") if isdbg('command');
896                 }
897
898                 eval $eval;
899
900                 $Cache{$package} = {mtime => $mtime } unless $@;
901         }
902
903         return "DXCommandmode::$package";
904 }
905
906 sub send
907 {
908         my $self = shift;
909         if ($self->{gtk}) {
910                 for (@_) {
911                         $self->SUPER::send(dd(['cmd',$_]));
912                 }
913         } else {
914                 $self->SUPER::send(@_);
915         }
916 }
917
918 sub local_send
919 {
920         my ($self, $let, $buf) = @_;
921         if ($self->{state} eq 'prompt' || $self->{state} eq 'talk' || $self->{state} eq 'chat') {
922                 if ($self->{enhanced}) {
923                         $self->send_later($let, $buf);
924                 } else {
925                         $self->send($buf);
926                 }
927         } else {
928                 $self->delay($buf);
929         }
930 }
931
932 # send a talk message here
933 sub talk
934 {
935         my ($self, $from, $to, $via, $line, $onode) = @_;
936         $line =~ s/\\5E/\^/g;
937         if ($self->{talk}) {
938                 if ($self->{gtk}) {
939                         $self->local_send('T', dd(['talk',$to,$from,$via,$line]));
940                 } else {
941                         $self->local_send('T', "$to de $from: $line");
942                 }
943         }
944         Log('talk', $to, $from, '<' . ($onode || '*'), $line);
945         # send a 'not here' message if required
946         unless ($self->{here} && $from ne $to) {
947                 my $key = "$to$from";
948                 unless (exists $nothereslug{$key}) {
949                         my ($ref, $dxchan);
950                         if (($ref = Route::get($from)) && ($dxchan = $ref->dxchan)) {
951                                 my $name = $self->user->name || $to;
952                                 my $s = $self->user->nothere || $dxchan->msg('nothere', $name);
953                                 $nothereslug{$key} = $main::systime;
954                                 $dxchan->talk($to, $from, undef, $s);
955                         }
956                 }
957         }
958 }
959
960 # send an announce
961 sub announce
962 {
963         my $self = shift;
964         my $line = shift;
965         my $isolate = shift;
966         my $to = shift;
967         my $target = shift;
968         my $text = shift;
969         my ($filter, $hops);
970
971         if (!$self->{ann_talk} && $to ne $self->{call}) {
972                 my $call = AnnTalk::is_talk_candidate($_[0], $text);
973                 return if $call;
974         }
975
976         if ($self->{annfilter}) {
977                 ($filter, $hops) = $self->{annfilter}->it(@_ );
978                 return unless $filter;
979         }
980
981         unless ($self->{ann}) {
982                 return if $_[0] ne $main::myalias && $_[0] ne $main::mycall;
983         }
984         return if $target eq 'SYSOP' && $self->{priv} < 5;
985         my $buf;
986         if ($self->{gtk}) {
987                 $buf = dd(['ann', $to, $target, $text, @_])
988         } else {
989                 $buf = "$to$target de $_[0]: $text";
990                 #$buf =~ s/\%5E/^/g;
991                 $buf .= "\a\a" if $self->{beep};
992         }
993         $self->local_send($target eq 'WX' ? 'W' : 'N', $buf);
994 }
995
996 # send a chat
997 sub chat
998 {
999         my $self = shift;
1000         my $line = shift;
1001         my $isolate = shift;
1002         my $target = shift;
1003         my $to = shift;
1004         my $text = shift;
1005         my ($filter, $hops);
1006
1007         return unless grep uc $_ eq $target, @{$self->{user}->{group}};
1008         
1009         $text =~ s/^\#\d+ //;
1010         my $buf;
1011         if ($self->{gtk}) {
1012                 $buf = dd(['chat', $to, $target, $text, @_])
1013         } else {
1014                 $buf = "$target de $_[0]: $text";
1015                 #$buf =~ s/\%5E/^/g;
1016                 $buf .= "\a\a" if $self->{beep};
1017         }
1018         $self->local_send('C', $buf);
1019 }
1020
1021 sub format_dx_spot
1022 {
1023         my $self = shift;
1024
1025         my $t = ztime($_[2]);
1026         my ($slot1, $slot2) = ('', '');
1027         
1028         my $clth = 30 + $self->{width} - 80;    # allow comment to grow according the screen width 
1029         my $c = $_[3];
1030         $c =~ s/\t/ /g;
1031         my $comment = substr (($c || ''), 0, $clth);
1032         $comment .= ' ' x ($clth - (length($comment)));
1033
1034         if ($self->{user}) {            # to allow the standalone program 'showdx' to work
1035                 if (!$slot1 && $self->{user}->wantgrid) {
1036                         my $ref = DXUser::get_current($_[1]);
1037                         if ($ref && $ref->qra) {
1038                                 $slot1 = ' ' . substr($ref->qra, 0, 4);
1039                         }
1040                 }
1041                 if (!$slot1 && $self->{user}->wantusstate) {
1042                         $slot1 = " $_[12]" if $_[12];
1043                 }
1044                 unless ($slot1) {
1045                         if ($self->{user}->wantdxitu) {
1046                                 $slot1 = sprintf(" %2d", $_[8]) if defined $_[8]; 
1047                         }
1048                         elsif ($self->{user}->wantdxcq) {
1049                                 $slot1 = sprintf(" %2d", $_[9]) if defined $_[9];
1050                         }
1051                 }
1052                 $comment = substr($comment, 0,  $clth-length($slot1)) . $slot1 if $slot1;
1053         
1054                 if (!$slot2 && $self->{user}->wantgrid) {
1055                         my $origin = $_[4];
1056                         $origin =~ s/-#$//;     # sigh......
1057                         my $ref = DXUser::get_current($origin);
1058                         if ($ref && $ref->qra) {
1059                                 $slot2 = ' ' . substr($ref->qra, 0, 4);
1060                         }
1061                 }
1062                 if (!$slot2 && $self->{user}->wantusstate) {
1063                         $slot2 = " $_[13]" if $_[13];
1064                 }
1065                 unless ($slot2) {
1066                         if ($self->{user}->wantdxitu) {
1067                                 $slot2 = sprintf(" %2d", $_[10]) if defined $_[10]; 
1068                         }
1069                         elsif ($self->{user}->wantdxcq) {
1070                                 $slot2 = sprintf(" %2d", $_[11]) if defined $_[11]; 
1071                         }
1072                 }
1073         }
1074
1075         my $o = sprintf("%-9s", $_[4] . ':');
1076         my $qrg = sprintf "%8.1f", $_[0];
1077         if (length $qrg >= 9) {
1078                 while (length($o)+length($qrg) > 17 && $o =~ / $/) {
1079                         chop $o;
1080                 }
1081         }
1082         my $spot = sprintf "%-12s", $_[1];
1083         my $front = "DX de $o $qrg  $spot";
1084         while (length($front) > 38 && $front =~ /  $/) {
1085                 chop $front;
1086         }
1087
1088         
1089         return sprintf "$front %-s $t$slot2", $comment;
1090 }
1091
1092
1093 # send a dx spot
1094 sub dx_spot
1095 {
1096         my $self = shift;
1097         my $line = shift;
1098         my $isolate = shift;
1099         return unless $self->{dx};
1100
1101         my ($filter, $hops);
1102
1103         if ($self->{spotsfilter}) {
1104                 ($filter, $hops) = $self->{spotsfilter}->it(@_ );
1105                 return unless $filter;
1106         }
1107
1108         dbg('spot: "' . join('","', @_) . '"') if isdbg('dxspot');
1109
1110         my $buf;
1111         if ($self->{ve7cc}) {
1112                 $buf = VE7CC::dx_spot($self, @_);
1113         } elsif ($self->{gtk}) {
1114                 my ($dxloc, $byloc);
1115
1116                 my $ref = DXUser::get_current($_[4]);
1117                 if ($ref) {
1118                         $byloc = $ref->qra;
1119                         $byloc = substr($byloc, 0, 4) if $byloc;
1120                 }
1121
1122                 my $spot = $_[1];
1123                 $spot =~ s|/\w{1,4}$||;
1124                 $ref = DXUser::get_current($spot);
1125                 if ($ref) {
1126                         $dxloc = $ref->qra;
1127                         $dxloc = substr($dxloc, 0, 4) if $dxloc;
1128                 }
1129                 $buf = dd(['dx', @_, ($dxloc||''), ($byloc||'')]);
1130                 
1131         } else {
1132                 $buf = $self->format_dx_spot(@_);
1133                 $buf .= "\a\a" if $self->{beep};
1134                 #$buf =~ s/\%5E/^/g;
1135         }
1136
1137         $self->local_send('X', $buf);
1138 }
1139
1140 sub wwv
1141 {
1142         my $self = shift;
1143         my $line = shift;
1144         my $isolate = shift;
1145         my ($filter, $hops);
1146
1147         return unless $self->{wwv};
1148         
1149         if ($self->{wwvfilter}) {
1150                 ($filter, $hops) = $self->{wwvfilter}->it(@_[7..$#_] );
1151                 return unless $filter;
1152         }
1153
1154         my $buf;
1155         if ($self->{gtk}) {
1156                 $buf = dd(['wwv', @_])
1157         } else {
1158                 $buf = "WWV de $_[6] <$_[1]>:   SFI=$_[2], A=$_[3], K=$_[4], $_[5]";
1159                 $buf .= "\a\a" if $self->{beep};
1160         }
1161         
1162         $self->local_send('V', $buf);
1163 }
1164
1165 sub wcy
1166 {
1167         my $self = shift;
1168         my $line = shift;
1169         my $isolate = shift;
1170         my ($filter, $hops);
1171
1172         return unless $self->{wcy};
1173         
1174         if ($self->{wcyfilter}) {
1175                 ($filter, $hops) = $self->{wcyfilter}->it(@_ );
1176                 return unless $filter;
1177         }
1178
1179         my $buf;
1180         if ($self->{gtk}) {
1181                 $buf = dd(['wcy', @_])
1182         } else {
1183                 $buf = "WCY de $_[10] <$_[1]> : K=$_[4] expK=$_[5] A=$_[3] R=$_[6] SFI=$_[2] SA=$_[7] GMF=$_[8] Au=$_[9]";
1184                 $buf .= "\a\a" if $self->{beep};
1185         }
1186         $self->local_send('Y', $buf);
1187 }
1188
1189 # broadcast debug stuff to all interested parties
1190 sub broadcast_debug
1191 {
1192         my $s = shift;                          # the line to be rebroadcast
1193         
1194         foreach my $dxchan (DXChannel::get_all_users) {
1195                 next unless $dxchan->{enhanced} && $dxchan->{senddbg};
1196                 if ($dxchan->{gtk}) {
1197                         $dxchan->send_later('L', dd(['db', $s]));
1198                 } else {
1199                         $dxchan->send_later('L', $s);
1200                 }
1201         }
1202 }
1203
1204 sub do_entry_stuff
1205 {
1206         my $self = shift;
1207         my $line = shift;
1208         my @out;
1209         
1210         if ($self->state eq 'enterbody') {
1211                 my $loc = $self->{loc} || confess "local var gone missing" ;
1212                 if ($line eq "\032" || $line eq '%1A' || uc $line eq "/EX") {
1213                         no strict 'refs';
1214                         push @out, &{$loc->{endaction}}($self);          # like this for < 5.8.0
1215                         $self->func(undef);
1216                         $self->state('prompt');
1217                 } elsif ($line eq "\031" || uc $line eq "/ABORT" || uc $line eq "/QUIT") {
1218                         push @out, $self->msg('m10');
1219                         delete $loc->{lines};
1220                         delete $self->{loc};
1221                         $self->func(undef);
1222                         $self->state('prompt');
1223                 } else {
1224                         push @{$loc->{lines}}, length($line) > 0 ? $line : " ";
1225                         # i.e. it ain't and end or abort, therefore store the line
1226                 }
1227         } else {
1228                 confess "Invalid state $self->{state}";
1229         }
1230         return @out;
1231 }
1232
1233 sub store_startup_script
1234 {
1235         my $self = shift;
1236         my $loc = $self->{loc} || confess "local var gone missing" ;
1237         my @out;
1238         my $call = $loc->{call} || confess "callsign gone missing";
1239         confess "lines array gone missing" unless ref $loc->{lines};
1240         my $r = Script::store($call, $loc->{lines});
1241         if (defined $r) {
1242                 if ($r) {
1243                         push @out, $self->msg('m19', $call, $r);
1244                 } else {
1245                         push @out, $self->msg('m20', $call);
1246                 }
1247         } else {
1248                 push @out, "error opening startup script $call $!";
1249         } 
1250         return @out;
1251 }
1252
1253 # Import any commands contained in any files in import_cmd directory
1254 #
1255 # If the filename has a recogisable callsign as some delimited part
1256 # of it, then this is the user the command will be run as. 
1257 #
1258 sub import_cmd
1259 {
1260         # are there any to do in this directory?
1261         return unless -d $cmdimportdir;
1262         unless (opendir(DIR, $cmdimportdir)) {
1263                 LogDbg('err', "can\'t open $cmdimportdir $!");
1264                 return;
1265         } 
1266
1267         my @names = readdir(DIR);
1268         closedir(DIR);
1269         my $name;
1270
1271         return unless @names;
1272         
1273         foreach $name (@names) {
1274                 next if $name =~ /^\./;
1275
1276                 my $s = Script->new($name, $cmdimportdir);
1277                 if ($s) {
1278                         LogDbg('DXCommand', "Run import cmd file $name");
1279                         my @cat = split /[^A-Za-z0-9]+/, $name;
1280                         my ($call) = grep {is_callsign(uc $_)} @cat;
1281                         $call ||= $main::mycall;
1282                         $call = uc $call;
1283                         my @out;
1284                         
1285                         
1286                         $s->inscript(0);        # switch off script checks
1287                         
1288                         if ($call eq $main::mycall) {
1289                                 @out = $s->run($main::me, 1);
1290                         } else {
1291                                 my $dxchan = DXChannel::get($call);
1292                             if ($dxchan) {
1293                                         @out = $s->run($dxchan, 1);
1294                                 } else {
1295                                         my $u = DXUser::get($call);
1296                                         if ($u) {
1297                                                 $dxchan = $main::me;
1298                                                 my $old = $dxchan->{call};
1299                                                 my $priv = $dxchan->{priv};
1300                                                 my $user = $dxchan->{user};
1301                                                 $dxchan->{call} = $call;
1302                                                 $dxchan->{priv} = $u->priv;
1303                                                 $dxchan->{user} = $u;
1304                                                 @out = $s->run($dxchan, 1);
1305                                                 $dxchan->{call} = $old;
1306                                                 $dxchan->{priv} = $priv;
1307                                                 $dxchan->{user} = $user;
1308                                         } else {
1309                                                 LogDbg('err', "Trying to run import cmd for non-existant user $call");
1310                                         }
1311                                 }
1312                         }
1313                         $s->erase;
1314                         for (@out) {
1315                                 LogDbg('DXCommand', "Import cmd $name/$call: $_");
1316                         }
1317                 } else {
1318                         LogDbg('err', "Failed to open $cmdimportdir/$name $!");
1319                         unlink "$cmdimportdir/$name";
1320                 }
1321         }
1322 }
1323
1324 sub print_find_reply
1325 {
1326         my ($self, $node, $target, $flag, $ms) = @_;
1327         my $sort = $flag == 2 ? "External" : "Local";
1328         $self->send("$sort $target found at $node in $ms ms" );
1329 }
1330
1331 # send the most relevant motd
1332 sub send_motd
1333 {
1334         my $self = shift;
1335         my $motd;
1336
1337         unless ($self->isregistered) {
1338                 $motd = "${main::motd}_nor_$self->{lang}";
1339                 $motd = "${main::motd}_nor" unless -e $motd;
1340         }
1341         $motd = "${main::motd}_$self->{lang}" unless $motd && -e $motd;
1342         $motd = $main::motd unless $motd && -e $motd;
1343         if ($self->conn->ax25) {
1344                 if ($motd) {
1345                         $motd = "${motd}_ax25" if -e "${motd}_ax25";
1346                 } else {
1347                         $motd = "${main::motd}_ax25" if -e "${main::motd}_ax25";
1348                 }
1349         }
1350         $self->send_file($motd) if -e $motd;
1351 }
1352
1353 # Punt off a long running command into a separate process
1354 #
1355 # This is called from commands to run some potentially long running
1356 # function. The process forks and then runs the function and returns
1357 # the result back to the cmd. 
1358 #
1359 # NOTE: this merely forks the current process and then runs the cmd in that (current) context.
1360 #       IT DOES NOT START UP SOME NEW PROGRAM AND RELIES ON THE FACT THAT IT IS RUNNING DXSPIDER 
1361 #       THE CURRENT CONTEXT!!
1362
1363 # call: $self->spawn_cmd($original_cmd_line, \<function>, [cb => sub{...}], [prefix => "cmd> "], [progress => 0|1], [args => [...]]);
1364 sub spawn_cmd
1365 {
1366         my $self = shift;
1367         my $line = shift;
1368         my $cmdref = shift;
1369         my $call = $self->{call};
1370         my %args = @_;
1371         my @out;
1372         
1373         my $cb = delete $args{cb};
1374         my $prefix = delete $args{prefix};
1375         my $progress = delete $args{progress};
1376         my $args = delete $args{args} || [];
1377         my $t0 = [gettimeofday];
1378
1379         no strict 'refs';
1380
1381         # just behave normally if something has set the "one-shot" _nospawn in the channel
1382         if ($self->{_nospawn}) {
1383                 eval { @out = $cmdref->(@$args); };
1384                 if ($@) {
1385                         DXDebug::dbgprintring(25);
1386                         push @out, DXDebug::shortmess($@);
1387                 }
1388                 return @out;
1389         }
1390         
1391         my $fc = DXSubprocess->new;
1392 #       $fc->serializer(\&encode_json);
1393 #       $fc->deserializer(\&decode_json);
1394         $fc->run(
1395                          sub {
1396                                  my $subpro = shift;
1397                                  if (isdbg('progress')) {
1398                                          my $s = qq{$call line: "$line"};
1399                                          $s .= ", args: " . join(', ', map { defined $_ ? qq{'$_'} : q{'undef'} } @$args) if $args && @$args;
1400                                          dbg($s);
1401                                  }
1402                                  eval {
1403                                          ++$self->{_in_sub_process};
1404                                          dbg "\$self->{_in_sub_process} = $self->{_in_sub_process}";
1405                                          @out = $cmdref->(@$args);
1406                                          --$self->{_in_sub_process} if $self->{_in_sub_process} > 0;
1407                                  };
1408                                  if ($@) {
1409                                          DXDebug::dbgprintring(25);
1410                                          push @out, DXDebug::shortmess($@);
1411                                  }
1412                                  return @out;
1413                          },
1414 #                        $args,
1415                          sub {
1416                                  my ($fc, $err, @res) = @_; 
1417                                  my $dxchan = DXChannel::get($call);
1418                                  return unless $dxchan;
1419
1420                                  if ($err) {
1421                                          my $s = "DXProt::spawn_cmd: call $call error $err";
1422                                          dbg($s) if isdbg('chan');
1423                                          $dxchan->send($s);
1424                                          return;
1425                                  }
1426                                  if ($cb) {
1427                                          # transform output if required
1428                                          @res = $cb->($dxchan, @res);
1429                                  }
1430                                  if (@res) {
1431                                          if (defined $prefix) {
1432                                                  $dxchan->send(map {"$prefix$_"} @res);
1433                                          } else {
1434                                                  $dxchan->send(@res);
1435                                          }
1436                                  }
1437                                  diffms("by $call", $line, $t0, scalar @res) if isdbg('progress');
1438                          });
1439         
1440         return @out;
1441 }
1442
1443 sub user_count
1444 {
1445     return ($users, $maxusers);
1446 }
1447
1448 # alias localhost if required. This is designed to repress all localhost and other
1449 # internal interfaces to a fixed (outside) IPv4 or IPV6 address
1450 sub alias_localhost
1451 {
1452         my $hostname = shift;
1453         if ($hostname =~ /./) {
1454                 return $hostname unless $main::localhost_alias_ipv4;
1455                 return (grep $hostname eq $_, @main::localhost_names) ? $main::localhost_alias_ipv4 : $hostname;
1456         } elsif ($hostname =~ /:/) {
1457                 return $hostname unless $main::localhost_alias_ipv6;
1458                 return (grep $hostname eq $_, @main::localhost_names) ? $main::localhost_alias_ipv6 : $hostname;
1459         }
1460         return $hostname;
1461 }
1462
1463 1;
1464 __END__