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