Sourcemeta Core 0.0.0
Loading...
Searching...
No Matches
http_message.h
1#ifndef SOURCEMETA_CORE_HTTP_MESSAGE_H_
2#define SOURCEMETA_CORE_HTTP_MESSAGE_H_
3
4#include <sourcemeta/core/http_syntax.h>
5#include <sourcemeta/core/text.h>
6
7#include <concepts> // std::convertible_to, std::invocable
8#include <cstddef> // std::size_t
9#include <optional> // std::nullopt, std::optional
10#include <string> // std::string
11#include <string_view> // std::string_view
12#include <type_traits> // std::is_same_v
13#include <utility> // std::move
14
15namespace sourcemeta::core {
16
28constexpr auto http_is_status_line(const std::string_view line) noexcept
29 -> bool {
30 // The prefix cannot open a field line, as RFC 9110 §5.6.2 defines tchar
31 // as "any VCHAR, except delimiters" where delimiters include the slash,
32 // and the protocol name is case-sensitive per RFC 9112 §2.3
33 return line.starts_with("HTTP/");
34}
35
54template <typename Buffer>
55 requires requires(Buffer buffer, std::string_view line) {
56 buffer.clear();
57 buffer.append(line);
58 }
59inline auto http_accumulate_header_line(Buffer &buffer,
60 const std::string_view line) -> void {
61 if (http_is_status_line(line)) {
62 buffer.clear();
63 }
64
65 buffer.append(line);
66}
67
88template <typename Callback>
89 requires std::invocable<Callback, std::string_view, std::string_view>
90inline auto http_parse_headers(const std::string_view input, Callback callback)
91 -> void {
92 std::size_t cursor{input.find("\r\n")};
93 while (cursor != std::string_view::npos) {
94 cursor += 2;
95 const auto end{input.find("\r\n", cursor)};
96 if (end == std::string_view::npos || end == cursor) {
97 break;
98 }
99
100 auto line{input.substr(cursor, end - cursor)};
101 cursor = end;
102
103 // RFC 9112 §5.2 deprecates obs-fold, defined as "OWS CRLF RWS", and
104 // mandates that a user agent "MUST replace each received obs-fold
105 // with one or more SP octets prior to interpreting the field value",
106 // so a line opening with whitespace continues the previous field
107 // line value and is reported with an empty name for the caller to join
108 if (line.front() == ' ' || line.front() == '\t') {
109 while (!line.empty() && (line.front() == ' ' || line.front() == '\t')) {
110 line.remove_prefix(1);
111 }
112
113 while (!line.empty() && (line.back() == ' ' || line.back() == '\t')) {
114 line.remove_suffix(1);
115 }
116
117 // RFC 9110 §5.5: "a recipient of CR, LF, or NUL within a field value
118 // MUST either reject the message or replace each of those characters
119 // with SP", so a continuation carrying a bare one is discarded
121 continue;
122 }
123
124 callback(std::string_view{}, line);
125 continue;
126 }
127
128 const auto parts{split_once(line, ':')};
129 if (!parts.has_value() || parts->first.empty()) {
130 continue;
131 }
132
133 const auto name{parts->first};
134 // RFC 9112 §5.1 mandates that "no whitespace is allowed between the
135 // field name and colon" because in the past such whitespace has "led
136 // to security vulnerabilities", so the field line is discarded
137 if (name.back() == ' ' || name.back() == '\t') {
138 continue;
139 }
140
141 auto value{parts->second};
142 // RFC 9112 §5 defines a field line as
143 // `field-name ":" OWS field-value OWS` where RFC 9110 §5.6.3 defines
144 // optional whitespace as `*( SP / HTAB )`
145 while (!value.empty() && (value.front() == ' ' || value.front() == '\t')) {
146 value.remove_prefix(1);
147 }
148
149 while (!value.empty() && (value.back() == ' ' || value.back() == '\t')) {
150 value.remove_suffix(1);
151 }
152
153 // RFC 9110 §5.5: "a recipient of CR, LF, or NUL within a field value MUST
154 // either reject the message or replace each of those characters with SP",
155 // so a field line whose name or value carries a bare one that survived the
156 // split on the line terminator is discarded
159 continue;
160 }
161
162 callback(name, value);
163 }
164}
165
192template <typename Callback>
193 requires std::invocable<Callback, std::string_view, std::string_view>
194inline auto http_parse_cookies(const std::string_view input, Callback callback)
195 -> void {
196 std::string_view rest{input};
197 while (!rest.empty()) {
198 std::string_view pair;
199 const auto separator{rest.find(';')};
200 if (separator == std::string_view::npos) {
201 pair = rest;
202 rest = {};
203 } else {
204 pair = rest.substr(0, separator);
205 rest = rest.substr(separator + 1);
206 }
207
208 const auto parts{split_once(trim(pair), '=')};
209 if (!parts.has_value()) {
210 continue;
211 }
212
213 const auto name{trim(parts->first)};
214 if (name.empty()) {
215 continue;
216 }
217
218 callback(name, trim(parts->second));
219 }
220}
221
241template <typename Container>
242 requires requires(Container container, std::string_view entry) {
243 container.emplace_back(entry, entry);
244 }
245inline auto http_parse_cookies(const std::string_view input, Container &cookies)
246 -> void {
247 http_parse_cookies(input,
248 [&cookies](const std::string_view name,
249 const std::string_view value) -> void {
250 cookies.emplace_back(name, value);
251 });
252}
253
281template <typename Container>
282 requires requires(Container container, std::string_view entry) {
283 container.emplace_back(entry);
284 }
285inline auto http_cookie_values(const std::string_view input,
286 const std::string_view name, Container &values)
287 -> void {
288 http_parse_cookies(input,
289 [&name, &values](const std::string_view cookie,
290 const std::string_view value) -> void {
291 if (cookie == name) {
292 values.emplace_back(value);
293 }
294 });
295}
296
318template <typename Container>
319 requires requires(Container container, std::string name, std::string value,
320 const char character) {
321 container.emplace_back(std::move(name), std::move(value));
322 { container.empty() } -> std::convertible_to<bool>;
323 container.back().second += character;
324 }
325inline auto http_parse_headers(const std::string_view input, Container &headers)
326 -> void {
327 http_parse_headers(input,
328 [&headers](const std::string_view name,
329 const std::string_view value) -> auto {
330 if (name.empty()) {
331 // RFC 9112 §5.2 mandates replacing "each received
332 // obs-fold with one or more SP octets prior to
333 // interpreting the field value"
334 if (!headers.empty()) {
335 auto &previous_value{headers.back().second};
336 previous_value += ' ';
337 previous_value += value;
338 }
339
340 return;
341 }
342
343 std::string header_name{name};
344 to_lowercase(header_name);
345 headers.emplace_back(std::move(header_name),
346 std::string{value});
347 });
348}
349
366template <typename Headers>
367inline auto http_serialize_headers(const Headers &headers) -> std::string {
368 std::size_t total_size{0};
369 for (const auto &[name, value] : headers) {
370 // A field dropped for a forbidden byte contributes no bytes, so the reserve
371 // is sized from only the fields that are actually emitted
373 continue;
374 }
375 // Account for the colon, the space, and the trailing CRLF
376 if constexpr (requires { value.bytes(); }) {
377 if (http_field_line_has_forbidden_byte(value.bytes())) {
378 continue;
379 }
380 total_size += name.size() + value.bytes().size() + 4;
381 } else {
383 continue;
384 }
385 total_size += name.size() + value.size() + 4;
386 }
387 }
388
389 std::string result;
390 result.reserve(total_size);
391 for (const auto &[name, value] : headers) {
392 // RFC 9110 §5.5: "a recipient of CR, LF, or NUL within a field value MUST
393 // either reject the message or replace each of those characters with SP
394 // before further processing or forwarding of that message", so a field
395 // whose name carries one is dropped rather than written to the wire as a
396 // header-injection defense
398 continue;
399 }
400
401 // A field value either carries its own bytes or already is the bytes, so
402 // which of the two it is settles only what gets read out of it here. A
403 // value that carries them hands back a view of storage it keeps, which is
404 // what lets the view below outlive the call that produced it
405 std::string_view bytes;
406 if constexpr (requires { value.bytes(); }) {
407 static_assert(std::is_same_v<decltype(value.bytes()), std::string_view>,
408 "A field value must hand back a view of bytes it keeps, "
409 "as an owning result would leave nothing to write out");
410 bytes = value.bytes();
411 } else {
412 bytes = value;
413 }
414
416 continue;
417 }
418
419 // RFC 9112 §5.1 notes that "a single SP preceding the field line
420 // value is preferred for consistent readability by humans"
421 result += name;
422 result += ": ";
423 result += bytes;
424 result += "\r\n";
425 }
426
427 return result;
428}
429
447template <typename Headers>
448inline auto http_header_find(const Headers &headers,
449 const std::string_view name)
450 -> std::optional<std::string_view> {
451 // Prefer the container's own lookup when it supports searching by the
452 // given name without converting it, as associative containers do it in
453 // logarithmic or constant time instead of a linear scan
454 if constexpr (requires { headers.find(name) != headers.end(); }) {
455 const auto match{headers.find(name)};
456 if (match != headers.end()) {
457 return std::string_view{match->second};
458 }
459
460 return std::nullopt;
461 } else {
462 for (const auto &[header_name, header_value] : headers) {
463 if (header_name == name) {
464 return std::string_view{header_value};
465 }
466 }
467
468 return std::nullopt;
469 }
470}
471
472} // namespace sourcemeta::core
473
474#endif
auto http_parse_cookies(const std::string_view input, Callback callback) -> void
Definition http_message.h:194
auto http_accumulate_header_line(Buffer &buffer, const std::string_view line) -> void
Definition http_message.h:59
auto http_field_line_has_forbidden_byte(const std::string_view value) noexcept -> bool
Definition http_syntax.h:220
constexpr auto http_is_status_line(const std::string_view line) noexcept -> bool
Definition http_message.h:28
auto http_parse_headers(const std::string_view input, Callback callback) -> void
Definition http_message.h:90
auto http_serialize_headers(const Headers &headers) -> std::string
Definition http_message.h:367
auto http_cookie_values(const std::string_view input, const std::string_view name, Container &values) -> void
Definition http_message.h:285
auto http_header_find(const Headers &headers, const std::string_view name) -> std::optional< std::string_view >
Definition http_message.h:448
constexpr auto to_lowercase(const Character character) noexcept -> Character
Definition text.h:75
SOURCEMETA_CORE_TEXT_EXPORT auto trim(const std::string_view input) noexcept -> std::string_view
SOURCEMETA_CORE_TEXT_EXPORT auto split_once(const std::string_view input, const char delimiter) noexcept -> std::optional< std::pair< std::string_view, std::string_view > >