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