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