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