* Standardised file description headers
[lhc/web/wiklou.git] / includes / IP.php
1 <?php
2 /**
3 * Functions and constants to play with IP addresses and ranges
4 *
5 * @file
6 * @author "Ashar Voultoiz" <hashar@altern.org>
7 * @license GPL v2 or later
8 */
9
10 // Some regex definition to "play" with IP address and IP address blocks
11
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 ')'
32 );
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 ')'
41 );
42
43 /**
44 * A collection of public static functions to play with IP address
45 * and IP blocks.
46 */
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
53 */
54 public static function isIPAddress( $ip ) {
55 if ( !$ip ) return false;
56 if ( is_array( $ip ) ) {
57 throw new MWException( "invalid value passed to " . __METHOD__ );
58 }
59 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
60 return preg_match( '/^' . IP_ADDRESS_STRING . '$/', $ip) && ( substr_count($ip, '::') < 2 );
61 }
62
63 public static function isIPv6( $ip ) {
64 if ( !$ip ) return false;
65 if( is_array( $ip ) ) {
66 throw new MWException( "invalid value passed to " . __METHOD__ );
67 }
68 $doubleColons = substr_count($ip, '::');
69 // IPv6 IPs with two "::" strings are ambiguous and thus invalid
70 return preg_match( '/^' . RE_IPV6_ADD . '(\/' . RE_IPV6_PREFIX . '|)$/', $ip)
71 && ( $doubleColons == 1 || substr_count($ip,':') == 7 );
72 }
73
74 public static function isIPv4( $ip ) {
75 if ( !$ip ) return false;
76 return preg_match( '/^' . RE_IP_ADD . '(\/' . RE_IP_PREFIX . '|)$/', $ip);
77 }
78
79 /**
80 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
81 * See http://www.answers.com/topic/ipv4-compatible-address
82 * IPs with the first 92 bits as zeros are reserved from IPv6
83 * @param $ip quad-dotted IP address.
84 * @return string
85 */
86 public static function IPv4toIPv6( $ip ) {
87 if ( !$ip ) return null;
88 // Convert only if needed
89 if ( self::isIPv6( $ip ) ) return $ip;
90 // IPv4 CIDRs
91 if ( strpos( $ip, '/' ) !== false ) {
92 $parts = explode( '/', $ip, 2 );
93 if ( count( $parts ) != 2 ) {
94 return false;
95 }
96 $network = self::toUnsigned( $parts[0] );
97 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
98 $bits = $parts[1] + 96;
99 return self::toOctet( $network ) . "/$bits";
100 } else {
101 return false;
102 }
103 }
104 return self::toOctet( self::toUnsigned( $ip ) );
105 }
106
107 /**
108 * Given an IPv6 address in octet notation, returns an unsigned integer.
109 * @param $ip octet ipv6 IP address.
110 * @return string
111 */
112 public static function toUnsigned6( $ip ) {
113 if ( !$ip ) return null;
114 $ip = explode(':', self::sanitizeIP( $ip ) );
115 $r_ip = '';
116 foreach ($ip as $v) {
117 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT );
118 }
119 $r_ip = wfBaseConvert( $r_ip, 16, 10 );
120 return $r_ip;
121 }
122
123 /**
124 * Given an IPv6 address in octet notation, returns the expanded octet.
125 * IPv4 IPs will be trimmed, thats it...
126 * @param $ip octet ipv6 IP address.
127 * @return string
128 */
129 public static function sanitizeIP( $ip ) {
130 $ip = trim( $ip );
131 if ( $ip === '' ) return null;
132 // Trim and return IPv4 addresses
133 if ( self::isIPv4($ip) ) return $ip;
134 // Only IPv6 addresses can be expanded
135 if ( !self::isIPv6($ip) ) return $ip;
136 // Remove any whitespaces, convert to upper case
137 $ip = strtoupper( $ip );
138 // Expand zero abbreviations
139 $abbrevPos = strpos( $ip, '::' );
140 if ( $abbrevPos !== false ) {
141 // If the '::' is at the beginning...
142 if( $abbrevPos == 0 ) {
143 $repeat = '0:'; $extra = ''; $pad = 9; // 7+2 (due to '::')
144 // If the '::' is at the end...
145 } else if( $abbrevPos == (strlen($ip)-2) ) {
146 $repeat = ':0'; $extra = ''; $pad = 9; // 7+2 (due to '::')
147 // If the '::' is at the end...
148 } else {
149 $repeat = ':0'; $extra = ':'; $pad = 8; // 6+2 (due to '::')
150 }
151 $ip = str_replace('::', str_repeat($repeat, $pad-substr_count($ip,':')).$extra, $ip);
152 }
153 // Remove leading zereos from each bloc as needed
154 $ip = preg_replace( '/(^|:)0+' . RE_IPV6_WORD . '/', '$1$2', $ip );
155 return $ip;
156 }
157
158 /**
159 * Given an unsigned integer, returns an IPv6 address in octet notation
160 * @param $ip_int integer IP address.
161 * @return string
162 */
163 public static function toOctet( $ip_int ) {
164 // Convert to padded uppercase hex
165 $ip_hex = wfBaseConvert($ip_int, 10, 16, 32, false);
166 // Separate into 8 octets
167 $ip_oct = substr( $ip_hex, 0, 4 );
168 for ($n=1; $n < 8; $n++) {
169 $ip_oct .= ':' . substr($ip_hex, 4*$n, 4);
170 }
171 // NO leading zeroes
172 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD . '/', '$1$2', $ip_oct );
173 return $ip_oct;
174 }
175
176 /**
177 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
178 */
179 public static function formatHex( $hex ) {
180 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
181 return self::hexToOctet( $hex );
182 } else {
183 return self::hexToQuad( $hex );
184 }
185 }
186
187 /**
188 * Given a hexadecimal number, returns to an IPv6 address in octet notation
189 * @param $ip_hex string hex IP
190 * @return string
191 */
192 public static function hextoOctet( $ip_hex ) {
193 // Convert to padded uppercase hex
194 $ip_hex = str_pad( strtoupper($ip_hex), 32, '0');
195 // Separate into 8 octets
196 $ip_oct = substr( $ip_hex, 0, 4 );
197 for ($n=1; $n < 8; $n++) {
198 $ip_oct .= ':' . substr($ip_hex, 4*$n, 4);
199 }
200 // NO leading zeroes
201 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD . '/', '$1$2', $ip_oct );
202 return $ip_oct;
203 }
204
205 /**
206 * Converts a hexadecimal number to an IPv4 address in octet notation
207 * @param $ip string Hex IP
208 * @return string
209 */
210 public static function hexToQuad( $ip ) {
211 // Converts a hexadecimal IP to nnn.nnn.nnn.nnn format
212 $s = '';
213 for ( $i = 0; $i < 4; $i++ ) {
214 if ( $s !== '' ) {
215 $s .= '.';
216 }
217 $s .= base_convert( substr( $ip, $i * 2, 2 ), 16, 10 );
218 }
219 return $s;
220 }
221
222 /**
223 * Convert a network specification in IPv6 CIDR notation to an integer network and a number of bits
224 * @return array(string, int)
225 */
226 public static function parseCIDR6( $range ) {
227 # Expand any IPv6 IP
228 $parts = explode( '/', IP::sanitizeIP( $range ), 2 );
229 if ( count( $parts ) != 2 ) {
230 return array( false, false );
231 }
232 $network = self::toUnsigned6( $parts[0] );
233 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 128 ) {
234 $bits = $parts[1];
235 if ( $bits == 0 ) {
236 $network = 0;
237 } else {
238 # Native 32 bit functions WONT work here!!!
239 # Convert to a padded binary number
240 $network = wfBaseConvert( $network, 10, 2, 128 );
241 # Truncate the last (128-$bits) bits and replace them with zeros
242 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
243 # Convert back to an integer
244 $network = wfBaseConvert( $network, 2, 10 );
245 }
246 } else {
247 $network = false;
248 $bits = false;
249 }
250 return array( $network, $bits );
251 }
252
253 /**
254 * Given a string range in a number of formats, return the start and end of
255 * the range in hexadecimal. For IPv6.
256 *
257 * Formats are:
258 * 2001:0db8:85a3::7344/96 CIDR
259 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
260 * 2001:0db8:85a3::7344/96 Single IP
261 * @return array(string, int)
262 */
263 public static function parseRange6( $range ) {
264 # Expand any IPv6 IP
265 $range = IP::sanitizeIP( $range );
266 if ( strpos( $range, '/' ) !== false ) {
267 # CIDR
268 list( $network, $bits ) = self::parseCIDR6( $range );
269 if ( $network === false ) {
270 $start = $end = false;
271 } else {
272 $start = wfBaseConvert( $network, 10, 16, 32, false );
273 # Turn network to binary (again)
274 $end = wfBaseConvert( $network, 10, 2, 128 );
275 # Truncate the last (128-$bits) bits and replace them with ones
276 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
277 # Convert to hex
278 $end = wfBaseConvert( $end, 2, 16, 32, false );
279 # see toHex() comment
280 $start = "v6-$start"; $end = "v6-$end";
281 }
282 } elseif ( strpos( $range, '-' ) !== false ) {
283 # Explicit range
284 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
285 $start = self::toUnsigned6( $start ); $end = self::toUnsigned6( $end );
286 if ( $start > $end ) {
287 $start = $end = false;
288 } else {
289 $start = wfBaseConvert( $start, 10, 16, 32, false );
290 $end = wfBaseConvert( $end, 10, 16, 32, false );
291 }
292 # see toHex() comment
293 $start = "v6-$start"; $end = "v6-$end";
294 } else {
295 # Single IP
296 $start = $end = self::toHex( $range );
297 }
298 if ( $start === false || $end === false ) {
299 return array( false, false );
300 } else {
301 return array( $start, $end );
302 }
303 }
304
305 /**
306 * Validate an IP address.
307 * @return boolean True if it is valid.
308 */
309 public static function isValid( $ip ) {
310 return ( preg_match( '/^' . RE_IP_ADD . '$/', $ip) || preg_match( '/^' . RE_IPV6_ADD . '$/', $ip) );
311 }
312
313 /**
314 * Validate an IP Block.
315 * @return boolean True if it is valid.
316 */
317 public static function isValidBlock( $ipblock ) {
318 return ( count(self::toArray($ipblock)) == 1 + 5 );
319 }
320
321 /**
322 * Determine if an IP address really is an IP address, and if it is public,
323 * i.e. not RFC 1918 or similar
324 * Comes from ProxyTools.php
325 */
326 public static function isPublic( $ip ) {
327 $n = self::toUnsigned( $ip );
328 if ( !$n ) {
329 return false;
330 }
331
332 // ip2long accepts incomplete addresses, as well as some addresses
333 // followed by garbage characters. Check that it's really valid.
334 if( $ip != long2ip( $n ) ) {
335 return false;
336 }
337
338 static $privateRanges = false;
339 if ( !$privateRanges ) {
340 $privateRanges = array(
341 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
342 array( '172.16.0.0', '172.31.255.255' ), # "
343 array( '192.168.0.0', '192.168.255.255' ), # "
344 array( '0.0.0.0', '0.255.255.255' ), # this network
345 array( '127.0.0.0', '127.255.255.255' ), # loopback
346 );
347 }
348
349 foreach ( $privateRanges as $r ) {
350 $start = self::toUnsigned( $r[0] );
351 $end = self::toUnsigned( $r[1] );
352 if ( $n >= $start && $n <= $end ) {
353 return false;
354 }
355 }
356 return true;
357 }
358
359 /**
360 * Split out an IP block as an array of 4 bytes and a mask,
361 * return false if it can't be determined
362 *
363 * @param $ipblock string A quad dotted/octet IP address
364 * @return array
365 */
366 public static function toArray( $ipblock ) {
367 $matches = array();
368 if( preg_match( '/^' . RE_IP_ADD . '(?:\/(?:'.RE_IP_PREFIX.'))?' . '$/', $ipblock, $matches ) ) {
369 return $matches;
370 } else if ( preg_match( '/^' . RE_IPV6_ADD . '(?:\/(?:'.RE_IPV6_PREFIX.'))?' . '$/', $ipblock, $matches ) ) {
371 return $matches;
372 } else {
373 return false;
374 }
375 }
376
377 /**
378 * Return a zero-padded hexadecimal representation of an IP address.
379 *
380 * Hexadecimal addresses are used because they can easily be extended to
381 * IPv6 support. To separate the ranges, the return value from this
382 * function for an IPv6 address will be prefixed with "v6-", a non-
383 * hexadecimal string which sorts after the IPv4 addresses.
384 *
385 * @param $ip Quad dotted/octet IP address.
386 * @return hexidecimal
387 */
388 public static function toHex( $ip ) {
389 $n = self::toUnsigned( $ip );
390 if ( $n !== false ) {
391 $n = self::isIPv6($ip) ? "v6-" . wfBaseConvert( $n, 10, 16, 32, false ) : wfBaseConvert( $n, 10, 16, 8, false );
392 }
393 return $n;
394 }
395
396 /**
397 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
398 * Like ip2long() except that it actually works and has a consistent error return value.
399 * Comes from ProxyTools.php
400 * @param $ip Quad dotted IP address.
401 * @return integer
402 */
403 public static function toUnsigned( $ip ) {
404 // Use IPv6 functions if needed
405 if ( self::isIPv6( $ip ) ) {
406 return self::toUnsigned6( $ip );
407 }
408 if ( $ip == '255.255.255.255' ) {
409 $n = -1;
410 } else {
411 $n = ip2long( $ip );
412 if ( $n == -1 || $n === false ) { # Return value on error depends on PHP version
413 $n = false;
414 }
415 }
416 if ( $n < 0 ) {
417 $n += pow( 2, 32 );
418 }
419 return $n;
420 }
421
422 /**
423 * Convert a dotted-quad IP to a signed integer
424 * Returns false on failure
425 */
426 public static function toSigned( $ip ) {
427 if ( $ip == '255.255.255.255' ) {
428 $n = -1;
429 } else {
430 $n = ip2long( $ip );
431 if ( $n == -1 ) {
432 $n = false;
433 }
434 }
435 return $n;
436 }
437
438 /**
439 * Convert a network specification in CIDR notation to an integer network and a number of bits
440 * @return array(string, int)
441 */
442 public static function parseCIDR( $range ) {
443 $parts = explode( '/', $range, 2 );
444 if ( count( $parts ) != 2 ) {
445 return array( false, false );
446 }
447 $network = self::toSigned( $parts[0] );
448 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
449 $bits = $parts[1];
450 if ( $bits == 0 ) {
451 $network = 0;
452 } else {
453 $network &= ~((1 << (32 - $bits)) - 1);
454 }
455 # Convert to unsigned
456 if ( $network < 0 ) {
457 $network += pow( 2, 32 );
458 }
459 } else {
460 $network = false;
461 $bits = false;
462 }
463 return array( $network, $bits );
464 }
465
466 /**
467 * Given a string range in a number of formats, return the start and end of
468 * the range in hexadecimal.
469 *
470 * Formats are:
471 * 1.2.3.4/24 CIDR
472 * 1.2.3.4 - 1.2.3.5 Explicit range
473 * 1.2.3.4 Single IP
474 *
475 * 2001:0db8:85a3::7344/96 CIDR
476 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
477 * 2001:0db8:85a3::7344 Single IP
478 * @return array(string, int)
479 */
480 public static function parseRange( $range ) {
481 // Use IPv6 functions if needed
482 if ( self::isIPv6( $range ) ) {
483 return self::parseRange6( $range );
484 }
485 if ( strpos( $range, '/' ) !== false ) {
486 # CIDR
487 list( $network, $bits ) = self::parseCIDR( $range );
488 if ( $network === false ) {
489 $start = $end = false;
490 } else {
491 $start = sprintf( '%08X', $network );
492 $end = sprintf( '%08X', $network + pow( 2, (32 - $bits) ) - 1 );
493 }
494 } elseif ( strpos( $range, '-' ) !== false ) {
495 # Explicit range
496 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
497 if( self::isIPAddress( $start ) && self::isIPAddress( $end ) ) {
498 $start = self::toUnsigned( $start ); $end = self::toUnsigned( $end );
499 if ( $start > $end ) {
500 $start = $end = false;
501 } else {
502 $start = sprintf( '%08X', $start );
503 $end = sprintf( '%08X', $end );
504 }
505 } else {
506 $start = $end = false;
507 }
508 } else {
509 # Single IP
510 $start = $end = self::toHex( $range );
511 }
512 if ( $start === false || $end === false ) {
513 return array( false, false );
514 } else {
515 return array( $start, $end );
516 }
517 }
518
519 /**
520 * Determine if a given IPv4/IPv6 address is in a given CIDR network
521 * @param $addr The address to check against the given range.
522 * @param $range The range to check the given address against.
523 * @return bool Whether or not the given address is in the given range.
524 */
525 public static function isInRange( $addr, $range ) {
526 // Convert to IPv6 if needed
527 $hexIP = self::toHex( $addr );
528 list( $start, $end ) = self::parseRange( $range );
529 return (strcmp($hexIP, $start) >= 0 &&
530 strcmp($hexIP, $end) <= 0);
531 }
532
533 /**
534 * Convert some unusual representations of IPv4 addresses to their
535 * canonical dotted quad representation.
536 *
537 * This currently only checks a few IPV4-to-IPv6 related cases. More
538 * unusual representations may be added later.
539 *
540 * @param $addr something that might be an IP address
541 * @return valid dotted quad IPv4 address or null
542 */
543 public static function canonicalize( $addr ) {
544 if ( self::isValid( $addr ) )
545 return $addr;
546
547 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
548 if ( strpos($addr,':') !==false && strpos($addr,'.') !==false ) {
549 $addr = substr( $addr, strrpos($addr,':')+1 );
550 if( self::isIPv4($addr) ) return $addr;
551 }
552
553 // IPv6 loopback address
554 $m = array();
555 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) )
556 return '127.0.0.1';
557
558 // IPv4-mapped and IPv4-compatible IPv6 addresses
559 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) )
560 return $m[1];
561 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD . ':' . RE_IPV6_WORD . '$/i', $addr, $m ) )
562 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
563
564 return null; // give up
565 }
566 }