ESPHome 2026.1.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
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->server_) {
122 this->end();
123 }
124 httpd_config_t config = HTTPD_DEFAULT_CONFIG();
125 config.server_port = this->port_;
126 config.uri_match_fn = [](const char * /*unused*/, const char * /*unused*/, size_t /*unused*/) { return true; };
127 // Always enable LRU purging to handle socket exhaustion gracefully.
128 // When max sockets is reached, the oldest connection is closed to make room for new ones.
129 // This prevents "httpd_accept_conn: error in accept (23)" errors.
130 // See: https://github.com/esphome/esphome/issues/12464
131 config.lru_purge_enable = true;
132 // Use custom close function that shuts down before closing to prevent lwIP race conditions
134 if (httpd_start(&this->server_, &config) == ESP_OK) {
135 const httpd_uri_t handler_get = {
136 .uri = "",
137 .method = HTTP_GET,
139 .user_ctx = this,
140 };
141 httpd_register_uri_handler(this->server_, &handler_get);
142
143 const httpd_uri_t handler_post = {
144 .uri = "",
145 .method = HTTP_POST,
147 .user_ctx = this,
148 };
149 httpd_register_uri_handler(this->server_, &handler_post);
150
151 const httpd_uri_t handler_options = {
152 .uri = "",
153 .method = HTTP_OPTIONS,
155 .user_ctx = this,
156 };
157 httpd_register_uri_handler(this->server_, &handler_options);
158 }
159}
160
161esp_err_t AsyncWebServer::request_post_handler(httpd_req_t *r) {
162 ESP_LOGVV(TAG, "Enter AsyncWebServer::request_post_handler. uri=%s", r->uri);
163 auto content_type = request_get_header(r, "Content-Type");
164
165 if (!request_has_header(r, "Content-Length")) {
166 ESP_LOGW(TAG, "Content length is required for post: %s", r->uri);
167 httpd_resp_send_err(r, HTTPD_411_LENGTH_REQUIRED, nullptr);
168 return ESP_OK;
169 }
170
171 if (content_type.has_value()) {
172 const char *content_type_char = content_type.value().c_str();
173
174 // Check most common case first
175 if (stristr(content_type_char, "application/x-www-form-urlencoded") != nullptr) {
176 // Normal form data - proceed with regular handling
177#ifdef USE_WEBSERVER_OTA
178 } else if (stristr(content_type_char, "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
249std::string AsyncWebServerRequest::url() const {
250 auto *str = strchr(this->req_->uri, '?');
251 if (str == nullptr) {
252 return this->req_->uri;
253 }
254 return std::string(this->req_->uri, str - this->req_->uri);
255}
256
257std::string AsyncWebServerRequest::host() const { return this->get_header("Host").value(); }
258
260 httpd_resp_send(*this, response->get_content_data(), response->get_content_size());
261}
262
263void AsyncWebServerRequest::send(int code, const char *content_type, const char *content) {
264 this->init_response_(nullptr, code, content_type);
265 if (content) {
266 httpd_resp_send(*this, content, HTTPD_RESP_USE_STRLEN);
267 } else {
268 httpd_resp_send(*this, nullptr, 0);
269 }
270}
271
272void AsyncWebServerRequest::redirect(const std::string &url) {
273 httpd_resp_set_status(*this, "302 Found");
274 httpd_resp_set_hdr(*this, "Location", url.c_str());
275 httpd_resp_set_hdr(*this, "Connection", "close");
276 httpd_resp_send(*this, nullptr, 0);
277}
278
279void AsyncWebServerRequest::init_response_(AsyncWebServerResponse *rsp, int code, const char *content_type) {
280 // Set status code - use constants for common codes, default to 500 for unknown codes
281 const char *status;
282 switch (code) {
283 case 200:
284 status = HTTPD_200;
285 break;
286 case 404:
287 status = HTTPD_404;
288 break;
289 case 409:
290 status = HTTPD_409;
291 break;
292 default:
293 status = HTTPD_500;
294 break;
295 }
296 httpd_resp_set_status(*this, status);
297
298 if (content_type && *content_type) {
299 httpd_resp_set_type(*this, content_type);
300 }
301 httpd_resp_set_hdr(*this, "Accept-Ranges", "none");
302
303 for (const auto &pair : DefaultHeaders::Instance().headers_) {
304 httpd_resp_set_hdr(*this, pair.first.c_str(), pair.second.c_str());
305 }
306
307 delete this->rsp_;
308 this->rsp_ = rsp;
309}
310
311#ifdef USE_WEBSERVER_AUTH
312bool AsyncWebServerRequest::authenticate(const char *username, const char *password) const {
313 if (username == nullptr || password == nullptr || *username == 0) {
314 return true;
315 }
316 auto auth = this->get_header("Authorization");
317 if (!auth.has_value()) {
318 return false;
319 }
320
321 auto *auth_str = auth.value().c_str();
322
323 const auto auth_prefix_len = sizeof("Basic ") - 1;
324 if (strncmp("Basic ", auth_str, auth_prefix_len) != 0) {
325 ESP_LOGW(TAG, "Only Basic authorization supported yet");
326 return false;
327 }
328
329 std::string user_info;
330 user_info += username;
331 user_info += ':';
332 user_info += password;
333
334 size_t n = 0, out;
335 esp_crypto_base64_encode(nullptr, 0, &n, reinterpret_cast<const uint8_t *>(user_info.c_str()), user_info.size());
336
337 auto digest = std::unique_ptr<char[]>(new char[n + 1]);
338 esp_crypto_base64_encode(reinterpret_cast<uint8_t *>(digest.get()), n, &out,
339 reinterpret_cast<const uint8_t *>(user_info.c_str()), user_info.size());
340
341 return strcmp(digest.get(), auth_str + auth_prefix_len) == 0;
342}
343
344void AsyncWebServerRequest::requestAuthentication(const char *realm) const {
345 httpd_resp_set_hdr(*this, "Connection", "keep-alive");
346 // Note: realm is never configured in ESPHome, always nullptr -> "Login Required"
347 (void) realm; // Unused - always use default
348 httpd_resp_set_hdr(*this, "WWW-Authenticate", "Basic realm=\"Login Required\"");
349 httpd_resp_send_err(*this, HTTPD_401_UNAUTHORIZED, nullptr);
350}
351#endif
352
354 // Check cache first - only successful lookups are cached
355 for (auto *param : this->params_) {
356 if (param->name() == name) {
357 return param;
358 }
359 }
360
361 // Look up value from query strings
363 if (!val.has_value()) {
364 auto url_query = request_get_url_query(*this);
365 if (url_query.has_value()) {
366 val = query_key_value(url_query.value(), name);
367 }
368 }
369
370 // Don't cache misses to avoid wasting memory when handlers check for
371 // optional parameters that don't exist in the request
372 if (!val.has_value()) {
373 return nullptr;
374 }
375
376 auto *param = new AsyncWebParameter(name, val.value()); // NOLINT(cppcoreguidelines-owning-memory)
377 this->params_.push_back(param);
378 return param;
379}
380
381void AsyncWebServerResponse::addHeader(const char *name, const char *value) {
382 httpd_resp_set_hdr(*this->req_, name, value);
383}
384
385void AsyncResponseStream::print(float value) {
386 // Use stack buffer to avoid temporary string allocation
387 // Size: sign (1) + digits (10) + decimal (1) + precision (6) + exponent (5) + null (1) = 24, use 32 for safety
388 char buf[32];
389 int len = snprintf(buf, sizeof(buf), "%f", value);
390 this->content_.append(buf, len);
391}
392
393void AsyncResponseStream::printf(const char *fmt, ...) {
394 va_list args;
395
396 va_start(args, fmt);
397 const int length = vsnprintf(nullptr, 0, fmt, args);
398 va_end(args);
399
400 std::string str;
401 str.resize(length);
402
403 va_start(args, fmt);
404 vsnprintf(&str[0], length + 1, fmt, args);
405 va_end(args);
406
407 this->print(str);
408}
409
410#ifdef USE_WEBSERVER
412 for (auto *ses : this->sessions_) {
413 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
414 }
415}
416
418 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory,clang-analyzer-cplusplus.NewDeleteLeaks)
419 auto *rsp = new AsyncEventSourceResponse(request, this, this->web_server_);
420 if (this->on_connect_) {
421 this->on_connect_(rsp);
422 }
423 this->sessions_.push_back(rsp);
424}
425
427 // Clean up dead sessions safely
428 // This follows the ESP-IDF pattern where free_ctx marks resources as dead
429 // and the main loop handles the actual cleanup to avoid race conditions
430 for (size_t i = 0; i < this->sessions_.size();) {
431 auto *ses = this->sessions_[i];
432 // If the session has a dead socket (marked by destroy callback)
433 if (ses->fd_.load() == 0) {
434 ESP_LOGD(TAG, "Removing dead event source session");
435 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
436 // Remove by swapping with last element (O(1) removal, order doesn't matter for sessions)
437 this->sessions_[i] = this->sessions_.back();
438 this->sessions_.pop_back();
439 } else {
440 ses->loop();
441 ++i;
442 }
443 }
444}
445
446void AsyncEventSource::try_send_nodefer(const char *message, const char *event, uint32_t id, uint32_t reconnect) {
447 for (auto *ses : this->sessions_) {
448 if (ses->fd_.load() != 0) { // Skip dead sessions
449 ses->try_send_nodefer(message, event, id, reconnect);
450 }
451 }
452}
453
454void AsyncEventSource::deferrable_send_state(void *source, const char *event_type,
455 message_generator_t *message_generator) {
456 // Skip if no connected clients to avoid unnecessary processing
457 if (this->empty())
458 return;
459 for (auto *ses : this->sessions_) {
460 if (ses->fd_.load() != 0) { // Skip dead sessions
461 ses->deferrable_send_state(source, event_type, message_generator);
462 }
463 }
464}
465
469 : server_(server), web_server_(ws), entities_iterator_(new esphome::web_server::ListEntitiesIterator(ws, server)) {
470 httpd_req_t *req = *request;
471
472 httpd_resp_set_status(req, HTTPD_200);
473 httpd_resp_set_type(req, "text/event-stream");
474 httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
475 httpd_resp_set_hdr(req, "Connection", "keep-alive");
476
477 for (const auto &pair : DefaultHeaders::Instance().headers_) {
478 httpd_resp_set_hdr(req, pair.first.c_str(), pair.second.c_str());
479 }
480
481 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
482
483 req->sess_ctx = this;
484 req->free_ctx = AsyncEventSourceResponse::destroy;
485
486 this->hd_ = req->handle;
487 this->fd_.store(httpd_req_to_sockfd(req));
488
489 // Use non-blocking send to prevent watchdog timeouts when TCP buffers are full
490 httpd_sess_set_send_override(this->hd_, this->fd_.load(), nonblocking_send);
491
492 // Configure reconnect timeout and send config
493 // this should always go through since the tcp send buffer is empty on connect
494 std::string message = ws->get_config_json();
495 this->try_send_nodefer(message.c_str(), "ping", millis(), 30000);
496
497#ifdef USE_WEBSERVER_SORTING
498 for (auto &group : ws->sorting_groups_) {
499 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
500 json::JsonBuilder builder;
501 JsonObject root = builder.root();
502 root["name"] = group.second.name;
503 root["sorting_weight"] = group.second.weight;
504 message = builder.serialize();
505 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
506
507 // a (very) large number of these should be able to be queued initially without defer
508 // since the only thing in the send buffer at this point is the initial ping/config
509 this->try_send_nodefer(message.c_str(), "sorting_group");
510 }
511#endif
512
514
515 // just dump them all up-front and take advantage of the deferred queue
516 // on second thought that takes too long, but leaving the commented code here for debug purposes
517 // while(!this->entities_iterator_->completed()) {
518 // this->entities_iterator_->advance();
519 //}
520}
521
523 auto *rsp = static_cast<AsyncEventSourceResponse *>(ptr);
524 int fd = rsp->fd_.exchange(0); // Atomically get and clear fd
525 ESP_LOGD(TAG, "Event source connection closed (fd: %d)", fd);
526 // Mark as dead - will be cleaned up in the main loop
527 // Note: We don't delete or remove from set here to avoid race conditions
528 // httpd will call our custom close_fn (safe_close_with_shutdown) which handles
529 // shutdown() before close() to prevent lwIP race conditions
530}
531
532// helper for allowing only unique entries in the queue
534 DeferredEvent item(source, message_generator);
535
536 // Use range-based for loop instead of std::find_if to reduce template instantiation overhead and binary size
537 for (auto &event : this->deferred_queue_) {
538 if (event == item) {
539 return; // Already in queue, no need to update since items are equal
540 }
541 }
542 this->deferred_queue_.push_back(item);
543}
544
546 while (!deferred_queue_.empty()) {
547 DeferredEvent &de = deferred_queue_.front();
548 std::string message = de.message_generator_(web_server_, de.source_);
549 if (this->try_send_nodefer(message.c_str(), "state")) {
550 // O(n) but memory efficiency is more important than speed here which is why std::vector was chosen
551 deferred_queue_.erase(deferred_queue_.begin());
552 } else {
553 break;
554 }
555 }
556}
557
559 if (event_buffer_.empty()) {
560 return;
561 }
562 if (event_bytes_sent_ == event_buffer_.size()) {
563 event_buffer_.resize(0);
565 return;
566 }
567
568 size_t remaining = event_buffer_.size() - event_bytes_sent_;
569 int bytes_sent =
570 httpd_socket_send(this->hd_, this->fd_.load(), event_buffer_.c_str() + event_bytes_sent_, remaining, 0);
571 if (bytes_sent == HTTPD_SOCK_ERR_TIMEOUT) {
572 // EAGAIN/EWOULDBLOCK - socket buffer full, try again later
573 // NOTE: Similar logic exists in web_server/web_server.cpp in DeferredUpdateEventSource::process_deferred_queue_()
574 // The implementations differ due to platform-specific APIs (HTTPD_SOCK_ERR_TIMEOUT vs DISCARDED, fd_.store(0) vs
575 // close()), but the failure counting and timeout logic should be kept in sync. If you change this logic, also
576 // update the Arduino implementation.
579 // Too many failures, connection is likely dead
580 ESP_LOGW(TAG, "Closing stuck EventSource connection after %" PRIu16 " failed sends",
582 this->fd_.store(0); // Mark for cleanup
583 this->deferred_queue_.clear();
584 }
585 return;
586 }
587 if (bytes_sent == HTTPD_SOCK_ERR_FAIL) {
588 // Real socket error - connection will be closed by httpd and destroy callback will be called
589 return;
590 }
591 if (bytes_sent <= 0) {
592 // Unexpected error or zero bytes sent
593 ESP_LOGW(TAG, "Unexpected send result: %d", bytes_sent);
594 return;
595 }
596
597 // Successful send - reset failure counter
599 event_bytes_sent_ += bytes_sent;
600
601 // Log partial sends for debugging
602 if (event_bytes_sent_ < event_buffer_.size()) {
603 ESP_LOGV(TAG, "Partial send: %d/%zu bytes (total: %zu/%zu)", bytes_sent, remaining, event_bytes_sent_,
604 event_buffer_.size());
605 }
606
607 if (event_bytes_sent_ == event_buffer_.size()) {
608 event_buffer_.resize(0);
610 }
611}
612
619
620bool AsyncEventSourceResponse::try_send_nodefer(const char *message, const char *event, uint32_t id,
621 uint32_t reconnect) {
622 if (this->fd_.load() == 0) {
623 return false;
624 }
625
627 if (!event_buffer_.empty()) {
628 // there is still pending event data to send first
629 return false;
630 }
631
632 // 8 spaces are standing in for the hexidecimal chunk length to print later
633 const char chunk_len_header[] = " " CRLF_STR;
634 const int chunk_len_header_len = sizeof(chunk_len_header) - 1;
635
636 event_buffer_.append(chunk_len_header);
637
638 // Use stack buffer for formatting numeric fields to avoid temporary string allocations
639 // Size: "retry: " (7) + max uint32 (10 digits) + CRLF (2) + null (1) = 20 bytes, use 32 for safety
640 constexpr size_t num_buf_size = 32;
641 char num_buf[num_buf_size];
642
643 if (reconnect) {
644 int len = snprintf(num_buf, num_buf_size, "retry: %" PRIu32 CRLF_STR, reconnect);
645 event_buffer_.append(num_buf, len);
646 }
647
648 if (id) {
649 int len = snprintf(num_buf, num_buf_size, "id: %" PRIu32 CRLF_STR, id);
650 event_buffer_.append(num_buf, len);
651 }
652
653 if (event && *event) {
654 event_buffer_.append("event: ", sizeof("event: ") - 1);
655 event_buffer_.append(event);
656 event_buffer_.append(CRLF_STR, CRLF_LEN);
657 }
658
659 // Match ESPAsyncWebServer: null message means no data lines and no terminating blank line
660 if (message) {
661 // SSE spec requires each line of a multi-line message to have its own "data:" prefix
662 // Handle \n, \r, and \r\n line endings (matching ESPAsyncWebServer behavior)
663
664 // Fast path: check if message contains any newlines at all
665 // Most SSE messages (JSON state updates) have no newlines
666 const char *first_n = strchr(message, '\n');
667 const char *first_r = strchr(message, '\r');
668
669 if (first_n == nullptr && first_r == nullptr) {
670 // No newlines - fast path (most common case)
671 event_buffer_.append("data: ", sizeof("data: ") - 1);
672 event_buffer_.append(message);
673 event_buffer_.append(CRLF_STR CRLF_STR, CRLF_LEN * 2); // data line + blank line terminator
674 } else {
675 // Has newlines - handle multi-line message
676 const char *line_start = message;
677 size_t msg_len = strlen(message);
678 const char *msg_end = message + msg_len;
679
680 // Reuse the first search results
681 const char *next_n = first_n;
682 const char *next_r = first_r;
683
684 while (line_start <= msg_end) {
685 const char *line_end;
686 const char *next_line;
687
688 if (next_n == nullptr && next_r == nullptr) {
689 // No more line breaks - output remaining text as final line
690 event_buffer_.append("data: ", sizeof("data: ") - 1);
691 event_buffer_.append(line_start);
692 event_buffer_.append(CRLF_STR, CRLF_LEN);
693 break;
694 }
695
696 // Determine line ending type and next line start
697 if (next_n != nullptr && next_r != nullptr) {
698 if (next_r + 1 == next_n) {
699 // \r\n sequence
700 line_end = next_r;
701 next_line = next_n + 1;
702 } else {
703 // Mixed \n and \r - use whichever comes first
704 line_end = (next_r < next_n) ? next_r : next_n;
705 next_line = line_end + 1;
706 }
707 } else if (next_n != nullptr) {
708 // Unix LF
709 line_end = next_n;
710 next_line = next_n + 1;
711 } else {
712 // Old Mac CR
713 line_end = next_r;
714 next_line = next_r + 1;
715 }
716
717 // Output this line
718 event_buffer_.append("data: ", sizeof("data: ") - 1);
719 event_buffer_.append(line_start, line_end - line_start);
720 event_buffer_.append(CRLF_STR, CRLF_LEN);
721
722 line_start = next_line;
723
724 // Check if we've consumed all content
725 if (line_start >= msg_end) {
726 break;
727 }
728
729 // Search for next newlines only in remaining string
730 next_n = strchr(line_start, '\n');
731 next_r = strchr(line_start, '\r');
732 }
733
734 // Terminate message with blank line
735 event_buffer_.append(CRLF_STR, CRLF_LEN);
736 }
737 }
738
739 if (event_buffer_.size() == static_cast<size_t>(chunk_len_header_len)) {
740 // Nothing was added, reset buffer
741 event_buffer_.resize(0);
742 return true;
743 }
744
745 event_buffer_.append(CRLF_STR, CRLF_LEN);
746
747 // chunk length header itself and the final chunk terminating CRLF are not counted as part of the chunk
748 int chunk_len = event_buffer_.size() - CRLF_LEN - chunk_len_header_len;
749 char chunk_len_str[9];
750 snprintf(chunk_len_str, 9, "%08x", chunk_len);
751 std::memcpy(&event_buffer_[0], chunk_len_str, 8);
752
755
756 return true;
757}
758
759void AsyncEventSourceResponse::deferrable_send_state(void *source, const char *event_type,
760 message_generator_t *message_generator) {
761 // allow all json "details_all" to go through before publishing bare state events, this avoids unnamed entries showing
762 // up in the web GUI and reduces event load during initial connect
763 if (!entities_iterator_->completed() && 0 != strcmp(event_type, "state_detail_all"))
764 return;
765
766 if (source == nullptr)
767 return;
768 if (event_type == nullptr)
769 return;
770 if (message_generator == nullptr)
771 return;
772
773 if (0 != strcmp(event_type, "state_detail_all") && 0 != strcmp(event_type, "state")) {
774 ESP_LOGE(TAG, "Can't defer non-state event");
775 }
776
779
780 if (!event_buffer_.empty() || !deferred_queue_.empty()) {
781 // outgoing event buffer or deferred queue still not empty which means downstream tcp send buffer full, no point
782 // trying to send first
783 deq_push_back_with_dedup_(source, message_generator);
784 } else {
785 std::string message = message_generator(web_server_, source);
786 if (!this->try_send_nodefer(message.c_str(), "state")) {
787 deq_push_back_with_dedup_(source, message_generator);
788 }
789 }
790}
791#endif
792
793#ifdef USE_WEBSERVER_OTA
794esp_err_t AsyncWebServer::handle_multipart_upload_(httpd_req_t *r, const char *content_type) {
795 static constexpr size_t MULTIPART_CHUNK_SIZE = 1460; // Match Arduino AsyncWebServer buffer size
796 static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024; // Yield every 16KB to prevent watchdog
797
798 // Parse boundary and create reader
799 const char *boundary_start;
800 size_t boundary_len;
801 if (!parse_multipart_boundary(content_type, &boundary_start, &boundary_len)) {
802 ESP_LOGE(TAG, "Failed to parse multipart boundary");
803 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
804 return ESP_FAIL;
805 }
806
808 AsyncWebHandler *handler = nullptr;
809 for (auto *h : this->handlers_) {
810 if (h->canHandle(&req)) {
811 handler = h;
812 break;
813 }
814 }
815
816 if (!handler) {
817 ESP_LOGW(TAG, "No handler found for OTA request");
818 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, nullptr);
819 return ESP_OK;
820 }
821
822 // Upload state
823 std::string filename;
824 size_t index = 0;
825 // Create reader on heap to reduce stack usage
826 auto reader = std::make_unique<MultipartReader>("--" + std::string(boundary_start, boundary_len));
827
828 // Configure callbacks
829 reader->set_data_callback([&](const uint8_t *data, size_t len) {
830 if (!reader->has_file() || !len)
831 return;
832
833 if (filename.empty()) {
834 filename = reader->get_current_part().filename;
835 ESP_LOGV(TAG, "Processing file: '%s'", filename.c_str());
836 handler->handleUpload(&req, filename, 0, nullptr, 0, false); // Start
837 }
838
839 handler->handleUpload(&req, filename, index, const_cast<uint8_t *>(data), len, false);
840 index += len;
841 });
842
843 reader->set_part_complete_callback([&]() {
844 if (index > 0) {
845 handler->handleUpload(&req, filename, index, nullptr, 0, true); // End
846 filename.clear();
847 index = 0;
848 }
849 });
850
851 // Process data
852 std::unique_ptr<char[]> buffer(new char[MULTIPART_CHUNK_SIZE]);
853 size_t bytes_since_yield = 0;
854
855 for (size_t remaining = r->content_len; remaining > 0;) {
856 int recv_len = httpd_req_recv(r, buffer.get(), std::min(remaining, MULTIPART_CHUNK_SIZE));
857
858 if (recv_len <= 0) {
859 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
860 nullptr);
861 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
862 }
863
864 if (reader->parse(buffer.get(), recv_len) != static_cast<size_t>(recv_len)) {
865 ESP_LOGW(TAG, "Multipart parser error");
866 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
867 return ESP_FAIL;
868 }
869
870 remaining -= recv_len;
871 bytes_since_yield += recv_len;
872
873 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
874 vTaskDelay(1);
875 bytes_since_yield = 0;
876 }
877 }
878
879 handler->handleRequest(&req);
880 return ESP_OK;
881}
882#endif // USE_WEBSERVER_OTA
883
884} // namespace web_server_idf
885} // namespace esphome
886
887#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:178
std::string get_config_json()
Return the webserver configuration as JSON.
std::map< uint64_t, SortingGroup > sorting_groups_
Definition web_server.h:468
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:7
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:533
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:25
std::string print()
uint16_t length
Definition tt21100.cpp:0