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