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