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/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 MockConnection and MockServer.
9
10
#include "proto_fuzzer/mock_server.h"
11
12
#include <fcntl.h>
13
#include <string.h>
14
#include <sys/select.h>
15
#include <sys/socket.h>
16
#include <sys/types.h>
17
#include <unistd.h>
18
19
#include <algorithm>
20
#include <cerrno>
21
#include <cstddef>
22
#include <cstdint>
23
#include <limits>
24
#include <string>
25
#include <string_view>
26
#include <vector>
27
28
#include "proto_fuzzer/multi_socket_driver.h"
29
#include "proto_fuzzer/scenario_limits.h"
30
#include "proto_fuzzer/ws_frame.h"
31
32
namespace proto_fuzzer {
33
34
// curl's debug-only event-based easy entrypoint is intentionally used by the
35
// API coverage lane. curl-fuzzer builds every bundled curl with ENABLE_DEBUG
36
// and visible symbols, matching curl's own command-line tool declaration.
37
/// @param easy Configured easy handle to perform.
38
/// @return The transfer result reported by the event-based entrypoint.
39
extern "C" CURLcode curl_easy_perform_ev(CURL* easy);
40
41
namespace {
42
43
constexpr int kMaxConnectOnlyIoIterations = 16;
44
constexpr std::size_t kConnectOnlyBufferSize = 1024;
45
46
// fd_set can only represent file descriptors < FD_SETSIZE. Reject any pair that couldn't participate in select()
47
// without memory corruption.
48
689k
bool FdFitsInFdSet(int fd) { return fd >= 0 && fd < FD_SETSIZE; }
49
50
}  // namespace
51
52
/// @class proto_fuzzer::MockConnection
53
/// @brief Owns one half of a socketpair used to feed canned responses to libcurl. The destructor closes the server-side
54
/// fd; the client-side fd is handed to libcurl via CURLOPT_OPENSOCKETFUNCTION and becomes curl's to close.
55
56
/// Construct a non-blocking AF_UNIX/SOCK_STREAM socketpair. Both fds are validated to fit inside FD_SETSIZE; on any
57
/// failure ok() returns false and the instance is unusable.
58
344k
MockConnection::MockConnection() : server_fd_(-1), client_fd_(-1), drain_limit_(0), incoming_data_observer_(nullptr) {
59
344k
  int fds[2];
60
61
344k
  if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) != 0) {
62
0
    return;
63
0
  }
64
65
  // The fds must be small enough to fit in an fd_set for select(). If not, close them and fail the constructor.
66
344k
  if (!FdFitsInFdSet(fds[0]) || !FdFitsInFdSet(fds[1])) {
67
0
    close(fds[0]);
68
0
    close(fds[1]);
69
0
    return;
70
0
  }
71
72
  // Set the server-side fd non-blocking so we can write to it without risk of hanging the fuzzer.
73
344k
  int flags = fcntl(fds[0], F_GETFL, 0);
74
344k
  if (flags < 0 || fcntl(fds[0], F_SETFL, flags | O_NONBLOCK) < 0) {
75
0
    close(fds[0]);
76
0
    close(fds[1]);
77
0
    return;
78
0
  }
79
80
  // Success: store the file descriptors.
81
344k
  server_fd_ = fds[0];
82
344k
  client_fd_ = fds[1];
