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