Explicitly initialize AsyncSocket in MockAsyncSSLSocket
[folly.git] / folly / IPAddressV4.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
25 #include <folly/Hash.h>
26 #include <folly/Range.h>
27 #include <folly/detail/IPAddress.h>
28
29 namespace folly {
30
31 class IPAddress;
32 class IPAddressV4;
33 class IPAddressV6;
34
35 /**
36  * Pair of IPAddressV4, netmask
37  */
38 typedef std::pair<IPAddressV4, uint8_t> CIDRNetworkV4;
39
40 /**
41  * Specialization for IPv4 addresses
42  */
43 typedef std::array<uint8_t, 4> ByteArray4;
44
45 /**
46  * IPv4 variation of IPAddress.
47  *
48  * Added methods: toLong, toLongHBO and createIPv6
49  *
50  * @note toLong/fromLong deal in network byte order, use toLongHBO/fromLongHBO
51  * if working in host byte order.
52  *
53  * @see IPAddress
54  */
55 class IPAddressV4 {
56  public:
57   // Max size of std::string returned by toFullyQualified.
58   static constexpr size_t kMaxToFullyQualifiedSize =
59       4 /*words*/ * 3 /*max chars per word*/ + 3 /*separators*/;
60
61   // returns true iff the input string can be parsed as an ipv4-address
62   static bool validate(StringPiece ip);
63
64   // create an IPAddressV4 instance from a uint32_t (network byte order)
65   static IPAddressV4 fromLong(uint32_t src);
66   // same as above but host byte order
67   static IPAddressV4 fromLongHBO(uint32_t src);
68
69   /**
70    * Create a new IPAddress instance from the provided binary data.
71    * @throws IPAddressFormatException if the input length is not 4 bytes.
72    */
73   static IPAddressV4 fromBinary(ByteRange bytes) {
74     IPAddressV4 addr;
75     addr.setFromBinary(bytes);
76     return addr;
77   }
78
79   /**
80    * Returns the address as a Range.
81    */
82   ByteRange toBinary() const {
83     return ByteRange((const unsigned char*)&addr_.inAddr_.s_addr, 4);
84   }
85
86   /**
87    * Create a new IPAddress instance from the in-addr.arpa representation.
88    * @throws IPAddressFormatException if the input is not a valid in-addr.arpa
89    * representation
90    */
91   static IPAddressV4 fromInverseArpaName(const std::string& arpaname);
92
93   /**
94    * Convert a IPv4 address string to a long in network byte order.
95    * @param [in] ip the address to convert
96    * @return the long representation of the address
97    */
98   static uint32_t toLong(StringPiece ip);
99   // Same as above, but in host byte order.
100   // This is slightly slower than toLong.
101   static uint32_t toLongHBO(StringPiece ip);
102
103   /**
104    * Default constructor for IPAddressV4.
105    *
106    * The address value will be 0.0.0.0
107    */
108   IPAddressV4();
109
110   // Create an IPAddressV4 from a string
111   // @throws IPAddressFormatException
112   explicit IPAddressV4(StringPiece ip);
113
114   // ByteArray4 constructor
115   explicit IPAddressV4(const ByteArray4& src);
116
117   // in_addr constructor
118   explicit IPAddressV4(const in_addr src);
119
120   // Return the V6 mapped representation of the address.
121   IPAddressV6 createIPv6() const;
122
123   /**
124    * Return a V6 address in the format of an 6To4 address.
125    */
126   IPAddressV6 getIPv6For6To4() const;
127
128   // Return the long (network byte order) representation of the address.
129   uint32_t toLong() const {
130     return toAddr().s_addr;
131   }
132
133   // Return the long (host byte order) representation of the address.
134   // This is slightly slower than toLong.
135   uint32_t toLongHBO() const {
136     return ntohl(toLong());
137   }
138
139   /**
140    * @see IPAddress#bitCount
141    * @returns 32
142    */
143   static constexpr size_t bitCount() {
144     return 32;
145   }
146
147   /**
148    * @See IPAddress#toJson
149    */
150   std::string toJson() const;
151
152   size_t hash() const {
153     static const uint32_t seed = AF_INET;
154     uint32_t hashed = hash::fnv32_buf(&addr_, 4);
155     return hash::hash_combine(seed, hashed);
156   }
157
158   // @see IPAddress#inSubnet
159   // @throws IPAddressFormatException if string doesn't contain a V4 address
160   bool inSubnet(StringPiece cidrNetwork) const;
161
162   // return true if address is in subnet
163   bool inSubnet(const IPAddressV4& subnet, uint8_t cidr) const {
164     return inSubnetWithMask(subnet, fetchMask(cidr));
165   }
166   bool inSubnetWithMask(const IPAddressV4& subnet, const ByteArray4 mask) const;
167
168   // @see IPAddress#isLoopback
169   bool isLoopback() const;
170
171   // @see IPAddress#isLinkLocal
172   bool isLinkLocal() const;
173
174   // @see IPAddress#isNonroutable
175   bool isNonroutable() const;
176
177   // @see IPAddress#isPrivate
178   bool isPrivate() const;
179
180   // @see IPAddress#isMulticast
181   bool isMulticast() const;
182
183   // @see IPAddress#isZero
184   bool isZero() const {
185     constexpr auto zero = ByteArray4{{}};
186     return 0 == std::memcmp(bytes(), zero.data(), zero.size());
187   }
188
189   bool isLinkLocalBroadcast() const {
190     return (INADDR_BROADCAST == toLongHBO());
191   }
192
193   // @see IPAddress#mask
194   IPAddressV4 mask(size_t numBits) const;
195
196   // @see IPAddress#str
197   std::string str() const;
198
199   std::string toInverseArpaName() const;
200
201   // return underlying in_addr structure
202   in_addr toAddr() const {
203     return addr_.inAddr_;
204   }
205
206   sockaddr_in toSockAddr() const {
207     sockaddr_in addr;
208     memset(&addr, 0, sizeof(sockaddr_in));
209     addr.sin_family = AF_INET;
210     memcpy(&addr.sin_addr, &addr_.inAddr_, sizeof(in_addr));
211     return addr;
212   }
213
214   ByteArray4 toByteArray() const {
215     ByteArray4 ba{{0}};
216     std::memcpy(ba.data(), bytes(), 4);
217     return ba;
218   }
219
220   // @see IPAddress#toFullyQualified
221   std::string toFullyQualified() const {
222     return str();
223   }
224
225   // @see IPAddress#toFullyQualifiedAppend
226   void toFullyQualifiedAppend(std::string& out) const;
227
228   // @see IPAddress#version
229   uint8_t version() const {
230     return 4;
231   }
232
233   /**
234    * Return the mask associated with the given number of bits.
235    * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
236    * be {0xff, 0xff, 0xff, 0x00}.
237    * @param [in] numBits bitmask to retrieve
238    * @throws abort if numBits == 0 or numBits > bitCount()
239    * @return mask associated with numBits
240    */
241   static const ByteArray4 fetchMask(size_t numBits);
242
243   // Given 2 IPAddressV4, mask pairs extract the longest common IPAddress,
244   // mask pair
245   static CIDRNetworkV4 longestCommonPrefix(
246       const CIDRNetworkV4& one,
247       const CIDRNetworkV4& two);
248   // Number of bytes in the address representation.
249   static size_t byteCount() {
250     return 4;
251   }
252   // get nth most significant bit - 0 indexed
253   bool getNthMSBit(size_t bitIndex) const {
254     return detail::getNthMSBitImpl(*this, bitIndex, AF_INET);
255   }
256   // get nth most significant byte - 0 indexed
257   uint8_t getNthMSByte(size_t byteIndex) const;
258   // get nth bit - 0 indexed
259   bool getNthLSBit(size_t bitIndex) const {
260     return getNthMSBit(bitCount() - bitIndex - 1);
261   }
262   // get nth byte - 0 indexed
263   uint8_t getNthLSByte(size_t byteIndex) const {
264     return getNthMSByte(byteCount() - byteIndex - 1);
265   }
266
267   const unsigned char* bytes() const {
268     return addr_.bytes_.data();
269   }
270
271  private:
272   union AddressStorage {
273     static_assert(
274         sizeof(in_addr) == sizeof(ByteArray4),
275         "size of in_addr and ByteArray4 are different");
276     in_addr inAddr_;
277     ByteArray4 bytes_;
278     AddressStorage() {
279       std::memset(this, 0, sizeof(AddressStorage));
280     }
281     explicit AddressStorage(const ByteArray4 bytes) : bytes_(bytes) {}
282     explicit AddressStorage(const in_addr addr) : inAddr_(addr) {}
283   } addr_;
284
285   /**
286    * Set the current IPAddressV4 object to have the address specified by bytes.
287    * @throws IPAddressFormatException if bytes.size() is not 4.
288    */
289   void setFromBinary(ByteRange bytes);
290 };
291
292 // boost::hash uses hash_value() so this allows boost::hash to work
293 // automatically for IPAddressV4
294 size_t hash_value(const IPAddressV4& addr);
295 std::ostream& operator<<(std::ostream& os, const IPAddressV4& addr);
296 // Define toAppend() to allow IPAddressV4 to be used with to<string>
297 void toAppend(IPAddressV4 addr, std::string* result);
298 void toAppend(IPAddressV4 addr, fbstring* result);
299
300 /**
301  * Return true if two addresses are equal.
302  */
303 inline bool operator==(const IPAddressV4& addr1, const IPAddressV4& addr2) {
304   return (addr1.toLong() == addr2.toLong());
305 }
306 // Return true if addr1 < addr2
307 inline bool operator<(const IPAddressV4& addr1, const IPAddressV4& addr2) {
308   return (addr1.toLongHBO() < addr2.toLongHBO());
309 }
310 // Derived operators
311 inline bool operator!=(const IPAddressV4& a, const IPAddressV4& b) {
312   return !(a == b);
313 }
314 inline bool operator>(const IPAddressV4& a, const IPAddressV4& b) {
315   return b < a;
316 }
317 inline bool operator<=(const IPAddressV4& a, const IPAddressV4& b) {
318   return !(a > b);
319 }
320 inline bool operator>=(const IPAddressV4& a, const IPAddressV4& b) {
321   return !(a < b);
322 }
323
324 } // namespace folly
325
326 namespace std {
327 template <>
328 struct hash<folly::IPAddressV4> {
329   size_t operator()(const folly::IPAddressV4 addr) const {
330     return addr.hash();
331   }
332 };
333 } // namespace std