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