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