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);
136 httpd_config_t config = HTTPD_DEFAULT_CONFIG();
137 config.server_port = this->
port_;
138 config.uri_match_fn = [](
const char * ,
const char * ,
size_t ) {
return true; };
143 if (httpd_start(&this->
server_, &config) == ESP_OK) {
144 const httpd_uri_t handler_get = {
150 httpd_register_uri_handler(this->
server_, &handler_get);
152 const httpd_uri_t handler_post = {
158 httpd_register_uri_handler(this->
server_, &handler_post);
160 const httpd_uri_t handler_options = {
162 .method = HTTP_OPTIONS,
166 httpd_register_uri_handler(this->
server_, &handler_options);
171 ESP_LOGVV(TAG,
"Enter AsyncWebServer::request_post_handler. uri=%s", r->uri);
175 ESP_LOGW(TAG,
"Content length is required for post: %s", r->uri);
176 httpd_resp_send_err(r, HTTPD_411_LENGTH_REQUIRED,
nullptr);
180 if (content_type.has_value()) {
181 const char *content_type_char = content_type.value().c_str();
184 if (
stristr(content_type_char,
"application/x-www-form-urlencoded") !=
nullptr) {
186#ifdef USE_WEBSERVER_OTA
187 }
else if (
stristr(content_type_char,
"multipart/form-data") !=
nullptr) {
192 ESP_LOGW(TAG,
"Unsupported content type for POST: %s", content_type_char);
199 if (r->content_len > CONFIG_HTTPD_MAX_REQ_HDR_LEN) {
200 ESP_LOGW(TAG,
"Request size is to big: %zu", r->content_len);
201 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
205 std::string post_query;
206 if (r->content_len > 0) {
207 post_query.resize(r->content_len);
208 const int ret = httpd_req_recv(r, &post_query[0], r->content_len + 1);
210 if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
211 httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT,
nullptr);
212 return ESP_ERR_TIMEOUT;
214 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
224 ESP_LOGVV(TAG,
"Enter AsyncWebServer::request_handler. method=%u, uri=%s", r->method, r->uri);
231 if (handler->canHandle(request)) {
234 handler->handleRequest(request);
242 return ESP_ERR_NOT_FOUND;
247 for (
auto *param : this->
params_) {
259 auto *str = strchr(this->
req_->uri,
'?');
260 if (str ==
nullptr) {
261 return this->
req_->uri;
263 return std::string(this->
req_->uri, str - this->req_->uri);
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, pair.first.c_str(), pair.second.c_str());
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");
338 std::string user_info;
339 user_info += username;
341 user_info += password;
344 esp_crypto_base64_encode(
nullptr, 0, &n,
reinterpret_cast<const uint8_t *
>(user_info.c_str()), user_info.size());
346 auto digest = std::unique_ptr<char[]>(
new char[n + 1]);
347 esp_crypto_base64_encode(
reinterpret_cast<uint8_t *
>(digest.get()), n, &out,
348 reinterpret_cast<const uint8_t *
>(user_info.c_str()), user_info.size());
350 return strcmp(digest.get(), auth_str + auth_prefix_len) == 0;
354 httpd_resp_set_hdr(*
this,
"Connection",
"keep-alive");
355 auto auth_val =
str_sprintf(
"Basic realm=\"%s\"", realm ? realm :
"Login Required");
356 httpd_resp_set_hdr(*
this,
"WWW-Authenticate", auth_val.c_str());
357 httpd_resp_send_err(*
this, HTTPD_401_UNAUTHORIZED,
nullptr);
363 for (
auto *param : this->
params_) {
364 if (param->name() == name) {
371 if (!
val.has_value()) {
373 if (url_query.has_value()) {
380 if (!
val.has_value()) {
385 this->params_.push_back(param);
390 httpd_resp_set_hdr(*this->
req_, name, value);
397 int len = snprintf(buf,
sizeof(buf),
"%f", value);
405 const int length = vsnprintf(
nullptr, 0, fmt, args);
412 vsnprintf(&str[0],
length + 1, fmt, args);
438 for (
size_t i = 0; i < this->
sessions_.size();) {
441 if (ses->fd_.load() == 0) {
442 ESP_LOGD(TAG,
"Removing dead event source session");
456 if (ses->fd_.load() != 0) {
457 ses->try_send_nodefer(
message, event,
id, reconnect);
468 if (ses->fd_.load() != 0) {
469 ses->deferrable_send_state(source, event_type, message_generator);
477 : server_(server), web_server_(ws), entities_iterator_(new
esphome::web_server::ListEntitiesIterator(ws, server)) {
478 httpd_req_t *req = *request;
480 httpd_resp_set_status(req, HTTPD_200);
481 httpd_resp_set_type(req,
"text/event-stream");
482 httpd_resp_set_hdr(req,
"Cache-Control",
"no-cache");
483 httpd_resp_set_hdr(req,
"Connection",
"keep-alive");
486 httpd_resp_set_hdr(req, pair.first.c_str(), pair.second.c_str());
489 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
491 req->sess_ctx =
this;
494 this->
hd_ = req->handle;
495 this->
fd_.store(httpd_req_to_sockfd(req));
498 httpd_sess_set_send_override(this->
hd_, this->
fd_.load(), nonblocking_send);
505#ifdef USE_WEBSERVER_SORTING
509 JsonObject root = builder.
root();
510 root[
"name"] = group.second.name;
511 root[
"sorting_weight"] = group.second.weight;
532 int fd = rsp->
fd_.exchange(0);
533 ESP_LOGD(TAG,
"Event source connection closed (fd: %d)", fd);
550 this->deferred_queue_.push_back(item);
579 if (bytes_sent == HTTPD_SOCK_ERR_TIMEOUT) {
588 ESP_LOGW(TAG,
"Closing stuck EventSource connection after %" PRIu16
" failed sends",
595 if (bytes_sent == HTTPD_SOCK_ERR_FAIL) {
599 if (bytes_sent <= 0) {
601 ESP_LOGW(TAG,
"Unexpected send result: %d", bytes_sent);
611 ESP_LOGV(TAG,
"Partial send: %d/%zu bytes (total: %zu/%zu)", bytes_sent, remaining,
event_bytes_sent_,
629 uint32_t reconnect) {
630 if (this->
fd_.load() == 0) {
641 const char chunk_len_header[] =
" " CRLF_STR;
642 const int chunk_len_header_len =
sizeof(chunk_len_header) - 1;
648 constexpr size_t num_buf_size = 32;
649 char num_buf[num_buf_size];
652 int len = snprintf(num_buf, num_buf_size,
"retry: %" PRIu32 CRLF_STR, reconnect);
657 int len = snprintf(num_buf, num_buf_size,
"id: %" PRIu32 CRLF_STR,
id);
661 if (event && *event) {
681 int chunk_len =
event_buffer_.size() - CRLF_LEN - chunk_len_header_len;
682 char chunk_len_str[9];
683 snprintf(chunk_len_str, 9,
"%08x", chunk_len);
699 if (source ==
nullptr)
701 if (event_type ==
nullptr)
703 if (message_generator ==
nullptr)
706 if (0 != strcmp(event_type,
"state_detail_all") && 0 != strcmp(event_type,
"state")) {
707 ESP_LOGE(TAG,
"Can't defer non-state event");
726#ifdef USE_WEBSERVER_OTA
728 static constexpr size_t MULTIPART_CHUNK_SIZE = 1460;
729 static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024;
732 const char *boundary_start;
735 ESP_LOGE(TAG,
"Failed to parse multipart boundary");
736 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
743 if (
h->canHandle(&req)) {
750 ESP_LOGW(TAG,
"No handler found for OTA request");
751 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND,
nullptr);
756 std::string filename;
759 auto reader = std::make_unique<MultipartReader>(
"--" + std::string(boundary_start, boundary_len));
762 reader->set_data_callback([&](
const uint8_t *data,
size_t len) {
763 if (!reader->has_file() || !
len)
766 if (filename.empty()) {
767 filename = reader->get_current_part().filename;
768 ESP_LOGV(TAG,
"Processing file: '%s'", filename.c_str());
769 handler->
handleUpload(&req, filename, 0,
nullptr, 0,
false);
772 handler->
handleUpload(&req, filename, index,
const_cast<uint8_t *
>(data),
len,
false);
776 reader->set_part_complete_callback([&]() {
778 handler->
handleUpload(&req, filename, index,
nullptr, 0,
true);
785 std::unique_ptr<char[]> buffer(
new char[MULTIPART_CHUNK_SIZE]);
786 size_t bytes_since_yield = 0;
788 for (
size_t remaining = r->content_len; remaining > 0;) {
789 int recv_len = httpd_req_recv(r, buffer.get(), std::min(remaining, MULTIPART_CHUNK_SIZE));
792 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
794 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
797 if (reader->parse(buffer.get(), recv_len) !=
static_cast<size_t>(recv_len)) {
798 ESP_LOGW(TAG,
"Multipart parser error");
799 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
803 remaining -= recv_len;
804 bytes_since_yield += recv_len;
806 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
808 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_
void set_lru_purge_enable(bool enable)
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
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.
std::string str_sprintf(const char *fmt,...)
uint32_t IRAM_ATTR HOT millis()
message_generator_t * message_generator_