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 httpd, imapd, and nntpd 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 }
16 use PublicInbox::DS qw(now);
17 use PublicInbox::Syscall qw($SFD_NONBLOCK);
18 require PublicInbox::Listener;
19 use PublicInbox::EOFpipe;
20 use PublicInbox::Sigfd;
21 use PublicInbox::GitAsyncCat;
23 my ($set_user, $oldset);
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', 993 => 'imaps' );
33 my %KNOWN_STARTTLS = ( 119 => 'nntp', 143 => 'imap' );
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 daemon_prepare ($) {
76 my ($default_listen) = @_;
77 my $listener_names = {}; # sockname => IO::Handle
78 $oldset = PublicInbox::Sigfd::block_signals();
80 my ($prog) = ($CMD[0] =~ m!([^/]+)\z!g);
82 usage: $prog [-l ADDRESS] [--cert=FILE] [--key=FILE]
86 -l ADDRESS address to listen on (default: $default_listen)
87 --cert=FILE default SSL/TLS certificate
88 --key=FILE default SSL/TLS certificate
89 -W WORKERS number of worker processes to spawn (default: 1)
91 See public-inbox-daemon(8) and $prog(1) man pages for more.
94 'l|listen=s' => \@cfg_listen,
95 '1|stdout=s' => \$stdout,
96 '2|stderr=s' => \$stderr,
97 'W|worker-processes=i' => \$worker_processes,
98 'P|pid-file=s' => \$pid_file,
100 'g|group=s' => \$group,
101 'D|daemonize' => \$daemonize,
102 'cert=s' => \$default_cert,
103 'key=s' => \$default_key,
104 'help|h' => \(my $show_help),
106 GetOptions(%opt) or die $help;
107 if ($show_help) { print $help; exit 0 };
109 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
110 die "--pid-file cannot end with '.oldbin'\n";
112 @listeners = inherit($listener_names);
114 # allow socket-activation users to set certs once and not
115 # have to configure each socket:
116 my @inherited_names = keys(%$listener_names) if defined($default_cert);
118 # ignore daemonize when inheriting
119 $daemonize = undef if scalar @listeners;
121 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
123 foreach my $l (@cfg_listen) {
126 if ($l =~ s!\A([^:]+)://!!) {
128 } elsif ($l =~ /\A(?:\[[^\]]+\]|[^:]+):([0-9])+/) {
129 my $s = $KNOWN_TLS{$1} // $KNOWN_STARTTLS{$1};
130 $scheme = $s if defined $s;
132 if ($l =~ s!/?\?(.+)\z!!) {
133 $tls_opt{"$scheme://$l"} = accept_tls_opt($1);
134 } elsif (defined($default_cert)) {
135 $tls_opt{"$scheme://$l"} = accept_tls_opt('');
136 } elsif ($scheme =~ /\A(?:https|imaps|imaps)\z/) {
137 die "$orig specified w/o cert=\n";
139 # TODO: use scheme to load either NNTP.pm or HTTP.pm
141 next if $listener_names->{$l}; # already inherited
143 if (index($l, '/') == 0) {
144 $sock_pkg = 'IO::Socket::UNIX';
145 eval "use $sock_pkg";
147 %o = (Type => SOCK_STREAM, Peer => $l);
149 my $c = $sock_pkg->new(%o);
150 if (!defined($c) && $!{ECONNREFUSED}) {
152 "failed to unlink stale socket=$l: $!\n";
153 } # else: let the bind fail
155 $o{Local} = delete $o{Peer};
157 # both work for IPv4, too
158 for (qw(IO::Socket::IP IO::Socket::INET6)) {
160 eval "use $sock_pkg";
164 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
167 my $prev = umask 0000;
168 my $s = eval { $sock_pkg->new(%o) };
169 warn "error binding $l: $! ($@)\n" unless $s;
172 $listener_names->{sockname($s)} = $s;
178 # cert/key options in @cfg_listen takes precedence when inheriting,
179 # but map well-known inherited ports if --listen isn't specified
181 for my $sockname (@inherited_names) {
182 $sockname =~ /:([0-9]+)\z/ or next;
183 if (my $scheme = $KNOWN_TLS{$1}) {
184 $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt('');
185 } elsif (($scheme = $KNOWN_STARTTLS{$1})) {
186 next if $tls_opt{"$scheme://$sockname"};
187 $tls_opt{''} ||= accept_tls_opt('');
191 die "No listeners bound\n" unless @listeners;
194 sub check_absolute ($$) {
195 my ($var, $val) = @_;
196 if (defined $val && index($val, '/') != 0) {
198 "--$var must be an absolute path when using --daemonize: $val\n";
205 foreach my $i (0..$#ARGV) {
208 $ARGV[$i] = Cwd::abs_path($arg);
210 check_absolute('stdout', $stdout);
211 check_absolute('stderr', $stderr);
212 check_absolute('pid-file', $pid_file);
214 chdir '/' or die "chdir failed: $!";
216 if (defined($pid_file) || defined($group) || defined($user)) {
217 eval { require Net::Server::Daemonize; 1 } // die <<EOF;
218 Net::Server required for --pid-file, --group, --user
222 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
223 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
224 if (defined $group) {
225 $gid = Net::Server::Daemonize::get_gid($group);
226 $gid = (split /\s+/, $gid)[0];
227 } elsif (defined $uid) {
228 $gid = (getpwuid($uid))[3];
231 # We change users in the worker to ensure upgradability,
232 # The upgrade will create the ".oldbin" pid file in the
233 # same directory as the given pid file.
234 $uid and $set_user = sub {
236 Net::Server::Daemonize::set_user($uid, $gid);
240 my $pid = fork // die "fork: $!";
243 open(STDIN, '+<', '/dev/null') or
244 die "redirect stdin failed: $!\n";
245 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
246 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
248 $pid = fork // die "fork: $!";
251 return unless defined $pid_file;
253 write_pid($pid_file);
255 bless { pid => $$, pid_file => \$pid_file }, __PACKAGE__;
258 sub worker_quit { # $_[0] = signal name or number (unused)
259 # killing again terminates immediately:
260 exit unless @listeners;
262 $_->close foreach @listeners; # call PublicInbox::DS::close
266 # drop idle connections and try to quit gracefully
267 PublicInbox::DS->SetPostLoopCallback(sub {
268 my ($dmap, undef) = @_;
272 foreach my $s (values %$dmap) {
273 $s->can('busy') or next;
274 if ($s->busy($now)) {
277 # close as much as possible, early as possible
282 if (($warn + 5) < now()) {
283 warn "$$ quitting, $n client(s) left\n";
286 unless (defined $proc_name) {
287 $proc_name = (split(/\s+/, $0))[0];
288 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
290 $0 = "$proc_name quitting, $n client(s) left";
292 $n; # true: loop continues, false: loop breaks
298 open STDOUT, '>>', $stdout or
299 warn "failed to redirect stdout to $stdout: $!\n";
300 STDOUT->autoflush(1);
304 open STDERR, '>>', $stderr or
305 warn "failed to redirect stderr to $stderr: $!\n";
306 STDERR->autoflush(1);
313 my $addr = getsockname($s) or return;
314 my ($host, $port) = host_with_port($addr);
315 if ($port == 0 && $host eq '127.0.0.1') {
316 my ($path) = Socket::sockaddr_un($addr);
322 sub unpack_ipv6 ($) {
326 # Socket.pm in Perl 5.14+ supports IPv6:
328 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
329 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
333 # Perl 5.12 or earlier? SpamAssassin and Net::Server use
334 # Socket6, so it may be installed on our system, already
335 # (otherwise die here):
338 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
339 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
344 sub host_with_port ($) {
348 # this eval will die on Unix sockets:
350 if (length($addr) >= 28) {
351 ($host, $port) = unpack_ipv6($addr);
354 ($port, $host) = Socket::sockaddr_in($addr);
355 $host = Socket::inet_ntoa($host);
358 $@ ? ('127.0.0.1', 0) : ($host, $port);
362 my ($listener_names) = @_;
363 return () if ($ENV{LISTEN_PID} || 0) != $$;
364 my $fds = $ENV{LISTEN_FDS} or return ();
365 my $end = $fds + 2; # LISTEN_FDS_START - 1
367 foreach my $fd (3..$end) {
368 my $s = IO::Handle->new_from_fd($fd, 'r');
369 if (my $k = sockname($s)) {
370 my $prev_was_blocking = $s->blocking(0);
371 warn <<"" if $prev_was_blocking;
372 Inherited socket (fd=$fd) is blocking, making it non-blocking.
373 Set 'NonBlocking = true' in the systemd.service unit to avoid stalled
374 processes when multiple service instances start.
376 $listener_names->{$k} = $s;
379 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
385 sub upgrade { # $_[0] = signal name or number (unused)
387 warn "upgrade in-progress: $reexec_pid\n";
390 if (defined $pid_file) {
391 if ($pid_file =~ /\.oldbin\z/) {
392 warn "BUG: .oldbin suffix exists: $pid_file\n";
395 unlink_pid_file_safe_ish($$, $pid_file);
396 $pid_file .= '.oldbin';
397 write_pid($pid_file);
400 unless (defined $pid) {
401 warn "fork failed: $!\n";
405 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
406 $ENV{LISTEN_FDS} = scalar @listeners;
407 $ENV{LISTEN_PID} = $$;
408 foreach my $s (@listeners) {
409 # @listeners are globs with workers, PI::L w/o workers
410 $s = $s->{sock} if ref($s) eq 'PublicInbox::Listener';
412 my $fl = fcntl($s, F_GETFD, 0);
413 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
416 die "Failed to exec: $!\n";
421 sub kill_workers ($) {
423 kill $sig, keys(%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 my $set_workers = $worker_processes;
480 USR1 => sub { reopen_logs(); kill_workers($_[0]); },
482 QUIT => \&master_quit,
483 INT => \&master_quit,
484 TERM => \&master_quit,
486 return if $ignore_winch || !@listeners;
487 if (-t STDIN || -t STDOUT || -t STDERR) {
490 ignoring SIGWINCH since we are not daemonized
493 $worker_processes = 0;
497 return unless @listeners;
498 $worker_processes = $set_workers;
502 return unless @listeners;
503 if ($set_workers > $worker_processes) {
506 $worker_processes = ++$set_workers;
510 $worker_processes = --$set_workers if $set_workers > 0;
512 CHLD => \&reap_children,
514 my $sigfd = PublicInbox::Sigfd->new($sig, 0);
515 local %SIG = (%SIG, %$sig) if !$sigfd;
516 PublicInbox::Sigfd::sig_setmask($oldset) if !$sigfd;
517 while (1) { # main loop
518 my $n = scalar keys %pids;
519 unless (@listeners) {
521 $set_workers = $worker_processes = $n = 0;
524 if ($n > $worker_processes) {
525 while (my ($k, $v) = each %pids) {
526 kill('TERM', $k) if $v >= $worker_processes;
528 $n = $worker_processes;
530 my $want = $worker_processes - 1;
532 PublicInbox::Sigfd::block_signals() if !$sigfd;
533 for my $i ($n..$want) {
536 warn "failed to fork worker[$i]: $!\n";
537 } elsif ($pid == 0) {
538 $set_user->() if $set_user;
539 return $p0; # run normal work code
541 warn "PID=$pid is worker[$i]\n";
545 PublicInbox::Sigfd::sig_setmask($oldset) if !$sigfd;
548 if ($sigfd) { # Linux and IO::KQueue users:
550 } else { # wake up every second
554 exit # never gets here, just for documentation
557 sub tls_start_cb ($$) {
558 my ($opt, $orig_post_accept) = @_;
560 my ($io, $addr, $srv) = @_;
561 my $ssl = IO::Socket::SSL->start_SSL($io, %$opt);
562 $orig_post_accept->($ssl, $addr, $srv);
566 sub defer_accept ($$) {
567 my ($s, $af_name) = @_;
568 return unless defined $af_name;
569 if ($^O eq 'linux') {
570 my $TCP_DEFER_ACCEPT = 9; # Socket::TCP_DEFER_ACCEPT is in 5.14+
571 my $x = getsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT);
572 return unless defined $x; # may be Unix socket
573 my $sec = unpack('i', $x);
574 return if $sec > 0; # systemd users may set a higher value
575 setsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 1);
576 } elsif ($^O eq 'freebsd') {
577 my $x = getsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER);
578 return if defined $x; # don't change if set
579 my $accf_arg = pack('a16a240', $af_name, '');
580 setsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER, $accf_arg);
584 sub daemon_loop ($$$$) {
585 my ($refresh, $post_accept, $tlsd, $af_default) = @_;
587 while (my ($k, $v) = each %tls_opt) {
588 if ($k =~ s!\A(?:https|imaps|nntps)://!!) {
589 $post_accept{$k} = tls_start_cb($v, $post_accept);
590 } elsif ($tlsd) { # STARTTLS, $k eq '' is OK
591 $tlsd->{accept_tls} = $v;
596 INT => \&worker_quit,
597 QUIT => \&worker_quit,
598 TERM => \&worker_quit,
601 USR1 => \&reopen_logs,
604 CHLD => \&PublicInbox::DS::enqueue_reap,
606 if ($worker_processes > 0) {
607 $refresh->(); # preload by default
608 my $fh = master_loop(); # returns if in child process
609 PublicInbox::EOFpipe->new($fh, \&worker_quit, undef);
612 $set_user->() if $set_user;
613 $sig->{USR2} = sub { worker_quit() if upgrade() };
619 my $tls_cb = $post_accept{sockname($_)};
621 # NNTPS, HTTPS, HTTP, IMAPS and POP3S are client-first traffic
622 # IMAP, NNTP and POP3 are server-first
623 defer_accept($_, $tls_cb ? 'dataready' : $af_default);
625 # this calls epoll_create:
626 PublicInbox::Listener->new($_, $tls_cb || $post_accept)
628 my $sigfd = PublicInbox::Sigfd->new($sig, $SFD_NONBLOCK);
629 local %SIG = (%SIG, %$sig) if !$sigfd;
631 # wake up every second to accept signals if we don't
632 # have signalfd or IO::KQueue:
633 PublicInbox::Sigfd::sig_setmask($oldset);
634 PublicInbox::DS->SetLoopTimeout(1000);
636 PublicInbox::DS->EventLoop;
640 my ($default, $refresh, $post_accept, $tlsd) = @_;
641 local $SIG{PIPE} = 'IGNORE';
642 daemon_prepare($default);
643 my $af_default = $default =~ /:8080\z/ ? 'httpready' : undef;
644 my $for_destroy = daemonize();
646 # localize GCF2C for tests:
647 local $PublicInbox::GitAsyncCat::GCF2C;
649 daemon_loop($refresh, $post_accept, $tlsd, $af_default);
650 PublicInbox::DS->Reset;
651 # ->DESTROY runs when $for_destroy goes out-of-scope
656 if (defined $uid and !chown($uid, $gid, $path)) {
657 warn "could not chown $path: $!\n";
663 Net::Server::Daemonize::create_pid_file($path);
668 unlink_pid_file_safe_ish($_[0]->{pid}, ${$_[0]->{pid_file}});