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