ce0085dedd10e1c52ee40850c51dc0cff14f18b5
[spider.git] / perl / client.pl
1 #!/usr/bin/perl
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
30 # search local then perl directories
31 BEGIN {
32         # root of directory tree for this system
33         $root = "/spider"; 
34         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
35         
36         unshift @INC, "$root/perl";     # this IS the right way round!
37         unshift @INC, "$root/local";
38 }
39
40 use Msg;
41 use DXVars;
42 use DXDebug;
43 use IO::File;
44 use IO::Socket;
45 use IPC::Open2;
46 use Net::Telnet qw(TELOPT_ECHO);
47 use Carp;
48
49 # cease communications
50 sub cease
51 {
52         my $sendz = shift;
53         if ($conn && $sendz) {
54                 $conn->send_now("Z$call|bye...\n");
55         }
56         $stdout->flush if $stdout;
57         kill(15, $pid) if $pid;
58         sleep(1);
59         exit(0);        
60 }
61
62 # terminate program from signal
63 sub sig_term
64 {
65         cease(1);
66 }
67
68 # terminate a child
69 sub sig_chld
70 {
71         $SIG{CHLD} = \&sig_chld;
72         $waitedpid = wait;
73 }
74
75
76 sub setmode
77 {
78         if ($mode == 1) {
79                 $mynl = "\r";
80         } else {
81                 $mynl = "\n";
82         }
83         $/ = $mynl;
84 }
85
86 # handle incoming messages
87 sub rec_socket
88 {
89         my ($con, $msg, $err) = @_;
90         if (defined $err && $err) {
91                 cease(1);
92         }
93         if (defined $msg) {
94                 my ($sort, $call, $line) = $msg =~ /^(\w)(\S+)\|(.*)$/;
95                 
96                 if ($sort eq 'D') {
97                         my $snl = $mynl;
98                         my $newsavenl = "";
99                         $snl = "" if $mode == 0;
100                         if ($mode == 2 && $line =~ />$/) {
101                                 $newsavenl = $snl;
102                                 $snl = ' ';
103                         }
104                         $line =~ s/\n/\r/og if $mode == 1;
105                         #my $p = qq($line$snl);
106                         if ($buffered) {
107                                 if (length $outqueue >= 128) {
108                                         print $stdout $outqueue;
109                                         $outqueue = "";
110                                 }
111                                 $outqueue .= "$savenl$line$snl";
112                                 $lasttime = time;
113                         } else {
114                                 print $stdout $savenl, $line, $snl;;
115                         }
116                         $savenl = $newsavenl;
117                 } elsif ($sort eq 'M') {
118                         $mode = $line;          # set new mode from cluster
119                         setmode();
120                 } elsif ($sort eq 'E') {
121                         if ($sort eq 'telnet') {
122                                 $mode = $line;          # set echo mode from cluster
123                                 my $term = POSIX::Termios->new;
124                                 $term->getattr(fileno($sock));
125                                 $term->setflag( &POSIX::ISIG );
126                                 $term->setattr(fileno($sock), &POSIX::TCSANOW );
127                         }
128                 } elsif ($sort eq 'I') {
129                         ;                       # ignore echoed I frames
130                 } elsif ($sort eq 'B') {
131                         if ($buffered && $outqueue) {
132                                 print $stdout $outqueue;
133                                 $outqueue = "";
134                         }
135                         $buffered = $line;      # set buffered or unbuffered
136                 } elsif ($sort eq 'Z') { # end, disconnect, go, away .....
137                         cease(0);
138                 }         
139         }
140         $lasttime = time; 
141 }
142
143 sub rec_stdin
144 {
145         my ($fh) = @_;
146         my $buf;
147         my @lines;
148         my $r;
149         my $first;
150         my $dangle = 0;
151         
152         $r = sysread($fh, $buf, 1024);
153         #  my $prbuf;
154         #  $prbuf = $buf;
155         #  $prbuf =~ s/\r/\\r/;
156         #  $prbuf =~ s/\n/\\n/;
157         #  print "sys: $r ($prbuf)\n";
158         if ($r > 0) {
159                 if ($mode) {
160                         $buf =~ s/\r/\n/og if $mode == 1;
161                         $dangle = !($buf =~ /\n$/);
162                         if ($buf eq "\n") {
163                                 @lines = (" ");
164                         } else {
165                                 @lines = split /\n/, $buf;
166                         }
167                         if ($dangle) {          # pull off any dangly bits
168                                 $buf = pop @lines;
169                         } else {
170                                 $buf = "";
171                         }
172                         $first = shift @lines;
173                         unshift @lines, ($lastbit . $first) if ($first);
174                         foreach $first (@lines) {
175                                 #                 print "send_now $call $first\n";
176                                 $conn->send_now("I$call|$first");
177                         }
178                         $lastbit = $buf;
179                         $savenl = "";           # reset savenl 'cos we will have done a newline on input
180                 } else {
181                         $conn->send_now("I$call|$buf");
182                 }
183         } elsif ($r == 0) {
184                 cease(1);
185         }
186         $lasttime = time;
187 }
188
189 sub doconnect
190 {
191         my ($sort, $line) = @_;
192         dbg('connect', "CONNECT sort: $sort command: $line");
193         if ($sort eq 'telnet') {
194                 # this is a straight network connect
195                 my ($host, $port) = split /\s+/, $line;
196                 $port = 23 if !$port;
197                 
198                 if ($port == 23) {
199                         $sock = new Net::Telnet (Timeout => $timeout, BinMode => 1);
200                         $sock->option_accept(Dont => TELOPT_ECHO, Wont => TELOPT_ECHO);
201                         $sock->option_log('option_log');
202                         $sock->dump_log('dump');
203                         $sock->open($host) or die "Can't connect to $host port $port $!";
204                 } else {
205                         $sock = IO::Socket::INET->new(PeerAddr => "$host:$port", Proto => 'tcp')
206                                 or die "Can't connect to $host port $port $!";
207                         
208                 }
209         } elsif ($sort eq 'ax25') {
210                 my @args = split /\s+/, $line;
211                 $rfh = new IO::File;
212                 $wfh = new IO::File;
213                 $pid = open2($rfh, $wfh, "$line") or die "can't do $line $!";
214                 dbg('connect', "got pid $pid");
215                 $wfh->autoflush(1);
216         } else {
217                 die "invalid type of connection ($sort)";
218         }
219         $csort = $sort;
220 }
221
222 sub doabort
223 {
224         my $string = shift;
225         dbg('connect', "abort $string");
226         $abort = $string;
227 }
228
229 sub dotimeout
230 {
231         my $val = shift;
232         dbg('connect', "timeout set to $val");
233         $timeout = $val;
234 }
235
236 sub dochat
237 {
238         my ($expect, $send) = @_;
239         dbg('connect', "CHAT \"$expect\" -> \"$send\"");
240     my $line;
241         
242         alarm($timeout);
243         
244     if ($expect) {
245                 for (;;) {
246                         if ($csort eq 'telnet') {
247                                 $line = $sock->get();
248                                 chomp;
249                         } elsif ($csort eq 'ax25') {
250                                 local $/ = "\r";
251                                 $line = <$rfh>;
252                                 $line =~ s/\r//og;
253                         }
254                         dbg('connect', "received \"$line\"");
255                         if ($abort && $line =~ /$abort/i) {
256                                 dbg('connect', "aborted on /$abort/");
257                                 cease(11);
258                         }
259                         last if $line =~ /$expect/i;
260                 }
261         }
262         if ($send) {
263                 if ($csort eq 'telnet') {
264                         $sock->print("$send\n");
265                 } elsif ($csort eq 'ax25') {
266                         local $\ = "\r";
267                         $wfh->print("$send");
268                 }
269                 dbg('connect', "sent \"$send\"");
270         }
271 }
272
273 sub timeout
274 {
275         dbg('connect', "timed out after $timeout seconds");
276         cease(10);
277 }
278
279
280 #
281 # initialisation
282 #
283
284 $mode = 2;                      # 1 - \n = \r as EOL, 2 - \n = \n, 0 - transparent
285 $call = "";                     # the callsign being used
286 @stdoutq = ();                  # the queue of stuff to send out to the user
287 $conn = 0;                      # the connection object for the cluster
288 $lastbit = "";                  # the last bit of an incomplete input line
289 $mynl = "\n";                   # standard terminator
290 $lasttime = time;               # lasttime something happened on the interface
291 $outqueue = "";                 # the output queue length
292 $buffered = 1;                  # buffer output
293 $savenl = "";                   # an NL that has been saved from last time
294 $timeout = 60;                  # default timeout for connects
295 $abort = "";                    # the current abort string
296 $cpath = "$root/connect";               # the basic connect directory
297
298 $pid = 0;                       # the pid of the child program
299 $csort = "";                    # the connection type
300 $sock = 0;                      # connection socket
301
302 $stdin = *STDIN;
303 $stdout = *STDOUT;
304 $rfh = 0;
305 $wfh = 0;
306
307
308 #
309 # deal with args
310 #
311
312 $call = uc shift @ARGV;
313 $call = uc $myalias if !$call; 
314 $connsort = lc shift @ARGV;
315 $connsort = 'local' if !$connsort;
316
317 #
318 # strip off any SSID if it is a telnet connection 
319 #
320 # SSID's are a problem, basically we don't allow them EXCEPT for the special case
321 # of local users. i.e. you can have a cluster call with an SSID and a usercall with
322 # an SSID and they are different to the system to those without SSIDs
323 #
324
325 $call =~ s/-\d+$//o if $mode eq 'telnet';
326 $mode = ($connsort eq 'ax25') ? 1 : 2;
327 setmode();
328
329 if ($call eq $mycall) {
330         print $stdout "You cannot connect as your cluster callsign ($mycall)", $nl;
331         cease(0);
332 }
333
334 $stdout->autoflush(1);
335
336 $SIG{'INT'} = \&sig_term;
337 $SIG{'TERM'} = \&sig_term;
338 $SIG{'HUP'} = 'IGNORE';
339 $SIG{'CHLD'} = \&sig_chld;
340
341 dbgadd('connect');
342
343 # is this an out going connection?
344 if ($connsort eq "connect") {
345         my $mcall = lc $call;
346         
347         open(IN, "$cpath/$mcall") or cease(2);
348         @in = <IN>;
349         close IN;
350         
351         #       alarm($timeout);
352         
353         for (@in) {
354                 chomp;
355                 next if /^\s*\#/o;
356                 next if /^\s*$/o;
357                 doconnect($1, $2) if /^\s*co\w*\s+(\w+)\s+(.*)$/io;
358                 doabort($1) if /^\s*a\w*\s+(.*)/io;
359                 dotimeout($1) if /^\s*t\w*\s+(\d+)/io;
360                 dochat($1, $2) if /\s*\'(.*)\'\s+\'(.*)\'/io;          
361         }
362         
363     dbg('connect', "Connected to $call, starting normal protocol");
364         dbgsub('connect');
365         
366         # if we get here we are connected
367         if ($csort eq 'ax25') {
368                 #               open(STDIN, "<&R"); 
369                 #               open(STDOUT, ">&W"); 
370                 #               close R;
371                 #               close W;
372         $stdin = $rfh;
373                 $stdout = $wfh;
374         } elsif ($csort eq 'telnet') {
375                 #               open(STDIN, "<&$sock"); 
376                 #               open(STDOUT, ">&$sock"); 
377                 #               close $sock;
378                 $stdin = $sock;
379                 $stdout = $sock;
380         }
381     alarm(0);
382     $outbound = 1;
383         $connsort = $csort;
384         $stdout->autoflush(1);
385         close STDIN;
386         close STDOUT;
387         close STDERR;
388         
389         
390         $mode = ($connsort =~ /^ax/o) ? 1 : 2;
391         setmode();
392 }
393
394 setmode();
395
396 $conn = Msg->connect("$clusteraddr", $clusterport, \&rec_socket);
397 if (! $conn) {
398         if (-r "$data/offline") {
399                 open IN, "$data/offline" or die;
400                 while (<IN>) {
401                         s/\n/\r/og if $mode == 1;
402                         print $stdout;
403                 }
404                 close IN;
405         } else {
406                 print $stdout "Sorry, the cluster $mycall is currently off-line", $mynl;
407         }
408         cease(0);
409 }
410
411 $let = $outbound ? 'O' : 'A';
412 $conn->send_now("$let$call|$connsort");
413 Msg->set_event_handler($stdin, "read" => \&rec_stdin);
414
415 for (;;) {
416         my $t;
417         Msg->event_loop(1, 0.010);
418         $t = time;
419         if ($t > $lasttime) {
420                 if ($outqueue) {
421                         print $stdout $outqueue;
422                         $outqueue = "";
423                 }
424                 $lasttime = $t;
425         }
426 }
427
428 exit(0);