Add prepareSkipTo() method to EliasFanoReader
[folly.git] / folly / IPAddressV6.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/IPAddressV6.h>
18
19 #include <ostream>
20 #include <string>
21
22 #include <folly/Format.h>
23 #include <folly/IPAddress.h>
24 #include <folly/IPAddressV4.h>
25 #include <folly/MacAddress.h>
26 #include <folly/detail/IPAddressSource.h>
27
28 #if !_WIN32
29 #include <net/if.h>
30 #else
31 // Because of the massive pain that is libnl, this can't go into the socket
32 // portability header as you can't include <linux/if.h> and <net/if.h> in
33 // the same translation unit without getting errors -_-...
34 #include <iphlpapi.h>
35 #include <ntddndis.h>
36
37 // Alias the max size of an interface name to what posix expects.
38 #define IFNAMSIZ IF_NAMESIZE
39 #endif
40
41 using std::ostream;
42 using std::string;
43
44 namespace folly {
45
46 // public static const
47 const uint32_t IPAddressV6::PREFIX_TEREDO = 0x20010000;
48 const uint32_t IPAddressV6::PREFIX_6TO4 = 0x2002;
49
50 // free functions
51 size_t hash_value(const IPAddressV6& addr) {
52   return addr.hash();
53 }
54 ostream& operator<<(ostream& os, const IPAddressV6& addr) {
55   os << addr.str();
56   return os;
57 }
58 void toAppend(IPAddressV6 addr, string* result) {
59   result->append(addr.str());
60 }
61 void toAppend(IPAddressV6 addr, fbstring* result) {
62   result->append(addr.str());
63 }
64
65 bool IPAddressV6::validate(StringPiece ip) {
66   if (ip.size() > 0 && ip.front() == '[' && ip.back() == ']') {
67     ip = ip.subpiece(1, ip.size() - 2);
68   }
69
70   constexpr size_t kStrMaxLen = INET6_ADDRSTRLEN;
71   std::array<char, kStrMaxLen + 1> ip_cstr;
72   const size_t len = std::min(ip.size(), kStrMaxLen);
73   std::memcpy(ip_cstr.data(), ip.data(), len);
74   ip_cstr[len] = 0;
75   struct in6_addr addr;
76   return 1 == inet_pton(AF_INET6, ip_cstr.data(), &addr);
77 }
78
79 // public default constructor
80 IPAddressV6::IPAddressV6() {}
81
82 // public string constructor
83 IPAddressV6::IPAddressV6(StringPiece addr) {
84   auto ip = addr.str();
85
86   // Allow addresses surrounded in brackets
87   if (ip.size() < 2) {
88     throw IPAddressFormatException(
89         sformat("Invalid IPv6 address '{}': address too short", ip));
90   }
91   if (ip.front() == '[' && ip.back() == ']') {
92     ip = ip.substr(1, ip.size() - 2);
93   }
94
95   struct addrinfo* result;
96   struct addrinfo hints;
97   memset(&hints, 0, sizeof(hints));
98   hints.ai_family = AF_INET6;
99   hints.ai_socktype = SOCK_STREAM;
100   hints.ai_flags = AI_NUMERICHOST;
101   if (!getaddrinfo(ip.c_str(), nullptr, &hints, &result)) {
102     struct sockaddr_in6* ipAddr = (struct sockaddr_in6*)result->ai_addr;
103     addr_.in6Addr_ = ipAddr->sin6_addr;
104     scope_ = uint16_t(ipAddr->sin6_scope_id);
105     freeaddrinfo(result);
106   } else {
107     throw IPAddressFormatException(sformat("Invalid IPv6 address '{}'", ip));
108   }
109 }
110
111 // in6_addr constructor
112 IPAddressV6::IPAddressV6(const in6_addr& src) : addr_(src) {}
113
114 // sockaddr_in6 constructor
115 IPAddressV6::IPAddressV6(const sockaddr_in6& src)
116     : addr_(src.sin6_addr), scope_(uint16_t(src.sin6_scope_id)) {}
117
118 // ByteArray16 constructor
119 IPAddressV6::IPAddressV6(const ByteArray16& src) : addr_(src) {}
120
121 // link-local constructor
122 IPAddressV6::IPAddressV6(LinkLocalTag, MacAddress mac) : addr_(mac) {}
123
124 IPAddressV6::AddressStorage::AddressStorage(MacAddress mac) {
125   // The link-local address uses modified EUI-64 format,
126   // See RFC 4291 sections 2.5.1, 2.5.6, and Appendix A
127   const auto* macBytes = mac.bytes();
128   memcpy(&bytes_.front(), "\xfe\x80\x00\x00\x00\x00\x00\x00", 8);
129   bytes_[8] = uint8_t(macBytes[0] ^ 0x02);
130   bytes_[9] = macBytes[1];
131   bytes_[10] = macBytes[2];
132   bytes_[11] = 0xff;
133   bytes_[12] = 0xfe;
134   bytes_[13] = macBytes[3];
135   bytes_[14] = macBytes[4];
136   bytes_[15] = macBytes[5];
137 }
138
139 Optional<MacAddress> IPAddressV6::getMacAddressFromLinkLocal() const {
140   // Returned MacAddress must be constructed from a link-local IPv6 address.
141   if (!(addr_.bytes_[0] == 0xfe && addr_.bytes_[1] == 0x80 &&
142         addr_.bytes_[2] == 0x00 && addr_.bytes_[3] == 0x00 &&
143         addr_.bytes_[4] == 0x00 && addr_.bytes_[5] == 0x00 &&
144         addr_.bytes_[6] == 0x00 && addr_.bytes_[7] == 0x00 &&
145         addr_.bytes_[11] == 0xff && addr_.bytes_[12] == 0xfe)) {
146     return folly::none;
147   }
148   // The link-local address uses modified EUI-64 format,
149   // See RFC 4291 sections 2.5.1, 2.5.6, and Appendix A
150   std::array<uint8_t, MacAddress::SIZE> bytes;
151   // Step 1: first 8 bytes are fe:80:00:00:00:00:00:00, and can be stripped
152   // Step 2: invert the universal/local (U/L) flag (bit 7)
153   bytes[0] = addr_.bytes_[8] ^ 0x02;
154   // Step 3: copy thhese bytes are they are
155   bytes[1] = addr_.bytes_[9];
156   bytes[2] = addr_.bytes_[10];
157   // Step 4: strip bytes (0xfffe), which are bytes_[11] and bytes_[12]
158   // Step 5: copy the rest.
159   bytes[3] = addr_.bytes_[13];
160   bytes[4] = addr_.bytes_[14];
161   bytes[5] = addr_.bytes_[15];
162   return Optional<MacAddress>(MacAddress::fromBinary(range(bytes)));
163 }
164
165 void IPAddressV6::setFromBinary(ByteRange bytes) {
166   if (bytes.size() != 16) {
167     throw IPAddressFormatException(sformat(
168         "Invalid IPv6 binary data: length must be 16 bytes, got {}",
169         bytes.size()));
170   }
171   memcpy(&addr_.in6Addr_.s6_addr, bytes.data(), sizeof(in6_addr));
172   scope_ = 0;
173 }
174
175 // static
176 IPAddressV6 IPAddressV6::fromInverseArpaName(const std::string& arpaname) {
177   auto piece = StringPiece(arpaname);
178   if (!piece.removeSuffix(".ip6.arpa")) {
179     throw IPAddressFormatException(sformat(
180         "Invalid input. Should end with 'ip6.arpa'. Got '{}'", arpaname));
181   }
182   std::vector<StringPiece> pieces;
183   split(".", piece, pieces);
184   if (pieces.size() != 32) {
185     throw IPAddressFormatException(sformat("Invalid input. Got '{}'", piece));
186   }
187   std::array<char, IPAddressV6::kToFullyQualifiedSize> ip;
188   size_t pos = 0;
189   int count = 0;
190   for (size_t i = 1; i <= pieces.size(); i++) {
191     ip[pos] = pieces[pieces.size() - i][0];
192     pos++;
193     count++;
194     // add ':' every 4 chars
195     if (count == 4 && pos < ip.size()) {
196       ip[pos++] = ':';
197       count = 0;
198     }
199   }
200   return IPAddressV6(folly::range(ip));
201 }
202
203 // public
204 IPAddressV4 IPAddressV6::createIPv4() const {
205   if (!isIPv4Mapped()) {
206     throw IPAddressFormatException("addr is not v4-to-v6-mapped");
207   }
208   const unsigned char* by = bytes();
209   return IPAddressV4(detail::Bytes::mkAddress4(&by[12]));
210 }
211
212 // convert two uint8_t bytes into a uint16_t as hibyte.lobyte
213 static inline uint16_t unpack(uint8_t lobyte, uint8_t hibyte) {
214   return uint16_t((uint16_t(hibyte) << 8) | lobyte);
215 }
216
217 // given a src string, unpack count*2 bytes into dest
218 // dest must have as much storage as count
219 static inline void
220 unpackInto(const unsigned char* src, uint16_t* dest, size_t count) {
221   for (size_t i = 0, hi = 1, lo = 0; i < count; i++) {
222     dest[i] = unpack(src[hi], src[lo]);
223     hi += 2;
224     lo += 2;
225   }
226 }
227
228 // public
229 IPAddressV4 IPAddressV6::getIPv4For6To4() const {
230   if (!is6To4()) {
231     throw IPAddressV6::TypeError(
232         sformat("Invalid IP '{}': not a 6to4 address", str()));
233   }
234   // convert 16x8 bytes into first 4x16 bytes
235   uint16_t ints[4] = {0, 0, 0, 0};
236   unpackInto(bytes(), ints, 4);
237   // repack into 4x8
238   union {
239     unsigned char bytes[4];
240     in_addr addr;
241   } ipv4;
242   ipv4.bytes[0] = (uint8_t)((ints[1] & 0xFF00) >> 8);
243   ipv4.bytes[1] = (uint8_t)(ints[1] & 0x00FF);
244   ipv4.bytes[2] = (uint8_t)((ints[2] & 0xFF00) >> 8);
245   ipv4.bytes[3] = (uint8_t)(ints[2] & 0x00FF);
246   return IPAddressV4(ipv4.addr);
247 }
248
249 // public
250 bool IPAddressV6::isIPv4Mapped() const {
251   // v4 mapped addresses have their first 10 bytes set to 0, the next 2 bytes
252   // set to 255 (0xff);
253   const unsigned char* by = bytes();
254
255   // check if first 10 bytes are 0
256   for (int i = 0; i < 10; i++) {
257     if (by[i] != 0x00) {
258       return false;
259     }
260   }
261   // check if bytes 11 and 12 are 255
262   if (by[10] == 0xff && by[11] == 0xff) {
263     return true;
264   }
265   return false;
266 }
267
268 // public
269 IPAddressV6::Type IPAddressV6::type() const {
270   // convert 16x8 bytes into first 2x16 bytes
271   uint16_t ints[2] = {0, 0};
272   unpackInto(bytes(), ints, 2);
273
274   if ((((uint32_t)ints[0] << 16) | ints[1]) == IPAddressV6::PREFIX_TEREDO) {
275     return Type::TEREDO;
276   }
277
278   if ((uint32_t)ints[0] == IPAddressV6::PREFIX_6TO4) {
279     return Type::T6TO4;
280   }
281
282   return Type::NORMAL;
283 }
284
285 // public
286 string IPAddressV6::toJson() const {
287   return sformat("{{family:'AF_INET6', addr:'{}', hash:{}}}", str(), hash());
288 }
289
290 // public
291 size_t IPAddressV6::hash() const {
292   if (isIPv4Mapped()) {
293     /* An IPAddress containing this object would be equal (i.e. operator==)
294        to an IPAddress containing the corresponding IPv4.
295        So we must make sure that the hash values are the same as well */
296     return IPAddress::createIPv4(*this).hash();
297   }
298
299   static const uint64_t seed = AF_INET6;
300   uint64_t hash1 = 0, hash2 = 0;
301   hash::SpookyHashV2::Hash128(&addr_, 16, &hash1, &hash2);
302   return hash::hash_combine(seed, hash1, hash2);
303 }
304
305 // public
306 bool IPAddressV6::inSubnet(StringPiece cidrNetwork) const {
307   auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
308   auto addr = subnetInfo.first;
309   if (!addr.isV6()) {
310     throw IPAddressFormatException(
311         sformat("Address '{}' is not a V6 address", addr.toJson()));
312   }
313   return inSubnetWithMask(addr.asV6(), fetchMask(subnetInfo.second));
314 }
315
316 // public
317 bool IPAddressV6::inSubnetWithMask(
318     const IPAddressV6& subnet,
319     const ByteArray16& cidrMask) const {
320   const auto mask = detail::Bytes::mask(toByteArray(), cidrMask);
321   const auto subMask = detail::Bytes::mask(subnet.toByteArray(), cidrMask);
322   return (mask == subMask);
323 }
324
325 // public
326 bool IPAddressV6::isLoopback() const {
327   // Check if v4 mapped is loopback
328   if (isIPv4Mapped() && createIPv4().isLoopback()) {
329     return true;
330   }
331   auto socka = toSockAddr();
332   return IN6_IS_ADDR_LOOPBACK(&socka.sin6_addr);
333 }
334
335 bool IPAddressV6::isRoutable() const {
336   return
337       // 2000::/3 is the only assigned global unicast block
338       inBinarySubnet({{0x20, 0x00}}, 3) ||
339       // ffxe::/16 are global scope multicast addresses,
340       // which are eligible to be routed over the internet
341       (isMulticast() && getMulticastScope() == 0xe);
342 }
343
344 bool IPAddressV6::isLinkLocalBroadcast() const {
345   static const IPAddressV6 kLinkLocalBroadcast("ff02::1");
346   return *this == kLinkLocalBroadcast;
347 }
348
349 // public
350 bool IPAddressV6::isPrivate() const {
351   // Check if mapped is private
352   if (isIPv4Mapped() && createIPv4().isPrivate()) {
353     return true;
354   }
355   return isLoopback() || inBinarySubnet({{0xfc, 0x00}}, 7);
356 }
357
358 // public
359 bool IPAddressV6::isLinkLocal() const {
360   return inBinarySubnet({{0xfe, 0x80}}, 10);
361 }
362
363 bool IPAddressV6::isMulticast() const {
364   return addr_.bytes_[0] == 0xff;
365 }
366
367 uint8_t IPAddressV6::getMulticastFlags() const {
368   DCHECK(isMulticast());
369   return uint8_t((addr_.bytes_[1] >> 4) & 0xf);
370 }
371
372 uint8_t IPAddressV6::getMulticastScope() const {
373   DCHECK(isMulticast());
374   return uint8_t(addr_.bytes_[1] & 0xf);
375 }
376
377 IPAddressV6 IPAddressV6::getSolicitedNodeAddress() const {
378   // Solicted node addresses must be constructed from unicast (or anycast)
379   // addresses
380   DCHECK(!isMulticast());
381
382   uint8_t bytes[16] = {
383       0xff,
384       0x02,
385       0x00,
386       0x00,
387       0x00,
388       0x00,
389       0x00,
390       0x00,
391       0x00,
392       0x00,
393       0x00,
394       0x01,
395       0xff,
396       addr_.bytes_[13],
397       addr_.bytes_[14],
398       addr_.bytes_[15],
399   };
400   return IPAddressV6::fromBinary(ByteRange(bytes, 16));
401 }
402
403 // public
404 IPAddressV6 IPAddressV6::mask(size_t numBits) const {
405   static const auto bits = bitCount();
406   if (numBits > bits) {
407     throw IPAddressFormatException(
408         sformat("numBits({}) > bitCount({})", numBits, bits));
409   }
410   ByteArray16 ba = detail::Bytes::mask(fetchMask(numBits), addr_.bytes_);
411   return IPAddressV6(ba);
412 }
413
414 // public
415 string IPAddressV6::str() const {
416   char buffer[INET6_ADDRSTRLEN + IFNAMSIZ + 1];
417
418   if (!inet_ntop(AF_INET6, toAddr().s6_addr, buffer, INET6_ADDRSTRLEN)) {
419     throw IPAddressFormatException(sformat(
420         "Invalid address with hex '{}' with error {}",
421         detail::Bytes::toHex(bytes(), 16),
422         strerror(errno)));
423   }
424
425   auto scopeId = getScopeId();
426   if (scopeId != 0) {
427     auto len = strlen(buffer);
428     buffer[len] = '%';
429
430     auto errsv = errno;
431     if (!if_indextoname(scopeId, buffer + len + 1)) {
432       // if we can't map the if because eg. it no longer exists,
433       // append the if index instead
434       snprintf(buffer + len + 1, IFNAMSIZ, "%u", scopeId);
435     }
436     errno = errsv;
437   }
438
439   return string(buffer);
440 }
441
442 // public
443 string IPAddressV6::toFullyQualified() const {
444   return detail::fastIpv6ToString(addr_.in6Addr_);
445 }
446
447 // public
448 void IPAddressV6::toFullyQualifiedAppend(std::string& out) const {
449   detail::fastIpv6AppendToString(addr_.in6Addr_, out);
450 }
451
452 // public
453 string IPAddressV6::toInverseArpaName() const {
454   constexpr folly::StringPiece lut = "0123456789abcdef";
455   std::array<char, 32> a;
456   int j = 0;
457   for (int i = 15; i >= 0; i--) {
458     a[j] = (lut[bytes()[i] & 0xf]);
459     a[j + 1] = (lut[bytes()[i] >> 4]);
460     j += 2;
461   }
462   return sformat("{}.ip6.arpa", join(".", a));
463 }
464
465 // public
466 uint8_t IPAddressV6::getNthMSByte(size_t byteIndex) const {
467   const auto highestIndex = byteCount() - 1;
468   if (byteIndex > highestIndex) {
469     throw std::invalid_argument(sformat(
470         "Byte index must be <= {} for addresses of type: {}",
471         highestIndex,
472         detail::familyNameStr(AF_INET6)));
473   }
474   return bytes()[byteIndex];
475 }
476
477 // protected
478 const ByteArray16 IPAddressV6::fetchMask(size_t numBits) {
479   static const size_t bits = bitCount();
480   if (numBits > bits) {
481     throw IPAddressFormatException("IPv6 addresses are 128 bits.");
482   }
483   if (numBits == 0) {
484     return {{0}};
485   }
486   constexpr auto _0s = uint64_t(0);
487   constexpr auto _1s = ~_0s;
488   auto const fragment = Endian::big(_1s << ((128 - numBits) % 64));
489   auto const hi = numBits <= 64 ? fragment : _1s;
490   auto const lo = numBits <= 64 ? _0s : fragment;
491   uint64_t const parts[] = {hi, lo};
492   ByteArray16 arr;
493   std::memcpy(arr.data(), parts, sizeof(parts));
494   return arr;
495 }
496
497 // public static
498 CIDRNetworkV6 IPAddressV6::longestCommonPrefix(
499     const CIDRNetworkV6& one,
500     const CIDRNetworkV6& two) {
501   auto prefix = detail::Bytes::longestCommonPrefix(
502       one.first.addr_.bytes_, one.second, two.first.addr_.bytes_, two.second);
503   return {IPAddressV6(prefix.first), prefix.second};
504 }
505
506 // protected
507 bool IPAddressV6::inBinarySubnet(
508     const std::array<uint8_t, 2> addr,
509     size_t numBits) const {
510   auto masked = mask(numBits);
511   return (std::memcmp(addr.data(), masked.bytes(), 2) == 0);
512 }
513 } // namespace folly