83
344k
}
84
85
/// Close the server-side fd (and the client-side fd if it was never handed off via take_client_fd()).
86
344k
MockConnection::~MockConnection() {
87
344k
  if (server_fd_ >= 0) {
88
344k
    close(server_fd_);
89
344k
  }
90
344k
  if (client_fd_ >= 0) {
91
11
    close(client_fd_);
92
11
  }
93
344k
}
94
95
/// @return true if the underlying socketpair was set up successfully.
96
1.67M
bool MockConnection::ok() const { return server_fd_ >= 0; }
97
98
/// @return the server-side fd (still owned by this MockConnection).
99
172k
int MockConnection::server_fd() const { return server_fd_; }
100
101
/// Query the capacity curl's endpoint reports for queued client writes while
102
/// this object still owns that endpoint. Synchronous protocol mocks use this
103
/// before transferring fd ownership because they cannot rely on the outer
104
/// driver to make room. A zero result covers both an invalid fd and a platform
105
/// query failure; callers need a verified capacity before proceeding.
106
/// @return SO_SNDBUF in bytes, or zero when it cannot be queried.
107
6.37k
std::size_t MockConnection::client_send_buffer_size() const {
108
6.37k
  if (client_fd_ < 0) {
109
0
    return 0;
110
0
  }
111
6.37k
  int size = 0;
112
6.37k
  socklen_t length = sizeof(size);
113
6.37k
  if (getsockopt(client_fd_, SOL_SOCKET, SO_SNDBUF, &size, &length) != 0 || size <= 0) {
114
0
    return 0;
115
0
  }
116
6.37k
  return static_cast<std::size_t>(size);
117
6.37k
}
118
119
/// Ensure curl's endpoint reports at least `minimum` bytes of send buffer,
120
/// requesting a larger SO_SNDBUF when the platform default is smaller. Linux
121
/// may transform socket-buffer requests, so the post-set query establishes the
122
/// contract rather than assuming setsockopt accepted the exact value.
123
/// @param minimum Smallest acceptable reported capacity in bytes.
124
/// @return true when the queried postcondition holds.
125
6.37k
bool MockConnection::EnsureClientSendBufferSize(std::size_t minimum) {
126
6.37k
  if (client_send_buffer_size() >= minimum) {
127
6.37k
    return true;
128
6.37k
  }
129
0
  if (client_fd_ < 0 || minimum > static_cast<std::size_t>(std::numeric_limits<int>::max())) {
130
0
    return false;
131
0
  }
132
0
  const int requested = static_cast<int>(minimum);
133
0
  if (setsockopt(client_fd_, SOL_SOCKET, SO_SNDBUF, &requested, sizeof(requested)) != 0) {
134
0
    return false;
135
0
  }
136
0
  return client_send_buffer_size() >= minimum;
137
0
}
138
139
/// Saturate curl's endpoint before ownership is transferred. The temporary
140
/// non-blocking flag makes the stopping condition explicit and is restored so
141
/// curl receives the same descriptor state as every other stream peer.
142
/// @return true only when the endpoint reached EAGAIN/EWOULDBLOCK.
143
169
bool MockConnection::FillClientSendBuffer() {
144
169
  if (client_fd_ < 0) {
145
0
    return false;
146
0
  }
147
169
  const int flags = fcntl(client_fd_, F_GETFL, 0);
148
169
  if (flags < 0 || fcntl(client_fd_, F_SETFL, flags | O_NONBLOCK) < 0) {
149
0
    return false;
150
0
  }
151
152
169
  static constexpr unsigned char kPadding[4096] = {};
153
169
  bool full = false;
154
338
  while (true) {
155
338
    const ssize_t written = ::send(client_fd_, kPadding, sizeof(kPadding), MSG_NOSIGNAL);
156
338
    if (written > 0) {
157
169
      continue;
158
169
    }
159
169
    full = written < 0 && (errno == EAGAIN || errno == EWOULDBLOCK);
160
169
    break;
161
338
  }
162
169
  if (fcntl(client_fd_, F_SETFL, flags) < 0) {
163
0
    return false;
164
0
  }
165
169
  return full;
166
169
}
167
168
/// Hand the client-side fd to libcurl. After this call the caller owns the fd and the MockConnection will not close it
169
/// on destruction.
170
/// @return the client-side socket fd as a curl_socket_t.
171
344k
curl_socket_t MockConnection::take_client_fd() {
172
344k
  int fd = client_fd_;
173
344k
  client_fd_ = -1;
174
344k
  return static_cast<curl_socket_t>(fd);
175
344k
}
176
177
/// Write 'size' bytes from 'data' to the server fd, looping until the whole
178
/// buffer is sent or a short/failed write occurs. MSG_NOSIGNAL is a harness
179
/// invariant rather than a curl behavior choice: a response race may leave the
180
/// peer closed, and that must look like an ordinary failed mock write instead
181
/// of terminating the fuzz process with SIGPIPE.
182
/// @param data Buffer to send.
183
/// @param size Number of bytes in 'data'.
184
/// @return false on short or failed write (treat the connection as lost).
185
678k
bool MockConnection::WriteAll(const unsigned char* data, std::size_t size) {
186
678k
  if (server_fd_ < 0) {
187
0
    return false;
188
0
  }
189
678k
  std::size_t written = 0;
190
1.35M
  while (written < size) {
191
678k
    ssize_t n = ::send(server_fd_, data + written, size - written, MSG_NOSIGNAL);
192
678k
    if (n <= 0) {
193
4.43k
      return false;
194
4.43k
    }
195
673k
    written += static_cast<std::size_t>(n);
196
673k
  }
197
673k
  return true;
198
678k
}
199
200
/// Advance incoming transport work according to the configured per-call
201
/// limit. This plaintext implementation reports bytes consumed; layered
202
/// transports may also report handshake state changes so the bounded outer
203
/// loop does not mistake useful protocol progress for an idle connection.
204
/// When a backpressure drain limit has been applied (see ApplyBackpressure),
205
/// stop after drain_limit_ bytes so the kernel recv buffer stays near-full
206
/// and curl keeps seeing short writes. Otherwise drain until read() returns
207
/// 0/EAGAIN, matching legacy behaviour.
208
/// @return number of bytes consumed during this call.
209
2.61M
std::size_t MockConnection::DrainIncoming() {
210
2.61M
  if (server_fd_ < 0) {
211
0
    return 0;
212
0
  }
213
2.61M
  unsigned char scratch[4096];
214
2.61M
  std::size_t drained = 0;
215
3.32M
  while (drain_limit_ == 0 || drained < drain_limit_) {
216
3.09M
    std::size_t want = sizeof(scratch);
217
3.09M
    if (drain_limit_ != 0) {
218
390k
      const std::size_t remaining = drain_limit_ - drained;
219
390k
      if (remaining < want) {
220
357k
        want = remaining;
221
357k
      }
222
390k
    }
223
3.09M
    ssize_t n = ::read(server_fd_, scratch, want);
224
3.09M
    if (n <= 0) {
225
2.38M
      break;
226
2.38M
    }
227
714k
    NotifyIncomingData(scratch, static_cast<std::size_t>(n));
228
714k
    drained += static_cast<std::size_t>(n);
229
714k
  }
230
2.61M
  return drained;
231
2.61M
}
232
233
/// Register a non-owning sink for bytes consumed from curl. TLS transports
234
/// notify it after decryption, while plaintext transports report socket
235
/// bytes directly. The observer must outlive this connection.
236
/// @param observer Observer to notify, or nullptr to disable observation.
237
136k
void MockConnection::SetIncomingDataObserver(IncomingDataObserver* observer) { incoming_data_observer_ = observer; }
238
239
/// Forward one application-data fragment to the optional observer.
240
/// @param data First byte of the fragment.
241
/// @param size Number of bytes available at `data`.
242
1.19M
void MockConnection::NotifyIncomingData(const unsigned char* data, std::size_t size) {
243
1.19M
  if (incoming_data_observer_ != nullptr) {
244
620k
    incoming_data_observer_->ObserveIncomingData(data, size);
245
620k
  }
246
1.19M
}
247
248
/// Apply deterministic backpressure knobs before traffic begins. A positive
249
/// recv_buf_bytes sets SO_RCVBUF on the server fd and SO_SNDBUF on the client
250
/// fd, which this object still owns, to make curl short-write or see EAGAIN.
251
/// Linux socketpairs effectively use max(SNDBUF, RCVBUF*2) as pipe capacity,
252
/// so both settings are needed to produce short writes reliably. Cap each
253
/// DrainIncoming call at drain_limit bytes; zero leaves the drain unlimited.
254
/// @param recv_buf_bytes SO_RCVBUF size in bytes, or 0 to leave default.
255
/// @param drain_limit    Max bytes drained per DrainIncoming call, 0 for unlimited.
256
340k
void MockConnection::ApplyBackpressure(int recv_buf_bytes, std::size_t drain_limit) {
257
340k
  if (recv_buf_bytes > 0) {
258
21.5k
    if (server_fd_ >= 0) {
259
21.5k
      (void)setsockopt(server_fd_, SOL_SOCKET, SO_RCVBUF, &recv_buf_bytes, sizeof(recv_buf_bytes));
260
21.5k
    }
261
21.5k
    if (client_fd_ >= 0) {
262
21.5k
      (void)setsockopt(client_fd_, SOL_SOCKET, SO_SNDBUF, &recv_buf_bytes, sizeof(recv_buf_bytes));
263
21.5k
    }
264
21.5k
  }
265
340k
  drain_limit_ = drain_limit;
266
340k
}
267
268
/// Non-blocking read: append whatever bytes are currently available on the
269
/// server fd to 'out'. Used by the WS handshake path to collect curl's HTTP
270
/// Upgrade request without losing any bytes.
271
/// @param out Destination buffer; unchanged if no bytes are pending.
272
25.0k
void MockConnection::ReadAvailable(std::string* out) {
273
25.0k
  if (server_fd_ < 0 || out == nullptr) {
274
0
    return;
275
0
  }
276
25.0k
  unsigned char scratch[4096];
277
40.3k
  while (true) {
278
40.3k
    ssize_t n = ::read(server_fd_, scratch, sizeof(scratch));
279
40.3k
    if (n <= 0) {
280
25.0k
      break;
281
25.0k
    }
282
15.3k
    out->append(reinterpret_cast<const char*>(scratch), static_cast<std::size_t>(n));
283
15.3k
  }
284
25.0k
}
285
286
/// Signal end-of-response to libcurl by half-closing the write side.
287
187k
void MockConnection::ShutdownWrite() {
288
187k
  if (server_fd_ < 0) {
289
0
    return;
290
0
  }
291
187k
  ::shutdown(server_fd_, SHUT_WR);
292
187k
}
293
294
/// @class proto_fuzzer::MockServer
295
/// @brief Orchestrates a bounded sequence of mock HTTP exchanges: installs
296
/// socket callbacks on an easy handle, assigns a response script to each new
297
/// socket, and feeds queued chunks as libcurl reads them.
298
299
/// Construct an idle MockServer with no scripted responses or open peers.
300
/// DriveScenario() configures it from a Scenario before curl can open a socket;
301
/// the fixed policy decides whether that scenario's ApiPlan controls the loop.
302
/// @param drive_policy Multi interface loop selected for this server.
303
MockServer::MockServer(MultiDrivePolicy drive_policy)
304
241k
    : MockServerBase(drive_policy),
