Completing code housekeeping stuff for rest of includes/ directory: removing unused...
[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) ;
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 $matches = array();
88 if(! preg_match( '/^' . RE_IP_ADD . '(?:\/(?:'.RE_IP_PREFIX.'))?' . '$/', $ipblock, $matches ) ) {
89 return false;
90 } else {
91 return $matches;
92 }
93 }
94
95 /**
96 * Return a zero-padded hexadecimal representation of an IP address.
97 *
98 * Hexadecimal addresses are used because they can easily be extended to
99 * IPv6 support. To separate the ranges, the return value from this
100 * function for an IPv6 address will be prefixed with "v6-", a non-
101 * hexadecimal string which sorts after the IPv4 addresses.
102 *
103 * @param $ip Quad dotted IP address.
104 */
105 public static function toHex( $ip ) {
106 $n = self::toUnsigned( $ip );
107 if ( $n !== false ) {
108 $n = sprintf( '%08X', $n );
109 }
110 return $n;
111 }
112
113 /**
114 * Given an IP address in dotted-quad notation, returns an unsigned integer.
115 * Like ip2long() except that it actually works and has a consistent error return value.
116 * Comes from ProxyTools.php
117 * @param $ip Quad dotted IP address.
118 */
119 public static function toUnsigned( $ip ) {
120 if ( $ip == '255.255.255.255' ) {
121 $n = -1;
122 } else {
123 $n = ip2long( $ip );
124 if ( $n == -1 || $n === false ) { # Return value on error depends on PHP version
125 $n = false;
126 }
127 }
128 if ( $n < 0 ) {
129 $n += pow( 2, 32 );
130 }
131 return $n;
132 }
133
134 /**
135 * Convert a dotted-quad IP to a signed integer
136 * Returns false on failure
137 */
138 public static function toSigned( $ip ) {
139 if ( $ip == '255.255.255.255' ) {
140 $n = -1;
141 } else {
142 $n = ip2long( $ip );
143 if ( $n == -1 ) {
144 $n = false;
145 }
146 }
147 return $n;
148 }
149
150 /**
151 * Convert a network specification in CIDR notation to an integer network and a number of bits
152 */
153 public static function parseCIDR( $range ) {
154 $parts = explode( '/', $range, 2 );
155 if ( count( $parts ) != 2 ) {
156 return array( false, false );
157 }
158 $network = IP::toSigned( $parts[0] );
159 if ( $network !== false && is_numeric( $parts[1] ) && $parts[1] >= 0 && $parts[1] <= 32 ) {
160 $bits = $parts[1];
161 if ( $bits == 0 ) {
162 $network = 0;
163 } else {
164 $network &= ~((1 << (32 - $bits)) - 1);
165 }
166 # Convert to unsigned
167 if ( $network < 0 ) {
168 $network += pow( 2, 32 );
169 }
170 } else {
171 $network = false;
172 $bits = false;
173 }
174 return array( $network, $bits );
175 }
176
177 /**
178 * Given a string range in a number of formats, return the start and end of
179 * the range in hexadecimal.
180 *
181 * Formats are:
182 * 1.2.3.4/24 CIDR
183 * 1.2.3.4 - 1.2.3.5 Explicit range
184 * 1.2.3.4 Single IP
185 */
186 public static function parseRange( $range ) {
187 if ( strpos( $range, '/' ) !== false ) {
188 # CIDR
189 list( $network, $bits ) = IP::parseCIDR( $range );
190 if ( $network === false ) {
191 $start = $end = false;
192 } else {
193 $start = sprintf( '%08X', $network );
194 $end = sprintf( '%08X', $network + pow( 2, (32 - $bits) ) - 1 );
195 }
196 } elseif ( strpos( $range, '-' ) !== false ) {
197 # Explicit range
198 list( $start, $end ) = array_map( 'trim', explode( '-', $range, 2 ) );
199 if ( $start > $end ) {
200 $start = $end = false;
201 } else {
202 $start = IP::toHex( $start );
203 $end = IP::toHex( $end );
204 }
205 } else {
206 # Single IP
207 $start = $end = IP::toHex( $range );
208 }
209 if ( $start === false || $end === false ) {
210 return array( false, false );
211 } else {
212 return array( $start, $end );
213 }
214 }
215
216 /**
217 * Determine if a given integer IPv4 address is in a given CIDR network
218 * @param $addr The address to check against the given range.
219 * @param $range The range to check the given address against.
220 * @return bool Whether or not the given address is in the given range.
221 */
222 public static function isInRange( $addr, $range ) {
223 $unsignedIP = IP::toUnsigned($addr);
224 list( $start, $end ) = IP::parseRange($range);
225
226 return (($unsignedIP >= $start) && ($unsignedIP <= $end));
227 }
228
229 /**
230 * Convert some unusual representations of IPv4 addresses to their
231 * canonical dotted quad representation.
232 *
233 * This currently only checks a few IPV4-to-IPv6 related cases. More
234 * unusual representations may be added later.
235 *
236 * @param $addr something that might be an IP address
237 * @return valid dotted quad IPv4 address or null
238 */
239 public static function canonicalize( $addr ) {
240 if ( IP::isValid( $addr ) )
241 return $addr;
242
243 // IPv6 loopback address
244 if ( preg_match( '/^0*' . RE_IPV6_GAP . '1$/', $addr, $m ) )
245 return '127.0.0.1';
246
247 // IPv4-mapped and IPv4-compatible IPv6 addresses
248 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m ) )
249 return $m[1];
250 if ( preg_match( '/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD . ':' . RE_IPV6_WORD . '$/i', $addr, $m ) )
251 return long2ip( ( hexdec( $m[1] ) << 16 ) + hexdec( $m[2] ) );
252
253 return null; // give up
254 }
255 }
256
257 ?>