removed unwanted pc21 for isolated nodes
[spider.git] / perl / client.pl
1 #!/usr/bin/perl -w
2 #
3 # A thing that implements dxcluster 'protocol'
4 #
5 # This is a perl module/program that sits on the end of a dxcluster
6 # 'protocol' connection and deals with anything that might come along.
7 #
8 # this program is called by ax25d or inetd and gets raw ax25 text on its input
9 # It can also be launched into the ether by the cluster program itself for outgoing
10 # connections
11 #
12 # Calling syntax is:-
13 #
14 # client.pl [callsign] [telnet|ax25|local] [[connect] [program name and args ...]]
15 #
16 # if the callsign isn't given then the sysop callsign in DXVars.pm is assumed
17 #
18 # if there is no connection type then 'local' is assumed
19 #
20 # if there is a 'connect' keyword then it will try to launch the following program
21 # and any arguments and connect the stdin & stdout of both the program and the 
22 # client together.
23 #
24 # Copyright (c) 1998 Dirk Koopman G1TLH
25 #
26 # $Id$
27
28
29 require 5.004;
30
31 # search local then perl directories
32 BEGIN {
33         # root of directory tree for this system
34         $root = "/spider"; 
35         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
36         
37         unshift @INC, "$root/perl";     # this IS the right way round!
38         unshift @INC, "$root/local";
39 }
40
41 use Msg;
42 use DXVars;
43 use DXDebug;
44 use IO::File;
45 use IO::Socket;
46 use IPC::Open2;
47 use Net::Telnet qw(TELOPT_ECHO);
48 use Carp qw{cluck};
49
50 # cease communications
51 sub cease
52 {
53         my $sendz = shift;
54         if ($conn && $sendz) {
55                 $conn->send_now("Z$call|bye...\n");
56         }
57         $stdout->flush if $stdout;
58         if ($pid) {
59                 dbg('connect', "killing $pid");
60                 kill(9, $pid);
61         }
62         dbgclose();
63 #       $SIG{__WARN__} = sub {my $a = shift; cluck($a); };
64         sleep(1);
65         exit(0);        
66 }
67
68 # terminate program from signal
69 sub sig_term
70 {
71         cease(1);
72 }
73
74 # terminate a child
75 sub sig_chld
76 {
77         $SIG{CHLD} = \&sig_chld;
78         $waitedpid = wait;
79         dbg('connect', "caught $pid");
80 }
81
82
83 sub setmode
84 {
85         if ($mode == 1) {
86                 $mynl = "\r";
87         } else {
88                 $mynl = "\n";
89         }
90         $/ = $mynl;
91 }
92
93 # handle incoming messages
94 sub rec_socket
95 {
96         my ($con, $msg, $err) = @_;
97         if (defined $err && $err) {
98                 cease(1);
99         }
100         if (defined $msg) {
101                 my ($sort, $call, $line) = $msg =~ /^(\w)(\S+)\|(.*)$/;
102                 
103                 if ($sort eq 'D') {
104                         my $snl = $mynl;
105                         my $newsavenl = "";
106                         $snl = "" if $mode == 0;
107                         if ($mode == 2 && $line =~ />$/) {
108                                 $newsavenl = $snl;
109                                 $snl = ' ';
110                         }
111                         $line =~ s/\n/\r/og if $mode == 1;
112                         #my $p = qq($line$snl);
113                         if ($buffered) {
114                                 if (length $outqueue >= $client_buffer_lth) {
115                                         print $stdout $outqueue;
116                                         $outqueue = "";
117                                 }
118                                 $outqueue .= "$savenl$line$snl";
119                                 $lasttime = time;
120                         } else {
121                                 print $stdout $savenl, $line, $snl;;
122                         }
123                         $savenl = $newsavenl;
124                 } elsif ($sort eq 'M') {
125                         $mode = $line;          # set new mode from cluster
126                         setmode();
127                 } elsif ($sort eq 'E') {
128                         if ($sort eq 'telnet') {
129                                 $mode = $line;          # set echo mode from cluster
130                                 my $term = POSIX::Termios->new;
131                                 $term->getattr(fileno($sock));
132                                 $term->setiflag( 0 );
133                                 $term->setoflag( 0 );
134                                 $term->setattr(fileno($sock), &POSIX::TCSANOW );
135                         }
136                 } elsif ($sort eq 'I') {
137                         ;                       # ignore echoed I frames
138                 } elsif ($sort eq 'B') {
139                         if ($buffered && $outqueue) {
140                                 print $stdout $outqueue;
141                                 $outqueue = "";
142                         }
143                         $buffered = $line;      # set buffered or unbuffered
144                 } elsif ($sort eq 'Z') { # end, disconnect, go, away .....
145                         cease(0);
146                 }         
147         }
148         $lasttime = time; 
149 }
150
151 sub rec_stdin
152 {
153         my ($fh) = @_;
154         my $buf;
155         my @lines;
156         my $r;
157         my $first;
158         my $dangle = 0;
159         
160         $r = sysread($fh, $buf, 1024);
161         #  my $prbuf;
162         #  $prbuf = $buf;
163         #  $prbuf =~ s/\r/\\r/;
164         #  $prbuf =~ s/\n/\\n/;
165         #  print "sys: $r ($prbuf)\n";
166         if (!defined $r || $r == 0) {
167                 cease(1);
168         } elsif ($r > 0) {
169                 if ($mode) {
170                         $buf =~ s/\r/\n/og if $mode == 1;
171                         $buf =~ s/\r\n/\n/og if $mode == 2;
172                         $dangle = !($buf =~ /\n$/);
173                         if ($buf eq "\n") {
174                                 @lines = (" ");
175                         } else {
176                                 @lines = split /\n/, $buf;
177                         }
178                         if ($dangle) {          # pull off any dangly bits
179                                 $buf = pop @lines;
180                         } else {
181                                 $buf = "";
182                         }
183                         $first = shift @lines;
184                         unshift @lines, ($lastbit . $first) if ($first);
185                         foreach $first (@lines) {
186                                 #                 print "send_now $call $first\n";
187                                 $conn->send_later("I$call|$first");
188                         }
189                         $lastbit = $buf;
190                         $savenl = "";           # reset savenl 'cos we will have done a newline on input
191                 } else {
192                         $conn->send_later("I$call|$buf");
193                 }
194         } 
195         $lasttime = time;
196 }
197
198 sub optioncb
199 {
200 }
201
202 sub doconnect
203 {
204         my ($sort, $line) = @_;
205         dbg('connect', "CONNECT sort: $sort command: $line");
206         if ($sort eq 'telnet') {
207                 # this is a straight network connect
208                 my ($host, $port) = split /\s+/, $line;
209                 $port = 23 if !$port;
210                 
211 #               if ($port == 23) {
212                         $sock = new Net::Telnet (Timeout => $timeout, Port => $port);
213                         $sock->option_callback(\&optioncb);
214                         $sock->output_record_separator('');
215                         $sock->option_log('option_log');
216                         $sock->dump_log('dump');
217                         $sock->option_accept(Wont => TELOPT_ECHO);
218                         $sock->open($host) or die "Can't connect to $host port $port $!";
219 #               } else {
220 #                       $sock = IO::Socket::INET->new(PeerAddr => "$host:$port", Proto => 'tcp')
221 #                               or die "Can't connect to $host port $port $!";
222 #               }
223         } elsif ($sort eq 'ax25' || $sort eq 'prog') {
224                 my @args = split /\s+/, $line;
225                 $rfh = new IO::File;
226                 $wfh = new IO::File;
227                 $pid = open2($rfh, $wfh, "$line") or die "can't do $line $!";
228                 dbg('connect', "got pid $pid");
229                 $wfh->autoflush(1);
230         } else {
231                 die "invalid type of connection ($sort)";
232         }
233         $csort = $sort;
234 }
235
236 sub doabort
237 {
238         my $string = shift;
239         dbg('connect', "abort $string");
240         $abort = $string;
241 }
242
243 sub dotimeout
244 {
245         my $val = shift;
246         dbg('connect', "timeout set to $val");
247         $timeout = $val;
248 }
249
250 sub dochat
251 {
252         my ($expect, $send) = @_;
253         dbg('connect', "CHAT \"$expect\" -> \"$send\"");
254     my $line;
255         
256         alarm($timeout);
257         
258     if ($expect) {
259                 for (;;) {
260                         if ($csort eq 'telnet') {
261                                 $line = $sock->get();
262                                 $line =~ s/\r\n/\n/og;
263                                 chomp;
264                         } elsif ($csort eq 'ax25' || $csort eq 'prog') {
265                                 local $/ = "\r";
266                                 $line = <$rfh>;
267                                 $line =~ s/\r//og;
268                         }
269                         dbg('connect', "received \"$line\"");
270                         if ($abort && $line =~ /$abort/i) {
271                                 dbg('connect', "aborted on /$abort/");
272                                 cease(11);
273                         }
274                         last if $line =~ /$expect/i;
275                 }
276         }
277         if ($send) {
278                 if ($csort eq 'telnet') {
279                         $sock->print("$send\n");
280                 } elsif ($csort eq 'ax25') {
281                         local $\ = "\r";
282                         $wfh->print("$send");
283                 }
284                 dbg('connect', "sent \"$send\"");
285         }
286 }
287
288 sub timeout
289 {
290         dbg('connect', "timed out after $timeout seconds");
291         cease(0);
292 }
293
294
295 #
296 # initialisation
297 #
298
299 $mode = 2;                      # 1 - \n = \r as EOL, 2 - \n = \n, 0 - transparent
300 $call = "";                     # the callsign being used
301 $conn = 0;                      # the connection object for the cluster
302 $lastbit = "";                  # the last bit of an incomplete input line
303 $mynl = "\n";                   # standard terminator
304 $lasttime = time;               # lasttime something happened on the interface
305 $outqueue = "";                 # the output queue 
306 $client_buffer_lth = 200;       # how many characters are buffered up on outqueue
307 $buffered = 1;                  # buffer output
308 $savenl = "";                   # an NL that has been saved from last time
309 $timeout = 60;                  # default timeout for connects
310 $abort = "";                    # the current abort string
311 $cpath = "$root/connect";               # the basic connect directory
312
313 $pid = 0;                       # the pid of the child program
314 $csort = "";                    # the connection type
315 $sock = 0;                      # connection socket
316
317 $stdin = *STDIN;
318 $stdout = *STDOUT;
319 $rfh = 0;
320 $wfh = 0;
321
322 $waitedpid = 0;
323
324 #
325 # deal with args
326 #
327
328 $call = uc shift @ARGV if @ARGV;
329 $call = uc $myalias if !$call;
330 $connsort = lc shift @ARGV if @ARGV;
331 $connsort = 'local' if !$connsort;
332
333 $loginreq = $call eq 'LOGIN';
334
335 # we will do this again later 'cos things may have changed
336 $mode = ($connsort eq 'ax25') ? 1 : 2;
337 setmode();
338
339 if ($call eq $mycall) {
340         print $stdout "You cannot connect as your cluster callsign ($mycall)", $nl;
341         cease(0);
342 }
343
344 $stdout->autoflush(1);
345
346 $SIG{'INT'} = \&sig_term;
347 $SIG{'TERM'} = \&sig_term;
348 $SIG{'HUP'} = 'IGNORE';
349 $SIG{'CHLD'} = \&sig_chld;
350 $SIG{'ALRM'} = \&timeout;
351
352 dbgadd('connect');
353
354 # do we need to do a login and password job?
355 if ($loginreq) {
356         my $user;
357         my $s;
358
359         if (-e "$data/issue") {
360                 open(I, "$data/issue") or die;
361                 local $/ = undef;
362                 $issue = <I>;
363                 close(I);
364                 $issue = s/\n/\r/og if $mode == 1;
365                 local $/ = $nl;
366                 $stdout->print($issue) if $issue;
367         }
368         
369
370         use DXUser;
371         
372         DXUser->init($userfn);
373         
374         # allow a login from an existing user. I could create a user but
375         # I want to check for valid callsigns and I don't have the 
376         # necessary info / regular expression yet
377         for ($state = 0; $state < 2; ) {
378                 alarm($timeout);
379                 
380                 if ($state == 0) {
381                         $stdout->print('login: ');
382                         $stdout->flush();
383                         local $\ = $nl;
384                         $s = $stdin->getline();
385                         chomp $s;
386                         $s =~ s/\s+//og;
387                         $s =~ s/-\d+$//o;            # no ssids!
388                         cease(0) unless $s gt ' ';
389                         $call = uc $s;
390                         $user = DXUser->get($call);
391                         $state = 1;
392                 } elsif ($state == 1) {
393                         $stdout->print('password: ');
394                         $stdout->flush();
395                         local $\ = $nl;
396                         $s = $stdin->getline();
397                         chomp $s;
398                         $state = 2;
399                         if (!$user || ($user->passwd && $user->passwd ne $s)) {
400                                 $stdout->print("sorry...$nl");
401                                 cease(0);
402                         }
403                 }
404         }
405 }
406
407 # handle callsign and connection type firtling
408 sub doclient
409 {
410         my $line = shift;
411         my @f = split /\s+/, $line;
412         $call = uc $f[0] if $f[0];
413         $csort = $f[1] if $f[1];
414 }
415
416 # is this an out going connection?
417 if ($connsort eq "connect") {
418         my $mcall = lc $call;
419         
420         open(IN, "$cpath/$mcall") or cease(2);
421         @in = <IN>;
422         close IN;
423
424         alarm($timeout);
425         
426         for (@in) {
427                 chomp;
428                 next if /^\s*\#/o;
429                 next if /^\s*$/o;
430                 doconnect($1, $2) if /^\s*co\w*\s+(\w+)\s+(.*)$/io;
431                 doabort($1) if /^\s*a\w*\s+(.*)/io;
432                 dotimeout($1) if /^\s*t\w*\s+(\d+)/io;
433                 dochat($1, $2) if /\s*\'(.*)\'\s+\'(.*)\'/io;
434                 if (/\s*cl\w+\s+(.*)/io) {
435                         doclient($1);
436                         last;
437                 }
438         }
439         
440     dbg('connect', "Connected to $call ($csort), starting normal protocol");
441         dbgsub('connect');
442         
443         # if we get here we are connected
444         if ($csort eq 'ax25' || $csort eq 'prog') {
445                 #               open(STDIN, "<&R"); 
446                 #               open(STDOUT, ">&W"); 
447                 #               close R;
448                 #               close W;
449         $stdin = $rfh;
450                 $stdout = $wfh;
451                 $csort = 'telnet' if $csort eq 'prog';
452         } elsif ($csort eq 'telnet') {
453                 #               open(STDIN, "<&$sock"); 
454                 #               open(STDOUT, ">&$sock"); 
455                 #               close $sock;
456                 $stdin = $sock;
457                 $stdout = $sock;
458         }
459     alarm(0);
460     $outbound = 1;
461         $connsort = $csort;
462         $stdout->autoflush(1);
463         close STDIN;
464         close STDOUT;
465         close STDERR;
466 }
467
468 $mode = ($connsort eq 'ax25') ? 1 : 2;
469 setmode();
470
471 $conn = Msg->connect("$clusteraddr", $clusterport, \&rec_socket);
472 if (! $conn) {
473         if (-r "$data/offline") {
474                 open IN, "$data/offline" or die;
475                 while (<IN>) {
476                         s/\n/\r/og if $mode == 1;
477                         print $stdout $_;
478                 }
479                 close IN;
480         } else {
481                 print $stdout "Sorry, the cluster $mycall is currently off-line", $mynl;
482         }
483         cease(0);
484 }
485
486 $let = $outbound ? 'O' : 'A';
487 $conn->send_now("$let$call|$connsort");
488 Msg->set_event_handler($stdin, "read" => \&rec_stdin);
489
490 for (;;) {
491         my $t;
492         Msg->event_loop(1, 0.010);
493         $t = time;
494         if ($t > $lasttime) {
495                 if ($outqueue) {
496                         print $stdout $outqueue;
497                         $outqueue = "";
498                 }
499                 $lasttime = $t;
500         }
501 }
502
503 exit(0);