Use hazptr_local and hazptr_array
[folly.git] / folly / IPAddress.cpp
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 #include <folly/IPAddress.h>
18
19 #include <limits>
20 #include <ostream>
21 #include <string>
22 #include <vector>
23
24 #include <folly/Format.h>
25 #include <folly/String.h>
26 #include <folly/detail/IPAddressSource.h>
27
28 using std::ostream;
29 using std::string;
30 using std::vector;
31
32 namespace folly {
33
34 // free functions
35 size_t hash_value(const IPAddress& addr) {
36   return addr.hash();
37 }
38 ostream& operator<<(ostream& os, const IPAddress& addr) {
39   os << addr.str();
40   return os;
41 }
42 void toAppend(IPAddress addr, string* result) {
43   result->append(addr.str());
44 }
45 void toAppend(IPAddress addr, fbstring* result) {
46   result->append(addr.str());
47 }
48
49 bool IPAddress::validate(StringPiece ip) noexcept {
50   return IPAddressV4::validate(ip) || IPAddressV6::validate(ip);
51 }
52
53 // public static
54 IPAddressV4 IPAddress::createIPv4(const IPAddress& addr) {
55   if (addr.isV4()) {
56     return addr.asV4();
57   } else {
58     return addr.asV6().createIPv4();
59   }
60 }
61
62 // public static
63 IPAddressV6 IPAddress::createIPv6(const IPAddress& addr) {
64   if (addr.isV6()) {
65     return addr.asV6();
66   } else {
67     return addr.asV4().createIPv6();
68   }
69 }
70
71 // public static
72 CIDRNetwork IPAddress::createNetwork(
73     StringPiece ipSlashCidr,
74     int defaultCidr, /* = -1 */
75     bool applyMask /* = true */) {
76   if (defaultCidr > std::numeric_limits<uint8_t>::max()) {
77     throw std::range_error("defaultCidr must be <= UINT8_MAX");
78   }
79   vector<string> vec;
80   split("/", ipSlashCidr, vec);
81   vector<string>::size_type elemCount = vec.size();
82
83   if (elemCount == 0 || // weird invalid string
84       elemCount > 2) { // invalid string (IP/CIDR/extras)
85     throw IPAddressFormatException(sformat(
86         "Invalid ipSlashCidr specified. Expected IP/CIDR format, got '{}'",
87         ipSlashCidr));
88   }
89   IPAddress subnet(vec.at(0));
90   auto cidr =
91       uint8_t((defaultCidr > -1) ? defaultCidr : (subnet.isV4() ? 32 : 128));
92
93   if (elemCount == 2) {
94     try {
95       cidr = to<uint8_t>(vec.at(1));
96     } catch (...) {
97       throw IPAddressFormatException(
98           sformat("Mask value '{}' not a valid mask", vec.at(1)));
99     }
100   }
101   if (cidr > subnet.bitCount()) {
102     throw IPAddressFormatException(sformat(
103         "CIDR value '{}' is > network bit count '{}'",
104         cidr,
105         subnet.bitCount()));
106   }
107   return std::make_pair(applyMask ? subnet.mask(cidr) : subnet, cidr);
108 }
109
110 // public static
111 std::string IPAddress::networkToString(const CIDRNetwork& network) {
112   return sformat("{}/{}", network.first.str(), network.second);
113 }
114
115 // public static
116 IPAddress IPAddress::fromBinary(ByteRange bytes) {
117   if (bytes.size() == 4) {
118     return IPAddress(IPAddressV4::fromBinary(bytes));
119   } else if (bytes.size() == 16) {
120     return IPAddress(IPAddressV6::fromBinary(bytes));
121   } else {
122     string hexval = detail::Bytes::toHex(bytes.data(), bytes.size());
123     throw IPAddressFormatException(
124         sformat("Invalid address with hex value '{}'", hexval));
125   }
126 }
127
128 Expected<IPAddress, IPAddressFormatError> IPAddress::tryFromBinary(
129     ByteRange bytes) noexcept {
130   // Check IPv6 first since it's our main protocol.
131   if (bytes.size() == 16) {
132     return IPAddressV6::tryFromBinary(bytes);
133   } else if (bytes.size() == 4) {
134     return IPAddressV4::tryFromBinary(bytes);
135   } else {
136     return makeUnexpected(IPAddressFormatError::UNSUPPORTED_ADDR_FAMILY);
137   }
138 }
139
140 // public static
141 IPAddress IPAddress::fromLong(uint32_t src) {
142   return IPAddress(IPAddressV4::fromLong(src));
143 }
144 IPAddress IPAddress::fromLongHBO(uint32_t src) {
145   return IPAddress(IPAddressV4::fromLongHBO(src));
146 }
147
148 // default constructor
149 IPAddress::IPAddress() : addr_(), family_(AF_UNSPEC) {}
150
151 // public string constructor
152 IPAddress::IPAddress(StringPiece str) : addr_(), family_(AF_UNSPEC) {
153   auto maybeIp = tryFromString(str);
154   if (maybeIp.hasError()) {
155     throw IPAddressFormatException(
156         to<std::string>("Invalid IP address '", str, "'"));
157   }
158   *this = std::move(maybeIp.value());
159 }
160
161 Expected<IPAddress, IPAddressFormatError> IPAddress::tryFromString(
162     StringPiece str) noexcept {
163   // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
164   // contain a period
165   if (str.find(':') != string::npos) {
166     return IPAddressV6::tryFromString(str);
167   } else if (str.find('.') != string::npos) {
168     return IPAddressV4::tryFromString(str);
169   } else {
170     return makeUnexpected(IPAddressFormatError::UNSUPPORTED_ADDR_FAMILY);
171   }
172 }
173
174 // public sockaddr constructor
175 IPAddress::IPAddress(const sockaddr* addr) : addr_(), family_(AF_UNSPEC) {
176   if (addr == nullptr) {
177     throw IPAddressFormatException("sockaddr == nullptr");
178   }
179   family_ = addr->sa_family;
180   switch (addr->sa_family) {
181     case AF_INET: {
182       const sockaddr_in* v4addr = reinterpret_cast<const sockaddr_in*>(addr);
183       addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
184       break;
185     }
186     case AF_INET6: {
187       const sockaddr_in6* v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
188       addr_.ipV6Addr = IPAddressV6(*v6addr);
189       break;
190     }
191     default:
192       throw InvalidAddressFamilyException(addr->sa_family);
193   }
194 }
195
196 // public ipv4 constructor
197 IPAddress::IPAddress(const IPAddressV4 ipV4Addr) noexcept
198     : addr_(ipV4Addr), family_(AF_INET) {}
199
200 // public ipv4 constructor
201 IPAddress::IPAddress(const in_addr ipV4Addr) noexcept
202     : addr_(IPAddressV4(ipV4Addr)), family_(AF_INET) {}
203
204 // public ipv6 constructor
205 IPAddress::IPAddress(const IPAddressV6& ipV6Addr) noexcept
206     : addr_(ipV6Addr), family_(AF_INET6) {}
207
208 // public ipv6 constructor
209 IPAddress::IPAddress(const in6_addr& ipV6Addr) noexcept
210     : addr_(IPAddressV6(ipV6Addr)), family_(AF_INET6) {}
211
212 // Assign from V4 address
213 IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) noexcept {
214   addr_ = IPAddressV46(ipv4_addr);
215   family_ = AF_INET;
216   return *this;
217 }
218
219 // Assign from V6 address
220 IPAddress& IPAddress::operator=(const IPAddressV6& ipv6_addr) noexcept {
221   addr_ = IPAddressV46(ipv6_addr);
222   family_ = AF_INET6;
223   return *this;
224 }
225
226 // public
227 bool IPAddress::inSubnet(StringPiece cidrNetwork) const {
228   auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
229   return inSubnet(subnetInfo.first, subnetInfo.second);
230 }
231
232 // public
233 bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
234   if (bitCount() == subnet.bitCount()) {
235     if (isV4()) {
236       return asV4().inSubnet(subnet.asV4(), cidr);
237     } else {
238       return asV6().inSubnet(subnet.asV6(), cidr);
239     }
240   }
241   // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
242   // address and vice-versa
243   if (isV6()) {
244     const IPAddressV6& v6addr = asV6();
245     const IPAddressV4& v4subnet = subnet.asV4();
246     if (v6addr.is6To4()) {
247       return v6addr.getIPv4For6To4().inSubnet(v4subnet, cidr);
248     }
249   } else if (subnet.isV6()) {
250     const IPAddressV6& v6subnet = subnet.asV6();
251     const IPAddressV4& v4addr = asV4();
252     if (v6subnet.is6To4()) {
253       return v4addr.inSubnet(v6subnet.getIPv4For6To4(), cidr);
254     }
255   }
256   return false;
257 }
258
259 // public
260 bool IPAddress::inSubnetWithMask(const IPAddress& subnet, ByteRange mask)
261     const {
262   auto mkByteArray4 = [&]() -> ByteArray4 {
263     ByteArray4 ba{{0}};
264     std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
265     return ba;
266   };
267
268   if (bitCount() == subnet.bitCount()) {
269     if (isV4()) {
270       return asV4().inSubnetWithMask(subnet.asV4(), mkByteArray4());
271     } else {
272       ByteArray16 ba{{0}};
273       std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 16));
274       return asV6().inSubnetWithMask(subnet.asV6(), ba);
275     }
276   }
277
278   // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
279   // address and vice-versa
280   if (isV6()) {
281     const IPAddressV6& v6addr = asV6();
282     const IPAddressV4& v4subnet = subnet.asV4();
283     if (v6addr.is6To4()) {
284       return v6addr.getIPv4For6To4().inSubnetWithMask(v4subnet, mkByteArray4());
285     }
286   } else if (subnet.isV6()) {
287     const IPAddressV6& v6subnet = subnet.asV6();
288     const IPAddressV4& v4addr = asV4();
289     if (v6subnet.is6To4()) {
290       return v4addr.inSubnetWithMask(v6subnet.getIPv4For6To4(), mkByteArray4());
291     }
292   }
293   return false;
294 }
295
296 uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
297   const auto highestIndex = byteCount() - 1;
298   if (byteIndex > highestIndex) {
299     throw std::invalid_argument(sformat(
300         "Byte index must be <= {} for addresses of type: {}",
301         highestIndex,
302         detail::familyNameStr(family())));
303   }
304   if (isV4()) {
305     return asV4().bytes()[byteIndex];
306   }
307   return asV6().bytes()[byteIndex];
308 }
309
310 // public
311 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
312   if (addr1.family() == addr2.family()) {
313     if (addr1.isV6()) {
314       return (addr1.asV6() == addr2.asV6());
315     } else if (addr1.isV4()) {
316       return (addr1.asV4() == addr2.asV4());
317     } else {
318       CHECK_EQ(addr1.family(), AF_UNSPEC);
319       // Two default initialized AF_UNSPEC addresses should be considered equal.
320       // AF_UNSPEC is the only other value for which an IPAddress can be
321       // created, in the default constructor case.
322       return true;
323     }
324   }
325   // addr1 is v4 mapped v6 address, addr2 is v4
326   if (addr1.isIPv4Mapped() && addr2.isV4()) {
327     if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
328       return true;
329     }
330   }
331   // addr2 is v4 mapped v6 address, addr1 is v4
332   if (addr2.isIPv4Mapped() && addr1.isV4()) {
333     if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
334       return true;
335     }
336   }
337   // we only compare IPv4 and IPv6 addresses
338   return false;
339 }
340
341 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
342   if (addr1.family() == addr2.family()) {
343     if (addr1.isV6()) {
344       return (addr1.asV6() < addr2.asV6());
345     } else if (addr1.isV4()) {
346       return (addr1.asV4() < addr2.asV4());
347     } else {
348       CHECK_EQ(addr1.family(), AF_UNSPEC);
349       // Two default initialized AF_UNSPEC addresses can not be less than each
350       // other. AF_UNSPEC is the only other value for which an IPAddress can be
351       // created, in the default constructor case.
352       return false;
353     }
354   }
355   if (addr1.isV6()) {
356     // means addr2 is v4, convert it to a mapped v6 address and compare
357     return addr1.asV6() < addr2.asV4().createIPv6();
358   }
359   if (addr2.isV6()) {
360     // means addr2 is v6, convert addr1 to v4 mapped and compare
361     return addr1.asV4().createIPv6() < addr2.asV6();
362   }
363   return false;
364 }
365
366 CIDRNetwork IPAddress::longestCommonPrefix(
367     const CIDRNetwork& one,
368     const CIDRNetwork& two) {
369   if (one.first.family() != two.first.family()) {
370     throw std::invalid_argument(sformat(
371         "Can't compute longest common prefix between addresses of different"
372         "families. Passed: {} and {}",
373         detail::familyNameStr(one.first.family()),
374         detail::familyNameStr(two.first.family())));
375   }
376   if (one.first.isV4()) {
377     auto prefix = IPAddressV4::longestCommonPrefix(
378         {one.first.asV4(), one.second}, {two.first.asV4(), two.second});
379     return {IPAddress(prefix.first), prefix.second};
380   } else if (one.first.isV6()) {
381     auto prefix = IPAddressV6::longestCommonPrefix(
382         {one.first.asV6(), one.second}, {two.first.asV6(), two.second});
383     return {IPAddress(prefix.first), prefix.second};
384   } else {
385     throw std::invalid_argument("Unknown address family");
386   }
387 }
388
389 [[noreturn]] void IPAddress::asV4Throw() const {
390   auto fam = detail::familyNameStr(family());
391   throw InvalidAddressFamilyException(
392       sformat("Can't convert address with family {} to AF_INET address", fam));
393 }
394
395 [[noreturn]] void IPAddress::asV6Throw() const {
396   auto fam = detail::familyNameStr(family());
397   throw InvalidAddressFamilyException(
398       sformat("Can't convert address with family {} to AF_INET6 address", fam));
399 }
400
401 } // namespace folly