1 # Copyright (C) 2015-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # contains common daemon code for the nntpd and httpd servers.
4 # This may be used for read-only IMAP server if we decide to implement it.
5 package PublicInbox::Daemon;
8 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
9 use IO::Handle; # ->autoflush
11 use POSIX qw(WNOHANG :signal_h);
12 use Socket qw(IPPROTO_TCP SOL_SOCKET);
13 sub SO_ACCEPTFILTER () { 0x1000 }
17 use PublicInbox::DS qw(now);
18 use PublicInbox::Syscall qw(SFD_NONBLOCK);
19 require PublicInbox::Listener;
20 require PublicInbox::ParentPipe;
21 require PublicInbox::Sigfd;
23 my ($set_user, $oldset, $newset);
24 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
25 my $worker_processes = 1;
28 my %tls_opt; # scheme://sockname => args for IO::Socket::SSL->start_SSL
31 my ($default_cert, $default_key);
32 my %KNOWN_TLS = ( 443 => 'https', 563 => 'nntps' );
33 my %KNOWN_STARTTLS = ( 119 => 'nntp' );
35 sub accept_tls_opt ($) {
37 # opt_str: opt1=val1,opt2=val2 (opt may repeat for multi-value)
38 require PublicInbox::TLS;
40 # allow ',' as delimiter since '&' is shell-unfriendly
41 foreach (split(/[,&]/, $opt_str)) {
42 my ($k, $v) = split(/=/, $_, 2);
43 push @{$o->{$k} ||= []}, $v;
46 # key may be a part of cert. At least
47 # p5-io-socket-ssl/example/ssl_server.pl has this fallback:
48 $o->{cert} //= [ $default_cert ];
49 $o->{key} //= defined($default_key) ? [ $default_key ] : $o->{cert};
50 my %ctx_opt = (SSL_server => 1);
51 # parse out hostname:/path/to/ mappings:
52 foreach my $k (qw(cert key)) {
53 my $x = $ctx_opt{'SSL_'.$k.'_file'} = {};
54 foreach my $path (@{$o->{$k}}) {
56 $path =~ s/\A([^:]+):// and $host = $1;
60 my $ctx = IO::Socket::SSL::SSL_Context->new(%ctx_opt) or
61 die 'SSL_Context->new: '.PublicInbox::TLS::err();
63 # save ~34K per idle connection (cf. SSL_CTX_set_mode(3ssl))
64 # RSS goes from 346MB to 171MB with 10K idle NNTPS clients on amd64
65 # cf. https://rt.cpan.org/Ticket/Display.html?id=129463
66 my $mode = eval { Net::SSLeay::MODE_RELEASE_BUFFERS() };
67 if ($mode && $ctx->{context}) {
68 eval { Net::SSLeay::CTX_set_mode($ctx->{context}, $mode) };
69 warn "W: $@ (setting SSL_MODE_RELEASE_BUFFERS)\n" if $@;
72 { SSL_server => 1, SSL_startHandshake => 0, SSL_reuse_ctx => $ctx };
75 sub sig_setmask { sigprocmask(SIG_SETMASK, @_) or die "sigprocmask: $!" }
77 sub daemon_prepare ($) {
78 my ($default_listen) = @_;
79 my $listener_names = {}; # sockname => IO::Handle
80 $oldset = POSIX::SigSet->new();
81 $newset = POSIX::SigSet->new();
82 $newset->fillset or die "fillset: $!";
83 sig_setmask($newset, $oldset);
86 'l|listen=s' => \@cfg_listen,
87 '1|stdout=s' => \$stdout,
88 '2|stderr=s' => \$stderr,
89 'W|worker-processes=i' => \$worker_processes,
90 'P|pid-file=s' => \$pid_file,
92 'g|group=s' => \$group,
93 'D|daemonize' => \$daemonize,
94 'cert=s' => \$default_cert,
95 'key=s' => \$default_key,
97 GetOptions(%opts) or die "bad command-line args\n";
99 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
100 die "--pid-file cannot end with '.oldbin'\n";
102 @listeners = inherit($listener_names);
104 # allow socket-activation users to set certs once and not
105 # have to configure each socket:
106 my @inherited_names = keys(%$listener_names) if defined($default_cert);
108 # ignore daemonize when inheriting
109 $daemonize = undef if scalar @listeners;
111 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
113 foreach my $l (@cfg_listen) {
116 if ($l =~ s!\A([^:]+)://!!) {
118 } elsif ($l =~ /\A(?:\[[^\]]+\]|[^:]+):([0-9])+/) {
119 my $s = $KNOWN_TLS{$1} // $KNOWN_STARTTLS{$1};
120 $scheme = $s if defined $s;
122 if ($l =~ s!/?\?(.+)\z!!) {
123 $tls_opt{"$scheme://$l"} = accept_tls_opt($1);
124 } elsif (defined($default_cert)) {
125 $tls_opt{"$scheme://$l"} = accept_tls_opt('');
126 } elsif ($scheme =~ /\A(?:nntps|https)\z/) {
127 die "$orig specified w/o cert=\n";
129 # TODO: use scheme to load either NNTP.pm or HTTP.pm
131 next if $listener_names->{$l}; # already inherited
133 if (index($l, '/') == 0) {
134 $sock_pkg = 'IO::Socket::UNIX';
135 eval "use $sock_pkg";
137 %o = (Type => SOCK_STREAM, Peer => $l);
139 my $c = $sock_pkg->new(%o);
140 if (!defined($c) && $!{ECONNREFUSED}) {
142 "failed to unlink stale socket=$l: $!\n";
143 } # else: let the bind fail
145 $o{Local} = delete $o{Peer};
147 # both work for IPv4, too
148 for (qw(IO::Socket::IP IO::Socket::INET6)) {
150 eval "use $sock_pkg";
154 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
157 my $prev = umask 0000;
158 my $s = eval { $sock_pkg->new(%o) };
159 warn "error binding $l: $! ($@)\n" unless $s;
162 $listener_names->{sockname($s)} = $s;
168 # cert/key options in @cfg_listen takes precedence when inheriting,
169 # but map well-known inherited ports if --listen isn't specified
171 for my $sockname (@inherited_names) {
172 $sockname =~ /:([0-9]+)\z/ or next;
173 if (my $scheme = $KNOWN_TLS{$1}) {
174 $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt('');
175 } elsif (($scheme = $KNOWN_STARTTLS{$1})) {
176 next if $tls_opt{"$scheme://$sockname"};
177 $tls_opt{''} ||= accept_tls_opt('');
181 die "No listeners bound\n" unless @listeners;
184 sub check_absolute ($$) {
185 my ($var, $val) = @_;
186 if (defined $val && index($val, '/') != 0) {
188 "--$var must be an absolute path when using --daemonize: $val\n";
194 foreach my $i (0..$#ARGV) {
197 $ARGV[$i] = abs_path($arg);
199 check_absolute('stdout', $stdout);
200 check_absolute('stderr', $stderr);
201 check_absolute('pid-file', $pid_file);
203 chdir '/' or die "chdir failed: $!";
206 return unless (defined $pid_file || defined $group || defined $user
209 eval { require Net::Server::Daemonize };
212 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
215 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
216 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
217 if (defined $group) {
218 $gid = Net::Server::Daemonize::get_gid($group);
219 $gid = (split /\s+/, $gid)[0];
220 } elsif (defined $uid) {
221 $gid = (getpwuid($uid))[3];
224 # We change users in the worker to ensure upgradability,
225 # The upgrade will create the ".oldbin" pid file in the
226 # same directory as the given pid file.
227 $uid and $set_user = sub {
229 Net::Server::Daemonize::set_user($uid, $gid);
234 die "could not fork: $!\n" unless defined $pid;
237 open(STDIN, '+<', '/dev/null') or
238 die "redirect stdin failed: $!\n";
239 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
240 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
243 die "could not fork: $!\n" unless defined $pid;
246 return unless defined $pid_file;
248 write_pid($pid_file);
250 bless { pid => $$, pid_file => \$pid_file }, __PACKAGE__;
253 sub worker_quit { # $_[0] = signal name or number (unused)
254 # killing again terminates immediately:
255 exit unless @listeners;
257 $_->close foreach @listeners; # call PublicInbox::DS::close
261 # drop idle connections and try to quit gracefully
262 PublicInbox::DS->SetPostLoopCallback(sub {
263 my ($dmap, undef) = @_;
267 foreach my $s (values %$dmap) {
268 $s->can('busy') or next;
269 if ($s->busy($now)) {
272 # close as much as possible, early as possible
277 if (($warn + 5) < now()) {
278 warn "$$ quitting, $n client(s) left\n";
281 unless (defined $proc_name) {
282 $proc_name = (split(/\s+/, $0))[0];
283 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
285 $0 = "$proc_name quitting, $n client(s) left";
287 $n; # true: loop continues, false: loop breaks
293 open STDOUT, '>>', $stdout or
294 warn "failed to redirect stdout to $stdout: $!\n";
295 STDOUT->autoflush(1);
299 open STDERR, '>>', $stderr or
300 warn "failed to redirect stderr to $stderr: $!\n";
301 STDERR->autoflush(1);
308 my $addr = getsockname($s) or return;
309 my ($host, $port) = host_with_port($addr);
310 if ($port == 0 && $host eq '127.0.0.1') {
311 my ($path) = Socket::sockaddr_un($addr);
317 sub unpack_ipv6 ($) {
321 # Socket.pm in Perl 5.14+ supports IPv6:
323 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
324 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
328 # Perl 5.12 or earlier? SpamAssassin and Net::Server use
329 # Socket6, so it may be installed on our system, already
330 # (otherwise die here):
333 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
334 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
339 sub host_with_port ($) {
343 # this eval will die on Unix sockets:
345 if (length($addr) >= 28) {
346 ($host, $port) = unpack_ipv6($addr);
349 ($port, $host) = Socket::sockaddr_in($addr);
350 $host = Socket::inet_ntoa($host);
353 $@ ? ('127.0.0.1', 0) : ($host, $port);
357 my ($listener_names) = @_;
358 return () if ($ENV{LISTEN_PID} || 0) != $$;
359 my $fds = $ENV{LISTEN_FDS} or return ();
360 my $end = $fds + 2; # LISTEN_FDS_START - 1
362 foreach my $fd (3..$end) {
363 my $s = IO::Handle->new_from_fd($fd, 'r');
364 if (my $k = sockname($s)) {
368 Inherited socket (fd=$fd) is blocking, making it non-blocking.
369 Set 'NonBlocking = true' in the systemd.service unit to avoid stalled
370 processes when multiple service instances start.
373 $listener_names->{$k} = $s;
376 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
382 sub upgrade { # $_[0] = signal name or number (unused)
384 warn "upgrade in-progress: $reexec_pid\n";
387 if (defined $pid_file) {
388 if ($pid_file =~ /\.oldbin\z/) {
389 warn "BUG: .oldbin suffix exists: $pid_file\n";
392 unlink_pid_file_safe_ish($$, $pid_file);
393 $pid_file .= '.oldbin';
394 write_pid($pid_file);
397 unless (defined $pid) {
398 warn "fork failed: $!\n";
402 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
403 $ENV{LISTEN_FDS} = scalar @listeners;
404 $ENV{LISTEN_PID} = $$;
405 foreach my $s (@listeners) {
406 # @listeners are globs with workers, PI::L w/o workers
407 $s = $s->{sock} if ref($s) eq 'PublicInbox::Listener';
409 my $fl = fcntl($s, F_GETFD, 0);
410 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
413 die "Failed to exec: $!\n";
418 sub kill_workers ($) {
421 while (my ($pid, $id) = each %pids) {
426 sub upgrade_aborted ($) {
428 warn "reexec PID($p) died with: $?\n";
430 return unless $pid_file;
432 my $file = $pid_file;
433 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
434 unlink_pid_file_safe_ish($$, $pid_file);
436 eval { write_pid($pid_file) };
440 sub reap_children { # $_[0] = 'CHLD' or POSIX::SIGCHLD()
442 my $p = waitpid(-1, WNOHANG) or return;
443 if (defined $reexec_pid && $p == $reexec_pid) {
445 } elsif (defined(my $id = delete $pids{$p})) {
446 warn "worker[$id] PID($p) died with: $?\n";
448 warn "unknown PID($p) reaped: $?\n";
455 sub unlink_pid_file_safe_ish ($$) {
456 my ($unlink_pid, $file) = @_;
457 return unless defined $unlink_pid && $unlink_pid == $$;
459 open my $fh, '<', $file or return;
461 defined(my $read_pid = <$fh>) or return;
463 if ($read_pid == $unlink_pid) {
464 Net::Server::Daemonize::unlink_pid_file($file);
468 sub master_quit ($) {
469 exit unless @listeners;
475 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
476 # 1031: F_SETPIPE_SZ, 4096: page size
477 fcntl($p1, 1031, 4096) if $^O eq 'linux';
478 my $set_workers = $worker_processes;
482 USR1 => sub { reopen_logs(); kill_workers($_[0]); },
484 QUIT => \&master_quit,
485 INT => \&master_quit,
486 TERM => \&master_quit,
488 return if $ignore_winch || !@listeners;
489 if (-t STDIN || -t STDOUT || -t STDERR) {
492 ignoring SIGWINCH since we are not daemonized
495 $worker_processes = 0;
499 return unless @listeners;
500 $worker_processes = $set_workers;
504 return unless @listeners;
505 if ($set_workers > $worker_processes) {
508 $worker_processes = ++$set_workers;
512 $worker_processes = --$set_workers if $set_workers > 0;
514 CHLD => \&reap_children,
516 my $sigfd = PublicInbox::Sigfd->new($sig, 0);
517 local %SIG = (%SIG, %$sig) if !$sigfd;
518 sig_setmask($oldset) if !$sigfd;
519 while (1) { # main loop
520 my $n = scalar keys %pids;
521 unless (@listeners) {
523 $set_workers = $worker_processes = $n = 0;
526 if ($n > $worker_processes) {
527 while (my ($k, $v) = each %pids) {
528 kill('TERM', $k) if $v >= $worker_processes;
530 $n = $worker_processes;
532 my $want = $worker_processes - 1;
534 sig_setmask($newset) if !$sigfd;
535 for my $i ($n..$want) {
538 warn "failed to fork worker[$i]: $!\n";
539 } elsif ($pid == 0) {
540 $set_user->() if $set_user;
541 return $p0; # run normal work code
543 warn "PID=$pid is worker[$i]\n";
547 sig_setmask($oldset) if !$sigfd;
550 if ($sigfd) { # Linux and IO::KQueue users:
552 } else { # wake up every second
556 exit # never gets here, just for documentation
559 sub tls_start_cb ($$) {
560 my ($opt, $orig_post_accept) = @_;
562 my ($io, $addr, $srv) = @_;
563 my $ssl = IO::Socket::SSL->start_SSL($io, %$opt);
564 $orig_post_accept->($ssl, $addr, $srv);
568 sub defer_accept ($$) {
569 my ($s, $af_name) = @_;
570 return unless defined $af_name;
571 if ($^O eq 'linux') {
572 my $TCP_DEFER_ACCEPT = 9; # Socket::TCP_DEFER_ACCEPT is in 5.14+
573 my $x = getsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT);
574 return unless defined $x; # may be Unix socket
575 my $sec = unpack('i', $x);
576 return if $sec > 0; # systemd users may set a higher value
577 setsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 1);
578 } elsif ($^O eq 'freebsd') {
579 my $x = getsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER);
580 return if defined $x; # don't change if set
581 my $accf_arg = pack('a16a240', $af_name, '');
582 setsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER, $accf_arg);
586 sub daemon_loop ($$$$) {
587 my ($refresh, $post_accept, $nntpd, $af_default) = @_;
589 while (my ($k, $v) = each %tls_opt) {
590 if ($k =~ s!\A(?:nntps|https)://!!) {
591 $post_accept{$k} = tls_start_cb($v, $post_accept);
592 } elsif ($nntpd) { # STARTTLS, $k eq '' is OK
593 $nntpd->{accept_tls} = $v;
598 INT => \&worker_quit,
599 QUIT => \&worker_quit,
600 TERM => \&worker_quit,
603 USR1 => \&reopen_logs,
606 CHLD => \&PublicInbox::DS::enqueue_reap,
608 if ($worker_processes > 0) {
609 $refresh->(); # preload by default
610 my $fh = master_loop(); # returns if in child process
611 PublicInbox::ParentPipe->new($fh, \&worker_quit);
614 $set_user->() if $set_user;
615 $sig->{USR2} = sub { worker_quit() if upgrade() };
621 my $tls_cb = $post_accept{sockname($_)};
623 # NNTPS, HTTPS, HTTP, and POP3S are client-first traffic
624 # NNTP and POP3 are server-first
625 defer_accept($_, $tls_cb ? 'dataready' : $af_default);
627 # this calls epoll_create:
628 PublicInbox::Listener->new($_, $tls_cb || $post_accept)
630 my $sigfd = PublicInbox::Sigfd->new($sig, SFD_NONBLOCK);
631 local %SIG = (%SIG, %$sig) if !$sigfd;
633 # wake up every second to accept signals if we don't
634 # have signalfd or IO::KQueue:
635 sig_setmask($oldset);
636 PublicInbox::DS->SetLoopTimeout(1000);
638 PublicInbox::DS->EventLoop;
642 my ($default, $refresh, $post_accept, $nntpd) = @_;
643 local $SIG{PIPE} = 'IGNORE';
644 daemon_prepare($default);
645 my $af_default = $default =~ /:8080\z/ ? 'httpready' : undef;
646 my $for_destroy = daemonize();
647 daemon_loop($refresh, $post_accept, $nntpd, $af_default);
648 PublicInbox::DS->Reset;
649 # ->DESTROY runs when $for_destroy goes out-of-scope
654 if (defined $uid and !chown($uid, $gid, $path)) {
655 warn "could not chown $path: $!\n";
661 Net::Server::Daemonize::create_pid_file($path);
666 unlink_pid_file_safe_ish($_[0]->{pid}, ${$_[0]->{pid_file}});