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