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