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