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