From 102867c587f5f7954232fb8ed8e85cda78bb4d32 Mon Sep 17 00:00:00 2001 From: Vasil Dimov Date: Mon, 24 Aug 2020 21:34:26 +0200 Subject: net: change CNetAddr::ip to have flexible size Before this change `CNetAddr::ip` was a fixed-size array of 16 bytes, not being able to store larger addresses (e.g. TORv3) and encoded smaller ones as 16-byte IPv6 addresses. Change its type to `prevector`, so that it can hold larger addresses and do not disguise non-IPv6 addresses as IPv6. So the IPv4 address `1.2.3.4` is now encoded as `01020304` instead of `00000000000000000000FFFF01020304`. Rename `CNetAddr::ip` to `CNetAddr::m_addr` because it is not an "IP" or "IP address" (TOR addresses are not IP addresses). In order to preserve backward compatibility with serialization (where e.g. `1.2.3.4` is serialized as `00000000000000000000FFFF01020304`) introduce `CNetAddr` dedicated legacy serialize/unserialize methods. Adjust `CSubNet` accordingly. Still use `CSubNet::netmask[]` of fixed 16 bytes, but use the first 4 for IPv4 (not the last 4). Only allow subnetting for IPv4 and IPv6. Co-authored-by: Carl Dong --- src/util/strencodings.cpp | 12 ++++++++++++ src/util/strencodings.h | 7 +++++++ 2 files changed, 19 insertions(+) (limited to 'src/util') diff --git a/src/util/strencodings.cpp b/src/util/strencodings.cpp index d10f92ffe6..44f9c708ba 100644 --- a/src/util/strencodings.cpp +++ b/src/util/strencodings.cpp @@ -318,6 +318,18 @@ bool ParseInt64(const std::string& str, int64_t *out) n <= std::numeric_limits::max(); } +bool ParseUInt8(const std::string& str, uint8_t *out) +{ + uint32_t u32; + if (!ParseUInt32(str, &u32) || u32 > std::numeric_limits::max()) { + return false; + } + if (out != nullptr) { + *out = static_cast(u32); + } + return true; +} + bool ParseUInt32(const std::string& str, uint32_t *out) { if (!ParsePrechecks(str)) diff --git a/src/util/strencodings.h b/src/util/strencodings.h index eaa0fa9992..8415e4bd6a 100644 --- a/src/util/strencodings.h +++ b/src/util/strencodings.h @@ -99,6 +99,13 @@ NODISCARD bool ParseInt32(const std::string& str, int32_t *out); */ NODISCARD bool ParseInt64(const std::string& str, int64_t *out); +/** + * Convert decimal string to unsigned 8-bit integer with strict parse error feedback. + * @returns true if the entire string could be parsed as valid integer, + * false if not the entire string could be parsed or when overflow or underflow occurred. + */ +NODISCARD bool ParseUInt8(const std::string& str, uint8_t *out); + /** * Convert decimal string to unsigned 32-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, -- cgit v1.2.3