]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Daemon.pm
daemon: set TCP_DEFER_ACCEPT on everything but NNTP
[public-inbox.git] / lib / PublicInbox / Daemon.pm
1 # Copyright (C) 2015-2018 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;
6 use strict;
7 use warnings;
8 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
9 use IO::Handle;
10 use IO::Socket;
11 use Socket qw(IPPROTO_TCP);
12 use Cwd qw/abs_path/;
13 STDOUT->autoflush(1);
14 STDERR->autoflush(1);
15 use PublicInbox::DS qw(now);
16 require PublicInbox::EvCleanup;
17 require POSIX;
18 require PublicInbox::Listener;
19 require PublicInbox::ParentPipe;
20 my @CMD;
21 my $set_user;
22 my (@cfg_listen, $stdout, $stderr, $group, $user, $pid_file, $daemonize);
23 my $worker_processes = 1;
24 my @listeners;
25 my %pids;
26 my %listener_names; # sockname => IO::Handle
27 my %tls_opt; # scheme://sockname => args for IO::Socket::SSL->start_SSL
28 my $reexec_pid;
29 my $cleanup;
30 my ($uid, $gid);
31 my ($default_cert, $default_key);
32 END { $cleanup->() if $cleanup };
33 my %KNOWN_TLS = ( 443 => 'https', 563 => 'nntps' );
34 my %KNOWN_STARTTLS = ( 119 => 'nntp' );
35
36 sub accept_tls_opt ($) {
37         my ($opt_str) = @_;
38         # opt_str: opt1=val1,opt2=val2 (opt may repeat for multi-value)
39         require PublicInbox::TLS;
40         my $o = {};
41         # allow ',' as delimiter since '&' is shell-unfriendly
42         foreach (split(/[,&]/, $opt_str)) {
43                 my ($k, $v) = split(/=/, $_, 2);
44                 push @{$o->{$k} ||= []}, $v;
45         }
46
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}}) {
56                         my $host = '';
57                         $path =~ s/\A([^:]+):// and $host = $1;
58                         $x->{$host} = $path;
59                 }
60         }
61         my $ctx = IO::Socket::SSL::SSL_Context->new(%ctx_opt) or
62                 die 'SSL_Context->new: '.PublicInbox::TLS::err();
63
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 $@;
71         }
72
73         { SSL_server => 1, SSL_startHandshake => 0, SSL_reuse_ctx => $ctx };
74 }
75
76 sub daemon_prepare ($) {
77         my ($default_listen) = @_;
78         @CMD = ($0, @ARGV);
79         $SIG{HUP} = $SIG{USR1} = $SIG{USR2} = $SIG{PIPE} =
80                 $SIG{TTIN} = $SIG{TTOU} = $SIG{WINCH} = 'IGNORE';
81         my %opts = (
82                 'l|listen=s' => \@cfg_listen,
83                 '1|stdout=s' => \$stdout,
84                 '2|stderr=s' => \$stderr,
85                 'W|worker-processes=i' => \$worker_processes,
86                 'P|pid-file=s' => \$pid_file,
87                 'u|user=s' => \$user,
88                 'g|group=s' => \$group,
89                 'D|daemonize' => \$daemonize,
90                 'cert=s' => \$default_cert,
91                 'key=s' => \$default_key,
92         );
93         GetOptions(%opts) or die "bad command-line args\n";
94
95         if (defined $pid_file && $pid_file =~ /\.oldbin\z/) {
96                 die "--pid-file cannot end with '.oldbin'\n";
97         }
98         @listeners = inherit();
99
100         # allow socket-activation users to set certs once and not
101         # have to configure each socket:
102         my @inherited_names = keys(%listener_names) if defined($default_cert);
103
104         # ignore daemonize when inheriting
105         $daemonize = undef if scalar @listeners;
106
107         push @cfg_listen, $default_listen unless (@listeners || @cfg_listen);
108
109         foreach my $l (@cfg_listen) {
110                 my $orig = $l;
111                 my $scheme = '';
112                 if ($l =~ s!\A([^:]+)://!!) {
113                         $scheme = $1;
114                 } elsif ($l =~ /\A(?:\[[^\]]+\]|[^:]+):([0-9])+/) {
115                         my $s = $KNOWN_TLS{$1} // $KNOWN_STARTTLS{$1};
116                         $scheme = $s if defined $s;
117                 }
118                 if ($l =~ s!/?\?(.+)\z!!) {
119                         $tls_opt{"$scheme://$l"} = accept_tls_opt($1);
120                 } elsif (defined($default_cert)) {
121                         $tls_opt{"$scheme://$l"} = accept_tls_opt('');
122                 } elsif ($scheme =~ /\A(?:nntps|https)\z/) {
123                         die "$orig specified w/o cert=\n";
124                 }
125                 # TODO: use scheme to load either NNTP.pm or HTTP.pm
126
127                 next if $listener_names{$l}; # already inherited
128                 my (%o, $sock_pkg);
129                 if (index($l, '/') == 0) {
130                         $sock_pkg = 'IO::Socket::UNIX';
131                         eval "use $sock_pkg";
132                         die $@ if $@;
133                         %o = (Type => SOCK_STREAM, Peer => $l);
134                         if (-S $l) {
135                                 my $c = $sock_pkg->new(%o);
136                                 if (!defined($c) && $!{ECONNREFUSED}) {
137                                         unlink $l or die
138 "failed to unlink stale socket=$l: $!\n";
139                                 } # else: let the bind fail
140                         }
141                         $o{Local} = delete $o{Peer};
142                 } else {
143                         # both work for IPv4, too
144                         for (qw(IO::Socket::IP IO::Socket::INET6)) {
145                                 $sock_pkg = $_;
146                                 eval "use $sock_pkg";
147                                 $@ or last;
148                         }
149                         die $@ if $@;
150                         %o = (LocalAddr => $l, ReuseAddr => 1, Proto => 'tcp');
151                 }
152                 $o{Listen} = 1024;
153                 my $prev = umask 0000;
154                 my $s = eval { $sock_pkg->new(%o) };
155                 warn "error binding $l: $! ($@)\n" unless $s;
156                 umask $prev;
157
158                 if ($s) {
159                         $listener_names{sockname($s)} = $s;
160                         push @listeners, $s;
161                 }
162         }
163
164         # cert/key options in @cfg_listen takes precedence when inheriting,
165         # but map well-known inherited ports if --listen isn't specified
166         # at all
167         for my $sockname (@inherited_names) {
168                 $sockname =~ /:([0-9]+)\z/ or next;
169                 if (my $scheme = $KNOWN_TLS{$1}) {
170                         $tls_opt{"$scheme://$sockname"} ||= accept_tls_opt('');
171                 } elsif (($scheme = $KNOWN_STARTTLS{$1})) {
172                         next if $tls_opt{"$scheme://$sockname"};
173                         $tls_opt{''} ||= accept_tls_opt('');
174                 }
175         }
176
177         die "No listeners bound\n" unless @listeners;
178 }
179
180 sub check_absolute ($$) {
181         my ($var, $val) = @_;
182         if (defined $val && index($val, '/') != 0) {
183                 die
184 "--$var must be an absolute path when using --daemonize: $val\n";
185         }
186 }
187
188 sub daemonize () {
189         if ($daemonize) {
190                 foreach my $i (0..$#ARGV) {
191                         my $arg = $ARGV[$i];
192                         next unless -e $arg;
193                         $ARGV[$i] = abs_path($arg);
194                 }
195                 check_absolute('stdout', $stdout);
196                 check_absolute('stderr', $stderr);
197                 check_absolute('pid-file', $pid_file);
198
199                 chdir '/' or die "chdir failed: $!";
200         }
201
202         return unless (defined $pid_file || defined $group || defined $user
203                         || $daemonize);
204
205         eval { require Net::Server::Daemonize };
206         if ($@) {
207                 die
208 "Net::Server required for --pid-file, --group, --user, and --daemonize\n$@\n";
209         }
210
211         Net::Server::Daemonize::check_pid_file($pid_file) if defined $pid_file;
212         $uid = Net::Server::Daemonize::get_uid($user) if defined $user;
213         if (defined $group) {
214                 $gid = Net::Server::Daemonize::get_gid($group);
215                 $gid = (split /\s+/, $gid)[0];
216         } elsif (defined $uid) {
217                 $gid = (getpwuid($uid))[3];
218         }
219
220         # We change users in the worker to ensure upgradability,
221         # The upgrade will create the ".oldbin" pid file in the
222         # same directory as the given pid file.
223         $uid and $set_user = sub {
224                 $set_user = undef;
225                 Net::Server::Daemonize::set_user($uid, $gid);
226         };
227
228         if ($daemonize) {
229                 my $pid = fork;
230                 die "could not fork: $!\n" unless defined $pid;
231                 exit if $pid;
232
233                 open(STDIN, '+<', '/dev/null') or
234                                         die "redirect stdin failed: $!\n";
235                 open STDOUT, '>&STDIN' or die "redirect stdout failed: $!\n";
236                 open STDERR, '>&STDIN' or die "redirect stderr failed: $!\n";
237                 POSIX::setsid();
238                 $pid = fork;
239                 die "could not fork: $!\n" unless defined $pid;
240                 exit if $pid;
241         }
242         if (defined $pid_file) {
243                 write_pid($pid_file);
244                 my $unlink_pid = $$;
245                 $cleanup = sub {
246                         $cleanup = undef; # avoid cyclic reference
247                         unlink_pid_file_safe_ish($unlink_pid, $pid_file);
248                 };
249         }
250 }
251
252
253 sub worker_quit {
254         my ($reason) = @_;
255         # killing again terminates immediately:
256         exit unless @listeners;
257
258         $_->close foreach @listeners; # call PublicInbox::DS::close
259         @listeners = ();
260         $reason->close if ref($reason) eq 'PublicInbox::ParentPipe';
261
262         my $proc_name;
263         my $warn = 0;
264         # drop idle connections and try to quit gracefully
265         PublicInbox::DS->SetPostLoopCallback(sub {
266                 my ($dmap, undef) = @_;
267                 my $n = 0;
268                 my $now = now();
269
270                 foreach my $s (values %$dmap) {
271                         $s->can('busy') or next;
272                         if ($s->busy($now)) {
273                                 ++$n;
274                         } else {
275                                 # close as much as possible, early as possible
276                                 $s->close;
277                         }
278                 }
279                 if ($n) {
280                         if (($warn + 5) < now()) {
281                                 warn "$$ quitting, $n client(s) left\n";
282                                 $warn = now();
283                         }
284                         unless (defined $proc_name) {
285                                 $proc_name = (split(/\s+/, $0))[0];
286                                 $proc_name =~ s!\A.*?([^/]+)\z!$1!;
287                         }
288                         $0 = "$proc_name quitting, $n client(s) left";
289                 }
290                 $n; # true: loop continues, false: loop breaks
291         });
292 }
293
294 sub reopen_logs {
295         if ($stdout) {
296                 open STDOUT, '>>', $stdout or
297                         warn "failed to redirect stdout to $stdout: $!\n";
298                 STDOUT->autoflush(1);
299                 do_chown($stdout);
300         }
301         if ($stderr) {
302                 open STDERR, '>>', $stderr or
303                         warn "failed to redirect stderr to $stderr: $!\n";
304                 STDERR->autoflush(1);
305                 do_chown($stderr);
306         }
307 }
308
309 sub sockname ($) {
310         my ($s) = @_;
311         my $addr = getsockname($s) or return;
312         my ($host, $port) = host_with_port($addr);
313         if ($port == 0 && $host eq '127.0.0.1') {
314                 my ($path) = Socket::sockaddr_un($addr);
315                 return $path;
316         }
317         "$host:$port";
318 }
319
320 sub unpack_ipv6 ($) {
321         my ($addr) = @_;
322         my ($port, $host);
323
324         # Socket.pm in Perl 5.14+ supports IPv6:
325         eval {
326                 ($port, $host) = Socket::unpack_sockaddr_in6($addr);
327                 $host = Socket::inet_ntop(Socket::AF_INET6(), $host);
328         };
329
330         if ($@) {
331                 # Perl 5.12 or earlier?  SpamAssassin and Net::Server use
332                 # Socket6, so it may be installed on our system, already
333                 # (otherwise die here):
334                 require Socket6;
335
336                 ($port, $host) = Socket6::unpack_sockaddr_in6($addr);
337                 $host = Socket6::inet_ntop(Socket6::AF_INET6(), $host);
338         }
339         ($host, $port);
340 }
341
342 sub host_with_port ($) {
343         my ($addr) = @_;
344         my ($port, $host);
345
346         # this eval will die on Unix sockets:
347         eval {
348                 if (length($addr) >= 28) {
349                         ($host, $port) = unpack_ipv6($addr);
350                         $host = "[$host]";
351                 } else {
352                         ($port, $host) = Socket::sockaddr_in($addr);
353                         $host = Socket::inet_ntoa($host);
354                 }
355         };
356         $@ ? ('127.0.0.1', 0) : ($host, $port);
357 }
358
359 sub inherit () {
360         return () if ($ENV{LISTEN_PID} || 0) != $$;
361         my $fds = $ENV{LISTEN_FDS} or return ();
362         my $end = $fds + 2; # LISTEN_FDS_START - 1
363         my @rv = ();
364         foreach my $fd (3..$end) {
365                 my $s = IO::Handle->new_from_fd($fd, 'r');
366                 if (my $k = sockname($s)) {
367                         $listener_names{$k} = $s;
368                         push @rv, $s;
369                 } else {
370                         warn "failed to inherit fd=$fd (LISTEN_FDS=$fds)";
371                 }
372         }
373         @rv
374 }
375
376 sub upgrade () {
377         if ($reexec_pid) {
378                 warn "upgrade in-progress: $reexec_pid\n";
379                 return;
380         }
381         if (defined $pid_file) {
382                 if ($pid_file =~ /\.oldbin\z/) {
383                         warn "BUG: .oldbin suffix exists: $pid_file\n";
384                         return;
385                 }
386                 unlink_pid_file_safe_ish($$, $pid_file);
387                 $pid_file .= '.oldbin';
388                 write_pid($pid_file);
389         }
390         my $pid = fork;
391         unless (defined $pid) {
392                 warn "fork failed: $!\n";
393                 return;
394         }
395         if ($pid == 0) {
396                 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD);
397                 $ENV{LISTEN_FDS} = scalar @listeners;
398                 $ENV{LISTEN_PID} = $$;
399                 foreach my $s (@listeners) {
400                         my $fl = fcntl($s, F_GETFD, 0);
401                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
402                 }
403                 exec @CMD;
404                 die "Failed to exec: $!\n";
405         }
406         $reexec_pid = $pid;
407 }
408
409 sub kill_workers ($) {
410         my ($s) = @_;
411
412         while (my ($pid, $id) = each %pids) {
413                 kill $s, $pid;
414         }
415 }
416
417 sub upgrade_aborted ($) {
418         my ($p) = @_;
419         warn "reexec PID($p) died with: $?\n";
420         $reexec_pid = undef;
421         return unless $pid_file;
422
423         my $file = $pid_file;
424         $file =~ s/\.oldbin\z// or die "BUG: no '.oldbin' suffix in $file";
425         unlink_pid_file_safe_ish($$, $pid_file);
426         $pid_file = $file;
427         eval { write_pid($pid_file) };
428         warn $@, "\n" if $@;
429 }
430
431 sub reap_children () {
432         while (1) {
433                 my $p = waitpid(-1, &POSIX::WNOHANG) or return;
434                 if (defined $reexec_pid && $p == $reexec_pid) {
435                         upgrade_aborted($p);
436                 } elsif (defined(my $id = delete $pids{$p})) {
437                         warn "worker[$id] PID($p) died with: $?\n";
438                 } elsif ($p > 0) {
439                         warn "unknown PID($p) reaped: $?\n";
440                 } else {
441                         return;
442                 }
443         }
444 }
445
446 sub unlink_pid_file_safe_ish ($$) {
447         my ($unlink_pid, $file) = @_;
448         return unless defined $unlink_pid && $unlink_pid == $$;
449
450         open my $fh, '<', $file or return;
451         local $/ = "\n";
452         defined(my $read_pid = <$fh>) or return;
453         chomp $read_pid;
454         if ($read_pid == $unlink_pid) {
455                 Net::Server::Daemonize::unlink_pid_file($file);
456         }
457 }
458
459 sub master_loop {
460         pipe(my ($p0, $p1)) or die "failed to create parent-pipe: $!";
461         pipe(my ($r, $w)) or die "failed to create self-pipe: $!";
462
463         if ($^O eq 'linux') { # 1031: F_SETPIPE_SZ = 1031
464                 fcntl($_, 1031, 4096) for ($w, $p1);
465         }
466
467         IO::Handle::blocking($w, 0);
468         my $set_workers = $worker_processes;
469         my @caught;
470         my $master_pid = $$;
471         foreach my $s (qw(HUP CHLD QUIT INT TERM USR1 USR2 TTIN TTOU WINCH)) {
472                 $SIG{$s} = sub {
473                         return if $$ != $master_pid;
474                         push @caught, $s;
475                         syswrite($w, '.');
476                 };
477         }
478         reopen_logs();
479         # main loop
480         my $quit = 0;
481         while (1) {
482                 while (my $s = shift @caught) {
483                         if ($s eq 'USR1') {
484                                 reopen_logs();
485                                 kill_workers($s);
486                         } elsif ($s eq 'USR2') {
487                                 upgrade();
488                         } elsif ($s =~ /\A(?:QUIT|TERM|INT)\z/) {
489                                 exit if $quit++;
490                                 kill_workers($s);
491                         } elsif ($s eq 'WINCH') {
492                                 if (-t STDIN || -t STDOUT || -t STDERR) {
493                                         warn
494 "ignoring SIGWINCH since we are not daemonized\n";
495                                         $SIG{WINCH} = 'IGNORE';
496                                 } else {
497                                         $worker_processes = 0;
498                                 }
499                         } elsif ($s eq 'HUP') {
500                                 $worker_processes = $set_workers;
501                                 kill_workers($s);
502                         } elsif ($s eq 'TTIN') {
503                                 if ($set_workers > $worker_processes) {
504                                         ++$worker_processes;
505                                 } else {
506                                         $worker_processes = ++$set_workers;
507                                 }
508                         } elsif ($s eq 'TTOU') {
509                                 if ($set_workers > 0) {
510                                         $worker_processes = --$set_workers;
511                                 }
512                         } elsif ($s eq 'CHLD') {
513                                 reap_children();
514                         }
515                 }
516
517                 my $n = scalar keys %pids;
518                 if ($quit) {
519                         exit if $n == 0;
520                         $set_workers = $worker_processes = $n = 0;
521                 }
522
523                 if ($n > $worker_processes) {
524                         while (my ($k, $v) = each %pids) {
525                                 kill('TERM', $k) if $v >= $worker_processes;
526                         }
527                         $n = $worker_processes;
528                 }
529                 foreach my $i ($n..($worker_processes - 1)) {
530                         my $pid = fork;
531                         if (!defined $pid) {
532                                 warn "failed to fork worker[$i]: $!\n";
533                         } elsif ($pid == 0) {
534                                 $set_user->() if $set_user;
535                                 return $p0; # run normal work code
536                         } else {
537                                 warn "PID=$pid is worker[$i]\n";
538                                 $pids{$pid} = $i;
539                         }
540                 }
541                 # just wait on signal events here:
542                 sysread($r, my $buf, 8);
543         }
544         exit # never gets here, just for documentation
545 }
546
547 sub tls_start_cb ($$) {
548         my ($opt, $orig_post_accept) = @_;
549         sub {
550                 my ($io, $addr, $srv) = @_;
551                 my $ssl = IO::Socket::SSL->start_SSL($io, %$opt);
552                 $orig_post_accept->($ssl, $addr, $srv);
553         }
554 }
555
556 sub defer_accept ($) {
557         if ($^O eq 'linux') {
558                 my ($s) = @_;
559                 my $x = getsockopt($s, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT());
560                 return unless defined $x; # may be Unix socket
561                 my $sec = unpack('i', $x);
562                 return if $sec > 0; # systemd users may set a higher value
563                 setsockopt($s, IPPROTO_TCP, Socket::TCP_DEFER_ACCEPT(), 1);
564         }
565         # TODO FreeBSD accf_http / accf_data
566 }
567
568 sub daemon_loop ($$$) {
569         my ($refresh, $post_accept, $nntpd) = @_;
570         PublicInbox::EvCleanup::enable(); # early for $refresh
571         my %post_accept;
572         while (my ($k, $v) = each %tls_opt) {
573                 if ($k =~ s!\A(?:nntps|https)://!!) {
574                         $post_accept{$k} = tls_start_cb($v, $post_accept);
575                 } elsif ($nntpd) { # STARTTLS, $k eq '' is OK
576                         $nntpd->{accept_tls} = $v;
577                 }
578         }
579         my $parent_pipe;
580         if ($worker_processes > 0) {
581                 $refresh->(); # preload by default
582                 my $fh = master_loop(); # returns if in child process
583                 $parent_pipe = PublicInbox::ParentPipe->new($fh, *worker_quit);
584         } else {
585                 reopen_logs();
586                 $set_user->() if $set_user;
587                 $SIG{USR2} = sub { worker_quit('USR2') if upgrade() };
588                 $refresh->();
589         }
590         $uid = $gid = undef;
591         reopen_logs();
592         $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = *worker_quit;
593         $SIG{USR1} = *reopen_logs;
594         $SIG{HUP} = $refresh;
595         $SIG{CHLD} = 'DEFAULT';
596         $SIG{$_} = 'IGNORE' for qw(USR2 TTIN TTOU WINCH);
597         @listeners = map {;
598                 my $tls_cb = $post_accept{sockname($_)};
599
600                 # NNTPS, HTTPS, HTTP, and POP3S are client-first traffic
601                 # NNTP and POP3 are server-first
602                 defer_accept($_) if $tls_cb || !$nntpd;
603
604                 # this calls epoll_create:
605                 PublicInbox::Listener->new($_, $tls_cb || $post_accept)
606         } @listeners;
607         PublicInbox::DS->EventLoop;
608         $parent_pipe = undef;
609 }
610
611
612 sub run ($$$;$) {
613         my ($default, $refresh, $post_accept, $nntpd) = @_;
614         daemon_prepare($default);
615         daemonize();
616         daemon_loop($refresh, $post_accept, $nntpd);
617 }
618
619 sub do_chown ($) {
620         my ($path) = @_;
621         if (defined $uid and !chown($uid, $gid, $path)) {
622                 warn "could not chown $path: $!\n";
623         }
624 }
625
626 sub write_pid ($) {
627         my ($path) = @_;
628         Net::Server::Daemonize::create_pid_file($path);
629         do_chown($path);
630 }
631
632 1;