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.
24 #include <boost/operators.hpp>
26 #include <folly/Hash.h>
27 #include <folly/Range.h>
28 #include <folly/detail/IPAddress.h>
38 * Pair of IPAddressV6, netmask
40 typedef std::pair<IPAddressV6, uint8_t> CIDRNetworkV6;
43 * Specialization for IPv6 addresses
45 typedef std::array<uint8_t, 16> ByteArray16;
48 * IPv6 variation of IPAddress.
50 * Added methods: createIPv4, getIPv4For6To4, is6To4,
51 * isTeredo, isIPv4Mapped, tryCreateIPv4, type
55 * Notes on scope ID parsing:
57 * getaddrinfo() uses if_nametoindex() to convert interface names
58 * into a numerical index. For instance,
59 * "fe80::202:c9ff:fec1:ee08%eth0" may return scope ID 2 on some
60 * hosts, but other numbers on other hosts. It will fail entirely on
61 * hosts without an eth0 interface.
63 * Serializing / Deserializing IPAddressB6's on different hosts
64 * that use link-local scoping probably won't work.
66 class IPAddressV6 : boost::totally_ordered<IPAddressV6> {
70 TEREDO, T6TO4, NORMAL,
72 // A constructor parameter to indicate that we should create a link-local
77 // Thrown when a type assertion fails
78 typedef std::runtime_error TypeError;
80 // Binary prefix for teredo networks
81 static const uint32_t PREFIX_TEREDO;
82 // Binary prefix for 6to4 networks
83 static const uint32_t PREFIX_6TO4;
85 // Size of std::string returned by toFullyQualified.
86 static constexpr size_t kToFullyQualifiedSize =
87 8 /*words*/ * 4 /*hex chars per word*/ + 7 /*separators*/;
89 // returns true iff the input string can be parsed as an ipv6-address
90 static bool validate(StringPiece ip);
93 * Create a new IPAddress instance from the provided binary data.
94 * @throws IPAddressFormatException if the input length is not 16 bytes.
96 static IPAddressV6 fromBinary(ByteRange bytes) {
98 addr.setFromBinary(bytes);
103 * Returns the address as a Range.
105 ByteRange toBinary() const {
106 return ByteRange((const unsigned char *) &addr_.in6Addr_.s6_addr, 16);
110 * Default constructor for IPAddressV6.
112 * The address value will be ::0
116 // Create an IPAddressV6 from a string
117 // @throws IPAddressFormatException
119 explicit IPAddressV6(StringPiece ip);
121 // ByteArray16 constructor
122 explicit IPAddressV6(const ByteArray16& src);
124 // in6_addr constructor
125 explicit IPAddressV6(const in6_addr& src);
127 // sockaddr_in6 constructor
128 explicit IPAddressV6(const sockaddr_in6& src);
131 * Create a link-local IPAddressV6 from the specified ethernet MAC address.
133 IPAddressV6(LinkLocalTag tag, MacAddress mac);
135 // return the mapped V4 address
136 // @throws IPAddressFormatException if !isIPv4Mapped
137 IPAddressV4 createIPv4() const;
140 * Return a V4 address if this is a 6To4 address.
141 * @throws TypeError if not a 6To4 address
143 IPAddressV4 getIPv4For6To4() const;
145 // Return true if a 6TO4 address
146 bool is6To4() const {
147 return type() == IPAddressV6::Type::T6TO4;
150 // Return true if a TEREDO address
151 bool isTeredo() const {
152 return type() == IPAddressV6::Type::TEREDO;
155 // return true if this is v4-to-v6-mapped
156 bool isIPv4Mapped() const;
158 // Return the V6 address type
162 * @see IPAddress#bitCount
165 static size_t bitCount() { return 128; }
168 * @see IPAddress#toJson
170 std::string toJson() const;
174 // @see IPAddress#inSubnet
175 // @throws IPAddressFormatException if string doesn't contain a V6 address
176 bool inSubnet(StringPiece cidrNetwork) const;
178 // return true if address is in subnet
179 bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
180 return inSubnetWithMask(subnet, fetchMask(cidr));
182 bool inSubnetWithMask(const IPAddressV6& subnet,
183 const ByteArray16& mask) const;
185 // @see IPAddress#isLoopback
186 bool isLoopback() const;
188 // @see IPAddress#isNonroutable
189 bool isNonroutable() const {
190 return !isRoutable();
194 * Return true if this address is routable.
196 bool isRoutable() const;
198 // @see IPAddress#isPrivate
199 bool isPrivate() const;
202 * Return true if this is a link-local IPv6 address.
204 * Note that this only returns true for addresses in the fe80::/10 range.
205 * It returns false for the loopback address (::1), even though this address
206 * is also effectively has link-local scope. It also returns false for
207 * link-scope and interface-scope multicast addresses.
209 bool isLinkLocal() const;
212 * Return true if this is a multicast address.
214 bool isMulticast() const;
217 * Return the flags for a multicast address.
218 * This method may only be called on multicast addresses.
220 uint8_t getMulticastFlags() const;
223 * Return the scope for a multicast address.
224 * This method may only be called on multicast addresses.
226 uint8_t getMulticastScope() const;
228 // @see IPAddress#isZero
229 bool isZero() const {
230 return detail::Bytes::isZero(bytes(), 16);
233 bool isLinkLocalBroadcast() const;
235 // @see IPAddress#mask
236 IPAddressV6 mask(size_t numBits) const;
238 // return underlying in6_addr structure
239 in6_addr toAddr() const { return addr_.in6Addr_; }
241 uint16_t getScopeId() const { return scope_; }
242 void setScopeId(uint16_t scope) {
246 sockaddr_in6 toSockAddr() const {
248 memset(&addr, 0, sizeof(sockaddr_in6));
249 addr.sin6_family = AF_INET6;
250 addr.sin6_scope_id = scope_;
251 memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
255 ByteArray16 toByteArray() const {
257 std::memcpy(ba.data(), bytes(), 16);
261 // @see IPAddress#toFullyQualified
262 std::string toFullyQualified() const;
264 // @see IPAddress#str
265 std::string str() const;
267 // @see IPAddress#version
268 size_t version() const { return 6; }
271 * Return the solicited-node multicast address for this address.
273 IPAddressV6 getSolicitedNodeAddress() const;
276 * Return the mask associated with the given number of bits.
277 * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
278 * be {0xff, 0xff, 0xff, 0x00}.
279 * @param [in] numBits bitmask to retrieve
280 * @throws abort if numBits == 0 or numBits > bitCount()
281 * @return mask associated with numBits
283 static const ByteArray16 fetchMask(size_t numBits);
284 // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
286 static CIDRNetworkV6 longestCommonPrefix(const CIDRNetworkV6& one,
287 const CIDRNetworkV6& two) {
288 auto prefix = detail::Bytes::longestCommonPrefix(
289 one.first.addr_.bytes_, one.second,
290 two.first.addr_.bytes_, two.second);
291 return {IPAddressV6(prefix.first), prefix.second};
293 // Number of bytes in the address representation.
294 static constexpr size_t byteCount() { return 16; }
296 //get nth most significant bit - 0 indexed
297 bool getNthMSBit(size_t bitIndex) const {
298 return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
300 //get nth most significant byte - 0 indexed
301 uint8_t getNthMSByte(size_t byteIndex) const;
302 //get nth bit - 0 indexed
303 bool getNthLSBit(size_t bitIndex) const {
304 return getNthMSBit(bitCount() - bitIndex - 1);
306 //get nth byte - 0 indexed
307 uint8_t getNthLSByte(size_t byteIndex) const {
308 return getNthMSByte(byteCount() - byteIndex - 1);
311 const unsigned char* bytes() const { return addr_.in6Addr_.s6_addr; }
314 * Helper that returns true if the address is in the binary subnet specified
317 bool inBinarySubnet(const std::array<uint8_t, 2> addr,
318 size_t numBits) const;
321 union AddressStorage {
325 std::memset(this, 0, sizeof(AddressStorage));
327 explicit AddressStorage(const ByteArray16& bytes): bytes_(bytes) {}
328 explicit AddressStorage(const in6_addr& addr): in6Addr_(addr) {}
329 explicit AddressStorage(MacAddress mac);
332 // Link-local scope id. This should always be 0 for IPAddresses that
333 // are *not* link-local.
336 static const std::array<ByteArray16, 129> masks_;
339 * Set the current IPAddressV6 object to have the address specified by bytes.
340 * @throws IPAddressFormatException if bytes.size() is not 16.
342 void setFromBinary(ByteRange bytes);
345 // boost::hash uses hash_value() so this allows boost::hash to work
346 // automatically for IPAddressV6
347 std::size_t hash_value(const IPAddressV6& addr);
348 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
349 // Define toAppend() to allow IPAddressV6 to be used with to<string>
350 void toAppend(IPAddressV6 addr, std::string* result);
351 void toAppend(IPAddressV6 addr, fbstring* result);
354 * Return true if two addresses are equal.
356 inline bool operator==(const IPAddressV6& addr1, const IPAddressV6& addr2) {
357 return (std::memcmp(addr1.toAddr().s6_addr, addr2.toAddr().s6_addr, 16) == 0)
358 && addr1.getScopeId() == addr2.getScopeId();
360 // Return true if addr1 < addr2
361 inline bool operator<(const IPAddressV6& addr1, const IPAddressV6& addr2) {
362 auto cmp = std::memcmp(addr1.toAddr().s6_addr,
363 addr2.toAddr().s6_addr, 16) < 0;
365 return addr1.getScopeId() < addr2.getScopeId();
375 struct hash<folly::IPAddressV6> {
376 size_t operator()(const folly::IPAddressV6& addr) const {