4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
20 * @author Brandon Black <blblack@gmail.com>
24 * Matches IP addresses against a set of CIDR specifications
27 * // At startup, calculate the optimized data structure for the set:
28 * $ipset = new IPSet( $wgSquidServersNoPurge );
29 * // runtime check against cached set (returns bool):
30 * $allowme = $ipset->match( $ip );
32 * In rough benchmarking, this takes about 80% more time than
33 * in_array() checks on a short (a couple hundred at most) array
34 * of addresses. It's fast either way at those levels, though,
35 * and IPSet would scale better than in_array if the array were
38 * For mixed-family CIDR sets, however, this code gives well over
39 * 100x speedup vs iterating IP::isInRange() over an array
42 * The basic implementation is two separate binary trees
43 * (IPv4 and IPv6) as nested php arrays with keys named 0 and 1.
44 * The values false and true are terminal match-fail and match-success,
45 * otherwise the value is a deeper node in the tree.
47 * A simple depth-compression scheme is also implemented: whole-byte
48 * tree compression at whole-byte boundaries only, where no branching
49 * occurs during that whole byte of depth. A compressed node has
50 * keys 'comp' (the byte to compare) and 'next' (the next node to
51 * recurse into if 'comp' matched successfully).
53 * For example, given these inputs:
57 * The v4 tree would look like:
69 * (multi-byte compression nodes were attempted as well, but were
70 * a net loss in my test scenarios due to additional match complexity)
75 /** @var array $root4: the root of the IPv4 matching tree */
76 private $root4 = array( false, false );
78 /** @var array $root6: the root of the IPv6 matching tree */
79 private $root6 = array( false, false );
82 * __construct() instantiate the object from an array of CIDR specs
84 * @param array $cfg array of IPv[46] CIDR specs as strings
85 * @return IPSet new IPSet object
87 * Invalid input network/mask values in $cfg will result in issuing
88 * E_WARNING and/or E_USER_WARNING and the bad values being ignored.
90 public function __construct( array $cfg ) {
91 foreach ( $cfg as $cidr ) {
92 $this->addCidr( $cidr );
95 self
::recOptimize( $this->root4
);
96 self
::recCompress( $this->root4
, 0, 24 );
97 self
::recOptimize( $this->root6
);
98 self
::recCompress( $this->root6
, 0, 120 );
102 * Add a single CIDR spec to the internal matching trees
104 * @param string $cidr string CIDR spec, IPv[46], optional /mask (def all-1's)
106 private function addCidr( $cidr ) {
108 if ( strpos( $cidr, ':' ) === false ) {
109 $node =& $this->root4
;
112 $node =& $this->root6
;
116 // Default to all-1's mask if no netmask in the input
117 if ( strpos( $cidr, '/' ) === false ) {
121 list( $net, $mask ) = explode( '/', $cidr, 2 );
122 if ( !ctype_digit( $mask ) ||
intval( $mask ) > $defMask ) {
123 trigger_error( "IPSet: Bad mask '$mask' from '$cidr', ignored", E_USER_WARNING
);
127 $mask = intval( $mask ); // explicit integer convert, checked above
129 // convert $net to an array of integer bytes, length 4 or 16:
130 $raw = inet_pton( $net );
131 if ( $raw === false ) {
132 return; // inet_pton() sends an E_WARNING for us
134 $rawOrd = array_map( 'ord', str_split( $raw ) );
136 // special-case: zero mask overwrites the whole tree with a pair of terminal successes
138 $node = array( true, true );
142 // iterate the bits of the address while walking the tree structure for inserts
145 $maskShift = 7 - ( $curBit & 7 );
146 $node =& $node[( $rawOrd[$curBit >> 3] & ( 1 << $maskShift ) ) >> $maskShift];
148 if ( $node === true ) {
149 // already added a larger supernet, no need to go deeper
151 } elseif ( $curBit == $mask ) {
152 // this may wipe out deeper subnets from earlier
155 } elseif ( $node === false ) {
156 // create new subarray to go deeper
157 $node = array( false, false );
163 * Match an IP address against the set
165 * @param string $ip string IPv[46] address
166 * @return boolean true is match success, false is match failure
168 * If $ip is unparseable, inet_pton may issue an E_WARNING to that effect
170 public function match( $ip ) {
171 $raw = inet_pton( $ip );
172 if ( $raw === false ) {
173 return false; // inet_pton() sends an E_WARNING for us
176 $rawOrd = array_map( 'ord', str_split( $raw ) );
177 if ( count( $rawOrd ) == 4 ) {
178 $node =& $this->root4
;
180 $node =& $this->root6
;
185 if ( isset( $node['comp'] ) ) {
186 // compressed node, matches 1 whole byte on a byte boundary
187 if ( $rawOrd[$curBit >> 3] != $node['comp'] ) {
191 $node =& $node['next'];
193 // uncompressed node, walk in the correct direction for the current bit-value
194 $maskShift = 7 - ( $curBit & 7 );
195 $node =& $node[( $rawOrd[$curBit >> 3] & ( 1 << $maskShift ) ) >> $maskShift];
199 if ( $node === true ||
$node === false ) {
206 * Recursively merges adjacent nets into larger supernets
208 * @param array &$node Tree node to optimize, by-reference
210 * e.g.: 8.0.0.0/8 + 9.0.0.0/8 -> 8.0.0.0/7
212 private static function recOptimize( &$node ) {
213 if ( $node[0] !== false && $node[0] !== true && self
::recOptimize( $node[0] ) ) {
216 if ( $node[1] !== false && $node[1] !== true && self
::recOptimize( $node[1] ) ) {
219 if ( $node[0] === true && $node[1] === true ) {
226 * Recursively compresses a tree
228 * @param array &$node Tree node to compress, by-reference
229 * @param integer $curBit current depth in the tree
230 * @param integer $maxCompStart maximum depth at which compression can start, family-specific
232 * This is a very simplistic compression scheme: if we go through a whole
233 * byte of address starting at a byte boundary with no real branching
234 * other than immediate false-vs-(node|true), compress that subtree down to a single
235 * byte-matching node.
236 * The $maxCompStart check elides recursing the final 7 levels of depth (family-dependent)
238 private static function recCompress( &$node, $curBit, $maxCompStart ) {
239 if ( !( $curBit & 7 ) ) { // byte boundary, check for depth-8 single path(s)
244 if ( $cnode[0] === false ) {
247 } elseif ( $cnode[1] === false ) {
250 // partial-byte branching, give up
254 if ( $i == -1 ) { // means we did not exit the while() via break
260 if ( $cnode !== true ) {
261 self
::recCompress( $cnode, $curBit, $maxCompStart );
268 if ( $curBit <= $maxCompStart ) {
269 if ( $node[0] !== false && $node[0] !== true ) {
270 self
::recCompress( $node[0], $curBit, $maxCompStart );
272 if ( $node[1] !== false && $node[1] !== true ) {
273 self
::recCompress( $node[1], $curBit, $maxCompStart );