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_base.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 MockServerBase — shared trampolines, shared
9
///        select() helper, DriveScenario multi-handle RAII, and the scheme
10
///        classifier that produces the right subclass for a Scenario.
11
12
#include "proto_fuzzer/mock_server_base.h"
13
14
#include <curl/multi.h>
15
#include <sys/select.h>
16
17
#include <cstdio>
18
19
#include "proto_fuzzer/allocation_fault_injection.h"
20
#include "proto_fuzzer/curl_raii.h"
21
#include "proto_fuzzer/mock_server.h"
22
#include "proto_fuzzer/multi_socket_driver.h"
23
24
namespace proto_fuzzer {
25
26
namespace {
27
28
constexpr long kSelectTimeoutUs = 1000;  // 1 ms; explicit timing cases only.
29
30
/// Enumerate attached handles without letting an injected failure prevent
31
/// harness-owned pushed-handle cleanup. Genuine allocation failure can still
32
/// return null and follows the caller's existing safe fallback.
33
/// @param multi Live multi handle whose attached easies are required.
34
/// @return Caller-owned, null-terminated handle array, or nullptr on real OOM.
35
303k
CURL** GetHandlesForCleanup(CURLM* multi) {
36
303k
  allocation_fault_injection::ScopedFailureSuppression suppress_failures;
37
303k
  return curl_multi_get_handles(multi);
38
303k
}
39
40
}  // namespace
41
42
/// @brief C trampoline for CURLOPT_OPENSOCKETFUNCTION. Declared at namespace
43
///        scope so it can be a friend of MockServerBase.
44
/// @param clientp Pointer to the MockServerBase instance.
45
/// @param purpose The socket role curl is asking the mock to provide.
46
/// @param address Curl's mutable description of the intended destination.
47
/// @return The client-side socket fd as a curl_socket_t.
48
374k
curl_socket_t MockServerBaseOpenSocketTrampoline(void* clientp, curlsocktype purpose, struct curl_sockaddr* address) {
49
374k
  return static_cast<MockServerBase*>(clientp)->HandleOpenSocket(purpose, address);
50
374k
}
51
52
/// Translate explicit peer transport metadata into curl's sockopt callback
53
/// contract. The descriptor is used only as an opaque identity; sandbox
54
/// policy must not decide whether an otherwise valid in-process transport can
55
/// run.
56
/// @param clientp Pointer to the MockServerBase instance.
57
/// @param curlfd Descriptor returned by the open-socket callback.
58
/// @param purpose Socket role assigned by curl.
59
/// @return CURL_SOCKOPT_ALREADY_CONNECTED for prepared stream peers, otherwise
60
///         CURL_SOCKOPT_OK.
61
349k
int MockServerBaseSockOptTrampoline(void* clientp, curl_socket_t curlfd, curlsocktype purpose) {
62
349k
  const auto disposition = static_cast<MockServerBase*>(clientp)->GetSocketSetupDisposition(curlfd, purpose);
63
349k
  return disposition == SocketSetupDisposition::kAlreadyConnected ? CURL_SOCKOPT_ALREADY_CONNECTED : CURL_SOCKOPT_OK;
64
349k
}
65
66
/// Construct an empty base instance with a fixed multi-drive policy.
67
/// @param drive_policy Whether to perform, use socket actions, or honor the
68
///        containing Scenario's ApiPlan.
69
MockServerBase::MockServerBase(MultiDrivePolicy drive_policy)
70
326k
    : connection_(nullptr),
71
326k
      pending_recv_buf_bytes_(0),
72
326k
      pending_drain_limit_(0),
73
326k
      multi_socket_driver_(nullptr),
74
326k
      additional_handle_cleanup_count_(0),
75
326k
      resume_response_(false),
76
326k
      drive_policy_(drive_policy) {}
77
78
/// Out-of-line destructor so MockConnection can stay forward-declared in the
79
/// base header (its complete type is only needed where unique_ptr is
80
/// instantiated for destruction).
81
326k
MockServerBase::~MockServerBase() = default;
82
83
/// Default no-op for peers without protocol-specific observations. Overrides
84
/// retain bounded state only in coverage and introspector builds; a derived
85
/// peer calls its base implementation before observing its own state.
86
307k
void MockServerBase::ObserveState() {}
87
88
/// @return the owned MockConnection, or nullptr if one has not been opened.
89
1.04M
MockConnection* MockServerBase::connection() { return connection_.get(); }
90
91
/// Install the common OPENSOCKETFUNCTION / OPENSOCKETDATA / SOCKOPTFUNCTION
92
/// callbacks on 'easy'. All subclasses share the trampolines, which route
93
/// back into this instance through HandleOpenSocket. Subclasses may override
94
/// to layer additional protocol-specific setopts, such as a WRITEFUNCTION
95
/// that exercises protocol APIs from inside a curl callback.
96
/// @param easy The curl easy handle to configure.
97
365k
void MockServerBase::Install(CURL* easy) {
98
365k
  curl_easy_setopt(easy, CURLOPT_OPENSOCKETFUNCTION, &MockServerBaseOpenSocketTrampoline);
99
365k
  curl_easy_setopt(easy, CURLOPT_OPENSOCKETDATA, this);
100
365k
  curl_easy_setopt(easy, CURLOPT_SOCKOPTFUNCTION, &MockServerBaseSockOptTrampoline);
101
365k
  curl_easy_setopt(easy, CURLOPT_SOCKOPTDATA, this);
102
365k
}
103
104
/// Describe the socket returned by HandleOpenSocket without issuing native
105
/// descriptor queries. Stream peers return connected socketpairs; accepted
106
/// sockets and datagram peers require curl's ordinary setup.
107
/// @param curlfd Descriptor returned by HandleOpenSocket.
108
/// @param purpose Role curl assigned to the descriptor.
109
/// @return Whether curl must perform its normal socket setup.
110
334k
SocketSetupDisposition MockServerBase::GetSocketSetupDisposition(curl_socket_t /*curlfd*/, curlsocktype purpose) const {
111
  // curl itself accepted CURLSOCKTYPE_ACCEPT descriptors, so they must follow
112
  // its normal post-accept option path. Every IPCXN socket returned by the
113
  // ordinary stream mocks is one end of an already-connected socketpair.
114
334k
  return purpose == CURLSOCKTYPE_ACCEPT ? SocketSetupDisposition::kNeedsSetup
115
334k
                                        : SocketSetupDisposition::kAlreadyConnected;
116
334k
}
117
118
/// Bind protocol-specific work to the request-data callbacks after their
119
/// per-scenario state has been constructed. Ordinary HTTP and WebSocket
120
/// mocks regain control in their outer perform loops and drain client
121
/// traffic there. Most mocks therefore need no hook; TELNET uses this
122
/// upload-callback boundary to drain client replies while curl owns the
123
/// thread.
124
/// @param request_data Callback state that outlives the subsequent drive.
125
357k
void MockServerBase::ConfigureRequestData(ScenarioRequestData* /*request_data*/) {}
126
127
/// Run 'scenario' to completion on 'easy': allocate a multi, attach 'easy',
128
/// delegate protocol-specific work to RunLoop, consume its completion
129
/// message, and clean up. Read the result before removing the only easy
130
/// handle so every protocol runner exercises the public multi-result path.
131
/// Harness setup failures return a stable sentinel; fuzzer callers may
132
/// ignore it while unit tests can assert the protocol result without adding
133
/// another callback or global.
134
/// @param easy     curl easy handle already Install()ed on this mock.
135
/// @param scenario the Scenario proto to drive.
136
/// @return the completed transfer's CURLcode, or CURLE_FAILED_INIT when the
137
/// bounded drive could not produce a completion message.
138
306k
CURLcode MockServerBase::DriveScenario(CURL* easy, const curl::fuzzer::proto::Scenario& scenario) {
139
306k
  const curl::fuzzer::proto::ApiPlan* api_plan =
140
306k
      drive_policy_ == MultiDrivePolicy::kFromApiPlan && scenario.has_api_plan() ? &scenario.api_plan() : nullptr;
141
306k
  const bool use_multi_socket =
142
306k
      drive_policy_ == MultiDrivePolicy::kSocketAction ||
143
303k
      (api_plan != nullptr && api_plan->drive_mode() == curl::fuzzer::proto::API_DRIVE_MULTI_SOCKET);
144
145
  // Cache backpressure knobs so HandleOpenSocket can apply them the moment
146
  // connection_ exists. Both default to 0, which matches the legacy "drain
147
  // greedily, kernel-default buffers" behaviour exactly.
148
306k
  const auto& bp = scenario.connection().backpressure();
149
306k
  pending_recv_buf_bytes_ = static_cast<int>(bp.recv_buf_bytes());
150
306k
  pending_drain_limit_ = static_cast<std::size_t>(bp.drain_limit());
151
306k
  additional_handle_cleanup_count_ = 0;
152
306k
  resume_response_ = api_plan != nullptr && api_plan->pause_response_once();
153
154
306k
  CurlMultiPtr multi(curl_multi_init());
155
306k
  if (multi == nullptr) {
156
2.63k
    resume_response_ = false;
157
2.63k
    return CURLE_FAILED_INIT;
158
2.63k
  }
159
160
303k
  CURLcode transfer_result = CURLE_FAILED_INIT;
161
162
  // Callback data must survive both remove_handle and multi_cleanup, since
163
  // either may emit CURL_POLL_REMOVE. Keeping it in this outer scope provides
164
  // that lifetime without allocating per-watch state.
165
303k
  MultiSocketDriver socket_driver;
166
303k
  if (use_multi_socket && socket_driver.Install(multi.get())) {
167
3.60k
    multi_socket_driver_ = &socket_driver;
168
3.60k
  }
169
303k
  if (curl_multi_add_handle(multi.get(), easy) == CURLM_OK) {
170
303k
    if (multi_observer_) {
171
6.81k
      multi_observer_(multi.get());
172
6.81k
    }
173
303k
    if (api_plan != nullptr && api_plan->wake_multi()) {
174
347
      if (multi_socket_driver_ != nullptr) {
175
113
        multi_socket_driver_->ProbeControlApis();
176
234
      } else {
177
234
        long timeout_ms = -1;
178
234
        (void)curl_multi_timeout(multi.get(), &timeout_ms);
179
234
        (void)curl_multi_wakeup(multi.get());
180
234
      }
181
347
    }
182
303k
    RunLoop(multi.get(), easy, scenario);
183
184
    // Completion messages are the multi API's only durable record of the
185
    // transfer result. Consume them while all easy handles are still attached:
186
    // otherwise every scenario systematically skips curl_multi_info_read's
187
    // result path and removal discards the opportunity. An accepted HTTP/2
188
    // push can contribute one additional completion message; only the caller's
189
    // parent determines DriveScenario's result.
190
303k
    int messages_remaining = 0;
191
303k
    CURLMsg* message = nullptr;
192
544k
    while ((message = curl_multi_info_read(multi.get(), &messages_remaining)) != nullptr) {
193
240k
      if (message->msg == CURLMSG_DONE && message->easy_handle == easy) {
194
239k
        transfer_result = message->data.result;
195
239k
      }
196
240k
    }
197
198
    // CURL_PUSH_OK transfers ownership of each automatically-added easy to
199
    // the application. Enumerate attached handles only after draining their
200
    // completion messages, then honor the public remove-before-cleanup
201
    // lifecycle. The original `easy` remains caller-owned.
202
303k
    CURL** handles = GetHandlesForCleanup(multi.get());
203
303k
    if (handles != nullptr) {
204
608k
      for (std::size_t index = 0; handles[index] != nullptr; ++index) {
205
305k
        CURL* handle = handles[index];
206
305k
        if (handle != easy && curl_multi_remove_handle(multi.get(), handle) == CURLM_OK) {
207
2.08k
          curl_easy_cleanup(handle);
208
2.08k
          ++additional_handle_cleanup_count_;
209
2.08k
        }
210
305k
      }
211
303k
      curl_free(handles);
212
303k
    }
213
214
303k
    curl_multi_remove_handle(multi.get(), easy);
215
303k
  }
216
  // Socket-action callbacks borrow the stack driver above, so that path must
217
  // clean its multi before this function returns. Perform-based protocol mocks
218
  // may retain the detached multi when their fixed lifecycle requires it.
219
303k
  if (use_multi_socket) {
220
3.60k
    multi.reset();
221
299k
  } else {
222
299k
    HandleDetachedMulti(std::move(multi));
223
299k
  }
224
303k
  multi_socket_driver_ = nullptr;
225
303k
  if (socket_driver.watch_exhausted()) {
226
0
    std::fputs("curl-fuzzer: socket watch capacity exhausted\n", stderr);
227
0
  }
228
303k
  resume_response_ = false;
229
303k
  return transfer_result;
230
306k
}
231
232
/// Dispose of or retain the multi after its easy handle has been removed.
233
/// The default destroys it before DriveScenario returns. A protocol mock
234
/// may retain it as member state when its fixed lifecycle requires easy
235
/// cleanup to happen first.
236
/// @param multi Detached multi handle and its live connection cache.
237
241k
void MockServerBase::HandleDetachedMulti(CurlMultiPtr /*multi*/) {}
238
239
/// Run through the public easy entrypoint when a protocol mock can preload
240
/// all peer work before curl takes control. The base preserves the ordinary
241
/// multi-drive fallback for protocols that require an outer driver to make
242
/// progress. The API policy currently forces HTTP, whose override preloads
243
/// its bounded response and calls curl_easy_perform without a thread.
244
/// @param easy curl easy handle already Install()ed on this mock.
245
/// @param scenario Scenario whose response the mock must prepare.
246
/// @param use_events Select curl's debug event-based easy entrypoint when
247
///        the concrete mock supports it.
248
/// @return Transfer result reported by the selected easy or fallback drive.
249
CURLcode MockServerBase::DriveEasyScenario(CURL* easy, const curl::fuzzer::proto::Scenario& scenario,
250
0
                                           bool /*use_events*/) {
251
0
  return DriveScenario(easy, scenario);
252
0
}
253
254
/// Establish a CONNECT_ONLY transport, then perform bounded direct I/O.
255
/// HTTP overrides this; other protocol mocks retain a safe fallback.
256
/// @param easy curl easy handle already Install()ed on this mock.
257
/// @param scenario Scenario supplying response and direct-I/O bytes.
258
/// @return Results and byte counts from connect, send, and receive probes.
259
ConnectOnlyRunStats MockServerBase::DriveConnectOnlyScenario(CURL* easy,
260
0
                                                             const curl::fuzzer::proto::Scenario& scenario) {
261
0
  ConnectOnlyRunStats stats;
262
0
  stats.connect_result = DriveScenario(easy, scenario);
263
0
  return stats;
264
0
}
265
266
/// Expose the callback state installed for the current socket-action drive.
267
/// HTTP's RunLoop uses this instead of reading the proto directly, so only
268
/// the dedicated API binary can opt into lifecycle work and compatibility
269
/// inputs containing the new field retain their old behavior. Ownership
270
/// remains in DriveScenario so no subclass can shorten the driver's lifetime.
271
/// @return active driver, or nullptr for the ordinary perform path.
272
206k
MultiSocketDriver* MockServerBase::multi_socket_driver() { return multi_socket_driver_; }
273
274
/// @return extra easy handles removed and cleaned after the latest drive.
275
/// Server push is currently the only path that can add one behind the
276
/// caller's back; exposing the count to subclasses keeps ownership in this
277
/// multi-owning base while allowing focused lifecycle assertions.
278
0
std::size_t MockServerBase::additional_handle_cleanup_count() const { return additional_handle_cleanup_count_; }
279
280
/// Resume receive-side callback output at one bounded drive boundary when
281
/// the dedicated API plan requested it. Calling CONT before the callback
282
/// pauses is harmless; repeating it ensures a later response chunk cannot
283
/// leave the transfer suspended until timeout.
284
/// @param easy Active easy handle whose receive callbacks may be paused.
285
1.59M
void MockServerBase::ResumeResponseIfRequested(CURL* easy) {
286
1.59M
  if (resume_response_) {
287
5.52k
    (void)curl_easy_pause(easy, CURLPAUSE_CONT);
288
5.52k
  }
289
1.59M
}
290
291
/// Apply the BackpressureConfig cached by DriveScenario to the new
292
/// connection_. Subclasses call this at the end of HandleOpenSocket, before
293
/// returning the client fd, so SO_RCVBUF takes effect before traffic flows.
294
/// Safe to call when connection_ is null or both knobs are zero: those cases
295
/// are no-ops.
296
22.8k
void MockServerBase::ApplyPendingBackpressure() {
297
22.8k
  if (connection_) {
298
22.8k
    connection_->ApplyBackpressure(pending_recv_buf_bytes_, pending_drain_limit_);
299
22.8k
  }
300
22.8k
}
301
302
/// Treat a non-default BackpressureConfig as an explicit request for the
303
/// slower, timed drive policy. Proto3 scalar defaults make this deterministic:
304
/// a present-but-empty message remains on the ordinary fast path.
305
/// @param scenario Scenario whose backpressure settings select the policy.
306
/// @return true when the scenario explicitly opted into socket backpressure.
307
27.1k
bool MockServerBase::UsesTimedDrive(const curl::fuzzer::proto::Scenario& scenario) {
308
27.1k
  const auto& bp = scenario.connection().backpressure();
309
27.1k
  return bp.recv_buf_bytes() != 0 || bp.drain_limit() != 0;
310
27.1k
}
311
312
/// Wait on curl's fdset with a short timeout. Drive loops call this only for
313
/// scenarios that explicitly request backpressure/timing behaviour; ordinary
314
/// scenarios run without wall-clock sleeps.
315
/// @param multi The multi handle whose fdset to poll.
316
/// @param rc    Out parameter: set to the CURLMcode on error.
317
/// @return select()'s result, or -1 on curl_multi_fdset failure.
318
316k
int MockServerBase::WaitOnMultiFdset(CURLM* multi, CURLMcode* rc) {
319
316k
  fd_set readfds;
320
316k
  fd_set writefds;
321
316k
  fd_set excfds;
322
316k
  FD_ZERO(&readfds);
323
316k
  FD_ZERO(&writefds);
324
316k
  FD_ZERO(&excfds);
325
316k
  int maxfd = -1;
326
316k
  *rc = curl_multi_fdset(multi, &readfds, &writefds, &excfds, &maxfd);
327
316k
  if (*rc != CURLM_OK) {
328
0
    return -1;
329
0
  }
330
316k
  if (maxfd < 0) {
331
0
    return 0;
332
0
  }
333
316k
  struct timeval timeout;
334
316k
  timeout.tv_sec = 0;
335
316k
  timeout.tv_usec = kSelectTimeoutUs;
336
316k
  return ::select(maxfd + 1, &readfds, &writefds, &excfds, &timeout);
337
316k
}
338
339
/// Ask curl to construct and inspect its connection-filter pollset without
340
/// waiting. A perform-only harness can complete local socketpair transfers
341
/// while skipping the public multi-poll path used by event-driven
342
/// applications. Selected opt-in scenarios make zero-timeout probes to retain
343
/// that coverage without taxing the default fast path. The result is ignored:
344
/// the protocol-specific perform loop determines transfer progress.
345
/// @param multi The active multi handle after at least one perform call.
346
97.4k
void MockServerBase::ProbeMultiPollset(CURLM* multi) {
347
97.4k
  int numfds = 0;
348
97.4k
  (void)curl_multi_poll(multi, nullptr, 0, 0, &numfds);
349
97.4k
}
350
351
/// Inspect one socket's current writable interest through curl's public multi
352
/// fdset API. MockConnection already rejects descriptors outside FD_SETSIZE,
353
/// so the matching FD_ISSET operation remains bounded.
354
/// @param multi Multi handle that owns the socket.
355
/// @param socket Socket returned to curl by the open-socket callback.
356
/// @return true when curl currently waits for the socket to become writable.
357
6.55k
bool MockServerBase::MultiPollsetWantsWrite(CURLM* multi, curl_socket_t socket) {
358
6.55k
  if (multi == nullptr || socket == CURL_SOCKET_BAD || socket < 0 || socket >= FD_SETSIZE) {
359
0
    return false;
360
0
  }
361
6.55k
  fd_set readfds;
362
6.55k
  fd_set writefds;
363
6.55k
  fd_set excfds;
364
6.55k
  FD_ZERO(&readfds);
365
6.55k
  FD_ZERO(&writefds);
366
6.55k
  FD_ZERO(&excfds);
367
6.55k
  int maxfd = -1;
368
6.55k
  if (curl_multi_fdset(multi, &readfds, &writefds, &excfds, &maxfd) != CURLM_OK) {
369
0
    return false;
370
0
  }
371
6.55k
  return socket <= maxfd && FD_ISSET(socket, &writefds);
372
6.55k
}
373
374
}  // namespace proto_fuzzer