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