added loginfo stuff
[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 Carp;
28 use Minimuf;
29 use DXDb;
30 use Sun;
31
32 use strict;
33 use vars qw(%Cache %cmd_cache $errstr %aliases $scriptbase);
34
35 %Cache = ();                                    # cache of dynamically loaded routine's mod times
36 %cmd_cache = ();                                # cache of short names
37 $errstr = ();                                   # error string from eval
38 %aliases = ();                                  # aliases for (parts of) commands
39 $scriptbase = "$main::root/scripts"; # the place where all users start scripts go
40
41 #
42 # obtain a new connection this is derived from dxchannel
43 #
44
45 sub new 
46 {
47         my $self = DXChannel::alloc(@_);
48         $self->{'sort'} = 'U';          # in absence of how to find out what sort of an object I am
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;
68         $self->{lang} = $user->lang;
69         $self->{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->{talk} = $user->wanttalk;
78         $self->{wx} = $user->wantwx;
79         $self->{dx} = $user->wantdx;
80         $self->{logininfo} = $user->wantlogininfo;
81         $self->{here} = 1;
82         
83         # add yourself to the database
84         my $node = DXNode->get($main::mycall) or die "$main::mycall not allocated in DXNode database";
85         my $cuser = DXNodeuser->new($self, $node, $call, 0, 1);
86         $node->dxchan($self) if $call eq $main::myalias; # send all output for mycall to myalias
87         
88         # issue a pc16 to everybody interested
89         my $nchan = DXChannel->get($main::mycall);
90         my @pc16 = DXProt::pc16($nchan, $cuser);
91         for (@pc16) {
92                 DXProt::broadcast_all_ak1a($_);
93         }
94         Log('DXCommand', "$call connected");
95
96         # send prompts and things
97         my $info = DXCluster::cluster();
98         $self->send("Cluster:$info");
99         $self->send($self->msg('namee1')) if !$user->name;
100         $self->send($self->msg('qthe1')) if !$user->qth;
101         $self->send($self->msg('qll')) if !$user->qra || (!$user->lat && !$user->long);
102         $self->send($self->msg('hnodee1')) if !$user->qth;
103         $self->send($self->msg('m9')) if DXMsg::for_me($call);
104         $self->send($self->msg('pr', $call));
105         
106         $self->tell_login('loginu');
107         
108 }
109
110 #
111 # This is the normal command prompt driver
112 #
113
114 sub normal
115 {
116         my $self = shift;
117         my $cmdline = shift;
118         my @ans;
119         
120         # remove leading and trailing spaces
121         $cmdline =~ s/^\s*(.*)\s*$/$1/;
122         
123         if ($self->{state} eq 'page') {
124                 my $i = $self->{pagelth};
125                 my $ref = $self->{pagedata};
126                 my $tot = @$ref;
127                 
128                 # abort if we get a line starting in with a
129                 if ($cmdline =~ /^a/io) {
130                         undef $ref;
131                         $i = 0;
132                 }
133         
134                 # send a tranche of data
135                 while ($i-- > 0 && @$ref) {
136                         my $line = shift @$ref;
137                         $line =~ s/\s+$//o;     # why am having to do this? 
138                         $self->send($line);
139                 }
140                 
141                 # reset state if none or else chuck out an intermediate prompt
142                 if ($ref && @$ref) {
143                         $tot -= $self->{pagelth};
144                         $self->send($self->msg('page', $tot));
145                 } else {
146                         $self->state('prompt');
147                 }
148         } elsif ($self->{state} eq 'sysop') {
149                 my $passwd = $self->{user}->passwd;
150                 my @pw = split / */, $passwd;
151                 if ($passwd) {
152                         my @l = @{$self->{passwd}};
153                         my $str = "$pw[$l[0]].*$pw[$l[1]].*$pw[$l[2]].*$pw[$l[3]].*$pw[$l[4]]";
154                         if ($cmdline =~ /$str/) {
155                                 $self->{priv} = $self->{user}->priv;
156                         } else {
157                                 $self->send($self->msg('sorry'));
158                         }
159                 } else {
160                         $self->send($self->msg('sorry'));
161                 }
162                 delete $self->{passwd};
163                 $self->state('prompt');
164         } else {
165                 @ans = run_cmd($self, $cmdline);           # if length $cmdline;
166                 
167                 if ($self->{pagelth} && @ans > $self->{pagelth}) {
168                         my $i;
169                         for ($i = $self->{pagelth}; $i-- > 0; ) {
170                                 my $line = shift @ans;
171                                 $line =~ s/\s+$//o;     # why am having to do this? 
172                                 $self->send($line);
173                         }
174                         $self->{pagedata} =  \@ans;
175                         $self->state('page');
176                         $self->send($self->msg('page', scalar @ans));
177                 } else {
178                         for (@ans) {
179                                 $self->send($_) if $_;
180                         }
181                 } 
182         } 
183         
184         # send a prompt only if we are in a prompt state
185         $self->prompt() if $self->{state} =~ /^prompt/o;
186 }
187
188
189 # this is the thing that runs the command, it is done like this for the 
190 # benefit of remote command execution
191 #
192
193 sub run_cmd
194 {
195         my $self = shift;
196         my $user = $self->{user};
197         my $call = $self->{call};
198         my $cmdline = shift;
199         my @ans;
200         
201         if ($self->{func}) {
202                 my $c = qq{ \@ans = $self->{func}(\$self, \$cmdline) };
203                 dbg('eval', "stored func cmd = $c\n");
204                 eval  $c;
205                 if ($@) {
206                         return ("Syserr: Eval err $errstr on stored func $self->{func}", $@);
207                 }
208         } else {
209
210                 return () if length $cmdline == 0;
211                 
212                 # strip out //
213                 $cmdline =~ s|//|/|og;
214                 
215                 # split the command line up into parts, the first part is the command
216                 my ($cmd, $args) = split /\s+/, $cmdline, 2;
217                 $args = "" unless $args;
218                 
219                 if ($cmd) {
220                         
221                         my ($path, $fcmd);
222                         
223                         dbg('command', "cmd: $cmd");
224                         
225                         # alias it if possible
226                         my $acmd = CmdAlias::get_cmd($cmd);
227                         if ($acmd) {
228                                 ($cmd, $args) = split /\s+/, "$acmd $args", 2;
229                                 $args = "" unless $args;
230                                 dbg('command', "aliased cmd: $cmd $args");
231                         }
232                         
233                         # first expand out the entry to a command
234                         ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
235                         ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
236
237                         if ($path && $cmd) {
238                                 dbg('command', "path: $cmd cmd: $fcmd");
239                         
240                                 my $package = find_cmd_name($path, $fcmd);
241                                 @ans = (0) if !$package ;
242                                 
243                                 if ($package) {
244                                         dbg('command', "package: $package");
245                                         my $c;
246                                         unless (exists $Cache{$package}->{'sub'}) {
247                                                 $c = eval $Cache{$package}->{'eval'};
248                                                 if ($@) {
249                                                         return ("Syserr: Syntax error in $package", $@);
250                                                 }
251                                                 $Cache{$package}->{'sub'} = $c;
252                                         }
253                                         $c = $Cache{$package}->{'sub'};
254                                         eval {
255                                                 @ans = &{$c}($self, $args);
256                                     };
257                                         
258                                         return ($@) if $@;
259                                 }
260                         } else {
261                                 dbg('command', "cmd: $cmd not found");
262                                 return ($self->msg('e1'));
263                         }
264                 }
265         }
266         
267         shift @ans;
268         return (@ans);
269 }
270
271 #
272 # This is called from inside the main cluster processing loop and is used
273 # for despatching commands that are doing some long processing job
274 #
275 sub process
276 {
277         my $t = time;
278         my @dxchan = DXChannel->get_all();
279         my $dxchan;
280         
281         foreach $dxchan (@dxchan) {
282                 next if $dxchan->sort ne 'U';  
283                 
284                 # send a prompt if no activity out on this channel
285                 if ($t >= $dxchan->t + $main::user_interval) {
286                         $dxchan->prompt() if $dxchan->{state} =~ /^prompt/o;
287                         $dxchan->t($t);
288                 }
289         }
290 }
291
292 #
293 # finish up a user context
294 #
295 sub finish
296 {
297         my $self = shift;
298         my $call = $self->call;
299
300         # log out text
301         if (-e "$main::data/logout") {
302                 open(I, "$main::data/logout") or confess;
303                 my @in = <I>;
304                 close(I);
305                 $self->send_now('D', @in);
306                 sleep(1);
307         }
308
309         if ($call eq $main::myalias) { # unset the channel if it is us really
310                 my $node = DXNode->get($main::mycall);
311                 $node->{dxchan} = 0;
312         }
313         
314         # issue a pc17 to everybody interested
315         my $nchan = DXChannel->get($main::mycall);
316         my $pc17 = $nchan->pc17($self);
317         DXProt::broadcast_all_ak1a($pc17);
318
319         # send info to all logged in thingies
320         $self->tell_login('logoutu');
321
322         Log('DXCommand', "$call disconnected");
323         my $ref = DXCluster->get_exact($call);
324         $ref->del() if $ref;
325 }
326
327 #
328 # short cut to output a prompt
329 #
330
331 sub prompt
332 {
333         my $self = shift;
334         $self->send($self->msg($self->here ? 'pr' : 'pr2', $self->call));
335 }
336
337 # broadcast a message to all users [except those mentioned after buffer]
338 sub broadcast
339 {
340         my $pkg = shift;                        # ignored
341         my $s = shift;                          # the line to be rebroadcast
342         my @except = @_;                        # to all channels EXCEPT these (dxchannel refs)
343         my @list = DXChannel->get_all(); # just in case we are called from some funny object
344         my ($dxchan, $except);
345         
346  L: foreach $dxchan (@list) {
347                 next if !$dxchan->sort eq 'U'; # only interested in user channels  
348                 foreach $except (@except) {
349                         next L if $except == $dxchan;   # ignore channels in the 'except' list
350                 }
351                 $dxchan->send($s);                      # send it
352         }
353 }
354
355 # gimme all the users
356 sub get_all
357 {
358         my @list = DXChannel->get_all();
359         my $ref;
360         my @out;
361         foreach $ref (@list) {
362                 push @out, $ref if $ref->sort eq 'U';
363         }
364         return @out;
365 }
366
367 # run a script for this user
368 sub run_script
369 {
370         my $self = shift;
371         my $silent = shift || 0;
372         
373 }
374
375 #
376 # search for the command in the cache of short->long form commands
377 #
378
379 sub search
380 {
381         my ($path, $short_cmd, $suffix) = @_;
382         my ($apath, $acmd);
383         
384         # commands are lower case
385         $short_cmd = lc $short_cmd;
386         dbg('command', "command: $path $short_cmd\n");
387
388         # do some checking for funny characters
389         return () if $short_cmd =~ /\/$/;
390
391         # return immediately if we have it
392         ($apath, $acmd) = split ',', $cmd_cache{$short_cmd} if $cmd_cache{$short_cmd};
393         if ($apath && $acmd) {
394                 dbg('command', "cached $short_cmd = ($apath, $acmd)\n");
395                 return ($apath, $acmd);
396         }
397         
398         # if not guess
399         my @parts = split '/', $short_cmd;
400         my $dirfn;
401         my $curdir = $path;
402         my $p;
403         my $i;
404         my @lparts;
405         
406         for ($i = 0; $i < @parts; $i++) {
407                 my  $p = $parts[$i];
408                 opendir(D, $curdir) or confess "can't open $curdir $!";
409                 my @ls = readdir D;
410                 closedir D;
411                 my $l;
412                 foreach $l (sort @ls) {
413                         next if $l =~ /^\./;
414                         if ($i < $#parts) {             # we are dealing with directories
415                                 if ((-d "$curdir/$l") && $p eq substr($l, 0, length $p)) {
416                                         dbg('command', "got dir: $curdir/$l\n");
417                                         $dirfn .= "$l/";
418                                         $curdir .= "/$l";
419                                         last;
420                                 }
421                         } else {                        # we are dealing with commands
422                                 @lparts = split /\./, $l;                  
423                                 next if $lparts[$#lparts] ne $suffix;        # only look for .$suffix files
424                                 if ($p eq substr($l, 0, length $p)) {
425                                         pop @lparts; #  remove the suffix
426                                         $l = join '.', @lparts;
427                                         #                 chop $dirfn;               # remove trailing /
428                                         $dirfn = "" unless $dirfn;
429                                         $cmd_cache{"$short_cmd"} = join(',', ($path, "$dirfn$l")); # cache it
430                                         dbg('command', "got path: $path cmd: $dirfn$l\n");
431                                         return ($path, "$dirfn$l"); 
432                                 }
433                         }
434                 }
435         }
436         return ();  
437 }  
438
439 # clear the command name cache
440 sub clear_cmd_cache
441 {
442         %cmd_cache = ();
443 }
444
445 #
446 # the persistant execution of things from the command directories
447 #
448 #
449 # This allows perl programs to call functions dynamically
450
451 # This has been nicked directly from the perlembed pages
452 #
453
454 #require Devel::Symdump;  
455
456 sub valid_package_name {
457         my($string) = @_;
458         $string =~ s/([^A-Za-z0-9\/])/sprintf("_%2x",unpack("C",$1))/eg;
459         
460         #second pass only for words starting with a digit
461         $string =~ s|/(\d)|sprintf("/_%2x",unpack("C",$1))|eg;
462         
463         #Dress it up as a real package name
464         $string =~ s/\//_/og;
465         return $string;
466 }
467
468 # find a cmd reference
469 # this is really for use in user written stubs
470 #
471 # use the result as a symbolic reference:-
472 #
473 # no strict 'refs';
474 # @out = &$r($self, $line);
475 #
476 sub find_cmd_ref
477 {
478         my $cmd = shift;
479         my $r;
480         
481         if ($cmd) {
482                 
483                 # first expand out the entry to a command
484                 my ($path, $fcmd) = search($main::localcmd, $cmd, "pl");
485                 ($path, $fcmd) = search($main::cmd, $cmd, "pl") if !$path || !$fcmd;
486                 
487                 # make sure it is loaded
488                 $r = find_cmd_name($path, $fcmd);
489         }
490         return $r;
491 }
492
493
494 # this bit of magic finds a command in the offered directory
495 sub find_cmd_name {
496         my $path = shift;
497         my $cmdname = shift;
498         my $package = valid_package_name($cmdname);
499         my $filename = "$path/$cmdname.pl";
500         my $mtime = -M $filename;
501         
502         # return if we can't find it
503         $errstr = undef;
504         unless (defined $mtime) {
505                 $errstr = DXM::msg('e1');
506                 return undef;
507         }
508         
509         if(defined $Cache{$package}->{mtime} &&$Cache{$package}->{mtime} <= $mtime) {
510                 #we have compiled this subroutine already,
511                 #it has not been updated on disk, nothing left to do
512                 #print STDERR "already compiled $package->handler\n";
513                 ;
514         } else {
515
516                 my $sub = readfilestr($filename);
517                 unless ($sub) {
518                         $errstr = "Syserr: can't open '$filename' $!";
519                         return undef;
520                 };
521                 
522                 #wrap the code into a subroutine inside our unique package
523                 my $eval = qq( sub { $sub } );
524                 
525                 if (isdbg('eval')) {
526                         my @list = split /\n/, $eval;
527                         my $line;
528                         for (@list) {
529                                 dbg('eval', $_, "\n");
530                         }
531                 }
532                 
533                 $Cache{$package} = {mtime => $mtime, 'eval' => $eval };
534         }
535
536         return $package;
537 }
538
539 1;
540 __END__