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