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