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