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