ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
async_stream_response.cpp
Go to the documentation of this file.
2#if !defined(USE_ESP32) && defined(USE_ARDUINO)
3
4#include <cinttypes>
5#include <cstring>
6
8#include "esphome/core/hal.h"
10#include "esphome/core/log.h"
11
12#ifndef USE_LIBRETINY
13#include <lwip/tcp.h>
14#endif
15
17
18ESPHOME_LOG_TAG(TAG, "web_server_base");
19
20static_assert(STREAM_ADD_FLAG_COPY == ASYNC_WRITE_FLAG_COPY && STREAM_ADD_FLAG_MORE == ASYNC_WRITE_FLAG_MORE,
21 "add_iovecs() flags must match the TCP library");
22
23// Bytes coalesced into one AsyncClient::add(); on the loop stack, so kept small
24static constexpr size_t ADD_SCRATCH_SIZE = 256;
25
26// Closes now and runs the disconnect callback. AsyncTCP (LibreTiny) deprecates close(bool); ESPAsyncTCP and
27// RPAsyncTCP need it, as their close() waits for the next poll.
28static void close_now(AsyncClient *client) {
29#ifdef USE_LIBRETINY
30 client->close();
31#else
32 client->close(true);
33#endif
34}
35
36#ifndef USE_LIBRETINY
37// Reaches the library's protected pcb
38struct AsyncClientPcb : AsyncClient {
39 static tcp_pcb *of(AsyncClient *client) { return client->*(&AsyncClientPcb::_pcb); }
40};
41#endif
42
43// Sends a RST and frees the pcb now. A graceful close queues its FIN behind data a stalled reader never takes, so
44// it would hold the pcb until the peer leaves. False on ESP8266/RP2, where the caller marks the stream disconnected;
45// LibreTiny's callback runs here or later from a queued error event that may still name the client, so never mark it.
46static bool abort_now(AsyncClient *client) {
47#ifdef USE_LIBRETINY
48 // AsyncTCP resets the pcb callbacks in the tcpip thread, aborts, then runs the disconnect callback here
49 client->abort();
50 return true;
51#else
52 // ESPAsyncTCP and RPAsyncTCP leave the pcb's error callback set, and RPAsyncTCP's would use the pcb lwIP freed
53 tcp_pcb *pcb = AsyncClientPcb::of(client);
54 if (pcb != nullptr)
55 tcp_err(pcb, nullptr);
56 client->abort();
57 return false;
58#endif
59}
60
61// The head strings may sit in flash on ESP8266, where String needs the flash helper to copy them
62#ifdef USE_ESP8266
63static String head_string(const char *str) { return String(reinterpret_cast<const __FlashStringHelper *>(str)); }
64#else
65static const char *head_string(const char *str) { return str; }
66#endif
67
68// The status line's code, for example 200 for "200 OK"; status may be in flash
69static int status_code(const char *status) {
70 int code = 0;
71 for (int i = 0; i < 3; i++) {
72 code = code * 10 + (progmem_read_byte(reinterpret_cast<const uint8_t *>(status + i)) - '0');
73 }
74 return code;
75}
76
77// Queues the head and hands the connection to the stream. The library runs _respond() in the network context right
78// after the handler returns; clientRelease() then unhooks the request, which frees itself and this response. A request
79// that ends before _respond() frees this response unanswered, which marks the stream disconnected for the main loop.
80class StreamHandoffResponse final : public AsyncWebServerResponse {
81 public:
82 StreamHandoffResponse(AsyncStreamResponse *stream, const char *status, const char *content_type,
83 std::span<const HttpHeader> headers, const char *body)
84 : stream_(stream), headers_(headers), body_(body) {
85 this->_code = status_code(status);
86 this->_contentType = head_string(content_type);
87 this->_sendContentLength = false;
88 }
89 ~StreamHandoffResponse() override {
90 if (this->stream_ != nullptr) {
91 this->stream_->state_.store(StreamState::STREAM_STATE_DISCONNECTED, std::memory_order_release);
92 }
93 }
94
95 void _respond(AsyncWebServerRequest *request) override {
96 AsyncClient *client = request->client();
97 // The library's own head: the status line, its default headers (copied by its constructor) and these
98 for (const auto &header : this->headers_) {
99 this->addHeader(head_string(header.name), head_string(header.value));
100 }
101 String head;
102 this->_assembleHead(head, request->version());
103 if (this->body_ != nullptr) {
104 head.concat(head_string(this->body_));
105 }
106 const size_t added = client->add(head.c_str(), head.length());
107 if (added != 0) {
108 client->send();
109 }
110 // lwIP can run short of memory while many connections close: the rest waits for the main loop as a C string
111 RAMUniquePtr<char[]> head_rest;
112 const size_t rest_len = head.length() - added;
113 if (rest_len != 0) {
114 head_rest = RAMAllocator<char>(RAMAllocator<char>::PREFER_INTERNAL).make_unique_array_for_overwrite(rest_len + 1);
115 if (head_rest != nullptr) {
116 std::memcpy(head_rest.get(), head.c_str() + added, rest_len + 1);
117 }
118 }
119 const bool head_kept = rest_len == 0 || head_rest != nullptr;
120 // Cleared first: clientRelease() may free the request, and this response with it
121 AsyncStreamResponse *stream = this->stream_;
122 this->stream_ = nullptr;
123 stream->attach_(request->clientRelease(), std::move(head_rest), head_kept);
124 }
125 bool _sourceValid() const override { return true; }
126
127 protected:
128 // Until _respond() hands the connection over
129 AsyncStreamResponse *stream_;
130 std::span<const HttpHeader> headers_;
131 const char *body_;
132};
133
134void AsyncStreamResponse::begin(AsyncWebServerRequest *request, const char *status, const char *content_type,
135 std::span<const HttpHeader> headers, const char *body) {
136 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory) the request owns and frees its response
137 request->send(new StreamHandoffResponse(this, status, content_type, headers, body));
138}
139
140void AsyncStreamResponse::attach_(AsyncClient *client, RAMUniquePtr<char[]> head_rest, bool head_kept) {
141 client->setRxTimeout(0);
142 // Backstop for data left unacked once writes stop; each send restarts it
143 client->setAckTimeout(SEND_STALL_TIMEOUT_MS);
144 client->setNoDelay(true);
145 // clientRelease() already cleared the request's data, ack, poll and error handlers
146 // Network context: store a flag and nothing else; the main loop frees the client. On LibreTiny async_tcp runs above
147 // the loop task and touches nothing after this callback, so the loop cannot free the client under it.
148 client->onDisconnect(
149 [](void *arg, AsyncClient *) {
151 std::memory_order_release);
152 },
153 this);
154 client->onTimeout(
155 [](void *arg, AsyncClient *, uint32_t) {
156 static_cast<AsyncStreamResponse *>(arg)->ack_timed_out_.store(true, std::memory_order_release);
157 },
158 this);
159 this->client_ = client;
160 // The ACK clock starts with the head
161 this->last_ack_ms_ = millis();
162 this->head_rest_ = std::move(head_rest);
163 // Without the rest of the head the stream cannot continue. Closing here, inside the client's receive callback,
164 // could free the pcb the library still uses after it, so the main loop closes it once the callback has returned.
165 if (!head_kept) {
166 this->close_requested_ = true;
167 }
168 // Last: the main loop reads everything above once it sees this
169 this->state_.store(StreamState::STREAM_STATE_ATTACHED, std::memory_order_release);
170}
171
173 AsyncClient *client = this->client_;
174 if (client == nullptr) {
175 return;
176 }
177 // Held so the RP2 network IRQ cannot run while the client goes away
179 client->onDisconnect(nullptr, nullptr);
180 client->onTimeout(nullptr, nullptr);
181 delete client; // NOLINT(cppcoreguidelines-owning-memory)
182}
183
185 if (this->close_requested_) {
186 return -1;
187 }
188 // Gone for good, before or after attaching
189 if (!this->is_connected()) {
190 this->close();
191 return -1;
192 }
193 // The request has not handed over the connection yet
194 if (!this->is_attached()) {
195 return 0;
196 }
197 // The rest of the head goes first; loop() sends it
198 if (this->head_rest_ != nullptr) {
199 return 0;
200 }
201 // Nothing to send is not a stall
202 if (iovecs_total(iov, iovcnt) == 0) {
203 return 0;
204 }
205 size_t sent = 0;
207 if (!this->stall_.is_running() || now - this->last_try_ms_ >= STALL_RETRY_MS) {
208 this->last_try_ms_ = now;
209 // RP2: the network IRQ may free the pcb between the check and the use, so hold it out across both
211 if (this->is_connected()) {
212#ifdef USE_ESP8266
213 // Every segment holds a full MSS pbuf on the heap until acked (LWIP_NETIF_TX_SINGLE_PBUF), so write only once
214 // the last send is acked, like ESPAsyncWebServer. canSend() is also false when a failed send never armed the
215 // library's ACK timeout, so the ACK age is checked here too.
216 if (!this->client_->canSend()) {
217 if (now - this->last_ack_ms_ >= SEND_STALL_TIMEOUT_MS) {
218 this->close_stuck_(now - this->last_ack_ms_, LOG_STR("without an ACK"));
219 return -1;
220 }
221 return 0;
222 }
223#endif
224 // Only an ACK grows the send buffer's free space (lwIP snd_buf). ESPAsyncTCP and RPAsyncTCP call onAck
225 // only once everything is acked, so it cannot measure this.
226 const size_t space_before = this->client_->space();
227 if (space_before > this->space_after_write_)
228 this->last_ack_ms_ = now;
229 char scratch[ADD_SCRATCH_SIZE];
230 sent = add_iovecs(*this->client_, iov, iovcnt, scratch, sizeof(scratch));
231 if (sent > 0) {
232 const size_t space_after = this->client_->space();
233 // On LibreTiny an ACK can arrive while the adds run in the tcpip thread; it leaves more space than they used.
234 // The space is then recorded as if it had not, so the ACKs for these bytes still count at the next write: a
235 // buffer the ACK emptied would otherwise look unchanged after an idle pause and the stream would be closed.
236 if (space_after + sent > space_before) {
237 this->last_ack_ms_ = now;
238 // add_iovecs() adds in several calls, so with ACKs between them it can queue more than space_before
239 this->space_after_write_ = sent < space_before ? space_before - sent : 0;
240 } else {
241 this->space_after_write_ = space_after;
242 }
243 }
244 }
245 }
246 if (sent > 0) {
247 this->stall_.clear();
248 // lwIP keeps queueing into a large buffer while the window is shut, so the buffer may never fill
249 if (now - this->last_ack_ms_ >= SEND_STALL_TIMEOUT_MS) {
250 this->close_stuck_(now - this->last_ack_ms_, LOG_STR("without an ACK"));
251 return -1;
252 }
253 return static_cast<ssize_t>(sent);
254 }
255 // Send buffer full, try again later; a buffer that stays full past the stall timeout is closed
256 return this->stall_or_close_(LOG_STR("without send progress")) ? -1 : 0;
257}
258
259ssize_t AsyncStreamResponse::write(const void *data, size_t len) {
260 StreamIovec iov = {const_cast<void *>(data), len};
261 return this->write(&iov, 1);
262}
263
264bool AsyncStreamResponse::stall_or_close_(const LogString *reason) {
267 return false;
268 }
269 this->close_stuck_(this->stall_.elapsed(now), reason);
270 return true;
271}
272
273void AsyncStreamResponse::close_stuck_(uint32_t elapsed_ms, const LogString *reason) {
274 ESP_LOGW(TAG, "Closing stuck stream after %" PRIu32 " ms %s", elapsed_ms, LOG_STR_ARG(reason));
275 this->abort_();
276}
277
279 this->close_requested_ = true;
280 this->close_client_(true);
281}
282
284 this->close_requested_ = true;
285 this->close_client_();
286}
287
289 // Before the connection is ours, close_requested_ keeps the close and loop() sends it once attached
290 if (this->close_sent_ || !this->is_connected() || !this->is_attached()) {
291 return;
292 }
293 this->close_sent_ = true;
295 if (!this->is_connected()) {
296 return;
297 }
298 if (!abort) {
299 close_now(this->client_);
300 } else if (!abort_now(this->client_)) {
301 this->state_.store(StreamState::STREAM_STATE_DISCONNECTED, std::memory_order_release);
302 }
303}
304
306 if (this->close_requested_) {
307 this->close_client_();
308 return;
309 }
310 if (this->ack_timed_out_.load(std::memory_order_acquire)) {
311 this->close_stuck_(SEND_STALL_TIMEOUT_MS, LOG_STR("without an ACK"));
312 return;
313 }
314 if (this->head_rest_ != nullptr) {
315 // Moved out so write() takes it; the stall and ACK clocks cover it like any write
316 RAMUniquePtr<char[]> rest = std::move(this->head_rest_);
317 const size_t len = strlen(rest.get());
318 const ssize_t sent = this->write(rest.get(), len);
319 if (sent >= 0 && static_cast<size_t>(sent) < len) {
320 memmove(rest.get(), rest.get() + sent, len - sent + 1);
321 this->head_rest_ = std::move(rest);
322 }
323 }
324}
325
326} // namespace esphome::web_server_base
327
328#endif // !USE_ESP32 && USE_ARDUINO
uint8_t status
Definition bl0942.h:8
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
Helper class to lock the lwIP TCPIP core when making lwIP API calls from non-TCPIP threads.
Definition helpers.h:2548
void loop()
Main loop, every pass. Aborts (RST) a stream whose last send went unacknowledged for SEND_STALL_TIMEO...
void close()
Main loop. Closes the connection; safe to call more than once.
void begin(AsyncWebServerRequest *request, const char *status, const char *content_type, std::span< const HttpHeader > headers, const char *body=nullptr)
Network context, from a request handler, once.
ssize_t write(StreamIovec *iov, int iovcnt)
Main loop.
void attach_(AsyncClient *client, RAMUniquePtr< char[]> head_rest, bool head_kept)
bool is_connected() const
The client is still connected.
bool is_attached() const
The connection is taken from the request and the head queued; write() needs it.
~AsyncStreamResponse()
Main loop, once safe_to_delete(): frees the connection.
bool start_or_expired(uint32_t now, uint32_t timeout_ms)
Starts the clock if needed; true once it has run for timeout_ms.
uint32_t elapsed(uint32_t now) const
__int64 ssize_t
Definition httplib.h:178
size_t iovecs_total(const Iovec *iov, int count)
Bytes in a gather list.
Definition stream_head.h:41
size_t add_iovecs(Client &client, const Iovec *iov, int count, char *scratch, size_t scratch_size)
Queues a gather list on an AsyncClient-like client through scratch, so each add() carries up to scrat...
ESPHOME_LOG_TAG(TAG, "web_server_base")
std::unique_ptr< T, RAMDeleter< T > > RAMUniquePtr
unique_ptr over RAMAllocator storage
Definition helpers.h:2659
const void size_t len
Definition hal.h:68
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
uint8_t progmem_read_byte(const uint8_t *addr)
Definition hal.h:51
static void uint32_t
watchdog_hw scratch[0]
One entry of the gather list AsyncStreamResponse::write() takes; the TCP libraries take plain buffers...
SemaphoreHandle_t lock