From: Nathael Pajani Date: Sat, 16 Mar 2019 16:28:02 +0000 (+0100) Subject: there is no packet ID in mqtt publish packets for QoS 0 publish X-Git-Url: http://git.techno-innov.fr/?a=commitdiff_plain;h=93c94e151bd3ecb72fcf3fee610b569947261867;p=soft%2Flpc122x%2Fcore there is no packet ID in mqtt publish packets for QoS 0 publish --- diff --git a/lib/protocols/mqtt.c b/lib/protocols/mqtt.c index d11a809..d0a62d4 100644 --- a/lib/protocols/mqtt.c +++ b/lib/protocols/mqtt.c @@ -253,10 +253,14 @@ int mqtt_pack_publish_packet(const struct mqtt_publish_pkt* pkt, uint8_t* buf, u return -ENODATA; } /* Compute message size - * Packet ID is 2 bytes long. There is no "message size" field in the publish packet, as the - * message size can be computed by substracting the topic string size and packet id size from - * the packet "remaining length" field. */ - remaining_length = 2 + pkt->message_size; + * There is no "message size" field in the publish packet, as the message size can be computed by + * substracting the topic string size and packet id size from the packet "remaining length" field. + */ + remaining_length = pkt->message_size; + /* Packet ID is 2 bytes long. If QoS is 0, then the packet must not include a packet ID */ + if (pkt->topic.QoS != 0) { + remaining_length += 2; + } /* Topic is mandatory */ if (pkt->topic.name == NULL) { return -EINVAL; @@ -283,9 +287,11 @@ 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.name, topic_len); /* Packet ID */ - tmp_packet_id = htons(pkt->packet_id); - memcpy((buf + len), &tmp_packet_id, 2); - len += 2; + if (pkt->topic.QoS != 0) { + 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) { memcpy((buf + len), pkt->application_message, pkt->message_size); @@ -334,13 +340,20 @@ int mqtt_unpack_publish_packet(struct mqtt_publish_pkt* pkt, uint8_t* buf, uint3 topic_len = ntohs(tmp); pkt->topic.name = (char*)(buf + idx + 2); idx += topic_len + 2; - if ((idx + 2) > size) { + /* Does it fit in the remaining length ? */ + tmp = idx; + if (pkt->topic.QoS != 0) { + tmp += 2; + } + if (tmp > size) { return -EPROTO; } /* Decode packet ID */ - idx += 2; + if (pkt->topic.QoS != 0) { memcpy(&tmp, (buf + idx), 2); pkt->packet_id = ntohs(tmp); + idx += 2; + } /* Get application message */ pkt->message_size = size - idx; if (pkt->message_size != 0) {