-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add HTTP/1.1 request serializer #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
934dda5
feat: add HTTP request serializer interface
zuudevs 142d11e
feat: implement HTTP/1.1 request serialization
zuudevs 6903485
test: cover HTTP request serialization
zuudevs 5938a13
build: compile request serializer
zuudevs e9ce595
test: wire request serializer tests
zuudevs 34e6d4b
fix: include move utility in request serializer
zuudevs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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()) { | ||
| 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When the caller supplies a whitespace-only
Hostvalue such as"\t",valid_header_valueaccepts the tab and this raw emptiness check passes. Serialization then succeeds with a semantically emptyHostheader 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 👍 / 👎.