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