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