2 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
3 # License: AGPLv3 or later (https://www.gnu.org/licenses/agpl-3.0.txt)
9 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
10 require PublicInbox::NewsGroup;
12 my $nntpd = PublicInbox::NNTPD->new;
13 my $refresh = sub { $nntpd->refresh_groups };
14 $SIG{HUP} = $SIG{USR1} = $SIG{USR2} = $SIG{PIPE} =
15 $SIG{TTIN} = $SIG{TTOU} = $SIG{WINCH} = 'IGNORE';
18 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
19 my $worker_processes = 0;
21 'l|listen=s' => \@cfg_listen,
22 '1|stdout=s' => \$stdout,
23 '2|stderr=s' => \$stderr,
24 'W|worker-processes=i' => \$worker_processes,
25 'P|pid-file=s' => \$pid_file,
27 'g|group=s' => \$group,
28 'D|daemonize' => \$daemonize,
30 GetOptions(%opts) or die "bad command-line args\n";
32 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
33 die "--pid-file cannot end with '.oldbin'\n";
39 my @listeners = inherit();
41 # ignore daemonize when inheriting
42 $daemonize = undef if scalar @listeners;
44 # default NNTP listener if no listeners
45 push @cfg_listen, '0.0.0.0:119' unless (@listeners || @cfg_listen);
47 foreach my $l (@cfg_listen) {
48 next if $listener_names{$l}; # already inherited
49 require IO::Socket::INET6; # works for IPv4, too
55 if (my $s = IO::Socket::INET6->new(%o)) {
56 $listener_names{sockname($s)} = $s;
59 warn "error binding $l: $!\n";
62 die 'No listeners bound' unless @listeners;
64 chdir '/' or die "chdir failed: $!\n";
65 open(STDIN, '+<', '/dev/null') or die "redirect stdin failed: $!\n";
67 if (defined $pid_file || defined $group || defined $user || $daemonize) {
68 require Net::Server::Daemonize;
70 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
71 my $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
74 $gid = Net::Server::Daemonize::get_gid($group);
75 $gid = (split /\s+/, $gid)[0];
76 } elsif (defined $uid) {
77 $gid = (getpwuid($uid))[3];
80 # We change users in the worker to ensure upgradability,
81 # The upgrade will create the ".oldbin" pid file in the
82 # same directory as the given pid file.
83 $uid and $set_user = sub {
84 Net::Server::Daemonize::set_user($uid, $gid);
88 my ($pid, $err) = do_fork();
89 die "could not fork: $err\n" unless defined $pid;
92 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
93 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
95 ($pid, $err) = do_fork();
96 die "could not fork: $err\n" unless defined $pid;
99 if (defined $pid_file) {
101 Net::Server::Daemonize::create_pid_file($pid_file);
102 if ($uid and !chown($uid, $gid, $pid_file)) {
103 warn "could not chown $pid_file: $!\n";
105 END { unlink_pid_file_safe_ish($unlink_pid, $pid_file) };
109 if ($worker_processes > 0) {
110 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!\n";
111 my %pwatch = ( fileno($p0) => sub { kill('TERM', $$) } );
112 pipe(my ($r, $w)) or die "failed to create self-pipe: $!\n";
113 IO::Handle::blocking($w, 0);
114 my $set_workers = $worker_processes;
117 foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
119 return if $$ != $master_pid;
127 while (my $s = shift @caught) {
131 } elsif ($s eq 'USR2') {
133 } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
134 # drops pipes and causes children to die
136 } elsif ($s eq 'WINCH') {
137 $worker_processes = 0;
138 } elsif ($s eq 'HUP') {
139 $worker_processes = $set_workers;
142 } elsif ($s eq 'TTIN') {
143 if ($set_workers > $worker_processes) {
146 $worker_processes = ++$set_workers;
148 } elsif ($s eq 'TTOU') {
149 if ($set_workers > 0) {
150 $worker_processes = --$set_workers;
152 } elsif ($s eq 'CHLD') {
157 my $n = scalar keys %pids;
158 if ($n > $worker_processes) {
159 while (my ($k, $v) = each %pids) {
160 kill('TERM', $k) if $v >= $worker_processes;
162 $n = $worker_processes;
164 foreach my $i ($n..($worker_processes - 1)) {
165 my ($pid, $err) = do_fork();
167 warn "failed to fork worker[$i]: $err\n";
168 } elsif ($pid == 0) {
169 $set_user->() if $set_user;
170 close($_) for ($w, $r, $p1);
171 Danga::Socket->AddOtherFds(%pwatch);
174 warn "PID=$pid is worker[$i]\n";
178 sysread($r, my $buf, 8);
181 $set_user->() if $set_user;
182 $SIG{USR2} = sub { worker_quit() if upgrade() };
184 # this calls epoll_create:
186 $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = *worker_quit;
187 $SIG{USR1} = *reopen_logs;
188 $SIG{HUP} = $refresh;
189 PublicInbox::Listener->new($_) for @listeners;
190 Danga::Socket->EventLoop;
196 # killing again terminates immediately:
197 exit unless @listeners;
201 # give slow clients 30s to finish reading/writing whatever
202 Danga::Socket->AddTimer(30, sub { exit });
204 # drop idle connections and try to quit gracefully
205 Danga::Socket->SetPostLoopCallback(sub {
206 my ($dmap, undef) = @_;
209 foreach my $s (values %$dmap) {
210 if ($s->can('busy') && $s->busy) {
216 $n; # true: loop continues, false: loop breaks
222 open STDOUT, '>>', $stdout or
223 warn "failed to redirect stdout to $stdout: $!\n";
226 open STDERR, '>>', $stderr or
227 warn "failed to redirect stderr to $stderr: $!\n";
233 my $n = getsockname($s) or return;
235 if (length($n) >= 28) {
237 ($port, $addr) = Socket6::unpack_sockaddr_in6($n);
239 ($port, $addr) = Socket::sockaddr_in($n);
241 if (length($addr) == 4) {
242 $n = Socket::inet_ntoa($addr)
244 $n = '['.Socket6::inet_ntop(Socket6::AF_INET6(), $addr).']';
250 return () if ($ENV{LISTEN_PID} || 0) != $$;
251 my $fds = $ENV{LISTEN_FDS} or return ();
252 my $end = $fds + 2; # LISTEN_FDS_START - 1
254 foreach my $fd (3..$end) {
255 my $s = IO::Handle->new;
256 $s->fdopen($fd, 'r');
257 if (my $k = sockname($s)) {
258 $listener_names{$k} = $s;
261 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
269 warn "upgrade in-progress: $reexec_pid\n";
272 if (defined $pid_file) {
273 if ($pid_file =~ /\.oldbin\z/) {
274 warn "BUG: .oldbin suffix exists: $pid_file\n";
277 unlink_pid_file_safe_ish($$, $pid_file);
278 $pid_file .= '.oldbin';
279 Net::Server::Daemonize::create_pid_file($pid_file);
281 my ($pid, $err) = do_fork();
282 unless (defined $pid) {
283 warn "fork failed: $err\n";
287 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
288 $ENV{LISTEN_FDS} = scalar @listeners;
289 $ENV{LISTEN_PID} = $$;
290 foreach my $s (@listeners) {
291 my $fl = fcntl($s, F_GETFD, 0);
292 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
295 die "Failed to exec: $!\n";
303 while (my ($pid, $id) = each %pids) {
310 my $new = POSIX::SigSet->new;
312 my $old = POSIX::SigSet->new;
313 POSIX::sigprocmask(&POSIX::SIG_BLOCK, $new, $old) or
314 die "SIG_BLOCK: $!\n";
317 POSIX::sigprocmask(&POSIX::SIG_SETMASK, $old) or
318 die "SIG_SETMASK: $!\n";
322 sub upgrade_aborted ($) {
324 warn "reexec PID($p) died with: $?\n";
326 return unless $pid_file;
328 my $file = $pid_file;
329 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file\n";
330 unlink_pid_file_safe_ish($$, $pid_file);
332 eval { Net::Server::Daemonize::create_pid_file($pid_file) };
338 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
339 if (defined $reexec_pid && $p == $reexec_pid) {
341 } elsif (defined(my $id = delete $pids{$p})) {
342 warn "worker[$id] PID($p) died with: $?\n";
344 warn "unknown PID($p) reaped: $?\n";
351 sub unlink_pid_file_safe_ish ($$) {
352 my ($unlink_pid, $file) = @_;
353 return unless defined $unlink_pid && $unlink_pid == $$;
355 open my $fh, '<', $file or return;
356 defined(my $read_pid = <$fh>) or return;
358 if ($read_pid == $unlink_pid) {
359 Net::Server::Daemonize::unlink_pid_file($file);
364 package PublicInbox::Listener;
367 use base 'Danga::Socket';
368 use Socket qw(SOL_SOCKET SO_KEEPALIVE IPPROTO_TCP TCP_NODELAY);
369 use PublicInbox::NNTP;
372 my ($class, $s) = @_;
373 setsockopt($s, SOL_SOCKET, SO_KEEPALIVE, 1);
374 setsockopt($s, IPPROTO_TCP, TCP_NODELAY, 1);
376 IO::Handle::blocking($s, 0);
377 my $self = fields::new($class);
378 $self->SUPER::new($s); # calls epoll_create for the first socket
379 $self->watch_read(1);
385 # no loop here, we want to fairly distribute clients
386 # between multiple processes sharing the same socket
387 if (accept(my $c, $self->{sock})) {
388 IO::Handle::blocking($c, 0); # no accept4 :<
389 PublicInbox::NNTP->new($c, $nntpd);
394 package PublicInbox::NNTPD;
397 use fields qw(groups grouplist err out);
401 my $self = fields::new($class);
402 $self->{groups} = {};
403 $self->{err} = \*STDERR;
404 $self->{out} = \*STDOUT;
405 $self->{grouplist} = [];
411 require PublicInbox::Config;
412 my $pi_config = PublicInbox::Config->new;
415 foreach my $k (keys %$pi_config) {
416 $k =~ /\Apublicinbox\.([^\.]+)\.mainrepo\z/ or next;
418 my $git_dir = $pi_config->{$k};
419 my $addr = $pi_config->{"publicinbox.$g.address"};
420 my $ngname = $pi_config->{"publicinbox.$g.newsgroup"};
421 if (defined $ngname) {
422 next if ($ngname eq ''); # disabled
425 my $ng = PublicInbox::NewsGroup->new($g, $git_dir, $addr);
426 my $old_ng = $self->{groups}->{$g};
428 # Reuse the old one if possible since it can hold
429 # references to valid mm and gcf objects
431 $old_ng->update($ng);
435 # Only valid if Msgmap works
441 @list = sort { $a->{name} cmp $b->{name} } @list;
442 $self->{grouplist} = \@list;
443 # this will destroy old groups that got deleted
444 %{$self->{groups}} = %$new;