diff --git a/src/protocol.h b/src/protocol.h --- a/src/protocol.h +++ b/src/protocol.h @@ -49,6 +49,13 @@ typedef std::array MessageMagic; explicit CMessageHeader(const MessageMagic &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 MessageMagic &pchMessageStartIn, const char *pszCommand, unsigned int nMessageSizeIn); diff --git a/src/protocol.cpp b/src/protocol.cpp --- a/src/protocol.cpp +++ b/src/protocol.cpp @@ -86,8 +86,17 @@ unsigned int nMessageSizeIn) { memcpy(std::begin(pchMessageStart), std::begin(pchMessageStartIn), MESSAGE_START_SIZE); - memset(pchCommand.data(), 0, sizeof(pchCommand)); - strncpy(pchCommand.data(), pszCommand, COMMAND_SIZE); + // Copy the command name, zero-padding to COMMAND_SIZE bytes + size_t i = 0; + for (; i < pchCommand.size() && pszCommand[i] != 0; ++i) { + pchCommand[i] = pszCommand[i]; + } + // Assert that the command name passed in is not longer than COMMAND_SIZE + assert(pszCommand[i] == 0); + for (; i < pchCommand.size(); ++i) { + pchCommand[i] = 0; + } + nMessageSize = nMessageSizeIn; memset(pchChecksum, 0, CHECKSUM_SIZE); }