Ipv6.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <?php
  2. /**
  3. * Class to validate and to work with IPv6 addresses
  4. *
  5. * @package Requests\Utilities
  6. */
  7. namespace WpOrg\Requests;
  8. use WpOrg\Requests\Exception\InvalidArgument;
  9. use WpOrg\Requests\Utility\InputValidator;
  10. /**
  11. * Class to validate and to work with IPv6 addresses
  12. *
  13. * This was originally based on the PEAR class of the same name, but has been
  14. * entirely rewritten.
  15. *
  16. * @package Requests\Utilities
  17. */
  18. final class Ipv6 {
  19. /**
  20. * Uncompresses an IPv6 address
  21. *
  22. * RFC 4291 allows you to compress consecutive zero pieces in an address to
  23. * '::'. This method expects a valid IPv6 address and expands the '::' to
  24. * the required number of zero pieces.
  25. *
  26. * Example: FF01::101 -> FF01:0:0:0:0:0:0:101
  27. * ::1 -> 0:0:0:0:0:0:0:1
  28. *
  29. * @author Alexander Merz <alexander.merz@web.de>
  30. * @author elfrink at introweb dot nl
  31. * @author Josh Peck <jmp at joshpeck dot org>
  32. * @copyright 2003-2005 The PHP Group
  33. * @license https://opensource.org/licenses/bsd-license.php
  34. *
  35. * @param string|Stringable $ip An IPv6 address
  36. * @return string The uncompressed IPv6 address
  37. *
  38. * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed argument is not a string or a stringable object.
  39. */
  40. public static function uncompress($ip) {
  41. if (InputValidator::is_string_or_stringable($ip) === false) {
  42. throw InvalidArgument::create(1, '$ip', 'string|Stringable', gettype($ip));
  43. }
  44. $ip = (string) $ip;
  45. if (substr_count($ip, '::') !== 1) {
  46. return $ip;
  47. }
  48. list($ip1, $ip2) = explode('::', $ip);
  49. $c1 = ($ip1 === '') ? -1 : substr_count($ip1, ':');
  50. $c2 = ($ip2 === '') ? -1 : substr_count($ip2, ':');
  51. if (strpos($ip2, '.') !== false) {
  52. $c2++;
  53. }
  54. if ($c1 === -1 && $c2 === -1) {
  55. // ::
  56. $ip = '0:0:0:0:0:0:0:0';
  57. } elseif ($c1 === -1) {
  58. // ::xxx
  59. $fill = str_repeat('0:', 7 - $c2);
  60. $ip = str_replace('::', $fill, $ip);
  61. } elseif ($c2 === -1) {
  62. // xxx::
  63. $fill = str_repeat(':0', 7 - $c1);
  64. $ip = str_replace('::', $fill, $ip);
  65. } else {
  66. // xxx::xxx
  67. $fill = ':' . str_repeat('0:', 6 - $c2 - $c1);
  68. $ip = str_replace('::', $fill, $ip);
  69. }
  70. return $ip;
  71. }
  72. /**
  73. * Compresses an IPv6 address
  74. *
  75. * RFC 4291 allows you to compress consecutive zero pieces in an address to
  76. * '::'. This method expects a valid IPv6 address and compresses consecutive
  77. * zero pieces to '::'.
  78. *
  79. * Example: FF01:0:0:0:0:0:0:101 -> FF01::101
  80. * 0:0:0:0:0:0:0:1 -> ::1
  81. *
  82. * @see \WpOrg\Requests\Ipv6::uncompress()
  83. *
  84. * @param string $ip An IPv6 address
  85. * @return string The compressed IPv6 address
  86. */
  87. public static function compress($ip) {
  88. // Prepare the IP to be compressed.
  89. // Note: Input validation is handled in the `uncompress()` method, which is the first call made in this method.
  90. $ip = self::uncompress($ip);
  91. $ip_parts = self::split_v6_v4($ip);
  92. // Replace all leading zeros
  93. $ip_parts[0] = preg_replace('/(^|:)0+([0-9])/', '\1\2', $ip_parts[0]);
  94. // Find bunches of zeros
  95. if (preg_match_all('/(?:^|:)(?:0(?::|$))+/', $ip_parts[0], $matches, PREG_OFFSET_CAPTURE)) {
  96. $max = 0;
  97. $pos = null;
  98. foreach ($matches[0] as $match) {
  99. if (strlen($match[0]) > $max) {
  100. $max = strlen($match[0]);
  101. $pos = $match[1];
  102. }
  103. }
  104. $ip_parts[0] = substr_replace($ip_parts[0], '::', $pos, $max);
  105. }
  106. if ($ip_parts[1] !== '') {
  107. return implode(':', $ip_parts);
  108. } else {
  109. return $ip_parts[0];
  110. }
  111. }
  112. /**
  113. * Splits an IPv6 address into the IPv6 and IPv4 representation parts
  114. *
  115. * RFC 4291 allows you to represent the last two parts of an IPv6 address
  116. * using the standard IPv4 representation
  117. *
  118. * Example: 0:0:0:0:0:0:13.1.68.3
  119. * 0:0:0:0:0:FFFF:129.144.52.38
  120. *
  121. * @param string $ip An IPv6 address
  122. * @return string[] [0] contains the IPv6 represented part, and [1] the IPv4 represented part
  123. */
  124. private static function split_v6_v4($ip) {
  125. if (strpos($ip, '.') !== false) {
  126. $pos = strrpos($ip, ':');
  127. $ipv6_part = substr($ip, 0, $pos);
  128. $ipv4_part = substr($ip, $pos + 1);
  129. return [$ipv6_part, $ipv4_part];
  130. } else {
  131. return [$ip, ''];
  132. }
  133. }
  134. /**
  135. * Checks an IPv6 address
  136. *
  137. * Checks if the given IP is a valid IPv6 address
  138. *
  139. * @param string $ip An IPv6 address
  140. * @return bool true if $ip is a valid IPv6 address
  141. */
  142. public static function check_ipv6($ip) {
  143. // Note: Input validation is handled in the `uncompress()` method, which is the first call made in this method.
  144. $ip = self::uncompress($ip);
  145. list($ipv6, $ipv4) = self::split_v6_v4($ip);
  146. $ipv6 = explode(':', $ipv6);
  147. $ipv4 = explode('.', $ipv4);
  148. if (count($ipv6) === 8 && count($ipv4) === 1 || count($ipv6) === 6 && count($ipv4) === 4) {
  149. foreach ($ipv6 as $ipv6_part) {
  150. // The section can't be empty
  151. if ($ipv6_part === '') {
  152. return false;
  153. }
  154. // Nor can it be over four characters
  155. if (strlen($ipv6_part) > 4) {
  156. return false;
  157. }
  158. // Remove leading zeros (this is safe because of the above)
  159. $ipv6_part = ltrim($ipv6_part, '0');
  160. if ($ipv6_part === '') {
  161. $ipv6_part = '0';
  162. }
  163. // Check the value is valid
  164. $value = hexdec($ipv6_part);
  165. if (dechex($value) !== strtolower($ipv6_part) || $value < 0 || $value > 0xFFFF) {
  166. return false;
  167. }
  168. }
  169. if (count($ipv4) === 4) {
  170. foreach ($ipv4 as $ipv4_part) {
  171. $value = (int) $ipv4_part;
  172. if ((string) $value !== $ipv4_part || $value < 0 || $value > 0xFF) {
  173. return false;
  174. }
  175. }
  176. }
  177. return true;
  178. } else {
  179. return false;
  180. }
  181. }
  182. }