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