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