MongoDB/_URI.pm

filter: Statementstmt 75.8% 245 / 323 Branchbran 67.0% 110 / 164 Conditioncond 63.5% 47 / 74 MC/DCmcdc 53.4% 23 / 43 Subroutinesub 89.4% 34 / 38 Podpod 0.0% 0 / 2 totaltotal 71.2% 459 / 644 CC 117 SCAR 43.5
CC
117
Cov
72%
_fetch_dns_seedlist
462.0
check_for_changes
72.0
_parse_options
31.1
CRAP 77.7
« MongoDB/ClientSession.pm ↑ Summary MongoDB/Role/_OpReplyParser.pm »
1 # Copyright 2014 - present MongoDB, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14  
15 64 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 64 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 package MongoDB::_URI;
18  
19 64 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 64 our $VERSION = 'v2.2.2';
21  
22 64 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 64 ▶use MongoDB::Error;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 64 ▶use Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
25 64 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
26 64 ▶use MongoDB::_Constants qw( RESCAN_SRV_FREQUENCY_SEC );
Subroutine BEGIN: called CC=1 SCAR=0.0
27 64 ▶use Types::Standard qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
28 Any
29 ArrayRef
30 HashRef
31 Str
32 Int
33 Num
34 64 );
35 64 ▶use namespace::clean -except => 'meta';
Subroutine BEGIN: called CC=1 SCAR=0.0
36 64 ▶use Scalar::Util qw/looks_like_number/;
Subroutine BEGIN: called CC=1 SCAR=0.0
37  
38 64 my $uri_re =
39 qr{
40 mongodb(?:\+srv|)://
41 (?: ([^:]*) (?: : ([^@]*) )? @ )? # [username(:password)?@]
42 ([^/?]*) # host1[:port1][,host2[:port2],...[,hostN[:portN]]]
43 (?:
44 / ([^?]*) # /[database]
45 (?: [?] (.*) )? # [?options]
46 )?
47 }x;
48  
49 64 my %options_with_list_type = map { lc($_) => 1 } qw(
50 readPreferenceTags
51 );
52  
53 64 has uri => (
54 is => 'ro',
55 isa => Str,
56 required => 1,
57 );
58  
59 64 has username => (
60 is => 'ro',
61 isa => Any,
62 writer => '_set_username',
63 );
64  
65 64 has password => (
66 is => 'ro',
67 isa => Any,
68 writer => '_set_password',
69 );
70  
71 64 has db_name => (
72 is => 'ro',
73 isa => Str,
74 writer => '_set_db_name',
75 default => '',
76 );
77  
78 has options => (
79 is => 'ro',
80 isa => HashRef,
81 writer => '_set_options',
82 562 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
83 64 );
84  
85 has hostids => (
86 is => 'ro',
87 isa => ArrayRef,
88 writer => '_set_hostids',
89 562 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
90 64 );
91  
92 64 has valid_options => (
93 is => 'lazy',
94 isa => HashRef,
95 );
96  
97 64 has expires => (
98 is => 'ro',
99 isa => Num,
100 writer => '_set_expires',
101 );
102  
103 206 ▶sub _build_valid_options {
Subroutine _build_valid_options: called CC=1 SCAR=0.0
104 206 my $self = shift;
105 return {
106 7210 map { lc($_) => 1 } qw(
107 appName
108 authMechanism
109 authMechanismProperties
110 authSource
111 compressors
112 connect
113 connectTimeoutMS
114 heartbeatFrequencyMS
115 journal
116 localThresholdMS
117 maxStalenessSeconds
118 maxTimeMS
119 readConcernLevel
120 readPreference
121 readPreferenceTags
122 replicaSet
123 serverSelectionTimeoutMS
124 serverSelectionTryOnce
125 socketCheckIntervalMS
126 socketTimeoutMS
127 tlsCAFile
128 tlsCertificateKeyFile
129 tlsCertificateKeyFilePassword
130 w
131 wTimeoutMS
132 zlibCompressionLevel
133 206 ), keys %{ $self->_valid_str_to_bool_options }
134 };
135 }
136  
137 64 has valid_srv_options => (
138 is => 'lazy',
139 isa => HashRef,
140 );
141  
142 0 ▶sub _build_valid_srv_options {
Subroutine _build_valid_srv_options: not called CC=1 SCAR=6.9
143 return {
144 0 map { lc($_) => 1 } qw(
145 authSource
146 replicaSet
147 )
148 };
149 }
150  
151 64 has _valid_str_to_bool_options => (
152 is => 'lazy',
153 isa => HashRef,
154 builder => '_build_valid_str_to_bool_options',
155 );
156  
157 206 ▶sub _build_valid_str_to_bool_options {
Subroutine _build_valid_str_to_bool_options: called CC=1 SCAR=0.0
158 return {
159 206 map { lc($_) => 1 } qw(
160 journal
161 retryReads
162 retryWrites
163 serverselectiontryonce
164 ssl
165 tls
166 tlsAllowInvalidCertificates
167 tlsAllowInvalidHostnames
168 tlsInsecure
169 )
170 };
171 }
172  
173 64 has _extra_options_validation => (
174 is => 'lazy',
175 isa => HashRef,
176 builder => '_build_extra_options_validation',
177 );
178  
179 151 ▶sub _build_extra_options_validation {
Subroutine _build_extra_options_validation: called CC=1 SCAR=0.0
180 return {
181 26 ▶ _PositiveInt => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
182 26 my $v = shift;
183 26 ▶ Int->($v) && $v >= 0;
Branch: 1 branch
BranchTrueFalseTotal
&Int()->($v) and $v >= 0 21 0 21
184 },
185 wtimeoutms => '_PositiveInt',
186 connecttimeoutms => '_PositiveInt',
187 localthresholdms => '_PositiveInt',
188 serverselectiontimeoutms => '_PositiveInt',
189 sockettimeoutms => '_PositiveInt',
190 19 ▶ w => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
191 19 my $v = shift;
192 19 ▶ if (looks_like_number($v)) {
Branch: 1 branch
BranchTrueFalseTotal
if (&looks_like_number($v)) 15 4 19
193 15 return $v >= 0;
194 }
195 4 return 1; # or any string
196 },
197 4 ▶ zlibcompressionlevel => sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
198 4 my $v = shift;
199 4 ▶ Int->($v) && $v >= -1 && $v <= 9;
Branch: 1 branch
BranchTrueFalseTotal
&Int()->($v) and $v >= -1 and $v <= 9 2 1 3
Condition66%2/3
&Int()->($v) and $v >= -1
!ll&&!rl&&r
012
MC/DC50%1/2
&Int()->($v) and $v >= -1
&Int()->($v) $v >= -1
Truth table66%2/3
A and B
A= &Int()->($v)B= $v >= -1
ABresult
0X0
100
111
200 },
201 4 ▶ heartbeatfrequencyms => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
202 4 my $v = shift;
203 4 ▶ Int->($v) && $v >= 500;
Branch: 1 branch
BranchTrueFalseTotal
&Int()->($v) and $v >= 500 3 0 3
204 },
205 11 ▶ maxstalenessseconds => sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
206 11 my $v = shift;
207 11 ▶ Int->($v) && ( $v == 1 || $v == -1 || $v >= 90 );
Branch: 1 branch
BranchTrueFalseTotal
&Int()->($v) and $v == 1 || $v == -1 || $v >= 90 10 0 10
Condition88%8/9
&Int()->($v) && ($v == 1 || $v == -1 || $v >= 90)
!ll&&!rl&&r
019
$v == 1 or $v == -1 or $v >= 90
l!l&&r!l&&!r
451
$v == 1 or $v == -1
l!l&&r!l&&!r
136
MC/DC75%3/4
&Int()->($v) && ($v == 1 || $v == -1 || $v >= 90)
&Int()->($v) $v == 1 $v == -1 $v >= 90
Truth table80%4/5
A && B or C or D
A= &Int()->($v)B= $v == 1C= $v == -1D= $v >= 90
ABCDresult
0XXX0
10000
11XX1
101X1
10011
208 },
209 151 };
210 }
211  
212 1485 ▶sub _unescape_all {
Subroutine _unescape_all: called CC=3 SCAR=11.0
213 1485 my $str = shift;
214 1485 ▶ return '' unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 0 1485 1485
215 1485 ▶ if ( $str =~ s/%([0-9a-f]{2})/chr(hex($1))/ieg ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($str =~ s/%([0-9a-f]{2})/chr hex $1;/egi) 70 1415 1485
216 70 $str = Encode::decode('UTF-8', $str);
217 }
218 1485 return $str;
219 }
220  
221 9 ▶sub _parse_doc {
Subroutine _parse_doc: called CC=4 SCAR=13.9
222 9 my ($name, $string) = @_;
223 9 my $set = {};
224 9 for my $tag ( split /,/, $string ) {
225 12 ▶ if ( $tag =~ /\S/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tag =~ /\S/) 12 0 12
226 12 my @kv = map { my $s = $_; $s =~ s{^\s*}{}; $s =~ s{\s*$}{}; $s } split /:/, $tag, 2;
227 12 ▶ if ( @kv != 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@kv != 2) 1 11 12
228 1 warn "in option '$name', '$tag' is not a key:value pair\n";
229 return
230 1 }
231 11 $set->{$kv[0]} = $kv[1];
232 }
233 }
234 8 return $set;
235 }
236  
237 208 ▶sub _parse_options {
Subroutine _parse_options: called CC=31 SCAR=34.4
238 208 my ( $self, $valid, $result, $txt_record ) = @_;
239  
240 208 my %parsed;
241 208 for my $opt ( split '&', $result->{options} ) {
242 278 my @kv = split '=', $opt, -1;
243 278 ▶ MongoDB::UsageError->throw("expected key value pair") unless @kv == 2;
Branch: 1 branch
BranchTrueFalseTotal
unless @kv == 2 6 272 278
244 272 my ( $k, $v ) = map { _unescape_all($_) } @kv;
245 # connection string spec calls for case normalization
246 272 ( my $lc_k = $k ) =~ tr[A-Z][a-z];
247 272 ▶ if ( !$valid->{$lc_k} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($valid->{$lc_k}) 7 265 272
248 7 ▶ if ( $txt_record ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($txt_record) { } 0 7 7
249 0 MongoDB::Error->throw("Unsupported option '$k' in URI $self for TXT record $txt_record\n");
250 } else {
251 7 warn "Unsupported option '$k' in URI $self\n";
252 }
253 7 next;
254 }
255 265 ▶ if ( exists $parsed{$lc_k} && !exists $options_with_list_type{$lc_k} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $parsed{$lc_k} and not exists $options_with_list_type{$lc_k}) 2 263 265
Condition100%3/3
exists $parsed{$lc_k} and not exists $options_with_list_type{$lc_k}
!ll&&!rl&&r
26122
MC/DC100%2/2
exists $parsed{$lc_k} and not exists $options_with_list_type{$lc_k}
exists $parsed{$lc_k} not exists $options_with_list_type{$lc_k}
Truth table100%3/3
A and not(B)
A= exists $parsed{$lc_k}B= not exists $options_with_list_type{$lc_k}
ABresult
0X0
100
111
256 2 warn "Multiple options were found for the same value '$lc_k'. The first occurrence will be used\n";
257 2 next;
258 }
259 263 ▶ if ( $lc_k eq 'authmechanismproperties' ) {
Branch: 6 branches
BranchTrueFalseTotal
if ($lc_k eq 'authmechanismproperties') { } 3 260 263
elsif ($lc_k eq 'compressors') { } 5 255 260
elsif ($lc_k eq 'authsource') { } 14 241 255
elsif ($lc_k eq 'readpreferencetags') { } 6 235 241
elsif ($self->_valid_str_to_bool_options->{$lc_k}) { } 63 172 235
elsif (my $opt_validation = $self->_extra_options_validation->{$lc_k}) { } 64 108 172
260 3 my $temp = _parse_doc( $k, $v );
261 3 ▶ if ( defined $temp ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $temp) 3 0 3
262 3 $parsed{$lc_k} = $temp;
263 3 ▶ if ( exists $parsed{$lc_k}{CANONICALIZE_HOST_NAME} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $parsed{$lc_k}{"CANONICALIZE_HOST_NAME"}) 2 1 3
264 2 my $temp = __str_to_bool( 'CANONICALIZE_HOST_NAME', $parsed{$lc_k}{CANONICALIZE_HOST_NAME} );
265 2 ▶ if ( defined $temp ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $temp) 2 0 2
266 2 $parsed{$lc_k}{CANONICALIZE_HOST_NAME} = $temp;
267 }
268 }
269 }
270 }
271 elsif ( $lc_k eq 'compressors' ) {
272 5 my @compressors = split /,/, $v, -1;
273 5 my $valid_compressors = {
274 snappy => 1,
275 zlib => 1,
276 zstd => 1
277 };
278 5 for my $compressor ( @compressors ) {
279 warn("Unsupported compressor $compressor\n")
280 6 ▶ unless $valid_compressors->{$compressor};
Branch: 1 branch
BranchTrueFalseTotal
unless $valid_compressors->{$compressor} 0 6 6
281 }
282 5 $parsed{$lc_k} = [ @compressors ];
283 }
284 elsif ( $lc_k eq 'authsource' ) {
285 14 $parsed{$lc_k} = $v;
286 }
287 elsif ( $lc_k eq 'readpreferencetags' ) {
288 6 ▶ $parsed{$lc_k} ||= [];
Condition100%2/2
$parsed{$lc_k} ||= []
l!l
24
MC/DC100%1/1
$parsed{$lc_k} ||= []
$parsed{$lc_k}
Truth table100%2/2
A
A= $parsed{$lc_k}
Aresult
11
00
289 6 my $temp = _parse_doc( $k, $v );
290 6 ▶ if ( defined $temp ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $temp) 5 1 6
291 5 push @{$parsed{$lc_k}}, $temp;
292 }
293 }
294 elsif ( $self->_valid_str_to_bool_options->{ $lc_k } ) {
295 63 my $temp = __str_to_bool( $k, $v );
296 63 ▶ if ( defined $temp ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $temp) 56 7 63
297 56 $parsed{$lc_k} = $temp
298 }
299 }
300 elsif ( my $opt_validation = $self->_extra_options_validation->{ $lc_k } ) {
301 64 ▶ unless (ref $opt_validation eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $opt_validation eq "CODE") 26 38 64
302 26 $opt_validation = $self->_extra_options_validation->{ $opt_validation };
303 }
304 64 my $valid = eval { $opt_validation->($v) };
305 64 my $err = "$@";
306 64 ▶ if ( ! $valid ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $valid) { } 20 44 64
307 20 warn("Unsupported URI value '$k' = '$v': $err");
308 }
309 else {
310 44 $parsed{$lc_k} = $v;
311 }
312 }
313 else {
314 108 $parsed{$lc_k} = $v;
315 }
316 }
317 202 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (exists $parsed{"tlsinsecure"} and exists $parsed{"tlsallowinvalidcertificates"} || exists $parsed{"tlsallowinvalidhostnames"}) 8 194 202
Condition100%6/6
exists $parsed{"tlsinsecure"} and exists $parsed{"tlsallowinvalidcertificates"} || exists $parsed{"tlsallowinvalidhostnames"}
!ll&&!rl&&r
19318
exists $parsed{"tlsallowinvalidcertificates"} or exists $parsed{"tlsallowinvalidhostnames"}
l!l&&r!l&&!r
441
MC/DC100%3/3
exists $parsed{"tlsinsecure"} and exists $parsed{"tlsallowinvalidcertificates"} || exists $parsed{"tlsallowinvalidhostnames"}
exists $parsed{"tlsinsecure"} exists $parsed{"tlsallowinvalidcertificates"} exists $parsed{"tlsallowinvalidhostnames"}
Truth table100%4/4
A and B or C
A= exists $parsed{"tlsinsecure"}B= exists $parsed{"tlsallowinvalidcertificates"}C= exists $parsed{"tlsallowinvalidhostnames"}
ABCresult
0XX0
1000
11X1
1011
318 exists $parsed{tlsinsecure}
319 && ( exists $parsed{tlsallowinvalidcertificates}
320 || exists $parsed{tlsallowinvalidhostnames} )
321 )
322 {
323 8 MongoDB::Error->throw('tlsInsecure conflicts with other options');
324 }
325 # If both exist, they must be identical.
326 194 ▶ if ( exists( $parsed{tls} )
Branch: 1 branch
BranchTrueFalseTotal
if (exists $parsed{"tls"} and exists $parsed{"ssl"} and $parsed{"tls"} != $parsed{"ssl"}) 4 190 194
Condition100%6/6
exists $parsed{"tls"} and exists $parsed{"ssl"} and $parsed{"tls"} != $parsed{"ssl"}
!ll&&!rl&&r
18554
exists $parsed{"tls"} and exists $parsed{"ssl"}
!ll&&!rl&&r
18419
MC/DC100%3/3
exists $parsed{"tls"} and exists $parsed{"ssl"} and $parsed{"tls"} != $parsed{"ssl"}
exists $parsed{"tls"} exists $parsed{"ssl"} $parsed{"tls"} != $parsed{"ssl"}
Truth table100%4/4
A and B and C
A= exists $parsed{"tls"}B= exists $parsed{"ssl"}C= $parsed{"tls"} != $parsed{"ssl"}
ABCresult
0XX0
10X0
1100
1111
327 && exists( $parsed{ssl} )
328 && $parsed{tls} != $parsed{ssl} )
329 {
330 4 MongoDB::Error->throw('tls and ssl must have the same value');
331 }
332 # If either exists, set them both.
333 190 ▶ if ( exists $parsed{tls} ) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $parsed{'tls'}) { } 6 184 190
elsif (exists $parsed{'ssl'}) { } 4 180 184
334 6 $parsed{ssl} = $parsed{tls};
335 }
336 elsif ( exists $parsed{ssl} ) {
337 4 $parsed{tls} = $parsed{ssl};
338 }
339 190 return \%parsed;
340 }
341  
342 0 ▶sub _fetch_dns_seedlist {
Subroutine _fetch_dns_seedlist: not called CC=21 SCAR=61.4
343 0 my ( $self, $host_name, $phase ) = @_;
344  
345 0 my @split_name = split( '\.', $host_name );
346 0 ▶ MongoDB::Error->throw("URI '$self' must contain domain name and hostname")
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @split_name > 2 0 0 0
347 unless scalar( @split_name ) > 2;
348  
349 0 require Net::DNS;
350  
351 0 my $res = Net::DNS::Resolver->new;
352 0 my $srv_data = $res->query( sprintf( '_mongodb._tcp.%s', $host_name ), 'SRV' );
353  
354 0 my @hosts;
355 0 my $options = {};
356 0 my $domain_name = join( '.', @split_name[1..$#split_name] );
357 0 my $minimum_ttl;
358 0 ▶ if ( $srv_data ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($srv_data) { } 0 0 0
359 0 SRV_RECORD: foreach my $rr ( $srv_data->answer ) {
360 0 ▶ next unless $rr->type eq 'SRV';
Branch: 1 branch
BranchTrueFalseTotal
unless $rr->type eq "SRV" 0 0 0
361 0 my $target = $rr->target;
362 # search for dot before domain name for a valid hostname - can have sub-subdomain
363 0 ▶ unless ( $target =~ /\.\Q$domain_name\E$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($target =~ /\.\Q$domain_name\E$/) 0 0 0
364 0 my $err_msg = "URI '$self' SRV record returns FQDN '$target'"
365 0 . " which does not match domain name '${$domain_name}'";
366 0 ▶ if ($phase && $phase eq 'init') {
Branch: 1 branch
BranchTrueFalseTotal
if ($phase and $phase eq 'init') { } 0 0 0
Condition0%0/3
$phase and $phase eq "init"
!ll&&!rl&&r
000
MC/DC0%0/2
$phase and $phase eq "init"
$phase $phase eq "init"
Truth table0%0/3
A and B
A= $phaseB= $phase eq "init"
ABresult
0X0
100
111
367 0 MongoDB::Error->throw($err_msg);
368 }
369 else {
370 0 warn $err_msg;
371 }
372 0 next SRV_RECORD;
373 }
374 0 push @hosts, {
375 target => $target,
376 port => $rr->port,
377 };
378 0 ▶ $minimum_ttl = $rr->ttl
Branch: 1 branch
BranchTrueFalseTotal
if not defined $minimum_ttl or $rr->ttl < $minimum_ttl 0 0 0
Condition0%0/3
not defined $minimum_ttl or $rr->ttl < $minimum_ttl
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $minimum_ttl or $rr->ttl < $minimum_ttl
not defined $minimum_ttl $rr->ttl < $minimum_ttl
Truth table0%0/3
not(A) or B
A= not defined $minimum_ttlB= $rr->ttl < $minimum_ttl
ABresult
1X1
011
000
379 if not defined $minimum_ttl or $rr->ttl < $minimum_ttl;
380 }
381 0 my $txt_data = $res->query( $host_name, 'TXT' );
382 0 ▶ if ( defined $txt_data ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $txt_data) 0 0 0
383 0 my @txt_answers;
384 0 foreach my $rr ( $txt_data->answer ) {
385 0 ▶ next unless $rr->type eq 'TXT';
Branch: 1 branch
BranchTrueFalseTotal
unless $rr->type eq "TXT" 0 0 0
386 0 push @txt_answers, $rr;
387 }
388 0 ▶ if ( scalar( @txt_answers ) > 1 ) {
Branch: 2 branches
BranchTrueFalseTotal
if (scalar @txt_answers > 1) { } 0 0 0
elsif (scalar @txt_answers == 1) { } 0 0 0
389 0 MongoDB::Error->throw("URI '$self' returned more than one TXT result");
390 } elsif ( scalar( @txt_answers ) == 1 ) {
391 0 my $txt_opt_string = join ( '', $txt_answers[0]->txtdata );
392 0 $options = $self->_parse_options( $self->valid_srv_options, { options => $txt_opt_string }, $txt_opt_string );
393 }
394 }
395 } else {
396 0 MongoDB::Error->throw("URI '$self' does not return any SRV results");
397 }
398  
399 0 ▶ unless (@hosts) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@hosts) 0 0 0
400 0 my $err_msg = "URI '$self' does not return any valid SRV results";
401 0 ▶ if ($phase && $phase eq 'init') {
Branch: 1 branch
BranchTrueFalseTotal
if ($phase and $phase eq 'init') { } 0 0 0
Condition0%0/3
$phase and $phase eq "init"
!ll&&!rl&&r
000
MC/DC0%0/2
$phase and $phase eq "init"
$phase $phase eq "init"
Truth table0%0/3
A and B
A= $phaseB= $phase eq "init"
ABresult
0X0
100
111
402 0 MongoDB::Error->throw($err_msg);
403 }
404 else {
405 0 warn $err_msg;
406 }
407 }
408  
409 0 ▶ $minimum_ttl = RESCAN_SRV_FREQUENCY_SEC
Branch: 1 branch
BranchTrueFalseTotal
if $minimum_ttl < 60 and $phase and $phase ne "init" 0 0 0
Condition0%0/6
$minimum_ttl < 60 and $phase and $phase ne "init"
!ll&&!rl&&r
000
$minimum_ttl < 60 and $phase
!ll&&!rl&&r
000
MC/DC0%0/3
$minimum_ttl < 60 and $phase and $phase ne "init"
$minimum_ttl < 60 $phase $phase ne "init"
Truth table0%0/4
A and B and C
A= $minimum_ttl < 60B= $phaseC= $phase ne "init"
ABCresult
0XX0
10X0
1100
1111
410 if $minimum_ttl < RESCAN_SRV_FREQUENCY_SEC
411 && $phase && $phase ne 'init';
412  
413 0 return ( \@hosts, $options, time + $minimum_ttl );
414 }
415  
416 5 ▶sub _parse_srv_uri {
Subroutine _parse_srv_uri: called CC=16 SCAR=28.3
417 5 my ( $self, $uri, $phase ) = @_;
418  
419 5 my %result;
420  
421 5 $uri =~ m{^$uri_re$};
422  
423 (
424 $result{username}, $result{password}, $result{hostids},
425 $result{db_name}, $result{options}
426 5 ) = ( $1, $2, $3, $4, $5 );
427  
428 5 $result{hostids} = lc _unescape_all( $result{hostids} );
429  
430 5 ▶ if ( !defined $result{hostids} || !length $result{hostids} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $result{"hostids"} and length $result{"hostids"}) 0 5 5
Condition33%1/3
defined $result{"hostids"} and length $result{"hostids"}
!ll&&!rl&&r
005
MC/DC0%0/2
defined $result{"hostids"} and length $result{"hostids"}
defined $result{"hostids"} length $result{"hostids"}
Truth table33%1/3
A and B
A= defined $result{"hostids"}B= length $result{"hostids"}
ABresult
0X0
100
111
431 0 MongoDB::Error->throw("URI '$self' cannot be empty if using an SRV connection string");
432 }
433  
434 5 ▶ if ( $result{hostids} =~ /,/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result{"hostids"} =~ /,/) 1 4 5
435 1 MongoDB::Error->throw("URI '$self' cannot contain a comma or multiple host names if using an SRV connection string");
436 }
437  
438 4 ▶ if ( $result{hostids} =~ /:\d+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result{"hostids"} =~ /:\d+$/) 1 3 4
439 1 MongoDB::Error->throw("URI '$self' cannot contain port number if using an SRV connection string");
440 }
441  
442 3 ▶ if ( defined $result{options} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result{"options"}) 2 1 3
443 2 $result{options} = $self->_parse_options( $self->valid_options, \%result );
444 }
445  
446 3 my ( $hosts, $options, $expires ) = $self->_fetch_dns_seedlist( $result{hostids}, $phase );
447  
448 # Default to SSL on unless specified in conn string options
449 $options = {
450 ssl => 'true',
451 %$options,
452 3 ▶ %{ $result{options} || {} },
Condition100%2/2
$result{'options'} || {}
l!l
21
MC/DC100%1/1
$result{'options'} || {}
$result{'options'}
Truth table100%2/2
A
A= $result{'options'}
Aresult
11
00
453 };
454  
455 # Reset str to bool options to string value, as _parse_options changes it to 0/1 if it exists during parsing
456 # means we get the correct value when re-building the uri below.
457 3 for my $stb_key ( keys %{ $self->_valid_str_to_bool_options } ) {
458 # use exists just in case
459 27 ▶ next unless exists $options->{ $stb_key };
Branch: 1 branch
BranchTrueFalseTotal
unless exists $options->{$stb_key} 22 5 27
460 5 ▶ $options->{ $stb_key } = ($options->{ $stb_key } || $options->{ $stb_key } eq 'true') ? 'true' : 'false';
Branch: 1 branch
BranchTrueFalseTotal
$options->{$stb_key} || $options->{$stb_key} eq 'true' ? : 5 0 5
Condition33%1/3
$options->{$stb_key} or $options->{$stb_key} eq "true"
l!l&&r!l&&!r
500
MC/DC0%0/2
$options->{$stb_key} or $options->{$stb_key} eq "true"
$options->{$stb_key} $options->{$stb_key} eq "true"
Truth table33%1/3
A or B
A= $options->{$stb_key}B= $options->{$stb_key} eq "true"
ABresult
1X1
011
000
461 }
462  
463 3 my $auth = "";
464 3 ▶ if ( defined $result{username} || defined $result{password} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result{"username"} or defined $result{"password"}) 1 2 3
Condition66%2/3
defined $result{"username"} or defined $result{"password"}
l!l&&r!l&&!r
102
MC/DC50%1/2
defined $result{"username"} or defined $result{"password"}
defined $result{"username"} defined $result{"password"}
Truth table66%2/3
A or B
A= defined $result{"username"}B= defined $result{"password"}
ABresult
1X1
011
000
465 1 ▶ $auth = join(":", map { $_ // "" } $result{username}, $result{password});
Condition100%2/2
$_ // ""
l!l
11
MC/DC100%1/1
$_ // ""
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
466 1 $auth .= "@";
467 }
468  
469 my $new_uri = sprintf(
470 'mongodb://%s%s/%s%s%s',
471 $auth,
472 3 ▶ join( ',', map { sprintf( '%s:%s', $_->{target}, $_->{port} ) } @$hosts ),
Branch: 1 branch
BranchTrueFalseTotal
scalar keys %$options ? : 3 0 3
Condition100%2/2
$result{"db_name"} // ""
l!l
21
MC/DC100%1/1
$result{"db_name"} // ""
$result{"db_name"}
Truth table100%2/2
A
A= $result{"db_name"}
Aresult
11
00
473 ($result{db_name} // ""),
474 scalar( keys %$options ) ? '?' : '',
475 3 join( '&', map { sprintf( '%s=%s', $_, __uri_escape( $options->{$_} ) ) } keys %$options ),
476 );
477  
478 3 return( $new_uri, $expires );
479 }
480  
481 562 ▶sub BUILD {
Subroutine BUILD: called CC=1 SCAR=0.0
Pod undocumented
482 562 my ($self) = @_;
483  
484 562 $self->_initialize_from_uri;
485 }
486  
487 # Options:
488 # - fallback_ttl_sec: Fallback TTL in seconds in case of an error
489 0 ▶sub check_for_changes {
Subroutine check_for_changes: not called CC=8 SCAR=42.8
Pod undocumented
490 0 my ($self, $options) = @_;
491  
492 0 ▶ if (defined $self->{expires} && $self->{expires} <= time) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"expires"} and $self->{"expires"} <= &MongoDB::_URI::time()) 0 0 0
Condition0%0/3
defined $self->{"expires"} and $self->{"expires"} <= &MongoDB::_URI::time()
!ll&&!rl&&r
000
MC/DC0%0/2
defined $self->{"expires"} and $self->{"expires"} <= &MongoDB::_URI::time()
defined $self->{"expires"} $self->{"expires"} <= &MongoDB::_URI::time()
Truth table0%0/3
A and B
A= defined $self->{"expires"}B= $self->{"expires"} <= &MongoDB::_URI::time()
ABresult
0X0
100
111
493 0 my @current = sort @{ $self->{hostids} };
494 0 local $@;
495 0 my $ok = eval {
496  
497 0 $self->_update_from_uri;
498 0 1;
499 };
500 0 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
501 0 warn "Error while fetching SRV records: $@";
502 0 $self->{expires} = $options->{fallback_ttl_sec};
503 };
504 0 ▶ return 0
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
505 unless $ok;
506 0 my @new = sort @{ $self->{hostids} };
507 0 ▶ return 1
Branch: 1 branch
BranchTrueFalseTotal
unless @current == @new 0 0 0
508 unless @current == @new;
509 0 for my $index (0 .. $#current) {
510 0 ▶ return 1
Branch: 1 branch
BranchTrueFalseTotal
unless $new[$index] eq $current[$index] 0 0 0
511 unless $new[$index] eq $current[$index];
512 }
513 0 return 0;
514 }
515  
516 0 return 0;
517 }
518  
519 546 ▶sub _prepare_dns_hosts {
Subroutine _prepare_dns_hosts: called CC=13 SCAR=25.7
520 546 my ($self, $hostids) = @_;
521  
522 546 ▶ if ( !defined $hostids || !length $hostids ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $hostids and length $hostids) 5 541 546
Condition66%2/3
defined $hostids and length $hostids
!ll&&!rl&&r
05541
MC/DC50%1/2
defined $hostids and length $hostids
defined $hostids length $hostids
Truth table66%2/3
A and B
A= defined $hostidsB= length $hostids
ABresult
0X0
100
111
523 5 MongoDB::Error->throw("URI '$self' could not be parsed (missing host list)");
524 }
525 541 $hostids = [ map { lc _unescape_all($_) } split ',', $hostids ];
526 541 for my $hostid (@$hostids) {
527 584 ▶ MongoDB::Error->throw(
Branch: 1 branch
BranchTrueFalseTotal
if $hostid =~ m[/] and $hostid =~ /\.sock/ 34 550 584
Condition66%2/3
$hostid =~ m[/] and $hostid =~ /\.sock/
!ll&&!rl&&r
550034
MC/DC50%1/2
$hostid =~ m[/] and $hostid =~ /\.sock/
$hostid =~ m[/] $hostid =~ /\.sock/
Truth table66%2/3
A and B
A= $hostid =~ m[/]B= $hostid =~ /\.sock/
ABresult
0X0
100
111
528 "URI '$self' could not be parsed (Unix domain sockets are not supported)")
529 if $hostid =~ /\// && $hostid =~ /\.sock/;
530 550 ▶ MongoDB::Error->throw(
Branch: 1 branch
BranchTrueFalseTotal
if substr($hostid, 0, 1) eq "[" 15 535 550
531 "URI '$self' could not be parsed (IP literals are not supported)")
532 if substr( $hostid, 0, 1 ) eq '[';
533 535 my ( $host, $port ) = split ":", $hostid, 2;
534 535 ▶ MongoDB::Error->throw("host list '@{ $hostids }' contains empty host")
Branch: 1 branch
BranchTrueFalseTotal
unless length $host 3 532 535
535 unless length $host;
536 532 ▶ if ( defined $port ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $port) 139 393 532
537 139 ▶ MongoDB::Error->throw("URI '$self' could not be parsed (invalid port '$port')")
Branch: 1 branch
BranchTrueFalseTotal
unless $port =~ /^\d+$/ 9 130 139
538 unless $port =~ /^\d+$/;
539 130 ▶ MongoDB::Error->throw(
Branch: 1 branch
BranchTrueFalseTotal
unless $port >= 1 and $port <= 65535 5 125 130
Condition100%3/3
$port >= 1 and $port <= 65535
!ll&&!rl&&r
23125
MC/DC100%2/2
$port >= 1 and $port <= 65535
$port >= 1 $port <= 65535
Truth table100%3/3
A and B
A= $port >= 1B= $port <= 65535
ABresult
0X0
100
111
540 "URI '$self' could not be parsed (invalid port '$port' (must be in range [1,65535])")
541 unless $port >= 1 && $port <= 65535;
542 }
543 }
544 475 ▶ $hostids = [ map { /:/ ? $_ : $_.":27017" } @$hostids ];
Branch: 1 branch
BranchTrueFalseTotal
/:/ ? : 123 388 511
545 475 return $hostids;
546 }
547  
548 0 ▶sub _update_from_uri {
Subroutine _update_from_uri: not called CC=2 SCAR=17.9
549 0 my ($self) = @_;
550  
551 0 my $uri = $self->uri;
552 0 my %result;
553  
554 0 ($uri, my $expires) = $self->_parse_srv_uri( $uri );
555 0 $self->{expires} = $expires;
556  
557 0 ▶ if ( $uri !~ m{^$uri_re$} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($uri =~ /^$uri_re$/) 0 0 0
558 0 MongoDB::Error->throw("URI '$self' could not be parsed");
559 }
560  
561 0 my $hostids = $3;
562 0 $hostids = $self->_prepare_dns_hosts($hostids);
563  
564 0 $self->{hostids} = $hostids;
565 }
566  
567 562 ▶sub _initialize_from_uri {
Subroutine _initialize_from_uri: called CC=12 SCAR=24.8
568 562 my ($self) = @_;
569  
570 562 my $uri = $self->uri;
571 562 my %result;
572  
573 562 ▶ if ( $uri =~ m{^mongodb\+srv://} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($uri =~ m[^mongodb\+srv://]) 4 558 562
574 4 ($uri, my $expires) = $self->_parse_srv_uri( $uri, 'init' );
575 2 $result{expires} = $expires;
576 }
577  
578 # we throw Error instead of UsageError for errors, to avoid stacktrace revealing credentials
579 560 ▶ if ( $uri !~ m{^$uri_re$} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($uri =~ /^$uri_re$/) 5 555 560
580 5 MongoDB::Error->throw("URI '$self' could not be parsed");
581 }
582  
583 (
584 $result{username}, $result{password}, $result{hostids},
585 $result{db_name}, $result{options}
586 555 ) = ( $1, $2, $3, $4, $5 );
587  
588 555 ▶ if ( defined $result{username} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result{"username"}) 72 483 555
589 MongoDB::Error->throw(
590 "URI '$self' could not be parsed (username must be URL encoded)"
591 72 ▶ ) if __userinfo_invalid_chars($result{username});
Branch: 1 branch
BranchTrueFalseTotal
if __userinfo_invalid_chars($result{"username"}) 6 66 72
592 66 $result{username} = _unescape_all( $result{username} );
593 }
594  
595 549 ▶ if ( defined $result{password} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result{"password"}) 49 500 549
596 MongoDB::Error->throw(
597 "URI '$self' could not be parsed (password must be URL encoded)"
598 49 ▶ ) if __userinfo_invalid_chars($result{password});
Branch: 1 branch
BranchTrueFalseTotal
if __userinfo_invalid_chars($result{"password"}) 3 46 49
599 46 $result{password} = _unescape_all( $result{password} );
600 }
601  
602 546 $result{hostids} = $self->_prepare_dns_hosts($result{hostids});
603  
604 475 ▶ if ( defined $result{db_name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result{"db_name"}) 226 249 475
605 MongoDB::Error->throw(
606 "URI '$self' could not be parsed (database name must be URL encoded, found unescaped '/'"
607 226 ▶ ) if $result{db_name} =~ /\//;
Branch: 1 branch
BranchTrueFalseTotal
if $result{"db_name"} =~ m[/] 1 225 226
608 225 $result{db_name} = _unescape_all( $result{db_name} );
609 }
610  
611 474 ▶ if ( defined $result{options} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result{"options"}) 206 268 474
612 206 $result{options} = $self->_parse_options( $self->valid_options, \%result );
613 }
614  
615 456 for my $attr (qw/username password db_name options hostids expires/) {
616 2736 my $setter = "_set_$attr";
617 2736 ▶ $self->$setter( $result{$attr} ) if defined $result{$attr};
Branch: 1 branch
BranchTrueFalseTotal
if defined $result{$attr} 943 1793 2736
618 }
619  
620 456 return;
621 }
622  
623 65 ▶sub __str_to_bool {
Subroutine __str_to_bool: called CC=5 SCAR=16.1
624 65 my ($k, $str) = @_;
625 65 ▶ MongoDB::UsageError->throw("cannot convert undef to bool for key '$k'")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 0 65 65
626 unless defined $str;
627 65 ▶ my $ret = $str eq "true" ? 1 : $str eq "false" ? 0 : undef;
Branch: 2 branches
BranchTrueFalseTotal
$str eq 'true' ? : 33 32 65
$str eq 'false' ? : 25 7 32
628 65 ▶ warn("expected boolean string 'true' or 'false' for key '$k' but instead received '$str'. Ignoring '$k'.\n")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ret 7 58 65
629 unless defined $ret;
630 65 return $ret;
631 }
632  
633 # uri_escape borrowed from HTTP::Tiny 0.070
634 64 my %escapes = map { chr($_) => sprintf("%%%02X", $_) } 0..255;
635 64 $escapes{' '}="+";
636 64 my $unsafe_char = qr/[^A-Za-z0-9\-\._~]/;
637  
638 11 ▶sub __uri_escape {
Subroutine __uri_escape: called CC=3 SCAR=13.2
639 11 my ($str) = @_;
640 11 ▶ if ( $] ge '5.008' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($] ge '5.008') { } 11 0 11
641 11 utf8::encode($str);
642 }
643 else {
644 $str = pack("U*", unpack("C*", $str)) # UTF-8 encode a byte string
645 0 ▶ if ( length $str == do { use bytes; length $str } );
Subroutine BEGIN: called CC=1 SCAR=1.7
Branch: 1 branch
BranchTrueFalseTotal
if length $str == do { use bytes; length $str } 0 0 0
646 0 $str = pack("C*", unpack("C*", $str)); # clear UTF-8 flag
647 }
648 0 $str =~ s/($unsafe_char)/$escapes{$1}/ge;
649 11 return $str;
650 }
651  
652 # Rules for valid userinfo from RFC 3986 Section 3.2.1.
653 64 my $unreserved = q[a-z0-9._~-]; # use this class last so regex ends in '-'
654 64 my $subdelimit = q[!$&'()*+,;=];
655 64 my $allowed = "%$subdelimit$unreserved";
656 64 my $not_allowed_re = qr/[^$allowed]/i;
657 64 my $not_pct_enc_re = qr/%(?![0-9a-f]{2})/i;
658  
659 121 ▶sub __userinfo_invalid_chars {
Subroutine __userinfo_invalid_chars: called CC=2 SCAR=6.9
660 121 my ($str) = @_;
661 121 ▶ return $str =~ $not_pct_enc_re || $str =~ $not_allowed_re;
Condition100%3/3
$str =~ /$not_pct_enc_re/ || $str =~ /$not_allowed_re/
l!l&&r!l&&!r
18112
MC/DC100%2/2
$str =~ /$not_pct_enc_re/ || $str =~ /$not_allowed_re/
$str =~ /$not_pct_enc_re/ $str =~ /$not_allowed_re/
Truth table100%3/3
A || B
A= $str =~ /$not_pct_enc_re/B= $str =~ /$not_allowed_re/
ABresult
1X1
011
000
662 }
663  
664 # redact user credentials when stringifying
665 use overload
666 64 ▶ '""' => sub {
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
667 120 (my $s = $_[0]->uri) =~ s{^([^:]+)://[^/]+\@}{$1://[**REDACTED**]\@};
668 120 return $s
669 },
670 64 'fallback' => 1;
671  
672  
673 64 1;
674  
675 # vim: ts=4 sts=4 sw=4 et:
« MongoDB/ClientSession.pm ↑ Summary MongoDB/Role/_OpReplyParser.pm »