Coverage Report

Created: 2026-12-01 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl_fuzzer/proto_fuzzer/ftp_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 FTP peer.
9
10
#include "proto_fuzzer/ftp_mock_server.h"
11
12
#include <fcntl.h>
13
#include <netinet/in.h>
14
#include <sys/socket.h>
15
#include <unistd.h>
16
17
#include <algorithm>
18
#include <cerrno>
19
#include <cstddef>
20
#include <cstdint>
21
#include <cstring>
22
#include <limits>
23
#include <memory>
24
#include <string>
25
#include <string_view>
26
27
#include "proto_fuzzer/allocation_fault_injection.h"
28
#include "proto_fuzzer/mock_server.h"
29
#include "proto_fuzzer/scenario_limits.h"
30
31
namespace proto_fuzzer {
32
33
/// Begin without a borrowed protobuf or open socketpairs. RunLoop borrows a
34
/// Scenario only for the synchronous DriveScenario call in which socket callbacks
35
/// can run. Keeping all session state in the object avoids process globals that
36
/// could leak one libFuzzer iteration's protocol position into the next.
37
FtpMockServer::FtpMockServer()
38
10.0k
    : scenario_(nullptr),
39
10.0k
      next_data_script_(0),
40
10.0k
      active_listener_fd_(-1),
41
10.0k
      active_listener_client_fd_(CURL_SOCKET_BAD),
42
10.0k
      pending_active_channel_(kMaxDataChannels),
43
10.0k
      control_reply_count_(0),
44
10.0k
      next_control_reply_(0),
45
10.0k
      prequeued_control_replies_(0),
46
10.0k
      active_pollset_probe_count_(0),
47
10.0k
      control_opened_(false) {}
48
49
/// Release server-owned descriptors and socketpair peers after curl has returned
50
/// its client fds. Loopback peers are unique_ptr-owned transports; the out-of-line
51
/// destructor also permits MockConnection to remain forward-declared in the
52
/// header.
53
10.0k
FtpMockServer::~FtpMockServer() { ReleaseConnections(); }
54
55
/// Create the default plaintext transport for the control and passive data
56
/// connections. The implicit-TLS FTPS subclass overrides this factory while
57
/// retaining the command parser and channel bookkeeping.
58
/// @return A new socketpair-backed connection.
59
11.3k
std::unique_ptr<MockConnection> FtpMockServer::CreateConnection() { return std::make_unique<MockConnection>(); }
60
61
/// Plain FTP can create and publish a real loopback listener for PORT/EPRT.
62
/// Subclasses that only expose wrapped socketpairs override this to keep the
63
/// active-mode request from producing an unusable plaintext endpoint.
64
/// @return true for the plaintext FTP peer.
65
251
bool FtpMockServer::SupportsActiveMode() const { return true; }
66
67
/// Retain decoded client bytes for the control parser. Data channels install
68
/// their own observer so upload bodies are routed without mixing them into the
69
/// command stream.
70
/// @param data First decoded byte.
71
/// @param size Number of bytes available at `data`.
72
59.6k
void FtpMockServer::ObserveIncomingData(const unsigned char* data, std::size_t size) {
73
59.6k
  if (data == nullptr || size == 0) {
74
0
    return;
75
0
  }
76
59.6k
  pending_control_bytes_.append(reinterpret_cast<const char*>(data), size);
77
59.6k
}
78
79
/// Append decoded bytes from one passive data channel. The bytes are captured
80
/// only while the channel is an upload; download channels still drain their
81
/// transport but discard any unexpected client payload after decoding.
82
/// @param data First decoded byte.
83
/// @param size Number of bytes available at `data`.
84
5.06k
void FtpMockServer::DataChannel::ObserveIncomingData(const unsigned char* data, std::size_t size) {
85
5.06k
  if (data == nullptr || size == 0) {
86
0
    return;
87
0
  }
88
5.06k
  incoming_data.append(reinterpret_cast<const char*>(data), size);
89
5.06k
}
90
91
/// Expose the bounded command capture from the most recent drive so tests can
92
/// verify FTP states without coupling assertions to curl debug output. The
93
/// capture is bounded independently of protocol processing.
94
/// @return A prefix of complete control commands, including line endings.
95
9.96k
const std::string& FtpMockServer::control_transcript() const { return control_transcript_; }
96
97
/// Expose a bounded upload prefix from the most recent drive while continuing
98
/// to drain all client bytes, so test observability cannot create backpressure.
99
/// @return Bytes curl sent over passive upload connections.
100
9.96k
const std::string& FtpMockServer::uploaded_data() const { return uploaded_data_; }
101
102
/// Report how many bounded data scripts curl assigned to passive or active
103
/// transfer sockets, rather than how many scripts the protobuf contains. Tests
104
/// can distinguish control-only failures from paths that reached data setup.
105
/// @return Number of bounded data scripts assigned to a transfer socket.
106
9.96k
std::size_t FtpMockServer::opened_data_connection_count() const { return next_data_script_; }
107
108
/// Report how many requested zero-timeout multi-poll probes ran during the
109
/// most recent drive. RunLoop increments this only after a successful perform
110
/// turn while curl still owns an active transfer and the control socket is
111
/// open.
112
/// @return Number of active FTP pollset probes in the previous drive.
113
0
std::size_t FtpMockServer::active_pollset_probe_count() const { return active_pollset_probe_count_; }
114
115
/// Close every server-owned transport before the borrowed scenario or a
116
/// subclass transport disappears. The out-of-line definition keeps
117
/// MockConnection complete here while the header only forward-declares it.
118
21.8k
void FtpMockServer::ReleaseConnections() {
119
21.8k
  CloseActiveDescriptors();
120
21.8k
  control_connection_.reset();
121
65.4k
  for (DataChannel& channel : data_channels_) {
122
65.4k
    channel.connection.reset();
123
65.4k
    channel.incoming_data.clear();
124
65.4k
  }
125
21.8k
}
126
127
/// Reset every borrowed pointer, descriptor, parser cursor, and observable
128
/// capture before borrowing the next Scenario. A server can be reused serially,
129
/// but no connection or response cursor is meaningful across easy-handle drives.
130
9.87k
void FtpMockServer::ResetForScenario(const curl::fuzzer::proto::Scenario& scenario) {
131
9.87k
  ReleaseConnections();
132
29.6k
  for (DataChannel& channel : data_channels_) {
133
29.6k
    channel.script = nullptr;
134
29.6k
    channel.transfer_started = false;
135
29.6k
    channel.upload = false;
136
29.6k
  }
137
138
9.87k
  scenario_ = &scenario;
139
9.87k
  next_data_script_ = 0;
140
9.87k
  pending_active_channel_ = kMaxDataChannels;
141
9.87k
  control_reply_count_ = std::min<std::size_t>(scenario_limits::kMaxResponseChunks,
142
9.87k
                                               static_cast<std::size_t>(scenario.connection().on_readable_size()));
143
9.87k
  next_control_reply_ = 0;
144
9.87k
  prequeued_control_replies_ = 0;
145
9.87k
  pending_control_bytes_.clear();
146
9.87k
  control_transcript_.clear();
147
9.87k
  uploaded_data_.clear();
148
9.87k
  active_pollset_probe_count_ = 0;
149
9.87k
  control_opened_ = false;
150
9.87k
}
151
152
/// Close only peer-owned active-mode descriptors before reuse or destruction.
153
/// Curl owns every listener fd returned by HandleOpenSocket;
154
/// active_listener_fd_ is a private duplicate.
155
21.8k
void FtpMockServer::CloseActiveDescriptors() {
156
21.8k
  active_listener_client_fd_ = CURL_SOCKET_BAD;
157
21.8k
  if (active_listener_fd_ >= 0) {
158
0
    close(active_listener_fd_);
159
0
    active_listener_fd_ = -1;
160
0
  }
161
65.4k
  for (DataChannel& channel : data_channels_) {
162
65.4k
    if (channel.active_fd >= 0) {
163
165
      close(channel.active_fd);
164
165
      channel.active_fd = -1;
165
165
    }
166
65.4k
  }
167
21.8k
  pending_active_channel_ = kMaxDataChannels;
168
21.8k
}
169
170
/// Apply bounded transport knobs when creating a scripted socket. Clamp a
171
/// compatibility input's raw protobuf socket size before crossing the platform
172
/// int boundary. Target policies normally clear FTP backpressure, but direct
173
/// corpus replay must retain deterministic, well-defined behavior.
174
14.0k
void FtpMockServer::ApplyScriptBackpressure(MockConnection* connection, const curl::fuzzer::proto::Connection& script) {
175
14.0k
  if (connection == nullptr) {
176
0
    return;
177
0
  }
178
179
14.0k
  const std::uint32_t int_max = static_cast<std::uint32_t>(std::numeric_limits<int>::max());
180
14.0k
  const auto& backpressure = script.backpressure();
181
14.0k
  const int receive_buffer = static_cast<int>(std::min(backpressure.recv_buf_bytes(), int_max));
182
14.0k
  connection->ApplyBackpressure(receive_buffer, static_cast<std::size_t>(backpressure.drain_limit()));
183
14.0k
}
184
185
/// Return whether the final FTPPORT setopt retained by the Scenario selected
186
/// active mode. Target policy constrains the actual value to loopback.
187
5.02k
bool FtpMockServer::UsesActiveMode() const {
188
5.02k
  if (scenario_ == nullptr) {
189
0
    return false;
190
0
  }
191
11.8k
  for (int index = scenario_->options_size() - 1; index >= 0; --index) {
192
7.10k
    const auto& option = scenario_->options(index);
193
7.10k
    if (option.option_id() == curl::fuzzer::proto::CURLOPT_FTPPORT) {
194
251
      return option.value_case() == curl::fuzzer::proto::SetOption::kStringValue && !option.string_value().empty();
195
251
    }
196
7.10k
  }
197
4.77k
  return false;
198
5.02k
}
199
200
/// Control/passive sockets are connected AF_UNIX pairs, while active FTP
201
/// needs curl to bind and listen on the real TCP descriptor returned by
202
/// OpenActiveListener. The descriptor identity is recorded when opened, so
203
/// this decision never depends on a sandbox-sensitive getsockopt call.
204
/// @param curlfd Descriptor returned by HandleOpenSocket.
205
/// @param purpose Role curl assigned to the descriptor.
206
/// @return Whether curl must perform its normal socket setup.
207
14.2k
SocketSetupDisposition FtpMockServer::GetSocketSetupDisposition(curl_socket_t curlfd, curlsocktype purpose) const {
208
14.2k
  if (purpose == CURLSOCKTYPE_ACCEPT || curlfd == active_listener_client_fd_) {
209
167
    return SocketSetupDisposition::kNeedsSetup;
210
167
  }
211
14.0k
  return SocketSetupDisposition::kAlreadyConnected;
212
14.2k
}
213
214
/// Give curl a genuine INET socket for bind/listen while retaining a duplicate
215
/// that can discover the ephemeral loopback port afterwards, without parsing
216
/// curl's generated PORT/EPRT command.
217
251
curl_socket_t FtpMockServer::OpenActiveListener(struct curl_sockaddr* address) {
218
251
  if (address == nullptr || (address->family != AF_INET && address->family != AF_INET6)) {
219
0
    return CURL_SOCKET_BAD;
220
0
  }
221
222
251
  if (pending_active_channel_ == kMaxDataChannels) {
223
222
    const std::size_t available_scripts =
224
222
        std::min<std::size_t>(kMaxDataChannels, static_cast<std::size_t>(scenario_->subsequent_connections_size()));
225
222
    if (next_data_script_ >= available_scripts) {
226
7
      return CURL_SOCKET_BAD;
227
7
    }
228
215
    pending_active_channel_ = next_data_script_++;
229
215
    DataChannel& channel = data_channels_[pending_active_channel_];
230
215
    channel.script = &scenario_->subsequent_connections(static_cast<int>(pending_active_channel_));
231
215
  }
232
233
244
  if (active_listener_fd_ >= 0) {
234
29
    close(active_listener_fd_);
235
29
    active_listener_fd_ = -1;
236
29
  }
237
244
  active_listener_client_fd_ = CURL_SOCKET_BAD;
238
239
244
  const int listener = socket(address->family, address->socktype, address->protocol);
240
244
  if (listener < 0) {
241
0
    return CURL_SOCKET_BAD;
242
0
  }
243
244
  active_listener_fd_ = dup(listener);
244
244
  if (active_listener_fd_ < 0) {
245
0
    close(listener);
246
0
    return CURL_SOCKET_BAD;
247
0
  }
248
244
  active_listener_client_fd_ = listener;
249
244
  (void)fcntl(active_listener_fd_, F_SETFD, FD_CLOEXEC);
250
244
  return listener;
251
244
}
252
253
/// Allocate one control socket followed by a bounded sequence of passive data
254
/// sockets, or a real listener when CURLOPT_FTPPORT selected active mode.
255
/// Data is intentionally not preloaded here: curl has not yet sent the command
256
/// that determines whether the stream is a listing, download, or upload.
257
/// @param purpose Socket role requested by curl.
258
/// @param address Mutable description of curl's intended destination.
259
/// @return Client descriptor for the selected FTP channel, or
260
///         CURL_SOCKET_BAD when no channel is available.
261
14.4k
curl_socket_t FtpMockServer::HandleOpenSocket(curlsocktype purpose, struct curl_sockaddr* address) {
262
14.4k
  if (scenario_ == nullptr || purpose != CURLSOCKTYPE_IPCXN) {
263
0
    return CURL_SOCKET_BAD;
264
0
  }
265
266
14.4k
  if (!control_opened_) {
267
9.40k
    control_connection_ = CreateConnection();
268
9.40k
    if (!control_connection_ || !control_connection_->ok()) {
269
0
      control_connection_.reset();
270
0
      return CURL_SOCKET_BAD;
271
0
    }
272
9.40k
    control_connection_->SetIncomingDataObserver(this);
273
274
9.40k
    ApplyScriptBackpressure(control_connection_.get(), scenario_->connection());
275
9.40k
    const std::string& greeting = scenario_->connection().initial_response();
276
9.40k
    if (!greeting.empty() &&
277
6.87k
        !control_connection_->WriteAll(reinterpret_cast<const unsigned char*>(greeting.data()), greeting.size())) {
278
0
      control_connection_.reset();
279
0
      return CURL_SOCKET_BAD;
280
0
    }
281
    // Do not consume the unique control slot until its peer is usable. Curl
282
    // may retry a failed application socket callback, and that retry must not
283
    // be mistaken for the first passive data connection.
284
9.40k
    control_opened_ = true;
285
9.40k
    return control_connection_->take_client_fd();
286
9.40k
  }
287
288
5.02k
  if (UsesActiveMode()) {
289
    // A TLS peer owns only wrapped socketpairs, so it cannot hand curl a real
290
    // listener that its data TLS server could later answer. Reject the request
291
    // immediately: the target policy already removes CURLOPT_FTPPORT, and this
292
    // guard keeps direct callers on a bounded failure instead of an unusable
293
    // plaintext data channel.
294
251
    if (!SupportsActiveMode()) {
295
0
      return CURL_SOCKET_BAD;
296
0
    }
297
251
    return OpenActiveListener(address);
298
251
  }
299
300
4.77k
  const std::size_t available_scripts =
301
4.77k
      std::min<std::size_t>(kMaxDataChannels, static_cast<std::size_t>(scenario_->subsequent_connections_size()));
302
4.77k
  if (next_data_script_ >= available_scripts) {
303
106
    return CURL_SOCKET_BAD;
304
106
  }
305
306
4.66k
  DataChannel& channel = data_channels_[next_data_script_];
307
4.66k
  channel.script = &scenario_->subsequent_connections(static_cast<int>(next_data_script_));
308
4.66k
  channel.connection = CreateConnection();
309
4.66k
  if (!channel.connection || !channel.connection->ok()) {
310
0
    channel.connection.reset();
311
0
    channel.script = nullptr;
312
0
    return CURL_SOCKET_BAD;
313
0
  }
314
4.66k
  channel.connection->SetIncomingDataObserver(&channel);
315
316
4.66k
  ApplyScriptBackpressure(channel.connection.get(), *channel.script);
317
4.66k
  ++next_data_script_;
318
4.66k
  return channel.connection->take_client_fd();
319
4.66k
}
320
321
/// Retry writes only while they can make immediate progress. Scenario bytes
322
/// are bounded, and dropping a suffix on EAGAIN is preferable to introducing
323
/// a wall-clock wait into one fuzz iteration.
324
63
bool FtpMockServer::WriteActiveBytes(int fd, const unsigned char* data, std::size_t size) {
325
63
  std::size_t offset = 0;
326
126
  while (offset < size) {
327
63
    const ssize_t written = send(fd, data + offset, size - offset, MSG_NOSIGNAL | MSG_DONTWAIT);
328
63
    if (written > 0) {
329
63
      offset += static_cast<std::size_t>(written);
330
63
      continue;
331
63
    }
332
0
    if (written < 0 && errno == EINTR) {
333
0
      continue;
334
0
    }
335
0
    return false;
336
0
  }
337
63
  return true;
338
63
}
339
340
/// Drain an active upload without waiting for curl. The accepted peer is
341
/// nonblocking and the outer perform loop calls this again after more output.
342
62
bool FtpMockServer::ReadActiveBytes(int fd, std::string* output) {
343
62
  bool made_progress = false;
344
62
  char buffer[16 * 1024];
345
76
  for (;;) {
346
76
    const ssize_t amount = recv(fd, buffer, sizeof(buffer), MSG_DONTWAIT);
347
76
    if (amount > 0) {
348
14
      output->append(buffer, static_cast<std::size_t>(amount));
349
14
      made_progress = true;
350
14
      continue;
351
14
    }
352
62
    if (amount < 0 && errno == EINTR) {
353
0
      continue;
354
0
    }
355
62
    return made_progress;
356
62
  }
357
62
}
358
359
/// Connect to curl's exact listener after queuing a successful PORT/EPRT
360
/// response. Since active_listener_fd_ duplicates that socket, getsockname
361
/// observes the assigned port without trusting or reparsing control bytes.
362
204
void FtpMockServer::ConnectActiveDataChannel() {
363
204
  if (active_listener_fd_ < 0 || pending_active_channel_ >= kMaxDataChannels) {
364
39
    return;
365
39
  }
366
367
165
  struct sockaddr_storage address;
368
165
  std::memset(&address, 0, sizeof(address));
369
165
  socklen_t address_length = sizeof(address);
370
165
  if (getsockname(active_listener_fd_, reinterpret_cast<struct sockaddr*>(&address), &address_length) != 0) {
371
0
    return;
372
0
  }
373
374
165
  const int fd = socket(address.ss_family, SOCK_STREAM, IPPROTO_TCP);
375
165
  if (fd < 0) {
376
0
    return;
377
0
  }
378
165
  if (connect(fd, reinterpret_cast<struct sockaddr*>(&address), address_length) != 0) {
379
0
    close(fd);
380
0
    return;
381
0
  }
382
165
  const int flags = fcntl(fd, F_GETFL, 0);
383
165
  if (flags >= 0) {
384
165
    (void)fcntl(fd, F_SETFL, flags | O_NONBLOCK);
385
165
  }
386
165
  (void)fcntl(fd, F_SETFD, FD_CLOEXEC);
387
388
165
  DataChannel& channel = data_channels_[pending_active_channel_];
389
165
  channel.active_fd = fd;
390
165
  close(active_listener_fd_);
391
165
  active_listener_fd_ = -1;
392
165
  active_listener_client_fd_ = CURL_SOCKET_BAD;
393
165
  pending_active_channel_ = kMaxDataChannels;
394
165
}
395
396
/// Retain only a bounded prefix for assertions. Parsing and draining continue
397
/// against the full transport bytes, so reaching the cap cannot change curl's
398
/// behavior or manufacture socket backpressure.
399
/// @param source Newly observed bytes.
400
/// @param limit Maximum retained destination size.
401
/// @param destination Capture buffer receiving the available prefix.
402
72.2k
void FtpMockServer::CapturePrefix(std::string_view source, std::size_t limit, std::string* destination) {
403
72.2k
  if (destination == nullptr || destination->size() >= limit) {
404
89
    return;
405
89
  }
406
72.2k
  const std::size_t available = limit - destination->size();
407
72.2k
  destination->append(source.data(), std::min(source.size(), available));
408
72.2k
}
409
410
/// Remove FTP's optional leading horizontal whitespace and return just the
411
/// verb without allocating. Arguments remain untouched because only curl, not
412
/// the mock harness, should interpret fuzzed paths and offsets.
413
/// @param command Complete command line.
414
/// @return View of its first non-whitespace token.
415
29.7k
std::string_view FtpMockServer::CommandVerb(std::string_view command) {
416
29.7k
  std::size_t begin = 0;
417
30.7k
  while (begin < command.size() && (command[begin] == ' ' || command[begin] == '\t')) {
418
951
    ++begin;
419
951
  }
420
421
29.7k
  std::size_t end = begin;
422
279k
  while (end < command.size() && command[end] != ' ' && command[end] != '\t' && command[end] != '\r' &&
423
250k
         command[end] != '\n') {
424
249k
    ++end;
425
249k
  }
426
29.7k
  return command.substr(begin, end - begin);
427
29.7k
}
428
429
/// Fold only ASCII lowercase command letters. FTP verbs are ASCII tokens, so
430
/// locale-aware case conversion would add state and undefined signed-char
431
/// behavior without accepting anything curl can legitimately send.
432
/// @param verb Parsed command token.
433
/// @param expected_uppercase Literal uppercase command name.
434
/// @return true when the verbs are equal ignoring ASCII case.
435
222k
bool FtpMockServer::VerbEquals(std::string_view verb, std::string_view expected_uppercase) {
436
222k
  if (verb.size() != expected_uppercase.size()) {
437
89.5k
    return false;
438
89.5k
  }
439
163k
  for (std::size_t index = 0; index < verb.size(); ++index) {
440
159k
    unsigned char actual = static_cast<unsigned char>(verb[index]);
441
159k
    if (actual >= 'a' && actual <= 'z') {
442
2.15k
      actual = static_cast<unsigned char>(actual - 'a' + 'A');
443
2.15k
    }
444
159k
    if (actual != static_cast<unsigned char>(expected_uppercase[index])) {
445
128k
      return false;
446
128k
    }
447
159k
  }
448
4.07k
  return true;
449
132k
}
450
451
/// Recognize curl's built-in data commands plus MLSD, the useful structured
452
/// listing custom request. PRET deliberately remains control-only even though
453
/// its argument can contain RETR/STOR: no data transfer has begun at that
454
/// point.
455
/// @param verb Parsed FTP command verb.
456
/// @return transfer direction, or kNone for control-only commands.
457
28.4k
FtpMockServer::TransferDirection FtpMockServer::DirectionForVerb(std::string_view verb) {
458
28.4k
  if (VerbEquals(verb, "STOR") || VerbEquals(verb, "APPE")) {
459
372
    return TransferDirection::kUpload;
460
372
  }
461
28.0k
  if (VerbEquals(verb, "RETR") || VerbEquals(verb, "LIST") || VerbEquals(verb, "NLST") || VerbEquals(verb, "MLSD")) {
462
2.63k
    return TransferDirection::kDownload;
463
2.63k
  }
464
25.4k
  return TransferDirection::kNone;
465
28.0k
}
466
467
/// Recognize the final CURLOPT_CUSTOMREQUEST value as a data command. Curl uses
468
/// it in place of LIST, so mutations need not rediscover a built-in allowed verb
469
/// before releasing the passive payload. Scan backwards because repeated setopt
470
/// calls are legal and libcurl keeps the last value. Comparing only the verb
471
/// preserves arbitrary custom arguments while avoiding false positives on
472
/// preparatory commands that receive a fuzzed 125/150 reply after EPSV.
473
/// @param verb Parsed command token sent by curl.
474
/// @return true when verb matches the effective custom request option.
475
25.4k
bool FtpMockServer::IsConfiguredCustomDownload(std::string_view verb) const {
476
25.4k
  if (scenario_ == nullptr || verb.empty()) {
477
677
    return false;
478
677
  }
479
480
52.3k
  for (int index = scenario_->options_size() - 1; index >= 0; --index) {
481
28.9k
    const auto& option = scenario_->options(index);
482
28.9k
    if (option.option_id() != curl::fuzzer::proto::CURLOPT_CUSTOMREQUEST) {
483
27.6k
      continue;
484
27.6k
    }
485
1.32k
    if (option.value_case() != curl::fuzzer::proto::SetOption::kStringValue) {
486
0
      return false;
487
0
    }
488
1.32k
    return VerbEquals(verb, CommandVerb(option.string_value()));
489
1.32k
  }
490
23.4k
  return false;
491
24.7k
}
492
493
/// Scan complete lines because a legal FTP response fragment may start with
494
/// one or more informational lines. curl ends a response at the first line
495
/// whose first three bytes are digits and whose fourth byte is a space.
496
/// @param response Raw control fragment.
497
/// @return numeric status, or -1 when no terminating line is present.
498
30.2k
int FtpMockServer::FirstReplyCode(std::string_view response) {
499
30.2k
  std::size_t line_start = 0;
500
585k
  while (line_start < response.size()) {
501
584k
    const std::size_t newline = response.find('\n', line_start);
502
584k
    if (newline == std::string_view::npos) {
503
2.79k
      return -1;
504
2.79k
    }
505
581k
    const std::size_t line_size = newline - line_start + 1;
506
581k
    if (line_size > 3) {
507
37.1k
      const unsigned char first = static_cast<unsigned char>(response[line_start]);
508
37.1k
      const unsigned char second = static_cast<unsigned char>(response[line_start + 1]);
509
37.1k
      const unsigned char third = static_cast<unsigned char>(response[line_start + 2]);
510
37.1k
      if (first >= '0' && first <= '9' && second >= '0' && second <= '9' && third >= '0' && third <= '9' &&
511
26.7k
          response[line_start + 3] == ' ') {
512
25.9k
        return 100 * (first - '0') + 10 * (second - '0') + (third - '0');
513
25.9k
      }
514
37.1k
    }
515
555k
    line_start = newline + 1;
516
555k
  }
517
1.51k
  return -1;
518
30.2k
}
519
520
/// A raw completion such as "226 done" needs only its missing newline. In
521
/// that common mutation, appending a second synthetic reply would leave bytes
522
/// in curl's control cache and misalign a later wildcard transfer.
523
/// @param response Raw control fragment.
524
/// @return true when the unterminated tail begins with "ddd ".
525
1.56k
bool FtpMockServer::TailNeedsOnlyNewline(std::string_view response) {
526
1.56k
  const std::size_t last_newline = response.rfind('\n');
527
1.56k
  const std::size_t tail = last_newline == std::string_view::npos ? 0 : last_newline + 1;
528
1.56k
  if (response.size() - tail <= 3) {
529
1.25k
    return false;
530
1.25k
  }
531
305
  const unsigned char first = static_cast<unsigned char>(response[tail]);
532
305
  const unsigned char second = static_cast<unsigned char>(response[tail + 1]);
533
305
  const unsigned char third = static_cast<unsigned char>(response[tail + 2]);
534
305
  return first >= '0' && first <= '9' && second >= '0' && second <= '9' && third >= '0' && third <= '9' &&
535
83
         response[tail + 3] == ' ';
536
1.56k
}
537
538
/// Return the next command-aligned primary response within the shared
539
/// response-count budget. Empty strings still advance the cursor: they are
540
/// meaningful truncation mutations for ordinary command states and explicitly
541
/// select control EOF at transfer completion.
542
/// @return Scenario-owned reply, or nullptr after the bounded prefix.
543
73.6k
const std::string* FtpMockServer::NextControlReply() {
544
73.6k
  if (scenario_ == nullptr || next_control_reply_ >= control_reply_count_) {
545
43.3k
    return nullptr;
546
43.3k
  }
547
30.2k
  return &scenario_->connection().on_readable(static_cast<int>(next_control_reply_++));
548
73.6k
}
549
550
/// Keep failed peer writes local to the mock. Response cursors must still
551
/// advance after curl closes early, otherwise a replacement socket could see
552
/// a reply intended for an earlier command.
553
/// @param bytes Response fragment to queue.
554
/// @return true when the complete fragment was queued.
555
39.9k
bool FtpMockServer::WriteControlBytes(std::string_view bytes) {
556
39.9k
  return bytes.empty() ||
557
38.9k
         (control_connection_ != nullptr &&
558
38.9k
          control_connection_->WriteAll(reinterpret_cast<const unsigned char*>(bytes.data()), bytes.size()));
559
39.9k
}
560
561
/// Queue a scenario-provided final reply before curl observes data EOF.
562
/// ftp_done_control_reply() calls getftpresponse() synchronously inside
563
/// curl_multi_perform, so the outer loop cannot provide the reply afterwards.
564
/// If the fuzzed fragment lacks a terminating numeric line, append the smallest
565
/// completion needed so curl returns to the harness immediately. An explicitly
566
/// empty repeated value instead half-closes the peer, retaining deterministic
567
/// liveness while making curl's missing-completion error path seedable.
568
3.16k
void FtpMockServer::QueueTransferCompletion() {
569
3.16k
  const std::string* response = NextControlReply();
570
3.16k
  if (response != nullptr && response->empty()) {
571
49
    if (control_connection_ != nullptr) {
572
49
      control_connection_->ShutdownWrite();
573
49
    }
574
49
    return;
575
49
  }
576
3.11k
  if (response != nullptr && !response->empty()) {
577
1.29k
    (void)WriteControlBytes(*response);
578
1.29k
    if (FirstReplyCode(*response) >= 0) {
579
111
      QueuePostQuoteReplies();
580
111
      return;
581
111
    }
582
1.18k
    if (TailNeedsOnlyNewline(*response)) {
583
32
      (void)WriteControlBytes("\r\n");
584
32
      QueuePostQuoteReplies();
585
32
      return;
586
32
    }
587
1.15k
    if (response->back() != '\n') {
588
1.03k
      (void)WriteControlBytes("\r\n");
589
1.03k
    }
590
1.15k
  }
591
592
  // This line is a liveness guard, not a forced successful outcome: any
593
  // complete fuzzed final response above remains the reply curl consumes.
594
2.96k
  (void)WriteControlBytes("226 mock transfer complete\r\n");
595
2.96k
  QueuePostQuoteReplies();
596
2.96k
}
597
598
/// Preload responses for the blocking POSTQUOTE loop. curl reads each reply
599
/// synchronously after the final transfer response, before the mock's outer
600
/// loop can drain the matching command. The commands remain observable on the
601
/// next service turn; prequeued_control_replies_ prevents double consumption.
602
3.11k
void FtpMockServer::QueuePostQuoteReplies() {
603
3.11k
  if (scenario_ == nullptr) {
604
0
    return;
605
0
  }
606
607
3.11k
  std::size_t remaining = scenario_limits::kMaxFtpQuoteCommands;
608
3.11k
  const std::size_t quote_count = std::min<std::size_t>(remaining, scenario_->ftp_quote_size());
609
3.11k
  remaining -= quote_count;
610
3.11k
  const std::size_t prequote_count = std::min<std::size_t>(remaining, scenario_->ftp_prequote_size());
611
3.11k
  remaining -= prequote_count;
612
3.11k
  const std::size_t postquote_count = std::min<std::size_t>(remaining, scenario_->ftp_postquote_size());
613
614
4.18k
  for (std::size_t index = 0; index < postquote_count; ++index) {
615
1.09k
    const std::string* response = NextControlReply();
616
1.09k
    ++prequeued_control_replies_;
617
1.09k
    if (response != nullptr && response->empty()) {
618
19
      if (control_connection_ != nullptr) {
619
19
        control_connection_->ShutdownWrite();
620
19
      }
621
19
      return;
622
19
    }
623
1.07k
    if (response != nullptr && !response->empty()) {
624
483
      (void)WriteControlBytes(*response);
625
483
      if (FirstReplyCode(*response) >= 0) {
626
110
        continue;
627
110
      }
628
373
      if (TailNeedsOnlyNewline(*response)) {
629
13
        (void)WriteControlBytes("\r\n");
630
13
        continue;
631
13
      }
632
360
      if (response->back() != '\n') {
633
276
        (void)WriteControlBytes("\r\n");
634
276
      }
635
360
    }
636
952
    (void)WriteControlBytes("200 mock postquote complete\r\n");
637
952
  }
638
3.11k
}
639
640
/// Send every runtime-visible data fragment once RETR/LIST has been accepted,
641
/// then half-close the peer. Delaying until the command prevents early EOF from
642
/// perturbing passive setup. Sending the complete bounded prefix lets curl drain
643
/// its data state without event-loop sleeps while each protobuf fragment still
644
/// affects byte content and parser behavior.
645
/// @param channel Data peer whose script supplies the download bytes.
646
2.61k
void FtpMockServer::PreloadDownload(DataChannel* channel) {
647
2.61k
  if (channel == nullptr || channel->script == nullptr || (channel->connection == nullptr && channel->active_fd < 0)) {
648
0
    return;
649
0
  }
650
651
2.61k
  const std::string& initial = channel->script->initial_response();
652
6.20k
  const auto write_bytes = [channel](const std::string& bytes) {
653
6.20k
    if (bytes.empty()) {
654
1.35k
      return true;
655
1.35k
    }
656
4.85k
    if (channel->connection != nullptr) {
657
4.78k
      return channel->connection->WriteAll(reinterpret_cast<const unsigned char*>(bytes.data()), bytes.size());
658
4.78k
    }
659
63
    return WriteActiveBytes(channel->active_fd, reinterpret_cast<const unsigned char*>(bytes.data()), bytes.size());
660
4.85k
  };
661
2.61k
  bool complete = write_bytes(initial);
662
2.61k
  const std::size_t chunk_count = std::min<std::size_t>(scenario_limits::kMaxResponseChunks,
663
2.61k
                                                        static_cast<std::size_t>(channel->script->on_readable_size()));
664
6.20k
  for (std::size_t index = 0; complete && index < chunk_count; ++index) {
665
3.58k
    const std::string& chunk = channel->script->on_readable(static_cast<int>(index));
666
3.58k
    complete = write_bytes(chunk);
667
3.58k
  }
668
2.61k
  (void)complete;
669
2.61k
  if (channel->connection != nullptr) {
670
2.55k
    channel->connection->ShutdownWrite();
671
2.55k
  } else {
672
61
    (void)shutdown(channel->active_fd, SHUT_WR);
673
61
  }
674
2.61k
}
675
676
/// Pair the next transfer command with the oldest passive socket that EPSV or
677
/// PASV opened but no command has used. FTP serializes data transfers, so this
678
/// simple cursor is sufficient and avoids interpreting fuzzed port numbers.
679
/// @param direction Whether curl will read or write the data connection.
680
3.16k
void FtpMockServer::StartNextTransfer(TransferDirection direction) {
681
3.62k
  for (std::size_t index = 0; index < next_data_script_; ++index) {
682
3.42k
    DataChannel& channel = data_channels_[index];
683
3.42k
    if ((channel.connection == nullptr && channel.active_fd < 0) || channel.transfer_started) {
684
468
      continue;
685
468
    }
686
687
2.95k
    channel.transfer_started = true;
688
2.95k
    channel.upload = direction == TransferDirection::kUpload;
689
2.95k
    if (!channel.upload) {
690
2.61k
      PreloadDownload(&channel);
691
2.61k
    }
692
    // Upload peers keep their write half open until cleanup. A real FTP server
693
    // does not send an early FIN while receiving a file, and a readiness
694
    // backend could otherwise report that FIN alongside POLLOUT before curl
695
    // has delivered the upload callback's bytes.
696
2.95k
    return;
697
3.42k
  }
698
3.16k
}
699
700
/// Advance one reply for every complete command. Accepted transfer commands
701
/// additionally consume their final reply now, because waiting until data EOF
702
/// would be too late to escape curl's blocking completion read.
703
/// @param command One newline-terminated command from curl.
704
70.3k
void FtpMockServer::HandleControlCommand(std::string_view command) {
705
70.3k
  if (prequeued_control_replies_ != 0) {
706
880
    --prequeued_control_replies_;
707
880
    return;
708
880
  }
709
69.4k
  const std::string* response = NextControlReply();
710
69.4k
  if (response == nullptr) {
711
40.9k
    return;
712
40.9k
  }
713
714
28.4k
  const int response_code = FirstReplyCode(*response);
715
28.4k
  const bool response_written = WriteControlBytes(*response);
716
717
28.4k
  const std::string_view verb = CommandVerb(command);
718
28.4k
  if (response_written && scenario_->ftp_auth_tls_filter_allocation_failure() && VerbEquals(verb, "AUTH") &&
719
459
      (response_code == 234 || response_code == 334)) {
720
3
    allocation_fault_injection::ArmNextAllocationFailure();
721
3
  }
722
28.4k
  if ((VerbEquals(verb, "EPRT") || VerbEquals(verb, "PORT")) && response_code >= 200 && response_code < 300) {
723
204
    ConnectActiveDataChannel();
724
204
  }
725
28.4k
  TransferDirection direction = DirectionForVerb(verb);
726
28.4k
  if (direction == TransferDirection::kNone && IsConfiguredCustomDownload(verb)) {
727
327
    direction = TransferDirection::kDownload;
728
327
  }
729
28.4k
  const bool starts_download =
730
28.4k
      direction == TransferDirection::kDownload && (response_code == 125 || response_code == 150);
731
  // curl's STOR handler accepts every response below 400 before initiating
732
  // the upload, even though 125/150 are the conventional successful replies.
733
28.4k
  const bool starts_upload = direction == TransferDirection::kUpload && response_code >= 100 && response_code < 400;
734
28.4k
  if (starts_download || starts_upload) {
735
3.16k
    StartNextTransfer(direction);
736
3.16k
    QueueTransferCompletion();
737
3.16k
  }
738
28.4k
}
739
740
/// Read without waiting, retain partial final commands, and process all full
741
/// lines already emitted by curl. The number of replies is bounded even if a
742
/// malformed command stream contains many newlines.
743
/// @return true when bytes or a command/reply cursor advanced.
744
124k
bool FtpMockServer::ServiceControlConnection() {
745
124k
  if (control_connection_ == nullptr) {
746
1.63k
    return false;
747
1.63k
  }
748
749
122k
  const std::size_t size_before_read = pending_control_bytes_.size();
750
122k
  const std::size_t transport_progress = control_connection_->DrainIncoming();
751
122k
  bool made_progress = pending_control_bytes_.size() != size_before_read || transport_progress != 0;
752
753
122k
  std::size_t consumed = 0;
754
193k
  while (consumed < pending_control_bytes_.size()) {
755
72.2k
    const std::size_t newline = pending_control_bytes_.find('\n', consumed);
756
72.2k
    if (newline == std::string::npos) {
757
1.93k
      break;
758
1.93k
    }
759
70.3k
    const std::size_t command_size = newline - consumed + 1;
760
70.3k
    const std::string_view command(pending_control_bytes_.data() + consumed, command_size);
761
70.3k
    CapturePrefix(command, kMaxCapturedControlBytes, &control_transcript_);
762
70.3k
    HandleControlCommand(command);
763
70.3k
    consumed += command_size;
764
70.3k
    made_progress = true;
765
70.3k
  }
766
767
122k
  if (consumed != 0) {
768
58.6k
    pending_control_bytes_.erase(0, consumed);
769
    // Replies queued while handling a command must reach the wire before the
770
    // next curl transition. FTP performs its final transfer-reply read inside
771
    // curl_multi_perform, so a deferred TLS record would turn a completed
772
    // download or upload into a control-response timeout.
773
58.6k
    const std::size_t flush_progress = control_connection_->DrainIncoming();
774
58.6k
    made_progress = made_progress || flush_progress != 0;
775
58.6k
  }
776
122k
  return made_progress;
777
124k
}
778
779
/// Advance every data transport so a TLS handshake and queued response records
780
/// make progress even when no upload is active. Decoded upload bytes are
781
/// appended by each channel's observer and copied into a temporary capture so
782
/// data beyond the observable cap is still removed from the transport. This
783
/// keeps curl's progress independent of how much a unit test chooses to retain.
784
/// @return true when a transport or captured upload advanced.
785
124k
bool FtpMockServer::ServiceDataConnections() {
786
124k
  bool made_progress = false;
787
161k
  for (std::size_t index = 0; index < next_data_script_; ++index) {
788
36.6k
    DataChannel& channel = data_channels_[index];
789
36.6k
    if (channel.connection != nullptr) {
790
34.5k
      const std::size_t transport_progress = channel.connection->DrainIncoming();
791
34.5k
      made_progress = made_progress || transport_progress != 0;
792
34.5k
      if (channel.upload && !channel.incoming_data.empty()) {
793
1.97k
        CapturePrefix(channel.incoming_data, kMaxCapturedUploadBytes, &uploaded_data_);
794
1.97k
        channel.incoming_data.clear();
795
1.97k
        made_progress = true;
796
1.97k
      }
797
34.5k
      continue;
798
34.5k
    }
799
800
2.16k
    if (channel.upload && channel.active_fd >= 0) {
801
62
      std::string bytes;
802
62
      (void)ReadActiveBytes(channel.active_fd, &bytes);
803
62
      if (!bytes.empty()) {
804
14
        CapturePrefix(bytes, kMaxCapturedUploadBytes, &uploaded_data_);
805
14
        made_progress = true;
806
14
      }
807
62
    }
808
2.16k
  }
809
124k
  return made_progress;
810
124k
}
811
812
/// Prepare cleanup while the mock can still write to curl's control socket.
813
/// A completed easy remains in multi's connection cache until cleanup, where
814
/// FTP sends QUIT and performs a blocking read. Preloading 221 handles that
815
/// path; an unfinished drive instead gets EOF so cleanup fails fast.
816
/// @param completed Whether curl reported that the transfer stopped.
817
9.87k
void FtpMockServer::FinishConnections(bool completed) {
818
9.87k
  if (control_connection_ != nullptr) {
819
9.40k
    if (completed) {
820
4.41k
      (void)WriteControlBytes("221 mock closing control connection\r\n");
821
4.41k
    }
822
9.40k
    control_connection_->ShutdownWrite();
823
9.40k
  }
824
14.7k
  for (std::size_t index = 0; index < next_data_script_; ++index) {
825
4.88k
    if (data_channels_[index].connection != nullptr) {
826
4.66k
      data_channels_[index].connection->ShutdownWrite();
827
4.66k
    }
828
4.88k
    if (data_channels_[index].active_fd >= 0) {
829
165
      (void)shutdown(data_channels_[index].active_fd, SHUT_WR);
830
165
    }
831
4.88k
  }
832
9.87k
  if (active_listener_fd_ >= 0) {
833
50
    close(active_listener_fd_);
834
50
    active_listener_fd_ = -1;
835
50
  }
836
9.87k
  active_listener_client_fd_ = CURL_SOCKET_BAD;
837
9.87k
}
838
839
/// Alternate curl transitions with immediate peer service until the transfer
840
/// completes or deterministic idle/operation caps win. No select(), poll(), or
841
/// sleep is needed: every transport is in-process, and malformed scripts are
842
/// terminated by half-close after the bounded loop.
843
/// @param multi Multi handle containing `easy`.
844
/// @param easy Easy handle already installed on this mock.
845
/// @param scenario Control and passive-data scripts to borrow.
846
9.87k
void FtpMockServer::RunLoop(CURLM* multi, CURL* easy, const curl::fuzzer::proto::Scenario& scenario) {
847
9.87k
  (void)easy;
848
9.87k
  ResetForScenario(scenario);
849
850
9.87k
  int still_running = 1;
851
9.87k
  int idle_iterations = 0;
852
9.87k
  int drive_iterations = 0;
853
9.87k
  CURLMcode result = CURLM_OK;
854
124k
  while (still_running && idle_iterations < kMaxIdleIterations && drive_iterations++ < kMaxDriveIterations) {
855
114k
    const int running_before = still_running;
856
114k
    result = curl_multi_perform(multi, &still_running);
857
114k
    if (result != CURLM_OK) {
858
0
      break;
859
0
    }
860
861
    // Pollset construction is opt-in coverage work. Waiting until the socket
862
    // callback has run and the transfer remains active reaches FTP's protocol
863
    // and DO_MORE pollsets without adding a syscall to the default hot loop.
864
114k
    if (scenario.probe_multi_pollset() && still_running && control_opened_) {
865
14.9k
      ProbeMultiPollset(multi);
866
14.9k
      ++active_pollset_probe_count_;
867
14.9k
    }
868
869
114k
    bool made_progress = still_running != running_before;
870
114k
    made_progress = ServiceControlConnection() || made_progress;
871
114k
    made_progress = ServiceDataConnections() || made_progress;
872
114k
    if (made_progress) {
873
70.8k
      idle_iterations = 0;
874
70.8k
    } else {
875
43.6k
      ++idle_iterations;
876
43.6k
    }
877
114k
  }
878
879
  // The final perform may have emitted upload or control bytes immediately
880
  // before marking the transfer done. Drain/capture them before cleanup.
881
9.87k
  (void)ServiceControlConnection();
882
9.87k
  (void)ServiceDataConnections();
883
9.87k
  FinishConnections(still_running == 0 && result == CURLM_OK);
884
9.87k
  scenario_ = nullptr;
885
9.87k
}
886
887
/// Retain protocol outcomes in coverage and introspector builds.
888
9.96k
void FtpMockServer::ObserveState() {
889
9.96k
#if defined(PROTO_FUZZER_OBSERVE_STATE)
890
9.96k
  MockServerBase::ObserveState();
891
9.96k
  const volatile std::size_t ftp_observation[] = {control_transcript().size(), uploaded_data().size(),
892
9.96k
                                                  opened_data_connection_count()};
893
9.96k
  (void)ftp_observation;
894
9.96k
#endif
895
9.96k
}
896
897
}  // namespace proto_fuzzer