Fix SimplerObservable build with -Werror=unused-local-typedefs
[folly.git] / folly / IPAddressV6.cpp
index 188a47761021b0bb7b79beb79e8a324130711b07..9904c406a5fc0f7d6142bda7a12fec87bfb12737 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2014 Facebook, Inc.
+ * Copyright 2016 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-#include "IPAddressV6.h"
+#include <folly/IPAddressV6.h>
 
 #include <ostream>
 #include <string>
@@ -23,6 +23,7 @@
 #include <folly/IPAddress.h>
 #include <folly/IPAddressV4.h>
 #include <folly/MacAddress.h>
+#include <folly/detail/IPAddressSource.h>
 
 using std::ostream;
 using std::string;
@@ -48,6 +49,20 @@ void toAppend(IPAddressV6 addr, fbstring* result) {
   result->append(addr.str());
 }
 
+bool IPAddressV6::validate(StringPiece ip) {
+  if (ip.size() > 0 && ip.front() == '[' && ip.back() == ']') {
+    ip = ip.subpiece(1, ip.size() - 2);
+  }
+
+  constexpr size_t kStrMaxLen = INET6_ADDRSTRLEN;
+  std::array<char, kStrMaxLen + 1> ip_cstr;
+  const size_t len = std::min(ip.size(), kStrMaxLen);
+  std::memcpy(ip_cstr.data(), ip.data(), len);
+  ip_cstr[len] = 0;
+  struct in6_addr addr;
+  return 1 == inet_pton(AF_INET6, ip_cstr.data(), &addr);
+}
+
 // public default constructor
 IPAddressV6::IPAddressV6() {
 }
