ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
web_server_idf.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2
3#include <algorithm>
4#include <cstdarg>
5#include <memory>
6#include <cstdio>
7#include <cstring>
8#include <cctype>
9#include <cinttypes>
10
13#include "esphome/core/log.h"
14
15#include <mbedtls/base64.h>
16#include <freertos/FreeRTOS.h>
17#include <freertos/task.h>
18
19#include "utils.h"
20#include "sse_chunk.h"
21#include "web_server_idf.h"
22
23#ifdef USE_WEBSERVER_AUTH_DIGEST
24#include <esp_random.h>
25#include <esp_rom_md5.h>
26#endif
27
28#ifdef USE_WEBSERVER_OTA
29#include <multipart_parser.h>
30#include "multipart.h" // For parse_multipart_boundary and other utils
31#endif
32
33#ifdef USE_WEBSERVER
36#endif // USE_WEBSERVER
37
38// Include socket headers after Arduino headers to avoid IPADDR_NONE/INADDR_NONE macro conflicts
39#include <cerrno>
40#include <sys/socket.h>
41
43
44// Status strings not provided by esp_http_server.h
45#ifndef HTTPD_401
46#define HTTPD_401 "401 Unauthorized"
47#endif
48#ifndef HTTPD_403
49#define HTTPD_403 "403 Forbidden"
50#endif
51#ifndef HTTPD_409
52#define HTTPD_409 "409 Conflict"
53#endif
54#ifndef HTTPD_422
55#define HTTPD_422 "422 Unprocessable Entity"
56#endif
57
58#define CRLF_STR "\r\n"
59#define CRLF_LEN (sizeof(CRLF_STR) - 1)
60
61ESPHOME_LOG_TAG(TAG, "web_server_idf");
62
63// Only prepare_json_() may hold the JSON arena: every other frame in this file is capped below one
64// arena. Measured at -Os on GCC 14; newer toolchains stay checked on purpose, older ones skip it.
65#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 14 && defined(__OPTIMIZE_SIZE__)
66#pragma GCC diagnostic error "-Wstack-usage=2048"
67#endif
68
69// Chunk size for streaming request bodies; matches the Arduino AsyncWebServer buffer size.
70// Buffers of this size must live on the heap - the httpd task stack is too small.
71static constexpr size_t RECV_CHUNK_SIZE = 1460;
72static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024; // Yield every 16KB to prevent watchdog
73
74// Global instance to avoid guard variable (saves 8 bytes)
75// This is initialized at program startup before any threads
76namespace {
77// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
78DefaultHeaders default_headers_instance;
79} // namespace
80
81DefaultHeaders &DefaultHeaders::Instance() { return default_headers_instance; }
82
83void DefaultHeaders::apply_(httpd_req_t *req, uint8_t skip_mask) const {
84 for (size_t i = 0; i < this->headers_.size(); i++) {
85 if (!(skip_mask & (1U << i)))
86 httpd_resp_set_hdr(req, this->headers_[i].name, this->headers_[i].value);
87 }
88}
89
90namespace {
91// Non-blocking send function to prevent watchdog timeouts when TCP buffers are full
106[[maybe_unused]] int nonblocking_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags) {
107 if (buf == nullptr) {
108 return HTTPD_SOCK_ERR_INVALID;
109 }
110
111 // Use MSG_DONTWAIT to prevent blocking when TCP send buffer is full
112 int ret = send(sockfd, buf, buf_len, flags | MSG_DONTWAIT);
113 if (ret < 0) {
114 const int err = errno;
115 if (err == EAGAIN || err == EWOULDBLOCK) {
116 // Buffer full - retry later
117 return HTTPD_SOCK_ERR_TIMEOUT;
118 }
119 // Real error
120 ESP_LOGD(TAG, "send error: errno %d", err);
121 return HTTPD_SOCK_ERR_FAIL;
122 }
123 return ret;
124}
125} // namespace
126
127void AsyncWebServer::safe_close_with_shutdown(httpd_handle_t hd, int sockfd) {
128 // CRITICAL: Shut down receive BEFORE closing to prevent lwIP race conditions
129 //
130 // The race condition occurs because close() initiates lwIP teardown while
131 // the TCP/IP thread can still receive packets, causing assertions when
132 // recv_tcp() sees partially-torn-down state.
133 //
134 // By shutting down receive first, we tell lwIP to stop accepting new data BEFORE
135 // the teardown begins, eliminating the race window. We only shutdown RD (not RDWR)
136 // to allow the FIN packet to be sent cleanly during close().
137 //
138 // Note: This function may be called with an already-closed socket if the network
139 // stack closed it. In that case, shutdown() will fail but close() is safe to call.
140 //
141 // See: https://github.com/esphome/esphome-webserver/issues/163
142
143 // Attempt shutdown - ignore errors as socket may already be closed
144 shutdown(sockfd, SHUT_RD);
145
146 // Always close - safe even if socket is already closed by network stack
147 close(sockfd);
148}
149
151 if (this->server_) {
152 httpd_stop(this->server_);
153 this->server_ = nullptr;
154 }
155}
156
158 if (this->server_) {
159 this->end();
160 }
161 // Allow room for SerializationBuffer's 640-byte stack buffer and HTTP request handling.
162 httpd_config_t config = HTTPD_DEFAULT_CONFIG();
163 config.stack_size = 4512;
164 config.server_port = this->port_;
165 config.max_open_sockets = WEB_SERVER_MAX_OPEN_SOCKETS;
166 config.uri_match_fn = [](const char * /*unused*/, const char * /*unused*/, size_t /*unused*/) { return true; };
167 // Always enable LRU purging to handle socket exhaustion gracefully.
168 // When max sockets is reached, the oldest connection is closed to make room for new ones.
169 // This prevents "httpd_accept_conn: error in accept (23)" errors.
170 // See: https://github.com/esphome/esphome/issues/12464
171 config.lru_purge_enable = true;
172 // Use custom close function that shuts down before closing to prevent lwIP race conditions
174 if (httpd_start(&this->server_, &config) == ESP_OK) {
175 const httpd_uri_t handler_get = {
176 .uri = "",
177 .method = HTTP_GET,
179 .user_ctx = this,
180 };
181 httpd_register_uri_handler(this->server_, &handler_get);
182
183 const httpd_uri_t handler_post = {
184 .uri = "",
185 .method = HTTP_POST,
187 .user_ctx = this,
188 };
189 httpd_register_uri_handler(this->server_, &handler_post);
190
191 const httpd_uri_t handler_options = {
192 .uri = "",
193 .method = HTTP_OPTIONS,
195 .user_ctx = this,
196 };
197 httpd_register_uri_handler(this->server_, &handler_options);
198 }
199}
200
201esp_err_t AsyncWebServer::request_post_handler(httpd_req_t *r) {
202 ESP_LOGVV(TAG, "Enter AsyncWebServer::request_post_handler. uri=%s", r->uri);
203 auto content_type = request_get_header(r, "Content-Type");
204
205 if (!request_has_header(r, "Content-Length")) {
206 ESP_LOGW(TAG, "Content length is required for post: %s", r->uri);
207 httpd_resp_send_err(r, HTTPD_411_LENGTH_REQUIRED, nullptr);
208 return ESP_OK;
209 }
210
211 if (content_type.has_value()) {
212 const char *content_type_char = content_type.value().c_str();
213
214 // Check most common case first
215 size_t content_type_len = strlen(content_type_char);
216 if (strcasestr_n(content_type_char, content_type_len, "application/x-www-form-urlencoded") != nullptr) {
217 // Normal form data - proceed with regular handling
218#ifdef USE_WEBSERVER_OTA
219 } else if (strcasestr_n(content_type_char, content_type_len, "multipart/form-data") != nullptr) {
220 auto *server = static_cast<AsyncWebServer *>(r->user_ctx);
221 return server->handle_multipart_upload_(r, content_type_char);
222#endif
223 } else {
224 // Other content types (e.g. application/json) are delivered raw to a matching
225 // custom handler via handleBody(), like the Arduino AsyncWebServer does
226 auto *server = static_cast<AsyncWebServer *>(r->user_ctx);
227 return server->handle_raw_body_(r, content_type_char);
228 }
229 }
230
231 // Handle regular form data
232 if (r->content_len > CONFIG_HTTPD_MAX_REQ_HDR_LEN) {
233 ESP_LOGW(TAG, "Request size is to big: %zu", r->content_len);
234 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
235 return ESP_FAIL;
236 }
237
238 std::string post_query;
239 if (r->content_len > 0) {
240 post_query.resize(r->content_len);
241 const int ret = httpd_req_recv(r, &post_query[0], r->content_len + 1);
242 if (ret <= 0) { // 0 return value indicates connection closed
243 if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
244 httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT, nullptr);
245 return ESP_ERR_TIMEOUT;
246 }
247 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
248 return ESP_FAIL;
249 }
250 }
251
252 AsyncWebServerRequest req(r, std::move(post_query));
253 return static_cast<AsyncWebServer *>(r->user_ctx)->request_handler_(&req);
254}
255
256esp_err_t AsyncWebServer::request_handler(httpd_req_t *r) {
257 ESP_LOGVV(TAG, "Enter AsyncWebServer::request_handler. method=%u, uri=%s", r->method, r->uri);
259 return static_cast<AsyncWebServer *>(r->user_ctx)->request_handler_(&req);
260}
261
263 for (auto *handler : this->handlers_) {
264 if (handler->canHandle(request)) {
265 // At now process only basic requests.
266 // OTA requires multipart request support and handleUpload for it
267 handler->handleRequest(request);
268 return ESP_OK;
269 }
270 }
271 if (this->on_not_found_) {
272 this->on_not_found_(request);
273 return ESP_OK;
274 }
275 return ESP_ERR_NOT_FOUND;
276}
277
278esp_err_t AsyncWebServer::handle_raw_body_(httpd_req_t *r, const char *content_type) {
280 AsyncWebHandler *handler = nullptr;
281 for (auto *h : this->handlers_) {
282 if (h->canHandle(&req)) {
283 handler = h;
284 break;
285 }
286 }
287
288 if (handler == nullptr) {
289 ESP_LOGW(TAG, "Unsupported content type for POST: %s", content_type);
290 // fallback to get handler to support backward compatibility
291 return this->request_handler_(&req);
292 }
293
294 const size_t total = r->content_len;
295 if (total > 0) {
296 auto buffer = std::make_unique_for_overwrite<char[]>(RECV_CHUNK_SIZE);
297 size_t bytes_since_yield = 0;
298
299 for (size_t index = 0; index < total;) {
300 int recv_len = httpd_req_recv(r, buffer.get(), std::min(total - index, RECV_CHUNK_SIZE));
301
302 if (recv_len <= 0) {
303 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
304 nullptr);
305 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
306 }
307
308 handler->handleBody(&req, reinterpret_cast<uint8_t *>(buffer.get()), recv_len, index, total);
309 index += recv_len;
310 bytes_since_yield += recv_len;
311
312 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
313 vTaskDelay(1);
314 bytes_since_yield = 0;
315 }
316 }
317 }
318
319 handler->handleRequest(&req);
320 return ESP_OK;
321}
322
324#ifdef USE_WEBSERVER_OTA
325 if (this->on_disconnect_)
326 this->on_disconnect_();
327#endif
328 delete this->rsp_;
329 for (auto *param : this->params_) {
330 delete param; // NOLINT(cppcoreguidelines-owning-memory)
331 }
332}
333
334bool AsyncWebServerRequest::hasHeader(const char *name) const { return request_has_header(*this, name); }
335
336optional<std::string> AsyncWebServerRequest::get_header(const char *name) const {
337 return request_get_header(*this, name);
338}
339
340size_t AsyncWebServerRequest::get_header_to(const char *name, std::span<char> buf) const {
341 return request_get_header_to(*this, name, buf);
342}
343
344StringRef AsyncWebServerRequest::url_to(std::span<char, URL_BUF_SIZE> buffer) const {
345 const char *uri = this->req_->uri;
346 const char *query_start = strchr(uri, '?');
347 size_t uri_len = query_start ? static_cast<size_t>(query_start - uri) : strlen(uri);
348 size_t copy_len = std::min(uri_len, URL_BUF_SIZE - 1);
349 memcpy(buffer.data(), uri, copy_len);
350 buffer[copy_len] = '\0';
351 // Decode URL-encoded characters in-place (e.g., %20 -> space)
352 size_t decoded_len = url_decode(buffer.data());
353 return StringRef(buffer.data(), decoded_len);
354}
355
356void AsyncWebServerRequest::redirect(const char *url) {
357 httpd_resp_set_status(*this, "302 Found");
358 httpd_resp_set_hdr(*this, "Location", url);
359 httpd_resp_set_hdr(*this, "Connection", "close");
360 httpd_resp_send(*this, nullptr, 0);
361}
362
363void AsyncWebServerRequest::init_response_(AsyncWebServerResponse *rsp, int code, const char *content_type) {
364 // Set status code - use constants for common codes, default to 500 for unknown codes
365 const char *status;
366 switch (code) {
367 case 200:
368 status = HTTPD_200;
369 break;
370 case 204:
371 status = HTTPD_204;
372 break;
373 case 400:
374 status = HTTPD_400;
375 break;
376 case 401:
377 status = HTTPD_401;
378 break;
379 case 403:
380 status = HTTPD_403;
381 break;
382 case 404:
383 status = HTTPD_404;
384 break;
385 case 409:
386 status = HTTPD_409;
387 break;
388 case 422:
389 status = HTTPD_422;
390 break;
391 default:
392 status = HTTPD_500;
393 break;
394 }
395 httpd_resp_set_status(*this, status);
396
397 if (content_type && *content_type) {
398 httpd_resp_set_type(*this, content_type);
399 }
400 httpd_resp_set_hdr(*this, "Accept-Ranges", "none");
401
402 // A response object sends the defaults in send(), after its own headers, so one it set itself can
403 // replace a default of the same name (httpd_resp_set_hdr only appends).
404 if (rsp == nullptr)
406
407 delete this->rsp_;
408 this->rsp_ = rsp;
409}
410
413 httpd_resp_send(*this, response->get_content_data(), response->get_content_size());
414}
415
416#ifdef USE_WEBSERVER_AUTH
417
418#ifdef USE_WEBSERVER_AUTH_DIGEST
419namespace {
420
421// Extract the value of a Digest auth parameter (e.g. "nonce") from the comma-separated
422// parameter list. Values may be quoted or bare. Returns an empty ref when the key is absent.
423// Only whole parameter names match, so "nc" does not match inside "cnonce".
424StringRef digest_param(StringRef params, const char *key) {
425 size_t key_len = strlen(key);
426 const char *base = params.c_str();
427 size_t n = params.size();
428 size_t i = 0;
429 while (i < n) {
430 while (i < n && (base[i] == ' ' || base[i] == ','))
431 i++;
432 size_t name_start = i;
433 while (i < n && base[i] != '=' && base[i] != ',')
434 i++;
435 if (i >= n || base[i] == ',')
436 continue; // token without a '=', skip it
437 size_t name_len = i - name_start;
438 while (name_len > 0 && base[name_start + name_len - 1] == ' ')
439 name_len--;
440 i++; // consume '='
441 const char *val_start;
442 size_t val_len;
443 if (i < n && base[i] == '"') {
444 i++;
445 val_start = base + i;
446 while (i < n && base[i] != '"')
447 i++;
448 val_len = (base + i) - val_start;
449 if (i < n)
450 i++; // consume closing quote
451 } else {
452 val_start = base + i;
453 while (i < n && base[i] != ',')
454 i++;
455 val_len = (base + i) - val_start;
456 }
457 if (name_len == key_len && memcmp(base + name_start, key, key_len) == 0)
458 return StringRef(val_start, val_len);
459 while (i < n && base[i] != ',')
460 i++;
461 }
462 return StringRef();
463}
464
465// Verify an RFC 2617 Digest response. Stateless (the nonce we issued is not tracked), which
466// matches the ESPAsyncWebServer backend used on the Arduino platforms.
467bool check_digest_auth(const char *username, const char *password, const std::string &header, const char *method) {
468 const size_t prefix_len = sizeof("Digest ") - 1;
469 StringRef params(header.c_str() + prefix_len, header.size() - prefix_len);
470
471 if (digest_param(params, "username") != username)
472 return false;
473
474 StringRef realm = digest_param(params, "realm");
475 StringRef nonce = digest_param(params, "nonce");
476 StringRef uri = digest_param(params, "uri");
477 StringRef qop = digest_param(params, "qop");
478 StringRef nc = digest_param(params, "nc");
479 StringRef cnonce = digest_param(params, "cnonce");
480 StringRef response = digest_param(params, "response");
481 if (response.size() != 32)
482 return false;
483
484 // Compute the three MD5 hashes by streaming the pieces straight into the ROM MD5 engine, so
485 // nothing is concatenated on the heap. Each hash is emitted as 32 lowercase hex characters.
486 md5_context_t ctx;
487 uint8_t digest[16];
488
489 // HA1 = MD5(username:realm:password) -- uses the realm the client echoed back.
490 char ha1[33];
491 esp_rom_md5_init(&ctx);
492 esp_rom_md5_update(&ctx, username, strlen(username));
493 esp_rom_md5_update(&ctx, ":", 1);
494 esp_rom_md5_update(&ctx, realm.c_str(), realm.size());
495 esp_rom_md5_update(&ctx, ":", 1);
496 esp_rom_md5_update(&ctx, password, strlen(password));
497 esp_rom_md5_final(digest, &ctx);
498 format_hex_to(ha1, digest, sizeof(digest));
499
500 // HA2 = MD5(method:uri) -- uses the uri the client echoed back.
501 char ha2[33];
502 esp_rom_md5_init(&ctx);
503 esp_rom_md5_update(&ctx, method, strlen(method));
504 esp_rom_md5_update(&ctx, ":", 1);
505 esp_rom_md5_update(&ctx, uri.c_str(), uri.size());
506 esp_rom_md5_final(digest, &ctx);
507 format_hex_to(ha2, digest, sizeof(digest));
508
509 // expected = MD5(HA1:nonce:nc:cnonce:qop:HA2)
510 char expected[33];
511 esp_rom_md5_init(&ctx);
512 esp_rom_md5_update(&ctx, ha1, 32);
513 esp_rom_md5_update(&ctx, ":", 1);
514 esp_rom_md5_update(&ctx, nonce.c_str(), nonce.size());
515 esp_rom_md5_update(&ctx, ":", 1);
516 esp_rom_md5_update(&ctx, nc.c_str(), nc.size());
517 esp_rom_md5_update(&ctx, ":", 1);
518 esp_rom_md5_update(&ctx, cnonce.c_str(), cnonce.size());
519 esp_rom_md5_update(&ctx, ":", 1);
520 esp_rom_md5_update(&ctx, qop.c_str(), qop.size());
521 esp_rom_md5_update(&ctx, ":", 1);
522 esp_rom_md5_update(&ctx, ha2, 32);
523 esp_rom_md5_final(digest, &ctx);
524 format_hex_to(expected, digest, sizeof(digest));
525
526 // Constant-time comparison of the two 32-char hex digests.
527 uint8_t result = 0;
528 for (size_t i = 0; i < 32; i++)
529 result |= static_cast<uint8_t>(expected[i] ^ response[i]);
530 return result == 0;
531}
532
533} // namespace
534#endif // USE_WEBSERVER_AUTH_DIGEST
535
536bool AsyncWebServerRequest::authenticate(const char *username, const char *password) const {
537 if (username == nullptr || password == nullptr || *username == 0) {
538 return true;
539 }
540 auto auth = this->get_header("Authorization");
541 if (!auth.has_value()) {
542 return false;
543 }
544
545 auto *auth_str = auth.value().c_str();
546
547#ifdef USE_WEBSERVER_AUTH_DIGEST
548 // The build fixed the scheme to Digest, so the Basic path is compiled out entirely.
549 const auto auth_prefix_len = sizeof("Digest ") - 1;
550 if (strncmp("Digest ", auth_str, auth_prefix_len) != 0) {
551 ESP_LOGW(TAG, "Only Digest authorization supported");
552 return false;
553 }
554 return check_digest_auth(username, password, auth.value(), http_method_str(this->method()));
555#else
556 const auto auth_prefix_len = sizeof("Basic ") - 1;
557 if (strncmp("Basic ", auth_str, auth_prefix_len) != 0) {
558 ESP_LOGW(TAG, "Only Basic authorization supported");
559 return false;
560 }
561
562 // Build user:pass in stack buffer to avoid heap allocation
563 constexpr size_t max_user_info_len = 256;
564 char user_info[max_user_info_len];
565 size_t user_len = strlen(username);
566 size_t pass_len = strlen(password);
567 size_t user_info_len = user_len + 1 + pass_len;
568
569 if (user_info_len >= max_user_info_len) {
570 ESP_LOGW(TAG, "Credentials too long for authentication");
571 return false;
572 }
573
574 memcpy(user_info, username, user_len);
575 user_info[user_len] = ':';
576 memcpy(user_info + user_len + 1, password, pass_len);
577 user_info[user_info_len] = '\0';
578
579 // Base64 output size is ceil(input_len * 4/3) + 1, with input bounded to 256 bytes
580 // max output is ceil(256 * 4/3) + 1 = 343 bytes, use 350 for safety
581 constexpr size_t max_digest_len = 350;
582 char digest[max_digest_len];
583 size_t out;
584 // The buffer bound above makes failure unreachable; reject rather than
585 // compare against an unwritten digest if that ever changes.
586 if (mbedtls_base64_encode(reinterpret_cast<uint8_t *>(digest), max_digest_len, &out,
587 reinterpret_cast<const uint8_t *>(user_info), user_info_len) != 0) {
588 return false;
589 }
590
591 // Constant-time comparison to avoid timing side channels.
592 // No early return on length mismatch — the length difference is folded
593 // into the accumulator so any mismatch is rejected.
594 const char *provided = auth_str + auth_prefix_len;
595 size_t digest_len = out;
596 // Derive provided_len from the already-sized std::string rather than
597 // rescanning with strlen (avoids attacker-controlled scan length).
598 size_t provided_len = auth.value().size() - auth_prefix_len;
599 // Use full-width XOR so any bit difference in the lengths is preserved
600 // (uint8_t truncation would miss differences in higher bytes, e.g.
601 // digest_len vs digest_len + 256).
602 volatile size_t result = digest_len ^ provided_len;
603 // Iterate over the expected digest length only — the full-width length
604 // XOR above already rejects any length mismatch, and bounding the loop
605 // prevents a long Authorization header from forcing extra work.
606 for (size_t i = 0; i < digest_len; i++) {
607 char provided_ch = (i < provided_len) ? provided[i] : 0;
608 result |= static_cast<uint8_t>(digest[i] ^ provided_ch);
609 }
610 return result == 0;
611#endif // USE_WEBSERVER_AUTH_DIGEST
612}
613
615 httpd_resp_set_hdr(*this, "Connection", "keep-alive");
616#ifdef USE_WEBSERVER_AUTH_DIGEST
617 // Issue a fresh random nonce and opaque. The nonce is not stored, so this is stateless and
618 // does not defend against replay -- its purpose is to keep the password off the wire.
619 // The header value must stay alive until httpd_resp_send_err() below sends it, so the buffer
620 // lives on this stack frame (httpd_resp_set_hdr stores the pointer, it does not copy).
621 uint8_t random_bytes[16];
622 char nonce[33];
623 char opaque[33];
624 char header[160];
625 esp_fill_random(random_bytes, sizeof(random_bytes));
626 format_hex_to(nonce, random_bytes, sizeof(random_bytes));
627 esp_fill_random(random_bytes, sizeof(random_bytes));
628 format_hex_to(opaque, random_bytes, sizeof(random_bytes));
629 snprintf(header, sizeof(header), R"(Digest realm="Login Required", qop="auth", nonce="%s", opaque="%s")", nonce,
630 opaque);
631 httpd_resp_set_hdr(*this, "WWW-Authenticate", header);
632#else
633 httpd_resp_set_hdr(*this, "WWW-Authenticate", "Basic realm=\"Login Required\"");
634#endif // USE_WEBSERVER_AUTH_DIGEST
635 httpd_resp_send_err(*this, HTTPD_401_UNAUTHORIZED, nullptr);
636}
637#endif // USE_WEBSERVER_AUTH
638
640 // Check cache first - only successful lookups are cached
641 for (auto *param : this->params_) {
642 if (param->name() == name) {
643 return param;
644 }
645 }
646
647 // Look up value from query strings
648 auto val = this->find_query_value_(name);
649
650 // Don't cache misses to avoid wasting memory when handlers check for
651 // optional parameters that don't exist in the request
652 if (!val.has_value()) {
653 return nullptr;
654 }
655
656 auto *param = new AsyncWebParameter(name, val.value()); // NOLINT(cppcoreguidelines-owning-memory)
657 this->params_.push_back(param);
658 return param;
659}
660
664template<typename Func>
665static auto search_query_sources(httpd_req_t *req, const std::string &post_query, const char *name, Func func)
666 -> decltype(func(nullptr, size_t{0}, name)) {
667 if (!post_query.empty()) {
668 auto result = func(post_query.c_str(), post_query.size(), name);
669 if (result) {
670 return result;
671 }
672 }
673 // Use httpd API for query length, then access string directly from URI.
674 // http_parser identifies components by offset/length without modifying the URI string.
675 // This is the same pattern used by url_to().
676 auto len = httpd_req_get_url_query_len(req);
677 if (len == 0) {
678 return {};
679 }
680 const char *query = strchr(req->uri, '?');
681 if (query == nullptr) {
682 return {};
683 }
684 query++; // skip '?'
685 return func(query, len, name);
686}
687
688optional<std::string> AsyncWebServerRequest::find_query_value_(const char *name) const {
689 return search_query_sources(this->req_, this->post_query_, name,
690 [](const char *q, size_t len, const char *k) { return query_key_value(q, len, k); });
691}
692
693bool AsyncWebServerRequest::hasArg(const char *name) {
694 return search_query_sources(this->req_, this->post_query_, name, query_has_key);
695}
696
697std::string AsyncWebServerRequest::arg(const char *name) {
698 auto val = this->find_query_value_(name);
699 if (val.has_value()) {
700 return std::move(val.value());
701 }
702 return {};
703}
704
705void AsyncWebServerResponse::addHeader(const char *name, const char *value) {
706 const auto &defaults = DefaultHeaders::Instance().headers_;
707 for (size_t i = 0; i < defaults.size(); i++) {
708 if (str_equals_case_insensitive(name, defaults[i].name))
709 this->replaced_defaults_ |= 1U << i;
710 }
711 httpd_resp_set_hdr(*this->req_, name, value);
712}
713
715 // Use stack buffer to avoid temporary string allocation
716 // Size: sign (1) + digits (10) + decimal (1) + precision (6) + exponent (5) + null (1) = 24, use 32 for safety
717 char buf[32];
718 int len = snprintf(buf, sizeof(buf), "%f", value);
719 this->content_.append(buf, len);
720}
721
722void AsyncResponseStream::printf(const char *fmt, ...) {
723 va_list args;
724
725 va_start(args, fmt);
726 const int length = vsnprintf(nullptr, 0, fmt, args);
727 va_end(args);
728
729 std::string str;
730 str.resize(length);
731
732 va_start(args, fmt);
733 vsnprintf(&str[0], length + 1, fmt, args);
734 va_end(args);
735
736 this->print(str);
737}
738
739#ifdef USE_WEBSERVER
741 LockGuard guard{this->pending_mutex_};
742 for (auto *vec : {&this->sessions_, &this->pending_sessions_}) {
743 for (auto *ses : *vec) {
744 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
745 }
746 }
747}
748
750 // Httpd task: set up the live httpd_req_t and park the session; main loop does the rest.
751 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory,clang-analyzer-cplusplus.NewDeleteLeaks)
752 auto *rsp = new AsyncEventSourceResponse(request, this, this->web_server_);
753 {
754 LockGuard guard{this->pending_mutex_};
755 this->pending_sessions_.push_back(rsp);
756 this->has_pending_sessions_.store(true, std::memory_order_release);
757 }
759}
760
761// clang-analyzer traces a false-positive leak path from loop() through
762// adopt_pending_sessions_main_loop_() into start_session_main_loop_() and
763// finally ArduinoJson. Suppress along the entire in-our-code call chain.
764// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks)
766 // Fast path: one atomic load per tick. Slow path is out-of-line on connect.
767 if (this->has_pending_sessions_.load(std::memory_order_acquire)) {
768 this->adopt_pending_sessions_main_loop_();
769 }
770
771 // Clean up dead sessions safely
772 // This follows the ESP-IDF pattern where free_ctx marks resources as dead
773 // and the main loop handles the actual cleanup to avoid race conditions
774 for (size_t i = 0; i < this->sessions_.size();) {
775 auto *ses = this->sessions_[i];
776 // If the session has a dead socket (marked by destroy callback)
777 if (ses->safe_to_delete_()) {
778 // destroy() already logged the close with the fd; don't double-log here.
779 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
780 // Remove by swapping with last element (O(1) removal, order doesn't matter for sessions)
781 this->sessions_[i] = this->sessions_.back();
782 this->sessions_.pop_back();
783 } else {
784 ses->loop();
785 ++i;
786 }
787 }
788 // A session still waiting for httpd to commit its context keeps the loop alive too
789 return !this->sessions_.empty() || this->has_pending_sessions_.load(std::memory_order_acquire);
790}
791
792void AsyncEventSource::adopt_pending_sessions_main_loop_() {
793 std::vector<AsyncEventSourceResponse *> incoming;
794 {
795 LockGuard guard{this->pending_mutex_};
796 incoming.swap(this->pending_sessions_);
797 this->has_pending_sessions_.store(false, std::memory_order_relaxed);
798 }
799 for (auto *rsp : incoming) {
800 // Already disconnected? Drop it; skip session start on a dead session.
801 if (rsp->safe_to_delete_()) {
802 delete rsp; // NOLINT(cppcoreguidelines-owning-memory)
803 continue;
804 }
805 // httpd commits the session context only after the creating handler returns, so stay
806 // pending until then; httpd_req_cleanup() always commits it or calls destroy()
807 if (httpd_sess_get_ctx(rsp->hd_, rsp->fd_.load()) != rsp) {
808 LockGuard guard{this->pending_mutex_};
809 this->pending_sessions_.push_back(rsp);
810 this->has_pending_sessions_.store(true, std::memory_order_release);
811 continue;
812 }
813 this->sessions_.push_back(rsp);
814 rsp->start_session_main_loop_();
815 }
816}
817// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
818
819void AsyncEventSource::try_send_nodefer(const char *message, size_t message_len, const char *event, uint32_t id,
820 uint32_t reconnect) {
821 for (auto *ses : this->sessions_) {
822 if (ses->fd_.load() != 0) { // Skip dead sessions
823 ses->try_send_nodefer(message, message_len, event, id, reconnect);
824 }
825 }
826}
827
828void AsyncEventSource::deferrable_send_state(void *source, bool detail_all, message_generator_t *message_generator) {
829 // Skip if no connected clients to avoid unnecessary processing
830 if (this->empty())
831 return;
832 for (auto *ses : this->sessions_) {
833 if (ses->fd_.load() != 0) { // Skip dead sessions
834 ses->deferrable_send_state(source, detail_all, message_generator);
835 }
836 }
837}
838
842 : server_(server), web_server_(ws), entities_iterator_(ws, server) {
843 // Httpd task only. start_session_main_loop_() sends the greeting and starts the iterator.
844 httpd_req_t *req = *request;
845
846 httpd_resp_set_status(req, HTTPD_200);
847 httpd_resp_set_type(req, "text/event-stream");
848 httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
849 httpd_resp_set_hdr(req, "Connection", "keep-alive");
850
852
853 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
854
855 req->sess_ctx = this;
856 req->free_ctx = AsyncEventSourceResponse::destroy;
857
858 this->hd_ = req->handle;
859 this->fd_.store(httpd_req_to_sockfd(req));
860
861 // Use non-blocking send to prevent watchdog timeouts when TCP buffers are full
862 httpd_sess_set_send_override(this->hd_, this->fd_.load(), nonblocking_send);
863}
864
865// NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
867 auto *ws = this->web_server_;
868
869 // The tcp send buffer is empty on connect. A refusal is a closing session or a failed tail
870 // allocation; nothing retries the greeting, so close and let the client reconnect.
871 auto message = ws->get_config_json();
872 if (!this->try_send_nodefer(message.c_str(), message.size(), "ping", millis(), 30000)) {
873 ESP_LOGW(TAG, "Config not sent to fd %d", this->fd_.load());
874 this->request_close_();
875 return;
876 }
877
878#ifdef USE_WEBSERVER_SORTING
879 for (auto &group : ws->sorting_groups_) {
880 json::JsonBuilder builder;
881 JsonObject root = builder.root();
882 root["name"] = json::linked(group.second.name);
883 root["sorting_weight"] = group.second.weight;
884 message = builder.serialize();
885
886 // a (very) large number of these should be able to be queued initially without defer
887 // since the only thing in the send buffer at this point is the initial ping/config.
888 // A refusal means the socket is full or closing; the remaining groups are not sent. The
889 // session stays up on purpose: partial grouping beats a reconnect loop on a slow link.
890 if (!this->try_send_nodefer(message.c_str(), message.size(), "sorting_group")) {
891 ESP_LOGW(TAG, "Sorting groups not sent to fd %d", this->fd_.load());
892 break;
893 }
894 }
895#endif
896
897 this->entities_iterator_.begin(ws->include_internal_);
898}
899// NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
900
902 auto *rsp = static_cast<AsyncEventSourceResponse *>(ptr);
903 int fd = rsp->fd_.exchange(0); // Atomically get and clear fd
904 ESP_LOGD(TAG, "Event source connection closed (fd: %d)", fd);
905 // Mark as dead - will be cleaned up in the main loop
906 // Note: We don't delete or remove from set here to avoid race conditions
907 // httpd will call our custom close_fn (safe_close_with_shutdown) which handles
908 // shutdown() before close() to prevent lwIP race conditions
909}
910
911// helper for allowing only unique entries in the queue
913 DeferredEvent item(source, message_generator);
914
915 // Use range-based for loop instead of std::find_if to reduce template instantiation overhead and binary size
916 for (auto &event : this->deferred_queue_) {
917 if (event == item) {
918 return; // Already in queue, no need to update since items are equal
919 }
920 }
921 this->deferred_queue_.push_back(item);
922}
923
925 if (this->close_requested_) {
926 return;
927 }
928 while (!deferred_queue_.empty()) {
929 DeferredEvent &de = deferred_queue_.front();
930 if (this->send_json_(de.source_, de.message_generator_)) {
931 if (this->close_requested_ || deferred_queue_.empty()) {
932 return;
933 }
934 // O(n) but memory efficiency is more important than speed here which is why std::vector was chosen
935 deferred_queue_.erase(deferred_queue_.begin());
936 } else {
937 break;
938 }
939 }
940}
941
943 if (!this->close_requested_) {
944 this->close_requested_ = true;
945 this->deferred_queue_.clear();
946 this->tail_.reset();
947 this->tail_cap_ = 0;
948 this->tail_len_ = 0;
949 this->tail_sent_ = 0;
951 }
952
953 this->process_close_();
954}
955
957 if (!this->close_requested_ || this->close_work_queued_.load(std::memory_order_acquire)) {
958 return;
959 }
960 const int fd = this->fd_.load();
961 if (fd == 0) {
962 return;
963 }
964
966 if (static_cast<int32_t>(now - this->next_close_attempt_ms_) < 0) {
967 return;
968 }
969
970 // Queue an identity-checked shutdown on the HTTPD task. The public
971 // httpd_sess_trigger_close() queues only a reusable fd/session slot and can
972 // therefore close a new client if the original peer disconnects meanwhile.
973 this->close_work_queued_.store(true, std::memory_order_release);
974 const esp_err_t err = httpd_queue_work(this->hd_, &AsyncEventSourceResponse::close_session_work, this);
976 if (err == ESP_OK) {
977 return;
978 }
979
980 this->close_work_queued_.store(false, std::memory_order_release);
981 if (!this->close_retry_warning_logged_) {
982 ESP_LOGW(TAG, "Failed to queue EventSource close (%s); retrying", esp_err_to_name(err));
983 this->close_retry_warning_logged_ = true;
984 }
985}
986
988 // httpd only advances a session's LRU counter when a request arrives, and an event stream receives one
989 // request ever, so the purge that frees a socket for a new client would evict the live streams first.
990 // The HTTPD task owns the session table, so the refresh runs there.
991 // A stalled stream is the socket the purge should take, and a zeroed fd has no session left to refresh.
992 if (this->send_failure_started_ms_ != 0 || this->fd_.load() == 0)
993 return;
996 this->lru_work_queued_.load(std::memory_order_acquire)) {
997 return;
998 }
999 this->last_lru_refresh_ms_ = now; // a full queue also waits for the next interval
1000 this->lru_work_queued_.store(true, std::memory_order_release);
1001 if (httpd_queue_work(this->hd_, &AsyncEventSourceResponse::refresh_lru_work, this) != ESP_OK) {
1002 this->lru_work_queued_.store(false, std::memory_order_release);
1003 }
1004}
1005
1007 auto *response = static_cast<AsyncEventSourceResponse *>(arg);
1008 const int fd = response->fd_.load();
1009 if (response->owns_session_(fd)) {
1010 httpd_sess_update_lru_counter(response->hd_, fd);
1011 }
1012 // Release self only after the HTTPD-task callback has finished every access.
1013 response->lru_work_queued_.store(false, std::memory_order_release);
1014}
1015
1017 auto *response = static_cast<AsyncEventSourceResponse *>(arg);
1018 const int fd = response->fd_.load();
1019 if (response->owns_session_(fd)) {
1020 // The HTTPD task remains the session owner. Shutting the socket down makes
1021 // its next select/recv path delete the session and invoke destroy().
1022 shutdown(fd, SHUT_RDWR);
1023 }
1024
1025 // Release self only after the HTTPD-task callback has finished every access.
1026 response->close_work_queued_.store(false, std::memory_order_release);
1027}
1028
1030 // httpd frees a session before closing its socket, so the fd may already be a new client's.
1031 // Treated as would-block; the stall timer ends a session that never becomes ours again.
1032 const int fd = this->fd_.load();
1033 if (!this->owns_session_(fd)) {
1034 return 0;
1035 }
1036 struct msghdr msg{};
1037 msg.msg_iov = iov;
1038 msg.msg_iovlen = iovcnt;
1039 const ssize_t sent = sendmsg(fd, &msg, MSG_DONTWAIT);
1040 if (sent >= 0) {
1041 return sent;
1042 }
1043 const int err = errno;
1044 if (err == EAGAIN || err == EWOULDBLOCK) {
1045 return 0;
1046 }
1047 ESP_LOGD(TAG, "send error: errno %d", err);
1048 this->request_close_();
1049 return -1;
1050}
1051
1053 if (this->sending_ || this->close_requested_ || this->tail_len_ == 0) {
1054 return;
1055 }
1056 SendGuard guard{*this};
1057
1058 const size_t remaining = this->tail_len_ - this->tail_sent_;
1059 struct iovec iov = {this->tail_.get() + this->tail_sent_, remaining};
1060 const ssize_t sent = this->send_(&iov, 1);
1061 if (sent < 0) {
1062 return;
1063 }
1064 if (sent == 0) {
1065 // Socket buffer full, try again later
1066 // NOTE: Similar logic exists in web_server/web_server.cpp in DeferredUpdateEventSource::process_deferred_queue_().
1067 // The IDF path is intentionally time-based and closes through HTTPD to preserve session ownership.
1069 if (this->send_failure_started_ms_ == 0) {
1070 this->send_failure_started_ms_ = now != 0 ? now : 1; // Reserve zero for no stall.
1071 }
1072 if (static_cast<int32_t>(now - (this->send_failure_started_ms_ + SEND_STALL_TIMEOUT_MS)) >= 0) {
1073 ESP_LOGW(TAG, "Closing stuck EventSource connection after %" PRIu32 " ms without send progress",
1074 now - this->send_failure_started_ms_);
1075 this->request_close_();
1076 }
1077 return;
1078 }
1079
1080 this->send_failure_started_ms_ = 0;
1081 this->tail_sent_ += sent;
1082 if (this->tail_sent_ < this->tail_len_) {
1083 ESP_LOGV(TAG, "Partial send: %zd/%zu bytes (total: %u/%u)", sent, remaining, this->tail_sent_, this->tail_len_);
1084 return;
1085 }
1086 // Fully sent; the storage stays for the next stall
1087 this->tail_len_ = 0;
1088}
1089
1091 if (this->tail_cap_ >= len) {
1092 return true;
1093 }
1094 if (len > TAIL_MAX_SIZE) {
1095 return false;
1096 }
1097 // Nothing is pending while the tail grows, so free the old block first. PREFER_INTERNAL keeps
1098 // the tail where plain new put it.
1099 this->tail_.reset();
1101 this->tail_cap_ = this->tail_ ? len : 0;
1102 return this->tail_cap_ != 0;
1103}
1104
1105bool AsyncEventSourceResponse::stash_chunk_(const char *prefix, size_t prefix_len, const char *message,
1106 size_t message_len, size_t total, size_t sent) {
1107 // A log event of nothing but line breaks is the largest chunk; reserve_tail_() must never
1108 // refuse it for size, only for memory
1110 "the log cut in web_server.h must keep a worst case log event inside the tail ceiling");
1111 if (!this->reserve_tail_(total)) {
1112 if (sent != 0) {
1113 // Part of the chunk is on the wire, so the stream is broken and the client has to go
1114 ESP_LOGW(TAG, "Cannot buffer a %zu byte chunk, closing", total);
1115 this->request_close_();
1116 } else {
1117 this->tail_alloc_failed_(total); // nothing on the wire, the caller retries on the stall clock
1118 }
1119 return false;
1120 }
1121 uint8_t *dst = this->tail_.get();
1122 std::memcpy(dst, prefix, prefix_len);
1123 dst += prefix_len;
1125 message, message_len,
1126 [](void *ctx, const char *piece, size_t len) {
1127 auto &out = *static_cast<uint8_t **>(ctx);
1128 std::memcpy(out, piece, len);
1129 out += len;
1130 },
1131 &dst);
1132 this->tail_len_ = total;
1133 this->tail_sent_ = sent;
1134 return true;
1135}
1136
1138 if (this->close_requested_) {
1139 this->process_close_();
1140 return;
1141 }
1142 this->refresh_lru_();
1143 drain_tail_();
1145 if (this->close_requested_)
1146 return;
1147 // One step per loop; refusals retry next pass
1149}
1150
1151#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 14 && defined(__OPTIMIZE_SIZE__)
1152#pragma GCC diagnostic push
1153#pragma GCC diagnostic ignored "-Wstack-usage=" // the one frame that holds the JSON arena
1154#endif
1155AsyncEventSourceResponse::JsonPrepareResult AsyncEventSourceResponse::prepare_json_(void *source,
1156 message_generator_t *generator,
1157 char *buffer, size_t *size_out) {
1158 // Log lines emitted while the generator runs are dropped for this session: on the large path they would fill
1159 // tail_ before it is overwritten, and on the small path they would go out ahead of the event being built.
1160 SendGuard guard{*this};
1162 json::JsonBuilder builder(&arena);
1163 generator(this->web_server_, source, builder);
1164 *size_out = builder.serialize_to(buffer, JSON_BUF_SIZE);
1165 if (*size_out < JSON_BUF_SIZE) {
1167 }
1168
1169 char prefix[PREFIX_BUF_SIZE];
1170 const size_t prefix_len = build_chunk_prefix(prefix, sizeof(prefix), "state", 0, 0, true);
1171
1172 // Nothing reaches the wire until the complete document and its framing are owned by the caller.
1173 size_t json_len = 0;
1174 size_t cap = std::max<size_t>(JSON_BUF_SIZE * 2, this->tail_cap_);
1175 for (;;) {
1176 if (!this->reserve_tail_(cap)) {
1177 *size_out = cap;
1179 }
1180 const size_t room = cap - prefix_len - SSE_SUFFIX_LEN;
1181 json_len = builder.serialize_to(reinterpret_cast<char *>(this->tail_.get()) + prefix_len, room);
1182 if (json_len < room) {
1183 break;
1184 }
1185 if (cap >= TAIL_MAX_SIZE) {
1186 *size_out = room;
1188 }
1189 cap = std::min<size_t>(cap * 2, TAIL_MAX_SIZE);
1190 }
1191
1192 const size_t total = prefix_len + json_len + SSE_SUFFIX_LEN;
1194 uint8_t *dst = this->tail_.get();
1195 std::memcpy(dst, prefix, prefix_len);
1196 std::memcpy(dst + prefix_len + json_len, SSE_SUFFIX, SSE_SUFFIX_LEN);
1197 this->tail_len_ = total;
1198 this->tail_sent_ = 0;
1200}
1201#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 14 && defined(__OPTIMIZE_SIZE__)
1202#pragma GCC diagnostic pop
1203#endif
1204
1206 if (!this->ready_to_send_()) {
1207 return false;
1208 }
1209 char buffer[JSON_BUF_SIZE];
1210 size_t size;
1211 const auto result = this->prepare_json_(source, generator, buffer, &size);
1212 switch (result) {
1214 return this->try_send_nodefer(buffer, size, "state");
1216 this->drain_tail_();
1217 return true;
1219 SendGuard guard{*this};
1220 this->tail_alloc_failed_(size);
1221 return false;
1222 }
1224 SendGuard guard{*this};
1225 ESP_LOGW(TAG, "State event does not fit %zu bytes, dropped", size);
1226 this->tail_.reset();
1227 this->tail_cap_ = 0;
1228 this->send_failure_started_ms_ = 0;
1229 return true;
1230 }
1231 }
1232 return false;
1233}
1234
1236 // Same stall clock as a socket that stops draining, so a session cannot retry forever
1238 if (this->send_failure_started_ms_ == 0) {
1239 this->send_failure_started_ms_ = now != 0 ? now : 1; // Reserve zero for no stall.
1240 ESP_LOGW(TAG, "No memory for a %zu byte chunk", cap);
1241 return;
1242 }
1243 if (static_cast<int32_t>(now - (this->send_failure_started_ms_ + SEND_STALL_TIMEOUT_MS)) >= 0) {
1244 ESP_LOGW(TAG, "Closing EventSource after %" PRIu32 " ms without memory", now - this->send_failure_started_ms_);
1245 this->request_close_();
1246 }
1247}
1248
1250 if (this->sending_ || this->fd_.load() == 0 || this->close_requested_) {
1251 return false;
1252 }
1253 drain_tail_();
1254 return !this->close_requested_ && this->tail_len_ == 0;
1255}
1256
1257bool AsyncEventSourceResponse::try_send_nodefer(const char *message, size_t message_len, const char *event, uint32_t id,
1258 uint32_t reconnect) {
1259 if (!this->ready_to_send_()) {
1260 return false;
1261 }
1262 SendGuard guard{*this};
1263
1264 // Everything after the prefix goes out straight from the caller's buffer
1265 char prefix[PREFIX_BUF_SIZE];
1266 const size_t prefix_len = build_chunk_prefix(prefix, sizeof(prefix), event, id, reconnect, message != nullptr);
1267 if (message == nullptr && prefix_len == CHUNK_HDR_LEN) {
1268 return true; // Match ESPAsyncWebServer: nothing to send
1269 }
1270 if (prefix_len >= PREFIX_BUF_SIZE - 1) {
1271 // The appenders truncate silently, which would put a malformed event on the wire
1272 ESP_LOGW(TAG, "Event name too long, dropped");
1273 return true;
1274 }
1275
1276 // Gather list: the prefix, then the data lines and their separators from the message
1277 struct Gather {
1278 struct iovec iov[MAX_SEND_IOV]; // left uninitialized on purpose
1279 int iovcnt{1};
1280 size_t total{0};
1281 bool fits{true};
1282 } g;
1283 g.total = prefix_len;
1285 message, message_len,
1286 [](void *ctx, const char *piece, size_t len) {
1287 auto &g = *static_cast<Gather *>(ctx);
1288 g.total += len;
1289 if (len == 0) {
1290 return;
1291 }
1292 if (g.iovcnt == MAX_SEND_IOV) {
1293 g.fits = false;
1294 return;
1295 }
1296 g.iov[g.iovcnt++] = {const_cast<char *>(piece), len};
1297 },
1298 &g);
1299 // The header and the terminator are not part of the chunk length
1300 write_chunk_header(prefix, g.total - CHUNK_HDR_LEN - CHUNK_END_LEN);
1301 g.iov[0] = {prefix, prefix_len};
1302
1303 // A message with more lines than the list holds skips straight to the tail
1304 const ssize_t sent = g.fits ? this->send_(g.iov, g.iovcnt) : 0;
1305 if (sent < 0) {
1306 return false;
1307 }
1308 if (static_cast<size_t>(sent) == g.total) {
1309 this->send_failure_started_ms_ = 0; // progress, whichever stall clock was running
1310 return true;
1311 }
1312 // The caller's buffers do not outlive this call, so keep the chunk and continue from loop()
1313 return this->stash_chunk_(prefix, prefix_len, message, message_len, g.total, sent);
1314}
1315
1316void AsyncEventSourceResponse::deferrable_send_state(void *source, bool detail_all,
1317 message_generator_t *message_generator) {
1318 // Let the detail_all listing finish before bare state events, so the web UI never shows unnamed entries and
1319 // initial connect sends less
1320 if (!detail_all && !this->entities_iterator_.completed())
1321 return;
1322
1323 drain_tail_();
1325
1326 if (this->close_requested_) {
1327 return;
1328 }
1329
1330 if (this->tail_len_ != 0 || !deferred_queue_.empty()) {
1331 // outgoing event buffer or deferred queue still not empty which means downstream tcp send buffer full, no point
1332 // trying to send first
1333 deq_push_back_with_dedup_(source, message_generator);
1334 } else {
1335 // A send error closes the session and clears the queue; nothing is queued after that
1336 if (!this->send_json_(source, message_generator) && !this->close_requested_) {
1337 deq_push_back_with_dedup_(source, message_generator);
1338 }
1339 }
1340}
1341#endif
1342
1343#ifdef USE_WEBSERVER_OTA
1344esp_err_t AsyncWebServer::handle_multipart_upload_(httpd_req_t *r, const char *content_type) {
1345 // Parse boundary and create reader
1346 const char *boundary_start;
1347 size_t boundary_len;
1348 if (!parse_multipart_boundary(content_type, &boundary_start, &boundary_len)) {
1349 ESP_LOGE(TAG, "Failed to parse multipart boundary");
1350 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
1351 return ESP_FAIL;
1352 }
1353
1354 AsyncWebServerRequest req(r);
1355 AsyncWebHandler *handler = nullptr;
1356 for (auto *h : this->handlers_) {
1357 if (h->canHandle(&req)) {
1358 handler = h;
1359 break;
1360 }
1361 }
1362
1363 if (!handler) {
1364 ESP_LOGW(TAG, "No handler found for OTA request");
1365 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, nullptr);
1366 return ESP_OK;
1367 }
1368
1369 // Upload state
1370 std::string filename;
1371 size_t index = 0;
1372 // Create reader on heap to reduce stack usage
1373 auto reader = std::make_unique<MultipartReader>("--" + std::string(boundary_start, boundary_len));
1374
1375 // Configure callbacks
1376 reader->set_data_callback([&](const uint8_t *data, size_t len) {
1377 if (!reader->has_file() || !len)
1378 return;
1379
1380 if (filename.empty()) {
1381 filename = reader->get_current_part().filename;
1382 ESP_LOGV(TAG, "Processing file: '%s'", filename.c_str());
1383 handler->handleUpload(&req, filename, 0, nullptr, 0, false); // Start
1384 }
1385
1386 handler->handleUpload(&req, filename, index, const_cast<uint8_t *>(data), len, false);
1387 index += len;
1388 });
1389
1390 reader->set_part_complete_callback([&]() {
1391 if (index > 0) {
1392 handler->handleUpload(&req, filename, index, nullptr, 0, true); // End
1393 filename.clear();
1394 index = 0;
1395 }
1396 });
1397
1398 auto buffer = std::make_unique_for_overwrite<char[]>(RECV_CHUNK_SIZE);
1399 size_t bytes_since_yield = 0;
1400
1401 for (size_t remaining = r->content_len; remaining > 0;) {
1402 int recv_len = httpd_req_recv(r, buffer.get(), std::min(remaining, RECV_CHUNK_SIZE));
1403
1404 if (recv_len <= 0) {
1405 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
1406 nullptr);
1407 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
1408 }
1409
1410 if (reader->parse(buffer.get(), recv_len) != static_cast<size_t>(recv_len)) {
1411 ESP_LOGW(TAG, "Multipart parser error");
1412 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
1413 return ESP_FAIL;
1414 }
1415
1416 remaining -= recv_len;
1417 bytes_since_yield += recv_len;
1418
1419 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
1420 vTaskDelay(1);
1421 bytes_since_yield = 0;
1422 }
1423 }
1424
1425 handler->handleRequest(&req);
1426 return ESP_OK;
1427}
1428#endif // USE_WEBSERVER_OTA
1429
1430} // namespace esphome::web_server_idf
1431
1432#endif // !defined(USE_ESP32)
uint8_t h
Definition bl0906.h:2
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.
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void begin(bool include_internal=false)
ESPHOME_ALWAYS_INLINE void try_advance(size_t max_steps)
Run up to max_steps iteration steps; stops early when iteration completes or a callback refuses (that...
Helper class that wraps a mutex with a RAII-style API.
Definition helpers.h:2222
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2396
RAMUniquePtr< T[]> make_unique_array_for_overwrite(size_t n)
n elements left uninitialized, as std::make_unique_for_overwrite does; empty on exhaustion,...
Definition helpers.h:2469
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
constexpr const char * c_str() const
Definition string_ref.h:78
constexpr size_type size() const
Definition string_ref.h:79
Bump allocator over a fixed buffer for a document built and serialized in one scope.
Definition json_util.h:194
Builder class for creating JSON documents without lambdas.
Definition json_util.h:256
SerializationBuffer serialize()
Serialize the JSON document to a SerializationBuffer (stack-first allocation) Uses 512-byte stack buf...
Definition json_util.cpp:96
This class allows users to create a web server with their ESP nodes.
Definition web_server.h:204
json::SerializationBuffer get_config_json()
Return the webserver configuration as JSON.
std::vector< AsyncEventSourceResponse * > pending_sessions_
bool loop()
Returns true if there are sessions remaining (including pending cleanup).
std::vector< AsyncEventSourceResponse * > sessions_
void try_send_nodefer(const char *message, size_t message_len, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
esphome::web_server::WebServer * web_server_
void handleRequest(AsyncWebServerRequest *request) override
void deferrable_send_state(void *source, bool detail_all, message_generator_t *message_generator)
void deferrable_send_state(void *source, bool detail_all, message_generator_t *message_generator)
JsonPrepareResult message_generator_t char * buffer
bool try_send_nodefer(const char *message, size_t message_len, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
void deq_push_back_with_dedup_(void *source, message_generator_t *message_generator)
ssize_t send_(struct iovec *iov, int iovcnt)
bool stash_chunk_(const char *prefix, size_t prefix_len, const char *message, size_t message_len, size_t total, size_t sent)
AsyncEventSourceResponse(const AsyncWebServerRequest *request, esphome::web_server_idf::AsyncEventSource *server, esphome::web_server::WebServer *ws)
esphome::web_server::WebServer * web_server_
JsonPrepareResult message_generator_t * generator
JsonPrepareResult message_generator_t char size_t * size_out
bool send_json_(void *source, message_generator_t *generator)
esphome::web_server::ListEntitiesIterator entities_iterator_
void printf(const char *fmt,...) __attribute__((format(printf
virtual void handleRequest(AsyncWebServerRequest *request)
virtual void handleUpload(AsyncWebServerRequest *request, const std::string &filename, size_t index, uint8_t *data, size_t len, bool final)
virtual void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total)
std::function< void(AsyncWebServerRequest *request)> on_not_found_
esp_err_t handle_raw_body_(httpd_req_t *r, const char *content_type)
static esp_err_t request_post_handler(httpd_req_t *r)
std::vector< AsyncWebHandler * > handlers_
esp_err_t request_handler_(AsyncWebServerRequest *request) const
esp_err_t handle_multipart_upload_(httpd_req_t *r, const char *content_type)
static void safe_close_with_shutdown(httpd_handle_t hd, int sockfd)
static esp_err_t request_handler(httpd_req_t *r)
size_t get_header_to(const char *name, std::span< char > buf) const
Copy a header value into buf without heap allocation.
AsyncWebParameter * getParam(const char *name)
optional< std::string > get_header(const char *name) const
StringRef url_to(std::span< char, URL_BUF_SIZE > buffer) const
Write URL (without query string) to buffer, returns StringRef pointing to buffer.
void send(AsyncWebServerResponse *response)
void init_response_(AsyncWebServerResponse *rsp, int code, const char *content_type)
static constexpr size_t URL_BUF_SIZE
Buffer size for url_to()
optional< std::string > find_query_value_(const char *name) const
bool authenticate(const char *username, const char *password) const
std::vector< AsyncWebParameter * > params_
virtual const char * get_content_data() const =0
void addHeader(const char *name, const char *value)
StaticVector< HttpHeader, WEB_SERVER_DEFAULT_HEADERS_COUNT > headers_
void apply_(httpd_req_t *req, uint8_t skip_mask=0) const
Set every default header on the response except those whose bit is set in skip_mask.
const LogString * message
Definition component.cpp:35
uint16_t flags
const char * key
std::vector< uint8_t > & out
Definition gif.cpp:49
uint32_t buffer
Definition gif.cpp:50
__int64 ssize_t
Definition httplib.h:178
int ret
mopeka_std_values val[3]
JsonString linked(const char *s)
Definition json_util.h:24
constexpr size_t CHUNK_END_LEN
Definition sse_chunk.h:17
size_t build_chunk_prefix(char *buf, size_t size, const char *event, uint32_t id, uint32_t reconnect, bool with_data)
Definition sse_chunk.cpp:38
bool query_has_key(const char *query_url, size_t query_len, const char *key)
Definition utils.cpp:79
void(esphome::web_server::WebServer *, void *, json::JsonBuilder &) message_generator_t
optional< std::string > request_get_header(httpd_req_t *req, const char *name)
Definition utils.cpp:36
size_t request_get_header_to(httpd_req_t *req, const char *name, std::span< char > buf)
Copy a header value into buf, nul-terminated, without heap allocation.
Definition utils.cpp:53
constexpr size_t SSE_SUFFIX_LEN
Definition sse_chunk.h:23
bool parse_multipart_boundary(const char *content_type, const char **boundary_start, size_t *boundary_len)
optional< std::string > query_key_value(const char *query_url, size_t query_len, const char *key)
Definition utils.cpp:62
const char * strcasestr_n(const char *haystack, size_t haystack_len, const char *needle)
Definition utils.cpp:102
constexpr size_t SSE_SEP_LEN
Definition sse_chunk.h:20
void write_chunk_header(char *buf, size_t chunk_len)
Definition sse_chunk.cpp:57
constexpr size_t CHUNK_HDR_LEN
Definition sse_chunk.h:14
constexpr char SSE_SUFFIX[]
Definition sse_chunk.h:22
size_t url_decode(char *str)
Decode URL-encoded string in-place (e.g., %20 -> space, + -> space) Returns the new length of the dec...
Definition utils.cpp:11
ESPHOME_LOG_TAG(TAG, "multipart")
bool request_has_header(httpd_req_t *req, const char *name)
Definition utils.cpp:34
void for_each_chunk_piece(const char *message, size_t message_len, ChunkPieceSink sink, void *ctx)
Definition sse_chunk.cpp:10
constexpr size_t LOG_EVENT_MAX_LEN
Definition web_server.h:43
bool random_bytes(uint8_t *data, size_t len)
Generate len random bytes using the platform's secure RNG (hardware RNG or OS CSPRNG).
Definition helpers.cpp:20
uint32_t value
Definition hal.cpp:41
va_end(args)
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:34
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
Definition helpers.cpp:210
size_t size_t const char va_start(args, fmt)
size_t size_t const char * fmt
Definition helpers.h:1334
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
char * format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as lowercase hex to buffer (base implementation).
Definition helpers.cpp:428
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
std::string print()
uint16_t length
Definition tt21100.cpp:0