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