This commit was generated by cvs2svn to compensate for changes in r8593,
[freeside.git] / FS / bin / freeside-selfservice-server
1 #!/usr/bin/perl -w
2
3 use strict;
4 use vars qw( $FREESIDE_LOG $FREESIDE_LOCK );
5 use vars qw( $Debug %kids $kids $max_kids $ssh_pid %old_ssh_pid $keepalives );
6 use subs qw( lock_write unlock_write myshutdown usage );
7 use Fcntl qw(:flock);
8 use POSIX qw(:sys_wait_h);
9 use IO::Handle;
10 use IO::Select;
11 use IO::File;
12 use Storable 2.09 qw(nstore_fd fd_retrieve);
13 use Net::SSH qw(sshopen2);
14 use FS::Daemon qw(daemonize1 drop_root logfile daemonize2 sigint sigterm);
15 use FS::UID qw(adminsuidsetup forksuidsetup);
16 use FS::ClientAPI;
17 use FS::ClientAPI_SessionCache;
18 use FS::Record qw( qsearch qsearchs );
19
20 use FS::Conf;
21 use FS::cust_svc;
22 use FS::agent;
23
24 $FREESIDE_LOG = "%%%FREESIDE_LOG%%%";
25 $FREESIDE_LOCK = "%%%FREESIDE_LOCK%%%";
26
27 $Debug = 1; # 2 will turn on more logging
28             # 3 will log packet contents, including passwords
29
30 $max_kids = '10'; #?
31 $keepalives = 0; #let clientd turn it on, so we don't barf on old ones
32 $kids = 0;
33
34 my $user = shift or die &usage;
35 my $machine = shift or die &usage;
36 my $tag = scalar(@ARGV) ? shift : '';
37
38 my $lock_file = "$FREESIDE_LOCK/selfservice.$machine.writelock";
39
40 # to keep pid files unique w/multi machines (and installs!)
41 # $FS::UID::datasrc not posible
42 daemonize1("freeside-selfservice-server","$user.$machine");
43
44 #false laziness w/Daemon::drop_root
45 my $freeside_gid = scalar(getgrnam('freeside'))
46   or die "can't find freeside group\n";
47
48 open(LOCKFILE,">$lock_file") or die "can't open $lock_file: $!";
49 chown $FS::UID::freeside_uid, $freeside_gid, $lock_file;
50
51 drop_root();
52
53 $ENV{HOME} = (getpwuid($>))[7]; #for ssh
54
55 adminsuidsetup $user;
56
57 #logfile("/usr/local/etc/freeside/selfservice.". $FS::UID::datasrc); #MACHINE
58 logfile("$FREESIDE_LOG/selfservice.$machine.log");
59
60 daemonize2();
61
62 my $conf = new FS::Conf;
63 if ( $conf->exists('selfservice-ignore_quantity') ) {
64   $FS::cust_svc::ignore_quantity = 1;
65   $FS::cust_svc::ignore_quantity = 1; #now it is used twice.
66 }
67
68 #clear the signup info cache so an "/etc/init.d/freeside restart" will pick
69 #up new info... (better as a callback in Signup.pm?)
70 my $cache = new FS::ClientAPI_SessionCache( {
71   'namespace' => 'FS::ClientAPI::Signup',
72 } );
73 $cache->remove('signup_info_cache');
74
75 #and also clear the selfservice skin info cache, for the same reason
76 my $ss_cache = new FS::ClientAPI_SessionCache( {
77   'namespace' => 'FS::ClientAPI::MyAccount',
78 } );
79 $ss_cache->remove($_)
80   foreach grep /^skin_info_cache_agent/, $ss_cache->get_keys();
81
82 my $clientd = "/usr/local/sbin/freeside-selfservice-clientd"; #better name?
83
84 my $warnkids=0;
85 while (1) {
86   my($writer,$reader,$error) = (new IO::Handle, new IO::Handle, new IO::Handle);
87   warn "connecting to $machine\n" if $Debug;
88
89   $ssh_pid = sshopen2($machine,$reader,$writer,$clientd,$tag);
90
91 #  nstore_fd(\*writer, {'hi'=>'there'});
92
93   warn "entering main loop\n" if $Debug;
94   my $undisp = 0;
95   my $keepalive_count = 0;
96   my $s = IO::Select->new( $reader );
97   while (1) {
98
99     &reap_kids;
100
101     warn "waiting for packet from client\n" if $Debug && !$undisp;
102     $undisp = 1;
103     my @handles = $s->can_read(5);
104     unless ( @handles ) {
105       myshutdown() if sigint() || sigterm();
106       if ( $keepalives && $keepalive_count++ > 10 ) {
107         $keepalive_count = 0;
108         lock_write;
109
110         nstore_fd( { _token => '_keepalive' }, $writer );
111         foreach my $agent ( qsearch( 'agent', { disabled => '' } ) ) {
112           my $config = qsearchs( 'conf', { name  => 'selfservice-bulk_ftp_dir',
113                                            agentnum => $agent->agentnum,
114                                } )
115             or next;
116
117           my $session =
118             FS::ClientAPI->dispatch( 'Agent/agent_login',
119                                      { username => $agent->username,
120                                        password => $agent->_password,
121                                      }
122             );
123
124           nstore_fd( { _token     => '_ftp_scan',
125                        dir        => $config->value,
126                        session_id => $session->{session_id},
127                      },
128                      $writer
129           );
130         }
131         unlock_write;
132       }
133       next;
134     }
135
136     $undisp = 0;
137
138     warn "receiving packet from client\n" if $Debug;
139
140     my $packet = eval { fd_retrieve($reader); };
141     if ( $@ ) {
142       warn "Storable error receiving packet from client".
143            " (assuming lost connection): $@\n"
144         if $Debug;
145       if ( $ssh_pid ) {
146         warn "sending TERM signal to ssh process $ssh_pid\n" if $Debug;
147         kill 'TERM', $ssh_pid;
148         $old_ssh_pid{$ssh_pid} = 1;
149         $ssh_pid = 0;
150       }
151       last;
152     }
153     warn "packet received\n".
154          join('', map { " $_=>$packet->{$_}\n" } keys %$packet )
155       if $Debug > 2;
156
157     if ( $packet->{_packet} eq '_enable_keepalive' ) {
158       warn "enabling keep alives\n" if $Debug;
159       $keepalives=1;
160       next;
161     }
162
163     #prevent runaway forking
164     my $warnkids = 0;
165     while ( $kids >= $max_kids ) {
166       warn "WARNING: maximum $kids children reached\n" unless $warnkids++;
167       &reap_kids;
168       sleep 1;
169     }
170
171     warn "forking child\n" if $Debug;
172     defined( my $pid = fork ) or die "can't fork: $!";
173     if ( $pid ) {
174       $kids++;
175       $kids{$pid} = 1;
176       warn "child $pid spawned\n" if $Debug;
177     } else { #kid time
178
179       ##get new db handle
180       $FS::UID::dbh->{InactiveDestroy} = 1;
181       forksuidsetup($user);
182
183       #get db handle
184       #adminsuidsetup($user);
185
186       my $type = $packet->{_packet};
187       warn "calling $type handler\n" if $Debug; 
188       my $rv = eval { FS::ClientAPI->dispatch($type, $packet); };
189       if ( $@ ) {
190         warn my $error = "WARNING: error dispatching $type: $@";
191         $rv = { _error => $error };
192       }
193       $rv->{_token} = $packet->{_token}; #identifier
194
195       open(LOCKFILE,">$lock_file") or die "can't open $lock_file: $!";
196       lock_write;
197       warn "sending response\n" if $Debug;
198       nstore_fd($rv, $writer) or die "FATAL: can't send response: $!";
199       $writer->flush or die "FATAL: can't flush: $!";
200       unlock_write;
201
202       warn "child exiting\n" if $Debug;
203       exit; #end-of-kid
204     }
205
206   }
207
208   myshutdown if sigint() || sigterm();
209   warn "connection lost, reconnecting\n" if $Debug;
210   sleep 3;
211
212 }
213
214 ###
215 # utility subroutines
216 ###
217
218 sub reap_kids {
219   #warn "reaping kids\n";
220   foreach my $pid ( keys %kids ) {
221     my $kid = waitpid($pid, WNOHANG);
222     if ( $kid > 0 ) {
223       $kids--;
224       delete $kids{$kid};
225     }
226   }
227
228   foreach my $pid ( keys %old_ssh_pid ) {
229     waitpid($pid, WNOHANG) and delete $old_ssh_pid{$pid};
230   }
231   #warn "done reaping\n";
232 }
233
234 sub myshutdown {
235   &reap_kids;
236   my $wait = 12; #wait up to 1 minute
237   while ( $kids > 0 && $wait-- ) {
238     warn "waiting for $kids children to terminate";
239     sleep 5;
240     &reap_kids;
241   }
242   warn "abandoning $kids children" if $kids;
243   kill 'TERM', $ssh_pid if $ssh_pid;
244   die "exiting";
245 }
246
247 sub lock_write {
248   warn "locking $lock_file mutex for write to write stream\n" if $Debug > 1;
249
250   #broken on freebsd?
251   #flock($writer, LOCK_EX) or die "FATAL: can't lock write stream: $!";
252
253   flock(LOCKFILE, LOCK_EX) or die "FATAL: can't lock $lock_file: $!";
254
255 }
256
257 sub unlock_write {
258   warn "unlocking $lock_file mutex\n" if $Debug > 1;
259
260   #broken on freebsd?
261   #flock($writer, LOCK_UN) or die "WARNING: can't release write lock: $!";
262
263   flock(LOCKFILE, LOCK_UN) or die "FATAL: can't unlock $lock_file: $!";
264
265 }
266
267 sub usage {
268   die "Usage:\n\n  freeside-selfservice-server user machine\n";
269 }
270