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