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