Coverage Report

Created: 2026-10-31 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/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
225k
bool AsciiEqualsIgnoreCase(std::string_view value, std::string_view expected_lowercase) {
27
225k
  if (value.size() != expected_lowercase.size()) {
28
197k
    return false;
29
197k
  }
30
52.1k
  for (std::size_t index = 0; index < value.size(); ++index) {
31
40.2k
    unsigned char actual = static_cast<unsigned char>(value[index]);
32
40.2k
    if (actual >= 'A' && actual <= 'Z') {
33
25.4k
      actual = static_cast<unsigned char>(actual - 'A' + 'a');
34
25.4k
    }
35
40.2k
    if (actual != static_cast<unsigned char>(expected_lowercase[index])) {
36
15.6k
      return false;
37
15.6k
    }
38
40.2k
  }
39
11.9k
  return true;
40
27.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.48k
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.48k
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.35k
void ImapMockServer::ResetProtocolState() {
58
6.35k
  current_tag_.clear();
59
6.35k
  authentication_continuation_active_ = false;
60
6.35k
}
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
98.5k
bool ImapMockServer::StatusLineNeedsTag(std::string_view line) {
68
98.5k
  const std::size_t space = line.find_first_of(" \r\n");
69
98.5k
  const std::string_view keyword = line.substr(0, space);
70
98.5k
  if (keyword.empty()) {
71
33.2k
    return false;
72
33.2k
  }
73
65.2k
  if (!AsciiEqualsIgnoreCase(keyword, "ok") && !AsciiEqualsIgnoreCase(keyword, "no") &&
74
53.3k
      !AsciiEqualsIgnoreCase(keyword, "bad") && !AsciiEqualsIgnoreCase(keyword, "preauth")) {
75
53.3k
    return false;
76
53.3k
  }
77
11.9k
  return space != std::string_view::npos;
78
65.2k
}
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
10.1k
bool ImapMockServer::ResponseHasContinuation(std::string_view response) {
86
10.1k
  std::size_t position = 0;
87
61.2k
  while (position < response.size()) {
88
54.3k
    const std::size_t newline = response.find('\n', position);
89
54.3k
    const std::size_t line_end = newline == std::string_view::npos ? response.size() : newline + 1;
90
54.3k
    const std::string_view line = response.substr(position, line_end - position);
91
54.3k
    if (!line.empty() && line.front() == '+') {
92
3.22k
      return true;
93
3.22k
    }
94
95
51.1k
    const std::size_t literal = LiteralSize(line);
96
51.1k
    const std::size_t available = response.size() - line_end;
97
51.1k
    position = line_end + std::min(literal, available);
98
51.1k
  }
99
6.94k
  return false;
100
10.1k
}
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
10.1k
bool ImapMockServer::ResponseHasTaggedCompletion(std::string_view response) const {
110
10.1k
  std::size_t position = 0;
111
42.7k
  while (position < response.size()) {
112
37.7k
    const std::size_t newline = response.find('\n', position);
113
37.7k
    const std::size_t line_end = newline == std::string_view::npos ? response.size() : newline + 1;
114
37.7k
    const std::string_view line = response.substr(position, line_end - position);
115
37.7k
    const bool tag_relative = StatusLineNeedsTag(line);
116
37.7k
    const bool has_current_tag = !current_tag_.empty() && line.size() > current_tag_.size() &&
117
17.5k
                                 line.compare(0, current_tag_.size(), current_tag_) == 0 &&
118
218
                                 line[current_tag_.size()] == ' ' &&
119
133
                                 StatusLineNeedsTag(line.substr(current_tag_.size() + 1));
120
37.7k
    if (tag_relative || has_current_tag) {
121
5.22k
      return true;
122
5.22k
    }
123
124
32.5k
    const std::size_t literal = LiteralSize(line);
125
32.5k
    const std::size_t available = response.size() - line_end;
126
32.5k
    position = line_end + std::min(literal, available);
127
32.5k
  }
128
4.94k
  return false;
129
10.1k
}
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
145k
std::size_t ImapMockServer::LiteralSize(std::string_view line) {
135
333k
  while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) {
136
187k
    line.remove_suffix(1);
137
187k
  }
138
145k
  if (line.empty() || line.back() != '}') {
139
144k
    return 0;
140
144k
  }
141
1.37k
  const std::size_t open = line.rfind('{');
142
1.37k
  if (open == std::string_view::npos || open + 2 > line.size()) {
143
250
    return 0;
144
250
  }
145
146
1.12k
  std::size_t position = open + 1;
147
1.12k
  std::size_t value = 0;
148
1.12k
  bool digits = false;
149
3.30k
  while (position < line.size() && line[position] >= '0' && line[position] <= '9') {
150
2.20k
    const std::size_t digit = static_cast<std::size_t>(line[position] - '0');
151
2.20k
    if (value > (std::numeric_limits<std::size_t>::max() - digit) / 10) {
152
14
      return 0;
153
14
    }
154
2.18k
    value = value * 10 + digit;
155
2.18k
    digits = true;
156
2.18k
    ++position;
157
2.18k
  }
158
1.10k
  if (!digits) {
159
168
    return 0;
160
168
  }
161
940
  if (position < line.size() && line[position] == '+') {
162
54
    ++position;
163
54
  }
164
940
  return position + 1 == line.size() ? value : 0;
165
1.10k
}
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.15k
std::size_t ImapMockServer::AppendLiteralSize(std::string_view command) {
173
3.45k
  while (!command.empty() && (command.back() == '\r' || command.back() == '\n')) {
174
2.30k
    command.remove_suffix(1);
175
2.30k
  }
176
1.15k
  if (command.empty() || command.back() != '}') {
177
10
    return std::numeric_limits<std::size_t>::max();
178
10
  }
179
1.14k
  const std::size_t open = command.rfind('{');
180
1.14k
  if (open == std::string_view::npos) {
181
1
    return std::numeric_limits<std::size_t>::max();
182
1
  }
183
184
1.13k
  std::size_t position = open + 1;
185
1.13k
  std::size_t value = 0;
186
1.13k
  bool digits = false;
187
8.11k
  while (position < command.size() && command[position] >= '0' && command[position] <= '9') {
188
6.97k
    const std::size_t digit = static_cast<std::size_t>(command[position] - '0');
189
6.97k
    if (value > (std::numeric_limits<std::size_t>::max() - digit) / 10) {
190
0
      return std::numeric_limits<std::size_t>::max();
191
0
    }
192
6.97k
    value = value * 10 + digit;
193
6.97k
    digits = true;
194
6.97k
    ++position;
195
6.97k
  }
196
1.13k
  if (!digits) {
197
0
    return std::numeric_limits<std::size_t>::max();
198
0
  }
199
1.13k
  if (position < command.size() && command[position] == '+') {
200
0
    ++position;
201
0
  }
202
1.13k
  return position + 1 == command.size() ? value : std::numeric_limits<std::size_t>::max();
203
1.13k
}
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
10.5k
std::string ImapMockServer::RewriteReply(std::string_view response) const {
211
10.5k
  std::string output;
212
10.5k
  output.reserve(response.size() + 16);
213
214
10.5k
  std::size_t position = 0;
215
72.4k
  while (position < response.size()) {
216
61.9k
    const std::size_t newline = response.find('\n', position);
217
61.9k
    const std::size_t line_end = newline == std::string_view::npos ? response.size() : newline + 1;
218
61.9k
    const std::string_view line = response.substr(position, line_end - position);
219
220
61.9k
    if (!current_tag_.empty() && StatusLineNeedsTag(line)) {
221
6.69k
      output.append(current_tag_);
222
6.69k
      output.push_back(' ');
223
6.69k
    }
224
61.9k
    output.append(line);
225
226
61.9k
    const std::size_t literal = LiteralSize(line);
227
61.9k
    if (literal == 0) {
228
61.6k
      position = line_end;
229
61.6k
      continue;
230
61.6k
    }
231
232
300
    const std::size_t body_start = line_end;
233
300
    const std::size_t available = response.size() - body_start;
234
300
    const std::size_t body_size = std::min(literal, available);
235
300
    output.append(response.substr(body_start, body_size));
236
300
    position = body_start + body_size;
237
300
  }
238
10.5k
  return output;
239
10.5k
}
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
5.91k
std::string ImapMockServer::NextCommandTag() const {
248
5.91k
  std::size_t digits_start = current_tag_.size();
249
15.3k
  while (digits_start > 0 && current_tag_[digits_start - 1] >= '0' && current_tag_[digits_start - 1] <= '9') {
250
9.42k
    --digits_start;
251
9.42k
  }
252
5.91k
  if (digits_start == current_tag_.size() || digits_start == 0) {
253
2.79k
    return std::string();
254
2.79k
  }
255
256
3.12k
  std::uint64_t number = 0;
257
12.4k
  for (std::size_t index = digits_start; index < current_tag_.size(); ++index) {
258
9.36k
    number = number * 10 + static_cast<std::uint64_t>(current_tag_[index] - '0');
259
9.36k
    if (number > 999999) {
260
0
      return std::string();
261
0
    }
262
9.36k
  }
263
3.12k
  ++number;
264
265
3.12k
  std::string digits = std::to_string(number);
266
3.12k
  const std::size_t width = current_tag_.size() - digits_start;
267
3.12k
  if (digits.size() < width) {
268
3.11k
    digits.insert(0, width - digits.size(), '0');
269
3.11k
  }
270
3.12k
  return current_tag_.substr(0, digits_start) + digits;
271
3.12k
}
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
191k
void ImapMockServer::HandleLine(std::string_view command) {
281
191k
  if (scenario() == nullptr) {
282
1.07k
    return;
283
1.07k
  }
284
285
190k
  const bool authentication_payload = authentication_continuation_active_;
286
190k
  if (!authentication_payload) {
287
183k
    current_tag_ = std::string(FirstToken(command));
288
183k
  }
289
290
190k
  const std::string* response = NextControlReply();
291
190k
  if (response == nullptr) {
292
180k
    return;
293
180k
  }
294
295
10.1k
  const bool continuation = ResponseHasContinuation(*response);
296
10.1k
  const bool tagged_completion = ResponseHasTaggedCompletion(*response);
297
10.1k
  (void)WriteControlBytes(RewriteReply(*response));
298
299
10.1k
  if (authentication_payload) {
300
332
    if (tagged_completion) {
301
196
      authentication_continuation_active_ = false;
302
196
    }
303
332
    return;
304
332
  }
305
306
9.83k
  const std::string_view verb = SecondToken(command);
307
9.83k
  if (continuation && TokenEquals(verb, "AUTHENTICATE")) {
308
708
    authentication_continuation_active_ = !tagged_completion;
309
708
    return;
310
708
  }
311
312
9.13k
  if (!continuation || !TokenEquals(verb, "APPEND")) {
313
7.98k
    return;
314
7.98k
  }
315
316
1.15k
  const std::size_t literal = AppendLiteralSize(command);
317
1.15k
  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
11
    return;
322
11
  }
