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