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();
81 'l|listen=s' => \@cfg_listen,
82 '1|stdout=s' => \$stdout,
83 '2|stderr=s' => \$stderr,
84 'W|worker-processes=i' => \$worker_processes,
85 'P|pid-file=s' => \$pid_file,
87 'g|group=s' => \$group,
88 'D|daemonize' => \$daemonize,
89 'cert=s' => \$default_cert,
90 'key=s' => \$default_key,
92 GetOptions(%opts) or die "bad command-line args\n";
94 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
95 die "--pid-file cannot end with '.oldbin'\n";
97 @listeners = inherit($listener_names);
99 # allow socket-activation users to set certs once and not
100 # have to configure each socket:
101 my @inherited_names = keys(%$listener_names) if defined($default_cert);
103 # ignore daemonize when inheriting
104 $daemonize = undef if scalar @listeners;
106 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
108 foreach my $l (@cfg_listen) {
111 if ($l =~ s!\A([^:]+)://!!) {
113 } elsif ($l =~ /\A(?:\[[^\]]+\]|[^:]+):([0-9])+/) {
114 my $s = $KNOWN_TLS{$1} // $KNOWN_STARTTLS{$1};
115 $scheme = $s if defined $s;
117 if ($l =~ s!/?\?(.+)\z!!) {
118 $tls_opt{"$scheme://$l"} = accept_tls_opt($1);
119 } elsif (defined($default_cert)) {
120 $tls_opt{"$scheme://$l"} = accept_tls_opt('');
121 } elsif ($scheme =~ /\A(?:https|imaps|imaps)\z/) {
122 die "$orig specified w/o cert=\n";
124 # TODO: use scheme to load either NNTP.pm or HTTP.pm
126 next if $listener_names->{$l}; # already inherited
128 if (index($l, '/') == 0) {
129 $sock_pkg = 'IO::Socket::UNIX';
130 eval "use $sock_pkg";
132 %o = (Type => SOCK_STREAM, Peer => $l);
134 my $c = $sock_pkg->new(%o);
135 if (!defined($c) && $!{ECONNREFUSED}) {
137 "failed to unlink stale socket=$l: $!\n";
138 } # else: let the bind fail
140 $o{Local} = delete $o{Peer};
142 # both work for IPv4, too
143 for (qw(IO::Socket::IP IO::Socket::INET6)) {
145 eval "use $sock_pkg";
149 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
152 my $prev = umask 0000;
153 my $s = eval { $sock_pkg->new(%o) };
154 warn "error binding $l: $! ($@)\n" unless $s;
157 $listener_names->{sockname($s)} = $s;
163 # cert/key options in @cfg_listen takes precedence when inheriting,
164 # but map well-known inherited ports if --listen isn't specified
166 for my $sockname (@inherited_names) {
167 $sockname =~ /:([0-9]+)\z/ or next;
168 if (my $scheme = $KNOWN_TLS{$1}) {
169 $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt('');
170 } elsif (($scheme = $KNOWN_STARTTLS{$1})) {
171 next if $tls_opt{"$scheme://$sockname"};
172 $tls_opt{''} ||= accept_tls_opt('');
176 die "No listeners bound\n" unless @listeners;
179 sub check_absolute ($$) {
180 my ($var, $val) = @_;
181 if (defined $val && index($val, '/') != 0) {
183 "--$var must be an absolute path when using --daemonize: $val\n";
189 foreach my $i (0..$#ARGV) {
192 $ARGV[$i] = abs_path($arg);
194 check_absolute('stdout', $stdout);
195 check_absolute('stderr', $stderr);
196 check_absolute('pid-file', $pid_file);
198 chdir '/' or die "chdir failed: $!";
201 return unless (defined $pid_file || defined $group || defined $user
204 eval { require Net::Server::Daemonize };
207 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
210 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
211 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
212 if (defined $group) {
213 $gid = Net::Server::Daemonize::get_gid($group);
214 $gid = (split /\s+/, $gid)[0];
215 } elsif (defined $uid) {
216 $gid = (getpwuid($uid))[3];
219 # We change users in the worker to ensure upgradability,
220 # The upgrade will create the ".oldbin" pid file in the
221 # same directory as the given pid file.
222 $uid and $set_user = sub {
224 Net::Server::Daemonize::set_user($uid, $gid);
229 die "could not fork: $!\n" unless defined $pid;
232 open(STDIN, '+<', '/dev/null') or
233 die "redirect stdin failed: $!\n";
234 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
235 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
238 die "could not fork: $!\n" unless defined $pid;
241 return unless defined $pid_file;
243 write_pid($pid_file);
245 bless { pid => $$, pid_file => \$pid_file }, __PACKAGE__;
248 sub worker_quit { # $_[0] = signal name or number (unused)
249 # killing again terminates immediately:
250 exit unless @listeners;
252 $_->close foreach @listeners; # call PublicInbox::DS::close
256 # drop idle connections and try to quit gracefully
257 PublicInbox::DS->SetPostLoopCallback(sub {
258 my ($dmap, undef) = @_;
262 foreach my $s (values %$dmap) {
263 $s->can('busy') or next;
264 if ($s->busy($now)) {
267 # close as much as possible, early as possible
272 if (($warn + 5) < now()) {
273 warn "$$ quitting, $n client(s) left\n";
276 unless (defined $proc_name) {
277 $proc_name = (split(/\s+/, $0))[0];
278 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
280 $0 = "$proc_name quitting, $n client(s) left";
282 $n; # true: loop continues, false: loop breaks
288 open STDOUT, '>>', $stdout or
289 warn "failed to redirect stdout to $stdout: $!\n";
290 STDOUT->autoflush(1);
294 open STDERR, '>>', $stderr or
295 warn "failed to redirect stderr to $stderr: $!\n";
296 STDERR->autoflush(1);
303 my $addr = getsockname($s) or return;
304 my ($host, $port) = host_with_port($addr);
305 if ($port == 0 && $host eq '127.0.0.1') {
306 my ($path) = Socket::sockaddr_un($addr);
312 sub unpack_ipv6 ($) {
316 # Socket.pm in Perl 5.14+ supports IPv6:
318 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
319 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
323 # Perl 5.12 or earlier? SpamAssassin and Net::Server use
324 # Socket6, so it may be installed on our system, already
325 # (otherwise die here):
328 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
329 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
334 sub host_with_port ($) {
338 # this eval will die on Unix sockets:
340 if (length($addr) >= 28) {
341 ($host, $port) = unpack_ipv6($addr);
344 ($port, $host) = Socket::sockaddr_in($addr);
345 $host = Socket::inet_ntoa($host);
348 $@ ? ('127.0.0.1', 0) : ($host, $port);
352 my ($listener_names) = @_;
353 return () if ($ENV{LISTEN_PID} || 0) != $$;
354 my $fds = $ENV{LISTEN_FDS} or return ();
355 my $end = $fds + 2; # LISTEN_FDS_START - 1
357 foreach my $fd (3..$end) {
358 my $s = IO::Handle->new_from_fd($fd, 'r');
359 if (my $k = sockname($s)) {
363 Inherited socket (fd=$fd) is blocking, making it non-blocking.
364 Set 'NonBlocking = true' in the systemd.service unit to avoid stalled
365 processes when multiple service instances start.
368 $listener_names->{$k} = $s;
371 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
377 sub upgrade { # $_[0] = signal name or number (unused)
379 warn "upgrade in-progress: $reexec_pid\n";
382 if (defined $pid_file) {
383 if ($pid_file =~ /\.oldbin\z/) {
384 warn "BUG: .oldbin suffix exists: $pid_file\n";
387 unlink_pid_file_safe_ish($$, $pid_file);
388 $pid_file .= '.oldbin';
389 write_pid($pid_file);
392 unless (defined $pid) {
393 warn "fork failed: $!\n";
397 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
398 $ENV{LISTEN_FDS} = scalar @listeners;
399 $ENV{LISTEN_PID} = $$;
400 foreach my $s (@listeners) {
401 # @listeners are globs with workers, PI::L w/o workers
402 $s = $s->{sock} if ref($s) eq 'PublicInbox::Listener';
404 my $fl = fcntl($s, F_GETFD, 0);
405 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
408 die "Failed to exec: $!\n";
413 sub kill_workers ($) {
416 while (my ($pid, $id) = each %pids) {
421 sub upgrade_aborted ($) {
423 warn "reexec PID($p) died with: $?\n";
425 return unless $pid_file;
427 my $file = $pid_file;
428 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
429 unlink_pid_file_safe_ish($$, $pid_file);
431 eval { write_pid($pid_file) };
435 sub reap_children { # $_[0] = 'CHLD' or POSIX::SIGCHLD()
437 my $p = waitpid(-1, WNOHANG) or return;
438 if (defined $reexec_pid && $p == $reexec_pid) {
440 } elsif (defined(my $id = delete $pids{$p})) {
441 warn "worker[$id] PID($p) died with: $?\n";
443 warn "unknown PID($p) reaped: $?\n";
450 sub unlink_pid_file_safe_ish ($$) {
451 my ($unlink_pid, $file) = @_;
452 return unless defined $unlink_pid && $unlink_pid == $$;
454 open my $fh, '<', $file or return;
456 defined(my $read_pid = <$fh>) or return;
458 if ($read_pid == $unlink_pid) {
459 Net::Server::Daemonize::unlink_pid_file($file);
463 sub master_quit ($) {
464 exit unless @listeners;
470 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
471 my $set_workers = $worker_processes;
475 USR1 => sub { reopen_logs(); kill_workers($_[0]); },
477 QUIT => \&master_quit,
478 INT => \&master_quit,
479 TERM => \&master_quit,
481 return if $ignore_winch || !@listeners;
482 if (-t STDIN || -t STDOUT || -t STDERR) {
485 ignoring SIGWINCH since we are not daemonized
488 $worker_processes = 0;
492 return unless @listeners;
493 $worker_processes = $set_workers;
497 return unless @listeners;
498 if ($set_workers > $worker_processes) {
501 $worker_processes = ++$set_workers;
505 $worker_processes = --$set_workers if $set_workers > 0;
507 CHLD => \&reap_children,
509 my $sigfd = PublicInbox::Sigfd->new($sig, 0);
510 local %SIG = (%SIG, %$sig) if !$sigfd;
511 PublicInbox::restore_signals($oldset) if !$sigfd;
512 while (1) { # main loop
513 my $n = scalar keys %pids;
514 unless (@listeners) {
516 $set_workers = $worker_processes = $n = 0;
519 if ($n > $worker_processes) {
520 while (my ($k, $v) = each %pids) {
521 kill('TERM', $k) if $v >= $worker_processes;
523 $n = $worker_processes;
525 my $want = $worker_processes - 1;
527 PublicInbox::Sigfd::block_signals() if !$sigfd;
528 for my $i ($n..$want) {
531 warn "failed to fork worker[$i]: $!\n";
532 } elsif ($pid == 0) {
533 $set_user->() if $set_user;
534 return $p0; # run normal work code
536 warn "PID=$pid is worker[$i]\n";
540 PubliInbox::Sigfd::set_sigmask($oldset) if !$sigfd;
543 if ($sigfd) { # Linux and IO::KQueue users:
545 } else { # wake up every second
549 exit # never gets here, just for documentation
552 sub tls_start_cb ($$) {
553 my ($opt, $orig_post_accept) = @_;
555 my ($io, $addr, $srv) = @_;
556 my $ssl = IO::Socket::SSL->start_SSL($io, %$opt);
557 $orig_post_accept->($ssl, $addr, $srv);
561 sub defer_accept ($$) {
562 my ($s, $af_name) = @_;
563 return unless defined $af_name;
564 if ($^O eq 'linux') {
565 my $TCP_DEFER_ACCEPT = 9; # Socket::TCP_DEFER_ACCEPT is in 5.14+
566 my $x = getsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT);
567 return unless defined $x; # may be Unix socket
568 my $sec = unpack('i', $x);
569 return if $sec > 0; # systemd users may set a higher value
570 setsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 1);
571 } elsif ($^O eq 'freebsd') {
572 my $x = getsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER);
573 return if defined $x; # don't change if set
574 my $accf_arg = pack('a16a240', $af_name, '');
575 setsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER, $accf_arg);
579 sub daemon_loop ($$$$) {
580 my ($refresh, $post_accept, $tlsd, $af_default) = @_;
582 while (my ($k, $v) = each %tls_opt) {
583 if ($k =~ s!\A(?:https|imaps|nntps)://!!) {
584 $post_accept{$k} = tls_start_cb($v, $post_accept);
585 } elsif ($tlsd) { # STARTTLS, $k eq '' is OK
586 $tlsd->{accept_tls} = $v;
591 INT => \&worker_quit,
592 QUIT => \&worker_quit,
593 TERM => \&worker_quit,
596 USR1 => \&reopen_logs,
599 CHLD => \&PublicInbox::DS::enqueue_reap,
601 if ($worker_processes > 0) {
602 $refresh->(); # preload by default
603 my $fh = master_loop(); # returns if in child process
604 PublicInbox::EOFpipe->new($fh, \&worker_quit, undef);
607 $set_user->() if $set_user;
608 $sig->{USR2} = sub { worker_quit() if upgrade() };
614 my $tls_cb = $post_accept{sockname($_)};
616 # NNTPS, HTTPS, HTTP, IMAPS and POP3S are client-first traffic
617 # IMAP, NNTP and POP3 are server-first
618 defer_accept($_, $tls_cb ? 'dataready' : $af_default);
620 # this calls epoll_create:
621 PublicInbox::Listener->new($_, $tls_cb || $post_accept)
623 my $sigfd = PublicInbox::Sigfd->new($sig, $SFD_NONBLOCK);
624 local %SIG = (%SIG, %$sig) if !$sigfd;
626 # wake up every second to accept signals if we don't
627 # have signalfd or IO::KQueue:
628 PublicInbox::Sigfd::set_sigmask($oldset);
629 PublicInbox::DS->SetLoopTimeout(1000);
631 PublicInbox::DS->EventLoop;
635 my ($default, $refresh, $post_accept, $tlsd) = @_;
636 local $SIG{PIPE} = 'IGNORE';
637 daemon_prepare($default);
638 my $af_default = $default =~ /:8080\z/ ? 'httpready' : undef;
639 my $for_destroy = daemonize();
640 daemon_loop($refresh, $post_accept, $tlsd, $af_default);
641 PublicInbox::DS->Reset;
642 # ->DESTROY runs when $for_destroy goes out-of-scope
647 if (defined $uid and !chown($uid, $gid, $path)) {
648 warn "could not chown $path: $!\n";
654 Net::Server::Daemonize::create_pid_file($path);
659 unlink_pid_file_safe_ish($_[0]->{pid}, ${$_[0]->{pid_file}});