blib/lib/IO/Async/Resolver.pm

filter: Statementstmt 65.3% 134 / 205 Branchbran 47.8% 68 / 142 Conditioncond 66.6% 22 / 33 MC/DCmcdc 22.2% 4 / 18 Subroutinesub 45.9% 17 / 37 Podpod 66.6% 4 / 6 totaltotal 56.4% 249 / 441 CC 87 SCAR 28.5
CC
87
Cov
59%
__ANON__
42.0
__ANON__
42.0
getaddrinfo
31.5
CRAP 17.2
« blib/lib/IO/Async/Loop/Poll.pm ↑ Summary blib/lib/IO/Async/Stream.pm »
1 # You may distribute under the terms of either the GNU General Public License
2 # or the Artistic License (the same terms as Perl itself)
3 #
4 # (C) Paul Evans, 2007-2024 -- leonerd@leonerd.org.uk
5  
6 package IO::Async::Resolver 0.805;
7  
8 7 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 ▶use base qw( IO::Async::Function );
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 # Socket 2.006 fails to getaddrinfo() AI_NUMERICHOST properly on MSWin32
13 7 use Socket 2.007 qw(
14 AI_NUMERICHOST AI_PASSIVE
15 NI_NUMERICHOST NI_NUMERICSERV NI_DGRAM
16 EAI_NONAME
17 7 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 7 ▶use IO::Async::Metrics '$METRICS';
Subroutine BEGIN: called CC=1 SCAR=0.0
20 7 ▶use IO::Async::OS;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 # Try to use HiRes alarm, but we don't strictly need it.
23 # MSWin32 doesn't implement it
24 BEGIN {
25 7 ▶ require Time::HiRes;
Subroutine BEGIN: called CC=2 SCAR=7.1
26 7 ▶ eval { Time::HiRes::alarm(0) } and Time::HiRes->import( qw( alarm ) );
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &Time::HiRes::alarm(0) } } and "Time::HiRes"->import("alarm") 0 7 7
27 }
28  
29 7 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 7 my $started = 0;
32 7 my %METHODS;
33  
34 =head1 NAME
35  
36 C<IO::Async::Resolver> - performing name resolutions asynchronously
37  
38 =head1 SYNOPSIS
39  
40 =for highlighter language=perl
41  
42 This object is used indirectly via an L<IO::Async::Loop>:
43  
44 use Future::AsyncAwait;
45 use IO::Async::Loop;
46  
47 my $loop = IO::Async::Loop->new;
48  
49 my @results = await $loop->resolver->getaddrinfo(
50 host => "www.example.com",
51 service => "http",
52 );
53  
54 foreach my $addr ( @results ) {
55 printf "http://www.example.com can be reached at " .
56 "socket(%d,%d,%d) + connect('%v02x')\n",
57 @{$addr}{qw( family socktype protocol addr )};
58 }
59  
60 my @pwent = await $loop->resolve( type => 'getpwuid', data => [ $< ] );
61  
62 print "My passwd ent: " . join( "|", @pwent ) . "\n";
63  
64 =head1 DESCRIPTION
65  
66 This module extends an L<IO::Async::Loop> to use the system's name resolver
67 functions asynchronously. It provides a number of named resolvers, each one
68 providing an asynchronous wrapper around a single resolver function.
69  
70 Because the system may not provide asynchronous versions of its resolver
71 functions, this class is implemented using a L<IO::Async::Function> object
72 that wraps the normal (blocking) functions. In this case, name resolutions
73 will be performed asynchronously from the rest of the program, but will likely
74 be done by a single background worker process, so will be processed in the
75 order they were requested; a single slow lookup will hold up the queue of
76 other requests behind it. To mitigate this, multiple worker processes can be
77 used; see the C<workers> argument to the constructor.
78  
79 The C<idle_timeout> parameter for the underlying L<IO::Async::Function> object
80 is set to a default of 30 seconds, and C<min_workers> is set to 0. This
81 ensures that there are no spare processes sitting idle during the common case
82 of no outstanding requests.
83  
84 =cut
85  
86 sub _init
87 {
88 6 ▶ my $self = shift;
Subroutine _init: called CC=1 SCAR=0.0
89 6 my ( $params ) = @_;
90 6 $self->SUPER::_init( @_ );
91  
92 6 $params->{module} = __PACKAGE__;
93 6 $params->{func} = "_resolve";
94  
95 6 $params->{idle_timeout} = 30;
96 6 $params->{min_workers} = 0;
97  
98 6 $started = 1;
99 }
100  
101 sub _resolve
102 {
103 0 ▶ my ( $type, $timeout, @data ) = @_;
Subroutine _resolve: not called CC=3 SCAR=24.8
104  
105 0 ▶ if( my $code = $METHODS{$type} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $code = $METHODS{$type}) { } 0 0 0
106 0 ▶ local $SIG{ALRM} = sub { die "Timed out\n" };
Subroutine __ANON__: not called CC=1 SCAR=6.9
107  
108 0 alarm( $timeout );
109 0 my @ret = eval { $code->( @data ) };
110 0 alarm( 0 );
111  
112 0 ▶ die $@ if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
113 0 return @ret;
114 }
115 else {
116 0 die "Unrecognised resolver request '$type'";
117 }
118 }
119  
120 sub debug_printf_call
121 {
122 13 ▶ my $self = shift;
Subroutine debug_printf_call: called CC=3 SCAR=11.0
Pod undocumented
123 13 my ( $type, undef, @data ) = @_;
124  
125 13 my $arg0;
126 13 ▶ if( $type eq "getaddrinfo" ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'getaddrinfo') { } 5 8 13
elsif ($type eq 'getnameinfo') { } 3 5 8
127 5 my %args = @data;
128 5 $arg0 = sprintf "%s:%s", @args{qw( host service )};
129 }
130 elsif( $type eq "getnameinfo" ) {
131 # cheat
132 3 $arg0 = sprintf "%s:%s", ( Socket::getnameinfo( $data[0], NI_NUMERICHOST|NI_NUMERICSERV ) )[1,2];
133 }
134 else {
135 5 $arg0 = $data[0];
136 }
137  
138 13 $self->debug_printf( "CALL $type $arg0" );
139 }
140  
141 sub debug_printf_result
142 {
143 12 ▶ my $self = shift;
Subroutine debug_printf_result: called CC=1 SCAR=0.0
Pod undocumented
144 12 my ( @result ) = @_;
145 12 $self->debug_printf( "RESULT n=" . scalar @result );
146 }
147  
148 =head1 METHODS
149  
150 The following methods documented in C<await> expressions return L<Future>
151 instances.
152  
153 =cut
154  
155 =head2 resolve
156  
157 @result = await $loop->resolve( %params );
158  
159 Performs a single name resolution operation, as given by the keys in the hash.
160  
161 The C<%params> hash keys the following keys:
162  
163 =over 8
164  
165 =item type => STRING
166  
167 Name of the resolution operation to perform. See BUILT-IN RESOLVERS for the
168 list of available operations.
169  
170 =item data => ARRAY
171  
172 Arguments to pass to the resolver function. Exact meaning depends on the
173 specific function chosen by the C<type>; see BUILT-IN RESOLVERS.
174  
175 =item timeout => NUMBER
176  
177 Optional. Timeout in seconds, after which the resolver operation will abort
178 with a timeout exception. If not supplied, a default of 10 seconds will apply.
179  
180 =back
181  
182 On failure, the fail category name is C<resolve>; the details give the
183 individual resolver function name (e.g. C<getaddrinfo>), followed by other
184 error details specific to the resolver in question.
185  
186 ->fail( $message, resolve => $type => @details )
187  
188 =head2 resolve (void)
189  
190 $resolver->resolve( %params );
191  
192 When not returning a future, additional parameters can be given containing the
193 continuations to invoke on success or failure:
194  
195 =over 8
196  
197 =item on_resolved => CODE
198  
199 A continuation that is invoked when the resolver function returns a successful
200 result. It will be passed the array returned by the resolver function.
201  
202 $on_resolved->( @result )
203  
204 =item on_error => CODE
205  
206 A continuation that is invoked when the resolver function fails. It will be
207 passed the exception thrown by the function.
208  
209 =back
210  
211 =cut
212  
213 sub resolve
214 {
215 13 ▶ my $self = shift;
Subroutine resolve: called CC=15 SCAR=28.1
Pod documented
216 13 my %args = @_;
217  
218 13 my $type = $args{type};
219 13 ▶ defined $type or croak "Expected 'type'";
Branch: 1 branch
BranchTrueFalseTotal
defined $type or croak("Expected 'type'") 0 13 13
220  
221 13 ▶ if( $type eq "getaddrinfo_hash" ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "getaddrinfo_hash") 1 12 13
222 1 $type = "getaddrinfo";
223 }
224  
225 13 ▶ exists $METHODS{$type} or croak "Expected 'type' to be an existing resolver method, got '$type'";
Branch: 1 branch
BranchTrueFalseTotal
exists $METHODS{$type} or croak("Expected 'type' to be an existing resolver method, got '${type}'") 0 13 13
226  
227 13 my $on_resolved;
228 13 ▶ if( $on_resolved = $args{on_resolved} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($on_resolved = $args{'on_resolved'}) { } 5 8 13
elsif (not defined wantarray) { } 0 8 8
229 5 ▶ ref $on_resolved or croak "Expected 'on_resolved' to be a reference";
Branch: 1 branch
BranchTrueFalseTotal
ref $on_resolved or croak("Expected 'on_resolved' to be a reference") 0 5 5
230 }
231 elsif( !defined wantarray ) {
232 0 croak "Expected 'on_resolved' or to return a Future";
233 }
234  
235 13 my $on_error;
236 13 ▶ if( $on_error = $args{on_error} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($on_error = $args{'on_error'}) { } 5 8 13
elsif (not defined wantarray) { } 0 8 8
237 5 ▶ ref $on_error or croak "Expected 'on_error' to be a reference";
Branch: 1 branch
BranchTrueFalseTotal
ref $on_error or croak("Expected 'on_error' to be a reference") 0 5 5
238 }
239 elsif( !defined wantarray ) {
240 0 croak "Expected 'on_error' or to return a Future";
241 }
242  
243 13 ▶ my $timeout = $args{timeout} || 10;
Condition50%1/2
$args{'timeout'} || 10
l!l
013
MC/DC0%0/1
$args{'timeout'} || 10
$args{'timeout'}
Truth table50%1/2
A
A= $args{'timeout'}
Aresult
11
00
244  
245 13 ▶ $METRICS and $METRICS->inc_counter( resolver_lookups => [ type => $type ] );
Branch: 1 branch
BranchTrueFalseTotal
$IO::Async::Resolver::METRICS and $IO::Async::Resolver::METRICS->inc_counter("resolver_lookups", ["type", $type]) 12 1 13
246  
247 my $future = $self->call(
248 13 args => [ $type, $timeout, @{$args{data}} ],
249 )->else( sub {
250 1 ▶ my ( $message, @detail ) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.1
251 1 ▶ $METRICS and $METRICS->inc_counter( resolver_failures => [ type => $type ] );
Branch: 1 branch
BranchTrueFalseTotal
$IO::Async::Resolver::METRICS and $IO::Async::Resolver::METRICS->inc_counter("resolver_failures", ["type", $type]) 1 0 1
252 1 Future->fail( $message, resolve => $type => @detail );
253 13 });
254  
255 13 ▶ $future->on_done( $on_resolved ) if $on_resolved;
Branch: 1 branch
BranchTrueFalseTotal
if $on_resolved 5 8 13
256 13 ▶ $future->on_fail( $on_error ) if $on_error;
Branch: 1 branch
BranchTrueFalseTotal
if $on_error 5 8 13
257  
258 13 ▶ return $future if defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if defined wantarray 8 5 13
259  
260 # Caller is not going to keep hold of the Future, so we have to ensure it
261 # stays alive somehow
262 5 ▶ $self->adopt_future( $future->else( sub { Future->done } ) );
Subroutine __ANON__: not called CC=1 SCAR=1.2
263 }
264  
265 =head2 getaddrinfo
266  
267 @addrs = await $resolver->getaddrinfo( %args );
268  
269 A shortcut wrapper around the C<getaddrinfo> resolver, taking its arguments in
270 a more convenient form.
271  
272 =over 8
273  
274 =item host => STRING
275  
276 =item service => STRING
277  
278 The host and service names to look up. At least one must be provided.
279  
280 =item family => INT or STRING
281  
282 =item socktype => INT or STRING
283  
284 =item protocol => INT
285  
286 Hint values used to filter the results.
287  
288 =item flags => INT
289  
290 Flags to control the C<getaddrinfo(3)> function. See the C<AI_*> constants in
291 L<Socket>'s C<getaddrinfo> function for more detail.
292  
293 =item passive => BOOL
294  
295 If true, sets the C<AI_PASSIVE> flag. This is provided as a convenience to
296 avoid the caller from having to import the C<AI_PASSIVE> constant from
297 C<Socket>.
298  
299 =item timeout => NUMBER
300  
301 Time in seconds after which to abort the lookup with a C<Timed out> exception
302  
303 =back
304  
305 On success, the future will yield the result as a list of HASH references;
306 each containing one result. Each result will contain fields called C<family>,
307 C<socktype>, C<protocol> and C<addr>. If requested by C<AI_CANONNAME> then the
308 C<canonname> field will also be present.
309  
310 On failure, the detail field will give the error number, which should match
311 one of the C<Socket::EAI_*> constants.
312  
313 ->fail( $message, resolve => getaddrinfo => $eai_errno )
314  
315 As a specific optimisation, this method will try to perform a lookup of
316 numeric values synchronously, rather than asynchronously, if it looks likely
317 to succeed.
318  
319 Specifically, if the service name is entirely numeric, and the hostname looks
320 like an IPv4 or IPv6 string, a synchronous lookup will first be performed
321 using the C<AI_NUMERICHOST> flag. If this gives an C<EAI_NONAME> error, then
322 the lookup is performed asynchronously instead.
323  
324 =head2 getaddrinfo (void)
325  
326 $resolver->getaddrinfo( %args );
327  
328 When not returning a future, additional parameters can be given containing the
329 continuations to invoke on success or failure:
330  
331 =over 8
332  
333 =item on_resolved => CODE
334  
335 Callback which is invoked after a successful lookup.
336  
337 $on_resolved->( @addrs );
338  
339 =item on_error => CODE
340  
341 Callback which is invoked after a failed lookup, including for a timeout.
342  
343 $on_error->( $exception );
344  
345 =back
346  
347 =cut
348  
349 sub getaddrinfo
350 {
351 16 ▶ my $self = shift;
Subroutine getaddrinfo: called CC=25 SCAR=34.5
Pod documented
352 16 my %args = @_;
353  
354 $args{on_resolved} or defined wantarray or
355 16 ▶ croak "Expected 'on_resolved' or to return a Future";
Branch: 1 branch
BranchTrueFalseTotal
$args{"on_resolved"} or defined wantarray or croak("Expected 'on_resolved' or to return a Future") 0 16 16
Condition66%2/3
$args{"on_resolved"} or defined wantarray
l!l&&r!l&&!r
4120
MC/DC0%0/2
$args{"on_resolved"} or defined wantarray
$args{"on_resolved"} defined wantarray
Truth table66%2/3
A or B
A= $args{"on_resolved"}B= defined wantarray
ABresult
1X1
011
000
356  
357 $args{on_error} or defined wantarray or
358 16 ▶ croak "Expected 'on_error' or to return a Future";
Branch: 1 branch
BranchTrueFalseTotal
$args{"on_error"} or defined wantarray or croak("Expected 'on_error' or to return a Future") 0 16 16
Condition66%2/3
$args{"on_error"} or defined wantarray
l!l&&r!l&&!r
4120
MC/DC0%0/2
$args{"on_error"} or defined wantarray
$args{"on_error"} defined wantarray
Truth table66%2/3
A or B
A= $args{"on_error"}B= defined wantarray
ABresult
1X1
011
000
359  
360 16 ▶ my $host = $args{host} || "";
Condition100%2/2
$args{'host'} || ''
l!l
142
MC/DC100%1/1
$args{'host'} || ''
$args{'host'}
Truth table100%2/2
A
A= $args{'host'}
Aresult
11
00
361 16 ▶ my $service = $args{service} // "";
Condition100%2/2
$args{"service"} // ""
l!l
142
MC/DC100%1/1
$args{"service"} // ""
$args{"service"}
Truth table100%2/2
A
A= $args{"service"}
Aresult
11
00
362 16 ▶ my $flags = $args{flags} || 0;
Condition50%1/2
$args{'flags'} || 0
l!l
016
MC/DC0%0/1
$args{'flags'} || 0
$args{'flags'}
Truth table50%1/2
A
A= $args{'flags'}
Aresult
11
00
363  
364 16 ▶ $flags |= AI_PASSIVE if $args{passive};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"passive"} 3 13 16
365  
366 16 ▶ $args{family} = IO::Async::OS->getfamilybyname( $args{family} ) if defined $args{family};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"family"} 6 10 16
367 16 ▶ $args{socktype} = IO::Async::OS->getsocktypebyname( $args{socktype} ) if defined $args{socktype};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"socktype"} 16 0 16
368  
369 # Clear any other existing but undefined hints
370 16 ▶ defined $args{$_} or delete $args{$_} for keys %args;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{$_} or delete $args{$_} 1 61 62
371  
372 # It's likely this will succeed with AI_NUMERICHOST if host contains only
373 # [\d.] (IPv4) or [[:xdigit:]:] (IPv6)
374 # Technically we should pass AI_NUMERICSERV but not all platforms support
375 # it, but since we're checking service contains only \d we should be fine.
376  
377 # These address tests don't have to be perfect as if it fails we'll get
378 # EAI_NONAME and just try it asynchronously anyway
379 16 ▶ if( ( $host =~ m/^[\d.]+$/ or $host =~ m/^[[:xdigit:]:]$/ or $host eq "" ) and
Branch: 1 branch
BranchTrueFalseTotal
if ($host =~ /^[\d.]+$/u || $host =~ /^[[:xdigit:]:]$/u || $host eq "" and $service =~ /^\d*$/u) 12 4 16
Condition77%7/9
$host =~ /^[\d.]+$/u || $host =~ /^[[:xdigit:]:]$/u || $host eq "" and $service =~ /^\d*$/u
!ll&&!rl&&r
4012
$host =~ /^[\d.]+$/u or $host =~ /^[[:xdigit:]:]$/u or $host eq ""
l!l&&r!l&&!r
1024
$host =~ /^[\d.]+$/u or $host =~ /^[[:xdigit:]:]$/u
l!l&&r!l&&!r
1006
MC/DC50%2/4
$host =~ /^[\d.]+$/u || $host =~ /^[[:xdigit:]:]$/u || $host eq "" and $service =~ /^\d*$/u
$host =~ /^[\d.]+$/u $host =~ /^[[:xdigit:]:]$/u $host eq "" $service =~ /^\d*$/u
Truth table42%3/7
A or B or C and D
A= $host =~ /^[\d.]+$/uB= $host =~ /^[[:xdigit:]:]$/uC= $host eq ""D= $service =~ /^\d*$/u
ABCDresult
000X0
1XX00
01X00
00100
1XX11
01X11
00111
380 $service =~ m/^\d*$/ ) {
381  
382 12 my ( $err, @results ) = Socket::getaddrinfo( $host, $service,
383 { %args, flags => $flags | AI_NUMERICHOST }
384 );
385  
386 12 ▶ if( !$err ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $err) { } 12 0 12
elsif ($err == -2) { } 0 0 0
387 12 my $future = $self->loop->new_future->done( @results );
388 12 ▶ $future->on_done( $args{on_resolved} ) if $args{on_resolved};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"on_resolved"} 3 9 12
389 12 return $future;
390 }
391 elsif( $err == EAI_NONAME ) {
392 # fallthrough to async case
393 }
394 else {
395 0 my $future = $self->loop->new_future->fail( $err, resolve => getaddrinfo => $err+0 );
396 0 ▶ $future->on_fail( $args{on_error} ) if $args{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"on_error"} 0 0 0
397 0 return $future;
398 }
399 }
400  
401 my $future = $self->resolve(
402 type => "getaddrinfo",
403 data => [
404 host => $host,
405 service => $service,
406 flags => $flags,
407 12 ▶ map { exists $args{$_} ? ( $_ => $args{$_} ) : () } qw( family socktype protocol ),
Branch: 1 branch
BranchTrueFalseTotal
exists $args{$_} ? : 7 5 12
408 ],
409 timeout => $args{timeout},
410 4 );
411  
412 4 ▶ $future->on_done( $args{on_resolved} ) if $args{on_resolved};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"on_resolved"} 1 3 4
413 4 ▶ $future->on_fail( $args{on_error} ) if $args{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"on_error"} 1 3 4
414  
415 4 ▶ return $future if defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if defined wantarray 3 1 4
416  
417 # Caller is not going to keep hold of the Future, so we have to ensure it
418 # stays alive somehow
419 1 ▶ $self->adopt_future( $future->else( sub { Future->done } ) );
Subroutine __ANON__: not called CC=1 SCAR=1.2
420 }
421  
422 =head2 getnameinfo
423  
424 ( $host, $service ) = await $resolver->getnameinfo( %args );
425  
426 A shortcut wrapper around the C<getnameinfo> resolver, taking its arguments in
427 a more convenient form.
428  
429 =over 8
430  
431 =item addr => STRING
432  
433 The packed socket address to look up.
434  
435 =item flags => INT
436  
437 Flags to control the C<getnameinfo(3)> function. See the C<NI_*> constants in
438 L<Socket>'s C<getnameinfo> for more detail.
439  
440 =item numerichost => BOOL
441  
442 =item numericserv => BOOL
443  
444 =item dgram => BOOL
445  
446 If true, set the C<NI_NUMERICHOST>, C<NI_NUMERICSERV> or C<NI_DGRAM> flags.
447  
448 =item numeric => BOOL
449  
450 If true, sets both C<NI_NUMERICHOST> and C<NI_NUMERICSERV> flags.
451  
452 =item timeout => NUMBER
453  
454 Time in seconds after which to abort the lookup with a C<Timed out> exception
455  
456 =back
457  
458 On failure, the detail field will give the error number, which should match
459 one of the C<Socket::EAI_*> constants.
460  
461 ->fail( $message, resolve => getnameinfo => $eai_errno )
462  
463 As a specific optimisation, this method will try to perform a lookup of
464 numeric values synchronously, rather than asynchronously, if both the
465 C<NI_NUMERICHOST> and C<NI_NUMERICSERV> flags are given.
466  
467 =head2 getnameinfo (void)
468  
469 $resolver->getnameinfo( %args );
470  
471 When not returning a future, additional parameters can be given containing the
472 continuations to invoke on success or failure:
473  
474 =over 8
475  
476 =item on_resolved => CODE
477  
478 Callback which is invoked after a successful lookup.
479  
480 $on_resolved->( $host, $service );
481  
482 =item on_error => CODE
483  
484 Callback which is invoked after a failed lookup, including for a timeout.
485  
486 $on_error->( $exception );
487  
488 =back
489  
490 =cut
491  
492 sub getnameinfo
493 {
494 5 ▶ my $self = shift;
Subroutine getnameinfo: called CC=17 SCAR=30.7
Pod documented
495 5 my %args = @_;
496  
497 $args{on_resolved} or defined wantarray or
498 5 ▶ croak "Expected 'on_resolved' or to return a Future";
Branch: 1 branch
BranchTrueFalseTotal
$args{"on_resolved"} or defined wantarray or croak("Expected 'on_resolved' or to return a Future") 0 5 5
Condition66%2/3
$args{"on_resolved"} or defined wantarray
l!l&&r!l&&!r
230
MC/DC0%0/2
$args{"on_resolved"} or defined wantarray
$args{"on_resolved"} defined wantarray
Truth table66%2/3
A or B
A= $args{"on_resolved"}B= defined wantarray
ABresult
1X1
011
000
499  
500 $args{on_error} or defined wantarray or
501 5 ▶ croak "Expected 'on_error' or to return a Future";
Branch: 1 branch
BranchTrueFalseTotal
$args{"on_error"} or defined wantarray or croak("Expected 'on_error' or to return a Future") 0 5 5
Condition66%2/3
$args{"on_error"} or defined wantarray
l!l&&r!l&&!r
230
MC/DC0%0/2
$args{"on_error"} or defined wantarray
$args{"on_error"} defined wantarray
Truth table66%2/3
A or B
A= $args{"on_error"}B= defined wantarray
ABresult
1X1
011
000
502  
503 5 ▶ my $flags = $args{flags} || 0;
Condition50%1/2
$args{'flags'} || 0
l!l
05
MC/DC0%0/1
$args{'flags'} || 0
$args{'flags'}
Truth table50%1/2
A
A= $args{'flags'}
Aresult
11
00
504  
505 5 ▶ $flags |= NI_NUMERICHOST if $args{numerichost};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"numerichost"} 0 5 5
506 5 ▶ $flags |= NI_NUMERICSERV if $args{numericserv};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"numericserv"} 0 5 5
507 5 ▶ $flags |= NI_DGRAM if $args{dgram};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"dgram"} 0 5 5
508  
509 5 ▶ $flags |= NI_NUMERICHOST|NI_NUMERICSERV if $args{numeric};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"numeric"} 2 3 5
510  
511 5 ▶ if( $flags & (NI_NUMERICHOST|NI_NUMERICSERV) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flags & 3) 2 3 5
512 # This is a numeric-only lookup that can be done synchronously
513 2 my ( $err, $host, $service ) = Socket::getnameinfo( $args{addr}, $flags );
514  
515 2 ▶ if( $err ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) { } 0 2 2
516 0 my $future = $self->loop->new_future->fail( $err, resolve => getnameinfo => $err+0 );
517 0 ▶ $future->on_fail( $args{on_error} ) if $args{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"on_error"} 0 0 0
518 0 return $future;
519 }
520 else {
521 2 my $future = $self->loop->new_future->done( $host, $service );
522 2 ▶ $future->on_done( $args{on_resolved} ) if $args{on_resolved};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"on_resolved"} 1 1 2
523 2 return $future;
524 }
525 }
526  
527 my $future = $self->resolve(
528 type => "getnameinfo",
529 data => [ $args{addr}, $flags ],
530 timeout => $args{timeout},
531 )->transform(
532 3 ▶ done => sub { @{ $_[0] } }, # unpack the ARRAY ref
Subroutine __ANON__: called CC=1 SCAR=0.0
533 3 );
534  
535 3 ▶ $future->on_done( $args{on_resolved} ) if $args{on_resolved};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"on_resolved"} 1 2 3
536 3 ▶ $future->on_fail( $args{on_error} ) if $args{on_error};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"on_error"} 1 2 3
537  
538 3 ▶ return $future if defined wantarray;
Branch: 1 branch
BranchTrueFalseTotal
if defined wantarray 2 1 3
539  
540 # Caller is not going to keep hold of the Future, so we have to ensure it
541 # stays alive somehow
542 1 ▶ $self->adopt_future( $future->else( sub { Future->done } ) );
Subroutine __ANON__: not called CC=1 SCAR=1.2
543 }
544  
545 =head1 FUNCTIONS
546  
547 =cut
548  
549 =head2 register_resolver
550  
551 register_resolver( $name, $code );
552  
553 Registers a new named resolver function that can be called by the C<resolve>
554 method. All named resolvers must be registered before the object is
555 constructed.
556  
557 =over 8
558  
559 =item $name
560  
561 The name of the resolver function; must be a plain string. This name will be
562 used by the C<type> argument to the C<resolve> method, to identify it.
563  
564 =item $code
565  
566 A CODE reference to the resolver function body. It will be called in list
567 context, being passed the list of arguments given in the C<data> argument to
568 the C<resolve> method. The returned list will be passed to the
569 C<on_resolved> callback. If the code throws an exception at call time, it will
570 be passed to the C<on_error> continuation. If it returns normally, the list of
571 values it returns will be passed to C<on_resolved>.
572  
573 =back
574  
575 =cut
576  
577 # Plain function, not a method
578 sub register_resolver
579 {
580 105 ▶ my ( $name, $code ) = @_;
Subroutine register_resolver: called CC=3 SCAR=11.4
Pod documented
581  
582 105 ▶ croak "Cannot register new resolver methods once the resolver has been started" if $started;
Branch: 1 branch
BranchTrueFalseTotal
if $started 0 105 105
583  
584 105 ▶ croak "Already have a resolver method called '$name'" if exists $METHODS{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $METHODS{$name} 0 105 105
585 105 $METHODS{$name} = $code;
586 }
587  
588 =head1 BUILT-IN RESOLVERS
589  
590 The following resolver names are implemented by the same-named perl function,
591 taking and returning a list of values exactly as the perl function does:
592  
593 getpwnam getpwuid
594 getgrnam getgrgid
595 getservbyname getservbyport
596 gethostbyname gethostbyaddr
597 getnetbyname getnetbyaddr
598 getprotobyname getprotobynumber
599  
600 =cut
601  
602 # Now register the inbuilt methods
603  
604 0 ▶register_resolver getpwnam => sub { my @r = getpwnam( $_[0] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = getpwnam $_[0] or die "$!\n" 0 0 0
605 0 ▶register_resolver getpwuid => sub { my @r = getpwuid( $_[0] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = getpwuid $_[0] or die "$!\n" 0 0 0
606  
607 0 ▶register_resolver getgrnam => sub { my @r = getgrnam( $_[0] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = getgrnam $_[0] or die "$!\n" 0 0 0
608 0 ▶register_resolver getgrgid => sub { my @r = getgrgid( $_[0] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = getgrgid $_[0] or die "$!\n" 0 0 0
609  
610 0 ▶register_resolver getservbyname => sub { my @r = getservbyname( $_[0], $_[1] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = getservbyname($_[0], $_[1]) or die "$!\n" 0 0 0
611 0 ▶register_resolver getservbyport => sub { my @r = getservbyport( $_[0], $_[1] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = getservbyport($_[0], $_[1]) or die "$!\n" 0 0 0
612  
613 0 ▶register_resolver gethostbyname => sub { my @r = gethostbyname( $_[0] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = gethostbyname $_[0] or die "$!\n" 0 0 0
614 0 ▶register_resolver gethostbyaddr => sub { my @r = gethostbyaddr( $_[0], $_[1] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = gethostbyaddr($_[0], $_[1]) or die "$!\n" 0 0 0
615  
616 0 ▶register_resolver getnetbyname => sub { my @r = getnetbyname( $_[0] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = getnetbyname $_[0] or die "$!\n" 0 0 0
617 0 ▶register_resolver getnetbyaddr => sub { my @r = getnetbyaddr( $_[0], $_[1] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = getnetbyaddr($_[0], $_[1]) or die "$!\n" 0 0 0
618  
619 0 ▶register_resolver getprotobyname => sub { my @r = getprotobyname( $_[0] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = getprotobyname $_[0] or die "$!\n" 0 0 0
620 0 ▶register_resolver getprotobynumber => sub { my @r = getprotobynumber( $_[0] ) or die "$!\n"; @r };
Subroutine __ANON__: not called CC=2 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
my(@r) = getprotobynumber($_[0]) or die "$!\n" 0 0 0
621  
622 =pod
623  
624 The following three resolver names are implemented using the L<Socket> module.
625  
626 getaddrinfo
627 getaddrinfo_array
628 getnameinfo
629  
630 The C<getaddrinfo> resolver takes arguments in a hash of name/value pairs and
631 returns a list of hash structures, as the C<Socket::getaddrinfo> function
632 does. For neatness it takes all its arguments as named values; taking the host
633 and service names from arguments called C<host> and C<service> respectively;
634 all the remaining arguments are passed into the hints hash. This name is also
635 aliased as simply C<getaddrinfo>.
636  
637 The C<getaddrinfo_array> resolver behaves more like the C<Socket6> version of
638 the function. It takes hints in a flat list, and mangles the result of the
639 function, so that the returned value is more useful to the caller. It splits
640 up the list of 5-tuples into a list of ARRAY refs, where each referenced array
641 contains one of the tuples of 5 values.
642  
643 As an extra convenience to the caller, both resolvers will also accept plain
644 string names for the C<family> argument, converting C<inet> and possibly
645 C<inet6> into the appropriate C<AF_*> value, and for the C<socktype> argument,
646 converting C<stream>, C<dgram> or C<raw> into the appropriate C<SOCK_*> value.
647  
648 The C<getnameinfo> resolver returns its result in the same form as C<Socket>.
649  
650 Because this module simply uses the system's C<getaddrinfo> resolver, it will
651 be fully IPv6-aware if the underlying platform's resolver is. This allows
652 programs to be fully IPv6-capable.
653  
654 =cut
655  
656 register_resolver getaddrinfo => sub {
657 0 ▶ my %args = @_;
Subroutine __ANON__: not called CC=6 SCAR=37.4
658  
659 0 my $host = delete $args{host};
660 0 my $service = delete $args{service};
661  
662 0 ▶ $args{family} = IO::Async::OS->getfamilybyname( $args{family} ) if defined $args{family};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"family"} 0 0 0
663 0 ▶ $args{socktype} = IO::Async::OS->getsocktypebyname( $args{socktype} ) if defined $args{socktype};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"socktype"} 0 0 0
664  
665 # Clear any other existing but undefined hints
666 0 ▶ defined $args{$_} or delete $args{$_} for keys %args;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{$_} or delete $args{$_} 0 0 0
667  
668 0 my ( $err, @addrs ) = Socket::getaddrinfo( $host, $service, \%args );
669  
670 0 ▶ die [ "$err", $err+0 ] if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
671  
672 0 return @addrs;
673 7 };
674  
675 register_resolver getaddrinfo_array => sub {
676 0 ▶ my ( $host, $service, $family, $socktype, $protocol, $flags ) = @_;
Subroutine __ANON__: not called CC=6 SCAR=37.4
677  
678 0 $family = IO::Async::OS->getfamilybyname( $family );
679 0 $socktype = IO::Async::OS->getsocktypebyname( $socktype );
680  
681 0 my %hints;
682 0 ▶ $hints{family} = $family if defined $family;
Branch: 1 branch
BranchTrueFalseTotal
if defined $family 0 0 0
683 0 ▶ $hints{socktype} = $socktype if defined $socktype;
Branch: 1 branch
BranchTrueFalseTotal
if defined $socktype 0 0 0
684 0 ▶ $hints{protocol} = $protocol if defined $protocol;
Branch: 1 branch
BranchTrueFalseTotal
if defined $protocol 0 0 0
685 0 ▶ $hints{flags} = $flags if defined $flags;
Branch: 1 branch
BranchTrueFalseTotal
if defined $flags 0 0 0
686  
687 0 my ( $err, @addrs ) = Socket::getaddrinfo( $host, $service, \%hints );
688  
689 0 ▶ die [ "$err", $err+0 ] if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
690  
691 # Convert the @addrs list into a list of ARRAY refs of 5 values each
692 return map {
693 0 [ $_->{family}, $_->{socktype}, $_->{protocol}, $_->{addr}, $_->{canonname} ]
694 } @addrs;
695 7 };
696  
697 register_resolver getnameinfo => sub {
698 0 ▶ my ( $addr, $flags ) = @_;
Subroutine __ANON__: not called CC=3 SCAR=24.8
699  
700 0 ▶ my ( $err, $host, $service ) = Socket::getnameinfo( $addr, $flags || 0 );
Condition0%0/2
$flags || 0
l!l
00
MC/DC0%0/1
$flags || 0
$flags
Truth table0%0/2
A
A= $flags
Aresult
11
00
701  
702 0 ▶ die [ "$err", $err+0 ] if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 0 0
703  
704 0 return [ $host, $service ];
705 7 };
706  
707 =head1 EXAMPLES
708  
709 The following somewhat contrieved example shows how to implement a new
710 resolver function. This example just uses in-memory data, but a real function
711 would likely make calls to OS functions to provide an answer. In traditional
712 Unix style, a pair of functions are provided that each look up the entity by
713 either type of key, where both functions return the same type of list. This is
714 purely a convention, and is in no way required or enforced by the
715 L<IO::Async::Resolver> itself.
716  
717 @numbers = qw( zero one two three four
718 five six seven eight nine );
719  
720 register_resolver getnumberbyindex => sub {
721 my ( $index ) = @_;
722 die "Bad index $index" unless $index >= 0 and $index < @numbers;
723 return ( $index, $numbers[$index] );
724 };
725  
726 register_resolver getnumberbyname => sub {
727 my ( $name ) = @_;
728 foreach my $index ( 0 .. $#numbers ) {
729 return ( $index, $name ) if $numbers[$index] eq $name;
730 }
731 die "Bad name $name";
732 };
733  
734 =head1 AUTHOR
735  
736 Paul Evans <leonerd@leonerd.org.uk>
737  
738 =cut
739  
740 7 0x55AA;
« blib/lib/IO/Async/Loop/Poll.pm ↑ Summary blib/lib/IO/Async/Stream.pm »