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/multi_transfer_runner.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 bounded concurrent easy-handle runner.
9
10
#include "proto_fuzzer/multi_transfer_runner.h"
11
12
#define CURL_ALLOW_OLD_MULTI_SOCKET
13
#include <curl/curl.h>
14
#include <curl/multi.h>
15
16
#include <algorithm>
17
#include <array>
18
#include <cstddef>
19
#include <cstdio>
20
#include <memory>
21
#include <string>
22
23
#include "proto_fuzzer/curl_raii.h"
24
#include "proto_fuzzer/mock_server.h"
25
#include "proto_fuzzer/multi_socket_driver.h"
26
#include "proto_fuzzer/option_apply.h"
27
#include "proto_fuzzer/request_data.h"
28
#include "proto_fuzzer/scenario_limits.h"
29
#include "proto_fuzzer/transfer_session.h"
30
31
namespace proto_fuzzer {
32
33
namespace {
34
35
/// Track shared-multi membership separately from each transfer's resources.
36
struct TransferState {
37
  TransferSession session;
38
  bool attached = false;
39
};
40
41
constexpr int kMaxDriveIterations = 512;
42
constexpr int kMaxIdleIterations = 8;
43
constexpr curl_off_t kStateProbeReceiveRate = 1;
44
constexpr long kStateProbeTimeoutMs = 20;
45
46
struct FileCloser {
47
2.23k
  void operator()(FILE* file) const {
48
2.23k
    if (file != nullptr) {
49
2.23k
      std::fclose(file);
50
2.23k
    }
51
2.23k
  }
52
};
53
54
using FilePtr = std::unique_ptr<FILE, FileCloser>;
55
56
/// Install the one intentionally slow transfer shape without exposing its
57
/// values through generic SetOption mutations. The anonymous stream is owned
58
/// by RunMultiTransferScenario and outlives every configured easy handle.
59
55.9k
bool ApplyStateProbeOptions(CURL* easy, curl::fuzzer::proto::MultiStateProbeProfile profile, FILE* progress_sink) {
60
55.9k
  if (profile != curl::fuzzer::proto::MULTI_STATE_PROBE_PROGRESS_RATE_LIMIT || progress_sink == nullptr) {
61
48.1k
    return false;
62
48.1k
  }
63
7.82k
  return curl_easy_setopt(easy, CURLOPT_STDERR, progress_sink) == CURLE_OK &&
64
7.82k
         curl_easy_setopt(easy, CURLOPT_TIMEOUT_MS, kStateProbeTimeoutMs) == CURLE_OK &&
65
7.82k
         curl_easy_setopt(easy, CURLOPT_NOPROGRESS, 0L) == CURLE_OK &&
66
7.82k
         curl_easy_setopt(easy, CURLOPT_MAX_RECV_SPEED_LARGE, kStateProbeReceiveRate) == CURLE_OK;
67
55.9k
}
68
69
18.2k
std::size_t RuntimeTransferCount(const curl::fuzzer::proto::MultiPlan& plan) {
70
18.2k
  return std::max(scenario_limits::kMinMultiTransfers,
71
18.2k
                  std::min(static_cast<std::size_t>(plan.transfer_count()), scenario_limits::kMaxMultiTransfers));
72
18.2k
}
73
74
76.1k
void RecordNotification(CURLM*, unsigned int notification, CURL*, void* userdata) {
75
76.1k
  auto* stats = static_cast<MultiTransferRunStats*>(userdata);
76
76.1k
  if (stats == nullptr) {
77
0
    return;
78
0
  }
79
76.1k
  if (notification == CURLMNOTIFY_INFO_READ) {
80
25.3k
    ++stats->info_read_notifications;
81
50.8k
  } else if (notification == CURLMNOTIFY_EASY_DONE) {
82
50.8k
    ++stats->easy_done_notifications;
83
50.8k
  }
84
76.1k
}
85
86
/// Group the operations that share one multi and its bounded transfer set.
87
/// RunMultiTransferScenario owns every borrowed object and performs cleanup;
88
/// the driver never destroys or detaches a transfer when its scope ends.
89
class MultiTransferDriver {
90
 public:
91
  MultiTransferDriver(CURLM* multi, std::array<TransferState, scenario_limits::kMaxMultiTransfers>& transfers,
92
                      std::size_t transfer_count, MultiTransferRunStats& stats)
93
18.1k
      : multi_(multi), transfers_(transfers), transfer_count_(transfer_count), stats_(stats) {}
94
95
  /// Consume every queued completion before handle removal can discard it.
96
  /// Re-added handles may complete more than once, so count messages rather
97
  /// than only distinct easy pointers.
98
269k
  bool DrainCompletionMessages() {
99
269k
    bool consumed = false;
100
269k
    int messages_remaining = 0;
101
269k
    CURLMsg* message = nullptr;
102
319k
    while ((message = curl_multi_info_read(multi_, &messages_remaining)) != nullptr) {
103
50.2k
      consumed = true;
104
50.2k
      if (message->msg != CURLMSG_DONE) {
105
0
        continue;
106
0
      }
107
110k
      for (std::size_t index = 0; index < transfer_count_; ++index) {
108
110k
        TransferState& transfer = transfers_[index];
109
110k
        if (transfer.session.easy() == message->easy_handle) {
110
50.2k
          ++stats_.completion_messages;
111
50.2k
          break;
112
50.2k
        }
113
110k
      }
114
50.2k
    }
115
269k
    return consumed;
116
269k
  }
117
118
  /// Apply one schema-safe lifecycle transition. Return true only when
119
  /// libcurl accepted a state change; the caller tracks action consumption
120
  /// separately so later ordered actions remain reachable.
121
31.2k
  bool ApplyAction(const curl::fuzzer::proto::MultiAction& action) {
122
31.2k
    if (transfer_count_ == 0) {
123
0
      return false;
124
0
    }
125
31.2k
    TransferState& transfer = transfers_[static_cast<std::size_t>(action.transfer_selector()) % transfer_count_];
126
31.2k
    CURL* easy = transfer.session.easy();
127
31.2k
    if (easy == nullptr) {
128
276
      return false;
129
276
    }
130
131
31.0k
    switch (action.kind()) {
132
1.87k
      case curl::fuzzer::proto::MULTI_ACTION_PAUSE_RECV:
133
1.87k
        return curl_easy_pause(easy, CURLPAUSE_RECV) == CURLE_OK;
134
1.53k
      case curl::fuzzer::proto::MULTI_ACTION_PAUSE_SEND:
135
1.53k
        return curl_easy_pause(easy, CURLPAUSE_SEND) == CURLE_OK;
136
1.23k
      case curl::fuzzer::proto::MULTI_ACTION_PAUSE_ALL:
137
1.23k
        return curl_easy_pause(easy, CURLPAUSE_ALL) == CURLE_OK;
138
955
      case curl::fuzzer::proto::MULTI_ACTION_RESUME:
139
955
        return curl_easy_pause(easy, CURLPAUSE_CONT) == CURLE_OK;
140
9.18k
      case curl::fuzzer::proto::MULTI_ACTION_REMOVE:
141
9.18k
        if (transfer.attached && curl_multi_remove_handle(multi_, easy) == CURLM_OK) {
142
7.84k
          transfer.attached = false;
143
7.84k
          return true;
144
7.84k
        }
145
1.34k
        return false;
146
9.40k
      case curl::fuzzer::proto::MULTI_ACTION_READD:
147
9.40k
        if (!transfer.attached && curl_multi_add_handle(multi_, easy) == CURLM_OK) {
148
6.64k
          transfer.attached = true;
149
6.64k
          return true;
150
6.64k
        }
151
2.76k
        return false;
152
6.83k
      case curl::fuzzer::proto::MULTI_ACTION_NONE:
153
6.83k
      default:
154
6.83k
        return false;
155
31.0k
    }
156
31.0k
  }
157
158
 private:
159
  CURLM* multi_;
160
  std::array<TransferState, scenario_limits::kMaxMultiTransfers>& transfers_;
161
  const std::size_t transfer_count_;
162
  MultiTransferRunStats& stats_;
163
};
164
165
/// Cover the public wait/poll/fdset queries from a valid shared-multi state
166
/// without introducing wall-clock delay.
167
18.1k
void ProbeMultiWaitApis(CURLM* multi) {
168
18.1k
  int numfds = 0;
169
18.1k
  (void)curl_multi_poll(multi, nullptr, 0, 0, &numfds);
170
18.1k
  (void)curl_multi_wait(multi, nullptr, 0, 0, &numfds);
171
172
18.1k
  unsigned int waitfd_count = 0;
173
18.1k
  (void)curl_multi_waitfds(multi, nullptr, 0, &waitfd_count);
174
18.1k
  std::array<curl_waitfd, scenario_limits::kMaxMultiTransfers * 2> waitfds{};
175
18.1k
  (void)curl_multi_waitfds(multi, waitfds.data(), static_cast<unsigned int>(waitfds.size()), &waitfd_count);
176
177
18.1k
  fd_set readfds;
178
18.1k
  fd_set writefds;
179
18.1k
  fd_set exceptfds;
180
18.1k
  FD_ZERO(&readfds);
181
18.1k
  FD_ZERO(&writefds);
182
18.1k
  FD_ZERO(&exceptfds);
183
18.1k
  int maxfd = -1;
184
18.1k
  (void)curl_multi_fdset(multi, &readfds, &writefds, &exceptfds, &maxfd);
185
18.1k
  long timeout_ms = -1;
186
18.1k
  (void)curl_multi_timeout(multi, &timeout_ms);
187
188
18.1k
  CURL** handles = curl_multi_get_handles(multi);
189
18.1k
  curl_free(handles);
190
191
18.1k
  constexpr CURLMinfo_offt kOffsetInfo[] = {
192
18.1k
      CURLMINFO_XFERS_CURRENT, CURLMINFO_XFERS_RUNNING, CURLMINFO_XFERS_PENDING,
193
18.1k
      CURLMINFO_XFERS_DONE,    CURLMINFO_XFERS_ADDED,
194
18.1k
  };
195
90.7k
  for (const CURLMinfo_offt info : kOffsetInfo) {
196
90.7k
    curl_off_t value = 0;
197
90.7k
    (void)curl_multi_get_offt(multi, info, &value);
198
90.7k
  }
199
18.1k
}
200
201
/// Exercise the two deprecated public entrypoints as real symbols rather than
202
/// curl_multi_socket's compatibility macro. Their output is deliberately not
203
/// used to select the primary runner: either call may advance a transfer, and
204
/// the normal bounded loop consumes whatever state remains.
205
18.1k
void ProbeLegacyMultiSocketApis(CURLM* multi) {
206
18.1k
  int running_handles = 0;
207
18.1k
#if defined(__GNUC__)
208
18.1k
#pragma GCC diagnostic push
209
18.1k
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
210
18.1k
#endif
211
18.1k
  (void)curl_multi_socket(multi, CURL_SOCKET_TIMEOUT, &running_handles);
212
18.1k
  (void)curl_multi_socket_all(multi, &running_handles);
213
18.1k
#if defined(__GNUC__)
214
18.1k
#pragma GCC diagnostic pop
215
18.1k
#endif
216
18.1k
}
217
218
}  // namespace
219
220
/// Drive two to four easy handles through one CURLM and one bounded in-process
221
/// HTTP peer. Runtime bounds repeat the mutation policy's limits so direct
222
/// unit-test and standalone calls cannot make work proportional to unchecked
223
/// input.
224
/// @param scenario HTTP transfer shape and concurrent lifecycle plan.
225
/// @return Bounded setup, action, and completion counts.
226
18.2k
MultiTransferRunStats RunMultiTransferScenario(const curl::fuzzer::proto::Scenario& scenario) {
227
18.2k
  MultiTransferRunStats stats;
228
18.2k
  const auto& plan = scenario.multi_plan();
229
18.2k
  const std::size_t transfer_count = RuntimeTransferCount(plan);
230
18.2k
  stats.configured_handles = transfer_count;
231
232
18.2k
  FilePtr progress_sink;
233
18.2k
  if (plan.state_probe_profile() == curl::fuzzer::proto::MULTI_STATE_PROBE_PROGRESS_RATE_LIMIT) {
234
2.23k
    progress_sink.reset(std::tmpfile());
235
2.23k
  }
236
237
  // The peer and socket callback state must outlive multi cleanup, which can
238
  // synchronously announce socket removals and close cached connections.
239
18.2k
  MockServer mock;
240
18.2k
  mock.SetScripts(scenario);
241
18.2k
  mock.SetKeepConnectionsOpen(plan.keep_connections_open());
242
18.2k
  MultiSocketDriver socket_driver;
243
18.2k
  CurlMultiPtr multi(curl_multi_init());
244
18.2k
  if (!multi) {
245
61
    return stats;
246
61
  }
247
248
18.1k
  const long max_host_connections =
249
18.1k
      static_cast<long>(std::min<std::size_t>(plan.max_host_connections(), transfer_count));
250
18.1k
  const long max_total_connections =
251
18.1k
      static_cast<long>(std::min<std::size_t>(plan.max_total_connections(), transfer_count));
252
18.1k
  const long cache_size =
253
18.1k
      static_cast<long>(std::min<std::size_t>(plan.connection_cache_size(), scenario_limits::kMaxMultiTransfers * 2));
254
18.1k
  (void)curl_multi_setopt(multi.get(), CURLMOPT_MAX_HOST_CONNECTIONS, max_host_connections);
255
18.1k
  (void)curl_multi_setopt(multi.get(), CURLMOPT_MAX_TOTAL_CONNECTIONS, max_total_connections);
256
18.1k
  (void)curl_multi_setopt(multi.get(), CURLMOPT_MAXCONNECTS, cache_size);
257
18.1k
  (void)curl_multi_setopt(multi.get(), CURLMOPT_PIPELINING,
258
18.1k
                          plan.multiplex() ? static_cast<long>(CURLPIPE_MULTIPLEX) : 0L);
259
18.1k
  (void)curl_multi_setopt(multi.get(), CURLMOPT_NOTIFYFUNCTION, &RecordNotification);
260
18.1k
  (void)curl_multi_setopt(multi.get(), CURLMOPT_NOTIFYDATA, &stats);
261
18.1k
  (void)curl_multi_notify_enable(multi.get(), CURLMNOTIFY_INFO_READ);
262
18.1k
  (void)curl_multi_notify_enable(multi.get(), CURLMNOTIFY_EASY_DONE);
263
18.1k
  (void)curl_multi_notify_disable(multi.get(), CURLMNOTIFY_INFO_READ);
264
18.1k
  (void)curl_multi_notify_enable(multi.get(), CURLMNOTIFY_INFO_READ);
265
18.1k
  (void)curl_multi_notify_disable(multi.get(), CURLMNOTIFY_EASY_DONE);
266
18.1k
  (void)curl_multi_notify_enable(multi.get(), CURLMNOTIFY_EASY_DONE);
267
268
18.1k
  const bool socket_mode = plan.drive_mode() == curl::fuzzer::proto::MULTI_DRIVE_SOCKET;
269
18.1k
  const bool socket_driver_installed = socket_mode && socket_driver.Install(multi.get());
270
18.1k
  std::array<TransferState, scenario_limits::kMaxMultiTransfers> transfers;
271
18.1k
  const std::string url = "http://" + scenario.host_path();
272
74.9k
  for (std::size_t index = 0; index < transfer_count; ++index) {
273
56.8k
    TransferState& transfer = transfers[index];
274
56.8k
    if (!transfer.session.Initialize()) {
275
841
      continue;
276
841
    }
277
55.9k
    transfer.session.ApplyBaseline(scenario);
278
55.9k
    (void)curl_easy_setopt(transfer.session.easy(), CURLOPT_URL, url.c_str());
279
55.9k
    mock.Install(transfer.session.easy());
280
55.9k
    (void)ApplyScenarioOptions(transfer.session.easy(), scenario);
281
55.9k
    if (ApplyStateProbeOptions(transfer.session.easy(), plan.state_probe_profile(), progress_sink.get())) {
282
7.82k
      ++stats.state_probe_handles;
283
7.82k
    }
284
55.9k
    mock.ConfigureRequestData(transfer.session.InstallRequestData(scenario));
285
55.9k
    if (curl_multi_add_handle(multi.get(), transfer.session.easy()) == CURLM_OK) {
286
55.9k
      transfer.attached = true;
287
55.9k
      ++stats.added_handles;
288
55.9k
    }
289
55.9k
  }
290
291
18.1k
  if (stats.added_handles == 0) {
292
2
    multi.reset();
293
2
    return stats;
294
2
  }
295
296
18.1k
  MultiTransferDriver driver(multi.get(), transfers, transfer_count, stats);
297
18.1k
  ProbeLegacyMultiSocketApis(multi.get());
298
299
18.1k
  const std::size_t action_count = std::min<std::size_t>(plan.actions_size(), scenario_limits::kMaxMultiActions);
300
18.1k
  std::size_t next_action = 0;
301
18.1k
  bool initial_action_changed = false;
302
18.1k
  if (next_action < action_count) {
303
4.69k
    initial_action_changed = driver.ApplyAction(plan.actions(static_cast<int>(next_action++)));
304
4.69k
    ++stats.actions_consumed;
305
4.69k
  }
306
307
18.1k
  int running_handles = 0;
308
18.1k
  CURLMcode result = socket_driver_installed ? socket_driver.Start(&running_handles)
309
18.1k
                                             : curl_multi_perform(multi.get(), &running_handles);
310
18.1k
  bool completion_progress = driver.DrainCompletionMessages();
311
18.1k
  ProbeMultiWaitApis(multi.get());
312
18.1k
  if (plan.wake_multi()) {
313
1.34k
    if (socket_driver_installed) {
314
586
      socket_driver.ProbeControlApis();
315
757
    } else {
316
757
      (void)curl_multi_wakeup(multi.get());
317
757
    }
318
1.34k
  }
319
320
18.1k
  int idle_iterations = initial_action_changed || completion_progress ? 0 : 1;
321
247k
  for (int iteration = 0; result == CURLM_OK && iteration < kMaxDriveIterations; ++iteration) {
322
247k
    if (running_handles == 0 && next_action >= action_count) {
323
14.3k
      break;
324
14.3k
    }
325
326
233k
    bool made_progress = mock.ServiceConnections();
327
233k
    if (next_action < action_count) {
328
26.5k
      made_progress = driver.ApplyAction(plan.actions(static_cast<int>(next_action++))) || made_progress;
329
26.5k
      ++stats.actions_consumed;
330
      // Consuming an ordered no-op is still harness progress: continue to the
331
      // next action instead of letting an idle transport hide its suffix.
332
26.5k
      made_progress = true;
333
26.5k
    }
334
335
233k
    const int running_before = running_handles;
336
233k
    if (socket_driver_installed) {
337
174k
      const MultiSocketDriver::DriveResult drive = socket_driver.DriveReady(&running_handles);
338
174k
      result = drive.code;
339
174k
      made_progress = drive.made_progress || made_progress;
340
174k
    } else {
341
58.4k
      result = curl_multi_perform(multi.get(), &running_handles);
342
58.4k
      made_progress = running_handles != running_before || made_progress;
343
58.4k
    }
344
233k
    made_progress = driver.DrainCompletionMessages() || made_progress;
345
346
233k
    if (made_progress) {
347
204k
      idle_iterations = 0;
348
204k
    } else if (++idle_iterations >= kMaxIdleIterations) {
349
3.53k
      break;
350
3.53k
    }
351
233k
  }
352
353
18.1k
  (void)driver.DrainCompletionMessages();
354
18.1k
  stats.opened_connections = mock.opened_connection_count();
355
74.9k
  for (std::size_t index = 0; index < transfer_count; ++index) {
356
56.8k
    TransferState& transfer = transfers[index];
357
56.8k
    if (transfer.session.easy() == nullptr) {
358
837
      continue;
359
837
    }
360
55.9k
    (void)curl_easy_pause(transfer.session.easy(), CURLPAUSE_CONT);
361
55.9k
    if (transfer.attached) {
362
54.7k
      (void)curl_multi_remove_handle(multi.get(), transfer.session.easy());
363
54.7k
      transfer.attached = false;
364
54.7k
    }
365
55.9k
  }
366
367
  // Destroy the multi while both its socket callback storage and mock peer are
368
  // live, then detach request-data pointers before cleaning each easy handle.
369
18.1k
  multi.reset();
370
18.1k
  stats.watch_exhausted = socket_driver.watch_exhausted();
371
18.1k
  if (stats.watch_exhausted) {
372
0
    std::fputs("curl-fuzzer: socket watch capacity exhausted\n", stderr);
373
0
  }
374
74.9k
  for (std::size_t index = 0; index < transfer_count; ++index) {
375
56.8k
    transfers[index].session.Close();
376
56.8k
  }
377
18.1k
  return stats;
378
18.1k
}
379
380
}  // namespace proto_fuzzer