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