From 851dc3b7ad873b1ea1478c2c104c4599ab399c31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=93scar=20Retana?= Date: Sat, 17 Dec 2016 16:40:08 -0600 Subject: [PATCH] Truncates payload if it doesn't fit in buffer When function Adafruit_MQTT::publishPacket constructs the MQTT packets to be published, no validation was done to make sure that the function never writes more than MAXBUFFERSIZE into buffer. This could lead to very difficult to debug problems, because the program quickly crashes after writing more than MAXBUFFERSIZE into buffer. This proposed change truncates the payload (only if necessary) to fit buffer. Of course, truncating the payload is still a problem, but it is easier to debug and find. A debug message will let know that the payload was truncated to fit MAXBUFFERSIZE. --- Adafruit_MQTT.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Adafruit_MQTT.cpp b/Adafruit_MQTT.cpp index f08ec05..05731a4 100644 --- a/Adafruit_MQTT.cpp +++ b/Adafruit_MQTT.cpp @@ -675,6 +675,14 @@ uint16_t Adafruit_MQTT::publishPacket(uint8_t *packet, const char *topic, packet_id_counter++; } + // Truncates payload if it doesn't fit in buffer + uint16_t used_buffer = p - packet; + uint16_t unused_buffer = MAXBUFFERSIZE - used_buffer; + if (bLen > unused_buffer) { + bLen = unused_buffer; + DEBUG_PRINTLN(F("Payload truncated to fit MAXBUFFERSIZE")); + } + memmove(p, data, bLen); p+= bLen; len = p - packet;