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