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/smtp_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 SMTP peer.
9
10
#include "proto_fuzzer/smtp_mock_server.h"
11
12
#include <algorithm>
13
#include <cstddef>
14
#include <memory>
15
#include <string>
16
#include <string_view>
17
18
#include "proto_fuzzer/allocation_fault_injection.h"
19
#include "proto_fuzzer/mock_server.h"
20
#include "proto_fuzzer/scenario_limits.h"
21
22
namespace proto_fuzzer {
23
24
/// Begin without a borrowed protobuf or open socketpair. RunLoop borrows a
25
/// Scenario only for the synchronous DriveScenario call in which socket
26
/// callbacks can run.
27
/// @param mode Closed SMTP transport probe selected by target policy.
28
SmtpMockServer::SmtpMockServer(curl::fuzzer::proto::SmtpProbeMode mode)
29
6.02k
    : recipient_count_(0),
30
6.02k
      rcpt_command_count_(0),
31
6.02k
      auth_exchange_active_(false),
32
6.02k
      mode_(mode),
33
6.02k
      tls_upgrade_started_(false) {}
34
35
/// Release the server-owned socketpair half after curl has returned its client
36
/// descriptor. The out-of-line destructor keeps MockConnection's complete type
37
/// local to this translation unit.
38
6.02k
SmtpMockServer::~SmtpMockServer() = default;
39
40
namespace {
41
42
/// A fixed command large enough to leave curl's pingpong send queue pending
43
/// under the probe's bounded receive-buffer pressure.
44
/// @return Process-lifetime command bytes copied by CURLOPT_CUSTOMREQUEST.
45
1
const std::string& SendBackpressureCommand() {
46
1
  static const std::string command = "NOOP " + std::string(16 * 1024, 'S');
47
1
  return command;
48
1
}
49
50
}  // namespace
51
52
/// Apply only closed, harness-owned client controls. The ordinary scenario
53
/// option list has already run when the production runner calls this hook.
54
/// @param easy Easy handle configured for the SMTP transfer.
55
6.00k
void SmtpMockServer::ConfigureClient(CURL* easy) const {
56
6.00k
  if (easy == nullptr) {
57
0
    return;
58
0
  }
59
6.00k
  switch (mode_) {
60
1
    case curl::fuzzer::proto::SMTP_PROBE_STARTTLS_TRY:
61
1
      (void)curl_easy_setopt(easy, CURLOPT_USE_SSL, static_cast<long>(CURLUSESSL_TRY));
62
1
      break;
63
3
    case curl::fuzzer::proto::SMTP_PROBE_STARTTLS_REQUIRE:
64
4
    case curl::fuzzer::proto::SMTP_PROBE_STARTTLS_FILTER_ALLOCATION_FAILURE:
65
4
      (void)curl_easy_setopt(easy, CURLOPT_USE_SSL, static_cast<long>(CURLUSESSL_ALL));
66
4
      break;
67
1
    case curl::fuzzer::proto::SMTP_PROBE_SEND_BACKPRESSURE:
68
1
      (void)curl_easy_setopt(easy, CURLOPT_UPLOAD, 0L);
69
1
      (void)curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, SendBackpressureCommand().c_str());
70
1
      break;
71
5.99k
    case curl::fuzzer::proto::SMTP_PROBE_DEFAULT:
72
5.99k
    default:
73
5.99k
      break;
74
6.00k
  }
75
6.00k
}
76
77
/// Create the default plaintext transport for the SMTP exchange. The SMTPS
78
/// subclass overrides this factory while retaining the command/reply parser.
79
/// @return A new socketpair-backed connection.
80
2.18k
std::unique_ptr<MockConnection> SmtpMockServer::CreateConnection() { return std::make_unique<MockConnection>(); }
81
82
/// Reset SMTP's recipient bookkeeping for a new drive. The shared base has
83
/// already cleared the transport, reply cursor, transcript, upload capture,
84
/// and any in-flight body phase.
85
5.90k
void SmtpMockServer::ResetProtocolState() {
86
5.90k
  const curl::fuzzer::proto::Scenario* script = scenario();
87
5.90k
  recipient_count_ = script == nullptr ? 0
88
5.90k
                                       : std::min<std::size_t>(scenario_limits::kMaxMailRecipients,
89
5.90k
                                                               static_cast<std::size_t>(script->mail_rcpt_size()));
90
5.90k
  rcpt_command_count_ = 0;
91
5.90k
  auth_exchange_active_ = false;
92
5.90k
  tls_upgrade_started_ = false;
93
5.90k
}
94
95
/// Return whether the selected probe asks curl to issue STARTTLS.
96
/// @return true when STARTTLS is enabled by the closed probe mode.
97
7
bool SmtpMockServer::IsStartTlsMode() const {
98
7
  return mode_ == curl::fuzzer::proto::SMTP_PROBE_STARTTLS_TRY ||
99
5
         mode_ == curl::fuzzer::proto::SMTP_PROBE_STARTTLS_REQUIRE ||
100
1
         mode_ == curl::fuzzer::proto::SMTP_PROBE_STARTTLS_FILTER_ALLOCATION_FAILURE;
101
7
}
102
103
/// Return whether the effective option list enables curl's
104
/// CURLOPT_MAIL_RCPT_ALLOWFAILS behavior. Scan backwards because repeated
105
/// setopt calls are legal and libcurl keeps the last value.
106
/// @return true when recipient errors may be followed by another RCPT TO.
107
478
bool SmtpMockServer::AllowsRecipientFailures() const {
108
478
  const curl::fuzzer::proto::Scenario* script = scenario();
109
478
  if (script == nullptr) {
110
0
    return false;
111
0
  }
112
1.20k
  for (int index = script->options_size() - 1; index >= 0; --index) {
113
757
    const auto& option = script->options(index);
114
757
    if (option.option_id() != curl::fuzzer::proto::CURLOPT_MAIL_RCPT_ALLOWFAILS) {
115
724
      continue;
116
724
    }
117
33
    if (option.value_case() == curl::fuzzer::proto::SetOption::kBoolValue) {
118
33
      return option.bool_value();
119
33
    }
120
0
    if (option.value_case() == curl::fuzzer::proto::SetOption::kUintValue) {
121
0
      return option.uint_value() != 0;
122
0
    }
123
0
    return false;
124
0
  }
125
445
  return false;
126
478
}
127
128
/// Scan complete lines because a legal SMTP response fragment may start with
129
/// one or more informational lines. curl ends a response at the first line
130
/// whose first three bytes are digits and whose fourth byte is a space.
131
/// @param response Raw control fragment.
132
/// @return numeric status, or -1 when no terminating line is present.
133
9.02k
int SmtpMockServer::FirstReplyCode(std::string_view response) {
134
9.02k
  std::size_t line_start = 0;
135
125k
  while (line_start < response.size()) {
136
124k
    const std::size_t newline = response.find('\n', line_start);
137
124k
    if (newline == std::string_view::npos) {
138
1.01k
      return -1;
139
1.01k
    }
140
123k
    const std::size_t line_size = newline - line_start + 1;
141
123k
    if (line_size > 3) {
142
18.9k
      const unsigned char first = static_cast<unsigned char>(response[line_start]);
143
18.9k
      const unsigned char second = static_cast<unsigned char>(response[line_start + 1]);
144
18.9k
      const unsigned char third = static_cast<unsigned char>(response[line_start + 2]);
145
18.9k
      if (first >= '0' && first <= '9' && second >= '0' && second <= '9' && third >= '0' && third <= '9' &&
146
13.4k
          response[line_start + 3] == ' ') {
147
6.61k
        return 100 * (first - '0') + 10 * (second - '0') + (third - '0');
148
6.61k
      }
149
18.9k
    }
150
116k
    line_start = newline + 1;
151
116k
  }
152
1.39k
  return -1;
153
9.02k
}
154
155
/// Advance one reply for every complete command. A successful DATA reply
156
/// switches the parser into body-draining mode. The reply that follows DATA is
157
/// queued immediately: curl's smtp_done() runs a blocking POSTDATA wait inside
158
/// curl_multi_perform, so the outer peer service loop cannot run after the body
159
/// has been written. Pre-queuing it, as the FTP peer does for its final
160
/// transfer reply, keeps that wait deterministic without changing the order
161
/// curl observes (354 first, then the post-body response).
162
/// @param command One newline-terminated command from curl.
163
1.06M
void SmtpMockServer::HandleLine(std::string_view command) {
164
1.06M
  const std::string_view verb = FirstToken(command);
165
1.06M
  const bool is_auth_continuation_reply = auth_exchange_active_;
166
167
1.06M
  const std::string* response = NextControlReply();
168
1.06M
  if (response == nullptr) {
169
1.05M
    return;
170
1.05M
  }
171
172
9.02k
  const int response_code = FirstReplyCode(*response);
173
9.02k
  const bool response_written = WriteControlBytes(*response);
174
175
9.02k
  if (TokenEquals(verb, "STARTTLS") && IsStartTlsMode() && response_code == 220) {
176
3
    if (response_written && mode_ == curl::fuzzer::proto::SMTP_PROBE_STARTTLS_FILTER_ALLOCATION_FAILURE) {
177
1
      allocation_fault_injection::ArmNextAllocationFailure();
178
1
    }
179
3
    tls_upgrade_started_ = true;
180
3
    BeginOpaqueDrain();
181
3
    ShutdownControlWrite();
182
3
    return;
183
3
  }
184
185
9.01k
  if (TokenEquals(verb, "AUTH")) {
186
    // A 334 reply is the only wire-visible distinction between SMTP AUTH and
187
    // a mutation-selected custom command that happens to start with AUTH.
188
177
    auth_exchange_active_ = response_code == 334;
189
8.84k
  } else if (is_auth_continuation_reply) {
190
108
    if (TokenEquals(verb, "*")) {
191
      // Curl accepts the cancellation reply before trying another enabled
192
      // SASL mechanism, so the exchange remains active across this error.
193
33
      auth_exchange_active_ = true;
194
75
    } else if (response_code != 334) {
195
70
      auth_exchange_active_ = false;
196
70
    }
197
108
  }
198
199
9.01k
  if (TokenEquals(verb, "DATA")) {
200
1.42k
    if (response_code == 354) {
201
978
      BeginMarkerBody(kEndOfBody);
202
978
      (void)WriteNextReply();
203
978
    } else if (response_code > 0) {
204
      // curl treats every non-354 DATA reply as terminal. Pre-queue the
205
      // shutdown reply so its blocking cleanup QUIT does not wait one second.
206
137
      (void)WriteControlBytes(kShutdownReply);
207
137
    }
208
1.42k
    return;
209
1.42k
  }
210
211
7.58k
  if (TokenEquals(verb, "RCPT")) {
212
1.99k
    ++rcpt_command_count_;
213
1.99k
  }
214
215
  // A terminal command error is followed by curl's blocking QUIT during
216
  // teardown. EHLO errors fall back to HELO, an early RCPT error may still be
217
  // followed by another recipient, and a failed AUTH exchange can cancel and
218
  // retry another mechanism. Those replies must not consume the shutdown
219
  // reply. Everything else can safely see a queued 221 next.
220
7.58k
  const bool final_rcpt_error =
221
7.58k
      TokenEquals(verb, "RCPT") && (rcpt_command_count_ >= recipient_count_ || !AllowsRecipientFailures());
222
7.58k
  const bool starttls_denial = TokenEquals(verb, "STARTTLS") && IsStartTlsMode();
223
7.58k
  const bool terminal_error = response_code >= 400 && !TokenEquals(verb, "EHLO") && !starttls_denial &&
224
42
                              !is_auth_continuation_reply && (!TokenEquals(verb, "RCPT") || final_rcpt_error);
225
7.58k
  if (terminal_error) {
226
24
    (void)WriteControlBytes(kShutdownReply);
227
24
  }
228
7.58k
}
229
230
/// Queue a 221 before the shared transport half-closes. SMTP's blocking QUIT
231
/// read has a one-second timeout when no reply is available, so even an
232
/// unfinished transfer gets a liveness reply; any real scripted response
233
/// already consumed by curl still determines the transfer result.
234
5.44k
void SmtpMockServer::QueueShutdownReply() {
235
5.44k
  if (!tls_upgrade_started_) {
236
5.44k
    (void)WriteControlBytes(kShutdownReply);
237
5.44k
  }
238
5.44k
}
239
240
/// Retain protocol outcomes in coverage and introspector builds.
241
6.00k
void SmtpMockServer::ObserveState() {
242
6.00k
#if defined(PROTO_FUZZER_OBSERVE_STATE)
243
6.00k
  PingpongMockServer::ObserveState();
244
6.00k
  const volatile std::size_t smtp_observation[] = {control_transcript().size(), uploaded_data().size()};
245
6.00k
  (void)smtp_observation;
246
6.00k
#endif
247
6.00k
}
248
249
}  // namespace proto_fuzzer