]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/CmdIPC4.pm
74dbf8a12ee4a8090a16d75a8ddbcaee6271cf3b
[public-inbox.git] / lib / PublicInbox / CmdIPC4.pm
1 # Copyright (C) 2020-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # callers should use PublicInbox::CmdIPC4->can('send_cmd4') (or recv_cmd4)
5 # first choice for script/lei front-end and 2nd choice for lei backend
6 # libsocket-msghdr-perl is in Debian but not many other distros as of 2021.
7 package PublicInbox::CmdIPC4;
8 use strict;
9 use v5.10.1;
10 use Socket qw(SOL_SOCKET SCM_RIGHTS);
11 BEGIN { eval {
12 require Socket::MsgHdr; # XS
13 no warnings 'once';
14
15 # any number of FDs per-sendmsg(2) + buffer
16 *send_cmd4 = sub ($$$$) { # (sock, fds, buf, flags) = @_;
17         my ($sock, $fds, undef, $flags) = @_;
18         my $mh = Socket::MsgHdr->new(buf => $_[2]);
19         $mh->cmsghdr(SOL_SOCKET, SCM_RIGHTS, pack('i' x scalar(@$fds), @$fds));
20         Socket::MsgHdr::sendmsg($sock, $mh, $flags);
21 };
22
23 *recv_cmd4 = sub ($$$) {
24         my ($s, undef, $len) = @_; # $_[1] = destination buffer
25         my $mh = Socket::MsgHdr->new(buflen => $len, controllen => 256);
26         my $r = Socket::MsgHdr::recvmsg($s, $mh, 0) // return ($_[1] = undef);
27         $_[1] = $mh->buf;
28         return () if $r == 0;
29         my (undef, undef, $data) = $mh->cmsghdr;
30         defined($data) ? unpack('i' x (length($data) / 4), $data) : ();
31 };
32
33 } } # /eval /BEGIN
34
35 1;