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