15#include <mbedtls/base64.h>
16#include <freertos/FreeRTOS.h>
17#include <freertos/task.h>
23#ifdef USE_WEBSERVER_AUTH_DIGEST
24#include <esp_random.h>
25#include <esp_rom_md5.h>
28#ifdef USE_WEBSERVER_OTA
29#include <multipart_parser.h>
40#include <sys/socket.h>
46#define HTTPD_401 "401 Unauthorized"
49#define HTTPD_403 "403 Forbidden"
52#define HTTPD_409 "409 Conflict"
55#define HTTPD_422 "422 Unprocessable Entity"
58#define CRLF_STR "\r\n"
59#define CRLF_LEN (sizeof(CRLF_STR) - 1)
65#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 14 && defined(__OPTIMIZE_SIZE__)
66#pragma GCC diagnostic error "-Wstack-usage=2048"
71static constexpr size_t RECV_CHUNK_SIZE = 1460;
72static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024;
84 for (
size_t i = 0; i < this->
headers_.size(); i++) {
85 if (!(skip_mask & (1U << i)))
106[[maybe_unused]]
int nonblocking_send(httpd_handle_t hd,
int sockfd,
const char *buf,
size_t buf_len,
int flags) {
107 if (buf ==
nullptr) {
108 return HTTPD_SOCK_ERR_INVALID;
112 int ret = send(sockfd, buf, buf_len,
flags | MSG_DONTWAIT);
114 const int err = errno;
115 if (err == EAGAIN || err == EWOULDBLOCK) {
117 return HTTPD_SOCK_ERR_TIMEOUT;
120 ESP_LOGD(TAG,
"send error: errno %d", err);
121 return HTTPD_SOCK_ERR_FAIL;
144 shutdown(sockfd, SHUT_RD);
162 httpd_config_t config = HTTPD_DEFAULT_CONFIG();
163 config.stack_size = 4512;
164 config.server_port = this->
port_;
165 config.max_open_sockets = WEB_SERVER_MAX_OPEN_SOCKETS;
166 config.uri_match_fn = [](
const char * ,
const char * ,
size_t ) {
return true; };
171 config.lru_purge_enable =
true;
174 if (httpd_start(&this->
server_, &config) == ESP_OK) {
175 const httpd_uri_t handler_get = {
181 httpd_register_uri_handler(this->
server_, &handler_get);
183 const httpd_uri_t handler_post = {
189 httpd_register_uri_handler(this->
server_, &handler_post);
191 const httpd_uri_t handler_options = {
193 .method = HTTP_OPTIONS,
197 httpd_register_uri_handler(this->
server_, &handler_options);
202 ESP_LOGVV(TAG,
"Enter AsyncWebServer::request_post_handler. uri=%s", r->uri);
206 ESP_LOGW(TAG,
"Content length is required for post: %s", r->uri);
207 httpd_resp_send_err(r, HTTPD_411_LENGTH_REQUIRED,
nullptr);
211 if (content_type.has_value()) {
212 const char *content_type_char = content_type.value().c_str();
215 size_t content_type_len = strlen(content_type_char);
216 if (
strcasestr_n(content_type_char, content_type_len,
"application/x-www-form-urlencoded") !=
nullptr) {
218#ifdef USE_WEBSERVER_OTA
219 }
else if (
strcasestr_n(content_type_char, content_type_len,
"multipart/form-data") !=
nullptr) {
232 if (r->content_len > CONFIG_HTTPD_MAX_REQ_HDR_LEN) {
233 ESP_LOGW(TAG,
"Request size is to big: %zu", r->content_len);
234 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
238 std::string post_query;
239 if (r->content_len > 0) {
240 post_query.resize(r->content_len);
241 const int ret = httpd_req_recv(r, &post_query[0], r->content_len + 1);
243 if (
ret == HTTPD_SOCK_ERR_TIMEOUT) {
244 httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT,
nullptr);
245 return ESP_ERR_TIMEOUT;
247 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
257 ESP_LOGVV(TAG,
"Enter AsyncWebServer::request_handler. method=%u, uri=%s", r->method, r->uri);
264 if (handler->canHandle(request)) {
267 handler->handleRequest(request);
275 return ESP_ERR_NOT_FOUND;
282 if (
h->canHandle(&req)) {
288 if (handler ==
nullptr) {
289 ESP_LOGW(TAG,
"Unsupported content type for POST: %s", content_type);
294 const size_t total = r->content_len;
296 auto buffer = std::make_unique_for_overwrite<char[]>(RECV_CHUNK_SIZE);
297 size_t bytes_since_yield = 0;
299 for (
size_t index = 0; index < total;) {
300 int recv_len = httpd_req_recv(r,
buffer.get(), std::min(total - index, RECV_CHUNK_SIZE));
303 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
305 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
308 handler->
handleBody(&req,
reinterpret_cast<uint8_t *
>(
buffer.get()), recv_len, index, total);
310 bytes_since_yield += recv_len;
312 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
314 bytes_since_yield = 0;
324#ifdef USE_WEBSERVER_OTA
329 for (
auto *param : this->
params_) {
345 const char *uri = this->
req_->uri;
346 const char *query_start = strchr(uri,
'?');
347 size_t uri_len = query_start ?
static_cast<size_t>(query_start - uri) : strlen(uri);
349 memcpy(
buffer.data(), uri, copy_len);
357 httpd_resp_set_status(*
this,
"302 Found");
358 httpd_resp_set_hdr(*
this,
"Location", url);
359 httpd_resp_set_hdr(*
this,
"Connection",
"close");
360 httpd_resp_send(*
this,
nullptr, 0);
395 httpd_resp_set_status(*
this,
status);
397 if (content_type && *content_type) {
398 httpd_resp_set_type(*
this, content_type);
400 httpd_resp_set_hdr(*
this,
"Accept-Ranges",
"none");
416#ifdef USE_WEBSERVER_AUTH
418#ifdef USE_WEBSERVER_AUTH_DIGEST
425 size_t key_len = strlen(
key);
426 const char *base = params.
c_str();
427 size_t n = params.
size();
430 while (i < n && (base[i] ==
' ' || base[i] ==
','))
432 size_t name_start = i;
433 while (i < n && base[i] !=
'=' && base[i] !=
',')
435 if (i >= n || base[i] ==
',')
437 size_t name_len = i - name_start;
438 while (name_len > 0 && base[name_start + name_len - 1] ==
' ')
441 const char *val_start;
443 if (i < n && base[i] ==
'"') {
445 val_start = base + i;
446 while (i < n && base[i] !=
'"')
448 val_len = (base + i) - val_start;
452 val_start = base + i;
453 while (i < n && base[i] !=
',')
455 val_len = (base + i) - val_start;
457 if (name_len == key_len && memcmp(base + name_start,
key, key_len) == 0)
458 return StringRef(val_start, val_len);
459 while (i < n && base[i] !=
',')
467bool check_digest_auth(
const char *username,
const char *password,
const std::string &header,
const char *method) {
468 const size_t prefix_len =
sizeof(
"Digest ") - 1;
469 StringRef params(header.c_str() + prefix_len, header.size() - prefix_len);
471 if (digest_param(params,
"username") != username)
474 StringRef realm = digest_param(params,
"realm");
475 StringRef nonce = digest_param(params,
"nonce");
476 StringRef uri = digest_param(params,
"uri");
477 StringRef qop = digest_param(params,
"qop");
478 StringRef nc = digest_param(params,
"nc");
479 StringRef cnonce = digest_param(params,
"cnonce");
480 StringRef response = digest_param(params,
"response");
481 if (response.size() != 32)
491 esp_rom_md5_init(&ctx);
492 esp_rom_md5_update(&ctx, username, strlen(username));
493 esp_rom_md5_update(&ctx,
":", 1);
494 esp_rom_md5_update(&ctx, realm.c_str(), realm.size());
495 esp_rom_md5_update(&ctx,
":", 1);
496 esp_rom_md5_update(&ctx, password, strlen(password));
497 esp_rom_md5_final(digest, &ctx);
502 esp_rom_md5_init(&ctx);
503 esp_rom_md5_update(&ctx, method, strlen(method));
504 esp_rom_md5_update(&ctx,
":", 1);
505 esp_rom_md5_update(&ctx, uri.c_str(), uri.size());
506 esp_rom_md5_final(digest, &ctx);
511 esp_rom_md5_init(&ctx);
512 esp_rom_md5_update(&ctx, ha1, 32);
513 esp_rom_md5_update(&ctx,
":", 1);
514 esp_rom_md5_update(&ctx, nonce.c_str(), nonce.size());
515 esp_rom_md5_update(&ctx,
":", 1);
516 esp_rom_md5_update(&ctx, nc.c_str(), nc.size());
517 esp_rom_md5_update(&ctx,
":", 1);
518 esp_rom_md5_update(&ctx, cnonce.c_str(), cnonce.size());
519 esp_rom_md5_update(&ctx,
":", 1);
520 esp_rom_md5_update(&ctx, qop.c_str(), qop.size());
521 esp_rom_md5_update(&ctx,
":", 1);
522 esp_rom_md5_update(&ctx, ha2, 32);
523 esp_rom_md5_final(digest, &ctx);
528 for (
size_t i = 0; i < 32; i++)
529 result |=
static_cast<uint8_t
>(expected[i] ^ response[i]);
537 if (username ==
nullptr || password ==
nullptr || *username == 0) {
540 auto auth = this->
get_header(
"Authorization");
541 if (!auth.has_value()) {
545 auto *auth_str = auth.value().c_str();
547#ifdef USE_WEBSERVER_AUTH_DIGEST
549 const auto auth_prefix_len =
sizeof(
"Digest ") - 1;
550 if (strncmp(
"Digest ", auth_str, auth_prefix_len) != 0) {
551 ESP_LOGW(TAG,
"Only Digest authorization supported");
554 return check_digest_auth(username, password, auth.value(), http_method_str(this->
method()));
556 const auto auth_prefix_len =
sizeof(
"Basic ") - 1;
557 if (strncmp(
"Basic ", auth_str, auth_prefix_len) != 0) {
558 ESP_LOGW(TAG,
"Only Basic authorization supported");
563 constexpr size_t max_user_info_len = 256;
564 char user_info[max_user_info_len];
565 size_t user_len = strlen(username);
566 size_t pass_len = strlen(password);
567 size_t user_info_len = user_len + 1 + pass_len;
569 if (user_info_len >= max_user_info_len) {
570 ESP_LOGW(TAG,
"Credentials too long for authentication");
574 memcpy(user_info, username, user_len);
575 user_info[user_len] =
':';
576 memcpy(user_info + user_len + 1, password, pass_len);
577 user_info[user_info_len] =
'\0';
581 constexpr size_t max_digest_len = 350;
582 char digest[max_digest_len];
586 if (mbedtls_base64_encode(
reinterpret_cast<uint8_t *
>(digest), max_digest_len, &
out,
587 reinterpret_cast<const uint8_t *
>(user_info), user_info_len) != 0) {
594 const char *provided = auth_str + auth_prefix_len;
595 size_t digest_len =
out;
598 size_t provided_len = auth.value().size() - auth_prefix_len;
602 volatile size_t result = digest_len ^ provided_len;
606 for (
size_t i = 0; i < digest_len; i++) {
607 char provided_ch = (i < provided_len) ? provided[i] : 0;
608 result |=
static_cast<uint8_t
>(digest[i] ^ provided_ch);
615 httpd_resp_set_hdr(*
this,
"Connection",
"keep-alive");
616#ifdef USE_WEBSERVER_AUTH_DIGEST
629 snprintf(header,
sizeof(header), R
"(Digest realm="Login Required", qop="auth", nonce="%s", opaque="%s")", nonce,
631 httpd_resp_set_hdr(*this,
"WWW-Authenticate", header);
633 httpd_resp_set_hdr(*
this,
"WWW-Authenticate",
"Basic realm=\"Login Required\"");
635 httpd_resp_send_err(*
this, HTTPD_401_UNAUTHORIZED,
nullptr);
641 for (
auto *param : this->
params_) {
642 if (param->name() == name) {
652 if (!
val.has_value()) {
657 this->params_.push_back(param);
664template<
typename Func>
665static auto search_query_sources(httpd_req_t *req,
const std::string &post_query,
const char *name, Func func)
666 ->
decltype(func(
nullptr,
size_t{0}, name)) {
667 if (!post_query.empty()) {
668 auto result = func(post_query.c_str(), post_query.size(), name);
676 auto len = httpd_req_get_url_query_len(req);
680 const char *query = strchr(req->uri,
'?');
681 if (query ==
nullptr) {
685 return func(query,
len, name);
699 if (
val.has_value()) {
700 return std::move(
val.value());
707 for (
size_t i = 0; i < defaults.size(); i++) {
711 httpd_resp_set_hdr(*this->
req_, name,
value);
718 int len = snprintf(buf,
sizeof(buf),
"%f",
value);
726 const int length = vsnprintf(
nullptr, 0,
fmt, args);
733 vsnprintf(&str[0],
length + 1,
fmt, args);
743 for (
auto *ses : *vec) {
768 this->adopt_pending_sessions_main_loop_();
774 for (
size_t i = 0; i < this->
sessions_.size();) {
777 if (ses->safe_to_delete_()) {
792void AsyncEventSource::adopt_pending_sessions_main_loop_() {
793 std::vector<AsyncEventSourceResponse *> incoming;
799 for (
auto *rsp : incoming) {
801 if (rsp->safe_to_delete_()) {
807 if (httpd_sess_get_ctx(rsp->hd_, rsp->fd_.load()) != rsp) {
814 rsp->start_session_main_loop_();
822 if (ses->fd_.load() != 0) {
823 ses->try_send_nodefer(
message, message_len, event,
id, reconnect);
833 if (ses->fd_.load() != 0) {
834 ses->deferrable_send_state(source, detail_all, message_generator);
842 : server_(server), web_server_(ws), entities_iterator_(ws, server) {
844 httpd_req_t *req = *request;
846 httpd_resp_set_status(req, HTTPD_200);
847 httpd_resp_set_type(req,
"text/event-stream");
848 httpd_resp_set_hdr(req,
"Cache-Control",
"no-cache");
849 httpd_resp_set_hdr(req,
"Connection",
"keep-alive");
853 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
855 req->sess_ctx =
this;
858 this->
hd_ = req->handle;
859 this->
fd_.store(httpd_req_to_sockfd(req));
862 httpd_sess_set_send_override(this->
hd_, this->
fd_.load(), nonblocking_send);
873 ESP_LOGW(TAG,
"Config not sent to fd %d", this->
fd_.load());
878#ifdef USE_WEBSERVER_SORTING
879 for (
auto &group : ws->sorting_groups_) {
881 JsonObject root = builder.
root();
883 root[
"sorting_weight"] = group.second.weight;
891 ESP_LOGW(TAG,
"Sorting groups not sent to fd %d", this->
fd_.load());
903 int fd = rsp->
fd_.exchange(0);
904 ESP_LOGD(TAG,
"Event source connection closed (fd: %d)", fd);
921 this->deferred_queue_.push_back(item);
960 const int fd = this->
fd_.load();
982 ESP_LOGW(TAG,
"Failed to queue EventSource close (%s); retrying", esp_err_to_name(err));
1008 const int fd = response->
fd_.load();
1009 if (response->owns_session_(fd)) {
1010 httpd_sess_update_lru_counter(response->hd_, fd);
1013 response->lru_work_queued_.store(
false, std::memory_order_release);
1018 const int fd = response->
fd_.load();
1019 if (response->owns_session_(fd)) {
1022 shutdown(fd, SHUT_RDWR);
1026 response->close_work_queued_.store(
false, std::memory_order_release);
1032 const int fd = this->
fd_.load();
1036 struct msghdr msg{};
1038 msg.msg_iovlen = iovcnt;
1039 const ssize_t sent = sendmsg(fd, &msg, MSG_DONTWAIT);
1043 const int err = errno;
1044 if (err == EAGAIN || err == EWOULDBLOCK) {
1047 ESP_LOGD(TAG,
"send error: errno %d", err);
1073 ESP_LOGW(TAG,
"Closing stuck EventSource connection after %" PRIu32
" ms without send progress",
1081 this->tail_sent_ += sent;
1083 ESP_LOGV(TAG,
"Partial send: %zd/%zu bytes (total: %u/%u)", sent, remaining, this->tail_sent_, this->tail_len_);
1087 this->tail_len_ = 0;
1099 this->
tail_.reset();
1106 size_t message_len,
size_t total,
size_t sent) {
1110 "the log cut in web_server.h must keep a worst case log event inside the tail ceiling");
1114 ESP_LOGW(TAG,
"Cannot buffer a %zu byte chunk, closing", total);
1121 uint8_t *dst = this->
tail_.get();
1122 std::memcpy(dst, prefix, prefix_len);
1126 [](
void *ctx,
const char *piece,
size_t len) {
1127 auto &
out = *
static_cast<uint8_t **
>(ctx);
1128 std::memcpy(
out, piece,
len);
1151#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 14 && defined(__OPTIMIZE_SIZE__)
1152#pragma GCC diagnostic push
1153#pragma GCC diagnostic ignored "-Wstack-usage="
1157 char *
buffer,
size_t *size_out) {
1160 SendGuard guard{*
this};
1170 const size_t prefix_len =
build_chunk_prefix(prefix,
sizeof(prefix),
"state", 0, 0,
true);
1173 size_t json_len = 0;
1181 json_len = builder.serialize_to(
reinterpret_cast<char *
>(this->
tail_.get()) + prefix_len, room);
1182 if (json_len < room) {
1194 uint8_t *dst = this->
tail_.get();
1195 std::memcpy(dst, prefix, prefix_len);
1201#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 14 && defined(__OPTIMIZE_SIZE__)
1202#pragma GCC diagnostic pop
1225 ESP_LOGW(TAG,
"State event does not fit %zu bytes, dropped",
size);
1226 this->
tail_.reset();
1240 ESP_LOGW(TAG,
"No memory for a %zu byte chunk", cap);
1250 if (this->
sending_ || this->
fd_.load() == 0 || this->close_requested_) {
1272 ESP_LOGW(TAG,
"Event name too long, dropped");
1278 struct iovec iov[MAX_SEND_IOV];
1283 g.total = prefix_len;
1286 [](
void *ctx,
const char *piece,
size_t len) {
1287 auto &g = *
static_cast<Gather *
>(ctx);
1296 g.iov[g.iovcnt++] = {
const_cast<char *
>(piece),
len};
1301 g.iov[0] = {prefix, prefix_len};
1304 const ssize_t sent = g.fits ? this->
send_(g.iov, g.iovcnt) : 0;
1308 if (
static_cast<size_t>(sent) == g.total) {
1343#ifdef USE_WEBSERVER_OTA
1346 const char *boundary_start;
1347 size_t boundary_len;
1349 ESP_LOGE(TAG,
"Failed to parse multipart boundary");
1350 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
1357 if (
h->canHandle(&req)) {
1364 ESP_LOGW(TAG,
"No handler found for OTA request");
1365 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND,
nullptr);
1370 std::string filename;
1373 auto reader = std::make_unique<MultipartReader>(
"--" + std::string(boundary_start, boundary_len));
1376 reader->set_data_callback([&](
const uint8_t *data,
size_t len) {
1377 if (!reader->has_file() || !
len)
1380 if (filename.empty()) {
1381 filename = reader->get_current_part().filename;
1382 ESP_LOGV(TAG,
"Processing file: '%s'", filename.c_str());
1383 handler->
handleUpload(&req, filename, 0,
nullptr, 0,
false);
1386 handler->
handleUpload(&req, filename, index,
const_cast<uint8_t *
>(data),
len,
false);
1390 reader->set_part_complete_callback([&]() {
1392 handler->
handleUpload(&req, filename, index,
nullptr, 0,
true);
1398 auto buffer = std::make_unique_for_overwrite<char[]>(RECV_CHUNK_SIZE);
1399 size_t bytes_since_yield = 0;
1401 for (
size_t remaining = r->content_len; remaining > 0;) {
1402 int recv_len = httpd_req_recv(r,
buffer.get(), std::min(remaining, RECV_CHUNK_SIZE));
1404 if (recv_len <= 0) {
1405 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
1407 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
1410 if (reader->parse(
buffer.get(), recv_len) !=
static_cast<size_t>(recv_len)) {
1411 ESP_LOGW(TAG,
"Multipart parser error");
1412 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
1416 remaining -= recv_len;
1417 bytes_since_yield += recv_len;
1419 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
1421 bytes_since_yield = 0;
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void enable_loop_soon_any_context()
Thread and ISR-safe version of enable_loop() that can be called from any context.
void begin(bool include_internal=false)
ESPHOME_ALWAYS_INLINE void try_advance(size_t max_steps)
Run up to max_steps iteration steps; stops early when iteration completes or a callback refuses (that...
Helper class that wraps a mutex with a RAII-style API.
An STL allocator that uses SPI or internal RAM.
RAMUniquePtr< T[]> make_unique_array_for_overwrite(size_t n)
n elements left uninitialized, as std::make_unique_for_overwrite does; empty on exhaustion,...
StringRef is a reference to a string owned by something else.
constexpr const char * c_str() const
constexpr size_type size() const
Bump allocator over a fixed buffer for a document built and serialized in one scope.
Builder class for creating JSON documents without lambdas.
SerializationBuffer serialize()
Serialize the JSON document to a SerializationBuffer (stack-first allocation) Uses 512-byte stack buf...
This class allows users to create a web server with their ESP nodes.
json::SerializationBuffer get_config_json()
Return the webserver configuration as JSON.
std::vector< AsyncEventSourceResponse * > pending_sessions_
~AsyncEventSource() override
std::atomic< bool > has_pending_sessions_
friend class AsyncEventSourceResponse
bool loop()
Returns true if there are sessions remaining (including pending cleanup).
std::vector< AsyncEventSourceResponse * > sessions_
void try_send_nodefer(const char *message, size_t message_len, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
esphome::web_server::WebServer * web_server_
void handleRequest(AsyncWebServerRequest *request) override
void deferrable_send_state(void *source, bool detail_all, message_generator_t *message_generator)
static constexpr uint32_t CLOSE_CONFIRM_INTERVAL_MS
void deferrable_send_state(void *source, bool detail_all, message_generator_t *message_generator)
std::atomic< bool > close_work_queued_
void start_session_main_loop_()
uint32_t send_failure_started_ms_
uint32_t last_lru_refresh_ms_
std::vector< DeferredEvent > deferred_queue_
JsonPrepareResult message_generator_t char * buffer
bool try_send_nodefer(const char *message, size_t message_len, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
void deq_push_back_with_dedup_(void *source, message_generator_t *message_generator)
void tail_alloc_failed_(size_t cap)
ssize_t send_(struct iovec *iov, int iovcnt)
static void destroy(void *p)
bool close_retry_warning_logged_
bool stash_chunk_(const char *prefix, size_t prefix_len, const char *message, size_t message_len, size_t total, size_t sent)
AsyncEventSourceResponse(const AsyncWebServerRequest *request, esphome::web_server_idf::AsyncEventSource *server, esphome::web_server::WebServer *ws)
esphome::web_server::WebServer * web_server_
static constexpr size_t MAX_SEND_IOV
static void refresh_lru_work(void *arg)
bool owns_session_(int fd) const
static void close_session_work(void *arg)
static constexpr uint32_t LRU_REFRESH_INTERVAL_MS
uint32_t next_close_attempt_ms_
static constexpr size_t PREFIX_BUF_SIZE
static constexpr uint32_t CLOSE_RETRY_INTERVAL_MS
static constexpr size_t TAIL_MAX_SIZE
static constexpr uint32_t SEND_STALL_TIMEOUT_MS
JsonPrepareResult message_generator_t * generator
JsonPrepareResult message_generator_t char size_t * size_out
void process_deferred_queue_()
static constexpr size_t JSON_BUF_SIZE
bool send_json_(void *source, message_generator_t *generator)
@ JSON_PREPARE_RESULT_NO_MEMORY
@ JSON_PREPARE_RESULT_TAIL
@ JSON_PREPARE_RESULT_BUFFER
@ JSON_PREPARE_RESULT_TOO_LARGE
std::atomic< bool > lru_work_queued_
esphome::web_server::ListEntitiesIterator entities_iterator_
RAMUniquePtr< uint8_t[]> tail_
bool reserve_tail_(size_t len)
void print(const char *str)
void printf(const char *fmt,...) __attribute__((format(printf
virtual void handleRequest(AsyncWebServerRequest *request)
virtual void handleUpload(AsyncWebServerRequest *request, const std::string &filename, size_t index, uint8_t *data, size_t len, bool final)
virtual void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total)
std::function< void(AsyncWebServerRequest *request)> on_not_found_
esp_err_t handle_raw_body_(httpd_req_t *r, const char *content_type)
static esp_err_t request_post_handler(httpd_req_t *r)
std::vector< AsyncWebHandler * > handlers_
esp_err_t request_handler_(AsyncWebServerRequest *request) const
esp_err_t handle_multipart_upload_(httpd_req_t *r, const char *content_type)
static void safe_close_with_shutdown(httpd_handle_t hd, int sockfd)
static esp_err_t request_handler(httpd_req_t *r)
size_t get_header_to(const char *name, std::span< char > buf) const
Copy a header value into buf without heap allocation.
AsyncWebParameter * getParam(const char *name)
optional< std::string > get_header(const char *name) const
bool hasArg(const char *name)
StringRef url_to(std::span< char, URL_BUF_SIZE > buffer) const
Write URL (without query string) to buffer, returns StringRef pointing to buffer.
void send(AsyncWebServerResponse *response)
bool hasHeader(const char *name) const
void init_response_(AsyncWebServerResponse *rsp, int code, const char *content_type)
static constexpr size_t URL_BUF_SIZE
Buffer size for url_to()
std::function< void()> on_disconnect_
http_method method() const
std::string arg(const char *name)
optional< std::string > find_query_value_(const char *name) const
void requestAuthentication() const
AsyncWebServerResponse * rsp_
bool authenticate(const char *username, const char *password) const
std::vector< AsyncWebParameter * > params_
void redirect(const char *url)
const AsyncWebServerRequest * req_
uint8_t replaced_defaults_
virtual const char * get_content_data() const =0
virtual size_t get_content_size() const =0
void addHeader(const char *name, const char *value)
const LogString * message
std::vector< uint8_t > & out
JsonString linked(const char *s)
constexpr size_t CHUNK_END_LEN
size_t build_chunk_prefix(char *buf, size_t size, const char *event, uint32_t id, uint32_t reconnect, bool with_data)
bool query_has_key(const char *query_url, size_t query_len, const char *key)
void(esphome::web_server::WebServer *, void *, json::JsonBuilder &) message_generator_t
optional< std::string > request_get_header(httpd_req_t *req, const char *name)
size_t request_get_header_to(httpd_req_t *req, const char *name, std::span< char > buf)
Copy a header value into buf, nul-terminated, without heap allocation.
constexpr size_t SSE_SUFFIX_LEN
bool parse_multipart_boundary(const char *content_type, const char **boundary_start, size_t *boundary_len)
optional< std::string > query_key_value(const char *query_url, size_t query_len, const char *key)
const char * strcasestr_n(const char *haystack, size_t haystack_len, const char *needle)
constexpr size_t SSE_SEP_LEN
void write_chunk_header(char *buf, size_t chunk_len)
constexpr size_t CHUNK_HDR_LEN
constexpr char SSE_SUFFIX[]
size_t url_decode(char *str)
Decode URL-encoded string in-place (e.g., %20 -> space, + -> space) Returns the new length of the dec...
ESPHOME_LOG_TAG(TAG, "multipart")
bool request_has_header(httpd_req_t *req, const char *name)
void for_each_chunk_piece(const char *message, size_t message_len, ChunkPieceSink sink, void *ctx)
constexpr size_t LOG_EVENT_MAX_LEN
bool random_bytes(uint8_t *data, size_t len)
Generate len random bytes using the platform's secure RNG (hardware RNG or OS CSPRNG).
bool str_equals_case_insensitive(const std::string &a, const std::string &b)
Compare strings for equality in case-insensitive manner.
size_t size_t const char va_start(args, fmt)
size_t size_t const char * fmt
uint32_t IRAM_ATTR HOT millis()
char * format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as lowercase hex to buffer (base implementation).
Application App
Global storage of Application pointer - only one Application can exist.
message_generator_t * message_generator_