fix bootstrap on osx
[folly.git] / folly / IPAddressV6.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
18
19 #include <cstring>
20
21 #include <array>
22 #include <functional>
23 #include <iosfwd>
24 #include <map>
25 #include <stdexcept>
26
27 #include <folly/Hash.h>
28 #include <folly/Range.h>
29 #include <folly/detail/IPAddress.h>
30
31 namespace folly {
32
33 class IPAddress;
34 class IPAddressV4;
35 class IPAddressV6;
36 class MacAddress;
37
38 /**
39  * Pair of IPAddressV6, netmask
40  */
41 typedef std::pair<IPAddressV6, uint8_t> CIDRNetworkV6;
42
43 /**
44  * Specialization for IPv6 addresses
45  */
46 typedef std::array<uint8_t, 16> ByteArray16;
47
48 /**
49  * IPv6 variation of IPAddress.
50  *
51  * Added methods: createIPv4, getIPv4For6To4, is6To4,
52  *                isTeredo, isIPv4Mapped, tryCreateIPv4, type
53  *
54  * @see IPAddress
55  *
56  * Notes on scope ID parsing:
57  *
58  * getaddrinfo() uses if_nametoindex() to convert interface names
59  * into a numerical index. For instance,
60  * "fe80::202:c9ff:fec1:ee08%eth0" may return scope ID 2 on some
61  * hosts, but other numbers on other hosts. It will fail entirely on
62  * hosts without an eth0 interface.
63  *
64  * Serializing / Deserializing IPAddressB6's on different hosts
65  * that use link-local scoping probably won't work.
66  */
67 class IPAddressV6 {
68  public:
69   // V6 Address Type
70   enum Type {
71     TEREDO, T6TO4, NORMAL,
72   };
73   // A constructor parameter to indicate that we should create a link-local
74   // IPAddressV6.
75   enum LinkLocalTag {
76     LINK_LOCAL,
77   };
78   // Thrown when a type assertion fails
79   typedef std::runtime_error TypeError;
80
81   // Binary prefix for teredo networks
82   static const uint32_t PREFIX_TEREDO;
83   // Binary prefix for 6to4 networks
84   static const uint32_t PREFIX_6TO4;
85
86   // Size of std::string returned by toFullyQualified.
87   static constexpr size_t kToFullyQualifiedSize =
88     8 /*words*/ * 4 /*hex chars per word*/ + 7 /*separators*/;
89
90   // returns true iff the input string can be parsed as an ipv6-address
91   static bool validate(StringPiece ip);
92
93   /**
94    * Create a new IPAddress instance from the provided binary data.
95    * @throws IPAddressFormatException if the input length is not 16 bytes.
96    */
97   static IPAddressV6 fromBinary(ByteRange bytes) {
98     IPAddressV6 addr;
99     addr.setFromBinary(bytes);
100     return addr;
101   }
102
103   /**
104    * Returns the address as a Range.
105    */
106   ByteRange toBinary() const {
107     return ByteRange((const unsigned char *) &addr_.in6Addr_.s6_addr, 16);
108   }
109
110   /**
111    * Default constructor for IPAddressV6.
112    *
113    * The address value will be ::0
114    */
115   IPAddressV6();
116
117   // Create an IPAddressV6 from a string
118   // @throws IPAddressFormatException
119   //
120   explicit IPAddressV6(StringPiece ip);
121
122   // ByteArray16 constructor
123   explicit IPAddressV6(const ByteArray16& src);
124
125   // in6_addr constructor
126   explicit IPAddressV6(const in6_addr& src);
127
128   // sockaddr_in6 constructor
129   explicit IPAddressV6(const sockaddr_in6& src);
130
131   /**
132    * Create a link-local IPAddressV6 from the specified ethernet MAC address.
133    */
134   IPAddressV6(LinkLocalTag tag, MacAddress mac);
135
136   // return the mapped V4 address
137   // @throws IPAddressFormatException if !isIPv4Mapped
138   IPAddressV4 createIPv4() const;
139
140   /**
141    * Return a V4 address if this is a 6To4 address.
142    * @throws TypeError if not a 6To4 address
143    */
144   IPAddressV4 getIPv4For6To4() const;
145
146   // Return true if a 6TO4 address
147   bool is6To4() const {
148     return type() == IPAddressV6::Type::T6TO4;
149   }
150
151   // Return true if a TEREDO address
152   bool isTeredo() const {
153     return type() == IPAddressV6::Type::TEREDO;
154   }
155
156   // return true if this is v4-to-v6-mapped
157   bool isIPv4Mapped() const;
158
159   // Return the V6 address type
160   Type type() const;
161
162   /**
163    * @see IPAddress#bitCount
164    * @returns 128
165    */
166   static size_t bitCount() { return 128; }
167
168   /**
169    * @see IPAddress#toJson
170    */
171   std::string toJson() const;
172
173   size_t hash() const;
174
175   // @see IPAddress#inSubnet
176   // @throws IPAddressFormatException if string doesn't contain a V6 address
177   bool inSubnet(StringPiece cidrNetwork) const;
178
179   // return true if address is in subnet
180   bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
181     return inSubnetWithMask(subnet, fetchMask(cidr));
182   }
183   bool inSubnetWithMask(const IPAddressV6& subnet,
184                         const ByteArray16& mask) const;
185
186   // @see IPAddress#isLoopback
187   bool isLoopback() const;
188
189   // @see IPAddress#isNonroutable
190   bool isNonroutable() const {
191     return !isRoutable();
192   }
193
194   /**
195    * Return true if this address is routable.
196    */
197   bool isRoutable() const;
198
199   // @see IPAddress#isPrivate
200   bool isPrivate() const;
201
202   /**
203    * Return true if this is a link-local IPv6 address.
204    *
205    * Note that this only returns true for addresses in the fe80::/10 range.
206    * It returns false for the loopback address (::1), even though this address
207    * is also effectively has link-local scope.  It also returns false for
208    * link-scope and interface-scope multicast addresses.
209    */
210   bool isLinkLocal() const;
211
212   /**
213    * Return true if this is a multicast address.
214    */
215   bool isMulticast() const;
216
217   /**
218    * Return the flags for a multicast address.
219    * This method may only be called on multicast addresses.
220    */
221   uint8_t getMulticastFlags() const;
222
223   /**
224    * Return the scope for a multicast address.
225    * This method may only be called on multicast addresses.
226    */
227   uint8_t getMulticastScope() const;
228
229   // @see IPAddress#isZero
230   bool isZero() const {
231     constexpr auto zero = ByteArray16{{}};
232     return 0 == std::memcmp(bytes(), zero.data(), zero.size());
233   }
234
235   bool isLinkLocalBroadcast() const;
236
237   // @see IPAddress#mask
238   IPAddressV6 mask(size_t numBits) const;
239
240   // return underlying in6_addr structure
241   in6_addr toAddr() const { return addr_.in6Addr_; }
242
243   uint16_t getScopeId() const { return scope_; }
244   void setScopeId(uint16_t scope) {
245     scope_ = scope;
246   }
247
248   sockaddr_in6 toSockAddr() const {
249     sockaddr_in6 addr;
250     memset(&addr, 0, sizeof(sockaddr_in6));
251     addr.sin6_family = AF_INET6;
252     addr.sin6_scope_id = scope_;
253     memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
254     return addr;
255   }
256
257   ByteArray16 toByteArray() const {
258     ByteArray16 ba{{0}};
259     std::memcpy(ba.data(), bytes(), 16);
260     return ba;
261   }
262
263   // @see IPAddress#toFullyQualified
264   std::string toFullyQualified() const;
265
266   // @see IPAddress#str
267   std::string str() const;
268
269   // @see IPAddress#version
270   size_t version() const { return 6; }
271
272   /**
273    * Return the solicited-node multicast address for this address.
274    */
275   IPAddressV6 getSolicitedNodeAddress() const;
276
277   /**
278    * Return the mask associated with the given number of bits.
279    * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
280    * be {0xff, 0xff, 0xff, 0x00}.
281    * @param [in] numBits bitmask to retrieve
282    * @throws abort if numBits == 0 or numBits > bitCount()
283    * @return mask associated with numBits
284    */
285   static const ByteArray16 fetchMask(size_t numBits);
286   // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
287   // mask pair
288   static CIDRNetworkV6 longestCommonPrefix(
289       const CIDRNetworkV6& one,
290       const CIDRNetworkV6& two);
291   // Number of bytes in the address representation.
292   static constexpr size_t byteCount() { return 16; }
293
294   //get nth most significant bit - 0 indexed
295   bool getNthMSBit(size_t bitIndex) const {
296     return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
297   }
298   //get nth most significant byte - 0 indexed
299   uint8_t getNthMSByte(size_t byteIndex) const;
300   //get nth bit - 0 indexed
301   bool getNthLSBit(size_t bitIndex) const {
302     return getNthMSBit(bitCount() - bitIndex - 1);
303   }
304   //get nth byte - 0 indexed
305   uint8_t getNthLSByte(size_t byteIndex) const {
306     return getNthMSByte(byteCount() - byteIndex - 1);
307   }
308
309   const unsigned char* bytes() const { return addr_.in6Addr_.s6_addr; }
310   protected:
311   /**
312    * Helper that returns true if the address is in the binary subnet specified
313    * by addr.
314    */
315   bool inBinarySubnet(const std::array<uint8_t, 2> addr,
316                       size_t numBits) const;
317
318  private:
319   union AddressStorage {
320     in6_addr in6Addr_;
321     ByteArray16 bytes_;
322     AddressStorage() {
323       std::memset(this, 0, sizeof(AddressStorage));
324     }
325     explicit AddressStorage(const ByteArray16& bytes): bytes_(bytes) {}
326     explicit AddressStorage(const in6_addr& addr): in6Addr_(addr) {}
327     explicit AddressStorage(MacAddress mac);
328   } addr_;
329
330   // Link-local scope id.  This should always be 0 for IPAddresses that
331   // are *not* link-local.
332   uint16_t scope_{0};
333
334   static const std::array<ByteArray16, 129> masks_;
335
336   /**
337    * Set the current IPAddressV6 object to have the address specified by bytes.
338    * @throws IPAddressFormatException if bytes.size() is not 16.
339    */
340   void setFromBinary(ByteRange bytes);
341 };
342
343 // boost::hash uses hash_value() so this allows boost::hash to work
344 // automatically for IPAddressV6
345 std::size_t hash_value(const IPAddressV6& addr);
346 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
347 // Define toAppend() to allow IPAddressV6 to be used with to<string>
348 void toAppend(IPAddressV6 addr, std::string* result);
349 void toAppend(IPAddressV6 addr, fbstring* result);
350
351 /**
352  * Return true if two addresses are equal.
353  */
354 inline bool operator==(const IPAddressV6& addr1, const IPAddressV6& addr2) {
355   return (std::memcmp(addr1.toAddr().s6_addr, addr2.toAddr().s6_addr, 16) == 0)
356     && addr1.getScopeId() == addr2.getScopeId();
357 }
358 // Return true if addr1 < addr2
359 inline bool operator<(const IPAddressV6& addr1, const IPAddressV6& addr2) {
360   auto cmp = std::memcmp(addr1.toAddr().s6_addr,
361                          addr2.toAddr().s6_addr, 16) < 0;
362   if (!cmp) {
363     return addr1.getScopeId() < addr2.getScopeId();
364   } else {
365     return cmp;
366   }
367 }
368 // Derived operators
369 inline bool operator!=(const IPAddressV6& a, const IPAddressV6& b) {
370   return !(a == b);
371 }
372 inline bool operator>(const IPAddressV6& a, const IPAddressV6& b) {
373   return b < a;
374 }
375 inline bool operator<=(const IPAddressV6& a, const IPAddressV6& b) {
376   return !(a > b);
377 }
378 inline bool operator>=(const IPAddressV6& a, const IPAddressV6& b) {
379   return !(a < b);
380 }
381
382 }  // folly
383
384 namespace std {
385 template<>
386 struct hash<folly::IPAddressV6> {
387   size_t operator()(const folly::IPAddressV6& addr) const {
388     return addr.hash();
389   }
390 };
391 }  // std