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