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