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;
22 use PublicInbox::GitAsyncCat;
24 my ($set_user, $oldset);
25 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
26 my $worker_processes = 1;
29 my %tls_opt; # scheme://sockname => args for IO::Socket::SSL->start_SSL
32 my ($default_cert, $default_key);
33 my %KNOWN_TLS = ( 443 => 'https', 563 => 'nntps', 993 => 'imaps' );
34 my %KNOWN_STARTTLS = ( 119 => 'nntp', 143 => 'imap' );
36 sub accept_tls_opt ($) {
38 # opt_str: opt1=val1,opt2=val2 (opt may repeat for multi-value)
39 require PublicInbox::TLS;
41 # allow ',' as delimiter since '&' is shell-unfriendly
42 foreach (split(/[,&]/, $opt_str)) {
43 my ($k, $v) = split(/=/, $_, 2);
44 push @{$o->{$k} ||= []}, $v;
47 # key may be a part of cert. At least
48 # p5-io-socket-ssl/example/ssl_server.pl has this fallback:
49 $o->{cert} //= [ $default_cert ];
50 $o->{key} //= defined($default_key) ? [ $default_key ] : $o->{cert};
51 my %ctx_opt = (SSL_server => 1);
52 # parse out hostname:/path/to/ mappings:
53 foreach my $k (qw(cert key)) {
54 my $x = $ctx_opt{'SSL_'.$k.'_file'} = {};
55 foreach my $path (@{$o->{$k}}) {
57 $path =~ s/\A([^:]+):// and $host = $1;
61 my $ctx = IO::Socket::SSL::SSL_Context->new(%ctx_opt) or
62 die 'SSL_Context->new: '.PublicInbox::TLS::err();
64 # save ~34K per idle connection (cf. SSL_CTX_set_mode(3ssl))
65 # RSS goes from 346MB to 171MB with 10K idle NNTPS clients on amd64
66 # cf. https://rt.cpan.org/Ticket/Display.html?id=129463
67 my $mode = eval { Net::SSLeay::MODE_RELEASE_BUFFERS() };
68 if ($mode && $ctx->{context}) {
69 eval { Net::SSLeay::CTX_set_mode($ctx->{context}, $mode) };
70 warn "W: $@ (setting SSL_MODE_RELEASE_BUFFERS)\n" if $@;
73 { SSL_server => 1, SSL_startHandshake => 0, SSL_reuse_ctx => $ctx };
76 sub daemon_prepare ($) {
77 my ($default_listen) = @_;
78 my $listener_names = {}; # sockname => IO::Handle
79 $oldset = PublicInbox::Sigfd::block_signals();
81 my ($prog) = ($CMD[0] =~ m!([^/]+)\z!g);
83 usage: $prog [-l ADDRESS] [--cert=FILE] [--key=FILE]
87 -l ADDRESS address to listen on (default: $default_listen)
88 --cert=FILE default SSL/TLS certificate
89 --key=FILE default SSL/TLS certificate
90 -W WORKERS number of worker processes to spawn (default: 1)
92 See public-inbox-daemon(8) and $prog(1) man pages for more.
95 'l|listen=s' => \@cfg_listen,
96 '1|stdout=s' => \$stdout,
97 '2|stderr=s' => \$stderr,
98 'W|worker-processes=i' => \$worker_processes,
99 'P|pid-file=s' => \$pid_file,
100 'u|user=s' => \$user,
101 'g|group=s' => \$group,
102 'D|daemonize' => \$daemonize,
103 'cert=s' => \$default_cert,
104 'key=s' => \$default_key,
105 'help|h' => \(my $show_help),
107 GetOptions(%opt) or die $help;
108 if ($show_help) { print $help; exit 0 };
110 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
111 die "--pid-file cannot end with '.oldbin'\n";
113 @listeners = inherit($listener_names);
115 # allow socket-activation users to set certs once and not
116 # have to configure each socket:
117 my @inherited_names = keys(%$listener_names) if defined($default_cert);
119 # ignore daemonize when inheriting
120 $daemonize = undef if scalar @listeners;
122 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
124 foreach my $l (@cfg_listen) {
127 if ($l =~ s!\A([^:]+)://!!) {
129 } elsif ($l =~ /\A(?:\[[^\]]+\]|[^:]+):([0-9])+/) {
130 my $s = $KNOWN_TLS{$1} // $KNOWN_STARTTLS{$1};
131 $scheme = $s if defined $s;
133 if ($l =~ s!/?\?(.+)\z!!) {
134 $tls_opt{"$scheme://$l"} = accept_tls_opt($1);
135 } elsif (defined($default_cert)) {
136 $tls_opt{"$scheme://$l"} = accept_tls_opt('');
137 } elsif ($scheme =~ /\A(?:https|imaps|imaps)\z/) {
138 die "$orig specified w/o cert=\n";
140 # TODO: use scheme to load either NNTP.pm or HTTP.pm
142 next if $listener_names->{$l}; # already inherited
144 if (index($l, '/') == 0) {
145 $sock_pkg = 'IO::Socket::UNIX';
146 eval "use $sock_pkg";
148 %o = (Type => SOCK_STREAM, Peer => $l);
150 my $c = $sock_pkg->new(%o);
151 if (!defined($c) && $!{ECONNREFUSED}) {
153 "failed to unlink stale socket=$l: $!\n";
154 } # else: let the bind fail
156 $o{Local} = delete $o{Peer};
158 # both work for IPv4, too
159 for (qw(IO::Socket::IP IO::Socket::INET6)) {
161 eval "use $sock_pkg";
165 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
168 my $prev = umask 0000;
169 my $s = eval { $sock_pkg->new(%o) };
170 warn "error binding $l: $! ($@)\n" unless $s;
173 $listener_names->{sockname($s)} = $s;
179 # cert/key options in @cfg_listen takes precedence when inheriting,
180 # but map well-known inherited ports if --listen isn't specified
182 for my $sockname (@inherited_names) {
183 $sockname =~ /:([0-9]+)\z/ or next;
184 if (my $scheme = $KNOWN_TLS{$1}) {
185 $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt('');
186 } elsif (($scheme = $KNOWN_STARTTLS{$1})) {
187 next if $tls_opt{"$scheme://$sockname"};
188 $tls_opt{''} ||= accept_tls_opt('');
192 die "No listeners bound\n" unless @listeners;
195 sub check_absolute ($$) {
196 my ($var, $val) = @_;
197 if (defined $val && index($val, '/') != 0) {
199 "--$var must be an absolute path when using --daemonize: $val\n";
205 foreach my $i (0..$#ARGV) {
208 $ARGV[$i] = 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: $!";
217 return unless (defined $pid_file || defined $group || defined $user
220 eval { require Net::Server::Daemonize };
223 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
226 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
227 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
228 if (defined $group) {
229 $gid = Net::Server::Daemonize::get_gid($group);
230 $gid = (split /\s+/, $gid)[0];
231 } elsif (defined $uid) {
232 $gid = (getpwuid($uid))[3];
235 # We change users in the worker to ensure upgradability,
236 # The upgrade will create the ".oldbin" pid file in the
237 # same directory as the given pid file.
238 $uid and $set_user = sub {
240 Net::Server::Daemonize::set_user($uid, $gid);
245 die "could not fork: $!\n" unless defined $pid;
248 open(STDIN, '+<', '/dev/null') or
249 die "redirect stdin failed: $!\n";
250 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
251 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
254 die "could not fork: $!\n" unless defined $pid;
257 return unless defined $pid_file;
259 write_pid($pid_file);
261 bless { pid => $$, pid_file => \$pid_file }, __PACKAGE__;
264 sub worker_quit { # $_[0] = signal name or number (unused)
265 # killing again terminates immediately:
266 exit unless @listeners;
268 $_->close foreach @listeners; # call PublicInbox::DS::close
272 # drop idle connections and try to quit gracefully
273 PublicInbox::DS->SetPostLoopCallback(sub {
274 my ($dmap, undef) = @_;
278 foreach my $s (values %$dmap) {
279 $s->can('busy') or next;
280 if ($s->busy($now)) {
283 # close as much as possible, early as possible
288 if (($warn + 5) < now()) {
289 warn "$$ quitting, $n client(s) left\n";
292 unless (defined $proc_name) {
293 $proc_name = (split(/\s+/, $0))[0];
294 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
296 $0 = "$proc_name quitting, $n client(s) left";
298 $n; # true: loop continues, false: loop breaks
304 open STDOUT, '>>', $stdout or
305 warn "failed to redirect stdout to $stdout: $!\n";
306 STDOUT->autoflush(1);
310 open STDERR, '>>', $stderr or
311 warn "failed to redirect stderr to $stderr: $!\n";
312 STDERR->autoflush(1);
319 my $addr = getsockname($s) or return;
320 my ($host, $port) = host_with_port($addr);
321 if ($port == 0 && $host eq '127.0.0.1') {
322 my ($path) = Socket::sockaddr_un($addr);
328 sub unpack_ipv6 ($) {
332 # Socket.pm in Perl 5.14+ supports IPv6:
334 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
335 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
339 # Perl 5.12 or earlier? SpamAssassin and Net::Server use
340 # Socket6, so it may be installed on our system, already
341 # (otherwise die here):
344 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
345 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
350 sub host_with_port ($) {
354 # this eval will die on Unix sockets:
356 if (length($addr) >= 28) {
357 ($host, $port) = unpack_ipv6($addr);
360 ($port, $host) = Socket::sockaddr_in($addr);
361 $host = Socket::inet_ntoa($host);
364 $@ ? ('127.0.0.1', 0) : ($host, $port);
368 my ($listener_names) = @_;
369 return () if ($ENV{LISTEN_PID} || 0) != $$;
370 my $fds = $ENV{LISTEN_FDS} or return ();
371 my $end = $fds + 2; # LISTEN_FDS_START - 1
373 foreach my $fd (3..$end) {
374 my $s = IO::Handle->new_from_fd($fd, 'r');
375 if (my $k = sockname($s)) {
379 Inherited socket (fd=$fd) is blocking, making it non-blocking.
380 Set 'NonBlocking = true' in the systemd.service unit to avoid stalled
381 processes when multiple service instances start.
384 $listener_names->{$k} = $s;
387 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
393 sub upgrade { # $_[0] = signal name or number (unused)
395 warn "upgrade in-progress: $reexec_pid\n";
398 if (defined $pid_file) {
399 if ($pid_file =~ /\.oldbin\z/) {
400 warn "BUG: .oldbin suffix exists: $pid_file\n";
403 unlink_pid_file_safe_ish($$, $pid_file);
404 $pid_file .= '.oldbin';
405 write_pid($pid_file);
408 unless (defined $pid) {
409 warn "fork failed: $!\n";
413 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
414 $ENV{LISTEN_FDS} = scalar @listeners;
415 $ENV{LISTEN_PID} = $$;
416 foreach my $s (@listeners) {
417 # @listeners are globs with workers, PI::L w/o workers
418 $s = $s->{sock} if ref($s) eq 'PublicInbox::Listener';
420 my $fl = fcntl($s, F_GETFD, 0);
421 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
424 die "Failed to exec: $!\n";
429 sub kill_workers ($) {
432 while (my ($pid, $id) = each %pids) {
437 sub upgrade_aborted ($) {
439 warn "reexec PID($p) died with: $?\n";
441 return unless $pid_file;
443 my $file = $pid_file;
444 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
445 unlink_pid_file_safe_ish($$, $pid_file);
447 eval { write_pid($pid_file) };
451 sub reap_children { # $_[0] = 'CHLD' or POSIX::SIGCHLD()
453 my $p = waitpid(-1, WNOHANG) or return;
454 if (defined $reexec_pid && $p == $reexec_pid) {
456 } elsif (defined(my $id = delete $pids{$p})) {
457 warn "worker[$id] PID($p) died with: $?\n";
459 warn "unknown PID($p) reaped: $?\n";
466 sub unlink_pid_file_safe_ish ($$) {
467 my ($unlink_pid, $file) = @_;
468 return unless defined $unlink_pid && $unlink_pid == $$;
470 open my $fh, '<', $file or return;
472 defined(my $read_pid = <$fh>) or return;
474 if ($read_pid == $unlink_pid) {
475 Net::Server::Daemonize::unlink_pid_file($file);
479 sub master_quit ($) {
480 exit unless @listeners;
486 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
487 my $set_workers = $worker_processes;
491 USR1 => sub { reopen_logs(); kill_workers($_[0]); },
493 QUIT => \&master_quit,
494 INT => \&master_quit,
495 TERM => \&master_quit,
497 return if $ignore_winch || !@listeners;
498 if (-t STDIN || -t STDOUT || -t STDERR) {
501 ignoring SIGWINCH since we are not daemonized
504 $worker_processes = 0;
508 return unless @listeners;
509 $worker_processes = $set_workers;
513 return unless @listeners;
514 if ($set_workers > $worker_processes) {
517 $worker_processes = ++$set_workers;
521 $worker_processes = --$set_workers if $set_workers > 0;
523 CHLD => \&reap_children,
525 my $sigfd = PublicInbox::Sigfd->new($sig, 0);
526 local %SIG = (%SIG, %$sig) if !$sigfd;
527 PublicInbox::Sigfd::sig_setmask($oldset) if !$sigfd;
528 while (1) { # main loop
529 my $n = scalar keys %pids;
530 unless (@listeners) {
532 $set_workers = $worker_processes = $n = 0;
535 if ($n > $worker_processes) {
536 while (my ($k, $v) = each %pids) {
537 kill('TERM', $k) if $v >= $worker_processes;
539 $n = $worker_processes;
541 my $want = $worker_processes - 1;
543 PublicInbox::Sigfd::block_signals() if !$sigfd;
544 for my $i ($n..$want) {
547 warn "failed to fork worker[$i]: $!\n";
548 } elsif ($pid == 0) {
549 $set_user->() if $set_user;
550 return $p0; # run normal work code
552 warn "PID=$pid is worker[$i]\n";
556 PublicInbox::Sigfd::sig_setmask($oldset) if !$sigfd;
559 if ($sigfd) { # Linux and IO::KQueue users:
561 } else { # wake up every second
565 exit # never gets here, just for documentation
568 sub tls_start_cb ($$) {
569 my ($opt, $orig_post_accept) = @_;
571 my ($io, $addr, $srv) = @_;
572 my $ssl = IO::Socket::SSL->start_SSL($io, %$opt);
573 $orig_post_accept->($ssl, $addr, $srv);
577 sub defer_accept ($$) {
578 my ($s, $af_name) = @_;
579 return unless defined $af_name;
580 if ($^O eq 'linux') {
581 my $TCP_DEFER_ACCEPT = 9; # Socket::TCP_DEFER_ACCEPT is in 5.14+
582 my $x = getsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT);
583 return unless defined $x; # may be Unix socket
584 my $sec = unpack('i', $x);
585 return if $sec > 0; # systemd users may set a higher value
586 setsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 1);
587 } elsif ($^O eq 'freebsd') {
588 my $x = getsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER);
589 return if defined $x; # don't change if set
590 my $accf_arg = pack('a16a240', $af_name, '');
591 setsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER, $accf_arg);
595 sub daemon_loop ($$$$) {
596 my ($refresh, $post_accept, $tlsd, $af_default) = @_;
598 while (my ($k, $v) = each %tls_opt) {
599 if ($k =~ s!\A(?:https|imaps|nntps)://!!) {
600 $post_accept{$k} = tls_start_cb($v, $post_accept);
601 } elsif ($tlsd) { # STARTTLS, $k eq '' is OK
602 $tlsd->{accept_tls} = $v;
607 INT => \&worker_quit,
608 QUIT => \&worker_quit,
609 TERM => \&worker_quit,
612 USR1 => \&reopen_logs,
615 CHLD => \&PublicInbox::DS::enqueue_reap,
617 if ($worker_processes > 0) {
618 $refresh->(); # preload by default
619 my $fh = master_loop(); # returns if in child process
620 PublicInbox::EOFpipe->new($fh, \&worker_quit, undef);
623 $set_user->() if $set_user;
624 $sig->{USR2} = sub { worker_quit() if upgrade() };
630 my $tls_cb = $post_accept{sockname($_)};
632 # NNTPS, HTTPS, HTTP, IMAPS and POP3S are client-first traffic
633 # IMAP, NNTP and POP3 are server-first
634 defer_accept($_, $tls_cb ? 'dataready' : $af_default);
636 # this calls epoll_create:
637 PublicInbox::Listener->new($_, $tls_cb || $post_accept)
639 my $sigfd = PublicInbox::Sigfd->new($sig, $SFD_NONBLOCK);
640 local %SIG = (%SIG, %$sig) if !$sigfd;
642 # wake up every second to accept signals if we don't
643 # have signalfd or IO::KQueue:
644 PublicInbox::Sigfd::sig_setmask($oldset);
645 PublicInbox::DS->SetLoopTimeout(1000);
647 PublicInbox::DS->EventLoop;
651 my ($default, $refresh, $post_accept, $tlsd) = @_;
652 local $SIG{PIPE} = 'IGNORE';
653 daemon_prepare($default);
654 my $af_default = $default =~ /:8080\z/ ? 'httpready' : undef;
655 my $for_destroy = daemonize();
657 # localize GCF2C for tests:
658 local $PublicInbox::GitAsyncCat::GCF2C;
660 daemon_loop($refresh, $post_accept, $tlsd, $af_default);
661 PublicInbox::DS->Reset;
662 # ->DESTROY runs when $for_destroy goes out-of-scope
667 if (defined $uid and !chown($uid, $gid, $path)) {
668 warn "could not chown $path: $!\n";
674 Net::Server::Daemonize::create_pid_file($path);
679 unlink_pid_file_safe_ish($_[0]->{pid}, ${$_[0]->{pid_file}});