]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Sigfd.pm
portability: constants for NetBSD
[public-inbox.git] / lib / PublicInbox / Sigfd.pm
1 # Copyright (C) 2019-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 package PublicInbox::Sigfd;
4 use strict;
5 use parent qw(PublicInbox::DS);
6 use fields qw(sig); # hashref similar to %SIG, but signal numbers as keys
7 use PublicInbox::Syscall qw(signalfd EPOLLIN EPOLLET SFD_NONBLOCK);
8 use POSIX ();
9 use IO::Handle ();
10
11 # returns a coderef to unblock signals if neither signalfd or kqueue
12 # are available.
13 sub new {
14         my ($class, $sig, $flags) = @_;
15         my $self = fields::new($class);
16         my %signo = map {;
17                 my $cb = $sig->{$_};
18                 # SIGWINCH is 28 on FreeBSD, NetBSD, OpenBSD
19                 my $num = ($_ eq 'WINCH' && $^O =~ /linux|bsd/i) ? 28 : do {
20                         my $m = "SIG$_";
21                         POSIX->$m;
22                 };
23                 $num => $cb;
24         } keys %$sig;
25         my $io;
26         my $fd = signalfd(-1, [keys %signo], $flags);
27         if (defined $fd && $fd >= 0) {
28                 $io = IO::Handle->new_from_fd($fd, 'r+');
29         } elsif (eval { require PublicInbox::DSKQXS }) {
30                 $io = PublicInbox::DSKQXS->signalfd([keys %signo], $flags);
31         } else {
32                 return; # wake up every second to check for signals
33         }
34         if ($flags & SFD_NONBLOCK) { # it can go into the event loop
35                 $self->SUPER::new($io, EPOLLIN | EPOLLET);
36         } else { # master main loop
37                 $self->{sock} = $io;
38         }
39         $self->{sig} = \%signo;
40         $self;
41 }
42
43 # PublicInbox::Daemon in master main loop (blocking)
44 sub wait_once ($) {
45         my ($self) = @_;
46         # 128 == sizeof(struct signalfd_siginfo)
47         my $r = sysread($self->{sock}, my $buf, 128 * 64);
48         if (defined($r)) {
49                 my $nr = $r / 128 - 1; # $nr may be -1
50                 for my $off (0..$nr) {
51                         # the first uint32_t of signalfd_siginfo: ssi_signo
52                         my $signo = unpack('L', substr($buf, 128 * $off, 4));
53                         my $cb = $self->{sig}->{$signo};
54                         $cb->($signo) if $cb ne 'IGNORE';
55                 }
56         }
57         $r;
58 }
59
60 # called by PublicInbox::DS in epoll_wait loop
61 sub event_step {
62         while (wait_once($_[0])) {} # non-blocking
63 }
64
65 1;