1 /* 2 * Copyright (c) Facebook, Inc. and its affiliates. 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 17 #pragma once 18 19 #include <cstring> 20 21 #include <array> 22 #include <functional> 23 #include <iosfwd> 24 25 #include <folly/Expected.h> 26 #include <folly/FBString.h> 27 #include <folly/IPAddressException.h> 28 #include <folly/Range.h> 29 #include <folly/detail/IPAddress.h> 30 #include <folly/hash/Hash.h> 31 32 #ifdef __XROS__ 33 #include <xros/portability/third_party/include/netinet/in.h> // @manual 34 #endif 35 36 namespace folly { 37 38 class IPAddress; 39 class IPAddressV4; 40 class IPAddressV6; 41 42 /** 43 * Pair of IPAddressV4, netmask 44 */ 45 typedef std::pair<IPAddressV4, uint8_t> CIDRNetworkV4; 46 47 /** 48 * Specialization for IPv4 addresses 49 */ 50 typedef std::array<uint8_t, 4> ByteArray4; 51 52 /** 53 * IPv4 variation of IPAddress. 54 * 55 * Added methods: toLong, toLongHBO and createIPv6 56 * 57 * @note toLong/fromLong deal in network byte order, use toLongHBO/fromLongHBO 58 * if working in host byte order. 59 * 60 * @see IPAddress 61 */ 62 class IPAddressV4 { 63 public: 64 // Max size of std::string returned by toFullyQualified. 65 static constexpr size_t kMaxToFullyQualifiedSize = 66 4 /*words*/ * 3 /*max chars per word*/ + 3 /*separators*/; 67 68 // returns true iff the input string can be parsed as an ipv4-address 69 static bool validate(StringPiece ip) noexcept; 70 71 // create an IPAddressV4 instance from a uint32_t (network byte order) 72 static IPAddressV4 fromLong(uint32_t src); 73 // same as above but host byte order 74 static IPAddressV4 fromLongHBO(uint32_t src); 75 76 /** 77 * Create a new IPAddress instance from the provided binary data. 78 * @throws IPAddressFormatException if the input length is not 4 bytes. 79 */ 80 static IPAddressV4 fromBinary(ByteRange bytes); 81 82 /** 83 * Non-throwing version of fromBinary(). 84 * On failure returns IPAddressFormatError. 85 */ 86 static Expected<IPAddressV4, IPAddressFormatError> tryFromBinary( 87 ByteRange bytes) noexcept; 88 89 /** 90 * Tries to create a new IPAddressV4 instance from provided string and 91 * returns it on success. Returns IPAddressFormatError on failure. 92 */ 93 static Expected<IPAddressV4, IPAddressFormatError> tryFromString( 94 StringPiece str) noexcept; 95 96 /** 97 * Returns the address as a Range. 98 */ toBinary()99 ByteRange toBinary() const { 100 return ByteRange((const unsigned char*)&addr_.inAddr_.s_addr, 4); 101 } 102 103 /** 104 * Create a new IPAddress instance from the in-addr.arpa representation. 105 * @throws IPAddressFormatException if the input is not a valid in-addr.arpa 106 * representation 107 */ 108 static IPAddressV4 fromInverseArpaName(const std::string& arpaname); 109 110 /** 111 * Convert a IPv4 address string to a long in network byte order. 112 * @param [in] ip the address to convert 113 * @return the long representation of the address 114 */ 115 static uint32_t toLong(StringPiece ip); 116 // Same as above, but in host byte order. 117 // This is slightly slower than toLong. 118 static uint32_t toLongHBO(StringPiece ip); 119 120 /** 121 * Default constructor for IPAddressV4. 122 * 123 * The address value will be 0.0.0.0 124 */ 125 IPAddressV4(); 126 127 // Create an IPAddressV4 from a string 128 // @throws IPAddressFormatException 129 explicit IPAddressV4(StringPiece addr); 130 131 // ByteArray4 constructor 132 explicit IPAddressV4(const ByteArray4& src) noexcept; 133 134 // in_addr constructor 135 explicit IPAddressV4(const in_addr src) noexcept; 136 137 // Return the V6 mapped representation of the address. 138 IPAddressV6 createIPv6() const; 139 140 /** 141 * Return a V6 address in the format of an 6To4 address. 142 */ 143 IPAddressV6 getIPv6For6To4() const; 144 145 // Return the long (network byte order) representation of the address. toLong()146 uint32_t toLong() const { return toAddr().s_addr; } 147 148 // Return the long (host byte order) representation of the address. 149 // This is slightly slower than toLong. toLongHBO()150 uint32_t toLongHBO() const { return ntohl(toLong()); } 151 152 /** 153 * @see IPAddress#bitCount 154 * @returns 32 155 */ bitCount()156 static constexpr size_t bitCount() { return 32; } 157 158 /** 159 * @See IPAddress#toJson 160 */ 161 std::string toJson() const; 162 hash()163 size_t hash() const { 164 static const uint32_t seed = AF_INET; 165 uint32_t hashed = hash::fnv32_buf(&addr_, 4); 166 return hash::hash_combine(seed, hashed); 167 } 168 169 // @see IPAddress#inSubnet 170 // @throws IPAddressFormatException if string doesn't contain a V4 address 171 bool inSubnet(StringPiece cidrNetwork) const; 172 173 // return true if address is in subnet inSubnet(const IPAddressV4 & subnet,uint8_t cidr)174 bool inSubnet(const IPAddressV4& subnet, uint8_t cidr) const { 175 return inSubnetWithMask(subnet, fetchMask(cidr)); 176 } 177 bool inSubnetWithMask(const IPAddressV4& subnet, const ByteArray4 mask) const; 178 179 // @see IPAddress#isLoopback 180 bool isLoopback() const; 181 182 // @see IPAddress#isLinkLocal 183 bool isLinkLocal() const; 184 185 // @see IPAddress#isNonroutable 186 bool isNonroutable() const; 187 188 // @see IPAddress#isPrivate 189 bool isPrivate() const; 190 191 // @see IPAddress#isMulticast 192 bool isMulticast() const; 193 194 // @see IPAddress#isZero isZero()195 bool isZero() const { 196 constexpr auto zero = ByteArray4{{}}; 197 return 0 == std::memcmp(bytes(), zero.data(), zero.size()); 198 } 199 isLinkLocalBroadcast()200 bool isLinkLocalBroadcast() const { 201 return (INADDR_BROADCAST == toLongHBO()); 202 } 203 204 // @see IPAddress#mask 205 IPAddressV4 mask(size_t numBits) const; 206 207 // @see IPAddress#str 208 std::string str() const; 209 210 std::string toInverseArpaName() const; 211 212 // return underlying in_addr structure toAddr()213 in_addr toAddr() const { return addr_.inAddr_; } 214 toSockAddr()215 sockaddr_in toSockAddr() const { 216 sockaddr_in addr; 217 memset(&addr, 0, sizeof(sockaddr_in)); 218 addr.sin_family = AF_INET; 219 memcpy(&addr.sin_addr, &addr_.inAddr_, sizeof(in_addr)); 220 return addr; 221 } 222 toByteArray()223 ByteArray4 toByteArray() const { 224 ByteArray4 ba{{0}}; 225 std::memcpy(ba.data(), bytes(), 4); 226 return ba; 227 } 228 229 // @see IPAddress#toFullyQualified toFullyQualified()230 std::string toFullyQualified() const { return str(); } 231 232 // @see IPAddress#toFullyQualifiedAppend 233 void toFullyQualifiedAppend(std::string& out) const; 234 235 // @see IPAddress#version version()236 uint8_t version() const { return 4; } 237 238 /** 239 * Return the mask associated with the given number of bits. 240 * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should 241 * be {0xff, 0xff, 0xff, 0x00}. 242 * @param [in] numBits bitmask to retrieve 243 * @throws abort if numBits == 0 or numBits > bitCount() 244 * @return mask associated with numBits 245 */ 246 static ByteArray4 fetchMask(size_t numBits); 247 248 // Given 2 IPAddressV4, mask pairs extract the longest common IPAddress, 249 // mask pair 250 static CIDRNetworkV4 longestCommonPrefix( 251 const CIDRNetworkV4& one, const CIDRNetworkV4& two); 252 // Number of bytes in the address representation. byteCount()253 static size_t byteCount() { return 4; } 254 // get nth most significant bit - 0 indexed getNthMSBit(size_t bitIndex)255 bool getNthMSBit(size_t bitIndex) const { 256 return detail::getNthMSBitImpl(*this, bitIndex, AF_INET); 257 } 258 // get nth most significant byte - 0 indexed 259 uint8_t getNthMSByte(size_t byteIndex) const; 260 // get nth bit - 0 indexed getNthLSBit(size_t bitIndex)261 bool getNthLSBit(size_t bitIndex) const { 262 return getNthMSBit(bitCount() - bitIndex - 1); 263 } 264 // get nth byte - 0 indexed getNthLSByte(size_t byteIndex)265 uint8_t getNthLSByte(size_t byteIndex) const { 266 return getNthMSByte(byteCount() - byteIndex - 1); 267 } 268 bytes()269 const unsigned char* bytes() const { return addr_.bytes_.data(); } 270 271 private: 272 union AddressStorage { 273 static_assert( 274 sizeof(in_addr) == sizeof(ByteArray4), 275 "size of in_addr and ByteArray4 are different"); 276 in_addr inAddr_; 277 ByteArray4 bytes_; AddressStorage()278 AddressStorage() { std::memset(this, 0, sizeof(AddressStorage)); } AddressStorage(const ByteArray4 bytes)279 explicit AddressStorage(const ByteArray4 bytes) : bytes_(bytes) {} AddressStorage(const in_addr addr)280 explicit AddressStorage(const in_addr addr) : inAddr_(addr) {} 281 } addr_; 282 283 /** 284 * Set the current IPAddressV4 object to have the address specified by bytes. 285 * Returns IPAddressFormatError if bytes.size() is not 4. 286 */ 287 Expected<Unit, IPAddressFormatError> trySetFromBinary( 288 ByteRange bytes) noexcept; 289 }; 290 291 // boost::hash uses hash_value() so this allows boost::hash to work 292 // automatically for IPAddressV4 293 size_t hash_value(const IPAddressV4& addr); 294 std::ostream& operator<<(std::ostream& os, const IPAddressV4& addr); 295 // Define toAppend() to allow IPAddressV4 to be used with to<string> 296 void toAppend(IPAddressV4 addr, std::string* result); 297 void toAppend(IPAddressV4 addr, fbstring* result); 298 299 /** 300 * Return true if two addresses are equal. 301 */ 302 inline bool operator==(const IPAddressV4& addr1, const IPAddressV4& addr2) { 303 return (addr1.toLong() == addr2.toLong()); 304 } 305 // Return true if addr1 < addr2 306 inline bool operator<(const IPAddressV4& addr1, const IPAddressV4& addr2) { 307 return (addr1.toLongHBO() < addr2.toLongHBO()); 308 } 309 // Derived operators 310 inline bool operator!=(const IPAddressV4& a, const IPAddressV4& b) { 311 return !(a == b); 312 } 313 inline bool operator>(const IPAddressV4& a, const IPAddressV4& b) { 314 return b < a; 315 } 316 inline bool operator<=(const IPAddressV4& a, const IPAddressV4& b) { 317 return !(a > b); 318 } 319 inline bool operator>=(const IPAddressV4& a, const IPAddressV4& b) { 320 return !(a < b); 321 } 322 323 } // namespace folly 324 325 namespace std { 326 template <> 327 struct hash<folly::IPAddressV4> { 328 size_t operator()(const folly::IPAddressV4 addr) const { return addr.hash(); } 329 }; 330 } // namespace std 331