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