3#include "log_sanitize.h"
4#include "origin_check.h"
5#include <esp32-hal-log.h>
6#include <esp_http_server.h>
12#if !CONFIG_HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT || !CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT
14#error "needs CONFIG_HTTPD_WS_PRE/POST_HANDSHAKE_CB_SUPPORT=y (custom_sdkconfig in platformio.ini)"
18enum class HeaderStatus {
28inline HeaderStatus read_header(httpd_req_t* req,
const char* name,
char* buf,
size_t cap,
size_t* len)
31 const size_t n = httpd_req_get_hdr_value_len(req, name);
34 return HeaderStatus::Absent;
36 if (n >= cap || httpd_req_get_hdr_value_str(req, name, buf, cap) != ESP_OK)
38 return HeaderStatus::TooLong;
41 return HeaderStatus::Ok;
55inline bool handshake_origin_ok(httpd_req_t* req,
const char* tag,
bool any_port =
false)
57 constexpr size_t kHdrBuf = 128;
60 size_t origin_len = 0;
63 const bool origin_too_long = read_header(req,
"Origin", origin, kHdrBuf, &origin_len) == HeaderStatus::TooLong;
64 if (read_header(req,
"Host", host, kHdrBuf, &host_len) != HeaderStatus::Ok)
71 ESP_LOGW(tag,
"request refused: Origin header too long");
74 const std::string_view o(origin, origin_len);
75 const std::string_view h(host, host_len);
76 if (!(any_port ? remote::origin_allowed_any_port(o, h) : remote::origin_allowed(o, h)))
79 remote::sanitize_for_log(origin, origin_len, safe,
sizeof(safe));
80 ESP_LOGW(tag,
"request refused: Origin %s", safe);
@ Ok
out holds exactly the stored bytes
@ Absent
the key does not exist (stored length 0)