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