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