ESPHome 2026.3.0-dev
Loading...
Searching...
No Matches
web_server_idf.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2
3#include <cstdarg>
4#include <memory>
5#include <cstring>
6#include <cctype>
7#include <cinttypes>
8
10#include "esphome/core/log.h"
11
12#include "esp_tls_crypto.h"
13#include <freertos/FreeRTOS.h>
14#include <freertos/task.h>
15
16#include "utils.h"
17#include "web_server_idf.h"
18
19#ifdef USE_WEBSERVER_OTA
20#include <multipart_parser.h>
21#include "multipart.h" // For parse_multipart_boundary and other utils
22#endif
23
24#ifdef USE_WEBSERVER
27#endif // USE_WEBSERVER
28
29// Include socket headers after Arduino headers to avoid IPADDR_NONE/INADDR_NONE macro conflicts
30#include <cerrno>
31#include <sys/socket.h>
32
34
35#ifndef HTTPD_409
36#define HTTPD_409 "409 Conflict"
37#endif
38
39#define CRLF_STR "\r\n"
40#define CRLF_LEN (sizeof(CRLF_STR) - 1)
41
42static const char *const TAG = "web_server_idf";
43
44// Global instance to avoid guard variable (saves 8 bytes)
45// This is initialized at program startup before any threads
46namespace {
47// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
48DefaultHeaders default_headers_instance;
49} // namespace
50
51DefaultHeaders &DefaultHeaders::Instance() { return default_headers_instance; }
52
53namespace {
54// Non-blocking send function to prevent watchdog timeouts when TCP buffers are full
69int nonblocking_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags) {
70 if (buf == nullptr) {
71 return HTTPD_SOCK_ERR_INVALID;
72 }
73
74 // Use MSG_DONTWAIT to prevent blocking when TCP send buffer is full
75 int ret = send(sockfd, buf, buf_len, flags | MSG_DONTWAIT);
76 if (ret < 0) {
77 if (errno == EAGAIN || errno == EWOULDBLOCK) {
78 // Buffer full - retry later
79 return HTTPD_SOCK_ERR_TIMEOUT;
80 }
81 // Real error
82 ESP_LOGD(TAG, "send error: errno %d", errno);
83 return HTTPD_SOCK_ERR_FAIL;
84 }
85 return ret;
86}
87} // namespace
88
89void AsyncWebServer::safe_close_with_shutdown(httpd_handle_t hd, int sockfd) {
90 // CRITICAL: Shut down receive BEFORE closing to prevent lwIP race conditions
91 //
92 // The race condition occurs because close() initiates lwIP teardown while
93 // the TCP/IP thread can still receive packets, causing assertions when
94 // recv_tcp() sees partially-torn-down state.
95 //
96 // By shutting down receive first, we tell lwIP to stop accepting new data BEFORE
97 // the teardown begins, eliminating the race window. We only shutdown RD (not RDWR)
98 // to allow the FIN packet to be sent cleanly during close().
99 //
100 // Note: This function may be called with an already-closed socket if the network
101 // stack closed it. In that case, shutdown() will fail but close() is safe to call.
102 //
103 // See: https://github.com/esphome/esphome-webserver/issues/163
104
105 // Attempt shutdown - ignore errors as socket may already be closed
106 shutdown(sockfd, SHUT_RD);
107
108 // Always close - safe even if socket is already closed by network stack
109 close(sockfd);
110}
111
113 if (this->server_) {
114 httpd_stop(this->server_);
115 this->server_ = nullptr;
116 }
117}
118
120 if (this->server_) {
121 this->end();
122 }
123 httpd_config_t config = HTTPD_DEFAULT_CONFIG();
124 config.server_port = this->port_;
125 config.uri_match_fn = [](const char * /*unused*/, const char * /*unused*/, size_t /*unused*/) { return true; };
126 // Always enable LRU purging to handle socket exhaustion gracefully.
127 // When max sockets is reached, the oldest connection is closed to make room for new ones.
128 // This prevents "httpd_accept_conn: error in accept (23)" errors.
129 // See: https://github.com/esphome/esphome/issues/12464
130 config.lru_purge_enable = true;
131 // Use custom close function that shuts down before closing to prevent lwIP race conditions
133 if (httpd_start(&this->server_, &config) == ESP_OK) {
134 const httpd_uri_t handler_get = {
135 .uri = "",
136 .method = HTTP_GET,
138 .user_ctx = this,
139 };
140 httpd_register_uri_handler(this->server_, &handler_get);
141
142 const httpd_uri_t handler_post = {
143 .uri = "",
144 .method = HTTP_POST,
146 .user_ctx = this,
147 };
148 httpd_register_uri_handler(this->server_, &handler_post);
149
150 const httpd_uri_t handler_options = {
151 .uri = "",
152 .method = HTTP_OPTIONS,
154 .user_ctx = this,
155 };
156 httpd_register_uri_handler(this->server_, &handler_options);
157 }
158}
159
160esp_err_t AsyncWebServer::request_post_handler(httpd_req_t *r) {
161 ESP_LOGVV(TAG, "Enter AsyncWebServer::request_post_handler. uri=%s", r->uri);
162 auto content_type = request_get_header(r, "Content-Type");
163
164 if (!request_has_header(r, "Content-Length")) {
165 ESP_LOGW(TAG, "Content length is required for post: %s", r->uri);
166 httpd_resp_send_err(r, HTTPD_411_LENGTH_REQUIRED, nullptr);
167 return ESP_OK;
168 }
169
170 if (content_type.has_value()) {
171 const char *content_type_char = content_type.value().c_str();
172
173 // Check most common case first
174 size_t content_type_len = strlen(content_type_char);
175 if (strcasestr_n(content_type_char, content_type_len, "application/x-www-form-urlencoded") != nullptr) {
176 // Normal form data - proceed with regular handling
177#ifdef USE_WEBSERVER_OTA
178 } else if (strcasestr_n(content_type_char, content_type_len, "multipart/form-data") != nullptr) {
179 auto *server = static_cast<AsyncWebServer *>(r->user_ctx);
180 return server->handle_multipart_upload_(r, content_type_char);
181#endif
182 } else {
183 ESP_LOGW(TAG, "Unsupported content type for POST: %s", content_type_char);
184 // fallback to get handler to support backward compatibility
186 }
187 }
188
189 // Handle regular form data
190 if (r->content_len > CONFIG_HTTPD_MAX_REQ_HDR_LEN) {
191 ESP_LOGW(TAG, "Request size is to big: %zu", r->content_len);
192 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
193 return ESP_FAIL;
194 }
195
196 std::string post_query;
197 if (r->content_len > 0) {
198 post_query.resize(r->content_len);
199 const int ret = httpd_req_recv(r, &post_query[0], r->content_len + 1);
200 if (ret <= 0) { // 0 return value indicates connection closed
201 if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
202 httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT, nullptr);
203 return ESP_ERR_TIMEOUT;
204 }
205 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
206 return ESP_FAIL;
207 }
208 }
209
210 AsyncWebServerRequest req(r, std::move(post_query));
211 return static_cast<AsyncWebServer *>(r->user_ctx)->request_handler_(&req);
212}
213
214esp_err_t AsyncWebServer::request_handler(httpd_req_t *r) {
215 ESP_LOGVV(TAG, "Enter AsyncWebServer::request_handler. method=%u, uri=%s", r->method, r->uri);
217 return static_cast<AsyncWebServer *>(r->user_ctx)->request_handler_(&req);
218}
219
221 for (auto *handler : this->handlers_) {
222 if (handler->canHandle(request)) {
223 // At now process only basic requests.
224 // OTA requires multipart request support and handleUpload for it
225 handler->handleRequest(request);
226 return ESP_OK;
227 }
228 }
229 if (this->on_not_found_) {
230 this->on_not_found_(request);
231 return ESP_OK;
232 }
233 return ESP_ERR_NOT_FOUND;
234}
235
237 delete this->rsp_;
238 for (auto *param : this->params_) {
239 delete param; // NOLINT(cppcoreguidelines-owning-memory)
240 }
241}
242
243bool AsyncWebServerRequest::hasHeader(const char *name) const { return request_has_header(*this, name); }
244
246 return request_get_header(*this, name);
247}
248
249StringRef AsyncWebServerRequest::url_to(std::span<char, URL_BUF_SIZE> buffer) const {
250 const char *uri = this->req_->uri;
251 const char *query_start = strchr(uri, '?');
252 size_t uri_len = query_start ? static_cast<size_t>(query_start - uri) : strlen(uri);
253 size_t copy_len = std::min(uri_len, URL_BUF_SIZE - 1);
254 memcpy(buffer.data(), uri, copy_len);
255 buffer[copy_len] = '\0';
256 // Decode URL-encoded characters in-place (e.g., %20 -> space)
257 size_t decoded_len = url_decode(buffer.data());
258 return StringRef(buffer.data(), decoded_len);
259}
260
262 httpd_resp_send(*this, response->get_content_data(), response->get_content_size());
263}
264
265void AsyncWebServerRequest::send(int code, const char *content_type, const char *content) {
266 this->init_response_(nullptr, code, content_type);
267 if (content) {
268 httpd_resp_send(*this, content, HTTPD_RESP_USE_STRLEN);
269 } else {
270 httpd_resp_send(*this, nullptr, 0);
271 }
272}
273
274void AsyncWebServerRequest::redirect(const std::string &url) {
275 httpd_resp_set_status(*this, "302 Found");
276 httpd_resp_set_hdr(*this, "Location", url.c_str());
277 httpd_resp_set_hdr(*this, "Connection", "close");
278 httpd_resp_send(*this, nullptr, 0);
279}
280
281void AsyncWebServerRequest::init_response_(AsyncWebServerResponse *rsp, int code, const char *content_type) {
282 // Set status code - use constants for common codes, default to 500 for unknown codes
283 const char *status;
284 switch (code) {
285 case 200:
286 status = HTTPD_200;
287 break;
288 case 404:
289 status = HTTPD_404;
290 break;
291 case 409:
292 status = HTTPD_409;
293 break;
294 default:
295 status = HTTPD_500;
296 break;
297 }
298 httpd_resp_set_status(*this, status);
299
300 if (content_type && *content_type) {
301 httpd_resp_set_type(*this, content_type);
302 }
303 httpd_resp_set_hdr(*this, "Accept-Ranges", "none");
304
305 for (const auto &header : DefaultHeaders::Instance().headers_) {
306 httpd_resp_set_hdr(*this, header.name, header.value);
307 }
308
309 delete this->rsp_;
310 this->rsp_ = rsp;
311}
312
313#ifdef USE_WEBSERVER_AUTH
314bool AsyncWebServerRequest::authenticate(const char *username, const char *password) const {
315 if (username == nullptr || password == nullptr || *username == 0) {
316 return true;
317 }
318 auto auth = this->get_header("Authorization");
319 if (!auth.has_value()) {
320 return false;
321 }
322
323 auto *auth_str = auth.value().c_str();
324
325 const auto auth_prefix_len = sizeof("Basic ") - 1;
326 if (strncmp("Basic ", auth_str, auth_prefix_len) != 0) {
327 ESP_LOGW(TAG, "Only Basic authorization supported yet");
328 return false;
329 }
330
331 // Build user:pass in stack buffer to avoid heap allocation
332 constexpr size_t max_user_info_len = 256;
333 char user_info[max_user_info_len];
334 size_t user_len = strlen(username);
335 size_t pass_len = strlen(password);
336 size_t user_info_len = user_len + 1 + pass_len;
337
338 if (user_info_len >= max_user_info_len) {
339 ESP_LOGW(TAG, "Credentials too long for authentication");
340 return false;
341 }
342
343 memcpy(user_info, username, user_len);
344 user_info[user_len] = ':';
345 memcpy(user_info + user_len + 1, password, pass_len);
346 user_info[user_info_len] = '\0';
347
348 // Base64 output size is ceil(input_len * 4/3) + 1, with input bounded to 256 bytes
349 // max output is ceil(256 * 4/3) + 1 = 343 bytes, use 350 for safety
350 constexpr size_t max_digest_len = 350;
351 char digest[max_digest_len];
352 size_t out;
353 esp_crypto_base64_encode(reinterpret_cast<uint8_t *>(digest), max_digest_len, &out,
354 reinterpret_cast<const uint8_t *>(user_info), user_info_len);
355
356 // Constant-time comparison to avoid timing side channels.
357 // No early return on length mismatch — the length difference is folded
358 // into the accumulator so any mismatch is rejected.
359 const char *provided = auth_str + auth_prefix_len;
360 size_t digest_len = out; // length from esp_crypto_base64_encode
361 // Derive provided_len from the already-sized std::string rather than
362 // rescanning with strlen (avoids attacker-controlled scan length).
363 size_t provided_len = auth.value().size() - auth_prefix_len;
364 // Use full-width XOR so any bit difference in the lengths is preserved
365 // (uint8_t truncation would miss differences in higher bytes, e.g.
366 // digest_len vs digest_len + 256).
367 volatile size_t result = digest_len ^ provided_len;
368 // Iterate over the expected digest length only — the full-width length
369 // XOR above already rejects any length mismatch, and bounding the loop
370 // prevents a long Authorization header from forcing extra work.
371 for (size_t i = 0; i < digest_len; i++) {
372 char provided_ch = (i < provided_len) ? provided[i] : 0;
373 result |= static_cast<uint8_t>(digest[i] ^ provided_ch);
374 }
375 return result == 0;
376}
377
378void AsyncWebServerRequest::requestAuthentication(const char *realm) const {
379 httpd_resp_set_hdr(*this, "Connection", "keep-alive");
380 // Note: realm is never configured in ESPHome, always nullptr -> "Login Required"
381 (void) realm; // Unused - always use default
382 httpd_resp_set_hdr(*this, "WWW-Authenticate", "Basic realm=\"Login Required\"");
383 httpd_resp_send_err(*this, HTTPD_401_UNAUTHORIZED, nullptr);
384}
385#endif
386
388 // Check cache first - only successful lookups are cached
389 for (auto *param : this->params_) {
390 if (param->name() == name) {
391 return param;
392 }
393 }
394
395 // Look up value from query strings
396 auto val = this->find_query_value_(name);
397
398 // Don't cache misses to avoid wasting memory when handlers check for
399 // optional parameters that don't exist in the request
400 if (!val.has_value()) {
401 return nullptr;
402 }
403
404 auto *param = new AsyncWebParameter(name, val.value()); // NOLINT(cppcoreguidelines-owning-memory)
405 this->params_.push_back(param);
406 return param;
407}
408
412template<typename Func>
413static auto search_query_sources(httpd_req_t *req, const std::string &post_query, const char *name, Func func)
414 -> decltype(func(nullptr, size_t{0}, name)) {
415 if (!post_query.empty()) {
416 auto result = func(post_query.c_str(), post_query.size(), name);
417 if (result) {
418 return result;
419 }
420 }
421 // Use httpd API for query length, then access string directly from URI.
422 // http_parser identifies components by offset/length without modifying the URI string.
423 // This is the same pattern used by url_to().
424 auto len = httpd_req_get_url_query_len(req);
425 if (len == 0) {
426 return {};
427 }
428 const char *query = strchr(req->uri, '?');
429 if (query == nullptr) {
430 return {};
431 }
432 query++; // skip '?'
433 return func(query, len, name);
434}
435
437 return search_query_sources(this->req_, this->post_query_, name,
438 [](const char *q, size_t len, const char *k) { return query_key_value(q, len, k); });
439}
440
441bool AsyncWebServerRequest::hasArg(const char *name) {
442 return search_query_sources(this->req_, this->post_query_, name, query_has_key);
443}
444
445std::string AsyncWebServerRequest::arg(const char *name) {
446 auto val = this->find_query_value_(name);
447 if (val.has_value()) {
448 return std::move(val.value());
449 }
450 return {};
451}
452
453void AsyncWebServerResponse::addHeader(const char *name, const char *value) {
454 httpd_resp_set_hdr(*this->req_, name, value);
455}
456
457void AsyncResponseStream::print(float value) {
458 // Use stack buffer to avoid temporary string allocation
459 // Size: sign (1) + digits (10) + decimal (1) + precision (6) + exponent (5) + null (1) = 24, use 32 for safety
460 char buf[32];
461 int len = snprintf(buf, sizeof(buf), "%f", value);
462 this->content_.append(buf, len);
463}
464
465void AsyncResponseStream::printf(const char *fmt, ...) {
466 va_list args;
467
468 va_start(args, fmt);
469 const int length = vsnprintf(nullptr, 0, fmt, args);
470 va_end(args);
471
472 std::string str;
473 str.resize(length);
474
475 va_start(args, fmt);
476 vsnprintf(&str[0], length + 1, fmt, args);
477 va_end(args);
478
479 this->print(str);
480}
481
482#ifdef USE_WEBSERVER
484 for (auto *ses : this->sessions_) {
485 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
486 }
487}
488
490 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory,clang-analyzer-cplusplus.NewDeleteLeaks)
491 auto *rsp = new AsyncEventSourceResponse(request, this, this->web_server_);
492 if (this->on_connect_) {
493 this->on_connect_(rsp);
494 }
495 this->sessions_.push_back(rsp);
496}
497
499 // Clean up dead sessions safely
500 // This follows the ESP-IDF pattern where free_ctx marks resources as dead
501 // and the main loop handles the actual cleanup to avoid race conditions
502 for (size_t i = 0; i < this->sessions_.size();) {
503 auto *ses = this->sessions_[i];
504 // If the session has a dead socket (marked by destroy callback)
505 if (ses->fd_.load() == 0) {
506 ESP_LOGD(TAG, "Removing dead event source session");
507 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
508 // Remove by swapping with last element (O(1) removal, order doesn't matter for sessions)
509 this->sessions_[i] = this->sessions_.back();
510 this->sessions_.pop_back();
511 } else {
512 ses->loop();
513 ++i;
514 }
515 }
516}
517
518void AsyncEventSource::try_send_nodefer(const char *message, const char *event, uint32_t id, uint32_t reconnect) {
519 for (auto *ses : this->sessions_) {
520 if (ses->fd_.load() != 0) { // Skip dead sessions
521 ses->try_send_nodefer(message, event, id, reconnect);
522 }
523 }
524}
525
526void AsyncEventSource::deferrable_send_state(void *source, const char *event_type,
527 message_generator_t *message_generator) {
528 // Skip if no connected clients to avoid unnecessary processing
529 if (this->empty())
530 return;
531 for (auto *ses : this->sessions_) {
532 if (ses->fd_.load() != 0) { // Skip dead sessions
533 ses->deferrable_send_state(source, event_type, message_generator);
534 }
535 }
536}
537
541 : server_(server), web_server_(ws), entities_iterator_(ws, server) {
542 httpd_req_t *req = *request;
543
544 httpd_resp_set_status(req, HTTPD_200);
545 httpd_resp_set_type(req, "text/event-stream");
546 httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
547 httpd_resp_set_hdr(req, "Connection", "keep-alive");
548
549 for (const auto &header : DefaultHeaders::Instance().headers_) {
550 httpd_resp_set_hdr(req, header.name, header.value);
551 }
552
553 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
554
555 req->sess_ctx = this;
556 req->free_ctx = AsyncEventSourceResponse::destroy;
557
558 this->hd_ = req->handle;
559 this->fd_.store(httpd_req_to_sockfd(req));
560
561 // Use non-blocking send to prevent watchdog timeouts when TCP buffers are full
562 httpd_sess_set_send_override(this->hd_, this->fd_.load(), nonblocking_send);
563
564 // Configure reconnect timeout and send config
565 // this should always go through since the tcp send buffer is empty on connect
566 auto message = ws->get_config_json();
567 this->try_send_nodefer(message.c_str(), "ping", millis(), 30000);
568
569#ifdef USE_WEBSERVER_SORTING
570 for (auto &group : ws->sorting_groups_) {
571 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
572 json::JsonBuilder builder;
573 JsonObject root = builder.root();
574 root["name"] = group.second.name;
575 root["sorting_weight"] = group.second.weight;
576 message = builder.serialize();
577 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
578
579 // a (very) large number of these should be able to be queued initially without defer
580 // since the only thing in the send buffer at this point is the initial ping/config
581 this->try_send_nodefer(message.c_str(), "sorting_group");
582 }
583#endif
584
586
587 // just dump them all up-front and take advantage of the deferred queue
588 // on second thought that takes too long, but leaving the commented code here for debug purposes
589 // while(!this->entities_iterator_.completed()) {
590 // this->entities_iterator_.advance();
591 //}
592}
593
595 auto *rsp = static_cast<AsyncEventSourceResponse *>(ptr);
596 int fd = rsp->fd_.exchange(0); // Atomically get and clear fd
597 ESP_LOGD(TAG, "Event source connection closed (fd: %d)", fd);
598 // Mark as dead - will be cleaned up in the main loop
599 // Note: We don't delete or remove from set here to avoid race conditions
600 // httpd will call our custom close_fn (safe_close_with_shutdown) which handles
601 // shutdown() before close() to prevent lwIP race conditions
602}
603
604// helper for allowing only unique entries in the queue
606 DeferredEvent item(source, message_generator);
607
608 // Use range-based for loop instead of std::find_if to reduce template instantiation overhead and binary size
609 for (auto &event : this->deferred_queue_) {
610 if (event == item) {
611 return; // Already in queue, no need to update since items are equal
612 }
613 }
614 this->deferred_queue_.push_back(item);
615}
616
618 while (!deferred_queue_.empty()) {
619 DeferredEvent &de = deferred_queue_.front();
621 if (this->try_send_nodefer(message.c_str(), "state")) {
622 // O(n) but memory efficiency is more important than speed here which is why std::vector was chosen
623 deferred_queue_.erase(deferred_queue_.begin());
624 } else {
625 break;
626 }
627 }
628}
629
631 if (event_buffer_.empty()) {
632 return;
633 }
634 if (event_bytes_sent_ == event_buffer_.size()) {
635 event_buffer_.resize(0);
637 return;
638 }
639
640 size_t remaining = event_buffer_.size() - event_bytes_sent_;
641 int bytes_sent =
642 httpd_socket_send(this->hd_, this->fd_.load(), event_buffer_.c_str() + event_bytes_sent_, remaining, 0);
643 if (bytes_sent == HTTPD_SOCK_ERR_TIMEOUT) {
644 // EAGAIN/EWOULDBLOCK - socket buffer full, try again later
645 // NOTE: Similar logic exists in web_server/web_server.cpp in DeferredUpdateEventSource::process_deferred_queue_()
646 // The implementations differ due to platform-specific APIs (HTTPD_SOCK_ERR_TIMEOUT vs DISCARDED, fd_.store(0) vs
647 // close()), but the failure counting and timeout logic should be kept in sync. If you change this logic, also
648 // update the Arduino implementation.
651 // Too many failures, connection is likely dead
652 ESP_LOGW(TAG, "Closing stuck EventSource connection after %" PRIu16 " failed sends",
654 this->fd_.store(0); // Mark for cleanup
655 this->deferred_queue_.clear();
656 }
657 return;
658 }
659 if (bytes_sent == HTTPD_SOCK_ERR_FAIL) {
660 // Real socket error - connection will be closed by httpd and destroy callback will be called
661 return;
662 }
663 if (bytes_sent <= 0) {
664 // Unexpected error or zero bytes sent
665 ESP_LOGW(TAG, "Unexpected send result: %d", bytes_sent);
666 return;
667 }
668
669 // Successful send - reset failure counter
671 event_bytes_sent_ += bytes_sent;
672
673 // Log partial sends for debugging
674 if (event_bytes_sent_ < event_buffer_.size()) {
675 ESP_LOGV(TAG, "Partial send: %d/%zu bytes (total: %zu/%zu)", bytes_sent, remaining, event_bytes_sent_,
676 event_buffer_.size());
677 }
678
679 if (event_bytes_sent_ == event_buffer_.size()) {
680 event_buffer_.resize(0);
682 }
683}
684
691
692bool AsyncEventSourceResponse::try_send_nodefer(const char *message, const char *event, uint32_t id,
693 uint32_t reconnect) {
694 if (this->fd_.load() == 0) {
695 return false;
696 }
697
699 if (!event_buffer_.empty()) {
700 // there is still pending event data to send first
701 return false;
702 }
703
704 // 8 spaces are standing in for the hexidecimal chunk length to print later
705 const char chunk_len_header[] = " " CRLF_STR;
706 const int chunk_len_header_len = sizeof(chunk_len_header) - 1;
707
708 event_buffer_.append(chunk_len_header);
709
710 // Use stack buffer for formatting numeric fields to avoid temporary string allocations
711 // Size: "retry: " (7) + max uint32 (10 digits) + CRLF (2) + null (1) = 20 bytes, use 32 for safety
712 constexpr size_t num_buf_size = 32;
713 char num_buf[num_buf_size];
714
715 if (reconnect) {
716 int len = snprintf(num_buf, num_buf_size, "retry: %" PRIu32 CRLF_STR, reconnect);
717 event_buffer_.append(num_buf, len);
718 }
719
720 if (id) {
721 int len = snprintf(num_buf, num_buf_size, "id: %" PRIu32 CRLF_STR, id);
722 event_buffer_.append(num_buf, len);
723 }
724
725 if (event && *event) {
726 event_buffer_.append("event: ", sizeof("event: ") - 1);
727 event_buffer_.append(event);
728 event_buffer_.append(CRLF_STR, CRLF_LEN);
729 }
730
731 // Match ESPAsyncWebServer: null message means no data lines and no terminating blank line
732 if (message) {
733 // SSE spec requires each line of a multi-line message to have its own "data:" prefix
734 // Handle \n, \r, and \r\n line endings (matching ESPAsyncWebServer behavior)
735
736 // Fast path: check if message contains any newlines at all
737 // Most SSE messages (JSON state updates) have no newlines
738 const char *first_n = strchr(message, '\n');
739 const char *first_r = strchr(message, '\r');
740
741 if (first_n == nullptr && first_r == nullptr) {
742 // No newlines - fast path (most common case)
743 event_buffer_.append("data: ", sizeof("data: ") - 1);
744 event_buffer_.append(message);
745 event_buffer_.append(CRLF_STR CRLF_STR, CRLF_LEN * 2); // data line + blank line terminator
746 } else {
747 // Has newlines - handle multi-line message
748 const char *line_start = message;
749 size_t msg_len = strlen(message);
750 const char *msg_end = message + msg_len;
751
752 // Reuse the first search results
753 const char *next_n = first_n;
754 const char *next_r = first_r;
755
756 while (line_start <= msg_end) {
757 const char *line_end;
758 const char *next_line;
759
760 if (next_n == nullptr && next_r == nullptr) {
761 // No more line breaks - output remaining text as final line
762 event_buffer_.append("data: ", sizeof("data: ") - 1);
763 event_buffer_.append(line_start);
764 event_buffer_.append(CRLF_STR, CRLF_LEN);
765 break;
766 }
767
768 // Determine line ending type and next line start
769 if (next_n != nullptr && next_r != nullptr) {
770 if (next_r + 1 == next_n) {
771 // \r\n sequence
772 line_end = next_r;
773 next_line = next_n + 1;
774 } else {
775 // Mixed \n and \r - use whichever comes first
776 line_end = (next_r < next_n) ? next_r : next_n;
777 next_line = line_end + 1;
778 }
779 } else if (next_n != nullptr) {
780 // Unix LF
781 line_end = next_n;
782 next_line = next_n + 1;
783 } else {
784 // Old Mac CR
785 line_end = next_r;
786 next_line = next_r + 1;
787 }
788
789 // Output this line
790 event_buffer_.append("data: ", sizeof("data: ") - 1);
791 event_buffer_.append(line_start, line_end - line_start);
792 event_buffer_.append(CRLF_STR, CRLF_LEN);
793
794 line_start = next_line;
795
796 // Check if we've consumed all content
797 if (line_start >= msg_end) {
798 break;
799 }
800
801 // Search for next newlines only in remaining string
802 next_n = strchr(line_start, '\n');
803 next_r = strchr(line_start, '\r');
804 }
805
806 // Terminate message with blank line
807 event_buffer_.append(CRLF_STR, CRLF_LEN);
808 }
809 }
810
811 if (event_buffer_.size() == static_cast<size_t>(chunk_len_header_len)) {
812 // Nothing was added, reset buffer
813 event_buffer_.resize(0);
814 return true;
815 }
816
817 event_buffer_.append(CRLF_STR, CRLF_LEN);
818
819 // chunk length header itself and the final chunk terminating CRLF are not counted as part of the chunk
820 int chunk_len = event_buffer_.size() - CRLF_LEN - chunk_len_header_len;
821 char chunk_len_str[9];
822 snprintf(chunk_len_str, 9, "%08x", chunk_len);
823 std::memcpy(&event_buffer_[0], chunk_len_str, 8);
824
827
828 return true;
829}
830
831void AsyncEventSourceResponse::deferrable_send_state(void *source, const char *event_type,
832 message_generator_t *message_generator) {
833 // allow all json "details_all" to go through before publishing bare state events, this avoids unnamed entries showing
834 // up in the web GUI and reduces event load during initial connect
835 if (!this->entities_iterator_.completed() && 0 != strcmp(event_type, "state_detail_all"))
836 return;
837
838 if (source == nullptr)
839 return;
840 if (event_type == nullptr)
841 return;
842 if (message_generator == nullptr)
843 return;
844
845 if (0 != strcmp(event_type, "state_detail_all") && 0 != strcmp(event_type, "state")) {
846 ESP_LOGE(TAG, "Can't defer non-state event");
847 }
848
851
852 if (!event_buffer_.empty() || !deferred_queue_.empty()) {
853 // outgoing event buffer or deferred queue still not empty which means downstream tcp send buffer full, no point
854 // trying to send first
855 deq_push_back_with_dedup_(source, message_generator);
856 } else {
857 auto message = message_generator(web_server_, source);
858 if (!this->try_send_nodefer(message.c_str(), "state")) {
859 deq_push_back_with_dedup_(source, message_generator);
860 }
861 }
862}
863#endif
864
865#ifdef USE_WEBSERVER_OTA
866esp_err_t AsyncWebServer::handle_multipart_upload_(httpd_req_t *r, const char *content_type) {
867 static constexpr size_t MULTIPART_CHUNK_SIZE = 1460; // Match Arduino AsyncWebServer buffer size
868 static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024; // Yield every 16KB to prevent watchdog
869
870 // Parse boundary and create reader
871 const char *boundary_start;
872 size_t boundary_len;
873 if (!parse_multipart_boundary(content_type, &boundary_start, &boundary_len)) {
874 ESP_LOGE(TAG, "Failed to parse multipart boundary");
875 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
876 return ESP_FAIL;
877 }
878
880 AsyncWebHandler *handler = nullptr;
881 for (auto *h : this->handlers_) {
882 if (h->canHandle(&req)) {
883 handler = h;
884 break;
885 }
886 }
887
888 if (!handler) {
889 ESP_LOGW(TAG, "No handler found for OTA request");
890 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, nullptr);
891 return ESP_OK;
892 }
893
894 // Upload state
895 std::string filename;
896 size_t index = 0;
897 // Create reader on heap to reduce stack usage
898 auto reader = std::make_unique<MultipartReader>("--" + std::string(boundary_start, boundary_len));
899
900 // Configure callbacks
901 reader->set_data_callback([&](const uint8_t *data, size_t len) {
902 if (!reader->has_file() || !len)
903 return;
904
905 if (filename.empty()) {
906 filename = reader->get_current_part().filename;
907 ESP_LOGV(TAG, "Processing file: '%s'", filename.c_str());
908 handler->handleUpload(&req, filename, 0, nullptr, 0, false); // Start
909 }
910
911 handler->handleUpload(&req, filename, index, const_cast<uint8_t *>(data), len, false);
912 index += len;
913 });
914
915 reader->set_part_complete_callback([&]() {
916 if (index > 0) {
917 handler->handleUpload(&req, filename, index, nullptr, 0, true); // End
918 filename.clear();
919 index = 0;
920 }
921 });
922
923 // Use heap buffer - 1460 bytes is too large for the httpd task stack
924 auto buffer = std::make_unique_for_overwrite<char[]>(MULTIPART_CHUNK_SIZE);
925 size_t bytes_since_yield = 0;
926
927 for (size_t remaining = r->content_len; remaining > 0;) {
928 int recv_len = httpd_req_recv(r, buffer.get(), std::min(remaining, MULTIPART_CHUNK_SIZE));
929
930 if (recv_len <= 0) {
931 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
932 nullptr);
933 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
934 }
935
936 if (reader->parse(buffer.get(), recv_len) != static_cast<size_t>(recv_len)) {
937 ESP_LOGW(TAG, "Multipart parser error");
938 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
939 return ESP_FAIL;
940 }
941
942 remaining -= recv_len;
943 bytes_since_yield += recv_len;
944
945 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
946 vTaskDelay(1);
947 bytes_since_yield = 0;
948 }
949 }
950
951 handler->handleRequest(&req);
952 return ESP_OK;
953}
954#endif // USE_WEBSERVER_OTA
955
956} // namespace esphome::web_server_idf
957
958#endif // !defined(USE_ESP32)
uint8_t h
Definition bl0906.h:2
uint8_t status
Definition bl0942.h:8
void begin(bool include_internal=false)
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
Builder class for creating JSON documents without lambdas.
Definition json_util.h:170
SerializationBuffer serialize()
Serialize the JSON document to a SerializationBuffer (stack-first allocation) Uses 512-byte stack buf...
Definition json_util.cpp:69
This class allows users to create a web server with their ESP nodes.
Definition web_server.h:190
json::SerializationBuffer get_config_json()
Return the webserver configuration as JSON.
std::map< uint64_t, SortingGroup > sorting_groups_
Definition web_server.h:497
std::vector< AsyncEventSourceResponse * > sessions_
void deferrable_send_state(void *source, const char *event_type, message_generator_t *message_generator)
esphome::web_server::WebServer * web_server_
void try_send_nodefer(const char *message, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
void handleRequest(AsyncWebServerRequest *request) override
void deferrable_send_state(void *source, const char *event_type, message_generator_t *message_generator)
esphome::web_server::WebServer * web_server_
void deq_push_back_with_dedup_(void *source, message_generator_t *message_generator)
AsyncEventSourceResponse(const AsyncWebServerRequest *request, esphome::web_server_idf::AsyncEventSource *server, esphome::web_server::WebServer *ws)
esphome::web_server::ListEntitiesIterator entities_iterator_
bool try_send_nodefer(const char *message, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
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)
std::function< void(AsyncWebServerRequest *request)> on_not_found_
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)
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
ESPDEPRECATED("Use url_to() instead. Removed in 2026.9.0", "2026.3.0") std void requestAuthentication(const char *realm=nullptr) const
std::vector< AsyncWebParameter * > params_
virtual const char * get_content_data() const =0
void addHeader(const char *name, const char *value)
const char * message
Definition component.cpp:38
uint16_t flags
mopeka_std_values val[4]
const char *const TAG
Definition spi.cpp:7
bool query_has_key(const char *query_url, size_t query_len, const char *key)
Definition utils.cpp:70
json::SerializationBuffer<>(esphome::web_server::WebServer *, void *) message_generator_t
optional< std::string > request_get_header(httpd_req_t *req, const char *name)
Definition utils.cpp:36
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:53
const char * strcasestr_n(const char *haystack, size_t haystack_len, const char *needle)
Definition utils.cpp:93
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
bool request_has_header(httpd_req_t *req, const char *name)
Definition utils.cpp:34
va_end(args)
std::string size_t len
Definition helpers.h:817
size_t size_t const char va_start(args, fmt)
size_t size_t const char * fmt
Definition helpers.h:855
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
std::string print()
uint16_t length
Definition tt21100.cpp:0