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