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