added qra conversions and heading/distance calculations
[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 # $Id$
8
9
10 package DXCommandmode;
11
12 @ISA = qw(DXChannel);
13
14 use DXUtil;
15 use DXChannel;
16 use DXUser;
17 use DXVars;
18 use DXDebug;
19 use DXM;
20 use DXLog;
21 use DXLogPrint;
22 use DXBearing;
23 use CmdAlias;
24 use FileHandle;
25 use Carp;
26
27 use strict;
28 use vars qw(%Cache %cmd_cache $errstr %aliases);
29
30 %Cache = ();                                    # cache of dynamically loaded routine's mod times
31 %cmd_cache = ();                                # cache of short names
32 $errstr = ();                                   # error string from eval
33 %aliases = ();                                  # aliases for (parts of) commands
34
35 #
36 # obtain a new connection this is derived from dxchannel
37 #
38
39 sub new 
40 {
41         my $self = DXChannel::alloc(@_);
42         $self->{sort} = 'U';            # in absence of how to find out what sort of an object I am
43         return $self;
44 }
45
46 # this is how a a connection starts, you get a hello message and the motd with
47 # possibly some other messages asking you to set various things up if you are
48 # new (or nearly new and slacking) user.
49
50 sub start
51
52         my ($self, $line, $sort) = @_;
53         my $user = $self->{user};
54         my $call = $self->{call};
55         my $name = $user->{name};
56         
57         $self->{name} = $name ? $name : $call;
58         $self->send($self->msg('l2',$self->{name}));
59         $self->send_file($main::motd) if (-e $main::motd);
60         $self->state('prompt');         # a bit of room for further expansion, passwords etc
61         $self->{priv} = $user->priv;
62         $self->{lang} = $user->lang;
63         $self->{pagelth} = 20;
64         $self->{priv} = 0 if $line =~ /^(ax|te)/; # set the connection priv to 0 - can be upgraded later
65         $self->{consort} = $line;       # save the connection type
66         
67         # set some necessary flags on the user if they are connecting
68         $self->{beep} = $self->{wwv} = $self->{talk} = $self->{ann} = $self->{here} = $self->{dx} = 1;
69         #  $self->prompt() if $self->{state} =~ /^prompt/o;
70         
71         # add yourself to the database
72         my $node = DXNode->get($main::mycall) or die "$main::mycall not allocated in DXNode database";
73         my $cuser = DXNodeuser->new($self, $node, $call, 0, 1);
74         $node->dxchan($self) if $call eq $main::myalias; # send all output for mycall to myalias
75         
76         # issue a pc16 to everybody interested
77         my $nchan = DXChannel->get($main::mycall);
78         my @pc16 = DXProt::pc16($nchan, $cuser);
79         DXProt::broadcast_ak1a(@pc16);
80         Log('DXCommand', "$call connected");
81         
82         # send prompts and things
83         my $info = DXCluster::cluster();
84         $self->send("Cluster:$info");
85         $self->send($self->msg('pr', $call));
86 }
87
88 #
89 # This is the normal command prompt driver
90 #
91
92 sub normal
93 {
94         my $self = shift;
95         my $cmdline = shift;
96         my @ans;
97         
98         # remove leading and trailing spaces
99         $cmdline =~ s/^\s*(.*)\s*$/$1/;
100         
101         if ($self->{state} eq 'page') {
102                 my $i = $self->{pagelth};
103                 my $ref = $self->{pagedata};
104                 my $tot = @$ref;
105                 
106                 # abort if we get a line starting in with a
107                 if ($cmdline =~ /^a/io) {
108                         undef $ref;
109                         $i = 0;
110                 }
111         
112                 # send a tranche of data
113                 while ($i-- > 0 && @$ref) {
114                         my $line = shift @$ref;
115                         $line =~ s/\s+$//o;     # why am having to do this? 
116                         $self->send($line);
117                 }
118                 
119                 # reset state if none or else chuck out an intermediate prompt
120                 if ($ref && @$ref) {
121                         $tot -= $self->{pagelth};
122                         $self->send($self->msg('page', $tot));
123                 } else {
124                         $self->state('prompt');
125                 }
126         } else {
127                 @ans = run_cmd($self, $cmdline) if length $cmdline;
128                 
129                 if ($self->{pagelth} && @ans > $self->{pagelth}) {
130                         my $i;
131                         for ($i = $self->{pagelth}; $i-- > 0; ) {
132                                 my $line = shift @ans;
133                                 $line =~ s/\s+$//o;     # why am having to do this? 
134                                 $self->send($line);
135                         }
136                         $self->{pagedata} =  \@ans;
137                         $self->state('page');
138                         $self->send($self->msg('page', scalar @ans));
139                 } else {
140                         for (@ans) {
141                                 s/\s+$//o;              # why ?????????
142                                 $self->send($_);
143                         }
144                 } 
145         } 
146         
147         # send a prompt only if we are in a prompt state
148         $self->prompt() if $self->{state} =~ /^prompt/o;
149 }
150
151
152 # this is the thing that runs the command, it is done like this for the 
153 # benefit of remote command execution
154 #
155
156 sub run_cmd
157 {
158         my $self = shift;
159         my $user = $self->{user};
160         my $call = $self->{call};
161         my $cmdline = shift;
162         my @ans;
163         
164         if ($self->{func}) {
165                 my $c = qq{ \@ans = $self->{func}(\$self, \$cmdline) };
166                 dbg('eval', "stored func cmd = $c\n");
167                 eval  $c;
168                 if ($@) {
169                         return (1, "Syserr: Eval err $errstr on stored func $self->{func}");
170                 }
171         } else {
172                 
173                 # strip out //
174                 $cmdline =~ s|//|/|og;
175                 
176                 # split the command line up into parts, the first part is the command
177                 my ($cmd, $args) = $cmdline =~ /^([\S\/]+)\s*(.*)/o;
178                 
179                 if ($cmd) {
180                         
181                         my ($path, $fcmd);
182                         
183                         dbg('command', "cmd: $cmd");
184                         
185                         # alias it if possible
186                         my $acmd = CmdAlias::get_cmd($cmd);
187                         if ($acmd) {
188                                 ($cmd, $args) = "$acmd $args" =~ /^([\w\/]+)\s*(.*)/o;
189                                 dbg('command', "aliased cmd: $cmd $args");
190                         }
191                         
192                         # first expand out the entry to a command
193                         ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
194                         ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
195
196                         dbg('command', "path: $cmd cmd: $fcmd");
197                         
198                         my $package = find_cmd_name($path, $fcmd);
199                         @ans = (0) if !$package ;
200                         
201                         if ($package) {
202                                 dbg('command', "package: $package");
203                                 
204                                 my $c = qq{ \@ans = $package(\$self, \$args) };
205                                 dbg('eval', "cluster cmd = $c\n");
206                                 eval  $c;
207                                 if ($@) {
208                                         @ans = (0, "Syserr: Eval err cached $package\n$@");
209                                 }
210                         }
211                 }
212         }
213         
214         if ($ans[0]) {
215                 shift @ans;
216         } else {
217                 shift @ans;
218                 if (@ans > 0) {
219                         unshift @ans, $self->msg('e2');
220                 } else {
221                         @ans = $self->msg('e1');
222                 }
223         }
224         return (@ans);
225 }
226
227 #
228 # This is called from inside the main cluster processing loop and is used
229 # for despatching commands that are doing some long processing job
230 #
231 sub process
232 {
233         my $t = time;
234         my @chan = DXChannel->get_all();
235         my $chan;
236         
237         foreach $chan (@chan) {
238                 next if $chan->sort ne 'U';  
239                 
240                 # send a prompt if no activity out on this channel
241                 if ($t >= $chan->t + $main::user_interval) {
242                         $chan->prompt() if $chan->{state} =~ /^prompt/o;
243                         $chan->t($t);
244                 }
245         }
246 }
247
248 #
249 # finish up a user context
250 #
251 sub finish
252 {
253         my $self = shift;
254         my $call = $self->call;
255         
256         if ($call eq $main::myalias) { # unset the channel if it is us really
257                 my $node = DXNode->get($main::mycall);
258                 $node->{dxchan} = 0;
259         }
260         my $ref = DXNodeuser->get($call);
261         
262         # issue a pc17 to everybody interested
263         my $nchan = DXChannel->get($main::mycall);
264         my $pc17 = $nchan->pc17($self);
265         DXProt::broadcast_ak1a($pc17);
266         
267         Log('DXCommand', "$call disconnected");
268         $ref->del() if $ref;
269 }
270
271 #
272 # short cut to output a prompt
273 #
274
275 sub prompt
276 {
277         my $self = shift;
278         my $call = $self->{call};
279         $self->send($self->msg('pr', $call));
280         #DXChannel::msg($self, 'pr', $call);
281 }
282
283 # broadcast a message to all users [except those mentioned after buffer]
284 sub broadcast
285 {
286         my $pkg = shift;                        # ignored
287         my $s = shift;                          # the line to be rebroadcast
288         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
289         my @list = DXChannel->get_all(); # just in case we are called from some funny object
290         my ($chan, $except);
291         
292  L: foreach $chan (@list) {
293                 next if !$chan->sort eq 'U'; # only interested in user channels  
294                 foreach $except (@except) {
295                         next L if $except == $chan;     # ignore channels in the 'except' list
296                 }
297                 chan->send($s);                 # send it
298         }
299 }
300
301 # gimme all the users
302 sub get_all
303 {
304         my @list = DXChannel->get_all();
305         my $ref;
306         my @out;
307         foreach $ref (@list) {
308                 push @out, $ref if $ref->sort eq 'U';
309         }
310         return @out;
311 }
312
313 #
314 # search for the command in the cache of short->long form commands
315 #
316
317 sub search
318 {
319         my ($path, $short_cmd, $suffix) = @_;
320         my ($apath, $acmd);
321         
322         # commands are lower case
323         $short_cmd = lc $short_cmd;
324         dbg('command', "command: $path $short_cmd\n");
325
326         # do some checking for funny characters
327         return () if $short_cmd =~ /\/$/;
328
329         # return immediately if we have it
330         my ($apath, $acmd) = split ',', $cmd_cache{$short_cmd};
331         if ($apath && $acmd) {
332                 dbg('command', "cached $short_cmd = ($apath, $acmd)\n");
333                 return ($apath, $acmd);
334         }
335         
336         # if not guess
337         my @parts = split '/', $short_cmd;
338         my $dirfn;
339         my $curdir = $path;
340         my $p;
341         my $i;
342         my @lparts;
343         
344         for ($i = 0; $i < @parts; $i++) {
345                 my  $p = $parts[$i];
346                 opendir(D, $curdir) or confess "can't open $curdir $!";
347                 my @ls = readdir D;
348                 closedir D;
349                 my $l;
350                 foreach $l (sort @ls) {
351                         next if $l =~ /^\./;
352                         if ($i < $#parts) {             # we are dealing with directories
353                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
354                                         dbg('command', "got dir: $curdir/$l\n");
355                                         $dirfn .= "$l/";
356                                         $curdir .= "/$l";
357                                         last;
358                                 }
359                         } else {                        # we are dealing with commands
360                                 @lparts = split /\./, $l;                  
361                                 next if $lparts[$#lparts] ne $suffix;        # only look for .$suffix files
362                                 if ($p eq substr($l, 0, length $p)) {
363                                         pop @lparts; #  remove the suffix
364                                         $l = join '.', @lparts;
365                                         #                 chop $dirfn;               # remove trailing /
366                                         $cmd_cache{"$short_cmd"} = join(',', ($path, "$dirfn$l")); # cache it
367                                         dbg('command', "got path: $path cmd: $dirfn$l\n");
368                                         return ($path, "$dirfn$l"); 
369                                 }
370                         }
371                 }
372         }
373         return ();  
374 }  
375
376 # clear the command name cache
377 sub clear_cmd_cache
378 {
379         %cmd_cache = ();
380 }
381
382 #
383 # the persistant execution of things from the command directories
384 #
385 #
386 # This allows perl programs to call functions dynamically
387
388 # This has been nicked directly from the perlembed pages
389 #
390
391 #require Devel::Symdump;  
392
393 sub valid_package_name {
394         my($string) = @_;
395         $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
396         
397         #second pass only for words starting with a digit
398         $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
399         
400         #Dress it up as a real package name
401         $string =~ s/\//_/og;
402         return "Emb_" . $string;
403 }
404
405 #borrowed from Safe.pm
406 sub delete_package {
407         my $pkg = shift;
408         my ($stem, $leaf);
409         
410         no strict 'refs';
411         $pkg = "DXCommandmode::$pkg\::"; # expand to full symbol table name
412         ($stem, $leaf) = $pkg =~ m/(.*::)(\w+::)$/;
413         
414         if ($stem && $leaf) {
415                 my $stem_symtab = *{$stem}{HASH};
416                 delete $stem_symtab->{$leaf};
417         }
418 }
419
420 # find a cmd reference
421 # this is really for use in user written stubs
422 #
423 # use the result as a symbolic reference:-
424 #
425 # no strict 'refs';
426 # @out = &$r($self, $line);
427 #
428 sub find_cmd_ref
429 {
430         my $cmd = shift;
431         my $r;
432         
433         if ($cmd) {
434                 
435                 # first expand out the entry to a command
436                 my ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
437                 ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
438                 
439                 # make sure it is loaded
440                 $r = find_cmd_name($path, $fcmd);
441         }
442         return $r;
443 }
444
445
446 # this bit of magic finds a command in the offered directory
447 sub find_cmd_name {
448         my $path = shift;
449         my $cmdname = shift;
450         my $package = valid_package_name($cmdname);
451         my $filename = "$path/$cmdname.pl";
452         my $mtime = -M $filename;
453         
454         # return if we can't find it
455         $errstr = undef;
456         if (undef $mtime) {
457                 $errstr = DXM::msg('e1');
458                 return undef;
459         }
460         
461         if(defined $Cache{$package}{mtime} && $Cache{$package}{mtime } <= $mtime) {
462                 #we have compiled this subroutine already,
463                 #it has not been updated on disk, nothing left to do
464                 #print STDERR "already compiled $package->handler\n";
465                 ;
466         } else {
467                 my $fh = new FileHandle;
468                 if (!open $fh, $filename) {
469                         $errstr = "Syserr: can't open '$filename' $!";
470                         return undef;
471                 };
472                 local $/ = undef;
473                 my $sub = <$fh>;
474                 close $fh;
475                 
476                 #wrap the code into a subroutine inside our unique package
477                 my $eval = qq{ 
478                         sub $package 
479                         { 
480                          $sub 
481                         } };
482                 
483                 if (isdbg('eval')) {
484                         my @list = split /\n/, $eval;
485                         my $line;
486                         for (@list) {
487                                 dbg('eval', $_, "\n");
488                         }
489                 }
490                 
491                 {
492                         #hide our variables within this block
493                         my($filename,$mtime,$package,$sub);
494                         eval $eval;
495                 }
496                 
497                 if ($@) {
498                         print "\$\@ = $@";
499                         $errstr = $@;
500                         delete_package($package);
501                 } else {
502                         #cache it unless we're cleaning out each time
503                         $Cache{$package}{mtime} = $mtime;
504                 }
505         }
506         
507         #print Devel::Symdump->rnew($package)->as_string, $/;
508         $package = "DXCommandmode::$package" if $package;
509         $package = undef if $errstr;
510         return $package;
511 }
512
513 1;
514 __END__