import torrus 1.0.9
[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 qw( load_clientapi_modules );
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 load_clientapi_modules;
56
57 adminsuidsetup $user;
58
59 #logfile("/usr/local/etc/freeside/selfservice.". $FS::UID::datasrc); #MACHINE
60 logfile("$FREESIDE_LOG/selfservice.$machine.log");
61
62 daemonize2();
63
64 my $conf = new FS::Conf;
65 if ( $conf->exists('selfservice-ignore_quantity') ) {
66   $FS::cust_svc::ignore_quantity = 1;
67   $FS::cust_svc::ignore_quantity = 1; #now it is used twice.
68 }
69
70 #clear the signup info cache so an "/etc/init.d/freeside restart" will pick
71 #up new info... (better as a callback in Signup.pm?)
72 my $cache = new FS::ClientAPI_SessionCache( {
73   'namespace' => 'FS::ClientAPI::Signup',
74 } );
75 $cache->remove('signup_info_cache');
76
77 #and also clear the selfservice skin info cache, for the same reason
78 my $ss_cache = new FS::ClientAPI_SessionCache( {
79   'namespace' => 'FS::ClientAPI::MyAccount',
80 } );
81 $ss_cache->remove($_)
82   foreach grep /^skin_info_cache_agent/, $ss_cache->get_keys();
83
84 my $clientd = "/usr/local/sbin/freeside-selfservice-clientd"; #better name?
85
86 my $warnkids=0;
87 while (1) {
88   my($writer,$reader,$error) = (new IO::Handle, new IO::Handle, new IO::Handle);
89   warn "connecting to $machine\n" if $Debug;
90
91   $ssh_pid = sshopen2($machine,$reader,$writer,$clientd,$tag);
92
93 #  nstore_fd(\*writer, {'hi'=>'there'});
94
95   warn "entering main loop\n" if $Debug;
96   my $undisp = 0;
97   my $keepalive_count = 0;
98   my $s = IO::Select->new( $reader );
99   while (1) {
100
101     &reap_kids;
102
103     warn "waiting for packet from client\n" if $Debug && !$undisp;
104     $undisp = 1;
105     my @handles = $s->can_read(5);
106     unless ( @handles ) {
107       myshutdown() if sigint() || sigterm();
108       if ( $keepalives && $keepalive_count++ > 10 ) {
109         $keepalive_count = 0;
110         lock_write;
111
112         nstore_fd( { _token => '_keepalive' }, $writer );
113         foreach my $agent ( qsearch( 'agent', { disabled => '' } ) ) {
114           my $config = qsearchs( 'conf', { name  => 'selfservice-bulk_ftp_dir',
115                                            agentnum => $agent->agentnum,
116                                } )
117             or next;
118
119           my $session =
120             FS::ClientAPI->dispatch( 'Agent/agent_login',
121                                      { username => $agent->username,
122                                        password => $agent->_password,
123                                      }
124             );
125
126           nstore_fd( { _token     => '_ftp_scan',
127                        dir        => $config->value,
128                        session_id => $session->{session_id},
129                      },
130                      $writer
131           );
132         }
133         unlock_write;
134       }
135       next;
136     }
137
138     $undisp = 0;
139
140     warn "receiving packet from client\n" if $Debug;
141
142     my $packet = eval { fd_retrieve($reader); };
143     if ( $@ ) {
144       warn "Storable error receiving packet from client".
145            " (assuming lost connection): $@\n"
146         if $Debug;
147       if ( $ssh_pid ) {
148         warn "sending TERM signal to ssh process $ssh_pid\n" if $Debug;
149         kill 'TERM', $ssh_pid;
150         $old_ssh_pid{$ssh_pid} = 1;
151         $ssh_pid = 0;
152       }
153       last;
154     }
155     warn "packet received\n".
156          join('', map { " $_=>$packet->{$_}\n" } keys %$packet )
157       if $Debug > 2;
158
159     if ( $packet->{_packet} eq '_enable_keepalive' ) {
160       warn "enabling keep alives\n" if $Debug;
161       $keepalives=1;
162       next;
163     }
164
165     #prevent runaway forking
166     my $warnkids = 0;
167     while ( $kids >= $max_kids ) {
168       warn "WARNING: maximum $kids children reached\n" unless $warnkids++;
169       &reap_kids;
170       sleep 1;
171     }
172
173     warn "forking child\n" if $Debug;
174     defined( my $pid = fork ) or die "can't fork: $!";
175     if ( $pid ) {
176       $kids++;
177       $kids{$pid} = 1;
178       warn "child $pid spawned\n" if $Debug;
179     } else { #kid time
180
181       ##get new db handle
182       $FS::UID::dbh->{InactiveDestroy} = 1;
183       forksuidsetup($user);
184
185       #get db handle
186       #adminsuidsetup($user);
187
188       my $type = $packet->{_packet};
189       warn "calling $type handler\n" if $Debug; 
190       my $rv = eval { FS::ClientAPI->dispatch($type, $packet); };
191       if ( $@ ) {
192         warn my $error = "WARNING: error dispatching $type: $@";
193         $rv = { _error => $error };
194       }
195       $rv->{_token} = $packet->{_token}; #identifier
196
197       open(LOCKFILE,">$lock_file") or die "can't open $lock_file: $!";
198       lock_write;
199       warn "sending response\n" if $Debug;
200       nstore_fd($rv, $writer) or die "FATAL: can't send response: $!";
201       $writer->flush or die "FATAL: can't flush: $!";
202       unlock_write;
203
204       warn "child exiting\n" if $Debug;
205       exit; #end-of-kid
206     }
207
208   }
209
210   myshutdown if sigint() || sigterm();
211   warn "connection lost, reconnecting\n" if $Debug;
212   sleep 3;
213
214 }
215
216 ###
217 # utility subroutines
218 ###
219
220 sub reap_kids {
221   #warn "reaping kids\n";
222   foreach my $pid ( keys %kids ) {
223     my $kid = waitpid($pid, WNOHANG);
224     if ( $kid > 0 ) {
225       $kids--;
226       delete $kids{$kid};
227     }
228   }
229
230   foreach my $pid ( keys %old_ssh_pid ) {
231     waitpid($pid, WNOHANG) and delete $old_ssh_pid{$pid};
232   }
233   #warn "done reaping\n";
234 }
235
236 sub myshutdown {
237   &reap_kids;
238   my $wait = 12; #wait up to 1 minute
239   while ( $kids > 0 && $wait-- ) {
240     warn "waiting for $kids children to terminate";
241     sleep 5;
242     &reap_kids;
243   }
244   warn "abandoning $kids children" if $kids;
245   kill 'TERM', $ssh_pid if $ssh_pid;
246   die "exiting";
247 }
248
249 sub lock_write {
250   warn "locking $lock_file mutex for write to write stream\n" if $Debug > 1;
251
252   #broken on freebsd?
253   #flock($writer, LOCK_EX) or die "FATAL: can't lock write stream: $!";
254
255   flock(LOCKFILE, LOCK_EX) or die "FATAL: can't lock $lock_file: $!";
256
257 }
258
259 sub unlock_write {
260   warn "unlocking $lock_file mutex\n" if $Debug > 1;
261
262   #broken on freebsd?
263   #flock($writer, LOCK_UN) or die "WARNING: can't release write lock: $!";
264
265   flock(LOCKFILE, LOCK_UN) or die "FATAL: can't unlock $lock_file: $!";
266
267 }
268
269 sub usage {
270   die "Usage:\n\n  freeside-selfservice-server user machine\n";
271 }
272