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