bdc8e15475ddf2a6286e8506e74571f51b539671
[freeside.git] / fs_selfservice / FS-SelfService / freeside-selfservice-clientd
1 #!/usr/bin/perl -w
2 #
3 # freeside-selfservice-clientd
4 #
5 # This is run REMOTELY over ssh by freeside-selfservice-server
6
7 use strict;
8 use subs qw(spawn logmsg lock_write unlock_write);
9 use Fcntl qw(:flock);
10 use POSIX qw(:sys_wait_h);
11 use Socket;
12 use Storable 2.09 qw(nstore_fd fd_retrieve);
13 use IO::Handle qw(_IONBF);
14 use IO::Select;
15 use IO::File;
16
17 #STDOUT->setbuf('');
18
19 my $tag = scalar(@ARGV) ? '.'.shift : '';
20
21 use vars qw( $Debug );
22 $Debug = 2; #2 will turn on child logging
23             #3 will log packet contents,#including passwords
24             #4 will log receipts of all packets from server including
25             #  keepalives (big!)
26
27 my $socket = "/usr/local/freeside/selfservice_socket$tag";
28 my $pid_file = "$socket.pid";
29
30 my $log_file = "/usr/local/freeside/selfservice$tag.log";
31
32 my $lock_file = "/usr/local/freeside/selfservice$tag.writelock";
33
34 #my $me = '[client]';
35
36 $|=1;
37
38 $SIG{__WARN__} = \&_logmsg;
39
40 #read data to be cached or something
41 #warn "$me Reading init data\n" if $Debug;
42 #my $signup_init = 
43
44 warn "Creating $lock_file\n" if $Debug;
45 open(LOCKFILE,">$lock_file") or die "can't open $lock_file: $!";
46 close LOCKFILE;
47
48 warn "Creating $socket\n" if $Debug;
49 my $uaddr = sockaddr_un($socket);
50 my $proto = getprotobyname('tcp');
51 socket(Server,PF_UNIX,SOCK_STREAM,0) or die "socket: $!";
52 unlink($socket);
53 bind(Server, $uaddr) or die "bind: $!";
54 listen(Server,SOMAXCONN) or die "listen: $!";
55
56 if ( -e $pid_file ) {
57   open(PIDFILE,"<$pid_file");
58   my $old_pid = <PIDFILE>;
59   close PIDFILE;
60   if ( $old_pid =~ /^(\d+)$/ ) {
61     kill 'TERM', $1;
62   }
63 }
64 open(PIDFILE,">$pid_file");
65 print PIDFILE "$$\n";
66 close PIDFILE;
67
68 #my $waitedpid;
69 #sub REAPER { $waitedpid = wait; $SIG{CHLD} = \&REAPER; }
70 #$SIG{CHLD} =  \&REAPER;
71
72 warn "enabling keep alives\n" if $Debug;
73 nstore_fd( { _packet => '_enable_keepalive' } , \*STDOUT );
74
75 warn "entering main loop\n" if $Debug;
76
77 my %kids;
78
79 my $s = new IO::Select;
80 $s->add(\*STDIN);
81 $s->add(\*Server);
82
83 #for ( $waitedpid = 0;
84 #      accept(Client,Server) || $waitedpid;
85 #      $waitedpid = 0, close Client)
86 #{
87 #  next if $waitedpid;
88
89 #$SIG{PIPE} = sub { warn "SIGPIPE received" };
90 #$SIG{CHLD} = sub { warn "SIGCHLD received" };
91
92 #sub REAPER { warn "SIGCHLD received"; my $pid = wait; $SIG{CHLD} = \&REAPER; }
93 #sub REAPER { my $pid = wait; $SIG{CHLD} = \&REAPER; }
94 #sub REAPER { my $pid = wait; delete $kids{$pid}; $SIG{CHLD} = \&REAPER; }
95 #$SIG{CHLD} =  \&REAPER;
96
97 my $undisp = 0;
98 while (1) {
99
100   &reap_kids;
101
102   warn "waiting for connection\n" if $Debug && !$undisp;
103
104   #my @handles = $s->can_read();
105   my @handles = $s->can_read(5);
106   $undisp = !scalar(@handles);
107   foreach my $handle ( @handles ) {
108
109     if ( $handle == \*STDIN ) {
110
111       warn "receiving packet from server\n" if $Debug > 3;
112
113       my $packet = fd_retrieve(\*STDIN);
114       my $token = $packet->{'_token'};
115
116       if ( $token eq '_keepalive' ) {
117         $undisp = 1;
118         next;
119       }
120
121       warn "received packet from server with token $token\n".
122            ( $Debug > 2
123              ? join('', map { " $_=>$packet->{$_}\n" } keys %$packet )
124              : '' )
125         if $Debug;
126
127      if ( exists($kids{$token}) ) {
128         warn "sending return packet to $token via $kids{$token}\n"
129           if $Debug;
130         nstore_fd($packet, $kids{$token});
131         warn "flushing to $token\n" if $Debug;
132         until ( $kids{$token}->flush ) {
133           warn "WARNING: error flushing: $!";
134           sleep 1;
135         }
136         #no close or delete here - will block waiting for child
137         warn "done with $token\n" if $Debug;
138       } else {
139         warn "WARNING: unknown token $token, discarding message";
140       }
141
142     } elsif ( $handle == \*Server ) {
143
144       until ( accept(Client, Server) ) {
145         warn "WARNING: accept failed: $!";
146         next;
147       }
148
149       warn "received local connection; forking\n" if $Debug;
150
151       spawn sub { #child
152         warn "[child-$$] reading packet from local client" if $Debug > 1;
153         my $packet = fd_retrieve(\*Client);
154         warn "[child-$$] packet received:\n".
155              join('', map { " $_=>$packet->{$_}\n" } keys %$packet )
156           if $Debug > 2;
157         my $command = $packet->{'command'};
158         #handle some commands weirdly?
159         $packet->{_token}=$$;
160
161         warn "[child-$$] locking write stream\n" if $Debug > 1;
162         lock_write;
163
164         warn "[child-$$] sending packet to remote server\n" if $Debug > 1;
165         nstore_fd($packet, \*STDOUT) or die "FATAL: can't send response: $!";
166         
167         warn "[child-$$] flushing write stream\n" if $Debug > 1;
168         STDOUT->flush or die "FATAL: can't flush: $!";
169         
170         warn "[child-$$] releasing write lock\n" if $Debug > 1;
171         unlock_write;
172
173         warn "[child-$$] closing write stream\n" if $Debug > 1;
174         close STDOUT or die "FATAL: can't close write stream: $!"; #??!
175
176         warn "[child-$$] waiting for response from parent\n" if $Debug > 1;
177         my $w = new IO::Select;
178         $w->add(\*STDIN);
179         until ( $w->can_read ) {
180           warn "[child-$$] WARNING: interrupted select: $!\n";
181         }
182         my $rv = fd_retrieve(\*STDIN);
183
184         #close STDIN;
185
186         warn "[child-$$] sending response to local client" if $Debug > 1;
187         nstore_fd($rv, \*Client);
188         Client->flush or die "FATAL: can't flush to local client: $!";
189         close Client or die "FATAL: can't close connection to local client: $!";
190
191         warn "[child-$$] child exiting" if $Debug > 1;
192         exit;
193
194       }; #eo child
195
196       #close Client;
197
198     } else {
199       die "wtf?  $handle";
200     }
201
202   }
203   
204 }
205
206 sub reap_kids {
207   #warn "reaping kids\n";
208   foreach my $pid ( keys %kids ) {
209     my $kid = waitpid($pid, WNOHANG);
210     if ( $kid > 0 ) {
211       close $kids{$kid};
212       delete $kids{$kid};
213     }
214   }
215   #warn "done reaping\n";
216 }
217
218 sub spawn {
219     my $coderef = shift;
220
221     unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') {
222         use Carp;
223         confess "usage: spawn CODEREF";
224     }
225
226     my $pid;
227     #if (!defined($pid = fork)) {
228     my $kid = new IO::Handle;
229     if (!defined($pid = open($kid, '|-'))) {
230         warn "WARNING: cannot fork: $!";
231         return;
232     } elsif ($pid) {
233         warn "begat $pid" if $Debug;
234         $kids{$pid} = $kid;
235         #$kids{$pid}->autoflush;
236         return; # I'm the parent
237     }
238     # else I'm the child -- go spawn
239
240 #    open(STDIN,  "<&Client")   || die "can't dup client to stdin";
241 #    open(STDOUT, ">&Client")   || die "can't dup client to stdout";
242 #     open(STDERR, ">&STDOUT") || die "can't dup stdout to stderr";
243     exit &$coderef();
244 }
245
246 sub _logmsg {
247   chomp( my $msg = shift );
248   my $log = new IO::File ">>$log_file";
249   die "can't open $log_file: $!" unless defined($log);
250   flock($log, LOCK_EX);
251   seek($log, 0, 2);
252   print $log "[client] [". scalar(localtime). "] [$$] $msg\n";
253   flock($log, LOCK_UN);
254   close $log;
255 }
256
257 sub lock_write {
258   #broken on freebsd?
259   #flock(STDOUT, LOCK_EX) or die "FATAL: can't lock write stream: $!";
260
261   #open a new one for each kid to get a unique lock
262   open(LOCKFILE,">$lock_file") or die "can't open $lock_file: $!";
263
264   flock(LOCKFILE, LOCK_EX) or die "FATAL: can't lock $lock_file: $!";
265 }
266
267 sub unlock_write {
268   #broken on freebsd?
269   #flock(STDOUT, LOCK_UN) or die "FATAL: can't release write lock: $!";
270
271   flock(LOCKFILE, LOCK_UN) or die "FATAL: can't unlock $lock_file: $!";
272 }