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_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
491k
short PollEventsForInterest(int interest) {
24
491k
  short events = 0;
25
491k
  if ((interest & CURL_POLL_IN) != 0) {
26
470k
    events |= POLLIN;
27
470k
  }
28
491k
  if ((interest & CURL_POLL_OUT) != 0) {
29
163k
    events |= POLLOUT;
30
163k
  }
31
491k
  return events;
32
491k
}
33
34
/// Translate an observed poll result into curl_multi_socket_action flags.
35
363k
int CurlEventsForPollResult(short events) {
36
363k
  int result = 0;
37
363k
  if ((events & (POLLIN | POLLHUP)) != 0) {
38
    // A stream hangup remains readable until curl consumes EOF.
39
36.4k
    result |= CURL_CSELECT_IN;
40
36.4k
  }
41
363k
  if ((events & POLLOUT) != 0) {
42
144k
    result |= CURL_CSELECT_OUT;
43
144k
  }
44
363k
  if ((events & (POLLERR | POLLHUP | POLLNVAL)) != 0) {
45
0
    result |= CURL_CSELECT_ERR;
46
0
  }
47
363k
  return result;
48
363k
}
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
321k
    : 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
321k
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
6.62k
bool MultiSocketDriver::Install(CURLM* multi) {
68
6.62k
  multi_ = multi;
69
6.62k
  if (multi_ == nullptr) {
70
0
    return false;
71
0
  }
72
6.62k
  return curl_multi_setopt(multi_, CURLMOPT_SOCKETFUNCTION, &MultiSocketDriver::SocketCallback) == CURLM_OK &&
73
6.62k
         curl_multi_setopt(multi_, CURLMOPT_SOCKETDATA, this) == CURLM_OK &&
74
6.62k
         curl_multi_setopt(multi_, CURLMOPT_TIMERFUNCTION, &MultiSocketDriver::TimerCallback) == CURLM_OK &&
75
6.62k
         curl_multi_setopt(multi_, CURLMOPT_TIMERDATA, this) == CURLM_OK;
76
6.62k
}
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
6.62k
CURLMcode MultiSocketDriver::Start(int* running_handles) {
85
6.62k
  if (multi_ == nullptr) {
86
0
    return CURLM_BAD_HANDLE;
87
0
  }
88
6.62k
  timer_pending_ = false;
89
6.62k
  return curl_multi_socket_action(multi_, CURL_SOCKET_TIMEOUT, 0, running_handles);
90
6.62k
}
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
235k
MultiSocketDriver::DriveResult MultiSocketDriver::DriveReady(int* running_handles) {
102
235k
  DriveResult result;
103
235k
  if (multi_ == nullptr) {
104
0
    result.code = CURLM_BAD_HANDLE;
105
0
    return result;
106
0
  }
107
108
235k
  std::array<struct pollfd, kMaxWatches> poll_fds{};
109
235k
  std::size_t poll_count = 0;
110
3.76M
  for (const Watch& watch : watches_) {
111
3.76M
    if (!watch.active) {
112
3.27M
      continue;
113
3.27M
    }
114
491k
    poll_fds[poll_count].fd = watch.socket;
115
491k
    poll_fds[poll_count].events = PollEventsForInterest(watch.interest);
116
491k
    ++poll_count;
117
491k
  }
118
119
235k
  const std::uint64_t generation_before = generation_;
120
235k
  const int running_before = running_handles == nullptr ? 0 : *running_handles;
121
235k
  bool action_dispatched = false;
122
235k
  if (poll_count != 0 && ::poll(poll_fds.data(), static_cast<nfds_t>(poll_count), 0) > 0) {
123
363k
    for (std::size_t index = 0; index < poll_count; ++index) {
124
363k
      if (running_handles != nullptr && *running_handles == 0) {
125
245
        break;
126
245
      }
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
363k
      Watch* current = FindWatch(poll_fds[index].fd);
131
363k
      if (current == nullptr) {
132
0
        continue;
133
0
      }
134
363k
      const int events = CurlEventsForPollResult(poll_fds[index].revents);
135
363k
      if (events == 0) {
136
188k
        continue;
137
188k
      }
138
175k
      result.code = curl_multi_socket_action(multi_, poll_fds[index].fd, events, running_handles);
139
175k
      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
175k
      break;
144
363k
    }
145
175k
  }
146
147
235k
  if (result.code == CURLM_OK && timer_pending_ && timeout_ms_ == 0) {
148
    // Clear first: the action may synchronously install another zero timer,
149
    // which belongs to the next outer loop turn rather than recursive work.
150
4.62k
    timer_pending_ = false;
151
4.62k
    result.code = curl_multi_socket_action(multi_, CURL_SOCKET_TIMEOUT, 0, running_handles);
152
4.62k
    action_dispatched = true;
153
4.62k
  }
154
155
235k
  const int running_after = running_handles == nullptr ? 0 : *running_handles;
156
  // A successful action can consume buffered protocol bytes without changing
157
  // either callbacks or handle count, so dispatch itself is observable
158
  // progress. The outer fixed operation cap still bounds permanently-ready
159
  // sockets.
160
235k
  result.made_progress = action_dispatched || generation_ != generation_before || running_after != running_before;
161
235k
  return result;
162
235k
}
163
164
/// Exercise the wakeup and timeout-query APIs from a valid live-multi state.
165
/// A zero-timeout query is informational; wakeup is also non-blocking when
166
/// no other thread is in a poll call, which is the deterministic behavior
167
/// this lane needs. Neither call waits or changes the operation budget.
168
699
void MultiSocketDriver::ProbeControlApis() {
169
699
  if (multi_ == nullptr) {
170
0
    return;
171
0
  }
172
699
  long timeout_ms = -1;
173
699
  (void)curl_multi_timeout(multi_, &timeout_ms);
174
699
  (void)curl_multi_wakeup(multi_);
175
699
}
176
177
/// Trampoline registered as CURLMOPT_SOCKETFUNCTION. Route the C callback
178
/// into state whose lifetime is owned by DriveScenario.
179
int MultiSocketDriver::SocketCallback(CURL* /*easy*/, curl_socket_t socket, int what, void* user_data,
180
38.9k
                                      void* socket_data) {
181
38.9k
  return static_cast<MultiSocketDriver*>(user_data)->UpdateSocket(socket, what, socket_data);
182
38.9k
}
183
184
/// Trampoline registered as CURLMOPT_TIMERFUNCTION. Record work for deferred
185
/// processing only: invoking curl_multi_socket_action here, including for
186
/// a zero timer, would recursively re-enter libcurl's callback API.
187
56.8k
int MultiSocketDriver::TimerCallback(CURLM* /*multi*/, long timeout_ms, void* user_data) {
188
56.8k
  return static_cast<MultiSocketDriver*>(user_data)->UpdateTimer(timeout_ms);
189
56.8k
}
190
191
/// Apply one socket callback transition to the fixed watch table, maintaining
192
/// a stable association for every observed fd. `socket_data` is used only as
193
/// a consistency hint: libcurl owns it and may legitimately pass null for
194
/// the first notification, while our fd lookup remains authoritative.
195
38.9k
int MultiSocketDriver::UpdateSocket(curl_socket_t socket, int what, void* socket_data) {
196
38.9k
  Watch* watch = FindWatch(socket);
197
38.9k
  if (what == CURL_POLL_REMOVE) {
198
18.7k
    if (watch != nullptr) {
199
18.7k
      (void)curl_multi_assign(multi_, socket, nullptr);
200
18.7k
      watch->active = false;
201
18.7k
      watch->socket = CURL_SOCKET_BAD;
202
18.7k
      watch->interest = CURL_POLL_NONE;
203
18.7k
      ++generation_;
204
18.7k
    }
205
18.7k
    return 0;
206
18.7k
  }
207
208
20.1k
  if (watch == nullptr) {
209
18.7k
    watch = FindFreeWatch();
210
18.7k
    if (watch == nullptr) {
211
0
      watch_exhausted_ = true;
212
0
      return -1;
213
0
    }
214
18.7k
    watch->socket = socket;
215
18.7k
    watch->active = true;
216
18.7k
    (void)curl_multi_assign(multi_, socket, watch);
217
18.7k
    ++generation_;
218
18.7k
  } else if (socket_data != nullptr && socket_data != watch) {
219
    // Reassert the stable association if an unusual transition supplied a
220
    // different application pointer. Never dereference foreign socket_data.
221
0
    (void)curl_multi_assign(multi_, socket, watch);
222
0
  }
223
224
20.1k
  if (watch->interest != what) {
225
20.1k
    watch->interest = what;
226
20.1k
    ++generation_;
227
20.1k
  }
228
20.1k
  return 0;
229
20.1k
}
230
231
/// Record libcurl's latest timer request for deferred processing. Only
232
/// meaningful timer transitions count as progress: repeated identical
233
/// callbacks could otherwise consume the full operation budget instead
234
/// of the much smaller idle budget.
235
56.8k
int MultiSocketDriver::UpdateTimer(long timeout_ms) {
236
56.8k
  if (!timer_pending_ || timeout_ms_ != timeout_ms) {
237
37.4k
    ++generation_;
238
37.4k
  }
239
56.8k
  timeout_ms_ = timeout_ms;
240
56.8k
  timer_pending_ = timeout_ms >= 0;
241
56.8k
  return 0;
242
56.8k
}
243
244
/// Find an active watch by fd without allocating or depending on fd
245
/// magnitude; socket descriptors are not safe array indexes.
246
402k
MultiSocketDriver::Watch* MultiSocketDriver::FindWatch(curl_socket_t socket) {
247
927k
  for (Watch& watch : watches_) {
248
927k
    if (watch.active && watch.socket == socket) {
249
383k
      return &watch;
250
383k
    }
251
927k
  }
252
18.7k
  return nullptr;
253
402k
}
254
255
/// Find the first inactive stable slot for a newly observed fd. The caller
256
/// reports exhaustion as a socket-callback error rather than losing readiness
257
/// notifications and silently consuming the idle budget.
258
18.7k
MultiSocketDriver::Watch* MultiSocketDriver::FindFreeWatch() {
259
30.4k
  for (Watch& watch : watches_) {
260
30.4k
    if (!watch.active) {
261
18.7k
      return &watch;
262
18.7k
    }
263
30.4k
  }
264
0
  return nullptr;
265
18.7k
}
266
267
}  // namespace proto_fuzzer