PageRenderTime 41ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/mediawiki-integration/source/php/mediawiki/includes/IP.php

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