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