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