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