IPAddressV4.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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/IPAddressV4.h>
  17. #include <ostream>
  18. #include <string>
  19. #include <folly/Format.h>
  20. #include <folly/IPAddress.h>
  21. #include <folly/IPAddressV6.h>
  22. #include <folly/detail/IPAddressSource.h>
  23. using std::ostream;
  24. using std::string;
  25. namespace folly {
  26. // free functions
  27. size_t hash_value(const IPAddressV4& addr) {
  28. return addr.hash();
  29. }
  30. ostream& operator<<(ostream& os, const IPAddressV4& addr) {
  31. os << addr.str();
  32. return os;
  33. }
  34. void toAppend(IPAddressV4 addr, string* result) {
  35. result->append(addr.str());
  36. }
  37. void toAppend(IPAddressV4 addr, fbstring* result) {
  38. result->append(addr.str());
  39. }
  40. bool IPAddressV4::validate(StringPiece ip) noexcept {
  41. return tryFromString(ip).hasValue();
  42. }
  43. // public static
  44. IPAddressV4 IPAddressV4::fromLong(uint32_t src) {
  45. in_addr addr;
  46. addr.s_addr = src;
  47. return IPAddressV4(addr);
  48. }
  49. IPAddressV4 IPAddressV4::fromLongHBO(uint32_t src) {
  50. in_addr addr;
  51. addr.s_addr = htonl(src);
  52. return IPAddressV4(addr);
  53. }
  54. // static public
  55. uint32_t IPAddressV4::toLong(StringPiece ip) {
  56. auto str = ip.str();
  57. in_addr addr;
  58. if (inet_pton(AF_INET, str.c_str(), &addr) != 1) {
  59. throw IPAddressFormatException(
  60. sformat("Can't convert invalid IP '{}' to long", ip));
  61. }
  62. return addr.s_addr;
  63. }
  64. // static public
  65. uint32_t IPAddressV4::toLongHBO(StringPiece ip) {
  66. return ntohl(IPAddressV4::toLong(ip));
  67. }
  68. // public default constructor
  69. IPAddressV4::IPAddressV4() {}
  70. // ByteArray4 constructor
  71. IPAddressV4::IPAddressV4(const ByteArray4& src) noexcept : addr_(src) {}
  72. // public string constructor
  73. IPAddressV4::IPAddressV4(StringPiece addr) : addr_() {
  74. auto maybeIp = tryFromString(addr);
  75. if (maybeIp.hasError()) {
  76. throw IPAddressFormatException(
  77. to<std::string>("Invalid IPv4 address '", addr, "'"));
  78. }
  79. *this = std::move(maybeIp.value());
  80. }
  81. Expected<IPAddressV4, IPAddressFormatError> IPAddressV4::tryFromString(
  82. StringPiece str) noexcept {
  83. struct in_addr inAddr;
  84. if (inet_pton(AF_INET, str.str().c_str(), &inAddr) != 1) {
  85. return makeUnexpected(IPAddressFormatError::INVALID_IP);
  86. }
  87. return IPAddressV4(inAddr);
  88. }
  89. // in_addr constructor
  90. IPAddressV4::IPAddressV4(const in_addr src) noexcept : addr_(src) {}
  91. IPAddressV4 IPAddressV4::fromBinary(ByteRange bytes) {
  92. auto maybeIp = tryFromBinary(bytes);
  93. if (maybeIp.hasError()) {
  94. throw IPAddressFormatException(to<std::string>(
  95. "Invalid IPv4 binary data: length must be 4 bytes, got ",
  96. bytes.size()));
  97. }
  98. return maybeIp.value();
  99. }
  100. Expected<IPAddressV4, IPAddressFormatError> IPAddressV4::tryFromBinary(
  101. ByteRange bytes) noexcept {
  102. IPAddressV4 addr;
  103. auto setResult = addr.trySetFromBinary(bytes);
  104. if (setResult.hasError()) {
  105. return makeUnexpected(std::move(setResult.error()));
  106. }
  107. return addr;
  108. }
  109. Expected<Unit, IPAddressFormatError> IPAddressV4::trySetFromBinary(
  110. ByteRange bytes) noexcept {
  111. if (bytes.size() != 4) {
  112. return makeUnexpected(IPAddressFormatError::INVALID_IP);
  113. }
  114. memcpy(&addr_.inAddr_.s_addr, bytes.data(), sizeof(in_addr));
  115. return folly::unit;
  116. }
  117. // static
  118. IPAddressV4 IPAddressV4::fromInverseArpaName(const std::string& arpaname) {
  119. auto piece = StringPiece(arpaname);
  120. // input must be something like 1.0.168.192.in-addr.arpa
  121. if (!piece.removeSuffix(".in-addr.arpa")) {
  122. throw IPAddressFormatException(
  123. sformat("input does not end with '.in-addr.arpa': '{}'", arpaname));
  124. }
  125. std::vector<StringPiece> pieces;
  126. split(".", piece, pieces);
  127. if (pieces.size() != 4) {
  128. throw IPAddressFormatException(sformat("Invalid input. Got {}", piece));
  129. }
  130. // reverse 1.0.168.192 -> 192.168.0.1
  131. return IPAddressV4(join(".", pieces.rbegin(), pieces.rend()));
  132. }
  133. IPAddressV6 IPAddressV4::createIPv6() const {
  134. ByteArray16 ba{};
  135. ba[10] = 0xff;
  136. ba[11] = 0xff;
  137. std::memcpy(&ba[12], bytes(), 4);
  138. return IPAddressV6(ba);
  139. }
  140. // public
  141. IPAddressV6 IPAddressV4::getIPv6For6To4() const {
  142. ByteArray16 ba{};
  143. ba[0] = (uint8_t)((IPAddressV6::PREFIX_6TO4 & 0xFF00) >> 8);
  144. ba[1] = (uint8_t)(IPAddressV6::PREFIX_6TO4 & 0x00FF);
  145. std::memcpy(&ba[2], bytes(), 4);
  146. return IPAddressV6(ba);
  147. }
  148. // public
  149. string IPAddressV4::toJson() const {
  150. return sformat("{{family:'AF_INET', addr:'{}', hash:{}}}", str(), hash());
  151. }
  152. // public
  153. bool IPAddressV4::inSubnet(StringPiece cidrNetwork) const {
  154. auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
  155. auto addr = subnetInfo.first;
  156. if (!addr.isV4()) {
  157. throw IPAddressFormatException(
  158. sformat("Address '{}' is not a V4 address", addr.toJson()));
  159. }
  160. return inSubnetWithMask(addr.asV4(), fetchMask(subnetInfo.second));
  161. }
  162. // public
  163. bool IPAddressV4::inSubnetWithMask(
  164. const IPAddressV4& subnet,
  165. const ByteArray4 cidrMask) const {
  166. const auto mask = detail::Bytes::mask(toByteArray(), cidrMask);
  167. const auto subMask = detail::Bytes::mask(subnet.toByteArray(), cidrMask);
  168. return (mask == subMask);
  169. }
  170. // public
  171. bool IPAddressV4::isLoopback() const {
  172. static IPAddressV4 loopback_addr("127.0.0.0");
  173. return inSubnetWithMask(loopback_addr, fetchMask(8));
  174. }
  175. // public
  176. bool IPAddressV4::isLinkLocal() const {
  177. static IPAddressV4 linklocal_addr("169.254.0.0");
  178. return inSubnetWithMask(linklocal_addr, fetchMask(16));
  179. }
  180. // public
  181. bool IPAddressV4::isNonroutable() const {
  182. auto ip = toLongHBO();
  183. return isPrivate() ||
  184. (/* align */ true && ip <= 0x00FFFFFF) || // 0.0.0.0-0.255.255.255
  185. (ip >= 0xC0000000 && ip <= 0xC00000FF) || // 192.0.0.0-192.0.0.255
  186. (ip >= 0xC0000200 && ip <= 0xC00002FF) || // 192.0.2.0-192.0.2.255
  187. (ip >= 0xC6120000 && ip <= 0xC613FFFF) || // 198.18.0.0-198.19.255.255
  188. (ip >= 0xC6336400 && ip <= 0xC63364FF) || // 198.51.100.0-198.51.100.255
  189. (ip >= 0xCB007100 && ip <= 0xCB0071FF) || // 203.0.113.0-203.0.113.255
  190. (ip >= 0xE0000000 && ip <= 0xFFFFFFFF) || // 224.0.0.0-255.255.255.255
  191. false;
  192. }
  193. // public
  194. bool IPAddressV4::isPrivate() const {
  195. auto ip = toLongHBO();
  196. return // some ranges below
  197. (ip >= 0x0A000000 && ip <= 0x0AFFFFFF) || // 10.0.0.0-10.255.255.255
  198. (ip >= 0x7F000000 && ip <= 0x7FFFFFFF) || // 127.0.0.0-127.255.255.255
  199. (ip >= 0xA9FE0000 && ip <= 0xA9FEFFFF) || // 169.254.0.0-169.254.255.255
  200. (ip >= 0xAC100000 && ip <= 0xAC1FFFFF) || // 172.16.0.0-172.31.255.255
  201. (ip >= 0xC0A80000 && ip <= 0xC0A8FFFF) || // 192.168.0.0-192.168.255.255
  202. false;
  203. }
  204. // public
  205. bool IPAddressV4::isMulticast() const {
  206. return (toLongHBO() & 0xf0000000) == 0xe0000000;
  207. }
  208. // public
  209. IPAddressV4 IPAddressV4::mask(size_t numBits) const {
  210. static const auto bits = bitCount();
  211. if (numBits > bits) {
  212. throw IPAddressFormatException(
  213. sformat("numBits({}) > bitsCount({})", numBits, bits));
  214. }
  215. ByteArray4 ba = detail::Bytes::mask(fetchMask(numBits), addr_.bytes_);
  216. return IPAddressV4(ba);
  217. }
  218. // public
  219. string IPAddressV4::str() const {
  220. return detail::fastIpv4ToString(addr_.inAddr_);
  221. }
  222. // public
  223. void IPAddressV4::toFullyQualifiedAppend(std::string& out) const {
  224. detail::fastIpv4AppendToString(addr_.inAddr_, out);
  225. }
  226. // public
  227. string IPAddressV4::toInverseArpaName() const {
  228. return sformat(
  229. "{}.{}.{}.{}.in-addr.arpa",
  230. addr_.bytes_[3],
  231. addr_.bytes_[2],
  232. addr_.bytes_[1],
  233. addr_.bytes_[0]);
  234. }
  235. // public
  236. uint8_t IPAddressV4::getNthMSByte(size_t byteIndex) const {
  237. const auto highestIndex = byteCount() - 1;
  238. if (byteIndex > highestIndex) {
  239. throw std::invalid_argument(sformat(
  240. "Byte index must be <= {} for addresses of type: {}",
  241. highestIndex,
  242. detail::familyNameStr(AF_INET)));
  243. }
  244. return bytes()[byteIndex];
  245. }
  246. // protected
  247. const ByteArray4 IPAddressV4::fetchMask(size_t numBits) {
  248. static const size_t bits = bitCount();
  249. if (numBits > bits) {
  250. throw IPAddressFormatException("IPv4 addresses are 32 bits");
  251. }
  252. auto const val = Endian::big(uint32_t(~uint64_t(0) << (32 - numBits)));
  253. ByteArray4 arr;
  254. std::memcpy(arr.data(), &val, sizeof(val));
  255. return arr;
  256. }
  257. // public static
  258. CIDRNetworkV4 IPAddressV4::longestCommonPrefix(
  259. const CIDRNetworkV4& one,
  260. const CIDRNetworkV4& two) {
  261. auto prefix = detail::Bytes::longestCommonPrefix(
  262. one.first.addr_.bytes_, one.second, two.first.addr_.bytes_, two.second);
  263. return {IPAddressV4(prefix.first), prefix.second};
  264. }
  265. } // namespace folly