1. Added talk mode so that I don't have to keep typing T <call> all the time.
[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                                 my $dxchan = DXChannel->get($via);
200                                 if ($dxchan && DXCluster->get_exact($to)) {
201                                         $dxchan->talk($self->{call}, $to, $via, $cmdline);
202                                 } else {
203                                         $self->send($self->msg('disc2', $via ? $via : $to));
204                                         my @l = grep { $_ ne $ent } @{$self->{talklist}};
205                                         if (@l) {
206                                                 $self->{talklist} = \@l;
207                                         } else {
208                                                 delete $self->{talklist};
209                                                 $self->state('prompt');
210                                         }
211                                 }
212                         }
213                         $self->send($self->talk_prompt) if $self->{state} eq 'talk';
214                 } else {
215                         # for safety
216                         $self->state('prompt');
217                 }
218         } else {
219                 $self->send_ans(run_cmd($self, $cmdline));
220         } 
221         
222         # send a prompt only if we are in a prompt state
223         $self->prompt() if $self->{state} =~ /^prompt/o;
224 }
225
226 sub talk_prompt
227 {
228         my $self = shift;
229         my @call;
230         for (@{$self->{talklist}}) {
231                 my ($to, $via) = /(\S+)>(\S+)/;
232                 push @call, $to;
233         }
234         return $self->msg('talkprompt', join(',', @call));
235 }
236
237 #
238 # send a load of stuff to a command user with page prompting
239 # and stuff
240 #
241
242 sub send_ans
243 {
244         my $self = shift;
245         
246         if ($self->{pagelth} && @_ > $self->{pagelth}) {
247                 my $i;
248                 for ($i = $self->{pagelth}; $i-- > 0; ) {
249                         my $line = shift @_;
250                         $line =~ s/\s+$//o;     # why am having to do this? 
251                         $self->send($line);
252                 }
253                 $self->{pagedata} =  \@_;
254                 $self->state('page');
255                 $self->send($self->msg('page', scalar @_));
256         } else {
257                 for (@_) {
258                         $self->send($_) if $_;
259                 }
260         } 
261 }
262
263 # this is the thing that runs the command, it is done like this for the 
264 # benefit of remote command execution
265 #
266
267 sub run_cmd
268 {
269         my $self = shift;
270         my $user = $self->{user};
271         my $call = $self->{call};
272         my $cmdline = shift;
273         my @ans;
274         
275         if ($self->{func}) {
276                 my $c = qq{ \@ans = $self->{func}(\$self, \$cmdline) };
277                 dbg('eval', "stored func cmd = $c\n");
278                 eval  $c;
279                 if ($@) {
280                         return ("Syserr: Eval err $errstr on stored func $self->{func}", $@);
281                 }
282         } else {
283
284                 return () if length $cmdline == 0;
285                 
286                 # strip out //
287                 $cmdline =~ s|//|/|og;
288                 
289                 # split the command line up into parts, the first part is the command
290                 my ($cmd, $args) = split /\s+/, $cmdline, 2;
291                 $args = "" unless $args;
292                 
293                 if ($cmd) {
294                         
295                         my ($path, $fcmd);
296                         
297                         dbg('command', "cmd: $cmd");
298                         
299                         # alias it if possible
300                         my $acmd = CmdAlias::get_cmd($cmd);
301                         if ($acmd) {
302                                 ($cmd, $args) = split /\s+/, "$acmd $args", 2;
303                                 $args = "" unless $args;
304                                 dbg('command', "aliased cmd: $cmd $args");
305                         }
306                         
307                         # first expand out the entry to a command
308                         ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
309                         ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
310
311                         if ($path && $cmd) {
312                                 dbg('command', "path: $cmd cmd: $fcmd");
313                         
314                                 my $package = find_cmd_name($path, $fcmd);
315                                 @ans = (0) if !$package ;
316                                 
317                                 if ($package) {
318                                         dbg('command', "package: $package");
319                                         my $c;
320                                         unless (exists $Cache{$package}->{'sub'}) {
321                                                 $c = eval $Cache{$package}->{'eval'};
322                                                 if ($@) {
323                                                         return DXDebug::shortmess($@);
324                                                 }
325                                                 $Cache{$package}->{'sub'} = $c;
326                                         }
327                                         $c = $Cache{$package}->{'sub'};
328                                         eval {
329                                                 @ans = &{$c}($self, $args);
330                                     };
331                                         
332                                         if ($@) {
333                                                 #cluck($@);
334                                                 return (DXDebug::shortmess($@));
335                                         };
336                                 }
337                         } else {
338                                 dbg('command', "cmd: $cmd not found");
339                                 return ($self->msg('e1'));
340                         }
341                 }
342         }
343         
344         shift @ans;
345         return (@ans);
346 }
347
348 #
349 # This is called from inside the main cluster processing loop and is used
350 # for despatching commands that are doing some long processing job
351 #
352 sub process
353 {
354         my $t = time;
355         my @dxchan = DXChannel->get_all();
356         my $dxchan;
357         
358         foreach $dxchan (@dxchan) {
359                 next if $dxchan->sort ne 'U';  
360                 
361                 # send a prompt if no activity out on this channel
362                 if ($t >= $dxchan->t + $main::user_interval) {
363                         $dxchan->prompt() if $dxchan->{state} =~ /^prompt/o;
364                         $dxchan->t($t);
365                 }
366         }
367 }
368
369 #
370 # finish up a user context
371 #
372 sub finish
373 {
374         my $self = shift;
375         my $conn = shift;
376         my $call = $self->call;
377
378         # I was the last node visited
379     $self->user->node($main::mycall);
380                 
381         # log out text
382         if ($conn && -e "$main::data/logout") {
383                 open(I, "$main::data/logout") or confess;
384                 my @in = <I>;
385                 close(I);
386                 $self->send_now('D', @in);
387                 sleep(1);
388         }
389
390         if ($call eq $main::myalias) { # unset the channel if it is us really
391                 my $node = DXNode->get($main::mycall);
392                 $node->{dxchan} = 0;
393         }
394         
395         # issue a pc17 to everybody interested
396         my $nchan = DXChannel->get($main::mycall);
397         my $pc17 = $nchan->pc17($self);
398         DXProt::broadcast_all_ak1a($pc17);
399
400         # send info to all logged in thingies
401         $self->tell_login('logoutu');
402
403         Log('DXCommand', "$call disconnected");
404         my $ref = DXCluster->get_exact($call);
405         $ref->del() if $ref;
406 }
407
408 #
409 # short cut to output a prompt
410 #
411
412 sub prompt
413 {
414         my $self = shift;
415         $self->send($self->msg($self->here ? 'pr' : 'pr2', $self->call));
416 }
417
418 # broadcast a message to all users [except those mentioned after buffer]
419 sub broadcast
420 {
421         my $pkg = shift;                        # ignored
422         my $s = shift;                          # the line to be rebroadcast
423         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
424         my @list = DXChannel->get_all(); # just in case we are called from some funny object
425         my ($dxchan, $except);
426         
427  L: foreach $dxchan (@list) {
428                 next if !$dxchan->sort eq 'U'; # only interested in user channels  
429                 foreach $except (@except) {
430                         next L if $except == $dxchan;   # ignore channels in the 'except' list
431                 }
432                 $dxchan->send($s);                      # send it
433         }
434 }
435
436 # gimme all the users
437 sub get_all
438 {
439         my @list = DXChannel->get_all();
440         my $ref;
441         my @out;
442         foreach $ref (@list) {
443                 push @out, $ref if $ref->sort eq 'U';
444         }
445         return @out;
446 }
447
448 # run a script for this user
449 sub run_script
450 {
451         my $self = shift;
452         my $silent = shift || 0;
453         
454 }
455
456 #
457 # search for the command in the cache of short->long form commands
458 #
459
460 sub search
461 {
462         my ($path, $short_cmd, $suffix) = @_;
463         my ($apath, $acmd);
464         
465         # commands are lower case
466         $short_cmd = lc $short_cmd;
467         dbg('command', "command: $path $short_cmd\n");
468
469         # do some checking for funny characters
470         return () if $short_cmd =~ /\/$/;
471
472         # return immediately if we have it
473         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
474         if ($apath && $acmd) {
475                 dbg('command', "cached $short_cmd = ($apath, $acmd)\n");
476                 return ($apath, $acmd);
477         }
478         
479         # if not guess
480         my @parts = split '/', $short_cmd;
481         my $dirfn;
482         my $curdir = $path;
483         my $p;
484         my $i;
485         my @lparts;
486         
487         for ($i = 0; $i < @parts; $i++) {
488                 my  $p = $parts[$i];
489                 opendir(D, $curdir) or confess "can't open $curdir $!";
490                 my @ls = readdir D;
491                 closedir D;
492                 my $l;
493                 foreach $l (sort @ls) {
494                         next if $l =~ /^\./;
495                         if ($i < $#parts) {             # we are dealing with directories
496                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
497                                         dbg('command', "got dir: $curdir/$l\n");
498                                         $dirfn .= "$l/";
499                                         $curdir .= "/$l";
500                                         last;
501                                 }
502                         } else {                        # we are dealing with commands
503                                 @lparts = split /\./, $l;                  
504                                 next if $lparts[$#lparts] ne $suffix;        # only look for .$suffix files
505                                 if ($p eq substr($l, 0, length $p)) {
506                                         pop @lparts; #  remove the suffix
507                                         $l = join '.', @lparts;
508                                         #                 chop $dirfn;               # remove trailing /
509                                         $dirfn = "" unless $dirfn;
510                                         $cmd_cache{"$short_cmd"} = join(',', ($path, "$dirfn$l")); # cache it
511                                         dbg('command', "got path: $path cmd: $dirfn$l\n");
512                                         return ($path, "$dirfn$l"); 
513                                 }
514                         }
515                 }
516         }
517         return ();  
518 }  
519
520 # clear the command name cache
521 sub clear_cmd_cache
522 {
523         %cmd_cache = ();
524 }
525
526 #
527 # the persistant execution of things from the command directories
528 #
529 #
530 # This allows perl programs to call functions dynamically
531
532 # This has been nicked directly from the perlembed pages
533 #
534
535 #require Devel::Symdump;  
536
537 sub valid_package_name {
538         my($string) = @_;
539         $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
540         
541         #second pass only for words starting with a digit
542         $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
543         
544         #Dress it up as a real package name
545         $string =~ s/\//_/og;
546         return $string;
547 }
548
549 # find a cmd reference
550 # this is really for use in user written stubs
551 #
552 # use the result as a symbolic reference:-
553 #
554 # no strict 'refs';
555 # @out = &$r($self, $line);
556 #
557 sub find_cmd_ref
558 {
559         my $cmd = shift;
560         my $r;
561         
562         if ($cmd) {
563                 
564                 # first expand out the entry to a command
565                 my ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
566                 ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
567                 
568                 # make sure it is loaded
569                 $r = find_cmd_name($path, $fcmd);
570         }
571         return $r;
572 }
573
574
575 # this bit of magic finds a command in the offered directory
576 sub find_cmd_name {
577         my $path = shift;
578         my $cmdname = shift;
579         my $package = valid_package_name($cmdname);
580         my $filename = "$path/$cmdname.pl";
581         my $mtime = -M $filename;
582         
583         # return if we can't find it
584         $errstr = undef;
585         unless (defined $mtime) {
586                 $errstr = DXM::msg('e1');
587                 return undef;
588         }
589         
590         if(defined $Cache{$package}->{mtime} &&$Cache{$package}->{mtime} <= $mtime) {
591                 #we have compiled this subroutine already,
592                 #it has not been updated on disk, nothing left to do
593                 #print STDERR "already compiled $package->handler\n";
594                 ;
595         } else {
596
597                 my $sub = readfilestr($filename);
598                 unless ($sub) {
599                         $errstr = "Syserr: can't open '$filename' $!";
600                         return undef;
601                 };
602                 
603                 #wrap the code into a subroutine inside our unique package
604                 my $eval = qq( sub { $sub } );
605                 
606                 if (isdbg('eval')) {
607                         my @list = split /\n/, $eval;
608                         my $line;
609                         for (@list) {
610                                 dbg('eval', $_, "\n");
611                         }
612                 }
613                 
614                 $Cache{$package} = {mtime => $mtime, 'eval' => $eval };
615         }
616
617         return $package;
618 }
619
620 # send a talk message here
621 sub talk
622 {
623         my ($self, $from, $to, $via, $line) = @_;
624         $line =~ s/\\5E/\^/g;
625         $self->send("$to de $from $line") if $self->{talk};
626         Log('talk', $to, $from, $main::mycall, $line);
627 }
628
629 # send an announce
630 sub announce
631 {
632
633 }
634
635 # send a dx spot
636 sub dx_spot
637 {
638         
639 }
640
641 1;
642 __END__