Commit 0b856bd5 authored by Yedidya Feldblum's avatar Yedidya Feldblum Committed by Facebook Github Bot

Apply clang-format to folly/**/*Address*.*

Summary: [Folly] Apply `clang-format` to `folly/**/*Address*.*`.

Reviewed By: Orvid

Differential Revision: D5581523

fbshipit-source-id: 97b5270e43e279e7deb9606524d5fee844a50649
parent d44f36ab
...@@ -69,9 +69,10 @@ IPAddressV6 IPAddress::createIPv6(const IPAddress& addr) { ...@@ -69,9 +69,10 @@ IPAddressV6 IPAddress::createIPv6(const IPAddress& addr) {
} }
// public static // public static
CIDRNetwork IPAddress::createNetwork(StringPiece ipSlashCidr, CIDRNetwork IPAddress::createNetwork(
int defaultCidr, /* = -1 */ StringPiece ipSlashCidr,
bool applyMask /* = true */) { int defaultCidr, /* = -1 */
bool applyMask /* = true */) {
if (defaultCidr > std::numeric_limits<uint8_t>::max()) { if (defaultCidr > std::numeric_limits<uint8_t>::max()) {
throw std::range_error("defaultCidr must be <= UINT8_MAX"); throw std::range_error("defaultCidr must be <= UINT8_MAX");
} }
...@@ -133,18 +134,11 @@ IPAddress IPAddress::fromLongHBO(uint32_t src) { ...@@ -133,18 +134,11 @@ IPAddress IPAddress::fromLongHBO(uint32_t src) {
} }
// default constructor // default constructor
IPAddress::IPAddress() IPAddress::IPAddress() : addr_(), family_(AF_UNSPEC) {}
: addr_()
, family_(AF_UNSPEC)
{
}
// public string constructor // public string constructor
IPAddress::IPAddress(StringPiece addr) IPAddress::IPAddress(StringPiece addr) : addr_(), family_(AF_UNSPEC) {
: addr_() string ip = addr.str(); // inet_pton() needs NUL-terminated string
, family_(AF_UNSPEC)
{
string ip = addr.str(); // inet_pton() needs NUL-terminated string
auto throwFormatException = [&](const string& msg) { auto throwFormatException = [&](const string& msg) {
throw IPAddressFormatException(sformat("Invalid IP '{}': {}", ip, msg)); throw IPAddressFormatException(sformat("Invalid IP '{}': {}", ip, msg));
}; };
...@@ -186,22 +180,19 @@ IPAddress::IPAddress(StringPiece addr) ...@@ -186,22 +180,19 @@ IPAddress::IPAddress(StringPiece addr)
} }
// public sockaddr constructor // public sockaddr constructor
IPAddress::IPAddress(const sockaddr* addr) IPAddress::IPAddress(const sockaddr* addr) : addr_(), family_(AF_UNSPEC) {
: addr_()
, family_(AF_UNSPEC)
{
if (addr == nullptr) { if (addr == nullptr) {
throw IPAddressFormatException("sockaddr == nullptr"); throw IPAddressFormatException("sockaddr == nullptr");
} }
family_ = addr->sa_family; family_ = addr->sa_family;
switch (addr->sa_family) { switch (addr->sa_family) {
case AF_INET: { case AF_INET: {
const sockaddr_in *v4addr = reinterpret_cast<const sockaddr_in*>(addr); const sockaddr_in* v4addr = reinterpret_cast<const sockaddr_in*>(addr);
addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr); addr_.ipV4Addr = IPAddressV4(v4addr->sin_addr);
break; break;
} }
case AF_INET6: { case AF_INET6: {
const sockaddr_in6 *v6addr = reinterpret_cast<const sockaddr_in6*>(addr); const sockaddr_in6* v6addr = reinterpret_cast<const sockaddr_in6*>(addr);
addr_.ipV6Addr = IPAddressV6(*v6addr); addr_.ipV6Addr = IPAddressV6(*v6addr);
break; break;
} }
...@@ -212,31 +203,19 @@ IPAddress::IPAddress(const sockaddr* addr) ...@@ -212,31 +203,19 @@ IPAddress::IPAddress(const sockaddr* addr)
// public ipv4 constructor // public ipv4 constructor
IPAddress::IPAddress(const IPAddressV4 ipV4Addr) IPAddress::IPAddress(const IPAddressV4 ipV4Addr)
: addr_(ipV4Addr) : addr_(ipV4Addr), family_(AF_INET) {}
, family_(AF_INET)
{
}
// public ipv4 constructor // public ipv4 constructor
IPAddress::IPAddress(const in_addr ipV4Addr) IPAddress::IPAddress(const in_addr ipV4Addr)
: addr_(IPAddressV4(ipV4Addr)) : addr_(IPAddressV4(ipV4Addr)), family_(AF_INET) {}
, family_(AF_INET)
{
}
// public ipv6 constructor // public ipv6 constructor
IPAddress::IPAddress(const IPAddressV6& ipV6Addr) IPAddress::IPAddress(const IPAddressV6& ipV6Addr)
: addr_(ipV6Addr) : addr_(ipV6Addr), family_(AF_INET6) {}
, family_(AF_INET6)
{
}
// public ipv6 constructor // public ipv6 constructor
IPAddress::IPAddress(const in6_addr& ipV6Addr) IPAddress::IPAddress(const in6_addr& ipV6Addr)
: addr_(IPAddressV6(ipV6Addr)) : addr_(IPAddressV6(ipV6Addr)), family_(AF_INET6) {}
, family_(AF_INET6)
{
}
// Assign from V4 address // Assign from V4 address
IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) { IPAddress& IPAddress::operator=(const IPAddressV4& ipv4_addr) {
...@@ -286,8 +265,8 @@ bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const { ...@@ -286,8 +265,8 @@ bool IPAddress::inSubnet(const IPAddress& subnet, uint8_t cidr) const {
} }
// public // public
bool IPAddress::inSubnetWithMask(const IPAddress& subnet, bool IPAddress::inSubnetWithMask(const IPAddress& subnet, ByteRange mask)
ByteRange mask) const { const {
auto mkByteArray4 = [&]() -> ByteArray4 { auto mkByteArray4 = [&]() -> ByteArray4 {
ByteArray4 ba{{0}}; ByteArray4 ba{{0}};
std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4)); std::memcpy(ba.data(), mask.begin(), std::min<size_t>(mask.size(), 4));
...@@ -392,8 +371,9 @@ bool operator<(const IPAddress& addr1, const IPAddress& addr2) { ...@@ -392,8 +371,9 @@ bool operator<(const IPAddress& addr1, const IPAddress& addr2) {
return false; return false;
} }
CIDRNetwork CIDRNetwork IPAddress::longestCommonPrefix(
IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) { const CIDRNetwork& one,
const CIDRNetwork& two) {
if (one.first.family() != two.first.family()) { if (one.first.family() != two.first.family()) {
throw std::invalid_argument(sformat( throw std::invalid_argument(sformat(
"Can't compute longest common prefix between addresses of different" "Can't compute longest common prefix between addresses of different"
...@@ -403,13 +383,11 @@ IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) { ...@@ -403,13 +383,11 @@ IPAddress::longestCommonPrefix(const CIDRNetwork& one, const CIDRNetwork& two) {
} }
if (one.first.isV4()) { if (one.first.isV4()) {
auto prefix = IPAddressV4::longestCommonPrefix( auto prefix = IPAddressV4::longestCommonPrefix(
{one.first.asV4(), one.second}, {one.first.asV4(), one.second}, {two.first.asV4(), two.second});
{two.first.asV4(), two.second});
return {IPAddress(prefix.first), prefix.second}; return {IPAddress(prefix.first), prefix.second};
} else if (one.first.isV6()) { } else if (one.first.isV6()) {
auto prefix = IPAddressV6::longestCommonPrefix( auto prefix = IPAddressV6::longestCommonPrefix(
{one.first.asV6(), one.second}, {one.first.asV6(), one.second}, {two.first.asV6(), two.second});
{two.first.asV6(), two.second});
return {IPAddress(prefix.first), prefix.second}; return {IPAddress(prefix.first), prefix.second};
} else { } else {
throw std::invalid_argument("Unknown address family"); throw std::invalid_argument("Unknown address family");
......
...@@ -95,7 +95,9 @@ class IPAddress { ...@@ -95,7 +95,9 @@ class IPAddress {
* @return pair with IPAddress network and uint8_t mask * @return pair with IPAddress network and uint8_t mask
*/ */
static CIDRNetwork createNetwork( static CIDRNetwork createNetwork(
StringPiece ipSlashCidr, int defaultCidr = -1, bool mask = true); StringPiece ipSlashCidr,
int defaultCidr = -1,
bool mask = true);
/** /**
* Return a string representation of a CIDR block created with createNetwork. * Return a string representation of a CIDR block created with createNetwork.
...@@ -122,8 +124,9 @@ class IPAddress { ...@@ -122,8 +124,9 @@ class IPAddress {
// Given 2 IPAddress,mask pairs extract the longest common IPAddress, // Given 2 IPAddress,mask pairs extract the longest common IPAddress,
// mask pair // mask pair
static CIDRNetwork longestCommonPrefix(const CIDRNetwork& one, static CIDRNetwork longestCommonPrefix(
const CIDRNetwork& two); const CIDRNetwork& one,
const CIDRNetwork& two);
/** /**
* Constructs an uninitialized IPAddress. * Constructs an uninitialized IPAddress.
...@@ -188,10 +191,12 @@ class IPAddress { ...@@ -188,10 +191,12 @@ class IPAddress {
} }
// Return sa_family_t of IPAddress // Return sa_family_t of IPAddress
sa_family_t family() const { return family_; } sa_family_t family() const {
return family_;
}
// Populate sockaddr_storage with an appropriate value // Populate sockaddr_storage with an appropriate value
int toSockaddrStorage(sockaddr_storage *dest, uint16_t port = 0) const { int toSockaddrStorage(sockaddr_storage* dest, uint16_t port = 0) const {
if (dest == nullptr) { if (dest == nullptr) {
throw IPAddressFormatException("dest must not be null"); throw IPAddressFormatException("dest must not be null");
} }
...@@ -199,7 +204,7 @@ class IPAddress { ...@@ -199,7 +204,7 @@ class IPAddress {
dest->ss_family = family(); dest->ss_family = family();
if (isV4()) { if (isV4()) {
sockaddr_in *sin = reinterpret_cast<sockaddr_in*>(dest); sockaddr_in* sin = reinterpret_cast<sockaddr_in*>(dest);
sin->sin_addr = asV4().toAddr(); sin->sin_addr = asV4().toAddr();
sin->sin_port = port; sin->sin_port = port;
#if defined(__APPLE__) #if defined(__APPLE__)
...@@ -207,7 +212,7 @@ class IPAddress { ...@@ -207,7 +212,7 @@ class IPAddress {
#endif #endif
return sizeof(*sin); return sizeof(*sin);
} else if (isV6()) { } else if (isV6()) {
sockaddr_in6 *sin = reinterpret_cast<sockaddr_in6*>(dest); sockaddr_in6* sin = reinterpret_cast<sockaddr_in6*>(dest);
sin->sin6_addr = asV6().toAddr(); sin->sin6_addr = asV6().toAddr();
sin->sin6_port = port; sin->sin6_port = port;
sin->sin6_scope_id = asV6().getScopeId(); sin->sin6_scope_id = asV6().getScopeId();
...@@ -260,16 +265,24 @@ class IPAddress { ...@@ -260,16 +265,24 @@ class IPAddress {
} }
// @return true if address is uninitialized // @return true if address is uninitialized
bool empty() const { return (family_ == AF_UNSPEC); } bool empty() const {
return (family_ == AF_UNSPEC);
}
// @return true if address is initialized // @return true if address is initialized
explicit operator bool() const { return !empty(); } explicit operator bool() const {
return !empty();
}
// @return true if this is an IPAddressV4 instance // @return true if this is an IPAddressV4 instance
bool isV4() const { return (family_ == AF_INET); } bool isV4() const {
return (family_ == AF_INET);
}
// @return true if this is an IPAddressV6 instance // @return true if this is an IPAddressV6 instance
bool isV6() const { return (family_ == AF_INET6); } bool isV6() const {
return (family_ == AF_INET6);
}
// @return true if this address is all zeros // @return true if this address is all zeros
bool isZero() const { bool isZero() const {
...@@ -284,17 +297,17 @@ class IPAddress { ...@@ -284,17 +297,17 @@ class IPAddress {
size_t byteCount() const { size_t byteCount() const {
return bitCount() / 8; return bitCount() / 8;
} }
//get nth most significant bit - 0 indexed // get nth most significant bit - 0 indexed
bool getNthMSBit(size_t bitIndex) const { bool getNthMSBit(size_t bitIndex) const {
return detail::getNthMSBitImpl(*this, bitIndex, family()); return detail::getNthMSBitImpl(*this, bitIndex, family());
} }
//get nth most significant byte - 0 indexed // get nth most significant byte - 0 indexed
uint8_t getNthMSByte(size_t byteIndex) const; uint8_t getNthMSByte(size_t byteIndex) const;
//get nth bit - 0 indexed // get nth bit - 0 indexed
bool getNthLSBit(size_t bitIndex) const { bool getNthLSBit(size_t bitIndex) const {
return getNthMSBit(bitCount() - bitIndex - 1); return getNthMSBit(bitCount() - bitIndex - 1);
} }
//get nth byte - 0 indexed // get nth byte - 0 indexed
uint8_t getNthLSByte(size_t byteIndex) const { uint8_t getNthLSByte(size_t byteIndex) const {
return getNthMSByte(byteCount() - byteIndex - 1); return getNthMSByte(byteCount() - byteIndex - 1);
} }
...@@ -408,8 +421,8 @@ class IPAddress { ...@@ -408,8 +421,8 @@ class IPAddress {
IPAddressV46() { IPAddressV46() {
std::memset(this, 0, sizeof(IPAddressV46)); std::memset(this, 0, sizeof(IPAddressV46));
} }
explicit IPAddressV46(const IPAddressV4& addr): ipV4Addr(addr) {} explicit IPAddressV46(const IPAddressV4& addr) : ipV4Addr(addr) {}
explicit IPAddressV46(const IPAddressV6& addr): ipV6Addr(addr) {} explicit IPAddressV46(const IPAddressV6& addr) : ipV6Addr(addr) {}
} IPAddressV46; } IPAddressV46;
IPAddressV46 addr_; IPAddressV46 addr_;
sa_family_t family_; sa_family_t family_;
......
...@@ -29,7 +29,6 @@ using std::string; ...@@ -29,7 +29,6 @@ using std::string;
namespace folly { namespace folly {
// free functions // free functions
size_t hash_value(const IPAddressV4& addr) { size_t hash_value(const IPAddressV4& addr) {
return addr.hash(); return addr.hash();
...@@ -85,19 +84,13 @@ uint32_t IPAddressV4::toLongHBO(StringPiece ip) { ...@@ -85,19 +84,13 @@ uint32_t IPAddressV4::toLongHBO(StringPiece ip) {
} }
// public default constructor // public default constructor
IPAddressV4::IPAddressV4() { IPAddressV4::IPAddressV4() {}
}
// ByteArray4 constructor // ByteArray4 constructor
IPAddressV4::IPAddressV4(const ByteArray4& src) IPAddressV4::IPAddressV4(const ByteArray4& src) : addr_(src) {}
: addr_(src)
{
}
// public string constructor // public string constructor
IPAddressV4::IPAddressV4(StringPiece addr) IPAddressV4::IPAddressV4(StringPiece addr) : addr_() {
: addr_()
{
auto ip = addr.str(); auto ip = addr.str();
if (inet_pton(AF_INET, ip.c_str(), &addr_.inAddr_) != 1) { if (inet_pton(AF_INET, ip.c_str(), &addr_.inAddr_) != 1) {
throw IPAddressFormatException(sformat("Invalid IPv4 address '{}'", addr)); throw IPAddressFormatException(sformat("Invalid IPv4 address '{}'", addr));
...@@ -105,10 +98,7 @@ IPAddressV4::IPAddressV4(StringPiece addr) ...@@ -105,10 +98,7 @@ IPAddressV4::IPAddressV4(StringPiece addr)
} }
// in_addr constructor // in_addr constructor
IPAddressV4::IPAddressV4(const in_addr src) IPAddressV4::IPAddressV4(const in_addr src) : addr_(src) {}
: addr_(src)
{
}
// public // public
void IPAddressV4::setFromBinary(ByteRange bytes) { void IPAddressV4::setFromBinary(ByteRange bytes) {
...@@ -172,11 +162,11 @@ bool IPAddressV4::inSubnet(StringPiece cidrNetwork) const { ...@@ -172,11 +162,11 @@ bool IPAddressV4::inSubnet(StringPiece cidrNetwork) const {
} }
// public // public
bool IPAddressV4::inSubnetWithMask(const IPAddressV4& subnet, bool IPAddressV4::inSubnetWithMask(
const ByteArray4 cidrMask) const { const IPAddressV4& subnet,
const ByteArray4 mask = detail::Bytes::mask(toByteArray(), cidrMask); const ByteArray4 cidrMask) const {
const ByteArray4 subMask = detail::Bytes::mask(subnet.toByteArray(), const auto mask = detail::Bytes::mask(toByteArray(), cidrMask);
cidrMask); const auto subMask = detail::Bytes::mask(subnet.toByteArray(), cidrMask);
return (mask == subMask); return (mask == subMask);
} }
...@@ -196,24 +186,26 @@ bool IPAddressV4::isLinkLocal() const { ...@@ -196,24 +186,26 @@ bool IPAddressV4::isLinkLocal() const {
bool IPAddressV4::isNonroutable() const { bool IPAddressV4::isNonroutable() const {
auto ip = toLongHBO(); auto ip = toLongHBO();
return isPrivate() || return isPrivate() ||
(ip <= 0x00FFFFFF) || // 0.0.0.0-0.255.255.255 (/* align */ true && ip <= 0x00FFFFFF) || // 0.0.0.0-0.255.255.255
(ip >= 0xC0000000 && ip <= 0xC00000FF) || // 192.0.0.0-192.0.0.255 (ip >= 0xC0000000 && ip <= 0xC00000FF) || // 192.0.0.0-192.0.0.255
(ip >= 0xC0000200 && ip <= 0xC00002FF) || // 192.0.2.0-192.0.2.255 (ip >= 0xC0000200 && ip <= 0xC00002FF) || // 192.0.2.0-192.0.2.255
(ip >= 0xC6120000 && ip <= 0xC613FFFF) || // 198.18.0.0-198.19.255.255 (ip >= 0xC6120000 && ip <= 0xC613FFFF) || // 198.18.0.0-198.19.255.255
(ip >= 0xC6336400 && ip <= 0xC63364FF) || // 198.51.100.0-198.51.100.255 (ip >= 0xC6336400 && ip <= 0xC63364FF) || // 198.51.100.0-198.51.100.255
(ip >= 0xCB007100 && ip <= 0xCB0071FF) || // 203.0.113.0-203.0.113.255 (ip >= 0xCB007100 && ip <= 0xCB0071FF) || // 203.0.113.0-203.0.113.255
(ip >= 0xE0000000 && ip <= 0xFFFFFFFF); // 224.0.0.0-255.255.255.255 (ip >= 0xE0000000 && ip <= 0xFFFFFFFF) || // 224.0.0.0-255.255.255.255
false;
} }
// public // public
bool IPAddressV4::isPrivate() const { bool IPAddressV4::isPrivate() const {
auto ip = toLongHBO(); auto ip = toLongHBO();
return return // some ranges below
(ip >= 0x0A000000 && ip <= 0x0AFFFFFF) || // 10.0.0.0-10.255.255.255 (ip >= 0x0A000000 && ip <= 0x0AFFFFFF) || // 10.0.0.0-10.255.255.255
(ip >= 0x7F000000 && ip <= 0x7FFFFFFF) || // 127.0.0.0-127.255.255.255 (ip >= 0x7F000000 && ip <= 0x7FFFFFFF) || // 127.0.0.0-127.255.255.255
(ip >= 0xA9FE0000 && ip <= 0xA9FEFFFF) || // 169.254.0.0-169.254.255.255 (ip >= 0xA9FE0000 && ip <= 0xA9FEFFFF) || // 169.254.0.0-169.254.255.255
(ip >= 0xAC100000 && ip <= 0xAC1FFFFF) || // 172.16.0.0-172.31.255.255 (ip >= 0xAC100000 && ip <= 0xAC1FFFFF) || // 172.16.0.0-172.31.255.255
(ip >= 0xC0A80000 && ip <= 0xC0A8FFFF); // 192.168.0.0-192.168.255.255 (ip >= 0xC0A80000 && ip <= 0xC0A8FFFF) || // 192.168.0.0-192.168.255.255
false;
} }
// public // public
......
...@@ -80,7 +80,7 @@ class IPAddressV4 { ...@@ -80,7 +80,7 @@ class IPAddressV4 {
* Returns the address as a Range. * Returns the address as a Range.
*/ */
ByteRange toBinary() const { ByteRange toBinary() const {
return ByteRange((const unsigned char *) &addr_.inAddr_.s_addr, 4); return ByteRange((const unsigned char*)&addr_.inAddr_.s_addr, 4);
} }
/** /**
...@@ -140,7 +140,9 @@ class IPAddressV4 { ...@@ -140,7 +140,9 @@ class IPAddressV4 {
* @see IPAddress#bitCount * @see IPAddress#bitCount
* @returns 32 * @returns 32
*/ */
static size_t bitCount() { return 32; } static size_t bitCount() {
return 32;
}
/** /**
* @See IPAddress#toJson * @See IPAddress#toJson
...@@ -197,7 +199,9 @@ class IPAddressV4 { ...@@ -197,7 +199,9 @@ class IPAddressV4 {
std::string toInverseArpaName() const; std::string toInverseArpaName() const;
// return underlying in_addr structure // return underlying in_addr structure
in_addr toAddr() const { return addr_.inAddr_; } in_addr toAddr() const {
return addr_.inAddr_;
}
sockaddr_in toSockAddr() const { sockaddr_in toSockAddr() const {
sockaddr_in addr; sockaddr_in addr;
...@@ -214,13 +218,17 @@ class IPAddressV4 { ...@@ -214,13 +218,17 @@ class IPAddressV4 {
} }
// @see IPAddress#toFullyQualified // @see IPAddress#toFullyQualified
std::string toFullyQualified() const { return str(); } std::string toFullyQualified() const {
return str();
}
// @see IPAddress#toFullyQualifiedAppend // @see IPAddress#toFullyQualifiedAppend
void toFullyQualifiedAppend(std::string& out) const; void toFullyQualifiedAppend(std::string& out) const;
// @see IPAddress#version // @see IPAddress#version
uint8_t version() const { return 4; } uint8_t version() const {
return 4;
}
/** /**
* Return the mask associated with the given number of bits. * Return the mask associated with the given number of bits.
...@@ -238,35 +246,40 @@ class IPAddressV4 { ...@@ -238,35 +246,40 @@ class IPAddressV4 {
const CIDRNetworkV4& one, const CIDRNetworkV4& one,
const CIDRNetworkV4& two); const CIDRNetworkV4& two);
// Number of bytes in the address representation. // Number of bytes in the address representation.
static size_t byteCount() { return 4; } static size_t byteCount() {
//get nth most significant bit - 0 indexed return 4;
}
// get nth most significant bit - 0 indexed
bool getNthMSBit(size_t bitIndex) const { bool getNthMSBit(size_t bitIndex) const {
return detail::getNthMSBitImpl(*this, bitIndex, AF_INET); return detail::getNthMSBitImpl(*this, bitIndex, AF_INET);
} }
//get nth most significant byte - 0 indexed // get nth most significant byte - 0 indexed
uint8_t getNthMSByte(size_t byteIndex) const; uint8_t getNthMSByte(size_t byteIndex) const;
//get nth bit - 0 indexed // get nth bit - 0 indexed
bool getNthLSBit(size_t bitIndex) const { bool getNthLSBit(size_t bitIndex) const {
return getNthMSBit(bitCount() - bitIndex - 1); return getNthMSBit(bitCount() - bitIndex - 1);
} }
//get nth byte - 0 indexed // get nth byte - 0 indexed
uint8_t getNthLSByte(size_t byteIndex) const { uint8_t getNthLSByte(size_t byteIndex) const {
return getNthMSByte(byteCount() - byteIndex - 1); return getNthMSByte(byteCount() - byteIndex - 1);
} }
const unsigned char* bytes() const { return addr_.bytes_.data(); } const unsigned char* bytes() const {
return addr_.bytes_.data();
}
private: private:
union AddressStorage { union AddressStorage {
static_assert(sizeof(in_addr) == sizeof(ByteArray4), static_assert(
"size of in_addr and ByteArray4 are different"); sizeof(in_addr) == sizeof(ByteArray4),
"size of in_addr and ByteArray4 are different");
in_addr inAddr_; in_addr inAddr_;
ByteArray4 bytes_; ByteArray4 bytes_;
AddressStorage() { AddressStorage() {
std::memset(this, 0, sizeof(AddressStorage)); std::memset(this, 0, sizeof(AddressStorage));
} }
explicit AddressStorage(const ByteArray4 bytes): bytes_(bytes) {} explicit AddressStorage(const ByteArray4 bytes) : bytes_(bytes) {}
explicit AddressStorage(const in_addr addr): inAddr_(addr) {} explicit AddressStorage(const in_addr addr) : inAddr_(addr) {}
} addr_; } addr_;
/** /**
......
...@@ -77,8 +77,7 @@ bool IPAddressV6::validate(StringPiece ip) { ...@@ -77,8 +77,7 @@ bool IPAddressV6::validate(StringPiece ip) {
} }
// public default constructor // public default constructor
IPAddressV6::IPAddressV6() { IPAddressV6::IPAddressV6() {}
}
// public string constructor // public string constructor
IPAddressV6::IPAddressV6(StringPiece addr) { IPAddressV6::IPAddressV6(StringPiece addr) {
...@@ -110,28 +109,17 @@ IPAddressV6::IPAddressV6(StringPiece addr) { ...@@ -110,28 +109,17 @@ IPAddressV6::IPAddressV6(StringPiece addr) {
} }
// in6_addr constructor // in6_addr constructor
IPAddressV6::IPAddressV6(const in6_addr& src) IPAddressV6::IPAddressV6(const in6_addr& src) : addr_(src) {}
: addr_(src)
{
}
// sockaddr_in6 constructor // sockaddr_in6 constructor
IPAddressV6::IPAddressV6(const sockaddr_in6& src) IPAddressV6::IPAddressV6(const sockaddr_in6& src)
: addr_(src.sin6_addr) : addr_(src.sin6_addr), scope_(uint16_t(src.sin6_scope_id)) {}
, scope_(uint16_t(src.sin6_scope_id))
{
}
// ByteArray16 constructor // ByteArray16 constructor
IPAddressV6::IPAddressV6(const ByteArray16& src) IPAddressV6::IPAddressV6(const ByteArray16& src) : addr_(src) {}
: addr_(src)
{
}
// link-local constructor // link-local constructor
IPAddressV6::IPAddressV6(LinkLocalTag, MacAddress mac) IPAddressV6::IPAddressV6(LinkLocalTag, MacAddress mac) : addr_(mac) {}
: addr_(mac) {
}
IPAddressV6::AddressStorage::AddressStorage(MacAddress mac) { IPAddressV6::AddressStorage::AddressStorage(MacAddress mac) {
// The link-local address uses modified EUI-64 format, // The link-local address uses modified EUI-64 format,
...@@ -228,9 +216,8 @@ static inline uint16_t unpack(uint8_t lobyte, uint8_t hibyte) { ...@@ -228,9 +216,8 @@ static inline uint16_t unpack(uint8_t lobyte, uint8_t hibyte) {
// given a src string, unpack count*2 bytes into dest // given a src string, unpack count*2 bytes into dest
// dest must have as much storage as count // dest must have as much storage as count
static inline void unpackInto(const unsigned char* src, static inline void
uint16_t* dest, unpackInto(const unsigned char* src, uint16_t* dest, size_t count) {
size_t count) {
for (size_t 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]); dest[i] = unpack(src[hi], src[lo]);
hi += 2; hi += 2;
...@@ -245,7 +232,7 @@ IPAddressV4 IPAddressV6::getIPv4For6To4() const { ...@@ -245,7 +232,7 @@ IPAddressV4 IPAddressV6::getIPv4For6To4() const {
sformat("Invalid IP '{}': not a 6to4 address", str())); sformat("Invalid IP '{}': not a 6to4 address", str()));
} }
// convert 16x8 bytes into first 4x16 bytes // convert 16x8 bytes into first 4x16 bytes
uint16_t ints[4] = {0,0,0,0}; uint16_t ints[4] = {0, 0, 0, 0};
unpackInto(bytes(), ints, 4); unpackInto(bytes(), ints, 4);
// repack into 4x8 // repack into 4x8
union { union {
...@@ -281,7 +268,7 @@ bool IPAddressV6::isIPv4Mapped() const { ...@@ -281,7 +268,7 @@ bool IPAddressV6::isIPv4Mapped() const {
// public // public
IPAddressV6::Type IPAddressV6::type() const { IPAddressV6::Type IPAddressV6::type() const {
// convert 16x8 bytes into first 2x16 bytes // convert 16x8 bytes into first 2x16 bytes
uint16_t ints[2] = {0,0}; uint16_t ints[2] = {0, 0};
unpackInto(bytes(), ints, 2); unpackInto(bytes(), ints, 2);
if ((((uint32_t)ints[0] << 16) | ints[1]) == IPAddressV6::PREFIX_TEREDO) { if ((((uint32_t)ints[0] << 16) | ints[1]) == IPAddressV6::PREFIX_TEREDO) {
...@@ -327,11 +314,11 @@ bool IPAddressV6::inSubnet(StringPiece cidrNetwork) const { ...@@ -327,11 +314,11 @@ bool IPAddressV6::inSubnet(StringPiece cidrNetwork) const {
} }
// public // public
bool IPAddressV6::inSubnetWithMask(const IPAddressV6& subnet, bool IPAddressV6::inSubnetWithMask(
const ByteArray16& cidrMask) const { const IPAddressV6& subnet,
const ByteArray16 mask = detail::Bytes::mask(toByteArray(), cidrMask); const ByteArray16& cidrMask) const {
const ByteArray16 subMask = detail::Bytes::mask(subnet.toByteArray(), const auto mask = detail::Bytes::mask(toByteArray(), cidrMask);
cidrMask); const auto subMask = detail::Bytes::mask(subnet.toByteArray(), cidrMask);
return (mask == subMask); return (mask == subMask);
} }
...@@ -347,11 +334,11 @@ bool IPAddressV6::isLoopback() const { ...@@ -347,11 +334,11 @@ bool IPAddressV6::isLoopback() const {
bool IPAddressV6::isRoutable() const { bool IPAddressV6::isRoutable() const {
return return
// 2000::/3 is the only assigned global unicast block // 2000::/3 is the only assigned global unicast block
inBinarySubnet({{0x20, 0x00}}, 3) || inBinarySubnet({{0x20, 0x00}}, 3) ||
// ffxe::/16 are global scope multicast addresses, // ffxe::/16 are global scope multicast addresses,
// which are eligible to be routed over the internet // which are eligible to be routed over the internet
(isMulticast() && getMulticastScope() == 0xe); (isMulticast() && getMulticastScope() == 0xe);
} }
bool IPAddressV6::isLinkLocalBroadcast() const { bool IPAddressV6::isLinkLocalBroadcast() const {
...@@ -392,11 +379,24 @@ IPAddressV6 IPAddressV6::getSolicitedNodeAddress() const { ...@@ -392,11 +379,24 @@ IPAddressV6 IPAddressV6::getSolicitedNodeAddress() const {
// addresses // addresses
DCHECK(!isMulticast()); DCHECK(!isMulticast());
uint8_t bytes[16] = { 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, uint8_t bytes[16] = {
0x00, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00, 0x00 }; 0xff,
bytes[13] = addr_.bytes_[13]; 0x02,
bytes[14] = addr_.bytes_[14]; 0x00,
bytes[15] = addr_.bytes_[15]; 0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x01,
0xff,
addr_.bytes_[13],
addr_.bytes_[14],
addr_.bytes_[15],
};
return IPAddressV6::fromBinary(ByteRange(bytes, 16)); return IPAddressV6::fromBinary(ByteRange(bytes, 16));
} }
...@@ -504,8 +504,9 @@ CIDRNetworkV6 IPAddressV6::longestCommonPrefix( ...@@ -504,8 +504,9 @@ CIDRNetworkV6 IPAddressV6::longestCommonPrefix(
} }
// protected // protected
bool IPAddressV6::inBinarySubnet(const std::array<uint8_t, 2> addr, bool IPAddressV6::inBinarySubnet(
size_t numBits) const { const std::array<uint8_t, 2> addr,
size_t numBits) const {
auto masked = mask(numBits); auto masked = mask(numBits);
return (std::memcmp(addr.data(), masked.bytes(), 2) == 0); return (std::memcmp(addr.data(), masked.bytes(), 2) == 0);
} }
......
...@@ -69,7 +69,9 @@ class IPAddressV6 { ...@@ -69,7 +69,9 @@ class IPAddressV6 {
public: public:
// V6 Address Type // V6 Address Type
enum Type { enum Type {
TEREDO, T6TO4, NORMAL, TEREDO,
T6TO4,
NORMAL,
}; };
// A constructor parameter to indicate that we should create a link-local // A constructor parameter to indicate that we should create a link-local
// IPAddressV6. // IPAddressV6.
...@@ -86,7 +88,7 @@ class IPAddressV6 { ...@@ -86,7 +88,7 @@ class IPAddressV6 {
// Size of std::string returned by toFullyQualified. // Size of std::string returned by toFullyQualified.
static constexpr size_t kToFullyQualifiedSize = static constexpr size_t kToFullyQualifiedSize =
8 /*words*/ * 4 /*hex chars per word*/ + 7 /*separators*/; 8 /*words*/ * 4 /*hex chars per word*/ + 7 /*separators*/;
// returns true iff the input string can be parsed as an ipv6-address // returns true iff the input string can be parsed as an ipv6-address
static bool validate(StringPiece ip); static bool validate(StringPiece ip);
...@@ -112,7 +114,7 @@ class IPAddressV6 { ...@@ -112,7 +114,7 @@ class IPAddressV6 {
* Returns the address as a Range. * Returns the address as a Range.
*/ */
ByteRange toBinary() const { ByteRange toBinary() const {
return ByteRange((const unsigned char *) &addr_.in6Addr_.s6_addr, 16); return ByteRange((const unsigned char*)&addr_.in6Addr_.s6_addr, 16);
} }
/** /**
...@@ -171,7 +173,9 @@ class IPAddressV6 { ...@@ -171,7 +173,9 @@ class IPAddressV6 {
* @see IPAddress#bitCount * @see IPAddress#bitCount
* @returns 128 * @returns 128
*/ */
static size_t bitCount() { return 128; } static size_t bitCount() {
return 128;
}
/** /**
* @see IPAddress#toJson * @see IPAddress#toJson
...@@ -188,8 +192,8 @@ class IPAddressV6 { ...@@ -188,8 +192,8 @@ class IPAddressV6 {
bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const { bool inSubnet(const IPAddressV6& subnet, uint8_t cidr) const {
return inSubnetWithMask(subnet, fetchMask(cidr)); return inSubnetWithMask(subnet, fetchMask(cidr));
} }
bool inSubnetWithMask(const IPAddressV6& subnet, bool inSubnetWithMask(const IPAddressV6& subnet, const ByteArray16& mask)
const ByteArray16& mask) const; const;
// @see IPAddress#isLoopback // @see IPAddress#isLoopback
bool isLoopback() const; bool isLoopback() const;
...@@ -256,9 +260,13 @@ class IPAddressV6 { ...@@ -256,9 +260,13 @@ class IPAddressV6 {
IPAddressV6 mask(size_t numBits) const; IPAddressV6 mask(size_t numBits) const;
// return underlying in6_addr structure // return underlying in6_addr structure
in6_addr toAddr() const { return addr_.in6Addr_; } in6_addr toAddr() const {
return addr_.in6Addr_;
}
uint16_t getScopeId() const { return scope_; } uint16_t getScopeId() const {
return scope_;
}
void setScopeId(uint16_t scope) { void setScopeId(uint16_t scope) {
scope_ = scope; scope_ = scope;
} }
...@@ -290,7 +298,9 @@ class IPAddressV6 { ...@@ -290,7 +298,9 @@ class IPAddressV6 {
std::string str() const; std::string str() const;
// @see IPAddress#version // @see IPAddress#version
uint8_t version() const { return 6; } uint8_t version() const {
return 6;
}
/** /**
* Return the solicited-node multicast address for this address. * Return the solicited-node multicast address for this address.
...@@ -312,32 +322,35 @@ class IPAddressV6 { ...@@ -312,32 +322,35 @@ class IPAddressV6 {
const CIDRNetworkV6& one, const CIDRNetworkV6& one,
const CIDRNetworkV6& two); const CIDRNetworkV6& two);
// Number of bytes in the address representation. // Number of bytes in the address representation.
static constexpr size_t byteCount() { return 16; } static constexpr size_t byteCount() {
return 16;
}
//get nth most significant bit - 0 indexed // get nth most significant bit - 0 indexed
bool getNthMSBit(size_t bitIndex) const { bool getNthMSBit(size_t bitIndex) const {
return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6); return detail::getNthMSBitImpl(*this, bitIndex, AF_INET6);
} }
//get nth most significant byte - 0 indexed // get nth most significant byte - 0 indexed
uint8_t getNthMSByte(size_t byteIndex) const; uint8_t getNthMSByte(size_t byteIndex) const;
//get nth bit - 0 indexed // get nth bit - 0 indexed
bool getNthLSBit(size_t bitIndex) const { bool getNthLSBit(size_t bitIndex) const {
return getNthMSBit(bitCount() - bitIndex - 1); return getNthMSBit(bitCount() - bitIndex - 1);
} }
//get nth byte - 0 indexed // get nth byte - 0 indexed
uint8_t getNthLSByte(size_t byteIndex) const { uint8_t getNthLSByte(size_t byteIndex) const {
return getNthMSByte(byteCount() - byteIndex - 1); return getNthMSByte(byteCount() - byteIndex - 1);
} }
const unsigned char* bytes() const { return addr_.in6Addr_.s6_addr; } const unsigned char* bytes() const {
return addr_.in6Addr_.s6_addr;
}
protected: protected:
/** /**
* Helper that returns true if the address is in the binary subnet specified * Helper that returns true if the address is in the binary subnet specified
* by addr. * by addr.
*/ */
bool inBinarySubnet(const std::array<uint8_t, 2> addr, bool inBinarySubnet(const std::array<uint8_t, 2> addr, size_t numBits) const;
size_t numBits) const;
private: private:
auto tie() const { auto tie() const {
...@@ -371,8 +384,8 @@ class IPAddressV6 { ...@@ -371,8 +384,8 @@ class IPAddressV6 {
AddressStorage() { AddressStorage() {
std::memset(this, 0, sizeof(AddressStorage)); std::memset(this, 0, sizeof(AddressStorage));
} }
explicit AddressStorage(const ByteArray16& bytes): bytes_(bytes) {} explicit AddressStorage(const ByteArray16& bytes) : bytes_(bytes) {}
explicit AddressStorage(const in6_addr& addr): in6Addr_(addr) {} explicit AddressStorage(const in6_addr& addr) : in6Addr_(addr) {}
explicit AddressStorage(MacAddress mac); explicit AddressStorage(MacAddress mac);
} addr_; } addr_;
......
...@@ -73,9 +73,7 @@ string MacAddress::toString() const { ...@@ -73,9 +73,7 @@ string MacAddress::toString() const {
void MacAddress::parse(StringPiece str) { void MacAddress::parse(StringPiece str) {
// Helper function to convert a single hex char into an integer // Helper function to convert a single hex char into an integer
auto isSeparatorChar = [](char c) { auto isSeparatorChar = [](char c) { return c == ':' || c == '-'; };
return c == ':' || c == '-';
};
uint8_t parsed[SIZE]; uint8_t parsed[SIZE];
auto p = str.begin(); auto p = str.begin();
......
...@@ -222,8 +222,9 @@ class MacAddress { ...@@ -222,8 +222,9 @@ class MacAddress {
/* Define toAppend() so to<string> will work */ /* Define toAppend() so to<string> will work */
template <class Tgt> template <class Tgt>
typename std::enable_if<IsSomeString<Tgt>::value>::type typename std::enable_if<IsSomeString<Tgt>::value>::type toAppend(
toAppend(MacAddress address, Tgt* result) { MacAddress address,
Tgt* result) {
toAppend(address.toString(), result); toAppend(address.toString(), result);
} }
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
*/ */
#ifndef __STDC_FORMAT_MACROS #ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS
#endif #endif
#include <folly/SocketAddress.h> #include <folly/SocketAddress.h>
...@@ -61,18 +61,15 @@ struct ScopedAddrInfo { ...@@ -61,18 +61,15 @@ struct ScopedAddrInfo {
*/ */
struct HostAndPort { struct HostAndPort {
HostAndPort(const char* str, bool hostRequired) HostAndPort(const char* str, bool hostRequired)
: host(nullptr), : host(nullptr), port(nullptr), allocated(nullptr) {
port(nullptr),
allocated(nullptr) {
// Look for the last colon // Look for the last colon
const char* colon = strrchr(str, ':'); const char* colon = strrchr(str, ':');
if (colon == nullptr) { if (colon == nullptr) {
// No colon, just a port number. // No colon, just a port number.
if (hostRequired) { if (hostRequired) {
throw std::invalid_argument( throw std::invalid_argument(
"expected a host and port string of the " "expected a host and port string of the "
"form \"<host>:<port>\""); "form \"<host>:<port>\"");
} }
port = str; port = str;
return; return;
...@@ -85,7 +82,7 @@ struct HostAndPort { ...@@ -85,7 +82,7 @@ struct HostAndPort {
throw std::bad_alloc(); throw std::bad_alloc();
} }
char *allocatedColon = allocated + (colon - str); char* allocatedColon = allocated + (colon - str);
*allocatedColon = '\0'; *allocatedColon = '\0';
host = allocated; host = allocated;
port = allocatedColon + 1; port = allocatedColon + 1;
...@@ -115,7 +112,7 @@ bool SocketAddress::isPrivateAddress() const { ...@@ -115,7 +112,7 @@ bool SocketAddress::isPrivateAddress() const {
auto family = getFamily(); auto family = getFamily();
if (family == AF_INET || family == AF_INET6) { if (family == AF_INET || family == AF_INET6) {
return storage_.addr.isPrivate() || return storage_.addr.isPrivate() ||
(storage_.addr.isV6() && storage_.addr.asV6().isLinkLocal()); (storage_.addr.isV6() && storage_.addr.asV6().isLinkLocal());
} else if (external_) { } else if (external_) {
// Unix addresses are always local to a host. Return true, // Unix addresses are always local to a host. Return true,
// since this conforms to the semantics of returning true for IP loopback // since this conforms to the semantics of returning true for IP loopback
...@@ -167,8 +164,8 @@ void SocketAddress::setFromLocalPort(const char* port) { ...@@ -167,8 +164,8 @@ void SocketAddress::setFromLocalPort(const char* port) {
void SocketAddress::setFromLocalIpPort(const char* addressAndPort) { void SocketAddress::setFromLocalIpPort(const char* addressAndPort) {
HostAndPort hp(addressAndPort, false); HostAndPort hp(addressAndPort, false);
ScopedAddrInfo results(getAddrInfo(hp.host, hp.port, ScopedAddrInfo results(
AI_NUMERICHOST | AI_ADDRCONFIG)); getAddrInfo(hp.host, hp.port, AI_NUMERICHOST | AI_ADDRCONFIG));
setFromLocalAddr(results.info); setFromLocalAddr(results.info);
} }
...@@ -263,49 +260,50 @@ void SocketAddress::setFromSockaddr(const struct sockaddr* address) { ...@@ -263,49 +260,50 @@ void SocketAddress::setFromSockaddr(const struct sockaddr* address) {
// to be able to distinguish anonymous addresses from addresses // to be able to distinguish anonymous addresses from addresses
// in Linux's abstract namespace. // in Linux's abstract namespace.
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress::setFromSockaddr(): the address " "SocketAddress::setFromSockaddr(): the address "
"length must be explicitly specified when " "length must be explicitly specified when "
"setting AF_UNIX addresses"); "setting AF_UNIX addresses");
} else { } else {
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress::setFromSockaddr() called " "SocketAddress::setFromSockaddr() called "
"with unsupported address type"); "with unsupported address type");
} }
setFromIpAddrPort(folly::IPAddress(address), port); setFromIpAddrPort(folly::IPAddress(address), port);
} }
void SocketAddress::setFromSockaddr(const struct sockaddr* address, void SocketAddress::setFromSockaddr(
socklen_t addrlen) { const struct sockaddr* address,
socklen_t addrlen) {
// Check the length to make sure we can access address->sa_family // Check the length to make sure we can access address->sa_family
if (addrlen < (offsetof(struct sockaddr, sa_family) + if (addrlen <
sizeof(address->sa_family))) { (offsetof(struct sockaddr, sa_family) + sizeof(address->sa_family))) {
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress::setFromSockaddr() called " "SocketAddress::setFromSockaddr() called "
"with length too short for a sockaddr"); "with length too short for a sockaddr");
} }
if (address->sa_family == AF_INET) { if (address->sa_family == AF_INET) {
if (addrlen < sizeof(struct sockaddr_in)) { if (addrlen < sizeof(struct sockaddr_in)) {
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress::setFromSockaddr() called " "SocketAddress::setFromSockaddr() called "
"with length too short for a sockaddr_in"); "with length too short for a sockaddr_in");
} }
setFromSockaddr(reinterpret_cast<const struct sockaddr_in*>(address)); setFromSockaddr(reinterpret_cast<const struct sockaddr_in*>(address));
} else if (address->sa_family == AF_INET6) { } else if (address->sa_family == AF_INET6) {
if (addrlen < sizeof(struct sockaddr_in6)) { if (addrlen < sizeof(struct sockaddr_in6)) {
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress::setFromSockaddr() called " "SocketAddress::setFromSockaddr() called "
"with length too short for a sockaddr_in6"); "with length too short for a sockaddr_in6");
} }
setFromSockaddr(reinterpret_cast<const struct sockaddr_in6*>(address)); setFromSockaddr(reinterpret_cast<const struct sockaddr_in6*>(address));
} else if (address->sa_family == AF_UNIX) { } else if (address->sa_family == AF_UNIX) {
setFromSockaddr(reinterpret_cast<const struct sockaddr_un*>(address), setFromSockaddr(
addrlen); reinterpret_cast<const struct sockaddr_un*>(address), addrlen);
} else { } else {
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress::setFromSockaddr() called " "SocketAddress::setFromSockaddr() called "
"with unsupported address type"); "with unsupported address type");
} }
} }
...@@ -319,13 +317,14 @@ void SocketAddress::setFromSockaddr(const struct sockaddr_in6* address) { ...@@ -319,13 +317,14 @@ void SocketAddress::setFromSockaddr(const struct sockaddr_in6* address) {
setFromSockaddr((sockaddr*)address); setFromSockaddr((sockaddr*)address);
} }
void SocketAddress::setFromSockaddr(const struct sockaddr_un* address, void SocketAddress::setFromSockaddr(
socklen_t addrlen) { const struct sockaddr_un* address,
socklen_t addrlen) {
assert(address->sun_family == AF_UNIX); assert(address->sun_family == AF_UNIX);
if (addrlen > sizeof(struct sockaddr_un)) { if (addrlen > sizeof(struct sockaddr_un)) {
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress::setFromSockaddr() called " "SocketAddress::setFromSockaddr() called "
"with length too long for a sockaddr_un"); "with length too long for a sockaddr_un");
} }
if (!external_) { if (!external_) {
...@@ -337,7 +336,7 @@ void SocketAddress::setFromSockaddr(const struct sockaddr_un* address, ...@@ -337,7 +336,7 @@ void SocketAddress::setFromSockaddr(const struct sockaddr_un* address,
// Fill the rest with 0s, just for safety // Fill the rest with 0s, just for safety
if (addrlen < sizeof(struct sockaddr_un)) { if (addrlen < sizeof(struct sockaddr_un)) {
char *p = reinterpret_cast<char*>(storage_.un.addr); char* p = reinterpret_cast<char*>(storage_.un.addr);
memset(p + addrlen, 0, sizeof(struct sockaddr_un) - addrlen); memset(p + addrlen, 0, sizeof(struct sockaddr_un) - addrlen);
} }
} }
...@@ -362,8 +361,8 @@ socklen_t SocketAddress::getActualSize() const { ...@@ -362,8 +361,8 @@ socklen_t SocketAddress::getActualSize() const {
return sizeof(struct sockaddr_in6); return sizeof(struct sockaddr_in6);
default: default:
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress::getActualSize() called " "SocketAddress::getActualSize() called "
"with unrecognized address family"); "with unrecognized address family");
} }
} }
...@@ -400,8 +399,8 @@ uint16_t SocketAddress::getPort() const { ...@@ -400,8 +399,8 @@ uint16_t SocketAddress::getPort() const {
return port_; return port_;
default: default:
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress::getPort() called on non-IP " "SocketAddress::getPort() called on non-IP "
"address"); "address");
} }
} }
...@@ -413,16 +412,16 @@ void SocketAddress::setPort(uint16_t port) { ...@@ -413,16 +412,16 @@ void SocketAddress::setPort(uint16_t port) {
return; return;
default: default:
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress::setPort() called on non-IP " "SocketAddress::setPort() called on non-IP "
"address"); "address");
} }
} }
void SocketAddress::convertToIPv4() { void SocketAddress::convertToIPv4() {
if (!tryConvertToIPv4()) { if (!tryConvertToIPv4()) {
throw std::invalid_argument( throw std::invalid_argument(
"convertToIPv4() called on an addresse that is " "convertToIPv4() called on an addresse that is "
"not an IPv4-mapped address"); "not an IPv4-mapped address");
} }
} }
...@@ -451,8 +450,8 @@ std::string SocketAddress::getHostStr() const { ...@@ -451,8 +450,8 @@ std::string SocketAddress::getHostStr() const {
std::string SocketAddress::getPath() const { std::string SocketAddress::getPath() const {
if (!external_) { if (!external_) {
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress: attempting to get path " "SocketAddress: attempting to get path "
"for a non-Unix address"); "for a non-Unix address");
} }
if (storage_.un.pathLength() == 0) { if (storage_.un.pathLength() == 0) {
...@@ -488,16 +487,14 @@ std::string SocketAddress::describe() const { ...@@ -488,16 +487,14 @@ std::string SocketAddress::describe() const {
switch (getFamily()) { switch (getFamily()) {
case AF_UNSPEC: case AF_UNSPEC:
return "<uninitialized address>"; return "<uninitialized address>";
case AF_INET: case AF_INET: {
{
char buf[NI_MAXHOST + 16]; char buf[NI_MAXHOST + 16];
getAddressStr(buf, sizeof(buf)); getAddressStr(buf, sizeof(buf));
size_t iplen = strlen(buf); size_t iplen = strlen(buf);
snprintf(buf + iplen, sizeof(buf) - iplen, ":%" PRIu16, getPort()); snprintf(buf + iplen, sizeof(buf) - iplen, ":%" PRIu16, getPort());
return buf; return buf;
} }
case AF_INET6: case AF_INET6: {
{
char buf[NI_MAXHOST + 18]; char buf[NI_MAXHOST + 18];
buf[0] = '['; buf[0] = '[';
getAddressStr(buf + 1, sizeof(buf) - 1); getAddressStr(buf + 1, sizeof(buf) - 1);
...@@ -505,11 +502,9 @@ std::string SocketAddress::describe() const { ...@@ -505,11 +502,9 @@ std::string SocketAddress::describe() const {
snprintf(buf + iplen, sizeof(buf) - iplen, "]:%" PRIu16, getPort()); snprintf(buf + iplen, sizeof(buf) - iplen, "]:%" PRIu16, getPort());
return buf; return buf;
} }
default: default: {
{
char buf[64]; char buf[64];
snprintf(buf, sizeof(buf), "<unknown address family %d>", snprintf(buf, sizeof(buf), "<unknown address family %d>", getFamily());
getFamily());
return buf; return buf;
} }
} }
...@@ -521,8 +516,7 @@ bool SocketAddress::operator==(const SocketAddress& other) const { ...@@ -521,8 +516,7 @@ bool SocketAddress::operator==(const SocketAddress& other) const {
} }
if (external_) { if (external_) {
// anonymous addresses are never equal to any other addresses // anonymous addresses are never equal to any other addresses
if (storage_.un.pathLength() == 0 || if (storage_.un.pathLength() == 0 || other.storage_.un.pathLength() == 0) {
other.storage_.un.pathLength() == 0) {
return false; return false;
} }
...@@ -539,16 +533,16 @@ bool SocketAddress::operator==(const SocketAddress& other) const { ...@@ -539,16 +533,16 @@ bool SocketAddress::operator==(const SocketAddress& other) const {
switch (getFamily()) { switch (getFamily()) {
case AF_INET: case AF_INET:
case AF_INET6: case AF_INET6:
return (other.storage_.addr == storage_.addr) && return (other.storage_.addr == storage_.addr) && (other.port_ == port_);
(other.port_ == port_);
default: default:
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress: unsupported address family " "SocketAddress: unsupported address family "
"for comparison"); "for comparison");
} }
} }
bool SocketAddress::prefixMatch(const SocketAddress& other, bool SocketAddress::prefixMatch(
const SocketAddress& other,
unsigned prefixLength) const { unsigned prefixLength) const {
if (other.getFamily() != getFamily()) { if (other.getFamily() != getFamily()) {
return false; return false;
...@@ -558,11 +552,9 @@ bool SocketAddress::prefixMatch(const SocketAddress& other, ...@@ -558,11 +552,9 @@ bool SocketAddress::prefixMatch(const SocketAddress& other,
case AF_INET: case AF_INET:
mask_length = 32; mask_length = 32;
FOLLY_FALLTHROUGH; FOLLY_FALLTHROUGH;
case AF_INET6: case AF_INET6: {
{
auto prefix = folly::IPAddress::longestCommonPrefix( auto prefix = folly::IPAddress::longestCommonPrefix(
{storage_.addr, mask_length}, {storage_.addr, mask_length}, {other.storage_.addr, mask_length});
{other.storage_.addr, mask_length});
return prefix.second >= prefixLength; return prefix.second >= prefixLength;
} }
default: default:
...@@ -570,13 +562,12 @@ bool SocketAddress::prefixMatch(const SocketAddress& other, ...@@ -570,13 +562,12 @@ bool SocketAddress::prefixMatch(const SocketAddress& other,
} }
} }
size_t SocketAddress::hash() const { size_t SocketAddress::hash() const {
size_t seed = folly::hash::twang_mix64(getFamily()); size_t seed = folly::hash::twang_mix64(getFamily());
if (external_) { if (external_) {
enum { kUnixPathMax = sizeof(storage_.un.addr->sun_path) }; enum { kUnixPathMax = sizeof(storage_.un.addr->sun_path) };
const char *path = storage_.un.addr->sun_path; const char* path = storage_.un.addr->sun_path;
auto pathLength = storage_.un.pathLength(); auto pathLength = storage_.un.pathLength();
// TODO: this probably could be made more efficient // TODO: this probably could be made more efficient
for (off_t n = 0; n < pathLength; ++n) { for (off_t n = 0; n < pathLength; ++n) {
...@@ -597,16 +588,15 @@ size_t SocketAddress::hash() const { ...@@ -597,16 +588,15 @@ size_t SocketAddress::hash() const {
case AF_UNSPEC: case AF_UNSPEC:
default: default:
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress: unsupported address family " "SocketAddress: unsupported address family "
"for hashing"); "for hashing");
} }
return seed; return seed;
} }
struct addrinfo* SocketAddress::getAddrInfo(const char* host, struct addrinfo*
uint16_t port, SocketAddress::getAddrInfo(const char* host, uint16_t port, int flags) {
int flags) {
// getaddrinfo() requires the port number as a string // getaddrinfo() requires the port number as a string
char portString[sizeof("65535")]; char portString[sizeof("65535")];
snprintf(portString, sizeof(portString), "%" PRIu16, port); snprintf(portString, sizeof(portString), "%" PRIu16, port);
...@@ -614,16 +604,15 @@ struct addrinfo* SocketAddress::getAddrInfo(const char* host, ...@@ -614,16 +604,15 @@ struct addrinfo* SocketAddress::getAddrInfo(const char* host,
return getAddrInfo(host, portString, flags); return getAddrInfo(host, portString, flags);
} }
struct addrinfo* SocketAddress::getAddrInfo(const char* host, struct addrinfo*
const char* port, SocketAddress::getAddrInfo(const char* host, const char* port, int flags) {
int flags) {
struct addrinfo hints; struct addrinfo hints;
memset(&hints, 0, sizeof(hints)); memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM; hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | flags; hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV | flags;
struct addrinfo *results; struct addrinfo* results;
int error = getaddrinfo(host, port, &hints, &results); int error = getaddrinfo(host, port, &hints, &results);
if (error != 0) { if (error != 0) {
auto os = folly::sformat( auto os = folly::sformat(
...@@ -674,19 +663,24 @@ std::string SocketAddress::getIpString(int flags) const { ...@@ -674,19 +663,24 @@ std::string SocketAddress::getIpString(int flags) const {
return std::string(addrString); return std::string(addrString);
} }
void SocketAddress::getIpString(char *buf, size_t buflen, int flags) const { void SocketAddress::getIpString(char* buf, size_t buflen, int flags) const {
auto family = getFamily(); auto family = getFamily();
if (family != AF_INET && if (family != AF_INET && family != AF_INET6) {
family != AF_INET6) {
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress: attempting to get IP address " "SocketAddress: attempting to get IP address "
"for a non-IP address"); "for a non-IP address");
} }
sockaddr_storage tmp_sock; sockaddr_storage tmp_sock;
storage_.addr.toSockaddrStorage(&tmp_sock, port_); storage_.addr.toSockaddrStorage(&tmp_sock, port_);
int rc = getnameinfo((sockaddr*)&tmp_sock, sizeof(sockaddr_storage), int rc = getnameinfo(
buf, buflen, nullptr, 0, flags); (sockaddr*)&tmp_sock,
sizeof(sockaddr_storage),
buf,
buflen,
nullptr,
0,
flags);
if (rc != 0) { if (rc != 0) {
auto os = sformat( auto os = sformat(
"getnameinfo() failed in getIpString() error = {}", gai_strerror(rc)); "getnameinfo() failed in getIpString() error = {}", gai_strerror(rc));
...@@ -697,8 +691,8 @@ void SocketAddress::getIpString(char *buf, size_t buflen, int flags) const { ...@@ -697,8 +691,8 @@ void SocketAddress::getIpString(char *buf, size_t buflen, int flags) const {
void SocketAddress::updateUnixAddressLength(socklen_t addrlen) { void SocketAddress::updateUnixAddressLength(socklen_t addrlen) {
if (addrlen < offsetof(struct sockaddr_un, sun_path)) { if (addrlen < offsetof(struct sockaddr_un, sun_path)) {
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress: attempted to set a Unix socket " "SocketAddress: attempted to set a Unix socket "
"with a length too short for a sockaddr_un"); "with a length too short for a sockaddr_un");
} }
storage_.un.len = addrlen; storage_.un.len = addrlen;
...@@ -755,13 +749,12 @@ bool SocketAddress::operator<(const SocketAddress& other) const { ...@@ -755,13 +749,12 @@ bool SocketAddress::operator<(const SocketAddress& other) const {
return port_ < other.port_; return port_ < other.port_;
} }
return return storage_.addr < other.storage_.addr;
storage_.addr < other.storage_.addr;
} }
case AF_UNSPEC: case AF_UNSPEC:
default: default:
throw std::invalid_argument( throw std::invalid_argument(
"SocketAddress: unsupported address family for comparing"); "SocketAddress: unsupported address family for comparing");
} }
} }
......
...@@ -47,8 +47,7 @@ class SocketAddress { ...@@ -47,8 +47,7 @@ class SocketAddress {
* This is potentially a very slow operation, so is disabled by * This is potentially a very slow operation, so is disabled by
* default. * default.
*/ */
SocketAddress(const char* host, uint16_t port, SocketAddress(const char* host, uint16_t port, bool allowNameLookup = false) {
bool allowNameLookup = false) {
// Initialize the address family first, // Initialize the address family first,
// since setFromHostPort() and setFromIpPort() will check it. // since setFromHostPort() and setFromIpPort() will check it.
...@@ -59,8 +58,10 @@ class SocketAddress { ...@@ -59,8 +58,10 @@ class SocketAddress {
} }
} }
SocketAddress(const std::string& host, uint16_t port, SocketAddress(
bool allowNameLookup = false) { const std::string& host,
uint16_t port,
bool allowNameLookup = false) {
// Initialize the address family first, // Initialize the address family first,
// since setFromHostPort() and setFromIpPort() will check it. // since setFromHostPort() and setFromIpPort() will check it.
...@@ -342,8 +343,7 @@ class SocketAddress { ...@@ -342,8 +343,7 @@ class SocketAddress {
* enough for the full address type required by * enough for the full address type required by
* address->sa_family. * address->sa_family.
*/ */
void setFromSockaddr(const struct sockaddr* address, void setFromSockaddr(const struct sockaddr* address, socklen_t addrlen);
socklen_t addrlen);
/** /**
* Initialize this SocketAddress from a struct sockaddr_in. * Initialize this SocketAddress from a struct sockaddr_in.
...@@ -367,9 +367,7 @@ class SocketAddress { ...@@ -367,9 +367,7 @@ class SocketAddress {
* the valid bytes of sun_path, not including any NUL * the valid bytes of sun_path, not including any NUL
* terminator. * terminator.
*/ */
void setFromSockaddr(const struct sockaddr_un* address, void setFromSockaddr(const struct sockaddr_un* address, socklen_t addrlen);
socklen_t addrlen);
/** /**
* Fill in a given sockaddr_storage with the ip or unix address. * Fill in a given sockaddr_storage with the ip or unix address.
...@@ -445,8 +443,7 @@ class SocketAddress { ...@@ -445,8 +443,7 @@ class SocketAddress {
* Return true if this is an IPv4-mapped IPv6 address. * Return true if this is an IPv4-mapped IPv6 address.
*/ */
bool isIPv4Mapped() const { bool isIPv4Mapped() const {
return (getFamily() == AF_INET6 && return (getFamily() == AF_INET6 && storage_.addr.isIPv4Mapped());
storage_.addr.isIPv4Mapped());
} }
/** /**
...@@ -540,7 +537,7 @@ class SocketAddress { ...@@ -540,7 +537,7 @@ class SocketAddress {
* the heap. * the heap.
*/ */
struct ExternalUnixAddr { struct ExternalUnixAddr {
struct sockaddr_un *addr; struct sockaddr_un* addr;
socklen_t len; socklen_t len;
socklen_t pathLength() const { socklen_t pathLength() const {
...@@ -552,12 +549,12 @@ class SocketAddress { ...@@ -552,12 +549,12 @@ class SocketAddress {
addr->sun_family = AF_UNIX; addr->sun_family = AF_UNIX;
len = 0; len = 0;
} }
void init(const ExternalUnixAddr &other) { void init(const ExternalUnixAddr& other) {
addr = new struct sockaddr_un; addr = new struct sockaddr_un;
len = other.len; len = other.len;
memcpy(addr, other.addr, size_t(len)); memcpy(addr, other.addr, size_t(len));
} }
void copy(const ExternalUnixAddr &other) { void copy(const ExternalUnixAddr& other) {
len = other.len; len = other.len;
memcpy(addr, other.addr, size_t(len)); memcpy(addr, other.addr, size_t(len));
} }
...@@ -572,7 +569,7 @@ class SocketAddress { ...@@ -572,7 +569,7 @@ class SocketAddress {
void setFromLocalAddr(const struct addrinfo* results); void setFromLocalAddr(const struct addrinfo* results);
void setFromSocket(int socket, int (*fn)(int, struct sockaddr*, socklen_t*)); void setFromSocket(int socket, int (*fn)(int, struct sockaddr*, socklen_t*));
std::string getIpString(int flags) const; std::string getIpString(int flags) const;
void getIpString(char *buf, size_t buflen, int flags) const; void getIpString(char* buf, size_t buflen, int flags) const;
void updateUnixAddressLength(socklen_t addrlen); void updateUnixAddressLength(socklen_t addrlen);
...@@ -603,7 +600,6 @@ class SocketAddress { ...@@ -603,7 +600,6 @@ class SocketAddress {
size_t hash_value(const SocketAddress& address); size_t hash_value(const SocketAddress& address);
std::ostream& operator<<(std::ostream& os, const SocketAddress& addr); std::ostream& operator<<(std::ostream& os, const SocketAddress& addr);
} }
namespace std { namespace std {
...@@ -611,10 +607,8 @@ namespace std { ...@@ -611,10 +607,8 @@ namespace std {
// Provide an implementation for std::hash<SocketAddress> // Provide an implementation for std::hash<SocketAddress>
template <> template <>
struct hash<folly::SocketAddress> { struct hash<folly::SocketAddress> {
size_t operator()( size_t operator()(const folly::SocketAddress& addr) const {
const folly::SocketAddress& addr) const {
return addr.hash(); return addr.hash();
} }
}; };
} }
...@@ -18,7 +18,8 @@ ...@@ -18,7 +18,8 @@
#include <folly/Format.h> #include <folly/Format.h>
namespace folly { namespace detail { namespace folly {
namespace detail {
std::string familyNameStrDefault(sa_family_t family) { std::string familyNameStrDefault(sa_family_t family) {
return sformat("sa_family_t({})", family); return sformat("sa_family_t({})", family);
...@@ -30,5 +31,5 @@ std::string familyNameStrDefault(sa_family_t family) { ...@@ -30,5 +31,5 @@ std::string familyNameStrDefault(sa_family_t family) {
bitCount, bitCount,
familyNameStr(family))); familyNameStr(family)));
} }
} // namespace detail
}} } // namespace folly
...@@ -22,7 +22,8 @@ ...@@ -22,7 +22,8 @@
#include <folly/portability/Sockets.h> #include <folly/portability/Sockets.h>
namespace folly { namespace detail { namespace folly {
namespace detail {
std::string familyNameStrDefault(sa_family_t family); std::string familyNameStrDefault(sa_family_t family);
...@@ -49,8 +50,8 @@ getNthMSBitImpl(const IPAddrType& ip, size_t bitIndex, sa_family_t family) { ...@@ -49,8 +50,8 @@ getNthMSBitImpl(const IPAddrType& ip, size_t bitIndex, sa_family_t family) {
if (bitIndex >= ip.bitCount()) { if (bitIndex >= ip.bitCount()) {
getNthMSBitImplThrow(ip.bitCount(), family); getNthMSBitImplThrow(ip.bitCount(), family);
} }
//Underlying bytes are in n/w byte order // Underlying bytes are in n/w byte order
return (ip.getNthMSByte(bitIndex / 8) & (0x80 >> (bitIndex % 8))) != 0; return (ip.getNthMSByte(bitIndex / 8) & (0x80 >> (bitIndex % 8))) != 0;
} }
} // namespace detail
}} // folly::detail } // namespace folly
...@@ -30,11 +30,8 @@ BENCHMARK(ipv4_to_string_inet_ntop, iters) { ...@@ -30,11 +30,8 @@ BENCHMARK(ipv4_to_string_inet_ntop, iters) {
char outputString[INET_ADDRSTRLEN] = {0}; char outputString[INET_ADDRSTRLEN] = {0};
while (iters--) { while (iters--) {
const char* val = inet_ntop( const char* val =
AF_INET, inet_ntop(AF_INET, &ip, outputString, sizeof(outputString));
&ip,
outputString,
sizeof(outputString));
} }
} }
...@@ -78,11 +75,8 @@ BENCHMARK(ipv6_to_string_inet_ntop, iters) { ...@@ -78,11 +75,8 @@ BENCHMARK(ipv6_to_string_inet_ntop, iters) {
bool checkResult = (iters == 1); bool checkResult = (iters == 1);
while (iters--) { while (iters--) {
const char* val = inet_ntop( const char* val =
AF_INET6, inet_ntop(AF_INET6, &ip, outputString, sizeof(outputString));
&ip,
outputString,
sizeof(outputString));
} }
} }
...@@ -135,7 +129,7 @@ BENCHMARK_RELATIVE(ipv6_append_to_fully_qualified_port, iters) { ...@@ -135,7 +129,7 @@ BENCHMARK_RELATIVE(ipv6_append_to_fully_qualified_port, iters) {
// ipv6_append_to_fully_qualified_port 178.73% 84.35ns 11.86M // ipv6_append_to_fully_qualified_port 178.73% 84.35ns 11.86M
// ============================================================================ // ============================================================================
int main(int argc, char *argv[]) { int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true); gflags::ParseCommandLineFlags(&argc, &argv, true);
runBenchmarks(); runBenchmarks();
return 0; return 0;
......
...@@ -244,7 +244,7 @@ TEST(IPAddress, InvalidAddressFamilyExceptions) { ...@@ -244,7 +244,7 @@ TEST(IPAddress, InvalidAddressFamilyExceptions) {
sockaddr_in addr; sockaddr_in addr;
addr.sin_family = AF_UNSPEC; addr.sin_family = AF_UNSPEC;
EXPECT_THROW(IPAddress((sockaddr *)&addr), InvalidAddressFamilyException); EXPECT_THROW(IPAddress((sockaddr*)&addr), InvalidAddressFamilyException);
} }
} }
...@@ -284,14 +284,14 @@ TEST(IPAddress, CreateNetwork) { ...@@ -284,14 +284,14 @@ TEST(IPAddress, CreateNetwork) {
// test empty string // test empty string
EXPECT_THROW(IPAddress::createNetwork(""), IPAddressFormatException); EXPECT_THROW(IPAddress::createNetwork(""), IPAddressFormatException);
// test multi slash string // test multi slash string
EXPECT_THROW(IPAddress::createNetwork("192.168.0.1/24/36"), EXPECT_THROW(
IPAddressFormatException); IPAddress::createNetwork("192.168.0.1/24/36"), IPAddressFormatException);
// test no slash string with default IPv4 // test no slash string with default IPv4
{ {
auto net = IPAddress::createNetwork("192.168.0.1"); auto net = IPAddress::createNetwork("192.168.0.1");
ASSERT_TRUE(net.first.isV4()); ASSERT_TRUE(net.first.isV4());
EXPECT_EQ("192.168.0.1", net.first.str()); EXPECT_EQ("192.168.0.1", net.first.str());
EXPECT_EQ(32, net.second); // auto-detected EXPECT_EQ(32, net.second); // auto-detected
net = IPAddress::createNetwork("192.168.0.1", -1, false); net = IPAddress::createNetwork("192.168.0.1", -1, false);
ASSERT_TRUE(net.first.isV4()); ASSERT_TRUE(net.first.isV4());
EXPECT_EQ("192.168.0.1", net.first.str()); EXPECT_EQ("192.168.0.1", net.first.str());
...@@ -305,9 +305,8 @@ TEST(IPAddress, CreateNetwork) { ...@@ -305,9 +305,8 @@ TEST(IPAddress, CreateNetwork) {
EXPECT_EQ(128, net.second); EXPECT_EQ(128, net.second);
} }
// test no slash string with invalid default // test no slash string with invalid default
EXPECT_THROW(IPAddress::createNetwork("192.168.0.1", 33), EXPECT_THROW(
IPAddressFormatException); IPAddress::createNetwork("192.168.0.1", 33), IPAddressFormatException);
} }
// test assignment operators // test assignment operators
...@@ -450,7 +449,7 @@ TEST(IPAddress, CtorSockaddr) { ...@@ -450,7 +449,7 @@ TEST(IPAddress, CtorSockaddr) {
addr.sin_family = AF_INET; addr.sin_family = AF_INET;
addr.sin_addr = sin_addr; addr.sin_addr = sin_addr;
IPAddress ipAddr((sockaddr *)&addr); IPAddress ipAddr((sockaddr*)&addr);
EXPECT_TRUE(ipAddr.isV4()); EXPECT_TRUE(ipAddr.isV4());
EXPECT_EQ("126.131.128.23", ipAddr.str()); EXPECT_EQ("126.131.128.23", ipAddr.str());
} }
...@@ -460,21 +459,20 @@ TEST(IPAddress, CtorSockaddr) { ...@@ -460,21 +459,20 @@ TEST(IPAddress, CtorSockaddr) {
sockaddr_in6 addr; sockaddr_in6 addr;
memset(&addr, 0, sizeof(addr)); memset(&addr, 0, sizeof(addr));
in6_addr sin_addr; in6_addr sin_addr;
ByteArray16 sec{{ // 2620:0:1cfe:face:b00c::3
// 2620:0:1cfe:face:b00c::3 ByteArray16 sec{
38,32,0,0,28,254,250,206,176,12,0,0,0,0,0,3 {38, 32, 0, 0, 28, 254, 250, 206, 176, 12, 0, 0, 0, 0, 0, 3}};
}};
std::memcpy(sin_addr.s6_addr, sec.data(), 16); std::memcpy(sin_addr.s6_addr, sec.data(), 16);
addr.sin6_family = AF_INET6; addr.sin6_family = AF_INET6;
addr.sin6_addr = sin_addr; addr.sin6_addr = sin_addr;
IPAddress ipAddr((sockaddr *)&addr); IPAddress ipAddr((sockaddr*)&addr);
EXPECT_TRUE(ipAddr.isV6()); EXPECT_TRUE(ipAddr.isV6());
EXPECT_EQ("2620:0:1cfe:face:b00c::3", ipAddr.str()); EXPECT_EQ("2620:0:1cfe:face:b00c::3", ipAddr.str());
} }
// test nullptr exception // test nullptr exception
{ {
sockaddr *addr = nullptr; sockaddr* addr = nullptr;
EXPECT_THROW(IPAddress((const sockaddr*)addr), IPAddressFormatException); EXPECT_THROW(IPAddress((const sockaddr*)addr), IPAddressFormatException);
} }
// test invalid family exception // test invalid family exception
...@@ -486,7 +484,7 @@ TEST(IPAddress, CtorSockaddr) { ...@@ -486,7 +484,7 @@ TEST(IPAddress, CtorSockaddr) {
addr.sin_family = AF_UNSPEC; addr.sin_family = AF_UNSPEC;
addr.sin_addr = sin_addr; addr.sin_addr = sin_addr;
EXPECT_THROW(IPAddress((sockaddr *)&addr), IPAddressFormatException); EXPECT_THROW(IPAddress((sockaddr*)&addr), IPAddressFormatException);
} }
} }
...@@ -519,7 +517,7 @@ TEST(IPAddress, ToSockaddrStorage) { ...@@ -519,7 +517,7 @@ TEST(IPAddress, ToSockaddrStorage) {
} }
// test nullptr exception // test nullptr exception
{ {
sockaddr_storage *out = nullptr; sockaddr_storage* out = nullptr;
IPAddress addr("127.0.0.1"); IPAddress addr("127.0.0.1");
EXPECT_THROW(addr.toSockaddrStorage(out), IPAddressFormatException); EXPECT_THROW(addr.toSockaddrStorage(out), IPAddressFormatException);
} }
...@@ -546,9 +544,16 @@ TEST(IPAddress, ToString) { ...@@ -546,9 +544,16 @@ TEST(IPAddress, ToString) {
EXPECT_EQ("1:2::3", folly::to<string>(addr_1_2_3)); EXPECT_EQ("1:2::3", folly::to<string>(addr_1_2_3));
// Test a combination of all the above arguments // Test a combination of all the above arguments
EXPECT_EQ("1:2::3 - 10.0.0.1 - ::1 - 10.1.2.3", EXPECT_EQ(
folly::to<string>(addr_1_2_3, " - ", addr_10_0_0_1, "1:2::3 - 10.0.0.1 - ::1 - 10.1.2.3",
" - ", addr_1, " - ", addr_10_1_2_3)); folly::to<string>(
addr_1_2_3,
" - ",
addr_10_0_0_1,
" - ",
addr_1,
" - ",
addr_10_1_2_3));
} }
TEST(IPaddress, toInverseArpaName) { TEST(IPaddress, toInverseArpaName) {
...@@ -584,8 +589,9 @@ TEST_P(IPAddressCtorTest, InvalidCreation) { ...@@ -584,8 +589,9 @@ TEST_P(IPAddressCtorTest, InvalidCreation) {
// Test that invalid binary values throw an exception // Test that invalid binary values throw an exception
TEST_P(IPAddressCtorBinaryTest, InvalidBinary) { TEST_P(IPAddressCtorBinaryTest, InvalidBinary) {
auto bin = GetParam(); auto bin = GetParam();
EXPECT_THROW(IPAddress::fromBinary(ByteRange(&bin[0], bin.size())), EXPECT_THROW(
IPAddressFormatException); IPAddress::fromBinary(ByteRange(&bin[0], bin.size())),
IPAddressFormatException);
} }
TEST(IPAddressSource, ToHex) { TEST(IPAddressSource, ToHex) {
...@@ -716,9 +722,9 @@ TEST(IPAddress, InSubnetWith6to4) { ...@@ -716,9 +722,9 @@ TEST(IPAddress, InSubnetWith6to4) {
} }
static const vector<string> ipv4Strs = { static const vector<string> ipv4Strs = {
"127.0.0.1", "127.0.0.1",
"198.168.0.1", "198.168.0.1",
"8.8.0.0", "8.8.0.0",
}; };
TEST(IPAddress, getIPv6For6To4) { TEST(IPAddress, getIPv6For6To4) {
for (auto ipv4Str : ipv4Strs) { for (auto ipv4Str : ipv4Strs) {
...@@ -732,9 +738,9 @@ TEST(IPAddress, getIPv6For6To4) { ...@@ -732,9 +738,9 @@ TEST(IPAddress, getIPv6For6To4) {
} }
} }
static const vector<pair<string, uint8_t> > invalidMasks = { static const vector<pair<string, uint8_t>> invalidMasks = {
{"127.0.0.1", 33}, {"127.0.0.1", 33},
{"::1", 129}, {"::1", 129},
}; };
TEST(IPAddress, InvalidMask) { TEST(IPAddress, InvalidMask) {
for (auto& tc : invalidMasks) { for (auto& tc : invalidMasks) {
...@@ -743,11 +749,11 @@ TEST(IPAddress, InvalidMask) { ...@@ -743,11 +749,11 @@ TEST(IPAddress, InvalidMask) {
} }
} }
static const vector<pair<string, IPAddressV6::Type> > v6types = { static const vector<pair<string, IPAddressV6::Type>> v6types = {
{"::1", IPAddressV6::Type::NORMAL}, {"::1", IPAddressV6::Type::NORMAL},
{"2620:0:1cfe:face:b00c::3", IPAddressV6::Type::NORMAL}, {"2620:0:1cfe:face:b00c::3", IPAddressV6::Type::NORMAL},
{"2001:0000:4136:e378:8000:63bf:3fff:fdd2", IPAddressV6::Type::TEREDO}, {"2001:0000:4136:e378:8000:63bf:3fff:fdd2", IPAddressV6::Type::TEREDO},
{"2002:c000:022a::", IPAddressV6::Type::T6TO4}, {"2002:c000:022a::", IPAddressV6::Type::T6TO4},
}; };
TEST(IPAddress, V6Types) { TEST(IPAddress, V6Types) {
auto mkName = [&](const IPAddressV6::Type t) -> string { auto mkName = [&](const IPAddressV6::Type t) -> string {
...@@ -786,11 +792,11 @@ TEST(IPAddress, V6Types) { ...@@ -786,11 +792,11 @@ TEST(IPAddress, V6Types) {
} }
} }
static const vector<pair<string, uint32_t> > provideToLong = { static const vector<pair<string, uint32_t>> provideToLong = {
{"0.0.0.0", 0}, {"0.0.0.0", 0},
{"10.0.0.0", 167772160}, {"10.0.0.0", 167772160},
{"126.131.128.23", 2122547223}, {"126.131.128.23", 2122547223},
{"192.168.0.0", 3232235520}, {"192.168.0.0", 3232235520},
}; };
TEST(IPAddress, ToLong) { TEST(IPAddress, ToLong) {
for (auto& tc : provideToLong) { for (auto& tc : provideToLong) {
...@@ -837,12 +843,12 @@ TEST(IPAddress, fromBinaryV4) { ...@@ -837,12 +843,12 @@ TEST(IPAddress, fromBinaryV4) {
} }
uint8_t data[20]; uint8_t data[20];
EXPECT_THROW(IPAddressV4::fromBinary(ByteRange(data, 3)), EXPECT_THROW(
IPAddressFormatException); IPAddressV4::fromBinary(ByteRange(data, 3)), IPAddressFormatException);
EXPECT_THROW(IPAddressV4::fromBinary(ByteRange(data, 16)), EXPECT_THROW(
IPAddressFormatException); IPAddressV4::fromBinary(ByteRange(data, 16)), IPAddressFormatException);
EXPECT_THROW(IPAddressV4::fromBinary(ByteRange(data, 20)), EXPECT_THROW(
IPAddressFormatException); IPAddressV4::fromBinary(ByteRange(data, 20)), IPAddressFormatException);
} }
TEST(IPAddress, toBinaryV4) { TEST(IPAddress, toBinaryV4) {
...@@ -861,22 +867,44 @@ TEST(IPAddress, toBinaryV4) { ...@@ -861,22 +867,44 @@ TEST(IPAddress, toBinaryV4) {
} }
} }
static const vector<pair<string, vector<uint8_t> > > provideBinary16Bytes = { using ByteArray8 = std::array<uint8_t, 8>;
{"::0",
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, static auto join8 = [](std::array<ByteArray8, 2> parts) {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, ByteArray16 _return;
{"1::2", std::memcpy(_return.data(), parts.data(), _return.size());
{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, return _return;
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}}, };
{"fe80::0012:34ff:fe56:78ab",
{0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, static const vector<pair<string, ByteArray16>> provideBinary16Bytes = {
0x00, 0x12, 0x34, 0xff, 0xfe, 0x56, 0x78, 0xab}}, make_pair(
{"2001:db8:1234:5678:90ab:cdef:8765:4321", "::0",
{0x20, 0x01, 0x0d, 0xb8, 0x12, 0x34, 0x56, 0x78, join8({{
0x90, 0xab, 0xcd, 0xef, 0x87, 0x65, 0x43, 0x21}}, ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{"::ffff:0:c0a8:1", ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }})),
0xff, 0xff, 0x00, 0x00, 0xc0, 0xa8, 0x00, 0x01}}, make_pair(
"1::2",
join8({{
ByteArray8{{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}},
}})),
make_pair(
"fe80::0012:34ff:fe56:78ab",
join8(
{{ByteArray8{{0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
ByteArray8{{0x00, 0x12, 0x34, 0xff, 0xfe, 0x56, 0x78, 0xab}}}})),
make_pair(
"2001:db8:1234:5678:90ab:cdef:8765:4321",
join8({{
ByteArray8{{0x20, 0x01, 0x0d, 0xb8, 0x12, 0x34, 0x56, 0x78}},
ByteArray8{{0x90, 0xab, 0xcd, 0xef, 0x87, 0x65, 0x43, 0x21}},
}})),
make_pair(
"::ffff:0:c0a8:1",
join8({{
ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
ByteArray8{{0xff, 0xff, 0x00, 0x00, 0xc0, 0xa8, 0x00, 0x01}},
}})),
}; };
TEST(IPAddress, fromBinaryV6) { TEST(IPAddress, fromBinaryV6) {
...@@ -899,12 +927,12 @@ TEST(IPAddress, fromBinaryV6) { ...@@ -899,12 +927,12 @@ TEST(IPAddress, fromBinaryV6) {
} }
uint8_t data[20]; uint8_t data[20];
EXPECT_THROW(IPAddressV6::fromBinary(ByteRange(data, 3)), EXPECT_THROW(
IPAddressFormatException); IPAddressV6::fromBinary(ByteRange(data, 3)), IPAddressFormatException);
EXPECT_THROW(IPAddressV6::fromBinary(ByteRange(data, 4)), EXPECT_THROW(
IPAddressFormatException); IPAddressV6::fromBinary(ByteRange(data, 4)), IPAddressFormatException);
EXPECT_THROW(IPAddressV6::fromBinary(ByteRange(data, 20)), EXPECT_THROW(
IPAddressFormatException); IPAddressV6::fromBinary(ByteRange(data, 20)), IPAddressFormatException);
} }
TEST(IPAddress, toBinaryV6) { TEST(IPAddress, toBinaryV6) {
...@@ -973,13 +1001,15 @@ TEST_P(IPAddressFlagTest, IsLinkLocalBroadcast) { ...@@ -973,13 +1001,15 @@ TEST_P(IPAddressFlagTest, IsLinkLocalBroadcast) {
TEST(IPAddress, SolicitedNodeAddress) { TEST(IPAddress, SolicitedNodeAddress) {
// An example from RFC 4291 section 2.7.1 // An example from RFC 4291 section 2.7.1
EXPECT_EQ(IPAddressV6("ff02::1:ff0e:8c6c"), EXPECT_EQ(
IPAddressV6("4037::01:800:200e:8c6c").getSolicitedNodeAddress()); IPAddressV6("ff02::1:ff0e:8c6c"),
IPAddressV6("4037::01:800:200e:8c6c").getSolicitedNodeAddress());
// An example from wikipedia // An example from wikipedia
// (http://en.wikipedia.org/wiki/Solicited-node_multicast_address) // (http://en.wikipedia.org/wiki/Solicited-node_multicast_address)
EXPECT_EQ(IPAddressV6("ff02::1:ff28:9c5a"), EXPECT_EQ(
IPAddressV6("fe80::2aa:ff:fe28:9c5a").getSolicitedNodeAddress()); IPAddressV6("ff02::1:ff28:9c5a"),
IPAddressV6("fe80::2aa:ff:fe28:9c5a").getSolicitedNodeAddress());
} }
TEST_P(IPAddressByteAccessorTest, CheckBytes) { TEST_P(IPAddressByteAccessorTest, CheckBytes) {
...@@ -988,42 +1018,46 @@ TEST_P(IPAddressByteAccessorTest, CheckBytes) { ...@@ -988,42 +1018,46 @@ TEST_P(IPAddressByteAccessorTest, CheckBytes) {
size_t i = 0; size_t i = 0;
for (auto byitr = addrData.bytes.begin(); i < ip.byteCount(); ++i, ++byitr) { for (auto byitr = addrData.bytes.begin(); i < ip.byteCount(); ++i, ++byitr) {
EXPECT_EQ(*byitr, ip.getNthMSByte(i)); EXPECT_EQ(*byitr, ip.getNthMSByte(i));
EXPECT_EQ(*byitr, ip.isV4() ? EXPECT_EQ(
ip.asV4().getNthMSByte(i) : ip.asV6().getNthMSByte(i)); *byitr,
ip.isV4() ? ip.asV4().getNthMSByte(i) : ip.asV6().getNthMSByte(i));
} }
i = 0; i = 0;
for (auto byritr = addrData.bytes.rbegin(); i < ip.byteCount(); ++i, for (auto byritr = addrData.bytes.rbegin(); i < ip.byteCount();
++byritr) { ++i, ++byritr) {
EXPECT_EQ(*byritr, ip.getNthLSByte(i)); EXPECT_EQ(*byritr, ip.getNthLSByte(i));
EXPECT_EQ(*byritr, ip.isV4() ? EXPECT_EQ(
ip.asV4().getNthLSByte(i) : ip.asV6().getNthLSByte(i)); *byritr,
ip.isV4() ? ip.asV4().getNthLSByte(i) : ip.asV6().getNthLSByte(i));
} }
} }
TEST_P(IPAddressBitAccessorTest, CheckBits) { TEST_P(IPAddressBitAccessorTest, CheckBits) {
auto addrData = GetParam(); auto addrData = GetParam();
auto littleEndianAddrData = addrData.bytes; auto littleEndianAddrData = addrData.bytes;
//IPAddress stores address data in n/w byte order. // IPAddress stores address data in n/w byte order.
reverse(littleEndianAddrData.begin(), littleEndianAddrData.end()); reverse(littleEndianAddrData.begin(), littleEndianAddrData.end());
//Bit iterator goes from LSBit to MSBit // Bit iterator goes from LSBit to MSBit
//We will traverse the IPAddress bits from 0 to bitCount -1 // We will traverse the IPAddress bits from 0 to bitCount -1
auto bitr = folly::makeBitIterator(littleEndianAddrData.begin()); auto bitr = folly::makeBitIterator(littleEndianAddrData.begin());
IPAddress ip(addrData.address); IPAddress ip(addrData.address);
for (size_t i = 0; i < ip.bitCount(); ++i) { for (size_t i = 0; i < ip.bitCount(); ++i) {
auto msbIndex = ip.bitCount() - i - 1; auto msbIndex = ip.bitCount() - i - 1;
EXPECT_EQ(*bitr, ip.getNthMSBit(msbIndex)); EXPECT_EQ(*bitr, ip.getNthMSBit(msbIndex));
EXPECT_EQ(*bitr, ip.isV4() ? ip.asV4().getNthMSBit(msbIndex) : EXPECT_EQ(
ip.asV6().getNthMSBit(msbIndex)); *bitr,
ip.isV4() ? ip.asV4().getNthMSBit(msbIndex)
: ip.asV6().getNthMSBit(msbIndex));
EXPECT_EQ(*bitr, ip.getNthLSBit(i)); EXPECT_EQ(*bitr, ip.getNthLSBit(i));
EXPECT_EQ(*bitr, ip.isV4() ? ip.asV4().getNthLSBit(i) : EXPECT_EQ(
ip.asV6().getNthLSBit(i)); *bitr, ip.isV4() ? ip.asV4().getNthLSBit(i) : ip.asV6().getNthLSBit(i));
++bitr; ++bitr;
} }
} }
TEST(IPAddress, InvalidByteAccess) { TEST(IPAddress, InvalidByteAccess) {
IPAddress ip4("10.10.10.10"); IPAddress ip4("10.10.10.10");
//MSByte, LSByte accessors are 0 indexed // MSByte, LSByte accessors are 0 indexed
EXPECT_THROW(ip4.getNthMSByte(ip4.byteCount()), std::invalid_argument); EXPECT_THROW(ip4.getNthMSByte(ip4.byteCount()), std::invalid_argument);
EXPECT_THROW(ip4.getNthLSByte(ip4.byteCount()), std::invalid_argument); EXPECT_THROW(ip4.getNthLSByte(ip4.byteCount()), std::invalid_argument);
EXPECT_THROW(ip4.getNthMSByte(-1), std::invalid_argument); EXPECT_THROW(ip4.getNthMSByte(-1), std::invalid_argument);
...@@ -1044,12 +1078,11 @@ TEST(IPAddress, InvalidByteAccess) { ...@@ -1044,12 +1078,11 @@ TEST(IPAddress, InvalidByteAccess) {
EXPECT_THROW(asV6.getNthLSByte(asV6.byteCount()), std::invalid_argument); EXPECT_THROW(asV6.getNthLSByte(asV6.byteCount()), std::invalid_argument);
EXPECT_THROW(asV6.getNthMSByte(-1), std::invalid_argument); EXPECT_THROW(asV6.getNthMSByte(-1), std::invalid_argument);
EXPECT_THROW(asV6.getNthLSByte(-1), std::invalid_argument); EXPECT_THROW(asV6.getNthLSByte(-1), std::invalid_argument);
} }
TEST(IPAddress, InvalidBBitAccess) { TEST(IPAddress, InvalidBBitAccess) {
IPAddress ip4("10.10.10.10"); IPAddress ip4("10.10.10.10");
//MSByte, LSByte accessors are 0 indexed // MSByte, LSByte accessors are 0 indexed
EXPECT_THROW(ip4.getNthMSBit(ip4.bitCount()), std::invalid_argument); EXPECT_THROW(ip4.getNthMSBit(ip4.bitCount()), std::invalid_argument);
EXPECT_THROW(ip4.getNthLSBit(ip4.bitCount()), std::invalid_argument); EXPECT_THROW(ip4.getNthLSBit(ip4.bitCount()), std::invalid_argument);
EXPECT_THROW(ip4.getNthMSBit(-1), std::invalid_argument); EXPECT_THROW(ip4.getNthMSBit(-1), std::invalid_argument);
...@@ -1082,8 +1115,8 @@ TEST(IPAddress, StringFormat) { ...@@ -1082,8 +1115,8 @@ TEST(IPAddress, StringFormat) {
a6.s6_addr16[i] = t; a6.s6_addr16[i] = t;
#endif #endif
} }
EXPECT_EQ("0123:4567:89ab:cdef:0123:4567:89ab:cdef", EXPECT_EQ(
detail::fastIpv6ToString(a6)); "0123:4567:89ab:cdef:0123:4567:89ab:cdef", detail::fastIpv6ToString(a6));
in_addr a4; in_addr a4;
a4.s_addr = htonl(0x01020304); a4.s_addr = htonl(0x01020304);
...@@ -1114,8 +1147,8 @@ TEST(IPAddress, LongestCommonPrefix) { ...@@ -1114,8 +1147,8 @@ TEST(IPAddress, LongestCommonPrefix) {
IPAddress ip128("128.0.0.0"); IPAddress ip128("128.0.0.0");
IPAddress ip10dot10("10.10.0.0"); IPAddress ip10dot10("10.10.0.0");
auto prefix = IPAddress::longestCommonPrefix({ip10, 8}, {ip128, 8}); auto prefix = IPAddress::longestCommonPrefix({ip10, 8}, {ip128, 8});
auto prefix4 = IPAddressV4::longestCommonPrefix({ip10.asV4(), 8}, auto prefix4 =
{ip128.asV4(), 8}); IPAddressV4::longestCommonPrefix({ip10.asV4(), 8}, {ip128.asV4(), 8});
// No bits match b/w 128/8 and 10/8 // No bits match b/w 128/8 and 10/8
EXPECT_EQ(IPAddress("0.0.0.0"), prefix.first); EXPECT_EQ(IPAddress("0.0.0.0"), prefix.first);
EXPECT_EQ(0, prefix.second); EXPECT_EQ(0, prefix.second);
...@@ -1123,8 +1156,8 @@ TEST(IPAddress, LongestCommonPrefix) { ...@@ -1123,8 +1156,8 @@ TEST(IPAddress, LongestCommonPrefix) {
EXPECT_EQ(0, prefix4.second); EXPECT_EQ(0, prefix4.second);
prefix = IPAddress::longestCommonPrefix({ip10, 8}, {ip10dot10, 16}); prefix = IPAddress::longestCommonPrefix({ip10, 8}, {ip10dot10, 16});
prefix4 = IPAddressV4::longestCommonPrefix({ip10.asV4(), 8}, prefix4 = IPAddressV4::longestCommonPrefix(
{ip10dot10.asV4(), 16}); {ip10.asV4(), 8}, {ip10dot10.asV4(), 16});
// Between 10/8 and 10.10/16, 10/8 is the longest common match // Between 10/8 and 10.10/16, 10/8 is the longest common match
EXPECT_EQ(ip10, prefix.first); EXPECT_EQ(ip10, prefix.first);
EXPECT_EQ(8, prefix.second); EXPECT_EQ(8, prefix.second);
...@@ -1132,8 +1165,8 @@ TEST(IPAddress, LongestCommonPrefix) { ...@@ -1132,8 +1165,8 @@ TEST(IPAddress, LongestCommonPrefix) {
EXPECT_EQ(8, prefix4.second); EXPECT_EQ(8, prefix4.second);
prefix = IPAddress::longestCommonPrefix({ip11, 8}, {ip12, 8}); prefix = IPAddress::longestCommonPrefix({ip11, 8}, {ip12, 8});
prefix4 = IPAddressV4::longestCommonPrefix({ip11.asV4(), 8}, prefix4 =
{ip12.asV4(), 8}); IPAddressV4::longestCommonPrefix({ip11.asV4(), 8}, {ip12.asV4(), 8});
// 12 = 1100, 11 = 1011, longest match - 1000 = 8 // 12 = 1100, 11 = 1011, longest match - 1000 = 8
EXPECT_EQ(IPAddress("8.0.0.0"), prefix.first); EXPECT_EQ(IPAddress("8.0.0.0"), prefix.first);
EXPECT_EQ(5, prefix.second); EXPECT_EQ(5, prefix.second);
...@@ -1142,19 +1175,19 @@ TEST(IPAddress, LongestCommonPrefix) { ...@@ -1142,19 +1175,19 @@ TEST(IPAddress, LongestCommonPrefix) {
// Between 128/1 and 128/2, longest match 128/1 // Between 128/1 and 128/2, longest match 128/1
prefix = IPAddress::longestCommonPrefix({ip128, 1}, {ip128, 2}); prefix = IPAddress::longestCommonPrefix({ip128, 1}, {ip128, 2});
prefix4 = IPAddressV4::longestCommonPrefix({ip128.asV4(), 1}, prefix4 =
{ip128.asV4(), 2}); IPAddressV4::longestCommonPrefix({ip128.asV4(), 1}, {ip128.asV4(), 2});
EXPECT_EQ(ip128, prefix.first); EXPECT_EQ(ip128, prefix.first);
EXPECT_EQ(1, prefix.second); EXPECT_EQ(1, prefix.second);
EXPECT_EQ(ip128.asV4(), prefix4.first); EXPECT_EQ(ip128.asV4(), prefix4.first);
EXPECT_EQ(1, prefix4.second); EXPECT_EQ(1, prefix4.second);
IPAddress ip6("2620:0:1cfe:face:b00c::3"); IPAddress ip6("2620:0:1cfe:face:b00c::3");
prefix = IPAddress::longestCommonPrefix({ip6, ip6.bitCount()}, prefix = IPAddress::longestCommonPrefix(
{ip6, ip6.bitCount()}); {ip6, ip6.bitCount()}, {ip6, ip6.bitCount()});
auto prefix6 = IPAddressV6::longestCommonPrefix( auto prefix6 = IPAddressV6::longestCommonPrefix(
{ip6.asV6(), IPAddressV6::bitCount()}, {ip6.asV6(), IPAddressV6::bitCount()},
{ip6.asV6(), IPAddressV6::bitCount()}); {ip6.asV6(), IPAddressV6::bitCount()});
// Longest common b/w me and myself is myself // Longest common b/w me and myself is myself
EXPECT_EQ(ip6, prefix.first); EXPECT_EQ(ip6, prefix.first);
EXPECT_EQ(ip6.bitCount(), prefix.second); EXPECT_EQ(ip6.bitCount(), prefix.second);
...@@ -1164,61 +1197,63 @@ TEST(IPAddress, LongestCommonPrefix) { ...@@ -1164,61 +1197,63 @@ TEST(IPAddress, LongestCommonPrefix) {
IPAddress ip6Zero("::"); IPAddress ip6Zero("::");
prefix = IPAddress::longestCommonPrefix({ip6, ip6.bitCount()}, {ip6Zero, 0}); prefix = IPAddress::longestCommonPrefix({ip6, ip6.bitCount()}, {ip6Zero, 0});
prefix6 = IPAddressV6::longestCommonPrefix( prefix6 = IPAddressV6::longestCommonPrefix(
{ip6.asV6(), IPAddressV6::bitCount()}, {ip6.asV6(), IPAddressV6::bitCount()}, {ip6Zero.asV6(), 0});
{ip6Zero.asV6(), 0});
// Longest common b/w :: (ipv6 equivalent of 0/0) is :: // Longest common b/w :: (ipv6 equivalent of 0/0) is ::
EXPECT_EQ(ip6Zero, prefix.first); EXPECT_EQ(ip6Zero, prefix.first);
EXPECT_EQ(0, prefix.second); EXPECT_EQ(0, prefix.second);
// Exceptional cases // Exceptional cases
EXPECT_THROW(IPAddress::longestCommonPrefix({ip10, 8}, {ip6, 128}), EXPECT_THROW(
std::invalid_argument); IPAddress::longestCommonPrefix({ip10, 8}, {ip6, 128}),
EXPECT_THROW(IPAddress::longestCommonPrefix({ip10, ip10.bitCount() + 1}, std::invalid_argument);
{ip10, 8}), EXPECT_THROW(
std::invalid_argument); IPAddress::longestCommonPrefix({ip10, ip10.bitCount() + 1}, {ip10, 8}),
EXPECT_THROW(IPAddressV4::longestCommonPrefix( std::invalid_argument);
{ip10.asV4(), IPAddressV4::bitCount() + 1}, EXPECT_THROW(
{ip10.asV4(), 8}), IPAddressV4::longestCommonPrefix(
std::invalid_argument); {ip10.asV4(), IPAddressV4::bitCount() + 1}, {ip10.asV4(), 8}),
EXPECT_THROW(IPAddress::longestCommonPrefix({ip6, ip6.bitCount() + 1}, std::invalid_argument);
{ip6, ip6.bitCount()}), EXPECT_THROW(
std::invalid_argument); IPAddress::longestCommonPrefix(
EXPECT_THROW(IPAddressV6::longestCommonPrefix( {ip6, ip6.bitCount() + 1}, {ip6, ip6.bitCount()}),
{ip6.asV6(), IPAddressV6::bitCount() + 1}, std::invalid_argument);
{ip6.asV6(), IPAddressV6::bitCount()}), EXPECT_THROW(
std::invalid_argument); IPAddressV6::longestCommonPrefix(
{ip6.asV6(), IPAddressV6::bitCount() + 1},
{ip6.asV6(), IPAddressV6::bitCount()}),
std::invalid_argument);
} }
static const vector<AddressData> validAddressProvider = { static const vector<AddressData> validAddressProvider = {
AddressData("127.0.0.1", {127,0,0,1}, 4), AddressData("127.0.0.1", {127, 0, 0, 1}, 4),
AddressData("69.63.189.16", {69,63,189,16}, 4), AddressData("69.63.189.16", {69, 63, 189, 16}, 4),
AddressData("0.0.0.0", {0,0,0,0}, 4), AddressData("0.0.0.0", {0, 0, 0, 0}, 4),
AddressData("::1", AddressData("::1", {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 6),
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}, 6), AddressData(
AddressData("2620:0:1cfe:face:b00c::3", "2620:0:1cfe:face:b00c::3",
{38,32,0,0,28,254,250,206,176,12,0,0,0,0,0,3}, 6), {38, 32, 0, 0, 28, 254, 250, 206, 176, 12, 0, 0, 0, 0, 0, 3},
6),
}; };
static const vector<string> invalidAddressProvider = { static const vector<string> invalidAddressProvider = {
"", "",
"foo", "foo",
"1.1.1.256", "1.1.1.256",
"1", "1",
":1", ":1",
"127.0.0.1,127.0.0.1", "127.0.0.1,127.0.0.1",
"[1234]", "[1234]",
}; };
static const vector<ByteVector> invalidBinaryProvider = { static const vector<ByteVector> invalidBinaryProvider = {
{0x31, 0x32, 0x37, 0x2e, 0x30, 0x30, 0x2e, 0x30, 0x2e, 0x31}, {0x31, 0x32, 0x37, 0x2e, 0x30, 0x30, 0x2e, 0x30, 0x2e, 0x31},
// foo // foo
{0x66, 0x6f, 0x6f}, {0x66, 0x6f, 0x6f},
{0x00}, {0x00},
{0x00, 0x00}, {0x00, 0x00},
{0x00, 0x00, 0x00}, {0x00, 0x00, 0x00},
{0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00},
{0xff}, {0xff},
}; };
static const uint8_t IS_LOCAL = AddressFlags::IS_LOCAL; static const uint8_t IS_LOCAL = AddressFlags::IS_LOCAL;
...@@ -1226,176 +1261,188 @@ static const uint8_t IS_NONROUTABLE = AddressFlags::IS_NONROUTABLE; ...@@ -1226,176 +1261,188 @@ static const uint8_t IS_NONROUTABLE = AddressFlags::IS_NONROUTABLE;
static const uint8_t IS_PRIVATE = AddressFlags::IS_PRIVATE; static const uint8_t IS_PRIVATE = AddressFlags::IS_PRIVATE;
static const uint8_t IS_ZERO = AddressFlags::IS_ZERO; static const uint8_t IS_ZERO = AddressFlags::IS_ZERO;
static const uint8_t IS_LINK_LOCAL = static const uint8_t IS_LINK_LOCAL =
AddressFlags::IS_LINK_LOCAL | IS_NONROUTABLE; AddressFlags::IS_LINK_LOCAL | IS_NONROUTABLE;
static const uint8_t IS_PVT_NONROUTE = IS_NONROUTABLE | IS_PRIVATE; static const uint8_t IS_PVT_NONROUTE = IS_NONROUTABLE | IS_PRIVATE;
static const uint8_t IS_MULTICAST = AddressFlags::IS_MULTICAST; static const uint8_t IS_MULTICAST = AddressFlags::IS_MULTICAST;
static const uint8_t IS_LINK_LOCAL_BROADCAST = static const uint8_t IS_LINK_LOCAL_BROADCAST =
AddressFlags::IS_LINK_LOCAL_BROADCAST; AddressFlags::IS_LINK_LOCAL_BROADCAST;
static vector<AddressFlags> flagProvider = { static vector<AddressFlags> flagProvider = {
// public v4 // public v4
AddressFlags("69.63.176.1", 4, 0), AddressFlags("69.63.176.1", 4, 0),
AddressFlags("128.12.65.3", 4, 0), AddressFlags("128.12.65.3", 4, 0),
AddressFlags("192.0.1.0", 4, 0), AddressFlags("192.0.1.0", 4, 0),
AddressFlags("198.51.101.0", 4, 0), AddressFlags("198.51.101.0", 4, 0),
AddressFlags("203.0.114.0", 4, 0), AddressFlags("203.0.114.0", 4, 0),
AddressFlags("128.12.64.115", 4, 0), AddressFlags("128.12.64.115", 4, 0),
// public v6 // public v6
AddressFlags("2620:0:1cfe:face:b00c::3", 6, 0), AddressFlags("2620:0:1cfe:face:b00c::3", 6, 0),
// localhost // localhost
AddressFlags("127.0.0.1", 4, IS_LOCAL | IS_PVT_NONROUTE), AddressFlags("127.0.0.1", 4, IS_LOCAL | IS_PVT_NONROUTE),
AddressFlags("::1", 6, IS_LOCAL | IS_PVT_NONROUTE), AddressFlags("::1", 6, IS_LOCAL | IS_PVT_NONROUTE),
// link-local v4 // link-local v4
AddressFlags("169.254.0.1", 4, IS_LINK_LOCAL | IS_PVT_NONROUTE), AddressFlags("169.254.0.1", 4, IS_LINK_LOCAL | IS_PVT_NONROUTE),
// private v4 // private v4
AddressFlags("10.0.0.0", 4, IS_PVT_NONROUTE), AddressFlags("10.0.0.0", 4, IS_PVT_NONROUTE),
AddressFlags("10.11.12.13", 4, IS_PVT_NONROUTE), AddressFlags("10.11.12.13", 4, IS_PVT_NONROUTE),
AddressFlags("10.255.255.255", 4, IS_PVT_NONROUTE), AddressFlags("10.255.255.255", 4, IS_PVT_NONROUTE),
AddressFlags("127.128.129.200", 4, IS_LOCAL | IS_PVT_NONROUTE), AddressFlags("127.128.129.200", 4, IS_LOCAL | IS_PVT_NONROUTE),
AddressFlags("127.255.255.255", 4, IS_LOCAL | IS_PVT_NONROUTE), AddressFlags("127.255.255.255", 4, IS_LOCAL | IS_PVT_NONROUTE),
AddressFlags("169.254.0.0", 4, IS_LINK_LOCAL | IS_PVT_NONROUTE), AddressFlags("169.254.0.0", 4, IS_LINK_LOCAL | IS_PVT_NONROUTE),
AddressFlags("192.168.0.0", 4, IS_PVT_NONROUTE), AddressFlags("192.168.0.0", 4, IS_PVT_NONROUTE),
AddressFlags("192.168.200.255", 4, IS_PVT_NONROUTE), AddressFlags("192.168.200.255", 4, IS_PVT_NONROUTE),
AddressFlags("192.168.255.255", 4, IS_PVT_NONROUTE), AddressFlags("192.168.255.255", 4, IS_PVT_NONROUTE),
// private v6 // private v6
AddressFlags("fd01:1637:1c56:66af::", 6, IS_PVT_NONROUTE), AddressFlags("fd01:1637:1c56:66af::", 6, IS_PVT_NONROUTE),
// non routable v4 // non routable v4
AddressFlags("0.0.0.0", 4, IS_NONROUTABLE | IS_ZERO), AddressFlags("0.0.0.0", 4, IS_NONROUTABLE | IS_ZERO),
AddressFlags("0.255.255.255", 4, IS_NONROUTABLE), AddressFlags("0.255.255.255", 4, IS_NONROUTABLE),
AddressFlags("192.0.0.0", 4, IS_NONROUTABLE), AddressFlags("192.0.0.0", 4, IS_NONROUTABLE),
AddressFlags("192.0.2.0", 4, IS_NONROUTABLE), AddressFlags("192.0.2.0", 4, IS_NONROUTABLE),
AddressFlags("198.18.0.0", 4, IS_NONROUTABLE), AddressFlags("198.18.0.0", 4, IS_NONROUTABLE),
AddressFlags("198.19.255.255", 4, IS_NONROUTABLE), AddressFlags("198.19.255.255", 4, IS_NONROUTABLE),
AddressFlags("198.51.100.0", 4, IS_NONROUTABLE), AddressFlags("198.51.100.0", 4, IS_NONROUTABLE),
AddressFlags("198.51.100.255", 4, IS_NONROUTABLE), AddressFlags("198.51.100.255", 4, IS_NONROUTABLE),
AddressFlags("203.0.113.0", 4, IS_NONROUTABLE), AddressFlags("203.0.113.0", 4, IS_NONROUTABLE),
AddressFlags("203.0.113.255", 4, IS_NONROUTABLE), AddressFlags("203.0.113.255", 4, IS_NONROUTABLE),
AddressFlags("224.0.0.0", 4, IS_NONROUTABLE | IS_MULTICAST), AddressFlags("224.0.0.0", 4, IS_NONROUTABLE | IS_MULTICAST),
AddressFlags("240.0.0.0", 4, IS_NONROUTABLE), AddressFlags("240.0.0.0", 4, IS_NONROUTABLE),
AddressFlags("224.0.0.0", 4, IS_NONROUTABLE), AddressFlags("224.0.0.0", 4, IS_NONROUTABLE),
// v4 link local broadcast // v4 link local broadcast
AddressFlags("255.255.255.255", 4, IS_NONROUTABLE | IS_LINK_LOCAL_BROADCAST), AddressFlags(
"255.255.255.255",
// non routable v6 4,
AddressFlags("1999::1", 6, IS_NONROUTABLE), IS_NONROUTABLE | IS_LINK_LOCAL_BROADCAST),
AddressFlags("0::0", 6, IS_NONROUTABLE | IS_ZERO),
AddressFlags("0::0:0", 6, IS_NONROUTABLE | IS_ZERO), // non routable v6
AddressFlags("0:0:0::0", 6, IS_NONROUTABLE | IS_ZERO), AddressFlags("1999::1", 6, IS_NONROUTABLE),
AddressFlags("0::0", 6, IS_NONROUTABLE | IS_ZERO),
// link-local v6 AddressFlags("0::0:0", 6, IS_NONROUTABLE | IS_ZERO),
AddressFlags("fe80::0205:73ff:fef9:46fc", 6, IS_LINK_LOCAL), AddressFlags("0:0:0::0", 6, IS_NONROUTABLE | IS_ZERO),
AddressFlags("fe80::0012:34ff:fe56:7890", 6, IS_LINK_LOCAL),
// link-local v6
// multicast v4 AddressFlags("fe80::0205:73ff:fef9:46fc", 6, IS_LINK_LOCAL),
AddressFlags("224.0.0.1", 4, IS_MULTICAST | IS_NONROUTABLE) , AddressFlags("fe80::0012:34ff:fe56:7890", 6, IS_LINK_LOCAL),
AddressFlags("224.0.0.251", 4, IS_MULTICAST | IS_NONROUTABLE),
AddressFlags("239.12.34.56", 4, IS_MULTICAST | IS_NONROUTABLE), // multicast v4
AddressFlags("224.0.0.1", 4, IS_MULTICAST | IS_NONROUTABLE),
// multicast v6 AddressFlags("224.0.0.251", 4, IS_MULTICAST | IS_NONROUTABLE),
AddressFlags("ff00::", 6, IS_MULTICAST | IS_NONROUTABLE), AddressFlags("239.12.34.56", 4, IS_MULTICAST | IS_NONROUTABLE),
AddressFlags("ff02:ffff::1", 6, IS_MULTICAST | IS_NONROUTABLE),
AddressFlags("ff02::101", 6, IS_MULTICAST | IS_NONROUTABLE), // multicast v6
AddressFlags("ff0e::101", 6, IS_MULTICAST), AddressFlags("ff00::", 6, IS_MULTICAST | IS_NONROUTABLE),
// v6 link local broadcast AddressFlags("ff02:ffff::1", 6, IS_MULTICAST | IS_NONROUTABLE),
AddressFlags("ff02::1", 6, IS_NONROUTABLE | IS_LINK_LOCAL_BROADCAST), AddressFlags("ff02::101", 6, IS_MULTICAST | IS_NONROUTABLE),
AddressFlags("ff0e::101", 6, IS_MULTICAST),
// v6 link local broadcast
AddressFlags("ff02::1", 6, IS_NONROUTABLE | IS_LINK_LOCAL_BROADCAST),
}; };
static const vector<pair<string, string> > mapProvider = { static const vector<pair<string, string>> mapProvider = {
{"::ffff:192.0.2.128", "192.0.2.128"}, {"::ffff:192.0.2.128", "192.0.2.128"},
{"192.0.2.128", "::ffff:192.0.2.128"}, {"192.0.2.128", "::ffff:192.0.2.128"},
{"::FFFF:129.144.52.38", "129.144.52.38"}, {"::FFFF:129.144.52.38", "129.144.52.38"},
{"129.144.52.38", "::FFFF:129.144.52.38"}, {"129.144.52.38", "::FFFF:129.144.52.38"},
{"0:0:0:0:0:FFFF:222.1.41.90", "222.1.41.90"}, {"0:0:0:0:0:FFFF:222.1.41.90", "222.1.41.90"},
{"::FFFF:222.1.41.90", "222.1.41.90"}, {"::FFFF:222.1.41.90", "222.1.41.90"},
}; };
static const vector<MaskData> masksProvider = { static const vector<MaskData> masksProvider = {
MaskData("255.255.255.255", 1, "128.0.0.0"), MaskData("255.255.255.255", 1, "128.0.0.0"),
MaskData("255.255.255.255", 2, "192.0.0.0"), MaskData("255.255.255.255", 2, "192.0.0.0"),
MaskData("192.0.2.42", 16, "192.0.0.0"), MaskData("192.0.2.42", 16, "192.0.0.0"),
MaskData("255.255.255.255", 24, "255.255.255.0"), MaskData("255.255.255.255", 24, "255.255.255.0"),
MaskData("255.255.255.255", 32, "255.255.255.255"), MaskData("255.255.255.255", 32, "255.255.255.255"),
MaskData("10.10.10.10", 0, "0.0.0.0"), MaskData("10.10.10.10", 0, "0.0.0.0"),
MaskData("::1", 64, "::"), MaskData("::1", 64, "::"),
MaskData("2620:0:1cfe:face:b00c::3", 1, "::"), MaskData("2620:0:1cfe:face:b00c::3", 1, "::"),
MaskData("2620:0:1cfe:face:b00c::3", 3, "2000::"), MaskData("2620:0:1cfe:face:b00c::3", 3, "2000::"),
MaskData("2620:0:1cfe:face:b00c::3", 6, "2400::"), MaskData("2620:0:1cfe:face:b00c::3", 6, "2400::"),
MaskData("2620:0:1cfe:face:b00c::3", 7, "2600::"), MaskData("2620:0:1cfe:face:b00c::3", 7, "2600::"),
MaskData("2620:0:1cfe:face:b00c::3", 11, "2620::"), MaskData("2620:0:1cfe:face:b00c::3", 11, "2620::"),
MaskData("2620:0:1cfe:face:b00c::3", 36, "2620:0:1000::"), MaskData("2620:0:1cfe:face:b00c::3", 36, "2620:0:1000::"),
MaskData("2620:0:1cfe:face:b00c::3", 37, "2620:0:1800::"), MaskData("2620:0:1cfe:face:b00c::3", 37, "2620:0:1800::"),
MaskData("2620:0:1cfe:face:b00c::3", 38, "2620:0:1c00::"), MaskData("2620:0:1cfe:face:b00c::3", 38, "2620:0:1c00::"),
MaskData("2620:0:1cfe:face:b00c::3", 41, "2620:0:1c80::"), MaskData("2620:0:1cfe:face:b00c::3", 41, "2620:0:1c80::"),
MaskData("2620:0:1cfe:face:b00c::3", 42, "2620:0:1cc0::"), MaskData("2620:0:1cfe:face:b00c::3", 42, "2620:0:1cc0::"),
MaskData("2620:0:1cfe:face:b00c::3", 43, "2620:0:1ce0::"), MaskData("2620:0:1cfe:face:b00c::3", 43, "2620:0:1ce0::"),
MaskData("2620:0:1cfe:face:b00c::3", 44, "2620:0:1cf0::"), MaskData("2620:0:1cfe:face:b00c::3", 44, "2620:0:1cf0::"),
MaskData("2620:0:1cfe:face:b00c::3", 45, "2620:0:1cf8::"), MaskData("2620:0:1cfe:face:b00c::3", 45, "2620:0:1cf8::"),
MaskData("2620:0:1cfe:face:b00c::3", 46, "2620:0:1cfc::"), MaskData("2620:0:1cfe:face:b00c::3", 46, "2620:0:1cfc::"),
MaskData("2620:0:1cfe:face:b00c::3", 47, "2620:0:1cfe::"), MaskData("2620:0:1cfe:face:b00c::3", 47, "2620:0:1cfe::"),
MaskData("2620:0:1cfe:face:b00c::3", 49, "2620:0:1cfe:8000::"), MaskData("2620:0:1cfe:face:b00c::3", 49, "2620:0:1cfe:8000::"),
MaskData("2620:0:1cfe:face:b00c::3", 50, "2620:0:1cfe:c000::"), MaskData("2620:0:1cfe:face:b00c::3", 50, "2620:0:1cfe:c000::"),
MaskData("2620:0:1cfe:face:b00c::3", 51, "2620:0:1cfe:e000::"), MaskData("2620:0:1cfe:face:b00c::3", 51, "2620:0:1cfe:e000::"),
MaskData("2620:0:1cfe:face:b00c::3", 52, "2620:0:1cfe:f000::"), MaskData("2620:0:1cfe:face:b00c::3", 52, "2620:0:1cfe:f000::"),
MaskData("2620:0:1cfe:face:b00c::3", 53, "2620:0:1cfe:f800::"), MaskData("2620:0:1cfe:face:b00c::3", 53, "2620:0:1cfe:f800::"),
MaskData("2620:0:1cfe:face:b00c::3", 55, "2620:0:1cfe:fa00::"), MaskData("2620:0:1cfe:face:b00c::3", 55, "2620:0:1cfe:fa00::"),
MaskData("2620:0:1cfe:face:b00c::3", 57, "2620:0:1cfe:fa80::"), MaskData("2620:0:1cfe:face:b00c::3", 57, "2620:0:1cfe:fa80::"),
MaskData("2620:0:1cfe:face:b00c::3", 58, "2620:0:1cfe:fac0::"), MaskData("2620:0:1cfe:face:b00c::3", 58, "2620:0:1cfe:fac0::"),
MaskData("2620:0:1cfe:face:b00c::3", 61, "2620:0:1cfe:fac8::"), MaskData("2620:0:1cfe:face:b00c::3", 61, "2620:0:1cfe:fac8::"),
MaskData("2620:0:1cfe:face:b00c::3", 62, "2620:0:1cfe:facc::"), MaskData("2620:0:1cfe:face:b00c::3", 62, "2620:0:1cfe:facc::"),
MaskData("2620:0:1cfe:face:b00c::3", 63, "2620:0:1cfe:face::"), MaskData("2620:0:1cfe:face:b00c::3", 63, "2620:0:1cfe:face::"),
MaskData("2620:0:1cfe:face:b00c::3", 65, "2620:0:1cfe:face:8000::"), MaskData("2620:0:1cfe:face:b00c::3", 65, "2620:0:1cfe:face:8000::"),
MaskData("2620:0:1cfe:face:b00c::3", 67, "2620:0:1cfe:face:a000::"), MaskData("2620:0:1cfe:face:b00c::3", 67, "2620:0:1cfe:face:a000::"),
MaskData("2620:0:1cfe:face:b00c::3", 68, "2620:0:1cfe:face:b000::"), MaskData("2620:0:1cfe:face:b00c::3", 68, "2620:0:1cfe:face:b000::"),
MaskData("2620:0:1cfe:face:b00c::3", 77, "2620:0:1cfe:face:b008::"), MaskData("2620:0:1cfe:face:b00c::3", 77, "2620:0:1cfe:face:b008::"),
MaskData("2620:0:1cfe:face:b00c::3", 78, "2620:0:1cfe:face:b00c::"), MaskData("2620:0:1cfe:face:b00c::3", 78, "2620:0:1cfe:face:b00c::"),
MaskData("2620:0:1cfe:face:b00c::3", 127, "2620:0:1cfe:face:b00c::2"), MaskData("2620:0:1cfe:face:b00c::3", 127, "2620:0:1cfe:face:b00c::2"),
MaskData("2620:0:1cfe:face:b00c::3", 128, "2620:0:1cfe:face:b00c::3"), MaskData("2620:0:1cfe:face:b00c::3", 128, "2620:0:1cfe:face:b00c::3"),
MaskData("2620:0:1cfe:face:b00c::3", 0, "::") MaskData("2620:0:1cfe:face:b00c::3", 0, "::"),
}; };
static const vector<MaskBoundaryData> maskBoundaryProvider = { static const vector<MaskBoundaryData> maskBoundaryProvider = {
MaskBoundaryData("10.1.1.1", 24, "10.1.1.1", true), MaskBoundaryData("10.1.1.1", 24, "10.1.1.1", true),
MaskBoundaryData("10.1.1.1", 8, "10.1.2.3", true), MaskBoundaryData("10.1.1.1", 8, "10.1.2.3", true),
MaskBoundaryData("2620:0:1cfe:face:b00c::1", 48, "2620:0:1cfe::", true), MaskBoundaryData("2620:0:1cfe:face:b00c::1", 48, "2620:0:1cfe::", true),
// addresses that are NOT in the same subnet once mask is applied // addresses that are NOT in the same subnet once mask is applied
MaskBoundaryData("10.1.1.1", 24, "10.1.2.1", false), MaskBoundaryData("10.1.1.1", 24, "10.1.2.1", false),
MaskBoundaryData("10.1.1.1", 16, "10.2.3.4", false), MaskBoundaryData("10.1.1.1", 16, "10.2.3.4", false),
MaskBoundaryData("2620:0:1cfe:face:b00c::1", 48, "2620:0:1cfc::", false), MaskBoundaryData("2620:0:1cfe:face:b00c::1", 48, "2620:0:1cfc::", false),
}; };
INSTANTIATE_TEST_CASE_P(IPAddress, INSTANTIATE_TEST_CASE_P(
IPAddressTest, IPAddress,
::testing::ValuesIn(validAddressProvider)); IPAddressTest,
INSTANTIATE_TEST_CASE_P(IPAddress, ::testing::ValuesIn(validAddressProvider));
IPAddressFlagTest, INSTANTIATE_TEST_CASE_P(
::testing::ValuesIn(flagProvider)); IPAddress,
INSTANTIATE_TEST_CASE_P(IPAddress, IPAddressFlagTest,
IPAddressMappedTest, ::testing::ValuesIn(flagProvider));
::testing::ValuesIn(mapProvider)); INSTANTIATE_TEST_CASE_P(
INSTANTIATE_TEST_CASE_P(IPAddress, IPAddress,
IPAddressCtorTest, IPAddressMappedTest,
::testing::ValuesIn(invalidAddressProvider)); ::testing::ValuesIn(mapProvider));
INSTANTIATE_TEST_CASE_P(IPAddress, INSTANTIATE_TEST_CASE_P(
IPAddressCtorBinaryTest, IPAddress,
::testing::ValuesIn(invalidBinaryProvider)); IPAddressCtorTest,
INSTANTIATE_TEST_CASE_P(IPAddress, ::testing::ValuesIn(invalidAddressProvider));
IPAddressMaskTest, INSTANTIATE_TEST_CASE_P(
::testing::ValuesIn(masksProvider)); IPAddress,
INSTANTIATE_TEST_CASE_P(IPAddress, IPAddressCtorBinaryTest,
IPAddressMaskBoundaryTest, ::testing::ValuesIn(invalidBinaryProvider));
::testing::ValuesIn(maskBoundaryProvider)); INSTANTIATE_TEST_CASE_P(
INSTANTIATE_TEST_CASE_P(IPAddress, IPAddress,
IPAddressByteAccessorTest, IPAddressMaskTest,
::testing::ValuesIn(validAddressProvider)); ::testing::ValuesIn(masksProvider));
INSTANTIATE_TEST_CASE_P(IPAddress, INSTANTIATE_TEST_CASE_P(
IPAddressBitAccessorTest, IPAddress,
::testing::ValuesIn(validAddressProvider)); IPAddressMaskBoundaryTest,
::testing::ValuesIn(maskBoundaryProvider));
INSTANTIATE_TEST_CASE_P(
IPAddress,
IPAddressByteAccessorTest,
::testing::ValuesIn(validAddressProvider));
INSTANTIATE_TEST_CASE_P(
IPAddress,
IPAddressBitAccessorTest,
::testing::ValuesIn(validAddressProvider));
TEST(IPAddressV4, fetchMask) { TEST(IPAddressV4, fetchMask) {
struct X : private IPAddressV4 { struct X : private IPAddressV4 {
...@@ -1420,63 +1467,55 @@ TEST(IPAddressV4, fetchMask) { ...@@ -1420,63 +1467,55 @@ TEST(IPAddressV4, fetchMask) {
} }
TEST(IPAddressV6, fetchMask) { TEST(IPAddressV6, fetchMask) {
using ByteArray8 = std::array<uint8_t, 8>;
struct X : private IPAddressV6 { struct X : private IPAddressV6 {
using IPAddressV6::fetchMask; using IPAddressV6::fetchMask;
}; };
auto join = [](std::array<ByteArray8, 2> parts) {
ByteArray16 _return;
std::memcpy(_return.data(), parts.data(), _return.size());
return _return;
};
EXPECT_THAT( EXPECT_THAT(
X::fetchMask(0), X::fetchMask(0),
::testing::ElementsAreArray(join({{ ::testing::ElementsAreArray(join8({{
ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
}}))); }})));
EXPECT_THAT( EXPECT_THAT(
X::fetchMask(1), X::fetchMask(1),
::testing::ElementsAreArray(join({{ ::testing::ElementsAreArray(join8({{
ByteArray8{{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, ByteArray8{{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
}}))); }})));
EXPECT_THAT( EXPECT_THAT(
X::fetchMask(63), X::fetchMask(63),
::testing::ElementsAreArray(join({{ ::testing::ElementsAreArray(join8({{
ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe}}, ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe}},
ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
}}))); }})));
EXPECT_THAT( EXPECT_THAT(
X::fetchMask(64), X::fetchMask(64),
::testing::ElementsAreArray(join({{ ::testing::ElementsAreArray(join8({{
ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, ByteArray8{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
}}))); }})));
EXPECT_THAT( EXPECT_THAT(
X::fetchMask(65), X::fetchMask(65),
::testing::ElementsAreArray(join({{ ::testing::ElementsAreArray(join8({{
ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
ByteArray8{{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, ByteArray8{{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
}}))); }})));
EXPECT_THAT( EXPECT_THAT(
X::fetchMask(127), X::fetchMask(127),
::testing::ElementsAreArray(join({{ ::testing::ElementsAreArray(join8({{
ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe}}, ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe}},
}}))); }})));
EXPECT_THAT( EXPECT_THAT(
X::fetchMask(128), X::fetchMask(128),
::testing::ElementsAreArray(join({{ ::testing::ElementsAreArray(join8({{
ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}}, ByteArray8{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
}}))); }})));
......
...@@ -94,8 +94,8 @@ TEST(MacAddress, fromBinary) { ...@@ -94,8 +94,8 @@ TEST(MacAddress, fromBinary) {
} }
TEST(MacAddress, toString) { TEST(MacAddress, toString) {
EXPECT_EQ("12:34:56:78:9a:bc", EXPECT_EQ(
MacAddress::fromHBO(0x123456789abc).toString()); "12:34:56:78:9a:bc", MacAddress::fromHBO(0x123456789abc).toString());
EXPECT_EQ("12:34:56:78:9a:bc", MacAddress("12:34:56:78:9a:bc").toString()); EXPECT_EQ("12:34:56:78:9a:bc", MacAddress("12:34:56:78:9a:bc").toString());
EXPECT_EQ("01:23:45:67:89:ab", MacAddress("01-23-45-67-89-ab").toString()); EXPECT_EQ("01:23:45:67:89:ab", MacAddress("01-23-45-67-89-ab").toString());
EXPECT_EQ("01:23:45:67:89:ab", MacAddress("0123456789ab").toString()); EXPECT_EQ("01:23:45:67:89:ab", MacAddress("0123456789ab").toString());
...@@ -131,10 +131,12 @@ TEST(MacAddress, attributes) { ...@@ -131,10 +131,12 @@ TEST(MacAddress, attributes) {
} }
TEST(MacAddress, createMulticast) { TEST(MacAddress, createMulticast) {
EXPECT_EQ(MacAddress("33:33:00:01:00:03"), EXPECT_EQ(
MacAddress::createMulticast(IPAddressV6("ff02:dead:beef::1:3"))); MacAddress("33:33:00:01:00:03"),
EXPECT_EQ(MacAddress("33:33:12:34:56:78"), MacAddress::createMulticast(IPAddressV6("ff02:dead:beef::1:3")));
MacAddress::createMulticast(IPAddressV6("ff02::abcd:1234:5678"))); EXPECT_EQ(
MacAddress("33:33:12:34:56:78"),
MacAddress::createMulticast(IPAddressV6("ff02::abcd:1234:5678")));
} }
void testCmp(const char* str1, const char* str2) { void testCmp(const char* str1, const char* str2) {
......
...@@ -20,6 +20,8 @@ ...@@ -20,6 +20,8 @@
#include <sstream> #include <sstream>
#include <system_error> #include <system_error>
#include <folly/Array.h>
#include <folly/String.h>
#include <folly/experimental/TestUtil.h> #include <folly/experimental/TestUtil.h>
#include <folly/portability/GTest.h> #include <folly/portability/GTest.h>
#include <folly/portability/Sockets.h> #include <folly/portability/Sockets.h>
...@@ -66,12 +68,9 @@ TEST(SocketAddress, IPv4ToStringConversion) { ...@@ -66,12 +68,9 @@ TEST(SocketAddress, IPv4ToStringConversion) {
SocketAddress addr; SocketAddress addr;
for (int pos = 0; pos < 4; ++pos) { for (int pos = 0; pos < 4; ++pos) {
for (int i = 0; i < 256; ++i) { for (int i = 0; i < 256; ++i) {
int fragments[] = {5,5,5,5}; auto fragments = folly::make_array(5, 5, 5, 5);
fragments[pos] = i; fragments[pos] = i;
std::ostringstream ss; auto ipString = folly::join(".", fragments);
ss << fragments[0] << "." << fragments[1] << "."
<< fragments[2] << "." << fragments[3];
string ipString = ss.str();
addr.setFromIpPort(ipString, 1234); addr.setFromIpPort(ipString, 1234);
EXPECT_EQ(addr.getAddressStr(), ipString); EXPECT_EQ(addr.getAddressStr(), ipString);
} }
...@@ -118,8 +117,7 @@ TEST(SocketAddress, SetFromInvalidIpv4) { ...@@ -118,8 +117,7 @@ TEST(SocketAddress, SetFromInvalidIpv4) {
// Try setting to an invalid value // Try setting to an invalid value
// Since setFromIpPort() shouldn't allow hostname lookups, setting to // Since setFromIpPort() shouldn't allow hostname lookups, setting to
// "localhost" should fail, even if localhost is resolvable // "localhost" should fail, even if localhost is resolvable
EXPECT_THROW(addr.setFromIpPort("localhost", 1234), EXPECT_THROW(addr.setFromIpPort("localhost", 1234), std::runtime_error);
std::runtime_error);
// Make sure the address still has the old contents // Make sure the address still has the old contents
EXPECT_EQ(addr.getFamily(), AF_INET); EXPECT_EQ(addr.getFamily(), AF_INET);
...@@ -416,8 +414,10 @@ TEST(SocketAddress, IsLoopback) { ...@@ -416,8 +414,10 @@ TEST(SocketAddress, IsLoopback) {
EXPECT_TRUE(addr.isLoopbackAddress()); EXPECT_TRUE(addr.isLoopbackAddress());
} }
void CheckPrefixMatch(const SocketAddress& first, void CheckPrefixMatch(
const SocketAddress& second, unsigned matchingPrefixLen) { const SocketAddress& first,
const SocketAddress& second,
unsigned matchingPrefixLen) {
unsigned i; unsigned i;
for (i = 0; i <= matchingPrefixLen; i++) { for (i = 0; i <= matchingPrefixLen; i++) {
EXPECT_TRUE(first.prefixMatch(second, i)); EXPECT_TRUE(first.prefixMatch(second, i));
...@@ -468,7 +468,7 @@ TEST(SocketAddress, CheckComparatorBehavior) { ...@@ -468,7 +468,7 @@ TEST(SocketAddress, CheckComparatorBehavior) {
// The following comparison are strict (so if first and second were // The following comparison are strict (so if first and second were
// inverted that is ok. // inverted that is ok.
//IP V4 // IP V4
// port comparisions // port comparisions
first.setFromIpPort("128.0.0.0", 0); first.setFromIpPort("128.0.0.0", 0);
...@@ -539,10 +539,10 @@ TEST(SocketAddress, Unix) { ...@@ -539,10 +539,10 @@ TEST(SocketAddress, Unix) {
// Test a path that is too large // Test a path that is too large
const char longPath[] = const char longPath[] =
"abcdefghijklmnopqrstuvwxyz0123456789" "abcdefghijklmnopqrstuvwxyz0123456789"
"abcdefghijklmnopqrstuvwxyz0123456789" "abcdefghijklmnopqrstuvwxyz0123456789"
"abcdefghijklmnopqrstuvwxyz0123456789" "abcdefghijklmnopqrstuvwxyz0123456789"
"abcdefghijklmnopqrstuvwxyz0123456789"; "abcdefghijklmnopqrstuvwxyz0123456789";
EXPECT_THROW(addr.setFromPath(longPath), std::invalid_argument); EXPECT_THROW(addr.setFromPath(longPath), std::invalid_argument);
// The original address should still be the same // The original address should still be the same
EXPECT_EQ(addr.getFamily(), AF_UNIX); EXPECT_EQ(addr.getFamily(), AF_UNIX);
...@@ -551,9 +551,9 @@ TEST(SocketAddress, Unix) { ...@@ -551,9 +551,9 @@ TEST(SocketAddress, Unix) {
// Test a path that exactly fits in sockaddr_un // Test a path that exactly fits in sockaddr_un
// (not including the NUL terminator) // (not including the NUL terminator)
const char exactLengthPath[] = const char exactLengthPath[] =
"abcdefghijklmnopqrstuvwxyz0123456789" "abcdefghijklmnopqrstuvwxyz0123456789"
"abcdefghijklmnopqrstuvwxyz0123456789" "abcdefghijklmnopqrstuvwxyz0123456789"
"abcdefghijklmnopqrstuvwxyz0123456789"; "abcdefghijklmnopqrstuvwxyz0123456789";
addr.setFromPath(exactLengthPath); addr.setFromPath(exactLengthPath);
EXPECT_EQ(addr.describe(), exactLengthPath); EXPECT_EQ(addr.describe(), exactLengthPath);
...@@ -661,22 +661,23 @@ TEST(SocketAddress, AnonymousUnix) { ...@@ -661,22 +661,23 @@ TEST(SocketAddress, AnonymousUnix) {
EXPECT_NE(addr0, addr0); EXPECT_NE(addr0, addr0);
} }
#define REQUIRE_ERRNO(cond, msg) \ #define REQUIRE_ERRNO(cond, msg) \
if (!(cond)) { \ if (!(cond)) { \
int _requireErrnoCopy_ = errno; \ int _requireErrnoCopy_ = errno; \
std::ostringstream _requireMsg_; \ std::ostringstream _requireMsg_; \
_requireMsg_ << (msg) << ": " << strerror(_requireErrnoCopy_); \ _requireMsg_ << (msg) << ": " << strerror(_requireErrnoCopy_); \
ADD_FAILURE(); \ ADD_FAILURE(); \
} }
void testSetFromSocket(const SocketAddress *serverBindAddr, void testSetFromSocket(
const SocketAddress *clientBindAddr, const SocketAddress* serverBindAddr,
SocketAddress *listenAddrRet, const SocketAddress* clientBindAddr,
SocketAddress *acceptAddrRet, SocketAddress* listenAddrRet,
SocketAddress *serverAddrRet, SocketAddress* acceptAddrRet,
SocketAddress *serverPeerAddrRet, SocketAddress* serverAddrRet,
SocketAddress *clientAddrRet, SocketAddress* serverPeerAddrRet,
SocketAddress *clientPeerAddrRet) { SocketAddress* clientAddrRet,
SocketAddress* clientPeerAddrRet) {
int listenSock = fsp::socket(serverBindAddr->getFamily(), SOCK_STREAM, 0); int listenSock = fsp::socket(serverBindAddr->getFamily(), SOCK_STREAM, 0);
REQUIRE_ERRNO(listenSock > 0, "failed to create listen socket"); REQUIRE_ERRNO(listenSock > 0, "failed to create listen socket");
sockaddr_storage laddr; sockaddr_storage laddr;
...@@ -690,8 +691,8 @@ void testSetFromSocket(const SocketAddress *serverBindAddr, ...@@ -690,8 +691,8 @@ void testSetFromSocket(const SocketAddress *serverBindAddr,
listenAddrRet->setFromLocalAddress(listenSock); listenAddrRet->setFromLocalAddress(listenSock);
SocketAddress listenPeerAddr; SocketAddress listenPeerAddr;
EXPECT_THROW(listenPeerAddr.setFromPeerAddress(listenSock), EXPECT_THROW(
std::runtime_error); listenPeerAddr.setFromPeerAddress(listenSock), std::runtime_error);
// Note that we use the family from serverBindAddr here, since we allow // Note that we use the family from serverBindAddr here, since we allow
// clientBindAddr to be nullptr. // clientBindAddr to be nullptr.
...@@ -701,21 +702,25 @@ void testSetFromSocket(const SocketAddress *serverBindAddr, ...@@ -701,21 +702,25 @@ void testSetFromSocket(const SocketAddress *serverBindAddr,
sockaddr_storage clientAddr; sockaddr_storage clientAddr;
clientBindAddr->getAddress(&clientAddr); clientBindAddr->getAddress(&clientAddr);
rc = bind(clientSock, reinterpret_cast<sockaddr*>(&clientAddr), rc = bind(
clientBindAddr->getActualSize()); clientSock,
reinterpret_cast<sockaddr*>(&clientAddr),
clientBindAddr->getActualSize());
REQUIRE_ERRNO(rc == 0, "failed to bind to client socket"); REQUIRE_ERRNO(rc == 0, "failed to bind to client socket");
} }
sockaddr_storage listenAddr; sockaddr_storage listenAddr;
listenAddrRet->getAddress(&listenAddr); listenAddrRet->getAddress(&listenAddr);
rc = connect(clientSock, reinterpret_cast<sockaddr*>(&listenAddr), rc = connect(
listenAddrRet->getActualSize()); clientSock,
reinterpret_cast<sockaddr*>(&listenAddr),
listenAddrRet->getActualSize());
REQUIRE_ERRNO(rc == 0, "failed to connect"); REQUIRE_ERRNO(rc == 0, "failed to connect");
sockaddr_storage acceptAddr; sockaddr_storage acceptAddr;
socklen_t acceptAddrLen = sizeof(acceptAddr); socklen_t acceptAddrLen = sizeof(acceptAddr);
int serverSock = accept(listenSock, int serverSock = accept(
reinterpret_cast<sockaddr*>(&acceptAddr), &acceptAddrLen); listenSock, reinterpret_cast<sockaddr*>(&acceptAddr), &acceptAddrLen);
REQUIRE_ERRNO(serverSock > 0, "failed to accept"); REQUIRE_ERRNO(serverSock > 0, "failed to accept");
acceptAddrRet->setFromSockaddr( acceptAddrRet->setFromSockaddr(
reinterpret_cast<sockaddr*>(&acceptAddr), acceptAddrLen); reinterpret_cast<sockaddr*>(&acceptAddr), acceptAddrLen);
...@@ -740,10 +745,15 @@ TEST(SocketAddress, SetFromSocketIPv4) { ...@@ -740,10 +745,15 @@ TEST(SocketAddress, SetFromSocketIPv4) {
SocketAddress clientAddr; SocketAddress clientAddr;
SocketAddress clientPeerAddr; SocketAddress clientPeerAddr;
testSetFromSocket(&serverBindAddr, &clientBindAddr, testSetFromSocket(
&listenAddr, &acceptAddr, &serverBindAddr,
&serverAddr, &serverPeerAddr, &clientBindAddr,
&clientAddr, &clientPeerAddr); &listenAddr,
&acceptAddr,
&serverAddr,
&serverPeerAddr,
&clientAddr,
&clientPeerAddr);
// The server socket's local address should have the same port as the listen // The server socket's local address should have the same port as the listen
// address. The IP will be different, since the listening socket is // address. The IP will be different, since the listening socket is
...@@ -781,10 +791,15 @@ TEST(SocketAddress, SetFromSocketUnixAbstract) { ...@@ -781,10 +791,15 @@ TEST(SocketAddress, SetFromSocketUnixAbstract) {
SocketAddress clientAddr; SocketAddress clientAddr;
SocketAddress clientPeerAddr; SocketAddress clientPeerAddr;
testSetFromSocket(&serverBindAddr, &clientBindAddr, testSetFromSocket(
&listenAddr, &acceptAddr, &serverBindAddr,
&serverAddr, &serverPeerAddr, &clientBindAddr,
&clientAddr, &clientPeerAddr); &listenAddr,
&acceptAddr,
&serverAddr,
&serverPeerAddr,
&clientAddr,
&clientPeerAddr);
// The server socket's local address should be the same as the listen // The server socket's local address should be the same as the listen
// address. // address.
...@@ -820,10 +835,15 @@ TEST(SocketAddress, SetFromSocketUnixExplicit) { ...@@ -820,10 +835,15 @@ TEST(SocketAddress, SetFromSocketUnixExplicit) {
serverBindAddr.setFromPath(serverPath.c_str()); serverBindAddr.setFromPath(serverPath.c_str());
clientBindAddr.setFromPath(clientPath.c_str()); clientBindAddr.setFromPath(clientPath.c_str());
testSetFromSocket(&serverBindAddr, &clientBindAddr, testSetFromSocket(
&listenAddr, &acceptAddr, &serverBindAddr,
&serverAddr, &serverPeerAddr, &clientBindAddr,
&clientAddr, &clientPeerAddr); &listenAddr,
&acceptAddr,
&serverAddr,
&serverPeerAddr,
&clientAddr,
&clientPeerAddr);
} catch (...) { } catch (...) {
// Remove the socket files after we are done // Remove the socket files after we are done
unlink(serverPath.c_str()); unlink(serverPath.c_str());
...@@ -861,10 +881,15 @@ TEST(SocketAddress, SetFromSocketUnixAnonymous) { ...@@ -861,10 +881,15 @@ TEST(SocketAddress, SetFromSocketUnixAnonymous) {
try { try {
serverBindAddr.setFromPath(serverPath.c_str()); serverBindAddr.setFromPath(serverPath.c_str());
testSetFromSocket(&serverBindAddr, nullptr, testSetFromSocket(
&listenAddr, &acceptAddr, &serverBindAddr,
&serverAddr, &serverPeerAddr, nullptr,
&clientAddr, &clientPeerAddr); &listenAddr,
&acceptAddr,
&serverAddr,
&serverPeerAddr,
&clientAddr,
&clientPeerAddr);
} catch (...) { } catch (...) {
// Remove the socket file after we are done // Remove the socket file after we are done
unlink(serverPath.c_str()); unlink(serverPath.c_str());
......
...@@ -47,5 +47,4 @@ bool SocketAddressTestHelper::isFamilyOfAddrEnabled(const char* addr) { ...@@ -47,5 +47,4 @@ bool SocketAddressTestHelper::isFamilyOfAddrEnabled(const char* addr) {
freeaddrinfo(resultsp); freeaddrinfo(resultsp);
return !err; return !err;
} }
} }
...@@ -20,28 +20,25 @@ namespace folly { ...@@ -20,28 +20,25 @@ namespace folly {
class SocketAddressTestHelper { class SocketAddressTestHelper {
public: public:
static constexpr const char* kLoopbackAddrIPv4 = "127.0.0.1"; static constexpr const char* kLoopbackAddrIPv4 = "127.0.0.1";
static constexpr const char* kLoopbackAddrIPv6 = "::1"; static constexpr const char* kLoopbackAddrIPv6 = "::1";
// https://developers.google.com/speed/public-dns/docs/using?hl=en // https://developers.google.com/speed/public-dns/docs/using?hl=en
static constexpr const char* kGooglePublicDnsAName = static constexpr const char* kGooglePublicDnsAName =
"google-public-dns-a.google.com"; "google-public-dns-a.google.com";
static constexpr const char* kGooglePublicDnsBName = static constexpr const char* kGooglePublicDnsBName =
"google-public-dns-b.google.com"; "google-public-dns-b.google.com";
static constexpr const char* kGooglePublicDnsAAddrIPv4 = "8.8.8.8"; static constexpr const char* kGooglePublicDnsAAddrIPv4 = "8.8.8.8";
static constexpr const char* kGooglePublicDnsBAddrIPv4 = "8.8.4.4"; static constexpr const char* kGooglePublicDnsBAddrIPv4 = "8.8.4.4";
static constexpr const char* kGooglePublicDnsAAddrIPv6 = static constexpr const char* kGooglePublicDnsAAddrIPv6 =
"2001:4860:4860::8888"; "2001:4860:4860::8888";
static constexpr const char* kGooglePublicDnsBAddrIPv6 = static constexpr const char* kGooglePublicDnsBAddrIPv6 =
"2001:4860:4860::8844"; "2001:4860:4860::8844";
static bool isIPv4Enabled(); static bool isIPv4Enabled();
static bool isIPv6Enabled(); static bool isIPv6Enabled();
private: private:
static bool isFamilyOfAddrEnabled(const char* addr); static bool isFamilyOfAddrEnabled(const char* addr);
}; };
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment