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