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