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 }
17 use PublicInbox::DS qw(now);
18 use PublicInbox::Syscall qw($SFD_NONBLOCK);
19 require PublicInbox::Listener;
20 use PublicInbox::EOFpipe;
21 use PublicInbox::Sigfd;
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 my $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";
204 foreach my $i (0..$#ARGV) {
207 $ARGV[$i] = abs_path($arg);
209 check_absolute('stdout', $stdout);
210 check_absolute('stderr', $stderr);
211 check_absolute('pid-file', $pid_file);
213 chdir '/' or die "chdir failed: $!";
216 return unless (defined $pid_file || defined $group || defined $user
219 eval { require Net::Server::Daemonize };
222 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
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);
244 die "could not fork: $!\n" unless defined $pid;
247 open(STDIN, '+<', '/dev/null') or
248 die "redirect stdin failed: $!\n";
249 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
250 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
253 die "could not fork: $!\n" unless defined $pid;
256 return unless defined $pid_file;
258 write_pid($pid_file);
260 bless { pid => $$, pid_file => \$pid_file }, __PACKAGE__;
263 sub worker_quit { # $_[0] = signal name or number (unused)
264 # killing again terminates immediately:
265 exit unless @listeners;
267 $_->close foreach @listeners; # call PublicInbox::DS::close
271 # drop idle connections and try to quit gracefully
272 PublicInbox::DS->SetPostLoopCallback(sub {
273 my ($dmap, undef) = @_;
277 foreach my $s (values %$dmap) {
278 $s->can('busy') or next;
279 if ($s->busy($now)) {
282 # close as much as possible, early as possible
287 if (($warn + 5) < now()) {
288 warn "$$ quitting, $n client(s) left\n";
291 unless (defined $proc_name) {
292 $proc_name = (split(/\s+/, $0))[0];
293 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
295 $0 = "$proc_name quitting, $n client(s) left";
297 $n; # true: loop continues, false: loop breaks
303 open STDOUT, '>>', $stdout or
304 warn "failed to redirect stdout to $stdout: $!\n";
305 STDOUT->autoflush(1);
309 open STDERR, '>>', $stderr or
310 warn "failed to redirect stderr to $stderr: $!\n";
311 STDERR->autoflush(1);
318 my $addr = getsockname($s) or return;
319 my ($host, $port) = host_with_port($addr);
320 if ($port == 0 && $host eq '127.0.0.1') {
321 my ($path) = Socket::sockaddr_un($addr);
327 sub unpack_ipv6 ($) {
331 # Socket.pm in Perl 5.14+ supports IPv6:
333 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
334 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
338 # Perl 5.12 or earlier? SpamAssassin and Net::Server use
339 # Socket6, so it may be installed on our system, already
340 # (otherwise die here):
343 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
344 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
349 sub host_with_port ($) {
353 # this eval will die on Unix sockets:
355 if (length($addr) >= 28) {
356 ($host, $port) = unpack_ipv6($addr);
359 ($port, $host) = Socket::sockaddr_in($addr);
360 $host = Socket::inet_ntoa($host);
363 $@ ? ('127.0.0.1', 0) : ($host, $port);
367 my ($listener_names) = @_;
368 return () if ($ENV{LISTEN_PID} || 0) != $$;
369 my $fds = $ENV{LISTEN_FDS} or return ();
370 my $end = $fds + 2; # LISTEN_FDS_START - 1
372 foreach my $fd (3..$end) {
373 my $s = IO::Handle->new_from_fd($fd, 'r');
374 if (my $k = sockname($s)) {
378 Inherited socket (fd=$fd) is blocking, making it non-blocking.
379 Set 'NonBlocking = true' in the systemd.service unit to avoid stalled
380 processes when multiple service instances start.
383 $listener_names->{$k} = $s;
386 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
392 sub upgrade { # $_[0] = signal name or number (unused)
394 warn "upgrade in-progress: $reexec_pid\n";
397 if (defined $pid_file) {
398 if ($pid_file =~ /\.oldbin\z/) {
399 warn "BUG: .oldbin suffix exists: $pid_file\n";
402 unlink_pid_file_safe_ish($$, $pid_file);
403 $pid_file .= '.oldbin';
404 write_pid($pid_file);
407 unless (defined $pid) {
408 warn "fork failed: $!\n";
412 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
413 $ENV{LISTEN_FDS} = scalar @listeners;
414 $ENV{LISTEN_PID} = $$;
415 foreach my $s (@listeners) {
416 # @listeners are globs with workers, PI::L w/o workers
417 $s = $s->{sock} if ref($s) eq 'PublicInbox::Listener';
419 my $fl = fcntl($s, F_GETFD, 0);
420 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
423 die "Failed to exec: $!\n";
428 sub kill_workers ($) {
431 while (my ($pid, $id) = each %pids) {
436 sub upgrade_aborted ($) {
438 warn "reexec PID($p) died with: $?\n";
440 return unless $pid_file;
442 my $file = $pid_file;
443 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
444 unlink_pid_file_safe_ish($$, $pid_file);
446 eval { write_pid($pid_file) };
450 sub reap_children { # $_[0] = 'CHLD' or POSIX::SIGCHLD()
452 my $p = waitpid(-1, WNOHANG) or return;
453 if (defined $reexec_pid && $p == $reexec_pid) {
455 } elsif (defined(my $id = delete $pids{$p})) {
456 warn "worker[$id] PID($p) died with: $?\n";
458 warn "unknown PID($p) reaped: $?\n";
465 sub unlink_pid_file_safe_ish ($$) {
466 my ($unlink_pid, $file) = @_;
467 return unless defined $unlink_pid && $unlink_pid == $$;
469 open my $fh, '<', $file or return;
471 defined(my $read_pid = <$fh>) or return;
473 if ($read_pid == $unlink_pid) {
474 Net::Server::Daemonize::unlink_pid_file($file);
478 sub master_quit ($) {
479 exit unless @listeners;
485 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
486 my $set_workers = $worker_processes;
490 USR1 => sub { reopen_logs(); kill_workers($_[0]); },
492 QUIT => \&master_quit,
493 INT => \&master_quit,
494 TERM => \&master_quit,
496 return if $ignore_winch || !@listeners;
497 if (-t STDIN || -t STDOUT || -t STDERR) {
500 ignoring SIGWINCH since we are not daemonized
503 $worker_processes = 0;
507 return unless @listeners;
508 $worker_processes = $set_workers;
512 return unless @listeners;
513 if ($set_workers > $worker_processes) {
516 $worker_processes = ++$set_workers;
520 $worker_processes = --$set_workers if $set_workers > 0;
522 CHLD => \&reap_children,
524 my $sigfd = PublicInbox::Sigfd->new($sig, 0);
525 local %SIG = (%SIG, %$sig) if !$sigfd;
526 PublicInbox::restore_signals($oldset) if !$sigfd;
527 while (1) { # main loop
528 my $n = scalar keys %pids;
529 unless (@listeners) {
531 $set_workers = $worker_processes = $n = 0;
534 if ($n > $worker_processes) {
535 while (my ($k, $v) = each %pids) {
536 kill('TERM', $k) if $v >= $worker_processes;
538 $n = $worker_processes;
540 my $want = $worker_processes - 1;
542 PublicInbox::Sigfd::block_signals() if !$sigfd;
543 for my $i ($n..$want) {
546 warn "failed to fork worker[$i]: $!\n";
547 } elsif ($pid == 0) {
548 $set_user->() if $set_user;
549 return $p0; # run normal work code
551 warn "PID=$pid is worker[$i]\n";
555 PubliInbox::Sigfd::set_sigmask($oldset) if !$sigfd;
558 if ($sigfd) { # Linux and IO::KQueue users:
560 } else { # wake up every second
564 exit # never gets here, just for documentation
567 sub tls_start_cb ($$) {
568 my ($opt, $orig_post_accept) = @_;
570 my ($io, $addr, $srv) = @_;
571 my $ssl = IO::Socket::SSL->start_SSL($io, %$opt);
572 $orig_post_accept->($ssl, $addr, $srv);
576 sub defer_accept ($$) {
577 my ($s, $af_name) = @_;
578 return unless defined $af_name;
579 if ($^O eq 'linux') {
580 my $TCP_DEFER_ACCEPT = 9; # Socket::TCP_DEFER_ACCEPT is in 5.14+
581 my $x = getsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT);
582 return unless defined $x; # may be Unix socket
583 my $sec = unpack('i', $x);
584 return if $sec > 0; # systemd users may set a higher value
585 setsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 1);
586 } elsif ($^O eq 'freebsd') {
587 my $x = getsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER);
588 return if defined $x; # don't change if set
589 my $accf_arg = pack('a16a240', $af_name, '');
590 setsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER, $accf_arg);
594 sub daemon_loop ($$$$) {
595 my ($refresh, $post_accept, $tlsd, $af_default) = @_;
597 while (my ($k, $v) = each %tls_opt) {
598 if ($k =~ s!\A(?:https|imaps|nntps)://!!) {
599 $post_accept{$k} = tls_start_cb($v, $post_accept);
600 } elsif ($tlsd) { # STARTTLS, $k eq '' is OK
601 $tlsd->{accept_tls} = $v;
606 INT => \&worker_quit,
607 QUIT => \&worker_quit,
608 TERM => \&worker_quit,
611 USR1 => \&reopen_logs,
614 CHLD => \&PublicInbox::DS::enqueue_reap,
616 if ($worker_processes > 0) {
617 $refresh->(); # preload by default
618 my $fh = master_loop(); # returns if in child process
619 PublicInbox::EOFpipe->new($fh, \&worker_quit, undef);
622 $set_user->() if $set_user;
623 $sig->{USR2} = sub { worker_quit() if upgrade() };
629 my $tls_cb = $post_accept{sockname($_)};
631 # NNTPS, HTTPS, HTTP, IMAPS and POP3S are client-first traffic
632 # IMAP, NNTP and POP3 are server-first
633 defer_accept($_, $tls_cb ? 'dataready' : $af_default);
635 # this calls epoll_create:
636 PublicInbox::Listener->new($_, $tls_cb || $post_accept)
638 my $sigfd = PublicInbox::Sigfd->new($sig, $SFD_NONBLOCK);
639 local %SIG = (%SIG, %$sig) if !$sigfd;
641 # wake up every second to accept signals if we don't
642 # have signalfd or IO::KQueue:
643 PublicInbox::Sigfd::set_sigmask($oldset);
644 PublicInbox::DS->SetLoopTimeout(1000);
646 PublicInbox::DS->EventLoop;
650 my ($default, $refresh, $post_accept, $tlsd) = @_;
651 local $SIG{PIPE} = 'IGNORE';
652 daemon_prepare($default);
653 my $af_default = $default =~ /:8080\z/ ? 'httpready' : undef;
654 my $for_destroy = daemonize();
655 daemon_loop($refresh, $post_accept, $tlsd, $af_default);
656 PublicInbox::DS->Reset;
657 # ->DESTROY runs when $for_destroy goes out-of-scope
662 if (defined $uid and !chown($uid, $gid, $path)) {
663 warn "could not chown $path: $!\n";
669 Net::Server::Daemonize::create_pid_file($path);
674 unlink_pid_file_safe_ish($_[0]->{pid}, ${$_[0]->{pid_file}});