Move common/network/IPAddress.h and related to folly/
[folly.git] / folly / IPAddressV6.h
1 /*
2  * Copyright 2014 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 class IPAddressV6 : boost::totally_ordered<IPAddressV6> {
56  public:
57   // V6 Address Type
58   enum Type {
59     TEREDO, T6TO4, NORMAL,
60   };
61   // A constructor parameter to indicate that we should create a link-local
62   // IPAddressV6.
63   enum LinkLocalTag {
64     LINK_LOCAL,
65   };
66   // Thrown when a type assertion fails
67   typedef std::runtime_error TypeError;
68
69   // Binary prefix for teredo networks
70   static const uint32_t PREFIX_TEREDO;
71   // Binary prefix for 6to4 networks
72   static const uint32_t PREFIX_6TO4;
73
74   /**
75    * Create a new IPAddress instance from the provided binary data.
76    * @throws IPAddressFormatException if the input length is not 16 bytes.
77    */
78   static IPAddressV6 fromBinary(ByteRange bytes) {
79     IPAddressV6 addr;
80     addr.setFromBinary(bytes);
81     return addr;
82   }
83
84   /**
85    * Default constructor for IPAddressV6.
86    *
87    * The address value will be ::0
88    */
89   IPAddressV6();
90
91   // Create an IPAddressV6 from a string
92   // @throws IPAddressFormatException
93   explicit IPAddressV6(StringPiece ip);
94
95   // ByteArray16 constructor
96   explicit IPAddressV6(const ByteArray16& src);
97
98   // in6_addr constructor
99   explicit IPAddressV6(const in6_addr& src);
100
101   /**
102    * Create a link-local IPAddressV6 from the specified ethernet MAC address.
103    */
104   IPAddressV6(LinkLocalTag tag, MacAddress mac);
105
106   // return the mapped V4 address
107   // @throws IPAddressFormatException if !isIPv4Mapped
108   IPAddressV4 createIPv4() const;
109
110   /**
111    * Return a V4 address if this is a 6To4 address.
112    * @throws TypeError if not a 6To4 address
113    */
114   IPAddressV4 getIPv4For6To4() const;
115
116   // Return true if a 6TO4 address
117   bool is6To4() const {
118     return type() == IPAddressV6::Type::T6TO4;
119   }
120
121   // Return true if a TEREDO address
122   bool isTeredo() const {
123     return type() == IPAddressV6::Type::TEREDO;
124   }
125
126   // return true if this is v4-to-v6-mapped
127   bool isIPv4Mapped() const;
128
129   // Return the V6 address type
130   Type type() const;
131
132   /**
133    * @see IPAddress#bitCount
134    * @returns 128
135    */
136   static size_t bitCount() { return 128; }
137
138   /**
139    * @see IPAddress#toJson
140    */
141   std::string toJson() const;
142
143   size_t hash() const;
144
145   // @see IPAddress#inSubnet
146   // @throws IPAddressFormatException if string doesn't contain a V6 address
147   bool inSubnet(StringPiece cidrNetwork) const;
148
149   // return true if address is in subnet
150   bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
151     return inSubnetWithMask(subnet, fetchMask(cidr));
152   }
153   bool inSubnetWithMask(const IPAddressV6& subnet,
154                         const ByteArray16& mask) const;
155
156   // @see IPAddress#isLoopback
157   bool isLoopback() const;
158
159   // @see IPAddress#isNonroutable
160   bool isNonroutable() const {
161     return !isRoutable();
162   }
163
164   /**
165    * Return true if this address is routable.
166    */
167   bool isRoutable() const;
168
169   // @see IPAddress#isPrivate
170   bool isPrivate() const;
171
172   /**
173    * Return true if this is a link-local IPv6 address.
174    *
175    * Note that this only returns true for addresses in the fe80::/10 range.
176    * It returns false for the loopback address (::1), even though this address
177    * is also effectively has link-local scope.  It also returns false for
178    * link-scope and interface-scope multicast addresses.
179    */
180   bool isLinkLocal() const;
181
182   /**
183    * Return true if this is a multicast address.
184    */
185   bool isMulticast() const;
186
187   /**
188    * Return the flags for a multicast address.
189    * This method may only be called on multicast addresses.
190    */
191   uint8_t getMulticastFlags() const;
192
193   /**
194    * Return the scope for a multicast address.
195    * This method may only be called on multicast addresses.
196    */
197   uint8_t getMulticastScope() const;
198
199   // @see IPAddress#isZero
200   bool isZero() const {
201     return detail::Bytes::isZero(bytes(), 16);
202   }
203
204   bool isLinkLocalBroadcast() const;
205
206   // @see IPAddress#mask
207   IPAddressV6 mask(size_t numBits) const;
208
209   // return underlying in6_addr structure
210   in6_addr toAddr() const { return addr_.in6Addr_; }
211
212   sockaddr_in6 toSockAddr() const {
213     sockaddr_in6 addr;
214     memset(&addr, 0, sizeof(sockaddr_in6));
215     addr.sin6_family = AF_INET6;
216     memcpy(&addr.sin6_addr, &addr_.in6Addr_, sizeof(in6_addr));
217     return addr;
218   }
219
220   ByteArray16 toByteArray() const {
221     ByteArray16 ba{{0}};
222     std::memcpy(ba.data(), bytes(), 16);
223     return ba;
224   }
225
226   // @see IPAddress#toFullyQualified
227   std::string toFullyQualified() const;
228
229   // @see IPAddress#str
230   std::string str() const;
231
232   // @see IPAddress#version
233   size_t version() const { return 6; }
234
235   /**
236    * Return the solicited-node multicast address for this address.
237    */
238   IPAddressV6 getSolicitedNodeAddress() const;
239
240   /**
241    * Return the mask associated with the given number of bits.
242    * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
243    * be {0xff, 0xff, 0xff, 0x00}.
244    * @param [in] numBits bitmask to retrieve
245    * @throws abort if numBits == 0 or numBits > bitCount()
246    * @return mask associated with numBits
247    */
248   static const ByteArray16 fetchMask(size_t numBits);
249   // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
250   // mask pair
251   static CIDRNetworkV6 longestCommonPrefix(const CIDRNetworkV6& one,
252                                            const CIDRNetworkV6& two) {
253     auto prefix = detail::Bytes::longestCommonPrefix(
254       one.first.addr_.bytes_, one.second,
255       two.first.addr_.bytes_, two.second);
256     return {IPAddressV6(prefix.first), prefix.second};
257   }
258   // Number of bytes in the address representation.
259   static constexpr size_t byteCount() { return 16; }
260
261   //get nth most significant bit - 0 indexed
262   bool getNthMSBit(size_t bitIndex) const {
263     return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
264   }
265   //get nth most significant byte - 0 indexed
266   uint8_t getNthMSByte(size_t byteIndex) const;
267   //get nth bit - 0 indexed
268   bool getNthLSBit(size_t bitIndex) const {
269     return getNthMSBit(bitCount() - bitIndex - 1);
270   }
271   //get nth byte - 0 indexed
272   uint8_t getNthLSByte(size_t byteIndex) const {
273     return getNthMSByte(byteCount() - byteIndex - 1);
274   }
275
276   const unsigned char* bytes() const { return addr_.in6Addr_.s6_addr; }
277   protected:
278   /**
279    * Helper that returns true if the address is in the binary subnet specified
280    * by addr.
281    */
282   bool inBinarySubnet(const std::array<uint8_t, 2> addr,
283                       size_t numBits) const;
284
285  private:
286   union AddressStorage {
287     in6_addr in6Addr_;
288     ByteArray16 bytes_;
289     AddressStorage() {
290       std::memset(this, 0, sizeof(AddressStorage));
291     }
292     explicit AddressStorage(const ByteArray16& bytes): bytes_(bytes) {}
293     explicit AddressStorage(const in6_addr& addr): in6Addr_(addr) {}
294     explicit AddressStorage(MacAddress mac);
295   } addr_;
296
297   static const std::array<ByteArray16, 129> masks_;
298
299   /**
300    * Set the current IPAddressV6 object to have the address specified by bytes.
301    * @throws IPAddressFormatException if bytes.size() is not 16.
302    */
303   void setFromBinary(ByteRange bytes);
304 };
305
306 // boost::hash uses hash_value() so this allows boost::hash to work
307 // automatically for IPAddressV6
308 std::size_t hash_value(const IPAddressV6& addr);
309 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
310 // Define toAppend() to allow IPAddressV6 to be used with to<string>
311 void toAppend(IPAddressV6 addr, std::string* result);
312 void toAppend(IPAddressV6 addr, fbstring* result);
313
314 /**
315  * Return true if two addresses are equal.
316  */
317 inline bool operator==(const IPAddressV6& addr1, const IPAddressV6& addr2) {
318   return (std::memcmp(addr1.toAddr().s6_addr, addr2.toAddr().s6_addr, 16) == 0);
319 }
320 // Return true if addr1 < addr2
321 inline bool operator<(const IPAddressV6& addr1, const IPAddressV6& addr2) {
322   return (std::memcmp(addr1.toAddr().s6_addr, addr2.toAddr().s6_addr, 16) < 0);
323 }
324
325 }  // folly
326
327 namespace std {
328 template<>
329 struct hash<folly::IPAddressV6> {
330   size_t operator()(const folly::IPAddressV6& addr) const {
331     return addr.hash();
332   }
333 };
334 }  // std