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