5. Only wonder down the msg queue every minute
[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                                         eval {
246                                                 @ans = &{$c}($self, $args);
247                                     };
248                                         
249                                         return ($@) if $@;
250                                 }
251                         } else {
252                                 dbg('command', "cmd: $cmd not found");
253                                 return ($self->msg('e1'));
254                         }
255                 }
256         }
257         
258         shift @ans;
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 # run a script for this user
356 sub run_script
357 {
358         my $self = shift;
359         my $silent = shift || 0;
360         
361 }
362
363 #
364 # search for the command in the cache of short->long form commands
365 #
366
367 sub search
368 {
369         my ($path, $short_cmd, $suffix) = @_;
370         my ($apath, $acmd);
371         
372         # commands are lower case
373         $short_cmd = lc $short_cmd;
374         dbg('command', "command: $path $short_cmd\n");
375
376         # do some checking for funny characters
377         return () if $short_cmd =~ /\/$/;
378
379         # return immediately if we have it
380         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
381         if ($apath && $acmd) {
382                 dbg('command', "cached $short_cmd = ($apath, $acmd)\n");
383                 return ($apath, $acmd);
384         }
385         
386         # if not guess
387         my @parts = split '/', $short_cmd;
388         my $dirfn;
389         my $curdir = $path;
390         my $p;
391         my $i;
392         my @lparts;
393         
394         for ($i = 0; $i < @parts; $i++) {
395                 my  $p = $parts[$i];
396                 opendir(D, $curdir) or confess "can't open $curdir $!";
397                 my @ls = readdir D;
398                 closedir D;
399                 my $l;
400                 foreach $l (sort @ls) {
401                         next if $l =~ /^\./;
402                         if ($i < $#parts) {             # we are dealing with directories
403                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
404                                         dbg('command', "got dir: $curdir/$l\n");
405                                         $dirfn .= "$l/";
406                                         $curdir .= "/$l";
407                                         last;
408                                 }
409                         } else {                        # we are dealing with commands
410                                 @lparts = split /\./, $l;                  
411                                 next if $lparts[$#lparts] ne $suffix;        # only look for .$suffix files
412                                 if ($p eq substr($l, 0, length $p)) {
413                                         pop @lparts; #  remove the suffix
414                                         $l = join '.', @lparts;
415                                         #                 chop $dirfn;               # remove trailing /
416                                         $dirfn = "" unless $dirfn;
417                                         $cmd_cache{"$short_cmd"} = join(',', ($path, "$dirfn$l")); # cache it
418                                         dbg('command', "got path: $path cmd: $dirfn$l\n");
419                                         return ($path, "$dirfn$l"); 
420                                 }
421                         }
422                 }
423         }
424         return ();  
425 }  
426
427 # clear the command name cache
428 sub clear_cmd_cache
429 {
430         %cmd_cache = ();
431 }
432
433 #
434 # the persistant execution of things from the command directories
435 #
436 #
437 # This allows perl programs to call functions dynamically
438
439 # This has been nicked directly from the perlembed pages
440 #
441
442 #require Devel::Symdump;  
443
444 sub valid_package_name {
445         my($string) = @_;
446         $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
447         
448         #second pass only for words starting with a digit
449         $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
450         
451         #Dress it up as a real package name
452         $string =~ s/\//_/og;
453         return $string;
454 }
455
456 # find a cmd reference
457 # this is really for use in user written stubs
458 #
459 # use the result as a symbolic reference:-
460 #
461 # no strict 'refs';
462 # @out = &$r($self, $line);
463 #
464 sub find_cmd_ref
465 {
466         my $cmd = shift;
467         my $r;
468         
469         if ($cmd) {
470                 
471                 # first expand out the entry to a command
472                 my ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
473                 ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
474                 
475                 # make sure it is loaded
476                 $r = find_cmd_name($path, $fcmd);
477         }
478         return $r;
479 }
480
481
482 # this bit of magic finds a command in the offered directory
483 sub find_cmd_name {
484         my $path = shift;
485         my $cmdname = shift;
486         my $package = valid_package_name($cmdname);
487         my $filename = "$path/$cmdname.pl";
488         my $mtime = -M $filename;
489         
490         # return if we can't find it
491         $errstr = undef;
492         unless (defined $mtime) {
493                 $errstr = DXM::msg('e1');
494                 return undef;
495         }
496         
497         if(defined $Cache{$package}->{mtime} &&$Cache{$package}->{mtime} <= $mtime) {
498                 #we have compiled this subroutine already,
499                 #it has not been updated on disk, nothing left to do
500                 #print STDERR "already compiled $package->handler\n";
501                 ;
502         } else {
503
504                 my $sub = readfilestr($filename);
505                 unless ($sub) {
506                         $errstr = "Syserr: can't open '$filename' $!";
507                         return undef;
508                 };
509                 
510                 #wrap the code into a subroutine inside our unique package
511                 my $eval = qq( sub { $sub } );
512                 
513                 if (isdbg('eval')) {
514                         my @list = split /\n/, $eval;
515                         my $line;
516                         for (@list) {
517                                 dbg('eval', $_, "\n");
518                         }
519                 }
520                 
521                 $Cache{$package} = {mtime => $mtime, eval => $eval };
522         }
523
524         return $package;
525 }
526
527 1;
528 __END__