2 * Copyright 2017 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/Optional.h>
29 #include <folly/Range.h>
30 #include <folly/detail/IPAddress.h>
40 * Pair of IPAddressV6, netmask
42 typedef std::pair<IPAddressV6, uint8_t> CIDRNetworkV6;
45 * Specialization for IPv6 addresses
47 typedef std::array<uint8_t, 16> ByteArray16;
50 * IPv6 variation of IPAddress.
52 * Added methods: createIPv4, getIPv4For6To4, is6To4,
53 * isTeredo, isIPv4Mapped, tryCreateIPv4, type
57 * Notes on scope ID parsing:
59 * getaddrinfo() uses if_nametoindex() to convert interface names
60 * into a numerical index. For instance,
61 * "fe80::202:c9ff:fec1:ee08%eth0" may return scope ID 2 on some
62 * hosts, but other numbers on other hosts. It will fail entirely on
63 * hosts without an eth0 interface.
65 * Serializing / Deserializing IPAddressB6's on different hosts
66 * that use link-local scoping probably won't work.
72 TEREDO, T6TO4, NORMAL,
74 // A constructor parameter to indicate that we should create a link-local
79 // Thrown when a type assertion fails
80 typedef std::runtime_error TypeError;
82 // Binary prefix for teredo networks
83 static const uint32_t PREFIX_TEREDO;
84 // Binary prefix for 6to4 networks
85 static const uint32_t PREFIX_6TO4;
87 // Size of std::string returned by toFullyQualified.
88 static constexpr size_t kToFullyQualifiedSize =
89 8 /*words*/ * 4 /*hex chars per word*/ + 7 /*separators*/;
91 // returns true iff the input string can be parsed as an ipv6-address
92 static bool validate(StringPiece ip);
95 * Create a new IPAddress instance from the provided binary data.
96 * @throws IPAddressFormatException if the input length is not 16 bytes.
98 static IPAddressV6 fromBinary(ByteRange bytes) {
100 addr.setFromBinary(bytes);
105 * Create a new IPAddress instance from the ip6.arpa representation.
106 * @throws IPAddressFormatException if the input is not a valid ip6.arpa
109 static IPAddressV6 fromInverseArpaName(const std::string& arpaname);
112 * Returns the address as a Range.
114 ByteRange toBinary() const {
115 return ByteRange((const unsigned char *) &addr_.in6Addr_.s6_addr, 16);
119 * Default constructor for IPAddressV6.
121 * The address value will be ::0
125 // Create an IPAddressV6 from a string
126 // @throws IPAddressFormatException
128 explicit IPAddressV6(StringPiece ip);
130 // ByteArray16 constructor
131 explicit IPAddressV6(const ByteArray16& src);
133 // in6_addr constructor
134 explicit IPAddressV6(const in6_addr& src);
136 // sockaddr_in6 constructor
137 explicit IPAddressV6(const sockaddr_in6& src);
140 * Create a link-local IPAddressV6 from the specified ethernet MAC address.
142 IPAddressV6(LinkLocalTag tag, MacAddress mac);
144 // return the mapped V4 address
145 // @throws IPAddressFormatException if !isIPv4Mapped
146 IPAddressV4 createIPv4() const;
149 * Return a V4 address if this is a 6To4 address.
150 * @throws TypeError if not a 6To4 address
152 IPAddressV4 getIPv4For6To4() const;
154 // Return true if a 6TO4 address
155 bool is6To4() const {
156 return type() == IPAddressV6::Type::T6TO4;
159 // Return true if a TEREDO address
160 bool isTeredo() const {
161 return type() == IPAddressV6::Type::TEREDO;
164 // return true if this is v4-to-v6-mapped
165 bool isIPv4Mapped() const;
167 // Return the V6 address type
171 * @see IPAddress#bitCount
174 static size_t bitCount() { return 128; }
177 * @see IPAddress#toJson
179 std::string toJson() const;
183 // @see IPAddress#inSubnet
184 // @throws IPAddressFormatException if string doesn't contain a V6 address
185 bool inSubnet(StringPiece cidrNetwork) const;
187 // return true if address is in subnet
188 bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
189 return inSubnetWithMask(subnet, fetchMask(cidr));
191 bool inSubnetWithMask(const IPAddressV6& subnet,
192 const ByteArray16& mask) const;
194 // @see IPAddress#isLoopback
195 bool isLoopback() const;
197 // @see IPAddress#isNonroutable
198 bool isNonroutable() const {
199 return !isRoutable();
203 * Return true if this address is routable.
205 bool isRoutable() const;
207 // @see IPAddress#isPrivate
208 bool isPrivate() const;
211 * Return true if this is a link-local IPv6 address.
213 * Note that this only returns true for addresses in the fe80::/10 range.
214 * It returns false for the loopback address (::1), even though this address
215 * is also effectively has link-local scope. It also returns false for
216 * link-scope and interface-scope multicast addresses.
218 bool isLinkLocal() const;
221 * Return the mac address if this is a link-local IPv6 address.
223 * @return an Optional<MacAddress> union representing the mac address.
225 * If the address is not a link-local one it will return an empty Optional.
226 * You can use Optional::value() to check whether the mac address is not null.
228 Optional<MacAddress> getMacAddressFromLinkLocal() const;
231 * Return true if this is a multicast address.
233 bool isMulticast() const;
236 * Return the flags for a multicast address.
237 * This method may only be called on multicast addresses.
239 uint8_t getMulticastFlags() const;
242 * Return the scope for a multicast address.
243 * This method may only be called on multicast addresses.
245 uint8_t getMulticastScope() const;
247 // @see IPAddress#isZero
248 bool isZero() const {
249 constexpr auto zero = ByteArray16{{}};
250 return 0 == std::memcmp(bytes(), zero.data(), zero.size());
253 bool isLinkLocalBroadcast() const;
255 // @see IPAddress#mask
256 IPAddressV6 mask(size_t numBits) const;
258 // return underlying in6_addr structure
259 in6_addr toAddr() const { return addr_.in6Addr_; }
261 uint16_t getScopeId() const { return scope_; }
262 void setScopeId(uint16_t scope) {
266 sockaddr_in6 toSockAddr() const {
268 memset(&addr, 0, sizeof(sockaddr_in6));
269 addr.sin6_family = AF_INET6;
270 addr.sin6_scope_id = scope_;
271 memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
275 ByteArray16 toByteArray() const {
277 std::memcpy(ba.data(), bytes(), 16);
281 // @see IPAddress#toFullyQualified
282 std::string toFullyQualified() const;
284 // @see IPAddress#toFullyQualifiedAppend
285 void toFullyQualifiedAppend(std::string& out) const;
287 std::string toInverseArpaName() const;
289 // @see IPAddress#str
290 std::string str() const;
292 // @see IPAddress#version
293 uint8_t version() const { return 6; }
296 * Return the solicited-node multicast address for this address.
298 IPAddressV6 getSolicitedNodeAddress() const;
301 * Return the mask associated with the given number of bits.
302 * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
303 * be {0xff, 0xff, 0xff, 0x00}.
304 * @param [in] numBits bitmask to retrieve
305 * @throws abort if numBits == 0 or numBits > bitCount()
306 * @return mask associated with numBits
308 static const ByteArray16 fetchMask(size_t numBits);
309 // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
311 static CIDRNetworkV6 longestCommonPrefix(
312 const CIDRNetworkV6& one,
313 const CIDRNetworkV6& two);
314 // Number of bytes in the address representation.
315 static constexpr size_t byteCount() { return 16; }
317 //get nth most significant bit - 0 indexed
318 bool getNthMSBit(size_t bitIndex) const {
319 return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
321 //get nth most significant byte - 0 indexed
322 uint8_t getNthMSByte(size_t byteIndex) const;
323 //get nth bit - 0 indexed
324 bool getNthLSBit(size_t bitIndex) const {
325 return getNthMSBit(bitCount() - bitIndex - 1);
327 //get nth byte - 0 indexed
328 uint8_t getNthLSByte(size_t byteIndex) const {
329 return getNthMSByte(byteCount() - byteIndex - 1);
332 const unsigned char* bytes() const { return addr_.in6Addr_.s6_addr; }
335 * Helper that returns true if the address is in the binary subnet specified
338 bool inBinarySubnet(const std::array<uint8_t, 2> addr,
339 size_t numBits) const;
342 union AddressStorage {
346 std::memset(this, 0, sizeof(AddressStorage));
348 explicit AddressStorage(const ByteArray16& bytes): bytes_(bytes) {}
349 explicit AddressStorage(const in6_addr& addr): in6Addr_(addr) {}
350 explicit AddressStorage(MacAddress mac);
353 // Link-local scope id. This should always be 0 for IPAddresses that
354 // are *not* link-local.
358 * Set the current IPAddressV6 object to have the address specified by bytes.
359 * @throws IPAddressFormatException if bytes.size() is not 16.
361 void setFromBinary(ByteRange bytes);
364 // boost::hash uses hash_value() so this allows boost::hash to work
365 // automatically for IPAddressV6
366 std::size_t hash_value(const IPAddressV6& addr);
367 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
368 // Define toAppend() to allow IPAddressV6 to be used with to<string>
369 void toAppend(IPAddressV6 addr, std::string* result);
370 void toAppend(IPAddressV6 addr, fbstring* result);
373 * Return true if two addresses are equal.
375 inline bool operator==(const IPAddressV6& addr1, const IPAddressV6& addr2) {
376 return (std::memcmp(addr1.toAddr().s6_addr, addr2.toAddr().s6_addr, 16) == 0)
377 && addr1.getScopeId() == addr2.getScopeId();
379 // Return true if addr1 < addr2
380 inline bool operator<(const IPAddressV6& addr1, const IPAddressV6& addr2) {
381 auto cmp = std::memcmp(addr1.toAddr().s6_addr,
382 addr2.toAddr().s6_addr, 16) < 0;
384 return addr1.getScopeId() < addr2.getScopeId();
390 inline bool operator!=(const IPAddressV6& a, const IPAddressV6& b) {
393 inline bool operator>(const IPAddressV6& a, const IPAddressV6& b) {
396 inline bool operator<=(const IPAddressV6& a, const IPAddressV6& b) {
399 inline bool operator>=(const IPAddressV6& a, const IPAddressV6& b) {
407 struct hash<folly::IPAddressV6> {
408 size_t operator()(const folly::IPAddressV6& addr) const {