323
324
1.13k
  BeginLiteralBody(literal);
325
326
1.13k
  const std::string* final_response = NextControlReply();
327
1.13k
  if (final_response != nullptr) {
328
371
    (void)WriteControlBytes(RewriteReply(*final_response));
329
371
  }
330
1.13k
}
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
5.91k
void ImapMockServer::QueueShutdownReply() {
336
5.91k
  const std::string next_tag = NextCommandTag();
337
5.91k
  if (!next_tag.empty()) {
338
3.12k
    (void)WriteControlBytes(next_tag + std::string(kShutdownTail));
339
3.12k
  } else {
340
2.79k
    (void)WriteControlBytes("* BYE imap mock closing\r\n");
341
2.79k
  }
342
5.91k
}
343
344
/// Retain protocol outcomes in coverage and introspector builds.
345
6.43k
void ImapMockServer::ObserveState() {
346
6.43k
#if defined(PROTO_FUZZER_OBSERVE_STATE)
347
6.43k
  PingpongMockServer::ObserveState();
348
6.43k
  const volatile std::size_t imap_observation[] = {control_transcript().size(), uploaded_data().size()};
349
6.43k
  (void)imap_observation;
350
6.43k
#endif
351
6.43k
}
352
353
}  // namespace proto_fuzzer