45ac6289f636189acdcfa09eb77831f310cc8176
3 * @Author "Ashar Voultoiz" <hashar@altern.org>
4 * @License GPL v2 or later
7 // Some regex definition to "play" with IP address and IP address blocks
9 // An IP is made of 4 bytes from x00 to xFF which is d0 to d255
10 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])');
11 define( 'RE_IP_ADD' , RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
. '\.' . RE_IP_BYTE
);
12 // An IPv4 block is an IP address and a prefix (d1 to d32)
13 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)');
14 define( 'RE_IP_BLOCK', RE_IP_ADD
. '\/' . RE_IP_PREFIX
);
15 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
16 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
17 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
18 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP
. '(?:ffff:)?' );
19 // An IPv6 block is an IP address and a prefix (d1 to d128)
20 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
21 // An IPv6 IP is made up of 8 octets. However abbreviations like "::" can be used.
22 // This is lax! Number of octets/double colons validation not done.
23 define( 'RE_IPV6_ADD',
25 ':(:' . RE_IPV6_WORD
. '){1,7}' . // IPs that start with ":"
27 RE_IPV6_WORD
. '(:{1,2}' . RE_IPV6_WORD
. '|::$){1,7}' . // IPs that don't start with ":"
30 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD
. '\/' . RE_IPV6_PREFIX
);
31 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
32 define( 'IP_ADDRESS_STRING',
34 RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)' . // IPv4
36 RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)' . // IPv6
41 * A collection of public static functions to play with IP address
46 * Given a string, determine if it as valid IP
47 * Unlike isValid(), this looks for networks too
48 * @param $ip IP address.
51 public static function isIPAddress( $ip ) {
52 if ( !$ip ) return false;
53 if ( is_array( $ip ) ) {
54 throw new MWException( "invalid value passed to " . __METHOD__
);
56 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
57 return preg_match( '/^' . IP_ADDRESS_STRING
. '$/', $ip) && ( substr_count($ip, '::') < 2 );
60 public static function isIPv6( $ip ) {
61 if ( !$ip ) return false;
62 if( is_array( $ip ) ) {
63 throw new MWException( "invalid value passed to " . __METHOD__
);
65 $doubleColons = substr_count($ip, '::');
66 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
67 return preg_match( '/^' . RE_IPV6_ADD
. '(\/' . RE_IPV6_PREFIX
. '|)$/', $ip)
68 && ( $doubleColons == 1 ||
substr_count($ip,':') == 7 );
71 public static function isIPv4( $ip ) {
72 if ( !$ip ) return false;
73 return preg_match( '/^' . RE_IP_ADD
. '(\/' . RE_IP_PREFIX
. '|)$/', $ip);
77 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
78 * See http://www.answers.com/topic/ipv4-compatible-address
79 * IPs with the first 92 bits as zeros are reserved from IPv6
80 * @param $ip quad-dotted IP address.
83 public static function IPv4toIPv6( $ip ) {
84 if ( !$ip ) return null;
85 // Convert only if needed
86 if ( self
::isIPv6( $ip ) ) return $ip;
88 if ( strpos( $ip, '/' ) !== false ) {
89 $parts = explode( '/', $ip, 2 );
90 if ( count( $parts ) != 2 ) {
93 $network = self
::toUnsigned( $parts[0] );
94 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
95 $bits = $parts[1] +
96;
96 return self
::toOctet( $network ) . "/$bits";
101 return self
::toOctet( self
::toUnsigned( $ip ) );
105 * Given an IPv6 address in octet notation, returns an unsigned integer.
106 * @param $ip octet ipv6 IP address.
109 public static function toUnsigned6( $ip ) {
110 if ( !$ip ) return null;
111 $ip = explode(':', self
::sanitizeIP( $ip ) );
113 foreach ($ip as $v) {
114 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT
);
116 $r_ip = wfBaseConvert( $r_ip, 16, 10 );
121 * Given an IPv6 address in octet notation, returns the expanded octet.
122 * IPv4 IPs will be trimmed, thats it...
123 * @param $ip octet ipv6 IP address.
126 public static function sanitizeIP( $ip ) {
128 if ( $ip === '' ) return null;
129 // Trim and return IPv4 addresses
130 if ( self
::isIPv4($ip) ) return $ip;
131 // Only IPv6 addresses can be expanded
132 if ( !self
::isIPv6($ip) ) return $ip;
133 // Remove any whitespaces, convert to upper case
134 $ip = strtoupper( $ip );
135 // Expand zero abbreviations
136 if ( strpos( $ip, '::' ) !== false ) {
137 $ip = str_replace('::', str_repeat(':0', 8 - substr_count($ip, ':')) . ':', $ip);
139 // For IPs that start with "::", correct the final IP so that it starts with '0' and not ':'
140 if ( $ip[0] == ':' ) $ip = "0$ip";
141 // Remove leading zereos from each bloc as needed
142 $ip = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip );
147 * Given an unsigned integer, returns an IPv6 address in octet notation
148 * @param $ip integer IP address.
151 public static function toOctet( $ip_int ) {
152 // Convert to padded uppercase hex
153 $ip_hex = wfBaseConvert($ip_int, 10, 16, 32, false);
154 // Separate into 8 octets
155 $ip_oct = substr( $ip_hex, 0, 4 );
156 for ($n=1; $n < 8; $n++
) {
157 $ip_oct .= ':' . substr($ip_hex, 4*$n, 4);
160 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip_oct );
165 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
167 public static function formatHex( $hex ) {
168 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
169 return self
::hexToOctet( $hex );
171 return self
::hexToQuad( $hex );
176 * Given a hexadecimal number, returns to an IPv6 address in octet notation
177 * @param $ip string hex IP
180 public static function hextoOctet( $ip_hex ) {
181 // Convert to padded uppercase hex
182 $ip_hex = str_pad( strtoupper($ip_hex), 32, '0');
183 // Separate into 8 octets
184 $ip_oct = substr( $ip_hex, 0, 4 );
185 for ($n=1; $n < 8; $n++
) {
186 $ip_oct .= ':' . substr($ip_hex, 4*$n, 4);
189 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD
. '/', '$1$2', $ip_oct );
194 * Converts a hexadecimal number to an IPv4 address in octet notation
195 * @param $ip string Hex IP
198 public static function hexToQuad( $ip ) {
199 // Converts a hexadecimal IP to nnn.nnn.nnn.nnn format
201 for ( $i = 0; $i < 4; $i++
) {
205 $s .= base_convert( substr( $ip, $i * 2, 2 ), 16, 10 );
211 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
212 * @return array(string, int)
214 public static function parseCIDR6( $range ) {
216 $parts = explode( '/', IP
::sanitizeIP( $range ), 2 );
217 if ( count( $parts ) != 2 ) {
218 return array( false, false );
220 $network = self
::toUnsigned6( $parts[0] );
221 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
226 # Native 32 bit functions WONT work here!!!
227 # Convert to a padded binary number
228 $network = wfBaseConvert( $network, 10, 2, 128 );
229 # Truncate the last (128-$bits) bits and replace them with zeros
230 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT
);
231 # Convert back to an integer
232 $network = wfBaseConvert( $network, 2, 10 );
238 return array( $network, $bits );
242 * Given a string range in a number of formats, return the start and end of
243 * the range in hexadecimal. For IPv6.
246 * 2001:0db8:85a3::7344/96 CIDR
247 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
248 * 2001:0db8:85a3::7344/96 Single IP
249 * @return array(string, int)
251 public static function parseRange6( $range ) {
253 $range = IP
::sanitizeIP( $range );
254 if ( strpos( $range, '/' ) !== false ) {
256 list( $network, $bits ) = self
::parseCIDR6( $range );
257 if ( $network === false ) {
258 $start = $end = false;
260 $start = wfBaseConvert( $network, 10, 16, 32, false );
261 # Turn network to binary (again)
262 $end = wfBaseConvert( $network, 10, 2, 128 );
263 # Truncate the last (128-$bits) bits and replace them with ones
264 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT
);
266 $end = wfBaseConvert( $end, 2, 16, 32, false );
267 # see toHex() comment
268 $start = "v6-$start"; $end = "v6-$end";
270 } elseif ( strpos( $range, '-' ) !== false ) {
272 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
273 $start = self
::toUnsigned6( $start ); $end = self
::toUnsigned6( $end );
274 if ( $start > $end ) {
275 $start = $end = false;
277 $start = wfBaseConvert( $start, 10, 16, 32, false );
278 $end = wfBaseConvert( $end, 10, 16, 32, false );
280 # see toHex() comment
281 $start = "v6-$start"; $end = "v6-$end";
284 $start = $end = self
::toHex( $range );
286 if ( $start === false ||
$end === false ) {
287 return array( false, false );
289 return array( $start, $end );
294 * Validate an IP address.
295 * @return boolean True if it is valid.
297 public static function isValid( $ip ) {
298 return ( preg_match( '/^' . RE_IP_ADD
. '$/', $ip) ||
preg_match( '/^' . RE_IPV6_ADD
. '$/', $ip) );
302 * Validate an IP Block.
303 * @return boolean True if it is valid.
305 public static function isValidBlock( $ipblock ) {
306 return ( count(self
::toArray($ipblock)) == 1 +
5 );
310 * Determine if an IP address really is an IP address, and if it is public,
311 * i.e. not RFC 1918 or similar
312 * Comes from ProxyTools.php
314 public static function isPublic( $ip ) {
315 $n = self
::toUnsigned( $ip );
320 // ip2long accepts incomplete addresses, as well as some addresses
321 // followed by garbage characters. Check that it's really valid.
322 if( $ip != long2ip( $n ) ) {
326 static $privateRanges = false;
327 if ( !$privateRanges ) {
328 $privateRanges = array(
329 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
330 array( '172.16.0.0', '172.31.255.255' ), # "
331 array( '192.168.0.0', '192.168.255.255' ), # "
332 array( '0.0.0.0', '0.255.255.255' ), # this network
333 array( '127.0.0.0', '127.255.255.255' ), # loopback
337 foreach ( $privateRanges as $r ) {
338 $start = self
::toUnsigned( $r[0] );
339 $end = self
::toUnsigned( $r[1] );
340 if ( $n >= $start && $n <= $end ) {
348 * Split out an IP block as an array of 4 bytes and a mask,
349 * return false if it can't be determined
351 * @param $ip string A quad dotted/octet IP address
354 public static function toArray( $ipblock ) {
356 if( preg_match( '/^' . RE_IP_ADD
. '(?:\/(?:'.RE_IP_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
358 } else if ( preg_match( '/^' . RE_IPV6_ADD
. '(?:\/(?:'.RE_IPV6_PREFIX
.'))?' . '$/', $ipblock, $matches ) ) {
366 * Return a zero-padded hexadecimal representation of an IP address.
368 * Hexadecimal addresses are used because they can easily be extended to
369 * IPv6 support. To separate the ranges, the return value from this
370 * function for an IPv6 address will be prefixed with "v6-", a non-
371 * hexadecimal string which sorts after the IPv4 addresses.
373 * @param $ip Quad dotted/octet IP address.
374 * @return hexidecimal
376 public static function toHex( $ip ) {
377 $n = self
::toUnsigned( $ip );
378 if ( $n !== false ) {
379 $n = self
::isIPv6($ip) ?
"v6-" . wfBaseConvert( $n, 10, 16, 32, false ) : wfBaseConvert( $n, 10, 16, 8, false );
385 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
386 * Like ip2long() except that it actually works and has a consistent error return value.
387 * Comes from ProxyTools.php
388 * @param $ip Quad dotted IP address.
391 public static function toUnsigned( $ip ) {
392 // Use IPv6 functions if needed
393 if ( self
::isIPv6( $ip ) ) {
394 return self
::toUnsigned6( $ip );
396 if ( $ip == '255.255.255.255' ) {
400 if ( $n == -1 ||
$n === false ) { # Return value on error depends on PHP version
411 * Convert a dotted-quad IP to a signed integer
412 * Returns false on failure
414 public static function toSigned( $ip ) {
415 if ( $ip == '255.255.255.255' ) {
427 * Convert a network specification in CIDR notation to an integer network and a number of bits
428 * @return array(string, int)
430 public static function parseCIDR( $range ) {
431 $parts = explode( '/', $range, 2 );
432 if ( count( $parts ) != 2 ) {
433 return array( false, false );
435 $network = self
::toSigned( $parts[0] );
436 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
441 $network &= ~
((1 << (32 - $bits)) - 1);
443 # Convert to unsigned
444 if ( $network < 0 ) {
445 $network +
= pow( 2, 32 );
451 return array( $network, $bits );
455 * Given a string range in a number of formats, return the start and end of
456 * the range in hexadecimal.
460 * 1.2.3.4 - 1.2.3.5 Explicit range
463 * 2001:0db8:85a3::7344/96 CIDR
464 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
465 * 2001:0db8:85a3::7344 Single IP
466 * @return array(string, int)
468 public static function parseRange( $range ) {
469 // Use IPv6 functions if needed
470 if ( self
::isIPv6( $range ) ) {
471 return self
::parseRange6( $range );
473 if ( strpos( $range, '/' ) !== false ) {
475 list( $network, $bits ) = self
::parseCIDR( $range );
476 if ( $network === false ) {
477 $start = $end = false;
479 $start = sprintf( '%08X', $network );
480 $end = sprintf( '%08X', $network +
pow( 2, (32 - $bits) ) - 1 );
482 } elseif ( strpos( $range, '-' ) !== false ) {
484 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
485 if( self
::isIPAddress( $start ) && self
::isIPAddress( $end ) ) {
486 $start = self
::toUnsigned( $start ); $end = self
::toUnsigned( $end );
487 if ( $start > $end ) {
488 $start = $end = false;
490 $start = sprintf( '%08X', $start );
491 $end = sprintf( '%08X', $end );
494 $start = $end = false;
498 $start = $end = self
::toHex( $range );
500 if ( $start === false ||
$end === false ) {
501 return array( false, false );
503 return array( $start, $end );
508 * Determine if a given IPv4/IPv6 address is in a given CIDR network
509 * @param $addr The address to check against the given range.
510 * @param $range The range to check the given address against.
511 * @return bool Whether or not the given address is in the given range.
513 public static function isInRange( $addr, $range ) {
514 // Convert to IPv6 if needed
515 $hexIP = self
::toHex( $addr );
516 list( $start, $end ) = self
::parseRange( $range );
517 return (strcmp($hexIP, $start) >= 0 &&
518 strcmp($hexIP, $end) <= 0);
522 * Convert some unusual representations of IPv4 addresses to their
523 * canonical dotted quad representation.
525 * This currently only checks a few IPV4-to-IPv6 related cases. More
526 * unusual representations may be added later.
528 * @param $addr something that might be an IP address
529 * @return valid dotted quad IPv4 address or null
531 public static function canonicalize( $addr ) {
532 if ( self
::isValid( $addr ) )
535 // Annoying IPv6 representations like ::ffff:1.2.3.4
536 if ( strpos($addr,':') !==false && strpos($addr,'.') !==false ) {
537 $addr = str_replace( '.', ':', $addr );
538 if( IP
::isIPv6( $addr ) )
542 // IPv6 loopback address
544 if ( preg_match( '/^0*' . RE_IPV6_GAP
. '1$/', $addr, $m ) )
547 // IPv4-mapped and IPv4-compatible IPv6 addresses
548 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. '(' . RE_IP_ADD
. ')$/i', $addr, $m ) )
550 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX
. RE_IPV6_WORD
. ':' . RE_IPV6_WORD
. '$/i', $addr, $m ) )
551 return long2ip( ( hexdec( $m[1] ) << 16 ) +
hexdec( $m[2] ) );
553 return null; // give up