ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
api_frame_helper_plaintext.cpp
Go to the documentation of this file.
2#ifdef USE_API
3#ifdef USE_API_PLAINTEXT
5#include "esphome/core/hal.h"
7#include "esphome/core/log.h"
8#include "proto.h"
9#include <cstring>
10#include <cinttypes>
11
12#ifdef USE_ESP8266
13#include <pgmspace.h>
14#endif
15
16namespace esphome::api {
17
18static const char *const TAG = "api.plaintext";
19
20// Maximum bytes to log in hex format (168 * 3 = 504, under TX buffer size of 512)
21static constexpr size_t API_MAX_LOG_BYTES = 168;
22
23#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
24#define HELPER_LOG(msg, ...) \
25 do { \
26 char peername_buf[socket::SOCKADDR_STR_LEN]; \
27 this->get_peername_to(peername_buf); \
28 ESP_LOGVV(TAG, "%s (%s): " msg, this->client_name_, peername_buf, ##__VA_ARGS__); \
29 } while (0)
30#else
31#define HELPER_LOG(msg, ...) ((void) 0)
32#endif
33
34#ifdef HELPER_LOG_PACKETS
35#define LOG_PACKET_RECEIVED(buffer) \
36 do { \
37 char hex_buf_[format_hex_pretty_size(API_MAX_LOG_BYTES)]; \
38 ESP_LOGVV(TAG, "Received frame: %s", \
39 format_hex_pretty_to(hex_buf_, (buffer).data(), \
40 (buffer).size() < API_MAX_LOG_BYTES ? (buffer).size() : API_MAX_LOG_BYTES)); \
41 } while (0)
42#else
43#define LOG_PACKET_RECEIVED(buffer) ((void) 0)
44#endif
45
48 APIError err = init_common_();
49 if (err != APIError::OK) {
50 return err;
51 }
52
54 return APIError::OK;
55}
57 if (state_ != State::DATA) {
59 }
60 if (!this->overflow_buf_.empty()) [[unlikely]] {
62 }
63 return APIError::OK;
64}
65
73 // read header
74 while (!rx_header_parsed_) {
75 // Now that we know when the socket is ready, we can read up to 3 bytes
76 // into the rx_header_buf_ before we have to switch back to reading
77 // one byte at a time to ensure we don't read past the message and
78 // into the next one.
79
80 // Read directly into rx_header_buf_ at the current position
81 // Try to get to at least 3 bytes total (indicator + 2 varint bytes), then read one byte at a time
82 ssize_t received =
83 this->socket_->read(&rx_header_buf_[rx_header_buf_pos_], rx_header_buf_pos_ < 3 ? 3 - rx_header_buf_pos_ : 1);
85 if (err != APIError::OK) {
86 return err;
87 }
88
89 // If this was the first read, validate the indicator byte
90 if (rx_header_buf_pos_ == 0 && received > 0) {
91 if (rx_header_buf_[0] != 0x00) {
92#ifdef USE_API_NOISE
93 // Dual build (encryption supported but no key set): a 0x01 first byte
94 // is a Noise client hello. Hand the connection off to a Noise helper
95 // running the all-zeros provisioning PSK so the encryption key can be
96 // set without crossing the wire in plaintext. Preserve the bytes we
97 // already consumed; they are the start of the Noise 3-byte header.
98 if (rx_header_buf_[0] == 0x01) {
99 rx_header_buf_pos_ = static_cast<uint8_t>(received);
101 }
102#endif
104 HELPER_LOG("Bad indicator byte %u", rx_header_buf_[0]);
106 }
107 }
108
109 rx_header_buf_pos_ += received;
110
111 // Check for buffer overflow
112 if (rx_header_buf_pos_ >= sizeof(rx_header_buf_)) {
114 HELPER_LOG("Header buffer overflow");
116 }
117
118 // Need at least 3 bytes total (indicator + 2 varint bytes) before trying to parse
119 if (rx_header_buf_pos_ < 3) {
120 continue;
121 }
122
123 // At this point, we have at least 3 bytes total:
124 // - Validated indicator byte (0x00) stored at position 0
125 // - At least 2 bytes in the buffer for the varints
126 // Buffer layout:
127 // [0]: indicator byte (0x00)
128 // [1-3]: Message size varint (variable length)
129 // - 2 bytes would only allow up to 16383, which is less than noise's UINT16_MAX (65535)
130 // - 3 bytes allows up to 2097151, ensuring we support at least as much as noise
131 // [2-5]: Message type varint (variable length)
132 // We now attempt to parse both varints. If either is incomplete,
133 // we'll continue reading more bytes.
134
135 // Skip indicator byte at position 0
136 uint8_t varint_pos = 1;
137
138 // rx_header_buf_pos_ >= 3 and varint_pos == 1, so len >= 2
139 auto msg_size_varint = ProtoVarInt::parse_non_empty(&rx_header_buf_[varint_pos], rx_header_buf_pos_ - varint_pos);
140 if (!msg_size_varint.has_value()) {
141 // not enough data there yet
142 continue;
143 }
144
145 if (msg_size_varint.value > MAX_MESSAGE_SIZE) {
147 HELPER_LOG("Bad packet: message size %" PRIu32 " exceeds maximum %u",
148 static_cast<uint32_t>(msg_size_varint.value), MAX_MESSAGE_SIZE);
150 }
151 rx_header_parsed_len_ = static_cast<uint16_t>(msg_size_varint.value);
152
153 // Move to next varint position
154 varint_pos += msg_size_varint.consumed;
155
156 auto msg_type_varint = ProtoVarInt::parse(&rx_header_buf_[varint_pos], rx_header_buf_pos_ - varint_pos);
157 if (!msg_type_varint.has_value()) {
158 // not enough data there yet
159 continue;
160 }
161 if (msg_type_varint.value > std::numeric_limits<uint16_t>::max()) {
163 HELPER_LOG("Bad packet: message type %" PRIu32 " exceeds maximum %u",
164 static_cast<uint32_t>(msg_type_varint.value), std::numeric_limits<uint16_t>::max());
166 }
167 rx_header_parsed_type_ = static_cast<uint16_t>(msg_type_varint.value);
168 rx_header_parsed_ = true;
169 }
170 // header reading done
171
172 // Reserve space for body (+ null terminator so protobuf StringRef fields
173 // can be safely null-terminated in-place after decode)
174 this->rx_buf_.resize(this->rx_header_parsed_len_ + RX_BUF_NULL_TERMINATOR);
175
177 // more data to read
178 uint16_t to_read = rx_header_parsed_len_ - rx_buf_len_;
179 ssize_t received = this->socket_->read(&rx_buf_[rx_buf_len_], to_read);
180 APIError err = handle_socket_read_result_(received);
181 if (err != APIError::OK) {
182 return err;
183 }
184 rx_buf_len_ += static_cast<uint16_t>(received);
185 if (static_cast<uint16_t>(received) != to_read) {
186 // not all read
188 }
189 }
190
191 LOG_PACKET_RECEIVED(this->rx_buf_);
192
193 // Clear state for next frame (rx_buf_ still contains data for caller)
194 this->rx_buf_len_ = 0;
195 this->rx_header_buf_pos_ = 0;
196 this->rx_header_parsed_ = false;
197
198 return APIError::OK;
199}
200
202 APIError aerr = this->check_data_state_();
203 if (aerr != APIError::OK)
204 return aerr;
205
206 aerr = this->try_read_frame_();
207 if (aerr != APIError::OK) {
208 if (aerr == APIError::BAD_INDICATOR) {
209 // Make sure to tell the remote that we don't
210 // understand the indicator byte so it knows
211 // we do not support it.
212 // The \x00 first byte is the marker for plaintext.
213 //
214 // The remote will know how to handle the indicator byte,
215 // but it likely won't understand the rest of the message.
216 //
217 // We must send at least 3 bytes to be read, so we add
218 // a message after the indicator byte to ensures its long
219 // enough and can aid in debugging.
220 static constexpr uint8_t INDICATOR_MSG_SIZE = 19;
221#ifdef USE_ESP8266
222 static const char MSG_PROGMEM[] PROGMEM = "\x00"
223 "Bad indicator byte";
224 char msg[INDICATOR_MSG_SIZE];
225 memcpy_P(msg, MSG_PROGMEM, INDICATOR_MSG_SIZE);
226 this->write_raw_buf_(msg, INDICATOR_MSG_SIZE);
227#else
228 static const char MSG[] = "\x00"
229 "Bad indicator byte";
230 this->write_raw_buf_(MSG, INDICATOR_MSG_SIZE);
231#endif
232 }
233 return aerr;
234 }
235
236 buffer->data = this->rx_buf_.data();
237 buffer->data_len = this->rx_header_parsed_len_;
238 buffer->type = this->rx_header_parsed_type_;
239 return APIError::OK;
240}
241
242// Encode a 16-bit varint (1-3 bytes) using pre-computed length.
243ESPHOME_ALWAYS_INLINE static inline void encode_varint_16(uint16_t value, uint8_t varint_len, uint8_t *p) {
244 if (varint_len >= 2) {
245 *p++ = static_cast<uint8_t>(value | 0x80);
246 value >>= 7;
247 if (varint_len == 3) {
248 *p++ = static_cast<uint8_t>(value | 0x80);
249 value >>= 7;
250 }
251 }
252 *p = static_cast<uint8_t>(value);
253}
254
255// Encode an 8-bit varint (1-2 bytes) using pre-computed length.
256ESPHOME_ALWAYS_INLINE static inline void encode_varint_8(uint8_t value, uint8_t varint_len, uint8_t *p) {
257 if (varint_len == 2) {
258 *p++ = static_cast<uint8_t>(value | 0x80);
259 *p = static_cast<uint8_t>(value >> 7);
260 } else {
261 *p = value;
262 }
263}
264
265// Write plaintext header into pre-allocated padding before payload.
266// padding_size: bytes reserved before payload (HEADER_PADDING for first/single msg,
267// actual header size for contiguous batch messages).
268// Returns the total header length (indicator + varints).
269ESPHOME_ALWAYS_INLINE static inline uint8_t write_plaintext_header(uint8_t *buf_start, uint16_t payload_size,
270 uint8_t message_type, uint8_t padding_size) {
271 uint8_t size_varint_len = ProtoSize::varint16(payload_size);
272 uint8_t type_varint_len = ProtoSize::varint8(message_type);
273 uint8_t total_header_len = 1 + size_varint_len + type_varint_len;
274
275 // The header is right-justified within the padding so it sits immediately before payload.
276 //
277 // Single/first message (padding_size = HEADER_PADDING = 6):
278 // Example (small, header=3): [0-2] unused | [3] 0x00 | [4] size | [5] type | [6...] payload
279 // Example (medium, header=4): [0-1] unused | [2] 0x00 | [3-4] size | [5] type | [6...] payload
280 // Example (large, header=6): [0] 0x00 | [1-3] size | [4-5] type | [6...] payload
281 //
282 // Batch messages 2+ (padding_size = actual header size, no unused bytes):
283 // Example (small, header=3): [0] 0x00 | [1] size | [2] type | [3...] payload
284 // Example (medium, header=4): [0] 0x00 | [1-2] size | [3] type | [4...] payload
285#ifdef ESPHOME_DEBUG_API
286 assert(padding_size >= total_header_len);
287#endif
288 uint32_t header_offset = padding_size - total_header_len;
289
290 // Write the plaintext header
291 buf_start[header_offset] = 0x00; // indicator
292
293 // Encode varints directly into buffer using pre-computed lengths
294 encode_varint_16(payload_size, size_varint_len, buf_start + header_offset + 1);
295 encode_varint_8(message_type, type_varint_len, buf_start + header_offset + 1 + size_varint_len);
296
297 return total_header_len;
298}
299
301#ifdef ESPHOME_DEBUG_API
302 assert(this->state_ == State::DATA);
303#endif
304
305 uint16_t payload_size = static_cast<uint16_t>(buffer.get_buffer()->size() - HEADER_PADDING);
306 uint8_t *buffer_data = buffer.get_buffer()->data();
307 uint8_t header_len = write_plaintext_header(buffer_data, payload_size, type, HEADER_PADDING);
308 return this->write_raw_fast_buf_(buffer_data + HEADER_PADDING - header_len,
309 static_cast<uint16_t>(header_len + payload_size));
310}
311
313 std::span<const MessageInfo> messages) {
314#ifdef ESPHOME_DEBUG_API
315 assert(this->state_ == State::DATA);
316 assert(!messages.empty());
317#endif
318 uint8_t *buffer_data = buffer.get_buffer()->data();
319
320 // First message has max padding (header_size = HEADER_PADDING), may have unused leading bytes.
321 // Subsequent messages were encoded with exact header sizes (header_size = actual header len).
322 // write_plaintext_header right-justifies the header within header_size bytes of padding.
323 const auto &first = messages[0];
324 uint8_t *first_start = buffer_data + first.offset;
325 uint8_t header_len = write_plaintext_header(first_start, first.payload_size, first.message_type, HEADER_PADDING);
326 uint8_t *write_start = first_start + HEADER_PADDING - header_len;
327 uint16_t total_len = header_len + first.payload_size;
328
329 for (size_t i = 1; i < messages.size(); i++) {
330 const auto &msg = messages[i];
331 header_len = write_plaintext_header(buffer_data + msg.offset, msg.payload_size, msg.message_type, msg.header_size);
332 total_len += header_len + msg.payload_size;
333 }
334
335 return this->write_raw_fast_buf_(write_start, total_len);
336}
337
338} // namespace esphome::api
339#endif // USE_API_PLAINTEXT
340#endif // USE_API
void resize(size_t n) ESPHOME_ALWAYS_INLINE
Definition api_buffer.h:43
APIError handle_socket_read_result_(ssize_t received)
APIError ESPHOME_ALWAYS_INLINE write_raw_fast_buf_(const void *data, uint16_t len)
APIError write_raw_buf_(const void *data, uint16_t len, ssize_t sent=WRITE_NOT_ATTEMPTED)
std::unique_ptr< socket::Socket > socket_
APIError ESPHOME_ALWAYS_INLINE check_data_state_() const
bool empty() const
True when no backlogged data is waiting.
APIError try_read_frame_()
Read a packet into the rx_buf_.
APIError init() override
Initialize the frame helper, returns OK if successful.
APIError write_protobuf_packet(uint8_t type, ProtoWriteBuffer buffer) override
APIError read_packet(ReadPacketBuffer *buffer) override
APIError write_protobuf_messages(ProtoWriteBuffer buffer, std::span< const MessageInfo > messages) override
static constexpr uint8_t ESPHOME_ALWAYS_INLINE varint8(uint8_t value)
Definition proto.h:688
static constexpr uint8_t ESPHOME_ALWAYS_INLINE varint16(uint16_t value)
Definition proto.h:683
static ProtoVarIntResult ESPHOME_ALWAYS_INLINE parse_non_empty(const uint8_t *buffer, uint32_t len)
Parse a varint from buffer.
Definition proto.h:140
static ProtoVarIntResult ESPHOME_ALWAYS_INLINE parse(const uint8_t *buffer, uint32_t len)
Parse a varint from buffer (safe for empty buffers).
Definition proto.h:153
APIBuffer * get_buffer() const
Definition proto.h:271
uint16_t type
__int64 ssize_t
Definition httplib.h:178
uint16_t size
Definition helpers.cpp:25
static void uint32_t
uint32_t payload_size()