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