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