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