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