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