Coverage Report

Created: 2026-12-01 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl_fuzzer/proto_fuzzer/multi_socket_driver.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 curl_multi_socket_action driver.
9
10
#include "proto_fuzzer/multi_socket_driver.h"
11
12
#include <poll.h>
13
14
#include <array>
15
#include <cstddef>
16
#include <cstdint>
17
18
namespace proto_fuzzer {
19
20
namespace {
21
22
/// Translate libcurl's read/write interest into poll(2) events.
23
427k
short PollEventsForInterest(int interest) {
24
427k
  short events = 0;
25
427k
  if ((interest & CURL_POLL_IN) != 0) {
26
417k
    events |= POLLIN;
27
417k
  }
28
427k
  if ((interest & CURL_POLL_OUT) != 0) {
29
121k
    events |= POLLOUT;
30
121k
  }
31
427k
  return events;
32
427k
}
33
34
/// Translate an observed poll result into curl_multi_socket_action flags.
35
289k
int CurlEventsForPollResult(short events) {
36
289k
  int result = 0;
37
289k
  if ((events & (POLLIN | POLLHUP)) != 0) {
38
    // A stream hangup remains readable until curl consumes EOF.
39
35.2k
    result |= CURL_CSELECT_IN;
40
35.2k
  }
41
289k
  if ((events & POLLOUT) != 0) {
42
109k
    result |= CURL_CSELECT_OUT;
43
109k
  }
44
289k
  if ((events & (POLLERR | POLLHUP | POLLNVAL)) != 0) {
45
0
    result |= CURL_CSELECT_ERR;
46
0
  }
47
289k
  return result;
48
289k
}
49
50
}  // namespace
51
52
/// Construct detached callback state. Install() supplies the multi only after
53
/// all watch storage has reached its final address.
54
MultiSocketDriver::MultiSocketDriver()
55
429k
    : multi_(nullptr), timeout_ms_(-1), timer_pending_(false), watch_exhausted_(false), generation_(0) {}
56
57
/// The owner deliberately destroys this after curl_multi_cleanup, so there is
58
/// no callback deregistration or libcurl access left for the destructor.
59
429k
MultiSocketDriver::~MultiSocketDriver() = default;
60
61
/// Install socket/timer callbacks on a caller-owned multi before adding an
62
/// easy handle. curl may announce a timer during curl_multi_add_handle, so
63
/// installing later would miss the event that starts an otherwise idle
64
/// socket-action application.
65
/// @param multi Multi handle that outlives this driver.
66
/// @return true when every callback option was accepted.
67
4.72k
bool MultiSocketDriver::Install(CURLM* multi) {
68
4.72k
  multi_ = multi;
69
4.72k
  if (multi_ == nullptr) {
70
0
    return false;
71
0
  }
72
4.72k
  return curl_multi_setopt(multi_, CURLMOPT_SOCKETFUNCTION, &MultiSocketDriver::SocketCallback) == CURLM_OK &&
73
4.72k
         curl_multi_setopt(multi_, CURLMOPT_SOCKETDATA, this) == CURLM_OK &&
74
4.72k
         curl_multi_setopt(multi_, CURLMOPT_TIMERFUNCTION, &MultiSocketDriver::TimerCallback) == CURLM_OK &&
75
4.72k
         curl_multi_setopt(multi_, CURLMOPT_TIMERDATA, this) == CURLM_OK;
76
4.72k
}
77
78
/// Start libcurl's socket state machine through the documented timeout
79
/// pseudo-socket without waiting for a real timer. This creates the first
80
/// socket and gives the callback its initial watch without a wall-clock
81
/// dependency.
82
/// @param running_handles Receives the number of unfinished transfers.
83
/// @return Result from curl_multi_socket_action.
84
4.72k
CURLMcode MultiSocketDriver::Start(int* running_handles) {
85
4.72k
  if (multi_ == nullptr) {
86
0
    return CURLM_BAD_HANDLE;
87
0
  }
88
4.72k
  timer_pending_ = false;
89
4.72k
  return curl_multi_socket_action(multi_, CURL_SOCKET_TIMEOUT, 0, running_handles);
90
4.72k
}
91
92
/// Run one bounded, non-blocking event-loop turn: poll the callback-provided
93
/// watch set with a zero timeout and report readiness back to libcurl.
94
/// The snapshot is intentional: a socket action may synchronously remove
95
/// the current watch or install another one, so the callback-owned table
96
/// must not be iterated as a live container across that call. Service a
97
/// deferred zero timer after socket callbacks, never recursively from the
98
/// timer callback.
99
/// @param running_handles In/out unfinished-transfer count.
100
/// @return Result code and whether observable driver state advanced.
101
219k
MultiSocketDriver::DriveResult MultiSocketDriver::DriveReady(int* running_handles) {
102
219k
  DriveResult result;
103
219k
  if (multi_ == nullptr) {
104
0
    result.code = CURLM_BAD_HANDLE;
105
0
    return result;
106
0
  }
107
108
219k
  std::array<struct pollfd, kMaxWatches> poll_fds{};
109
219k
  std::size_t poll_count = 0;
110
3.51M
  for (const Watch& watch : watches_) {
111
3.51M
    if (!watch.active) {
112
3.08M
      continue;
113
3.08M
    }
114
427k
    poll_fds[poll_count].fd = watch.socket;
115
427k
    poll_fds[poll_count].events = PollEventsForInterest(watch.interest);
116
427k
    ++poll_count;
117
427k
  }
118
119
219k
  const std::uint64_t generation_before = generation_;
120
219k
  const int running_before = running_handles == nullptr ? 0 : *running_handles;
121
219k
  bool action_dispatched = false;
122
219k
  if (poll_count != 0 && ::poll(poll_fds.data(), static_cast<nfds_t>(poll_count), 0) > 0) {
123
289k
    for (std::size_t index = 0; index < poll_count; ++index) {
124
289k
      if (running_handles != nullptr && *running_handles == 0) {
125
88
        break;
126
88
      }
127
      // An earlier action can synchronously remove or repurpose any later fd
128
      // in the snapshot. Revalidate it against the callback-owned table so a
129
      // stale readiness notification never reaches curl under a new meaning.
130
289k
      Watch* current = FindWatch(poll_fds[index].fd);
131
289k
      if (current == nullptr) {
132
0
        continue;
133
0
      }
134
289k
      const int events = CurlEventsForPollResult(poll_fds[index].revents);
135
289k
      if (events == 0) {
136
148k
        continue;
137
148k
      }
138
141k
      result.code = curl_multi_socket_action(multi_, poll_fds[index].fd, events, running_handles);
139
141k
      action_dispatched = true;
140
      // Process at most one snapshot entry. Its callbacks can repurpose an fd
141
      // with the same numeric value and interest, which no post-hoc lookup can
142
      // distinguish; the outer loop rebuilds readiness from fresh watches.
143
141k
      break;
144
289k
    }
145
141k
  }
146
147
219k
  long remaining_ms = -1;
148
219k
  if (result.code == CURLM_OK && timer_pending_ && timeout_ms_ > 0) {
149
207k
    (void)curl_multi_timeout(multi_, &remaining_ms);
150
207k
  }
151
219k
  if (result.code == CURLM_OK && timer_pending_ && (timeout_ms_ == 0 || (timeout_ms_ > 0 && remaining_ms == 0))) {
152
    // Clear first: the action may synchronously install another zero timer,
153
    // which belongs to the next outer loop turn rather than recursive work.
154
41.2k
    timer_pending_ = false;
155
41.2k
    result.code = curl_multi_socket_action(multi_, CURL_SOCKET_TIMEOUT, 0, running_handles);
156
41.2k
    action_dispatched = true;
157
41.2k
  }
158
159
219k
  const int running_after = running_handles == nullptr ? 0 : *running_handles;
160
  // A successful action can consume buffered protocol bytes without changing
161
  // either callbacks or handle count, so dispatch itself is observable
162
  // progress. The outer fixed operation cap still bounds permanently-ready
163
  // sockets.
164
219k
  result.made_progress = action_dispatched || generation_ != generation_before || running_after != running_before;
165
219k
  return result;
166
219k
}
167
168
/// Exercise the wakeup and timeout-query APIs from a valid live-multi state.
169
/// A zero-timeout query is informational; wakeup is also non-blocking when
170
/// no other thread is in a poll call, which is the deterministic behavior
171
/// this lane needs. Neither call waits or changes the operation budget.
172
172
void MultiSocketDriver::ProbeControlApis() {
173
172
  if (multi_ == nullptr) {
174
0
    return;
175
0
  }
176
172
  long timeout_ms = -1;
177
172
  (void)curl_multi_timeout(multi_, &timeout_ms);
178
172
  (void)curl_multi_wakeup(multi_);
179
172
}
180
181
/// Trampoline registered as CURLMOPT_SOCKETFUNCTION. Route the C callback
182
/// into state whose lifetime is owned by DriveScenario.
183
int MultiSocketDriver::SocketCallback(CURL* /*easy*/, curl_socket_t socket, int what, void* user_data,
184
25.8k
                                      void* socket_data) {
185
25.8k
  return static_cast<MultiSocketDriver*>(user_data)->UpdateSocket(socket, what, socket_data);
186
25.8k
}
187
188
/// Trampoline registered as CURLMOPT_TIMERFUNCTION. Record work for deferred
189
/// processing only: invoking curl_multi_socket_action here, including for
190
/// a zero timer, would recursively re-enter libcurl's callback API.
191
78.2k
int MultiSocketDriver::TimerCallback(CURLM* /*multi*/, long timeout_ms, void* user_data) {
192
78.2k
  return static_cast<MultiSocketDriver*>(user_data)->UpdateTimer(timeout_ms);
193
78.2k
}
194
195
/// Apply one socket callback transition to the fixed watch table, maintaining
196
/// a stable association for every observed fd. `socket_data` is used only as
197
/// a consistency hint: libcurl owns it and may legitimately pass null for
198
/// the first notification, while our fd lookup remains authoritative.
199
25.8k
int MultiSocketDriver::UpdateSocket(curl_socket_t socket, int what, void* socket_data) {
200
25.8k
  Watch* watch = FindWatch(socket);
201
25.8k
  if (what == CURL_POLL_REMOVE) {
202
12.2k
    if (watch != nullptr) {
203
12.2k
      (void)curl_multi_assign(multi_, socket, nullptr);
204
12.2k
      watch->active = false;
205
12.2k
      watch->socket = CURL_SOCKET_BAD;
206
12.2k
      watch->interest = CURL_POLL_NONE;
207
12.2k
      ++generation_;
208
12.2k
    }
209
12.2k
    return 0;
210
12.2k
  }
211
212
13.5k
  if (watch == nullptr) {
213
12.2k
    watch = FindFreeWatch();
214
12.2k
    if (watch == nullptr) {
215
0
      watch_exhausted_ = true;
216
0
      return -1;
217
0
    }
218
12.2k
    watch->socket = socket;
219
12.2k
    watch->active = true;
220
12.2k
    (void)curl_multi_assign(multi_, socket, watch);
221
12.2k
    ++generation_;
222
12.2k
  } else if (socket_data != nullptr && socket_data != watch) {
223
    // Reassert the stable association if an unusual transition supplied a
224
    // different application pointer. Never dereference foreign socket_data.
225
0
    (void)curl_multi_assign(multi_, socket, watch);
226
0
  }
227
228
13.5k
  if (watch->interest != what) {
229
13.5k
    watch->interest = what;
230
13.5k
    ++generation_;
231
13.5k
  }
232
13.5k
  return 0;
233
13.5k
}
234
235
/// Record libcurl's latest timer request for deferred processing. Only
236
/// meaningful timer transitions count as progress: repeated identical
237
/// callbacks could otherwise consume the full operation budget instead
238
/// of the much smaller idle budget.
239
78.2k
int MultiSocketDriver::UpdateTimer(long timeout_ms) {
240
78.2k
  if (!timer_pending_ || timeout_ms_ != timeout_ms) {
241
61.8k
    ++generation_;
242
61.8k
  }
243
78.2k
  timeout_ms_ = timeout_ms;
244
78.2k
  timer_pending_ = timeout_ms >= 0;
245
78.2k
  return 0;
246
78.2k
}
247
248
/// Find an active watch by fd without allocating or depending on fd
249
/// magnitude; socket descriptors are not safe array indexes.
250
315k
MultiSocketDriver::Watch* MultiSocketDriver::FindWatch(curl_socket_t socket) {
251
699k
  for (Watch& watch : watches_) {
252
699k
    if (watch.active && watch.socket == socket) {
253
303k
      return &watch;
254
303k
    }
255
699k
  }
256
12.2k
  return nullptr;
257
315k
}
258
259
/// Find the first inactive stable slot for a newly observed fd. The caller
260
/// reports exhaustion as a socket-callback error rather than losing readiness
261
/// notifications and silently consuming the idle budget.
262
12.2k
MultiSocketDriver::Watch* MultiSocketDriver::FindFreeWatch() {
263
20.1k
  for (Watch& watch : watches_) {
264
20.1k
    if (!watch.active) {
265
12.2k
      return &watch;
266
12.2k
    }
267
20.1k
  }
268
0
  return nullptr;
269
12.2k
}
270
271
}  // namespace proto_fuzzer