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