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