fix: improve error handling for size directive and chunked body parsing

This commit is contained in:
whaffman 2025-10-16 01:14:54 +02:00
parent 67ab96f9da
commit 377ff71e1e
4 changed files with 24 additions and 8 deletions

View File

@ -25,7 +25,14 @@ void SizeDirective::parse(const std::string &value)
{
throw std::invalid_argument("Invalid size directive: " + value);
}
try
{
value_ = std::stoul(number, &idx);
}
catch (const std::exception &e)
{
throw std::invalid_argument("Invalid size directive: " + value + " - " + e.what());
}
if (idx == number.size())
{
return;
@ -33,15 +40,15 @@ void SizeDirective::parse(const std::string &value)
std::string suffix = number.substr(idx);
if (suffix == "k")
{
multiplier = 1024;
multiplier = 1024UL;
}
else if (suffix == "m")
{
multiplier = 1024 * 1024;
multiplier = 1024UL * 1024UL;
}
else if (suffix == "g")
{
multiplier = 1024 * 1024 * 1024;
multiplier = 1024UL * 1024UL * 1024UL;
}
else
{

View File

@ -7,7 +7,7 @@
#include <cctype> // for tolower
#include <utility> // for pair
std::optional<size_t> HttpHeaders::getContentLength() const noexcept
std::optional<size_t> HttpHeaders::getContentLength() const
{
const auto &value = this->get("Content-Length");
if (value.empty())

View File

@ -26,7 +26,7 @@ class HttpHeaders
void remove(const std::string &name) noexcept;
[[nodiscard]] std::string toString() const noexcept;
[[nodiscard]] std::optional<size_t> getContentLength() const noexcept;
[[nodiscard]] std::optional<size_t> getContentLength() const;
[[nodiscard]] std::optional<std::string> getContentType() const noexcept;
[[nodiscard]] std::optional<std::string> getHost() const noexcept;

View File

@ -182,8 +182,17 @@ bool HttpRequest::parseBufferforChunkedBody()
}
std::string chunkSizeStr = buffer_.substr(0, pos);
Log::debug("Chunk size string: " + chunkSizeStr);
size_t chunkSize = utils::stoul(chunkSizeStr, 16);
Log::warning("Invalid chunk size: " + chunkSizeStr);
size_t chunkSize = 0;
try
{
chunkSize = utils::stoul(chunkSizeStr, 16);
}
catch (const std::exception &e)
{
Log::warning("Invalid chunk size: " + chunkSizeStr + " - " + e.what());
setState(State::ParseError);
return false;
}
if (chunkSize == 0)
{
setState(State::Complete); // Last chunk