ESPHome 2025.11.4
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
33namespace esphome {
34namespace web_server_idf {
35
36#ifndef HTTPD_409
37#define HTTPD_409 "409 Conflict"
38#endif
39
40#define CRLF_STR "\r\n"
41#define CRLF_LEN (sizeof(CRLF_STR) - 1)
42
43static const char *const TAG = "web_server_idf";
44
45// Global instance to avoid guard variable (saves 8 bytes)
46// This is initialized at program startup before any threads
47namespace {
48// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
49DefaultHeaders default_headers_instance;
50} // namespace
51
52DefaultHeaders &DefaultHeaders::Instance() { return default_headers_instance; }
53
54namespace {
55// Non-blocking send function to prevent watchdog timeouts when TCP buffers are full
70int nonblocking_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags) {
71 if (buf == nullptr) {
72 return HTTPD_SOCK_ERR_INVALID;
73 }
74
75 // Use MSG_DONTWAIT to prevent blocking when TCP send buffer is full
76 int ret = send(sockfd, buf, buf_len, flags | MSG_DONTWAIT);
77 if (ret < 0) {
78 if (errno == EAGAIN || errno == EWOULDBLOCK) {
79 // Buffer full - retry later
80 return HTTPD_SOCK_ERR_TIMEOUT;
81 }
82 // Real error
83 ESP_LOGD(TAG, "send error: errno %d", errno);
84 return HTTPD_SOCK_ERR_FAIL;
85 }
86 return ret;
87}
88} // namespace
89
90void AsyncWebServer::safe_close_with_shutdown(httpd_handle_t hd, int sockfd) {
91 // CRITICAL: Shut down receive BEFORE closing to prevent lwIP race conditions
92 //
93 // The race condition occurs because close() initiates lwIP teardown while
94 // the TCP/IP thread can still receive packets, causing assertions when
95 // recv_tcp() sees partially-torn-down state.
96 //
97 // By shutting down receive first, we tell lwIP to stop accepting new data BEFORE
98 // the teardown begins, eliminating the race window. We only shutdown RD (not RDWR)
99 // to allow the FIN packet to be sent cleanly during close().
100 //
101 // Note: This function may be called with an already-closed socket if the network
102 // stack closed it. In that case, shutdown() will fail but close() is safe to call.
103 //
104 // See: https://github.com/esphome/esphome-webserver/issues/163
105
106 // Attempt shutdown - ignore errors as socket may already be closed
107 shutdown(sockfd, SHUT_RD);
108
109 // Always close - safe even if socket is already closed by network stack
110 close(sockfd);
111}
112
114 if (this->server_) {
115 httpd_stop(this->server_);
116 this->server_ = nullptr;
117 }
118}
119
121 if (this->lru_purge_enable_ == enable) {
122 return; // No change needed
123 }
124 this->lru_purge_enable_ = enable;
125 // If server is already running, restart it with new config
126 if (this->server_) {
127 this->end();
128 this->begin();
129 }
130}
131
133 if (this->server_) {
134 this->end();
135 }
136 httpd_config_t config = HTTPD_DEFAULT_CONFIG();
137 config.server_port = this->port_;
138 config.uri_match_fn = [](const char * /*unused*/, const char * /*unused*/, size_t /*unused*/) { return true; };
139 // Enable LRU purging if requested (e.g., by captive portal to handle probe bursts)
140 config.lru_purge_enable = this->lru_purge_enable_;
141 // Use custom close function that shuts down before closing to prevent lwIP race conditions
143 if (httpd_start(&this->server_, &config) == ESP_OK) {
144 const httpd_uri_t handler_get = {
145 .uri = "",
146 .method = HTTP_GET,
148 .user_ctx = this,
149 };
150 httpd_register_uri_handler(this->server_, &handler_get);
151
152 const httpd_uri_t handler_post = {
153 .uri = "",
154 .method = HTTP_POST,
156 .user_ctx = this,
157 };
158 httpd_register_uri_handler(this->server_, &handler_post);
159
160 const httpd_uri_t handler_options = {
161 .uri = "",
162 .method = HTTP_OPTIONS,
164 .user_ctx = this,
165 };
166 httpd_register_uri_handler(this->server_, &handler_options);
167 }
168}
169
170esp_err_t AsyncWebServer::request_post_handler(httpd_req_t *r) {
171 ESP_LOGVV(TAG, "Enter AsyncWebServer::request_post_handler. uri=%s", r->uri);
172 auto content_type = request_get_header(r, "Content-Type");
173
174 if (!request_has_header(r, "Content-Length")) {
175 ESP_LOGW(TAG, "Content length is required for post: %s", r->uri);
176 httpd_resp_send_err(r, HTTPD_411_LENGTH_REQUIRED, nullptr);
177 return ESP_OK;
178 }
179
180 if (content_type.has_value()) {
181 const char *content_type_char = content_type.value().c_str();
182
183 // Check most common case first
184 if (stristr(content_type_char, "application/x-www-form-urlencoded") != nullptr) {
185 // Normal form data - proceed with regular handling
186#ifdef USE_WEBSERVER_OTA
187 } else if (stristr(content_type_char, "multipart/form-data") != nullptr) {
188 auto *server = static_cast<AsyncWebServer *>(r->user_ctx);
189 return server->handle_multipart_upload_(r, content_type_char);
190#endif
191 } else {
192 ESP_LOGW(TAG, "Unsupported content type for POST: %s", content_type_char);
193 // fallback to get handler to support backward compatibility
195 }
196 }
197
198 // Handle regular form data
199 if (r->content_len > CONFIG_HTTPD_MAX_REQ_HDR_LEN) {
200 ESP_LOGW(TAG, "Request size is to big: %zu", r->content_len);
201 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
202 return ESP_FAIL;
203 }
204
205 std::string post_query;
206 if (r->content_len > 0) {
207 post_query.resize(r->content_len);
208 const int ret = httpd_req_recv(r, &post_query[0], r->content_len + 1);
209 if (ret <= 0) { // 0 return value indicates connection closed
210 if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
211 httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT, nullptr);
212 return ESP_ERR_TIMEOUT;
213 }
214 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
215 return ESP_FAIL;
216 }
217 }
218
219 AsyncWebServerRequest req(r, std::move(post_query));
220 return static_cast<AsyncWebServer *>(r->user_ctx)->request_handler_(&req);
221}
222
223esp_err_t AsyncWebServer::request_handler(httpd_req_t *r) {
224 ESP_LOGVV(TAG, "Enter AsyncWebServer::request_handler. method=%u, uri=%s", r->method, r->uri);
226 return static_cast<AsyncWebServer *>(r->user_ctx)->request_handler_(&req);
227}
228
230 for (auto *handler : this->handlers_) {
231 if (handler->canHandle(request)) {
232 // At now process only basic requests.
233 // OTA requires multipart request support and handleUpload for it
234 handler->handleRequest(request);
235 return ESP_OK;
236 }
237 }
238 if (this->on_not_found_) {
239 this->on_not_found_(request);
240 return ESP_OK;
241 }
242 return ESP_ERR_NOT_FOUND;
243}
244
246 delete this->rsp_;
247 for (auto *param : this->params_) {
248 delete param; // NOLINT(cppcoreguidelines-owning-memory)
249 }
250}
251
252bool AsyncWebServerRequest::hasHeader(const char *name) const { return request_has_header(*this, name); }
253
255 return request_get_header(*this, name);
256}
257
258std::string AsyncWebServerRequest::url() const {
259 auto *str = strchr(this->req_->uri, '?');
260 if (str == nullptr) {
261 return this->req_->uri;
262 }
263 return std::string(this->req_->uri, str - this->req_->uri);
264}
265
266std::string AsyncWebServerRequest::host() const { return this->get_header("Host").value(); }
267
269 httpd_resp_send(*this, response->get_content_data(), response->get_content_size());
270}
271
272void AsyncWebServerRequest::send(int code, const char *content_type, const char *content) {
273 this->init_response_(nullptr, code, content_type);
274 if (content) {
275 httpd_resp_send(*this, content, HTTPD_RESP_USE_STRLEN);
276 } else {
277 httpd_resp_send(*this, nullptr, 0);
278 }
279}
280
281void AsyncWebServerRequest::redirect(const std::string &url) {
282 httpd_resp_set_status(*this, "302 Found");
283 httpd_resp_set_hdr(*this, "Location", url.c_str());
284 httpd_resp_set_hdr(*this, "Connection", "close");
285 httpd_resp_send(*this, nullptr, 0);
286}
287
288void AsyncWebServerRequest::init_response_(AsyncWebServerResponse *rsp, int code, const char *content_type) {
289 // Set status code - use constants for common codes, default to 500 for unknown codes
290 const char *status;
291 switch (code) {
292 case 200:
293 status = HTTPD_200;
294 break;
295 case 404:
296 status = HTTPD_404;
297 break;
298 case 409:
299 status = HTTPD_409;
300 break;
301 default:
302 status = HTTPD_500;
303 break;
304 }
305 httpd_resp_set_status(*this, status);
306
307 if (content_type && *content_type) {
308 httpd_resp_set_type(*this, content_type);
309 }
310 httpd_resp_set_hdr(*this, "Accept-Ranges", "none");
311
312 for (const auto &pair : DefaultHeaders::Instance().headers_) {
313 httpd_resp_set_hdr(*this, pair.first.c_str(), pair.second.c_str());
314 }
315
316 delete this->rsp_;
317 this->rsp_ = rsp;
318}
319
320#ifdef USE_WEBSERVER_AUTH
321bool AsyncWebServerRequest::authenticate(const char *username, const char *password) const {
322 if (username == nullptr || password == nullptr || *username == 0) {
323 return true;
324 }
325 auto auth = this->get_header("Authorization");
326 if (!auth.has_value()) {
327 return false;
328 }
329
330 auto *auth_str = auth.value().c_str();
331
332 const auto auth_prefix_len = sizeof("Basic ") - 1;
333 if (strncmp("Basic ", auth_str, auth_prefix_len) != 0) {
334 ESP_LOGW(TAG, "Only Basic authorization supported yet");
335 return false;
336 }
337
338 std::string user_info;
339 user_info += username;
340 user_info += ':';
341 user_info += password;
342
343 size_t n = 0, out;
344 esp_crypto_base64_encode(nullptr, 0, &n, reinterpret_cast<const uint8_t *>(user_info.c_str()), user_info.size());
345
346 auto digest = std::unique_ptr<char[]>(new char[n + 1]);
347 esp_crypto_base64_encode(reinterpret_cast<uint8_t *>(digest.get()), n, &out,
348 reinterpret_cast<const uint8_t *>(user_info.c_str()), user_info.size());
349
350 return strcmp(digest.get(), auth_str + auth_prefix_len) == 0;
351}
352
353void AsyncWebServerRequest::requestAuthentication(const char *realm) const {
354 httpd_resp_set_hdr(*this, "Connection", "keep-alive");
355 auto auth_val = str_sprintf("Basic realm=\"%s\"", realm ? realm : "Login Required");
356 httpd_resp_set_hdr(*this, "WWW-Authenticate", auth_val.c_str());
357 httpd_resp_send_err(*this, HTTPD_401_UNAUTHORIZED, nullptr);
358}
359#endif
360
362 // Check cache first - only successful lookups are cached
363 for (auto *param : this->params_) {
364 if (param->name() == name) {
365 return param;
366 }
367 }
368
369 // Look up value from query strings
371 if (!val.has_value()) {
372 auto url_query = request_get_url_query(*this);
373 if (url_query.has_value()) {
374 val = query_key_value(url_query.value(), name);
375 }
376 }
377
378 // Don't cache misses to avoid wasting memory when handlers check for
379 // optional parameters that don't exist in the request
380 if (!val.has_value()) {
381 return nullptr;
382 }
383
384 auto *param = new AsyncWebParameter(name, val.value()); // NOLINT(cppcoreguidelines-owning-memory)
385 this->params_.push_back(param);
386 return param;
387}
388
389void AsyncWebServerResponse::addHeader(const char *name, const char *value) {
390 httpd_resp_set_hdr(*this->req_, name, value);
391}
392
393void AsyncResponseStream::print(float value) {
394 // Use stack buffer to avoid temporary string allocation
395 // Size: sign (1) + digits (10) + decimal (1) + precision (6) + exponent (5) + null (1) = 24, use 32 for safety
396 char buf[32];
397 int len = snprintf(buf, sizeof(buf), "%f", value);
398 this->content_.append(buf, len);
399}
400
401void AsyncResponseStream::printf(const char *fmt, ...) {
402 va_list args;
403
404 va_start(args, fmt);
405 const int length = vsnprintf(nullptr, 0, fmt, args);
406 va_end(args);
407
408 std::string str;
409 str.resize(length);
410
411 va_start(args, fmt);
412 vsnprintf(&str[0], length + 1, fmt, args);
413 va_end(args);
414
415 this->print(str);
416}
417
418#ifdef USE_WEBSERVER
420 for (auto *ses : this->sessions_) {
421 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
422 }
423}
424
426 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory,clang-analyzer-cplusplus.NewDeleteLeaks)
427 auto *rsp = new AsyncEventSourceResponse(request, this, this->web_server_);
428 if (this->on_connect_) {
429 this->on_connect_(rsp);
430 }
431 this->sessions_.push_back(rsp);
432}
433
435 // Clean up dead sessions safely
436 // This follows the ESP-IDF pattern where free_ctx marks resources as dead
437 // and the main loop handles the actual cleanup to avoid race conditions
438 for (size_t i = 0; i < this->sessions_.size();) {
439 auto *ses = this->sessions_[i];
440 // If the session has a dead socket (marked by destroy callback)
441 if (ses->fd_.load() == 0) {
442 ESP_LOGD(TAG, "Removing dead event source session");
443 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
444 // Remove by swapping with last element (O(1) removal, order doesn't matter for sessions)
445 this->sessions_[i] = this->sessions_.back();
446 this->sessions_.pop_back();
447 } else {
448 ses->loop();
449 ++i;
450 }
451 }
452}
453
454void AsyncEventSource::try_send_nodefer(const char *message, const char *event, uint32_t id, uint32_t reconnect) {
455 for (auto *ses : this->sessions_) {
456 if (ses->fd_.load() != 0) { // Skip dead sessions
457 ses->try_send_nodefer(message, event, id, reconnect);
458 }
459 }
460}
461
462void AsyncEventSource::deferrable_send_state(void *source, const char *event_type,
463 message_generator_t *message_generator) {
464 // Skip if no connected clients to avoid unnecessary processing
465 if (this->empty())
466 return;
467 for (auto *ses : this->sessions_) {
468 if (ses->fd_.load() != 0) { // Skip dead sessions
469 ses->deferrable_send_state(source, event_type, message_generator);
470 }
471 }
472}
473
477 : server_(server), web_server_(ws), entities_iterator_(new esphome::web_server::ListEntitiesIterator(ws, server)) {
478 httpd_req_t *req = *request;
479
480 httpd_resp_set_status(req, HTTPD_200);
481 httpd_resp_set_type(req, "text/event-stream");
482 httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
483 httpd_resp_set_hdr(req, "Connection", "keep-alive");
484
485 for (const auto &pair : DefaultHeaders::Instance().headers_) {
486 httpd_resp_set_hdr(req, pair.first.c_str(), pair.second.c_str());
487 }
488
489 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
490
491 req->sess_ctx = this;
492 req->free_ctx = AsyncEventSourceResponse::destroy;
493
494 this->hd_ = req->handle;
495 this->fd_.store(httpd_req_to_sockfd(req));
496
497 // Use non-blocking send to prevent watchdog timeouts when TCP buffers are full
498 httpd_sess_set_send_override(this->hd_, this->fd_.load(), nonblocking_send);
499
500 // Configure reconnect timeout and send config
501 // this should always go through since the tcp send buffer is empty on connect
502 std::string message = ws->get_config_json();
503 this->try_send_nodefer(message.c_str(), "ping", millis(), 30000);
504
505#ifdef USE_WEBSERVER_SORTING
506 for (auto &group : ws->sorting_groups_) {
507 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
508 json::JsonBuilder builder;
509 JsonObject root = builder.root();
510 root["name"] = group.second.name;
511 root["sorting_weight"] = group.second.weight;
512 message = builder.serialize();
513 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
514
515 // a (very) large number of these should be able to be queued initially without defer
516 // since the only thing in the send buffer at this point is the initial ping/config
517 this->try_send_nodefer(message.c_str(), "sorting_group");
518 }
519#endif
520
522
523 // just dump them all up-front and take advantage of the deferred queue
524 // on second thought that takes too long, but leaving the commented code here for debug purposes
525 // while(!this->entities_iterator_->completed()) {
526 // this->entities_iterator_->advance();
527 //}
528}
529
531 auto *rsp = static_cast<AsyncEventSourceResponse *>(ptr);
532 int fd = rsp->fd_.exchange(0); // Atomically get and clear fd
533 ESP_LOGD(TAG, "Event source connection closed (fd: %d)", fd);
534 // Mark as dead - will be cleaned up in the main loop
535 // Note: We don't delete or remove from set here to avoid race conditions
536 // httpd will call our custom close_fn (safe_close_with_shutdown) which handles
537 // shutdown() before close() to prevent lwIP race conditions
538}
539
540// helper for allowing only unique entries in the queue
542 DeferredEvent item(source, message_generator);
543
544 // Use range-based for loop instead of std::find_if to reduce template instantiation overhead and binary size
545 for (auto &event : this->deferred_queue_) {
546 if (event == item) {
547 return; // Already in queue, no need to update since items are equal
548 }
549 }
550 this->deferred_queue_.push_back(item);
551}
552
554 while (!deferred_queue_.empty()) {
555 DeferredEvent &de = deferred_queue_.front();
556 std::string message = de.message_generator_(web_server_, de.source_);
557 if (this->try_send_nodefer(message.c_str(), "state")) {
558 // O(n) but memory efficiency is more important than speed here which is why std::vector was chosen
559 deferred_queue_.erase(deferred_queue_.begin());
560 } else {
561 break;
562 }
563 }
564}
565
567 if (event_buffer_.empty()) {
568 return;
569 }
570 if (event_bytes_sent_ == event_buffer_.size()) {
571 event_buffer_.resize(0);
573 return;
574 }
575
576 size_t remaining = event_buffer_.size() - event_bytes_sent_;
577 int bytes_sent =
578 httpd_socket_send(this->hd_, this->fd_.load(), event_buffer_.c_str() + event_bytes_sent_, remaining, 0);
579 if (bytes_sent == HTTPD_SOCK_ERR_TIMEOUT) {
580 // EAGAIN/EWOULDBLOCK - socket buffer full, try again later
581 // NOTE: Similar logic exists in web_server/web_server.cpp in DeferredUpdateEventSource::process_deferred_queue_()
582 // The implementations differ due to platform-specific APIs (HTTPD_SOCK_ERR_TIMEOUT vs DISCARDED, fd_.store(0) vs
583 // close()), but the failure counting and timeout logic should be kept in sync. If you change this logic, also
584 // update the Arduino implementation.
587 // Too many failures, connection is likely dead
588 ESP_LOGW(TAG, "Closing stuck EventSource connection after %" PRIu16 " failed sends",
590 this->fd_.store(0); // Mark for cleanup
591 this->deferred_queue_.clear();
592 }
593 return;
594 }
595 if (bytes_sent == HTTPD_SOCK_ERR_FAIL) {
596 // Real socket error - connection will be closed by httpd and destroy callback will be called
597 return;
598 }
599 if (bytes_sent <= 0) {
600 // Unexpected error or zero bytes sent
601 ESP_LOGW(TAG, "Unexpected send result: %d", bytes_sent);
602 return;
603 }
604
605 // Successful send - reset failure counter
607 event_bytes_sent_ += bytes_sent;
608
609 // Log partial sends for debugging
610 if (event_bytes_sent_ < event_buffer_.size()) {
611 ESP_LOGV(TAG, "Partial send: %d/%zu bytes (total: %zu/%zu)", bytes_sent, remaining, event_bytes_sent_,
612 event_buffer_.size());
613 }
614
615 if (event_bytes_sent_ == event_buffer_.size()) {
616 event_buffer_.resize(0);
618 }
619}
620
627
628bool AsyncEventSourceResponse::try_send_nodefer(const char *message, const char *event, uint32_t id,
629 uint32_t reconnect) {
630 if (this->fd_.load() == 0) {
631 return false;
632 }
633
635 if (!event_buffer_.empty()) {
636 // there is still pending event data to send first
637 return false;
638 }
639
640 // 8 spaces are standing in for the hexidecimal chunk length to print later
641 const char chunk_len_header[] = " " CRLF_STR;
642 const int chunk_len_header_len = sizeof(chunk_len_header) - 1;
643
644 event_buffer_.append(chunk_len_header);
645
646 // Use stack buffer for formatting numeric fields to avoid temporary string allocations
647 // Size: "retry: " (7) + max uint32 (10 digits) + CRLF (2) + null (1) = 20 bytes, use 32 for safety
648 constexpr size_t num_buf_size = 32;
649 char num_buf[num_buf_size];
650
651 if (reconnect) {
652 int len = snprintf(num_buf, num_buf_size, "retry: %" PRIu32 CRLF_STR, reconnect);
653 event_buffer_.append(num_buf, len);
654 }
655
656 if (id) {
657 int len = snprintf(num_buf, num_buf_size, "id: %" PRIu32 CRLF_STR, id);
658 event_buffer_.append(num_buf, len);
659 }
660
661 if (event && *event) {
662 event_buffer_.append("event: ", sizeof("event: ") - 1);
663 event_buffer_.append(event);
664 event_buffer_.append(CRLF_STR, CRLF_LEN);
665 }
666
667 if (message && *message) {
668 event_buffer_.append("data: ", sizeof("data: ") - 1);
669 event_buffer_.append(message);
670 event_buffer_.append(CRLF_STR, CRLF_LEN);
671 }
672
673 if (event_buffer_.empty()) {
674 return true;
675 }
676
677 event_buffer_.append(CRLF_STR, CRLF_LEN);
678 event_buffer_.append(CRLF_STR, CRLF_LEN);
679
680 // chunk length header itself and the final chunk terminating CRLF are not counted as part of the chunk
681 int chunk_len = event_buffer_.size() - CRLF_LEN - chunk_len_header_len;
682 char chunk_len_str[9];
683 snprintf(chunk_len_str, 9, "%08x", chunk_len);
684 std::memcpy(&event_buffer_[0], chunk_len_str, 8);
685
688
689 return true;
690}
691
692void AsyncEventSourceResponse::deferrable_send_state(void *source, const char *event_type,
693 message_generator_t *message_generator) {
694 // allow all json "details_all" to go through before publishing bare state events, this avoids unnamed entries showing
695 // up in the web GUI and reduces event load during initial connect
696 if (!entities_iterator_->completed() && 0 != strcmp(event_type, "state_detail_all"))
697 return;
698
699 if (source == nullptr)
700 return;
701 if (event_type == nullptr)
702 return;
703 if (message_generator == nullptr)
704 return;
705
706 if (0 != strcmp(event_type, "state_detail_all") && 0 != strcmp(event_type, "state")) {
707 ESP_LOGE(TAG, "Can't defer non-state event");
708 }
709
712
713 if (!event_buffer_.empty() || !deferred_queue_.empty()) {
714 // outgoing event buffer or deferred queue still not empty which means downstream tcp send buffer full, no point
715 // trying to send first
716 deq_push_back_with_dedup_(source, message_generator);
717 } else {
718 std::string message = message_generator(web_server_, source);
719 if (!this->try_send_nodefer(message.c_str(), "state")) {
720 deq_push_back_with_dedup_(source, message_generator);
721 }
722 }
723}
724#endif
725
726#ifdef USE_WEBSERVER_OTA
727esp_err_t AsyncWebServer::handle_multipart_upload_(httpd_req_t *r, const char *content_type) {
728 static constexpr size_t MULTIPART_CHUNK_SIZE = 1460; // Match Arduino AsyncWebServer buffer size
729 static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024; // Yield every 16KB to prevent watchdog
730
731 // Parse boundary and create reader
732 const char *boundary_start;
733 size_t boundary_len;
734 if (!parse_multipart_boundary(content_type, &boundary_start, &boundary_len)) {
735 ESP_LOGE(TAG, "Failed to parse multipart boundary");
736 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
737 return ESP_FAIL;
738 }
739
741 AsyncWebHandler *handler = nullptr;
742 for (auto *h : this->handlers_) {
743 if (h->canHandle(&req)) {
744 handler = h;
745 break;
746 }
747 }
748
749 if (!handler) {
750 ESP_LOGW(TAG, "No handler found for OTA request");
751 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, nullptr);
752 return ESP_OK;
753 }
754
755 // Upload state
756 std::string filename;
757 size_t index = 0;
758 // Create reader on heap to reduce stack usage
759 auto reader = std::make_unique<MultipartReader>("--" + std::string(boundary_start, boundary_len));
760
761 // Configure callbacks
762 reader->set_data_callback([&](const uint8_t *data, size_t len) {
763 if (!reader->has_file() || !len)
764 return;
765
766 if (filename.empty()) {
767 filename = reader->get_current_part().filename;
768 ESP_LOGV(TAG, "Processing file: '%s'", filename.c_str());
769 handler->handleUpload(&req, filename, 0, nullptr, 0, false); // Start
770 }
771
772 handler->handleUpload(&req, filename, index, const_cast<uint8_t *>(data), len, false);
773 index += len;
774 });
775
776 reader->set_part_complete_callback([&]() {
777 if (index > 0) {
778 handler->handleUpload(&req, filename, index, nullptr, 0, true); // End
779 filename.clear();
780 index = 0;
781 }
782 });
783
784 // Process data
785 std::unique_ptr<char[]> buffer(new char[MULTIPART_CHUNK_SIZE]);
786 size_t bytes_since_yield = 0;
787
788 for (size_t remaining = r->content_len; remaining > 0;) {
789 int recv_len = httpd_req_recv(r, buffer.get(), std::min(remaining, MULTIPART_CHUNK_SIZE));
790
791 if (recv_len <= 0) {
792 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
793 nullptr);
794 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
795 }
796
797 if (reader->parse(buffer.get(), recv_len) != static_cast<size_t>(recv_len)) {
798 ESP_LOGW(TAG, "Multipart parser error");
799 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
800 return ESP_FAIL;
801 }
802
803 remaining -= recv_len;
804 bytes_since_yield += recv_len;
805
806 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
807 vTaskDelay(1);
808 bytes_since_yield = 0;
809 }
810 }
811
812 handler->handleRequest(&req);
813 return ESP_OK;
814}
815#endif // USE_WEBSERVER_OTA
816
817} // namespace web_server_idf
818} // namespace esphome
819
820#endif // !defined(USE_ESP32)
uint8_t h
Definition bl0906.h:2
uint8_t status
Definition bl0942.h:8
void begin(bool include_internal=false)
Builder class for creating JSON documents without lambdas.
Definition json_util.h:62
value_type const & value() const
Definition optional.h:94
This class allows users to create a web server with their ESP nodes.
Definition web_server.h:173
std::string get_config_json()
Return the webserver configuration as JSON.
std::map< uint64_t, SortingGroup > sorting_groups_
Definition web_server.h:501
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)
std::unique_ptr< 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 std::string &name)
optional< std::string > get_header(const char *name) const
void send(AsyncWebServerResponse *response)
void init_response_(AsyncWebServerResponse *rsp, int code, const char *content_type)
void requestAuthentication(const char *realm=nullptr) 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)
const char * message
Definition component.cpp:38
uint16_t flags
mopeka_std_values val[4]
const char *const TAG
Definition spi.cpp:8
optional< std::string > request_get_url_query(httpd_req_t *req)
Definition utils.cpp:56
optional< std::string > request_get_header(httpd_req_t *req, const char *name)
Definition utils.cpp:39
bool parse_multipart_boundary(const char *content_type, const char **boundary_start, size_t *boundary_len)
std::string(esphome::web_server::WebServer *, void *) message_generator_t
optional< std::string > query_key_value(const std::string &query_url, const std::string &key)
Definition utils.cpp:74
const char * stristr(const char *haystack, const char *needle)
Definition utils.cpp:104
bool request_has_header(httpd_req_t *req, const char *name)
Definition utils.cpp:37
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
std::string size_t len
Definition helpers.h:486
std::string str_sprintf(const char *fmt,...)
Definition helpers.cpp:222
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:30
std::string print()
uint16_t length
Definition tt21100.cpp:0