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