Coverage Report

Created: 2026-10-15 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl_fuzzer/proto_fuzzer/websocket_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 WebSocketMockServer.
9
10
#include "proto_fuzzer/websocket_mock_server.h"
11
12
#include <curl/websockets.h>
13
14
#include <algorithm>
15
#include <cstddef>
16
#include <cstdint>
17
#include <string>
18
#include <utility>
19
20
#include "proto_fuzzer/option_apply.h"
21
#include "proto_fuzzer/scenario_limits.h"
22
#include "proto_fuzzer/ws_accept_key.h"
23
#include "proto_fuzzer/ws_frame.h"
24
25
namespace proto_fuzzer {
26
27
namespace {
28
29
// Iteration caps for the post-handshake manual WS drive. Kept small because
30
// every iteration makes a curl_ws_recv / curl_ws_send call.
31
constexpr std::size_t kMaxWsRecvIterations = 128;
32
constexpr std::size_t kMaxWsSendIterations = 32;
33
34
/// Ordered list of flag combinations fed to curl_ws_send / curl_ws_start_frame
35
/// during the manual-drive tail. Sequencing matters: the TEXT|CONT entry puts
36
/// the encoder into `contfragment=true`, so subsequent CONT / TEXT|CONT /
37
/// BINARY|CONT entries then take the contfragment-aware branches in
38
/// ws_frame_flags2firstbyte that would otherwise be unreachable from the
39
/// fuzzer. A lone CURLWS_CONT runs first (contfragment=false → "No ongoing
40
/// fragmented message" failf), and a bare `0` directly after CURLWS_CONT
41
/// drives the "no flags given; interpreting as continuation" compatibility
42
/// path. (TEXT|BINARY), (CLOSE|CONT), (PING|CONT), (PONG|CONT) cover the
43
/// invalid-combination failf() branches; the trailing lone `0` reaches the
44
/// ordinary "no flags given" rejection with contfragment=false.
45
constexpr unsigned int kWsSendFlagMatrix[] = {
46
    CURLWS_CONT,
47
    CURLWS_TEXT,
48
    CURLWS_BINARY,
49
    CURLWS_TEXT | CURLWS_OFFSET,
50
    CURLWS_BINARY | CURLWS_OFFSET,
51
    CURLWS_TEXT | CURLWS_CONT,
52
    CURLWS_CONT,
53
    0,
54
    CURLWS_TEXT,
55
    CURLWS_BINARY | CURLWS_CONT,
56
    CURLWS_BINARY,
57
    CURLWS_PING,
58
    CURLWS_PONG,
59
    CURLWS_CLOSE,
60
    0,
61
    CURLWS_CLOSE | CURLWS_CONT,
62
    CURLWS_PING | CURLWS_CONT,
63
    CURLWS_PONG | CURLWS_CONT,
64
    CURLWS_TEXT | CURLWS_BINARY,
65
};
66
67
/// Find "Sec-WebSocket-Key:" in the request and return the trimmed value.
68
/// @param request The raw HTTP request bytes buffered from the client.
69
/// @return The header value, or an empty string if not found.
70
24.7k
std::string ExtractWebSocketKey(const std::string& request) {
71
24.7k
  static const char kHeader[] = "Sec-WebSocket-Key:";
72
24.7k
  std::size_t pos = request.find(kHeader);
73
24.7k
  if (pos == std::string::npos) {
74
20
    return {};
75
20
  }
76
24.7k
  pos += sizeof(kHeader) - 1;
77
50.8k
  while (pos < request.size() && (request[pos] == ' ' || request[pos] == '\t')) {
78
26.1k
    ++pos;
79
26.1k
  }
80
24.7k
  std::size_t end = request.find("\r\n", pos);
81
24.7k
  if (end == std::string::npos) {
82
6
    return {};
83
6
  }
84
25.8k
  while (end > pos && (request[end - 1] == ' ' || request[end - 1] == '\t')) {
85
1.18k
    --end;
86
1.18k
  }
87
24.6k
  return request.substr(pos, end - pos);
88
24.7k
}
89
90
/// SHA1(key + WS magic guid), base64-encoded — RFC 6455 §4.2.2.
91
/// Delegates to the standalone implementation in ws_accept_key.h so we don't
92
/// need OpenSSL.
93
24.6k
std::string ComputeWebSocketAccept(const std::string& key) { return proto_fuzzer::ComputeWebSocketAcceptKey(key); }
94
95
/// Build the ordered list of chunks to deliver once the 101 handshake has
96
/// completed. Mixes raw `on_readable` bytes (fuzzer-controlled) with serialised
97
/// `server_frames` (structured RFC 6455 frames from the proto) under a shared
98
/// shared response-chunk budget.
99
32.3k
std::vector<std::string> BuildFrameChunks(const curl::fuzzer::proto::Connection& conn) {
100
32.3k
  std::vector<std::string> chunks;
101
32.3k
  chunks.reserve(scenario_limits::kMaxResponseChunks);
102
32.3k
  const std::size_t raw_budget = std::min<std::size_t>(scenario_limits::kMaxResponseChunks, conn.on_readable_size());
103
41.8k
  for (std::size_t i = 0; i < raw_budget; ++i) {
104
9.51k
    chunks.emplace_back(conn.on_readable(i));
105
9.51k
  }
106
32.3k
  const std::size_t frame_budget = scenario_limits::kMaxResponseChunks - chunks.size();
107
32.3k
  const std::size_t frame_count = std::min<std::size_t>(frame_budget, conn.server_frames_size());
108
48.6k
  for (std::size_t i = 0; i < frame_count; ++i) {
109
16.3k
    chunks.emplace_back(SerializeWebSocketFrame(conn.server_frames(static_cast<int>(i))));
110
16.3k
  }
111
32.3k
  return chunks;
112
32.3k
}
113
114
/// WRITEFUNCTION / HEADERFUNCTION installed on the easy handle by
115
/// WebSocketMockServer::Install. Pokes curl_ws_meta on every invocation (so
116
/// the Curl_is_in_callback-guarded branch stays covered), and fires a
117
/// one-shot curl_ws_send probe to reach ws_send_raw_blocking — that target
118
/// is unreachable unless CURLWS_RAW_MODE is set AND the caller is inside a
119
/// callback. The probe is sized larger than typical backpressure recv
120
/// buffers so the partial-write / SOCKET_WRITABLE loop engages under a
121
/// tightened SO_RCVBUF. The one-shot gate keeps the per-scenario cost
122
/// bounded when SOCKET_WRITABLE times out. WRITEDATA is the owning
123
/// WebSocketMockServer so callback state lives on the server, not globals.
124
148k
size_t WebSocketWriteCallback(void* /*contents*/, size_t size, size_t nmemb, void* userdata) {
125
148k
  auto* server = static_cast<WebSocketMockServer*>(userdata);
126
148k
  if (server != nullptr) {
127
24.8k
    CURL* easy = server->easy_handle();
128
24.8k
    if (easy != nullptr) {
129
24.8k
      (void)curl_ws_meta(easy);
130
24.8k
      if (!server->ws_probe_fired()) {
131
1.83k
        server->MarkWsProbeFired();
132
1.83k
        static unsigned char kProbe[16384];
133
1.83k
        std::fill(kProbe, kProbe + sizeof(kProbe), 'P');
134
1.83k
        std::size_t sent = 0;
135
1.83k
        (void)curl_ws_send(easy, kProbe, sizeof(kProbe), &sent, 0, 0);
136
1.83k
      }
137
24.8k
    }
138
24.8k
  }
139
148k
  return size * nmemb;
140
148k
}
141
142
/// Drain curl_ws_recv in a tight loop until it returns CURLE_AGAIN / nothing
143
/// pending. Bounded; not expected to do anything on well-formed scenarios.
144
15.7k
std::size_t DrainWsRecv(CURL* easy) {
145
15.7k
  std::size_t total_received = 0;
146
98.6k
  for (std::size_t i = 0; i < kMaxWsRecvIterations; ++i) {
147
98.5k
    unsigned char buffer[4096];
148
98.5k
    std::size_t nread = 0;
149
98.5k
    const struct curl_ws_frame* meta = nullptr;
150
98.5k
    CURLcode rr = curl_ws_recv(easy, buffer, sizeof(buffer), &nread, &meta);
151
98.5k
    if (rr == CURLE_AGAIN) {
152
8.99k
      break;
153
8.99k
    }
154
89.5k
    if (rr != CURLE_OK && rr != CURLE_GOT_NOTHING) {
155
6.64k
      break;
156
6.64k
    }
157
82.8k
    if (nread == 0 && meta == nullptr) {
158
0
      break;
159
0
    }
160
82.8k
    total_received += nread;
161
82.8k
  }
162
15.7k
  return total_received;
163
15.7k
}
164
165
}  // namespace
166
167
/// Mirror the sequential CURLOPT_CONNECT_ONLY setopts applied by
168
/// ApplyScenarioOptions. Values above 2 are rejected by libcurl and therefore
169
/// cannot replace the last accepted setting. Use the same descriptor-aware
170
/// scalar decoder as ApplySetOption so compatibility inputs and cross-family
171
/// mutations cannot make curl and its mock disagree about manual delivery.
172
/// Restricting the scan to RuntimeOptionCount also prevents a compatibility-
173
/// only suffix from changing mock delivery after curl stops observing options.
174
/// @param scenario Structured input whose retained option prefix is inspected.
175
/// @return True when the final accepted CONNECT_ONLY value is 2.
176
32.3k
bool ScenarioRequestsManualWsDrive(const curl::fuzzer::proto::Scenario& scenario) {
177
32.3k
  bool manual_delivery = false;
178
32.3k
  const std::size_t option_count = RuntimeOptionCount(scenario);
179
147k
  for (std::size_t index = 0; index < option_count; ++index) {
180
114k
    const auto& option = scenario.options(static_cast<int>(index));
181
114k
    if (option.option_id() != curl::fuzzer::proto::CURLOPT_CONNECT_ONLY) {
182
109k
      continue;
183
109k
    }
184
4.96k
    const std::uint64_t value = DecodeIntegralOptionValue(option);
185
4.96k
    if (value <= 2) {
186
3.82k
      manual_delivery = value == 2;
187
3.82k
    }
188
4.96k
  }
189
32.3k
  return manual_delivery;
190
32.3k
}
191
192
/// Construct an idle WebSocketMockServer with no queued frames. Install()
193
/// on the base class and DriveScenario() configure it from a Scenario proto.
194
WebSocketMockServer::WebSocketMockServer()
195
32.5k
    : next_chunk_(0),
196
32.5k
      manual_delivery_(false),
197
32.5k
      handshake_sent_(false),
198
32.5k
      ws_probe_fired_(false),
199
32.5k
      easy_handle_(nullptr),
200
32.5k
      manual_received_bytes_(0) {}
201
202
/// Default destructor; the owned MockConnection (if any) cleans up its socketpair.
203
32.5k
WebSocketMockServer::~WebSocketMockServer() = default;
204
205
/// Install the shared socket trampolines via the base, then layer a
206
/// WebSocket-aware WRITEFUNCTION / HEADERFUNCTION on top. These call curl_ws_meta
207
/// inside the callback to reach its Curl_is_in_callback-guarded branch. WRITEDATA
208
/// points to this server so the callback can consult the easy handle and the
209
/// one-shot probe flag.
210
/// @param easy The curl easy handle to configure.
211
32.4k
void WebSocketMockServer::Install(CURL* easy) {
212
32.4k
  MockServerBase::Install(easy);
213
32.4k
  easy_handle_ = easy;
214
32.4k
  ws_probe_fired_ = false;
215
32.4k
  curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, &WebSocketWriteCallback);
216
32.4k
  curl_easy_setopt(easy, CURLOPT_WRITEDATA, this);
217
32.4k
  curl_easy_setopt(easy, CURLOPT_HEADERFUNCTION, &WebSocketWriteCallback);
218
32.4k
}
219
220
/// Return the one-shot probe gate. The write callback calls curl_ws_send once
221
/// per scenario to reach ws_send_raw_blocking; firing it per callback would wedge
222
/// each frame under backpressure. Public so the free-function callback can read
223
/// and flip it; reset by Install().
224
/// @return true once the one-shot WS probe has fired for this scenario.
225
24.8k
bool WebSocketMockServer::ws_probe_fired() const { return ws_probe_fired_; }
226
227
/// Flip the one-shot gate closed. Called from the write callback before it
228
/// invokes curl_ws_send, so subsequent callback entries skip the probe.
229
1.83k
void WebSocketMockServer::MarkWsProbeFired() { ws_probe_fired_ = true; }
230
231
/// @return the curl easy handle cached by Install() for the write callback.
232
24.8k
CURL* WebSocketMockServer::easy_handle() const { return easy_handle_; }
233
234
/// @return Application payload bytes returned by curl_ws_recv during the
235
/// latest manual-drive tail.
236
32.4k
std::size_t WebSocketMockServer::manual_received_bytes() const { return manual_received_bytes_; }
237
238
/// Queue RFC 6455 wire-byte chunks to emit once the handshake has completed.
239
/// Resets the next-chunk cursor.
240
/// @param frames Ordered list of chunk byte strings.
241
32.3k
void WebSocketMockServer::SetFrames(std::vector<std::string> frames) {
242
32.3k
  frames_ = std::move(frames);
243
32.3k
  next_chunk_ = 0;
244
32.3k
}
245
246
/// Toggle streaming (false, default) vs manual (true) chunk delivery.
247
/// @param manual Whether to suppress automatic chunk pushing by the
248
///        drive loop.
249
32.3k
void WebSocketMockServer::SetManualDelivery(bool manual) { manual_delivery_ = manual; }
250
251
/// @return true if chunks are caller-driven rather than drive-loop-driven.
252
650k
bool WebSocketMockServer::manual_delivery() const { return manual_delivery_; }
253
254
/// @return true once a 101 Switching Protocols response has been written.
255
1.85M
bool WebSocketMockServer::handshake_sent() const { return handshake_sent_; }
256
257
/// @return true if at least one frame chunk has not yet been sent.
258
587k
bool WebSocketMockServer::has_more_chunks() const { return next_chunk_ < frames_.size(); }
259
260
/// @return the number of queued chunks not yet consumed.
261
15.7k
std::size_t WebSocketMockServer::remaining_chunks() const {
262
15.7k
  return next_chunk_ >= frames_.size() ? 0 : frames_.size() - next_chunk_;
263
15.7k
}
264
265
/// Access a pending chunk without consuming it.
266
/// @param index Offset from the next-pending cursor.
267
/// @return reference to the chunk byte string.
268
13.1k
const std::string& WebSocketMockServer::PeekChunk(std::size_t index) const { return frames_[next_chunk_ + index]; }
269
270
/// Advance the pending-chunk cursor by one. No-op when no chunks remain.
271
13.1k
void WebSocketMockServer::ConsumeChunk() {
272
13.1k
  if (next_chunk_ < frames_.size()) {
273
13.1k
    ++next_chunk_;
274
13.1k
  }
275
13.1k
}
276
277
/// Construct the transport used for the WebSocket exchange. Secure WebSocket
278
/// peers override this factory while retaining the same Upgrade and frame
279
/// state machine.
280
/// @return a new plaintext socketpair connection.
281
16.7k
std::unique_ptr<MockConnection> WebSocketMockServer::CreateConnection() { return std::make_unique<MockConnection>(); }
282
283
/// Consume the plaintext Upgrade request without applying DrainIncoming's
284
/// backpressure limit. This preserves the historical WS and compatibility
285
/// behavior; layered transports override the hook to perform their decoding.
286
/// @return Number of request bytes appended during this call.
287
29.1k
std::size_t WebSocketMockServer::DrainHandshakeData() {
288
29.1k
  if (!connection_) {
289
0
    return 0;
290
0
  }
291
29.1k
  const std::size_t size_before = ws_request_buffer_.size();
292
29.1k
  connection_->ReadAvailable(&ws_request_buffer_);
293
29.1k
  return ws_request_buffer_.size() - size_before;
294
29.1k
}
295
296
/// Flush application writes when the carrier queues them. Plain socket writes
297
/// are synchronous, so the historical transport has nothing to do here.
298
27.5k
void WebSocketMockServer::FlushTransport() {}
299
300
/// Collect application bytes consumed by the active transport. Plaintext
301
/// connections report socket bytes directly; TLS connections report them only
302
/// after record decryption, keeping the WebSocket handshake transport-agnostic.
303
/// @param data First byte of one application-data fragment.
304
/// @param size Number of bytes available at `data`.
305
99.0k
void WebSocketMockServer::ObserveIncomingData(const unsigned char* data, std::size_t size) {
306
99.0k
  if (!handshake_sent_ && data != nullptr && size != 0) {
307
10.5k
    ws_request_buffer_.append(reinterpret_cast<const char*>(data), size);
308
10.5k
  }
309
99.0k
}
310
311
/// Called by the OPENSOCKETFUNCTION trampoline in the base class. Creates the
312
/// MockConnection but does NOT write anything — the handshake is driven later
313
/// by TryAdvanceHandshake().
314
/// @param purpose Socket role requested by curl; this peer accepts one outbound
315
///                WebSocket transport only.
316
/// @param address Intended destination retained by curl; the already-connected
317
///                socketpair leaves it unchanged.
318
/// @return the client-side fd to hand to libcurl, or CURL_SOCKET_BAD on
319
///         failure.
320
27.9k
curl_socket_t WebSocketMockServer::HandleOpenSocket(curlsocktype purpose, struct curl_sockaddr* address) {
321
27.9k
  (void)purpose;
322
27.9k
  (void)address;
323
27.9k
  if (connection_) {
324
0
    return CURL_SOCKET_BAD;
325
0
  }
326
27.9k
  connection_ = CreateConnection();
327
27.9k
  if (!connection_ || !connection_->ok()) {
328
0
    connection_.reset();
329
0
    return CURL_SOCKET_BAD;
330
0
  }
331
27.9k
  connection_->SetIncomingDataObserver(this);
332
27.9k
  ApplyPendingBackpressure();
333
  // Wait for curl's Upgrade request before we write anything — the drive
334
  // loop calls TryAdvanceHandshake() to drive that exchange.
335
27.9k
  return connection_->take_client_fd();
336
27.9k
}
337
338
/// Push raw bytes onto the server fd. Used by the manual-drive path to feed
339
/// frame bytes directly into curl without any mock-side framing.
340
/// @param data Buffer to send.
341
/// @param size Number of bytes in 'data'.
342
/// @return false on short or failed write.
343
12.5k
bool WebSocketMockServer::PushRawBytes(const unsigned char* data, std::size_t size) {
344
12.5k
  if (!connection_) {
345
0
    return false;
346
0
  }
347
12.5k
  connection_->DrainIncoming();
348
12.5k
  const bool written = connection_->WriteAll(data, size);
349
12.5k
  if (written) {
350
12.2k
    FlushTransport();
351
12.2k
  }
352
12.5k
  return written;
353
12.5k
}
354
355
/// Push the next queued frame when curl is ready. Used in streaming mode;
356
/// the drive loop calls this after the handshake has been sent. Shuts
357
/// the write side once the last chunk is delivered.
358
/// @return true when a chunk was consumed from the script.
359
9.84k
bool WebSocketMockServer::DeliverNextChunk() {
360
9.84k
  if (!connection_ || next_chunk_ >= frames_.size()) {
361
0
    return false;
362
0
  }
363
9.84k
  connection_->DrainIncoming();
364
9.84k
  const std::string& chunk = frames_[next_chunk_++];
365
9.84k
  if (!chunk.empty()) {
366
9.15k
    if (connection_->WriteAll(reinterpret_cast<const unsigned char*>(chunk.data()), chunk.size())) {
367
9.15k
      FlushTransport();
368
9.15k
    }
369
9.15k
  }
370
9.84k
  if (next_chunk_ >= frames_.size()) {
371
2.92k
    connection_->ShutdownWrite();
372
2.92k
  }
373
9.84k
  return true;
374
9.84k
}
375
376
/// Drive the WebSocket opening handshake: read whatever curl has written so
377
/// far, and once we've seen the end of the request headers, reply with a
378
/// valid 101 Switching Protocols.
379
/// @param made_progress Optional result set when transport or handshake state
380
///        advanced during this call.
381
/// @return true once the 101 response has been written (idempotent afterwards).
382
58.1k
bool WebSocketMockServer::TryAdvanceHandshake(bool* made_progress) {
383
58.1k
  if (made_progress != nullptr) {
384
58.1k
    *made_progress = false;
385
58.1k
  }
386
58.1k
  if (handshake_sent_ || !connection_) {
387
7.17k
    return handshake_sent_;
388
7.17k
  }
389
50.9k
  if (DrainHandshakeData() != 0 && made_progress != nullptr) {
390
36.9k
    *made_progress = true;
391
36.9k
  }
392
50.9k
  if (ws_request_buffer_.find("\r\n\r\n") == std::string::npos) {
393
26.2k
    return false;
394
26.2k
  }
395
24.7k
  std::string key = ExtractWebSocketKey(ws_request_buffer_);
396
  // Even if parsing failed, reply with *something* so curl doesn't wedge.
397
  // A bad Accept exercises curl's handshake-error path.
398
24.7k
  std::string accept = key.empty() ? std::string("AAAAAAAAAAAAAAAAAAAAAAAAAAA=") : ComputeWebSocketAccept(key);
399
24.7k
  std::string response =
400
24.7k
      "HTTP/1.1 101 Switching Protocols\r\n"
401
24.7k
      "Upgrade: websocket\r\n"
402
24.7k
      "Connection: Upgrade\r\n"
403
24.7k
      "Sec-WebSocket-Accept: " +
404
24.7k
      accept + "\r\n\r\n";
405
24.7k
  connection_->WriteAll(reinterpret_cast<const unsigned char*>(response.data()), response.size());
406
24.7k
  FlushTransport();
407
24.7k
  handshake_sent_ = true;
408
24.7k
  if (made_progress != nullptr) {
409
24.7k
    *made_progress = true;
410
24.7k
  }
411
24.7k
  return true;
412
50.9k
}
413
414
/// Seed the mock from the scenario, then run the perform loop. Drives the 101
415
/// handshake on every iteration; in streaming mode also pushes queued frame
416
/// chunks as curl becomes readable. In manual mode (CURLOPT_CONNECT_ONLY=2)
417
/// chunks are left alone during the loop — once the loop returns, this method
418
/// pushes them as raw bytes and exercises curl_ws_recv / curl_ws_send against
419
/// a small flag matrix.
420
/// @param multi    caller-owned multi; 'easy' is already added.
421
/// @param easy     the curl easy handle attached to this mock.
422
/// @param scenario source of the frame chunks and CONNECT_ONLY setting.
423
32.3k
void WebSocketMockServer::RunLoop(CURLM* multi, CURL* easy, const curl::fuzzer::proto::Scenario& scenario) {
424
32.3k
  SetManualDelivery(ScenarioRequestsManualWsDrive(scenario));
425
32.3k
  manual_received_bytes_ = 0;
426
  // initial_response is unused in WS mode; we synthesise the 101 dynamically
427
  // from curl's Upgrade request.
428
32.3k
  SetFrames(BuildFrameChunks(scenario.connection()));
429
430
32.3k
  int still_running = 1;
431
32.3k
  int idle_iterations = 0;
432
32.3k
  int drive_iterations = 0;
433
32.3k
  bool pollset_probed = false;
434
32.3k
  const bool timed_drive = UsesTimedDrive(scenario);
435
32.3k
  const int idle_limit = timed_drive ? kMaxTimedIdleIterations : kMaxIdleIterations;
436
32.3k
  CURLMcode rc = CURLM_OK;
437
438
650k
  while (still_running && idle_iterations < idle_limit && drive_iterations++ < kMaxDriveIterations) {
439
632k
    bool made_progress = false;
440
632k
    const int running_before = still_running;
441
632k
    rc = curl_multi_perform(multi, &still_running);
442
632k
    if (rc != CURLM_OK) {
443
0
      break;
444
0
    }
445
632k
    made_progress = still_running != running_before;
446
632k
    if (timed_drive && still_running && !pollset_probed) {
447
      // At this point curl has created the Upgrade connection but the mock has
448
      // not necessarily replied, which gives curl_multi_poll a meaningful WS
449
      // filter state without adding a timeout to fixed fast-lane inputs.
450
3.69k
      ProbeMultiPollset(multi);
451
3.69k
      pollset_probed = true;
452
3.69k
    }
453
    // Drive the 101 handshake on every iteration; no-op once sent.
454
632k
    if (!handshake_sent()) {
455
58.1k
      bool handshake_progress = false;
456
58.1k
      (void)TryAdvanceHandshake(&handshake_progress);
457
58.1k
      made_progress = handshake_progress || made_progress;
458
58.1k
    }
459
632k
    if (!still_running) {
460
14.9k
      break;
461
14.9k
    }
462
463
    // Only push frame chunks in streaming mode — in manual mode the caller
464
    // will push them below after the handshake.
465
617k
    if (!manual_delivery() && handshake_sent() && has_more_chunks()) {
466
9.84k
      made_progress = DeliverNextChunk() || made_progress;
467
607k
    } else if (handshake_sent() && connection() != nullptr) {
468
      // Uploading WS scenarios can have no server frames at all. Drain their
469
      // encoded client data here so they make deterministic progress and do
470
      // not have to wait for CURLOPT_TIMEOUT_MS just to exercise cr_ws_read.
471
581k
      made_progress = connection()->DrainIncoming() != 0 || made_progress;
472
581k
    }
473
474
617k
    if (made_progress) {
475
80.7k
      idle_iterations = 0;
476
80.7k
      continue;
477
80.7k
    }
478
479
537k
    if (timed_drive) {
480
398k
      (void)WaitOnMultiFdset(multi, &rc);
481
398k
      if (rc != CURLM_OK) {
482
0
        break;
483
0
      }
484
398k
    }
485
537k
    ++idle_iterations;
486
537k
  }
487
488
32.3k
  if (!manual_delivery() || !handshake_sent()) {
489
29.6k
    return;
490
29.6k
  }
491
492
  // Manual-drive tail: feed every remaining scripted chunk straight onto the
493
  // server fd as raw frame bytes, draining curl_ws_recv between each push.
494
15.7k
  while (remaining_chunks() > 0) {
495
13.1k
    const std::string& chunk = PeekChunk(0);
496
13.1k
    if (!chunk.empty()) {
497
12.5k
      PushRawBytes(reinterpret_cast<const unsigned char*>(chunk.data()), chunk.size());
498
12.5k
    }
499
13.1k
    ConsumeChunk();
500
13.1k
    manual_received_bytes_ += DrainWsRecv(easy);
501
13.1k
  }
502
  // Final drain in case frame parsing produced more work after the last push.
503
2.64k
  manual_received_bytes_ += DrainWsRecv(easy);
504
505
2.64k
  const auto& probes = scenario.connection().manual_probes();
506
2.64k
  static const unsigned char kPayload[] = "hello-from-proto-fuzzer";
507
2.64k
  const std::size_t payload_len = sizeof(kPayload) - 1;
508
509
2.64k
  if (probes.flag_matrix()) {
510
    // Exercise curl_ws_send with a fixed matrix of flags. We don't care whether
511
    // the send actually lands on the wire — the point is to reach the encode
512
    // paths in ws_enc_add_frame / ws_enc_write_head.
513
823
    std::size_t iteration = 0;
514
15.6k
    for (unsigned int flags : kWsSendFlagMatrix) {
515
15.6k
      if (iteration++ >= kMaxWsSendIterations) {
516
0
        break;
517
0
      }
518
      // Announce the frame via the public curl_ws_start_frame entrypoint before
519
      // the actual send. In non-raw mode this writes the frame head into the
520
      // sendbuf; the follow-up curl_ws_send with the same flags finishes the
521
      // exchange or fails cleanly on invalid flag combos.
522
15.6k
      (void)curl_ws_start_frame(easy, flags, static_cast<curl_off_t>(payload_len));
523
15.6k
      std::size_t sent = 0;
524
15.6k
      curl_off_t fragsize = (flags & CURLWS_OFFSET) ? static_cast<curl_off_t>(payload_len) : 0;
525
15.6k
      (void)curl_ws_send(easy, kPayload, payload_len, &sent, fragsize, flags);
526
15.6k
      if (connection() != nullptr) {
527
15.6k
        connection()->DrainIncoming();
528
15.6k
      }
529
15.6k
    }
530
823
  }
531
532
2.64k
  if (probes.unaligned_send()) {
533
    // Multi-call mis-sized send probe: declare a fragsize=200 frame, send 23
534
    // bytes, then call curl_ws_send again with a buflen much bigger than the
535
    // remaining payload. Hits the "unaligned frame size" failf in ws_enc_send.
536
532
    constexpr curl_off_t kBigFrag = 200;
537
532
    (void)curl_ws_start_frame(easy, CURLWS_TEXT | CURLWS_OFFSET, kBigFrag);
538
532
    std::size_t sent = 0;
539
532
    (void)curl_ws_send(easy, kPayload, payload_len, &sent, kBigFrag, CURLWS_TEXT | CURLWS_OFFSET);
540
    // Now enc.payload_remain ≈ kBigFrag - payload_len. A follow-up send with
541
    // buflen > remaining trips the guard at ws_enc_send:~1050.
542
532
    std::size_t sent2 = 0;
543
532
    constexpr std::size_t kOverrun = 500;
544
532
    unsigned char overrun[kOverrun];
545
532
    std::fill(overrun, overrun + kOverrun, 'X');
546
532
    (void)curl_ws_send(easy, overrun, kOverrun, &sent2, kBigFrag, CURLWS_TEXT | CURLWS_OFFSET);
547
532
    if (connection() != nullptr) {
548
532
      connection()->DrainIncoming();
549
532
    }
550
532
  }
551
552
2.64k
  if (probes.raw_send()) {
553
    // Raw-mode send path: reachable only when CURLOPT_WS_OPTIONS has
554
    // CURLWS_RAW_MODE set. curl_ws_send with flags=0, fragsize=0 takes the
555
    // data->set.ws_raw_mode branch → ws_send_raw. No-op for non-raw scenarios
556
    // (hits the "no flags given" failure path instead).
557
324
    std::size_t sent = 0;
558
324
    (void)curl_ws_send(easy, kPayload, payload_len, &sent, 0, 0);
559
324
    if (connection() != nullptr) {
560
324
      connection()->DrainIncoming();
561
324
    }
562
324
  }
563
2.64k
}
564
565
}  // namespace proto_fuzzer