[mqtt] Use stack buffers for discovery message formatting

This commit is contained in:
J. Nick Koston
2026-01-14 13:57:45 -10:00
parent f1e5d3a39a
commit 2182d1e9f0
2 changed files with 13 additions and 2 deletions

View File

@@ -91,7 +91,15 @@ void MQTTClientComponent::send_device_info_() {
uint8_t index = 0;
for (auto &ip : network::get_ip_addresses()) {
if (ip.is_set()) {
root["ip" + (index == 0 ? "" : esphome::to_string(index))] = ip.str();
char key[8]; // "ip" + up to 3 digits + null
char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
if (index == 0) {
strcpy(key, "ip");
} else {
snprintf(key, sizeof(key), "ip%u", index);
}
ip.str_to(ip_buf);
root[key] = ip_buf;
index++;
}
}

View File

@@ -232,7 +232,10 @@ bool MQTTComponent::send_discovery_() {
#else
const char *fmt = ver_fmt;
#endif
device_info[MQTT_DEVICE_SW_VERSION] = str_sprintf(fmt, App.get_config_hash());
// sizeof(ver_fmt) + 8: format specifier expands to 8 hex digits, plus safety margin
char version_buf[sizeof(ver_fmt) + 8];
snprintf(version_buf, sizeof(version_buf), fmt, App.get_config_hash());
device_info[MQTT_DEVICE_SW_VERSION] = version_buf;
device_info[MQTT_DEVICE_MODEL] = ESPHOME_BOARD;
#if defined(USE_ESP8266) || defined(USE_ESP32)
device_info[MQTT_DEVICE_MANUFACTURER] = "Espressif";