@@ -70,6 +70,7 @@ MqttClient::MqttClient(Client* client) :
70
70
_keepAliveInterval(60 * 1000L ),
71
71
_connectionTimeout(30 * 1000L ),
72
72
_tx_payload_buffer_size(TX_PAYLOAD_BUFFER_SIZE),
73
+ _last_mallocd_size(0 ), // DEBUG NOOJ
73
74
_connectError(MQTT_SUCCESS),
74
75
_connected(false ),
75
76
_subscribeQos(0x00 ),
@@ -666,6 +667,36 @@ size_t MqttClient::write(const uint8_t *buf, size_t size)
666
667
667
668
if (_txPayloadBuffer == NULL ) {
668
669
_txPayloadBuffer = (uint8_t *)malloc (_tx_payload_buffer_size);
670
+ _last_mallocd_size = _tx_payload_buffer_size; // DEBUG NOOJ
671
+ }
672
+
673
+ if (_txPayloadBufferIndex + size > _last_mallocd_size) {
674
+ log_e (
675
+ " MqttClient::write() ERROR: BUFFER OVERFLOW: _last_mallocd_size = %d, total bytes being written = %d" ,
676
+ _last_mallocd_size, _txPayloadBufferIndex + size
677
+ );
678
+
679
+ /*
680
+ * Working example of buffer overflow bug:
681
+ *
682
+ // make my_settings > 512 chars
683
+ mqttClient.beginMessage(SETTINGS_TOPIC);
684
+ mqttClient.print(my_settings); // prints first 256 chars of my_settings
685
+ mqttClient.endMessage();
686
+
687
+ mqttClient.setTxPayloadSize(512);
688
+ mqttClient.beginMessage(SETTINGS_TOPIC);
689
+ mqttClient.print(my_settings); // heap corruption
690
+ mqttClient.endMessage();
691
+
692
+ // output
693
+ [V][ssl_client.cpp:295] send_ssl_data(): Writing HTTP request with 17 bytes...
694
+ [V][ssl_client.cpp:295] send_ssl_data(): Writing HTTP request with 256 bytes...
695
+ [I][MqttClient.cpp:815] setTxPayloadSize(): MqttClient::setTxPayloadSize(): NOOJ says: _txPayloadBuffer should be freed and NULLed here.
696
+ [E][MqttClient.cpp:677] write(): MqttClient::write() ERROR: BUFFER OVERFLOW: _last_mallocd_size = 256, total bytes being written = 512
697
+ CORRUPT HEAP: multi_heap.c:432 detected at 0x3ffd6ab4
698
+ abort() was called at PC 0x4008d447 on core 1
699
+ */
669
700
}
670
701
671
702
memcpy (&_txPayloadBuffer[_txPayloadBufferIndex], buf, size);
@@ -803,6 +834,7 @@ void MqttClient::setConnectionTimeout(unsigned long timeout)
803
834
void MqttClient::setTxPayloadSize (unsigned short size)
804
835
{
805
836
// NOOJ WAS HERE
837
+ log_i (" MqttClient::setTxPayloadSize(): NOOJ says: _txPayloadBuffer should be freed and NULLed here." );
806
838
_tx_payload_buffer_size = size;
807
839
}
808
840
0 commit comments