add support for whenAll to waitWithSemaphore
[folly.git] / folly / IPAddress.cpp
1 /*
2  * Copyright 2014 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 "IPAddress.h"
18
19 #include <limits>
20 #include <ostream>
21 #include <string>
22 #include <vector>
23
24 #include "folly/String.h"
25
26 using std::ostream;
27 using std::string;
28 using std::vector;
29
30 namespace folly {
31
32 // free functions
33 size_t hash_value(const IPAddress& addr) {
34   return addr.hash();
35 }
36 ostream& operator<<(ostream& os, const IPAddress& addr) {
37   os << addr.str();
38   return os;
39 }
40 void toAppend(IPAddress addr, string* result) {
41   result->append(addr.str());
42 }
43 void toAppend(IPAddress addr, fbstring* result) {
44   result->append(addr.str());
45 }
46
47 // public static
48 IPAddressV4 IPAddress::createIPv4(const IPAddress& addr) {
49   if (addr.isV4()) {
50     return addr.asV4();
51   } else {
52     return addr.asV6().createIPv4();
53   }
54 }
55
56 // public static
57 IPAddressV6 IPAddress::createIPv6(const IPAddress& addr) {
58   if (addr.isV6()) {
59     return addr.asV6();
60   } else {
61     return addr.asV4().createIPv6();
62   }
63 }
64
65 // public static
66 CIDRNetwork IPAddress::createNetwork(StringPiece ipSlashCidr,
67                                      int defaultCidr, /* = -1 */
68                                      bool applyMask /* = true */) {
69   if (defaultCidr > std::numeric_limits<uint8_t>::max()) {
70     throw std::range_error("defaultCidr must be <= UINT8_MAX");
71   }
72   vector<string> vec;
73   split("/", ipSlashCidr, vec);
74   vector<string>::size_type elemCount = vec.size();
75
76   if (elemCount == 0 || // weird invalid string
77       elemCount > 2) { // invalid string (IP/CIDR/extras)
78     throw IPAddressFormatException("Invalid ipSlashCidr specified. ",
79                                    "Expected IP/CIDR format, got ",
80                                    "'", ipSlashCidr, "'");
81   }
82   IPAddress subnet(vec.at(0));
83   uint8_t cidr = (defaultCidr > -1) ? defaultCidr : (subnet.isV4() ? 32 : 128);
84
85   if (elemCount == 2) {
86     try {
87       cidr = to<uint8_t>(vec.at(1));
88     } catch (...) {
89       throw IPAddressFormatException("Mask value ",
90                                      "'", vec.at(1), "' not a valid mask");
91     }
92   }
93   if (cidr > subnet.bitCount()) {
94     throw IPAddressFormatException("CIDR value '", cidr, "' ",
95                                    "is > network bit count ",
96                                    "'", subnet.bitCount(), "'");
97   }
98   return std::make_pair(applyMask ? subnet.mask(cidr) : subnet, cidr);
99 }
100
101 // public static
102 IPAddress IPAddress::fromBinary(ByteRange bytes) {
103   if (bytes.size() == 4) {
104     return IPAddress(IPAddressV4::fromBinary(bytes));
105   } else if (bytes.size() == 16) {
106     return IPAddress(IPAddressV6::fromBinary(bytes));
107   } else {
108     string hexval = detail::Bytes::toHex(bytes.data(), bytes.size());
109     throw IPAddressFormatException("Invalid address with hex value ",
110                                    "'", hexval, "'");
111   }
112 }
113
114 // public static
115 IPAddress IPAddress::fromLong(uint32_t src) {
116   return IPAddress(IPAddressV4::fromLong(src));
117 }
118 IPAddress IPAddress::fromLongHBO(uint32_t src) {
119   return IPAddress(IPAddressV4::fromLongHBO(src));
120 }
121
122 // default constructor
123 IPAddress::IPAddress()
124   : addr_()
125   , family_(AF_UNSPEC)
126 {
127 }
128
129 // public string constructor
130 IPAddress::IPAddress(StringPiece addr)
131   : addr_()
132   , family_(AF_UNSPEC)
133 {
134   string ip = addr.str();  // inet_pton() needs NUL-terminated string
135   auto throwFormatException = [&](const string& msg) {
136     throw IPAddressFormatException("Invalid IP '", ip, "': ", msg);
137   };
138
139   if (ip.size() < 2) {
140     throwFormatException("address too short");
141   }
142   if (ip.front() == '[' && ip.back() == ']') {
143     ip = ip.substr(1, ip.size() - 2);
144   }
145
146   // need to check for V4 address second, since IPv4-mapped IPv6 addresses may
147   // contain a period
148   if (ip.find(':') != string::npos) {
149     in6_addr ipAddr;
150     if (inet_pton(AF_INET6, ip.c_str(), &ipAddr) != 1) {
151       throwFormatException("inet_pton failed for V6 address");
152     }
153     addr_ = IPAddressV46(IPAddressV6(ipAddr));
154     family_ = AF_INET6;
155   } else if (ip.find('.') != string::npos) {
156     in_addr ipAddr;
157     if (inet_pton(AF_INET, ip.c_str(), &ipAddr) != 1) {
158       throwFormatException("inet_pton failed for V4 address");
159     }
160     addr_ = IPAddressV46(IPAddressV4(ipAddr));
161     family_ = AF_INET;
162   } else {
163     throwFormatException("invalid address format");
164   }
165 }
166
167 // public sockaddr constructor
168 IPAddress::IPAddress(const sockaddr* addr)
169   : addr_()
170   , family_(AF_UNSPEC)
171 {
172   if (addr == nullptr) {
173     throw IPAddressFormatException("sockaddr == nullptr");
174   }
175   family_ = addr->sa_family;
176   switch (addr->sa_family) {
177     case AF_INET: {
178       const sockaddr_in *v4addr = reinterpret_cast<const sockaddr_in*>(addr);
179       addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
180       break;
181     }
182     case AF_INET6: {
183       const sockaddr_in6 *v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
184       addr_.ipV6Addr = IPAddressV6(v6addr->sin6_addr);
185       break;
186     }
187     default:
188       throw InvalidAddressFamilyException(addr->sa_family);
189   }
190 }
191
192 // public ipv4 constructor
193 IPAddress::IPAddress(const IPAddressV4 ipV4Addr)
194   : addr_(ipV4Addr)
195   , family_(AF_INET)
196 {
197 }
198
199 // public ipv4 constructor
200 IPAddress::IPAddress(const in_addr ipV4Addr)
201   : addr_(IPAddressV4(ipV4Addr))
202   , family_(AF_INET)
203 {
204 }
205
206 // public ipv6 constructor
207 IPAddress::IPAddress(const IPAddressV6& ipV6Addr)
208   : addr_(ipV6Addr)
209   , family_(AF_INET6)
210 {
211 }
212
213 // public ipv6 constructor
214 IPAddress::IPAddress(const in6_addr& ipV6Addr)
215   : addr_(IPAddressV6(ipV6Addr))
216   , family_(AF_INET6)
217 {
218 }
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,
269                                  ByteRange mask) 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(to<string>("Byte index must be <= ",
308         to<string>(highestIndex), " for addresses of type :",
309         detail::familyNameStr(family())));
310   }
311   if (isV4()) {
312     return asV4().bytes()[byteIndex];
313   }
314   return asV6().bytes()[byteIndex];
315 }
316
317 // public
318 bool operator==(const IPAddress& addr1, const IPAddress& addr2) {
319   if (addr1.family() == addr2.family()) {
320     if (addr1.isV6()) {
321       return (addr1.asV6() == addr2.asV6());
322     } else if (addr1.isV4()) {
323       return (addr1.asV4() == addr2.asV4());
324     } else {
325       CHECK_EQ(addr1.family(), AF_UNSPEC);
326       // Two default initialized AF_UNSPEC addresses should be considered equal.
327       // AF_UNSPEC is the only other value for which an IPAddress can be
328       // created, in the default constructor case.
329       return true;
330     }
331   }
332   // addr1 is v4 mapped v6 address, addr2 is v4
333   if (addr1.isIPv4Mapped()) {
334     if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
335       return true;
336     }
337   }
338   // addr2 is v4 mapped v6 address, addr1 is v4
339   if (addr2.isIPv4Mapped()) {
340     if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
341       return true;
342     }
343   }
344   // we only compare IPv4 and IPv6 addresses
345   return false;
346 }
347
348 bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
349   if (addr1.family() == addr2.family()) {
350     if (addr1.isV6()) {
351       return (addr1.asV6() < addr2.asV6());
352     } else if (addr1.isV4()) {
353       return (addr1.asV4() < addr2.asV4());
354     } else {
355       CHECK_EQ(addr1.family(), AF_UNSPEC);
356       // Two default initialized AF_UNSPEC addresses can not be less than each
357       // other. AF_UNSPEC is the only other value for which an IPAddress can be
358       // created, in the default constructor case.
359       return false;
360     }
361   }
362   if (addr1.isV6()) {
363     // means addr2 is v4, convert it to a mapped v6 address and compare
364     return addr1.asV6() < addr2.asV4().createIPv6();
365   }
366   if (addr2.isV6()) {
367     // means addr2 is v6, convert addr1 to v4 mapped and compare
368     return addr1.asV4().createIPv6() < addr2.asV6();
369   }
370   return false;
371 }
372
373 CIDRNetwork
374 IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) {
375   if (one.first.family() != two.first.family()) {
376       throw std::invalid_argument(to<string>("Can't compute "
377             "longest common prefix between addresses of different families. "
378             "Passed: ", detail::familyNameStr(one.first.family()), " and ",
379             detail::familyNameStr(two.first.family())));
380   }
381   if (one.first.isV4()) {
382     auto prefix = IPAddressV4::longestCommonPrefix(
383       {one.first.asV4(), one.second},
384       {two.first.asV4(), two.second});
385     return {IPAddress(prefix.first), prefix.second};
386   } else if (one.first.isV6()) {
387     auto prefix = IPAddressV6::longestCommonPrefix(
388       {one.first.asV6(), one.second},
389       {two.first.asV6(), two.second});
390     return {IPAddress(prefix.first), prefix.second};
391   } else {
392     throw std::invalid_argument("Unknown address family");
393   }
394   return {IPAddress(0), 0};
395 }
396
397 }  // folly