Fixed mistake in r73686 where I wrapped CSS in a JavaScript conditional.
[mediawiki.git] / includes / IP.php
blob5da0afb43f6f4863fe4ae01a0b8baff5596eec74
1 <?php
2 /**
3 * Functions and constants to play with IP addresses and ranges
5 * @file
6 * @author Ashar Voultoiz <hashar at free dot fr>
7 * @license GPL v2 or later
8 */
10 // Some regex definition to "play" with IP address and IP address blocks
12 // An IP is made of 4 bytes from x00 to xFF which is d0 to d255
13 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])' );
14 define( 'RE_IP_ADD' , RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE );
15 // An IPv4 block is an IP address and a prefix (d1 to d32)
16 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)' );
17 define( 'RE_IP_BLOCK', RE_IP_ADD . '\/' . RE_IP_PREFIX );
18 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
19 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
20 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
21 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP . '(?:ffff:)?' );
22 // An IPv6 block is an IP address and a prefix (d1 to d128)
23 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
24 // An IPv6 IP is made up of 8 octets. However abbreviations like "::" can be used.
25 // This is lax! Number of octets/double colons validation not done.
26 define( 'RE_IPV6_ADD',
27 '(' .
28 ':(:' . RE_IPV6_WORD . '){1,7}' . // IPs that start with ":"
29 '|' .
30 RE_IPV6_WORD . '(:{1,2}' . RE_IPV6_WORD . '|::$){1,7}' . // IPs that don't start with ":"
31 ')'
33 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD . '\/' . RE_IPV6_PREFIX );
34 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
35 define( 'IP_ADDRESS_STRING',
36 '(?:' .
37 RE_IP_ADD . '(\/' . RE_IP_PREFIX . '|)' . // IPv4
38 '|' .
39 RE_IPV6_ADD . '(\/' . RE_IPV6_PREFIX . '|)' . // IPv6
40 ')'
43 /**
44 * A collection of public static functions to play with IP address
45 * and IP blocks.
47 class IP {
48 /**
49 * Given a string, determine if it as valid IP
50 * Unlike isValid(), this looks for networks too
51 * @param $ip IP address.
52 * @return string
54 public static function isIPAddress( $ip ) {
55 if ( !$ip ) {
56 return false;
58 if ( is_array( $ip ) ) {
59 throw new MWException( 'invalid value passed to ' . __METHOD__ );
61 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
62 return preg_match( '/^' . IP_ADDRESS_STRING . '$/', $ip ) && ( substr_count( $ip, '::' ) < 2 );
65 public static function isIPv6( $ip ) {
66 if ( !$ip ) {
67 return false;
69 if( is_array( $ip ) ) {
70 throw new MWException( 'invalid value passed to ' . __METHOD__ );
72 $doubleColons = substr_count( $ip, '::' );
73 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
74 return preg_match( '/^' . RE_IPV6_ADD . '(\/' . RE_IPV6_PREFIX . '|)$/', $ip )
75 && ( $doubleColons == 1 || substr_count( $ip, ':' ) == 7 );
78 public static function isIPv4( $ip ) {
79 if ( !$ip ) {
80 return false;
82 return preg_match( '/^' . RE_IP_ADD . '(\/' . RE_IP_PREFIX . '|)$/', $ip);
85 /**
86 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
87 * See http://www.answers.com/topic/ipv4-compatible-address
88 * IPs with the first 92 bits as zeros are reserved from IPv6
89 * @param $ip quad-dotted IP address.
90 * @return string
92 public static function IPv4toIPv6( $ip ) {
93 if ( !$ip ) {
94 return null;
96 // Convert only if needed
97 if ( self::isIPv6( $ip ) ) {
98 return $ip;
100 // IPv4 CIDRs
101 if ( strpos( $ip, '/' ) !== false ) {
102 $parts = explode( '/', $ip, 2 );
103 if ( count( $parts ) != 2 ) {
104 return false;
106 $network = self::toUnsigned( $parts[0] );
107 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
108 $bits = $parts[1] + 96;
109 return self::toOctet( $network ) . "/$bits";
110 } else {
111 return false;
114 return self::toOctet( self::toUnsigned( $ip ) );
118 * Given an IPv6 address in octet notation, returns an unsigned integer.
119 * @param $ip octet ipv6 IP address.
120 * @return string
122 public static function toUnsigned6( $ip ) {
123 if ( !$ip ) {
124 return null;
126 $ip = explode( ':', self::sanitizeIP( $ip ) );
127 $r_ip = '';
128 foreach ( $ip as $v ) {
129 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT );
131 $r_ip = wfBaseConvert( $r_ip, 16, 10 );
132 return $r_ip;
136 * Given an IPv6 address in octet notation, returns the expanded octet.
137 * IPv4 IPs will be trimmed, thats it...
138 * @param $ip octet ipv6 IP address.
139 * @return string
141 public static function sanitizeIP( $ip ) {
142 $ip = trim( $ip );
143 if ( $ip === '' ) {
144 return null;
146 // Trim and return IPv4 addresses
147 if ( self::isIPv4( $ip ) ) {
148 return $ip;
150 // Only IPv6 addresses can be expanded
151 if ( !self::isIPv6( $ip ) ) {
152 return $ip;
154 // Remove any whitespaces, convert to upper case
155 $ip = strtoupper( $ip );
156 // Expand zero abbreviations
157 $abbrevPos = strpos( $ip, '::' );
158 if ( $abbrevPos !== false ) {
159 // If the '::' is at the beginning...
160 if( $abbrevPos == 0 ) {
161 $repeat = '0:';
162 $extra = '';
163 $pad = 9; // 7+2 (due to '::')
164 // If the '::' is at the end...
165 } elseif( $abbrevPos == ( strlen( $ip ) - 2 ) ) {
166 $repeat = ':0';
167 $extra = '';
168 $pad = 9; // 7+2 (due to '::')
169 // If the '::' is at the end...
170 } else {
171 $repeat = ':0';
172 $extra = ':';
173 $pad = 8; // 6+2 (due to '::')
175 $ip = str_replace( '::', str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra, $ip );
177 // Remove leading zereos from each bloc as needed
178 $ip = preg_replace( '/(^|:)0+' . RE_IPV6_WORD . '/', '$1$2', $ip );
179 return $ip;
183 * Given an unsigned integer, returns an IPv6 address in octet notation
184 * @param $ip_int integer IP address.
185 * @return string
187 public static function toOctet( $ip_int ) {
188 // Convert to padded uppercase hex
189 $ip_hex = wfBaseConvert( $ip_int, 10, 16, 32, false );
190 // Separate into 8 octets
191 $ip_oct = substr( $ip_hex, 0, 4 );
192 for ( $n = 1; $n < 8; $n++ ) {
193 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
195 // NO leading zeroes
196 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD . '/', '$1$2', $ip_oct );
197 return $ip_oct;
201 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
203 public static function formatHex( $hex ) {
204 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
205 return self::hexToOctet( $hex );
206 } else {
207 return self::hexToQuad( $hex );
212 * Given a hexadecimal number, returns to an IPv6 address in octet notation
213 * @param $ip_hex string hex IP
214 * @return string
216 public static function hextoOctet( $ip_hex ) {
217 // Convert to padded uppercase hex
218 $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0' );
219 // Separate into 8 octets
220 $ip_oct = substr( $ip_hex, 0, 4 );
221 for ( $n = 1; $n < 8; $n++ ) {
222 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
224 // NO leading zeroes
225 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD . '/', '$1$2', $ip_oct );
226 return $ip_oct;
230 * Converts a hexadecimal number to an IPv4 address in octet notation
231 * @param $ip string Hex IP
232 * @return string
234 public static function hexToQuad( $ip ) {
235 // Converts a hexadecimal IP to nnn.nnn.nnn.nnn format
236 $s = '';
237 for ( $i = 0; $i < 4; $i++ ) {
238 if ( $s !== '' ) {
239 $s .= '.';
241 $s .= base_convert( substr( $ip, $i * 2, 2 ), 16, 10 );
243 return $s;
247 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
248 * @return array(string, int)
250 public static function parseCIDR6( $range ) {
251 # Expand any IPv6 IP
252 $parts = explode( '/', IP::sanitizeIP( $range ), 2 );
253 if ( count( $parts ) != 2 ) {
254 return array( false, false );
256 $network = self::toUnsigned6( $parts[0] );
257 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
258 $bits = $parts[1];
259 if ( $bits == 0 ) {
260 $network = 0;
261 } else {
262 # Native 32 bit functions WONT work here!!!
263 # Convert to a padded binary number
264 $network = wfBaseConvert( $network, 10, 2, 128 );
265 # Truncate the last (128-$bits) bits and replace them with zeros
266 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
267 # Convert back to an integer
268 $network = wfBaseConvert( $network, 2, 10 );
270 } else {
271 $network = false;
272 $bits = false;
274 return array( $network, $bits );
278 * Given a string range in a number of formats, return the start and end of
279 * the range in hexadecimal. For IPv6.
281 * Formats are:
282 * 2001:0db8:85a3::7344/96 CIDR
283 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
284 * 2001:0db8:85a3::7344/96 Single IP
285 * @return array(string, int)
287 public static function parseRange6( $range ) {
288 # Expand any IPv6 IP
289 $range = IP::sanitizeIP( $range );
290 if ( strpos( $range, '/' ) !== false ) {
291 # CIDR
292 list( $network, $bits ) = self::parseCIDR6( $range );
293 if ( $network === false ) {
294 $start = $end = false;
295 } else {
296 $start = wfBaseConvert( $network, 10, 16, 32, false );
297 # Turn network to binary (again)
298 $end = wfBaseConvert( $network, 10, 2, 128 );
299 # Truncate the last (128-$bits) bits and replace them with ones
300 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
301 # Convert to hex
302 $end = wfBaseConvert( $end, 2, 16, 32, false );
303 # see toHex() comment
304 $start = "v6-$start";
305 $end = "v6-$end";
307 } elseif ( strpos( $range, '-' ) !== false ) {
308 # Explicit range
309 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
310 $start = self::toUnsigned6( $start );
311 $end = self::toUnsigned6( $end );
312 if ( $start > $end ) {
313 $start = $end = false;
314 } else {
315 $start = wfBaseConvert( $start, 10, 16, 32, false );
316 $end = wfBaseConvert( $end, 10, 16, 32, false );
318 # see toHex() comment
319 $start = "v6-$start";
320 $end = "v6-$end";
321 } else {
322 # Single IP
323 $start = $end = self::toHex( $range );
325 if ( $start === false || $end === false ) {
326 return array( false, false );
327 } else {
328 return array( $start, $end );
333 * Validate an IP address.
334 * @return boolean True if it is valid.
336 public static function isValid( $ip ) {
337 return ( preg_match( '/^' . RE_IP_ADD . '$/', $ip ) || preg_match( '/^' . RE_IPV6_ADD . '$/', $ip ) );
341 * Validate an IP Block.
342 * @return boolean True if it is valid.
344 public static function isValidBlock( $ipblock ) {
345 return ( count( self::toArray( $ipblock ) ) == 1 + 5 );
349 * Determine if an IP address really is an IP address, and if it is public,
350 * i.e. not RFC 1918 or similar
351 * Comes from ProxyTools.php
353 public static function isPublic( $ip ) {
354 $n = self::toUnsigned( $ip );
355 if ( !$n ) {
356 return false;
359 // ip2long accepts incomplete addresses, as well as some addresses
360 // followed by garbage characters. Check that it's really valid.
361 if( $ip != long2ip( $n ) ) {
362 return false;
365 static $privateRanges = false;
366 if ( !$privateRanges ) {
367 $privateRanges = array(
368 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
369 array( '172.16.0.0', '172.31.255.255' ), # "
370 array( '192.168.0.0', '192.168.255.255' ), # "
371 array( '0.0.0.0', '0.255.255.255' ), # this network
372 array( '127.0.0.0', '127.255.255.255' ), # loopback
376 foreach ( $privateRanges as $r ) {
377 $start = self::toUnsigned( $r[0] );
378 $end = self::toUnsigned( $r[1] );
379 if ( $n >= $start && $n <= $end ) {
380 return false;
383 return true;
387 * Split out an IP block as an array of 4 bytes and a mask,
388 * return false if it can't be determined
390 * @param $ipblock string A quad dotted/octet IP address
391 * @return array
393 public static function toArray( $ipblock ) {
394 $matches = array();
395 if( preg_match( '/^' . RE_IP_ADD . '(?:\/(?:' . RE_IP_PREFIX . '))?' . '$/', $ipblock, $matches ) ) {
396 return $matches;
397 } elseif ( preg_match( '/^' . RE_IPV6_ADD . '(?:\/(?:' . RE_IPV6_PREFIX . '))?' . '$/', $ipblock, $matches ) ) {
398 return $matches;
399 } else {
400 return false;
405 * Return a zero-padded hexadecimal representation of an IP address.
407 * Hexadecimal addresses are used because they can easily be extended to
408 * IPv6 support. To separate the ranges, the return value from this
409 * function for an IPv6 address will be prefixed with "v6-", a non-
410 * hexadecimal string which sorts after the IPv4 addresses.
412 * @param $ip Quad dotted/octet IP address.
413 * @return hexidecimal
415 public static function toHex( $ip ) {
416 $n = self::toUnsigned( $ip );
417 if ( $n !== false ) {
418 $n = self::isIPv6( $ip ) ? 'v6-' . wfBaseConvert( $n, 10, 16, 32, false ) : wfBaseConvert( $n, 10, 16, 8, false );
420 return $n;
424 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
425 * Like ip2long() except that it actually works and has a consistent error return value.
426 * Comes from ProxyTools.php
427 * @param $ip Quad dotted IP address.
428 * @return integer
430 public static function toUnsigned( $ip ) {
431 // Use IPv6 functions if needed
432 if ( self::isIPv6( $ip ) ) {
433 return self::toUnsigned6( $ip );
435 if ( $ip == '255.255.255.255' ) {
436 $n = -1;
437 } else {
438 $n = ip2long( $ip );
439 if ( $n == -1 || $n === false ) { # Return value on error depends on PHP version
440 $n = false;
443 if ( $n < 0 ) {
444 $n += pow( 2, 32 );
446 return $n;
450 * Convert a dotted-quad IP to a signed integer
451 * Returns false on failure
453 public static function toSigned( $ip ) {
454 if ( $ip == '255.255.255.255' ) {
455 $n = -1;
456 } else {
457 $n = ip2long( $ip );
458 if ( $n == -1 ) {
459 $n = false;
462 return $n;
466 * Convert a network specification in CIDR notation to an integer network and a number of bits
467 * @return array(string, int)
469 public static function parseCIDR( $range ) {
470 $parts = explode( '/', $range, 2 );
471 if ( count( $parts ) != 2 ) {
472 return array( false, false );
474 $network = self::toSigned( $parts[0] );
475 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
476 $bits = $parts[1];
477 if ( $bits == 0 ) {
478 $network = 0;
479 } else {
480 $network &= ~( ( 1 << ( 32 - $bits ) ) - 1);
482 # Convert to unsigned
483 if ( $network < 0 ) {
484 $network += pow( 2, 32 );
486 } else {
487 $network = false;
488 $bits = false;
490 return array( $network, $bits );
494 * Given a string range in a number of formats, return the start and end of
495 * the range in hexadecimal.
497 * Formats are:
498 * 1.2.3.4/24 CIDR
499 * 1.2.3.4 - 1.2.3.5 Explicit range
500 * 1.2.3.4 Single IP
502 * 2001:0db8:85a3::7344/96 CIDR
503 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
504 * 2001:0db8:85a3::7344 Single IP
505 * @return array(string, int)
507 public static function parseRange( $range ) {
508 // Use IPv6 functions if needed
509 if ( self::isIPv6( $range ) ) {
510 return self::parseRange6( $range );
512 if ( strpos( $range, '/' ) !== false ) {
513 # CIDR
514 list( $network, $bits ) = self::parseCIDR( $range );
515 if ( $network === false ) {
516 $start = $end = false;
517 } else {
518 $start = sprintf( '%08X', $network );
519 $end = sprintf( '%08X', $network + pow( 2, ( 32 - $bits ) ) - 1 );
521 } elseif ( strpos( $range, '-' ) !== false ) {
522 # Explicit range
523 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
524 if( self::isIPAddress( $start ) && self::isIPAddress( $end ) ) {
525 $start = self::toUnsigned( $start );
526 $end = self::toUnsigned( $end );
527 if ( $start > $end ) {
528 $start = $end = false;
529 } else {
530 $start = sprintf( '%08X', $start );
531 $end = sprintf( '%08X', $end );
533 } else {
534 $start = $end = false;
536 } else {
537 # Single IP
538 $start = $end = self::toHex( $range );
540 if ( $start === false || $end === false ) {
541 return array( false, false );
542 } else {
543 return array( $start, $end );
548 * Determine if a given IPv4/IPv6 address is in a given CIDR network
549 * @param $addr The address to check against the given range.
550 * @param $range The range to check the given address against.
551 * @return bool Whether or not the given address is in the given range.
553 public static function isInRange( $addr, $range ) {
554 // Convert to IPv6 if needed
555 $hexIP = self::toHex( $addr );
556 list( $start, $end ) = self::parseRange( $range );
557 return ( strcmp( $hexIP, $start ) >= 0 &&
558 strcmp( $hexIP, $end ) <= 0 );
562 * Convert some unusual representations of IPv4 addresses to their
563 * canonical dotted quad representation.
565 * This currently only checks a few IPV4-to-IPv6 related cases. More
566 * unusual representations may be added later.
568 * @param $addr something that might be an IP address
569 * @return valid dotted quad IPv4 address or null
571 public static function canonicalize( $addr ) {
572 if ( self::isValid( $addr ) ) {
573 return $addr;
576 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
577 if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
578 $addr = substr( $addr, strrpos( $addr, ':' ) + 1 );
579 if( self::isIPv4( $addr ) ) {
580 return $addr;
584 // IPv6 loopback address
585 $m = array();
586 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) ) {
587 return '127.0.0.1';
590 // IPv4-mapped and IPv4-compatible IPv6 addresses
591 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) ) {
592 return $m[1];
594 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD . ':' . RE_IPV6_WORD . '$/i', $addr, $m ) ) {
595 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
598 return null; // give up