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