lib/Net/Tools/Socket/Pair.pm

filter: Statementstmt 96.9% 64 / 66 Branchbran 85.0% 34 / 40 Conditioncond 85.7% 24 / 28 MC/DCmcdc 75.0% 12 / 16 Subroutinesub 100% 8 / 8 Podpod 0.0% 0 / 3 totaltotal 88.2% 142 / 161 CC 30 SCAR 23.9
CC
30
Cov
91%
socketpair_send
16.1
socketpair_recv
11.0
socketpair_create
4.1
CRAP 10.9
↑ Summary lib/Net/Tools/Socket.pm »
1 ##############################################################################
2 #
3 # Net::Tools::Socket::Pair socketpair high-level API
4 # Copyright (c) 2026 Vladi Belperchinov-Shabanski "Cade"
5 # <cade@noxrun.com>
6 # http://cade.noxrun.com/
7 #
8 # GPL
9 #
10 ##############################################################################
11 #
12 # socketpair_create() / socketpair_send() / socketpair_recv()
13 # non-blocking message passing over socketpair( AF_UNIX, SOCK_SEQPACKET )
14 # (default) or socketpair( AF_UNIX, SOCK_DGRAM )
15 #
16 # send/recv never sleep, regardless of the blocking mode of the
17 # handle (MSG_DONTWAIT is used on every call), never raise SIGPIPE and,
18 # given valid arguments, never die (see POD). Result is 1 (ok), 0 (again,
19 # too big or error) or undef (EOF), the reason is in $SOCK_ERR, see
20 # Net::Tools::Socket::Err.
21 #
22 # one socketpair_send() is exactly one socketpair_recv() on the other side.
23 # messages are byte strings; serialize data structures before sending.
24 #
25 # my ( $sock1, $sock2 ) = socketpair_create( $type );
26 #
27 # $type is 'seqpacket' (default) or 'dgram', case insensitive
28 # returns two connected handles, or empty list on error ($SOCK_ERR is
29 # errno, or SOCK_E_INVAL for unknown $type)
30 #
31 # 'dgram' has no EOF on recv: when the peer has closed, recv returns 0
32 # (SOCK_E_AGAIN) forever, only send() returns undef (SOCK_E_EOF)
33 #
34 # my $res = socketpair_send( $fh, $data );
35 #
36 # 1 message queued for the peer (always the whole message)
37 # 0 SOCK_E_AGAIN peer's queue is full, nothing sent, retry when writable
38 # SOCK_E_TOOBIG message larger than $MSG_MAX or than the socket buffer
39 # SOCK_E_EMPTY undef or empty message, nothing sent
40 # SOCK_E_INVAL message is a reference or has wide characters
41 # errno anything else (positive), see $SOCK_ERRSTR
42 # undef SOCK_E_EOF peer has closed
43 #
44 # my $res = socketpair_recv( $fh, \$data );
45 #
46 # 1 one complete message is in $data
47 # 0 SOCK_E_AGAIN nothing waiting, retry when readable
48 # SOCK_E_TOOBIG incoming message exceeded $MSG_MAX and was discarded
49 # SOCK_E_INVAL $data is not a scalar reference, nothing read
50 # errno anything else (positive), see $SOCK_ERRSTR
51 # undef SOCK_E_EOF peer has closed and all queued messages were read
52 # (seqpacket only)
53 #
54 # every call clears $SOCK_ERR and $SOCK_ERRSTR (Net::Tools::Socket::Err) on
55 # entry and sets them to the reason when the result is not 1.
56 #
57 # loop logic is: when return value is:
58 # 1 -- operation successful, send/recv got message
59 # 0 -- no message or temporary error, repeat loop
60 # undef -- EOF or permanent error, close socket
61 #
62 ##############################################################################
63 package Net::Tools::Socket::Pair;
64 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
65 1 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
66 1 ▶use Socket qw( AF_UNIX SOCK_SEQPACKET SOCK_DGRAM PF_UNSPEC SOL_SOCKET SO_TYPE MSG_DONTWAIT MSG_NOSIGNAL );
Subroutine BEGIN: called CC=1 SCAR=0.0
67 1 ▶use Net::Tools::Socket::Err;
Subroutine BEGIN: called CC=1 SCAR=0.0
68  
69 1 our $VERSION = '1.60';
70  
71 1 our @ISA = qw( Exporter );
72 1 our @EXPORT = qw(
73 socketpair_create
74 socketpair_send
75 socketpair_recv
76 );
77  
78 1 our $MSG_MAX = 128 * 1024;
79  
80 1 my %SOCK_TYPES = (
81 'SEQPACKET' => SOCK_SEQPACKET,
82 'SEQ' => SOCK_SEQPACKET,
83 'DGRAM' => SOCK_DGRAM,
84 'DG' => SOCK_DGRAM,
85 );
86  
87 # MSG_NOSIGNAL flag if the system has it (Linux, BSDs), else 0 and SIGPIPE
88 # is ignored during send instead (macOS). Socket croaks when an undefined
89 # macro is used, hence eval. "our" only to allow tests of the fallback
90 1 ▶our $MSG_NOSIGNAL = eval { MSG_NOSIGNAL() } || 0;
Condition50%1/2
eval { do { 16384 } } || 0
l!l
10
MC/DC0%0/1
eval { do { 16384 } } || 0
eval { do { 16384 } }
Truth table50%1/2
A
A= eval { do { 16384 } }
Aresult
11
00
91  
92 ##############################################################################
93  
94 sub socketpair_create
95 8 ▶{
Subroutine socketpair_create: called CC=4 SCAR=14.2
Pod undocumented
96 8 ▶ my $type = uc( shift() || 'SEQPACKET' );
Condition100%2/2
shift() || 'SEQPACKET'
l!l
53
MC/DC100%1/1
shift() || 'SEQPACKET'
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
97  
98 8 sock_err_clear();
99 8 ▶ my $st = $SOCK_TYPES{ $type } or do { sock_err( SOCK_E_INVAL ); return () };
Branch: 1 branch
BranchTrueFalseTotal
my $st = $SOCK_TYPES{$type} or do { sock_err(-10); return () } 7 1 8
100 0 ▶ socketpair( my $sock1, my $sock2, AF_UNIX, $st, PF_UNSPEC ) or do { sock_err_sys(); return () }; # errno
Branch: 1 branch
BranchTrueFalseTotal
socketpair my $sock1, my $sock2, 1, $st, 0 or do { sock_err_sys(); return () } 7 0 7
101 7 return ( $sock1, $sock2 );
102 }
103  
104 # returns SOCK_SEQPACKET, SOCK_DGRAM, etc. of a socket handle, -1 if unknown
105 sub __sock_type
106 3 ▶{
Subroutine __sock_type: called CC=2 SCAR=7.1
107 3 my $fh = shift;
108 3 my $t = getsockopt( $fh, SOL_SOCKET, SO_TYPE );
109 3 ▶ return defined $t ? unpack( 'i', $t ) : -1;
Branch: 1 branch
BranchTrueFalseTotal
defined $t ? : 3 0 3
110 }
111  
112 sub socketpair_send
113 231 ▶{
Subroutine socketpair_send: called CC=16 SCAR=27.8
Pod undocumented
114 231 my $fh = shift;
115 231 my $data = shift;
116  
117 231 sock_err_clear();
118  
119 231 ▶ return sock_err( SOCK_E_EMPTY, 0 ) unless defined $data and length( $data ) > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data and length $data > 0 3 228 231
Condition100%3/3
defined $data and length $data > 0
!ll&&!rl&&r
12228
MC/DC100%2/2
defined $data and length $data > 0
defined $data length $data > 0
Truth table100%3/3
A and B
A= defined $dataB= length $data > 0
ABresult
0X0
100
111
120 228 ▶ return sock_err( SOCK_E_INVAL, 0 ) if ref( $data ) or ! utf8::downgrade( $data, 1 );
Branch: 1 branch
BranchTrueFalseTotal
if ref $data or not utf8::downgrade($data, 1) 4 224 228
Condition100%3/3
ref $data or not utf8::downgrade($data, 1)
l!l&&r!l&&!r
31224
MC/DC100%2/2
ref $data or not utf8::downgrade($data, 1)
ref $data not utf8::downgrade($data, 1)
Truth table100%3/3
A or not(B)
A= ref $dataB= not utf8::downgrade($data, 1)
ABresult
1X1
011
000
121 224 ▶ return sock_err( SOCK_E_TOOBIG, 0 ) if length( $data ) > $MSG_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if length $data > $Net::Tools::Socket::Pair::MSG_MAX 1 223 224
122  
123 # no SIGPIPE when the peer has closed: MSG_NOSIGNAL, or else SIGPIPE is
124 # ignored only during this call, send() then fails with EPIPE (EOF below)
125 223 ▶ local $SIG{ 'PIPE' } = 'IGNORE' unless $MSG_NOSIGNAL;
Branch: 1 branch
BranchTrueFalseTotal
unless $Net::Tools::Socket::Pair::MSG_NOSIGNAL 1 222 223
126  
127 223 while( 1 )
128 {
129 223 my $n = send( $fh, $data, MSG_DONTWAIT | $MSG_NOSIGNAL );
130 223 ▶ return 1 if defined $n;
Branch: 1 branch
BranchTrueFalseTotal
if defined $n 215 8 223
131 8 ▶ next if $!{ EINTR };
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EINTR"} 0 8 8
132 8 ▶ return sock_err( SOCK_E_AGAIN, 0 ) if $!{ EAGAIN } or $!{ EWOULDBLOCK };
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EAGAIN"} or $!{"EWOULDBLOCK"} 2 6 8
Condition66%2/3
$!{"EAGAIN"} or $!{"EWOULDBLOCK"}
l!l&&r!l&&!r
206
MC/DC50%1/2
$!{"EAGAIN"} or $!{"EWOULDBLOCK"}
$!{"EAGAIN"} $!{"EWOULDBLOCK"}
Truth table66%2/3
A or B
A= $!{"EAGAIN"}B= $!{"EWOULDBLOCK"}
ABresult
1X1
011
000
133 # seqpacket: ECONNRESET, then EPIPE; dgram: ECONNREFUSED, then ENOTCONN
134 6 ▶ return sock_err( SOCK_E_EOF ) if $!{ EPIPE } or $!{ ECONNRESET } or $!{ ENOTCONN } or $!{ ECONNREFUSED };
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EPIPE"} or $!{"ECONNRESET"} or $!{"ENOTCONN"} or $!{"ECONNREFUSED"} 5 1 6
Condition88%8/9
$!{"EPIPE"} or $!{"ECONNRESET"} or $!{"ENOTCONN"} or $!{"ECONNREFUSED"}
l!l&&r!l&&!r
411
$!{"EPIPE"} or $!{"ECONNRESET"} or $!{"ENOTCONN"}
l!l&&r!l&&!r
312
$!{"EPIPE"} or $!{"ECONNRESET"}
l!l&&r!l&&!r
303
MC/DC75%3/4
$!{"EPIPE"} or $!{"ECONNRESET"} or $!{"ENOTCONN"} or $!{"ECONNREFUSED"}
$!{"EPIPE"} $!{"ECONNRESET"} $!{"ENOTCONN"} $!{"ECONNREFUSED"}
Truth table80%4/5
A or B or C or D
A= $!{"EPIPE"}B= $!{"ECONNRESET"}C= $!{"ENOTCONN"}D= $!{"ECONNREFUSED"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
135 1 ▶ return sock_err( SOCK_E_TOOBIG, 0 ) if $!{ EMSGSIZE };
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EMSGSIZE"} 0 1 1
136 1 return sock_err_sys( 0 ); # errno
137 }
138 }
139  
140 sub socketpair_recv
141 230 ▶{
Subroutine socketpair_recv: called CC=11 SCAR=24.0
Pod undocumented
142 230 my $fh = shift;
143 230 my $data = shift;
144  
145 230 sock_err_clear();
146  
147 230 ▶ return sock_err( SOCK_E_INVAL, 0 ) unless ref( $data ) eq 'SCALAR';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "SCALAR" 4 226 230
148  
149 226 while( 1 )
150 {
151 # receive directly into the caller's scalar, its buffer is reused by the
152 # next call, no new $MSG_MAX buffer and no copy per message.
153 # "$$data = undef" below keeps the allocated buffer, only marks it undef
154 228 my $r = recv( $fh, $$data, $MSG_MAX + 1, MSG_DONTWAIT );
155 228 ▶ if( defined $r )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $r) 218 10 228
156 {
157 218 my $len = length( $$data );
158 218 ▶ return 1 if $len > 0 and $len <= $MSG_MAX;
Branch: 1 branch
BranchTrueFalseTotal
if $len > 0 and $len <= $Net::Tools::Socket::Pair::MSG_MAX 213 5 218
Condition100%3/3
$len > 0 and $len <= $Net::Tools::Socket::Pair::MSG_MAX
!ll&&!rl&&r
32213
MC/DC100%2/2
$len > 0 and $len <= $Net::Tools::Socket::Pair::MSG_MAX
$len > 0 $len <= $Net::Tools::Socket::Pair::MSG_MAX
Truth table100%3/3
A and B
A= $len > 0B= $len <= $Net::Tools::Socket::Pair::MSG_MAX
ABresult
0X0
100
111
159 5 $$data = undef;
160 5 ▶ if( $len == 0 )
Branch: 1 branch
BranchTrueFalseTotal
if ($len == 0) 3 2 5
161 {
162 # dgram has no EOF, empty read is an empty datagram, which is never
163 # sent by socketpair_send(), skip it. type is checked only here
164 3 ▶ next if __sock_type( $fh ) == SOCK_DGRAM;
Branch: 1 branch
BranchTrueFalseTotal
if __sock_type($fh) == 2 2 1 3
165 1 return sock_err( SOCK_E_EOF );
166 }
167 2 return sock_err( SOCK_E_TOOBIG, 0 );
168 }
169 10 $$data = undef;
170 10 ▶ next if $!{ EINTR };
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EINTR"} 0 10 10
171 10 ▶ return sock_err( SOCK_E_AGAIN, 0 ) if $!{ EAGAIN } or $!{ EWOULDBLOCK };
Branch: 1 branch
BranchTrueFalseTotal
if $!{"EAGAIN"} or $!{"EWOULDBLOCK"} 9 1 10
Condition66%2/3
$!{"EAGAIN"} or $!{"EWOULDBLOCK"}
l!l&&r!l&&!r
901
MC/DC50%1/2
$!{"EAGAIN"} or $!{"EWOULDBLOCK"}
$!{"EAGAIN"} $!{"EWOULDBLOCK"}
Truth table66%2/3
A or B
A= $!{"EAGAIN"}B= $!{"EWOULDBLOCK"}
ABresult
1X1
011
000
172 1 ▶ return sock_err( SOCK_E_EOF ) if $!{ ECONNRESET };
Branch: 1 branch
BranchTrueFalseTotal
if $!{"ECONNRESET"} 0 1 1
173 1 return sock_err_sys( 0 ); # errno
174 }
175 }
176  
177 ##############################################################################
178 1 1;
179  
180  
181 =pod
182  
183 =head1 NAME
184  
185 Net::Tools::Socket::Pair - non-blocking message passing over socketpair()
186  
187 =head1 SYNOPSIS
188  
189 use Net::Tools::Socket::Pair;
190 use Net::Tools::Socket::Err; # only if error details are needed
191  
192 my ( $parent_sock, $child_sock ) = socketpair_create()
193 or die "socketpair: $SOCK_ERRSTR\n";
194  
195 # sender
196 my $res = socketpair_send( $parent_sock, $message_bytes );
197 # retry later if $SOCK_ERR == SOCK_E_AGAIN
198  
199 # receiver, read all pending messages
200 my $data;
201 while( socketpair_recv( $child_sock, \$data ) )
202 {
203 # one complete message is in $data
204 }
205 # peer closed if $SOCK_ERR == SOCK_E_EOF
206  
207 =head1 DESCRIPTION
208  
209 Message passing over C<socketpair( AF_UNIX, SOCK_SEQPACKET )> or
210 C<socketpair( AF_UNIX, SOCK_DGRAM )>, see L</SOCKET TYPES>. Each
211 C<socketpair_send()> is received by exactly one C<socketpair_recv()> on the
212 other side, always as a whole message. Messages are byte strings, data
213 structures must be serialized before sending.
214  
215 C<socketpair_send()> and C<socketpair_recv()> never sleep, regardless of
216 the blocking mode of the handle (C<MSG_DONTWAIT> is used on every call), and
217 never raise C<SIGPIPE> (C<MSG_NOSIGNAL> is used, where the system does not
218 have it, SIGPIPE is ignored only for the time of the send() call, the
219 caller's C<$SIG{ 'PIPE' }> is restored). They return:
220  
221 1 one whole message sent or received successfully
222 0 nothing to read or peer's queue is full (SOCK_E_AGAIN), message
223 too big (SOCK_E_TOOBIG), invalid message or system error
224 those are considered temporary and operation should be repeated
225 undef peer closed (SOCK_E_EOF), for recv after all queued messages
226 were read, socket must be closed
227  
228 So the result is true only for a message, false for "nothing now", and
229 undef when the peer is gone, which allows:
230  
231 while( socketpair_recv( $fh, \$data ) ) { ... } # read all pending
232 if( ! defined socketpair_recv( $fh, \$data ) ) { ... } # peer closed
233  
234 The reason for 0 or undef is in C<$SOCK_ERR>, see L</ERRORS>.
235  
236 C<socketpair_recv()> sets C<$data> to undef whenever the result is not 1,
237 so a stale value is never left there.
238  
239 Empty or undef messages are not sent, C<socketpair_send()> returns 0 with
240 C<SOCK_E_EMPTY>, because the peer would read an empty message as end of
241 file.
242  
243 Maximum message size is C<$Net::Tools::Socket::Pair::MSG_MAX> (128 KiB by
244 default).
245  
246 All functions are exported by default.
247  
248 =head1 SOCKET TYPES
249  
250 my ( $s1, $s2 ) = socketpair_create(); # SOCK_SEQPACKET
251 my ( $s1, $s2 ) = socketpair_create( 'dgram' ); # SOCK_DGRAM
252  
253 The type is 'seqpacket' (the default) or 'dgram', case insensitive. An
254 unknown type returns an empty list with C<SOCK_E_INVAL>.
255  
256 Both keep message boundaries, never drop messages (a full queue returns
257 C<SOCK_E_AGAIN> to the sender) and hold about the same count of messages.
258 They differ only when the peer closes:
259  
260 seqpacket recv returns undef (SOCK_E_EOF) after all queued messages are
261 read, poll() reports POLLHUP, send returns undef (SOCK_E_EOF)
262  
263 dgram recv never returns EOF, it returns 0 (SOCK_E_AGAIN) forever,
264 poll() reports nothing, only send returns undef (SOCK_E_EOF)
265  
266 So with 'dgram' a receiver which never sends must find out that its peer
267 is gone in another way (getppid(), waitpid(), etc.). On the other hand,
268 a 'dgram' handle may be shared by many processes writing to one reader,
269 which never sees EOF while any of them is still writing.
270  
271 =head1 ERRORS
272  
273 All functions clear C<$SOCK_ERR> and C<$SOCK_ERRSTR> on entry and set them
274 when the result is not 1:
275  
276 SOCK_E_AGAIN nothing to read, or peer's queue is full
277 SOCK_E_EOF peer closed
278 SOCK_E_TOOBIG message over $MSG_MAX or the socket buffer, an incoming
279 message over $MSG_MAX is read and discarded
280 SOCK_E_EMPTY empty or undef message, not sent
281 SOCK_E_INVAL send: message is a reference or has wide (over 255)
282 characters, encode it first
283 recv: $data is not a scalar reference
284 errno any other system error, the positive errno value,
285 its text is in $SOCK_ERRSTR
286  
287 C<socketpair_create()> sets errno on failure, C<SOCK_E_INVAL> for an
288 unknown socket type.
289  
290 errno values are always positive, SOCK_E_* codes are negative, so they never
291 collide. C<sock_err_name()> returns 'EBADF', etc. for errno values.
292  
293 They are exported by L<Net::Tools::Socket::Err>, which must be used by the
294 caller to read them. The error state describes the last call only.
295  
296 =head1 NOTES
297  
298 =over 4
299  
300 =item *
301  
302 Both functions must be given a socket handle, undef or a value that is not
303 a handle will die (a closed handle returns 0 with errno). C<socketpair_recv()> must be given a reference to a
304 writable scalar (C<\$data>) for the received data: anything that is not a
305 scalar reference returns 0 with C<SOCK_E_INVAL> and the message stays
306 queued, a reference to a read-only value (C<\'text'>) will die.
307  
308 =item *
309  
310 Tested on Linux only. C<SOCK_SEQPACKET> on C<AF_UNIX> sockets is not
311 supported on macOS, use 'dgram' there, but the system may limit 'dgram'
312 messages far below C<$MSG_MAX> (net.local.dgram.maxdgram). Where
313 C<MSG_NOSIGNAL> is not available (macOS), C<SIGPIPE> is ignored during
314 send instead, see above.
315  
316 =back
317  
318 =head1 SEE ALSO
319  
320 L<Net::Tools::Socket>, L<Net::Tools::Socket::Err>, L<socketpair(2)>, L<Socket>
321  
322 =head1 AUTHOR
323  
324 Vladi Belperchinov-Shabanski "Cade"
325 <cade@noxrun.com>
326 http://cade.noxrun.com/
327  
328 =head1 COPYRIGHT AND LICENSE
329  
330 Copyright (c) 2026 Vladi Belperchinov-Shabanski "Cade"
331  
332 This program is free software; you can redistribute it and/or modify it
333 under the terms of the GNU General Public License as published by the
334 Free Software Foundation; either version 2 of the License, or (at your
335 option) any later version.
336  
337 =cut
↑ Summary lib/Net/Tools/Socket.pm »