1 # Copyright (C) 2015-2019 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 nntpd and httpd 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/;
11 use POSIX qw(WNOHANG);
12 use Socket qw(IPPROTO_TCP SOL_SOCKET);
13 sub SO_ACCEPTFILTER () { 0x1000 }
17 use PublicInbox::DS qw(now);
18 require PublicInbox::EvCleanup;
19 require PublicInbox::Listener;
20 require PublicInbox::ParentPipe;
23 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
24 my $worker_processes = 1;
27 my %listener_names; # sockname => IO::Handle
28 my %tls_opt; # scheme://sockname => args for IO::Socket::SSL->start_SSL
32 my ($default_cert, $default_key);
33 END { $cleanup->() if $cleanup };
34 my %KNOWN_TLS = ( 443 => 'https', 563 => 'nntps' );
35 my %KNOWN_STARTTLS = ( 119 => 'nntp' );
37 sub accept_tls_opt ($) {
39 # opt_str: opt1=val1,opt2=val2 (opt may repeat for multi-value)
40 require PublicInbox::TLS;
42 # allow ',' as delimiter since '&' is shell-unfriendly
43 foreach (split(/[,&]/, $opt_str)) {
44 my ($k, $v) = split(/=/, $_, 2);
45 push @{$o->{$k} ||= []}, $v;
48 # key may be a part of cert. At least
49 # p5-io-socket-ssl/example/ssl_server.pl has this fallback:
50 $o->{cert} //= [ $default_cert ];
51 $o->{key} //= defined($default_key) ? [ $default_key ] : $o->{cert};
52 my %ctx_opt = (SSL_server => 1);
53 # parse out hostname:/path/to/ mappings:
54 foreach my $k (qw(cert key)) {
55 my $x = $ctx_opt{'SSL_'.$k.'_file'} = {};
56 foreach my $path (@{$o->{$k}}) {
58 $path =~ s/\A([^:]+):// and $host = $1;
62 my $ctx = IO::Socket::SSL::SSL_Context->new(%ctx_opt) or
63 die 'SSL_Context->new: '.PublicInbox::TLS::err();
65 # save ~34K per idle connection (cf. SSL_CTX_set_mode(3ssl))
66 # RSS goes from 346MB to 171MB with 10K idle NNTPS clients on amd64
67 # cf. https://rt.cpan.org/Ticket/Display.html?id=129463
68 my $mode = eval { Net::SSLeay::MODE_RELEASE_BUFFERS() };
69 if ($mode && $ctx->{context}) {
70 eval { Net::SSLeay::CTX_set_mode($ctx->{context}, $mode) };
71 warn "W: $@ (setting SSL_MODE_RELEASE_BUFFERS)\n" if $@;
74 { SSL_server => 1, SSL_startHandshake => 0, SSL_reuse_ctx => $ctx };
77 sub daemon_prepare ($) {
78 my ($default_listen) = @_;
80 $SIG{HUP} = $SIG{USR1} = $SIG{USR2} = $SIG{PIPE} =
81 $SIG{TTIN} = $SIG{TTOU} = $SIG{WINCH} = 'IGNORE';
83 'l|listen=s' => \@cfg_listen,
84 '1|stdout=s' => \$stdout,
85 '2|stderr=s' => \$stderr,
86 'W|worker-processes=i' => \$worker_processes,
87 'P|pid-file=s' => \$pid_file,
89 'g|group=s' => \$group,
90 'D|daemonize' => \$daemonize,
91 'cert=s' => \$default_cert,
92 'key=s' => \$default_key,
94 GetOptions(%opts) or die "bad command-line args\n";
96 if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
97 die "--pid-file cannot end with '.oldbin'\n";
99 @listeners = inherit();
101 # allow socket-activation users to set certs once and not
102 # have to configure each socket:
103 my @inherited_names = keys(%listener_names) if defined($default_cert);
105 # ignore daemonize when inheriting
106 $daemonize = undef if scalar @listeners;
108 push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
110 foreach my $l (@cfg_listen) {
113 if ($l =~ s!\A([^:]+)://!!) {
115 } elsif ($l =~ /\A(?:\[[^\]]+\]|[^:]+):([0-9])+/) {
116 my $s = $KNOWN_TLS{$1} // $KNOWN_STARTTLS{$1};
117 $scheme = $s if defined $s;
119 if ($l =~ s!/?\?(.+)\z!!) {
120 $tls_opt{"$scheme://$l"} = accept_tls_opt($1);
121 } elsif (defined($default_cert)) {
122 $tls_opt{"$scheme://$l"} = accept_tls_opt('');
123 } elsif ($scheme =~ /\A(?:nntps|https)\z/) {
124 die "$orig specified w/o cert=\n";
126 # TODO: use scheme to load either NNTP.pm or HTTP.pm
128 next if $listener_names{$l}; # already inherited
130 if (index($l, '/') == 0) {
131 $sock_pkg = 'IO::Socket::UNIX';
132 eval "use $sock_pkg";
134 %o = (Type => SOCK_STREAM, Peer => $l);
136 my $c = $sock_pkg->new(%o);
137 if (!defined($c) && $!{ECONNREFUSED}) {
139 "failed to unlink stale socket=$l: $!\n";
140 } # else: let the bind fail
142 $o{Local} = delete $o{Peer};
144 # both work for IPv4, too
145 for (qw(IO::Socket::IP IO::Socket::INET6)) {
147 eval "use $sock_pkg";
151 %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
154 my $prev = umask 0000;
155 my $s = eval { $sock_pkg->new(%o) };
156 warn "error binding $l: $! ($@)\n" unless $s;
159 $listener_names{sockname($s)} = $s;
165 # cert/key options in @cfg_listen takes precedence when inheriting,
166 # but map well-known inherited ports if --listen isn't specified
168 for my $sockname (@inherited_names) {
169 $sockname =~ /:([0-9]+)\z/ or next;
170 if (my $scheme = $KNOWN_TLS{$1}) {
171 $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt('');
172 } elsif (($scheme = $KNOWN_STARTTLS{$1})) {
173 next if $tls_opt{"$scheme://$sockname"};
174 $tls_opt{''} ||= accept_tls_opt('');
178 die "No listeners bound\n" unless @listeners;
181 sub check_absolute ($$) {
182 my ($var, $val) = @_;
183 if (defined $val && index($val, '/') != 0) {
185 "--$var must be an absolute path when using --daemonize: $val\n";
191 foreach my $i (0..$#ARGV) {
194 $ARGV[$i] = abs_path($arg);
196 check_absolute('stdout', $stdout);
197 check_absolute('stderr', $stderr);
198 check_absolute('pid-file', $pid_file);
200 chdir '/' or die "chdir failed: $!";
203 return unless (defined $pid_file || defined $group || defined $user
206 eval { require Net::Server::Daemonize };
209 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
212 Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
213 $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
214 if (defined $group) {
215 $gid = Net::Server::Daemonize::get_gid($group);
216 $gid = (split /\s+/, $gid)[0];
217 } elsif (defined $uid) {
218 $gid = (getpwuid($uid))[3];
221 # We change users in the worker to ensure upgradability,
222 # The upgrade will create the ".oldbin" pid file in the
223 # same directory as the given pid file.
224 $uid and $set_user = sub {
226 Net::Server::Daemonize::set_user($uid, $gid);
231 die "could not fork: $!\n" unless defined $pid;
234 open(STDIN, '+<', '/dev/null') or
235 die "redirect stdin failed: $!\n";
236 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
237 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
240 die "could not fork: $!\n" unless defined $pid;
243 if (defined $pid_file) {
244 write_pid($pid_file);
247 $cleanup = undef; # avoid cyclic reference
248 unlink_pid_file_safe_ish($unlink_pid, $pid_file);
255 # killing again terminates immediately:
256 exit unless @listeners;
258 $_->close foreach @listeners; # call PublicInbox::DS::close
263 # drop idle connections and try to quit gracefully
264 PublicInbox::DS->SetPostLoopCallback(sub {
265 my ($dmap, undef) = @_;
269 foreach my $s (values %$dmap) {
270 $s->can('busy') or next;
271 if ($s->busy($now)) {
274 # close as much as possible, early as possible
279 if (($warn + 5) < now()) {
280 warn "$$ quitting, $n client(s) left\n";
283 unless (defined $proc_name) {
284 $proc_name = (split(/\s+/, $0))[0];
285 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
287 $0 = "$proc_name quitting, $n client(s) left";
289 $n; # true: loop continues, false: loop breaks
295 open STDOUT, '>>', $stdout or
296 warn "failed to redirect stdout to $stdout: $!\n";
297 STDOUT->autoflush(1);
301 open STDERR, '>>', $stderr or
302 warn "failed to redirect stderr to $stderr: $!\n";
303 STDERR->autoflush(1);
310 my $addr = getsockname($s) or return;
311 my ($host, $port) = host_with_port($addr);
312 if ($port == 0 && $host eq '127.0.0.1') {
313 my ($path) = Socket::sockaddr_un($addr);
319 sub unpack_ipv6 ($) {
323 # Socket.pm in Perl 5.14+ supports IPv6:
325 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
326 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
330 # Perl 5.12 or earlier? SpamAssassin and Net::Server use
331 # Socket6, so it may be installed on our system, already
332 # (otherwise die here):
335 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
336 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
341 sub host_with_port ($) {
345 # this eval will die on Unix sockets:
347 if (length($addr) >= 28) {
348 ($host, $port) = unpack_ipv6($addr);
351 ($port, $host) = Socket::sockaddr_in($addr);
352 $host = Socket::inet_ntoa($host);
355 $@ ? ('127.0.0.1', 0) : ($host, $port);
359 return () if ($ENV{LISTEN_PID} || 0) != $$;
360 my $fds = $ENV{LISTEN_FDS} or return ();
361 my $end = $fds + 2; # LISTEN_FDS_START - 1
363 foreach my $fd (3..$end) {
364 my $s = IO::Handle->new_from_fd($fd, 'r');
365 if (my $k = sockname($s)) {
369 Inherited socket (fd=$fd) is blocking, making it non-blocking.
370 Set 'NonBlocking = true' in the systemd.service unit to avoid stalled
371 processes when multiple service instances start.
374 $listener_names{$k} = $s;
377 warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
385 warn "upgrade in-progress: $reexec_pid\n";
388 if (defined $pid_file) {
389 if ($pid_file =~ /\.oldbin\z/) {
390 warn "BUG: .oldbin suffix exists: $pid_file\n";
393 unlink_pid_file_safe_ish($$, $pid_file);
394 $pid_file .= '.oldbin';
395 write_pid($pid_file);
398 unless (defined $pid) {
399 warn "fork failed: $!\n";
403 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
404 $ENV{LISTEN_FDS} = scalar @listeners;
405 $ENV{LISTEN_PID} = $$;
406 foreach my $s (@listeners) {
407 my $fl = fcntl($s, F_GETFD, 0);
408 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
411 die "Failed to exec: $!\n";
416 sub kill_workers ($) {
419 while (my ($pid, $id) = each %pids) {
424 sub upgrade_aborted ($) {
426 warn "reexec PID($p) died with: $?\n";
428 return unless $pid_file;
430 my $file = $pid_file;
431 $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
432 unlink_pid_file_safe_ish($$, $pid_file);
434 eval { write_pid($pid_file) };
438 sub reap_children () {
440 my $p = waitpid(-1, WNOHANG) or return;
441 if (defined $reexec_pid && $p == $reexec_pid) {
443 } elsif (defined(my $id = delete $pids{$p})) {
444 warn "worker[$id] PID($p) died with: $?\n";
446 warn "unknown PID($p) reaped: $?\n";
453 sub unlink_pid_file_safe_ish ($$) {
454 my ($unlink_pid, $file) = @_;
455 return unless defined $unlink_pid && $unlink_pid == $$;
457 open my $fh, '<', $file or return;
459 defined(my $read_pid = <$fh>) or return;
461 if ($read_pid == $unlink_pid) {
462 Net::Server::Daemonize::unlink_pid_file($file);
467 pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
468 pipe(my ($r, $w)) or die "failed to create self-pipe: $!";
470 if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ = 1031
471 fcntl($_, 1031, 4096) for ($w, $p1);
474 IO::Handle::blocking($w, 0);
475 my $set_workers = $worker_processes;
478 foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
480 return if $$ != $master_pid;
489 while (my $s = shift @caught) {
493 } elsif ($s eq 'USR2') {
495 } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
498 } elsif ($s eq 'WINCH') {
499 if (-t STDIN || -t STDOUT || -t STDERR) {
501 "ignoring SIGWINCH since we are not daemonized\n";
502 $SIG{WINCH} = 'IGNORE';
504 $worker_processes = 0;
506 } elsif ($s eq 'HUP') {
507 $worker_processes = $set_workers;
509 } elsif ($s eq 'TTIN') {
510 if ($set_workers > $worker_processes) {
513 $worker_processes = ++$set_workers;
515 } elsif ($s eq 'TTOU') {
516 if ($set_workers > 0) {
517 $worker_processes = --$set_workers;
519 } elsif ($s eq 'CHLD') {
524 my $n = scalar keys %pids;
527 $set_workers = $worker_processes = $n = 0;
530 if ($n > $worker_processes) {
531 while (my ($k, $v) = each %pids) {
532 kill('TERM', $k) if $v >= $worker_processes;
534 $n = $worker_processes;
536 foreach my $i ($n..($worker_processes - 1)) {
539 warn "failed to fork worker[$i]: $!\n";
540 } elsif ($pid == 0) {
541 $set_user->() if $set_user;
542 return $p0; # run normal work code
544 warn "PID=$pid is worker[$i]\n";
548 # just wait on signal events here:
549 sysread($r, my $buf, 8);
551 exit # never gets here, just for documentation
554 sub tls_start_cb ($$) {
555 my ($opt, $orig_post_accept) = @_;
557 my ($io, $addr, $srv) = @_;
558 my $ssl = IO::Socket::SSL->start_SSL($io, %$opt);
559 $orig_post_accept->($ssl, $addr, $srv);
563 sub defer_accept ($$) {
564 my ($s, $af_name) = @_;
565 return unless defined $af_name;
566 if ($^O eq 'linux') {
567 my $x = getsockopt($s, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT());
568 return unless defined $x; # may be Unix socket
569 my $sec = unpack('i', $x);
570 return if $sec > 0; # systemd users may set a higher value
571 setsockopt($s, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT(), 1);
572 } elsif ($^O eq 'freebsd') {
573 my $x = getsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER);
574 return if defined $x; # don't change if set
575 my $accf_arg = pack('a16a240', $af_name, '');
576 setsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER, $accf_arg);
580 sub daemon_loop ($$$$) {
581 my ($refresh, $post_accept, $nntpd, $af_default) = @_;
582 PublicInbox::EvCleanup::enable(); # early for $refresh
584 while (my ($k, $v) = each %tls_opt) {
585 if ($k =~ s!\A(?:nntps|https)://!!) {
586 $post_accept{$k} = tls_start_cb($v, $post_accept);
587 } elsif ($nntpd) { # STARTTLS, $k eq '' is OK
588 $nntpd->{accept_tls} = $v;
592 if ($worker_processes > 0) {
593 $refresh->(); # preload by default
594 my $fh = master_loop(); # returns if in child process
595 $parent_pipe = PublicInbox::ParentPipe->new($fh, *worker_quit);
598 $set_user->() if $set_user;
599 $SIG{USR2} = sub { worker_quit() if upgrade() };
604 $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = *worker_quit;
605 $SIG{USR1} = *reopen_logs;
606 $SIG{HUP} = $refresh;
607 $SIG{CHLD} = 'DEFAULT';
608 $SIG{$_} = 'IGNORE' for qw(USR2 TTIN TTOU WINCH);
610 my $tls_cb = $post_accept{sockname($_)};
612 # NNTPS, HTTPS, HTTP, and POP3S are client-first traffic
613 # NNTP and POP3 are server-first
614 defer_accept($_, $tls_cb ? 'dataready' : $af_default);
616 # this calls epoll_create:
617 PublicInbox::Listener->new($_, $tls_cb || $post_accept)
619 PublicInbox::DS->EventLoop;
620 $parent_pipe = undef;
625 my ($default, $refresh, $post_accept, $nntpd) = @_;
626 daemon_prepare($default);
627 my $af_default = $default =~ /:8080\z/ ? 'httpready' : undef;
629 daemon_loop($refresh, $post_accept, $nntpd, $af_default);
634 if (defined $uid and !chown($uid, $gid, $path)) {
635 warn "could not chown $path: $!\n";
641 Net::Server::Daemonize::create_pid_file($path);