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