obtain a new descriptor for the lock in kids, this should fix locking problems
[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   $old_pid =~ /^(\d+)$/;
61   kill 'TERM', $1;
62 }
63 open(PIDFILE,">$pid_file");
64 print PIDFILE "$$\n";
65 close PIDFILE;
66
67 #my $waitedpid;
68 #sub REAPER { $waitedpid = wait; $SIG{CHLD} = \&REAPER; }
69 #$SIG{CHLD} =  \&REAPER;
70
71 warn "enabling keep alives\n" if $Debug;
72 nstore_fd( { _packet => '_enable_keepalive' } , \*STDOUT );
73
74 warn "entering main loop\n" if $Debug;
75
76 my %kids;
77
78 my $s = new IO::Select;
79 $s->add(\*STDIN);
80 $s->add(\*Server);
81
82 #for ( $waitedpid = 0;
83 #      accept(Client,Server) || $waitedpid;
84 #      $waitedpid = 0, close Client)
85 #{
86 #  next if $waitedpid;
87
88 #$SIG{PIPE} = sub { warn "SIGPIPE received" };
89 #$SIG{CHLD} = sub { warn "SIGCHLD received" };
90
91 #sub REAPER { warn "SIGCHLD received"; my $pid = wait; $SIG{CHLD} = \&REAPER; }
92 #sub REAPER { my $pid = wait; $SIG{CHLD} = \&REAPER; }
93 #sub REAPER { my $pid = wait; delete $kids{$pid}; $SIG{CHLD} = \&REAPER; }
94 #$SIG{CHLD} =  \&REAPER;
95
96 my $undisp = 0;
97 while (1) {
98
99   &reap_kids;
100
101   warn "waiting for connection\n" if $Debug && !$undisp;
102
103   #my @handles = $s->can_read();
104   my @handles = $s->can_read(5);
105   $undisp = !scalar(@handles);
106   foreach my $handle ( @handles ) {
107
108     if ( $handle == \*STDIN ) {
109
110       warn "receiving packet from server\n" if $Debug > 3;
111
112       my $packet = fd_retrieve(\*STDIN);
113       my $token = $packet->{'_token'};
114
115       if ( $token eq '_keepalive' ) {
116         $undisp = 1;
117         next;
118       }
119
120       warn "received packet from server with token $token\n".
121            ( $Debug > 2
122              ? join('', map { " $_=>$packet->{$_}\n" } keys %$packet )
123              : '' )
124         if $Debug;
125
126      if ( exists($kids{$token}) ) {
127         warn "sending return packet to $token via $kids{$token}\n"
128           if $Debug;
129         nstore_fd($packet, $kids{$token});
130         warn "flushing to $token\n" if $Debug;
131         until ( $kids{$token}->flush ) {
132           warn "WARNING: error flushing: $!";
133           sleep 1;
134         }
135         #no close or delete here - will block waiting for child
136         warn "done with $token\n" if $Debug;
137       } else {
138         warn "WARNING: unknown token $token, discarding message";
139       }
140
141     } elsif ( $handle == \*Server ) {
142
143       until ( accept(Client, Server) ) {
144         warn "WARNING: accept failed: $!";
145         next;
146       }
147
148       warn "received local connection; forking\n" if $Debug;
149
150       spawn sub { #child
151         warn "[child-$$] reading packet from local client" if $Debug > 1;
152         my $packet = fd_retrieve(\*Client);
153         warn "[child-$$] packet received:\n".
154              join('', map { " $_=>$packet->{$_}\n" } keys %$packet )
155           if $Debug > 2;
156         my $command = $packet->{'command'};
157         #handle some commands weirdly?
158         $packet->{_token}=$$;
159
160         warn "[child-$$] locking write stream\n" if $Debug > 1;
161         lock_write;
162
163         warn "[child-$$] sending packet to remote server\n" if $Debug > 1;
164         nstore_fd($packet, \*STDOUT) or die "FATAL: can't send response: $!";
165         
166         warn "[child-$$] flushing write stream\n" if $Debug > 1;
167         STDOUT->flush or die "FATAL: can't flush: $!";
168         
169         warn "[child-$$] releasing write lock\n" if $Debug > 1;
170         unlock_write;
171
172         warn "[child-$$] closing write stream\n" if $Debug > 1;
173         close STDOUT or die "FATAL: can't close write stream: $!"; #??!
174
175         warn "[child-$$] waiting for response from parent\n" if $Debug > 1;
176         my $w = new IO::Select;
177         $w->add(\*STDIN);
178         until ( $w->can_read ) {
179           warn "[child-$$] WARNING: interrupted select: $!\n";
180         }
181         my $rv = fd_retrieve(\*STDIN);
182
183         #close STDIN;
184
185         warn "[child-$$] sending response to local client" if $Debug > 1;
186         nstore_fd($rv, \*Client);
187         Client->flush or die "FATAL: can't flush to local client: $!";
188         close Client or die "FATAL: can't close connection to local client: $!";
189
190         warn "[child-$$] child exiting" if $Debug > 1;
191         exit;
192
193       }; #eo child
194
195       #close Client;
196
197     } else {
198       die "wtf?  $handle";
199     }
200
201   }
202   
203 }
204
205 sub reap_kids {
206   #warn "reaping kids\n";
207   foreach my $pid ( keys %kids ) {
208     my $kid = waitpid($pid, WNOHANG);
209     if ( $kid > 0 ) {
210       close $kids{$kid};
211       delete $kids{$kid};
212     }
213   }
214   #warn "done reaping\n";
215 }
216
217 sub spawn {
218     my $coderef = shift;
219
220     unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') {
221         use Carp;
222         confess "usage: spawn CODEREF";
223     }
224
225     my $pid;
226     #if (!defined($pid = fork)) {
227     my $kid = new IO::Handle;
228     if (!defined($pid = open($kid, '|-'))) {
229         warn "WARNING: cannot fork: $!";
230         return;
231     } elsif ($pid) {
232         warn "begat $pid" if $Debug;
233         $kids{$pid} = $kid;
234         #$kids{$pid}->autoflush;
235         return; # I'm the parent
236     }
237     # else I'm the child -- go spawn
238
239 #    open(STDIN,  "<&Client")   || die "can't dup client to stdin";
240 #    open(STDOUT, ">&Client")   || die "can't dup client to stdout";
241 #     open(STDERR, ">&STDOUT") || die "can't dup stdout to stderr";
242     exit &$coderef();
243 }
244
245 sub _logmsg {
246   chomp( my $msg = shift );
247   my $log = new IO::File ">>$log_file";
248   die "can't open $log_file: $!" unless defined($log);
249   flock($log, LOCK_EX);
250   seek($log, 0, 2);
251   print $log "[client] [". scalar(localtime). "] [$$] $msg\n";
252   flock($log, LOCK_UN);
253   close $log;
254 }
255
256 sub lock_write {
257   #broken on freebsd?
258   #flock(STDOUT, LOCK_EX) or die "FATAL: can't lock write stream: $!";
259
260   #open a new one for each kid to get a unique lock
261   open(LOCKFILE,">$lock_file") or die "can't open $lock_file: $!";
262
263   flock(LOCKFILE, LOCK_EX) or die "FATAL: can't lock $lock_file: $!";
264 }
265
266 sub unlock_write {
267   #broken on freebsd?
268   #flock(STDOUT, LOCK_UN) or die "FATAL: can't release write lock: $!";
269
270   flock(LOCKFILE, LOCK_UN) or die "FATAL: can't unlock $lock_file: $!";
271 }