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