Converter.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. /**
  3. * League.Uri (https://uri.thephpleague.com)
  4. *
  5. * (c) Ignace Nyamagana Butera <nyamsprod@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. declare(strict_types=1);
  11. namespace League\Uri\IPv4;
  12. use BackedEnum;
  13. use League\Uri\Exceptions\MissingFeature;
  14. use League\Uri\FeatureDetection;
  15. use Stringable;
  16. use function array_pop;
  17. use function count;
  18. use function explode;
  19. use function extension_loaded;
  20. use function hexdec;
  21. use function long2ip;
  22. use function ltrim;
  23. use function preg_match;
  24. use function str_ends_with;
  25. use function substr;
  26. use const FILTER_FLAG_IPV4;
  27. use const FILTER_FLAG_IPV6;
  28. use const FILTER_VALIDATE_IP;
  29. final class Converter
  30. {
  31. private const REGEXP_IPV4_HOST = '/
  32. (?(DEFINE) # . is missing as it is used to separate labels
  33. (?<hexadecimal>0x[[:xdigit:]]*)
  34. (?<octal>0[0-7]*)
  35. (?<decimal>\d+)
  36. (?<ipv4_part>(?:(?&hexadecimal)|(?&octal)|(?&decimal))*)
  37. )
  38. ^(?:(?&ipv4_part)\.){0,3}(?&ipv4_part)\.?$
  39. /x';
  40. private const REGEXP_IPV4_NUMBER_PER_BASE = [
  41. '/^0x(?<number>[[:xdigit:]]*)$/' => 16,
  42. '/^0(?<number>[0-7]*)$/' => 8,
  43. '/^(?<number>\d+)$/' => 10,
  44. ];
  45. private const IPV6_6TO4_PREFIX = '2002:';
  46. private const IPV4_MAPPED_PREFIX = '::ffff:';
  47. private readonly mixed $maxIPv4Number;
  48. public function __construct(
  49. private readonly Calculator $calculator
  50. ) {
  51. $this->maxIPv4Number = $calculator->sub($calculator->pow(2, 32), 1);
  52. }
  53. /**
  54. * Returns an instance using a GMP calculator.
  55. */
  56. public static function fromGMP(): self
  57. {
  58. return new self(new GMPCalculator());
  59. }
  60. /**
  61. * Returns an instance using a Bcmath calculator.
  62. */
  63. public static function fromBCMath(): self
  64. {
  65. return new self(new BCMathCalculator());
  66. }
  67. /**
  68. * Returns an instance using a PHP native calculator (requires 64bits PHP).
  69. */
  70. public static function fromNative(): self
  71. {
  72. return new self(new NativeCalculator());
  73. }
  74. /**
  75. * Returns an instance using a detected calculator depending on the PHP environment.
  76. *
  77. * @throws MissingFeature If no Calculator implementing object can be used on the platform
  78. *
  79. * @codeCoverageIgnore
  80. */
  81. public static function fromEnvironment(): self
  82. {
  83. FeatureDetection::supportsIPv4Conversion();
  84. return match (true) {
  85. extension_loaded('gmp') => self::fromGMP(),
  86. extension_loaded('bcmath') => self::fromBCMath(),
  87. default => self::fromNative(),
  88. };
  89. }
  90. public function isIpv4(BackedEnum|Stringable|string|null $host): bool
  91. {
  92. if ($host instanceof BackedEnum) {
  93. $host = (string) $host->value;
  94. }
  95. if (null === $host) {
  96. return false;
  97. }
  98. if (null !== $this->toDecimal($host)) {
  99. return true;
  100. }
  101. $host = (string) $host;
  102. if (false === filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
  103. return false;
  104. }
  105. $ipAddress = strtolower((string) inet_ntop((string) inet_pton($host)));
  106. if (str_starts_with($ipAddress, self::IPV4_MAPPED_PREFIX)) {
  107. return false !== filter_var(substr($ipAddress, 7), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
  108. }
  109. if (!str_starts_with($ipAddress, self::IPV6_6TO4_PREFIX)) {
  110. return false;
  111. }
  112. $hexParts = explode(':', substr($ipAddress, 5, 9));
  113. if (count($hexParts) < 2) {
  114. return false;
  115. }
  116. $ipAddress = long2ip((int) hexdec($hexParts[0]) * 65536 + (int) hexdec($hexParts[1]));
  117. return '' !== ''.$ipAddress;
  118. }
  119. public function toIPv6Using6to4(BackedEnum|Stringable|string|null $host): ?string
  120. {
  121. $host = $this->toDecimal($host);
  122. if (null === $host) {
  123. return null;
  124. }
  125. /** @var array<string> $parts */
  126. $parts = array_map(
  127. fn (string $part): string => sprintf('%02x', $part),
  128. explode('.', $host)
  129. );
  130. return '['.self::IPV6_6TO4_PREFIX.$parts[0].$parts[1].':'.$parts[2].$parts[3].'::]';
  131. }
  132. public function toIPv6UsingMapping(BackedEnum|Stringable|string|null $host): ?string
  133. {
  134. $host = $this->toDecimal($host);
  135. if (null === $host) {
  136. return null;
  137. }
  138. return '['.self::IPV4_MAPPED_PREFIX.$host.']';
  139. }
  140. public function toOctal(BackedEnum|Stringable|string|null $host): ?string
  141. {
  142. $host = $this->toDecimal($host);
  143. return match (null) {
  144. $host => null,
  145. default => implode('.', array_map(
  146. fn ($value) => str_pad(decoct((int) $value), 4, '0', STR_PAD_LEFT),
  147. explode('.', $host)
  148. )),
  149. };
  150. }
  151. public function toHexadecimal(BackedEnum|Stringable|string|null $host): ?string
  152. {
  153. $host = $this->toDecimal($host);
  154. return match (null) {
  155. $host => null,
  156. default => '0x'.implode('', array_map(
  157. fn ($value) => dechex((int) $value),
  158. explode('.', $host)
  159. )),
  160. };
  161. }
  162. /**
  163. * Tries to convert a IPv4 hexadecimal or a IPv4 octal notation into a IPv4 dot-decimal notation if possible
  164. * otherwise returns null.
  165. *
  166. * @see https://url.spec.whatwg.org/#concept-ipv4-parser
  167. */
  168. public function toDecimal(BackedEnum|Stringable|string|null $host): ?string
  169. {
  170. if ($host instanceof BackedEnum) {
  171. $host = $host->value;
  172. }
  173. $host = (string) $host;
  174. if (str_starts_with($host, '[') && str_ends_with($host, ']')) {
  175. $host = substr($host, 1, -1);
  176. if (false === filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
  177. return null;
  178. }
  179. $ipAddress = strtolower((string) inet_ntop((string) inet_pton($host)));
  180. if (str_starts_with($ipAddress, self::IPV4_MAPPED_PREFIX)) {
  181. return substr($ipAddress, 7);
  182. }
  183. if (!str_starts_with($ipAddress, self::IPV6_6TO4_PREFIX)) {
  184. return null;
  185. }
  186. $hexParts = explode(':', substr($ipAddress, 5, 9));
  187. return (string) match (true) {
  188. count($hexParts) < 2 => null,
  189. default => long2ip((int) hexdec($hexParts[0]) * 65536 + (int) hexdec($hexParts[1])),
  190. };
  191. }
  192. if (1 !== preg_match(self::REGEXP_IPV4_HOST, $host)) {
  193. return null;
  194. }
  195. if (str_ends_with($host, '.')) {
  196. $host = substr($host, 0, -1);
  197. }
  198. $numbers = [];
  199. foreach (explode('.', $host) as $label) {
  200. $number = $this->labelToNumber($label);
  201. if (null === $number) {
  202. return null;
  203. }
  204. $numbers[] = $number;
  205. }
  206. $ipv4 = array_pop($numbers);
  207. $max = $this->calculator->pow(256, 6 - count($numbers));
  208. if ($this->calculator->compare($ipv4, $max) > 0) {
  209. return null;
  210. }
  211. foreach ($numbers as $offset => $number) {
  212. if ($this->calculator->compare($number, 255) > 0) {
  213. return null;
  214. }
  215. $ipv4 = $this->calculator->add($ipv4, $this->calculator->multiply(
  216. $number,
  217. $this->calculator->pow(256, 3 - $offset)
  218. ));
  219. }
  220. return $this->long2Ip($ipv4);
  221. }
  222. /**
  223. * Converts a domain label into a IPv4 integer part.
  224. *
  225. * @see https://url.spec.whatwg.org/#ipv4-number-parser
  226. *
  227. * @return mixed returns null if it cannot correctly convert the label
  228. */
  229. private function labelToNumber(string $label): mixed
  230. {
  231. foreach (self::REGEXP_IPV4_NUMBER_PER_BASE as $regexp => $base) {
  232. if (1 !== preg_match($regexp, $label, $matches)) {
  233. continue;
  234. }
  235. $number = ltrim($matches['number'], '0');
  236. if ('' === $number) {
  237. return 0;
  238. }
  239. $number = $this->calculator->baseConvert($number, $base);
  240. if (0 <= $this->calculator->compare($number, 0) && 0 >= $this->calculator->compare($number, $this->maxIPv4Number)) {
  241. return $number;
  242. }
  243. }
  244. return null;
  245. }
  246. /**
  247. * Generates the dot-decimal notation for IPv4.
  248. *
  249. * @see https://url.spec.whatwg.org/#concept-ipv4-parser
  250. *
  251. * @param mixed $ipAddress the number representation of the IPV4address
  252. */
  253. private function long2Ip(mixed $ipAddress): string
  254. {
  255. $output = '';
  256. for ($offset = 0; $offset < 4; $offset++) {
  257. $output = $this->calculator->mod($ipAddress, 256).$output;
  258. if ($offset < 3) {
  259. $output = '.'.$output;
  260. }
  261. $ipAddress = $this->calculator->div($ipAddress, 256);
  262. }
  263. return $output;
  264. }
  265. }