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