Skip to content

Commit

Permalink
net: Fail instead of truncate command name in CMessageHeader
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
laanwj authored and random-zebra committed Dec 20, 2020
1 parent 2e6aeed commit c223041
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/protocol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,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);
}
Expand Down
6 changes: 5 additions & 1 deletion src/protocol.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,11 @@ class CMessageHeader
public:
typedef unsigned char MessageStartChars[MESSAGE_START_SIZE];

CMessageHeader(const MessageStartChars& pchMessageStartIn);
explicit 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;
Expand Down

0 comments on commit c223041

Please sign in to comment.