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