Coverage Report

Created: 2026-09-14 07:12

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
14.6k
std::string ExtractWebSocketKey(const std::string& request) {
71
14.6k
  static const char kHeader[] = "Sec-WebSocket-Key:";
72
14.6k
  std::size_t pos = request.find(kHeader);
73
14.6k
  if (pos == std::string::npos) {
74
12
    return {};
75
12
  }
76
14.6k
  pos += sizeof(kHeader) - 1;
77
30.3k
  while (pos < request.size() && (request[pos] == ' ' || request[pos] == '\t')) {
78
15.6k
    ++pos;
79
15.6k
  }
80
14.6k
  std::size_t end = request.find("\r\n", pos);
81
14.6k
  if (end == std::string::npos) {
82
8
    return {};
83
8
  }
84
15.7k
  while (end > pos && (request[end - 1] == ' ' || request[end - 1] == '\t')) {
85
1.05k
    --end;
86
1.05k
  }
87
14.6k
  return request.substr(pos, end - pos);
88
14.6k
}
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
14.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
29.8k
std::vector<std::string> BuildFrameChunks(const curl::fuzzer::proto::Connection& conn) {
100
29.8k
  std::vector<std::string> chunks;
101
29.8k
  chunks.reserve(scenario_limits::kMaxResponseChunks);
102
29.8k
  const std::size_t raw_budget = std::min<std::size_t>(scenario_limits::kMaxResponseChunks, conn.on_readable_size());
103
37.4k
  for (std::size_t i = 0; i < raw_budget; ++i) {
104
7.58k
    chunks.emplace_back(conn.on_readable(i));
105
7.58k
  }
106
29.8k
  const std::size_t frame_budget = scenario_limits::kMaxResponseChunks - chunks.size();
107
29.8k
  const std::size_t frame_count = std::min<std::size_t>(frame_budget, conn.server_frames_size());
108
40.8k
  for (std::size_t i = 0; i < frame_count; ++i) {
109
10.9k
    chunks.emplace_back(SerializeWebSocketFrame(conn.server_frames(static_cast<int>(i))));
110
10.9k
  }
111
29.8k
  return chunks;
112
29.8k
}
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
94.5k
size_t WebSocketWriteCallback(void* /*contents*/, size_t size, size_t nmemb, void* userdata) {
125
94.5k
  auto* server = static_cast<WebSocketMockServer*>(userdata);
126
94.5k
  if (server != nullptr) {
127
21.2k
    CURL* easy = server->easy_handle();
128
21.2k
    if (easy != nullptr) {
129
21.2k
      (void)curl_ws_meta(easy);
130
21.2k
      if (!server->ws_probe_fired()) {
131
1.45k
        server->MarkWsProbeFired();
132
1.45k
        static unsigned char kProbe[16384];
133
1.45k
        std::fill(kProbe, kProbe + sizeof(kProbe), 'P');
134
1.45k
        std::size_t sent = 0;
135
1.45k
        (void)curl_ws_send(easy, kProbe, sizeof(kProbe), &sent, 0, 0);
136
1.45k
      }
137
21.2k
    }
138
21.2k
  }
139
94.5k
  return size * nmemb;
140
94.5k
}
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
9.67k
void DrainWsRecv(CURL* easy) {
145
48.0k
  for (std::size_t i = 0; i < kMaxWsRecvIterations; ++i) {
146
48.0k
    unsigned char buffer[4096];
147
48.0k
    std::size_t nread = 0;
148
48.0k
    const struct curl_ws_frame* meta = nullptr;
149
48.0k
    CURLcode rr = curl_ws_recv(easy, buffer, sizeof(buffer), &nread, &meta);
150
48.0k
    if (rr == CURLE_AGAIN) {
151
5.82k
      break;
152
5.82k
    }
153
42.1k
    if (rr != CURLE_OK && rr != CURLE_GOT_NOTHING) {
154
3.77k
      break;
155
3.77k
    }
156
38.3k
    if (nread == 0 && meta == nullptr) {
157
0
      break;
158
0
    }
159
38.3k
  }
160
9.67k
}
161
162
}  // namespace
163
164
/// Mirror the sequential CURLOPT_CONNECT_ONLY setopts applied by
165
/// ApplyScenarioOptions. Values above 2 are rejected by libcurl and therefore
166
/// cannot replace the last accepted setting. Use the same descriptor-aware
167
/// scalar decoder as ApplySetOption so compatibility inputs and cross-family
168
/// mutations cannot make curl and its mock disagree about manual delivery.
169
/// Restricting the scan to RuntimeOptionCount also prevents a compatibility-
170
/// only suffix from changing mock delivery after curl stops observing options.
171
29.8k
bool ScenarioRequestsManualWsDrive(const curl::fuzzer::proto::Scenario& scenario) {
172
29.8k
  bool manual_delivery = false;
173
29.8k
  const std::size_t option_count = RuntimeOptionCount(scenario);
174
134k
  for (std::size_t index = 0; index < option_count; ++index) {
175
104k
    const auto& option = scenario.options(static_cast<int>(index));
176
104k
    if (option.option_id() != curl::fuzzer::proto::CURLOPT_CONNECT_ONLY) {
177
99.8k
      continue;
178
99.8k
    }
179
4.56k
    const std::uint64_t value = DecodeIntegralOptionValue(option);
180
4.56k
    if (value <= 2) {
181
3.19k
      manual_delivery = value == 2;
182
3.19k
    }
183
4.56k
  }
184
29.8k
  return manual_delivery;
185
29.8k
}
186
187
/// Construct an idle WebSocketMockServer with no queued frames. Install()
188
/// on the base class and DriveScenario() configure it from a Scenario proto.
189
WebSocketMockServer::WebSocketMockServer()
190
29.8k
    : next_chunk_(0), manual_delivery_(false), handshake_sent_(false), ws_probe_fired_(false), easy_handle_(nullptr) {}
