convert "::1" and other pseudo-IPv6 addresses that Apache may throw at us to their...
[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]\d|1\d\d|[1-9]?\d)');
14 define( 'RE_IP_ADD' , RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE );
15 // An IP 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
23 class IP {
24
25 /**
26 * Validate an IP address.
27 * @return boolean True if it is valid.
28 */
29 public static function isValid( $ip ) {
30 return preg_match( '/^' . RE_IP_ADD . '$/', $ip, $matches) ;
31 }
32
33 /**
34 * Validate an IP Block.
35 * @return boolean True if it is valid.
36 */
37 public static function isValidBlock( $ipblock ) {
38 return ( count(self::toArray($ipblock)) == 1 + 5 );
39 }
40
41 /**
42 * Determine if an IP address really is an IP address, and if it is public,
43 * i.e. not RFC 1918 or similar
44 * Comes from ProxyTools.php
45 */
46 public static function isPublic( $ip ) {
47 $n = IP::toUnsigned( $ip );
48 if ( !$n ) {
49 return false;
50 }
51
52 // ip2long accepts incomplete addresses, as well as some addresses
53 // followed by garbage characters. Check that it's really valid.
54 if( $ip != long2ip( $n ) ) {
55 return false;
56 }
57
58 static $privateRanges = false;
59 if ( !$privateRanges ) {
60 $privateRanges = array(
61 array( '10.0.0.0', '10.255.255.255' ), # RFC 1918 (private)
62 array( '172.16.0.0', '172.31.255.255' ), # "
63 array( '192.168.0.0', '192.168.255.255' ), # "
64 array( '0.0.0.0', '0.255.255.255' ), # this network
65 array( '127.0.0.0', '127.255.255.255' ), # loopback
66 );
67 }
68
69 foreach ( $privateRanges as $r ) {
70 $start = IP::toUnsigned( $r[0] );
71 $end = IP::toUnsigned( $r[1] );
72 if ( $n >= $start && $n <= $end ) {
73 return false;
74 }
75 }
76 return true;
77 }
78
79 /**
80 * Split out an IP block as an array of 4 bytes and a mask,
81 * return false if it cant be determined
82 *
83 * @parameter $ip string A quad dotted IP address
84 * @return array
85 */
86 public static function toArray( $ipblock ) {
87 if(! preg_match( '/^' . RE_IP_ADD . '(?:\/(?:'.RE_IP_PREFIX.'))?' . '$/', $ipblock, $matches ) ) {
88 return false;
89 } else {
90 return $matches;
91 }
92 }
93
94 /**
95 * Return a zero-padded hexadecimal representation of an IP address.
96 *
97 * Hexadecimal addresses are used because they can easily be extended to
98 * IPv6 support. To separate the ranges, the return value from this
99 * function for an IPv6 address will be prefixed with "v6-", a non-
100 * hexadecimal string which sorts after the IPv4 addresses.
101 *
102 * @param $ip Quad dotted IP address.
103 */
104 public static function toHex( $ip ) {
105 $n = self::toUnsigned( $ip );
106 if ( $n !== false ) {
107 $n = sprintf( '%08X', $n );
108 }
109 return $n;
110 }
111
112 /**
113 * Given an IP address in dotted-quad notation, returns an unsigned integer.
114 * Like ip2long() except that it actually works and has a consistent error return value.
115 * Comes from ProxyTools.php
116 * @param $ip Quad dotted IP address.
117 */
118 public static function toUnsigned( $ip ) {
119 if ( $ip == '255.255.255.255' ) {
120 $n = -1;
121 } else {
122 $n = ip2long( $ip );
123 if ( $n == -1 || $n === false ) { # Return value on error depends on PHP version
124 $n = false;
125 }
126 }
127 if ( $n < 0 ) {
128 $n += pow( 2, 32 );
129 }
130 return $n;
131 }
132
133 /**
134 * Convert a dotted-quad IP to a signed integer
135 * Returns false on failure
136 */
137 public static function toSigned( $ip ) {
138 if ( $ip == '255.255.255.255' ) {
139 $n = -1;
140 } else {
141 $n = ip2long( $ip );
142 if ( $n == -1 ) {
143 $n = false;
144 }
145 }
146 return $n;
147 }
148
149 /**
150 * Convert a network specification in CIDR notation to an integer network and a number of bits
151 */
152 public static function parseCIDR( $range ) {
153 $parts = explode( '/', $range, 2 );
154 if ( count( $parts ) != 2 ) {
155 return array( false, false );
156 }
157 $network = IP::toSigned( $parts[0] );
158 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
159 $bits = $parts[1];
160 if ( $bits == 0 ) {
161 $network = 0;
162 } else {
163 $network &= ~((1 << (32 - $bits)) - 1);
164 }
165 # Convert to unsigned
166 if ( $network < 0 ) {
167 $network += pow( 2, 32 );
168 }
169 } else {
170 $network = false;
171 $bits = false;
172 }
173 return array( $network, $bits );
174 }
175
176 /**
177 * Given a string range in a number of formats, return the start and end of
178 * the range in hexadecimal.
179 *
180 * Formats are:
181 * 1.2.3.4/24 CIDR
182 * 1.2.3.4 - 1.2.3.5 Explicit range
183 * 1.2.3.4 Single IP
184 */
185 public static function parseRange( $range ) {
186 if ( strpos( $range, '/' ) !== false ) {
187 # CIDR
188 list( $network, $bits ) = IP::parseCIDR( $range );
189 if ( $network === false ) {
190 $start = $end = false;
191 } else {
192 $start = sprintf( '%08X', $network );
193 $end = sprintf( '%08X', $network + pow( 2, (32 - $bits) ) - 1 );
194 }
195 } elseif ( strpos( $range, '-' ) !== false ) {
196 # Explicit range
197 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
198 if ( $start > $end ) {
199 $start = $end = false;
200 } else {
201 $start = IP::toHex( $start );
202 $end = IP::toHex( $end );
203 }
204 } else {
205 # Single IP
206 $start = $end = IP::toHex( $range );
207 }
208 if ( $start === false || $end === false ) {
209 return array( false, false );
210 } else {
211 return array( $start, $end );
212 }
213 }
214
215 /**
216 * Determine if a given integer IPv4 address is in a given CIDR network
217 * @param $addr The address to check against the given range.
218 * @param $range The range to check the given address against.
219 * @return bool Whether or not the given address is in the given range.
220 */
221 public static function isInRange( $addr, $range ) {
222 $unsignedIP = IP::toUnsigned($addr);
223 list( $start, $end ) = IP::parseRange($range);
224
225 return (($unsignedIP >= $start) && ($unsignedIP <= $end));
226 }
227
228 /**
229 * Convert some unusual representations of IPv4 addresses to their
230 * canonical dotted quad representation.
231 *
232 * This currently only checks a few IPV4-to-IPv6 related cases. More
233 * unusual representations may be added later.
234 *
235 * @param $addr something that might be an IP address
236 * @return valid dotted quad IPv4 address or null
237 */
238 public static function canonicalize( $addr ) {
239 if ( IP::isValid( $addr ) )
240 return $addr;
241
242 // IPv6 loopback address
243 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) )
244 return '127.0.0.1';
245
246 // IPv4-mapped and IPv4-compatible IPv6 addresses
247 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) )
248 return $m[1];
249 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD . ':' . RE_IPV6_WORD . '$/i', $addr, $m ) )
250 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
251
252 return null; // give up
253 }
254 }
255
256 ?>