ESPHome 2025.12.3
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 auto auth_val = str_sprintf("Basic realm=\"%s\"", realm ? realm : "Login Required");
347 httpd_resp_set_hdr(*this, "WWW-Authenticate", auth_val.c_str());
348 httpd_resp_send_err(*this, HTTPD_401_UNAUTHORIZED, nullptr);
349}
350#endif
351
353 // Check cache first - only successful lookups are cached
354 for (auto *param : this->params_) {
355 if (param->name() == name) {
356 return param;
357 }
358 }
359
360 // Look up value from query strings
362 if (!val.has_value()) {
363 auto url_query = request_get_url_query(*this);
364 if (url_query.has_value()) {
365 val = query_key_value(url_query.value(), name);
366 }
367 }
368
369 // Don't cache misses to avoid wasting memory when handlers check for
370 // optional parameters that don't exist in the request
371 if (!val.has_value()) {
372 return nullptr;
373 }
374
375 auto *param = new AsyncWebParameter(name, val.value()); // NOLINT(cppcoreguidelines-owning-memory)
376 this->params_.push_back(param);
377 return param;
378}
379
380void AsyncWebServerResponse::addHeader(const char *name, const char *value) {
381 httpd_resp_set_hdr(*this->req_, name, value);
382}
383
384void AsyncResponseStream::print(float value) {
385 // Use stack buffer to avoid temporary string allocation
386 // Size: sign (1) + digits (10) + decimal (1) + precision (6) + exponent (5) + null (1) = 24, use 32 for safety
387 char buf[32];
388 int len = snprintf(buf, sizeof(buf), "%f", value);
389 this->content_.append(buf, len);
390}
391
392void AsyncResponseStream::printf(const char *fmt, ...) {
393 va_list args;
394
395 va_start(args, fmt);
396 const int length = vsnprintf(nullptr, 0, fmt, args);
397 va_end(args);
398
399 std::string str;
400 str.resize(length);
401
402 va_start(args, fmt);
403 vsnprintf(&str[0], length + 1, fmt, args);
404 va_end(args);
405
406 this->print(str);
407}
408
409#ifdef USE_WEBSERVER
411 for (auto *ses : this->sessions_) {
412 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
413 }
414}
415
417 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory,clang-analyzer-cplusplus.NewDeleteLeaks)
418 auto *rsp = new AsyncEventSourceResponse(request, this, this->web_server_);
419 if (this->on_connect_) {
420 this->on_connect_(rsp);
421 }
422 this->sessions_.push_back(rsp);
423}
424
426 // Clean up dead sessions safely
427 // This follows the ESP-IDF pattern where free_ctx marks resources as dead
428 // and the main loop handles the actual cleanup to avoid race conditions
429 for (size_t i = 0; i < this->sessions_.size();) {
430 auto *ses = this->sessions_[i];
431 // If the session has a dead socket (marked by destroy callback)
432 if (ses->fd_.load() == 0) {
433 ESP_LOGD(TAG, "Removing dead event source session");
434 delete ses; // NOLINT(cppcoreguidelines-owning-memory)
435 // Remove by swapping with last element (O(1) removal, order doesn't matter for sessions)
436 this->sessions_[i] = this->sessions_.back();
437 this->sessions_.pop_back();
438 } else {
439 ses->loop();
440 ++i;
441 }
442 }
443}
444
445void AsyncEventSource::try_send_nodefer(const char *message, const char *event, uint32_t id, uint32_t reconnect) {
446 for (auto *ses : this->sessions_) {
447 if (ses->fd_.load() != 0) { // Skip dead sessions
448 ses->try_send_nodefer(message, event, id, reconnect);
449 }
450 }
451}
452
453void AsyncEventSource::deferrable_send_state(void *source, const char *event_type,
454 message_generator_t *message_generator) {
455 // Skip if no connected clients to avoid unnecessary processing
456 if (this->empty())
457 return;
458 for (auto *ses : this->sessions_) {
459 if (ses->fd_.load() != 0) { // Skip dead sessions
460 ses->deferrable_send_state(source, event_type, message_generator);
461 }
462 }
463}
464
468 : server_(server), web_server_(ws), entities_iterator_(new esphome::web_server::ListEntitiesIterator(ws, server)) {
469 httpd_req_t *req = *request;
470
471 httpd_resp_set_status(req, HTTPD_200);
472 httpd_resp_set_type(req, "text/event-stream");
473 httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
474 httpd_resp_set_hdr(req, "Connection", "keep-alive");
475
476 for (const auto &pair : DefaultHeaders::Instance().headers_) {
477 httpd_resp_set_hdr(req, pair.first.c_str(), pair.second.c_str());
478 }
479
480 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
481
482 req->sess_ctx = this;
483 req->free_ctx = AsyncEventSourceResponse::destroy;
484
485 this->hd_ = req->handle;
486 this->fd_.store(httpd_req_to_sockfd(req));
487
488 // Use non-blocking send to prevent watchdog timeouts when TCP buffers are full
489 httpd_sess_set_send_override(this->hd_, this->fd_.load(), nonblocking_send);
490
491 // Configure reconnect timeout and send config
492 // this should always go through since the tcp send buffer is empty on connect
493 std::string message = ws->get_config_json();
494 this->try_send_nodefer(message.c_str(), "ping", millis(), 30000);
495
496#ifdef USE_WEBSERVER_SORTING
497 for (auto &group : ws->sorting_groups_) {
498 // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks) false positive with ArduinoJson
499 json::JsonBuilder builder;
500 JsonObject root = builder.root();
501 root["name"] = group.second.name;
502 root["sorting_weight"] = group.second.weight;
503 message = builder.serialize();
504 // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks)
505
506 // a (very) large number of these should be able to be queued initially without defer
507 // since the only thing in the send buffer at this point is the initial ping/config
508 this->try_send_nodefer(message.c_str(), "sorting_group");
509 }
510#endif
511
513
514 // just dump them all up-front and take advantage of the deferred queue
515 // on second thought that takes too long, but leaving the commented code here for debug purposes
516 // while(!this->entities_iterator_->completed()) {
517 // this->entities_iterator_->advance();
518 //}
519}
520
522 auto *rsp = static_cast<AsyncEventSourceResponse *>(ptr);
523 int fd = rsp->fd_.exchange(0); // Atomically get and clear fd
524 ESP_LOGD(TAG, "Event source connection closed (fd: %d)", fd);
525 // Mark as dead - will be cleaned up in the main loop
526 // Note: We don't delete or remove from set here to avoid race conditions
527 // httpd will call our custom close_fn (safe_close_with_shutdown) which handles
528 // shutdown() before close() to prevent lwIP race conditions
529}
530
531// helper for allowing only unique entries in the queue
533 DeferredEvent item(source, message_generator);
534
535 // Use range-based for loop instead of std::find_if to reduce template instantiation overhead and binary size
536 for (auto &event : this->deferred_queue_) {
537 if (event == item) {
538 return; // Already in queue, no need to update since items are equal
539 }
540 }
541 this->deferred_queue_.push_back(item);
542}
543
545 while (!deferred_queue_.empty()) {
546 DeferredEvent &de = deferred_queue_.front();
547 std::string message = de.message_generator_(web_server_, de.source_);
548 if (this->try_send_nodefer(message.c_str(), "state")) {
549 // O(n) but memory efficiency is more important than speed here which is why std::vector was chosen
550 deferred_queue_.erase(deferred_queue_.begin());
551 } else {
552 break;
553 }
554 }
555}
556
558 if (event_buffer_.empty()) {
559 return;
560 }
561 if (event_bytes_sent_ == event_buffer_.size()) {
562 event_buffer_.resize(0);
564 return;
565 }
566
567 size_t remaining = event_buffer_.size() - event_bytes_sent_;
568 int bytes_sent =
569 httpd_socket_send(this->hd_, this->fd_.load(), event_buffer_.c_str() + event_bytes_sent_, remaining, 0);
570 if (bytes_sent == HTTPD_SOCK_ERR_TIMEOUT) {
571 // EAGAIN/EWOULDBLOCK - socket buffer full, try again later
572 // NOTE: Similar logic exists in web_server/web_server.cpp in DeferredUpdateEventSource::process_deferred_queue_()
573 // The implementations differ due to platform-specific APIs (HTTPD_SOCK_ERR_TIMEOUT vs DISCARDED, fd_.store(0) vs
574 // close()), but the failure counting and timeout logic should be kept in sync. If you change this logic, also
575 // update the Arduino implementation.
578 // Too many failures, connection is likely dead
579 ESP_LOGW(TAG, "Closing stuck EventSource connection after %" PRIu16 " failed sends",
581 this->fd_.store(0); // Mark for cleanup
582 this->deferred_queue_.clear();
583 }
584 return;
585 }
586 if (bytes_sent == HTTPD_SOCK_ERR_FAIL) {
587 // Real socket error - connection will be closed by httpd and destroy callback will be called
588 return;
589 }
590 if (bytes_sent <= 0) {
591 // Unexpected error or zero bytes sent
592 ESP_LOGW(TAG, "Unexpected send result: %d", bytes_sent);
593 return;
594 }
595
596 // Successful send - reset failure counter
598 event_bytes_sent_ += bytes_sent;
599
600 // Log partial sends for debugging
601 if (event_bytes_sent_ < event_buffer_.size()) {
602 ESP_LOGV(TAG, "Partial send: %d/%zu bytes (total: %zu/%zu)", bytes_sent, remaining, event_bytes_sent_,
603 event_buffer_.size());
604 }
605
606 if (event_bytes_sent_ == event_buffer_.size()) {
607 event_buffer_.resize(0);
609 }
610}
611
618
619bool AsyncEventSourceResponse::try_send_nodefer(const char *message, const char *event, uint32_t id,
620 uint32_t reconnect) {
621 if (this->fd_.load() == 0) {
622 return false;
623 }
624
626 if (!event_buffer_.empty()) {
627 // there is still pending event data to send first
628 return false;
629 }
630
631 // 8 spaces are standing in for the hexidecimal chunk length to print later
632 const char chunk_len_header[] = " " CRLF_STR;
633 const int chunk_len_header_len = sizeof(chunk_len_header) - 1;
634
635 event_buffer_.append(chunk_len_header);
636
637 // Use stack buffer for formatting numeric fields to avoid temporary string allocations
638 // Size: "retry: " (7) + max uint32 (10 digits) + CRLF (2) + null (1) = 20 bytes, use 32 for safety
639 constexpr size_t num_buf_size = 32;
640 char num_buf[num_buf_size];
641
642 if (reconnect) {
643 int len = snprintf(num_buf, num_buf_size, "retry: %" PRIu32 CRLF_STR, reconnect);
644 event_buffer_.append(num_buf, len);
645 }
646
647 if (id) {
648 int len = snprintf(num_buf, num_buf_size, "id: %" PRIu32 CRLF_STR, id);
649 event_buffer_.append(num_buf, len);
650 }
651
652 if (event && *event) {
653 event_buffer_.append("event: ", sizeof("event: ") - 1);
654 event_buffer_.append(event);
655 event_buffer_.append(CRLF_STR, CRLF_LEN);
656 }
657
658 // Match ESPAsyncWebServer: null message means no data lines and no terminating blank line
659 if (message) {
660 // SSE spec requires each line of a multi-line message to have its own "data:" prefix
661 // Handle \n, \r, and \r\n line endings (matching ESPAsyncWebServer behavior)
662
663 // Fast path: check if message contains any newlines at all
664 // Most SSE messages (JSON state updates) have no newlines
665 const char *first_n = strchr(message, '\n');
666 const char *first_r = strchr(message, '\r');
667
668 if (first_n == nullptr && first_r == nullptr) {
669 // No newlines - fast path (most common case)
670 event_buffer_.append("data: ", sizeof("data: ") - 1);
671 event_buffer_.append(message);
672 event_buffer_.append(CRLF_STR CRLF_STR, CRLF_LEN * 2); // data line + blank line terminator
673 } else {
674 // Has newlines - handle multi-line message
675 const char *line_start = message;
676 size_t msg_len = strlen(message);
677 const char *msg_end = message + msg_len;
678
679 // Reuse the first search results
680 const char *next_n = first_n;
681 const char *next_r = first_r;
682
683 while (line_start <= msg_end) {
684 const char *line_end;
685 const char *next_line;
686
687 if (next_n == nullptr && next_r == nullptr) {
688 // No more line breaks - output remaining text as final line
689 event_buffer_.append("data: ", sizeof("data: ") - 1);
690 event_buffer_.append(line_start);
691 event_buffer_.append(CRLF_STR, CRLF_LEN);
692 break;
693 }
694
695 // Determine line ending type and next line start
696 if (next_n != nullptr && next_r != nullptr) {
697 if (next_r + 1 == next_n) {
698 // \r\n sequence
699 line_end = next_r;
700 next_line = next_n + 1;
701 } else {
702 // Mixed \n and \r - use whichever comes first
703 line_end = (next_r < next_n) ? next_r : next_n;
704 next_line = line_end + 1;
705 }
706 } else if (next_n != nullptr) {
707 // Unix LF
708 line_end = next_n;
709 next_line = next_n + 1;
710 } else {
711 // Old Mac CR
712 line_end = next_r;
713 next_line = next_r + 1;
714 }
715
716 // Output this line
717 event_buffer_.append("data: ", sizeof("data: ") - 1);
718 event_buffer_.append(line_start, line_end - line_start);
719 event_buffer_.append(CRLF_STR, CRLF_LEN);
720
721 line_start = next_line;
722
723 // Check if we've consumed all content
724 if (line_start >= msg_end) {
725 break;
726 }
727
728 // Search for next newlines only in remaining string
729 next_n = strchr(line_start, '\n');
730 next_r = strchr(line_start, '\r');
731 }
732
733 // Terminate message with blank line
734 event_buffer_.append(CRLF_STR, CRLF_LEN);
735 }
736 }
737
738 if (event_buffer_.size() == static_cast<size_t>(chunk_len_header_len)) {
739 // Nothing was added, reset buffer
740 event_buffer_.resize(0);
741 return true;
742 }
743
744 event_buffer_.append(CRLF_STR, CRLF_LEN);
745
746 // chunk length header itself and the final chunk terminating CRLF are not counted as part of the chunk
747 int chunk_len = event_buffer_.size() - CRLF_LEN - chunk_len_header_len;
748 char chunk_len_str[9];
749 snprintf(chunk_len_str, 9, "%08x", chunk_len);
750 std::memcpy(&event_buffer_[0], chunk_len_str, 8);
751
754
755 return true;
756}
757
758void AsyncEventSourceResponse::deferrable_send_state(void *source, const char *event_type,
759 message_generator_t *message_generator) {
760 // allow all json "details_all" to go through before publishing bare state events, this avoids unnamed entries showing
761 // up in the web GUI and reduces event load during initial connect
762 if (!entities_iterator_->completed() && 0 != strcmp(event_type, "state_detail_all"))
763 return;
764
765 if (source == nullptr)
766 return;
767 if (event_type == nullptr)
768 return;
769 if (message_generator == nullptr)
770 return;
771
772 if (0 != strcmp(event_type, "state_detail_all") && 0 != strcmp(event_type, "state")) {
773 ESP_LOGE(TAG, "Can't defer non-state event");
774 }
775
778
779 if (!event_buffer_.empty() || !deferred_queue_.empty()) {
780 // outgoing event buffer or deferred queue still not empty which means downstream tcp send buffer full, no point
781 // trying to send first
782 deq_push_back_with_dedup_(source, message_generator);
783 } else {
784 std::string message = message_generator(web_server_, source);
785 if (!this->try_send_nodefer(message.c_str(), "state")) {
786 deq_push_back_with_dedup_(source, message_generator);
787 }
788 }
789}
790#endif
791
792#ifdef USE_WEBSERVER_OTA
793esp_err_t AsyncWebServer::handle_multipart_upload_(httpd_req_t *r, const char *content_type) {
794 static constexpr size_t MULTIPART_CHUNK_SIZE = 1460; // Match Arduino AsyncWebServer buffer size
795 static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024; // Yield every 16KB to prevent watchdog
796
797 // Parse boundary and create reader
798 const char *boundary_start;
799 size_t boundary_len;
800 if (!parse_multipart_boundary(content_type, &boundary_start, &boundary_len)) {
801 ESP_LOGE(TAG, "Failed to parse multipart boundary");
802 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
803 return ESP_FAIL;
804 }
805
807 AsyncWebHandler *handler = nullptr;
808 for (auto *h : this->handlers_) {
809 if (h->canHandle(&req)) {
810 handler = h;
811 break;
812 }
813 }
814
815 if (!handler) {
816 ESP_LOGW(TAG, "No handler found for OTA request");
817 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, nullptr);
818 return ESP_OK;
819 }
820
821 // Upload state
822 std::string filename;
823 size_t index = 0;
824 // Create reader on heap to reduce stack usage
825 auto reader = std::make_unique<MultipartReader>("--" + std::string(boundary_start, boundary_len));
826
827 // Configure callbacks
828 reader->set_data_callback([&](const uint8_t *data, size_t len) {
829 if (!reader->has_file() || !len)
830 return;
831
832 if (filename.empty()) {
833 filename = reader->get_current_part().filename;
834 ESP_LOGV(TAG, "Processing file: '%s'", filename.c_str());
835 handler->handleUpload(&req, filename, 0, nullptr, 0, false); // Start
836 }
837
838 handler->handleUpload(&req, filename, index, const_cast<uint8_t *>(data), len, false);
839 index += len;
840 });
841
842 reader->set_part_complete_callback([&]() {
843 if (index > 0) {
844 handler->handleUpload(&req, filename, index, nullptr, 0, true); // End
845 filename.clear();
846 index = 0;
847 }
848 });
849
850 // Process data
851 std::unique_ptr<char[]> buffer(new char[MULTIPART_CHUNK_SIZE]);
852 size_t bytes_since_yield = 0;
853
854 for (size_t remaining = r->content_len; remaining > 0;) {
855 int recv_len = httpd_req_recv(r, buffer.get(), std::min(remaining, MULTIPART_CHUNK_SIZE));
856
857 if (recv_len <= 0) {
858 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
859 nullptr);
860 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
861 }
862
863 if (reader->parse(buffer.get(), recv_len) != static_cast<size_t>(recv_len)) {
864 ESP_LOGW(TAG, "Multipart parser error");
865 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST, nullptr);
866 return ESP_FAIL;
867 }
868
869 remaining -= recv_len;
870 bytes_since_yield += recv_len;
871
872 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
873 vTaskDelay(1);
874 bytes_since_yield = 0;
875 }
876 }
877
878 handler->handleRequest(&req);
879 return ESP_OK;
880}
881#endif // USE_WEBSERVER_OTA
882
883} // namespace web_server_idf
884} // namespace esphome
885
886#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:183
std::string get_config_json()
Return the webserver configuration as JSON.
std::map< uint64_t, SortingGroup > sorting_groups_
Definition web_server.h:515
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:503
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