public-inbox.git  about / heads / tags
an "archives first" approach to mailing lists
blob 2f102ec65edab85c5002f812e7bd269056ee79fa 1588 bytes (raw)
$ git show HEAD:lib/PublicInbox/CmdIPC4.pm	# shows this blob on the CLI

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 
# Copyright (C) all contributors <meta@public-inbox.org>
# License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>

# callers should use PublicInbox::CmdIPC4->can('send_cmd4') (or recv_cmd4)
# first choice for script/lei front-end and 2nd choice for lei backend
# libsocket-msghdr-perl is in Debian but not many other distros as of 2021.
package PublicInbox::CmdIPC4;
use v5.12;
use Socket qw(SOL_SOCKET SCM_RIGHTS);

sub sendmsg_retry ($) {
	return 1 if $!{EINTR};
	return unless ($!{ENOMEM} || $!{ENOBUFS} || $!{ETOOMANYREFS});
	return if ++$_[0] >= 50;
	warn "# sleeping on sendmsg: $! (#$_[0])\n";
	select(undef, undef, undef, 0.1);
	1;
}

BEGIN { eval {
require Socket::MsgHdr; # XS
no warnings 'once';

# any number of FDs per-sendmsg(2) + buffer
*send_cmd4 = sub ($$$$) { # (sock, fds, buf, flags) = @_;
	my ($sock, $fds, undef, $flags) = @_;
	my $mh = Socket::MsgHdr->new(buf => $_[2]);
	$mh->cmsghdr(SOL_SOCKET, SCM_RIGHTS, pack('i' x scalar(@$fds), @$fds));
	my $s;
	my $try = 0;
	do {
		$s = Socket::MsgHdr::sendmsg($sock, $mh, $flags);
	} while (!defined($s) && sendmsg_retry($try));
	$s;
};

*recv_cmd4 = sub ($$$) {
	my ($s, undef, $len) = @_; # $_[1] = destination buffer
	my $mh = Socket::MsgHdr->new(buflen => $len, controllen => 256);
	my $r;
	do {
		$r = Socket::MsgHdr::recvmsg($s, $mh, 0);
	} while (!defined($r) && $!{EINTR});
	if (!defined($r)) {
		$_[1] = '';
		return (undef);
	}
	$_[1] = $mh->buf;
	return () if $r == 0;
	my (undef, undef, $data) = $mh->cmsghdr;
	defined($data) ? unpack('i' x (length($data) / 4), $data) : ();
};

} } # /eval /BEGIN

1;

git clone https://public-inbox.org/public-inbox.git
git clone http://7fh6tueqddpjyxjmgtdiueylzoqt6pt7hec3pukyptlmohoowvhde4yd.onion/public-inbox.git