12#include "esp_tls_crypto.h"
13#include <freertos/FreeRTOS.h>
14#include <freertos/task.h>
19#ifdef USE_WEBSERVER_OTA
20#include <multipart_parser.h>
31#include <sys/socket.h>
34namespace web_server_idf {
37#define HTTPD_409 "409 Conflict"
40#define CRLF_STR "\r\n"
41#define CRLF_LEN (sizeof(CRLF_STR) - 1)
43static const char *
const TAG =
"web_server_idf";
49DefaultHeaders default_headers_instance;
70int nonblocking_send(httpd_handle_t hd,
int sockfd,
const char *buf,
size_t buf_len,
int flags) {
72 return HTTPD_SOCK_ERR_INVALID;
76 int ret = send(sockfd, buf, buf_len,
flags | MSG_DONTWAIT);
78 if (errno == EAGAIN || errno == EWOULDBLOCK) {
80 return HTTPD_SOCK_ERR_TIMEOUT;
83 ESP_LOGD(TAG,
"send error: errno %d", errno);
84 return HTTPD_SOCK_ERR_FAIL;
107 shutdown(sockfd, SHUT_RD);
124 httpd_config_t config = HTTPD_DEFAULT_CONFIG();
125 config.server_port = this->
port_;
126 config.uri_match_fn = [](
const char * ,
const char * ,
size_t ) {
return true; };
131 config.lru_purge_enable =
true;
134 if (httpd_start(&this->
server_, &config) == ESP_OK) {
135 const httpd_uri_t handler_get = {
141 httpd_register_uri_handler(this->
server_, &handler_get);
143 const httpd_uri_t handler_post = {
149 httpd_register_uri_handler(this->
server_, &handler_post);
151 const httpd_uri_t handler_options = {
153 .method = HTTP_OPTIONS,
157 httpd_register_uri_handler(this->
server_, &handler_options);
162 ESP_LOGVV(TAG,
"Enter AsyncWebServer::request_post_handler. uri=%s", r->uri);
166 ESP_LOGW(TAG,
"Content length is required for post: %s", r->uri);
167 httpd_resp_send_err(r, HTTPD_411_LENGTH_REQUIRED,
nullptr);
171 if (content_type.has_value()) {
172 const char *content_type_char = content_type.value().c_str();
175 if (
stristr(content_type_char,
"application/x-www-form-urlencoded") !=
nullptr) {
177#ifdef USE_WEBSERVER_OTA
178 }
else if (
stristr(content_type_char,
"multipart/form-data") !=
nullptr) {
183 ESP_LOGW(TAG,
"Unsupported content type for POST: %s", content_type_char);
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);
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);
201 if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
202 httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT,
nullptr);
203 return ESP_ERR_TIMEOUT;
205 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
215 ESP_LOGVV(TAG,
"Enter AsyncWebServer::request_handler. method=%u, uri=%s", r->method, r->uri);
222 if (handler->canHandle(request)) {
225 handler->handleRequest(request);
233 return ESP_ERR_NOT_FOUND;
238 for (
auto *param : this->
params_) {
250 auto *query_start = strchr(this->
req_->uri,
'?');
252 if (query_start ==
nullptr) {
253 result = this->
req_->uri;
255 result = std::string(this->
req_->uri, query_start - this->req_->uri);
259 if (!result.empty()) {
261 result.resize(new_len);
275 httpd_resp_send(*
this, content, HTTPD_RESP_USE_STRLEN);
277 httpd_resp_send(*
this,
nullptr, 0);
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);
305 httpd_resp_set_status(*
this,
status);
307 if (content_type && *content_type) {
308 httpd_resp_set_type(*
this, content_type);
310 httpd_resp_set_hdr(*
this,
"Accept-Ranges",
"none");
313 httpd_resp_set_hdr(*
this, header.name, header.value);
320#ifdef USE_WEBSERVER_AUTH
322 if (username ==
nullptr || password ==
nullptr || *username == 0) {
325 auto auth = this->
get_header(
"Authorization");
326 if (!auth.has_value()) {
330 auto *auth_str = auth.value().c_str();
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");
339 constexpr size_t max_user_info_len = 256;
340 char user_info[max_user_info_len];
341 size_t user_len = strlen(username);
342 size_t pass_len = strlen(password);
343 size_t user_info_len = user_len + 1 + pass_len;
345 if (user_info_len >= max_user_info_len) {
346 ESP_LOGW(TAG,
"Credentials too long for authentication");
350 memcpy(user_info, username, user_len);
351 user_info[user_len] =
':';
352 memcpy(user_info + user_len + 1, password, pass_len);
353 user_info[user_info_len] =
'\0';
356 esp_crypto_base64_encode(
nullptr, 0, &n,
reinterpret_cast<const uint8_t *
>(user_info), user_info_len);
358 auto digest = std::unique_ptr<char[]>(
new char[n + 1]);
359 esp_crypto_base64_encode(
reinterpret_cast<uint8_t *
>(digest.get()), n, &out,
360 reinterpret_cast<const uint8_t *
>(user_info), user_info_len);
362 return strcmp(digest.get(), auth_str + auth_prefix_len) == 0;
366 httpd_resp_set_hdr(*
this,
"Connection",
"keep-alive");
369 httpd_resp_set_hdr(*
this,
"WWW-Authenticate",
"Basic realm=\"Login Required\"");
370 httpd_resp_send_err(*
this, HTTPD_401_UNAUTHORIZED,
nullptr);
376 for (
auto *param : this->
params_) {
377 if (param->name() == name) {
384 if (!
val.has_value()) {
386 if (url_query.has_value()) {
393 if (!
val.has_value()) {
398 this->params_.push_back(param);
403 httpd_resp_set_hdr(*this->
req_, name, value);
410 int len = snprintf(buf,
sizeof(buf),
"%f", value);
418 const int length = vsnprintf(
nullptr, 0, fmt, args);
425 vsnprintf(&str[0],
length + 1, fmt, args);
451 for (
size_t i = 0; i < this->
sessions_.size();) {
454 if (ses->fd_.load() == 0) {
455 ESP_LOGD(TAG,
"Removing dead event source session");
469 if (ses->fd_.load() != 0) {
470 ses->try_send_nodefer(
message, event,
id, reconnect);
481 if (ses->fd_.load() != 0) {
482 ses->deferrable_send_state(source, event_type, message_generator);
490 : server_(server), web_server_(ws), entities_iterator_(new
esphome::web_server::ListEntitiesIterator(ws, server)) {
491 httpd_req_t *req = *request;
493 httpd_resp_set_status(req, HTTPD_200);
494 httpd_resp_set_type(req,
"text/event-stream");
495 httpd_resp_set_hdr(req,
"Cache-Control",
"no-cache");
496 httpd_resp_set_hdr(req,
"Connection",
"keep-alive");
499 httpd_resp_set_hdr(req, header.name, header.value);
502 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
504 req->sess_ctx =
this;
507 this->
hd_ = req->handle;
508 this->
fd_.store(httpd_req_to_sockfd(req));
511 httpd_sess_set_send_override(this->
hd_, this->
fd_.load(), nonblocking_send);
518#ifdef USE_WEBSERVER_SORTING
522 JsonObject root = builder.
root();
523 root[
"name"] = group.second.name;
524 root[
"sorting_weight"] = group.second.weight;
545 int fd = rsp->
fd_.exchange(0);
546 ESP_LOGD(TAG,
"Event source connection closed (fd: %d)", fd);
563 this->deferred_queue_.push_back(item);
592 if (bytes_sent == HTTPD_SOCK_ERR_TIMEOUT) {
601 ESP_LOGW(TAG,
"Closing stuck EventSource connection after %" PRIu16
" failed sends",
608 if (bytes_sent == HTTPD_SOCK_ERR_FAIL) {
612 if (bytes_sent <= 0) {
614 ESP_LOGW(TAG,
"Unexpected send result: %d", bytes_sent);
624 ESP_LOGV(TAG,
"Partial send: %d/%zu bytes (total: %zu/%zu)", bytes_sent, remaining,
event_bytes_sent_,
642 uint32_t reconnect) {
643 if (this->
fd_.load() == 0) {
654 const char chunk_len_header[] =
" " CRLF_STR;
655 const int chunk_len_header_len =
sizeof(chunk_len_header) - 1;
661 constexpr size_t num_buf_size = 32;
662 char num_buf[num_buf_size];
665 int len = snprintf(num_buf, num_buf_size,
"retry: %" PRIu32 CRLF_STR, reconnect);
670 int len = snprintf(num_buf, num_buf_size,
"id: %" PRIu32 CRLF_STR,
id);
674 if (event && *event) {
687 const char *first_n = strchr(
message,
'\n');
688 const char *first_r = strchr(
message,
'\r');
690 if (first_n ==
nullptr && first_r ==
nullptr) {
697 const char *line_start =
message;
698 size_t msg_len = strlen(
message);
699 const char *msg_end =
message + msg_len;
702 const char *next_n = first_n;
703 const char *next_r = first_r;
705 while (line_start <= msg_end) {
706 const char *line_end;
707 const char *next_line;
709 if (next_n ==
nullptr && next_r ==
nullptr) {
718 if (next_n !=
nullptr && next_r !=
nullptr) {
719 if (next_r + 1 == next_n) {
722 next_line = next_n + 1;
725 line_end = (next_r < next_n) ? next_r : next_n;
726 next_line = line_end + 1;
728 }
else if (next_n !=
nullptr) {
731 next_line = next_n + 1;
735 next_line = next_r + 1;
743 line_start = next_line;
746 if (line_start >= msg_end) {
751 next_n = strchr(line_start,
'\n');
752 next_r = strchr(line_start,
'\r');
760 if (
event_buffer_.size() ==
static_cast<size_t>(chunk_len_header_len)) {
769 int chunk_len =
event_buffer_.size() - CRLF_LEN - chunk_len_header_len;
770 char chunk_len_str[9];
771 snprintf(chunk_len_str, 9,
"%08x", chunk_len);
787 if (source ==
nullptr)
789 if (event_type ==
nullptr)
791 if (message_generator ==
nullptr)
794 if (0 != strcmp(event_type,
"state_detail_all") && 0 != strcmp(event_type,
"state")) {
795 ESP_LOGE(TAG,
"Can't defer non-state event");
814#ifdef USE_WEBSERVER_OTA
816 static constexpr size_t MULTIPART_CHUNK_SIZE = 1460;
817 static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024;
820 const char *boundary_start;
823 ESP_LOGE(TAG,
"Failed to parse multipart boundary");
824 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
831 if (
h->canHandle(&req)) {
838 ESP_LOGW(TAG,
"No handler found for OTA request");
839 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND,
nullptr);
844 std::string filename;
847 auto reader = std::make_unique<MultipartReader>(
"--" + std::string(boundary_start, boundary_len));
850 reader->set_data_callback([&](
const uint8_t *data,
size_t len) {
851 if (!reader->has_file() || !
len)
854 if (filename.empty()) {
855 filename = reader->get_current_part().filename;
856 ESP_LOGV(TAG,
"Processing file: '%s'", filename.c_str());
857 handler->
handleUpload(&req, filename, 0,
nullptr, 0,
false);
860 handler->
handleUpload(&req, filename, index,
const_cast<uint8_t *
>(data),
len,
false);
864 reader->set_part_complete_callback([&]() {
866 handler->
handleUpload(&req, filename, index,
nullptr, 0,
true);
873 std::unique_ptr<char[]> buffer(
new char[MULTIPART_CHUNK_SIZE]);
874 size_t bytes_since_yield = 0;
876 for (
size_t remaining = r->content_len; remaining > 0;) {
877 int recv_len = httpd_req_recv(r, buffer.get(), std::min(remaining, MULTIPART_CHUNK_SIZE));
880 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
882 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
885 if (reader->parse(buffer.get(), recv_len) !=
static_cast<size_t>(recv_len)) {
886 ESP_LOGW(TAG,
"Multipart parser error");
887 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
891 remaining -= recv_len;
892 bytes_since_yield += recv_len;
894 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
896 bytes_since_yield = 0;
void begin(bool include_internal=false)
Builder class for creating JSON documents without lambdas.
value_type const & value() const
This class allows users to create a web server with their ESP nodes.
std::string get_config_json()
Return the webserver configuration as JSON.
std::map< uint64_t, SortingGroup > sorting_groups_
~AsyncEventSource() override
friend class AsyncEventSourceResponse
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
connect_handler_t on_connect_
static void destroy(void *p)
std::vector< DeferredEvent > deferred_queue_
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)
void process_deferred_queue_()
AsyncEventSourceResponse(const AsyncWebServerRequest *request, esphome::web_server_idf::AsyncEventSource *server, esphome::web_server::WebServer *ws)
static constexpr uint16_t MAX_CONSECUTIVE_SEND_FAILURES
std::unique_ptr< esphome::web_server::ListEntitiesIterator > entities_iterator_
uint16_t consecutive_send_failures_
bool try_send_nodefer(const char *message, const char *event=nullptr, uint32_t id=0, uint32_t reconnect=0)
std::string event_buffer_
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)
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)
bool hasHeader(const char *name) const
void init_response_(AsyncWebServerResponse *rsp, int code, const char *content_type)
void requestAuthentication(const char *realm=nullptr) const
AsyncWebServerResponse * rsp_
bool authenticate(const char *username, const char *password) const
std::vector< AsyncWebParameter * > params_
void redirect(const std::string &url)
const AsyncWebServerRequest * req_
virtual const char * get_content_data() const =0
virtual size_t get_content_size() const =0
void addHeader(const char *name, const char *value)
optional< std::string > request_get_url_query(httpd_req_t *req)
optional< std::string > request_get_header(httpd_req_t *req, const char *name)
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
size_t url_decode(char *str)
Decode URL-encoded string in-place (e.g., %20 -> space, + -> space) Returns the new length of the dec...
optional< std::string > query_key_value(const std::string &query_url, const std::string &key)
const char * stristr(const char *haystack, const char *needle)
bool request_has_header(httpd_req_t *req, const char *name)
Providing packet encoding functions for exchanging data with a remote host.
uint32_t IRAM_ATTR HOT millis()
message_generator_t * message_generator_