lib/Net/Tools/Socket/Protocols.pm

filter: Statementstmt 96.3% 105 / 109 Branchbran 94.1% 32 / 34 Conditioncond 100% 8 / 8 MC/DCmcdc 100% 5 / 5 Subroutinesub 90.9% 20 / 22 Podpod 18.7% 3 / 16 totaltotal 89.1% 173 / 194 CC 22 SCAR 14.9
CC
22
Cov
96%
socket_protocol_read_message
9.0
socket_protocol_write_message
7.0
load_protocol
5.0
CRAP 4.4
« lib/Net/Tools/Socket.pm ↑ Summary lib/Net/Tools/Socket/Err.pm »
1 ##############################################################################
2 #
3 # Net::Tools::Socket::Protocols perl module
4 # Copyright (c) 2013-2026 Vladi Belperchinov-Shabanski "Cade"
5 # <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
6 # http://cade.noxrun.com/
7 #
8 # GPL
9 #
10 # Net::Tools::Socket::Protocols is ported from Decor's
11 # Decor::Shared::Net::Protocols: https://github.com/cade-vs/perl-decor
12 #
13 ##############################################################################
14 package Net::Tools::Socket::Protocols;
15 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use Data::Tools;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use Net::Tools::Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use Net::Tools::Socket::Err;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 1 our $VERSION = '1.60';
23  
24 1 our @ISA = qw( Exporter );
25 1 our @EXPORT = qw(
26 socket_protocol_read_message
27 socket_protocol_write_message
28  
29 socket_protocols_allow
30 );
31  
32 1 our %EXPORT_TAGS = (
33 'all' => \@EXPORT,
34 'none' => [],
35 );
36  
37 1 my %PROTOCOL_TYPES = (
38 'b' => {
39 # binary. does not require anything
40 },
41 'p' => {
42 'require' => 'Storable',
43 'pack' => \&protocol_type_storable_pack,
44 'unpack' => \&protocol_type_storable_unpack,
45 },
46 'e' => {
47 'require' => 'Sereal',
48 'pack' => \&protocol_type_sereal_pack,
49 'unpack' => \&protocol_type_sereal_unpack,
50 },
51 's' => {
52 'require' => 'Data::Stacker',
53 'pack' => \&protocol_type_stacker_pack,
54 'unpack' => \&protocol_type_stacker_unpack,
55 },
56 'j' => {
57 'require' => 'JSON',
58 'pack' => \&protocol_type_json_pack,
59 'unpack' => \&protocol_type_json_unpack,
60 },
61 'h' => {
62 'require' => undef,
63 'pack' => \&protocol_type_hash_pack,
64 'unpack' => \&protocol_type_hash_unpack,
65 },
66 'H' => {
67 'require' => undef,
68 'pack' => \&protocol_type_hash_url_pack,
69 'unpack' => \&protocol_type_hash_url_unpack,
70 },
71 );
72  
73 1 my %PROTOCOL_ALLOW = map { $_ => 1 } keys %PROTOCOL_TYPES;
74 1 delete $PROTOCOL_ALLOW{ 'p' }; # Storable, sadly, is reported unsafe
75  
76 sub socket_protocol_read_message
77 33 ▶{
Subroutine socket_protocol_read_message: called CC=9 SCAR=22.0
Pod documented
78 33 my $socket = shift;
79 33 my $timeout = shift;
80 33 my $maxlen = shift;
81  
82 # socket_read_message() clears and sets $SOCK_ERR
83 33 ▶ my $data = socket_read_message( $socket, $timeout, $maxlen ) // return undef;
Condition100%2/2
socket_read_message($socket, $timeout, $maxlen) // (return undef)
l!l
312
MC/DC100%1/1
socket_read_message($socket, $timeout, $maxlen) // (return undef)
socket_read_message($socket, $timeout, $maxlen)
Truth table100%2/2
A
A= socket_read_message($socket, $timeout, $maxlen)
Aresult
11
00
84 31 my $data_read_len = length( $data );
85  
86 31 ▶ return sock_err( SOCK_E_EMPTY ) if $data_read_len < 1; # no protocol type and payload
Branch: 1 branch
BranchTrueFalseTotal
if $data_read_len < 1 2 29 31
87  
88 29 my $ptype = substr( $data, 0, 1 );
89  
90 29 ▶ return sock_err( SOCK_E_PROTO, undef, "unknown or forbidden PROTOCOL_TYPE [hex:" . str_hex( $ptype ) . "]" ) unless exists $PROTOCOL_ALLOW{ $ptype };
Branch: 1 branch
BranchTrueFalseTotal
unless exists $PROTOCOL_ALLOW{$ptype} 5 24 29
91  
92 24 my $hr;
93 24 ▶ if( $ptype eq 'b' )
Branch: 1 branch
BranchTrueFalseTotal
if ($ptype eq 'b') { } 5 19 24
94 {
95 # no unpack for binary messages payload
96 5 $hr = substr( $data, 1 );
97 }
98 else
99 {
100 19 local $@;
101 19 $hr = eval { $PROTOCOL_TYPES{ $ptype }->{ 'unpack' }->( substr( $data, 1 ) ) };
102 19 ▶ my $err = eval_err_strip( $@ ) || ( ref( $hr ) eq 'HASH' ? undef : 'invalid data, expected HASH reference' );
Branch: 1 branch
BranchTrueFalseTotal
ref $hr eq 'HASH' ? : 16 1 17
Condition100%3/3
eval_err_strip($@) || (ref $hr eq 'HASH' ? undef : 'invalid data, expected HASH reference')
l!l&&r!l&&!r
2116
MC/DC100%2/2
eval_err_strip($@) || (ref $hr eq 'HASH' ? undef : 'invalid data, expected HASH reference')
eval_err_strip($@) (ref $hr eq 'HASH' ? undef : 'invalid data, expected HASH reference')
Truth table100%3/3
A || B
A= eval_err_strip($@)B= (ref $hr eq 'HASH' ? undef : 'invalid data, expected HASH reference')
ABresult
1X1
011
000
103 19 ▶ return sock_err( SOCK_E_PROTO, undef, $err ) if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 3 16 19
104 }
105  
106 21 ▶ return wantarray ? ( $hr, $ptype ) : $hr;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 19 21
107 }
108  
109 sub socket_protocol_write_message
110 39 ▶{
Subroutine socket_protocol_write_message: called CC=7 SCAR=19.5
Pod documented
111 39 my $socket = shift;
112 39 my $ptype = shift;
113 39 my $hr = shift; # hash reference or plain data if proto is 'b'inary
114 39 my $timeout = shift;
115  
116 39 sock_err_clear();
117  
118 #FIXME: str_hex() wraps a wide character type to its low byte, "\x{16a}" shows as [hex:6a]
119 39 ▶ return sock_err( SOCK_E_PROTO, undef, "unknown or forbidden PROTOCOL_TYPE [hex:" . str_hex( $ptype ) . "]" ) unless length( $ptype ) == 1 and exists $PROTOCOL_ALLOW{ $ptype };
Branch: 1 branch
BranchTrueFalseTotal
unless length $ptype == 1 and exists $PROTOCOL_ALLOW{$ptype} 11 28 39
Condition100%3/3
length $ptype == 1 and exists $PROTOCOL_ALLOW{$ptype}
!ll&&!rl&&r
4728
MC/DC100%2/2
length $ptype == 1 and exists $PROTOCOL_ALLOW{$ptype}
length $ptype == 1 exists $PROTOCOL_ALLOW{$ptype}
Truth table100%3/3
A and B
A= length $ptype == 1B= exists $PROTOCOL_ALLOW{$ptype}
ABresult
0X0
100
111
120  
121 28 my $data;
122  
123 28 ▶ if( $ptype eq 'b' )
Branch: 1 branch
BranchTrueFalseTotal
if ($ptype eq 'b') { } 10 18 28
124 {
125 10 ▶ return sock_err( SOCK_E_INVAL ) if ref( $hr );
Branch: 1 branch
BranchTrueFalseTotal
if ref $hr 4 6 10
126 # no pack for binary messages payload
127 6 $data = $ptype . $hr;
128 }
129 else
130 {
131 18 ▶ return sock_err( SOCK_E_INVAL ) unless ref( $hr ) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $hr eq "HASH" 2 16 18
132 16 local $@;
133 16 my $packed = eval { $PROTOCOL_TYPES{ $ptype }->{ 'pack' }->( $hr ) };
134 16 ▶ return sock_err( SOCK_E_PROTO, undef, eval_err_strip( $@ ) ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 15 16
135 15 $data = $ptype . $packed;
136 }
137  
138 21 return socket_write_message( $socket, $data, $timeout );
139 }
140  
141  
142 sub socket_protocols_allow
143 12 ▶{
Subroutine socket_protocols_allow: called CC=4 SCAR=13.9
Pod documented
144 12 my @p = split //, join '', @_;
145 12 my %p;
146 12 for my $ptype ( @p )
147 {
148 18 ▶ if( $ptype eq '*' )
Branch: 1 branch
BranchTrueFalseTotal
if ($ptype eq '*') { } 5 13 18
149 {
150 5 %p = map { $_ => 1 } keys %PROTOCOL_TYPES;
151 5 delete $p{ 'p' }; # Storable, sadly, is reported unsafe
152 }
153 else
154 {
155 13 ▶ confess( "unknown PROTOCOL_TYPE requested [$ptype] expected one of [" . join( ',', sort keys %PROTOCOL_TYPES ) . "]" ) unless exists $PROTOCOL_TYPES{ $ptype };
Branch: 1 branch
BranchTrueFalseTotal
unless exists $PROTOCOL_TYPES{$ptype} 2 11 13
156 11 $p{ $ptype }++;
157 }
158 }
159 10 %PROTOCOL_ALLOW = %p;
160 10 return 1;
161 }
162  
163 1 my %PROTOCOL_LOADED;
164 sub load_protocol
165 35 ▶{
Subroutine load_protocol: called CC=5 SCAR=16.1
Pod undocumented
166 35 my $ptype = shift;
167 35 ▶ return 1 if exists $PROTOCOL_LOADED{ $ptype };
Branch: 1 branch
BranchTrueFalseTotal
if exists $PROTOCOL_LOADED{$ptype} 30 5 35
168 5 ▶ confess( "unknown or forbidden PROTOCOL_TYPE requested [$ptype] expected one of [" . join( ',', sort keys %PROTOCOL_ALLOW ) . "]" ) unless exists $PROTOCOL_ALLOW{ $ptype };
Branch: 1 branch
BranchTrueFalseTotal
unless exists $PROTOCOL_ALLOW{$ptype} 0 5 5
169  
170 5 my $req = $PROTOCOL_TYPES{ $ptype }{ 'require' };
171 5 ▶ if( $req )
Branch: 1 branch
BranchTrueFalseTotal
if ($req) 3 2 5
172 {
173 3 local $@;
174 3 eval { my $fn = perl_package_to_file( $req ); require $fn; };
175 3 ▶ confess( $@ ) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 3 3
176 }
177 5 $PROTOCOL_LOADED{ $ptype }++;
178 5 return 2;
179 }
180  
181  
182 sub protocol_type_storable_pack
183 2 ▶{
Subroutine protocol_type_storable_pack: called CC=1 SCAR=0.0
Pod undocumented
184 2 load_protocol( 'p' );
185 2 return Storable::nfreeze( shift );
186 }
187  
188 sub protocol_type_storable_unpack
189 2 ▶{
Subroutine protocol_type_storable_unpack: called CC=1 SCAR=0.0
Pod undocumented
190 2 load_protocol( 'p' );
191 2 return Storable::thaw( shift(), 0 ); # do not allow bless and tie
192 }
193  
194 sub protocol_type_sereal_pack
195 1 ▶{
Subroutine protocol_type_sereal_pack: called CC=1 SCAR=0.0
Pod undocumented
196 1 load_protocol( 'e' );
197 1 return Sereal::encode_sereal( shift );
198 }
199  
200 sub protocol_type_sereal_unpack
201 1 ▶{
Subroutine protocol_type_sereal_unpack: called CC=1 SCAR=0.0
Pod undocumented
202 1 load_protocol( 'e' );
203 1 return Sereal::decode_sereal( shift );
204 }
205  
206 sub protocol_type_stacker_pack
207 0 ▶{
Subroutine protocol_type_stacker_pack: not called CC=1 SCAR=6.9
Pod undocumented
208 0 load_protocol( 's' );
209 0 return Data::Stacker::stack_data( shift );
210 }
211  
212 sub protocol_type_stacker_unpack
213 0 ▶{
Subroutine protocol_type_stacker_unpack: not called CC=1 SCAR=6.9
Pod undocumented
214 0 load_protocol( 's' );
215 0 return Data::Stacker::unstack_data( shift );
216 }
217  
218 sub protocol_type_json_pack
219 2 ▶{
Subroutine protocol_type_json_pack: called CC=1 SCAR=0.0
Pod undocumented
220 2 load_protocol( 'j' );
221 2 return JSON::encode_json( shift );
222 }
223  
224 sub protocol_type_json_unpack
225 4 ▶{
Subroutine protocol_type_json_unpack: called CC=1 SCAR=0.0
Pod undocumented
226 4 load_protocol( 'j' );
227 4 return JSON::decode_json( shift );
228 }
229  
230 sub protocol_type_hash_pack
231 9 ▶{
Subroutine protocol_type_hash_pack: called CC=1 SCAR=0.0
Pod undocumented
232 9 load_protocol( 'h' );
233 9 return hash2str( shift );
234 }
235  
236 sub protocol_type_hash_unpack
237 10 ▶{
Subroutine protocol_type_hash_unpack: called CC=1 SCAR=0.0
Pod undocumented
238 10 load_protocol( 'h' );
239 10 return str2hash( shift );
240 }
241  
242 sub protocol_type_hash_url_pack
243 2 ▶{
Subroutine protocol_type_hash_url_pack: called CC=1 SCAR=0.0
Pod undocumented
244 2 load_protocol( 'H' );
245 2 return hash2str_url( shift );
246 }
247  
248 sub protocol_type_hash_url_unpack
249 2 ▶{
Subroutine protocol_type_hash_url_unpack: called CC=1 SCAR=0.0
Pod undocumented
250 2 load_protocol( 'H' );
251 2 return str2hash_url( shift );
252 }
253  
254 ##############################################################################
255  
256 =pod
257  
258  
259 =head1 NAME
260  
261 Net::Tools::Socket::Protocols - transparent serialization on top of the Net::Tools::Socket message functions
262  
263 =head1 SYNOPSIS
264  
265 use Net::Tools::Socket::Protocols qw( :all ); # import all functions
266 use Net::Tools::Socket::Protocols; # the same as :all :)
267 use Net::Tools::Socket::Protocols qw( :none ); # do not import anything
268  
269 # --------------------------------------------------------------------------
270  
271 # send a hash reference, serialized with the 'j'son protocol
272 socket_protocol_write_message( $socket, 'j', $hash_ref, $timeout );
273  
274 # read it back, the protocol type is taken from the message itself
275 my $hash_ref = socket_protocol_read_message( $socket, $timeout, $maxlen );
276  
277 # in list context the protocol type is returned too, to reply in the same type
278 my ( $hash_ref, $ptype ) = socket_protocol_read_message( $socket, $timeout );
279  
280 # error details
281 use Net::Tools::Socket::Err;
282 print "error: $SOCK_ERRSTR\n" unless defined $hash_ref;
283  
284 # the 'b'inary protocol carries plain data instead of a hash reference
285 socket_protocol_write_message( $socket, 'b', $raw_data, $timeout );
286  
287 # --------------------------------------------------------------------------
288  
289 # restrict which protocol types will be accepted and sent
290 socket_protocols_allow( 'bjh' ); # only binary, json and hash
291 socket_protocols_allow( 'b', 'jh' ); # the same, arguments are concatenated
292 socket_protocols_allow( '*' ); # all types again, except 'p' Storable
293 socket_protocols_allow( '*p' ); # really all types, including Storable
294  
295 # --------------------------------------------------------------------------
296  
297 =head1 PROTOCOL TYPES
298  
299 A protocol type is a single character, sent as the first byte of every
300 message. The rest of the message is the payload, serialized accordingly:
301  
302 'b' binary, payload is plain data, not a hash reference
303 'p' Storable (nfreeze/thaw), forbidden by default, see below
304 'e' Sereal
305 's' Data::Stacker
306 'j' JSON
307 'h' hash2str() from Data::Tools, needs no extra module
308 'H' hash2str_url() from Data::Tools, needs no extra module
309  
310 Except for 'b', the payload is always a hash reference.
311  
312 The module needed by a protocol type is loaded on demand, the first time
313 that type is actually used, so a missing module is only a problem if the
314 corresponding protocol type is used. 'b', 'h' and 'H' need no extra module.
315  
316 'p' Storable is not safe on untrusted input, so it is forbidden by default
317 and is not allowed by '*' either. It must be allowed explicitly with
318 socket_protocols_allow(), only when both peers are trusted.
319  
320 NOTE: Storable is a core module and JSON is already required by
321 Data::Tools, so those modules are always installed ('p' still
322 has to be allowed first). Sereal and Data::Stacker are not
323 required by this distribution and may need to be installed
324 separately.
325  
326 =head1 FUNCTIONS
327  
328 =head2 socket_protocol_write_message( $socket, $ptype, $data, $timeout )
329  
330 Serializes $data according to the $ptype protocol type, prefixes it with the
331 protocol type character and sends it with socket_write_message().
332  
333 $data must be a hash reference, unless $ptype is 'b', in which case it is
334 plain data (a string, not a reference).
335  
336 $timeout is passed to socket_write_message(), see L<Net::Tools::Socket>.
337  
338 Returns 1 on success or undef if the message could not be sent, with
339 $SOCK_ERR set (see L</ERRORS>):
340  
341 SOCK_E_PROTO $ptype is not a single known and allowed protocol type,
342 or serializing failed (including a missing serializer
343 module), details in $SOCK_ERRSTR
344 SOCK_E_INVAL $data is not a hash reference for a non-binary protocol
345 type, or is a reference or has wide characters for 'b'
346 ... any socket_write_message() error
347  
348 On a socket_write_message() error the stream may be out of sync, see
349 L<Net::Tools::Socket>.
350  
351 WARNING! Writing to a socket closed by the peer raises SIGPIPE, which kills
352 the process by default. The caller must set C<$SIG{ 'PIPE' } = 'IGNORE'>,
353 see socket_write() in L<Net::Tools::Socket>.
354  
355 =head2 socket_protocol_read_message( $socket, $timeout, $maxlen )
356  
357 Reads a message with socket_read_message(), takes the protocol type from its
358 first byte and deserializes the rest accordingly.
359  
360 $timeout and $maxlen are passed to socket_read_message(), see
361 L<Net::Tools::Socket>. $maxlen limits the whole message, including the
362 protocol type byte.
363  
364 Returns the deserialized hash reference, or the plain data for 'b' ("" if
365 the 'b' message has no payload), or undef on error with $SOCK_ERR set (see
366 L</ERRORS>):
367  
368 SOCK_E_EMPTY the message is empty, it has no protocol type byte
369 SOCK_E_PROTO the protocol type is not known or not allowed, or the
370 payload does not deserialize into a hash reference
371 (including an empty payload and a missing deserializer
372 module), details in $SOCK_ERRSTR
373 ... any socket_read_message() error
374  
375 After SOCK_E_EMPTY and SOCK_E_PROTO the socket stream is still in sync (the
376 whole message was read), so the socket may be used further.
377  
378 In list context it returns the data and the protocol type character of the
379 message, for example to reply in the same protocol type:
380  
381 my ( $hash_ref, $ptype ) = socket_protocol_read_message( $socket, $timeout );
382 socket_protocol_write_message( $socket, $ptype, $reply_ref, $timeout ) if $hash_ref;
383  
384 On error it returns a single undef in list context too, so both $hash_ref
385 and $ptype are undef.
386  
387 NOTE: arguments of a function without a prototype, such as Test::More's
388 is_deeply(), are evaluated in list context, use scalar() there to get the
389 data only.
390  
391 =head2 socket_protocols_allow( @protocol_types )
392  
393 Sets which protocol types will be accepted and sent, replacing the previous
394 set. The arguments are concatenated and then split into single characters,
395 so these are the same:
396  
397 socket_protocols_allow( 'bjh' );
398 socket_protocols_allow( 'b', 'j', 'h' );
399  
400 '*' stands for all known protocol types except 'p'. It replaces everything
401 before it, so 'j*' is the same as '*', and types after it are added, so
402 '*p' allows all types including 'p'.
403  
404 Called with no arguments (or only empty strings) it forbids all protocol
405 types, no message can be sent or accepted until it is called again.
406  
407 By default all protocol types except 'p' are allowed.
408  
409 Returns 1. Confesses if an unknown protocol type is given, in which case
410 the allowed set is not changed.
411  
412 =head1 ERRORS
413  
414 Both read and write functions clear $SOCK_ERR and $SOCK_ERRSTR on entry and
415 set them on failure. They are exported by L<Net::Tools::Socket::Err>, which
416 must be used by the caller to read them. See also L<Net::Tools::Socket>.
417  
418 =head1 REQUIRED MODULES
419  
420 Net::Tools::Socket::Protocols uses:
421  
422 * Data::Tools
423 * Net::Tools::Socket
424 * Net::Tools::Socket::Err
425  
426 and, on demand and only for the corresponding protocol types:
427  
428 * Storable, Sereal, Data::Stacker, JSON
429  
430 =head1 GITHUB REPOSITORY
431  
432 git@github.com:cade-vs/perl-net-tools.git
433  
434 git clone https://github.com/cade-vs/perl-net-tools.git
435  
436 =head1 AUTHOR
437  
438 Vladi Belperchinov-Shabanski "Cade"
439 <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
440 http://cade.noxrun.com/
441  
442 =head1 COPYRIGHT AND LICENSE
443  
444 Copyright (c) 2013-2026 Vladi Belperchinov-Shabanski "Cade"
445  
446 This program is free software; you can redistribute it and/or modify it
447 under the terms of the GNU General Public License as published by the
448 Free Software Foundation; either version 2 of the License, or (at your
449 option) any later version.
450  
451 =cut
452  
453 ##############################################################################
454 1 1;
« lib/Net/Tools/Socket.pm ↑ Summary lib/Net/Tools/Socket/Err.pm »