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