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