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