commit 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                                 $self->send_talks($_,  $self->msg('talkend'));
184                         }
185                         $self->state('prompt');
186                         delete $self->{talklist};
187                 } elsif ($cmdline =~ m(^/\w+)) {
188                         $cmdline =~ s(^/)();
189                         $self->send_ans(run_cmd($self, $cmdline));
190                         $self->send($self->talk_prompt);
191                 } elsif ($self->{talklist} && @{$self->{talklist}}) {
192                         # send what has been said to whoever is in this person's talk list
193                         for (@{$self->{talklist}}) {
194                                 $self->send_talks($_, $cmdline);
195                         }
196                         $self->send($self->talk_prompt) if $self->{state} eq 'talk';
197                 } else {
198                         # for safety
199                         $self->state('prompt');
200                 }
201         } else {
202                 $self->send_ans(run_cmd($self, $cmdline));
203         } 
204         
205         # send a prompt only if we are in a prompt state
206         $self->prompt() if $self->{state} =~ /^prompt/o;
207 }
208
209 # send out the talk messages taking into account vias and connectivity
210 sub send_talks
211 {
212         my ($self, $ent, $line) = @_;
213         
214         my ($to, $via) = $ent =~ /(\S+)>(\S+)/;
215         $to = $ent unless $to;
216         my $call = $via ? $via : $to;
217         my $clref = DXCluster->get_exact($call);
218         my $dxchan = $clref->dxchan if $clref;
219         if ($dxchan) {
220                 $dxchan->talk($self->{call}, $to, $via, $line);
221         } else {
222                 $self->send($self->msg('disc2', $via ? $via : $to));
223                 my @l = grep { $_ ne $ent } @{$self->{talklist}};
224                 if (@l) {
225                         $self->{talklist} = \@l;
226                 } else {
227                         delete $self->{talklist};
228                         $self->state('prompt');
229                 }
230         }
231 }
232
233 sub talk_prompt
234 {
235         my $self = shift;
236         my @call;
237         for (@{$self->{talklist}}) {
238                 my ($to, $via) = /(\S+)>(\S+)/;
239                 $to = $_ unless $to;
240                 push @call, $to;
241         }
242         return $self->msg('talkprompt', join(',', @call));
243 }
244
245 #
246 # send a load of stuff to a command user with page prompting
247 # and stuff
248 #
249
250 sub send_ans
251 {
252         my $self = shift;
253         
254         if ($self->{pagelth} && @_ > $self->{pagelth}) {
255                 my $i;
256                 for ($i = $self->{pagelth}; $i-- > 0; ) {
257                         my $line = shift @_;
258                         $line =~ s/\s+$//o;     # why am having to do this? 
259                         $self->send($line);
260                 }
261                 $self->{pagedata} =  [ @_ ];
262                 $self->state('page');
263                 $self->send($self->msg('page', scalar @_));
264         } else {
265                 for (@_) {
266                         $self->send($_) if $_;
267                 }
268         } 
269 }
270
271 # this is the thing that runs the command, it is done like this for the 
272 # benefit of remote command execution
273 #
274
275 sub run_cmd
276 {
277         my $self = shift;
278         my $user = $self->{user};
279         my $call = $self->{call};
280         my $cmdline = shift;
281         my @ans;
282         
283         if ($self->{func}) {
284                 my $c = qq{ \@ans = $self->{func}(\$self, \$cmdline) };
285                 dbg('eval', "stored func cmd = $c\n");
286                 eval  $c;
287                 if ($@) {
288                         return ("Syserr: Eval err $errstr on stored func $self->{func}", $@);
289                 }
290         } else {
291
292                 return () if length $cmdline == 0;
293                 
294                 # strip out //
295                 $cmdline =~ s|//|/|og;
296                 
297                 # split the command line up into parts, the first part is the command
298                 my ($cmd, $args) = split /\s+/, $cmdline, 2;
299                 $args = "" unless $args;
300                 
301                 if ($cmd) {
302                         
303                         my ($path, $fcmd);
304                         
305                         dbg('command', "cmd: $cmd");
306                         
307                         # alias it if possible
308                         my $acmd = CmdAlias::get_cmd($cmd);
309                         if ($acmd) {
310                                 ($cmd, $args) = split /\s+/, "$acmd $args", 2;
311                                 $args = "" unless $args;
312                                 dbg('command', "aliased cmd: $cmd $args");
313                         }
314                         
315                         # first expand out the entry to a command
316                         ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
317                         ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
318
319                         if ($path && $cmd) {
320                                 dbg('command', "path: $cmd cmd: $fcmd");
321                         
322                                 my $package = find_cmd_name($path, $fcmd);
323                                 @ans = (0) if !$package ;
324                                 
325                                 if ($package) {
326                                         dbg('command', "package: $package");
327                                         my $c;
328                                         unless (exists $Cache{$package}->{'sub'}) {
329                                                 $c = eval $Cache{$package}->{'eval'};
330                                                 if ($@) {
331                                                         return DXDebug::shortmess($@);
332                                                 }
333                                                 $Cache{$package}->{'sub'} = $c;
334                                         }
335                                         $c = $Cache{$package}->{'sub'};
336                                         eval {
337                                                 @ans = &{$c}($self, $args);
338                                     };
339                                         
340                                         if ($@) {
341                                                 #cluck($@);
342                                                 return (DXDebug::shortmess($@));
343                                         };
344                                 }
345                         } else {
346                                 dbg('command', "cmd: $cmd not found");
347                                 return ($self->msg('e1'));
348                         }
349                 }
350         }
351         
352         shift @ans;
353         return (@ans);
354 }
355
356 #
357 # This is called from inside the main cluster processing loop and is used
358 # for despatching commands that are doing some long processing job
359 #
360 sub process
361 {
362         my $t = time;
363         my @dxchan = DXChannel->get_all();
364         my $dxchan;
365         
366         foreach $dxchan (@dxchan) {
367                 next if $dxchan->sort ne 'U';  
368                 
369                 # send a prompt if no activity out on this channel
370                 if ($t >= $dxchan->t + $main::user_interval) {
371                         $dxchan->prompt() if $dxchan->{state} =~ /^prompt/o;
372                         $dxchan->t($t);
373                 }
374         }
375 }
376
377 #
378 # finish up a user context
379 #
380 sub finish
381 {
382         my $self = shift;
383         my $conn = shift;
384         my $call = $self->call;
385
386         # I was the last node visited
387     $self->user->node($main::mycall);
388                 
389         # log out text
390         if ($conn && -e "$main::data/logout") {
391                 open(I, "$main::data/logout") or confess;
392                 my @in = <I>;
393                 close(I);
394                 $self->send_now('D', @in);
395                 sleep(1);
396         }
397
398         if ($call eq $main::myalias) { # unset the channel if it is us really
399                 my $node = DXNode->get($main::mycall);
400                 $node->{dxchan} = 0;
401         }
402         
403         # issue a pc17 to everybody interested
404         my $nchan = DXChannel->get($main::mycall);
405         my $pc17 = $nchan->pc17($self);
406         DXProt::broadcast_all_ak1a($pc17);
407
408         # send info to all logged in thingies
409         $self->tell_login('logoutu');
410
411         Log('DXCommand', "$call disconnected");
412         my $ref = DXCluster->get_exact($call);
413         $ref->del() if $ref;
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));
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__