11#include "esp_tls_crypto.h"
12#include <freertos/FreeRTOS.h>
13#include <freertos/task.h>
18#ifdef USE_WEBSERVER_OTA
19#include <multipart_parser.h>
29namespace web_server_idf {
32#define HTTPD_409 "409 Conflict"
35#define CRLF_STR "\r\n"
36#define CRLF_LEN (sizeof(CRLF_STR) - 1)
38static const char *
const TAG =
"web_server_idf";
44DefaultHeaders default_headers_instance;
60 httpd_config_t config = HTTPD_DEFAULT_CONFIG();
61 config.server_port = this->
port_;
62 config.uri_match_fn = [](
const char * ,
const char * ,
size_t ) {
return true; };
63 if (httpd_start(&this->
server_, &config) == ESP_OK) {
64 const httpd_uri_t handler_get = {
70 httpd_register_uri_handler(this->
server_, &handler_get);
72 const httpd_uri_t handler_post = {
78 httpd_register_uri_handler(this->
server_, &handler_post);
80 const httpd_uri_t handler_options = {
82 .method = HTTP_OPTIONS,
86 httpd_register_uri_handler(this->
server_, &handler_options);
91 ESP_LOGVV(TAG,
"Enter AsyncWebServer::request_post_handler. uri=%s", r->uri);
95 ESP_LOGW(TAG,
"Content length is required for post: %s", r->uri);
96 httpd_resp_send_err(r, HTTPD_411_LENGTH_REQUIRED,
nullptr);
100 if (content_type.has_value()) {
101 const char *content_type_char = content_type.value().c_str();
104 if (
stristr(content_type_char,
"application/x-www-form-urlencoded") !=
nullptr) {
106#ifdef USE_WEBSERVER_OTA
107 }
else if (
stristr(content_type_char,
"multipart/form-data") !=
nullptr) {
112 ESP_LOGW(TAG,
"Unsupported content type for POST: %s", content_type_char);
119 if (r->content_len > CONFIG_HTTPD_MAX_REQ_HDR_LEN) {
120 ESP_LOGW(TAG,
"Request size is to big: %zu", r->content_len);
121 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
125 std::string post_query;
126 if (r->content_len > 0) {
127 post_query.resize(r->content_len);
128 const int ret = httpd_req_recv(r, &post_query[0], r->content_len + 1);
130 if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
131 httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT,
nullptr);
132 return ESP_ERR_TIMEOUT;
134 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
144 ESP_LOGVV(TAG,
"Enter AsyncWebServer::request_handler. method=%u, uri=%s", r->method, r->uri);
151 if (handler->canHandle(request)) {
154 handler->handleRequest(request);
162 return ESP_ERR_NOT_FOUND;
167 for (
const auto &pair : this->
params_) {
179 auto *str = strchr(this->
req_->uri,
'?');
180 if (str ==
nullptr) {
181 return this->
req_->uri;
183 return std::string(this->
req_->uri, str - this->req_->uri);
195 httpd_resp_send(*
this, content, HTTPD_RESP_USE_STRLEN);
197 httpd_resp_send(*
this,
nullptr, 0);
202 httpd_resp_set_status(*
this,
"302 Found");
203 httpd_resp_set_hdr(*
this,
"Location",
url.c_str());
204 httpd_resp_send(*
this,
nullptr, 0);
208 httpd_resp_set_status(*
this, code == 200 ? HTTPD_200
209 : code == 404 ? HTTPD_404
210 : code == 409 ? HTTPD_409
211 : to_string(code).c_str());
213 if (content_type && *content_type) {
214 httpd_resp_set_type(*
this, content_type);
216 httpd_resp_set_hdr(*
this,
"Accept-Ranges",
"none");
219 httpd_resp_set_hdr(*
this, pair.first.c_str(), pair.second.c_str());
226#ifdef USE_WEBSERVER_AUTH
228 if (username ==
nullptr || password ==
nullptr || *username == 0) {
231 auto auth = this->
get_header(
"Authorization");
232 if (!auth.has_value()) {
236 auto *auth_str = auth.value().c_str();
238 const auto auth_prefix_len =
sizeof(
"Basic ") - 1;
239 if (strncmp(
"Basic ", auth_str, auth_prefix_len) != 0) {
240 ESP_LOGW(TAG,
"Only Basic authorization supported yet");
244 std::string user_info;
245 user_info += username;
247 user_info += password;
250 esp_crypto_base64_encode(
nullptr, 0, &n,
reinterpret_cast<const uint8_t *
>(user_info.c_str()), user_info.size());
252 auto digest = std::unique_ptr<char[]>(
new char[n + 1]);
253 esp_crypto_base64_encode(
reinterpret_cast<uint8_t *
>(digest.get()), n, &out,
254 reinterpret_cast<const uint8_t *
>(user_info.c_str()), user_info.size());
256 return strncmp(digest.get(), auth_str + auth_prefix_len, auth.value().size() - auth_prefix_len) == 0;
260 httpd_resp_set_hdr(*
this,
"Connection",
"keep-alive");
261 auto auth_val =
str_sprintf(
"Basic realm=\"%s\"", realm ? realm :
"Login Required");
262 httpd_resp_set_hdr(*
this,
"WWW-Authenticate", auth_val.c_str());
263 httpd_resp_send_err(*
this, HTTPD_401_UNAUTHORIZED,
nullptr);
268 auto find = this->
params_.find(name);
269 if (find != this->
params_.end()) {
274 if (!
val.has_value()) {
276 if (url_query.has_value()) {
282 if (
val.has_value()) {
285 this->
params_.insert({name, param});
290 httpd_resp_set_hdr(*this->
req_, name, value);
299 const int length = vsnprintf(
nullptr, 0, fmt, args);
306 vsnprintf(&str[0],
length + 1, fmt, args);
336 if (ses->fd_.load() == 0) {
337 ESP_LOGD(TAG,
"Removing dead event source session");
349 if (ses->fd_.load() != 0) {
350 ses->try_send_nodefer(message, event,
id, reconnect);
358 if (ses->fd_.load() != 0) {
359 ses->deferrable_send_state(source, event_type, message_generator);
367 : server_(server), web_server_(ws), entities_iterator_(new
esphome::web_server::ListEntitiesIterator(ws, server)) {
368 httpd_req_t *req = *request;
370 httpd_resp_set_status(req, HTTPD_200);
371 httpd_resp_set_type(req,
"text/event-stream");
372 httpd_resp_set_hdr(req,
"Cache-Control",
"no-cache");
373 httpd_resp_set_hdr(req,
"Connection",
"keep-alive");
376 httpd_resp_set_hdr(req, pair.first.c_str(), pair.second.c_str());
379 httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);
381 req->sess_ctx =
this;
384 this->
hd_ = req->handle;
385 this->
fd_.store(httpd_req_to_sockfd(req));
392#ifdef USE_WEBSERVER_SORTING
396 root[
"name"] = group.second.name;
397 root[
"sorting_weight"] = group.second.weight;
418 ESP_LOGD(TAG,
"Event source connection closed (fd: %d)", rsp->fd_.load());
435 this->deferred_queue_.push_back(item);
463 if (bytes_sent == HTTPD_SOCK_ERR_TIMEOUT || bytes_sent == HTTPD_SOCK_ERR_FAIL) {
484 uint32_t reconnect) {
485 if (this->
fd_.load() == 0) {
496 const char chunk_len_header[] =
" " CRLF_STR;
497 const int chunk_len_header_len =
sizeof(chunk_len_header) - 1;
513 if (event && *event) {
519 if (message && *message) {
533 int chunk_len =
event_buffer_.size() - CRLF_LEN - chunk_len_header_len;
534 char chunk_len_str[9];
535 snprintf(chunk_len_str, 9,
"%08x", chunk_len);
551 if (source ==
nullptr)
553 if (event_type ==
nullptr)
555 if (message_generator ==
nullptr)
558 if (0 != strcmp(event_type,
"state_detail_all") && 0 != strcmp(event_type,
"state")) {
559 ESP_LOGE(TAG,
"Can't defer non-state event");
570 std::string message = message_generator(
web_server_, source);
578#ifdef USE_WEBSERVER_OTA
580 static constexpr size_t MULTIPART_CHUNK_SIZE = 1460;
581 static constexpr size_t YIELD_INTERVAL_BYTES = 16 * 1024;
584 const char *boundary_start;
587 ESP_LOGE(TAG,
"Failed to parse multipart boundary");
588 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
595 if (
h->canHandle(&req)) {
602 ESP_LOGW(TAG,
"No handler found for OTA request");
603 httpd_resp_send_err(r, HTTPD_404_NOT_FOUND,
nullptr);
608 std::string filename;
611 auto reader = std::make_unique<MultipartReader>(
"--" + std::string(boundary_start, boundary_len));
614 reader->set_data_callback([&](
const uint8_t *data,
size_t len) {
615 if (!reader->has_file() || !
len)
618 if (filename.empty()) {
619 filename = reader->get_current_part().filename;
620 ESP_LOGV(TAG,
"Processing file: '%s'", filename.c_str());
621 handler->
handleUpload(&req, filename, 0,
nullptr, 0,
false);
624 handler->
handleUpload(&req, filename, index,
const_cast<uint8_t *
>(data),
len,
false);
628 reader->set_part_complete_callback([&]() {
630 handler->
handleUpload(&req, filename, index,
nullptr, 0,
true);
637 std::unique_ptr<char[]> buffer(
new char[MULTIPART_CHUNK_SIZE]);
638 size_t bytes_since_yield = 0;
640 for (
size_t remaining = r->content_len; remaining > 0;) {
641 int recv_len = httpd_req_recv(r, buffer.get(), std::min(remaining, MULTIPART_CHUNK_SIZE));
644 httpd_resp_send_err(r, recv_len == HTTPD_SOCK_ERR_TIMEOUT ? HTTPD_408_REQ_TIMEOUT : HTTPD_400_BAD_REQUEST,
646 return recv_len == HTTPD_SOCK_ERR_TIMEOUT ? ESP_ERR_TIMEOUT : ESP_FAIL;
649 if (reader->parse(buffer.get(), recv_len) !=
static_cast<size_t>(recv_len)) {
650 ESP_LOGW(TAG,
"Multipart parser error");
651 httpd_resp_send_err(r, HTTPD_400_BAD_REQUEST,
nullptr);
655 remaining -= recv_len;
656 bytes_since_yield += recv_len;
658 if (bytes_since_yield > YIELD_INTERVAL_BYTES) {
660 bytes_since_yield = 0;
void begin(bool include_internal=false)
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::set< 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)
std::unique_ptr< esphome::web_server::ListEntitiesIterator > entities_iterator_
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)
std::map< std::string, AsyncWebParameter * > params_
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
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)
std::string build_json(const json_build_t &f)
Build a JSON string with the provided json build function.
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_