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