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