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