From 197cf6f445bf3bb70aa367f782c648028aa17bf9 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 7 Jan 2026 19:56:16 -1000 Subject: [PATCH] [web_server] Use centralized length constants for buffer sizing --- esphome/components/web_server/web_server.cpp | 13 ++++++++----- esphome/core/entity_base.h | 8 +++++++- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/esphome/components/web_server/web_server.cpp b/esphome/components/web_server/web_server.cpp index e5705d7b47..3a2ae79094 100644 --- a/esphome/components/web_server/web_server.cpp +++ b/esphome/components/web_server/web_server.cpp @@ -498,13 +498,16 @@ static void set_json_id(JsonObject &root, EntityBase *obj, const char *prefix, J // Build id into stack buffer - ArduinoJson copies the string // Format: {prefix}/{device?}/{name} - // Buffer size guaranteed by schema validation (NAME_MAX_LENGTH=120): - // With devices: domain(20) + "/" + device(120) + "/" + name(120) + null = 263, rounded up to 280 for safety margin - // Without devices: domain(20) + "/" + name(120) + null = 142, rounded up to 150 for safety margin + // Buffer sizes use constants from entity_base.h validated in core/config.py #ifdef USE_DEVICES - char id_buf[280]; + // domain + "/" + device + "/" + name + null + static constexpr size_t ID_BUF_SIZE = + ESPHOME_DOMAIN_MAX_LEN + 1 + ESPHOME_DEVICE_NAME_MAX_LEN + 1 + ESPHOME_FRIENDLY_NAME_MAX_LEN + 1; + char id_buf[ID_BUF_SIZE]; #else - char id_buf[150]; + // domain + "/" + name + null + static constexpr size_t ID_BUF_SIZE = ESPHOME_DOMAIN_MAX_LEN + 1 + ESPHOME_FRIENDLY_NAME_MAX_LEN + 1; + char id_buf[ID_BUF_SIZE]; #endif char *p = id_buf; memcpy(p, prefix, prefix_len); diff --git a/esphome/core/entity_base.h b/esphome/core/entity_base.h index 1649077dd0..7208618832 100644 --- a/esphome/core/entity_base.h +++ b/esphome/core/entity_base.h @@ -16,7 +16,13 @@ namespace esphome { // Maximum device name length - keep in sync with validate_hostname() in esphome/core/config.py static constexpr size_t ESPHOME_DEVICE_NAME_MAX_LEN = 31; -// Maximum size for object_id buffer - keep in sync with friendly_name cv.Length(max=120) in esphome/core/config.py +// Maximum friendly name length - keep in sync with friendly_name cv.Length(max=120) in esphome/core/config.py +static constexpr size_t ESPHOME_FRIENDLY_NAME_MAX_LEN = 120; + +// Maximum domain length (longest: "alarm_control_panel" = 19) +static constexpr size_t ESPHOME_DOMAIN_MAX_LEN = 20; + +// Maximum size for object_id buffer (friendly_name + margin for sanitization) static constexpr size_t OBJECT_ID_MAX_LEN = 128; enum EntityCategory : uint8_t {