diff --git a/src/netaddress.cpp b/src/netaddress.cpp index b0b17eec0..18139ede0 100644 --- a/src/netaddress.cpp +++ b/src/netaddress.cpp @@ -1,938 +1,943 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include -#include #include #include -static const uint8_t pchIPv4[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}; -static const uint8_t pchOnionCat[] = {0xFD, 0x87, 0xD8, 0x7E, 0xEB, 0x43}; +#include + +#include +#include +#include +#include +#include -// 0xFD + sha256("bitcoin")[0:5] -static const uint8_t g_internal_prefix[] = {0xFD, 0x6B, 0x88, 0xC0, 0x87, 0x24}; +constexpr size_t CNetAddr::V1_SERIALIZATION_SIZE; /** * Construct an unspecified IPv6 network address (::/128). * * @note This address is considered invalid by CNetAddr::IsValid() */ -CNetAddr::CNetAddr() { - memset(ip, 0, sizeof(ip)); -} +CNetAddr::CNetAddr() {} void CNetAddr::SetIP(const CNetAddr &ipIn) { + // Size check. + switch (ipIn.m_net) { + case NET_IPV4: + assert(ipIn.m_addr.size() == ADDR_IPV4_SIZE); + break; + case NET_IPV6: + assert(ipIn.m_addr.size() == ADDR_IPV6_SIZE); + break; + case NET_ONION: + assert(ipIn.m_addr.size() == ADDR_TORV2_SIZE); + break; + case NET_INTERNAL: + assert(ipIn.m_addr.size() == ADDR_INTERNAL_SIZE); + break; + case NET_UNROUTABLE: + case NET_MAX: + assert(false); + } // no default case, so the compiler can warn about missing cases + m_net = ipIn.m_net; - memcpy(ip, ipIn.ip, sizeof(ip)); + m_addr = ipIn.m_addr; +} + +template +inline bool HasPrefix(const T1 &obj, + const std::array &prefix) { + return obj.size() >= PREFIX_LEN && + std::equal(std::begin(prefix), std::end(prefix), std::begin(obj)); } -void CNetAddr::SetLegacyIPv6(const uint8_t ipv6[16]) { - if (memcmp(ipv6, pchIPv4, sizeof(pchIPv4)) == 0) { +void CNetAddr::SetLegacyIPv6(Span ipv6) { + assert(ipv6.size() == ADDR_IPV6_SIZE); + + size_t skip{0}; + + if (HasPrefix(ipv6, IPV4_IN_IPV6_PREFIX)) { + // IPv4-in-IPv6 m_net = NET_IPV4; - } else if (memcmp(ipv6, pchOnionCat, sizeof(pchOnionCat)) == 0) { + skip = sizeof(IPV4_IN_IPV6_PREFIX); + } else if (HasPrefix(ipv6, TORV2_IN_IPV6_PREFIX)) { + // TORv2-in-IPv6 m_net = NET_ONION; - } else if (memcmp(ipv6, g_internal_prefix, sizeof(g_internal_prefix)) == - 0) { + skip = sizeof(TORV2_IN_IPV6_PREFIX); + } else if (HasPrefix(ipv6, INTERNAL_IN_IPV6_PREFIX)) { + // Internal-in-IPv6 m_net = NET_INTERNAL; + skip = sizeof(INTERNAL_IN_IPV6_PREFIX); } else { + // IPv6 m_net = NET_IPV6; } - memcpy(ip, ipv6, 16); -} -void CNetAddr::SetRaw(Network network, const uint8_t *ip_in) { - switch (network) { - case NET_IPV4: - m_net = NET_IPV4; - memcpy(ip, pchIPv4, 12); - memcpy(ip + 12, ip_in, 4); - break; - case NET_IPV6: - SetLegacyIPv6(ip_in); - break; - default: - assert(!"invalid network"); - } + m_addr.assign(ipv6.begin() + skip, ipv6.end()); } /** - * Try to make this a dummy address that maps the specified name into IPv6 like - * so: (0xFD + %sha256("bitcoin")[0:5]) + %sha256(name)[0:10]. Such dummy - * addresses have a prefix of fd6b:88c0:8724::/48 and are guaranteed to not be - * publicly routable as it falls under RFC4193's fc00::/7 subnet allocated to - * unique-local addresses. - * - * CAddrMan uses these fake addresses to keep track of which DNS seeds were - * used. - * + * Create an "internal" address that represents a name or FQDN. CAddrMan uses + * these fake addresses to keep track of which DNS seeds were used. * @returns Whether or not the operation was successful. - * - * @see CNetAddr::IsInternal(), CNetAddr::IsRFC4193() + * @see NET_INTERNAL, INTERNAL_IN_IPV6_PREFIX, CNetAddr::IsInternal(), + * CNetAddr::IsRFC4193() */ bool CNetAddr::SetInternal(const std::string &name) { if (name.empty()) { return false; } m_net = NET_INTERNAL; uint8_t hash[32] = {}; CSHA256().Write((const uint8_t *)name.data(), name.size()).Finalize(hash); - memcpy(ip, g_internal_prefix, sizeof(g_internal_prefix)); - memcpy(ip + sizeof(g_internal_prefix), hash, - sizeof(ip) - sizeof(g_internal_prefix)); + m_addr.assign(hash, hash + ADDR_INTERNAL_SIZE); return true; } /** - * Try to make this a dummy address that maps the specified onion address into - * IPv6 using OnionCat's range and encoding. Such dummy addresses have a prefix - * of fd87:d87e:eb43::/48 and are guaranteed to not be publicly routable as they - * fall under RFC4193's fc00::/7 subnet allocated to unique-local addresses. + * Parse a TORv2 address and set this object to it. * * @returns Whether or not the operation was successful. * - * @see CNetAddr::IsTor(), CNetAddr::IsRFC4193() + * @see CNetAddr::IsTor() */ bool CNetAddr::SetSpecial(const std::string &strName) { if (strName.size() > 6 && strName.substr(strName.size() - 6, 6) == ".onion") { std::vector vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str()); - if (vchAddr.size() != 16 - sizeof(pchOnionCat)) { + if (vchAddr.size() != ADDR_TORV2_SIZE) { return false; } m_net = NET_ONION; - memcpy(ip, pchOnionCat, sizeof(pchOnionCat)); - for (unsigned int i = 0; i < 16 - sizeof(pchOnionCat); i++) { - ip[i + sizeof(pchOnionCat)] = vchAddr[i]; - } + m_addr.assign(vchAddr.begin(), vchAddr.end()); return true; } return false; } CNetAddr::CNetAddr(const struct in_addr &ipv4Addr) { - SetRaw(NET_IPV4, (const uint8_t *)&ipv4Addr); + m_net = NET_IPV4; + const uint8_t *ptr = reinterpret_cast(&ipv4Addr); + m_addr.assign(ptr, ptr + ADDR_IPV4_SIZE); } CNetAddr::CNetAddr(const struct in6_addr &ipv6Addr, const uint32_t scope) { - SetRaw(NET_IPV6, (const uint8_t *)&ipv6Addr); + SetLegacyIPv6(Span( + reinterpret_cast(&ipv6Addr), sizeof(ipv6Addr))); scopeId = scope; } -unsigned int CNetAddr::GetByte(int n) const { - return ip[15 - n]; -} - bool CNetAddr::IsBindAny() const { - const int cmplen = IsIPv4() ? 4 : 16; - for (int i = 0; i < cmplen; ++i) { - if (GetByte(i)) { - return false; - } + if (!IsIPv4() && !IsIPv6()) { + return false; } - - return true; + return std::all_of(m_addr.begin(), m_addr.end(), + [](uint8_t b) { return b == 0; }); } bool CNetAddr::IsIPv4() const { return m_net == NET_IPV4; } bool CNetAddr::IsIPv6() const { return m_net == NET_IPV6; } bool CNetAddr::IsRFC1918() const { return IsIPv4() && - (GetByte(3) == 10 || (GetByte(3) == 192 && GetByte(2) == 168) || - (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31))); + (m_addr[0] == 10 || (m_addr[0] == 192 && m_addr[1] == 168) || + (m_addr[0] == 172 && m_addr[1] >= 16 && m_addr[1] <= 31)); } bool CNetAddr::IsRFC2544() const { - return IsIPv4() && GetByte(3) == 198 && - (GetByte(2) == 18 || GetByte(2) == 19); + return IsIPv4() && m_addr[0] == 198 && (m_addr[1] == 18 || m_addr[1] == 19); } bool CNetAddr::IsRFC3927() const { - return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254); + return IsIPv4() && HasPrefix(m_addr, std::array{{169, 254}}); } bool CNetAddr::IsRFC6598() const { - return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && - GetByte(2) <= 127; + return IsIPv4() && m_addr[0] == 100 && m_addr[1] >= 64 && m_addr[1] <= 127; } bool CNetAddr::IsRFC5737() const { return IsIPv4() && - ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) || - (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) || - (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113)); + (HasPrefix(m_addr, std::array{{192, 0, 2}}) || + HasPrefix(m_addr, std::array{{198, 51, 100}}) || + HasPrefix(m_addr, std::array{{203, 0, 113}})); } bool CNetAddr::IsRFC3849() const { - return IsIPv6() && GetByte(15) == 0x20 && GetByte(14) == 0x01 && - GetByte(13) == 0x0D && GetByte(12) == 0xB8; + return IsIPv6() && + HasPrefix(m_addr, std::array{{0x20, 0x01, 0x0D, 0xB8}}); } bool CNetAddr::IsRFC3964() const { - return IsIPv6() && GetByte(15) == 0x20 && GetByte(14) == 0x02; + return IsIPv6() && HasPrefix(m_addr, std::array{{0x20, 0x02}}); } bool CNetAddr::IsRFC6052() const { - static const uint8_t pchRFC6052[] = {0, 0x64, 0xFF, 0x9B, 0, 0, - 0, 0, 0, 0, 0, 0}; - return IsIPv6() && memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0; + return IsIPv6() && + HasPrefix(m_addr, std::array{{0x00, 0x64, 0xFF, 0x9B, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00}}); } bool CNetAddr::IsRFC4380() const { - return IsIPv6() && GetByte(15) == 0x20 && GetByte(14) == 0x01 && - GetByte(13) == 0 && GetByte(12) == 0; + return IsIPv6() && + HasPrefix(m_addr, std::array{{0x20, 0x01, 0x00, 0x00}}); } bool CNetAddr::IsRFC4862() const { - static const uint8_t pchRFC4862[] = {0xFE, 0x80, 0, 0, 0, 0, 0, 0}; - return IsIPv6() && memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0; + return IsIPv6() && + HasPrefix(m_addr, std::array{{0xFE, 0x80, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00}}); } bool CNetAddr::IsRFC4193() const { - return IsIPv6() && (GetByte(15) & 0xFE) == 0xFC; + return IsIPv6() && (m_addr[0] & 0xFE) == 0xFC; } bool CNetAddr::IsRFC6145() const { - static const uint8_t pchRFC6145[] = {0, 0, 0, 0, 0, 0, - 0, 0, 0xFF, 0xFF, 0, 0}; - return IsIPv6() && memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0; + return IsIPv6() && + HasPrefix(m_addr, std::array{{0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0xFF, 0xFF, 0x00, 0x00}}); } bool CNetAddr::IsRFC4843() const { - return IsIPv6() && GetByte(15) == 0x20 && GetByte(14) == 0x01 && - GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10; + return IsIPv6() && + HasPrefix(m_addr, std::array{{0x20, 0x01, 0x00}}) && + (m_addr[3] & 0xF0) == 0x10; } bool CNetAddr::IsRFC7343() const { - return IsIPv6() && GetByte(15) == 0x20 && GetByte(14) == 0x01 && - GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x20; + return IsIPv6() && + HasPrefix(m_addr, std::array{{0x20, 0x01, 0x00}}) && + (m_addr[3] & 0xF0) == 0x20; } bool CNetAddr::IsHeNet() const { - return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && - GetByte(12) == 0x70); + return IsIPv6() && + HasPrefix(m_addr, std::array{{0x20, 0x01, 0x04, 0x70}}); } /** * @returns Whether or not this is a dummy address that maps an onion address * into IPv6. * * @see CNetAddr::SetSpecial(const std::string &) */ bool CNetAddr::IsTor() const { return m_net == NET_ONION; } bool CNetAddr::IsLocal() const { // IPv4 loopback (127.0.0.0/8 or 0.0.0.0/8) - if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0)) { + if (IsIPv4() && (m_addr[0] == 127 || m_addr[0] == 0)) { return true; } // IPv6 loopback (::1/128) static const uint8_t pchLocal[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; - if (IsIPv6() && memcmp(ip, pchLocal, 16) == 0) { + if (IsIPv6() && memcmp(m_addr.data(), pchLocal, sizeof(pchLocal)) == 0) { return true; } return false; } /** * @returns Whether or not this network address is a valid address that @a could * be used to refer to an actual host. * * @note A valid address may or may not be publicly routable on the global * internet. As in, the set of valid addresses is a superset of the set of * publicly routable addresses. * * @see CNetAddr::IsRoutable() */ bool CNetAddr::IsValid() const { // Cleanup 3-byte shifted addresses caused by garbage in size field of addr // messages from versions before 0.2.9 checksum. // Two consecutive addr messages look like this: // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 // addr26 addr26... so if the first length field is garbled, it reads the // second batch of addr misaligned by 3 bytes. - if (IsIPv6() && memcmp(ip, pchIPv4 + 3, sizeof(pchIPv4) - 3) == 0) { + if (IsIPv6() && memcmp(m_addr.data(), IPV4_IN_IPV6_PREFIX.data() + 3, + sizeof(IPV4_IN_IPV6_PREFIX) - 3) == 0) { return false; } // unspecified IPv6 address (::/128) uint8_t ipNone6[16] = {}; - if (IsIPv6() && memcmp(ip, ipNone6, 16) == 0) { + if (IsIPv6() && memcmp(m_addr.data(), ipNone6, sizeof(ipNone6)) == 0) { return false; } // documentation IPv6 address if (IsRFC3849()) { return false; } if (IsInternal()) { return false; } if (IsIPv4()) { - // INADDR_NONE - uint32_t ipNone = INADDR_NONE; - if (memcmp(ip + 12, &ipNone, 4) == 0) { - return false; - } - - // 0 - ipNone = 0; - if (memcmp(ip + 12, &ipNone, 4) == 0) { + const uint32_t addr = ReadBE32(m_addr.data()); + if (addr == INADDR_ANY || addr == INADDR_NONE) { return false; } } return true; } /** * @returns Whether or not this network address is publicly routable on the * global internet. * * @note A routable address is always valid. As in, the set of routable * addresses is a subset of the set of valid addresses. * * @see CNetAddr::IsValid() */ bool CNetAddr::IsRoutable() const { return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsRFC7343() || IsLocal() || IsInternal()); } /** - * @returns Whether or not this is a dummy address that maps a name into IPv6. + * @returns Whether or not this is a dummy address that represents a name. * * @see CNetAddr::SetInternal(const std::string &) */ bool CNetAddr::IsInternal() const { return m_net == NET_INTERNAL; } enum Network CNetAddr::GetNetwork() const { if (IsInternal()) { return NET_INTERNAL; } if (!IsRoutable()) { return NET_UNROUTABLE; } return m_net; } std::string CNetAddr::ToStringIP() const { if (IsTor()) { - return EncodeBase32(&ip[6], 10) + ".onion"; + return EncodeBase32(m_addr.data(), m_addr.size()) + ".onion"; } if (IsInternal()) { - return EncodeBase32(ip + sizeof(g_internal_prefix), - sizeof(ip) - sizeof(g_internal_prefix)) + - ".internal"; + return EncodeBase32(m_addr.data(), m_addr.size()) + ".internal"; } CService serv(*this, 0); struct sockaddr_storage sockaddr; socklen_t socklen = sizeof(sockaddr); if (serv.GetSockAddr((struct sockaddr *)&sockaddr, &socklen)) { char name[1025] = ""; if (!getnameinfo((const struct sockaddr *)&sockaddr, socklen, name, sizeof(name), nullptr, 0, NI_NUMERICHOST)) { return std::string(name); } } if (IsIPv4()) { - return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), - GetByte(0)); + return strprintf("%u.%u.%u.%u", m_addr[0], m_addr[1], m_addr[2], + m_addr[3]); } - - return strprintf("%x:%x:%x:%x:%x:%x:%x:%x", GetByte(15) << 8 | GetByte(14), - GetByte(13) << 8 | GetByte(12), - GetByte(11) << 8 | GetByte(10), - GetByte(9) << 8 | GetByte(8), GetByte(7) << 8 | GetByte(6), - GetByte(5) << 8 | GetByte(4), GetByte(3) << 8 | GetByte(2), - GetByte(1) << 8 | GetByte(0)); + assert(IsIPv6()); + return strprintf("%x:%x:%x:%x:%x:%x:%x:%x", m_addr[0] << 8 | m_addr[1], + m_addr[2] << 8 | m_addr[3], m_addr[4] << 8 | m_addr[5], + m_addr[6] << 8 | m_addr[7], m_addr[8] << 8 | m_addr[9], + m_addr[10] << 8 | m_addr[11], m_addr[12] << 8 | m_addr[13], + m_addr[14] << 8 | m_addr[15]); } std::string CNetAddr::ToString() const { return ToStringIP(); } bool operator==(const CNetAddr &a, const CNetAddr &b) { - return a.m_net == b.m_net && memcmp(a.ip, b.ip, 16) == 0; + return a.m_net == b.m_net && a.m_addr == b.m_addr; } bool operator<(const CNetAddr &a, const CNetAddr &b) { - return a.m_net < b.m_net || - (a.m_net == b.m_net && memcmp(a.ip, b.ip, 16) < 0); + return std::tie(a.m_net, a.m_addr) < std::tie(b.m_net, b.m_addr); } /** * Try to get our IPv4 address. * * @param[out] pipv4Addr The in_addr struct to which to copy. * * @returns Whether or not the operation was successful, in particular, whether * or not our address was an IPv4 address. * * @see CNetAddr::IsIPv4() */ bool CNetAddr::GetInAddr(struct in_addr *pipv4Addr) const { if (!IsIPv4()) { return false; } - memcpy(pipv4Addr, ip + 12, 4); + assert(sizeof(*pipv4Addr) == m_addr.size()); + memcpy(pipv4Addr, m_addr.data(), m_addr.size()); return true; } /** * Try to get our IPv6 address. * * @param[out] pipv6Addr The in6_addr struct to which to copy. * * @returns Whether or not the operation was successful, in particular, whether * or not our address was an IPv6 address. * * @see CNetAddr::IsIPv6() */ bool CNetAddr::GetIn6Addr(struct in6_addr *pipv6Addr) const { if (!IsIPv6()) { return false; } - memcpy(pipv6Addr, ip, 16); + assert(sizeof(*pipv6Addr) == m_addr.size()); + memcpy(pipv6Addr, m_addr.data(), m_addr.size()); return true; } bool CNetAddr::HasLinkedIPv4() const { return IsRoutable() && (IsIPv4() || IsRFC6145() || IsRFC6052() || IsRFC3964() || IsRFC4380()); } uint32_t CNetAddr::GetLinkedIPv4() const { - if (IsIPv4() || IsRFC6145() || IsRFC6052()) { - // IPv4, mapped IPv4, SIIT translated IPv4: the IPv4 address is the last - // 4 bytes of the address - return ReadBE32(ip + 12); + if (IsIPv4()) { + return ReadBE32(m_addr.data()); + } else if (IsRFC6052() || IsRFC6145()) { + // mapped IPv4, SIIT translated IPv4: the IPv4 address is the last 4 + // bytes of the address + return ReadBE32(MakeSpan(m_addr).last(ADDR_IPV4_SIZE).data()); } else if (IsRFC3964()) { // 6to4 tunneled IPv4: the IPv4 address is in bytes 2-6 - return ReadBE32(ip + 2); + return ReadBE32(MakeSpan(m_addr).subspan(2, ADDR_IPV4_SIZE).data()); } else if (IsRFC4380()) { // Teredo tunneled IPv4: the IPv4 address is in the last 4 bytes of the // address, but bitflipped - return ~ReadBE32(ip + 12); + return ~ReadBE32(MakeSpan(m_addr).last(ADDR_IPV4_SIZE).data()); } assert(false); } uint32_t CNetAddr::GetNetClass() const { uint32_t net_class = NET_IPV6; if (IsLocal()) { net_class = 255; } if (IsInternal()) { net_class = NET_INTERNAL; } else if (!IsRoutable()) { net_class = NET_UNROUTABLE; } else if (HasLinkedIPv4()) { net_class = NET_IPV4; } else if (IsTor()) { net_class = NET_ONION; } return net_class; } uint32_t CNetAddr::GetMappedAS(const std::vector &asmap) const { uint32_t net_class = GetNetClass(); if (asmap.size() == 0 || (net_class != NET_IPV4 && net_class != NET_IPV6)) { return 0; // Indicates not found, safe because AS0 is reserved per // RFC7607. } std::vector ip_bits(128); if (HasLinkedIPv4()) { - // For lookup, treat as if it was just an IPv4 address (pchIPv4 prefix + - // IPv4 bits) + // For lookup, treat as if it was just an IPv4 address + // (IPV4_IN_IPV6_PREFIX + IPv4 bits) for (int8_t byte_i = 0; byte_i < 12; ++byte_i) { for (uint8_t bit_i = 0; bit_i < 8; ++bit_i) { ip_bits[byte_i * 8 + bit_i] = - (pchIPv4[byte_i] >> (7 - bit_i)) & 1; + (IPV4_IN_IPV6_PREFIX[byte_i] >> (7 - bit_i)) & 1; } } uint32_t ipv4 = GetLinkedIPv4(); for (int i = 0; i < 32; ++i) { ip_bits[96 + i] = (ipv4 >> (31 - i)) & 1; } } else { // Use all 128 bits of the IPv6 address otherwise + assert(IsIPv6()); for (int8_t byte_i = 0; byte_i < 16; ++byte_i) { - uint8_t cur_byte = GetByte(15 - byte_i); + uint8_t cur_byte = m_addr[byte_i]; for (uint8_t bit_i = 0; bit_i < 8; ++bit_i) { ip_bits[byte_i * 8 + bit_i] = (cur_byte >> (7 - bit_i)) & 1; } } } uint32_t mapped_as = Interpret(asmap, ip_bits); return mapped_as; } /** * Get the canonical identifier of our network group * * The groups are assigned in a way where it should be costly for an attacker to * obtain addresses with many different group identifiers, even if it is cheap * to obtain addresses with the same identifier. * * @note No two connections will be attempted to addresses with the same network * group. */ std::vector CNetAddr::GetGroup(const std::vector &asmap) const { std::vector vchRet; uint32_t net_class = GetNetClass(); // If non-empty asmap is supplied and the address is IPv4/IPv6, // return ASN to be used for bucketing. uint32_t asn = GetMappedAS(asmap); if (asn != 0) { // Either asmap was empty, or address has non-asmappable net // class (e.g. TOR). vchRet.push_back(NET_IPV6); // IPv4 and IPv6 with same ASN should be in // the same bucket for (int i = 0; i < 4; i++) { vchRet.push_back((asn >> (8 * i)) & 0xFF); } return vchRet; } vchRet.push_back(net_class); - int nStartByte = 0; - int nBits = 16; + int nBits{0}; if (IsLocal()) { // all local addresses belong to the same group - nBits = 0; } else if (IsInternal()) { // all internal-usage addresses get their own group - nStartByte = sizeof(g_internal_prefix); - nBits = (sizeof(ip) - sizeof(g_internal_prefix)) * 8; + nBits = ADDR_INTERNAL_SIZE * 8; } else if (!IsRoutable()) { // all other unroutable addresses belong to the same group - nBits = 0; } else if (HasLinkedIPv4()) { // IPv4 addresses (and mapped IPv4 addresses) use /16 groups uint32_t ipv4 = GetLinkedIPv4(); vchRet.push_back((ipv4 >> 24) & 0xFF); vchRet.push_back((ipv4 >> 16) & 0xFF); return vchRet; } else if (IsTor()) { - nStartByte = 6; nBits = 4; } else if (IsHeNet()) { // for he.net, use /36 groups nBits = 36; } else { // for the rest of the IPv6 network, use /32 groups nBits = 32; } - // push our ip onto vchRet byte by byte... - while (nBits >= 8) { - vchRet.push_back(GetByte(15 - nStartByte)); - nStartByte++; - nBits -= 8; - } + // Push our address onto vchRet. + const size_t num_bytes = nBits / 8; + vchRet.insert(vchRet.end(), m_addr.begin(), m_addr.begin() + num_bytes); + nBits %= 8; // ...for the last byte, push nBits and for the rest of the byte push 1's if (nBits > 0) { - vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1)); + assert(num_bytes < m_addr.size()); + vchRet.push_back(m_addr[num_bytes] | ((1 << (8 - nBits)) - 1)); } return vchRet; } +std::vector CNetAddr::GetAddrBytes() const { + uint8_t serialized[V1_SERIALIZATION_SIZE]; + SerializeV1Array(serialized); + return {std::begin(serialized), std::end(serialized)}; +} + uint64_t CNetAddr::GetHash() const { - uint256 hash = Hash(ip); + uint256 hash = Hash(m_addr); uint64_t nRet; memcpy(&nRet, &hash, sizeof(nRet)); return nRet; } // private extensions to enum Network, only returned by GetExtNetwork, and only // used in GetReachabilityFrom static const int NET_UNKNOWN = NET_MAX + 0; static const int NET_TEREDO = NET_MAX + 1; static int GetExtNetwork(const CNetAddr *addr) { if (addr == nullptr) { return NET_UNKNOWN; } if (addr->IsRFC4380()) { return NET_TEREDO; } return addr->GetNetwork(); } /** Calculates a metric for how reachable (*this) is from a given partner */ int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const { enum Reachability { REACH_UNREACHABLE, REACH_DEFAULT, REACH_TEREDO, REACH_IPV6_WEAK, REACH_IPV4, REACH_IPV6_STRONG, REACH_PRIVATE }; if (!IsRoutable() || IsInternal()) { return REACH_UNREACHABLE; } int ourNet = GetExtNetwork(this); int theirNet = GetExtNetwork(paddrPartner); bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145(); switch (theirNet) { case NET_IPV4: switch (ourNet) { default: return REACH_DEFAULT; case NET_IPV4: return REACH_IPV4; } case NET_IPV6: switch (ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV4: return REACH_IPV4; // only prefer giving our IPv6 address if it's not tunnelled case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; } case NET_ONION: switch (ourNet) { default: return REACH_DEFAULT; // Tor users can connect to IPv4 as well case NET_IPV4: return REACH_IPV4; case NET_ONION: return REACH_PRIVATE; } case NET_TEREDO: switch (ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV6: return REACH_IPV6_WEAK; case NET_IPV4: return REACH_IPV4; } case NET_UNKNOWN: case NET_UNROUTABLE: default: switch (ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV6: return REACH_IPV6_WEAK; case NET_IPV4: return REACH_IPV4; // either from Tor, or don't care about our address case NET_ONION: return REACH_PRIVATE; } } } CService::CService() : port(0) {} CService::CService(const CNetAddr &cip, unsigned short portIn) : CNetAddr(cip), port(portIn) {} CService::CService(const struct in_addr &ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn) {} CService::CService(const struct in6_addr &ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn) {} CService::CService(const struct sockaddr_in &addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port)) { assert(addr.sin_family == AF_INET); } CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr, addr.sin6_scope_id), port(ntohs(addr.sin6_port)) { assert(addr.sin6_family == AF_INET6); } bool CService::SetSockAddr(const struct sockaddr *paddr) { switch (paddr->sa_family) { case AF_INET: *this = CService(*reinterpret_cast(paddr)); return true; case AF_INET6: *this = CService(*reinterpret_cast(paddr)); return true; default: return false; } } unsigned short CService::GetPort() const { return port; } bool operator==(const CService &a, const CService &b) { return static_cast(a) == static_cast(b) && a.port == b.port; } bool operator<(const CService &a, const CService &b) { return static_cast(a) < static_cast(b) || (static_cast(a) == static_cast(b) && a.port < b.port); } /** * Obtain the IPv4/6 socket address this represents. * * @param[out] paddr The obtained socket address. * @param[in,out] addrlen The size, in bytes, of the address structure pointed * to by paddr. The value that's pointed to by this * parameter might change after calling this function if * the size of the corresponding address structure * changed. * * @returns Whether or not the operation was successful. */ bool CService::GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const { if (IsIPv4()) { if (*addrlen < (socklen_t)sizeof(struct sockaddr_in)) { return false; } *addrlen = sizeof(struct sockaddr_in); struct sockaddr_in *paddrin = reinterpret_cast(paddr); memset(paddrin, 0, *addrlen); if (!GetInAddr(&paddrin->sin_addr)) { return false; } paddrin->sin_family = AF_INET; paddrin->sin_port = htons(port); return true; } if (IsIPv6()) { if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6)) { return false; } *addrlen = sizeof(struct sockaddr_in6); struct sockaddr_in6 *paddrin6 = reinterpret_cast(paddr); memset(paddrin6, 0, *addrlen); if (!GetIn6Addr(&paddrin6->sin6_addr)) { return false; } paddrin6->sin6_scope_id = scopeId; paddrin6->sin6_family = AF_INET6; paddrin6->sin6_port = htons(port); return true; } return false; } /** * @returns An identifier unique to this service's address and port number. */ std::vector CService::GetKey() const { auto key = GetAddrBytes(); // most significant byte of our port key.push_back(port / 0x100); // least significant byte of our port key.push_back(port & 0x0FF); return key; } std::string CService::ToStringPort() const { return strprintf("%u", port); } std::string CService::ToStringIPPort() const { if (IsIPv4() || IsTor() || IsInternal()) { return ToStringIP() + ":" + ToStringPort(); } else { return "[" + ToStringIP() + "]:" + ToStringPort(); } } std::string CService::ToString() const { return ToStringIPPort(); } CSubNet::CSubNet() : valid(false) { memset(netmask, 0, sizeof(netmask)); } -CSubNet::CSubNet(const CNetAddr &addr, int32_t mask) { - valid = true; - network = addr; - // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address - memset(netmask, 255, sizeof(netmask)); - - // IPv4 addresses start at offset 12, and first 12 bytes must match, so just - // offset n - const int astartofs = network.IsIPv4() ? 12 : 0; - - // Only valid if in range of bits of address - int32_t n = mask; - if (n >= 0 && n <= (128 - astartofs * 8)) { - n += astartofs * 8; - // Clear bits [n..127] - for (; n < 128; ++n) { - netmask[n >> 3] &= ~(1 << (7 - (n & 7))); - } - } else { - valid = false; +CSubNet::CSubNet(const CNetAddr &addr, uint8_t mask) : CSubNet() { + valid = (addr.IsIPv4() && mask <= ADDR_IPV4_SIZE * 8) || + (addr.IsIPv6() && mask <= ADDR_IPV6_SIZE * 8); + if (!valid) { + return; } - // Normalize network according to netmask - for (int x = 0; x < 16; ++x) { - network.ip[x] &= netmask[x]; + assert(mask <= sizeof(netmask) * 8); + + network = addr; + + uint8_t n = mask; + for (size_t i = 0; i < network.m_addr.size(); ++i) { + const uint8_t bits = n < 8 ? n : 8; + // Set first bits. + netmask[i] = (uint8_t)((uint8_t)0xFF << (8 - bits)); + // Normalize network according to netmask. + network.m_addr[i] &= netmask[i]; + n -= bits; } } /** * @returns The number of 1-bits in the prefix of the specified subnet mask. If * the specified subnet mask is not a valid one, -1. */ static inline int NetmaskBits(uint8_t x) { switch (x) { case 0x00: return 0; case 0x80: return 1; case 0xc0: return 2; case 0xe0: return 3; case 0xf0: return 4; case 0xf8: return 5; case 0xfc: return 6; case 0xfe: return 7; case 0xff: return 8; default: return -1; } } -CSubNet::CSubNet(const CNetAddr &addr, const CNetAddr &mask) { - valid = true; +CSubNet::CSubNet(const CNetAddr &addr, const CNetAddr &mask) : CSubNet() { + valid = (addr.IsIPv4() || addr.IsIPv6()) && addr.m_net == mask.m_net; + if (!valid) { + return; + } // Check if `mask` contains 1-bits after 0-bits (which is an invalid // netmask). bool zeros_found = false; - for (size_t i = mask.IsIPv4() ? 12 : 0; i < sizeof(mask.ip); ++i) { - const int num_bits = NetmaskBits(mask.ip[i]); + for (auto b : mask.m_addr) { + const int num_bits = NetmaskBits(b); if (num_bits == -1 || (zeros_found && num_bits != 0)) { valid = false; return; } if (num_bits < 8) { zeros_found = true; } } - network = addr; - // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address - memset(netmask, 255, sizeof(netmask)); - // IPv4 addresses start at offset 12, and first 12 bytes must match, so just - // offset n - const int astartofs = network.IsIPv4() ? 12 : 0; + assert(mask.m_addr.size() <= sizeof(netmask)); - for (int x = astartofs; x < 16; ++x) { - netmask[x] = mask.ip[x]; - } + memcpy(netmask, mask.m_addr.data(), mask.m_addr.size()); + + network = addr; // Normalize network according to netmask - for (int x = 0; x < 16; ++x) { - network.ip[x] &= netmask[x]; + for (size_t x = 0; x < network.m_addr.size(); ++x) { + network.m_addr[x] &= netmask[x]; } } -CSubNet::CSubNet(const CNetAddr &addr) : valid(addr.IsValid()) { - memset(netmask, 255, sizeof(netmask)); +CSubNet::CSubNet(const CNetAddr &addr) : CSubNet() { + valid = addr.IsIPv4() || addr.IsIPv6(); + if (!valid) { + return; + } + + assert(addr.m_addr.size() <= sizeof(netmask)); + + memset(netmask, 0xFF, addr.m_addr.size()); + network = addr; } /** * @returns True if this subnet is valid, the specified address is valid, and * the specified address belongs in this subnet. */ bool CSubNet::Match(const CNetAddr &addr) const { if (!valid || !addr.IsValid() || network.m_net != addr.m_net) { return false; } - for (int x = 0; x < 16; ++x) { - if ((addr.ip[x] & netmask[x]) != network.ip[x]) { + assert(network.m_addr.size() == addr.m_addr.size()); + for (size_t x = 0; x < addr.m_addr.size(); ++x) { + if ((addr.m_addr[x] & netmask[x]) != network.m_addr[x]) { return false; } } return true; } std::string CSubNet::ToString() const { + assert(network.m_addr.size() <= sizeof(netmask)); + uint8_t cidr = 0; - for (size_t i = network.IsIPv4() ? 12 : 0; i < sizeof(netmask); ++i) { + for (size_t i = 0; i < network.m_addr.size(); ++i) { if (netmask[i] == 0x00) { break; } cidr += NetmaskBits(netmask[i]); } return network.ToString() + strprintf("/%u", cidr); } bool CSubNet::IsValid() const { return valid; } bool operator==(const CSubNet &a, const CSubNet &b) { return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16); } bool operator<(const CSubNet &a, const CSubNet &b) { return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0)); } bool SanityCheckASMap(const std::vector &asmap) { // For IP address lookups, the input is 128 bits return SanityCheckASMap(asmap, 128); } diff --git a/src/netaddress.h b/src/netaddress.h index 55680bcea..67a202b4e 100644 --- a/src/netaddress.h +++ b/src/netaddress.h @@ -1,255 +1,358 @@ // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_NETADDRESS_H #define BITCOIN_NETADDRESS_H #if defined(HAVE_CONFIG_H) #include #endif +#include #include +#include #include +#include #include #include #include /** * A network type. * @note An address may belong to more than one network, for example `10.0.0.1` * belongs to both `NET_UNROUTABLE` and `NET_IPV4`. * Keep these sequential starting from 0 and `NET_MAX` as the last entry. * We have loops like `for (int i = 0; i < NET_MAX; i++)` that expect to iterate * over all enum values and also `GetExtNetwork()` "extends" this enum by * introducing standalone constants starting from `NET_MAX`. */ enum Network { /// Addresses from these networks are not publicly routable on the global /// Internet. NET_UNROUTABLE = 0, /// IPv4 NET_IPV4, /// IPv6 NET_IPV6, /// TORv2 NET_ONION, - /// A set of dummy addresses that map a name to an IPv6 address. These - /// addresses belong to RFC4193's fc00::/7 subnet (unique-local addresses). - /// We use them to map a string or FQDN to an IPv6 address in CAddrMan to - /// keep track of which DNS seeds were used. + /// A set of addresses that represent the hash of a string or FQDN. We use + /// them in CAddrMan to keep track of which DNS seeds were used. NET_INTERNAL, /// Dummy value to indicate the number of NET_* constants. NET_MAX, }; +/// Prefix of an IPv6 address when it contains an embedded IPv4 address. +/// Used when (un)serializing addresses in ADDRv1 format (pre-BIP155). +static const std::array IPV4_IN_IPV6_PREFIX{ + {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF}}; + +/// Prefix of an IPv6 address when it contains an embedded TORv2 address. +/// Used when (un)serializing addresses in ADDRv1 format (pre-BIP155). +/// Such dummy IPv6 addresses are guaranteed to not be publicly routable as they +/// fall under RFC4193's fc00::/7 subnet allocated to unique-local addresses. +static const std::array TORV2_IN_IPV6_PREFIX{ + {0xFD, 0x87, 0xD8, 0x7E, 0xEB, 0x43}}; + +/// Prefix of an IPv6 address when it contains an embedded "internal" address. +/// Used when (un)serializing addresses in ADDRv1 format (pre-BIP155). +/// The prefix comes from 0xFD + SHA256("bitcoin")[0:5]. +/// Such dummy IPv6 addresses are guaranteed to not be publicly routable as they +/// fall under RFC4193's fc00::/7 subnet allocated to unique-local addresses. +static const std::array INTERNAL_IN_IPV6_PREFIX{ + // 0xFD + sha256("bitcoin")[0:5]. + {0xFD, 0x6B, 0x88, 0xC0, 0x87, 0x24}}; + +/// Size of IPv4 address (in bytes). +static constexpr size_t ADDR_IPV4_SIZE = 4; + +/// Size of IPv6 address (in bytes). +static constexpr size_t ADDR_IPV6_SIZE = 16; + +/// Size of TORv2 address (in bytes). +static constexpr size_t ADDR_TORV2_SIZE = 10; + +/// Size of "internal" (NET_INTERNAL) address (in bytes). +static constexpr size_t ADDR_INTERNAL_SIZE = 10; + /** * Network address. */ class CNetAddr { protected: + /** + * Raw representation of the network address. + * In network byte order (big endian) for IPv4 and IPv6. + */ + prevector m_addr{ADDR_IPV6_SIZE, 0x0}; + /** * Network to which this address belongs. */ Network m_net{NET_IPV6}; - // in network byte order - uint8_t ip[16]; // for scoped/link-local ipv6 addresses uint32_t scopeId{0}; public: CNetAddr(); explicit CNetAddr(const struct in_addr &ipv4Addr); void SetIP(const CNetAddr &ip); /** * Set from a legacy IPv6 address. * Legacy IPv6 address may be a normal IPv6 address, or another address * (e.g. IPv4) disguised as IPv6. This encoding is used in the legacy * `addr` encoding. */ - void SetLegacyIPv6(const uint8_t ipv6[16]); - - /** - * Set raw IPv4 or IPv6 address (in network byte order) - * @note Only NET_IPV4 and NET_IPV6 are allowed for network. - */ - void SetRaw(Network network, const uint8_t *data); + void SetLegacyIPv6(Span ipv6); bool SetInternal(const std::string &name); // for Tor addresses bool SetSpecial(const std::string &strName); // INADDR_ANY equivalent bool IsBindAny() const; // IPv4 mapped address (::FFFF:0:0/96, 0.0.0.0/0) bool IsIPv4() const; // IPv6 address (not mapped IPv4, not Tor) bool IsIPv6() const; // IPv4 private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12) bool IsRFC1918() const; // IPv4 inter-network communications (198.18.0.0/15) bool IsRFC2544() const; // IPv4 ISP-level NAT (100.64.0.0/10) bool IsRFC6598() const; // IPv4 documentation addresses (192.0.2.0/24, 198.51.100.0/24, // 203.0.113.0/24) bool IsRFC5737() const; // IPv6 documentation address (2001:0DB8::/32) bool IsRFC3849() const; // IPv4 autoconfig (169.254.0.0/16) bool IsRFC3927() const; // IPv6 6to4 tunnelling (2002::/16) bool IsRFC3964() const; // IPv6 unique local (FC00::/7) bool IsRFC4193() const; // IPv6 Teredo tunnelling (2001::/32) bool IsRFC4380() const; // IPv6 ORCHID (deprecated) (2001:10::/28) bool IsRFC4843() const; // IPv6 ORCHIDv2 (2001:20::/28) bool IsRFC7343() const; // IPv6 autoconfig (FE80::/64) bool IsRFC4862() const; // IPv6 well-known prefix for IPv4-embedded address (64:FF9B::/96) bool IsRFC6052() const; // IPv6 IPv4-translated address (::FFFF:0:0:0/96) (actually defined in // RFC2765) bool IsRFC6145() const; // IPv6 Hurricane Electric - https://he.net (2001:0470::/36) bool IsHeNet() const; bool IsTor() const; bool IsLocal() const; bool IsRoutable() const; bool IsInternal() const; bool IsValid() const; enum Network GetNetwork() const; std::string ToString() const; std::string ToStringIP() const; - unsigned int GetByte(int n) const; uint64_t GetHash() const; bool GetInAddr(struct in_addr *pipv4Addr) const; uint32_t GetNetClass() const; //! For IPv4, mapped IPv4, SIIT translated IPv4, Teredo, 6to4 tunneled //! addresses, return the relevant IPv4 address as a uint32. uint32_t GetLinkedIPv4() const; //! Whether this address has a linked IPv4 address (see GetLinkedIPv4()). bool HasLinkedIPv4() const; // The AS on the BGP path to the node we use to diversify // peers in AddrMan bucketing based on the AS infrastructure. // The ip->AS mapping depends on how asmap is constructed. uint32_t GetMappedAS(const std::vector &asmap) const; std::vector GetGroup(const std::vector &asmap) const; - std::vector GetAddrBytes() const { - return {std::begin(ip), std::end(ip)}; - } + std::vector GetAddrBytes() const; int GetReachabilityFrom(const CNetAddr *paddrPartner = nullptr) const; explicit CNetAddr(const struct in6_addr &pipv6Addr, const uint32_t scope = 0); bool GetIn6Addr(struct in6_addr *pipv6Addr) const; friend bool operator==(const CNetAddr &a, const CNetAddr &b); friend bool operator!=(const CNetAddr &a, const CNetAddr &b) { return !(a == b); } friend bool operator<(const CNetAddr &a, const CNetAddr &b); /** * Serialize to a stream. */ - template void Serialize(Stream &s) const { s << ip; } + template void Serialize(Stream &s) const { + SerializeV1Stream(s); + } /** * Unserialize from a stream. */ template void Unserialize(Stream &s) { - uint8_t ip_temp[sizeof(ip)]; - s >> ip_temp; + UnserializeV1Stream(s); + } + + friend class CSubNet; + +private: + /** + * Size of CNetAddr when serialized as ADDRv1 (pre-BIP155) (in bytes). + */ + static constexpr size_t V1_SERIALIZATION_SIZE = ADDR_IPV6_SIZE; + + /** + * Serialize in pre-ADDRv2/BIP155 format to an array. + * Some addresses (e.g. TORv3) cannot be serialized in pre-BIP155 format. + */ + void SerializeV1Array(uint8_t (&arr)[V1_SERIALIZATION_SIZE]) const { + size_t prefix_size; + + switch (m_net) { + case NET_IPV6: + assert(m_addr.size() == sizeof(arr)); + memcpy(arr, m_addr.data(), m_addr.size()); + return; + case NET_IPV4: + prefix_size = sizeof(IPV4_IN_IPV6_PREFIX); + assert(prefix_size + m_addr.size() == sizeof(arr)); + memcpy(arr, IPV4_IN_IPV6_PREFIX.data(), prefix_size); + memcpy(arr + prefix_size, m_addr.data(), m_addr.size()); + return; + case NET_ONION: + prefix_size = sizeof(TORV2_IN_IPV6_PREFIX); + assert(prefix_size + m_addr.size() == sizeof(arr)); + memcpy(arr, TORV2_IN_IPV6_PREFIX.data(), prefix_size); + memcpy(arr + prefix_size, m_addr.data(), m_addr.size()); + return; + case NET_INTERNAL: + prefix_size = sizeof(INTERNAL_IN_IPV6_PREFIX); + assert(prefix_size + m_addr.size() == sizeof(arr)); + memcpy(arr, INTERNAL_IN_IPV6_PREFIX.data(), prefix_size); + memcpy(arr + prefix_size, m_addr.data(), m_addr.size()); + return; + case NET_UNROUTABLE: + case NET_MAX: + assert(false); + } // no default case, so the compiler can warn about missing cases + + assert(false); + } + + /** + * Serialize in pre-ADDRv2/BIP155 format to a stream. + * Some addresses (e.g. TORv3) cannot be serialized in pre-BIP155 format. + */ + template void SerializeV1Stream(Stream &s) const { + uint8_t serialized[V1_SERIALIZATION_SIZE]; + + SerializeV1Array(serialized); + + s << serialized; + } + + /** + * Unserialize from a pre-ADDRv2/BIP155 format from an array. + */ + void UnserializeV1Array(uint8_t (&arr)[V1_SERIALIZATION_SIZE]) { // Use SetLegacyIPv6() so that m_net is set correctly. For example // ::FFFF:0102:0304 should be set as m_net=NET_IPV4 (1.2.3.4). - SetLegacyIPv6(ip_temp); + SetLegacyIPv6(arr); } - friend class CSubNet; + /** + * Unserialize from a pre-ADDRv2/BIP155 format from a stream. + */ + template void UnserializeV1Stream(Stream &s) { + uint8_t serialized[V1_SERIALIZATION_SIZE]; + + s >> serialized; + + UnserializeV1Array(serialized); + } }; class CSubNet { protected: /// Network (base) address CNetAddr network; /// Netmask, in network byte order uint8_t netmask[16]; /// Is this value valid? (only used to signal parse errors) bool valid; public: CSubNet(); - CSubNet(const CNetAddr &addr, int32_t mask); + CSubNet(const CNetAddr &addr, uint8_t mask); CSubNet(const CNetAddr &addr, const CNetAddr &mask); // constructor for single ip subnet (/32 or /128) explicit CSubNet(const CNetAddr &addr); bool Match(const CNetAddr &addr) const; std::string ToString() const; bool IsValid() const; friend bool operator==(const CSubNet &a, const CSubNet &b); friend bool operator!=(const CSubNet &a, const CSubNet &b) { return !(a == b); } friend bool operator<(const CSubNet &a, const CSubNet &b); SERIALIZE_METHODS(CSubNet, obj) { READWRITE(obj.network, obj.netmask, obj.valid); } }; /** A combination of a network address (CNetAddr) and a (TCP) port */ class CService : public CNetAddr { protected: // host order uint16_t port; public: CService(); CService(const CNetAddr &ip, unsigned short port); CService(const struct in_addr &ipv4Addr, unsigned short port); explicit CService(const struct sockaddr_in &addr); unsigned short GetPort() const; bool GetSockAddr(struct sockaddr *paddr, socklen_t *addrlen) const; bool SetSockAddr(const struct sockaddr *paddr); friend bool operator==(const CService &a, const CService &b); friend bool operator!=(const CService &a, const CService &b) { return !(a == b); } friend bool operator<(const CService &a, const CService &b); std::vector GetKey() const; std::string ToString() const; std::string ToStringPort() const; std::string ToStringIPPort() const; CService(const struct in6_addr &ipv6Addr, unsigned short port); explicit CService(const struct sockaddr_in6 &addr); SERIALIZE_METHODS(CService, obj) { READWRITEAS(CNetAddr, obj); READWRITE(Using>(obj.port)); } }; bool SanityCheckASMap(const std::vector &asmap); #endif // BITCOIN_NETADDRESS_H diff --git a/src/netbase.cpp b/src/netbase.cpp index b5ad6ab89..65df37f45 100644 --- a/src/netbase.cpp +++ b/src/netbase.cpp @@ -1,1014 +1,1014 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include #ifndef WIN32 #include #endif #ifdef USE_POLL #include #endif #if !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // Settings static RecursiveMutex cs_proxyInfos; static proxyType proxyInfo[NET_MAX] GUARDED_BY(cs_proxyInfos); static proxyType nameProxy GUARDED_BY(cs_proxyInfos); int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; bool fNameLookup = DEFAULT_NAME_LOOKUP; // Need ample time for negotiation for very slow proxies such as Tor // (milliseconds) static const int SOCKS5_RECV_TIMEOUT = 20 * 1000; static std::atomic interruptSocks5Recv(false); enum Network ParseNetwork(const std::string &net_in) { std::string net = ToLower(net_in); if (net == "ipv4") { return NET_IPV4; } if (net == "ipv6") { return NET_IPV6; } if (net == "onion") { return NET_ONION; } if (net == "tor") { LogPrintf("Warning: net name 'tor' is deprecated and will be removed " "in the future. You should use 'onion' instead.\n"); return NET_ONION; } return NET_UNROUTABLE; } std::string GetNetworkName(enum Network net) { switch (net) { case NET_IPV4: return "ipv4"; case NET_IPV6: return "ipv6"; case NET_ONION: return "onion"; default: return ""; } } static bool LookupIntern(const std::string &name, std::vector &vIP, unsigned int nMaxSolutions, bool fAllowLookup) { vIP.clear(); if (!ValidAsCString(name)) { return false; } { CNetAddr addr; // From our perspective, onion addresses are not hostnames but rather // direct encodings of CNetAddr much like IPv4 dotted-decimal notation // or IPv6 colon-separated hextet notation. Since we can't use // getaddrinfo to decode them and it wouldn't make sense to resolve // them, we return a network address representing it instead. See // CNetAddr::SetSpecial(const std::string&) for more details. if (addr.SetSpecial(name)) { vIP.push_back(addr); return true; } } struct addrinfo aiHint; memset(&aiHint, 0, sizeof(struct addrinfo)); // We want a TCP port, which is a streaming socket type aiHint.ai_socktype = SOCK_STREAM; aiHint.ai_protocol = IPPROTO_TCP; // We don't care which address family (IPv4 or IPv6) is returned aiHint.ai_family = AF_UNSPEC; // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only // return addresses whose family we have an address configured for. // // If we don't allow lookups, then use the AI_NUMERICHOST flag for // getaddrinfo to only decode numerical network addresses and suppress // hostname lookups. aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST; struct addrinfo *aiRes = nullptr; int nErr = getaddrinfo(name.c_str(), nullptr, &aiHint, &aiRes); if (nErr) { return false; } // Traverse the linked list starting with aiTrav, add all non-internal // IPv4,v6 addresses to vIP while respecting nMaxSolutions. struct addrinfo *aiTrav = aiRes; while (aiTrav != nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) { CNetAddr resolved; if (aiTrav->ai_family == AF_INET) { assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in)); resolved = CNetAddr(reinterpret_cast(aiTrav->ai_addr) ->sin_addr); } if (aiTrav->ai_family == AF_INET6) { assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6)); struct sockaddr_in6 *s6 = reinterpret_cast(aiTrav->ai_addr); resolved = CNetAddr(s6->sin6_addr, s6->sin6_scope_id); } // Never allow resolving to an internal address. Consider any such // result invalid. if (!resolved.IsInternal()) { vIP.push_back(resolved); } aiTrav = aiTrav->ai_next; } freeaddrinfo(aiRes); return (vIP.size() > 0); } /** * Resolve a host string to its corresponding network addresses. * * @param name The string representing a host. Could be a name or a numerical * IP address (IPv6 addresses in their bracketed form are * allowed). * @param[out] vIP The resulting network addresses to which the specified host * string resolved. * * @returns Whether or not the specified host string successfully resolved to * any resulting network addresses. * * @see Lookup(const char *, std::vector&, int, bool, unsigned int) * for additional parameter descriptions. */ bool LookupHost(const std::string &name, std::vector &vIP, unsigned int nMaxSolutions, bool fAllowLookup) { if (!ValidAsCString(name)) { return false; } std::string strHost = name; if (strHost.empty()) { return false; } if (strHost.front() == '[' && strHost.back() == ']') { strHost = strHost.substr(1, strHost.size() - 2); } return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup); } /** * Resolve a host string to its first corresponding network address. * * @see LookupHost(const std::string&, std::vector&, unsigned int, * bool) for additional parameter descriptions. */ bool LookupHost(const std::string &name, CNetAddr &addr, bool fAllowLookup) { if (!ValidAsCString(name)) { return false; } std::vector vIP; LookupHost(name, vIP, 1, fAllowLookup); if (vIP.empty()) { return false; } addr = vIP.front(); return true; } /** * Resolve a service string to its corresponding service. * * @param name The string representing a service. Could be a name or a * numerical IP address (IPv6 addresses should be in their * disambiguated bracketed form), optionally followed by a port * number. (e.g. example.com:8333 or * [2001:db8:85a3:8d3:1319:8a2e:370:7348]:420) * @param[out] vAddr The resulting services to which the specified service * string resolved. * @param portDefault The default port for resulting services if not specified * by the service string. * @param fAllowLookup Whether or not hostname lookups are permitted. If yes, * external queries may be performed. * @param nMaxSolutions The maximum number of results we want, specifying 0 * means "as many solutions as we get." * * @returns Whether or not the service string successfully resolved to any * resulting services. */ bool Lookup(const std::string &name, std::vector &vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions) { if (name.empty() || !ValidAsCString(name)) { return false; } int port = portDefault; std::string hostname; SplitHostPort(name, port, hostname); std::vector vIP; bool fRet = LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup); if (!fRet) { return false; } vAddr.resize(vIP.size()); for (unsigned int i = 0; i < vIP.size(); i++) { vAddr[i] = CService(vIP[i], port); } return true; } /** * Resolve a service string to its first corresponding service. * * @see Lookup(const char *, std::vector&, int, bool, unsigned int) * for additional parameter descriptions. */ bool Lookup(const std::string &name, CService &addr, int portDefault, bool fAllowLookup) { if (!ValidAsCString(name)) { return false; } std::vector vService; bool fRet = Lookup(name, vService, portDefault, fAllowLookup, 1); if (!fRet) { return false; } addr = vService[0]; return true; } /** * Resolve a service string with a numeric IP to its first corresponding * service. * * @returns The resulting CService if the resolution was successful, [::]:0 * otherwise. * * @see Lookup(const char *, CService&, int, bool) for additional parameter * descriptions. */ CService LookupNumeric(const std::string &name, int portDefault) { if (!ValidAsCString(name)) { return {}; } CService addr; // "1.2:345" will fail to resolve the ip, but will still set the port. // If the ip fails to resolve, re-init the result. if (!Lookup(name, addr, portDefault, false)) { addr = CService(); } return addr; } struct timeval MillisToTimeval(int64_t nTimeout) { struct timeval timeout; timeout.tv_sec = nTimeout / 1000; timeout.tv_usec = (nTimeout % 1000) * 1000; return timeout; } /** SOCKS version */ enum SOCKSVersion : uint8_t { SOCKS4 = 0x04, SOCKS5 = 0x05 }; /** Values defined for METHOD in RFC1928 */ enum SOCKS5Method : uint8_t { NOAUTH = 0x00, //!< No authentication required GSSAPI = 0x01, //!< GSSAPI USER_PASS = 0x02, //!< Username/password NO_ACCEPTABLE = 0xff, //!< No acceptable methods }; /** Values defined for CMD in RFC1928 */ enum SOCKS5Command : uint8_t { CONNECT = 0x01, BIND = 0x02, UDP_ASSOCIATE = 0x03 }; /** Values defined for REP in RFC1928 */ enum SOCKS5Reply : uint8_t { SUCCEEDED = 0x00, //!< Succeeded GENFAILURE = 0x01, //!< General failure NOTALLOWED = 0x02, //!< Connection not allowed by ruleset NETUNREACHABLE = 0x03, //!< Network unreachable HOSTUNREACHABLE = 0x04, //!< Network unreachable CONNREFUSED = 0x05, //!< Connection refused TTLEXPIRED = 0x06, //!< TTL expired CMDUNSUPPORTED = 0x07, //!< Command not supported ATYPEUNSUPPORTED = 0x08, //!< Address type not supported }; /** Values defined for ATYPE in RFC1928 */ enum SOCKS5Atyp : uint8_t { IPV4 = 0x01, DOMAINNAME = 0x03, IPV6 = 0x04, }; /** Status codes that can be returned by InterruptibleRecv */ enum class IntrRecvError { OK, Timeout, Disconnected, NetworkError, Interrupted }; /** * Try to read a specified number of bytes from a socket. Please read the "see * also" section for more detail. * * @param data The buffer where the read bytes should be stored. * @param len The number of bytes to read into the specified buffer. * @param timeout The total timeout in milliseconds for this read. * @param hSocket The socket (has to be in non-blocking mode) from which to read * bytes. * * @returns An IntrRecvError indicating the resulting status of this read. * IntrRecvError::OK only if all of the specified number of bytes were * read. * * @see This function can be interrupted by calling InterruptSocks5(bool). * Sockets can be made non-blocking with SetSocketNonBlocking(const * SOCKET&, bool). */ static IntrRecvError InterruptibleRecv(uint8_t *data, size_t len, int timeout, const SOCKET &hSocket) { int64_t curTime = GetTimeMillis(); int64_t endTime = curTime + timeout; // Maximum time to wait for I/O readiness. It will take up until this time // (in millis) to break off in case of an interruption. const int64_t maxWait = 1000; while (len > 0 && curTime < endTime) { // Optimistically try the recv first ssize_t ret = recv(hSocket, (char *)data, len, 0); if (ret > 0) { len -= ret; data += ret; } else if (ret == 0) { // Unexpected disconnection return IntrRecvError::Disconnected; } else { // Other error or blocking int nErr = WSAGetLastError(); if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { if (!IsSelectableSocket(hSocket)) { return IntrRecvError::NetworkError; } // Only wait at most maxWait milliseconds at a time, unless // we're approaching the end of the specified total timeout int timeout_ms = std::min(endTime - curTime, maxWait); #ifdef USE_POLL struct pollfd pollfd = {}; pollfd.fd = hSocket; pollfd.events = POLLIN; int nRet = poll(&pollfd, 1, timeout_ms); #else struct timeval tval = MillisToTimeval(timeout_ms); fd_set fdset; FD_ZERO(&fdset); FD_SET(hSocket, &fdset); int nRet = select(hSocket + 1, &fdset, nullptr, nullptr, &tval); #endif if (nRet == SOCKET_ERROR) { return IntrRecvError::NetworkError; } } else { return IntrRecvError::NetworkError; } } if (interruptSocks5Recv) { return IntrRecvError::Interrupted; } curTime = GetTimeMillis(); } return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout; } /** Credentials for proxy authentication */ struct ProxyCredentials { std::string username; std::string password; }; /** Convert SOCKS5 reply to an error message */ static std::string Socks5ErrorString(uint8_t err) { switch (err) { case SOCKS5Reply::GENFAILURE: return "general failure"; case SOCKS5Reply::NOTALLOWED: return "connection not allowed"; case SOCKS5Reply::NETUNREACHABLE: return "network unreachable"; case SOCKS5Reply::HOSTUNREACHABLE: return "host unreachable"; case SOCKS5Reply::CONNREFUSED: return "connection refused"; case SOCKS5Reply::TTLEXPIRED: return "TTL expired"; case SOCKS5Reply::CMDUNSUPPORTED: return "protocol error"; case SOCKS5Reply::ATYPEUNSUPPORTED: return "address type not supported"; default: return "unknown"; } } /** * Connect to a specified destination service through an already connected * SOCKS5 proxy. * * @param strDest The destination fully-qualified domain name. * @param port The destination port. * @param auth The credentials with which to authenticate with the specified * SOCKS5 proxy. * @param hSocket The SOCKS5 proxy socket. * * @returns Whether or not the operation succeeded. * * @note The specified SOCKS5 proxy socket must already be connected to the * SOCKS5 proxy. * * @see RFC1928: SOCKS Protocol * Version 5 */ static bool Socks5(const std::string &strDest, int port, const ProxyCredentials *auth, const SOCKET &hSocket) { IntrRecvError recvr; LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest); if (strDest.size() > 255) { return error("Hostname too long"); } // Construct the version identifier/method selection message std::vector vSocks5Init; // We want the SOCK5 protocol vSocks5Init.push_back(SOCKSVersion::SOCKS5); if (auth) { // 2 method identifiers follow... vSocks5Init.push_back(0x02); vSocks5Init.push_back(SOCKS5Method::NOAUTH); vSocks5Init.push_back(SOCKS5Method::USER_PASS); } else { // 1 method identifier follows... vSocks5Init.push_back(0x01); vSocks5Init.push_back(SOCKS5Method::NOAUTH); } ssize_t ret = send(hSocket, (const char *)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vSocks5Init.size()) { return error("Error sending to proxy"); } uint8_t pchRet1[2]; if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() " "timeout or other failure\n", strDest, port); return false; } if (pchRet1[0] != SOCKSVersion::SOCKS5) { return error("Proxy failed to initialize"); } if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) { // Perform username/password authentication (as described in RFC1929) std::vector vAuth; // Current (and only) version of user/pass subnegotiation vAuth.push_back(0x01); if (auth->username.size() > 255 || auth->password.size() > 255) { return error("Proxy username or password too long"); } vAuth.push_back(auth->username.size()); vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end()); vAuth.push_back(auth->password.size()); vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end()); ret = send(hSocket, (const char *)vAuth.data(), vAuth.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vAuth.size()) { return error("Error sending authentication to proxy"); } LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password); uint8_t pchRetA[2]; if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { return error("Error reading proxy authentication response"); } if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) { return error("Proxy authentication unsuccessful"); } } else if (pchRet1[1] == SOCKS5Method::NOAUTH) { // Perform no authentication } else { return error("Proxy requested wrong authentication method %02x", pchRet1[1]); } std::vector vSocks5; // VER protocol version vSocks5.push_back(SOCKSVersion::SOCKS5); // CMD CONNECT vSocks5.push_back(SOCKS5Command::CONNECT); // RSV Reserved must be 0 vSocks5.push_back(0x00); // ATYP DOMAINNAME vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // Length<=255 is checked at beginning of function vSocks5.push_back(strDest.size()); vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end()); vSocks5.push_back((port >> 8) & 0xFF); vSocks5.push_back((port >> 0) & 0xFF); ret = send(hSocket, (const char *)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vSocks5.size()) { return error("Error sending to proxy"); } uint8_t pchRet2[4]; if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { if (recvr == IntrRecvError::Timeout) { /** * If a timeout happens here, this effectively means we timed out * while connecting to the remote node. This is very common for Tor, * so do not print an error message. */ return false; } else { return error("Error while reading proxy response"); } } if (pchRet2[0] != SOCKSVersion::SOCKS5) { return error("Proxy failed to accept request"); } if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) { // Failures to connect to a peer that are not proxy errors LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1])); return false; } // Reserved field must be 0 if (pchRet2[2] != 0x00) { return error("Error: malformed proxy response"); } uint8_t pchRet3[256]; switch (pchRet2[3]) { case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break; case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break; case SOCKS5Atyp::DOMAINNAME: { recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket); if (recvr != IntrRecvError::OK) { return error("Error reading from proxy"); } int nRecv = pchRet3[0]; recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket); break; } default: return error("Error: malformed proxy response"); } if (recvr != IntrRecvError::OK) { return error("Error reading from proxy"); } if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { return error("Error reading from proxy"); } LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest); return true; } /** * Try to create a socket file descriptor with specific properties in the * communications domain (address family) of the specified service. * * For details on the desired properties, see the inline comments in the source * code. */ SOCKET CreateSocket(const CService &addrConnect) { // Create a sockaddr from the specified service. struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrConnect.GetSockAddr((struct sockaddr *)&sockaddr, &len)) { LogPrintf("Cannot create socket for %s: unsupported network\n", addrConnect.ToString()); return INVALID_SOCKET; } // Create a TCP socket in the address family of the specified service. SOCKET hSocket = socket(((struct sockaddr *)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hSocket == INVALID_SOCKET) { return INVALID_SOCKET; } // Ensure that waiting for I/O on this socket won't result in undefined // behavior. if (!IsSelectableSocket(hSocket)) { CloseSocket(hSocket); LogPrintf("Cannot create connection: non-selectable socket created (fd " ">= FD_SETSIZE ?)\n"); return INVALID_SOCKET; } #ifdef SO_NOSIGPIPE int set = 1; // Set the no-sigpipe option on the socket for BSD systems, other UNIXes // should use the MSG_NOSIGNAL flag for every send. setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (sockopt_arg_type)&set, sizeof(int)); #endif // Set the no-delay option (disable Nagle's algorithm) on the TCP socket. SetSocketNoDelay(hSocket); // Set the non-blocking option on the socket. if (!SetSocketNonBlocking(hSocket, true)) { CloseSocket(hSocket); LogPrintf("CreateSocket: Setting socket to non-blocking " "failed, error %s\n", NetworkErrorString(WSAGetLastError())); } return hSocket; } template static void LogConnectFailure(bool manual_connection, const char *fmt, const Args &... args) { std::string error_message = tfm::format(fmt, args...); if (manual_connection) { LogPrintf("%s\n", error_message); } else { LogPrint(BCLog::NET, "%s\n", error_message); } } /** * Try to connect to the specified service on the specified socket. * * @param addrConnect The service to which to connect. * @param hSocket The socket on which to connect. * @param nTimeout Wait this many milliseconds for the connection to be * established. * @param manual_connection Whether or not the connection was manually requested * (e.g. through the addnode RPC) * * @returns Whether or not a connection was successfully made. */ bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET &hSocket, int nTimeout, bool manual_connection) { // Create a sockaddr from the specified service. struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (hSocket == INVALID_SOCKET) { LogPrintf("Cannot connect to %s: invalid socket\n", addrConnect.ToString()); return false; } if (!addrConnect.GetSockAddr((struct sockaddr *)&sockaddr, &len)) { LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString()); return false; } // Connect to the addrConnect service on the hSocket socket. if (connect(hSocket, (struct sockaddr *)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); // WSAEINVAL is here because some legacy version of winsock uses it if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { // Connection didn't actually fail, but is being established // asynchronously. Thus, use async I/O api (select/poll) // synchronously to check for successful connection with a timeout. #ifdef USE_POLL struct pollfd pollfd = {}; pollfd.fd = hSocket; pollfd.events = POLLIN | POLLOUT; int nRet = poll(&pollfd, 1, nTimeout); #else struct timeval timeout = MillisToTimeval(nTimeout); fd_set fdset; FD_ZERO(&fdset); FD_SET(hSocket, &fdset); int nRet = select(hSocket + 1, nullptr, &fdset, nullptr, &timeout); #endif // Upon successful completion, both select and poll return the total // number of file descriptors that have been selected. A value of 0 // indicates that the call timed out and no file descriptors have // been selected. if (nRet == 0) { LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString()); return false; } if (nRet == SOCKET_ERROR) { LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); return false; } // Even if the select/poll was successful, the connect might not // have been successful. The reason for this failure is hidden away // in the SO_ERROR for the socket in modern systems. We read it into // nRet here. socklen_t nRetSize = sizeof(nRet); if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&nRet, &nRetSize) == SOCKET_ERROR) { LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); return false; } if (nRet != 0) { LogConnectFailure(manual_connection, "connect() to %s failed after select(): %s", addrConnect.ToString(), NetworkErrorString(nRet)); return false; } } #ifdef WIN32 else if (WSAGetLastError() != WSAEISCONN) #else else #endif { LogConnectFailure(manual_connection, "connect() to %s failed: %s", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); return false; } } return true; } bool SetProxy(enum Network net, const proxyType &addrProxy) { assert(net >= 0 && net < NET_MAX); if (!addrProxy.IsValid()) { return false; } LOCK(cs_proxyInfos); proxyInfo[net] = addrProxy; return true; } bool GetProxy(enum Network net, proxyType &proxyInfoOut) { assert(net >= 0 && net < NET_MAX); LOCK(cs_proxyInfos); if (!proxyInfo[net].IsValid()) { return false; } proxyInfoOut = proxyInfo[net]; return true; } /** * Set the name proxy to use for all connections to nodes specified by a * hostname. After setting this proxy, connecting to a node specified by a * hostname won't result in a local lookup of said hostname, rather, connect to * the node by asking the name proxy for a proxy connection to the hostname, * effectively delegating the hostname lookup to the specified proxy. * * This delegation increases privacy for those who set the name proxy as they no * longer leak their external hostname queries to their DNS servers. * * @returns Whether or not the operation succeeded. * * @note SOCKS5's support for UDP-over-SOCKS5 has been considered, but no SOCK5 * server in common use (most notably Tor) actually implements UDP * support, and a DNS resolver is beyond the scope of this project. */ bool SetNameProxy(const proxyType &addrProxy) { if (!addrProxy.IsValid()) { return false; } LOCK(cs_proxyInfos); nameProxy = addrProxy; return true; } bool GetNameProxy(proxyType &nameProxyOut) { LOCK(cs_proxyInfos); if (!nameProxy.IsValid()) { return false; } nameProxyOut = nameProxy; return true; } bool HaveNameProxy() { LOCK(cs_proxyInfos); return nameProxy.IsValid(); } bool IsProxy(const CNetAddr &addr) { LOCK(cs_proxyInfos); for (int i = 0; i < NET_MAX; i++) { if (addr == static_cast(proxyInfo[i].proxy)) { return true; } } return false; } /** * Connect to a specified destination service through a SOCKS5 proxy by first * connecting to the SOCKS5 proxy. * * @param proxy The SOCKS5 proxy. * @param strDest The destination service to which to connect. * @param port The destination port. * @param hSocket The socket on which to connect to the SOCKS5 proxy. * @param nTimeout Wait this many milliseconds for the connection to the SOCKS5 * proxy to be established. * @param[out] outProxyConnectionFailed Whether or not the connection to the * SOCKS5 proxy failed. * * @returns Whether or not the operation succeeded. */ bool ConnectThroughProxy(const proxyType &proxy, const std::string &strDest, int port, const SOCKET &hSocket, int nTimeout, bool &outProxyConnectionFailed) { // first connect to proxy server if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout, true)) { outProxyConnectionFailed = true; return false; } // do socks negotiation if (proxy.randomize_credentials) { ProxyCredentials random_auth; static std::atomic_int counter(0); random_auth.username = random_auth.password = strprintf("%i", counter++); if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket)) { return false; } } else if (!Socks5(strDest, (unsigned short)port, 0, hSocket)) { return false; } return true; } /** * Parse and resolve a specified subnet string into the appropriate internal * representation. * * @param strSubnet A string representation of a subnet of the form `network * address [ "/", ( CIDR-style suffix | netmask ) ]`(e.g. * `2001:db8::/32`, `192.0.2.0/255.255.255.0`, or `8.8.8.8`). * @param ret The resulting internal representation of a subnet. * * @returns Whether the operation succeeded or not. */ bool LookupSubNet(const std::string &strSubnet, CSubNet &ret) { if (!ValidAsCString(strSubnet)) { return false; } size_t slash = strSubnet.find_last_of('/'); std::vector vIP; std::string strAddress = strSubnet.substr(0, slash); // TODO: Use LookupHost(const std::string&, CNetAddr&, bool) instead to just // get one CNetAddr. if (LookupHost(strAddress, vIP, 1, false)) { CNetAddr network = vIP[0]; if (slash != strSubnet.npos) { std::string strNetmask = strSubnet.substr(slash + 1); - int32_t n; - if (ParseInt32(strNetmask, &n)) { + uint8_t n; + if (ParseUInt8(strNetmask, &n)) { // If valid number, assume CIDR variable-length subnet masking ret = CSubNet(network, n); return ret.IsValid(); } else { // If not a valid number, try full netmask syntax // Never allow lookup for netmask if (LookupHost(strNetmask, vIP, 1, false)) { ret = CSubNet(network, vIP[0]); return ret.IsValid(); } } } else { ret = CSubNet(network); return ret.IsValid(); } } return false; } #ifdef WIN32 std::string NetworkErrorString(int err) { char buf[256]; buf[0] = 0; if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, sizeof(buf), nullptr)) { return strprintf("%s (%d)", buf, err); } else { return strprintf("Unknown error (%d)", err); } } #else std::string NetworkErrorString(int err) { char buf[256]; buf[0] = 0; /** * Too bad there are two incompatible implementations of the * thread-safe strerror. */ const char *s; #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ s = strerror_r(err, buf, sizeof(buf)); #else s = buf; /* POSIX variant always returns message in buffer */ if (strerror_r(err, buf, sizeof(buf))) { buf[0] = 0; } #endif return strprintf("%s (%d)", s, err); } #endif bool CloseSocket(SOCKET &hSocket) { if (hSocket == INVALID_SOCKET) { return false; } #ifdef WIN32 int ret = closesocket(hSocket); #else int ret = close(hSocket); #endif if (ret) { LogPrintf("Socket close failed: %d. Error: %s\n", hSocket, NetworkErrorString(WSAGetLastError())); } hSocket = INVALID_SOCKET; return ret != SOCKET_ERROR; } bool SetSocketNonBlocking(const SOCKET &hSocket, bool fNonBlocking) { if (fNonBlocking) { #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) { #else int fFlags = fcntl(hSocket, F_GETFL, 0); if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) { #endif return false; } } else { #ifdef WIN32 u_long nZero = 0; if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) { #else int fFlags = fcntl(hSocket, F_GETFL, 0); if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) { #endif return false; } } return true; } bool SetSocketNoDelay(const SOCKET &hSocket) { int set = 1; int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (sockopt_arg_type)&set, sizeof(int)); return rc == 0; } void InterruptSocks5(bool interrupt) { interruptSocks5Recv = interrupt; } diff --git a/src/test/fuzz/asmap.cpp b/src/test/fuzz/asmap.cpp index e00daac76..93e6e9ee0 100644 --- a/src/test/fuzz/asmap.cpp +++ b/src/test/fuzz/asmap.cpp @@ -1,69 +1,79 @@ // Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include //! asmap code that consumes nothing static const std::vector IPV6_PREFIX_ASMAP = {}; //! asmap code that consumes the 96 prefix bits of ::ffff:0/96 (IPv4-in-IPv6 //! map) static const std::vector IPV4_PREFIX_ASMAP = { true, true, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, // Match 0x00 true, true, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, // Match 0x00 true, true, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, // Match 0x00 true, true, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, // Match 0x00 true, true, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, // Match 0x00 true, true, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, // Match 0x00 true, true, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, // Match 0x00 true, true, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, // Match 0x00 true, true, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, // Match 0x00 true, true, false, true, true, true, true, true, true, true, false, false, false, false, false, false, false, false, // Match 0x00 true, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // Match 0xFF true, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true // Match 0xFF }; void test_one_input(const std::vector &buffer) { // Encoding: [7 bits: asmap size] [1 bit: ipv6?] [3-130 bytes: asmap] [4 or // 16 bytes: addr] if (buffer.size() < 1 + 3 + 4) { return; } int asmap_size = 3 + (buffer[0] & 127); bool ipv6 = buffer[0] & 128; - int addr_size = ipv6 ? 16 : 4; + const size_t addr_size = ipv6 ? ADDR_IPV6_SIZE : ADDR_IPV4_SIZE; if (buffer.size() < size_t(1 + asmap_size + addr_size)) { return; } std::vector asmap = ipv6 ? IPV6_PREFIX_ASMAP : IPV4_PREFIX_ASMAP; asmap.reserve(asmap.size() + 8 * asmap_size); for (int i = 0; i < asmap_size; ++i) { for (int j = 0; j < 8; ++j) { asmap.push_back((buffer[1 + i] >> j) & 1); } } if (!SanityCheckASMap(asmap)) { return; } + + const uint8_t *addr_data = buffer.data() + 1 + asmap_size; CNetAddr net_addr; - net_addr.SetRaw(ipv6 ? NET_IPV6 : NET_IPV4, buffer.data() + 1 + asmap_size); + if (ipv6) { + assert(addr_size == ADDR_IPV6_SIZE); + net_addr.SetLegacyIPv6(Span(addr_data, addr_size)); + } else { + assert(addr_size == ADDR_IPV4_SIZE); + in_addr ipv4; + memcpy(&ipv4, addr_data, addr_size); + net_addr.SetIP(CNetAddr{ipv4}); + } (void)net_addr.GetMappedAS(asmap); } diff --git a/src/test/fuzz/netaddress.cpp b/src/test/fuzz/netaddress.cpp index a4cb3b887..4743409a9 100644 --- a/src/test/fuzz/netaddress.cpp +++ b/src/test/fuzz/netaddress.cpp @@ -1,117 +1,114 @@ // Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include #include #include #include #include #include #include #include void test_one_input(const std::vector &buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const CNetAddr net_addr = ConsumeNetAddr(fuzzed_data_provider); - for (int i = 0; i < 15; ++i) { - (void)net_addr.GetByte(i); - } (void)net_addr.GetHash(); (void)net_addr.GetNetClass(); if (net_addr.GetNetwork() == Network::NET_IPV4) { assert(net_addr.IsIPv4()); } if (net_addr.GetNetwork() == Network::NET_IPV6) { assert(net_addr.IsIPv6()); } if (net_addr.GetNetwork() == Network::NET_ONION) { assert(net_addr.IsTor()); } if (net_addr.GetNetwork() == Network::NET_INTERNAL) { assert(net_addr.IsInternal()); } if (net_addr.GetNetwork() == Network::NET_UNROUTABLE) { assert(!net_addr.IsRoutable()); } (void)net_addr.IsBindAny(); if (net_addr.IsInternal()) { assert(net_addr.GetNetwork() == Network::NET_INTERNAL); } if (net_addr.IsIPv4()) { assert(net_addr.GetNetwork() == Network::NET_IPV4 || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } if (net_addr.IsIPv6()) { assert(net_addr.GetNetwork() == Network::NET_IPV6 || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } (void)net_addr.IsLocal(); if (net_addr.IsRFC1918() || net_addr.IsRFC2544() || net_addr.IsRFC6598() || net_addr.IsRFC5737() || net_addr.IsRFC3927()) { assert(net_addr.IsIPv4()); } (void)net_addr.IsRFC2544(); if (net_addr.IsRFC3849() || net_addr.IsRFC3964() || net_addr.IsRFC4380() || net_addr.IsRFC4843() || net_addr.IsRFC7343() || net_addr.IsRFC4862() || net_addr.IsRFC6052() || net_addr.IsRFC6145()) { assert(net_addr.IsIPv6()); } (void)net_addr.IsRFC3927(); (void)net_addr.IsRFC3964(); if (net_addr.IsRFC4193()) { assert(net_addr.GetNetwork() == Network::NET_ONION || net_addr.GetNetwork() == Network::NET_INTERNAL || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } (void)net_addr.IsRFC4380(); (void)net_addr.IsRFC4843(); (void)net_addr.IsRFC4862(); (void)net_addr.IsRFC5737(); (void)net_addr.IsRFC6052(); (void)net_addr.IsRFC6145(); (void)net_addr.IsRFC6598(); (void)net_addr.IsRFC7343(); if (!net_addr.IsRoutable()) { assert(net_addr.GetNetwork() == Network::NET_UNROUTABLE || net_addr.GetNetwork() == Network::NET_INTERNAL); } if (net_addr.IsTor()) { assert(net_addr.GetNetwork() == Network::NET_ONION); } (void)net_addr.IsValid(); (void)net_addr.ToString(); (void)net_addr.ToStringIP(); const CSubNet sub_net{net_addr, - fuzzed_data_provider.ConsumeIntegral()}; + fuzzed_data_provider.ConsumeIntegral()}; (void)sub_net.IsValid(); (void)sub_net.ToString(); const CService service{net_addr, fuzzed_data_provider.ConsumeIntegral()}; (void)service.GetKey(); (void)service.GetPort(); (void)service.ToString(); (void)service.ToStringIPPort(); (void)service.ToStringPort(); const CNetAddr other_net_addr = ConsumeNetAddr(fuzzed_data_provider); (void)net_addr.GetReachabilityFrom(&other_net_addr); (void)sub_net.Match(other_net_addr); const CService other_service{ net_addr, fuzzed_data_provider.ConsumeIntegral()}; assert((service == other_service) != (service != other_service)); (void)(service < other_service); const CSubNet sub_net_copy_1{net_addr, other_net_addr}; const CSubNet sub_net_copy_2{net_addr}; CNetAddr mutable_net_addr; mutable_net_addr.SetIP(net_addr); assert(net_addr == mutable_net_addr); } diff --git a/src/test/fuzz/util.h b/src/test/fuzz/util.h index 068f9a7ae..551e31401 100644 --- a/src/test/fuzz/util.h +++ b/src/test/fuzz/util.h @@ -1,490 +1,490 @@ // Copyright (c) 2009-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TEST_FUZZ_UTIL_H #define BITCOIN_TEST_FUZZ_UTIL_H #include #include #include #include #include #include #include