Skip to content

Commit b837b33

Browse files
committed
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.
1 parent 8a56f79 commit b837b33

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

src/protocol.cpp

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,8 +85,13 @@ CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)
8585
CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
8686
{
8787
memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
88-
memset(pchCommand, 0, sizeof(pchCommand));
89-
strncpy(pchCommand, pszCommand, COMMAND_SIZE);
88+
89+
// Copy the command name, zero-padding to COMMAND_SIZE bytes
90+
size_t i = 0;
91+
for (; i < COMMAND_SIZE && pszCommand[i] != 0; ++i) pchCommand[i] = pszCommand[i];
92+
assert(pszCommand[i] == 0); // Assert that the command name passed in is not longer than COMMAND_SIZE
93+
for (; i < COMMAND_SIZE; ++i) pchCommand[i] = 0;
94+
9095
nMessageSize = nMessageSizeIn;
9196
memset(pchChecksum, 0, CHECKSUM_SIZE);
9297
}

src/protocol.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ class CMessageHeader
3737
typedef unsigned char MessageStartChars[MESSAGE_START_SIZE];
3838

3939
explicit CMessageHeader(const MessageStartChars& pchMessageStartIn);
40+
41+
/** Construct a P2P message header from message-start characters, a command and the size of the message.
42+
* @note Passing in a `pszCommand` longer than COMMAND_SIZE will result in a run-time assertion error.
43+
*/
4044
CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn);
4145

4246
std::string GetCommand() const;

0 commit comments

Comments
 (0)