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