made the reaping code a tad more sophisticated (probably in the correct
[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         # I was the last node visited
394     $self->user->node($main::mycall);
395                 
396         # log out text
397         if ($conn && -e "$main::data/logout") {
398                 open(I, "$main::data/logout") or confess;
399                 my @in = <I>;
400                 close(I);
401                 $self->send_now('D', @in);
402                 sleep(1);
403         }
404
405 #       if ($call eq $main::myalias) { # unset the channel if it is us really
406 #               my $node = DXNode->get($main::mycall);
407 #               $node->{dxchan} = 0;
408 #       }
409         
410         # issue a pc17 to everybody interested
411         my $nchan = DXChannel->get($main::mycall);
412         my $pc17 = $nchan->pc17($self);
413         DXProt::broadcast_all_ak1a($pc17);
414
415         # send info to all logged in thingies
416         $self->tell_login('logoutu');
417
418         Log('DXCommand', "$call disconnected");
419         my $ref = DXCluster->get_exact($call);
420         $ref->del() if $ref;
421 }
422
423 #
424 # short cut to output a prompt
425 #
426
427 sub prompt
428 {
429         my $self = shift;
430         $self->send($self->msg($self->here ? 'pr' : 'pr2', $self->call, cldate($main::systime), ztime($main::systime)));
431 }
432
433 # broadcast a message to all users [except those mentioned after buffer]
434 sub broadcast
435 {
436         my $pkg = shift;                        # ignored
437         my $s = shift;                          # the line to be rebroadcast
438         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
439         my @list = DXChannel->get_all(); # just in case we are called from some funny object
440         my ($dxchan, $except);
441         
442  L: foreach $dxchan (@list) {
443                 next if !$dxchan->sort eq 'U'; # only interested in user channels  
444                 foreach $except (@except) {
445                         next L if $except == $dxchan;   # ignore channels in the 'except' list
446                 }
447                 $dxchan->send($s);                      # send it
448         }
449 }
450
451 # gimme all the users
452 sub get_all
453 {
454         my @list = DXChannel->get_all();
455         my $ref;
456         my @out;
457         foreach $ref (@list) {
458                 push @out, $ref if $ref->sort eq 'U';
459         }
460         return @out;
461 }
462
463 # run a script for this user
464 sub run_script
465 {
466         my $self = shift;
467         my $silent = shift || 0;
468         
469 }
470
471 #
472 # search for the command in the cache of short->long form commands
473 #
474
475 sub search
476 {
477         my ($path, $short_cmd, $suffix) = @_;
478         my ($apath, $acmd);
479         
480         # commands are lower case
481         $short_cmd = lc $short_cmd;
482         dbg('command', "command: $path $short_cmd\n");
483
484         # do some checking for funny characters
485         return () if $short_cmd =~ /\/$/;
486
487         # return immediately if we have it
488         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
489         if ($apath && $acmd) {
490                 dbg('command', "cached $short_cmd = ($apath, $acmd)\n");
491                 return ($apath, $acmd);
492         }
493         
494         # if not guess
495         my @parts = split '/', $short_cmd;
496         my $dirfn;
497         my $curdir = $path;
498         my $p;
499         my $i;
500         my @lparts;
501         
502         for ($i = 0; $i < @parts; $i++) {
503                 my  $p = $parts[$i];
504                 opendir(D, $curdir) or confess "can't open $curdir $!";
505                 my @ls = readdir D;
506                 closedir D;
507                 my $l;
508                 foreach $l (sort @ls) {
509                         next if $l =~ /^\./;
510                         if ($i < $#parts) {             # we are dealing with directories
511                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
512                                         dbg('command', "got dir: $curdir/$l\n");
513                                         $dirfn .= "$l/";
514                                         $curdir .= "/$l";
515                                         last;
516                                 }
517                         } else {                        # we are dealing with commands
518                                 @lparts = split /\./, $l;                  
519                                 next if $lparts[$#lparts] ne $suffix;        # only look for .$suffix files
520                                 if ($p eq substr($l, 0, length $p)) {
521                                         pop @lparts; #  remove the suffix
522                                         $l = join '.', @lparts;
523                                         #                 chop $dirfn;               # remove trailing /
524                                         $dirfn = "" unless $dirfn;
525                                         $cmd_cache{"$short_cmd"} = join(',', ($path, "$dirfn$l")); # cache it
526                                         dbg('command', "got path: $path cmd: $dirfn$l\n");
527                                         return ($path, "$dirfn$l"); 
528                                 }
529                         }
530                 }
531         }
532         return ();  
533 }  
534
535 # clear the command name cache
536 sub clear_cmd_cache
537 {
538         %cmd_cache = ();
539 }
540
541 #
542 # the persistant execution of things from the command directories
543 #
544 #
545 # This allows perl programs to call functions dynamically
546
547 # This has been nicked directly from the perlembed pages
548 #
549
550 #require Devel::Symdump;  
551
552 sub valid_package_name {
553         my($string) = @_;
554         $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
555         
556         #second pass only for words starting with a digit
557         $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
558         
559         #Dress it up as a real package name
560         $string =~ s/\//_/og;
561         return $string;
562 }
563
564 # find a cmd reference
565 # this is really for use in user written stubs
566 #
567 # use the result as a symbolic reference:-
568 #
569 # no strict 'refs';
570 # @out = &$r($self, $line);
571 #
572 sub find_cmd_ref
573 {
574         my $cmd = shift;
575         my $r;
576         
577         if ($cmd) {
578                 
579                 # first expand out the entry to a command
580                 my ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
581                 ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
582                 
583                 # make sure it is loaded
584                 $r = find_cmd_name($path, $fcmd);
585         }
586         return $r;
587 }
588
589
590 # this bit of magic finds a command in the offered directory
591 sub find_cmd_name {
592         my $path = shift;
593         my $cmdname = shift;
594         my $package = valid_package_name($cmdname);
595         my $filename = "$path/$cmdname.pl";
596         my $mtime = -M $filename;
597         
598         # return if we can't find it
599         $errstr = undef;
600         unless (defined $mtime) {
601                 $errstr = DXM::msg('e1');
602                 return undef;
603         }
604         
605         if(defined $Cache{$package}->{mtime} &&$Cache{$package}->{mtime} <= $mtime) {
606                 #we have compiled this subroutine already,
607                 #it has not been updated on disk, nothing left to do
608                 #print STDERR "already compiled $package->handler\n";
609                 ;
610         } else {
611
612                 my $sub = readfilestr($filename);
613                 unless ($sub) {
614                         $errstr = "Syserr: can't open '$filename' $!";
615                         return undef;
616                 };
617                 
618                 #wrap the code into a subroutine inside our unique package
619                 my $eval = qq( sub { $sub } );
620                 
621                 if (isdbg('eval')) {
622                         my @list = split /\n/, $eval;
623                         my $line;
624                         for (@list) {
625                                 dbg('eval', $_, "\n");
626                         }
627                 }
628                 
629                 $Cache{$package} = {mtime => $mtime, 'eval' => $eval };
630         }
631
632         return $package;
633 }
634
635 # send a talk message here
636 sub talk
637 {
638         my ($self, $from, $to, $via, $line) = @_;
639         $line =~ s/\\5E/\^/g;
640         $self->send("$to de $from: $line") if $self->{talk};
641         Log('talk', $to, $from, $main::mycall, $line);
642 }
643
644 # send an announce
645 sub announce
646 {
647
648 }
649
650 # send a dx spot
651 sub dx_spot
652 {
653         
654 }
655
656 1;
657 __END__