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