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