From 3fd3563d0a72a1c6035d5bc5e81f24bdd0cbbf80 Mon Sep 17 00:00:00 2001 From: "Wladimir J. van der Laan" Date: Mon, 30 Sep 2019 12:27:27 +0200 Subject: [PATCH] net: Fail instead of truncate command name in CMessageHeader Replace the memset/strncpy dance in `CMessageHeader::CMessageHeader` with explicit code that copies then name and asserts the length. This removes a warning in g++ 9.1.1 and IMO makes the code more readable by not relying on strncpy padding and silent truncation behavior. Cherry-picked from: b837b33 --- src/protocol.cpp | 9 +++++++-- src/protocol.h | 5 +++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/protocol.cpp b/src/protocol.cpp index 94bc2a9c8..6d266eef9 100644 --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -87,8 +87,13 @@ CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn) CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn) { memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE); - memset(pchCommand, 0, sizeof(pchCommand)); - strncpy(pchCommand, pszCommand, COMMAND_SIZE); + + // Copy the command name, zero-padding to COMMAND_SIZE bytes + size_t i = 0; + for (; i < COMMAND_SIZE && pszCommand[i] != 0; ++i) pchCommand[i] = pszCommand[i]; + assert(pszCommand[i] == 0); // Assert that the command name passed in is not longer than COMMAND_SIZE + for (; i < COMMAND_SIZE; ++i) pchCommand[i] = 0; + nMessageSize = nMessageSizeIn; memset(pchChecksum, 0, CHECKSUM_SIZE); } diff --git a/src/protocol.h b/src/protocol.h index f8bf85141..1d66a754d 100644 --- a/src/protocol.h +++ b/src/protocol.h @@ -39,7 +39,12 @@ public: }; typedef unsigned char MessageStartChars[MESSAGE_START_SIZE]; + CMessageHeader(const MessageStartChars& pchMessageStartIn); + + /** Construct a P2P message header from message-start characters, a command and the size of the message. + * @note Passing in a `pszCommand` longer than COMMAND_SIZE will result in a run-time assertion error. + */ CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn); std::string GetCommand() const;