Fix include ordering for OpenSSLPtrTypes.h
[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/Conv.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(StringPiece ipSlashCidr,
73                                      int defaultCidr, /* = -1 */
74                                      bool applyMask /* = true */) {
75   if (defaultCidr > std::numeric_limits<uint8_t>::max()) {
76     throw std::range_error("defaultCidr must be <= UINT8_MAX");
77   }
78   vector<string> vec;
79   split("/", ipSlashCidr, vec);
80   vector<string>::size_type elemCount = vec.size();
81
82   if (elemCount == 0 || // weird invalid string
83       elemCount > 2) { // invalid string (IP/CIDR/extras)
84     throw IPAddressFormatException(to<std::string>(
85         "Invalid ipSlashCidr specified. ",
86         "Expected IP/CIDR format, got ",
87         "'",
88         ipSlashCidr,
89         "'"));
90   }
91   IPAddress subnet(vec.at(0));
92   auto cidr =
93       uint8_t((defaultCidr > -1) ? defaultCidr : (subnet.isV4() ? 32 : 128));
94
95   if (elemCount == 2) {
96     try {
97       cidr = to<uint8_t>(vec.at(1));
98     } catch (...) {
99       throw IPAddressFormatException(
100           to<std::string>("Mask value ", "'", vec.at(1), "' not a valid mask"));
101     }
102   }
103   if (cidr > subnet.bitCount()) {
104     throw IPAddressFormatException(to<std::string>(
105         "CIDR value '",
106         cidr,
107         "' ",
108         "is > network bit count ",
109         "'",
110         subnet.bitCount(),
111         "'"));
112   }
113   return std::make_pair(applyMask ? subnet.mask(cidr) : subnet, cidr);
114 }
115
116 // public static
117 std::string IPAddress::networkToString(const CIDRNetwork& network) {
118   return network.first.str() + "/" + folly::to<std::string>(network.second);
119 }
120
121 // public static
122 IPAddress IPAddress::fromBinary(ByteRange bytes) {
123   if (bytes.size() == 4) {
124     return IPAddress(IPAddressV4::fromBinary(bytes));
125   } else if (bytes.size() == 16) {
126     return IPAddress(IPAddressV6::fromBinary(bytes));
127   } else {
128     string hexval = detail::Bytes::toHex(bytes.data(), bytes.size());
129     throw IPAddressFormatException(
130         to<std::string>("Invalid address with hex value ", "'", hexval, "'"));
131   }
132 }
133
134 // public static
135 IPAddress IPAddress::fromLong(uint32_t src) {
136   return IPAddress(IPAddressV4::fromLong(src));
137 }
138 IPAddress IPAddress::fromLongHBO(uint32_t src) {
139   return IPAddress(IPAddressV4::fromLongHBO(src));
140 }
141
142 // default constructor
143 IPAddress::IPAddress()
144   : addr_()
145   , family_(AF_UNSPEC)
146 {
147 }
148
149 // public string constructor
150 IPAddress::IPAddress(StringPiece addr)
151   : addr_()
152   , family_(AF_UNSPEC)
153 {
154   string ip = addr.str();  // inet_pton() needs NUL-terminated string
155   auto throwFormatException = [&](const string& msg) {
156     throw IPAddressFormatException(
157         to<std::string>("Invalid IP '", ip, "': ", msg));
158   };
159
160   if (ip.size() < 2) {
161     throwFormatException("address too short");
162   }
163   if (ip.front() == '[' && ip.back() == ']') {
164     ip = ip.substr(1, ip.size() - 2);
165   }
166
167   // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
168   // contain a period
169   if (ip.find(':') != string::npos) {
170     struct addrinfo* result;
171     struct addrinfo hints;
172     memset(&hints, 0, sizeof(hints));
173     hints.ai_family = AF_INET6;
174     hints.ai_socktype = SOCK_STREAM;
175     hints.ai_flags = AI_NUMERICHOST;
176     if (!getaddrinfo(ip.c_str(), nullptr, &hints, &result)) {
177       struct sockaddr_in6* ipAddr = (struct sockaddr_in6*)result->ai_addr;
178       addr_ = IPAddressV46(IPAddressV6(*ipAddr));
179       family_ = AF_INET6;
180       freeaddrinfo(result);
181     } else {
182       throwFormatException("getsockaddr failed for V6 address");
183     }
184   } else if (ip.find('.') != string::npos) {
185     in_addr ipAddr;
186     if (inet_pton(AF_INET, ip.c_str(), &ipAddr) != 1) {
187       throwFormatException("inet_pton failed for V4 address");
188     }
189     addr_ = IPAddressV46(IPAddressV4(ipAddr));
190     family_ = AF_INET;
191   } else {
192     throwFormatException("invalid address format");
193   }
194 }
195
196 // public sockaddr constructor
197 IPAddress::IPAddress(const sockaddr* addr)
198   : addr_()
199   , family_(AF_UNSPEC)
200 {
201   if (addr == nullptr) {
202     throw IPAddressFormatException("sockaddr == nullptr");
203   }
204   family_ = addr->sa_family;
205   switch (addr->sa_family) {
206     case AF_INET: {
207       const sockaddr_in *v4addr = reinterpret_cast<const sockaddr_in*>(addr);
208       addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
209       break;
210     }
211     case AF_INET6: {
212       const sockaddr_in6 *v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
213       addr_.ipV6Addr = IPAddressV6(*v6addr);
214       break;
215     }
216     default:
217       throw InvalidAddressFamilyException(addr->sa_family);
218   }
219 }
220
221 // public ipv4 constructor
222 IPAddress::IPAddress(const IPAddressV4 ipV4Addr)
223   : addr_(ipV4Addr)
224   , family_(AF_INET)
225 {
226 }
227
228 // public ipv4 constructor
229 IPAddress::IPAddress(const in_addr ipV4Addr)
230   : addr_(IPAddressV4(ipV4Addr))
231   , family_(AF_INET)
232 {
233 }
234
235 // public ipv6 constructor
236 IPAddress::IPAddress(const IPAddressV6& ipV6Addr)
237   : addr_(ipV6Addr)
238   , family_(AF_INET6)
239 {
240 }
241
242 // public ipv6 constructor
243 IPAddress::IPAddress(const in6_addr& ipV6Addr)
244   : addr_(IPAddressV6(ipV6Addr))
245   , family_(AF_INET6)
246 {
247 }
248
249 // Assign from V4 address
250 IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) {
251   addr_ = IPAddressV46(ipv4_addr);
252   family_ = AF_INET;
253   return *this;
254 }
255
256 // Assign from V6 address
257 IPAddress& IPAddress::operator=(const IPAddressV6& ipv6_addr) {
258   addr_ = IPAddressV46(ipv6_addr);
259   family_ = AF_INET6;
260   return *this;
261 }
262
263 // public
264 bool IPAddress::inSubnet(StringPiece cidrNetwork) const {
265   auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
266   return inSubnet(subnetInfo.first, subnetInfo.second);
267 }
268
269 // public
270 bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
271   if (bitCount() == subnet.bitCount()) {
272     if (isV4()) {
273       return asV4().inSubnet(subnet.asV4(), cidr);
274     } else {
275       return asV6().inSubnet(subnet.asV6(), cidr);
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().inSubnet(v4subnet, cidr);
285     }
286   } else if (subnet.isV6()) {
287     const IPAddressV6& v6subnet = subnet.asV6();
288     const IPAddressV4& v4addr = asV4();
289     if (v6subnet.is6To4()) {
290       return v4addr.inSubnet(v6subnet.getIPv4For6To4(), cidr);
291     }
292   }
293   return false;
294 }
295
296 // public
297 bool IPAddress::inSubnetWithMask(const IPAddress& subnet,
298                                  ByteRange mask) const {
299   auto mkByteArray4 = [&]() -> ByteArray4 {
300     ByteArray4 ba{{0}};
301     std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
302     return ba;
303   };
304
305   if (bitCount() == subnet.bitCount()) {
306     if (isV4()) {
307       return asV4().inSubnetWithMask(subnet.asV4(), mkByteArray4());
308     } else {
309       ByteArray16 ba{{0}};
310       std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 16));
311       return asV6().inSubnetWithMask(subnet.asV6(), ba);
312     }
313   }
314
315   // an IPv4 address can never belong in a IPv6 subnet unless the IPv6 is a 6to4
316   // address and vice-versa
317   if (isV6()) {
318     const IPAddressV6& v6addr = asV6();
319     const IPAddressV4& v4subnet = subnet.asV4();
320     if (v6addr.is6To4()) {
321       return v6addr.getIPv4For6To4().inSubnetWithMask(v4subnet, mkByteArray4());
322     }
323   } else if (subnet.isV6()) {
324     const IPAddressV6& v6subnet = subnet.asV6();
325     const IPAddressV4& v4addr = asV4();
326     if (v6subnet.is6To4()) {
327       return v4addr.inSubnetWithMask(v6subnet.getIPv4For6To4(), mkByteArray4());
328     }
329   }
330   return false;
331 }
332
333 uint8_t IPAddress::getNthMSByte(size_t byteIndex) const {
334   const auto highestIndex = byteCount() - 1;
335   if (byteIndex > highestIndex) {
336     throw std::invalid_argument(to<string>("Byte index must be <= ",
337         to<string>(highestIndex), " for addresses of type :",
338         detail::familyNameStr(family())));
339   }
340   if (isV4()) {
341     return asV4().bytes()[byteIndex];
342   }
343   return asV6().bytes()[byteIndex];
344 }
345
346 // public
347 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
348   if (addr1.family() == addr2.family()) {
349     if (addr1.isV6()) {
350       return (addr1.asV6() == addr2.asV6());
351     } else if (addr1.isV4()) {
352       return (addr1.asV4() == addr2.asV4());
353     } else {
354       CHECK_EQ(addr1.family(), AF_UNSPEC);
355       // Two default initialized AF_UNSPEC addresses should be considered equal.
356       // AF_UNSPEC is the only other value for which an IPAddress can be
357       // created, in the default constructor case.
358       return true;
359     }
360   }
361   // addr1 is v4 mapped v6 address, addr2 is v4
362   if (addr1.isIPv4Mapped() && addr2.isV4()) {
363     if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
364       return true;
365     }
366   }
367   // addr2 is v4 mapped v6 address, addr1 is v4
368   if (addr2.isIPv4Mapped() && addr1.isV4()) {
369     if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
370       return true;
371     }
372   }
373   // we only compare IPv4 and IPv6 addresses
374   return false;
375 }
376
377 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
378   if (addr1.family() == addr2.family()) {
379     if (addr1.isV6()) {
380       return (addr1.asV6() < addr2.asV6());
381     } else if (addr1.isV4()) {
382       return (addr1.asV4() < addr2.asV4());
383     } else {
384       CHECK_EQ(addr1.family(), AF_UNSPEC);
385       // Two default initialized AF_UNSPEC addresses can not be less than each
386       // other. AF_UNSPEC is the only other value for which an IPAddress can be
387       // created, in the default constructor case.
388       return false;
389     }
390   }
391   if (addr1.isV6()) {
392     // means addr2 is v4, convert it to a mapped v6 address and compare
393     return addr1.asV6() < addr2.asV4().createIPv6();
394   }
395   if (addr2.isV6()) {
396     // means addr2 is v6, convert addr1 to v4 mapped and compare
397     return addr1.asV4().createIPv6() < addr2.asV6();
398   }
399   return false;
400 }
401
402 CIDRNetwork
403 IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) {
404   if (one.first.family() != two.first.family()) {
405       throw std::invalid_argument(to<string>("Can't compute "
406             "longest common prefix between addresses of different families. "
407             "Passed: ", detail::familyNameStr(one.first.family()), " and ",
408             detail::familyNameStr(two.first.family())));
409   }
410   if (one.first.isV4()) {
411     auto prefix = IPAddressV4::longestCommonPrefix(
412       {one.first.asV4(), one.second},
413       {two.first.asV4(), two.second});
414     return {IPAddress(prefix.first), prefix.second};
415   } else if (one.first.isV6()) {
416     auto prefix = IPAddressV6::longestCommonPrefix(
417       {one.first.asV6(), one.second},
418       {two.first.asV6(), two.second});
419     return {IPAddress(prefix.first), prefix.second};
420   } else {
421     throw std::invalid_argument("Unknown address family");
422   }
423 }
424
425 [[noreturn]] void IPAddress::asV4Throw() const {
426   auto fam = detail::familyNameStr(family());
427   throw InvalidAddressFamilyException(to<std::string>(
428       "Can't convert address with family ", fam, " to AF_INET address"));
429 }
430
431 [[noreturn]] void IPAddress::asV6Throw() const {
432   auto fam = detail::familyNameStr(family());
433   throw InvalidAddressFamilyException(to<std::string>(
434       "Can't convert address with family ", fam, " to AF_INET6 address"));
435 }
436
437
438 }  // folly