From 98ad5a71419906ce53cbe9ef2ab86b4678530e9a Mon Sep 17 00:00:00 2001 From: Uku Loskit Date: Sun, 29 Oct 2023 23:38:54 +0200 Subject: [PATCH] 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 --- Userland/Libraries/LibHTTP/HttpRequest.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Userland/Libraries/LibHTTP/HttpRequest.cpp b/Userland/Libraries/LibHTTP/HttpRequest.cpp index 41c85a05663..d8196f549d7 100644 --- a/Userland/Libraries/LibHTTP/HttpRequest.cpp +++ b/Userland/Libraries/LibHTTP/HttpRequest.cpp @@ -62,17 +62,28 @@ ErrorOr 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(); }