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