1 # Copyright (C) 2015-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Contains common daemon code for the httpd, imapd, and nntpd servers
5 # and designed for handling thousands of untrusted clients over slow
6 # and/or lossy connections.
7 package PublicInbox::Daemon;
10 use Getopt::Long qw(:config gnu_getopt no_ignore_case auto_abbrev);
11 use IO::Handle; # ->autoflush
13 use POSIX qw(WNOHANG :signal_h);
14 use Socket qw(IPPROTO_TCP SOL_SOCKET);
17 use PublicInbox::DS qw(now);
18 use PublicInbox::Listener;
19 use PublicInbox::EOFpipe;
20 use PublicInbox::Sigfd;
22 use PublicInbox::GitAsyncCat;
24 our $SO_ACCEPTFILTER = 0x1000;
26 my ($set_user, $oldset);
27 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
28 my $worker_processes = 1;
31 my %tls_opt; # scheme://sockname => args for IO::Socket::SSL->start_SSL
34 my ($default_cert, $default_key);
35 my %KNOWN_TLS = ( 443 => 'https', 563 => 'nntps', 993 => 'imaps' );
36 my %KNOWN_STARTTLS = ( 119 => 'nntp', 143 => 'imap' );
38 sub accept_tls_opt ($) {
40 # opt_str: opt1=val1,opt2=val2 (opt may repeat for multi-value)
41 require PublicInbox::TLS;
43 # allow ',' as delimiter since '&' is shell-unfriendly
44 foreach (split(/[,&]/, $opt_str)) {
45 my ($k, $v) = split(/=/, $_, 2);
46 push @{$o->{$k} ||= []}, $v;
49 # key may be a part of cert. At least
50 # p5-io-socket-ssl/example/ssl_server.pl has this fallback:
51 $o->{cert} //= [ $default_cert ];
52 $o->{key} //= defined($default_key) ? [ $default_key ] : $o->{cert};
53 my %ctx_opt = (SSL_server => 1);
54 # parse out hostname:/path/to/ mappings:
55 foreach my $k (qw(cert key)) {
56 my $x = $ctx_opt{'SSL_'.$k.'_file'} = {};
57 foreach my $path (@{$o->{$k}}) {
59 $path =~ s/\A([^:]+):// and $host = $1;
63 my $ctx = IO::Socket::SSL::SSL_Context->new(%ctx_opt) or
64 die 'SSL_Context->new: '.PublicInbox::TLS::err();
66 # save ~34K per idle connection (cf. SSL_CTX_set_mode(3ssl))
67 # RSS goes from 346MB to 171MB with 10K idle NNTPS clients on amd64
68 # cf. https://rt.cpan.org/Ticket/Display.html?id=129463
69 my $mode = eval { Net::SSLeay::MODE_RELEASE_BUFFERS() };
70 if ($mode && $ctx->{context}) {
71 eval { Net::SSLeay::CTX_set_mode($ctx->{context}, $mode) };
72 warn "W: $@ (setting SSL_MODE_RELEASE_BUFFERS)\n" if $@;
75 { SSL_server => 1, SSL_startHandshake => 0, SSL_reuse_ctx => $ctx };
78 sub daemon_prepare ($) {
79 my ($default_listen) = @_;
80 my $listener_names = {}; # sockname => IO::Handle
81 $oldset = PublicInbox::DS::block_signals();
83 my ($prog) = ($CMD[0] =~ m!([^/]+)\z!g);
85 usage: $prog [-l ADDRESS] [--cert=FILE] [--key=FILE]
89 -l ADDRESS address to listen on (default: $default_listen)
90 --cert=FILE default SSL/TLS certificate
91 --key=FILE default SSL/TLS certificate
92 -W WORKERS number of worker processes to spawn (default: 1)
94 See public-inbox-daemon(8) and $prog(1) man pages for more.
97 'l|listen=s' => \@cfg_listen,
98 '1|stdout=s' => \$stdout,
99 '2|stderr=s' => \$stderr,
100 'W|worker-processes=i' => \$worker_processes,
101 'P|pid-file=s' => \$pid_file,
102 'u|user=s' => \$user,
103 'g|group=s' => \$group,
104 'D|daemonize' => \$daemonize,
105 'cert=s' => \$default_cert,
106 'key=s' => \$default_key,
107 'help|h' => \(my $show_help),
109 GetOptions(%opt) or die $help;
110 if ($show_help) { print $help; exit 0 };
112 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
113 die "--pid-file cannot end with '.oldbin'\n";
115 @listeners = inherit($listener_names);
117 # allow socket-activation users to set certs once and not
118 # have to configure each socket:
119 my @inherited_names = keys(%$listener_names) if defined($default_cert);
121 # ignore daemonize when inheriting
122 $daemonize = undef if scalar @listeners;
124 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
126 foreach my $l (@cfg_listen) {
129 if ($l =~ s!\A([^:]+)://!!) {
131 } elsif ($l =~ /\A(?:\[[^\]]+\]|[^:]+):([0-9])+/) {
132 my $s = $KNOWN_TLS{$1} // $KNOWN_STARTTLS{$1};
133 $scheme = $s if defined $s;
135 if ($l =~ s!/?\?(.+)\z!!) {
136 $tls_opt{"$scheme://$l"} = accept_tls_opt($1);
137 } elsif (defined($default_cert)) {
138 $tls_opt{"$scheme://$l"} = accept_tls_opt('');
139 } elsif ($scheme =~ /\A(?:https|imaps|imaps)\z/) {
140 die "$orig specified w/o cert=\n";
142 # TODO: use scheme to load either NNTP.pm or HTTP.pm
144 next if $listener_names->{$l}; # already inherited
146 if (index($l, '/') == 0) {
147 $sock_pkg = 'IO::Socket::UNIX';
148 eval "use $sock_pkg";
150 %o = (Type => SOCK_STREAM, Peer => $l);
152 my $c = $sock_pkg->new(%o);
153 if (!defined($c) && $!{ECONNREFUSED}) {
155 "failed to unlink stale socket=$l: $!\n";
156 } # else: let the bind fail
158 $o{Local} = delete $o{Peer};
160 # both work for IPv4, too
161 for (qw(IO::Socket::IP IO::Socket::INET6)) {
163 eval "use $sock_pkg";
167 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
170 my $prev = umask 0000;
171 my $s = eval { $sock_pkg->new(%o) };
172 warn "error binding $l: $! ($@)\n" unless $s;
175 $listener_names->{sockname($s)} = $s;
181 # cert/key options in @cfg_listen takes precedence when inheriting,
182 # but map well-known inherited ports if --listen isn't specified
184 for my $sockname (@inherited_names) {
185 $sockname =~ /:([0-9]+)\z/ or next;
186 if (my $scheme = $KNOWN_TLS{$1}) {
187 $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt('');
188 } elsif (($scheme = $KNOWN_STARTTLS{$1})) {
189 next if $tls_opt{"$scheme://$sockname"};
190 $tls_opt{''} ||= accept_tls_opt('');
194 die "No listeners bound\n" unless @listeners;
197 sub check_absolute ($$) {
198 my ($var, $val) = @_;
199 if (defined $val && index($val, '/') != 0) {
201 "--$var must be an absolute path when using --daemonize: $val\n";
208 foreach my $i (0..$#ARGV) {
211 $ARGV[$i] = Cwd::abs_path($arg);
213 check_absolute('stdout', $stdout);
214 check_absolute('stderr', $stderr);
215 check_absolute('pid-file', $pid_file);
217 chdir '/' or die "chdir failed: $!";
219 if (defined($pid_file) || defined($group) || defined($user)) {
220 eval { require Net::Server::Daemonize; 1 } // die <<EOF;
221 Net::Server required for --pid-file, --group, --user
225 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
226 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
227 if (defined $group) {
228 $gid = Net::Server::Daemonize::get_gid($group);
229 $gid = (split /\s+/, $gid)[0];
230 } elsif (defined $uid) {
231 $gid = (getpwuid($uid))[3];
234 # We change users in the worker to ensure upgradability,
235 # The upgrade will create the ".oldbin" pid file in the
236 # same directory as the given pid file.
237 $uid and $set_user = sub {
239 Net::Server::Daemonize::set_user($uid, $gid);
243 my $pid = fork // die "fork: $!";
246 open(STDIN, '+<', '/dev/null') or
247 die "redirect stdin failed: $!\n";
248 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
249 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
251 $pid = fork // die "fork: $!";
254 return unless defined $pid_file;
256 write_pid($pid_file);
258 bless { pid => $$, pid_file => \$pid_file }, __PACKAGE__;
261 sub worker_quit { # $_[0] = signal name or number (unused)
262 # killing again terminates immediately:
263 exit unless @listeners;
265 $_->close foreach @listeners; # call PublicInbox::DS::close
269 # drop idle connections and try to quit gracefully
270 PublicInbox::DS->SetPostLoopCallback(sub {
271 my ($dmap, undef) = @_;
274 for my $s (values %$dmap) {
275 $s->can('busy') or next;
278 } else { # close as much as possible, early as possible
283 if (($warn + 5) < now()) {
284 warn "$$ quitting, $n client(s) left\n";
287 unless (defined $proc_name) {
288 $proc_name = (split(/\s+/, $0))[0];
289 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
291 $0 = "$proc_name quitting, $n client(s) left";
293 $n; # true: loop continues, false: loop breaks
299 open STDOUT, '>>', $stdout or
300 warn "failed to redirect stdout to $stdout: $!\n";
301 STDOUT->autoflush(1);
305 open STDERR, '>>', $stderr or
306 warn "failed to redirect stderr to $stderr: $!\n";
307 STDERR->autoflush(1);
314 my $addr = getsockname($s) or return;
315 my ($host, $port) = host_with_port($addr);
316 if ($port == 0 && $host eq '127.0.0.1') {
317 my ($path) = Socket::sockaddr_un($addr);
323 sub unpack_ipv6 ($) {
327 # Socket.pm in Perl 5.14+ supports IPv6:
329 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
330 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
334 # Perl 5.12 or earlier? SpamAssassin and Net::Server use
335 # Socket6, so it may be installed on our system, already
336 # (otherwise die here):
339 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
340 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
345 sub host_with_port ($) {
349 # this eval will die on Unix sockets:
351 if (length($addr) >= 28) {
352 ($host, $port) = unpack_ipv6($addr);
355 ($port, $host) = Socket::sockaddr_in($addr);
356 $host = Socket::inet_ntoa($host);
359 $@ ? ('127.0.0.1', 0) : ($host, $port);
363 my ($listener_names) = @_;
364 return () if ($ENV{LISTEN_PID} || 0) != $$;
365 my $fds = $ENV{LISTEN_FDS} or return ();
366 my $end = $fds + 2; # LISTEN_FDS_START - 1
368 foreach my $fd (3..$end) {
369 open(my $s, '<&=', $fd) or warn "fdopen fd=$fd: $!";
370 if (my $k = sockname($s)) {
371 my $prev_was_blocking = $s->blocking(0);
372 warn <<"" if $prev_was_blocking;
373 Inherited socket (fd=$fd) is blocking, making it non-blocking.
374 Set 'NonBlocking = true' in the systemd.service unit to avoid stalled
375 processes when multiple service instances start.
377 $listener_names->{$k} = $s;
380 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
386 sub upgrade { # $_[0] = signal name or number (unused)
388 warn "upgrade in-progress: $reexec_pid\n";
391 if (defined $pid_file) {
392 if ($pid_file =~ /\.oldbin\z/) {
393 warn "BUG: .oldbin suffix exists: $pid_file\n";
396 unlink_pid_file_safe_ish($$, $pid_file);
397 $pid_file .= '.oldbin';
398 write_pid($pid_file);
401 unless (defined $pid) {
402 warn "fork failed: $!\n";
406 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
407 $ENV{LISTEN_FDS} = scalar @listeners;
408 $ENV{LISTEN_PID} = $$;
409 foreach my $s (@listeners) {
410 # @listeners are globs with workers, PI::L w/o workers
411 $s = $s->{sock} if ref($s) eq 'PublicInbox::Listener';
413 my $fl = fcntl($s, F_GETFD, 0);
414 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
417 die "Failed to exec: $!\n";
422 sub kill_workers ($) {
424 kill $sig, keys(%pids);
427 sub upgrade_aborted ($) {
429 warn "reexec PID($p) died with: $?\n";
431 return unless $pid_file;
433 my $file = $pid_file;
434 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
435 unlink_pid_file_safe_ish($$, $pid_file);
437 eval { write_pid($pid_file) };
441 sub reap_children { # $_[0] = 'CHLD' or POSIX::SIGCHLD()
443 my $p = waitpid(-1, WNOHANG) or return;
444 if (defined $reexec_pid && $p == $reexec_pid) {
446 } elsif (defined(my $id = delete $pids{$p})) {
447 warn "worker[$id] PID($p) died with: $?\n";
449 warn "unknown PID($p) reaped: $?\n";
456 sub unlink_pid_file_safe_ish ($$) {
457 my ($unlink_pid, $file) = @_;
458 return unless defined $unlink_pid && $unlink_pid == $$;
460 open my $fh, '<', $file or return;
462 defined(my $read_pid = <$fh>) or return;
464 if ($read_pid == $unlink_pid) {
465 Net::Server::Daemonize::unlink_pid_file($file);
469 sub master_quit ($) {
470 exit unless @listeners;
476 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
477 my $set_workers = $worker_processes;
481 USR1 => sub { reopen_logs(); kill_workers($_[0]); },
483 QUIT => \&master_quit,
484 INT => \&master_quit,
485 TERM => \&master_quit,
487 return if $ignore_winch || !@listeners;
488 if (-t STDIN || -t STDOUT || -t STDERR) {
491 ignoring SIGWINCH since we are not daemonized
494 $worker_processes = 0;
498 return unless @listeners;
499 $worker_processes = $set_workers;
503 return unless @listeners;
504 if ($set_workers > $worker_processes) {
507 $worker_processes = ++$set_workers;
511 $worker_processes = --$set_workers if $set_workers > 0;
513 CHLD => \&reap_children,
515 my $sigfd = PublicInbox::Sigfd->new($sig);
516 local @SIG{keys %$sig} = values(%$sig) unless $sigfd;
517 PublicInbox::DS::sig_setmask($oldset) if !$sigfd;
518 while (1) { # main loop
519 my $n = scalar keys %pids;
520 unless (@listeners) {
522 $set_workers = $worker_processes = $n = 0;
525 if ($n > $worker_processes) {
526 while (my ($k, $v) = each %pids) {
527 kill('TERM', $k) if $v >= $worker_processes;
529 $n = $worker_processes;
531 my $want = $worker_processes - 1;
533 PublicInbox::DS::block_signals() if !$sigfd;
534 for my $i ($n..$want) {
535 my $seed = rand(0xffffffff);
538 warn "failed to fork worker[$i]: $!\n";
539 } elsif ($pid == 0) {
541 eval { Net::SSLeay::randomize() };
542 $set_user->() if $set_user;
543 return $p0; # run normal work code
545 warn "PID=$pid is worker[$i]\n";
549 PublicInbox::DS::sig_setmask($oldset) if !$sigfd;
552 if ($sigfd) { # Linux and IO::KQueue users:
554 } else { # wake up every second
558 exit # never gets here, just for documentation
561 sub tls_start_cb ($$) {
562 my ($opt, $orig_post_accept) = @_;
564 my ($io, $addr, $srv) = @_;
565 my $ssl = IO::Socket::SSL->start_SSL($io, %$opt);
566 $orig_post_accept->($ssl, $addr, $srv);
570 sub defer_accept ($$) {
571 my ($s, $af_name) = @_;
572 return unless defined $af_name;
573 if ($^O eq 'linux') {
574 my $TCP_DEFER_ACCEPT = 9; # Socket::TCP_DEFER_ACCEPT is in 5.14+
575 my $x = getsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT);
576 return unless defined $x; # may be Unix socket
577 my $sec = unpack('i', $x);
578 return if $sec > 0; # systemd users may set a higher value
579 setsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 1);
580 } elsif ($^O eq 'freebsd') {
581 my $x = getsockopt($s, SOL_SOCKET, $SO_ACCEPTFILTER);
582 return if defined $x; # don't change if set
583 my $accf_arg = pack('a16a240', $af_name, '');
584 setsockopt($s, SOL_SOCKET, $SO_ACCEPTFILTER, $accf_arg);
588 sub daemon_loop ($$$$) {
589 my ($refresh, $post_accept, $tlsd, $af_default) = @_;
591 while (my ($k, $v) = each %tls_opt) {
592 if ($k =~ s!\A(?:https|imaps|nntps)://!!) {
593 $post_accept{$k} = tls_start_cb($v, $post_accept);
594 } elsif ($tlsd) { # STARTTLS, $k eq '' is OK
595 $tlsd->{accept_tls} = $v;
600 INT => \&worker_quit,
601 QUIT => \&worker_quit,
602 TERM => \&worker_quit,
605 USR1 => \&reopen_logs,
608 CHLD => \&PublicInbox::DS::enqueue_reap,
610 if ($worker_processes > 0) {
611 $refresh->(); # preload by default
612 my $fh = master_loop(); # returns if in child process
613 PublicInbox::EOFpipe->new($fh, \&worker_quit, undef);
616 $set_user->() if $set_user;
617 $sig->{USR2} = sub { worker_quit() if upgrade() };
623 my $tls_cb = $post_accept{sockname($_)};
625 # NNTPS, HTTPS, HTTP, IMAPS and POP3S are client-first traffic
626 # IMAP, NNTP and POP3 are server-first
627 defer_accept($_, $tls_cb ? 'dataready' : $af_default);
629 # this calls epoll_create:
630 PublicInbox::Listener->new($_, $tls_cb || $post_accept)
632 PublicInbox::DS::event_loop($sig, $oldset);
636 my ($default, $refresh, $post_accept, $tlsd) = @_;
637 daemon_prepare($default);
638 my $af_default = $default =~ /:8080\z/ ? 'httpready' : undef;
639 my $for_destroy = daemonize();
641 # localize GCF2C for tests:
642 local $PublicInbox::GitAsyncCat::GCF2C;
643 local $PublicInbox::Git::async_warn = 1;
644 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
646 daemon_loop($refresh, $post_accept, $tlsd, $af_default);
647 PublicInbox::DS->Reset;
648 # ->DESTROY runs when $for_destroy goes out-of-scope
653 if (defined $uid and !chown($uid, $gid, $path)) {
654 warn "could not chown $path: $!\n";
660 Net::Server::Daemonize::create_pid_file($path);
665 unlink_pid_file_safe_ish($_[0]->{pid}, ${$_[0]->{pid_file}});