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;
101 httpd_config_t config = HTTPD_DEFAULT_CONFIG();
102 config.server_port = this->
port_;
103 config.uri_match_fn = [](
const char * ,
const char * ,
size_t ) {
return true; };
104 if (httpd_start(&this->
server_, &config) == ESP_OK) {
105 const httpd_uri_t handler_get = {
111 httpd_register_uri_handler(this->
server_, &handler_get);
113 const httpd_uri_t handler_post = {
119 httpd_register_uri_handler(this->
server_, &handler_post);
121 const httpd_uri_t handler_options = {
123 .method = HTTP_OPTIONS,
127 httpd_register_uri_handler(this->
server_, &handler_options);
132 ESP_LOGVV(TAG,
"Enter AsyncWebServer::request_post_handler. uri=%s", r->uri);
136 ESP_LOGW(TAG,
"Content length is required for post: %s", r->uri);
137 httpd_resp_send_err(r, HTTPD_411_LENGTH_REQUIRED,
nullptr);
141 if (content_type.has_value()) {
142 const char *content_type_char = content_type.value().c_str();
145 if (
stristr(content_type_char,
"application/x-www-form-urlencoded") !=
nullptr) {
147#ifdef USE_WEBSERVER_OTA
148 }
else if (
stristr(content_type_char,
"multipart/form-data") !=
nullptr) {
153 ESP_LOGW(TAG,
"Unsupported content type for POST: %s", content_type_char);
160 if (r->content_len > CONFIG_HTTPD_MAX_REQ_HDR_LEN) {
161 ESP_LOGW(TAG,
"Request size is to big: %zu", r->content_len);
162 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
166 std::string post_query;
167 if (r->content_len > 0) {
168 post_query.resize(r->content_len);
169 const int ret = httpd_req_recv(r, &post_query[0], r->content_len + 1);
171 if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
172 httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT,
nullptr);
173 return ESP_ERR_TIMEOUT;
175 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
185 ESP_LOGVV(TAG,
"Enter AsyncWebServer::request_handler. method=%u, uri=%s", r->method, r->uri);
192 if (handler->canHandle(request)) {
195 handler->handleRequest(request);
203 return ESP_ERR_NOT_FOUND;
208 for (
auto *param : this->
params_) {
220 auto *str = strchr(this->
req_->uri,
'?');
221 if (str ==
nullptr) {
222 return this->
req_->uri;
224 return std::string(this->
req_->uri, str - this->req_->uri);
236 httpd_resp_send(*
this, content, HTTPD_RESP_USE_STRLEN);
238 httpd_resp_send(*
this,
nullptr, 0);
243 httpd_resp_set_status(*
this,
"302 Found");
244 httpd_resp_set_hdr(*
this,
"Location",
url.c_str());
245 httpd_resp_send(*
this,
nullptr, 0);
265 httpd_resp_set_status(*
this,
status);
267 if (content_type && *content_type) {
268 httpd_resp_set_type(*
this, content_type);
270 httpd_resp_set_hdr(*
this,
"Accept-Ranges",
"none");
273 httpd_resp_set_hdr(*
this, pair.first.c_str(), pair.second.c_str());
280#ifdef USE_WEBSERVER_AUTH
282 if (username ==
nullptr || password ==
nullptr || *username == 0) {
285 auto auth = this->
get_header(
"Authorization");
286 if (!auth.has_value()) {
290 auto *auth_str = auth.value().c_str();
292 const auto auth_prefix_len =
sizeof(
"Basic ") - 1;
293 if (strncmp(
"Basic ", auth_str, auth_prefix_len) != 0) {
294 ESP_LOGW(TAG,
"Only Basic authorization supported yet");
298 std::string user_info;
299 user_info += username;
301 user_info += password;
304 esp_crypto_base64_encode(
nullptr, 0, &n,
reinterpret_cast<const uint8_t *
>(user_info.c_str()), user_info.size());
306 auto digest = std::unique_ptr<char[]>(
new char[n + 1]);
307 esp_crypto_base64_encode(
reinterpret_cast<uint8_t *
>(digest.get()), n, &out,
308 reinterpret_cast<const uint8_t *
>(user_info.c_str()), user_info.size());
310 return strcmp(digest.get(), auth_str + auth_prefix_len) == 0;
314 httpd_resp_set_hdr(*
this,
"Connection",
"keep-alive");
315 auto auth_val =
str_sprintf(
"Basic realm=\"%s\"", realm ? realm :
"Login Required");
316 httpd_resp_set_hdr(*
this,
"WWW-Authenticate", auth_val.c_str());
317 httpd_resp_send_err(*
this, HTTPD_401_UNAUTHORIZED,
nullptr);
323 for (
auto *param : this->
params_) {
324 if (param->name() == name) {
331 if (!
val.has_value()) {
333 if (url_query.has_value()) {
340 if (!
val.has_value()) {
345 this->params_.push_back(param);
350 httpd_resp_set_hdr(*this->
req_, name, value);
357 int len = snprintf(buf,
sizeof(buf),
"%f", value);
365 const int length = vsnprintf(
nullptr, 0, fmt, args);
372 vsnprintf(&str[0],
length + 1, fmt, args);
398 for (
size_t i = 0; i < this->
sessions_.size();) {
401 if (ses->fd_.load() == 0) {
402 ESP_LOGD(TAG,
"Removing dead event source session");
416 if (ses->fd_.load() != 0) {
417 ses->try_send_nodefer(
message, event,
id, reconnect);
428 if (ses->fd_.load() != 0) {
429 ses->deferrable_send_state(source, event_type, message_generator);
437 : server_(server), web_server_(ws), entities_iterator_(new
esphome::web_server::ListEntitiesIterator(ws, server)) {
438 httpd_req_t *req = *request;
440 httpd_resp_set_status(req, HTTPD_200);
441 httpd_resp_set_type(req,
"text/event-stream");
442 httpd_resp_set_hdr(req,
"Cache-Control",
"no-cache");
443 httpd_resp_set_hdr(req,
"Connection",
"keep-alive");
446 httpd_resp_set_hdr(req, pair.first.c_str(), pair.second.c_str());
449 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
451 req->sess_ctx =
this;
454 this->
hd_ = req->handle;
455 this->
fd_.store(httpd_req_to_sockfd(req));
458 httpd_sess_set_send_override(this->
hd_, this->
fd_.load(), nonblocking_send);
465#ifdef USE_WEBSERVER_SORTING
469 JsonObject root = builder.
root();
470 root[
"name"] = group.second.name;
471 root[
"sorting_weight"] = group.second.weight;
492 ESP_LOGD(TAG,
"Event source connection closed (fd: %d)", rsp->fd_.load());
508 this->deferred_queue_.push_back(item);
537 if (bytes_sent == HTTPD_SOCK_ERR_TIMEOUT) {
546 ESP_LOGW(TAG,
"Closing stuck EventSource connection after %" PRIu16
" failed sends",
553 if (bytes_sent == HTTPD_SOCK_ERR_FAIL) {
557 if (bytes_sent <= 0) {
559 ESP_LOGW(TAG,
"Unexpected send result: %d", bytes_sent);
569 ESP_LOGV(TAG,
"Partial send: %d/%zu bytes (total: %zu/%zu)", bytes_sent, remaining,
event_bytes_sent_,
587 uint32_t reconnect) {
588 if (this->
fd_.load() == 0) {
599 const char chunk_len_header[] =
" " CRLF_STR;
600 const int chunk_len_header_len =
sizeof(chunk_len_header) - 1;
606 constexpr size_t num_buf_size = 32;
607 char num_buf[num_buf_size];
610 int len = snprintf(num_buf, num_buf_size,
"retry: %" PRIu32 CRLF_STR, reconnect);
615 int len = snprintf(num_buf, num_buf_size,
"id: %" PRIu32 CRLF_STR,
id);
619 if (event && *event) {
639 int chunk_len =
event_buffer_.size() - CRLF_LEN - chunk_len_header_len;
640 char chunk_len_str[9];
641 snprintf(chunk_len_str, 9,
"%08x", chunk_len);
657 if (source ==
nullptr)
659 if (event_type ==
nullptr)
661 if (message_generator ==
nullptr)
664 if (0 != strcmp(event_type,
"state_detail_all") && 0 != strcmp(event_type,
"state")) {
665 ESP_LOGE(TAG,
"Can't defer non-state event");
684#ifdef USE_WEBSERVER_OTA
686 static constexpr size_t MULTIPART_CHUNK_SIZE = 1460;
687 static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024;
690 const char *boundary_start;
693 ESP_LOGE(TAG,
"Failed to parse multipart boundary");
694 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
701 if (
h->canHandle(&req)) {
708 ESP_LOGW(TAG,
"No handler found for OTA request");
709 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND,
nullptr);
714 std::string filename;
717 auto reader = std::make_unique<MultipartReader>(
"--" + std::string(boundary_start, boundary_len));
720 reader->set_data_callback([&](
const uint8_t *data,
size_t len) {
721 if (!reader->has_file() || !
len)
724 if (filename.empty()) {
725 filename = reader->get_current_part().filename;
726 ESP_LOGV(TAG,
"Processing file: '%s'", filename.c_str());
727 handler->
handleUpload(&req, filename, 0,
nullptr, 0,
false);
730 handler->
handleUpload(&req, filename, index,
const_cast<uint8_t *
>(data),
len,
false);
734 reader->set_part_complete_callback([&]() {
736 handler->
handleUpload(&req, filename, index,
nullptr, 0,
true);
743 std::unique_ptr<char[]> buffer(
new char[MULTIPART_CHUNK_SIZE]);
744 size_t bytes_since_yield = 0;
746 for (
size_t remaining = r->content_len; remaining > 0;) {
747 int recv_len = httpd_req_recv(r, buffer.get(), std::min(remaining, MULTIPART_CHUNK_SIZE));
750 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
752 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
755 if (reader->parse(buffer.get(), recv_len) !=
static_cast<size_t>(recv_len)) {
756 ESP_LOGW(TAG,
"Multipart parser error");
757 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
761 remaining -= recv_len;
762 bytes_since_yield += recv_len;
764 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
766 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 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_