blib/lib/Net/IP/Match/Regexp.pm

filter: Statementstmt 100% 60 / 60 Branchbran 100% 38 / 38 Conditioncond 100% 17 / 17 MC/DCmcdc 100% 11 / 11 Subroutinesub 100% 13 / 13 Podpod 100% 3 / 3 totaltotal 100% 142 / 142 CC 27 SCAR 19.5
CC
27
Cov
100%
_build_regexp
11.0
_tree2re_depthfirst
10.0
_tree2re
6.0
CRAP 7.1
↑ Summary
1 package Net::IP::Match::Regexp;
2  
3 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use English qw(-no_match_vars);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use base 'Exporter';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 our @EXPORT_OK = qw( create_iprange_regexp create_iprange_regexp_depthfirst match_ip );
10 1 our $VERSION = '1.01';
11  
12 =head1 NAME
13  
14 Net::IP::Match::Regexp - Efficiently match IP addresses against ranges
15  
16 =head1 LICENSE
17  
18 Copyright 2005-2006 Clotho Advanced Media, Inc., <cpan@clotho.com>
19  
20 Copyright 2007-2008 Chris Dolan, <cdolan@cpan.org>
21  
22 This library is free software; you can redistribute it and/or modify it
23 under the same terms as Perl itself.
24  
25 =head1 SYNOPSIS
26  
27 use Net::IP::Match::Regexp qw( create_iprange_regexp match_ip );
28
29 my $regexp = create_iprange_regexp(
30 qw( 10.0.0.0/8 87.134.66.128 87.134.87.0/24 145.97.0.0/16 )
31 );
32 if (match_ip('209.249.163.62', $regexp)) {
33 ...
34 }
35  
36 =head1 DESCRIPTION
37  
38 This module allows you to check an IP address against one or more IP
39 ranges. It employs Perl's highly optimized regular expression engine
40 to do the hard work, so it is very fast. It is optimized for speed by
41 doing the match against a regexp which implicitly checks the broadest
42 IP ranges first. An advantage is that the regexp can be computed and
43 stored in advance (in source code, in a database table, etc) and
44 reused, saving much time if the IP ranges don't change too often. The
45 match can optionally report a value (e.g. a network name) instead of
46 just a boolean, which makes module useful for mapping IP ranges to
47 names or codes or anything else.
48  
49 =head1 LIMITATIONS
50  
51 This module does not yet support IPv6 addresses, although that feature
52 should not be hard to implement as long as the regexps start with a 4
53 vs. 6 flag. Patches welcome. :-)
54  
55 This module only accepts IP ranges in C<a.b.c.d/x> (aka CIDR)
56 notation. To work around that limitation, I recommend
57 Net::CIDR::Lite to conveniently convert collections of IP address
58 ranges into CIDR format.
59  
60 This module makes no effort to validate the IP addresses or ranges
61 passed as arguments. If you pass address ranges like
62 C<1000.0.0.0/300>, you will probably get weird regexps out.
63  
64 =head1 FUNCTIONS
65  
66 =over
67  
68 =cut
69  
70 =item create_iprange_regexp($iprange | $hashref | $arrayref, ...)
71  
72 This function digests IP ranges into a regular expression that can
73 subsequently be used to efficiently test single IP addresses. It
74 returns a regular expression string that can be passed to match_ip().
75  
76 The simple way to use this is to pass a list of IP ranges as
77 C<aaa.bbb.ccc.ddd/n>. When used this way, the return value of the
78 match_ip() function will be simply C<1> or C<undef>.
79  
80 The more complex way is to pass a hash reference of IP range => return
81 value pairs. When used this way, the return value of the match_ip()
82 function will be the specified return value or C<undef> for no match.
83  
84 For example:
85  
86 my $re1 = create_iprange_regexp('209.249.163.0/25', '127.0.0.1/32');
87 print match_ip('209.249.163.62', $re1); # prints '1'
88
89 my $re2 = create_iprange_regexp({'209.249.163.0/25' => 'clotho.com',
90 '127.0.0.1/32' => 'localhost'});
91 print match_ip('209.249.163.62', $re2); # prints 'clotho.com'
92  
93 Be aware that the value string will be wrapped in single quotes in the
94 regexp. Therefore, you must double-escape any single quotes in that
95 value. For example:
96  
97 create_iprange_regexp({'208.201.239.36/31' => 'O\\'Reilly publishing'});
98  
99 Note that the scalar and hash styles can be mixed (a rarely used
100 feature). These two examples are equivalent:
101  
102 create_iprange_regexp('127.0.0.1/32',
103 {'209.249.163.0/25' => 'clotho.com'},
104 '10.0.0.0/8',
105 {'192.168.0.0/16' => 'LAN'});
106
107 create_iprange_regexp({'127.0.0.1/32' => 1,
108 '209.249.163.0/25' => 'clotho.com',
109 '10.0.0.0/8' => 1,
110 '192.168.0.0/16' => 'LAN'});
111  
112 If any of the IP ranges are overlapping, the broadest one is used. If
113 they are equivalent, then the first one passed is used. If you have
114 some data that might be ambiguous, you pass an arrayref instead of a
115 hashref, but it's better to clean up your data instead! For example:
116  
117 my $re = create_iprange_regexp(['1.1.1.0/31' => 'zero', '1.1.1.1/31' => 'one']);
118 print match_ip('1.1.1.1', $re)); # prints 'zero', since both match
119  
120 WARNING: This function does no checking for validity of IP ranges. It
121 happily accepts C<1000.0.0.0/-38> and makes a garbage regexp.
122 Hopefully a future version will validate the ranges, perhaps via
123 Net::CIDR or Net::IP.
124  
125 =cut
126  
127 79 ▶sub create_iprange_regexp { ##no critic (ArgUnpacking)
Subroutine create_iprange_regexp: called CC=1 SCAR=0.0
Pod documented
128 79 return _build_regexp(0, \@_);
129 }
130  
131 =item create_iprange_regexp_depthfirst($iprange | $hashref | $arrayref, ...)
132  
133 Returns a regexp in matches the most specific IP range instead of the
134 broadest range. Example:
135  
136 my $re = create_iprange_regexp_depthfirst({'192.168.0.0/16' => 'LAN',
137 '192.168.0.1' => 'router'});
138 match_ip('192.168.0.1', $re);
139  
140 returns 'router' instead of 'LAN'.
141  
142 =cut
143  
144 2 ▶sub create_iprange_regexp_depthfirst { ##no critic (ArgUnpacking)
Subroutine create_iprange_regexp_depthfirst: called CC=1 SCAR=0.0
Pod documented
145 2 return _build_regexp(1, \@_);
146 }
147 81 ▶sub _build_regexp {
Subroutine _build_regexp: called CC=11 SCAR=24.0
148 81 my ($depthfirst, $ipranges) = @_;
149  
150 # If an argument is a hash or array ref, flatten it
151 # If an argument is a scalar, make it a key and give it a value of 1
152 my @map
153 = map { ! ref $_ ? ( $_ => 1 )
154 3 : ref $_ eq 'ARRAY' ? @{$_}
155 81 ▶ : %{$_} } @{$ipranges};
Branch: 2 branches
BranchTrueFalseTotal
!ref($_) ? : 80 8 88
ref $_ eq 'ARRAY' ? : 3 5 8
156  
157 # The tree is a temporary construct. It has three possible
158 # properties: 0, 1, and code. The code is the return value for a
159 # match.
160 81 my %tree;
161  
162 IPRANGE:
163 81 ▶ for ( my $i = 0; $i < @map; $i += 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @map) 104 81 185
164 104 my $range = $map[ $i ];
165 104 my $match = $map[ $i + 1 ];
166  
167 104 my ( $ip, $mask ) = split m/\//xms, $range;
168 104 ▶ if (! defined $mask) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $mask) 5 99 104
169 5 $mask = 32; ## no critic(MagicNumbers)
170 }
171  
172 104 my $tree = \%tree;
173 104 my @bits = split m//xms, unpack 'B32', pack 'C4', split m/[.]/xms, $ip;
174  
175 104 for my $bit ( @bits[ 0 .. $mask - 1 ] ) {
176  
177 # If this case is hit, it means that our IP range is a subset
178 # of some other range, and thus ignorable
179 1890 ▶ next IPRANGE if !$depthfirst && $tree->{code};
Branch: 1 branch
BranchTrueFalseTotal
if not $depthfirst and $tree->{"code"} 3 1887 1890
Condition100%3/3
not $depthfirst and $tree->{"code"}
!ll&&!rl&&r
25616313
MC/DC100%2/2
not $depthfirst and $tree->{"code"}
not $depthfirst $tree->{"code"}
Truth table100%3/3
not(A) and B
A= not $depthfirstB= $tree->{"code"}
ABresult
0X0
100
111
180  
181 1887 ▶ $tree->{$bit} ||= {}; # Turn a leaf into a branch, if needed
Condition100%2/2
$tree->{$bit} ||= {}
l!l
3011586
MC/DC100%1/1
$tree->{$bit} ||= {}
$tree->{$bit}
Truth table100%2/2
A
A= $tree->{$bit}
Aresult
11
00
182 1887 $tree = $tree->{$bit}; # Follow one branch
183 }
184  
185 # Our $tree is now a leaf node of %tree. Set its value
186 # If the code is already set, it's a non-fatal error (redundant data)
187 101 ▶ $tree->{code} ||= $match;
Condition100%3/3
$tree->{"code"} ||= $match
l!l&&r!l&&!r
1991
MC/DC100%2/2
$tree->{"code"} ||= $match
$tree->{"code"} $match
Truth table100%3/3
A ||= B
A= $tree->{"code"}B= $match
ABresult
1X1
011
000
188  
189 # Ignore case where $tree->{0} or $tree->{1} are set (i.e. if
190 # the current range encompasses any earlier-processed ranges).
191 # Those branches will be ignored in _tree2re()
192 }
193  
194 # Recurse into the tree making it into a regexp
195 81 ▶ my $re = join q{}, '^4', $depthfirst ? _tree2re_depthfirst( \%tree ) : _tree2re( \%tree );
Branch: 1 branch
BranchTrueFalseTotal
$depthfirst ? : 2 79 81
196  
197 ## Performance optimization:
198  
199 # If we are going to use the pattern repeatedly, it's more
200 # effiecient if it's already a regexp instead of a string.
201 # Otherwise, it needs to be compiled in each invocation of
202 # match_ip(). If the regexp is merely stored and not used then
203 # this is wasted effort.
204  
205 1 ▶ use re 'eval'; # needed because we're interpolating into a regexp
Subroutine BEGIN: called CC=1 SCAR=0.0
206 81 $re = qr/$re/xms;
207  
208 81 return $re;
209 }
210  
211 =item match_ip($ipaddr, $regexp)
212  
213 Given a single IP address as a string of the form C<aaa.bbb.ccc.ddd>
214 and a regular expression string (typically the output of
215 create_iprange_regexp()), this function returns a specified value
216 (typically C<1>) if the IP is in one of the ranges, or C<undef> if no
217 ranges match.
218  
219 See create_ipranges_regexp() for more details about the return value
220 of this function.
221  
222 WARNING: This function does no checking for validity of the IP address.
223  
224 =cut
225  
226 627 ▶sub match_ip {
Subroutine match_ip: called CC=3 SCAR=11.0
Pod documented
227 627 my ( $ip, $re ) = @_;
228  
229 627 ▶ return if !$ip;
Branch: 1 branch
BranchTrueFalseTotal
unless $ip 2 625 627
230 625 ▶ return if !$re;
Branch: 1 branch
BranchTrueFalseTotal
unless $re 1 624 625
231  
232 624 local $LAST_REGEXP_CODE_RESULT = undef;
233 1 ▶ use re 'eval';
Subroutine BEGIN: called CC=1 SCAR=0.0
234 624 ( '4' . unpack 'B32', pack 'C4', split m/[.]/xms, $ip ) =~ m/$re/xms;
235 624 return $LAST_REGEXP_CODE_RESULT;
236 }
237  
238 # Helper function. This recurses to build the regular expression
239 # string from a tree of IP ranges constructed by
240 # create_iprange_regexp().
241  
242 1548 ▶sub _tree2re {
Subroutine _tree2re: called CC=6 SCAR=17.9
243 1548 my ( $tree ) = @_;
244  
245 return
246 defined $tree->{code} ? ( "(?{'$tree->{code}'})" ) # Match
247 : $tree->{0} && $tree->{1} ? ( '(?>0', _tree2re($tree->{0}),
248 '|1', _tree2re($tree->{1}), ')' ) # Choice
249 : $tree->{0} ? ( '0', _tree2re($tree->{0}) ) # Literal, no choice
250 1548 ▶ : $tree->{1} ? ( '1', _tree2re($tree->{1}) ) # Literal, no choice
Branch: 4 branches
BranchTrueFalseTotal
defined $tree->{'code'} ? : 87 1461 1548
$tree->{'0'} && $tree->{'1'} ? : 8 1453 1461
$tree->{'0'} ? : 801 652 1453
$tree->{'1'} ? : 651 1 652
Condition100%3/3
$tree->{0} and $tree->{1}
!ll&&!rl&&r
6528018
MC/DC100%2/2
$tree->{0} and $tree->{1}
$tree->{0} $tree->{1}
Truth table100%3/3
A and B
A= $tree->{0}B= $tree->{1}
ABresult
0X0
100
111
251 : die 'Internal error: failed to create a regexp from the supplied IP ranges'
252 ;
253 }
254  
255 113 ▶sub _tree2re_depthfirst {
Subroutine _tree2re_depthfirst: called CC=10 SCAR=23.0
256 113 my ( $tree ) = @_;
257  
258 113 ▶ if (defined $tree->{code}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $tree->{'code'}) { } 11 102 113
259 return '(?>',
260 $tree->{0} && $tree->{1} ? ( '(?>0', _tree2re_depthfirst($tree->{0}),
261 '|1', _tree2re_depthfirst($tree->{1}), ')|' )
262 : $tree->{0} ? ( '0', _tree2re_depthfirst($tree->{0}), q{|} )
263 11 ▶ : $tree->{1} ? ( '1', _tree2re_depthfirst($tree->{1}), q{|} )
Branch: 3 branches
BranchTrueFalseTotal
$tree->{'0'} && $tree->{'1'} ? : 1 10 11
$tree->{'0'} ? : 2 8 10
$tree->{'1'} ? : 1 7 8
Condition100%3/3
$tree->{0} and $tree->{1}
!ll&&!rl&&r
821
MC/DC100%2/2
$tree->{0} and $tree->{1}
$tree->{0} $tree->{1}
Truth table100%3/3
A and B
A= $tree->{0}B= $tree->{1}
ABresult
0X0
100
111
264 : (),
265 "(?{'$tree->{code}'}))";
266 } else {
267 return
268 $tree->{0} && $tree->{1} ? ( '(?>0', _tree2re_depthfirst($tree->{0}),
269 '|1', _tree2re_depthfirst($tree->{1}), ')' ) # Choice
270 : $tree->{0} ? ( '0', _tree2re_depthfirst($tree->{0}) ) # Literal, no choice
271 102 ▶ : $tree->{1} ? ( '1', _tree2re_depthfirst($tree->{1}) ) # Literal, no choice
Branch: 3 branches
BranchTrueFalseTotal
$tree->{'0'} && $tree->{'1'} ? : 4 98 102
$tree->{'0'} ? : 78 20 98
$tree->{'1'} ? : 19 1 20
Condition100%3/3
$tree->{0} and $tree->{1}
!ll&&!rl&&r
20784
MC/DC100%2/2
$tree->{0} and $tree->{1}
$tree->{0} $tree->{1}
Truth table100%3/3
A and B
A= $tree->{0}B= $tree->{1}
ABresult
0X0
100
111
272 : die 'Internal error: failed to create a regexp from the supplied IP ranges'
273 ;
274 }
275 }
276  
277 1 1;
278  
279 __END__
↑ Summary