summaryrefslogtreecommitdiff
path: root/fs_selfservice/freeside-selfservice-server
blob: 0e1c75e43c2f43f2ff4064e3b2f5310cbdfb1253 (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
283
284
#!/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 );
use Fcntl qw(:flock);
use POSIX qw(:sys_wait_h setsid);
use IO::Handle;
use IO::Select;
use IO::File;
use Storable qw(nstore_fd fd_retrieve);
use Net::SSH qw(sshopen2);

use FS::UID qw(adminsuidsetup forksuidsetup);

#use Tie::RefHash;
#use FS::Conf;
#use FS::Record qw( qsearch qsearchs );
#use FS::cust_main_county;
#use FS::cust_main;
#use FS::Msgcat qw(gettext);

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

$shutdown = 0;
$max_kids = '10'; #?
$kids = 0;

my $user = shift or die &usage;
my $machine = shift or die &usage;
my $pid_file = "/var/run/freeside-selfservice-server.$user.pid";
#my $pid_file = "/var/run/freeside-selfservice-server.$user.pid"; $FS::UID::datasrc not posible, but should include machine name at least, hmm

&init($user);

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

my %dispatch = (
  'signup' => \&signup,
  #'signup_init' => 'signup_init',
  'passwd' => \&passwd,

);

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);

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

  warn "entering main loop\n" if $Debug;
  my $undisp = 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;
      next;
    }

    $undisp = 0;

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

    my $packet = fd_retrieve($reader);
    warn "packet received\n".
         join('', map { " $_=>$packet->{$_}\n" } keys %$packet )
      if $Debug > 1;

    #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);

      my $sub = $dispatch{$packet->{_packet}};
      my $rv;
      if ( $sub ) {
        warn "calling $sub handler\n" if $Debug; 
        $rv = &{$sub}($packet);
      } else {
        warn my $error = "WARNING: unknown packet type ". $packet->{_packet};
        $rv = { _error => $error };
      }
      $rv->{_token} = $packet->{_token}; #identifier

      warn "sending response\n" if $Debug;
      flock($writer, LOCK_EX) or die "FATAL: can't lock write stream: $!";
      nstore_fd($rv, $writer) or die "FATAL: can't send response: $!";
      $writer->flush or die "FATAL: can't flush: $!";
      flock($writer, LOCK_UN) or die "WARNING: can't release write lock: $!";

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

  }

}

###
# dispatch subroutines (should live elsewhere eventually)
###

sub passwd {
  #sleep 3;
  use FS::Record qw(qsearchs);
  use FS::svc_acct;
  #use FS::svc_domain;

  my $packet = shift;

  #my $domain = qsearchs('svc_domain', { 'domain' => $packet->{'domain'} } )
  #  or return { error => "Domain $domain not found" };

  my $old_password = $packet->{'old_password'};
  my $new_password = $packet->{'new_password'};
  my $new_gecos = $packet->{'new_gecos'};
  my $new_shell = $packet->{'new_shell'};

  my $svc_acct =
    ( length($old_password) < 13
      && qsearchs( 'svc_acct', { 'username'  => $packet->{'username'},
                                 #'domsvc'    => $svc_domain->domsvc,
                                 '_password' => $old_password } )
    )
    || qsearchs( 'svc_acct', { 'username'  => $packet->{'username'},
                               #'domsvc'    => $svc_domain->domsvc,
                               '_password' => $old_password } );

  unless ( $svc_acct ) { return { error => 'Incorrect password.' } }

  my %hash = $svc_acct->hash;
  my $new_svc_acct = new FS::svc_acct ( \%hash );
  $new_svc_acct->setfield('_password', $new_password ) 
    if $new_password && $new_password ne $old_password;
  $new_svc_acct->setfield('finger',$new_gecos) if $new_gecos;
  $new_svc_acct->setfield('shell',$new_shell) if $new_shell;
  my $error = $new_svc_acct->replace($svc_acct);

  return { error => $error };

}

###
# 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 usage {
  die "Usage:\n\n  fs_signup_server user machine\n";
}