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 * Returns the address as a Range.
107 ByteRange toBinary() const {
108 return ByteRange((const unsigned char *) &addr_.in6Addr_.s6_addr, 16);
112 * Default constructor for IPAddressV6.
114 * The address value will be ::0
118 // Create an IPAddressV6 from a string
119 // @throws IPAddressFormatException
121 explicit IPAddressV6(StringPiece ip);
123 // ByteArray16 constructor
124 explicit IPAddressV6(const ByteArray16& src);
126 // in6_addr constructor
127 explicit IPAddressV6(const in6_addr& src);
129 // sockaddr_in6 constructor
130 explicit IPAddressV6(const sockaddr_in6& src);
133 * Create a link-local IPAddressV6 from the specified ethernet MAC address.
135 IPAddressV6(LinkLocalTag tag, MacAddress mac);
137 // return the mapped V4 address
138 // @throws IPAddressFormatException if !isIPv4Mapped
139 IPAddressV4 createIPv4() const;
142 * Return a V4 address if this is a 6To4 address.
143 * @throws TypeError if not a 6To4 address
145 IPAddressV4 getIPv4For6To4() const;
147 // Return true if a 6TO4 address
148 bool is6To4() const {
149 return type() == IPAddressV6::Type::T6TO4;
152 // Return true if a TEREDO address
153 bool isTeredo() const {
154 return type() == IPAddressV6::Type::TEREDO;
157 // return true if this is v4-to-v6-mapped
158 bool isIPv4Mapped() const;
160 // Return the V6 address type
164 * @see IPAddress#bitCount
167 static size_t bitCount() { return 128; }
170 * @see IPAddress#toJson
172 std::string toJson() const;
176 // @see IPAddress#inSubnet
177 // @throws IPAddressFormatException if string doesn't contain a V6 address
178 bool inSubnet(StringPiece cidrNetwork) const;
180 // return true if address is in subnet
181 bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
182 return inSubnetWithMask(subnet, fetchMask(cidr));
184 bool inSubnetWithMask(const IPAddressV6& subnet,
185 const ByteArray16& mask) const;
187 // @see IPAddress#isLoopback
188 bool isLoopback() const;
190 // @see IPAddress#isNonroutable
191 bool isNonroutable() const {
192 return !isRoutable();
196 * Return true if this address is routable.
198 bool isRoutable() const;
200 // @see IPAddress#isPrivate
201 bool isPrivate() const;
204 * Return true if this is a link-local IPv6 address.
206 * Note that this only returns true for addresses in the fe80::/10 range.
207 * It returns false for the loopback address (::1), even though this address
208 * is also effectively has link-local scope. It also returns false for
209 * link-scope and interface-scope multicast addresses.
211 bool isLinkLocal() const;
214 * Return the mac address if this is a link-local IPv6 address.
216 * @return an Optional<MacAddress> union representing the mac address.
218 * If the address is not a link-local one it will return an empty Optional.
219 * You can use Optional::value() to check whether the mac address is not null.
221 Optional<MacAddress> getMacAddressFromLinkLocal() const;
224 * Return true if this is a multicast address.
226 bool isMulticast() const;
229 * Return the flags for a multicast address.
230 * This method may only be called on multicast addresses.
232 uint8_t getMulticastFlags() const;
235 * Return the scope for a multicast address.
236 * This method may only be called on multicast addresses.
238 uint8_t getMulticastScope() const;
240 // @see IPAddress#isZero
241 bool isZero() const {
242 constexpr auto zero = ByteArray16{{}};
243 return 0 == std::memcmp(bytes(), zero.data(), zero.size());
246 bool isLinkLocalBroadcast() const;
248 // @see IPAddress#mask
249 IPAddressV6 mask(size_t numBits) const;
251 // return underlying in6_addr structure
252 in6_addr toAddr() const { return addr_.in6Addr_; }
254 uint16_t getScopeId() const { return scope_; }
255 void setScopeId(uint16_t scope) {
259 sockaddr_in6 toSockAddr() const {
261 memset(&addr, 0, sizeof(sockaddr_in6));
262 addr.sin6_family = AF_INET6;
263 addr.sin6_scope_id = scope_;
264 memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
268 ByteArray16 toByteArray() const {
270 std::memcpy(ba.data(), bytes(), 16);
274 // @see IPAddress#toFullyQualified
275 std::string toFullyQualified() const;
277 std::string toInverseArpaName() const;
279 // @see IPAddress#str
280 std::string str() const;
282 // @see IPAddress#version
283 uint8_t version() const { return 6; }
286 * Return the solicited-node multicast address for this address.
288 IPAddressV6 getSolicitedNodeAddress() const;
291 * Return the mask associated with the given number of bits.
292 * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
293 * be {0xff, 0xff, 0xff, 0x00}.
294 * @param [in] numBits bitmask to retrieve
295 * @throws abort if numBits == 0 or numBits > bitCount()
296 * @return mask associated with numBits
298 static const ByteArray16 fetchMask(size_t numBits);
299 // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
301 static CIDRNetworkV6 longestCommonPrefix(
302 const CIDRNetworkV6& one,
303 const CIDRNetworkV6& two);
304 // Number of bytes in the address representation.
305 static constexpr size_t byteCount() { return 16; }
307 //get nth most significant bit - 0 indexed
308 bool getNthMSBit(size_t bitIndex) const {
309 return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
311 //get nth most significant byte - 0 indexed
312 uint8_t getNthMSByte(size_t byteIndex) const;
313 //get nth bit - 0 indexed
314 bool getNthLSBit(size_t bitIndex) const {
315 return getNthMSBit(bitCount() - bitIndex - 1);
317 //get nth byte - 0 indexed
318 uint8_t getNthLSByte(size_t byteIndex) const {
319 return getNthMSByte(byteCount() - byteIndex - 1);
322 const unsigned char* bytes() const { return addr_.in6Addr_.s6_addr; }
325 * Helper that returns true if the address is in the binary subnet specified
328 bool inBinarySubnet(const std::array<uint8_t, 2> addr,
329 size_t numBits) const;
332 union AddressStorage {
336 std::memset(this, 0, sizeof(AddressStorage));
338 explicit AddressStorage(const ByteArray16& bytes): bytes_(bytes) {}
339 explicit AddressStorage(const in6_addr& addr): in6Addr_(addr) {}
340 explicit AddressStorage(MacAddress mac);
343 // Link-local scope id. This should always be 0 for IPAddresses that
344 // are *not* link-local.
347 static const std::array<ByteArray16, 129> masks_;
350 * Set the current IPAddressV6 object to have the address specified by bytes.
351 * @throws IPAddressFormatException if bytes.size() is not 16.
353 void setFromBinary(ByteRange bytes);
356 // boost::hash uses hash_value() so this allows boost::hash to work
357 // automatically for IPAddressV6
358 std::size_t hash_value(const IPAddressV6& addr);
359 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
360 // Define toAppend() to allow IPAddressV6 to be used with to<string>
361 void toAppend(IPAddressV6 addr, std::string* result);
362 void toAppend(IPAddressV6 addr, fbstring* result);
365 * Return true if two addresses are equal.
367 inline bool operator==(const IPAddressV6& addr1, const IPAddressV6& addr2) {
368 return (std::memcmp(addr1.toAddr().s6_addr, addr2.toAddr().s6_addr, 16) == 0)
369 && addr1.getScopeId() == addr2.getScopeId();
371 // Return true if addr1 < addr2
372 inline bool operator<(const IPAddressV6& addr1, const IPAddressV6& addr2) {
373 auto cmp = std::memcmp(addr1.toAddr().s6_addr,
374 addr2.toAddr().s6_addr, 16) < 0;
376 return addr1.getScopeId() < addr2.getScopeId();
382 inline bool operator!=(const IPAddressV6& a, const IPAddressV6& b) {
385 inline bool operator>(const IPAddressV6& a, const IPAddressV6& b) {
388 inline bool operator<=(const IPAddressV6& a, const IPAddressV6& b) {
391 inline bool operator>=(const IPAddressV6& a, const IPAddressV6& b) {
399 struct hash<folly::IPAddressV6> {
400 size_t operator()(const folly::IPAddressV6& addr) const {