Move the DeferredUpdates hierarchy to its own directory
[lhc/web/wiklou.git] / includes / IP.php
1 <?php
2 /**
3 * Functions and constants to play with IP addresses and ranges
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Antoine Musso "<hashar at free dot fr>", Aaron Schulz
22 */
23
24 // Some regex definition to "play" with IP address and IP address blocks
25
26 // An IPv4 address is made of 4 bytes from x00 to xFF which is d0 to d255
27 define( 'RE_IP_BYTE', '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])' );
28 define( 'RE_IP_ADD', RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE );
29 // An IPv4 block is an IP address and a prefix (d1 to d32)
30 define( 'RE_IP_PREFIX', '(3[0-2]|[12]?\d)' );
31 define( 'RE_IP_BLOCK', RE_IP_ADD . '\/' . RE_IP_PREFIX );
32
33 // An IPv6 address is made up of 8 words (each x0000 to xFFFF).
34 // However, the "::" abbreviation can be used on consecutive x0000 words.
35 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
36 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)' );
37 define( 'RE_IPV6_ADD',
38 '(?:' . // starts with "::" (including "::")
39 ':(?::|(?::' . RE_IPV6_WORD . '){1,7})' .
40 '|' . // ends with "::" (except "::")
41 RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){0,6}::' .
42 '|' . // contains one "::" in the middle (the ^ makes the test fail if none found)
43 RE_IPV6_WORD . '(?::((?(-1)|:))?' . RE_IPV6_WORD . '){1,6}(?(-2)|^)' .
44 '|' . // contains no "::"
45 RE_IPV6_WORD . '(?::' . RE_IPV6_WORD . '){7}' .
46 ')'
47 );
48 // An IPv6 block is an IP address and a prefix (d1 to d128)
49 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD . '\/' . RE_IPV6_PREFIX );
50 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
51 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
52 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP . '(?:ffff:)?' );
53
54 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
55 define( 'IP_ADDRESS_STRING',
56 '(?:' .
57 RE_IP_ADD . '(?:\/' . RE_IP_PREFIX . ')?' . // IPv4
58 '|' .
59 RE_IPV6_ADD . '(?:\/' . RE_IPV6_PREFIX . ')?' . // IPv6
60 ')'
61 );
62
63 /**
64 * A collection of public static functions to play with IP address
65 * and IP blocks.
66 */
67 class IP {
68 /**
69 * Determine if a string is as valid IP address or network (CIDR prefix).
70 * SIIT IPv4-translated addresses are rejected.
71 * Note: canonicalize() tries to convert translated addresses to IPv4.
72 *
73 * @param string $ip possible IP address
74 * @return Boolean
75 */
76 public static function isIPAddress( $ip ) {
77 return (bool)preg_match( '/^' . IP_ADDRESS_STRING . '$/', $ip );
78 }
79
80 /**
81 * Given a string, determine if it as valid IP in IPv6 only.
82 * Note: Unlike isValid(), this looks for networks too.
83 *
84 * @param string $ip possible IP address
85 * @return Boolean
86 */
87 public static function isIPv6( $ip ) {
88 return (bool)preg_match( '/^' . RE_IPV6_ADD . '(?:\/' . RE_IPV6_PREFIX . ')?$/', $ip );
89 }
90
91 /**
92 * Given a string, determine if it as valid IP in IPv4 only.
93 * Note: Unlike isValid(), this looks for networks too.
94 *
95 * @param string $ip possible IP address
96 * @return Boolean
97 */
98 public static function isIPv4( $ip ) {
99 return (bool)preg_match( '/^' . RE_IP_ADD . '(?:\/' . RE_IP_PREFIX . ')?$/', $ip );
100 }
101
102 /**
103 * Validate an IP address. Ranges are NOT considered valid.
104 * SIIT IPv4-translated addresses are rejected.
105 * Note: canonicalize() tries to convert translated addresses to IPv4.
106 *
107 * @param $ip String
108 * @return Boolean: True if it is valid.
109 */
110 public static function isValid( $ip ) {
111 return ( preg_match( '/^' . RE_IP_ADD . '$/', $ip )
112 || preg_match( '/^' . RE_IPV6_ADD . '$/', $ip ) );
113 }
114
115 /**
116 * Validate an IP Block (valid address WITH a valid prefix).
117 * SIIT IPv4-translated addresses are rejected.
118 * Note: canonicalize() tries to convert translated addresses to IPv4.
119 *
120 * @param $ipblock String
121 * @return Boolean: True if it is valid.
122 */
123 public static function isValidBlock( $ipblock ) {
124 return ( preg_match( '/^' . RE_IPV6_BLOCK . '$/', $ipblock )
125 || preg_match( '/^' . RE_IP_BLOCK . '$/', $ipblock ) );
126 }
127
128 /**
129 * Convert an IP into a verbose, uppercase, normalized form.
130 * IPv6 addresses in octet notation are expanded to 8 words.
131 * IPv4 addresses are just trimmed.
132 *
133 * @param string $ip IP address in quad or octet form (CIDR or not).
134 * @return String
135 */
136 public static function sanitizeIP( $ip ) {
137 $ip = trim( $ip );
138 if ( $ip === '' ) {
139 return null;
140 }
141 if ( self::isIPv4( $ip ) || !self::isIPv6( $ip ) ) {
142 return $ip; // nothing else to do for IPv4 addresses or invalid ones
143 }
144 // Remove any whitespaces, convert to upper case
145 $ip = strtoupper( $ip );
146 // Expand zero abbreviations
147 $abbrevPos = strpos( $ip, '::' );
148 if ( $abbrevPos !== false ) {
149 // We know this is valid IPv6. Find the last index of the
150 // address before any CIDR number (e.g. "a:b:c::/24").
151 $CIDRStart = strpos( $ip, "/" );
152 $addressEnd = ( $CIDRStart !== false )
153 ? $CIDRStart - 1
154 : strlen( $ip ) - 1;
155 // If the '::' is at the beginning...
156 if ( $abbrevPos == 0 ) {
157 $repeat = '0:';
158 $extra = ( $ip == '::' ) ? '0' : ''; // for the address '::'
159 $pad = 9; // 7+2 (due to '::')
160 // If the '::' is at the end...
161 } elseif ( $abbrevPos == ( $addressEnd - 1 ) ) {
162 $repeat = ':0';
163 $extra = '';
164 $pad = 9; // 7+2 (due to '::')
165 // If the '::' is in the middle...
166 } else {
167 $repeat = ':0';
168 $extra = ':';
169 $pad = 8; // 6+2 (due to '::')
170 }
171 $ip = str_replace( '::',
172 str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra,
173 $ip
174 );
175 }
176 // Remove leading zeros from each bloc as needed
177 $ip = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD . ')/', '$1$2', $ip );
178 return $ip;
179 }
180
181 /**
182 * Prettify an IP for display to end users.
183 * This will make it more compact and lower-case.
184 *
185 * @param $ip string
186 * @return string
187 */
188 public static function prettifyIP( $ip ) {
189 $ip = self::sanitizeIP( $ip ); // normalize (removes '::')
190 if ( self::isIPv6( $ip ) ) {
191 // Split IP into an address and a CIDR
192 if ( strpos( $ip, '/' ) !== false ) {
193 list( $ip, $cidr ) = explode( '/', $ip, 2 );
194 } else {
195 list( $ip, $cidr ) = array( $ip, '' );
196 }
197 // Get the largest slice of words with multiple zeros
198 $offset = 0;
199 $longest = $longestPos = false;
200 while ( preg_match(
201 '!(?:^|:)0(?::0)+(?:$|:)!', $ip, $m, PREG_OFFSET_CAPTURE, $offset
202 ) ) {
203 list( $match, $pos ) = $m[0]; // full match
204 if ( strlen( $match ) > strlen( $longest ) ) {
205 $longest = $match;
206 $longestPos = $pos;
207 }
208 $offset = ( $pos + strlen( $match ) ); // advance
209 }
210 if ( $longest !== false ) {
211 // Replace this portion of the string with the '::' abbreviation
212 $ip = substr_replace( $ip, '::', $longestPos, strlen( $longest ) );
213 }
214 // Add any CIDR back on
215 if ( $cidr !== '' ) {
216 $ip = "{$ip}/{$cidr}";
217 }
218 // Convert to lower case to make it more readable
219 $ip = strtolower( $ip );
220 }
221 return $ip;
222 }
223
224 /**
225 * Given a host/port string, like one might find in the host part of a URL
226 * per RFC 2732, split the hostname part and the port part and return an
227 * array with an element for each. If there is no port part, the array will
228 * have false in place of the port. If the string was invalid in some way,
229 * false is returned.
230 *
231 * This was easy with IPv4 and was generally done in an ad-hoc way, but
232 * with IPv6 it's somewhat more complicated due to the need to parse the
233 * square brackets and colons.
234 *
235 * A bare IPv6 address is accepted despite the lack of square brackets.
236 *
237 * @param string $both The string with the host and port
238 * @return array
239 */
240 public static function splitHostAndPort( $both ) {
241 if ( substr( $both, 0, 1 ) === '[' ) {
242 if ( preg_match( '/^\[(' . RE_IPV6_ADD . ')\](?::(?P<port>\d+))?$/', $both, $m ) ) {
243 if ( isset( $m['port'] ) ) {
244 return array( $m[1], intval( $m['port'] ) );
245 } else {
246 return array( $m[1], false );
247 }
248 } else {
249 // Square bracket found but no IPv6
250 return false;
251 }
252 }
253 $numColons = substr_count( $both, ':' );
254 if ( $numColons >= 2 ) {
255 // Is it a bare IPv6 address?
256 if ( preg_match( '/^' . RE_IPV6_ADD . '$/', $both ) ) {
257 return array( $both, false );
258 } else {
259 // Not valid IPv6, but too many colons for anything else
260 return false;
261 }
262 }
263 if ( $numColons >= 1 ) {
264 // Host:port?
265 $bits = explode( ':', $both );
266 if ( preg_match( '/^\d+/', $bits[1] ) ) {
267 return array( $bits[0], intval( $bits[1] ) );
268 } else {
269 // Not a valid port
270 return false;
271 }
272 }
273 // Plain hostname
274 return array( $both, false );
275 }
276
277 /**
278 * Given a host name and a port, combine them into host/port string like
279 * you might find in a URL. If the host contains a colon, wrap it in square
280 * brackets like in RFC 2732. If the port matches the default port, omit
281 * the port specification
282 *
283 * @param $host string
284 * @param $port int
285 * @param $defaultPort bool|int
286 * @return string
287 */
288 public static function combineHostAndPort( $host, $port, $defaultPort = false ) {
289 if ( strpos( $host, ':' ) !== false ) {
290 $host = "[$host]";
291 }
292 if ( $defaultPort !== false && $port == $defaultPort ) {
293 return $host;
294 } else {
295 return "$host:$port";
296 }
297 }
298
299 /**
300 * Given an unsigned integer, returns an IPv6 address in octet notation
301 *
302 * @param $ip_int String: IP address.
303 * @return String
304 */
305 public static function toOctet( $ip_int ) {
306 return self::hexToOctet( wfBaseConvert( $ip_int, 10, 16, 32, false ) );
307 }
308
309 /**
310 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
311 *
312 * @param string $hex number, with "v6-" prefix if it is IPv6
313 * @return String: quad-dotted (IPv4) or octet notation (IPv6)
314 */
315 public static function formatHex( $hex ) {
316 if ( substr( $hex, 0, 3 ) == 'v6-' ) { // IPv6
317 return self::hexToOctet( substr( $hex, 3 ) );
318 } else { // IPv4
319 return self::hexToQuad( $hex );
320 }
321 }
322
323 /**
324 * Converts a hexadecimal number to an IPv6 address in octet notation
325 *
326 * @param $ip_hex String: pure hex (no v6- prefix)
327 * @return String (of format a:b:c:d:e:f:g:h)
328 */
329 public static function hexToOctet( $ip_hex ) {
330 // Pad hex to 32 chars (128 bits)
331 $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0', STR_PAD_LEFT );
332 // Separate into 8 words
333 $ip_oct = substr( $ip_hex, 0, 4 );
334 for ( $n = 1; $n < 8; $n++ ) {
335 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
336 }
337 // NO leading zeroes
338 $ip_oct = preg_replace( '/(^|:)0+(' . RE_IPV6_WORD . ')/', '$1$2', $ip_oct );
339 return $ip_oct;
340 }
341
342 /**
343 * Converts a hexadecimal number to an IPv4 address in quad-dotted notation
344 *
345 * @param $ip_hex String: pure hex
346 * @return String (of format a.b.c.d)
347 */
348 public static function hexToQuad( $ip_hex ) {
349 // Pad hex to 8 chars (32 bits)
350 $ip_hex = str_pad( strtoupper( $ip_hex ), 8, '0', STR_PAD_LEFT );
351 // Separate into four quads
352 $s = '';
353 for ( $i = 0; $i < 4; $i++ ) {
354 if ( $s !== '' ) {
355 $s .= '.';
356 }
357 $s .= base_convert( substr( $ip_hex, $i * 2, 2 ), 16, 10 );
358 }
359 return $s;
360 }
361
362 /**
363 * Determine if an IP address really is an IP address, and if it is public,
364 * i.e. not RFC 1918 or similar
365 * Comes from ProxyTools.php
366 *
367 * @param $ip String
368 * @return Boolean
369 */
370 public static function isPublic( $ip ) {
371 if ( self::isIPv6( $ip ) ) {
372 return self::isPublic6( $ip );
373 }
374 $n = self::toUnsigned( $ip );
375 if ( !$n ) {
376 return false;
377 }
378
379 // ip2long accepts incomplete addresses, as well as some addresses
380 // followed by garbage characters. Check that it's really valid.
381 if ( $ip != long2ip( $n ) ) {
382 return false;
383 }
384
385 static $privateRanges = false;
386 if ( !$privateRanges ) {
387 $privateRanges = array(
388 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
389 array( '172.16.0.0', '172.31.255.255' ), # RFC 1918 (private)
390 array( '192.168.0.0', '192.168.255.255' ), # RFC 1918 (private)
391 array( '0.0.0.0', '0.255.255.255' ), # this network
392 array( '127.0.0.0', '127.255.255.255' ), # loopback
393 );
394 }
395
396 foreach ( $privateRanges as $r ) {
397 $start = self::toUnsigned( $r[0] );
398 $end = self::toUnsigned( $r[1] );
399 if ( $n >= $start && $n <= $end ) {
400 return false;
401 }
402 }
403 return true;
404 }
405
406 /**
407 * Determine if an IPv6 address really is an IP address, and if it is public,
408 * i.e. not RFC 4193 or similar
409 *
410 * @param $ip String
411 * @return Boolean
412 */
413 private static function isPublic6( $ip ) {
414 static $privateRanges = false;
415 if ( !$privateRanges ) {
416 $privateRanges = array(
417 array( 'fc00::', 'fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' ), # RFC 4193 (local)
418 array( '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1' ), # loopback
419 );
420 }
421 $n = self::toHex( $ip );
422 foreach ( $privateRanges as $r ) {
423 $start = self::toHex( $r[0] );
424 $end = self::toHex( $r[1] );
425 if ( $n >= $start && $n <= $end ) {
426 return false;
427 }
428 }
429 return true;
430 }
431
432 /**
433 * Return a zero-padded upper case hexadecimal representation of an IP address.
434 *
435 * Hexadecimal addresses are used because they can easily be extended to
436 * IPv6 support. To separate the ranges, the return value from this
437 * function for an IPv6 address will be prefixed with "v6-", a non-
438 * hexadecimal string which sorts after the IPv4 addresses.
439 *
440 * @param string $ip quad dotted/octet IP address.
441 * @return String
442 */
443 public static function toHex( $ip ) {
444 if ( self::isIPv6( $ip ) ) {
445 $n = 'v6-' . self::IPv6ToRawHex( $ip );
446 } else {
447 $n = self::toUnsigned( $ip );
448 if ( $n !== false ) {
449 $n = wfBaseConvert( $n, 10, 16, 8, false );
450 }
451 }
452 return $n;
453 }
454
455 /**
456 * Given an IPv6 address in octet notation, returns a pure hex string.
457 *
458 * @param string $ip octet ipv6 IP address.
459 * @return String: pure hex (uppercase)
460 */
461 private static function IPv6ToRawHex( $ip ) {
462 $ip = self::sanitizeIP( $ip );
463 if ( !$ip ) {
464 return null;
465 }
466 $r_ip = '';
467 foreach ( explode( ':', $ip ) as $v ) {
468 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT );
469 }
470 return $r_ip;
471 }
472
473 /**
474 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
475 * Like ip2long() except that it actually works and has a consistent error return value.
476 * Comes from ProxyTools.php
477 *
478 * @param string $ip quad dotted IP address.
479 * @return Mixed: string/int/false
480 */
481 public static function toUnsigned( $ip ) {
482 if ( self::isIPv6( $ip ) ) {
483 $n = self::toUnsigned6( $ip );
484 } else {
485 $n = ip2long( $ip );
486 if ( $n < 0 ) {
487 $n += pow( 2, 32 );
488 # On 32-bit platforms (and on Windows), 2^32 does not fit into an int,
489 # so $n becomes a float. We convert it to string instead.
490 if ( is_float( $n ) ) {
491 $n = (string)$n;
492 }
493 }
494 }
495 return $n;
496 }
497
498 /**
499 * @param $ip
500 * @return String
501 */
502 private static function toUnsigned6( $ip ) {
503 return wfBaseConvert( self::IPv6ToRawHex( $ip ), 16, 10 );
504 }
505
506 /**
507 * Convert a network specification in CIDR notation
508 * to an integer network and a number of bits
509 *
510 * @param string $range IP with CIDR prefix
511 * @return array(int or string, int)
512 */
513 public static function parseCIDR( $range ) {
514 if ( self::isIPv6( $range ) ) {
515 return self::parseCIDR6( $range );
516 }
517 $parts = explode( '/', $range, 2 );
518 if ( count( $parts ) != 2 ) {
519 return array( false, false );
520 }
521 list( $network, $bits ) = $parts;
522 $network = ip2long( $network );
523 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
524 if ( $bits == 0 ) {
525 $network = 0;
526 } else {
527 $network &= ~( ( 1 << ( 32 - $bits ) ) - 1 );
528 }
529 # Convert to unsigned
530 if ( $network < 0 ) {
531 $network += pow( 2, 32 );
532 }
533 } else {
534 $network = false;
535 $bits = false;
536 }
537 return array( $network, $bits );
538 }
539
540 /**
541 * Given a string range in a number of formats,
542 * return the start and end of the range in hexadecimal.
543 *
544 * Formats are:
545 * 1.2.3.4/24 CIDR
546 * 1.2.3.4 - 1.2.3.5 Explicit range
547 * 1.2.3.4 Single IP
548 *
549 * 2001:0db8:85a3::7344/96 CIDR
550 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
551 * 2001:0db8:85a3::7344 Single IP
552 * @param string $range IP range
553 * @return array(string, string)
554 */
555 public static function parseRange( $range ) {
556 // CIDR notation
557 if ( strpos( $range, '/' ) !== false ) {
558 if ( self::isIPv6( $range ) ) {
559 return self::parseRange6( $range );
560 }
561 list( $network, $bits ) = self::parseCIDR( $range );
562 if ( $network === false ) {
563 $start = $end = false;
564 } else {
565 $start = sprintf( '%08X', $network );
566 $end = sprintf( '%08X', $network + pow( 2, ( 32 - $bits ) ) - 1 );
567 }
568 // Explicit range
569 } elseif ( strpos( $range, '-' ) !== false ) {
570 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
571 if ( self::isIPv6( $start ) && self::isIPv6( $end ) ) {
572 return self::parseRange6( $range );
573 }
574 if ( self::isIPv4( $start ) && self::isIPv4( $end ) ) {
575 $start = self::toUnsigned( $start );
576 $end = self::toUnsigned( $end );
577 if ( $start > $end ) {
578 $start = $end = false;
579 } else {
580 $start = sprintf( '%08X', $start );
581 $end = sprintf( '%08X', $end );
582 }
583 } else {
584 $start = $end = false;
585 }
586 } else {
587 # Single IP
588 $start = $end = self::toHex( $range );
589 }
590 if ( $start === false || $end === false ) {
591 return array( false, false );
592 } else {
593 return array( $start, $end );
594 }
595 }
596
597 /**
598 * Convert a network specification in IPv6 CIDR notation to an
599 * integer network and a number of bits
600 *
601 * @param $range
602 *
603 * @return array(string, int)
604 */
605 private static function parseCIDR6( $range ) {
606 # Explode into <expanded IP,range>
607 $parts = explode( '/', IP::sanitizeIP( $range ), 2 );
608 if ( count( $parts ) != 2 ) {
609 return array( false, false );
610 }
611 list( $network, $bits ) = $parts;
612 $network = self::IPv6ToRawHex( $network );
613 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
614 if ( $bits == 0 ) {
615 $network = "0";
616 } else {
617 # Native 32 bit functions WONT work here!!!
618 # Convert to a padded binary number
619 $network = wfBaseConvert( $network, 16, 2, 128 );
620 # Truncate the last (128-$bits) bits and replace them with zeros
621 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
622 # Convert back to an integer
623 $network = wfBaseConvert( $network, 2, 10 );
624 }
625 } else {
626 $network = false;
627 $bits = false;
628 }
629 return array( $network, (int)$bits );
630 }
631
632 /**
633 * Given a string range in a number of formats, return the
634 * start and end of the range in hexadecimal. For IPv6.
635 *
636 * Formats are:
637 * 2001:0db8:85a3::7344/96 CIDR
638 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
639 * 2001:0db8:85a3::7344/96 Single IP
640 *
641 * @param $range
642 *
643 * @return array(string, string)
644 */
645 private static function parseRange6( $range ) {
646 # Expand any IPv6 IP
647 $range = IP::sanitizeIP( $range );
648 // CIDR notation...
649 if ( strpos( $range, '/' ) !== false ) {
650 list( $network, $bits ) = self::parseCIDR6( $range );
651 if ( $network === false ) {
652 $start = $end = false;
653 } else {
654 $start = wfBaseConvert( $network, 10, 16, 32, false );
655 # Turn network to binary (again)
656 $end = wfBaseConvert( $network, 10, 2, 128 );
657 # Truncate the last (128-$bits) bits and replace them with ones
658 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
659 # Convert to hex
660 $end = wfBaseConvert( $end, 2, 16, 32, false );
661 # see toHex() comment
662 $start = "v6-$start";
663 $end = "v6-$end";
664 }
665 // Explicit range notation...
666 } elseif ( strpos( $range, '-' ) !== false ) {
667 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
668 $start = self::toUnsigned6( $start );
669 $end = self::toUnsigned6( $end );
670 if ( $start > $end ) {
671 $start = $end = false;
672 } else {
673 $start = wfBaseConvert( $start, 10, 16, 32, false );
674 $end = wfBaseConvert( $end, 10, 16, 32, false );
675 }
676 # see toHex() comment
677 $start = "v6-$start";
678 $end = "v6-$end";
679 } else {
680 # Single IP
681 $start = $end = self::toHex( $range );
682 }
683 if ( $start === false || $end === false ) {
684 return array( false, false );
685 } else {
686 return array( $start, $end );
687 }
688 }
689
690 /**
691 * Determine if a given IPv4/IPv6 address is in a given CIDR network
692 *
693 * @param string $addr the address to check against the given range.
694 * @param string $range the range to check the given address against.
695 * @return Boolean: whether or not the given address is in the given range.
696 */
697 public static function isInRange( $addr, $range ) {
698 $hexIP = self::toHex( $addr );
699 list( $start, $end ) = self::parseRange( $range );
700 return ( strcmp( $hexIP, $start ) >= 0 &&
701 strcmp( $hexIP, $end ) <= 0 );
702 }
703
704 /**
705 * Convert some unusual representations of IPv4 addresses to their
706 * canonical dotted quad representation.
707 *
708 * This currently only checks a few IPV4-to-IPv6 related cases. More
709 * unusual representations may be added later.
710 *
711 * @param string $addr something that might be an IP address
712 * @return String: valid dotted quad IPv4 address or null
713 */
714 public static function canonicalize( $addr ) {
715 // remove zone info (bug 35738)
716 $addr = preg_replace( '/\%.*/', '', $addr );
717
718 if ( self::isValid( $addr ) ) {
719 return $addr;
720 }
721 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
722 if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
723 $addr = substr( $addr, strrpos( $addr, ':' ) + 1 );
724 if ( self::isIPv4( $addr ) ) {
725 return $addr;
726 }
727 }
728 // IPv6 loopback address
729 $m = array();
730 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) ) {
731 return '127.0.0.1';
732 }
733 // IPv4-mapped and IPv4-compatible IPv6 addresses
734 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) ) {
735 return $m[1];
736 }
737 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD .
738 ':' . RE_IPV6_WORD . '$/i', $addr, $m ) )
739 {
740 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
741 }
742
743 return null; // give up
744 }
745
746 /**
747 * Gets rid of unneeded numbers in quad-dotted/octet IP strings
748 * For example, 127.111.113.151/24 -> 127.111.113.0/24
749 * @param string $range IP address to normalize
750 * @return string
751 */
752 public static function sanitizeRange( $range ) {
753 list( /*...*/, $bits ) = self::parseCIDR( $range );
754 list( $start, /*...*/ ) = self::parseRange( $range );
755 $start = self::formatHex( $start );
756 if ( $bits === false ) {
757 return $start; // wasn't actually a range
758 }
759 return "$start/$bits";
760 }
761 }