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