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