@@ -58,15 +73,27 @@ IPAddressV6::IPAddressV6(StringPiece addr) {
 
   // Allow addresses surrounded in brackets
   if (ip.size() < 2) {
-    throw IPAddressFormatException("Invalid IPv6 address '", ip,
-                                   "': address too short");
+    throw IPAddressFormatException(
+        to<std::string>("Invalid IPv6 address '", ip, "': address too short"));
   }
   if (ip.front() == '[' && ip.back() == ']') {
     ip = ip.substr(1, ip.size() - 2);
   }
 
-  if (inet_pton(AF_INET6, ip.c_str(), &addr_.in6Addr_) != 1) {
-    throw IPAddressFormatException("Invalid IPv6 address '", ip, "'");
+  struct addrinfo* result;
+  struct addrinfo hints;
+  memset(&hints, 0, sizeof(hints));
+  hints.ai_family = AF_INET6;
+  hints.ai_socktype = SOCK_STREAM;
+  hints.ai_flags = AI_NUMERICHOST;
+  if (!getaddrinfo(ip.c_str(), nullptr, &hints, &result)) {
+    struct sockaddr_in6* ipAddr = (struct sockaddr_in6*)result->ai_addr;
+    addr_.in6Addr_ = ipAddr->sin6_addr;
+    scope_ = ipAddr->sin6_scope_id;
+    freeaddrinfo(result);
+  } else {
+    throw IPAddressFormatException(
+        to<std::string>("Invalid IPv6 address '", ip, "'"));
   }
 }
 
@@ -76,6 +103,13 @@ IPAddressV6::IPAddressV6(const in6_addr& src)
 {
 }
 
+// sockaddr_in6 constructor
+IPAddressV6::IPAddressV6(const sockaddr_in6& src)
+  : addr_(src.sin6_addr)
+  , scope_(src.sin6_scope_id)
+{
+}
+
 // ByteArray16 constructor
 IPAddressV6::IPAddressV6(const ByteArray16& src)
   : addr_(src)
@@ -104,10 +138,13 @@ IPAddressV6::AddressStorage::AddressStorage(MacAddress mac) {
 
 void IPAddressV6::setFromBinary(ByteRange bytes) {
   if (bytes.size() != 16) {
-    throw IPAddressFormatException("Invalid IPv6 binary data: length must "
-                                   "be 16 bytes, got ", bytes.size());
+    throw IPAddressFormatException(to<std::string>(
+        "Invalid IPv6 binary data: length must ",
+        "be 16 bytes, got ",
+        bytes.size()));
   }
   memcpy(&addr_.in6Addr_.s6_addr, bytes.data(), sizeof(in6_addr));
+  scope_ = 0;
 }
 
 // public
@@ -129,7 +166,7 @@ static inline uint16_t unpack(uint8_t lobyte, uint8_t hibyte) {
 static inline void unpackInto(const unsigned char* src,
                               uint16_t* dest,
                               size_t count) {
-  for (int i = 0, hi = 1, lo = 0; i < count; i++) {
+  for (size_t i = 0, hi = 1, lo = 0; i < count; i++) {
     dest[i] = unpack(src[hi], src[lo]);
     hi += 2;
     lo += 2;
@@ -219,8 +256,8 @@ bool IPAddressV6::inSubnet(StringPiece cidrNetwork) const {
   auto subnetInfo = IPAddress::createNetwork(cidrNetwork);
   auto addr = subnetInfo.first;
   if (!addr.isV6()) {
-    throw IPAddressFormatException("Address '", addr.toJson(), "' ",
-                                   "is not a V6 address");
+    throw IPAddressFormatException(to<std::string>(
+        "Address '", addr.toJson(), "' ", "is not a V6 address"));
   }
   return inSubnetWithMask(addr.asV6(), fetchMask(subnetInfo.second));
 }
@@ -236,13 +273,12 @@ bool IPAddressV6::inSubnetWithMask(const IPAddressV6& subnet,
 
 // public
 bool IPAddressV6::isLoopback() const {
-  const unsigned char* by = bytes();
-  for (int i = 0; i < 15; i++) {
-    if (by[i] != 0x00) {
-      return false;
-    }
+  // Check if v4 mapped is loopback
+  if (isIPv4Mapped() && createIPv4().isLoopback()) {
+    return true;
   }
-  return (by[15] == 0x01);
+  auto socka = toSockAddr();
+  return IN6_IS_ADDR_LOOPBACK(&socka.sin6_addr);
 }
 
 bool IPAddressV6::isRoutable() const {
@@ -261,9 +297,14 @@ bool IPAddressV6::isLinkLocalBroadcast() const {
 
 // public
 bool IPAddressV6::isPrivate() const {
+  // Check if mapped is private
+  if (isIPv4Mapped() && createIPv4().isPrivate()) {
+    return true;
+  }
   return isLoopback() || inBinarySubnet({{0xfc, 0x00}}, 7);
 }
 
+// public
 bool IPAddressV6::isLinkLocal() const {
   return inBinarySubnet({{0xfe, 0x80}}, 10);
 }
@@ -299,8 +340,8 @@ IPAddressV6 IPAddressV6::getSolicitedNodeAddress() const {
 IPAddressV6 IPAddressV6::mask(size_t numBits) const {
   static const auto bits = bitCount();
   if (numBits > bits) {
-    throw IPAddressFormatException("numBits(", numBits, ") > bitCount(",
-                                   bits, ")");
+    throw IPAddressFormatException(
+        to<std::string>("numBits(", numBits, ") > bitCount(", bits, ")"));
   }
   ByteArray16 ba = detail::Bytes::mask(fetchMask(numBits), addr_.bytes_);
   return IPAddressV6(ba);
@@ -309,12 +350,20 @@ IPAddressV6 IPAddressV6::mask(size_t numBits) const {
 // public
 string IPAddressV6::str() const {
   char buffer[INET6_ADDRSTRLEN] = {0};
-  if (!inet_ntop(AF_INET6, &addr_.in6Addr_, buffer, INET6_ADDRSTRLEN)) {
-    throw IPAddressFormatException("Invalid address with hex ",
-                                   "'", detail::Bytes::toHex(bytes(), 16), "'");
+  sockaddr_in6 sock = toSockAddr();
+  if (!getnameinfo(
+        (sockaddr*)&sock, sizeof(sock),
+        buffer, INET6_ADDRSTRLEN,
+        nullptr, 0, NI_NUMERICHOST)) {
+    string ip(buffer);
+    return ip;
+  } else {
+    throw IPAddressFormatException(to<std::string>(
+        "Invalid address with hex ",
+        "'",
+        detail::Bytes::toHex(bytes(), 16),
+        "'"));
   }
-  string ip(buffer);
-  return std::move(ip);
 }
 
 // public
@@ -343,11 +392,20 @@ const ByteArray16 IPAddressV6::fetchMask(size_t numBits) {
   return masks_[numBits];
 }
 
+// public static
+CIDRNetworkV6 IPAddressV6::longestCommonPrefix(
+    const CIDRNetworkV6& one,
+    const CIDRNetworkV6& two) {
+  auto prefix = detail::Bytes::longestCommonPrefix(
+      one.first.addr_.bytes_, one.second, two.first.addr_.bytes_, two.second);
+  return {IPAddressV6(prefix.first), prefix.second};
+}
+
 // protected
 bool IPAddressV6::inBinarySubnet(const std::array<uint8_t, 2> addr,
                                  size_t numBits) const {
-  const unsigned char* subbytes = mask(numBits).bytes();
-  return (std::memcmp(addr.data(), subbytes, 2) == 0);
+  auto masked = mask(numBits);
+  return (std::memcmp(addr.data(), masked.bytes(), 2) == 0);
 }
 
 // static private