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