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.
76 // A constructor parameter to indicate that we should create a link-local
81 // Thrown when a type assertion fails
82 typedef std::runtime_error TypeError;
84 // Binary prefix for teredo networks
85 static const uint32_t PREFIX_TEREDO;
86 // Binary prefix for 6to4 networks
87 static const uint32_t PREFIX_6TO4;
89 // Size of std::string returned by toFullyQualified.
90 static constexpr size_t kToFullyQualifiedSize =
91 8 /*words*/ * 4 /*hex chars per word*/ + 7 /*separators*/;
93 // returns true iff the input string can be parsed as an ipv6-address
94 static bool validate(StringPiece ip);
97 * Create a new IPAddress instance from the provided binary data.
98 * @throws IPAddressFormatException if the input length is not 16 bytes.
100 static IPAddressV6 fromBinary(ByteRange bytes) {
102 addr.setFromBinary(bytes);
107 * Create a new IPAddress instance from the ip6.arpa representation.
108 * @throws IPAddressFormatException if the input is not a valid ip6.arpa
111 static IPAddressV6 fromInverseArpaName(const std::string& arpaname);
114 * Returns the address as a Range.
116 ByteRange toBinary() const {
117 return ByteRange((const unsigned char*)&addr_.in6Addr_.s6_addr, 16);
121 * Default constructor for IPAddressV6.
123 * The address value will be ::0
127 // Create an IPAddressV6 from a string
128 // @throws IPAddressFormatException
130 explicit IPAddressV6(StringPiece ip);
132 // ByteArray16 constructor
133 explicit IPAddressV6(const ByteArray16& src);
135 // in6_addr constructor
136 explicit IPAddressV6(const in6_addr& src);
138 // sockaddr_in6 constructor
139 explicit IPAddressV6(const sockaddr_in6& src);
142 * Create a link-local IPAddressV6 from the specified ethernet MAC address.
144 IPAddressV6(LinkLocalTag tag, MacAddress mac);
146 // return the mapped V4 address
147 // @throws IPAddressFormatException if !isIPv4Mapped
148 IPAddressV4 createIPv4() const;
151 * Return a V4 address if this is a 6To4 address.
152 * @throws TypeError if not a 6To4 address
154 IPAddressV4 getIPv4For6To4() const;
156 // Return true if a 6TO4 address
157 bool is6To4() const {
158 return type() == IPAddressV6::Type::T6TO4;
161 // Return true if a TEREDO address
162 bool isTeredo() const {
163 return type() == IPAddressV6::Type::TEREDO;
166 // return true if this is v4-to-v6-mapped
167 bool isIPv4Mapped() const;
169 // Return the V6 address type
173 * @see IPAddress#bitCount
176 static constexpr size_t bitCount() {
181 * @see IPAddress#toJson
183 std::string toJson() const;
187 // @see IPAddress#inSubnet
188 // @throws IPAddressFormatException if string doesn't contain a V6 address
189 bool inSubnet(StringPiece cidrNetwork) const;
191 // return true if address is in subnet
192 bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
193 return inSubnetWithMask(subnet, fetchMask(cidr));
195 bool inSubnetWithMask(const IPAddressV6& subnet, const ByteArray16& mask)
198 // @see IPAddress#isLoopback
199 bool isLoopback() const;
201 // @see IPAddress#isNonroutable
202 bool isNonroutable() const {
203 return !isRoutable();
207 * Return true if this address is routable.
209 bool isRoutable() const;
211 // @see IPAddress#isPrivate
212 bool isPrivate() const;
215 * Return true if this is a link-local IPv6 address.
217 * Note that this only returns true for addresses in the fe80::/10 range.
218 * It returns false for the loopback address (::1), even though this address
219 * is also effectively has link-local scope. It also returns false for
220 * link-scope and interface-scope multicast addresses.
222 bool isLinkLocal() const;
225 * Return the mac address if this is a link-local IPv6 address.
227 * @return an Optional<MacAddress> union representing the mac address.
229 * If the address is not a link-local one it will return an empty Optional.
230 * You can use Optional::value() to check whether the mac address is not null.
232 Optional<MacAddress> getMacAddressFromLinkLocal() const;
235 * Return the mac address if this is an auto-configured IPv6 address based on
238 * @return an Optional<MacAddress> union representing the mac address.
239 * If the address is not based on EUI-64 it will return an empty Optional.
240 * You can use Optional::value() to check whether the mac address is not null.
242 Optional<MacAddress> getMacAddressFromEUI64() const;
245 * Return true if this is a multicast address.
247 bool isMulticast() const;
250 * Return the flags for a multicast address.
251 * This method may only be called on multicast addresses.
253 uint8_t getMulticastFlags() const;
256 * Return the scope for a multicast address.
257 * This method may only be called on multicast addresses.
259 uint8_t getMulticastScope() const;
261 // @see IPAddress#isZero
262 bool isZero() const {
263 constexpr auto zero = ByteArray16{{}};
264 return 0 == std::memcmp(bytes(), zero.data(), zero.size());
267 bool isLinkLocalBroadcast() const;
269 // @see IPAddress#mask
270 IPAddressV6 mask(size_t numBits) const;
272 // return underlying in6_addr structure
273 in6_addr toAddr() const {
274 return addr_.in6Addr_;
277 uint16_t getScopeId() const {
280 void setScopeId(uint16_t scope) {
284 sockaddr_in6 toSockAddr() const {
286 memset(&addr, 0, sizeof(sockaddr_in6));
287 addr.sin6_family = AF_INET6;
288 addr.sin6_scope_id = scope_;
289 memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
293 ByteArray16 toByteArray() const {
295 std::memcpy(ba.data(), bytes(), 16);
299 // @see IPAddress#toFullyQualified
300 std::string toFullyQualified() const;
302 // @see IPAddress#toFullyQualifiedAppend
303 void toFullyQualifiedAppend(std::string& out) const;
305 std::string toInverseArpaName() const;
307 // @see IPAddress#str
308 std::string str() const;
310 // @see IPAddress#version
311 uint8_t version() const {
316 * Return the solicited-node multicast address for this address.
318 IPAddressV6 getSolicitedNodeAddress() const;
321 * Return the mask associated with the given number of bits.
322 * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
323 * be {0xff, 0xff, 0xff, 0x00}.
324 * @param [in] numBits bitmask to retrieve
325 * @throws abort if numBits == 0 or numBits > bitCount()
326 * @return mask associated with numBits
328 static const ByteArray16 fetchMask(size_t numBits);
329 // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
331 static CIDRNetworkV6 longestCommonPrefix(
332 const CIDRNetworkV6& one,
333 const CIDRNetworkV6& two);
334 // Number of bytes in the address representation.
335 static constexpr size_t byteCount() {
339 // get nth most significant bit - 0 indexed
340 bool getNthMSBit(size_t bitIndex) const {
341 return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
343 // get nth most significant byte - 0 indexed
344 uint8_t getNthMSByte(size_t byteIndex) const;
345 // get nth bit - 0 indexed
346 bool getNthLSBit(size_t bitIndex) const {
347 return getNthMSBit(bitCount() - bitIndex - 1);
349 // get nth byte - 0 indexed
350 uint8_t getNthLSByte(size_t byteIndex) const {
351 return getNthMSByte(byteCount() - byteIndex - 1);
354 const unsigned char* bytes() const {
355 return addr_.in6Addr_.s6_addr;
360 * Helper that returns true if the address is in the binary subnet specified
363 bool inBinarySubnet(const std::array<uint8_t, 2> addr, size_t numBits) const;
367 return std::tie(addr_.bytes_, scope_);
371 friend inline bool operator==(const IPAddressV6& a, const IPAddressV6& b) {
372 return a.tie() == b.tie();
374 friend inline bool operator!=(const IPAddressV6& a, const IPAddressV6& b) {
375 return a.tie() != b.tie();
377 friend inline bool operator<(const IPAddressV6& a, const IPAddressV6& b) {
378 return a.tie() < b.tie();
380 friend inline bool operator>(const IPAddressV6& a, const IPAddressV6& b) {
381 return a.tie() > b.tie();
383 friend inline bool operator<=(const IPAddressV6& a, const IPAddressV6& b) {
384 return a.tie() <= b.tie();
386 friend inline bool operator>=(const IPAddressV6& a, const IPAddressV6& b) {
387 return a.tie() >= b.tie();
391 union AddressStorage {
395 std::memset(this, 0, sizeof(AddressStorage));
397 explicit AddressStorage(const ByteArray16& bytes) : bytes_(bytes) {}
398 explicit AddressStorage(const in6_addr& addr) : in6Addr_(addr) {}
399 explicit AddressStorage(MacAddress mac);
402 // Link-local scope id. This should always be 0 for IPAddresses that
403 // are *not* link-local.
407 * Set the current IPAddressV6 object to have the address specified by bytes.
408 * @throws IPAddressFormatException if bytes.size() is not 16.
410 void setFromBinary(ByteRange bytes);
413 // boost::hash uses hash_value() so this allows boost::hash to work
414 // automatically for IPAddressV6
415 std::size_t hash_value(const IPAddressV6& addr);
416 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
417 // Define toAppend() to allow IPAddressV6 to be used with to<string>
418 void toAppend(IPAddressV6 addr, std::string* result);
419 void toAppend(IPAddressV6 addr, fbstring* result);
425 struct hash<folly::IPAddressV6> {
426 size_t operator()(const folly::IPAddressV6& addr) const {