305
241k
      script_count_(0),
306
241k
      next_script_(0),
307
241k
      active_script_(nullptr),
308
241k
      preload_all_chunks_(false),
309
241k
      keep_connections_open_(false) {}
310
311
/// Default destructor; current and previous MockConnections clean up their
312
/// server-side descriptors only after curl has been removed from the multi.
313
241k
MockServer::~MockServer() = default;
314
315
/// Build the complete borrowed script table before entering curl. The primary
316
/// Connection always occupies slot zero for backwards compatibility; only
317
/// three subsequent pointers are retained so protobuf mutations cannot
318
/// allocate socketpairs or prolong redirects in proportion to repeated-field
319
/// size. The caller must keep the Scenario alive and unmodified until the
320
/// synchronous drive finishes. RunScenario provides that lifetime, making
321
/// borrowing safe while avoiding copies of response bytes before curl
322
/// requests the corresponding socket or chunk.
323
/// @param scenario Source of the primary and bounded follow-on scripts.
324
241k
void MockServer::SetScripts(const curl::fuzzer::proto::Scenario& scenario) {
325
241k
  ResetConnections();
326
241k
  script_count_ = 0;
327
241k
  next_script_ = 0;
328
329
307k
  const auto append_script = [this](const curl::fuzzer::proto::Connection& connection) {
330
307k
    ConnectionScript& script = scripts_[script_count_++];
331
307k
    script.connection = &connection;
332
307k
    script.raw_chunk_count = std::min<std::size_t>(scenario_limits::kMaxResponseChunks, connection.on_readable_size());
333
307k
    const std::size_t frame_budget = scenario_limits::kMaxResponseChunks - script.raw_chunk_count;
334
307k
    script.frame_chunk_count = std::min<std::size_t>(frame_budget, connection.server_frames_size());
335
307k
    script.next_chunk = 0;
336
307k
  };
337
338
241k
  append_script(scenario.connection());
339
241k
  const std::size_t subsequent_count = std::min<std::size_t>(
340
241k
      scenario_limits::kMaxConnections - 1, static_cast<std::size_t>(scenario.subsequent_connections_size()));
341
307k
  for (std::size_t i = 0; i < subsequent_count; ++i) {
342
66.8k
    append_script(scenario.subsequent_connections(static_cast<int>(i)));
343
66.8k
  }
344
241k
}
345
346
/// Keep completed response sockets writable instead of half-closing them.
347
/// The multi-transfer lane uses this to let a queued easy handle reuse an
348
/// HTTP/1.1 connection; ordinary protocol drives retain close-on-completion.
349
/// @param keep_open Whether the peer should suppress its response-side FIN.
350
40.6k
void MockServer::SetKeepConnectionsOpen(bool keep_open) { keep_connections_open_ = keep_open; }
351
352
/// @return true if at least one on_readable chunk has not yet been sent.
353
2.55M
bool MockServer::has_more_chunks() const {
354
2.55M
  return active_script_ != nullptr && active_script_->next_chunk < active_script_->chunk_count();
355
2.55M
}
356
357
/// Construct the transport used for one HTTP exchange. HTTPS overrides this
358
/// factory with a TLS record layer while retaining the same bounded response
359
/// scripts and redirect lifetimes, without copying the HTTP state machine.
360
/// @return a new connection, whose ok() result is checked before use.
361
168k
std::unique_ptr<MockConnection> MockServer::CreateConnection() { return std::make_unique<MockConnection>(); }
362
363
/// Release all current and retired socketpairs before resetting transport-
364
/// specific state. Derived destructors call this while their borrowed state
365
/// is still alive. This is separate from SetScripts because a derived class
366
/// may need a stricter order than C++'s derived-member-before-base teardown.
367
346k
void MockServer::ResetConnections() {
368
346k
  active_script_ = nullptr;
369
346k
  connection_.reset();
370
346k
  previous_connections_.clear();
371
346k
}
372
373
/// Observe curl while its connection filters are still attached. Plain HTTP
374
/// has no transport-specific state to inspect; layered transports override
375
/// this instead of querying stale state after the multi has been dismantled.
376
/// @param easy Active easy handle, unused by the plaintext transport.
377
1.02M
void MockServer::ObserveActiveTransfer(CURL* /*easy*/) {}
378
379
/// Called by the OPENSOCKETFUNCTION trampoline in the base class. Creates the
380
/// MockConnection, writes initial_response into it, and returns the
381
/// client-side fd to hand to libcurl.
382
/// @param purpose Socket role requested by curl; ordinary stream mocks do not
383
///                need to distinguish outbound HTTP roles.
384
/// @param address Intended destination retained by curl; the socketpair is
385
///                already connected and therefore leaves it untouched.
386
/// @return the client-side fd to hand to libcurl, or CURL_SOCKET_BAD on
387
///         failure.
388
297k
curl_socket_t MockServer::HandleOpenSocket(curlsocktype purpose, struct curl_sockaddr* address) {
389
297k
  (void)purpose;
390
297k
  (void)address;
391
297k
  if (next_script_ >= script_count_) {
392
    // Refusing a fifth socket keeps redirect loops bounded even if curl's own
393
    // redirect limit is mutated upward or an authentication scheme retries.
394
24.8k
    return CURL_SOCKET_BAD;
395
24.8k
  }
396
397
273k
  if (connection_) {
398
    // libcurl owns the corresponding client fd, so retain the server half
399
    // until the easy handle leaves the multi instead of closing it at the
400
    // moment a redirect or retry opens its replacement.
401
45.1k
    previous_connections_.push_back(std::move(connection_));
402
45.1k
  }
403
404
273k
  active_script_ = &scripts_[next_script_++];
405
273k
  const curl::fuzzer::proto::Connection& script_connection = *active_script_->connection;
406
273k
  connection_ = CreateConnection();
407
273k
  if (!connection_ || !connection_->ok()) {
408
0
    connection_.reset();
409
0
    active_script_ = nullptr;
410
0
    return CURL_SOCKET_BAD;
411
0
  }
412
413
  // Target policies clamp/clear these values before execution. Saturating the
414
  // compatibility lane's raw uint32 avoids implementation-defined narrowing
415
  // while preserving its ability to request any representable socket size.
416
273k
  const std::uint32_t int_max = static_cast<std::uint32_t>(std::numeric_limits<int>::max());
417
273k
  const auto& backpressure = script_connection.backpressure();
418
273k
  const int recv_buf_bytes = static_cast<int>(std::min(backpressure.recv_buf_bytes(), int_max));
419
273k
  connection_->ApplyBackpressure(recv_buf_bytes, static_cast<std::size_t>(backpressure.drain_limit()));
420
421
273k
  const std::string& initial_response = script_connection.initial_response();
422
273k
  if (!initial_response.empty()) {
423
122k
    if (!connection_->WriteAll(reinterpret_cast<const unsigned char*>(initial_response.data()),
424
122k
                               initial_response.size())) {
425
0
      connection_.reset();
426
0
      active_script_ = nullptr;
427
0
      return CURL_SOCKET_BAD;
428
0
    }
429
122k
  }
430
273k
  if (preload_all_chunks_) {
431
19.0k
    while (has_more_chunks()) {
432
15.8k
      (void)DeliverNextChunk();
433
15.8k
    }
434
3.13k
  }
435
273k
  if (active_script_->chunk_count() == 0 && !keep_connections_open_) {
436
120k
    connection_->ShutdownWrite();
437
120k
  }
438
273k
  return connection_->take_client_fd();
439
273k
}
440
441
/// Preload all bounded response bytes from inside OPENSOCKETFUNCTION, where
442
/// the mock still owns both socketpair ends, and half-close the peer when the
443
/// preload finishes. This avoids a helper thread and prevents
444
/// curl from waiting for the outer chunk-delivery loop. The total serialized
445
/// fuzz input is capped by libFuzzer's max_len. If a non-blocking preload fills
446
/// the local socket, curl observes only the successfully queued prefix and
447
/// the timeouts below bound the incomplete response. This drive has no
448
/// iteration budget of its own, so it reasserts those timeouts after scenario
449
/// setopts and clears the option that can disable them.
450
/// @param easy Configured easy handle whose open-socket callback targets this
451
///        mock.
452
/// @param scenario Bounded response script to preload before performing.
453
/// @param use_events Select curl's debug event-based easy entrypoint.
454
/// @return Transfer result reported by curl's selected easy entrypoint.
455
1.63k
CURLcode MockServer::DriveEasyScenario(CURL* easy, const curl::fuzzer::proto::Scenario& scenario, bool use_events) {
456
1.63k
  SetScripts(scenario);
457
1.63k
  preload_all_chunks_ = true;
458
1.63k
  (void)curl_easy_setopt(easy, CURLOPT_TIMEOUT_MS, 50L);
459
1.63k
  (void)curl_easy_setopt(easy, CURLOPT_CONNECTTIMEOUT_MS, 50L);
460
  // CONNECT_ONLY makes curl's timeleft check report "no limit" for the whole
461
  // post-connect phase, so the timeouts above stop being enforced; value 2
462
  // additionally skips the connect-only shortcut and runs a complete transfer.
463
  // Clearing it is not a coverage loss: the multi-driven WebSocket lanes still
464
  // exercise CONNECT_ONLY under their own iteration budget. Zero rather than
465
  // one because CONNECT_ONLY=1 also disables the timeout and stays bounded only
466
  // through a curl-internal shortcut this harness should not depend on.
467
1.63k
  (void)curl_easy_setopt(easy, CURLOPT_CONNECT_ONLY, 0L);
468
1.63k
  const CURLcode result = use_events ? curl_easy_perform_ev(easy) : curl_easy_perform(easy);
469
1.63k
  preload_all_chunks_ = false;
470
1.63k
  return result;
471
1.63k
}
472
473
/// Establish only the HTTP transport, then pass bounded application bytes
474
/// through curl's public direct-I/O wrappers. Preloading makes receive
475
/// readiness deterministic without a helper thread; the socketpair peer stays
476
/// readable after ShutdownWrite and continues accepting the outgoing probe.
477
/// @param easy Configured easy handle whose transport this mock supplies.
478
/// @param scenario Source of the bounded response and direct-I/O probe bytes.
479
/// @return Results and byte counts from connect, send, and receive operations.
480
286
ConnectOnlyRunStats MockServer::DriveConnectOnlyScenario(CURL* easy, const curl::fuzzer::proto::Scenario& scenario) {
481
286
  ConnectOnlyRunStats stats;
482
286
  SetScripts(scenario);
483
286
  preload_all_chunks_ = true;
484
286
  (void)curl_easy_setopt(easy, CURLOPT_TIMEOUT_MS, 50L);
485
286
  (void)curl_easy_setopt(easy, CURLOPT_CONNECTTIMEOUT_MS, 50L);
486
286
  (void)curl_easy_setopt(easy, CURLOPT_CONNECT_ONLY, 1L);
487
286
  stats.connect_result = curl_easy_perform(easy);
488
286
  preload_all_chunks_ = false;
489
286
  if (stats.connect_result != CURLE_OK || connection_ == nullptr) {
490
57
    return stats;
491
57
  }
492
493
229
  constexpr std::string_view kFallbackRequest = "GET / HTTP/1.0\r\n\r\n";
494
229
  const std::string& upload = scenario.upload().data();
495
229
  const std::string_view source = upload.empty() ? kFallbackRequest : std::string_view(upload);
496
229
  const std::string_view outgoing = source.substr(0, scenario_limits::kMaxApiStringBytes);
497
229
  stats.send_result = CURLE_OK;
498
415
  for (int iteration = 0; stats.sent_bytes < outgoing.size() && iteration < kMaxConnectOnlyIoIterations; ++iteration) {
499
229
    std::size_t sent = 0;
500
229
    stats.send_result =
501
229
        curl_easy_send(easy, outgoing.data() + stats.sent_bytes, outgoing.size() - stats.sent_bytes, &sent);
502
229
    stats.sent_bytes += sent;
503
229
    (void)connection_->DrainIncoming();
504
229
    if (stats.send_result != CURLE_OK && stats.send_result != CURLE_AGAIN) {
505
43
      break;
506
43
    }
507
229
  }
508
509
229
  std::array<unsigned char, kConnectOnlyBufferSize> incoming{};
510
406
  for (int iteration = 0; iteration < kMaxConnectOnlyIoIterations; ++iteration) {
511
405
    std::size_t received = 0;
512
405
    stats.recv_result = curl_easy_recv(easy, incoming.data(), incoming.size(), &received);
513
405
    stats.received_bytes += received;
514
405
    if ((stats.recv_result != CURLE_OK && stats.recv_result != CURLE_AGAIN) ||
515
258
        (stats.recv_result == CURLE_OK && received == 0)) {
516
228
      break;
517
228
    }
518
405
  }
519
229
  return stats;
520
286
}
521
522
/// Push the next queued chunk. Called by the drive loop when curl is ready
523
/// for more data.
524
/// @return true when a chunk was consumed from the script.
525
592k
bool MockServer::DeliverNextChunk() {
526
592k
  if (!connection_ || !has_more_chunks()) {
527
0
    return false;
528
0
  }
529
592k
  connection_->DrainIncoming();
530
592k
  const std::size_t chunk_index = active_script_->next_chunk++;
531
592k
  const auto& script_connection = *active_script_->connection;
532
592k
  if (chunk_index < active_script_->raw_chunk_count) {
533
500k
    const std::string& chunk = script_connection.on_readable(static_cast<int>(chunk_index));
534
500k
    if (!chunk.empty()) {
535
458k
      connection_->WriteAll(reinterpret_cast<const unsigned char*>(chunk.data()), chunk.size());
536
458k
    }
537
500k
  } else {
538
    // HTTP scenarios historically accept structured WebSocket frames as raw
539
    // response bytes after every on_readable chunk. Serialize only the frame
540
    // curl is about to receive: follow-on scripts and capped suffix frames may
541
    // never be consumed, so eagerly materialising all of them wastes mutations.
542
92.6k
    const std::size_t frame_index = chunk_index - active_script_->raw_chunk_count;
543
92.6k
    const std::string chunk = SerializeWebSocketFrame(script_connection.server_frames(static_cast<int>(frame_index)));
544
92.6k
    if (!chunk.empty()) {
545
92.6k
      connection_->WriteAll(reinterpret_cast<const unsigned char*>(chunk.data()), chunk.size());
546
92.6k
    }
547
92.6k
  }
548
592k
  if (!has_more_chunks() && !keep_connections_open_) {
549
107k
    connection_->ShutdownWrite();
550
107k
  }
551
592k
  return true;
552
592k
}
553
554
/// Drain every live mock peer. Previous connections are normally quiescent,
555
/// but curl can finish sending a request body or close one after it has begun
556
/// resolving/opening the redirect target. Servicing both sides makes that
557
/// overlap deterministic without conflating their response scripts.
558
/// @return total bytes drained during this call.
559
1.34M
std::size_t MockServer::DrainIncomingConnections() {
560
1.34M
  std::size_t drained = 0;
561
1.34M
  for (const auto& previous : previous_connections_) {
562
419k
    drained += previous->DrainIncoming();
563
419k
  }
564
1.34M
  if (connection_) {
565
1.32M
    drained += connection_->DrainIncoming();
566
1.32M
  }
567
1.34M
  return drained;
568
1.34M
}
569
570
/// Service one deterministic application event-loop turn by draining all
571
/// available request bytes and releasing at most one response chunk. The
572
/// shared-multi driver owns the outer loop and calls this directly; ordinary
573
/// perform and socket-action drives use the same peer servicing. Draining
574
/// first creates request-side space before a response can provoke another
575
/// write, and releasing only one chunk preserves the scenario's mutation-
576
/// controlled parser boundaries.
577
/// @return true when any request or response byte advanced.
578
1.34M
bool MockServer::ServiceConnections() {
579
1.34M
  bool made_progress = DrainIncomingConnections() != 0;
580
1.34M
  if (has_more_chunks()) {
581
577k
    made_progress = DeliverNextChunk() || made_progress;
582
577k
  }
583
1.34M
  return made_progress;
584
1.34M
}
585
586
/// Report how many peer sockets curl opened during the current script run.
587
/// @return Number of response scripts assigned to live or retired sockets.
588
18.1k
std::size_t MockServer::opened_connection_count() const { return next_script_; }
589
590
/// Run a zero-wait application event loop around curl_multi_socket_action
591
/// using callback state owned by MockServerBase::DriveScenario. Positive
592
/// timers are deliberately not slept: the API lane clears timing controls
593
/// and covers event-driven dispatch, while the timing lane remains
594
/// responsible for clock-dependent behavior. Return after curl finishes or
595
/// a deterministic idle/operation cap wins.
596
/// @param multi Multi handle containing `easy`.
597
/// @param easy The easy handle attached to the mock.
598
720
void MockServer::RunSocketActionLoop(CURLM* multi, CURL* easy) {
599
720
  MultiSocketDriver* driver = multi_socket_driver();
600
720
  if (driver == nullptr) {
601
0
    return;
602
0
  }
603
604
720
  int still_running = 1;
605
720
  CURLMcode rc = driver->Start(&still_running);
606
720
  ObserveActiveTransfer(easy);
607
720
  ResumeResponseIfRequested(easy);
608
720
  int idle_iterations = 0;
609
720
  int drive_iterations = 0;
610
10.2k
  while (rc == CURLM_OK && still_running && idle_iterations < kMaxIdleIterations &&
611
9.52k
         drive_iterations++ < kMaxDriveIterations) {
612
9.52k
    bool made_progress = ServiceConnections();
613
9.52k
    const MultiSocketDriver::DriveResult drive_result = driver->DriveReady(&still_running);
614
9.52k
    rc = drive_result.code;
615
9.52k
    ObserveActiveTransfer(easy);
616
9.52k
    ResumeResponseIfRequested(easy);
617
9.52k
    made_progress = drive_result.made_progress || made_progress;
618
9.52k
    if (made_progress) {
619
9.33k
      idle_iterations = 0;
620
9.33k
    } else {
621
184
      ++idle_iterations;
622
184
    }
623
9.52k
  }
624
720
}
625
626
/// Ordinary HTTP and compatibility peers retain the historical perform-only
627
/// loop even if an append-only scenario field is present. Protocol subclasses
628
/// opt in only when their peer can service every repeated poll turn.
629
/// @return False for the generic mock server.
630
1.50k
bool MockServer::SupportsRepeatedPollsetProbe() const { return false; }
631
632
/// Seed the mock from the scenario, then drive the perform loop until curl is
633
/// done or a deterministic operation/idle budget is hit. Ordinary scenarios
634
/// never wait; explicit backpressure scenarios may use short select() waits.
635
/// @param multi    caller-owned multi; 'easy' is already added.
636
/// @param easy     the curl easy handle attached to this mock.
637
/// @param scenario source of the initial_response and on_readable chunks.
638
202k
void MockServer::RunLoop(CURLM* multi, CURL* easy, const curl::fuzzer::proto::Scenario& scenario) {
639
202k
  SetScripts(scenario);
640
641
202k
  if (multi_socket_driver() != nullptr) {
642
720
    RunSocketActionLoop(multi, easy);
643
720
    return;
644
720
  }
645
646
201k
  int still_running = 1;
647
201k
  int idle_iterations = 0;
648
201k
  int drive_iterations = 0;
649
201k
  bool pollset_probed = false;
650
  // Each newly opened socket can carry its own pressure settings. Inspect only
651
  // the borrowed, runtime-bounded scripts: ignored repeated protobuf entries must
652
  // not opt a fast transfer into timed waits.
653
201k
  const bool timed_drive =
654
237k
      std::any_of(scripts_.begin(), scripts_.begin() + script_count_, [](const ConnectionScript& script) {
655
237k
        const auto& backpressure = script.connection->backpressure();
656
237k
        return backpressure.recv_buf_bytes() != 0 || backpressure.drain_limit() != 0;
657
237k
      });
658
201k
  const int idle_limit = timed_drive ? kMaxTimedIdleIterations : kMaxIdleIterations;
659
201k
  const bool repeated_pollset_probe = scenario.probe_multi_pollset() && SupportsRepeatedPollsetProbe();
660
201k
  CURLMcode rc = CURLM_OK;
661
662
1.30M
  while (still_running && idle_iterations < idle_limit && drive_iterations++ < kMaxDriveIterations) {
663
1.28M
    bool made_progress = false;
664
1.28M
    const int running_before = still_running;
665
1.28M
    rc = curl_multi_perform(multi, &still_running);
666
1.28M
    if (rc != CURLM_OK) {
667
0
      break;
668
0
    }
669
1.28M
    ObserveActiveTransfer(easy);
670
1.28M
    ResumeResponseIfRequested(easy);
671
1.28M
    made_progress = still_running != running_before;
672
1.28M
    if (still_running && ((timed_drive && !pollset_probed) || repeated_pollset_probe)) {
673
      // Probe only after curl has built the socket/filter chain. Timing cases
674
      // need one zero-timeout poll; an explicit protocol opt-in probes each
675
      // bounded perform turn so filters installed after a SOCKS handshake
676
      // (notably HAProxy) are observed while active. Default fast paths remain
677
      // free of a per-input polling syscall.
678
48.2k
      ProbeMultiPollset(multi);
679
48.2k
      pollset_probed = true;
680
48.2k
    }
681
1.28M
    if (!still_running) {
682
184k
      break;
683
184k
    }
684
685
    // Always drain whatever curl has written. Under backpressure the kernel
686
    // recv buffer would otherwise stay full — curl short-writes, the mock
687
    // never consumes, and the transfer wedges until the drive budget. With
688
    // drain_limit set this still honours the per-tick byte budget.
689
1.10M
    made_progress = ServiceConnections() || made_progress;
690
691
1.10M
    if (made_progress) {
692
841k
      idle_iterations = 0;
693
841k
      continue;
694
841k
    }
695
696
    // Ordinary socketpair scenarios never sleep: repeated no-progress
697
    // performs are enough to settle curl's local state machine. Only an
698
    // explicit BackpressureConfig opts into short waits so timeout-related
699
    // behaviour remains fuzzable without taxing every corpus entry.
700
262k
    if (timed_drive) {
701
92.5k
      (void)WaitOnMultiFdset(multi, &rc);
702
92.5k
      if (rc != CURLM_OK) {
703
0
        break;
704
0
      }
705
92.5k
    }
706
262k
    ++idle_iterations;
707
262k
  }
708
201k
}
709
710
}  // namespace proto_fuzzer