From afc0d3aa27c7fdc73b57e980b11e58ce93660c4d Mon Sep 17 00:00:00 2001 From: Johannes Schriewer Date: Mon, 30 Jul 2018 22:20:10 +0200 Subject: [PATCH] Bugfix: Do not allow DUP flag for QoS 0 Re #11 --- src/packet.c | 5 +++++ tests/encode_packet.c | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/packet.c b/src/packet.c index d80ba8c..9ab55b1 100644 --- a/src/packet.c +++ b/src/packet.c @@ -475,6 +475,11 @@ Buffer *encode_publish(PublishPayload *payload) { } buffer->data[buffer->position - 2] |= (payload->qos << 1); if (payload->duplicate) { + if (payload->qos == MQTT_QOS_0) { + DEBUG_LOG("You can not set a DUP flag for QoS Level 0."); + buffer_release(buffer); + return NULL; + } buffer->data[buffer->position - 2] |= 8; } diff --git a/tests/encode_packet.c b/tests/encode_packet.c index 42dbfbb..52970da 100644 --- a/tests/encode_packet.c +++ b/tests/encode_packet.c @@ -274,6 +274,25 @@ TestResult test_encode_publish_no_msg(void) { ); } +TestResult test_encode_publish_dup_qos0(void) { + char data[] = { + 0x33, 0x0e, // header, qos1, retain + 0x00, 0x0a, 't', 'e', 's', 't', '/', 't', 'o', 'p', 'i', 'c', + 0x00, 0x0a // packet id + }; + PublishPayload *payload = calloc(1, sizeof(PublishPayload)); + + payload->qos = MQTT_QOS_0; + payload->duplicate = true; + payload->retain = true; + payload->topic = "test/topic"; + payload->packet_id = 10; + + Buffer *encoded = mqtt_packet_encode(&(MQTTPacket){ PacketTypePublish, payload }); + free(payload); + TESTASSERT(encoded == NULL, "DUP and QoS level 0 is an incompatible combination"); +} + TestResult test_encode_publish_with_msg(void) { char data[] = { 0x3b, 0x15, // header, qos1, retain @@ -511,6 +530,7 @@ TESTS( TEST("Encode Connect with auth", test_encode_connect_auth), TEST("Encode ConnAck", test_encode_connack), TEST("Encode Publish with no message", test_encode_publish_no_msg), + TEST("Encode Publish with invalid flags", test_encode_publish_dup_qos0), TEST("Encode Publish with message", test_encode_publish_with_msg), TEST("Encode PubAck", test_encode_puback), TEST("Encode PubRec", test_encode_pubrec),