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/FBString.h>
28 #include <folly/Hash.h>
29 #include <folly/Optional.h>
30 #include <folly/Range.h>
31 #include <folly/detail/IPAddress.h>
41 * Pair of IPAddressV6, netmask
43 typedef std::pair<IPAddressV6, uint8_t> CIDRNetworkV6;
46 * Specialization for IPv6 addresses
48 typedef std::array<uint8_t, 16> ByteArray16;
51 * IPv6 variation of IPAddress.
53 * Added methods: createIPv4, getIPv4For6To4, is6To4,
54 * isTeredo, isIPv4Mapped, tryCreateIPv4, type
58 * Notes on scope ID parsing:
60 * getaddrinfo() uses if_nametoindex() to convert interface names
61 * into a numerical index. For instance,
62 * "fe80::202:c9ff:fec1:ee08%eth0" may return scope ID 2 on some
63 * hosts, but other numbers on other hosts. It will fail entirely on
64 * hosts without an eth0 interface.
66 * Serializing / Deserializing IPAddressB6's on different hosts
67 * that use link-local scoping probably won't work.
77 // A constructor parameter to indicate that we should create a link-local
82 // Thrown when a type assertion fails
83 typedef std::runtime_error TypeError;
85 // Binary prefix for teredo networks
86 static const uint32_t PREFIX_TEREDO;
87 // Binary prefix for 6to4 networks
88 static const uint32_t PREFIX_6TO4;
90 // Size of std::string returned by toFullyQualified.
91 static constexpr size_t kToFullyQualifiedSize =
92 8 /*words*/ * 4 /*hex chars per word*/ + 7 /*separators*/;
94 // returns true iff the input string can be parsed as an ipv6-address
95 static bool validate(StringPiece ip);
98 * Create a new IPAddress instance from the provided binary data.
99 * @throws IPAddressFormatException if the input length is not 16 bytes.
101 static IPAddressV6 fromBinary(ByteRange bytes) {
103 addr.setFromBinary(bytes);
108 * Create a new IPAddress instance from the ip6.arpa representation.
109 * @throws IPAddressFormatException if the input is not a valid ip6.arpa
112 static IPAddressV6 fromInverseArpaName(const std::string& arpaname);
115 * Returns the address as a Range.
117 ByteRange toBinary() const {
118 return ByteRange((const unsigned char*)&addr_.in6Addr_.s6_addr, 16);
122 * Default constructor for IPAddressV6.
124 * The address value will be ::0
128 // Create an IPAddressV6 from a string
129 // @throws IPAddressFormatException
131 explicit IPAddressV6(StringPiece ip);
133 // ByteArray16 constructor
134 explicit IPAddressV6(const ByteArray16& src);
136 // in6_addr constructor
137 explicit IPAddressV6(const in6_addr& src);
139 // sockaddr_in6 constructor
140 explicit IPAddressV6(const sockaddr_in6& src);
143 * Create a link-local IPAddressV6 from the specified ethernet MAC address.
145 IPAddressV6(LinkLocalTag tag, MacAddress mac);
147 // return the mapped V4 address
148 // @throws IPAddressFormatException if !isIPv4Mapped
149 IPAddressV4 createIPv4() const;
152 * Return a V4 address if this is a 6To4 address.
153 * @throws TypeError if not a 6To4 address
155 IPAddressV4 getIPv4For6To4() const;
157 // Return true if a 6TO4 address
158 bool is6To4() const {
159 return type() == IPAddressV6::Type::T6TO4;
162 // Return true if a TEREDO address
163 bool isTeredo() const {
164 return type() == IPAddressV6::Type::TEREDO;
167 // return true if this is v4-to-v6-mapped
168 bool isIPv4Mapped() const;
170 // Return the V6 address type
174 * @see IPAddress#bitCount
177 static constexpr size_t bitCount() {
182 * @see IPAddress#toJson
184 std::string toJson() const;
188 // @see IPAddress#inSubnet
189 // @throws IPAddressFormatException if string doesn't contain a V6 address
190 bool inSubnet(StringPiece cidrNetwork) const;
192 // return true if address is in subnet
193 bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
194 return inSubnetWithMask(subnet, fetchMask(cidr));
196 bool inSubnetWithMask(const IPAddressV6& subnet, const ByteArray16& mask)
199 // @see IPAddress#isLoopback
200 bool isLoopback() const;
202 // @see IPAddress#isNonroutable
203 bool isNonroutable() const {
204 return !isRoutable();
208 * Return true if this address is routable.
210 bool isRoutable() const;
212 // @see IPAddress#isPrivate
213 bool isPrivate() const;
216 * Return true if this is a link-local IPv6 address.
218 * Note that this only returns true for addresses in the fe80::/10 range.
219 * It returns false for the loopback address (::1), even though this address
220 * is also effectively has link-local scope. It also returns false for
221 * link-scope and interface-scope multicast addresses.
223 bool isLinkLocal() const;
226 * Return the mac address if this is a link-local IPv6 address.
228 * @return an Optional<MacAddress> union representing the mac address.
230 * If the address is not a link-local one it will return an empty Optional.
231 * You can use Optional::value() to check whether the mac address is not null.
233 Optional<MacAddress> getMacAddressFromLinkLocal() const;
236 * Return the mac address if this is an auto-configured IPv6 address based on
239 * @return an Optional<MacAddress> union representing the mac address.
240 * If the address is not based on EUI-64 it will return an empty Optional.
241 * You can use Optional::value() to check whether the mac address is not null.
243 Optional<MacAddress> getMacAddressFromEUI64() const;
246 * Return true if this is a multicast address.
248 bool isMulticast() const;
251 * Return the flags for a multicast address.
252 * This method may only be called on multicast addresses.
254 uint8_t getMulticastFlags() const;
257 * Return the scope for a multicast address.
258 * This method may only be called on multicast addresses.
260 uint8_t getMulticastScope() const;
262 // @see IPAddress#isZero
263 bool isZero() const {
264 constexpr auto zero = ByteArray16{{}};
265 return 0 == std::memcmp(bytes(), zero.data(), zero.size());
268 bool isLinkLocalBroadcast() const;
270 // @see IPAddress#mask
271 IPAddressV6 mask(size_t numBits) const;
273 // return underlying in6_addr structure
274 in6_addr toAddr() const {
275 return addr_.in6Addr_;
278 uint16_t getScopeId() const {
281 void setScopeId(uint16_t scope) {
285 sockaddr_in6 toSockAddr() const {
287 memset(&addr, 0, sizeof(sockaddr_in6));
288 addr.sin6_family = AF_INET6;
289 addr.sin6_scope_id = scope_;
290 memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
294 ByteArray16 toByteArray() const {
296 std::memcpy(ba.data(), bytes(), 16);
300 // @see IPAddress#toFullyQualified
301 std::string toFullyQualified() const;
303 // @see IPAddress#toFullyQualifiedAppend
304 void toFullyQualifiedAppend(std::string& out) const;
306 std::string toInverseArpaName() const;
308 // @see IPAddress#str
309 std::string str() const;
311 // @see IPAddress#version
312 uint8_t version() const {
317 * Return the solicited-node multicast address for this address.
319 IPAddressV6 getSolicitedNodeAddress() const;
322 * Return the mask associated with the given number of bits.
323 * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
324 * be {0xff, 0xff, 0xff, 0x00}.
325 * @param [in] numBits bitmask to retrieve
326 * @throws abort if numBits == 0 or numBits > bitCount()
327 * @return mask associated with numBits
329 static const ByteArray16 fetchMask(size_t numBits);
330 // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
332 static CIDRNetworkV6 longestCommonPrefix(
333 const CIDRNetworkV6& one,
334 const CIDRNetworkV6& two);
335 // Number of bytes in the address representation.
336 static constexpr size_t byteCount() {
340 // get nth most significant bit - 0 indexed
341 bool getNthMSBit(size_t bitIndex) const {
342 return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
344 // get nth most significant byte - 0 indexed
345 uint8_t getNthMSByte(size_t byteIndex) const;
346 // get nth bit - 0 indexed
347 bool getNthLSBit(size_t bitIndex) const {
348 return getNthMSBit(bitCount() - bitIndex - 1);
350 // get nth byte - 0 indexed
351 uint8_t getNthLSByte(size_t byteIndex) const {
352 return getNthMSByte(byteCount() - byteIndex - 1);
355 const unsigned char* bytes() const {
356 return addr_.in6Addr_.s6_addr;
361 * Helper that returns true if the address is in the binary subnet specified
364 bool inBinarySubnet(const std::array<uint8_t, 2> addr, size_t numBits) const;
368 return std::tie(addr_.bytes_, scope_);
372 friend inline bool operator==(const IPAddressV6& a, const IPAddressV6& b) {
373 return a.tie() == b.tie();
375 friend inline bool operator!=(const IPAddressV6& a, const IPAddressV6& b) {
376 return a.tie() != b.tie();
378 friend inline bool operator<(const IPAddressV6& a, const IPAddressV6& b) {
379 return a.tie() < b.tie();
381 friend inline bool operator>(const IPAddressV6& a, const IPAddressV6& b) {
382 return a.tie() > b.tie();
384 friend inline bool operator<=(const IPAddressV6& a, const IPAddressV6& b) {
385 return a.tie() <= b.tie();
387 friend inline bool operator>=(const IPAddressV6& a, const IPAddressV6& b) {
388 return a.tie() >= b.tie();
392 union AddressStorage {
396 std::memset(this, 0, sizeof(AddressStorage));
398 explicit AddressStorage(const ByteArray16& bytes) : bytes_(bytes) {}
399 explicit AddressStorage(const in6_addr& addr) : in6Addr_(addr) {}
400 explicit AddressStorage(MacAddress mac);
403 // Link-local scope id. This should always be 0 for IPAddresses that
404 // are *not* link-local.
408 * Set the current IPAddressV6 object to have the address specified by bytes.
409 * @throws IPAddressFormatException if bytes.size() is not 16.
411 void setFromBinary(ByteRange bytes);
414 // boost::hash uses hash_value() so this allows boost::hash to work
415 // automatically for IPAddressV6
416 std::size_t hash_value(const IPAddressV6& addr);
417 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
418 // Define toAppend() to allow IPAddressV6 to be used with to<string>
419 void toAppend(IPAddressV6 addr, std::string* result);
420 void toAppend(IPAddressV6 addr, fbstring* result);
426 struct hash<folly::IPAddressV6> {
427 size_t operator()(const folly::IPAddressV6& addr) const {