Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ add_library(internal
${CMAKE_CURRENT_SOURCE_DIR}/dummy.cpp
${CMAKE_CURRENT_SOURCE_DIR}/url.cpp
${CMAKE_CURRENT_SOURCE_DIR}/headers.cpp
${CMAKE_CURRENT_SOURCE_DIR}/http/request_serializer.cpp
${CMAKE_CURRENT_SOURCE_DIR}/platform/native_socket.cpp
${CMAKE_CURRENT_SOURCE_DIR}/platform/network_runtime.cpp
${CMAKE_CURRENT_SOURCE_DIR}/platform/socket_mode.cpp
Expand Down
240 changes: 240 additions & 0 deletions src/http/request_serializer.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
#include "http/request_serializer.hpp"

#include <charconv>
#include <cstddef>
#include <string>
#include <string_view>
#include <utility>

namespace cpp_request::detail::http {
namespace {

[[nodiscard]] constexpr std::string_view method_token(Method method) noexcept {
switch (method) {
case Method::Get: return "GET";
case Method::Head: return "HEAD";
case Method::Post: return "POST";
case Method::Put: return "PUT";
case Method::Patch: return "PATCH";
case Method::Delete: return "DELETE";
}
return {};
}

[[nodiscard]] constexpr char ascii_lower(char ch) noexcept {
return ch >= 'A' && ch <= 'Z'
? static_cast<char>(ch + ('a' - 'A'))
: ch;
}

[[nodiscard]] bool ascii_iequals(
std::string_view lhs,
std::string_view rhs) noexcept {
if (lhs.size() != rhs.size()) {
return false;
}

for (std::size_t index = 0; index < lhs.size(); ++index) {
if (ascii_lower(lhs[index]) != ascii_lower(rhs[index])) {
return false;
}
}
return true;
}

[[nodiscard]] constexpr bool is_tchar(unsigned char ch) noexcept {
if ((ch >= '0' && ch <= '9')
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z')) {
return true;
}

switch (ch) {
case '!':
case '#':
case '$':
case '%':
case '&':
case '\'':
case '*':
case '+':
case '-':
case '.':
case '^':
case '_':
case '`':
case '|':
case '~':
return true;
default:
return false;
}
}

[[nodiscard]] bool valid_header_name(std::string_view name) noexcept {
if (name.empty()) {
return false;
}

for (const unsigned char ch : name) {
if (!is_tchar(ch)) {
return false;
}
}
return true;
}

[[nodiscard]] bool valid_header_value(std::string_view value) noexcept {
for (const unsigned char ch : value) {
if (ch == '\t') {
continue;
}
if (ch < 0x20 || ch == 0x7f) {
return false;
}
}
return true;
}

[[nodiscard]] bool parse_content_length(
std::string_view text,
std::size_t& value) noexcept {
if (text.empty()) {
return false;
}

const char* const begin = text.data();
const char* const end = text.data() + text.size();
const auto parsed = std::from_chars(begin, end, value, 10);
return parsed.ec == std::errc{} && parsed.ptr == end;
}

void append_decimal(std::string& output, std::size_t value) {
char buffer[32]{};
const auto converted = std::to_chars(
buffer,
buffer + sizeof(buffer),
value,
10);
output.append(buffer, converted.ptr);
}

void append_port(std::string& output, std::uint16_t port) {
char buffer[8]{};
const auto converted = std::to_chars(
buffer,
buffer + sizeof(buffer),
port,
10);
output.append(buffer, converted.ptr);
}

void append_generated_host(std::string& output, const Url& url) {
output.append("Host: ");
if (url.host_is_ipv6_literal()) {
output.push_back('[');
output.append(url.host().data(), url.host().size());
output.push_back(']');
} else {
output.append(url.host().data(), url.host().size());
}

if (url.has_explicit_port()) {
output.push_back(':');
append_port(output, url.port());
}
output.append("\r\n");
}

} // namespace

Result<SerializedRequest> serialize_request(const Request& request) {
auto parsed_url = Url::parse(request.url());
if (!parsed_url) {
return parsed_url.error();
}

const std::string_view method = method_token(request.method());
if (method.empty()) {
return Error{ErrorCode::Unknown};
}

std::size_t host_count = 0;
std::size_t content_length_count = 0;
std::size_t declared_content_length = 0;

for (const auto& field : request.headers()) {
if (!valid_header_name(field.name) || !valid_header_value(field.value)) {
return Error{ErrorCode::InvalidHeader};
}

if (ascii_iequals(field.name, "Host")) {
++host_count;
if (field.value.empty()) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject whitespace-only Host values

When the caller supplies a whitespace-only Host value such as "\t", valid_header_value accepts the tab and this raw emptiness check passes. Serialization then succeeds with a semantically empty Host header while suppressing generation from the URL, producing an invalid HTTP/1.1 request that servers can reject. Check for an empty value after removing optional whitespace, or fully validate the Host authority.

Useful? React with 👍 / 👎.

return Error{ErrorCode::InvalidHeader};
}
} else if (ascii_iequals(field.name, "Content-Length")) {
++content_length_count;
if (!parse_content_length(field.value, declared_content_length)) {
return Error{ErrorCode::InvalidContentLength};
}
} else if (ascii_iequals(field.name, "Transfer-Encoding")) {
return Error{ErrorCode::ConflictingMessageFraming};
}
}

if (host_count > 1) {
return Error{ErrorCode::InvalidHeader};
}
if (content_length_count > 1) {
return Error{ErrorCode::InvalidContentLength};
}
if (content_length_count == 1
&& declared_content_length != request.body().size()) {
return Error{ErrorCode::InvalidContentLength};
}

SerializedRequest serialized;
serialized.url = std::move(parsed_url).value();
serialized.body = request.body();

std::size_t reserve_size = method.size()
+ 1
+ serialized.url.target().size()
+ sizeof(" HTTP/1.1\r\n") - 1
+ request.headers().size() * 16
+ 64;
for (const auto& field : request.headers()) {
reserve_size += field.name.size() + field.value.size();
}
serialized.head.reserve(reserve_size);

serialized.head.append(method.data(), method.size());
serialized.head.push_back(' ');
serialized.head.append(
serialized.url.target().data(),
serialized.url.target().size());
serialized.head.append(" HTTP/1.1\r\n");

if (host_count == 0) {
append_generated_host(serialized.head, serialized.url);
}

for (const auto& field : request.headers()) {
serialized.head.append(field.name);
serialized.head.append(": ");
serialized.head.append(field.value);
serialized.head.append("\r\n");
}

if (!request.body().empty() && content_length_count == 0) {
serialized.head.append("Content-Length: ");
append_decimal(serialized.head, request.body().size());
serialized.head.append("\r\n");
}

serialized.head.append("\r\n");
return serialized;
}

} // namespace cpp_request::detail::http
20 changes: 20 additions & 0 deletions src/http/request_serializer.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#pragma once

#include <string>
#include <string_view>

#include <cpp_request/request.hpp>
#include <cpp_request/result.hpp>
#include <cpp_request/url.hpp>

namespace cpp_request::detail::http {

struct SerializedRequest final {
Url url;
std::string head;
std::string_view body;
};

[[nodiscard]] Result<SerializedRequest> serialize_request(const Request& request);

} // namespace cpp_request::detail::http
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ add_executable(cpp_request_tests
${CMAKE_CURRENT_SOURCE_DIR}/url_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/headers_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/request_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/request_serializer_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/native_socket_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/resolver_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/tcp_connection_test.cpp
Expand Down
Loading
Loading