1 # Copyright (C) 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 };
80 my $modc = "PublicInbox::\U$scheme";
82 eval "require $mod"; # IMAPD|HTTPD|NNTPD|POP3D
84 my %xn = map { $_ => $mod->can($_) } qw(refresh post_accept);
85 $xn{tlsd} = $mod->new if $mod->can('refresh_groups'); #!HTTPD
87 $xn{refresh} //= sub { $tlsd->refresh_groups(@_) };
88 $xn{post_accept} //= sub { $modc->new($_[0], $tlsd) };
89 $xn{af_default} = 'httpready' if $modc eq 'PublicInbox::HTTP';
93 sub daemon_prepare ($$) {
94 my ($default_listen, $xnetd) = @_;
95 my $listener_names = {}; # sockname => IO::Handle
96 $oldset = PublicInbox::DS::block_signals();
98 my ($prog) = ($CMD[0] =~ m!([^/]+)\z!g);
99 my $dh = defined($default_listen) ? " (default: $default_listen)" : '';
101 usage: $prog [-l ADDRESS] [--cert=FILE] [--key=FILE]
105 -l ADDRESS address to listen on$dh
106 --cert=FILE default SSL/TLS certificate
107 --key=FILE default SSL/TLS certificate
108 -W WORKERS number of worker processes to spawn (default: 1)
110 See public-inbox-daemon(8) and $prog(1) man pages for more.
113 'l|listen=s' => \@cfg_listen,
114 '1|stdout=s' => \$stdout,
115 '2|stderr=s' => \$stderr,
116 'W|worker-processes=i' => \$worker_processes,
117 'P|pid-file=s' => \$pid_file,
118 'u|user=s' => \$user,
119 'g|group=s' => \$group,
120 'D|daemonize' => \$daemonize,
121 'cert=s' => \$default_cert,
122 'key=s' => \$default_key,
123 'help|h' => \(my $show_help),
125 GetOptions(%opt) or die $help;
126 if ($show_help) { print $help; exit 0 };
128 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
129 die "--pid-file cannot end with '.oldbin'\n";
131 @listeners = inherit($listener_names);
133 # allow socket-activation users to set certs once and not
134 # have to configure each socket:
135 my @inherited_names = keys(%$listener_names) if defined($default_cert);
137 # ignore daemonize when inheriting
138 $daemonize = undef if scalar @listeners;
140 unless (@listeners || @cfg_listen) {
141 $default_listen // die "no listeners specified\n";
142 push @cfg_listen, $default_listen
145 foreach my $l (@cfg_listen) {
148 if ($l =~ s!\A([^:]+)://!!) {
150 } elsif ($l =~ /\A(?:\[[^\]]+\]|[^:]+):([0-9])+/) {
151 my $s = $KNOWN_TLS{$1} // $KNOWN_STARTTLS{$1};
152 $scheme = $s if defined $s;
154 if ($l =~ s!/?\?(.+)\z!!) {
155 $tls_opt{"$scheme://$l"} = accept_tls_opt($1);
156 } elsif (defined($default_cert)) {
157 $tls_opt{"$scheme://$l"} = accept_tls_opt('');
158 } elsif ($scheme =~ /\A(?:https|imaps|imaps)\z/) {
159 die "$orig specified w/o cert=\n";
161 $scheme =~ /\A(http|imap|nntp|pop3)/ and
162 $xnetd->{$l} = load_mod($1);
164 next if $listener_names->{$l}; # already inherited
166 if (index($l, '/') == 0) {
167 $sock_pkg = 'IO::Socket::UNIX';
168 eval "use $sock_pkg";
170 %o = (Type => SOCK_STREAM, Peer => $l);
172 my $c = $sock_pkg->new(%o);
173 if (!defined($c) && $!{ECONNREFUSED}) {
175 "failed to unlink stale socket=$l: $!\n";
176 } # else: let the bind fail
178 $o{Local} = delete $o{Peer};
180 # both work for IPv4, too
181 for (qw(IO::Socket::IP IO::Socket::INET6)) {
183 eval "use $sock_pkg";
187 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
190 my $prev = umask 0000;
191 my $s = eval { $sock_pkg->new(%o) };
192 warn "error binding $l: $! ($@)\n" unless $s;
195 $listener_names->{sockname($s)} = $s;
201 # cert/key options in @cfg_listen takes precedence when inheriting,
202 # but map well-known inherited ports if --listen isn't specified
204 for my $sockname (@inherited_names) {
205 $sockname =~ /:([0-9]+)\z/ or next;
206 if (my $scheme = $KNOWN_TLS{$1}) {
207 $xnetd->{$sockname} = load_mod(substr($scheme, 0, -1));
208 $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt('');
209 } elsif (($scheme = $KNOWN_STARTTLS{$1})) {
210 $xnetd->{$sockname} = load_mod($scheme);
211 next if $tls_opt{"$scheme://$sockname"};
212 $tls_opt{''} ||= accept_tls_opt('');
216 die "No listeners bound\n" unless @listeners;
219 sub check_absolute ($$) {
220 my ($var, $val) = @_;
221 if (defined $val && index($val, '/') != 0) {
223 "--$var must be an absolute path when using --daemonize: $val\n";
230 foreach my $i (0..$#ARGV) {
233 $ARGV[$i] = Cwd::abs_path($arg);
235 check_absolute('stdout', $stdout);
236 check_absolute('stderr', $stderr);
237 check_absolute('pid-file', $pid_file);
239 chdir '/' or die "chdir failed: $!";
241 if (defined($pid_file) || defined($group) || defined($user)) {
242 eval { require Net::Server::Daemonize; 1 } // die <<EOF;
243 Net::Server required for --pid-file, --group, --user
247 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
248 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
249 if (defined $group) {
250 $gid = Net::Server::Daemonize::get_gid($group);
251 $gid = (split /\s+/, $gid)[0];
252 } elsif (defined $uid) {
253 $gid = (getpwuid($uid))[3];
256 # We change users in the worker to ensure upgradability,
257 # The upgrade will create the ".oldbin" pid file in the
258 # same directory as the given pid file.
259 $uid and $set_user = sub {
261 Net::Server::Daemonize::set_user($uid, $gid);
265 my $pid = fork // die "fork: $!";
268 open(STDIN, '+<', '/dev/null') or
269 die "redirect stdin failed: $!\n";
270 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
271 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
273 $pid = fork // die "fork: $!";
276 return unless defined $pid_file;
278 write_pid($pid_file);
280 bless { pid => $$, pid_file => \$pid_file }, __PACKAGE__;
283 sub worker_quit { # $_[0] = signal name or number (unused)
284 # killing again terminates immediately:
285 exit unless @listeners;
287 $_->close foreach @listeners; # call PublicInbox::DS::close
291 # drop idle connections and try to quit gracefully
292 PublicInbox::DS->SetPostLoopCallback(sub {
293 my ($dmap, undef) = @_;
296 for my $s (values %$dmap) {
297 $s->can('busy') or next;
300 } else { # close as much as possible, early as possible
305 if (($warn + 5) < now()) {
306 warn "$$ quitting, $n client(s) left\n";
309 unless (defined $proc_name) {
310 $proc_name = (split(/\s+/, $0))[0];
311 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
313 $0 = "$proc_name quitting, $n client(s) left";
315 $n; # true: loop continues, false: loop breaks
321 open STDOUT, '>>', $stdout or
322 warn "failed to redirect stdout to $stdout: $!\n";
323 STDOUT->autoflush(1);
327 open STDERR, '>>', $stderr or
328 warn "failed to redirect stderr to $stderr: $!\n";
329 STDERR->autoflush(1);
336 my $addr = getsockname($s) or return;
337 my ($host, $port) = host_with_port($addr);
338 if ($port == 0 && $host eq '127.0.0.1') {
339 my ($path) = Socket::sockaddr_un($addr);
345 sub unpack_ipv6 ($) {
349 # Socket.pm in Perl 5.14+ supports IPv6:
351 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
352 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
356 # Perl 5.12 or earlier? SpamAssassin and Net::Server use
357 # Socket6, so it may be installed on our system, already
358 # (otherwise die here):
361 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
362 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
367 sub host_with_port ($) {
371 # this eval will die on Unix sockets:
373 if (length($addr) >= 28) {
374 ($host, $port) = unpack_ipv6($addr);
377 ($port, $host) = Socket::sockaddr_in($addr);
378 $host = Socket::inet_ntoa($host);
381 $@ ? ('127.0.0.1', 0) : ($host, $port);
385 my ($listener_names) = @_;
386 return () if ($ENV{LISTEN_PID} || 0) != $$;
387 my $fds = $ENV{LISTEN_FDS} or return ();
388 my $end = $fds + 2; # LISTEN_FDS_START - 1
390 foreach my $fd (3..$end) {
391 open(my $s, '<&=', $fd) or warn "fdopen fd=$fd: $!";
392 if (my $k = sockname($s)) {
393 my $prev_was_blocking = $s->blocking(0);
394 warn <<"" if $prev_was_blocking;
395 Inherited socket (fd=$fd) is blocking, making it non-blocking.
396 Set 'NonBlocking = true' in the systemd.service unit to avoid stalled
397 processes when multiple service instances start.
399 $listener_names->{$k} = $s;
402 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
408 sub upgrade { # $_[0] = signal name or number (unused)
410 warn "upgrade in-progress: $reexec_pid\n";
413 if (defined $pid_file) {
414 if ($pid_file =~ /\.oldbin\z/) {
415 warn "BUG: .oldbin suffix exists: $pid_file\n";
418 unlink_pid_file_safe_ish($$, $pid_file);
419 $pid_file .= '.oldbin';
420 write_pid($pid_file);
423 unless (defined $pid) {
424 warn "fork failed: $!\n";
428 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
429 $ENV{LISTEN_FDS} = scalar @listeners;
430 $ENV{LISTEN_PID} = $$;
431 foreach my $s (@listeners) {
432 # @listeners are globs with workers, PI::L w/o workers
433 $s = $s->{sock} if ref($s) eq 'PublicInbox::Listener';
435 my $fl = fcntl($s, F_GETFD, 0);
436 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
439 die "Failed to exec: $!\n";
444 sub kill_workers ($) {
446 kill $sig, keys(%pids);
449 sub upgrade_aborted ($) {
451 warn "reexec PID($p) died with: $?\n";
453 return unless $pid_file;
455 my $file = $pid_file;
456 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
457 unlink_pid_file_safe_ish($$, $pid_file);
459 eval { write_pid($pid_file) };
463 sub reap_children { # $_[0] = 'CHLD' or POSIX::SIGCHLD()
465 my $p = waitpid(-1, WNOHANG) or return;
466 if (defined $reexec_pid && $p == $reexec_pid) {
468 } elsif (defined(my $id = delete $pids{$p})) {
469 warn "worker[$id] PID($p) died with: $?\n";
471 warn "unknown PID($p) reaped: $?\n";
478 sub unlink_pid_file_safe_ish ($$) {
479 my ($unlink_pid, $file) = @_;
480 return unless defined $unlink_pid && $unlink_pid == $$;
482 open my $fh, '<', $file or return;
484 defined(my $read_pid = <$fh>) or return;
486 if ($read_pid == $unlink_pid) {
487 Net::Server::Daemonize::unlink_pid_file($file);
491 sub master_quit ($) {
492 exit unless @listeners;
498 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
499 my $set_workers = $worker_processes;
503 USR1 => sub { reopen_logs(); kill_workers($_[0]); },
505 QUIT => \&master_quit,
506 INT => \&master_quit,
507 TERM => \&master_quit,
509 return if $ignore_winch || !@listeners;
510 if (-t STDIN || -t STDOUT || -t STDERR) {
513 ignoring SIGWINCH since we are not daemonized
516 $worker_processes = 0;
520 return unless @listeners;
521 $worker_processes = $set_workers;
525 return unless @listeners;
526 if ($set_workers > $worker_processes) {
529 $worker_processes = ++$set_workers;
533 $worker_processes = --$set_workers if $set_workers > 0;
535 CHLD => \&reap_children,
537 my $sigfd = PublicInbox::Sigfd->new($sig);
538 local @SIG{keys %$sig} = values(%$sig) unless $sigfd;
539 PublicInbox::DS::sig_setmask($oldset) if !$sigfd;
540 while (1) { # main loop
541 my $n = scalar keys %pids;
542 unless (@listeners) {
544 $set_workers = $worker_processes = $n = 0;
547 if ($n > $worker_processes) {
548 while (my ($k, $v) = each %pids) {
549 kill('TERM', $k) if $v >= $worker_processes;
551 $n = $worker_processes;
553 my $want = $worker_processes - 1;
555 PublicInbox::DS::block_signals() if !$sigfd;
556 for my $i ($n..$want) {
557 my $seed = rand(0xffffffff);
560 warn "failed to fork worker[$i]: $!\n";
561 } elsif ($pid == 0) {
563 eval { Net::SSLeay::randomize() };
564 $set_user->() if $set_user;
565 return $p0; # run normal work code
567 warn "PID=$pid is worker[$i]\n";
571 PublicInbox::DS::sig_setmask($oldset) if !$sigfd;
574 if ($sigfd) { # Linux and IO::KQueue users:
576 } else { # wake up every second
580 exit # never gets here, just for documentation
583 sub tls_start_cb ($$) {
584 my ($opt, $orig_post_accept) = @_;
586 my ($io, $addr, $srv) = @_;
587 my $ssl = IO::Socket::SSL->start_SSL($io, %$opt);
588 $orig_post_accept->($ssl, $addr, $srv);
592 sub defer_accept ($$) {
593 my ($s, $af_name) = @_;
594 return unless defined $af_name;
595 if ($^O eq 'linux') {
596 my $TCP_DEFER_ACCEPT = 9; # Socket::TCP_DEFER_ACCEPT is in 5.14+
597 my $x = getsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT);
598 return unless defined $x; # may be Unix socket
599 my $sec = unpack('i', $x);
600 return if $sec > 0; # systemd users may set a higher value
601 setsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 1);
602 } elsif ($^O eq 'freebsd') {
603 my $x = getsockopt($s, SOL_SOCKET, $SO_ACCEPTFILTER);
604 return if defined $x; # don't change if set
605 my $accf_arg = pack('a16a240', $af_name, '');
606 setsockopt($s, SOL_SOCKET, $SO_ACCEPTFILTER, $accf_arg);
610 sub daemon_loop ($) {
614 for my $xn (values %$xnetd) {
615 eval { $xn->{refresh}->($sig) };
616 warn "refresh $@\n" if $@;
620 while (my ($k, $v) = each %tls_opt) {
622 $l =~ s!\A([^:]+)://!!;
623 my $scheme = $1 // '';
624 my $xn = $xnetd->{$l} // $xnetd->{''};
625 if ($scheme =~ m!\A(?:https|imaps|nntps)!) {
626 $post_accept{$l} = tls_start_cb($v, $xn->{post_accept});
627 } elsif ($xn->{tlsd}) { # STARTTLS, $k eq '' is OK
628 $xn->{tlsd}->{accept_tls} = $v;
633 INT => \&worker_quit,
634 QUIT => \&worker_quit,
635 TERM => \&worker_quit,
638 USR1 => \&reopen_logs,
641 CHLD => \&PublicInbox::DS::enqueue_reap,
643 if ($worker_processes > 0) {
644 $refresh->(); # preload by default
645 my $fh = master_loop(); # returns if in child process
646 PublicInbox::EOFpipe->new($fh, \&worker_quit, undef);
649 $set_user->() if $set_user;
650 $sig->{USR2} = sub { worker_quit() if upgrade() };
656 my $l = sockname($_);
657 my $tls_cb = $post_accept{$l};
658 my $xn = $xnetd->{$l} // $xnetd->{''};
660 # NNTPS, HTTPS, HTTP, IMAPS and POP3S are client-first traffic
661 # IMAP, NNTP and POP3 are server-first
662 defer_accept($_, $tls_cb ? 'dataready' : $xn->{af_default});
664 # this calls epoll_create:
665 PublicInbox::Listener->new($_, $tls_cb || $xn->{post_accept})
667 PublicInbox::DS::event_loop($sig, $oldset);
671 my ($default_listen) = @_;
673 if ($default_listen) {
674 $default_listen =~ /\A(http|imap|nntp|pop3)/ or
675 die "BUG: $default_listen";
676 $xnetd->{''} = load_mod($1);
678 daemon_prepare($default_listen, $xnetd);
679 my $for_destroy = daemonize();
681 # localize GCF2C for tests:
682 local $PublicInbox::GitAsyncCat::GCF2C;
683 local $PublicInbox::Git::async_warn = 1;
684 local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb();
687 PublicInbox::DS->Reset;
688 # ->DESTROY runs when $for_destroy goes out-of-scope
693 if (defined $uid and !chown($uid, $gid, $path)) {
694 warn "could not chown $path: $!\n";
700 Net::Server::Daemonize::create_pid_file($path);
705 unlink_pid_file_safe_ish($_[0]->{pid}, ${$_[0]->{pid_file}});