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