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