Support folly::getCurrentThreadID() without PThread
[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    * Convert a IPv4 address string to a long in network byte order.
84    * @param [in] ip the address to convert
85    * @return the long representation of the address
86    */
87   static uint32_t toLong(StringPiece ip);
88   // Same as above, but in host byte order.
89   // This is slightly slower than toLong.
90   static uint32_t toLongHBO(StringPiece ip);
91
92   /**
93    * Default constructor for IPAddressV4.
94    *
95    * The address value will be 0.0.0.0
96    */
97   IPAddressV4();
98
99   // Create an IPAddressV4 from a string
100   // @throws IPAddressFormatException
101   explicit IPAddressV4(StringPiece ip);
102
103   // ByteArray4 constructor
104   explicit IPAddressV4(const ByteArray4& src);
105
106   // in_addr constructor
107   explicit IPAddressV4(const in_addr src);
108
109   // Return the V6 mapped representation of the address.
110   IPAddressV6 createIPv6() const;
111
112   /**
113    * Return a V6 address in the format of an 6To4 address.
114    */
115   IPAddressV6 getIPv6For6To4() const;
116
117   // Return the long (network byte order) representation of the address.
118   uint32_t toLong() const {
119     return toAddr().s_addr;
120   }
121
122   // Return the long (host byte order) representation of the address.
123   // This is slightly slower than toLong.
124   uint32_t toLongHBO() const {
125     return ntohl(toLong());
126   }
127
128   /**
129    * @see IPAddress#bitCount
130    * @returns 32
131    */
132   static size_t bitCount() { return 32; }
133
134   /**
135    * @See IPAddress#toJson
136    */
137   std::string toJson() const;
138
139   size_t hash() const {
140     static const uint32_t seed = AF_INET;
141     uint32_t hashed = hash::fnv32_buf(&addr_, 4);
142     return hash::hash_combine(seed, hashed);
143   }
144
145   // @see IPAddress#inSubnet
146   // @throws IPAddressFormatException if string doesn't contain a V4 address
147   bool inSubnet(StringPiece cidrNetwork) const;
148
149   // return true if address is in subnet
150   bool inSubnet(const IPAddressV4& subnet, uint8_t cidr) const {
151     return inSubnetWithMask(subnet, fetchMask(cidr));
152   }
153   bool inSubnetWithMask(const IPAddressV4& subnet, const ByteArray4 mask) const;
154
155   // @see IPAddress#isLoopback
156   bool isLoopback() const;
157
158   // @see IPAddress#isLinkLocal
159   bool isLinkLocal() const;
160
161   // @see IPAddress#isNonroutable
162   bool isNonroutable() const;
163
164   // @see IPAddress#isPrivate
165   bool isPrivate() const;
166
167   // @see IPAddress#isMulticast
168   bool isMulticast() const;
169
170   // @see IPAddress#isZero
171   bool isZero() const {
172     constexpr auto zero = ByteArray4{{}};
173     return 0 == std::memcmp(bytes(), zero.data(), zero.size());
174   }
175
176   bool isLinkLocalBroadcast() const {
177     return (INADDR_BROADCAST == toLongHBO());
178   }
179
180   // @see IPAddress#mask
181   IPAddressV4 mask(size_t numBits) const;
182
183   // @see IPAddress#str
184   std::string str() const;
185
186   std::string toInverseArpaName() const;
187
188   // return underlying in_addr structure
189   in_addr toAddr() const { return addr_.inAddr_; }
190
191   sockaddr_in toSockAddr() const {
192     sockaddr_in addr;
193     memset(&addr, 0, sizeof(sockaddr_in));
194     addr.sin_family = AF_INET;
195     memcpy(&addr.sin_addr, &addr_.inAddr_, sizeof(in_addr));
196     return addr;
197   }
198
199   ByteArray4 toByteArray() const {
200     ByteArray4 ba{{0}};
201     std::memcpy(ba.data(), bytes(), 4);
202     return ba;
203   }
204
205   // @see IPAddress#toFullyQualified
206   std::string toFullyQualified() const { return str(); }
207
208   // @see IPAddress#version
209   uint8_t version() const { return 4; }
210
211   /**
212    * Return the mask associated with the given number of bits.
213    * If for instance numBits was 24 (e.g. /24) then the V4 mask returned should
214    * be {0xff, 0xff, 0xff, 0x00}.
215    * @param [in] numBits bitmask to retrieve
216    * @throws abort if numBits == 0 or numBits > bitCount()
217    * @return mask associated with numBits
218    */
219   static const ByteArray4 fetchMask(size_t numBits);
220
221   // Given 2 IPAddressV4, mask pairs extract the longest common IPAddress,
222   // mask pair
223   static CIDRNetworkV4 longestCommonPrefix(
224       const CIDRNetworkV4& one,
225       const CIDRNetworkV4& two);
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 // Derived operators
286 inline bool operator!=(const IPAddressV4& a, const IPAddressV4& b) {
287   return !(a == b);
288 }
289 inline bool operator>(const IPAddressV4& a, const IPAddressV4& b) {
290   return b < a;
291 }
292 inline bool operator<=(const IPAddressV4& a, const IPAddressV4& b) {
293   return !(a > b);
294 }
295 inline bool operator>=(const IPAddressV4& a, const IPAddressV4& b) {
296   return !(a < b);
297 }
298
299 }  // folly
300
301 namespace std {
302 template<>
303 struct hash<folly::IPAddressV4> {
304   size_t operator()(const folly::IPAddressV4 addr) const {
305     return addr.hash();
306   }
307 };
308 }  // std