diff --git a/src/net_processing.cpp b/src/net_processing.cpp index 99ae0e8fa1..618dbd99d0 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -3443,7 +3443,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, if (!vRecv.empty()) { std::string strSubVer; vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH); - cleanSubVer = SanitizeString(strSubVer); + cleanSubVer = SanitizeString(strSubVer, SAFE_CHARS_PRINTABLE); } if (!vRecv.empty()) { vRecv >> starting_height; @@ -3584,7 +3584,7 @@ void PeerManagerImpl::ProcessMessage(CNode& pfrom, const std::string& msg_type, const auto mapped_as{m_connman.GetMappedAS(pfrom.addr)}; LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, txrelay=%d, peer=%d%s%s\n", - cleanSubVer, pfrom.nVersion, + SanitizeString(cleanSubVer, SAFE_CHARS_DEFAULT, true), pfrom.nVersion, peer->m_starting_height, addrMe.ToStringAddrPort(), fRelay, pfrom.GetId(), remoteAddr, (mapped_as ? strprintf(", mapped_as=%d", mapped_as) : "")); diff --git a/src/util/strencodings.cpp b/src/util/strencodings.cpp index a54f408496..06fc6dd6f5 100644 --- a/src/util/strencodings.cpp +++ b/src/util/strencodings.cpp @@ -4,6 +4,7 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include +#include #include #include @@ -23,14 +24,17 @@ static const std::string SAFE_CHARS[] = CHARS_ALPHA_NUM + " .,;-_?@", // SAFE_CHARS_UA_COMMENT CHARS_ALPHA_NUM + ".-_", // SAFE_CHARS_FILENAME CHARS_ALPHA_NUM + "!*'();:@&=+$,/?#[]-_.~%", // SAFE_CHARS_URI + CHARS_ALPHA_NUM + " .,;-_/:?@()!\"#$%&'*+<=>[\\]^`{|}~" // SAFE_CHARS_PRINTABLE }; -std::string SanitizeString(std::string_view str, int rule) +std::string SanitizeString(std::string_view str, int rule, bool escape) { std::string result; for (char c : str) { - if (SAFE_CHARS[rule].find(c) != std::string::npos) { + if (SAFE_CHARS[rule].find(c) != std::string::npos || (c == '%' && escape)) { result.push_back(c); + } else if (escape) { + result += strprintf("%%%02X", c); } } return result; diff --git a/src/util/strencodings.h b/src/util/strencodings.h index 439678c24a..52bd1b0d66 100644 --- a/src/util/strencodings.h +++ b/src/util/strencodings.h @@ -30,6 +30,7 @@ enum SafeChars SAFE_CHARS_UA_COMMENT, //!< BIP-0014 subset SAFE_CHARS_FILENAME, //!< Chars allowed in filenames SAFE_CHARS_URI, //!< Chars allowed in URIs (RFC 3986) + SAFE_CHARS_PRINTABLE, //!< The full set of printable chars }; /** @@ -56,7 +57,7 @@ enum class ByteUnit : uint64_t { * @param[in] rule The set of safe chars to choose (default: least restrictive) * @return A new string without unsafe chars */ -std::string SanitizeString(std::string_view str, int rule = SAFE_CHARS_DEFAULT); +std::string SanitizeString(std::string_view str, int rule = SAFE_CHARS_DEFAULT, bool escape = false); /** Parse the hex string into bytes (uint8_t or std::byte). Ignores whitespace. Returns nullopt on invalid input. */ template std::optional> TryParseHex(std::string_view str);