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