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