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