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