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