Add mechanizm for caching local and peer addresses in AsyncSSLSocket.
[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    * Returns the address as a Range.
101    */
102   ByteRange toBinary() const {
103     return ByteRange((const unsigned char *) &addr_.in6Addr_.s6_addr, 16);
104   }
105
106   /**
107    * Default constructor for IPAddressV6.
108    *
109    * The address value will be ::0
110    */
111   IPAddressV6();
112
113   // Create an IPAddressV6 from a string
114   // @throws IPAddressFormatException
115   //
116   explicit IPAddressV6(StringPiece ip);
117
118   // ByteArray16 constructor
119   explicit IPAddressV6(const ByteArray16& src);
120
121   // in6_addr constructor
122   explicit IPAddressV6(const in6_addr& src);
123
124   // sockaddr_in6 constructor
125   explicit IPAddressV6(const sockaddr_in6& src);
126
127   /**
128    * Create a link-local IPAddressV6 from the specified ethernet MAC address.
129    */
130   IPAddressV6(LinkLocalTag tag, MacAddress mac);
131
132   // return the mapped V4 address
133   // @throws IPAddressFormatException if !isIPv4Mapped
134   IPAddressV4 createIPv4() const;
135
136   /**
137    * Return a V4 address if this is a 6To4 address.
138    * @throws TypeError if not a 6To4 address
139    */
140   IPAddressV4 getIPv4For6To4() const;
141
142   // Return true if a 6TO4 address
143   bool is6To4() const {
144     return type() == IPAddressV6::Type::T6TO4;
145   }
146
147   // Return true if a TEREDO address
148   bool isTeredo() const {
149     return type() == IPAddressV6::Type::TEREDO;
150   }
151
152   // return true if this is v4-to-v6-mapped
153   bool isIPv4Mapped() const;
154
155   // Return the V6 address type
156   Type type() const;
157
158   /**
159    * @see IPAddress#bitCount
160    * @returns 128
161    */
162   static size_t bitCount() { return 128; }
163
164   /**
165    * @see IPAddress#toJson
166    */
167   std::string toJson() const;
168
169   size_t hash() const;
170
171   // @see IPAddress#inSubnet
172   // @throws IPAddressFormatException if string doesn't contain a V6 address
173   bool inSubnet(StringPiece cidrNetwork) const;
174
175   // return true if address is in subnet
176   bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
177     return inSubnetWithMask(subnet, fetchMask(cidr));
178   }
179   bool inSubnetWithMask(const IPAddressV6& subnet,
180                         const ByteArray16& mask) const;
181
182   // @see IPAddress#isLoopback
183   bool isLoopback() const;
184
185   // @see IPAddress#isNonroutable
186   bool isNonroutable() const {
187     return !isRoutable();
188   }
189
190   /**
191    * Return true if this address is routable.
192    */
193   bool isRoutable() const;
194
195   // @see IPAddress#isPrivate
196   bool isPrivate() const;
197
198   /**
199    * Return true if this is a link-local IPv6 address.
200    *
201    * Note that this only returns true for addresses in the fe80::/10 range.
202    * It returns false for the loopback address (::1), even though this address
203    * is also effectively has link-local scope.  It also returns false for
204    * link-scope and interface-scope multicast addresses.
205    */
206   bool isLinkLocal() const;
207
208   /**
209    * Return true if this is a multicast address.
210    */
211   bool isMulticast() const;
212
213   /**
214    * Return the flags for a multicast address.
215    * This method may only be called on multicast addresses.
216    */
217   uint8_t getMulticastFlags() const;
218
219   /**
220    * Return the scope for a multicast address.
221    * This method may only be called on multicast addresses.
222    */
223   uint8_t getMulticastScope() const;
224
225   // @see IPAddress#isZero
226   bool isZero() const {
227     return detail::Bytes::isZero(bytes(), 16);
228   }
229
230   bool isLinkLocalBroadcast() const;
231
232   // @see IPAddress#mask
233   IPAddressV6 mask(size_t numBits) const;
234
235   // return underlying in6_addr structure
236   in6_addr toAddr() const { return addr_.in6Addr_; }
237
238   uint16_t getScopeId() const { return scope_; }
239   void setScopeId(uint16_t scope) {
240     scope_ = scope;
241   }
242
243   sockaddr_in6 toSockAddr() const {
244     sockaddr_in6 addr;
245     memset(&addr, 0, sizeof(sockaddr_in6));
246     addr.sin6_family = AF_INET6;
247     addr.sin6_scope_id = scope_;
248     memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
249     return addr;
250   }
251
252   ByteArray16 toByteArray() const {
253     ByteArray16 ba{{0}};
254     std::memcpy(ba.data(), bytes(), 16);
255     return ba;
256   }
257
258   // @see IPAddress#toFullyQualified
259   std::string toFullyQualified() const;
260
261   // @see IPAddress#str
262   std::string str() const;
263
264   // @see IPAddress#version
265   size_t version() const { return 6; }
266
267   /**
268    * Return the solicited-node multicast address for this address.
269    */
270   IPAddressV6 getSolicitedNodeAddress() const;
271
272   /**
273    * Return the mask associated with the given number of bits.
274    * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
275    * be {0xff, 0xff, 0xff, 0x00}.
276    * @param [in] numBits bitmask to retrieve
277    * @throws abort if numBits == 0 or numBits > bitCount()
278    * @return mask associated with numBits
279    */
280   static const ByteArray16 fetchMask(size_t numBits);
281   // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
282   // mask pair
283   static CIDRNetworkV6 longestCommonPrefix(const CIDRNetworkV6& one,
284                                            const CIDRNetworkV6& two) {
285     auto prefix = detail::Bytes::longestCommonPrefix(
286       one.first.addr_.bytes_, one.second,
287       two.first.addr_.bytes_, two.second);
288     return {IPAddressV6(prefix.first), prefix.second};
289   }
290   // Number of bytes in the address representation.
291   static constexpr size_t byteCount() { return 16; }
292
293   //get nth most significant bit - 0 indexed
294   bool getNthMSBit(size_t bitIndex) const {
295     return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
296   }
297   //get nth most significant byte - 0 indexed
298   uint8_t getNthMSByte(size_t byteIndex) const;
299   //get nth bit - 0 indexed
300   bool getNthLSBit(size_t bitIndex) const {
301     return getNthMSBit(bitCount() - bitIndex - 1);
302   }
303   //get nth byte - 0 indexed
304   uint8_t getNthLSByte(size_t byteIndex) const {
305     return getNthMSByte(byteCount() - byteIndex - 1);
306   }
307
308   const unsigned char* bytes() const { return addr_.in6Addr_.s6_addr; }
309   protected:
310   /**
311    * Helper that returns true if the address is in the binary subnet specified
312    * by addr.
313    */
314   bool inBinarySubnet(const std::array<uint8_t, 2> addr,
315                       size_t numBits) const;
316
317  private:
318   union AddressStorage {
319     in6_addr in6Addr_;
320     ByteArray16 bytes_;
321     AddressStorage() {
322       std::memset(this, 0, sizeof(AddressStorage));
323     }
324     explicit AddressStorage(const ByteArray16& bytes): bytes_(bytes) {}
325     explicit AddressStorage(const in6_addr& addr): in6Addr_(addr) {}
326     explicit AddressStorage(MacAddress mac);
327   } addr_;
328
329   // Link-local scope id.  This should always be 0 for IPAddresses that
330   // are *not* link-local.
331   uint16_t scope_{0};
332
333   static const std::array<ByteArray16, 129> masks_;
334
335   /**
336    * Set the current IPAddressV6 object to have the address specified by bytes.
337    * @throws IPAddressFormatException if bytes.size() is not 16.
338    */
339   void setFromBinary(ByteRange bytes);
340 };
341
342 // boost::hash uses hash_value() so this allows boost::hash to work
343 // automatically for IPAddressV6
344 std::size_t hash_value(const IPAddressV6& addr);
345 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
346 // Define toAppend() to allow IPAddressV6 to be used with to<string>
347 void toAppend(IPAddressV6 addr, std::string* result);
348 void toAppend(IPAddressV6 addr, fbstring* result);
349
350 /**
351  * Return true if two addresses are equal.
352  */
353 inline bool operator==(const IPAddressV6& addr1, const IPAddressV6& addr2) {
354   return (std::memcmp(addr1.toAddr().s6_addr, addr2.toAddr().s6_addr, 16) == 0)
355     && addr1.getScopeId() == addr2.getScopeId();
356 }
357 // Return true if addr1 < addr2
358 inline bool operator<(const IPAddressV6& addr1, const IPAddressV6& addr2) {
359   auto cmp = std::memcmp(addr1.toAddr().s6_addr,
360                          addr2.toAddr().s6_addr, 16) < 0;
361   if (!cmp) {
362     return addr1.getScopeId() < addr2.getScopeId();
363   } else {
364     return cmp;
365   }
366 }
367
368 }  // folly
369
370 namespace std {
371 template<>
372 struct hash<folly::IPAddressV6> {
373   size_t operator()(const folly::IPAddressV6& addr) const {
374     return addr.hash();
375   }
376 };
377 }  // std