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