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