/src/curl_fuzzer/proto_fuzzer/imap_mock_server.cc
Line | Count | Source |
1 | | /* |
2 | | * Copyright (C) Max Dymond, <cmeister2@gmail.com>, et al. |
3 | | * |
4 | | * SPDX-License-Identifier: curl |
5 | | */ |
6 | | |
7 | | /// @file |
8 | | /// @brief Implementation of the command-aware in-process IMAP peer. |
9 | | |
10 | | #include "proto_fuzzer/imap_mock_server.h" |
11 | | |
12 | | #include <algorithm> |
13 | | #include <cstddef> |
14 | | #include <cstdint> |
15 | | #include <limits> |
16 | | #include <string> |
17 | | #include <string_view> |
18 | | |
19 | | namespace proto_fuzzer { |
20 | | |
21 | | namespace { |
22 | | |
23 | | /// Fold only ASCII lowercase command bytes. IMAP status keywords are ASCII |
24 | | /// tokens, so locale-aware conversion would add state without accepting |
25 | | /// anything curl can legitimately send. |
26 | 485k | bool AsciiEqualsIgnoreCase(std::string_view value, std::string_view expected_lowercase) { |
27 | 485k | if (value.size() != expected_lowercase.size()) { |
28 | 429k | return false; |
29 | 429k | } |
30 | 89.9k | for (std::size_t index = 0; index < value.size(); ++index) { |
31 | 73.8k | unsigned char actual = static_cast<unsigned char>(value[index]); |
32 | 73.8k | if (actual >= 'A' && actual <= 'Z') { |
33 | 40.8k | actual = static_cast<unsigned char>(actual - 'A' + 'a'); |
34 | 40.8k | } |
35 | 73.8k | if (actual != static_cast<unsigned char>(expected_lowercase[index])) { |
36 | 40.5k | return false; |
37 | 40.5k | } |
38 | 73.8k | } |
39 | 16.0k | return true; |
40 | 56.6k | } |
41 | | |
42 | | } // namespace |
43 | | |
44 | | /// Begin without a borrowed protobuf or open socketpair. RunLoop borrows a |
45 | | /// Scenario only for the synchronous DriveScenario call in which socket |
46 | | /// callbacks can run. |
47 | 6.57k | ImapMockServer::ImapMockServer() = default; |
48 | | |
49 | | /// Release the server-owned socketpair half after curl has returned its client |
50 | | /// descriptor. The out-of-line destructor keeps MockConnection's complete type |
51 | | /// local to this translation unit. |
52 | 6.57k | ImapMockServer::~ImapMockServer() = default; |
53 | | |
54 | | /// Clear the tag remembered from the previous drive. The shared base has |
55 | | /// already reset the transport, reply cursor, transcript, upload capture, and |
56 | | /// body phase. |
57 | 6.43k | void ImapMockServer::ResetProtocolState() { |
58 | 6.43k | current_tag_.clear(); |
59 | 6.43k | authentication_continuation_active_ = false; |
60 | 6.43k | } |
61 | | |
62 | | /// Return whether a scripted line is a tagged status response. Untagged (`*`) |
63 | | /// and continuation (`+`) lines are left alone, as are already-tagged or |
64 | | /// arbitrary bytes that curl should observe verbatim. |
65 | | /// @param line One complete response line, including its line ending. |
66 | | /// @return true when the current command tag must be prepended. |
67 | 533k | bool ImapMockServer::StatusLineNeedsTag(std::string_view line) { |
68 | 533k | const std::size_t space = line.find_first_of(" \r\n"); |
69 | 533k | const std::string_view keyword = line.substr(0, space); |
70 | 533k | if (keyword.empty()) { |
71 | 400k | return false; |
72 | 400k | } |
73 | 133k | if (!AsciiEqualsIgnoreCase(keyword, "ok") && !AsciiEqualsIgnoreCase(keyword, "no") && |
74 | 117k | !AsciiEqualsIgnoreCase(keyword, "bad") && !AsciiEqualsIgnoreCase(keyword, "preauth")) { |
75 | 117k | return false; |
76 | 117k | } |
77 | 16.0k | return space != std::string_view::npos; |
78 | 133k | } |
79 | | |
80 | | /// Return whether a scripted response contains an IMAP continuation line. |
81 | | /// Literal bodies are skipped with the same rules as RewriteReply so their |
82 | | /// arbitrary bytes cannot start a continuation exchange. |
83 | | /// @param response Scenario-owned reply fragment. |
84 | | /// @return true when a non-literal response line begins with `+`. |
85 | 12.0k | bool ImapMockServer::ResponseHasContinuation(std::string_view response) { |
86 | 12.0k | std::size_t position = 0; |
87 | 306k | while (position < response.size()) { |
88 | 298k | const std::size_t newline = response.find('\n', position); |
89 | 298k | const std::size_t line_end = newline == std::string_view::npos ? response.size() : newline + 1; |
90 | 298k | const std::string_view line = response.substr(position, line_end - position); |
91 | 298k | if (!line.empty() && line.front() == '+') { |
92 | 3.71k | return true; |
93 | 3.71k | } |
94 | | |
95 | 294k | const std::size_t literal = LiteralSize(line); |
96 | 294k | const std::size_t available = response.size() - line_end; |
97 | 294k | position = line_end + std::min(literal, available); |
98 | 294k | } |
99 | 8.31k | return false; |
100 | 12.0k | } |
101 | | |
102 | | /// Return whether a scripted response contains a terminal status for the |
103 | | /// current tag. Literal bodies are skipped with the same rules as RewriteReply |
104 | | /// so body bytes that happen to begin with an IMAP status word cannot end |
105 | | /// authentication. Both tag-relative placeholders and an exact already-tagged |
106 | | /// line are accepted. |
107 | | /// @param response Scenario-owned reply fragment. |
108 | | /// @return true when the response completes the current tagged command. |
109 | 12.0k | bool ImapMockServer::ResponseHasTaggedCompletion(std::string_view response) const { |
110 | 12.0k | std::size_t position = 0; |
111 | 230k | while (position < response.size()) { |
112 | 224k | const std::size_t newline = response.find('\n', position); |
113 | 224k | const std::size_t line_end = newline == std::string_view::npos ? response.size() : newline + 1; |
114 | 224k | const std::string_view line = response.substr(position, line_end - position); |
115 | 224k | const bool tag_relative = StatusLineNeedsTag(line); |
116 | 224k | const bool has_current_tag = !current_tag_.empty() && line.size() > current_tag_.size() && |
117 | 19.3k | line.compare(0, current_tag_.size(), current_tag_) == 0 && |
118 | 421 | line[current_tag_.size()] == ' ' && |
119 | 248 | StatusLineNeedsTag(line.substr(current_tag_.size() + 1)); |
120 | 224k | if (tag_relative || has_current_tag) { |
121 | 5.25k | return true; |
122 | 5.25k | } |
123 | | |
124 | 218k | const std::size_t literal = LiteralSize(line); |
125 | 218k | const std::size_t available = response.size() - line_end; |
126 | 218k | position = line_end + std::min(literal, available); |
127 | 218k | } |
128 | 6.78k | return false; |
129 | 12.0k | } |
130 | | |
131 | | /// Parse a trailing IMAP literal marker such as `{42}` or `{42+}`. |
132 | | /// @param line One response or command line. |
133 | | /// @return Literal byte count, or 0 when no well-formed marker is present. |
134 | 824k | std::size_t ImapMockServer::LiteralSize(std::string_view line) { |
135 | 1.72M | while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) { |
136 | 902k | line.remove_suffix(1); |
137 | 902k | } |
138 | 824k | if (line.empty() || line.back() != '}') { |
139 | 821k | return 0; |
140 | 821k | } |
141 | 2.91k | const std::size_t open = line.rfind('{'); |
142 | 2.91k | if (open == std::string_view::npos || open + 2 > line.size()) { |
143 | 319 | return 0; |
144 | 319 | } |
145 | | |
146 | 2.59k | std::size_t position = open + 1; |
147 | 2.59k | std::size_t value = 0; |
148 | 2.59k | bool digits = false; |
149 | 11.1k | while (position < line.size() && line[position] >= '0' && line[position] <= '9') { |
150 | 8.52k | const std::size_t digit = static_cast<std::size_t>(line[position] - '0'); |
151 | 8.52k | if (value > (std::numeric_limits<std::size_t>::max() - digit) / 10) { |
152 | 12 | return 0; |
153 | 12 | } |
154 | 8.51k | value = value * 10 + digit; |
155 | 8.51k | digits = true; |
156 | 8.51k | ++position; |
157 | 8.51k | } |
158 | 2.58k | if (!digits) { |
159 | 615 | return 0; |
160 | 615 | } |
161 | 1.96k | if (position < line.size() && line[position] == '+') { |
162 | 43 | ++position; |
163 | 43 | } |
164 | 1.96k | return position + 1 == line.size() ? value : 0; |
165 | 2.58k | } |
166 | | |
167 | | /// Parse the literal size from an APPEND command. Only the command's final |
168 | | /// marker matters; earlier braces in a mailbox name are ignored. |
169 | | /// @param command Complete APPEND command line. |
170 | | /// @return Announced literal size, or the maximum size_t when the command has |
171 | | /// no well-formed marker. Zero is a valid literal length. |
172 | 1.10k | std::size_t ImapMockServer::AppendLiteralSize(std::string_view command) { |
173 | 3.35k | while (!command.empty() && (command.back() == '\r' || command.back() == '\n')) { |
174 | 2.24k | command.remove_suffix(1); |
175 | 2.24k | } |
176 | 1.10k | if (command.empty() || command.back() != '}') { |
177 | 12 | return std::numeric_limits<std::size_t>::max(); |
178 | 12 | } |
179 | 1.09k | const std::size_t open = command.rfind('{'); |
180 | 1.09k | if (open == std::string_view::npos) { |
181 | 10 | return std::numeric_limits<std::size_t>::max(); |
182 | 10 | } |
183 | | |
184 | 1.08k | std::size_t position = open + 1; |
185 | 1.08k | std::size_t value = 0; |
186 | 1.08k | bool digits = false; |
187 | 7.46k | while (position < command.size() && command[position] >= '0' && command[position] <= '9') { |
188 | 6.37k | const std::size_t digit = static_cast<std::size_t>(command[position] - '0'); |
189 | 6.37k | if (value > (std::numeric_limits<std::size_t>::max() - digit) / 10) { |
190 | 4 | return std::numeric_limits<std::size_t>::max(); |
191 | 4 | } |
192 | 6.37k | value = value * 10 + digit; |
193 | 6.37k | digits = true; |
194 | 6.37k | ++position; |
195 | 6.37k | } |
196 | 1.08k | if (!digits) { |
197 | 18 | return std::numeric_limits<std::size_t>::max(); |
198 | 18 | } |
199 | 1.06k | if (position < command.size() && command[position] == '+') { |
200 | 3 | ++position; |
201 | 3 | } |
202 | 1.06k | return position + 1 == command.size() ? value : std::numeric_limits<std::size_t>::max(); |
203 | 1.08k | } |
204 | | |
205 | | /// Resolve one scripted reply to wire bytes. A tagged status line gains the |
206 | | /// tag of the command currently being answered. Literal bodies are copied |
207 | | /// verbatim so fuzzed body bytes cannot be mistaken for status lines. |
208 | | /// @param response Scenario-owned reply fragment. |
209 | | /// @return Bytes to queue on the control socket. |
210 | 12.2k | std::string ImapMockServer::RewriteReply(std::string_view response) const { |
211 | 12.2k | std::string output; |
212 | 12.2k | output.reserve(response.size() + 16); |
213 | | |
214 | 12.2k | std::size_t position = 0; |
215 | 323k | while (position < response.size()) { |
216 | 311k | const std::size_t newline = response.find('\n', position); |
217 | 311k | const std::size_t line_end = newline == std::string_view::npos ? response.size() : newline + 1; |
218 | 311k | const std::string_view line = response.substr(position, line_end - position); |
219 | | |
220 | 311k | if (!current_tag_.empty() && StatusLineNeedsTag(line)) { |
221 | 10.8k | output.append(current_tag_); |
222 | 10.8k | output.push_back(' '); |
223 | 10.8k | } |
224 | 311k | output.append(line); |
225 | | |
226 | 311k | const std::size_t literal = LiteralSize(line); |
227 | 311k | if (literal == 0) { |
228 | 310k | position = line_end; |
229 | 310k | continue; |
230 | 310k | } |
231 | | |
232 | 949 | const std::size_t body_start = line_end; |
233 | 949 | const std::size_t available = response.size() - body_start; |
234 | 949 | const std::size_t body_size = std::min(literal, available); |
235 | 949 | output.append(response.substr(body_start, body_size)); |
236 | 949 | position = body_start + body_size; |
237 | 949 | } |
238 | 12.2k | return output; |
239 | 12.2k | } |
240 | | |
241 | | /// Derive the tag curl will assign to its next command. Curl formats the tag |
242 | | /// as `<letter><3-digit connection-local command id>`; the letter is stable |
243 | | /// for a connection and the id increments once per command. The predicted tag |
244 | | /// only drives a teardown liveness reply, so a malformed previous tag simply |
245 | | /// falls back to an untagged BYE and the final half-close. |
246 | | /// @return Predicted tag, or empty when the previous tag was not numeric. |
247 | 6.03k | std::string ImapMockServer::NextCommandTag() const { |
248 | 6.03k | std::size_t digits_start = current_tag_.size(); |
249 | 15.1k | while (digits_start > 0 && current_tag_[digits_start - 1] >= '0' && current_tag_[digits_start - 1] <= '9') { |
250 | 9.06k | --digits_start; |
251 | 9.06k | } |
252 | 6.03k | if (digits_start == current_tag_.size() || digits_start == 0) { |
253 | 3.01k | return std::string(); |
254 | 3.01k | } |
255 | | |
256 | 3.02k | std::uint64_t number = 0; |
257 | 12.0k | for (std::size_t index = digits_start; index < current_tag_.size(); ++index) { |
258 | 9.05k | number = number * 10 + static_cast<std::uint64_t>(current_tag_[index] - '0'); |
259 | 9.05k | if (number > 999999) { |
260 | 2 | return std::string(); |
261 | 2 | } |
262 | 9.05k | } |
263 | 3.02k | ++number; |
264 | | |
265 | 3.02k | std::string digits = std::to_string(number); |
266 | 3.02k | const std::size_t width = current_tag_.size() - digits_start; |
267 | 3.02k | if (digits.size() < width) { |
268 | 3.00k | digits.insert(0, width - digits.size(), '0'); |
269 | 3.00k | } |
270 | 3.02k | return current_tag_.substr(0, digits_start) + digits; |
271 | 3.02k | } |
272 | | |
273 | | /// Advance one reply for every complete command or AUTHENTICATE continuation. |
274 | | /// Continuation data keeps the initiating command tag until a scripted tagged |
275 | | /// status ends the exchange. A `+` reply to APPEND enters literal-draining mode |
276 | | /// and pre-queues the next scripted reply as the final tagged completion. |
277 | | /// Curl's imap_done() waits for that completion inside curl_multi_perform, so |
278 | | /// the outer peer loop cannot provide it later. |
279 | | /// @param command One newline-terminated client line from curl. |
280 | 456k | void ImapMockServer::HandleLine(std::string_view command) { |
281 | 456k | if (scenario() == nullptr) { |
282 | 1.10k | return; |
283 | 1.10k | } |
284 | | |
285 | 454k | const bool authentication_payload = authentication_continuation_active_; |
286 | 454k | if (!authentication_payload) { |
287 | 448k | current_tag_ = std::string(FirstToken(command)); |
288 | 448k | } |
289 | | |
290 | 454k | const std::string* response = NextControlReply(); |
291 | 454k | if (response == nullptr) { |
292 | 442k | return; |
293 | 442k | } |
294 | | |
295 | 12.0k | const bool continuation = ResponseHasContinuation(*response); |
296 | 12.0k | const bool tagged_completion = ResponseHasTaggedCompletion(*response); |
297 | 12.0k | (void)WriteControlBytes(RewriteReply(*response)); |
298 | | |
299 | 12.0k | if (authentication_payload) { |
300 | 167 | if (tagged_completion) { |
301 | 90 | authentication_continuation_active_ = false; |
302 | 90 | } |
303 | 167 | return; |
304 | 167 | } |
305 | | |
306 | 11.8k | const std::string_view verb = SecondToken(command); |
307 | 11.8k | if (continuation && TokenEquals(verb, "AUTHENTICATE")) { |
308 | 601 | authentication_continuation_active_ = !tagged_completion; |
309 | 601 | return; |
310 | 601 | } |
311 | | |
312 | 11.2k | if (!continuation || !TokenEquals(verb, "APPEND")) { |
313 | 10.1k | return; |
314 | 10.1k | } |
315 | | |
316 | 1.10k | const std::size_t literal = AppendLiteralSize(command); |
317 | 1.10k | if (literal == std::numeric_limits<std::size_t>::max()) { |
318 | | // Curl always announces the literal size here. Without one, leave the |
319 | | // transfer to the bounded idle budget and final half-close instead of |
320 | | // guessing where an arbitrary body ends. |
321 | 52 | return; |
322 | 52 | } |
323 | | |
324 | 1.05k | BeginLiteralBody(literal); |
325 | | |
326 | 1.05k | const std::string* final_response = NextControlReply(); |
327 | 1.05k | if (final_response != nullptr) { |
328 | 169 | (void)WriteControlBytes(RewriteReply(*final_response)); |
329 | 169 | } |
330 | 1.05k | } |
331 | | |
332 | | /// Queue a tagged completion for curl's blocking LOGOUT during teardown. Any |
333 | | /// real scripted response already consumed by curl still determines the |
334 | | /// transfer result; this line only prevents a teardown timeout. |
335 | 6.03k | void ImapMockServer::QueueShutdownReply() { |
336 | 6.03k | const std::string next_tag = NextCommandTag(); |
337 | 6.03k | if (!next_tag.empty()) { |
338 | 3.02k | (void)WriteControlBytes(next_tag + std::string(kShutdownTail)); |
339 | 3.02k | } else { |
340 | 3.01k | (void)WriteControlBytes("* BYE imap mock closing\r\n"); |
341 | 3.01k | } |
342 | 6.03k | } |
343 | | |
344 | | /// Retain protocol outcomes in coverage and introspector builds. |
345 | 6.54k | void ImapMockServer::ObserveState() { |
346 | 6.54k | #if defined(PROTO_FUZZER_OBSERVE_STATE) |
347 | 6.54k | PingpongMockServer::ObserveState(); |
348 | 6.54k | const volatile std::size_t imap_observation[] = {control_transcript().size(), uploaded_data().size()}; |
349 | 6.54k | (void)imap_observation; |
350 | 6.54k | #endif |
351 | 6.54k | } |
352 | | |
353 | | } // namespace proto_fuzzer |