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 *str = strchr(this->
req_->uri,
'?');
251 if (str ==
nullptr) {
252 return this->
req_->uri;
254 return std::string(this->
req_->uri, str - this->req_->uri);
266 httpd_resp_send(*
this, content, HTTPD_RESP_USE_STRLEN);
268 httpd_resp_send(*
this,
nullptr, 0);
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);
296 httpd_resp_set_status(*
this,
status);
298 if (content_type && *content_type) {
299 httpd_resp_set_type(*
this, content_type);
301 httpd_resp_set_hdr(*
this,
"Accept-Ranges",
"none");
304 httpd_resp_set_hdr(*
this, pair.first.c_str(), pair.second.c_str());
311#ifdef USE_WEBSERVER_AUTH
313 if (username ==
nullptr || password ==
nullptr || *username == 0) {
316 auto auth = this->
get_header(
"Authorization");
317 if (!auth.has_value()) {
321 auto *auth_str = auth.value().c_str();
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");
329 std::string user_info;
330 user_info += username;
332 user_info += password;
335 esp_crypto_base64_encode(
nullptr, 0, &n,
reinterpret_cast<const uint8_t *
>(user_info.c_str()), user_info.size());
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());
341 return strcmp(digest.get(), auth_str + auth_prefix_len) == 0;
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);
354 for (
auto *param : this->
params_) {
355 if (param->name() == name) {
362 if (!
val.has_value()) {
364 if (url_query.has_value()) {
371 if (!
val.has_value()) {
376 this->params_.push_back(param);
381 httpd_resp_set_hdr(*this->
req_, name, value);
388 int len = snprintf(buf,
sizeof(buf),
"%f", value);
396 const int length = vsnprintf(
nullptr, 0, fmt, args);
403 vsnprintf(&str[0],
length + 1, fmt, args);
429 for (
size_t i = 0; i < this->
sessions_.size();) {
432 if (ses->fd_.load() == 0) {
433 ESP_LOGD(TAG,
"Removing dead event source session");
447 if (ses->fd_.load() != 0) {
448 ses->try_send_nodefer(
message, event,
id, reconnect);
459 if (ses->fd_.load() != 0) {
460 ses->deferrable_send_state(source, event_type, message_generator);
468 : server_(server), web_server_(ws), entities_iterator_(new
esphome::web_server::ListEntitiesIterator(ws, server)) {
469 httpd_req_t *req = *request;
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");
477 httpd_resp_set_hdr(req, pair.first.c_str(), pair.second.c_str());
480 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
482 req->sess_ctx =
this;
485 this->
hd_ = req->handle;
486 this->
fd_.store(httpd_req_to_sockfd(req));
489 httpd_sess_set_send_override(this->
hd_, this->
fd_.load(), nonblocking_send);
496#ifdef USE_WEBSERVER_SORTING
500 JsonObject root = builder.
root();
501 root[
"name"] = group.second.name;
502 root[
"sorting_weight"] = group.second.weight;
523 int fd = rsp->
fd_.exchange(0);
524 ESP_LOGD(TAG,
"Event source connection closed (fd: %d)", fd);
541 this->deferred_queue_.push_back(item);
570 if (bytes_sent == HTTPD_SOCK_ERR_TIMEOUT) {
579 ESP_LOGW(TAG,
"Closing stuck EventSource connection after %" PRIu16
" failed sends",
586 if (bytes_sent == HTTPD_SOCK_ERR_FAIL) {
590 if (bytes_sent <= 0) {
592 ESP_LOGW(TAG,
"Unexpected send result: %d", bytes_sent);
602 ESP_LOGV(TAG,
"Partial send: %d/%zu bytes (total: %zu/%zu)", bytes_sent, remaining,
event_bytes_sent_,
620 uint32_t reconnect) {
621 if (this->
fd_.load() == 0) {
632 const char chunk_len_header[] =
" " CRLF_STR;
633 const int chunk_len_header_len =
sizeof(chunk_len_header) - 1;
639 constexpr size_t num_buf_size = 32;
640 char num_buf[num_buf_size];
643 int len = snprintf(num_buf, num_buf_size,
"retry: %" PRIu32 CRLF_STR, reconnect);
648 int len = snprintf(num_buf, num_buf_size,
"id: %" PRIu32 CRLF_STR,
id);
652 if (event && *event) {
665 const char *first_n = strchr(
message,
'\n');
666 const char *first_r = strchr(
message,
'\r');
668 if (first_n ==
nullptr && first_r ==
nullptr) {
675 const char *line_start =
message;
676 size_t msg_len = strlen(
message);
677 const char *msg_end =
message + msg_len;
680 const char *next_n = first_n;
681 const char *next_r = first_r;
683 while (line_start <= msg_end) {
684 const char *line_end;
685 const char *next_line;
687 if (next_n ==
nullptr && next_r ==
nullptr) {
696 if (next_n !=
nullptr && next_r !=
nullptr) {
697 if (next_r + 1 == next_n) {
700 next_line = next_n + 1;
703 line_end = (next_r < next_n) ? next_r : next_n;
704 next_line = line_end + 1;
706 }
else if (next_n !=
nullptr) {
709 next_line = next_n + 1;
713 next_line = next_r + 1;
721 line_start = next_line;
724 if (line_start >= msg_end) {
729 next_n = strchr(line_start,
'\n');
730 next_r = strchr(line_start,
'\r');
738 if (
event_buffer_.size() ==
static_cast<size_t>(chunk_len_header_len)) {
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);
765 if (source ==
nullptr)
767 if (event_type ==
nullptr)
769 if (message_generator ==
nullptr)
772 if (0 != strcmp(event_type,
"state_detail_all") && 0 != strcmp(event_type,
"state")) {
773 ESP_LOGE(TAG,
"Can't defer non-state event");
792#ifdef USE_WEBSERVER_OTA
794 static constexpr size_t MULTIPART_CHUNK_SIZE = 1460;
795 static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024;
798 const char *boundary_start;
801 ESP_LOGE(TAG,
"Failed to parse multipart boundary");
802 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
809 if (
h->canHandle(&req)) {
816 ESP_LOGW(TAG,
"No handler found for OTA request");
817 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND,
nullptr);
822 std::string filename;
825 auto reader = std::make_unique<MultipartReader>(
"--" + std::string(boundary_start, boundary_len));
828 reader->set_data_callback([&](
const uint8_t *data,
size_t len) {
829 if (!reader->has_file() || !
len)
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);
838 handler->
handleUpload(&req, filename, index,
const_cast<uint8_t *
>(data),
len,
false);
842 reader->set_part_complete_callback([&]() {
844 handler->
handleUpload(&req, filename, index,
nullptr, 0,
true);
851 std::unique_ptr<char[]> buffer(
new char[MULTIPART_CHUNK_SIZE]);
852 size_t bytes_since_yield = 0;
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));
858 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
860 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
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);
869 remaining -= recv_len;
870 bytes_since_yield += recv_len;
872 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
874 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
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_