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