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