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