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