Refer to nullptr not NULL
[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   std::string toInverseArpaName() const;
285
286   // @see IPAddress#str
287   std::string str() const;
288
289   // @see IPAddress#version
290   uint8_t version() const { return 6; }
291
292   /**
293    * Return the solicited-node multicast address for this address.
294    */
295   IPAddressV6 getSolicitedNodeAddress() const;
296
297   /**
298    * Return the mask associated with the given number of bits.
299    * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
300    * be {0xff, 0xff, 0xff, 0x00}.
301    * @param [in] numBits bitmask to retrieve
302    * @throws abort if numBits == 0 or numBits > bitCount()
303    * @return mask associated with numBits
304    */
305   static const ByteArray16 fetchMask(size_t numBits);
306   // Given 2 IPAddressV6,mask pairs extract the longest common IPAddress,
307   // mask pair
308   static CIDRNetworkV6 longestCommonPrefix(
309       const CIDRNetworkV6& one,
310       const CIDRNetworkV6& two);
311   // Number of bytes in the address representation.
312   static constexpr size_t byteCount() { return 16; }
313
314   //get nth most significant bit - 0 indexed
315   bool getNthMSBit(size_t bitIndex) const {
316     return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
317   }
318   //get nth most significant byte - 0 indexed
319   uint8_t getNthMSByte(size_t byteIndex) const;
320   //get nth bit - 0 indexed
321   bool getNthLSBit(size_t bitIndex) const {
322     return getNthMSBit(bitCount() - bitIndex - 1);
323   }
324   //get nth byte - 0 indexed
325   uint8_t getNthLSByte(size_t byteIndex) const {
326     return getNthMSByte(byteCount() - byteIndex - 1);
327   }
328
329   const unsigned char* bytes() const { return addr_.in6Addr_.s6_addr; }
330   protected:
331   /**
332    * Helper that returns true if the address is in the binary subnet specified
333    * by addr.
334    */
335   bool inBinarySubnet(const std::array<uint8_t, 2> addr,
336                       size_t numBits) const;
337
338  private:
339   union AddressStorage {
340     in6_addr in6Addr_;
341     ByteArray16 bytes_;
342     AddressStorage() {
343       std::memset(this, 0, sizeof(AddressStorage));
344     }
345     explicit AddressStorage(const ByteArray16& bytes): bytes_(bytes) {}
346     explicit AddressStorage(const in6_addr& addr): in6Addr_(addr) {}
347     explicit AddressStorage(MacAddress mac);
348   } addr_;
349
350   // Link-local scope id.  This should always be 0 for IPAddresses that
351   // are *not* link-local.
352   uint16_t scope_{0};
353
354   static const std::array<ByteArray16, 129> masks_;
355
356   /**
357    * Set the current IPAddressV6 object to have the address specified by bytes.
358    * @throws IPAddressFormatException if bytes.size() is not 16.
359    */
360   void setFromBinary(ByteRange bytes);
361 };
362
363 // boost::hash uses hash_value() so this allows boost::hash to work
364 // automatically for IPAddressV6
365 std::size_t hash_value(const IPAddressV6& addr);
366 std::ostream& operator<<(std::ostream& os, const IPAddressV6& addr);
367 // Define toAppend() to allow IPAddressV6 to be used with to<string>
368 void toAppend(IPAddressV6 addr, std::string* result);
369 void toAppend(IPAddressV6 addr, fbstring* result);
370
371 /**
372  * Return true if two addresses are equal.
373  */
374 inline bool operator==(const IPAddressV6& addr1, const IPAddressV6& addr2) {
375   return (std::memcmp(addr1.toAddr().s6_addr, addr2.toAddr().s6_addr, 16) == 0)
376     && addr1.getScopeId() == addr2.getScopeId();
377 }
378 // Return true if addr1 < addr2
379 inline bool operator<(const IPAddressV6& addr1, const IPAddressV6& addr2) {
380   auto cmp = std::memcmp(addr1.toAddr().s6_addr,
381                          addr2.toAddr().s6_addr, 16) < 0;
382   if (!cmp) {
383     return addr1.getScopeId() < addr2.getScopeId();
384   } else {
385     return cmp;
386   }
387 }
388 // Derived operators
389 inline bool operator!=(const IPAddressV6& a, const IPAddressV6& b) {
390   return !(a == b);
391 }
392 inline bool operator>(const IPAddressV6& a, const IPAddressV6& b) {
393   return b < a;
394 }
395 inline bool operator<=(const IPAddressV6& a, const IPAddressV6& b) {
396   return !(a > b);
397 }
398 inline bool operator>=(const IPAddressV6& a, const IPAddressV6& b) {
399   return !(a < b);
400 }
401
402 }  // folly
403
404 namespace std {
405 template<>
406 struct hash<folly::IPAddressV6> {
407   size_t operator()(const folly::IPAddressV6& addr) const {
408     return addr.hash();
409   }
410 };
411 }  // std