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