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