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