X-Git-Url: http://www.git.stargrave.org/?a=blobdiff_plain;f=lib%2FPublicInbox%2FDaemon.pm;h=0392d15f8578260403f89a5c3f28b481a65fced9;hb=c38111d6f3877cf31d28b0a0339d063df0fa58f6;hp=6b92b60dac8ee7e290279c7261717ccab440596f;hpb=2755c6f839f0a0552cd134160e1691380511a61a;p=public-inbox.git diff --git a/lib/PublicInbox/Daemon.pm b/lib/PublicInbox/Daemon.pm index 6b92b60d..0392d15f 100644 --- a/lib/PublicInbox/Daemon.pm +++ b/lib/PublicInbox/Daemon.pm @@ -1,4 +1,4 @@ -# Copyright (C) 2015-2020 all contributors +# Copyright (C) all contributors # License: AGPL-3.0+ # # Contains common daemon code for the httpd, imapd, and nntpd servers @@ -6,53 +6,61 @@ # and/or lossy connections. package PublicInbox::Daemon; use strict; -use warnings; -use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/; +use v5.10.1; +use Getopt::Long qw(:config gnu_getopt no_ignore_case auto_abbrev); use IO::Handle; # ->autoflush use IO::Socket; +use File::Spec; use POSIX qw(WNOHANG :signal_h); use Socket qw(IPPROTO_TCP SOL_SOCKET); -sub SO_ACCEPTFILTER () { 0x1000 } -use Cwd qw/abs_path/; STDOUT->autoflush(1); STDERR->autoflush(1); use PublicInbox::DS qw(now); -use PublicInbox::Syscall qw($SFD_NONBLOCK); -require PublicInbox::Listener; +use PublicInbox::Listener; use PublicInbox::EOFpipe; use PublicInbox::Sigfd; +use PublicInbox::Git; use PublicInbox::GitAsyncCat; +use PublicInbox::Eml; +our $SO_ACCEPTFILTER = 0x1000; my @CMD; my ($set_user, $oldset); my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize); my $worker_processes = 1; my @listeners; -my %pids; +my (%pids, %logs); my %tls_opt; # scheme://sockname => args for IO::Socket::SSL->start_SSL my $reexec_pid; my ($uid, $gid); my ($default_cert, $default_key); -my %KNOWN_TLS = ( 443 => 'https', 563 => 'nntps', 993 => 'imaps' ); -my %KNOWN_STARTTLS = ( 119 => 'nntp', 143 => 'imap' ); +my %KNOWN_TLS = (443 => 'https', 563 => 'nntps', 993 => 'imaps', 995 =>'pop3s'); +my %KNOWN_STARTTLS = (110 => 'pop3', 119 => 'nntp', 143 => 'imap'); -sub accept_tls_opt ($) { - my ($opt_str) = @_; - # opt_str: opt1=val1,opt2=val2 (opt may repeat for multi-value) - require PublicInbox::TLS; +sub listener_opt ($) { + my ($str) = @_; # opt1=val1,opt2=val2 (opt may repeat for multi-value) my $o = {}; # allow ',' as delimiter since '&' is shell-unfriendly - foreach (split(/[,&]/, $opt_str)) { + for (split(/[,&]/, $str)) { my ($k, $v) = split(/=/, $_, 2); - push @{$o->{$k} ||= []}, $v; + push @{$o->{$k}}, $v; } # key may be a part of cert. At least # p5-io-socket-ssl/example/ssl_server.pl has this fallback: - $o->{cert} //= [ $default_cert ]; + $o->{cert} //= [ $default_cert ] if defined($default_cert); $o->{key} //= defined($default_key) ? [ $default_key ] : $o->{cert}; + $o; +} + +sub accept_tls_opt ($) { + my ($opt) = @_; + my $o = ref($opt) eq 'HASH' ? $opt : listener_opt($opt); + return if !defined($o->{cert}); + require PublicInbox::TLS; my %ctx_opt = (SSL_server => 1); # parse out hostname:/path/to/ mappings: - foreach my $k (qw(cert key)) { + for my $k (qw(cert key)) { + $o->{$k} // next; my $x = $ctx_opt{'SSL_'.$k.'_file'} = {}; foreach my $path (@{$o->{$k}}) { my $host = ''; @@ -75,18 +83,77 @@ sub accept_tls_opt ($) { { SSL_server => 1, SSL_startHandshake => 0, SSL_reuse_ctx => $ctx }; } -sub daemon_prepare ($) { - my ($default_listen) = @_; +sub check_absolute ($$) { + my ($var, $val) = @_; + die <>', $_[1] or die "open(>> $_[1]): $!"; + $_[0]->autoflush(1); + do_chown($_[1]); +} + +sub load_mod ($;$) { + my ($scheme, $opt) = @_; + my $modc = "PublicInbox::\U$scheme"; + my $mod = $modc.'D'; + eval "require $mod"; # IMAPD|HTTPD|NNTPD|POP3D + die $@ if $@; + my %xn; + my $tlsd = $xn{tlsd} = $mod->new; + my %env = map { + substr($_, length('env.')) => $opt->{$_}->[-1]; + } grep(/\Aenv\./, keys %$opt); + $xn{refresh} = sub { + my ($sig) = @_; + local @ENV{keys %env} = values %env; + $tlsd->refresh_groups($sig); + }; + $xn{post_accept} = $tlsd->can('post_accept_cb') ? + $tlsd->post_accept_cb : sub { $modc->new($_[0], $tlsd) }; + my @paths = qw(out err); + if ($modc eq 'PublicInbox::HTTP') { + @paths = qw(err); + $xn{af_default} = 'httpready'; + if (my $p = $opt->{psgi}) { + die "multiple psgi= options specified\n" if @$p > 1; + check_absolute('psgi=', $p->[0]) if $daemonize; + $tlsd->{psgi} = $p->[0]; + } + } + for my $f (@paths) { + my $p = $opt->{$f} or next; + die "multiple $f= options specified\n" if @$p > 1; + check_absolute("$f=", $p->[0]) if $daemonize; + $p = File::Spec->canonpath($p->[0]); + open_log_path(my $fh, $p); + $tlsd->{$f} = $logs{$p} = $fh; + } + \%xn; +} + +sub daemon_prepare ($$) { + my ($default_listen, $xnetd) = @_; my $listener_names = {}; # sockname => IO::Handle - $oldset = PublicInbox::Sigfd::block_signals(); + $oldset = PublicInbox::DS::block_signals(); @CMD = ($0, @ARGV); my ($prog) = ($CMD[0] =~ m!([^/]+)\z!g); + my $dh = defined($default_listen) ? " (default: $default_listen)" : ''; my $help = <canonpath($_ // next) for ($stdout, $stderr); if (defined $pid_file && $pid_file =~ /\.oldbin\z/) { die "--pid-file cannot end with '.oldbin'\n"; } @@ -121,7 +189,10 @@ EOF # ignore daemonize when inheriting $daemonize = undef if scalar @listeners; - push @cfg_listen, $default_listen unless (@listeners || @cfg_listen); + unless (@listeners || @cfg_listen) { + $default_listen // die "no listeners specified\n"; + push @cfg_listen, $default_listen + } foreach my $l (@cfg_listen) { my $orig = $l; @@ -132,14 +203,17 @@ EOF my $s = $KNOWN_TLS{$1} // $KNOWN_STARTTLS{$1}; $scheme = $s if defined $s; } + my $opt; # non-TLS options if ($l =~ s!/?\?(.+)\z!!) { - $tls_opt{"$scheme://$l"} = accept_tls_opt($1); + $opt = listener_opt($1); + $tls_opt{"$scheme://$l"} = accept_tls_opt($opt); } elsif (defined($default_cert)) { $tls_opt{"$scheme://$l"} = accept_tls_opt(''); - } elsif ($scheme =~ /\A(?:https|imaps|imaps)\z/) { + } elsif ($scheme =~ /\A(?:https|imaps|nntps|pop3s)\z/) { die "$orig specified w/o cert=\n"; } - # TODO: use scheme to load either NNTP.pm or HTTP.pm + $scheme =~ /\A(http|imap|nntp|pop3)/ and + $xnetd->{$l} = load_mod($1, $opt); next if $listener_names->{$l}; # already inherited my (%o, $sock_pkg); @@ -184,34 +258,31 @@ EOF for my $sockname (@inherited_names) { $sockname =~ /:([0-9]+)\z/ or next; if (my $scheme = $KNOWN_TLS{$1}) { + $xnetd->{$sockname} = load_mod(substr($scheme, 0, -1)); $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt(''); } elsif (($scheme = $KNOWN_STARTTLS{$1})) { - next if $tls_opt{"$scheme://$sockname"}; + $xnetd->{$sockname} = load_mod($scheme); + $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt(''); $tls_opt{''} ||= accept_tls_opt(''); } } - + my @d; + while (my ($k, $v) = each %tls_opt) { push(@d, $k) if !defined($v) } + delete @tls_opt{@d}; die "No listeners bound\n" unless @listeners; } -sub check_absolute ($$) { - my ($var, $val) = @_; - if (defined $val && index($val, '/') != 0) { - die -"--$var must be an absolute path when using --daemonize: $val\n"; - } -} - sub daemonize () { if ($daemonize) { + require Cwd; foreach my $i (0..$#ARGV) { my $arg = $ARGV[$i]; next unless -e $arg; - $ARGV[$i] = abs_path($arg); + $ARGV[$i] = Cwd::abs_path($arg); } - check_absolute('stdout', $stdout); - check_absolute('stderr', $stderr); - check_absolute('pid-file', $pid_file); + check_absolute('--stdout', $stdout); + check_absolute('--stderr', $stderr); + check_absolute('--pid-file', $pid_file); chdir '/' or die "chdir failed: $!"; } @@ -270,13 +341,11 @@ sub worker_quit { # $_[0] = signal name or number (unused) my ($dmap, undef) = @_; my $n = 0; my $now = now(); - - foreach my $s (values %$dmap) { + for my $s (values %$dmap) { $s->can('busy') or next; - if ($s->busy($now)) { + if ($s->busy) { ++$n; - } else { - # close as much as possible, early as possible + } else { # close as much as possible, early as possible $s->close; } } @@ -296,18 +365,9 @@ sub worker_quit { # $_[0] = signal name or number (unused) } sub reopen_logs { - if ($stdout) { - open STDOUT, '>>', $stdout or - warn "failed to redirect stdout to $stdout: $!\n"; - STDOUT->autoflush(1); - do_chown($stdout); - } - if ($stderr) { - open STDERR, '>>', $stderr or - warn "failed to redirect stderr to $stderr: $!\n"; - STDERR->autoflush(1); - do_chown($stderr); - } + $logs{$stdout} //= \*STDOUT if defined $stdout; + $logs{$stderr} //= \*STDERR if defined $stderr; + while (my ($p, $fh) = each %logs) { open_log_path($fh, $p) } } sub sockname ($) { @@ -367,16 +427,14 @@ sub inherit ($) { my $end = $fds + 2; # LISTEN_FDS_START - 1 my @rv = (); foreach my $fd (3..$end) { - my $s = IO::Handle->new_from_fd($fd, 'r'); + open(my $s, '<&=', $fd) or warn "fdopen fd=$fd: $!"; if (my $k = sockname($s)) { - if ($s->blocking) { - $s->blocking(0); - warn <<""; + my $prev_was_blocking = $s->blocking(0); + warn <<"" if $prev_was_blocking; Inherited socket (fd=$fd) is blocking, making it non-blocking. Set 'NonBlocking = true' in the systemd.service unit to avoid stalled processes when multiple service instances start. - } $listener_names->{$k} = $s; push @rv, $s; } else { @@ -423,11 +481,8 @@ sub upgrade { # $_[0] = signal name or number (unused) } sub kill_workers ($) { - my ($s) = @_; - - while (my ($pid, $id) = each %pids) { - kill $s, $pid; - } + my ($sig) = @_; + kill $sig, keys(%pids); } sub upgrade_aborted ($) { @@ -518,9 +573,9 @@ EOF }, CHLD => \&reap_children, }; - my $sigfd = PublicInbox::Sigfd->new($sig, 0); - local %SIG = (%SIG, %$sig) if !$sigfd; - PublicInbox::Sigfd::sig_setmask($oldset) if !$sigfd; + my $sigfd = PublicInbox::Sigfd->new($sig); + local @SIG{keys %$sig} = values(%$sig) unless $sigfd; + PublicInbox::DS::sig_setmask($oldset) if !$sigfd; while (1) { # main loop my $n = scalar keys %pids; unless (@listeners) { @@ -536,12 +591,15 @@ EOF } my $want = $worker_processes - 1; if ($n <= $want) { - PublicInbox::Sigfd::block_signals() if !$sigfd; + PublicInbox::DS::block_signals() if !$sigfd; for my $i ($n..$want) { + my $seed = rand(0xffffffff); my $pid = fork; if (!defined $pid) { warn "failed to fork worker[$i]: $!\n"; } elsif ($pid == 0) { + srand($seed); + eval { Net::SSLeay::randomize() }; $set_user->() if $set_user; return $p0; # run normal work code } else { @@ -549,7 +607,7 @@ EOF $pids{$pid} = $i; } } - PublicInbox::Sigfd::sig_setmask($oldset) if !$sigfd; + PublicInbox::DS::sig_setmask($oldset) if !$sigfd; } if ($sigfd) { # Linux and IO::KQueue users: @@ -581,21 +639,32 @@ sub defer_accept ($$) { return if $sec > 0; # systemd users may set a higher value setsockopt($s, IPPROTO_TCP, $TCP_DEFER_ACCEPT, 1); } elsif ($^O eq 'freebsd') { - my $x = getsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER); + my $x = getsockopt($s, SOL_SOCKET, $SO_ACCEPTFILTER); return if defined $x; # don't change if set my $accf_arg = pack('a16a240', $af_name, ''); - setsockopt($s, SOL_SOCKET, SO_ACCEPTFILTER, $accf_arg); + setsockopt($s, SOL_SOCKET, $SO_ACCEPTFILTER, $accf_arg); } } -sub daemon_loop ($$$$) { - my ($refresh, $post_accept, $tlsd, $af_default) = @_; +sub daemon_loop ($) { + my ($xnetd) = @_; + my $refresh = sub { + my ($sig) = @_; + for my $xn (values %$xnetd) { + eval { $xn->{refresh}->($sig) }; + warn "refresh $@\n" if $@; + } + }; my %post_accept; while (my ($k, $v) = each %tls_opt) { - if ($k =~ s!\A(?:https|imaps|nntps)://!!) { - $post_accept{$k} = tls_start_cb($v, $post_accept); - } elsif ($tlsd) { # STARTTLS, $k eq '' is OK - $tlsd->{accept_tls} = $v; + my $l = $k; + $l =~ s!\A([^:]+)://!!; + my $scheme = $1 // ''; + my $xn = $xnetd->{$l} // $xnetd->{''}; + if ($scheme =~ m!\A(?:https|imaps|nntps|pop3s)!) { + $post_accept{$l} = tls_start_cb($v, $xn->{post_accept}); + } elsif ($xn->{tlsd}) { # STARTTLS, $k eq '' is OK + $xn->{tlsd}->{accept_tls} = $v; } } my $sig = { @@ -623,48 +692,41 @@ sub daemon_loop ($$$$) { $uid = $gid = undef; reopen_logs(); @listeners = map {; - my $tls_cb = $post_accept{sockname($_)}; + my $l = sockname($_); + my $tls_cb = $post_accept{$l}; + my $xn = $xnetd->{$l} // $xnetd->{''}; # NNTPS, HTTPS, HTTP, IMAPS and POP3S are client-first traffic # IMAP, NNTP and POP3 are server-first - defer_accept($_, $tls_cb ? 'dataready' : $af_default); + defer_accept($_, $tls_cb ? 'dataready' : $xn->{af_default}); # this calls epoll_create: - PublicInbox::Listener->new($_, $tls_cb || $post_accept) + PublicInbox::Listener->new($_, $tls_cb || $xn->{post_accept}) } @listeners; - my $sigfd = PublicInbox::Sigfd->new($sig, $SFD_NONBLOCK); - local %SIG = (%SIG, %$sig) if !$sigfd; - if (!$sigfd) { - # wake up every second to accept signals if we don't - # have signalfd or IO::KQueue: - PublicInbox::Sigfd::sig_setmask($oldset); - PublicInbox::DS->SetLoopTimeout(1000); - } - PublicInbox::DS->EventLoop; + PublicInbox::DS::event_loop($sig, $oldset); } -sub run ($$$;$) { - my ($default, $refresh, $post_accept, $tlsd) = @_; - local $SIG{PIPE} = 'IGNORE'; - daemon_prepare($default); - my $af_default = $default =~ /:8080\z/ ? 'httpready' : undef; +sub run { + my ($default_listen) = @_; + my $xnetd = {}; + if ($default_listen) { + $default_listen =~ /\A(http|imap|nntp|pop3)/ or + die "BUG: $default_listen"; + $xnetd->{''} = load_mod($1); + } + daemon_prepare($default_listen, $xnetd); my $for_destroy = daemonize(); # localize GCF2C for tests: local $PublicInbox::GitAsyncCat::GCF2C; + local $PublicInbox::Git::async_warn = 1; + local $SIG{__WARN__} = PublicInbox::Eml::warn_ignore_cb(); - daemon_loop($refresh, $post_accept, $tlsd, $af_default); + daemon_loop($xnetd); PublicInbox::DS->Reset; # ->DESTROY runs when $for_destroy goes out-of-scope } -sub do_chown ($) { - my ($path) = @_; - if (defined $uid and !chown($uid, $gid, $path)) { - warn "could not chown $path: $!\n"; - } -} - sub write_pid ($) { my ($path) = @_; Net::Server::Daemonize::create_pid_file($path);