[web_server_idf] Reduce heap usage in DefaultHeaders and auth (#13141)

This commit is contained in:
J. Nick Koston
2026-01-11 17:17:57 -10:00
committed by GitHub
parent 6a3737bac3
commit 684790c2ab
5 changed files with 36 additions and 12 deletions

View File

@@ -309,8 +309,8 @@ void AsyncWebServerRequest::init_response_(AsyncWebServerResponse *rsp, int code
}
httpd_resp_set_hdr(*this, "Accept-Ranges", "none");
for (const auto &pair : DefaultHeaders::Instance().headers_) {
httpd_resp_set_hdr(*this, pair.first.c_str(), pair.second.c_str());
for (const auto &header : DefaultHeaders::Instance().headers_) {
httpd_resp_set_hdr(*this, header.name, header.value);
}
delete this->rsp_;
@@ -335,17 +335,29 @@ bool AsyncWebServerRequest::authenticate(const char *username, const char *passw
return false;
}
std::string user_info;
user_info += username;
user_info += ':';
user_info += password;
// Build user:pass in stack buffer to avoid heap allocation
constexpr size_t max_user_info_len = 256;
char user_info[max_user_info_len];
size_t user_len = strlen(username);
size_t pass_len = strlen(password);
size_t user_info_len = user_len + 1 + pass_len;
if (user_info_len >= max_user_info_len) {
ESP_LOGW(TAG, "Credentials too long for authentication");
return false;
}
memcpy(user_info, username, user_len);
user_info[user_len] = ':';
memcpy(user_info + user_len + 1, password, pass_len);
user_info[user_info_len] = '\0';
size_t n = 0, out;
esp_crypto_base64_encode(nullptr, 0, &n, reinterpret_cast<const uint8_t *>(user_info.c_str()), user_info.size());
esp_crypto_base64_encode(nullptr, 0, &n, reinterpret_cast<const uint8_t *>(user_info), user_info_len);
auto digest = std::unique_ptr<char[]>(new char[n + 1]);
esp_crypto_base64_encode(reinterpret_cast<uint8_t *>(digest.get()), n, &out,
reinterpret_cast<const uint8_t *>(user_info.c_str()), user_info.size());
reinterpret_cast<const uint8_t *>(user_info), user_info_len);
return strcmp(digest.get(), auth_str + auth_prefix_len) == 0;
}
@@ -483,8 +495,8 @@ AsyncEventSourceResponse::AsyncEventSourceResponse(const AsyncWebServerRequest *
httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
httpd_resp_set_hdr(req, "Connection", "keep-alive");
for (const auto &pair : DefaultHeaders::Instance().headers_) {
httpd_resp_set_hdr(req, pair.first.c_str(), pair.second.c_str());
for (const auto &header : DefaultHeaders::Instance().headers_) {
httpd_resp_set_hdr(req, header.name, header.value);
}
httpd_resp_send_chunk(req, CRLF_STR, CRLF_LEN);