From c44b7d0f7ff21edb702745e4c019d0537928c373 Mon Sep 17 00:00:00 2001 From: Arvid Norlander <132438847+arvid-norlander@users.noreply.github.com> Date: Tue, 5 Mar 2024 16:46:29 +0100 Subject: Fix unaligned reads and writes of the checksum (fixes #237) (#238) Co-authored-by: Arvid Norlander --- protocol.c | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/protocol.c b/protocol.c index 73e8056..843a719 100644 --- a/protocol.c +++ b/protocol.c @@ -1072,11 +1072,14 @@ enet_protocol_handle_incoming_commands (ENetHost * host, ENetEvent * event) if (host -> checksum != NULL) { - enet_uint32 * checksum = (enet_uint32 *) & host -> receivedData [headerSize - sizeof (enet_uint32)], - desiredChecksum = * checksum; + enet_uint32 * checksum = (enet_uint32 *) & host -> receivedData [headerSize - sizeof (enet_uint32)]; + enet_uint32 desiredChecksum, newChecksum; ENetBuffer buffer; + /* Checksum may be an unaligned pointer, use memcpy to avoid undefined behaviour. */ + memcpy (& desiredChecksum, checksum, sizeof (enet_uint32)); - * checksum = peer != NULL ? peer -> connectID : 0; + newChecksum = peer != NULL ? peer -> connectID : 0; + memcpy (checksum, & newChecksum, sizeof (enet_uint32)); buffer.data = host -> receivedData; buffer.dataLength = host -> receivedDataLength; @@ -1704,9 +1707,12 @@ enet_protocol_send_outgoing_commands (ENetHost * host, ENetEvent * event, int ch if (host -> checksum != NULL) { enet_uint32 * checksum = (enet_uint32 *) & headerData [host -> buffers -> dataLength]; - * checksum = currentPeer -> outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID ? currentPeer -> connectID : 0; + enet_uint32 newChecksum = currentPeer -> outgoingPeerID < ENET_PROTOCOL_MAXIMUM_PEER_ID ? currentPeer -> connectID : 0; + /* Checksum may be unaligned, use memcpy to avoid undefined behaviour. */ + memcpy(checksum, & newChecksum, sizeof (enet_uint32)); host -> buffers -> dataLength += sizeof (enet_uint32); - * checksum = host -> checksum (host -> buffers, host -> bufferCount); + newChecksum = host -> checksum (host -> buffers, host -> bufferCount); + memcpy(checksum, & newChecksum, sizeof (enet_uint32)); } if (shouldCompress > 0) -- cgit v1.2.3