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