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