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