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