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