Skip to content
File

Blob: src/workerd/util/header-validation.h

cpp44 lines
1// Copyright (c) 2017-2025 Cloudflare, Inc.
2// Licensed under the Apache 2.0 license found in the LICENSE file or at:
3// https://opensource.org/licenses/Apache-2.0
4 
5#pragma once
6 
7#include <kj/common.h>
8#include <kj/parse/char.h>
9#include <kj/string.h>
10 
11namespace workerd::util {
12 
13inline bool isValidHeaderValue(kj::ArrayPtr<const char> value) {
14 if (value == nullptr) return true;
15 for (auto c: value) {
16 if (c == '\0' || c == '\r' || c == '\n') {
17 return false;
18 }
19 }
20 return true;
21}
22 
23constexpr auto HTTP_SEPARATOR_CHARS = kj::parse::anyOfChars("()<>@,;:\\\"/[]?={} \t");
24// RFC2616 section 2.2: https://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
25 
26constexpr auto HTTP_TOKEN_CHARS = kj::parse::controlChar.orChar('\x7f')
27 .orGroup(kj::parse::whitespaceChar)
28 .orGroup(HTTP_SEPARATOR_CHARS)
29 .invert();
30// RFC2616 section 2.2: https://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html#sec2.2
31// RFC2616 section 4.2: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
32 
33inline constexpr bool isHttpWhitespace(char c) {
34 return c == '\t' || c == '\r' || c == '\n' || c == ' ';
35}
36static_assert(isHttpWhitespace(' '));
37static_assert(!isHttpWhitespace('A'));
38inline constexpr bool isHttpTokenChar(char c) {
39 return HTTP_TOKEN_CHARS.contains(c);
40}
41static_assert(isHttpTokenChar('A'));
42static_assert(!isHttpTokenChar(' '));
43} // namespace workerd::util