Flesh out Optional members swap, reset, emplace, has_value
[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) {
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 // public static
129 IPAddress IPAddress::fromLong(uint32_t src) {
130   return IPAddress(IPAddressV4::fromLong(src));
131 }
132 IPAddress IPAddress::fromLongHBO(uint32_t src) {
133   return IPAddress(IPAddressV4::fromLongHBO(src));
134 }
135
136 // default constructor
137 IPAddress::IPAddress() : addr_(), family_(AF_UNSPEC) {}
138
139 // public string constructor
140 IPAddress::IPAddress(StringPiece addr) : addr_(), family_(AF_UNSPEC) {
141   string ip = addr.str(); // inet_pton() needs NUL-terminated string
142   auto throwFormatException = [&](const string& msg) {
143     throw IPAddressFormatException(sformat("Invalid IP '{}': {}", ip, msg));
144   };
145
146   if (ip.size() < 2) {
147     throwFormatException("address too short");
148   }
149   if (ip.front() == '[' && ip.back() == ']') {
150     ip = ip.substr(1, ip.size() - 2);
151   }
152
153   // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
154   // contain a period
155   if (ip.find(':') != string::npos) {
156     struct addrinfo* result;
157     struct addrinfo hints;
158     memset(&hints, 0, sizeof(hints));
159     hints.ai_family = AF_INET6;
160     hints.ai_socktype = SOCK_STREAM;
161     hints.ai_flags = AI_NUMERICHOST;
162     if (!getaddrinfo(ip.c_str(), nullptr, &hints, &result)) {
163       struct sockaddr_in6* ipAddr = (struct sockaddr_in6*)result->ai_addr;
164       addr_ = IPAddressV46(IPAddressV6(*ipAddr));
165       family_ = AF_INET6;
166       freeaddrinfo(result);
167     } else {
168       throwFormatException("getsockaddr failed for V6 address");
169     }
170   } else if (ip.find('.') != string::npos) {
171     in_addr ipAddr;
172     if (inet_pton(AF_INET, ip.c_str(), &ipAddr) != 1) {
173       throwFormatException("inet_pton failed for V4 address");
174     }
175     addr_ = IPAddressV46(IPAddressV4(ipAddr));
176     family_ = AF_INET;
177   } else {
178     throwFormatException("invalid address format");
179   }
180 }
181
182 // public sockaddr constructor
183 IPAddress::IPAddress(const sockaddr* addr) : addr_(), family_(AF_UNSPEC) {
184   if (addr == nullptr) {
185     throw IPAddressFormatException("sockaddr == nullptr");
186   }
187   family_ = addr->sa_family;
188   switch (addr->sa_family) {
189     case AF_INET: {
190       const sockaddr_in* v4addr = reinterpret_cast<const sockaddr_in*>(addr);
191       addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
192       break;
193     }
194     case AF_INET6: {
195       const sockaddr_in6* v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
196       addr_.ipV6Addr = IPAddressV6(*v6addr);
197       break;
198     }
199     default:
200       throw InvalidAddressFamilyException(addr->sa_family);
201   }
202 }
203
204 // public ipv4 constructor
205 IPAddress::IPAddress(const IPAddressV4 ipV4Addr)
206     : addr_(ipV4Addr), family_(AF_INET) {}
207
208 // public ipv4 constructor
209 IPAddress::IPAddress(const in_addr ipV4Addr)
210     : addr_(IPAddressV4(ipV4Addr)), family_(AF_INET) {}
211
212 // public ipv6 constructor
213 IPAddress::IPAddress(const IPAddressV6& ipV6Addr)
214     : addr_(ipV6Addr), family_(AF_INET6) {}
215
216 // public ipv6 constructor
217 IPAddress::IPAddress(const in6_addr& ipV6Addr)
218     : addr_(IPAddressV6(ipV6Addr)), family_(AF_INET6) {}
219
220 // Assign from V4 address
221 IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) {
222   addr_ = IPAddressV46(ipv4_addr);
223   family_ = AF_INET;
224   return *this;
225 }
226
227 // Assign from V6 address
228 IPAddress& IPAddress::operator=(const IPAddressV6& ipv6_addr) {
229   addr_ = IPAddressV46(ipv6_addr);
230   family_ = AF_INET6;
231   return *this;
232 }
233
234 // public
235 bool IPAddress::inSubnet(StringPiece cidrNetwork) const {
236   auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
237   return inSubnet(subnetInfo.first, subnetInfo.second);
238 }
239
240 // public
241 bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
242   if (bitCount() == subnet.bitCount()) {
243     if (isV4()) {
244       return asV4().inSubnet(subnet.asV4(), cidr);
245     } else {
246       return asV6().inSubnet(subnet.asV6(), cidr);
247     }
248   }
249   // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
250   // address and vice-versa
251   if (isV6()) {
252     const IPAddressV6& v6addr = asV6();
253     const IPAddressV4& v4subnet = subnet.asV4();
254     if (v6addr.is6To4()) {
255       return v6addr.getIPv4For6To4().inSubnet(v4subnet, cidr);
256     }
257   } else if (subnet.isV6()) {
258     const IPAddressV6& v6subnet = subnet.asV6();
259     const IPAddressV4& v4addr = asV4();
260     if (v6subnet.is6To4()) {
261       return v4addr.inSubnet(v6subnet.getIPv4For6To4(), cidr);
262     }
263   }
264   return false;
265 }
266
267 // public
268 bool IPAddress::inSubnetWithMask(const IPAddress& subnet, ByteRange mask)
269     const {
270   auto mkByteArray4 = [&]() -> ByteArray4 {
271     ByteArray4 ba{{0}};
272     std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
273     return ba;
274   };
275
276   if (bitCount() == subnet.bitCount()) {
277     if (isV4()) {
278       return asV4().inSubnetWithMask(subnet.asV4(), mkByteArray4());
279     } else {
280       ByteArray16 ba{{0}};
281       std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 16));
282       return asV6().inSubnetWithMask(subnet.asV6(), ba);
283     }
284   }
285
286   // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
287   // address and vice-versa
288   if (isV6()) {
289     const IPAddressV6& v6addr = asV6();
290     const IPAddressV4& v4subnet = subnet.asV4();
291     if (v6addr.is6To4()) {
292       return v6addr.getIPv4For6To4().inSubnetWithMask(v4subnet, mkByteArray4());
293     }
294   } else if (subnet.isV6()) {
295     const IPAddressV6& v6subnet = subnet.asV6();
296     const IPAddressV4& v4addr = asV4();
297     if (v6subnet.is6To4()) {
298       return v4addr.inSubnetWithMask(v6subnet.getIPv4For6To4(), mkByteArray4());
299     }
300   }
301   return false;
302 }
303
304 uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
305   const auto highestIndex = byteCount() - 1;
306   if (byteIndex > highestIndex) {
307     throw std::invalid_argument(sformat(
308         "Byte index must be <= {} for addresses of type: {}",
309         highestIndex,
310         detail::familyNameStr(family())));
311   }
312   if (isV4()) {
313     return asV4().bytes()[byteIndex];
314   }
315   return asV6().bytes()[byteIndex];
316 }
317
318 // public
319 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
320   if (addr1.family() == addr2.family()) {
321     if (addr1.isV6()) {
322       return (addr1.asV6() == addr2.asV6());
323     } else if (addr1.isV4()) {
324       return (addr1.asV4() == addr2.asV4());
325     } else {
326       CHECK_EQ(addr1.family(), AF_UNSPEC);
327       // Two default initialized AF_UNSPEC addresses should be considered equal.
328       // AF_UNSPEC is the only other value for which an IPAddress can be
329       // created, in the default constructor case.
330       return true;
331     }
332   }
333   // addr1 is v4 mapped v6 address, addr2 is v4
334   if (addr1.isIPv4Mapped() && addr2.isV4()) {
335     if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
336       return true;
337     }
338   }
339   // addr2 is v4 mapped v6 address, addr1 is v4
340   if (addr2.isIPv4Mapped() && addr1.isV4()) {
341     if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
342       return true;
343     }
344   }
345   // we only compare IPv4 and IPv6 addresses
346   return false;
347 }
348
349 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
350   if (addr1.family() == addr2.family()) {
351     if (addr1.isV6()) {
352       return (addr1.asV6() < addr2.asV6());
353     } else if (addr1.isV4()) {
354       return (addr1.asV4() < addr2.asV4());
355     } else {
356       CHECK_EQ(addr1.family(), AF_UNSPEC);
357       // Two default initialized AF_UNSPEC addresses can not be less than each
358       // other. AF_UNSPEC is the only other value for which an IPAddress can be
359       // created, in the default constructor case.
360       return false;
361     }
362   }
363   if (addr1.isV6()) {
364     // means addr2 is v4, convert it to a mapped v6 address and compare
365     return addr1.asV6() < addr2.asV4().createIPv6();
366   }
367   if (addr2.isV6()) {
368     // means addr2 is v6, convert addr1 to v4 mapped and compare
369     return addr1.asV4().createIPv6() < addr2.asV6();
370   }
371   return false;
372 }
373
374 CIDRNetwork IPAddress::longestCommonPrefix(
375     const CIDRNetwork& one,
376     const CIDRNetwork& two) {
377   if (one.first.family() != two.first.family()) {
378     throw std::invalid_argument(sformat(
379         "Can't compute longest common prefix between addresses of different"
380         "families. Passed: {} and {}",
381         detail::familyNameStr(one.first.family()),
382         detail::familyNameStr(two.first.family())));
383   }
384   if (one.first.isV4()) {
385     auto prefix = IPAddressV4::longestCommonPrefix(
386         {one.first.asV4(), one.second}, {two.first.asV4(), two.second});
387     return {IPAddress(prefix.first), prefix.second};
388   } else if (one.first.isV6()) {
389     auto prefix = IPAddressV6::longestCommonPrefix(
390         {one.first.asV6(), one.second}, {two.first.asV6(), two.second});
391     return {IPAddress(prefix.first), prefix.second};
392   } else {
393     throw std::invalid_argument("Unknown address family");
394   }
395 }
396
397 [[noreturn]] void IPAddress::asV4Throw() const {
398   auto fam = detail::familyNameStr(family());
399   throw InvalidAddressFamilyException(
400       sformat("Can't convert address with family {} to AF_INET address", fam));
401 }
402
403 [[noreturn]] void IPAddress::asV6Throw() const {
404   auto fam = detail::familyNameStr(family());
405   throw InvalidAddressFamilyException(
406       sformat("Can't convert address with family {} to AF_INET6 address", fam));
407 }
408
409 } // namespace folly