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>
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);
15 sub SO_ACCEPTFILTER () { 0x1000 }
18 use PublicInbox::DS qw(now);
19 use PublicInbox::Syscall qw(SFD_NONBLOCK);
20 require PublicInbox::Listener;
21 use PublicInbox::EOFpipe;
22 use PublicInbox::Sigfd;
23 use PublicInbox::GitAsyncCat;
25 my ($set_user, $oldset);
26 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
27 my $worker_processes = 1;
30 my %tls_opt; # scheme://sockname => args for IO::Socket::SSL->start_SSL
33 my ($default_cert, $default_key);
34 my %KNOWN_TLS = ( 443 => 'https', 563 => 'nntps', 993 => 'imaps' );
35 my %KNOWN_STARTTLS = ( 119 => 'nntp', 143 => 'imap' );
37 sub accept_tls_opt ($) {
39 # opt_str: opt1=val1,opt2=val2 (opt may repeat for multi-value)
40 require PublicInbox::TLS;
42 # allow ',' as delimiter since '&' is shell-unfriendly
43 foreach (split(/[,&]/, $opt_str)) {
44 my ($k, $v) = split(/=/, $_, 2);
45 push @{$o->{$k} ||= []}, $v;
48 # key may be a part of cert. At least
49 # p5-io-socket-ssl/example/ssl_server.pl has this fallback:
50 $o->{cert} //= [ $default_cert ];
51 $o->{key} //= defined($default_key) ? [ $default_key ] : $o->{cert};
52 my %ctx_opt = (SSL_server => 1);
53 # parse out hostname:/path/to/ mappings:
54 foreach my $k (qw(cert key)) {
55 my $x = $ctx_opt{'SSL_'.$k.'_file'} = {};
56 foreach my $path (@{$o->{$k}}) {
58 $path =~ s/\A([^:]+):// and $host = $1;
62 my $ctx = IO::Socket::SSL::SSL_Context->new(%ctx_opt) or
63 die 'SSL_Context->new: '.PublicInbox::TLS::err();
65 # save ~34K per idle connection (cf. SSL_CTX_set_mode(3ssl))
66 # RSS goes from 346MB to 171MB with 10K idle NNTPS clients on amd64
67 # cf. https://rt.cpan.org/Ticket/Display.html?id=129463
68 my $mode = eval { Net::SSLeay::MODE_RELEASE_BUFFERS() };
69 if ($mode && $ctx->{context}) {
70 eval { Net::SSLeay::CTX_set_mode($ctx->{context}, $mode) };
71 warn "W: $@ (setting SSL_MODE_RELEASE_BUFFERS)\n" if $@;
74 { SSL_server => 1, SSL_startHandshake => 0, SSL_reuse_ctx => $ctx };
77 sub daemon_prepare ($) {
78 my ($default_listen) = @_;
79 my $listener_names = {}; # sockname => IO::Handle
80 $oldset = PublicInbox::Sigfd::block_signals();
82 my ($prog) = ($CMD[0] =~ m!([^/]+)\z!g);
84 usage: $prog [-l ADDRESS] [--cert=FILE] [--key=FILE]
88 -l ADDRESS address to listen on (default: $default_listen)
89 --cert=FILE default SSL/TLS certificate
90 --key=FILE default SSL/TLS certificate
91 -W WORKERS number of worker processes to spawn (default: 1)
93 See public-inbox-daemon(8) and $prog(1) man pages for more.
96 'l|listen=s' => \@cfg_listen,
97 '1|stdout=s' => \$stdout,
98 '2|stderr=s' => \$stderr,
99 'W|worker-processes=i' => \$worker_processes,
100 'P|pid-file=s' => \$pid_file,
101 'u|user=s' => \$user,
102 'g|group=s' => \$group,
103 'D|daemonize' => \$daemonize,
104 'cert=s' => \$default_cert,
105 'key=s' => \$default_key,
106 'help|h' => \(my $show_help),
108 GetOptions(%opt) or die $help;
109 if ($show_help) { print $help; exit 0 };
111 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
112 die "--pid-file cannot end with '.oldbin'\n";
114 @listeners = inherit($listener_names);
116 # allow socket-activation users to set certs once and not
117 # have to configure each socket:
118 my @inherited_names = keys(%$listener_names) if defined($default_cert);
120 # ignore daemonize when inheriting
121 $daemonize = undef if scalar @listeners;
123 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
125 foreach my $l (@cfg_listen) {
128 if ($l =~ s!\A([^:]+)://!!) {
130 } elsif ($l =~ /\A(?:\[[^\]]+\]|[^:]+):([0-9])+/) {
131 my $s = $KNOWN_TLS{$1} // $KNOWN_STARTTLS{$1};
132 $scheme = $s if defined $s;
134 if ($l =~ s!/?\?(.+)\z!!) {
135 $tls_opt{"$scheme://$l"} = accept_tls_opt($1);
136 } elsif (defined($default_cert)) {
137 $tls_opt{"$scheme://$l"} = accept_tls_opt('');
138 } elsif ($scheme =~ /\A(?:https|imaps|imaps)\z/) {
139 die "$orig specified w/o cert=\n";
141 # TODO: use scheme to load either NNTP.pm or HTTP.pm
143 next if $listener_names->{$l}; # already inherited
145 if (index($l, '/') == 0) {
146 $sock_pkg = 'IO::Socket::UNIX';
147 eval "use $sock_pkg";
149 %o = (Type => SOCK_STREAM, Peer => $l);
151 my $c = $sock_pkg->new(%o);
152 if (!defined($c) && $!{ECONNREFUSED}) {
154 "failed to unlink stale socket=$l: $!\n";
155 } # else: let the bind fail
157 $o{Local} = delete $o{Peer};
159 # both work for IPv4, too
160 for (qw(IO::Socket::IP IO::Socket::INET6)) {
162 eval "use $sock_pkg";
166 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
169 my $prev = umask 0000;
170 my $s = eval { $sock_pkg->new(%o) };
171 warn "error binding $l: $! ($@)\n" unless $s;
174 $listener_names->{sockname($s)} = $s;
180 # cert/key options in @cfg_listen takes precedence when inheriting,
181 # but map well-known inherited ports if --listen isn't specified
183 for my $sockname (@inherited_names) {
184 $sockname =~ /:([0-9]+)\z/ or next;
185 if (my $scheme = $KNOWN_TLS{$1}) {
186 $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt('');
187 } elsif (($scheme = $KNOWN_STARTTLS{$1})) {
188 next if $tls_opt{"$scheme://$sockname"};
189 $tls_opt{''} ||= accept_tls_opt('');
193 die "No listeners bound\n" unless @listeners;
196 sub check_absolute ($$) {
197 my ($var, $val) = @_;
198 if (defined $val && index($val, '/') != 0) {
200 "--$var must be an absolute path when using --daemonize: $val\n";
207 foreach my $i (0..$#ARGV) {
210 $ARGV[$i] = Cwd::abs_path($arg);
212 check_absolute('stdout', $stdout);
213 check_absolute('stderr', $stderr);
214 check_absolute('pid-file', $pid_file);
216 chdir '/' or die "chdir failed: $!";
218 if (defined($pid_file) || defined($group) || defined($user)) {
219 eval { require Net::Server::Daemonize; 1 } // die <<EOF;
220 Net::Server required for --pid-file, --group, --user
224 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
225 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
226 if (defined $group) {
227 $gid = Net::Server::Daemonize::get_gid($group);
228 $gid = (split /\s+/, $gid)[0];
229 } elsif (defined $uid) {
230 $gid = (getpwuid($uid))[3];
233 # We change users in the worker to ensure upgradability,
234 # The upgrade will create the ".oldbin" pid file in the
235 # same directory as the given pid file.
236 $uid and $set_user = sub {
238 Net::Server::Daemonize::set_user($uid, $gid);
242 my $pid = fork // die "fork: $!";
245 open(STDIN, '+<', '/dev/null') or
246 die "redirect stdin failed: $!\n";
247 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
248 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
250 $pid = fork // die "fork: $!";
253 return unless defined $pid_file;
255 write_pid($pid_file);
257 bless { pid => $$, pid_file => \$pid_file }, __PACKAGE__;
260 sub worker_quit { # $_[0] = signal name or number (unused)
261 # killing again terminates immediately:
262 exit unless @listeners;
264 $_->close foreach @listeners; # call PublicInbox::DS::close
268 # drop idle connections and try to quit gracefully
269 PublicInbox::DS->SetPostLoopCallback(sub {
270 my ($dmap, undef) = @_;
274 foreach my $s (values %$dmap) {
275 $s->can('busy') or next;
276 if ($s->busy($now)) {
279 # close as much as possible, early as possible
284 if (($warn + 5) < now()) {
285 warn "$$ quitting, $n client(s) left\n";
288 unless (defined $proc_name) {
289 $proc_name = (split(/\s+/, $0))[0];
290 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
292 $0 = "$proc_name quitting, $n client(s) left";
294 $n; # true: loop continues, false: loop breaks
300 open STDOUT, '>>', $stdout or
301 warn "failed to redirect stdout to $stdout: $!\n";
302 STDOUT->autoflush(1);
306 open STDERR, '>>', $stderr or
307 warn "failed to redirect stderr to $stderr: $!\n";
308 STDERR->autoflush(1);
315 my $addr = getsockname($s) or return;
316 my ($host, $port) = host_with_port($addr);
317 if ($port == 0 && $host eq '127.0.0.1') {
318 my ($path) = Socket::sockaddr_un($addr);
324 sub unpack_ipv6 ($) {
328 # Socket.pm in Perl 5.14+ supports IPv6:
330 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
331 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
335 # Perl 5.12 or earlier? SpamAssassin and Net::Server use
336 # Socket6, so it may be installed on our system, already
337 # (otherwise die here):
340 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
341 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
346 sub host_with_port ($) {
350 # this eval will die on Unix sockets:
352 if (length($addr) >= 28) {
353 ($host, $port) = unpack_ipv6($addr);
356 ($port, $host) = Socket::sockaddr_in($addr);
357 $host = Socket::inet_ntoa($host);
360 $@ ? ('127.0.0.1', 0) : ($host, $port);
364 my ($listener_names) = @_;
365 return () if ($ENV{LISTEN_PID} || 0) != $$;
366 my $fds = $ENV{LISTEN_FDS} or return ();
367 my $end = $fds + 2; # LISTEN_FDS_START - 1
369 foreach my $fd (3..$end) {
370 my $s = IO::Handle->new_from_fd($fd, 'r');
371 if (my $k = sockname($s)) {
372 my $prev_was_blocking = $s->blocking(0);
373 warn <<"" if $prev_was_blocking;
374 Inherited socket (fd=$fd) is blocking, making it non-blocking.
375 Set 'NonBlocking = true' in the systemd.service unit to avoid stalled
376 processes when multiple service instances start.
378 $listener_names->{$k} = $s;
381 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
387 sub upgrade { # $_[0] = signal name or number (unused)
389 warn "upgrade in-progress: $reexec_pid\n";
392 if (defined $pid_file) {
393 if ($pid_file =~ /\.oldbin\z/) {
394 warn "BUG: .oldbin suffix exists: $pid_file\n";
397 unlink_pid_file_safe_ish($$, $pid_file);
398 $pid_file .= '.oldbin';
399 write_pid($pid_file);
402 unless (defined $pid) {
403 warn "fork failed: $!\n";
407 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
408 $ENV{LISTEN_FDS} = scalar @listeners;
409 $ENV{LISTEN_PID} = $$;
410 foreach my $s (@listeners) {
411 # @listeners are globs with workers, PI::L w/o workers
412 $s = $s->{sock} if ref($s) eq 'PublicInbox::Listener';
414 my $fl = fcntl($s, F_GETFD, 0);
415 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
418 die "Failed to exec: $!\n";
423 sub kill_workers ($) {
425 kill $sig, keys(%pids);
428 sub upgrade_aborted ($) {
430 warn "reexec PID($p) died with: $?\n";
432 return unless $pid_file;
434 my $file = $pid_file;
435 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
436 unlink_pid_file_safe_ish($$, $pid_file);
438 eval { write_pid($pid_file) };
442 sub reap_children { # $_[0] = 'CHLD' or POSIX::SIGCHLD()
444 my $p = waitpid(-1, WNOHANG) or return;
445 if (defined $reexec_pid && $p == $reexec_pid) {
447 } elsif (defined(my $id = delete $pids{$p})) {
448 warn "worker[$id] PID($p) died with: $?\n";
450 warn "unknown PID($p) reaped: $?\n";
457 sub unlink_pid_file_safe_ish ($$) {
458 my ($unlink_pid, $file) = @_;
459 return unless defined $unlink_pid && $unlink_pid == $$;
461 open my $fh, '<', $file or return;
463 defined(my $read_pid = <$fh>) or return;
465 if ($read_pid == $unlink_pid) {
466 Net::Server::Daemonize::unlink_pid_file($file);
470 sub master_quit ($) {
471 exit unless @listeners;
477 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
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 PublicInbox::Sigfd::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 PublicInbox::Sigfd::block_signals() 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 PublicInbox::Sigfd::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, $tlsd, $af_default) = @_;
589 while (my ($k, $v) = each %tls_opt) {
590 if ($k =~ s!\A(?:https|imaps|nntps)://!!) {
591 $post_accept{$k} = tls_start_cb($v, $post_accept);
592 } elsif ($tlsd) { # STARTTLS, $k eq '' is OK
593 $tlsd->{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::EOFpipe->new($fh, \&worker_quit, undef);
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, IMAPS and POP3S are client-first traffic
624 # IMAP, 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 PublicInbox::Sigfd::sig_setmask($oldset);
636 PublicInbox::DS->SetLoopTimeout(1000);
638 PublicInbox::DS->EventLoop;
642 my ($default, $refresh, $post_accept, $tlsd) = @_;
643 local $SIG{PIPE} = 'IGNORE';
644 daemon_prepare($default);
645 my $af_default = $default =~ /:8080\z/ ? 'httpready' : undef;
646 my $for_destroy = daemonize();
648 # localize GCF2C for tests:
649 local $PublicInbox::GitAsyncCat::GCF2C;
651 daemon_loop($refresh, $post_accept, $tlsd, $af_default);
652 PublicInbox::DS->Reset;
653 # ->DESTROY runs when $for_destroy goes out-of-scope
658 if (defined $uid and !chown($uid, $gid, $path)) {
659 warn "could not chown $path: $!\n";
665 Net::Server::Daemonize::create_pid_file($path);
670 unlink_pid_file_safe_ish($_[0]->{pid}, ${$_[0]->{pid_file}});