From 8a6c08a63686bf6afab1ab6863d641e8a87b4eb8 Mon Sep 17 00:00:00 2001 From: Nathael Pajani Date: Sun, 10 Mar 2019 03:00:37 +0100 Subject: [PATCH] Fix copy of uint16_t to buff, destination may not be aligned on word boundary. --- lib/protocols/mqtt.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/protocols/mqtt.c b/lib/protocols/mqtt.c index a781b44..36cd5fe 100644 --- a/lib/protocols/mqtt.c +++ b/lib/protocols/mqtt.c @@ -90,7 +90,8 @@ static int decode_remaining_length(uint8_t* buf, uint32_t* length) */ static int mqtt_pack_str(uint8_t *buf, char* str, uint16_t len) { - *(uint16_t*)buf = htons(len); + uint16_t tmp = htons(len); + memcpy(buf, &tmp, 2); memcpy((buf + 2), str, len); return len + 2; } @@ -181,8 +182,9 @@ int mqtt_pack_connect_packet(const struct mqtt_connect_pkt* pkt, uint8_t* buf, u /* Add optionnal Will message */ if ((pkt->will_msg_size != 0) && (pkt->will_topic != NULL) && (pkt->will_msg != NULL)) { + uint16_t tmp = htons(pkt->will_msg_size); len += mqtt_pack_str((buf + len), pkt->will_topic, will_topic_len); - *(uint16_t*)(buf + len) = htons(pkt->will_msg_size); + memcpy((buf + len), &tmp, 2); memcpy((buf + len + 2), pkt->will_msg, pkt->will_msg_size); len += pkt->will_msg_size + 2; } @@ -240,6 +242,7 @@ int mqtt_pack_publish_packet(const struct mqtt_publish_pkt* pkt, uint8_t* buf, u uint32_t remaining_length = 0; uint32_t len = 0; uint16_t topic_len = 0; + uint16_t tmp_packet_id = 0; uint8_t publish_flags = 0; if ((pkt == NULL) || (buf == NULL)) { @@ -280,7 +283,8 @@ int mqtt_pack_publish_packet(const struct mqtt_publish_pkt* pkt, uint8_t* buf, u /* Topic is mandatory */ len += mqtt_pack_str((buf + len), pkt->topic, topic_len); /* Packet ID */ - *(uint16_t*)(buf + len) = htons(pkt->packet_id); + tmp_packet_id = htons(pkt->packet_id); + memcpy((buf + len), &tmp_packet_id, 2); len += 2; /* Add optionnal application message */ if (pkt->message_size != 0) { @@ -351,6 +355,7 @@ int mqtt_unpack_publish_packet(struct mqtt_publish_pkt* pkt, uint8_t* buf, uint3 */ int mqtt_pack_publish_response_pkt(uint8_t* buf, uint16_t acked_pkt_id, uint8_t type) { + uint16_t tmp_acked_pkt_id = 0; if (buf == NULL) { return -EINVAL; } @@ -359,7 +364,8 @@ int mqtt_pack_publish_response_pkt(uint8_t* buf, uint16_t acked_pkt_id, uint8_t buf[0] |= MQTT_PUBREL_FLAG; } buf[1] = 0x02; - *(uint16_t*)(buf + 2) = htons(acked_pkt_id); + tmp_acked_pkt_id = htons(acked_pkt_id); + memcpy((buf + 2), &tmp_acked_pkt_id, 2); return 4; } -- 2.43.0