191
192
/// Default destructor; the owned MockConnection (if any) cleans up its socketpair.
193
29.8k
WebSocketMockServer::~WebSocketMockServer() = default;
194
195
/// Install the common socket callbacks via the base, then overwrite
196
/// WRITEFUNCTION / HEADERFUNCTION with a ws-aware variant and wire
197
/// WRITEDATA to this server instance so the callback can consult per-
198
/// scenario state (easy handle, one-shot probe flag).
199
29.8k
void WebSocketMockServer::Install(CURL* easy) {
200
29.8k
  MockServerBase::Install(easy);
201
29.8k
  easy_handle_ = easy;
202
29.8k
  ws_probe_fired_ = false;
203
29.8k
  curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, &WebSocketWriteCallback);
204
29.8k
  curl_easy_setopt(easy, CURLOPT_WRITEDATA, this);
205
29.8k
  curl_easy_setopt(easy, CURLOPT_HEADERFUNCTION, &WebSocketWriteCallback);
206
29.8k
}
207
208
/// @return true once the one-shot WS probe has fired for this scenario.
209
21.2k
bool WebSocketMockServer::ws_probe_fired() const { return ws_probe_fired_; }
210
211
/// Flip the one-shot gate closed. Called from the write callback before it
212
/// invokes curl_ws_send, so subsequent callback entries skip the probe.
213
1.45k
void WebSocketMockServer::MarkWsProbeFired() { ws_probe_fired_ = true; }
214
215
/// @return the curl easy handle cached by Install() for the write callback.
216
21.2k
CURL* WebSocketMockServer::easy_handle() const { return easy_handle_; }
217
218
/// Queue RFC 6455 wire-byte chunks to emit once the handshake has completed.
219
/// Resets the next-chunk cursor.
220
/// @param frames Ordered list of chunk byte strings.
221
29.8k
void WebSocketMockServer::SetFrames(std::vector<std::string> frames) {
222
29.8k
  frames_ = std::move(frames);
223
29.8k
  next_chunk_ = 0;
224
29.8k
}
225
226
/// Toggle streaming (false, default) vs manual (true) chunk delivery.
227
/// @param manual Whether to suppress automatic chunk pushing by the
228
///        drive loop.
229
29.8k
void WebSocketMockServer::SetManualDelivery(bool manual) { manual_delivery_ = manual; }
230
231
/// @return true if chunks are caller-driven rather than drive-loop-driven.
232
536k
bool WebSocketMockServer::manual_delivery() const { return manual_delivery_; }
233
234
/// @return true once a 101 Switching Protocols response has been written.
235
1.52M
bool WebSocketMockServer::handshake_sent() const { return handshake_sent_; }
236
237
/// @return true if at least one frame chunk has not yet been sent.
238
453k
bool WebSocketMockServer::has_more_chunks() const { return next_chunk_ < frames_.size(); }
239
240
/// @return the number of queued chunks not yet consumed.
241
9.67k
std::size_t WebSocketMockServer::remaining_chunks() const {
242
9.67k
  return next_chunk_ >= frames_.size() ? 0 : frames_.size() - next_chunk_;
243
9.67k
}
244
245
/// Access a pending chunk without consuming it.
246
/// @param index Offset from the next-pending cursor.
247
/// @return reference to the chunk byte string.
248
7.93k
const std::string& WebSocketMockServer::PeekChunk(std::size_t index) const { return frames_[next_chunk_ + index]; }
249
250
/// Advance the pending-chunk cursor by one. No-op when no chunks remain.
251
7.93k
void WebSocketMockServer::ConsumeChunk() {
252
7.93k
  if (next_chunk_ < frames_.size()) {
253
7.93k
    ++next_chunk_;
254
7.93k
  }
255
7.93k
}
256
257
/// Called by the OPENSOCKETFUNCTION trampoline in the base class. Creates the
258
/// MockConnection but does NOT write anything — the handshake is driven later
259
/// by TryAdvanceHandshake().
260
/// @param purpose Socket role requested by curl; this peer accepts one outbound
261
///                WebSocket transport only.
262
/// @param address Intended destination retained by curl; the already-connected
263
///                socketpair leaves it unchanged.
264
/// @return the client-side fd to hand to libcurl, or CURL_SOCKET_BAD on
265
///         failure.
266
22.3k
curl_socket_t WebSocketMockServer::HandleOpenSocket(curlsocktype purpose, struct curl_sockaddr* address) {
267
22.3k
  (void)purpose;
268
22.3k
  (void)address;
269
22.3k
  if (connection_) {
270
0
    return CURL_SOCKET_BAD;
271
0
  }
272
22.3k
  connection_ = std::make_unique<MockConnection>();
273
22.3k
  if (!connection_->ok()) {
274
0
    connection_.reset();
275
0
    return CURL_SOCKET_BAD;
276
0
  }
277
22.3k
  ApplyPendingBackpressure();
278
  // Wait for curl's Upgrade request before we write anything — the drive
279
  // loop calls TryAdvanceHandshake() to drive that exchange.
280
22.3k
  return connection_->take_client_fd();
281
22.3k
}
282
283
/// Push raw bytes onto the server fd. Used by the manual-drive path to feed
284
/// frame bytes directly into curl without any mock-side framing.
285
/// @param data Buffer to send.
286
/// @param size Number of bytes in 'data'.
287
/// @return false on short or failed write.
288
7.44k
bool WebSocketMockServer::PushRawBytes(const unsigned char* data, std::size_t size) {
289
7.44k
  if (!connection_) {
290
0
    return false;
291
0
  }
292
7.44k
  connection_->DrainIncoming();
293
7.44k
  return connection_->WriteAll(data, size);
294
7.44k
}
295
296
/// Push the next queued frame when curl is ready. Used in streaming mode;
297
/// the drive loop calls this after the handshake has been sent. Shuts
298
/// the write side once the last chunk is delivered.
299
/// @return true when a chunk was consumed from the script.
300
7.46k
bool WebSocketMockServer::DeliverNextChunk() {
301
7.46k
  if (!connection_ || next_chunk_ >= frames_.size()) {
302
0
    return false;
303
0
  }
304
7.46k
  connection_->DrainIncoming();
305
7.46k
  const std::string& chunk = frames_[next_chunk_++];
306
7.46k
  if (!chunk.empty()) {
307
7.00k
    connection_->WriteAll(reinterpret_cast<const unsigned char*>(chunk.data()), chunk.size());
308
7.00k
  }
309
7.46k
  if (next_chunk_ >= frames_.size()) {
310
2.13k
    connection_->ShutdownWrite();
311
2.13k
  }
312
7.46k
  return true;
313
7.46k
}
314
315
/// Drive the WebSocket opening handshake: read whatever curl has written so
316
/// far, and once we've seen the end of the request headers, reply with a
317
/// valid 101 Switching Protocols.
318
/// @return true once the 101 response has been written (idempotent afterwards).
319
74.0k
bool WebSocketMockServer::TryAdvanceHandshake() {
320
74.0k
  if (handshake_sent_ || !connection_) {
321
7.47k
    return handshake_sent_;
322
7.47k
  }
323
66.5k
  connection_->ReadAvailable(&ws_request_buffer_);
324
66.5k
  if (ws_request_buffer_.find("\r\n\r\n") == std::string::npos) {
325
51.8k
    return false;
326
51.8k
  }
327
14.6k
  std::string key = ExtractWebSocketKey(ws_request_buffer_);
328
  // Even if parsing failed, reply with *something* so curl doesn't wedge.
329
  // A bad Accept exercises curl's handshake-error path.
330
14.6k
  std::string accept = key.empty() ? std::string("AAAAAAAAAAAAAAAAAAAAAAAAAAA=") : ComputeWebSocketAccept(key);
331
14.6k
  std::string response =
332
14.6k
      "HTTP/1.1 101 Switching Protocols\r\n"
333
14.6k
      "Upgrade: websocket\r\n"
334
14.6k
      "Connection: Upgrade\r\n"
335
14.6k
      "Sec-WebSocket-Accept: " +
336
14.6k
      accept + "\r\n\r\n";
337
14.6k
  connection_->WriteAll(reinterpret_cast<const unsigned char*>(response.data()), response.size());
338
14.6k
  handshake_sent_ = true;
339
14.6k
  return true;
340
66.5k
}
341
342
/// Seed the mock from the scenario, then run the perform loop. Drives the 101
343
/// handshake on every iteration; in streaming mode also pushes queued frame
344
/// chunks as curl becomes readable. In manual mode (CURLOPT_CONNECT_ONLY=2)
345
/// chunks are left alone during the loop — once the loop returns, this method
346
/// pushes them as raw bytes and exercises curl_ws_recv / curl_ws_send against
347
/// a small flag matrix.
348
/// @param multi    caller-owned multi; 'easy' is already added.
349
/// @param easy     the curl easy handle attached to this mock.
350
/// @param scenario source of the frame chunks and CONNECT_ONLY setting.
351
29.8k
void WebSocketMockServer::RunLoop(CURLM* multi, CURL* easy, const curl::fuzzer::proto::Scenario& scenario) {
352
29.8k
  SetManualDelivery(ScenarioRequestsManualWsDrive(scenario));
353
  // initial_response is unused in WS mode; we synthesise the 101 dynamically
354
  // from curl's Upgrade request.
355
29.8k
  SetFrames(BuildFrameChunks(scenario.connection()));
356
357
29.8k
  int still_running = 1;
358
29.8k
  int idle_iterations = 0;
359
29.8k
  int drive_iterations = 0;
360
29.8k
  bool pollset_probed = false;
361
29.8k
  const bool timed_drive = UsesTimedDrive(scenario);
362
29.8k
  const int idle_limit = timed_drive ? kMaxTimedIdleIterations : kMaxIdleIterations;
363
29.8k
  CURLMcode rc = CURLM_OK;
364
365
536k
  while (still_running && idle_iterations < idle_limit && drive_iterations++ < kMaxDriveIterations) {
366
522k
    bool made_progress = false;
367
522k
    const int running_before = still_running;
368
522k
    rc = curl_multi_perform(multi, &still_running);
369
522k
    if (rc != CURLM_OK) {
370
0
      break;
371
0
    }
372
522k
    made_progress = still_running != running_before;
373
522k
    if (timed_drive && still_running && !pollset_probed) {
374
      // At this point curl has created the Upgrade connection but the mock has
375
      // not necessarily replied, which gives curl_multi_poll a meaningful WS
376
      // filter state without adding a timeout to fixed fast-lane inputs.
377
3.47k
      ProbeMultiPollset(multi);
378
3.47k
      pollset_probed = true;
379
3.47k
    }
380
    // Drive the 101 handshake on every iteration; no-op once sent.
381
522k
    if (!handshake_sent()) {
382
74.0k
      if (TryAdvanceHandshake()) {
383
14.6k
        made_progress = true;
384
14.6k
      }
385
74.0k
    }
386
522k
    if (!still_running) {
387
15.4k
      break;
388
15.4k
    }
389
390
    // Only push frame chunks in streaming mode — in manual mode the caller
391
    // will push them below after the handshake.
392
507k
    if (!manual_delivery() && handshake_sent() && has_more_chunks()) {
393
7.46k
      made_progress = DeliverNextChunk() || made_progress;
394
499k
    } else if (handshake_sent() && connection() != nullptr) {
395
      // Uploading WS scenarios can have no server frames at all. Drain their
396
      // encoded client data here so they make deterministic progress and do
397
      // not have to wait for CURLOPT_TIMEOUT_MS just to exercise cr_ws_read.
398
449k
      made_progress = connection()->DrainIncoming() != 0 || made_progress;
399
449k
    }
400
401
507k
    if (made_progress) {
402
53.3k
      idle_iterations = 0;
403
53.3k
      continue;
404
53.3k
    }
405
406
453k
    if (timed_drive) {
407
339k
      (void)WaitOnMultiFdset(multi, &rc);
408
339k
      if (rc != CURLM_OK) {
409
0
        break;
410
0
      }
411
339k
    }
412
453k
    ++idle_iterations;
413
453k
  }
414
415
29.8k
  if (!manual_delivery() || !handshake_sent()) {
416
28.0k
    return;
417
28.0k
  }
418
419
  // Manual-drive tail: feed every remaining scripted chunk straight onto the
420
  // server fd as raw frame bytes, draining curl_ws_recv between each push.
421
9.67k
  while (remaining_chunks() > 0) {
422
7.93k
    const std::string& chunk = PeekChunk(0);
423
7.93k
    if (!chunk.empty()) {
424
7.44k
      PushRawBytes(reinterpret_cast<const unsigned char*>(chunk.data()), chunk.size());
425
7.44k
    }
426
7.93k
    ConsumeChunk();
427
7.93k
    DrainWsRecv(easy);
428
7.93k
  }
429
  // Final drain in case frame parsing produced more work after the last push.
430
1.74k
  DrainWsRecv(easy);
431
432
1.74k
  const auto& probes = scenario.connection().manual_probes();
433
1.74k
  static const unsigned char kPayload[] = "hello-from-proto-fuzzer";
434
1.74k
  const std::size_t payload_len = sizeof(kPayload) - 1;
435
436
1.74k
  if (probes.flag_matrix()) {
437
    // Exercise curl_ws_send with a fixed matrix of flags. We don't care whether
438
    // the send actually lands on the wire — the point is to reach the encode
439
    // paths in ws_enc_add_frame / ws_enc_write_head.
440
389
    std::size_t iteration = 0;
441
7.39k
    for (unsigned int flags : kWsSendFlagMatrix) {
442
7.39k
      if (iteration++ >= kMaxWsSendIterations) {
443
0
        break;
444
0
      }
445
      // Announce the frame via the public curl_ws_start_frame entrypoint before
446
      // the actual send. In non-raw mode this writes the frame head into the
447
      // sendbuf; the follow-up curl_ws_send with the same flags finishes the
448
      // exchange or fails cleanly on invalid flag combos.
449
7.39k
      (void)curl_ws_start_frame(easy, flags, static_cast<curl_off_t>(payload_len));
450
7.39k
      std::size_t sent = 0;
451
7.39k
      curl_off_t fragsize = (flags & CURLWS_OFFSET) ? static_cast<curl_off_t>(payload_len) : 0;
452
7.39k
      (void)curl_ws_send(easy, kPayload, payload_len, &sent, fragsize, flags);
453
7.39k
      if (connection() != nullptr) {
454
7.39k
        connection()->DrainIncoming();
455
7.39k
      }
456
7.39k
    }
457
389
  }
458
459
1.74k
  if (probes.unaligned_send()) {
460
    // Multi-call mis-sized send probe: declare a fragsize=200 frame, send 23
461
    // bytes, then call curl_ws_send again with a buflen much bigger than the
462
    // remaining payload. Hits the "unaligned frame size" failf in ws_enc_send.
463
233
    constexpr curl_off_t kBigFrag = 200;
464
233
    (void)curl_ws_start_frame(easy, CURLWS_TEXT | CURLWS_OFFSET, kBigFrag);
465
233
    std::size_t sent = 0;
466
233
    (void)curl_ws_send(easy, kPayload, payload_len, &sent, kBigFrag, CURLWS_TEXT | CURLWS_OFFSET);
467
    // Now enc.payload_remain ≈ kBigFrag - payload_len. A follow-up send with
468
    // buflen > remaining trips the guard at ws_enc_send:~1050.
469
233
    std::size_t sent2 = 0;
470
233
    constexpr std::size_t kOverrun = 500;
471
233
    unsigned char overrun[kOverrun];
472
233
    std::fill(overrun, overrun + kOverrun, 'X');
473
233
    (void)curl_ws_send(easy, overrun, kOverrun, &sent2, kBigFrag, CURLWS_TEXT | CURLWS_OFFSET);
474
233
    if (connection() != nullptr) {
475
233
      connection()->DrainIncoming();
476
233
    }
477
233
  }
478
479
1.74k
  if (probes.raw_send()) {
480
    // Raw-mode send path: reachable only when CURLOPT_WS_OPTIONS has
481
    // CURLWS_RAW_MODE set. curl_ws_send with flags=0, fragsize=0 takes the
482
    // data->set.ws_raw_mode branch → ws_send_raw. No-op for non-raw scenarios
483
    // (hits the "no flags given" failure path instead).
484
166
    std::size_t sent = 0;
485
166
    (void)curl_ws_send(easy, kPayload, payload_len, &sent, 0, 0);
486
166
    if (connection() != nullptr) {
487
166
      connection()->DrainIncoming();
488
166
    }
489
166
  }
490
1.74k
}
491
492
}  // namespace proto_fuzzer