summaryrefslogtreecommitdiff
path: root/FS/bin/freeside-selfservice-server
blob: a83664db2fe56264d44362f4f107ff5b7bbe8ccf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
#!/usr/bin/perl -w
#
# freeside-selfservice-server

# alas, much false laziness with freeside-queued and fs_signup_server.  at
# least it is slated to replace fs_{signup,passwd,mailadmin}_server
# should probably generalize the version in here, or better yet use
# Proc::Daemon or somesuch

use strict;
use vars qw( $Debug %kids $kids $max_kids $shutdown $log_file $ssh_pid
             $keepalives );
use subs qw( lock_write unlock_write );
use Fcntl qw(:flock);
use POSIX qw(:sys_wait_h setsid);
use IO::Handle;
use IO::Select;
use IO::File;
use Storable 2.09 qw(nstore_fd fd_retrieve);
use Net::SSH qw(sshopen2);
use FS::UID qw(adminsuidsetup forksuidsetup);
use FS::ClientAPI;

use FS::Conf;
use FS::cust_bill;
use FS::cust_pkg;

$Debug = 1; # >= 2 will log packet contents, including potentially compromising
            # information

$shutdown = 0;
$max_kids = '10'; #?
$keepalives = 0; #let clientd turn it on, so we don't barf on old ones
$kids = 0;

my $user = shift or die &usage;
my $machine = shift or die &usage;
my $tag = scalar(@ARGV) ? shift : '';

# $FS::UID::datasrc not posible
my $pid_file = "/var/run/freeside-selfservice-server.$user.$machine.pid";

my $lock_file = "/usr/local/etc/freeside/selfservice.$machine.writelock";
open(LOCKFILE,">$lock_file") or die "can't open $lock_file: $!";

&init($user);

my $conf = new FS::Conf;

my $clientd = "/usr/local/sbin/freeside-selfservice-clientd"; #better name?

my $warnkids=0;
while (1) {
  my($writer,$reader,$error) = (new IO::Handle, new IO::Handle, new IO::Handle);
  warn "connecting to $machine\n" if $Debug;

  $ssh_pid = sshopen2($machine,$reader,$writer,$clientd,$tag);

#  nstore_fd(\*writer, {'hi'=>'there'});

  warn "entering main loop\n" if $Debug;
  my $undisp = 0;
  my $keepalive_count = 0;
  my $s = IO::Select->new( $reader );
  while (1) {

    &reap_kids;

    warn "waiting for packet from client\n" if $Debug && !$undisp;
    $undisp = 1;
    my @handles = $s->can_read(5);
    unless ( @handles ) {
      &shutdown if $shutdown;
      if ( $keepalives && $keepalive_count++ > 10 ) {
        $keepalive_count = 0;
        nstore_fd( { _token => '_keepalive' }, $writer );
      }
      next;
    }

    $undisp = 0;

    warn "receiving packet from client\n" if $Debug;

    my $packet = eval { fd_retrieve($reader); };
    if ( $@ ) {
      warn "Storable error receiving packet from client".
           " (assuming lost connection): $@\n"
        if $Debug;
      if ( $ssh_pid ) {
        warn "sending TERM signal to ssh process $ssh_pid\n" if $Debug;
        kill 'TERM', $ssh_pid;
        $ssh_pid = 0;
      }
      last;
    }
    warn "packet received\n".
         join('', map { " $_=>$packet->{$_}\n" } keys %$packet )
      if $Debug > 1;

    if ( $packet->{_packet} eq '_enable_keepalive' ) {
      warn "enabling keep alives\n" if $Debug;
      $keepalives=1;
      next;
    }

    #prevent runaway forking
    my $warnkids = 0;
    while ( $kids >= $max_kids ) {
      warn "WARNING: maximum $kids children reached\n" unless $warnkids++;
      &reap_kids;
      sleep 1;
    }

    warn "forking child\n" if $Debug;
    defined( my $pid = fork ) or die "can't fork: $!";
    if ( $pid ) {
      $kids++;
      $kids{$pid} = 1;
      warn "child $pid spawned\n" if $Debug;
    } else { #kid time

      ##get new db handle
      #$FS::UID::dbh->{InactiveDestroy} = 1;
      #forksuidsetup($user);

      #get db handle
      adminsuidsetup($user);

      my $type = $packet->{_packet};
      warn "calling $type handler\n" if $Debug; 
      my $rv = eval { FS::ClientAPI->dispatch($type, $packet); };
      if ( $@ ) {
        warn my $error = "WARNING: error dispatching $type: $@";
        $rv = { _error => $error };
      }
      $rv->{_token} = $packet->{_token}; #identifier

      warn "sending response\n" if $Debug;
      lock_write;
      nstore_fd($rv, $writer) or die "FATAL: can't send response: $!";
      $writer->flush or die "FATAL: can't flush: $!";
      unlock_write;

      warn "child exiting\n" if $Debug;
      exit; #end-of-kid
    }

  }

  warn "connection lost, reconnecting\n" if $Debug;
  sleep 3;

}

