added spoofing
[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) = split /\s+/, $cmdline, 2;
210                 $args = "" unless $args;
211                 
212                 if ($cmd) {
213                         
214                         my ($path, $fcmd);
215                         
216                         dbg('command', "cmd: $cmd");
217                         
218                         # alias it if possible
219                         my $acmd = CmdAlias::get_cmd($cmd);
220                         if ($acmd) {
221                                 ($cmd, $args) = split /\s+/, "$acmd $args", 2;
222                                 $args = "" unless $args;
223                                 dbg('command', "aliased cmd: $cmd $args");
224                         }
225                         
226                         # first expand out the entry to a command
227                         ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
228                         ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
229
230                         if ($path && $cmd) {
231                                 dbg('command', "path: $cmd cmd: $fcmd");
232                         
233                                 my $package = find_cmd_name($path, $fcmd);
234                                 @ans = (0) if !$package ;
235                                 
236                                 if ($package) {
237                                         dbg('command', "package: $package");
238                                         my $c;
239                                         unless (exists $Cache{$package}->{sub}) {
240                                                 $c = eval $Cache{$package}->{eval};
241                                                 if ($@) {
242                                                         return ("Syserr: Syntax error in $package", $@);
243                                                 }
244                                                 $Cache{$package}->{sub} = $c;
245                                         }
246                                         $c = $Cache{$package}->{sub};
247                                         eval {
248                                                 @ans = &{$c}($self, $args);
249                                     };
250                                         
251                                         return ($@) if $@;
252                                 }
253                         } else {
254                                 dbg('command', "cmd: $cmd not found");
255                                 return ($self->msg('e1'));
256                         }
257                 }
258         }
259         
260         shift @ans;
261         return (@ans);
262 }
263
264 #
265 # This is called from inside the main cluster processing loop and is used
266 # for despatching commands that are doing some long processing job
267 #
268 sub process
269 {
270         my $t = time;
271         my @dxchan = DXChannel->get_all();
272         my $dxchan;
273         
274         foreach $dxchan (@dxchan) {
275                 next if $dxchan->sort ne 'U';  
276                 
277                 # send a prompt if no activity out on this channel
278                 if ($t >= $dxchan->t + $main::user_interval) {
279                         $dxchan->prompt() if $dxchan->{state} =~ /^prompt/o;
280                         $dxchan->t($t);
281                 }
282         }
283 }
284
285 #
286 # finish up a user context
287 #
288 sub finish
289 {
290         my $self = shift;
291         my $call = $self->call;
292
293         # log out text
294         if (-e "$main::data/logout") {
295                 open(I, "$main::data/logout") or confess;
296                 my @in = <I>;
297                 close(I);
298                 $self->send_now('D', @in);
299                 sleep(1);
300         }
301
302         if ($call eq $main::myalias) { # unset the channel if it is us really
303                 my $node = DXNode->get($main::mycall);
304                 $node->{dxchan} = 0;
305         }
306         my $ref = DXCluster->get_exact($call);
307         
308         # issue a pc17 to everybody interested
309         my $nchan = DXChannel->get($main::mycall);
310         my $pc17 = $nchan->pc17($self);
311         DXProt::broadcast_all_ak1a($pc17);
312         
313         Log('DXCommand', "$call disconnected");
314         $ref->del() if $ref;
315 }
316
317 #
318 # short cut to output a prompt
319 #
320
321 sub prompt
322 {
323         my $self = shift;
324         $self->send($self->msg($self->here ? 'pr' : 'pr2', $self->call));
325 }
326
327 # broadcast a message to all users [except those mentioned after buffer]
328 sub broadcast
329 {
330         my $pkg = shift;                        # ignored
331         my $s = shift;                          # the line to be rebroadcast
332         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
333         my @list = DXChannel->get_all(); # just in case we are called from some funny object
334         my ($dxchan, $except);
335         
336  L: foreach $dxchan (@list) {
337                 next if !$dxchan->sort eq 'U'; # only interested in user channels  
338                 foreach $except (@except) {
339                         next L if $except == $dxchan;   # ignore channels in the 'except' list
340                 }
341                 $dxchan->send($s);                      # send it
342         }
343 }
344
345 # gimme all the users
346 sub get_all
347 {
348         my @list = DXChannel->get_all();
349         my $ref;
350         my @out;
351         foreach $ref (@list) {
352                 push @out, $ref if $ref->sort eq 'U';
353         }
354         return @out;
355 }
356
357 # run a script for this user
358 sub run_script
359 {
360         my $self = shift;
361         my $silent = shift || 0;
362         
363 }
364
365 #
366 # search for the command in the cache of short->long form commands
367 #
368
369 sub search
370 {
371         my ($path, $short_cmd, $suffix) = @_;
372         my ($apath, $acmd);
373         
374         # commands are lower case
375         $short_cmd = lc $short_cmd;
376         dbg('command', "command: $path $short_cmd\n");
377
378         # do some checking for funny characters
379         return () if $short_cmd =~ /\/$/;
380
381         # return immediately if we have it
382         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
383         if ($apath && $acmd) {
384                 dbg('command', "cached $short_cmd = ($apath, $acmd)\n");
385                 return ($apath, $acmd);
386         }
387         
388         # if not guess
389         my @parts = split '/', $short_cmd;
390         my $dirfn;
391         my $curdir = $path;
392         my $p;
393         my $i;
394         my @lparts;
395         
396         for ($i = 0; $i < @parts; $i++) {
397                 my  $p = $parts[$i];
398                 opendir(D, $curdir) or confess "can't open $curdir $!";
399                 my @ls = readdir D;
400                 closedir D;
401                 my $l;
402                 foreach $l (sort @ls) {
403                         next if $l =~ /^\./;
404                         if ($i < $#parts) {             # we are dealing with directories
405                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
406                                         dbg('command', "got dir: $curdir/$l\n");
407                                         $dirfn .= "$l/";
408                                         $curdir .= "/$l";
409                                         last;
410                                 }
411                         } else {                        # we are dealing with commands
412                                 @lparts = split /\./, $l;                  
413                                 next if $lparts[$#lparts] ne $suffix;        # only look for .$suffix files
414                                 if ($p eq substr($l, 0, length $p)) {
415                                         pop @lparts; #  remove the suffix
416                                         $l = join '.', @lparts;
417                                         #                 chop $dirfn;               # remove trailing /
418                                         $dirfn = "" unless $dirfn;
419                                         $cmd_cache{"$short_cmd"} = join(',', ($path, "$dirfn$l")); # cache it
420                                         dbg('command', "got path: $path cmd: $dirfn$l\n");
421                                         return ($path, "$dirfn$l"); 
422                                 }
423                         }
424                 }
425         }
426         return ();  
427 }  
428
429 # clear the command name cache
430 sub clear_cmd_cache
431 {
432         %cmd_cache = ();
433 }
434
435 #
436 # the persistant execution of things from the command directories
437 #
438 #
439 # This allows perl programs to call functions dynamically
440
441 # This has been nicked directly from the perlembed pages
442 #
443
444 #require Devel::Symdump;  
445
446 sub valid_package_name {
447         my($string) = @_;
448         $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
449         
450         #second pass only for words starting with a digit
451         $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
452         
453         #Dress it up as a real package name
454         $string =~ s/\//_/og;
455         return $string;
456 }
457
458 # find a cmd reference
459 # this is really for use in user written stubs
460 #
461 # use the result as a symbolic reference:-
462 #
463 # no strict 'refs';
464 # @out = &$r($self, $line);
465 #
466 sub find_cmd_ref
467 {
468         my $cmd = shift;
469         my $r;
470         
471         if ($cmd) {
472                 
473                 # first expand out the entry to a command
474                 my ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
475                 ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
476                 
477                 # make sure it is loaded
478                 $r = find_cmd_name($path, $fcmd);
479         }
480         return $r;
481 }
482
483
484 # this bit of magic finds a command in the offered directory
485 sub find_cmd_name {
486         my $path = shift;
487         my $cmdname = shift;
488         my $package = valid_package_name($cmdname);
489         my $filename = "$path/$cmdname.pl";
490         my $mtime = -M $filename;
491         
492         # return if we can't find it
493         $errstr = undef;
494         unless (defined $mtime) {
495                 $errstr = DXM::msg('e1');
496                 return undef;
497         }
498         
499         if(defined $Cache{$package}->{mtime} &&$Cache{$package}->{mtime} <= $mtime) {
500                 #we have compiled this subroutine already,
501                 #it has not been updated on disk, nothing left to do
502                 #print STDERR "already compiled $package->handler\n";
503                 ;
504         } else {
505
506                 my $sub = readfilestr($filename);
507                 unless ($sub) {
508                         $errstr = "Syserr: can't open '$filename' $!";
509                         return undef;
510                 };
511                 
512                 #wrap the code into a subroutine inside our unique package
513                 my $eval = qq( sub { $sub } );
514                 
515                 if (isdbg('eval')) {
516                         my @list = split /\n/, $eval;
517                         my $line;
518                         for (@list) {
519                                 dbg('eval', $_, "\n");
520                         }
521                 }
522                 
523                 $Cache{$package} = {mtime => $mtime, eval => $eval };
524         }
525
526         return $package;
527 }
528
529 1;
530 __END__