mirror of
https://github.com/bitcoin/bitcoin.git
synced 2025-06-25 08:21:24 +02:00
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.
This commit is contained in:
parent
8a56f79d49
commit
b837b334db
@ -85,8 +85,13 @@ CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)
|
|||||||
CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
|
CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
|
||||||
{
|
{
|
||||||
memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
|
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;
|
nMessageSize = nMessageSizeIn;
|
||||||
memset(pchChecksum, 0, CHECKSUM_SIZE);
|
memset(pchChecksum, 0, CHECKSUM_SIZE);
|
||||||
}
|
}
|
||||||
|
@ -37,6 +37,10 @@ public:
|
|||||||
typedef unsigned char MessageStartChars[MESSAGE_START_SIZE];
|
typedef unsigned char MessageStartChars[MESSAGE_START_SIZE];
|
||||||
|
|
||||||
explicit 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);
|
CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn);
|
||||||
|
|
||||||
std::string GetCommand() const;
|
std::string GetCommand() const;
|
||||||
|
Loading…
x
Reference in New Issue
Block a user