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