LibHTTP: Fix issues with HTTP POST request and requests with a body

The previous implementation created invalid HTTP requests in cases
where the request method was POST or when the request contained a
body. There were two bugs for these cases:

1) the 'Content-Type' header was sent twice
2) a stray CRLF was appended to the request
This commit is contained in:
Uku Loskit 2023-10-29 23:38:54 +02:00 committed by Andreas Kling
parent 549dee4db1
commit 98ad5a7141
Notes: sideshowbarker 2024-07-17 16:23:06 +09:00

View File

@ -62,17 +62,28 @@ ErrorOr<ByteBuffer> HttpRequest::to_raw_request() const
if (m_url.port().has_value())
TRY(builder.try_appendff(":{}", *m_url.port()));
TRY(builder.try_append("\r\n"sv));
// Start headers.
bool has_content_length = false;
for (auto& header : m_headers) {
if (header.name.equals_ignoring_ascii_case("Content-Length"sv))
has_content_length = true;
TRY(builder.try_append(header.name));
TRY(builder.try_append(": "sv));
TRY(builder.try_append(header.value));
TRY(builder.try_append("\r\n"sv));
}
if (!m_body.is_empty() || method() == Method::POST) {
TRY(builder.try_appendff("Content-Length: {}\r\n\r\n", m_body.size()));
// Add Content-Length header if it's not already present.
if (!has_content_length) {
TRY(builder.try_appendff("Content-Length: {}\r\n", m_body.size()));
}
// Finish headers.
TRY(builder.try_append("\r\n"sv));
TRY(builder.try_append((char const*)m_body.data(), m_body.size()));
} else {
// Finish headers.
TRY(builder.try_append("\r\n"sv));
}
TRY(builder.try_append("\r\n"sv));
return builder.to_byte_buffer();
}