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