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