Subnet.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. <?php
  2. namespace IPLib\Range;
  3. use IPLib\Address\AddressInterface;
  4. use IPLib\Address\IPv4;
  5. use IPLib\Address\Type as AddressType;
  6. use IPLib\Factory;
  7. use IPLib\ParseStringFlag;
  8. /**
  9. * Represents an address range in subnet format (eg CIDR).
  10. *
  11. * @example 127.0.0.1/32
  12. * @example ::/8
  13. */
  14. class Subnet extends AbstractRange
  15. {
  16. /**
  17. * Starting address of the range.
  18. *
  19. * @var \IPLib\Address\AddressInterface
  20. */
  21. protected $fromAddress;
  22. /**
  23. * Final address of the range.
  24. *
  25. * @var \IPLib\Address\AddressInterface
  26. */
  27. protected $toAddress;
  28. /**
  29. * Number of the same bits of the range.
  30. *
  31. * @var int
  32. */
  33. protected $networkPrefix;
  34. /**
  35. * The type of the range of this IP range.
  36. *
  37. * @var int|null
  38. *
  39. * @since 1.5.0
  40. */
  41. protected $rangeType;
  42. /**
  43. * The 6to4 address IPv6 address range.
  44. *
  45. * @var self|null
  46. */
  47. private static $sixToFour;
  48. /**
  49. * Initializes the instance.
  50. *
  51. * @param \IPLib\Address\AddressInterface $fromAddress
  52. * @param \IPLib\Address\AddressInterface $toAddress
  53. * @param int $networkPrefix
  54. *
  55. * @internal
  56. */
  57. public function __construct(AddressInterface $fromAddress, AddressInterface $toAddress, $networkPrefix)
  58. {
  59. $this->fromAddress = $fromAddress;
  60. $this->toAddress = $toAddress;
  61. $this->networkPrefix = $networkPrefix;
  62. }
  63. /**
  64. * {@inheritdoc}
  65. *
  66. * @see \IPLib\Range\RangeInterface::__toString()
  67. */
  68. public function __toString()
  69. {
  70. return $this->toString();
  71. }
  72. /**
  73. * @deprecated since 1.17.0: use the parseString() method instead.
  74. * For upgrading:
  75. * - if $supportNonDecimalIPv4 is true, use the ParseStringFlag::IPV4_MAYBE_NON_DECIMAL flag
  76. *
  77. * @param string|mixed $range
  78. * @param bool $supportNonDecimalIPv4
  79. *
  80. * @return static|null
  81. *
  82. * @see \IPLib\Range\Subnet::parseString()
  83. * @since 1.10.0 added the $supportNonDecimalIPv4 argument
  84. */
  85. public static function fromString($range, $supportNonDecimalIPv4 = false)
  86. {
  87. return static::parseString($range, ParseStringFlag::MAY_INCLUDE_PORT | ParseStringFlag::MAY_INCLUDE_ZONEID | ($supportNonDecimalIPv4 ? ParseStringFlag::IPV4_MAYBE_NON_DECIMAL : 0));
  88. }
  89. /**
  90. * Try get the range instance starting from its string representation.
  91. *
  92. * @param string|mixed $range
  93. * @param int $flags A combination or zero or more flags
  94. *
  95. * @return static|null
  96. *
  97. * @see \IPLib\ParseStringFlag
  98. * @since 1.17.0
  99. */
  100. public static function parseString($range, $flags = 0)
  101. {
  102. if (!is_string($range)) {
  103. return null;
  104. }
  105. $parts = explode('/', $range);
  106. if (count($parts) !== 2) {
  107. return null;
  108. }
  109. $flags = (int) $flags;
  110. if (strpos($parts[0], ':') === false && $flags & ParseStringFlag::IPV4SUBNET_MAYBE_COMPACT) {
  111. $missingDots = 3 - substr_count($parts[0], '.');
  112. if ($missingDots > 0) {
  113. $parts[0] .= str_repeat('.0', $missingDots);
  114. }
  115. }
  116. $address = Factory::parseAddressString($parts[0], $flags);
  117. if ($address === null) {
  118. return null;
  119. }
  120. if (!preg_match('/^[0-9]{1,9}$/', $parts[1])) {
  121. return null;
  122. }
  123. $networkPrefix = (int) $parts[1];
  124. $addressBytes = $address->getBytes();
  125. $totalBytes = count($addressBytes);
  126. $numDifferentBits = $totalBytes * 8 - $networkPrefix;
  127. if ($numDifferentBits < 0) {
  128. return null;
  129. }
  130. $numSameBytes = $networkPrefix >> 3;
  131. $sameBytes = array_slice($addressBytes, 0, $numSameBytes);
  132. $differentBytesStart = ($totalBytes === $numSameBytes) ? array() : array_fill(0, $totalBytes - $numSameBytes, 0);
  133. $differentBytesEnd = ($totalBytes === $numSameBytes) ? array() : array_fill(0, $totalBytes - $numSameBytes, 255);
  134. $startSameBits = $networkPrefix % 8;
  135. if ($startSameBits !== 0) {
  136. $varyingByte = $addressBytes[$numSameBytes];
  137. $differentBytesStart[0] = $varyingByte & bindec(str_pad(str_repeat('1', $startSameBits), 8, '0', STR_PAD_RIGHT));
  138. $differentBytesEnd[0] = $differentBytesStart[0] + bindec(str_repeat('1', 8 - $startSameBits));
  139. }
  140. return new static(
  141. Factory::addressFromBytes(array_merge($sameBytes, $differentBytesStart)),
  142. Factory::addressFromBytes(array_merge($sameBytes, $differentBytesEnd)),
  143. $networkPrefix
  144. );
  145. }
  146. /**
  147. * {@inheritdoc}
  148. *
  149. * @see \IPLib\Range\RangeInterface::toString()
  150. */
  151. public function toString($long = false)
  152. {
  153. return $this->fromAddress->toString($long) . '/' . $this->networkPrefix;
  154. }
  155. /**
  156. * {@inheritdoc}
  157. *
  158. * @see \IPLib\Range\RangeInterface::getAddressType()
  159. */
  160. public function getAddressType()
  161. {
  162. return $this->fromAddress->getAddressType();
  163. }
  164. /**
  165. * {@inheritdoc}
  166. *
  167. * @see \IPLib\Range\RangeInterface::getStartAddress()
  168. */
  169. public function getStartAddress()
  170. {
  171. return $this->fromAddress;
  172. }
  173. /**
  174. * {@inheritdoc}
  175. *
  176. * @see \IPLib\Range\RangeInterface::getEndAddress()
  177. */
  178. public function getEndAddress()
  179. {
  180. return $this->toAddress;
  181. }
  182. /**
  183. * {@inheritdoc}
  184. *
  185. * @see \IPLib\Range\RangeInterface::getComparableStartString()
  186. */
  187. public function getComparableStartString()
  188. {
  189. return $this->fromAddress->getComparableString();
  190. }
  191. /**
  192. * {@inheritdoc}
  193. *
  194. * @see \IPLib\Range\RangeInterface::getComparableEndString()
  195. */
  196. public function getComparableEndString()
  197. {
  198. return $this->toAddress->getComparableString();
  199. }
  200. /**
  201. * {@inheritdoc}
  202. *
  203. * @see \IPLib\Range\RangeInterface::asSubnet()
  204. */
  205. public function asSubnet()
  206. {
  207. return $this;
  208. }
  209. /**
  210. * {@inheritdoc}
  211. *
  212. * @see \IPLib\Range\RangeInterface::asPattern()
  213. * @since 1.8.0
  214. */
  215. public function asPattern()
  216. {
  217. $address = $this->getStartAddress();
  218. $networkPrefix = $this->getNetworkPrefix();
  219. switch ($address->getAddressType()) {
  220. case AddressType::T_IPv4:
  221. return $networkPrefix % 8 === 0 ? new Pattern($address, $address, 4 - $networkPrefix / 8) : null;
  222. case AddressType::T_IPv6:
  223. return $networkPrefix % 16 === 0 ? new Pattern($address, $address, 8 - $networkPrefix / 16) : null;
  224. }
  225. }
  226. /**
  227. * Get the 6to4 address IPv6 address range.
  228. *
  229. * @return self
  230. *
  231. * @since 1.5.0
  232. */
  233. public static function get6to4()
  234. {
  235. if (self::$sixToFour === null) {
  236. self::$sixToFour = self::parseString('2002::/16');
  237. }
  238. return self::$sixToFour;
  239. }
  240. /**
  241. * {@inheritdoc}
  242. *
  243. * @see \IPLib\Range\RangeInterface::getNetworkPrefix()
  244. * @since 1.7.0
  245. */
  246. public function getNetworkPrefix()
  247. {
  248. return $this->networkPrefix;
  249. }
  250. /**
  251. * {@inheritdoc}
  252. *
  253. * @see \IPLib\Range\RangeInterface::getSubnetMask()
  254. */
  255. public function getSubnetMask()
  256. {
  257. if ($this->getAddressType() !== AddressType::T_IPv4) {
  258. return null;
  259. }
  260. $bytes = array();
  261. $prefix = $this->getNetworkPrefix();
  262. while ($prefix >= 8) {
  263. $bytes[] = 255;
  264. $prefix -= 8;
  265. }
  266. if ($prefix !== 0) {
  267. $bytes[] = bindec(str_pad(str_repeat('1', $prefix), 8, '0'));
  268. }
  269. $bytes = array_pad($bytes, 4, 0);
  270. return IPv4::fromBytes($bytes);
  271. }
  272. /**
  273. * {@inheritdoc}
  274. *
  275. * @see \IPLib\Range\RangeInterface::getReverseDNSLookupName()
  276. */
  277. public function getReverseDNSLookupName()
  278. {
  279. switch ($this->getAddressType()) {
  280. case AddressType::T_IPv4:
  281. $unitSize = 8; // bytes
  282. $maxUnits = 4;
  283. $isHex = false;
  284. $rxUnit = '\d+';
  285. break;
  286. case AddressType::T_IPv6:
  287. $unitSize = 4; // nibbles
  288. $maxUnits = 32;
  289. $isHex = true;
  290. $rxUnit = '[0-9A-Fa-f]';
  291. break;
  292. }
  293. $totBits = $unitSize * $maxUnits;
  294. $prefixUnits = (int) ($this->networkPrefix / $unitSize);
  295. $extraBits = ($totBits - $this->networkPrefix) % $unitSize;
  296. if ($extraBits !== 0) {
  297. $prefixUnits += 1;
  298. }
  299. $numVariants = 1 << $extraBits;
  300. $result = array();
  301. $unitsToRemove = $maxUnits - $prefixUnits;
  302. $initialPointer = preg_replace("/^(({$rxUnit})\.){{$unitsToRemove}}/", '', $this->getStartAddress()->getReverseDNSLookupName());
  303. $chunks = explode('.', $initialPointer, 2);
  304. for ($index = 0; $index < $numVariants; $index++) {
  305. if ($index !== 0) {
  306. $chunks[0] = $isHex ? dechex(1 + hexdec($chunks[0])) : (string) (1 + (int) $chunks[0]);
  307. }
  308. $result[] = implode('.', $chunks);
  309. }
  310. return $result;
  311. }
  312. /**
  313. * {@inheritdoc}
  314. *
  315. * @see \IPLib\Range\RangeInterface::getSize()
  316. */
  317. public function getSize()
  318. {
  319. $fromAddress = $this->fromAddress;
  320. $maxPrefix = $fromAddress::getNumberOfBits();
  321. $prefix = $this->getNetworkPrefix();
  322. return pow(2, ($maxPrefix - $prefix));
  323. }
  324. }