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