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