###
# utility subroutines
###

sub reap_kids {
  #warn "reaping kids\n";
  foreach my $pid ( keys %kids ) {
    my $kid = waitpid($pid, WNOHANG);
    if ( $kid > 0 ) {
      $kids--;
      delete $kids{$kid};
    }
  }
  #warn "done reaping\n";
}

sub init {
  my $user = shift;

  chdir "/" or die "Can't chdir to /: $!";
  open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
  defined(my $pid = fork) or die "Can't fork: $!";
  if ( $pid ) {
    print "freeside-selfservice-server to $machine started with pid $pid\n"; #logging to $log_file
    exit unless $pid_file;
    my $pidfh = new IO::File ">$pid_file" or exit;
    print $pidfh "$pid\n";
    exit;
  }

#  sub REAPER { my $pid = wait; $SIG{CHLD} = \&REAPER; $kids--; }
#  #sub REAPER { my $pid = wait; $kids--; $SIG{CHLD} = \&REAPER; }
#  $SIG{CHLD} =  \&REAPER;

  $shutdown = 0;
  $SIG{HUP} = sub { warn "SIGHUP received; shutting down\n"; $shutdown++; };
  $SIG{INT} = sub { warn "SIGINT received; shutting down\n"; $shutdown++; };
  $SIG{TERM} = sub { warn "SIGTERM received; shutting down\n"; $shutdown++; };
  $SIG{QUIT} = sub { warn "SIGQUIT received; shutting down\n"; $shutdown++; };
  $SIG{PIPE} = sub { warn "SIGPIPE received; shutting down\n"; $shutdown++; };

  #false laziness w/freeside-queued
  my $freeside_gid = scalar(getgrnam('freeside'))
    or die "can't setgid to freeside group\n";
  $) = $freeside_gid;
  $( = $freeside_gid;
  #if freebsd can't setuid(), presumably it can't setgid() either.  grr fleabsd
  ($(,$)) = ($),$();
  $) = $freeside_gid;

  $> = $FS::UID::freeside_uid;
  $< = $FS::UID::freeside_uid;
  #freebsd is sofa king broken, won't setuid()
  ($<,$>) = ($>,$<);
  $> = $FS::UID::freeside_uid;
  #eslaf

  $ENV{HOME} = (getpwuid($>))[7]; #for ssh
  #adminsuidsetup $user;

  #$log_file = "/usr/local/etc/freeside/selfservice.". $FS::UID::datasrc; #MACHINE NAME
  $log_file = "/usr/local/etc/freeside/selfservice.$machine.log";

  open STDOUT, '>/dev/null'
                            or die "Can't write to /dev/null: $!";
  setsid                  or die "Can't start a new session: $!";
  open STDERR, '>&STDOUT' or die "Can't dup stdout: $!";

  $SIG{__DIE__} = \&_die;
  $SIG{__WARN__} = \&_logmsg;

  warn "freeside-selfservice-server starting\n";

}

sub shutdown {
  my $wait = 12; #wait up to 1 minute
  while ( $kids > 0 && $wait-- ) {
    warn "waiting for $kids children to terminate";
    sleep 5;
  }
  warn "abandoning $kids children" if $kids;
  kill 'TERM', $ssh_pid if $ssh_pid;
  die "exiting";
}

sub _die {
  my $msg = shift;
  unlink $pid_file if -e $pid_file;
  _logmsg($msg);
}

sub _logmsg {
  chomp( my $msg = shift );
  _do_logmsg( "[server] [". scalar(localtime). "] [$$] $msg\n" );
}

sub _do_logmsg {
  chomp( my $msg = shift );
  my $log = new IO::File ">>$log_file";
  flock($log, LOCK_EX);
  seek($log, 0, 2);
  print $log "$msg\n";
  flock($log, LOCK_UN);
  close $log;
}

sub lock_write {
  #broken on freebsd?
  #flock($writer, LOCK_EX) or die "FATAL: can't lock write stream: $!";

  flock(LOCKFILE, LOCK_EX) or die "FATAL: can't lock $lock_file: $!";

}

sub unlock_write {
  #broken on freebsd?
  #flock($writer, LOCK_UN) or die "WARNING: can't release write lock: $!";

  flock(LOCKFILE, LOCK_UN) or die "FATAL: can't unlock $lock_file: $!";

}

sub usage {
  die "Usage:\n\n  freeside-selfservice-server user machine\n";
}