ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
http_request_arduino.cpp
Go to the documentation of this file.
2
3#if defined(USE_ARDUINO) && !defined(USE_ESP32) && !defined(USE_LIBRETINY)
4
5#include <cstring>
6
9
12#include "esphome/core/log.h"
14
15// Include BearSSL error constants for TLS failure diagnostics
16#ifdef USE_ESP8266
17#include <bearssl/bearssl_ssl.h>
18#endif
19
20namespace esphome::http_request {
21
22ESPHOME_LOG_TAG(TAG, "http_request");
23#ifdef USE_ESP8266
24// ESP8266 Arduino core (WiFiClientSecureBearSSL.cpp) returns -1000 on OOM
25static constexpr int ESP8266_SSL_ERR_OOM = -1000;
26#endif
27
28std::shared_ptr<HttpContainer> HttpRequestArduino::perform(const char *url, const char *method, const std::string &body,
29 const std::vector<Header> &request_headers,
30 const std::vector<std::string> &lower_case_collect_headers,
31 uint32_t timeout_ms) {
32 if (!network::is_connected()) {
33 this->status_momentary_error(1000);
34 ESP_LOGW(TAG, "HTTP Request failed; Not connected to network");
35 return nullptr;
36 }
37
38 std::shared_ptr<HttpContainerArduino> container = std::make_shared<HttpContainerArduino>();
39 container->set_parent(this);
40
41 const uint32_t start = millis();
42
43 // Only the scheme counts; "https:" later in the URL (a query string) does not make it secure
44 bool secure = ESPHOME_strncasecmp_P(url, ESPHOME_PSTR("https:"), 6) == 0;
45 container->set_secure(secure);
46 container->set_watchdog_timeout(this->get_watchdog_timeout(timeout_ms));
47
48 watchdog::WatchdogManager wdm(container->get_watchdog_timeout());
49
50 if (this->follow_redirects_) {
51 container->client_.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS);
52 container->client_.setRedirectLimit(this->redirect_limit_);
53 } else {
54 container->client_.setFollowRedirects(HTTPC_DISABLE_FOLLOW_REDIRECTS);
55 }
56
57#if defined(USE_ESP8266)
58 std::unique_ptr<WiFiClient> stream_ptr;
59#ifdef USE_HTTP_REQUEST_ESP8266_HTTPS
60 if (secure) {
61 ESP_LOGV(TAG, "ESP8266 HTTPS connection with WiFiClientSecure");
62 stream_ptr = std::make_unique<WiFiClientSecure>();
63 WiFiClientSecure *secure_client = static_cast<WiFiClientSecure *>(stream_ptr.get());
64 secure_client->setBufferSizes(this->tls_buffer_size_rx_, this->tls_buffer_size_tx_);
65 secure_client->setInsecure();
66 } else {
67 stream_ptr = std::make_unique<WiFiClient>();
68 }
69#else
70 ESP_LOGV(TAG, "ESP8266 HTTP connection with WiFiClient");
71 if (secure) {
72 ESP_LOGE(TAG, "Can't use HTTPS connection with esp8266_disable_ssl_support");
73 return nullptr;
74 }
75 stream_ptr = std::make_unique<WiFiClient>();
76#endif // USE_HTTP_REQUEST_ESP8266_HTTPS
77
78 bool status = container->client_.begin(*stream_ptr, url);
79
80#elif defined(USE_RP2)
81 if (secure) {
82 container->client_.setInsecure();
83 }
84 bool status = container->client_.begin(url);
85#endif
86
87 App.feed_wdt();
88
89 if (!status) {
90 ESP_LOGW(TAG, "HTTP Request failed; URL: %s", url);
91 container->end();
92 this->status_momentary_error(1000);
93 return nullptr;
94 }
95
96 container->client_.setReuse(true);
97 container->client_.setTimeout(timeout_ms);
98
99 if (this->useragent_ != nullptr) {
100 container->client_.setUserAgent(this->useragent_);
101 }
102 for (const auto &header : request_headers) {
103 container->client_.addHeader(header.name.c_str(), header.value.c_str(), false, true);
104 }
105
106 // returned needed headers must be collected before the requests
107 const char *header_keys[lower_case_collect_headers.size()];
108 int index = 0;
109 for (auto const &header_name : lower_case_collect_headers) {
110 header_keys[index++] = header_name.c_str();
111 }
112 container->client_.collectHeaders(header_keys, index);
113
114 App.feed_wdt();
115 container->status_code = container->client_.sendRequest(method, body.c_str());
116 App.feed_wdt();
117 if (container->status_code < 0) {
118#if defined(USE_ESP8266) && defined(USE_HTTP_REQUEST_ESP8266_HTTPS)
119 if (secure) {
120 WiFiClientSecure *secure_client = static_cast<WiFiClientSecure *>(stream_ptr.get());
121 int last_error = secure_client->getLastSSLError();
122
123 if (last_error != 0) {
124 const LogString *error_msg;
125 switch (last_error) {
126 case ESP8266_SSL_ERR_OOM:
127 error_msg = LOG_STR("Unable to allocate buffer memory");
128 break;
129 case BR_ERR_TOO_LARGE:
130 error_msg = LOG_STR("Incoming TLS record does not fit in receive buffer (BR_ERR_TOO_LARGE)");
131 break;
132 default:
133 error_msg = LOG_STR("Unknown SSL error");
134 break;
135 }
136 ESP_LOGW(TAG, "SSL failure: %s (Code: %d)", LOG_STR_ARG(error_msg), last_error);
137 if (last_error == ESP8266_SSL_ERR_OOM) {
138 ESP_LOGW(TAG, "Configured TLS buffer sizes: %u/%u bytes, check max free heap block using the debug component",
139 (unsigned int) this->tls_buffer_size_rx_, (unsigned int) this->tls_buffer_size_tx_);
140 }
141 } else {
142 ESP_LOGW(TAG, "Connection failure with no error code");
143 }
144 }
145#endif
146
147 ESP_LOGW(TAG, "HTTP Request failed; URL: %s; Error: %s", url,
148 HTTPClient::errorToString(container->status_code).c_str());
149
150 this->status_momentary_error(1000);
151 container->end();
152 return nullptr;
153 }
154 if (!is_success(container->status_code)) {
155 ESP_LOGE(TAG, "HTTP Request failed; URL: %s; Code: %d", url, container->status_code);
156 this->status_momentary_error(1000);
157 // Still return the container, so it can be used to get the status code and error message
158 }
159
160 container->response_headers_.clear();
161 auto header_count = container->client_.headers();
162 for (int i = 0; i < header_count; i++) {
163 const std::string header_name = str_lower_case(container->client_.headerName(i).c_str()); // NOLINT
164 if (should_collect_header(lower_case_collect_headers, header_name)) {
165 std::string header_value = container->client_.header(i).c_str();
166 ESP_LOGD(TAG, "Received response header, name: %s, value: %s", header_name.c_str(), header_value.c_str());
167 container->response_headers_.push_back({header_name, header_value});
168 }
169 }
170
171 // HTTPClient::getSize() returns -1 for chunked transfer encoding (no Content-Length).
172 // When cast to size_t, -1 becomes SIZE_MAX (4294967295 on 32-bit).
173 // The read() method uses a chunked transfer encoding decoder (read_chunked_) to strip
174 // chunk framing and deliver only decoded content. When the final 0-size chunk is received,
175 // is_chunked_ is cleared and content_length is set to the actual decoded size, so
176 // is_read_complete() returns true and callers exit their read loops correctly.
177 int content_length = container->client_.getSize();
178 ESP_LOGD(TAG, "Content-Length: %d", content_length);
179 container->content_length = (size_t) content_length;
180 // -1 (SIZE_MAX when cast to size_t) means chunked transfer encoding
181 container->set_chunked(content_length == -1);
182 container->duration_ms = millis() - start;
183
184 return container;
185}
186
187// Arduino HTTP read implementation
188//
189// WARNING: Return values differ from BSD sockets! See http_request.h for full documentation.
190//
191// Arduino's WiFiClient is inherently non-blocking - available() returns 0 when
192// no data is ready. We use connected() to distinguish "no data yet" from
193// "connection closed".
194//
195// WiFiClient behavior:
196// available() > 0: data ready to read
197// available() == 0 && connected(): no data yet, still connected
198// available() == 0 && !connected(): connection closed
199//
200// We normalize to HttpContainer::read() contract (NOT BSD socket semantics!):
201// > 0: bytes read
202// 0: no data yet, retry <-- NOTE: 0 means retry, NOT EOF!
203// < 0: error/connection closed <-- connection closed returns -1, not 0
204//
205// For chunked transfer encoding, read_chunked_() decodes chunk framing and delivers
206// only the payload data. When the final 0-size chunk is received, it clears is_chunked_
207// and sets content_length = bytes_read_ so is_read_complete() returns true.
208int HttpContainerArduino::read(uint8_t *buf, size_t max_len) {
209 const uint32_t start = millis();
211
212 WiFiClient *stream_ptr = this->client_.getStreamPtr();
213 if (stream_ptr == nullptr) {
214 ESP_LOGE(TAG, "Stream pointer vanished!");
215 return HTTP_ERROR_CONNECTION_CLOSED;
216 }
217
218 if (this->is_chunked_) {
219 int result = this->read_chunked_(buf, max_len, stream_ptr);
220 this->duration_ms += (millis() - start);
221 if (result > 0) {
222 return result;
223 }
224 // result <= 0: check for completion or errors
225 if (this->is_read_complete()) {
226 return 0; // Chunked transfer complete (final 0-size chunk received)
227 }
228 if (result < 0) {
229 return result; // Stream error during chunk decoding
230 }
231 // read_chunked_ returned 0: no data was available (available() was 0).
232 // This happens when the TCP buffer is empty - either more data is in flight,
233 // or the connection dropped. Arduino's connected() returns false only when
234 // both the remote has closed AND the receive buffer is empty, so any buffered
235 // data is fully drained before we report the drop.
236 if (!stream_ptr->connected()) {
237 return HTTP_ERROR_CONNECTION_CLOSED;
238 }
239 return 0; // No data yet, caller should retry
240 }
241
242 // Non-chunked path
243 int available_data = stream_ptr->available();
244 size_t remaining = (this->content_length > 0) ? (this->content_length - this->bytes_read_) : max_len;
245 int bufsize = std::min({max_len, remaining, (size_t) available_data});
246
247 if (bufsize == 0) {
248 this->duration_ms += (millis() - start);
249 if (this->is_read_complete()) {
250 return 0; // All content read successfully
251 }
252 if (!stream_ptr->connected()) {
253 return HTTP_ERROR_CONNECTION_CLOSED;
254 }
255 return 0; // No data yet, caller should retry
256 }
257
258 App.feed_wdt();
259 int read_len = stream_ptr->readBytes(buf, bufsize);
260 this->bytes_read_ += read_len;
261
262 this->duration_ms += (millis() - start);
263
264 return read_len;
265}
266
268 if (this->chunk_remaining_ == 0) {
270 this->chunk_remaining_ = 1; // repurpose as at-start-of-line flag
271 } else {
273 }
274}
275
276// Chunked transfer encoding decoder
277//
278// On Arduino, getStreamPtr() returns raw TCP data. For chunked responses, this includes
279// chunk framing (size headers, CRLF delimiters) mixed with payload data. This decoder
280// strips the framing and delivers only decoded content to the caller.
281//
282// Chunk format (RFC 9112 Section 7.1):
283// <hex-size>[;extension]\r\n
284// <data bytes>\r\n
285// ...
286// 0\r\n
287// [trailer-field\r\n]*
288// \r\n
289//
290// Non-blocking: only processes bytes already in the TCP receive buffer.
291// State (chunk_state_, chunk_remaining_) is preserved between calls, so partial
292// chunk headers or split \r\n sequences resume correctly on the next call.
293// Framing bytes (hex sizes, \r\n) may be consumed without producing output;
294// the caller sees 0 and retries via the normal read timeout logic.
295//
296// WiFiClient::read() returns -1 on error despite available() > 0 (connection reset
297// between check and read). On any stream error (c < 0 or readBytes <= 0), we return
298// already-decoded data if any; otherwise HTTP_ERROR_CONNECTION_CLOSED. The error
299// will surface again on the next call since the stream stays broken.
300//
301// Returns: > 0 decoded bytes, 0 no data available, < 0 error
302int HttpContainerArduino::read_chunked_(uint8_t *buf, size_t max_len, WiFiClient *stream) {
303 int total_decoded = 0;
304
305 while (total_decoded < (int) max_len && this->chunk_state_ != ChunkedState::COMPLETE) {
306 // Non-blocking: only process what's already buffered
307 if (stream->available() == 0)
308 break;
309
310 // CHUNK_DATA reads multiple bytes; handle before the single-byte switch
312 // Only read what's available, what fits in buf, and what remains in this chunk
313 size_t to_read =
314 std::min({max_len - (size_t) total_decoded, this->chunk_remaining_, (size_t) stream->available()});
315 if (to_read == 0)
316 break;
317 App.feed_wdt();
318 int read_len = stream->readBytes(buf + total_decoded, to_read);
319 if (read_len <= 0)
320 return total_decoded > 0 ? total_decoded : HTTP_ERROR_CONNECTION_CLOSED;
321 total_decoded += read_len;
322 this->chunk_remaining_ -= read_len;
323 this->bytes_read_ += read_len;
324 if (this->chunk_remaining_ == 0)
326 continue;
327 }
328
329 // All other states consume a single byte
330 int c = stream->read();
331 if (c < 0)
332 return total_decoded > 0 ? total_decoded : HTTP_ERROR_CONNECTION_CLOSED;
333
334 switch (this->chunk_state_) {
335 // Parse hex chunk size, one byte at a time: "<hex>[;ext]\r\n"
336 // Note: if no hex digits are parsed (e.g., bare \r\n), chunk_remaining_ stays 0
337 // and is treated as the final chunk. This is intentionally lenient — on embedded
338 // devices, rejecting malformed framing is less useful than terminating cleanly.
339 // Overflow of chunk_remaining_ from extremely long hex strings (>8 digits on
340 // 32-bit) is not checked; >4GB chunks are unrealistic on embedded targets and
341 // would simply cause fewer bytes to be read from that chunk.
343 if (c == '\n') {
344 // \n terminates the size line; chunk_remaining_ == 0 means last chunk
346 } else {
347 uint8_t hex = parse_hex_char(c);
348 if (hex != INVALID_HEX_CHAR) {
349 this->chunk_remaining_ = (this->chunk_remaining_ << 4) | hex;
350 } else if (c != '\r') {
351 this->chunk_state_ = ChunkedState::CHUNK_HEADER_EXT; // ';' starts extension, skip to \n
352 }
353 }
354 break;
355
356 // Skip chunk extension bytes until \n (e.g., ";name=value\r\n")
358 if (c == '\n') {
360 }
361 break;
362
363 // Consume \r\n trailing each chunk's data
365 if (c == '\n') {
367 this->chunk_remaining_ = 0; // reset for next chunk's hex accumulation
368 }
369 // else: \r is consumed silently, next iteration gets \n
370 break;
371
372 // Consume optional trailer headers and terminating empty line after final chunk.
373 // Per RFC 9112 Section 7.1: "0\r\n" is followed by optional "field\r\n" lines
374 // and a final "\r\n". chunk_remaining_ is repurposed as a flag: 1 = at start
375 // of line (may be the empty terminator), 0 = mid-line (reading a trailer field).
377 if (c == '\n') {
378 if (this->chunk_remaining_ != 0) {
379 this->chunk_state_ = ChunkedState::COMPLETE; // Empty line terminates trailers
380 } else {
381 this->chunk_remaining_ = 1; // End of trailer field, at start of next line
382 }
383 } else if (c != '\r') {
384 this->chunk_remaining_ = 0; // Non-CRLF char: reading a trailer field
385 }
386 // \r doesn't change the flag — it's part of \r\n line endings
387 break;
388
389 default:
390 break;
391 }
392
394 // Clear chunked flag and set content_length to actual decoded size so
395 // is_read_complete() returns true and callers exit their read loops
396 this->is_chunked_ = false;
397 this->content_length = this->bytes_read_;
398 }
399 }
400
401 return total_decoded;
402}
403
408
409} // namespace esphome::http_request
410
411#endif // USE_ARDUINO && !USE_ESP32
uint8_t status
Definition bl0942.h:8
void feed_wdt()
Feed the task watchdog.
void status_momentary_error(uint32_t length=5000)
Set error status flag and clear it after length ms.
int read_chunked_(uint8_t *buf, size_t max_len, WiFiClient *stream)
Decode chunked transfer encoding from the raw stream.
size_t chunk_remaining_
Bytes remaining in current chunk.
int read(uint8_t *buf, size_t max_len) override
void chunk_header_complete_()
Transition from chunk header to data or trailer based on parsed size.
virtual bool is_read_complete() const
Check if all expected content has been read.
bool is_chunked_
True if response uses chunked transfer encoding.
std::shared_ptr< HttpContainer > perform(const char *url, const char *method, const std::string &body, const std::vector< Header > &request_headers, const std::vector< std::string > &lower_case_collect_headers, uint32_t timeout_ms) override
std::shared_ptr< HttpContainer > start(const char *url, const char *method, const std::string &body, const std::vector< Header > &request_headers)
bool should_collect_header(const std::vector< std::string > &lower_case_collect_headers, const std::string &lower_header_name)
Check if a header name should be collected (linear scan, fine for small lists)
bool is_success(int const status)
Checks if the given HTTP status code indicates a successful request.
ESPHOME_LOG_TAG(TAG, "http_request")
@ CHUNK_DATA
Reading chunk data bytes.
@ COMPLETE
Finished: final chunk and trailers consumed.
@ CHUNK_HEADER
Reading hex digits of chunk size.
@ CHUNK_HEADER_EXT
Skipping chunk extensions until .
@ CHUNK_DATA_TRAIL
Skipping \r after chunk data.
@ CHUNK_TRAILER
Consuming trailer headers after final 0-size chunk.
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:36
std::string str_lower_case(const std::string &str)
Convert the string to lower case.
constexpr uint8_t parse_hex_char(char c)
Definition helpers.h:1445
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t