IPv6.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. <?php
  2. namespace IPLib\Address;
  3. use IPLib\ParseStringFlag;
  4. use IPLib\Range\RangeInterface;
  5. use IPLib\Range\Subnet;
  6. use IPLib\Range\Type as RangeType;
  7. use IPLib\Service\BinaryMath;
  8. use IPLib\Service\NumberInChunks;
  9. /**
  10. * An IPv6 address.
  11. */
  12. class IPv6 implements AddressInterface
  13. {
  14. /**
  15. * The long string representation of the address.
  16. *
  17. * @var string
  18. *
  19. * @example '0000:0000:0000:0000:0000:0000:0000:0001'
  20. */
  21. protected $longAddress;
  22. /**
  23. * The long string representation of the address.
  24. *
  25. * @var string|null
  26. *
  27. * @example '::1'
  28. */
  29. protected $shortAddress;
  30. /**
  31. * The byte list of the IP address.
  32. *
  33. * @var int[]|null
  34. */
  35. protected $bytes;
  36. /**
  37. * The word list of the IP address.
  38. *
  39. * @var int[]|null
  40. */
  41. protected $words;
  42. /**
  43. * The type of the range of this IP address.
  44. *
  45. * @var int|null
  46. */
  47. protected $rangeType;
  48. /**
  49. * An array containing RFC designated address ranges.
  50. *
  51. * @var array|null
  52. */
  53. private static $reservedRanges;
  54. /**
  55. * Initializes the instance.
  56. *
  57. * @param string $longAddress
  58. */
  59. public function __construct($longAddress)
  60. {
  61. $this->longAddress = $longAddress;
  62. $this->shortAddress = null;
  63. $this->bytes = null;
  64. $this->words = null;
  65. $this->rangeType = null;
  66. }
  67. /**
  68. * {@inheritdoc}
  69. *
  70. * @see \IPLib\Address\AddressInterface::__toString()
  71. */
  72. public function __toString()
  73. {
  74. return $this->toString();
  75. }
  76. /**
  77. * {@inheritdoc}
  78. *
  79. * @see \IPLib\Address\AddressInterface::getNumberOfBits()
  80. */
  81. public static function getNumberOfBits()
  82. {
  83. return 128;
  84. }
  85. /**
  86. * @deprecated since 1.17.0: use the parseString() method instead.
  87. * For upgrading:
  88. * - if $mayIncludePort is true, use the ParseStringFlag::MAY_INCLUDE_PORT flag
  89. * - if $mayIncludeZoneID is true, use the ParseStringFlag::MAY_INCLUDE_ZONEID flag
  90. *
  91. * @param string|mixed $address
  92. * @param bool $mayIncludePort
  93. * @param bool $mayIncludeZoneID
  94. *
  95. * @return static|null
  96. *
  97. * @see \IPLib\Address\IPv6::parseString()
  98. * @since 1.1.0 added the $mayIncludePort argument
  99. * @since 1.3.0 added the $mayIncludeZoneID argument
  100. */
  101. public static function fromString($address, $mayIncludePort = true, $mayIncludeZoneID = true)
  102. {
  103. return static::parseString($address, 0 | ($mayIncludePort ? ParseStringFlag::MAY_INCLUDE_PORT : 0) | ($mayIncludeZoneID ? ParseStringFlag::MAY_INCLUDE_ZONEID : 0));
  104. }
  105. /**
  106. * Parse a string and returns an IPv6 instance if the string is valid, or null otherwise.
  107. *
  108. * @param string|mixed $address the address to parse
  109. * @param int $flags A combination or zero or more flags
  110. *
  111. * @return static|null
  112. *
  113. * @see \IPLib\ParseStringFlag
  114. * @since 1.17.0
  115. */
  116. public static function parseString($address, $flags = 0)
  117. {
  118. if (!is_string($address)) {
  119. return null;
  120. }
  121. $matches = null;
  122. $flags = (int) $flags;
  123. if ($flags & ParseStringFlag::ADDRESS_MAYBE_RDNS) {
  124. if (preg_match('/^([0-9a-f](?:\.[0-9a-f]){31})\.ip6\.arpa\.?/i', $address, $matches)) {
  125. $nibbles = array_reverse(explode('.', $matches[1]));
  126. $quibbles = array();
  127. foreach (array_chunk($nibbles, 4) as $n) {
  128. $quibbles[] = implode('', $n);
  129. }
  130. $address = implode(':', $quibbles);
  131. }
  132. }
  133. $result = null;
  134. if (is_string($address) && strpos($address, ':') !== false && strpos($address, ':::') === false) {
  135. if ($flags & ParseStringFlag::MAY_INCLUDE_PORT && $address[0] === '[' && preg_match('/^\[(.+)]:\d+$/', $address, $matches)) {
  136. $address = $matches[1];
  137. }
  138. if ($flags & ParseStringFlag::MAY_INCLUDE_ZONEID) {
  139. $percentagePos = strpos($address, '%');
  140. if ($percentagePos > 0) {
  141. $address = substr($address, 0, $percentagePos);
  142. }
  143. }
  144. if (preg_match('/^((?:[0-9a-f]*:+)+)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i', $address, $matches)) {
  145. $address6 = static::parseString($matches[1] . '0:0');
  146. if ($address6 !== null) {
  147. $address4 = IPv4::parseString($matches[2]);
  148. if ($address4 !== null) {
  149. $bytes4 = $address4->getBytes();
  150. $address6->longAddress = substr($address6->longAddress, 0, -9) . sprintf('%02x%02x:%02x%02x', $bytes4[0], $bytes4[1], $bytes4[2], $bytes4[3]);
  151. $result = $address6;
  152. }
  153. }
  154. } else {
  155. if (strpos($address, '::') === false) {
  156. $chunks = explode(':', $address);
  157. } else {
  158. $chunks = array();
  159. $parts = explode('::', $address);
  160. if (count($parts) === 2) {
  161. $before = ($parts[0] === '') ? array() : explode(':', $parts[0]);
  162. $after = ($parts[1] === '') ? array() : explode(':', $parts[1]);
  163. $missing = 8 - count($before) - count($after);
  164. if ($missing >= 0) {
  165. $chunks = $before;
  166. if ($missing !== 0) {
  167. $chunks = array_merge($chunks, array_fill(0, $missing, '0'));
  168. }
  169. $chunks = array_merge($chunks, $after);
  170. }
  171. }
  172. }
  173. if (count($chunks) === 8) {
  174. $nums = array_map(
  175. function ($chunk) {
  176. return preg_match('/^[0-9A-Fa-f]{1,4}$/', $chunk) ? hexdec($chunk) : false;
  177. },
  178. $chunks
  179. );
  180. if (!in_array(false, $nums, true)) {
  181. $longAddress = implode(
  182. ':',
  183. array_map(
  184. function ($num) {
  185. return sprintf('%04x', $num);
  186. },
  187. $nums
  188. )
  189. );
  190. $result = new static($longAddress);
  191. }
  192. }
  193. }
  194. }
  195. return $result;
  196. }
  197. /**
  198. * Parse an array of bytes and returns an IPv6 instance if the array is valid, or null otherwise.
  199. *
  200. * @param int[]|array $bytes
  201. *
  202. * @return static|null
  203. */
  204. public static function fromBytes(array $bytes)
  205. {
  206. $result = null;
  207. if (count($bytes) === 16) {
  208. $address = '';
  209. for ($i = 0; $i < 16; $i++) {
  210. if ($i !== 0 && $i % 2 === 0) {
  211. $address .= ':';
  212. }
  213. $byte = $bytes[$i];
  214. if (is_int($byte) && $byte >= 0 && $byte <= 255) {
  215. $address .= sprintf('%02x', $byte);
  216. } else {
  217. $address = null;
  218. break;
  219. }
  220. }
  221. if ($address !== null) {
  222. $result = new static($address);
  223. }
  224. }
  225. return $result;
  226. }
  227. /**
  228. * Parse an array of words and returns an IPv6 instance if the array is valid, or null otherwise.
  229. *
  230. * @param int[]|array $words
  231. *
  232. * @return static|null
  233. */
  234. public static function fromWords(array $words)
  235. {
  236. $result = null;
  237. if (count($words) === 8) {
  238. $chunks = array();
  239. for ($i = 0; $i < 8; $i++) {
  240. $word = $words[$i];
  241. if (is_int($word) && $word >= 0 && $word <= 0xffff) {
  242. $chunks[] = sprintf('%04x', $word);
  243. } else {
  244. $chunks = null;
  245. break;
  246. }
  247. }
  248. if ($chunks !== null) {
  249. $result = new static(implode(':', $chunks));
  250. }
  251. }
  252. return $result;
  253. }
  254. /**
  255. * {@inheritdoc}
  256. *
  257. * @see \IPLib\Address\AddressInterface::toString()
  258. */
  259. public function toString($long = false)
  260. {
  261. if ($long) {
  262. $result = $this->longAddress;
  263. } else {
  264. if ($this->shortAddress === null) {
  265. if (strpos($this->longAddress, '0000:0000:0000:0000:0000:ffff:') === 0) {
  266. $lastBytes = array_slice($this->getBytes(), -4);
  267. $this->shortAddress = '::ffff:' . implode('.', $lastBytes);
  268. } else {
  269. $chunks = array_map(
  270. function ($word) {
  271. return dechex($word);
  272. },
  273. $this->getWords()
  274. );
  275. $shortAddress = implode(':', $chunks);
  276. $matches = null;
  277. for ($i = 8; $i > 1; $i--) {
  278. $search = '(?:^|:)' . rtrim(str_repeat('0:', $i), ':') . '(?:$|:)';
  279. if (preg_match('/^(.*?)' . $search . '(.*)$/', $shortAddress, $matches)) {
  280. $shortAddress = $matches[1] . '::' . $matches[2];
  281. break;
  282. }
  283. }
  284. $this->shortAddress = $shortAddress;
  285. }
  286. }
  287. $result = $this->shortAddress;
  288. }
  289. return $result;
  290. }
  291. /**
  292. * {@inheritdoc}
  293. *
  294. * @see \IPLib\Address\AddressInterface::getBytes()
  295. */
  296. public function getBytes()
  297. {
  298. if ($this->bytes === null) {
  299. $bytes = array();
  300. foreach ($this->getWords() as $word) {
  301. $bytes[] = $word >> 8;
  302. $bytes[] = $word & 0xff;
  303. }
  304. $this->bytes = $bytes;
  305. }
  306. return $this->bytes;
  307. }
  308. /**
  309. * {@inheritdoc}
  310. *
  311. * @see \IPLib\Address\AddressInterface::getBits()
  312. */
  313. public function getBits()
  314. {
  315. $parts = array();
  316. foreach ($this->getBytes() as $byte) {
  317. $parts[] = sprintf('%08b', $byte);
  318. }
  319. return implode('', $parts);
  320. }
  321. /**
  322. * Get the word list of the IP address.
  323. *
  324. * @return int[]
  325. */
  326. public function getWords()
  327. {
  328. if ($this->words === null) {
  329. $this->words = array_map(
  330. function ($chunk) {
  331. return hexdec($chunk);
  332. },
  333. explode(':', $this->longAddress)
  334. );
  335. }
  336. return $this->words;
  337. }
  338. /**
  339. * {@inheritdoc}
  340. *
  341. * @see \IPLib\Address\AddressInterface::getAddressType()
  342. */
  343. public function getAddressType()
  344. {
  345. return Type::T_IPv6;
  346. }
  347. /**
  348. * {@inheritdoc}
  349. *
  350. * @see \IPLib\Address\AddressInterface::getDefaultReservedRangeType()
  351. */
  352. public static function getDefaultReservedRangeType()
  353. {
  354. return RangeType::T_RESERVED;
  355. }
  356. /**
  357. * {@inheritdoc}
  358. *
  359. * @see \IPLib\Address\AddressInterface::getReservedRanges()
  360. */
  361. public static function getReservedRanges()
  362. {
  363. if (self::$reservedRanges === null) {
  364. $reservedRanges = array();
  365. foreach (array(
  366. // RFC 4291
  367. '::/128' => array(RangeType::T_UNSPECIFIED),
  368. // RFC 4291
  369. '::1/128' => array(RangeType::T_LOOPBACK),
  370. // RFC 4291
  371. '100::/8' => array(RangeType::T_DISCARD, array('100::/64' => RangeType::T_DISCARDONLY)),
  372. //'2002::/16' => array(RangeType::),
  373. // RFC 4291
  374. '2000::/3' => array(RangeType::T_PUBLIC),
  375. // RFC 4193
  376. 'fc00::/7' => array(RangeType::T_PRIVATENETWORK),
  377. // RFC 4291
  378. 'fe80::/10' => array(RangeType::T_LINKLOCAL_UNICAST),
  379. // RFC 4291
  380. 'ff00::/8' => array(RangeType::T_MULTICAST),
  381. // RFC 4291
  382. //'::/8' => array(RangeType::T_RESERVED),
  383. // RFC 4048
  384. //'200::/7' => array(RangeType::T_RESERVED),
  385. // RFC 4291
  386. //'400::/6' => array(RangeType::T_RESERVED),
  387. // RFC 4291
  388. //'800::/5' => array(RangeType::T_RESERVED),
  389. // RFC 4291
  390. //'1000::/4' => array(RangeType::T_RESERVED),
  391. // RFC 4291
  392. //'4000::/3' => array(RangeType::T_RESERVED),
  393. // RFC 4291
  394. //'6000::/3' => array(RangeType::T_RESERVED),
  395. // RFC 4291
  396. //'8000::/3' => array(RangeType::T_RESERVED),
  397. // RFC 4291
  398. //'a000::/3' => array(RangeType::T_RESERVED),
  399. // RFC 4291
  400. //'c000::/3' => array(RangeType::T_RESERVED),
  401. // RFC 4291
  402. //'e000::/4' => array(RangeType::T_RESERVED),
  403. // RFC 4291
  404. //'f000::/5' => array(RangeType::T_RESERVED),
  405. // RFC 4291
  406. //'f800::/6' => array(RangeType::T_RESERVED),
  407. // RFC 4291
  408. //'fe00::/9' => array(RangeType::T_RESERVED),
  409. // RFC 3879
  410. //'fec0::/10' => array(RangeType::T_RESERVED),
  411. ) as $range => $data) {
  412. $exceptions = array();
  413. if (isset($data[1])) {
  414. foreach ($data[1] as $exceptionRange => $exceptionType) {
  415. $exceptions[] = new AssignedRange(Subnet::parseString($exceptionRange), $exceptionType);
  416. }
  417. }
  418. $reservedRanges[] = new AssignedRange(Subnet::parseString($range), $data[0], $exceptions);
  419. }
  420. self::$reservedRanges = $reservedRanges;
  421. }
  422. return self::$reservedRanges;
  423. }
  424. /**
  425. * {@inheritdoc}
  426. *
  427. * @see \IPLib\Address\AddressInterface::getRangeType()
  428. */
  429. public function getRangeType()
  430. {
  431. if ($this->rangeType === null) {
  432. $ipv4 = $this->toIPv4();
  433. if ($ipv4 !== null) {
  434. $this->rangeType = $ipv4->getRangeType();
  435. } else {
  436. $rangeType = null;
  437. foreach (static::getReservedRanges() as $reservedRange) {
  438. $rangeType = $reservedRange->getAddressType($this);
  439. if ($rangeType !== null) {
  440. break;
  441. }
  442. }
  443. $this->rangeType = $rangeType === null ? static::getDefaultReservedRangeType() : $rangeType;
  444. }
  445. }
  446. return $this->rangeType;
  447. }
  448. /**
  449. * Create an IPv4 representation of this address (if possible, otherwise returns null).
  450. *
  451. * @return \IPLib\Address\IPv4|null
  452. */
  453. public function toIPv4()
  454. {
  455. if (strpos($this->longAddress, '2002:') === 0) {
  456. // 6to4
  457. return IPv4::fromBytes(array_slice($this->getBytes(), 2, 4));
  458. }
  459. if (strpos($this->longAddress, '0000:0000:0000:0000:0000:ffff:') === 0) {
  460. // IPv4-mapped IPv6 addresses
  461. return IPv4::fromBytes(array_slice($this->getBytes(), -4));
  462. }
  463. return null;
  464. }
  465. /**
  466. * Render this IPv6 address in the "mixed" IPv6 (first 12 bytes) + IPv4 (last 4 bytes) mixed syntax.
  467. *
  468. * @param bool $ipV6Long render the IPv6 part in "long" format?
  469. * @param bool $ipV4Long render the IPv4 part in "long" format?
  470. *
  471. * @return string
  472. *
  473. * @example '::13.1.68.3'
  474. * @example '0000:0000:0000:0000:0000:0000:13.1.68.3' when $ipV6Long is true
  475. * @example '::013.001.068.003' when $ipV4Long is true
  476. * @example '0000:0000:0000:0000:0000:0000:013.001.068.003' when $ipV6Long and $ipV4Long are true
  477. *
  478. * @see https://tools.ietf.org/html/rfc4291#section-2.2 point 3.
  479. * @since 1.9.0
  480. */
  481. public function toMixedIPv6IPv4String($ipV6Long = false, $ipV4Long = false)
  482. {
  483. $myBytes = $this->getBytes();
  484. $ipv6Bytes = array_merge(array_slice($myBytes, 0, 12), array(0xff, 0xff, 0xff, 0xff));
  485. $ipv6String = static::fromBytes($ipv6Bytes)->toString($ipV6Long);
  486. $ipv4Bytes = array_slice($myBytes, 12, 4);
  487. $ipv4String = IPv4::fromBytes($ipv4Bytes)->toString($ipV4Long);
  488. return preg_replace('/((ffff:ffff)|(\d+(\.\d+){3}))$/i', $ipv4String, $ipv6String);
  489. }
  490. /**
  491. * {@inheritdoc}
  492. *
  493. * @see \IPLib\Address\AddressInterface::getComparableString()
  494. */
  495. public function getComparableString()
  496. {
  497. return $this->longAddress;
  498. }
  499. /**
  500. * {@inheritdoc}
  501. *
  502. * @see \IPLib\Address\AddressInterface::matches()
  503. */
  504. public function matches(RangeInterface $range)
  505. {
  506. return $range->contains($this);
  507. }
  508. /**
  509. * {@inheritdoc}
  510. *
  511. * @see \IPLib\Address\AddressInterface::getAddressAtOffset()
  512. */
  513. public function getAddressAtOffset($n)
  514. {
  515. if (is_int($n)) {
  516. $thatChunks = NumberInChunks::fromInteger($n, NumberInChunks::CHUNKSIZE_WORDS);
  517. } elseif (($s = BinaryMath::getInstance()->normalizeIntegerString($n)) !== '') {
  518. $thatChunks = NumberInChunks::fromNumericString($s, NumberInChunks::CHUNKSIZE_WORDS);
  519. } else {
  520. return null;
  521. }
  522. $myWords = $this->getWords();
  523. while (isset($myWords[1]) && $myWords[0] === 0) {
  524. array_shift($myWords);
  525. }
  526. $myChunks = new NumberInChunks(false, $myWords, NumberInChunks::CHUNKSIZE_WORDS);
  527. $result = $myChunks->add($thatChunks);
  528. if ($result->negative || count($result->chunks) > 8) {
  529. return null;
  530. }
  531. return static::fromWords(array_pad($result->chunks, -8, 0));
  532. }
  533. /**
  534. * {@inheritdoc}
  535. *
  536. * @see \IPLib\Address\AddressInterface::getNextAddress()
  537. */
  538. public function getNextAddress()
  539. {
  540. return $this->getAddressAtOffset(1);
  541. }
  542. /**
  543. * {@inheritdoc}
  544. *
  545. * @see \IPLib\Address\AddressInterface::getPreviousAddress()
  546. */
  547. public function getPreviousAddress()
  548. {
  549. return $this->getAddressAtOffset(-1);
  550. }
  551. /**
  552. * {@inheritdoc}
  553. *
  554. * @see \IPLib\Address\AddressInterface::getReverseDNSLookupName()
  555. */
  556. public function getReverseDNSLookupName()
  557. {
  558. return implode(
  559. '.',
  560. array_reverse(str_split(str_replace(':', '', $this->toString(true)), 1))
  561. ) . '.ip6.arpa';
  562. }
  563. /**
  564. * {@inheritdoc}
  565. *
  566. * @see \IPLib\Address\AddressInterface::shift()
  567. */
  568. public function shift($bits)
  569. {
  570. $bits = (int) $bits;
  571. if ($bits === 0) {
  572. return $this;
  573. }
  574. $absBits = abs($bits);
  575. if ($absBits >= 128) {
  576. return new self('0000:0000:0000:0000:0000:0000:0000:0000');
  577. }
  578. $pad = str_repeat('0', $absBits);
  579. $paddedBits = $this->getBits();
  580. if ($bits > 0) {
  581. $paddedBits = $pad . substr($paddedBits, 0, -$bits);
  582. } else {
  583. $paddedBits = substr($paddedBits, $absBits) . $pad;
  584. }
  585. $bytes = array_map('bindec', str_split($paddedBits, 16));
  586. return static::fromWords($bytes);
  587. }
  588. /**
  589. * {@inheritdoc}
  590. *
  591. * @see \IPLib\Address\AddressInterface::add()
  592. */
  593. public function add(AddressInterface $other)
  594. {
  595. if (!$other instanceof self) {
  596. return null;
  597. }
  598. $myWords = $this->getWords();
  599. $otherWords = $other->getWords();
  600. $sum = array_fill(0, 8, 0);
  601. $carry = 0;
  602. for ($index = 7; $index >= 0; $index--) {
  603. $word = $myWords[$index] + $otherWords[$index] + $carry;
  604. if ($word > 0xFFFF) {
  605. $carry = $word >> 16;
  606. $word &= 0xFFFF;
  607. } else {
  608. $carry = 0;
  609. }
  610. $sum[$index] = $word;
  611. }
  612. if ($carry !== 0) {
  613. return null;
  614. }
  615. return static::fromWords($sum);
  616. }
  617. }