Expected coroutines support
[folly.git] / folly / IPAddress.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 <functional>
20 #include <iosfwd>
21 #include <memory>
22 #include <string>
23 #include <utility> // std::pair
24
25 #include <folly/IPAddressException.h>
26 #include <folly/IPAddressV4.h>
27 #include <folly/IPAddressV6.h>
28 #include <folly/Range.h>
29 #include <folly/detail/IPAddress.h>
30
31 namespace folly {
32
33 class IPAddress;
34
35 /**
36  * Pair of IPAddress, netmask
37  */
38 typedef std::pair<IPAddress, uint8_t> CIDRNetwork;
39
40 /**
41  * Provides a unified interface for IP addresses.
42  *
43  * @note If you compare 2 IPAddress instances, v4-to-v6-mapped addresses are
44  * compared as V4 addresses.
45  *
46  * @note toLong/fromLong deal in network byte order, use toLongHBO/fromLongHBO
47  * if working in host byte order.
48  *
49  * Example usage:
50  * @code
51  *   IPAddress v4addr("192.0.2.129");
52  *   IPAddress v6map("::ffff:192.0.2.129");
53  *   CHECK(v4addr.inSubnet("192.0.2.0/24") ==
54  *         v4addr.inSubnet(IPAddress("192.0.2.0"), 24));
55  *   CHECK(v4addr.inSubnet("192.0.2.128/30"));
56  *   CHECK(!v4addr.inSubnet("192.0.2.128/32"));
57  *   CHECK(v4addr.asV4().toLong() == 2164392128);
58  *   CHECK(v4addr.asV4().toLongHBO() == 3221226113);
59  *   CHECK(v4addr.isV4());
60  *   CHECK(v6addr.isV6());
61  *   CHECK(v4addr == v6map);
62  *   CHECK(v6map.isIPv4Mapped());
63  *   CHECK(v4addr.asV4() == IPAddress::createIPv4(v6map));
64  *   CHECK(IPAddress::createIPv6(v4addr) == v6map.asV6());
65  * @encode
66  */
67 class IPAddress {
68  private:
69   template <typename F>
70   auto pick(F f) const {
71     return isV4() ? f(asV4()) : f(asV6());
72   }
73
74  public:
75   // returns true iff the input string can be parsed as an ip-address
76   static bool validate(StringPiece ip);
77
78   // return the V4 representation of the address, converting it from V6 to V4 if
79   // needed. Note that this will throw an IPAddressFormatException if the V6
80   // address is not IPv4Mapped.
81   static IPAddressV4 createIPv4(const IPAddress& addr);
82
83   // return the V6 representation of the address, converting it from V4 to V6 if
84   // needed.
85   static IPAddressV6 createIPv6(const IPAddress& addr);
86
87   /**
88    * Create a network and mask from a CIDR formatted address string.
89    * @param [in] ipSlashCidr IP/CIDR formatted string to split
90    * @param [in] defaultCidr default value if no /N specified (if defaultCidr
91    *             is -1, will use /32 for IPv4 and /128 for IPv6)
92    * @param [in] mask apply mask on the address or not,
93    *             e.g. 192.168.13.46/24 => 192.168.13.0/24
94    * @throws IPAddressFormatException if invalid address
95    * @return pair with IPAddress network and uint8_t mask
96    */
97   static CIDRNetwork createNetwork(
98       StringPiece ipSlashCidr,
99       int defaultCidr = -1,
100       bool mask = true);
101
102   /**
103    * Return a string representation of a CIDR block created with createNetwork.
104    * @param [in] network, pair of address and cidr
105    *
106    * @return string representing the netblock
107    */
108   static std::string networkToString(const CIDRNetwork& network);
109
110   /**
111    * Create a new IPAddress instance from the provided binary data
112    * in network byte order.
113    * @throws IPAddressFormatException if len is not 4 or 16
114    */
115   static IPAddress fromBinary(ByteRange bytes);
116
117   /**
118    * Create an IPAddress from a 32bit long (network byte order).
119    * @throws IPAddressFormatException
120    */
121   static IPAddress fromLong(uint32_t src);
122   // Same as above, but host byte order
123   static IPAddress fromLongHBO(uint32_t src);
124
125   // Given 2 IPAddress,mask pairs extract the longest common IPAddress,
126   // mask pair
127   static CIDRNetwork longestCommonPrefix(
128       const CIDRNetwork& one,
129       const CIDRNetwork& two);
130
131   /**
132    * Constructs an uninitialized IPAddress.
133    */
134   IPAddress();
135
136   /**
137    * Parse an IPAddress from a string representation.
138    *
139    * Formats accepted are exactly the same as the ones accepted by inet_pton(),
140    * using AF_INET6 if the string contains colons, and AF_INET otherwise;
141    * with the exception that the whole address can optionally be enclosed
142    * in square brackets.
143    *
144    * @throws IPAddressFormatException
145    */
146   explicit IPAddress(StringPiece ip);
147
148   /**
149    * Create an IPAddress from a sockaddr.
150    * @throws IPAddressFormatException if nullptr or not AF_INET or AF_INET6
151    */
152   explicit IPAddress(const sockaddr* addr);
153
154   // Create an IPAddress from a V4 address
155   /* implicit */ IPAddress(const IPAddressV4 ipV4Addr);
156   /* implicit */ IPAddress(const in_addr addr);
157
158   // Create an IPAddress from a V6 address
159   /* implicit */ IPAddress(const IPAddressV6& ipV6Addr);
160   /* implicit */ IPAddress(const in6_addr& addr);
161
162   // Assign from V4 address
163   IPAddress& operator=(const IPAddressV4& ipV4Addr);
164
165   // Assign from V6 address
166   IPAddress& operator=(const IPAddressV6& ipV6Addr);
167
168   /**
169    * Converts an IPAddress to an IPAddressV4 instance.
170    * @note This is not some handy convenience wrapper to convert an IPv4 address
171    *       to a mapped IPv6 address. If you want that use
172    *       IPAddress::createIPv6(addr)
173    * @throws IPAddressFormatException is not a V4 instance
174    */
175   const IPAddressV4& asV4() const {
176     if (UNLIKELY(!isV4())) {
177       asV4Throw();
178     }
179     return addr_.ipV4Addr;
180   }
181
182   /**
183    * Converts an IPAddress to an IPAddressV6 instance.
184    * @throws InvalidAddressFamilyException is not a V6 instance
185    */
186   const IPAddressV6& asV6() const {
187     if (UNLIKELY(!isV6())) {
188       asV6Throw();
189     }
190     return addr_.ipV6Addr;
191   }
192
193   // Return sa_family_t of IPAddress
194   sa_family_t family() const {
195     return family_;
196   }
197
198   // Populate sockaddr_storage with an appropriate value
199   int toSockaddrStorage(sockaddr_storage* dest, uint16_t port = 0) const {
200     if (dest == nullptr) {
201       throw IPAddressFormatException("dest must not be null");
202     }
203     memset(dest, 0, sizeof(sockaddr_storage));
204     dest->ss_family = family();
205
206     if (isV4()) {
207       sockaddr_in* sin = reinterpret_cast<sockaddr_in*>(dest);
208       sin->sin_addr = asV4().toAddr();
209       sin->sin_port = port;
210 #if defined(__APPLE__)
211       sin->sin_len = sizeof(*sin);
212 #endif
213       return sizeof(*sin);
214     } else if (isV6()) {
215       sockaddr_in6* sin = reinterpret_cast<sockaddr_in6*>(dest);
216       sin->sin6_addr = asV6().toAddr();
217       sin->sin6_port = port;
218       sin->sin6_scope_id = asV6().getScopeId();
219 #if defined(__APPLE__)
220       sin->sin6_len = sizeof(*sin);
221 #endif
222       return sizeof(*sin);
223     } else {
224       throw InvalidAddressFamilyException(family());
225     }
226   }
227
228   /**
229    * Check if the address is found in the specified CIDR netblock.
230    *
231    * This will return false if the specified cidrNet is V4, but the address is
232    * V6. It will also return false if the specified cidrNet is V6 but the
233    * address is V4. This method will do the right thing in the case of a v6
234    * mapped v4 address.
235    *
236    * @note This is slower than the below counterparts. If perf is important use
237    *       one of the two argument variations below.
238    * @param [in] ipSlashCidr address in "192.168.1.0/24" format
239    * @throws IPAddressFormatException if no /mask
240    * @return true if address is part of specified subnet with cidr
241    */
242   bool inSubnet(StringPiece ipSlashCidr) const;
243
244   /**
245    * Check if an IPAddress belongs to a subnet.
246    * @param [in] subnet Subnet to check against (e.g. 192.168.1.0)
247    * @param [in] cidr   CIDR for subnet (e.g. 24 for /24)
248    * @return true if address is part of specified subnet with cidr
249    */
250   bool inSubnet(const IPAddress& subnet, uint8_t cidr) const;
251
252   /**
253    * Check if an IPAddress belongs to the subnet with the given mask.
254    * This is the same as inSubnet but the mask is provided instead of looked up
255    * from the cidr.
256    * @param [in] subnet Subnet to check against
257    * @param [in] mask   The netmask for the subnet
258    * @return true if address is part of the specified subnet with mask
259    */
260   bool inSubnetWithMask(const IPAddress& subnet, ByteRange mask) const;
261
262   // @return true if address is a v4 mapped address
263   bool isIPv4Mapped() const {
264     return isV6() && asV6().isIPv4Mapped();
265   }
266
267   // @return true if address is uninitialized
268   bool empty() const {
269     return family_ == AF_UNSPEC;
270   }
271
272   // @return true if address is initialized
273   explicit operator bool() const {
274     return !empty();
275   }
276
277   // @return true if this is an IPAddressV4 instance
278   bool isV4() const {
279     return family_ == AF_INET;
280   }
281
282   // @return true if this is an IPAddressV6 instance
283   bool isV6() const {
284     return family_ == AF_INET6;
285   }
286
287   // @return true if this address is all zeros
288   bool isZero() const {
289     return pick([&](auto& _) { return _.isZero(); });
290   }
291
292   // Number of bits in the address representation.
293   size_t bitCount() const {
294     return pick([&](auto& _) { return _.bitCount(); });
295   }
296   // Number of bytes in the address representation.
297   size_t byteCount() const {
298     return bitCount() / 8;
299   }
300   // get nth most significant bit - 0 indexed
301   bool getNthMSBit(size_t bitIndex) const {
302     return detail::getNthMSBitImpl(*this, bitIndex, family());
303   }
304   // get nth most significant byte - 0 indexed
305   uint8_t getNthMSByte(size_t byteIndex) const;
306   // get nth bit - 0 indexed
307   bool getNthLSBit(size_t bitIndex) const {
308     return getNthMSBit(bitCount() - bitIndex - 1);
309   }
310   // get nth byte - 0 indexed
311   uint8_t getNthLSByte(size_t byteIndex) const {
312     return getNthMSByte(byteCount() - byteIndex - 1);
313   }
314   /**
315    * Get human-readable string representation of the address.
316    *
317    * This prints a string representation of the address, for human consumption
318    * or logging. The string will take the form of a JSON object that looks like:
319    * {family:'AF_INET|AF_INET6', addr:'address', hash:long}.
320    */
321   std::string toJson() const {
322     return pick([&](auto& _) { return _.toJson(); });
323   }
324
325   // Hash of address
326   std::size_t hash() const {
327     return pick([&](auto& _) { return _.hash(); });
328   }
329
330   // Return true if the address qualifies as localhost.
331   bool isLoopback() const {
332     return pick([&](auto& _) { return _.isLoopback(); });
333   }
334
335   // Return true if the address qualifies as link local
336   bool isLinkLocal() const {
337     return pick([&](auto& _) { return _.isLinkLocal(); });
338   }
339
340   // Return true if the address qualifies as broadcast.
341   bool isLinkLocalBroadcast() const {
342     return pick([&](auto& _) { return _.isLinkLocalBroadcast(); });
343   }
344
345   /**
346    * Return true if the address is a special purpose address, as per rfc6890
347    * (i.e. 0.0.0.0).
348    * For V6, true if the address is not in one of global scope blocks:
349    * 2000::/3, ffxe::/16.
350    */
351   bool isNonroutable() const {
352     return pick([&](auto& _) { return _.isNonroutable(); });
353   }
354
355   /**
356    * Return true if the address is private, as per rfc1918 and rfc4193
357    * (for example, 192.168.xxx.xxx or fc00::/7 addresses)
358    */
359   bool isPrivate() const {
360     return pick([&](auto& _) { return _.isPrivate(); });
361   }
362
363   // Return true if the address is a multicast address.
364   bool isMulticast() const {
365     return pick([&](auto& _) { return _.isMulticast(); });
366   }
367
368   /**
369    * Creates IPAddress instance with all but most significant numBits set to 0.
370    * @param [in] numBits number of bits to mask
371    * @throws abort if numBits > bitCount()
372    * @return IPAddress instance with bits set to 0
373    */
374   IPAddress mask(uint8_t numBits) const {
375     return pick([&](auto& _) { return IPAddress(_.mask(numBits)); });
376   }
377
378   /**
379    * Provides a string representation of address.
380    * @note The string representation is calculated on demand.
381    * @throws IPAddressFormatException on inet_ntop error
382    */
383   std::string str() const {
384     return pick([&](auto& _) { return _.str(); });
385   }
386
387   /**
388    * Return the fully qualified string representation of the address.
389    * For V4 addresses this is the same as calling str(). For V6 addresses
390    * this is the hex representation with : characters inserted every 4 digits.
391    */
392   std::string toFullyQualified() const {
393     return pick([&](auto& _) { return _.toFullyQualified(); });
394   }
395
396   /// Same as toFullyQualified but append to an output string.
397   void toFullyQualifiedAppend(std::string& out) const {
398     return pick([&](auto& _) { return _.toFullyQualifiedAppend(out); });
399   }
400
401   // Address version (4 or 6)
402   uint8_t version() const {
403     return pick([&](auto& _) { return _.version(); });
404   }
405
406   /**
407    * Access to address bytes, in network byte order.
408    */
409   const unsigned char* bytes() const {
410     return pick([&](auto& _) { return _.bytes(); });
411   }
412
413  private:
414   [[noreturn]] void asV4Throw() const;
415   [[noreturn]] void asV6Throw() const;
416
417   typedef union IPAddressV46 {
418     IPAddressV4 ipV4Addr;
419     IPAddressV6 ipV6Addr;
420     // default constructor
421     IPAddressV46() {
422       std::memset(this, 0, sizeof(IPAddressV46));
423     }
424     explicit IPAddressV46(const IPAddressV4& addr) : ipV4Addr(addr) {}
425     explicit IPAddressV46(const IPAddressV6& addr) : ipV6Addr(addr) {}
426   } IPAddressV46;
427   IPAddressV46 addr_;
428   sa_family_t family_;
429 };
430
431 // boost::hash uses hash_value() so this allows boost::hash to work
432 // automatically for IPAddress
433 std::size_t hash_value(const IPAddress& addr);
434 std::ostream& operator<<(std::ostream& os, const IPAddress& addr);
435 // Define toAppend() to allow IPAddress to be used with folly::to<string>
436 void toAppend(IPAddress addr, std::string* result);
437 void toAppend(IPAddress addr, fbstring* result);
438
439 /**
440  * Return true if two addresses are equal.
441  *
442  * @note This takes into consideration V4 mapped addresses as well. If one
443  *       address is v4 mapped we compare the v4 addresses.
444  *
445  * @return true if the two addresses are equal.
446  */
447 bool operator==(const IPAddress& addr1, const IPAddress& addr2);
448 // Return true if addr1 < addr2
449 bool operator<(const IPAddress& addr1, const IPAddress& addr2);
450 // Derived operators
451 inline bool operator!=(const IPAddress& a, const IPAddress& b) {
452   return !(a == b);
453 }
454 inline bool operator>(const IPAddress& a, const IPAddress& b) {
455   return b < a;
456 }
457 inline bool operator<=(const IPAddress& a, const IPAddress& b) {
458   return !(a > b);
459 }
460 inline bool operator>=(const IPAddress& a, const IPAddress& b) {
461   return !(a < b);
462 }
463
464 } // namespace folly
465
466 namespace std {
467 template <>
468 struct hash<folly::IPAddress> {
469   size_t operator()(const folly::IPAddress& addr) const {
470     return addr.hash();
471   }
472 };
473 } // namespace std