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