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