Line data Source code
1 : #pragma once
2 :
3 : // Strong ETag support for the per-design HTTP data endpoints (M1.3).
4 : //
5 : // An ETag binds the design name, the design archive file's mtime and size, the
6 : // per-design cache invalidation generation, and the endpoint path with an
7 : // FNV-1a 64-bit hash, rendered as a quoted lowercase hex string
8 : // ("a1b2c3d4e5f60718").
9 : //
10 : // Invalidation contract: replacing or re-uploading a design archive changes
11 : // the on-disk mtime/size, and in-memory replacements (POST /filemodels with
12 : // save=false, upload-overwrite invalidation) bump the cache invalidation
13 : // generation — either way the tag changes with no explicit invalidation step,
14 : // so a client revalidating with the stale tag's If-None-Match no longer
15 : // matches and receives a fresh 200.
16 : //
17 : // Gzip interplay: the tag is the strong validator of the UNCOMPRESSED
18 : // representation. It is computed before Crow serializes the body, hence also
19 : // before Crow compresses it for the wire, so it does not vary with the
20 : // content-coding (a strong variant of the uncompressed representation).
21 :
22 : #include <cctype>
23 : #include <cstdint>
24 : #include <cstring>
25 : #include <filesystem>
26 : #include <string>
27 : #include <string_view>
28 : #include <system_error>
29 :
30 : namespace Utils
31 : {
32 : constexpr inline std::uint64_t FNV1A64_OFFSET_BASIS = 14695981039346656037ull;
33 : constexpr inline std::uint64_t FNV1A64_PRIME = 1099511628211ull;
34 :
35 : // FNV-1a 64-bit over sizeBytes bytes at data, continuing from hash
36 : // (defaults to the offset basis, i.e. start of a fresh digest).
37 125 : inline std::uint64_t Fnv1a64(const char* data, std::size_t sizeBytes, std::uint64_t hash = FNV1A64_OFFSET_BASIS)
38 : {
39 1438 : for (std::size_t i = 0; i < sizeBytes; ++i)
40 : {
41 1313 : hash ^= static_cast<unsigned char>(data[i]);
42 1313 : hash *= FNV1A64_PRIME;
43 : }
44 125 : return hash;
45 : }
46 :
47 : // Builds the quoted ETag string from the raw hashed fields.
48 : // Exposed separately from MakeDesignEtag so tests can pin the digest
49 : // behavior (determinism, field sensitivity, formatting) without files.
50 : // generation: the design's cache invalidation generation (0 = no
51 : // in-memory invalidation has occurred); folded into the digest so
52 : // cache-only changes (POST /filemodels with save=false) rotate the tag.
53 25 : inline std::string MakeEtag(const std::string& designName, std::int64_t mtimeTicks, std::uint64_t sizeBytes, const std::string& endpointPath, std::uint64_t generation = 0)
54 : {
55 25 : auto hash = Fnv1a64(designName.data(), designName.size());
56 25 : hash = Fnv1a64(reinterpret_cast<const char*>(&mtimeTicks), sizeof(mtimeTicks), hash);
57 25 : hash = Fnv1a64(reinterpret_cast<const char*>(&sizeBytes), sizeof(sizeBytes), hash);
58 25 : hash = Fnv1a64(endpointPath.data(), endpointPath.size(), hash);
59 25 : hash = Fnv1a64(reinterpret_cast<const char*>(&generation), sizeof(generation), hash);
60 :
61 : static constexpr char HEX_DIGITS[] = "0123456789abcdef";
62 25 : std::string tag;
63 25 : tag.reserve(18);
64 25 : tag += '"';
65 425 : for (int shift = 60; shift >= 0; shift -= 4)
66 : {
67 400 : tag += HEX_DIGITS[(hash >> shift) & 0xF];
68 : }
69 25 : tag += '"';
70 25 : return tag;
71 0 : }
72 :
73 : // Locates the design's archive file exactly the way DesignCache does when
74 : // serving (DesignCache::FindArchivePath): the first regular file in the
75 : // designs directory whose path stem matches designName (the stem strips
76 : // only the LAST extension — "foo.tar.gz" has stem "foo.tar"). Keeping the
77 : // two resolvers identical is what makes the validator attest the same
78 : // archive that is served; a divergent extension-stripping rule here would
79 : // let the tag name a different file than the one behind the body. The
80 : // stem comparison is case-sensitive, mirroring DesignCache's lookup.
81 : // Returns an empty path when no archive matches or the directory cannot
82 : // be read.
83 21 : inline std::filesystem::path FindDesignArchiveFile(const std::string& designsDir, const std::string& designName)
84 : {
85 21 : if (designsDir.empty() || designName.empty())
86 : {
87 0 : return {};
88 : }
89 :
90 21 : std::error_code ec;
91 21 : std::filesystem::directory_iterator dirIt(designsDir, std::filesystem::directory_options::skip_permission_denied, ec);
92 21 : if (ec)
93 : {
94 1 : return {};
95 : }
96 :
97 38 : for (const auto& entry : dirIt)
98 : {
99 26 : if (!entry.is_regular_file(ec) || ec)
100 : {
101 0 : ec.clear();
102 0 : continue;
103 : }
104 :
105 26 : if (entry.path().stem() == designName)
106 : {
107 17 : return entry.path();
108 : }
109 37 : }
110 :
111 3 : return {};
112 21 : }
113 :
114 : // Computes the strong ETag for a per-design data endpoint: locates the
115 : // design's archive file under designsDir and hashes (design name, archive
116 : // mtime, archive size, endpoint path, cache invalidation generation).
117 : // Returns the quoted tag, or an empty string when the archive file cannot
118 : // be found or stat'ed — the endpoint will 404 on load in that case, so no
119 : // caching headers are emitted.
120 10 : inline std::string MakeDesignEtag(const std::string& designsDir, const std::string& designName, const std::string& endpointPath, std::uint64_t generation = 0)
121 : {
122 10 : const auto archivePath = FindDesignArchiveFile(designsDir, designName);
123 10 : if (archivePath.empty())
124 : {
125 2 : return "";
126 : }
127 :
128 9 : std::error_code ec;
129 9 : const auto mtime = std::filesystem::last_write_time(archivePath, ec);
130 9 : if (ec)
131 : {
132 0 : return "";
133 : }
134 9 : const auto sizeBytes = std::filesystem::file_size(archivePath, ec);
135 9 : if (ec)
136 : {
137 0 : return "";
138 : }
139 :
140 : // file_time_type ticks are stable across server restarts on a given
141 : // platform, which is all an ETag requires: it is only ever compared
142 : // against itself, never interpreted as a timestamp.
143 9 : const auto mtimeTicks = static_cast<std::int64_t>(mtime.time_since_epoch().count());
144 9 : return MakeEtag(designName, mtimeTicks, sizeBytes, endpointPath, generation);
145 10 : }
146 :
147 : // RFC 7232 If-None-Match evaluation using weak comparison (the spec mandates
148 : // weak comparison for If-None-Match even against strong validators like
149 : // ours): the header may be "*" (matches any current representation) or a
150 : // comma-separated list of entity-tags, each optionally weak-prefixed
151 : // (W/"..."); comparison covers the opaque quoted part only.
152 7 : inline bool IfNoneMatchMatches(const std::string& header, const std::string& etag)
153 : {
154 7 : if (header.empty() || etag.empty())
155 : {
156 1 : return false;
157 : }
158 :
159 6 : constexpr const char* OWS = " \t";
160 6 : std::size_t start = 0;
161 7 : while (start <= header.size())
162 : {
163 7 : const auto comma = header.find(',', start);
164 7 : const auto end = (comma == std::string::npos) ? header.size() : comma;
165 :
166 7 : auto tokenStart = start;
167 7 : auto tokenEnd = end;
168 8 : while (tokenStart < tokenEnd && std::strchr(OWS, header[tokenStart]) != nullptr) ++tokenStart;
169 7 : while (tokenEnd > tokenStart && std::strchr(OWS, header[tokenEnd - 1]) != nullptr) --tokenEnd;
170 7 : auto token = header.substr(tokenStart, tokenEnd - tokenStart);
171 :
172 7 : if (token.size() >= 2 && (token[0] == 'W' || token[0] == 'w') && token[1] == '/')
173 : {
174 1 : token = token.substr(2);
175 : }
176 :
177 7 : if (token == "*" || token == etag)
178 : {
179 4 : return true;
180 : }
181 :
182 3 : if (comma == std::string::npos)
183 : {
184 2 : break;
185 : }
186 1 : start = comma + 1;
187 7 : }
188 :
189 2 : return false;
190 : }
191 : }
|