2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
27 #include <folly/Hash.h>
28 #include <folly/Range.h>
29 #include <folly/detail/IPAddress.h>
39 * Pair of IPAddressV6, netmask
41 typedef std::pair<IPAddressV6, uint8_t> CIDRNetworkV6;
44 * Specialization for IPv6 addresses
46 typedef std::array<uint8_t, 16> ByteArray16;
49 * IPv6 variation of IPAddress.
51 * Added methods: createIPv4, getIPv4For6To4, is6To4,
52 * isTeredo, isIPv4Mapped, tryCreateIPv4, type
56 * Notes on scope ID parsing:
58 * getaddrinfo() uses if_nametoindex() to convert interface names
59 * into a numerical index. For instance,
60 * "fe80::202:c9ff:fec1:ee08%eth0" may return scope ID 2 on some
61 * hosts, but other numbers on other hosts. It will fail entirely on
62 * hosts without an eth0 interface.
64 * Serializing / Deserializing IPAddressB6's on different hosts
65 * that use link-local scoping probably won't work.
71 TEREDO, T6TO4, NORMAL,
73 // A constructor parameter to indicate that we should create a link-local
78 // Thrown when a type assertion fails
79 typedef std::runtime_error TypeError;
81 // Binary prefix for teredo networks
82 static const uint32_t PREFIX_TEREDO;
83 // Binary prefix for 6to4 networks
84 static const uint32_t PREFIX_6TO4;
86 // Size of std::string returned by toFullyQualified.
87 static constexpr size_t kToFullyQualifiedSize =
88 8 /*words*/ * 4 /*hex chars per word*/ + 7 /*separators*/;
90 // returns true iff the input string can be parsed as an ipv6-address
91 static bool validate(StringPiece ip);
94 * Create a new IPAddress instance from the provided binary data.
95 * @throws IPAddressFormatException if the input length is not 16 bytes.
97 static IPAddressV6 fromBinary(ByteRange bytes) {
99 addr.setFromBinary(bytes);
104 * Returns the address as a Range.
106 ByteRange toBinary() const {
107 return ByteRange((const unsigned char *) &addr_.in6Addr_.s6_addr, 16);
111 * Default constructor for IPAddressV6.
113 * The address value will be ::0
117 // Create an IPAddressV6 from a string
118 // @throws IPAddressFormatException
120 explicit IPAddressV6(StringPiece ip);
122 // ByteArray16 constructor
123 explicit IPAddressV6(const ByteArray16& src);
125 // in6_addr constructor
126 explicit IPAddressV6(const in6_addr& src);
128 // sockaddr_in6 constructor
129 explicit IPAddressV6(const sockaddr_in6& src);
132 * Create a link-local IPAddressV6 from the specified ethernet MAC address.
134 IPAddressV6(LinkLocalTag tag, MacAddress mac);
136 // return the mapped V4 address
137 // @throws IPAddressFormatException if !isIPv4Mapped
138 IPAddressV4 createIPv4() const;
141 * Return a V4 address if this is a 6To4 address.
142 * @throws TypeError if not a 6To4 address
144 IPAddressV4 getIPv4For6To4() const;
146 // Return true if a 6TO4 address
147 bool is6To4() const {
148 return type() == IPAddressV6::Type::T6TO4;
151 // Return true if a TEREDO address
152 bool isTeredo() const {
153 return type() == IPAddressV6::Type::TEREDO;
156 // return true if this is v4-to-v6-mapped
157 bool isIPv4Mapped() const;
159 // Return the V6 address type
163 * @see IPAddress#bitCount
166 static size_t bitCount() { return 128; }
169 * @see IPAddress#toJson
171 std::string toJson() const;
175 // @see IPAddress#inSubnet
176 // @throws IPAddressFormatException if string doesn't contain a V6 address
177 bool inSubnet(StringPiece cidrNetwork) const;
179 // return true if address is in subnet
180 bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
181 return inSubnetWithMask(subnet, fetchMask(cidr));
183 bool inSubnetWithMask(const IPAddressV6& subnet,
184 const ByteArray16& mask) const;
186 // @see IPAddress#isLoopback
187 bool isLoopback() const;
189 // @see IPAddress#isNonroutable
190 bool isNonroutable() const {
191 return !isRoutable();
195 * Return true if this address is routable.
197 bool isRoutable() const;
199 // @see IPAddress#isPrivate
200 bool isPrivate() const;
203 * Return true if this is a link-local IPv6 address.
205 * Note that this only returns true for addresses in the fe80::/10 range.
206 * It returns false for the loopback address (::1), even though this address
207 * is also effectively has link-local scope. It also returns false for
208 * link-scope and interface-scope multicast addresses.
210 bool isLinkLocal() const;
213 * Return true if this is a multicast address.
215 bool isMulticast() const;
218 * Return the flags for a multicast address.
219 * This method may only be called on multicast addresses.
221 uint8_t getMulticastFlags() const;
224 * Return the scope for a multicast address.
225 * This method may only be called on multicast addresses.
227 uint8_t getMulticastScope() const;
229 // @see IPAddress#isZero
230 bool isZero() const {
231 constexpr auto zero = ByteArray16{{}};
232 return 0 == std::memcmp(bytes(), zero.data(), zero.size());
235 bool isLinkLocalBroadcast() const;
237 // @see IPAddress#mask
238 IPAddressV6 mask(size_t numBits) const;
240 // return underlying in6_addr structure
241 in6_addr toAddr() const { return addr_.in6Addr_; }
243 uint16_t getScopeId() const { return scope_; }
244 void setScopeId(uint16_t scope) {
248 sockaddr_in6 toSockAddr() const {
250 memset(&addr, 0, sizeof(sockaddr_in6));
251 addr.sin6_family = AF_INET6;
252 addr.sin6_scope_id = scope_;
253 memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
257 ByteArray16 toByteArray() const {
259 std::memcpy(ba.data(), bytes(), 16);
263 // @see IPAddress#toFullyQualified
264 std::string toFullyQualified() const;
266 // @see IPAddress#str
267 std::string str() const;
269 // @see IPAddress#version
270 uint8_t version() const { return 6; }
273 * Return the solicited-node multicast address for this address.
275 IPAddressV6 getSolicitedNodeAddress() const;
278 * Return the mask associated with the given number of bits.
279 * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
280 * be {0xff, 0xff, 0xff, 0x00}.
281 * @param [in] numBits bitmask to retrieve
282 * @throws abort if numBits == 0 or numBits > bitCount()
283 * @return mask associated with numBits
285 static const ByteArray16 fetchMask(size_t numBits);
286 // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
288 static CIDRNetworkV6 longestCommonPrefix(
289 const CIDRNetworkV6& one,
290 const CIDRNetworkV6& two);
291 // Number of bytes in the address representation.
292 static constexpr size_t byteCount() { return 16; }
294 //get nth most significant bit - 0 indexed
295 bool getNthMSBit(size_t bitIndex) const {
296 return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
298 //get nth most significant byte - 0 indexed
299 uint8_t getNthMSByte(size_t byteIndex) const;
300 //get nth bit - 0 indexed
301 bool getNthLSBit(size_t bitIndex) const {
302 return getNthMSBit(bitCount() - bitIndex - 1);
304 //get nth byte - 0 indexed
305 uint8_t getNthLSByte(size_t byteIndex) const {
306 return getNthMSByte(byteCount() - byteIndex - 1);
309 const unsigned char* bytes() const { return addr_.in6Addr_.s6_addr; }
312 * Helper that returns true if the address is in the binary subnet specified
315 bool inBinarySubnet(const std::array<uint8_t, 2> addr,
316 size_t numBits) const;
319 union AddressStorage {
323 std::memset(this, 0, sizeof(AddressStorage));
325 explicit AddressStorage(const ByteArray16& bytes): bytes_(bytes) {}
326 explicit AddressStorage(const in6_addr& addr): in6Addr_(addr) {}
327 explicit AddressStorage(MacAddress mac);
330 // Link-local scope id. This should always be 0 for IPAddresses that
331 // are *not* link-local.
334 static const std::array<ByteArray16, 129> masks_;
337 * Set the current IPAddressV6 object to have the address specified by bytes.
338 * @throws IPAddressFormatException if bytes.size() is not 16.
340 void setFromBinary(ByteRange bytes);
343 // boost::hash uses hash_value() so this allows boost::hash to work
344 // automatically for IPAddressV6
345 std::size_t hash_value(const IPAddressV6& addr);
346 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
347 // Define toAppend() to allow IPAddressV6 to be used with to<string>
348 void toAppend(IPAddressV6 addr, std::string* result);
349 void toAppend(IPAddressV6 addr, fbstring* result);
352 * Return true if two addresses are equal.
354 inline bool operator==(const IPAddressV6& addr1, const IPAddressV6& addr2) {
355 return (std::memcmp(addr1.toAddr().s6_addr, addr2.toAddr().s6_addr, 16) == 0)
356 && addr1.getScopeId() == addr2.getScopeId();
358 // Return true if addr1 < addr2
359 inline bool operator<(const IPAddressV6& addr1, const IPAddressV6& addr2) {
360 auto cmp = std::memcmp(addr1.toAddr().s6_addr,
361 addr2.toAddr().s6_addr, 16) < 0;
363 return addr1.getScopeId() < addr2.getScopeId();
369 inline bool operator!=(const IPAddressV6& a, const IPAddressV6& b) {
372 inline bool operator>(const IPAddressV6& a, const IPAddressV6& b) {
375 inline bool operator<=(const IPAddressV6& a, const IPAddressV6& b) {
378 inline bool operator>=(const IPAddressV6& a, const IPAddressV6& b) {
386 struct hash<folly::IPAddressV6> {
387 size_t operator()(const folly::IPAddressV6& addr) const {