* Removed redundant check in toUnsigned6().
[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 Ashar Voultoiz <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 IP 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 block is an IP address and a prefix (d1 to d128)
34 define( 'RE_IPV6_WORD', '([0-9A-Fa-f]{1,4})' );
35 define( 'RE_IPV6_PREFIX', '(12[0-8]|1[01][0-9]|[1-9]?\d)');
36 // An IPv6 address is made up of 8 words. However, the "::" abbreviations can be used.
37 define( 'RE_IPV6_ADD',
38 '(' . // starts with "::" (includes the address "::")
39 '(::|:(:' . RE_IPV6_WORD . '){1,7})' .
40 '|' . // ends with "::" (not including the address "::")
41 RE_IPV6_WORD . '(:' . RE_IPV6_WORD . '){0,6}::' .
42 '|' . // has no "::"
43 RE_IPV6_WORD . '(:' . RE_IPV6_WORD . '){7}' .
44 '|' . // contains one "::" in the middle ("^" check always fails if no "::" found)
45 RE_IPV6_WORD . '(:(?P<abbr>(?(abbr)|:))?' . RE_IPV6_WORD . '){1,6}(?(abbr)|^)' .
46 ')'
47 );
48 define( 'RE_IPV6_BLOCK', RE_IPV6_ADD . '\/' . RE_IPV6_PREFIX );
49 // For IPv6 canonicalization (NOT for strict validation; these are quite lax!)
50 define( 'RE_IPV6_GAP', ':(?:0+:)*(?::(?:0+:)*)?' );
51 define( 'RE_IPV6_V4_PREFIX', '0*' . RE_IPV6_GAP . '(?:ffff:)?' );
52
53 // This might be useful for regexps used elsewhere, matches any IPv6 or IPv6 address or network
54 define( 'IP_ADDRESS_STRING',
55 '(?:' .
56 RE_IP_ADD . '(\/' . RE_IP_PREFIX . '|)' . // IPv4
57 '|' .
58 RE_IPV6_ADD . '(\/' . RE_IPV6_PREFIX . '|)' . // IPv6
59 ')'
60 );
61
62 /**
63 * A collection of public static functions to play with IP address
64 * and IP blocks.
65 */
66 class IP {
67 /**
68 * Determine if a string is as valid IP address or network (CIDR prefix).
69 * SIIT IPv4-translated addresses are rejected.
70 * Note: canonicalize() tries to convert translated addresses to IPv4.
71 * @param string $ip possible IP address
72 * @return bool
73 */
74 public static function isIPAddress( $ip ) {
75 return (bool)preg_match( '/^' . IP_ADDRESS_STRING . '$/', $ip );
76 }
77
78 /**
79 * Given a string, determine if it as valid IP in IPv6 only.
80 * Note: Unlike isValid(), this looks for networks too.
81 * @param string $ip possible IP address
82 * @return bool
83 */
84 public static function isIPv6( $ip ) {
85 return (bool)preg_match( '/^' . RE_IPV6_ADD . '(\/' . RE_IPV6_PREFIX . '|)$/', $ip );
86 }
87
88 /**
89 * Given a string, determine if it as valid IP in IPv4 only.
90 * Note: Unlike isValid(), this looks for networks too.
91 * @param string $ip possible IP address
92 * @return bool
93 */
94 public static function isIPv4( $ip ) {
95 return (bool)preg_match( '/^' . RE_IP_ADD . '(\/' . RE_IP_PREFIX . '|)$/', $ip );
96 }
97
98 /**
99 * Validate an IP address. Ranges are NOT considered valid.
100 * SIIT IPv4-translated addresses are rejected.
101 * Note: canonicalize() tries to convert translated addresses to IPv4.
102 * @param string $ip
103 * @return boolean True if it is valid.
104 */
105 public static function isValid( $ip ) {
106 return ( preg_match( '/^' . RE_IP_ADD . '$/', $ip )
107 || preg_match( '/^' . RE_IPV6_ADD . '$/', $ip ) );
108 }
109
110 /**
111 * Validate an IP Block (valid address WITH a valid prefix).
112 * SIIT IPv4-translated addresses are rejected.
113 * Note: canonicalize() tries to convert translated addresses to IPv4.
114 * @param string $ipblock
115 * @return boolean True if it is valid.
116 */
117 public static function isValidBlock( $ipblock ) {
118 return ( preg_match( '/^' . RE_IPV6_BLOCK . '$/', $ipblock )
119 || preg_match( '/^' . RE_IPV4_BLOCK . '$/', $ipblock ) );
120 }
121
122 /**
123 * Given an IP address in dotted-quad notation, returns an IPv6 octet.
124 * See http://www.answers.com/topic/ipv4-compatible-address
125 * IPs with the first 92 bits as zeros are reserved from IPv6
126 * @param string $ip quad-dotted IP address.
127 * @return string
128 */
129 public static function IPv4toIPv6( $ip ) {
130 if ( !$ip ) {
131 return null;
132 }
133 // Convert only if needed
134 if ( self::isIPv6( $ip ) ) {
135 return $ip;
136 }
137 // IPv4 address with CIDR
138 if ( strpos( $ip, '/' ) !== false ) {
139 $parts = explode( '/', $ip, 2 );
140 if ( count( $parts ) != 2 ) {
141 return false;
142 }
143 list( $network, $bits ) = $parts;
144 $network = self::toUnsigned( $network );
145 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
146 $bits += 96;
147 return self::toOctet( $network ) . "/$bits";
148 } else {
149 return false;
150 }
151 }
152 return self::toOctet( self::toUnsigned( $ip ) );
153 }
154
155 /**
156 * Convert an IP into a nice standard form.
157 * IPv6 addresses in octet notation are expanded to 8 words.
158 * IPv4 addresses are just trimmed.
159 * @param string $ip IP address in quad or octet form (CIDR or not).
160 * @return string
161 */
162 public static function sanitizeIP( $ip ) {
163 $ip = trim( $ip );
164 if ( $ip === '' ) {
165 return null;
166 }
167 if ( self::isIPv4( $ip ) || !self::isIPv6( $ip ) ) {
168 return $ip; // nothing else to do for IPv4 addresses or invalid ones
169 }
170 // Remove any whitespaces, convert to upper case
171 $ip = strtoupper( $ip );
172 // Expand zero abbreviations
173 $abbrevPos = strpos( $ip, '::' );
174 if ( $abbrevPos !== false ) {
175 // We know this is valid IPv6. Find the last index of the
176 // address before any CIDR number (e.g. "a:b:c::/24").
177 $CIDRStart = strpos( $ip, "/" );
178 $addressEnd = ( $CIDRStart !== false )
179 ? $CIDRStart - 1
180 : strlen( $ip ) - 1;
181 // If the '::' is at the beginning...
182 if( $abbrevPos == 0 ) {
183 $repeat = '0:';
184 $extra = ( $ip == '::' ) ? '0' : ''; // for the address '::'
185 $pad = 9; // 7+2 (due to '::')
186 // If the '::' is at the end...
187 } elseif( $abbrevPos == ( $addressEnd - 1 ) ) {
188 $repeat = ':0';
189 $extra = '';
190 $pad = 9; // 7+2 (due to '::')
191 // If the '::' is in the middle...
192 } else {
193 $repeat = ':0';
194 $extra = ':';
195 $pad = 8; // 6+2 (due to '::')
196 }
197 $ip = str_replace( '::',
198 str_repeat( $repeat, $pad - substr_count( $ip, ':' ) ) . $extra,
199 $ip
200 );
201 }
202 // Remove leading zereos from each bloc as needed
203 $ip = preg_replace( '/(^|:)0+' . RE_IPV6_WORD . '/', '$1$2', $ip );
204 return $ip;
205 }
206
207 /**
208 * Given an unsigned integer, returns an IPv6 address in octet notation
209 * @param string $ip_int IP address.
210 * @return string
211 */
212 public static function toOctet( $ip_int ) {
213 return self::hexToOctet( wfBaseConvert( $ip_int, 10, 16, 32, false ) );
214 }
215
216 /**
217 * Convert an IPv4 or IPv6 hexadecimal representation back to readable format
218 * @param string $hex number, with "v6-" prefix if it is IPv6
219 * @return string quad-dotted (IPv4) or octet notation (IPv6)
220 */
221 public static function formatHex( $hex ) {
222 if ( substr( $hex, 0, 3 ) == 'v6-' ) { // IPv6
223 return self::hexToOctet( substr( $hex, 3 ) );
224 } else { // IPv4
225 return self::hexToQuad( $hex );
226 }
227 }
228
229 /**
230 * Converts a hexadecimal number to an IPv6 address in octet notation
231 * @param string $ip_hex pure hex (no v6- prefix)
232 * @return string (of format a:b:c:d:e:f:g:h)
233 */
234 public static function hexToOctet( $ip_hex ) {
235 // Pad hex to 32 chars (128 bits)
236 $ip_hex = str_pad( strtoupper( $ip_hex ), 32, '0', STR_PAD_LEFT );
237 // Separate into 8 words
238 $ip_oct = substr( $ip_hex, 0, 4 );
239 for ( $n = 1; $n < 8; $n++ ) {
240 $ip_oct .= ':' . substr( $ip_hex, 4 * $n, 4 );
241 }
242 // NO leading zeroes
243 $ip_oct = preg_replace( '/(^|:)0+' . RE_IPV6_WORD . '/', '$1$2', $ip_oct );
244 return $ip_oct;
245 }
246
247 /**
248 * Converts a hexadecimal number to an IPv4 address in quad-dotted notation
249 * @param string $ip_hex pure hex
250 * @return string (of format a.b.c.d)
251 */
252 public static function hexToQuad( $ip_hex ) {
253 // Pad hex to 8 chars (32 bits)
254 $ip_hex = str_pad( strtoupper( $ip_hex ), 8, '0', STR_PAD_LEFT );
255 // Separate into four quads
256 $s = '';
257 for ( $i = 0; $i < 4; $i++ ) {
258 if ( $s !== '' ) {
259 $s .= '.';
260 }
261 $s .= base_convert( substr( $ip_hex, $i * 2, 2 ), 16, 10 );
262 }
263 return $s;
264 }
265
266 /**
267 * Determine if an IP address really is an IP address, and if it is public,
268 * i.e. not RFC 1918 or similar
269 * Comes from ProxyTools.php
270 * @param string $ip
271 * @return bool
272 */
273 public static function isPublic( $ip ) {
274 if ( self::isIPv6( $ip ) ) {
275 return self::isPublic6( $ip );
276 }
277 $n = self::toUnsigned( $ip );
278 if ( !$n ) {
279 return false;
280 }
281
282 // ip2long accepts incomplete addresses, as well as some addresses
283 // followed by garbage characters. Check that it's really valid.
284 if( $ip != long2ip( $n ) ) {
285 return false;
286 }
287
288 static $privateRanges = false;
289 if ( !$privateRanges ) {
290 $privateRanges = array(
291 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
292 array( '172.16.0.0', '172.31.255.255' ), # "
293 array( '192.168.0.0', '192.168.255.255' ), # "
294 array( '0.0.0.0', '0.255.255.255' ), # this network
295 array( '127.0.0.0', '127.255.255.255' ), # loopback
296 );
297 }
298
299 foreach ( $privateRanges as $r ) {
300 $start = self::toUnsigned( $r[0] );
301 $end = self::toUnsigned( $r[1] );
302 if ( $n >= $start && $n <= $end ) {
303 return false;
304 }
305 }
306 return true;
307 }
308
309 /**
310 * Determine if an IPv6 address really is an IP address, and if it is public,
311 * i.e. not RFC 4193 or similar
312 * @param string $ip
313 * @return bool
314 */
315 private static function isPublic6( $ip ) {
316 static $privateRanges = false;
317 if ( !$privateRanges ) {
318 $privateRanges = array(
319 array( 'fc::', 'fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' ), # RFC 4193 (local)
320 array( '0:0:0:0:0:0:0:1', '0:0:0:0:0:0:0:1' ), # loopback
321 );
322 }
323 $n = self::toHex( $ip );
324 foreach ( $privateRanges as $r ) {
325 $start = self::toHex( $r[0] );
326 $end = self::toHex( $r[1] );
327 if ( $n >= $start && $n <= $end ) {
328 return false;
329 }
330 }
331 return true;
332 }
333
334 /**
335 * Return a zero-padded upper case hexadecimal representation of an IP address.
336 *
337 * Hexadecimal addresses are used because they can easily be extended to
338 * IPv6 support. To separate the ranges, the return value from this
339 * function for an IPv6 address will be prefixed with "v6-", a non-
340 * hexadecimal string which sorts after the IPv4 addresses.
341 *
342 * @param string $ip Quad dotted/octet IP address.
343 * @return string
344 */
345 public static function toHex( $ip ) {
346 if ( self::isIPv6( $ip ) ) {
347 $n = 'v6-' . self::IPv6ToRawHex( $ip );
348 } else {
349 $n = self::toUnsigned( $ip );
350 if ( $n !== false ) {
351 $n = wfBaseConvert( $n, 10, 16, 8, false );
352 }
353 }
354 return $n;
355 }
356
357 /**
358 * Given an IPv6 address in octet notation, returns a pure hex string.
359 * @param string $ip octet ipv6 IP address.
360 * @return string pure hex (uppercase)
361 */
362 private static function IPv6ToRawHex( $ip ) {
363 $ip = self::sanitizeIP( $ip );
364 if ( !$ip ) {
365 return null;
366 }
367 $r_ip = '';
368 foreach ( explode( ':', $ip ) as $v ) {
369 $r_ip .= str_pad( $v, 4, 0, STR_PAD_LEFT );
370 }
371 return $r_ip;
372 }
373
374 /**
375 * Given an IP address in dotted-quad/octet notation, returns an unsigned integer.
376 * Like ip2long() except that it actually works and has a consistent error return value.
377 * Comes from ProxyTools.php
378 * @param string $ip Quad dotted IP address.
379 * @return mixed (string/int/false)
380 */
381 public static function toUnsigned( $ip ) {
382 if ( self::isIPv6( $ip ) ) {
383 $n = wfBaseConvert( self::IPv6ToRawHex( $ip ), 16, 10 );
384 } else {
385 $n = ip2long( $ip );
386 if ( $n < 0 ) {
387 $n += pow( 2, 32 );
388 }
389 }
390 return $n;
391 }
392
393 private static function toUnsigned6( $ip ) {
394 return wfBaseConvert( self::IPv6ToRawHex( $ip ), 16, 10 );
395 }
396
397 /**
398 * Convert a network specification in CIDR notation
399 * to an integer network and a number of bits
400 * @param string $range (CIDR IP)
401 * @return array(int, int)
402 */
403 public static function parseCIDR( $range ) {
404 $parts = explode( '/', $range, 2 );
405 if ( count( $parts ) != 2 ) {
406 return array( false, false );
407 }
408 list( $network, $bits ) = $parts;
409 $network = ip2long( $network );
410 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 32 ) {
411 if ( $bits == 0 ) {
412 $network = 0;
413 } else {
414 $network &= ~( ( 1 << ( 32 - $bits ) ) - 1);
415 }
416 # Convert to unsigned
417 if ( $network < 0 ) {
418 $network += pow( 2, 32 );
419 }
420 } else {
421 $network = false;
422 $bits = false;
423 }
424 return array( $network, $bits );
425 }
426
427 /**
428 * Given a string range in a number of formats, return the start and end of
429 * the range in hexadecimal.
430 *
431 * Formats are:
432 * 1.2.3.4/24 CIDR
433 * 1.2.3.4 - 1.2.3.5 Explicit range
434 * 1.2.3.4 Single IP
435 *
436 * 2001:0db8:85a3::7344/96 CIDR
437 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
438 * 2001:0db8:85a3::7344 Single IP
439 * @param string $range IP range
440 * @return array(string, int)
441 */
442 public static function parseRange( $range ) {
443 // Use IPv6 functions if needed
444 if ( self::isIPv6( $range ) ) {
445 return self::parseRange6( $range );
446 }
447 if ( strpos( $range, '/' ) !== false ) {
448 # CIDR
449 list( $network, $bits ) = self::parseCIDR( $range );
450 if ( $network === false ) {
451 $start = $end = false;
452 } else {
453 $start = sprintf( '%08X', $network );
454 $end = sprintf( '%08X', $network + pow( 2, ( 32 - $bits ) ) - 1 );
455 }
456 } elseif ( strpos( $range, '-' ) !== false ) {
457 # Explicit range
458 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
459 if( self::isIPAddress( $start ) && self::isIPAddress( $end ) ) {
460 $start = self::toUnsigned( $start );
461 $end = self::toUnsigned( $end );
462 if ( $start > $end ) {
463 $start = $end = false;
464 } else {
465 $start = sprintf( '%08X', $start );
466 $end = sprintf( '%08X', $end );
467 }
468 } else {
469 $start = $end = false;
470 }
471 } else {
472 # Single IP
473 $start = $end = self::toHex( $range );
474 }
475 if ( $start === false || $end === false ) {
476 return array( false, false );
477 } else {
478 return array( $start, $end );
479 }
480 }
481
482 /**
483 * Convert a network specification in IPv6 CIDR notation to an
484 * integer network and a number of bits
485 * @return array(string, int)
486 */
487 private static function parseCIDR6( $range ) {
488 # Explode into <expanded IP,range>
489 $parts = explode( '/', IP::sanitizeIP( $range ), 2 );
490 if ( count( $parts ) != 2 ) {
491 return array( false, false );
492 }
493 list( $network, $bits ) = $parts;
494 $network = self::IPv6ToRawHex( $network );
495 if ( $network !== false && is_numeric( $bits ) && $bits >= 0 && $bits <= 128 ) {
496 if ( $bits == 0 ) {
497 $network = "0";
498 } else {
499 # Native 32 bit functions WONT work here!!!
500 # Convert to a padded binary number
501 $network = wfBaseConvert( $network, 16, 2, 128 );
502 # Truncate the last (128-$bits) bits and replace them with zeros
503 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
504 # Convert back to an integer
505 $network = wfBaseConvert( $network, 2, 10 );
506 }
507 } else {
508 $network = false;
509 $bits = false;
510 }
511 return array( $network, (int)$bits );
512 }
513
514 /**
515 * Given a string range in a number of formats, return the
516 * start and end of the range in hexadecimal. For IPv6.
517 *
518 * Formats are:
519 * 2001:0db8:85a3::7344/96 CIDR
520 * 2001:0db8:85a3::7344 - 2001:0db8:85a3::7344 Explicit range
521 * 2001:0db8:85a3::7344/96 Single IP
522 * @return array(string, int)
523 */
524 private static function parseRange6( $range ) {
525 # Expand any IPv6 IP
526 $range = IP::sanitizeIP( $range );
527 // CIDR notation...
528 if ( strpos( $range, '/' ) !== false ) {
529 list( $network, $bits ) = self::parseCIDR6( $range );
530 if ( $network === false ) {
531 $start = $end = false;
532 } else {
533 $start = wfBaseConvert( $network, 10, 16, 32, false );
534 # Turn network to binary (again)
535 $end = wfBaseConvert( $network, 10, 2, 128 );
536 # Truncate the last (128-$bits) bits and replace them with ones
537 $end = str_pad( substr( $end, 0, $bits ), 128, 1, STR_PAD_RIGHT );
538 # Convert to hex
539 $end = wfBaseConvert( $end, 2, 16, 32, false );
540 # see toHex() comment
541 $start = "v6-$start";
542 $end = "v6-$end";
543 }
544 // Explicit range notation...
545 } elseif ( strpos( $range, '-' ) !== false ) {
546 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
547 $start = self::toUnsigned6( $start );
548 $end = self::toUnsigned6( $end );
549 if ( $start > $end ) {
550 $start = $end = false;
551 } else {
552 $start = wfBaseConvert( $start, 10, 16, 32, false );
553 $end = wfBaseConvert( $end, 10, 16, 32, false );
554 }
555 # see toHex() comment
556 $start = "v6-$start";
557 $end = "v6-$end";
558 } else {
559 # Single IP
560 $start = $end = self::toHex( $range );
561 }
562 if ( $start === false || $end === false ) {
563 return array( false, false );
564 } else {
565 return array( $start, $end );
566 }
567 }
568
569 /**
570 * Determine if a given IPv4/IPv6 address is in a given CIDR network
571 * @param $addr The address to check against the given range.
572 * @param $range The range to check the given address against.
573 * @return bool Whether or not the given address is in the given range.
574 */
575 public static function isInRange( $addr, $range ) {
576 $hexIP = self::toHex( $addr );
577 list( $start, $end ) = self::parseRange( $range );
578 return ( strcmp( $hexIP, $start ) >= 0 &&
579 strcmp( $hexIP, $end ) <= 0 );
580 }
581
582 /**
583 * Convert some unusual representations of IPv4 addresses to their
584 * canonical dotted quad representation.
585 *
586 * This currently only checks a few IPV4-to-IPv6 related cases. More
587 * unusual representations may be added later.
588 *
589 * @param $addr something that might be an IP address
590 * @return valid dotted quad IPv4 address or null
591 */
592 public static function canonicalize( $addr ) {
593 if ( self::isValid( $addr ) ) {
594 return $addr;
595 }
596
597 // Turn mapped addresses from ::ce:ffff:1.2.3.4 to 1.2.3.4
598 if ( strpos( $addr, ':' ) !== false && strpos( $addr, '.' ) !== false ) {
599 $addr = substr( $addr, strrpos( $addr, ':' ) + 1 );
600 if( self::isIPv4( $addr ) ) {
601 return $addr;
602 }
603 }
604
605 // IPv6 loopback address
606 $m = array();
607 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) ) {
608 return '127.0.0.1';
609 }
610
611 // IPv4-mapped and IPv4-compatible IPv6 addresses
612 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) ) {
613 return $m[1];
614 }
615 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD . ':' . RE_IPV6_WORD . '$/i', $addr, $m ) ) {
616 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
617 }
618
619 return null; // give up
620 }
621 }