IPAddress.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /*
  2. * Copyright 2014-present Facebook, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <folly/IPAddress.h>
  17. #include <limits>
  18. #include <ostream>
  19. #include <string>
  20. #include <vector>
  21. #include <folly/Format.h>
  22. #include <folly/String.h>
  23. #include <folly/detail/IPAddressSource.h>
  24. using std::ostream;
  25. using std::string;
  26. using std::vector;
  27. namespace folly {
  28. // free functions
  29. size_t hash_value(const IPAddress& addr) {
  30. return addr.hash();
  31. }
  32. ostream& operator<<(ostream& os, const IPAddress& addr) {
  33. os << addr.str();
  34. return os;
  35. }
  36. void toAppend(IPAddress addr, string* result) {
  37. result->append(addr.str());
  38. }
  39. void toAppend(IPAddress addr, fbstring* result) {
  40. result->append(addr.str());
  41. }
  42. bool IPAddress::validate(StringPiece ip) noexcept {
  43. return IPAddressV4::validate(ip) || IPAddressV6::validate(ip);
  44. }
  45. // public static
  46. IPAddressV4 IPAddress::createIPv4(const IPAddress& addr) {
  47. if (addr.isV4()) {
  48. return addr.asV4();
  49. } else {
  50. return addr.asV6().createIPv4();
  51. }
  52. }
  53. // public static
  54. IPAddressV6 IPAddress::createIPv6(const IPAddress& addr) {
  55. if (addr.isV6()) {
  56. return addr.asV6();
  57. } else {
  58. return addr.asV4().createIPv6();
  59. }
  60. }
  61. namespace {
  62. vector<string> splitIpSlashCidr(StringPiece ipSlashCidr) {
  63. vector<string> vec;
  64. split("/", ipSlashCidr, vec);
  65. return vec;
  66. }
  67. } // namespace
  68. // public static
  69. CIDRNetwork IPAddress::createNetwork(
  70. StringPiece ipSlashCidr,
  71. int defaultCidr, /* = -1 */
  72. bool applyMask /* = true */) {
  73. auto const ret =
  74. IPAddress::tryCreateNetwork(ipSlashCidr, defaultCidr, applyMask);
  75. if (ret.hasValue()) {
  76. return ret.value();
  77. }
  78. if (ret.error() == CIDRNetworkError::INVALID_DEFAULT_CIDR) {
  79. throw std::range_error("defaultCidr must be <= UINT8_MAX");
  80. }
  81. if (ret.error() == CIDRNetworkError::INVALID_IP_SLASH_CIDR) {
  82. throw IPAddressFormatException(sformat(
  83. "Invalid ipSlashCidr specified. Expected IP/CIDR format, got '{}'",
  84. ipSlashCidr));
  85. }
  86. // Handler the remaining error cases. We re-parse the ip/mask pair
  87. // to make error messages more meaningful
  88. auto const vec = splitIpSlashCidr(ipSlashCidr);
  89. switch (ret.error()) {
  90. case CIDRNetworkError::INVALID_IP:
  91. CHECK_GE(vec.size(), 1);
  92. throw IPAddressFormatException(
  93. sformat("Invalid IP address {}", vec.at(0)));
  94. case CIDRNetworkError::INVALID_CIDR:
  95. CHECK_GE(vec.size(), 2);
  96. throw IPAddressFormatException(
  97. sformat("Mask value '{}' not a valid mask", vec.at(1)));
  98. case CIDRNetworkError::CIDR_MISMATCH: {
  99. auto const subnet = IPAddress::tryFromString(vec.at(0)).value();
  100. auto cidr = static_cast<uint8_t>(
  101. (defaultCidr > -1) ? defaultCidr : (subnet.isV4() ? 32 : 128));
  102. throw IPAddressFormatException(sformat(
  103. "CIDR value '{}' is > network bit count '{}'",
  104. vec.size() == 2 ? vec.at(1) : to<string>(cidr),
  105. subnet.bitCount()));
  106. }
  107. default:
  108. // unreachable
  109. break;
  110. }
  111. CHECK(0);
  112. return CIDRNetwork{};
  113. }
  114. // public static
  115. Expected<CIDRNetwork, CIDRNetworkError> IPAddress::tryCreateNetwork(
  116. StringPiece ipSlashCidr,
  117. int defaultCidr,
  118. bool applyMask) {
  119. if (defaultCidr > std::numeric_limits<uint8_t>::max()) {
  120. return makeUnexpected(CIDRNetworkError::INVALID_DEFAULT_CIDR);
  121. }
  122. auto const vec = splitIpSlashCidr(ipSlashCidr);
  123. auto const elemCount = vec.size();
  124. if (elemCount == 0 || // weird invalid string
  125. elemCount > 2) { // invalid string (IP/CIDR/extras)
  126. return makeUnexpected(CIDRNetworkError::INVALID_IP_SLASH_CIDR);
  127. }
  128. auto const subnet = IPAddress::tryFromString(vec.at(0));
  129. if (subnet.hasError()) {
  130. return makeUnexpected(CIDRNetworkError::INVALID_IP);
  131. }
  132. auto cidr = static_cast<uint8_t>(
  133. (defaultCidr > -1) ? defaultCidr : (subnet.value().isV4() ? 32 : 128));
  134. if (elemCount == 2) {
  135. auto const maybeCidr = tryTo<uint8_t>(vec.at(1));
  136. if (maybeCidr.hasError()) {
  137. return makeUnexpected(CIDRNetworkError::INVALID_CIDR);
  138. }
  139. cidr = maybeCidr.value();
  140. }
  141. if (cidr > subnet.value().bitCount()) {
  142. return makeUnexpected(CIDRNetworkError::CIDR_MISMATCH);
  143. }
  144. return std::make_pair(
  145. applyMask ? subnet.value().mask(cidr) : subnet.value(), cidr);
  146. }
  147. // public static
  148. std::string IPAddress::networkToString(const CIDRNetwork& network) {
  149. return sformat("{}/{}", network.first.str(), network.second);
  150. }
  151. // public static
  152. IPAddress IPAddress::fromBinary(ByteRange bytes) {
  153. if (bytes.size() == 4) {
  154. return IPAddress(IPAddressV4::fromBinary(bytes));
  155. } else if (bytes.size() == 16) {
  156. return IPAddress(IPAddressV6::fromBinary(bytes));
  157. } else {
  158. string hexval = detail::Bytes::toHex(bytes.data(), bytes.size());
  159. throw IPAddressFormatException(
  160. sformat("Invalid address with hex value '{}'", hexval));
  161. }
  162. }
  163. Expected<IPAddress, IPAddressFormatError> IPAddress::tryFromBinary(
  164. ByteRange bytes) noexcept {
  165. // Check IPv6 first since it's our main protocol.
  166. if (bytes.size() == 16) {
  167. return IPAddressV6::tryFromBinary(bytes);
  168. } else if (bytes.size() == 4) {
  169. return IPAddressV4::tryFromBinary(bytes);
  170. } else {
  171. return makeUnexpected(IPAddressFormatError::UNSUPPORTED_ADDR_FAMILY);
  172. }
  173. }
  174. // public static
  175. IPAddress IPAddress::fromLong(uint32_t src) {
  176. return IPAddress(IPAddressV4::fromLong(src));
  177. }
  178. IPAddress IPAddress::fromLongHBO(uint32_t src) {
  179. return IPAddress(IPAddressV4::fromLongHBO(src));
  180. }
  181. // default constructor
  182. IPAddress::IPAddress() : addr_(), family_(AF_UNSPEC) {}
  183. // public string constructor
  184. IPAddress::IPAddress(StringPiece str) : addr_(), family_(AF_UNSPEC) {
  185. auto maybeIp = tryFromString(str);
  186. if (maybeIp.hasError()) {
  187. throw IPAddressFormatException(
  188. to<std::string>("Invalid IP address '", str, "'"));
  189. }
  190. *this = std::move(maybeIp.value());
  191. }
  192. Expected<IPAddress, IPAddressFormatError> IPAddress::tryFromString(
  193. StringPiece str) noexcept {
  194. // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
  195. // contain a period
  196. if (str.find(':') != string::npos) {
  197. return IPAddressV6::tryFromString(str);
  198. } else if (str.find('.') != string::npos) {
  199. return IPAddressV4::tryFromString(str);
  200. } else {
  201. return makeUnexpected(IPAddressFormatError::UNSUPPORTED_ADDR_FAMILY);
  202. }
  203. }
  204. // public sockaddr constructor
  205. IPAddress::IPAddress(const sockaddr* addr) : addr_(), family_(AF_UNSPEC) {
  206. if (addr == nullptr) {
  207. throw IPAddressFormatException("sockaddr == nullptr");
  208. }
  209. family_ = addr->sa_family;
  210. switch (addr->sa_family) {
  211. case AF_INET: {
  212. const sockaddr_in* v4addr = reinterpret_cast<const sockaddr_in*>(addr);
  213. addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
  214. break;
  215. }
  216. case AF_INET6: {
  217. const sockaddr_in6* v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
  218. addr_.ipV6Addr = IPAddressV6(*v6addr);
  219. break;
  220. }
  221. default:
  222. throw InvalidAddressFamilyException(addr->sa_family);
  223. }
  224. }
  225. // public ipv4 constructor
  226. IPAddress::IPAddress(const IPAddressV4 ipV4Addr) noexcept
  227. : addr_(ipV4Addr), family_(AF_INET) {}
  228. // public ipv4 constructor
  229. IPAddress::IPAddress(const in_addr ipV4Addr) noexcept
  230. : addr_(IPAddressV4(ipV4Addr)), family_(AF_INET) {}
  231. // public ipv6 constructor
  232. IPAddress::IPAddress(const IPAddressV6& ipV6Addr) noexcept
  233. : addr_(ipV6Addr), family_(AF_INET6) {}
  234. // public ipv6 constructor
  235. IPAddress::IPAddress(const in6_addr& ipV6Addr) noexcept
  236. : addr_(IPAddressV6(ipV6Addr)), family_(AF_INET6) {}
  237. // Assign from V4 address
  238. IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) noexcept {
  239. addr_ = IPAddressV46(ipv4_addr);
  240. family_ = AF_INET;
  241. return *this;
  242. }
  243. // Assign from V6 address
  244. IPAddress& IPAddress::operator=(const IPAddressV6& ipv6_addr) noexcept {
  245. addr_ = IPAddressV46(ipv6_addr);
  246. family_ = AF_INET6;
  247. return *this;
  248. }
  249. // public
  250. bool IPAddress::inSubnet(StringPiece cidrNetwork) const {
  251. auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
  252. return inSubnet(subnetInfo.first, subnetInfo.second);
  253. }
  254. // public
  255. bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
  256. if (bitCount() == subnet.bitCount()) {
  257. if (isV4()) {
  258. return asV4().inSubnet(subnet.asV4(), cidr);
  259. } else {
  260. return asV6().inSubnet(subnet.asV6(), cidr);
  261. }
  262. }
  263. // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
  264. // address and vice-versa
  265. if (isV6()) {
  266. const IPAddressV6& v6addr = asV6();
  267. const IPAddressV4& v4subnet = subnet.asV4();
  268. if (v6addr.is6To4()) {
  269. return v6addr.getIPv4For6To4().inSubnet(v4subnet, cidr);
  270. }
  271. } else if (subnet.isV6()) {
  272. const IPAddressV6& v6subnet = subnet.asV6();
  273. const IPAddressV4& v4addr = asV4();
  274. if (v6subnet.is6To4()) {
  275. return v4addr.inSubnet(v6subnet.getIPv4For6To4(), cidr);
  276. }
  277. }
  278. return false;
  279. }
  280. // public
  281. bool IPAddress::inSubnetWithMask(const IPAddress& subnet, ByteRange mask)
  282. const {
  283. auto mkByteArray4 = [&]() -> ByteArray4 {
  284. ByteArray4 ba{{0}};
  285. std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
  286. return ba;
  287. };
  288. if (bitCount() == subnet.bitCount()) {
  289. if (isV4()) {
  290. return asV4().inSubnetWithMask(subnet.asV4(), mkByteArray4());
  291. } else {
  292. ByteArray16 ba{{0}};
  293. std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 16));
  294. return asV6().inSubnetWithMask(subnet.asV6(), ba);
  295. }
  296. }
  297. // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
  298. // address and vice-versa
  299. if (isV6()) {
  300. const IPAddressV6& v6addr = asV6();
  301. const IPAddressV4& v4subnet = subnet.asV4();
  302. if (v6addr.is6To4()) {
  303. return v6addr.getIPv4For6To4().inSubnetWithMask(v4subnet, mkByteArray4());
  304. }
  305. } else if (subnet.isV6()) {
  306. const IPAddressV6& v6subnet = subnet.asV6();
  307. const IPAddressV4& v4addr = asV4();
  308. if (v6subnet.is6To4()) {
  309. return v4addr.inSubnetWithMask(v6subnet.getIPv4For6To4(), mkByteArray4());
  310. }
  311. }
  312. return false;
  313. }
  314. uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
  315. const auto highestIndex = byteCount() - 1;
  316. if (byteIndex > highestIndex) {
  317. throw std::invalid_argument(sformat(
  318. "Byte index must be <= {} for addresses of type: {}",
  319. highestIndex,
  320. detail::familyNameStr(family())));
  321. }
  322. if (isV4()) {
  323. return asV4().bytes()[byteIndex];
  324. }
  325. return asV6().bytes()[byteIndex];
  326. }
  327. // public
  328. bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
  329. if (addr1.family() == addr2.family()) {
  330. if (addr1.isV6()) {
  331. return (addr1.asV6() == addr2.asV6());
  332. } else if (addr1.isV4()) {
  333. return (addr1.asV4() == addr2.asV4());
  334. } else {
  335. CHECK_EQ(addr1.family(), AF_UNSPEC);
  336. // Two default initialized AF_UNSPEC addresses should be considered equal.
  337. // AF_UNSPEC is the only other value for which an IPAddress can be
  338. // created, in the default constructor case.
  339. return true;
  340. }
  341. }
  342. // addr1 is v4 mapped v6 address, addr2 is v4
  343. if (addr1.isIPv4Mapped() && addr2.isV4()) {
  344. if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
  345. return true;
  346. }
  347. }
  348. // addr2 is v4 mapped v6 address, addr1 is v4
  349. if (addr2.isIPv4Mapped() && addr1.isV4()) {
  350. if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
  351. return true;
  352. }
  353. }
  354. // we only compare IPv4 and IPv6 addresses
  355. return false;
  356. }
  357. bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
  358. if (addr1.family() == addr2.family()) {
  359. if (addr1.isV6()) {
  360. return (addr1.asV6() < addr2.asV6());
  361. } else if (addr1.isV4()) {
  362. return (addr1.asV4() < addr2.asV4());
  363. } else {
  364. CHECK_EQ(addr1.family(), AF_UNSPEC);
  365. // Two default initialized AF_UNSPEC addresses can not be less than each
  366. // other. AF_UNSPEC is the only other value for which an IPAddress can be
  367. // created, in the default constructor case.
  368. return false;
  369. }
  370. }
  371. if (addr1.isV6()) {
  372. // means addr2 is v4, convert it to a mapped v6 address and compare
  373. return addr1.asV6() < addr2.asV4().createIPv6();
  374. }
  375. if (addr2.isV6()) {
  376. // means addr2 is v6, convert addr1 to v4 mapped and compare
  377. return addr1.asV4().createIPv6() < addr2.asV6();
  378. }
  379. return false;
  380. }
  381. CIDRNetwork IPAddress::longestCommonPrefix(
  382. const CIDRNetwork& one,
  383. const CIDRNetwork& two) {
  384. if (one.first.family() != two.first.family()) {
  385. throw std::invalid_argument(sformat(
  386. "Can't compute longest common prefix between addresses of different"
  387. "families. Passed: {} and {}",
  388. detail::familyNameStr(one.first.family()),
  389. detail::familyNameStr(two.first.family())));
  390. }
  391. if (one.first.isV4()) {
  392. auto prefix = IPAddressV4::longestCommonPrefix(
  393. {one.first.asV4(), one.second}, {two.first.asV4(), two.second});
  394. return {IPAddress(prefix.first), prefix.second};
  395. } else if (one.first.isV6()) {
  396. auto prefix = IPAddressV6::longestCommonPrefix(
  397. {one.first.asV6(), one.second}, {two.first.asV6(), two.second});
  398. return {IPAddress(prefix.first), prefix.second};
  399. } else {
  400. throw std::invalid_argument("Unknown address family");
  401. }
  402. }
  403. // clang-format off
  404. [[noreturn]] void IPAddress::asV4Throw() const {
  405. auto fam = detail::familyNameStr(family());
  406. throw InvalidAddressFamilyException(
  407. sformat("Can't convert address with family {} to AF_INET address", fam));
  408. }
  409. [[noreturn]] void IPAddress::asV6Throw() const {
  410. auto fam = detail::familyNameStr(family());
  411. throw InvalidAddressFamilyException(
  412. sformat("Can't convert address with family {} to AF_INET6 address", fam));
  413. }
  414. // clang-format on
  415. } // namespace folly