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