Coverage Report

Created: 2026-12-01 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl_fuzzer/proto_fuzzer/http3_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 ngtcp2 QUIC transport and nghttp3 peer implementation.
9
10
#include "proto_fuzzer/http3_mock_server.h"
11
12
#include <arpa/inet.h>
13
#include <fcntl.h>
14
#include <nghttp3/nghttp3.h>
15
#include <ngtcp2/ngtcp2.h>
16
#include <ngtcp2/ngtcp2_crypto.h>
17
#include <ngtcp2/ngtcp2_crypto_ossl.h>
18
#include <openssl/err.h>
19
#include <openssl/pem.h>
20
#include <openssl/ssl.h>
21
#include <poll.h>
22
#include <sys/socket.h>
23
#include <unistd.h>
24
25
#include <algorithm>
26
#include <array>
27
#include <cerrno>
28
#include <chrono>
29
#include <climits>
30
#include <cstddef>
31
#include <cstdint>
32
#include <cstring>
33
#include <memory>
34
#include <string>
35
#include <utility>
36
#include <vector>
37
38
#include "proto_fuzzer/multi_socket_driver.h"
39
#include "proto_fuzzer/scenario_limits.h"
40
#include "proto_fuzzer/tls_test_credentials.h"
41
42
namespace proto_fuzzer {
43
44
namespace {
45
46
constexpr std::int64_t kNoStreamId = -1;
47
constexpr std::size_t kMaxDatagramsPerTurn = 64;
48
constexpr std::size_t kServerConnectionIdBytes = 18;
49
constexpr std::size_t kReceiveBufferBytes = 64 * 1024;
50
// One request plus the six HTTP/3 critical streams leave room for every
51
// bounded action to create a fresh raw unidirectional stream.
52
constexpr std::size_t kMaxStreams = scenario_limits::kMaxHttp3Actions + 8;
53
constexpr std::size_t kMaxWritesPerTurn = 64;
54
constexpr std::size_t kMaxPendingPlaintextBytes = 64 * 1024;
55
constexpr int kHttp3IdleIterations = 32;
56
// QUIC's first two bits select one of these wire widths. The remaining bits
57
// encode the integer itself.
58
constexpr std::array<std::size_t, 4> kQuicVarintByteWidths = {1, 2, 4, 8};
59
constexpr unsigned int kQuicVarintTagBits = 2;
60
constexpr unsigned int kQuicVarintTagShift = CHAR_BIT - kQuicVarintTagBits;
61
static_assert(CHAR_BIT == 8, "QUIC varints require 8-bit bytes");
62
63
enum StreamRoleIndex : std::size_t {
64
  kResponseStream = 0,
65
  kControlStream = 1,
66
  kQpackEncoderStream = 2,
67
  kQpackDecoderStream = 3,
68
  kStreamRoleCount = 4,
69
};
70
71
/// Keep server-side OpenSSL failures from changing error classification in
72
/// curl's OpenSSL client, which executes on the same thread.
73
class OpenSslErrorQueueGuard {
74
 public:
75
52.1k
  OpenSslErrorQueueGuard() { ERR_clear_error(); }
76
52.1k
  ~OpenSslErrorQueueGuard() { ERR_clear_error(); }
77
78
  OpenSslErrorQueueGuard(const OpenSslErrorQueueGuard&) = delete;
79
  OpenSslErrorQueueGuard& operator=(const OpenSslErrorQueueGuard&) = delete;
80
};
81
82
/// Configure callback-created descriptors explicitly: curl's requested
83
/// SOCK_NONBLOCK and SOCK_CLOEXEC flags do not constrain an application fd.
84
3.94k
bool ConfigureSocket(int fd) {
85
3.94k
  if (fd < 0) {
86
0
    return false;
87
0
  }
88
3.94k
  const int descriptor_flags = ::fcntl(fd, F_GETFD, 0);
89
3.94k
  if (descriptor_flags < 0 || ::fcntl(fd, F_SETFD, descriptor_flags | FD_CLOEXEC) < 0) {
90
0
    return false;
91
0
  }
92
3.94k
  const int status_flags = ::fcntl(fd, F_GETFL, 0);
93
3.94k
  return status_flags >= 0 && ::fcntl(fd, F_SETFL, status_flags | O_NONBLOCK) == 0;
94
3.94k
}
95
96
/// Bind one private IPv4 UDP endpoint to an ephemeral loopback port.
97
1.97k
int OpenLoopbackSocket(struct sockaddr_in* bound_address) {
98
1.97k
  if (bound_address == nullptr) {
99
0
    return -1;
100
0
  }
101
102
1.97k
  const int fd = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
103
1.97k
  if (fd < 0 || !ConfigureSocket(fd)) {
104
0
    if (fd >= 0) {
105
0
      (void)::close(fd);
106
0
    }
107
0
    return -1;
108
0
  }
109
110
1.97k
  struct sockaddr_in requested = {};
111
1.97k
  requested.sin_family = AF_INET;
112
1.97k
  requested.sin_port = htons(0);
113
1.97k
  requested.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
114
1.97k
  if (::bind(fd, reinterpret_cast<const struct sockaddr*>(&requested), sizeof(requested)) != 0) {
115
0
    (void)::close(fd);
116
0
    return -1;
117
0
  }
118
119
1.97k
  socklen_t length = sizeof(*bound_address);
120
1.97k
  std::memset(bound_address, 0, sizeof(*bound_address));
121
1.97k
  if (::getsockname(fd, reinterpret_cast<struct sockaddr*>(bound_address), &length) != 0 ||
122
1.97k
      length != sizeof(*bound_address) || bound_address->sin_family != AF_INET) {
123
0
    (void)::close(fd);
124
0
    return -1;
125
0
  }
126
1.97k
  return fd;
127
1.97k
}
128
129
/// Replace all destination metadata curl can retain with the private listener.
130
1.97k
bool RewriteDestination(struct curl_sockaddr* address, const struct sockaddr_in& destination) {
131
1.97k
  if (address == nullptr || sizeof(destination) > sizeof(address->addr)) {
132
0
    return false;
133
0
  }
134
1.97k
  address->family = AF_INET;
135
1.97k
  address->socktype = SOCK_DGRAM;
136
1.97k
  address->protocol = IPPROTO_UDP;
137
1.97k
  address->addrlen = sizeof(destination);
138
1.97k
  std::memset(&address->addr, 0, sizeof(address->addr));
139
1.97k
  std::memcpy(&address->addr, &destination, sizeof(destination));
140
1.97k
  return true;
141
1.97k
}
142
143
/// Select only the final RFC HTTP/3 ALPN identifier.
144
int SelectHttp3Alpn(SSL* /*ssl*/, const unsigned char** selected, unsigned char* selected_length,
145
1.96k
                    const unsigned char* client_protocols, unsigned int client_protocols_length, void* /*userdata*/) {
146
1.96k
  static constexpr unsigned char server_protocols[] = {2, 'h', '3'};
147
1.96k
  unsigned char* match = nullptr;
148
1.96k
  unsigned char match_length = 0;
149
1.96k
  const int result = SSL_select_next_proto(&match, &match_length, server_protocols, sizeof(server_protocols),
150
1.96k
                                           client_protocols, client_protocols_length);
151
1.96k
  if (result != OPENSSL_NPN_NEGOTIATED) {
152
0
    return SSL_TLSEXT_ERR_ALERT_FATAL;
153
0
  }
154
1.96k
  *selected = match;
155
1.96k
  *selected_length = match_length;
156
1.96k
  return SSL_TLSEXT_ERR_OK;
157
1.96k
}
158
159
/// Append one profile-selected certificate without transferring a malformed
160
/// object into the context on parse failure.
161
282
bool AddExtraChainCertificate(SSL_CTX* context, const char* certificate_pem) {
162
282
  BIO* certificate_bio = BIO_new_mem_buf(certificate_pem, -1);
163
282
  if (certificate_bio == nullptr) {
164
0
    return false;
165
0
  }
166
282
  X509* certificate = PEM_read_bio_X509(certificate_bio, nullptr, nullptr, nullptr);
167
282
  BIO_free(certificate_bio);
168
282
  if (certificate == nullptr) {
169
0
    return false;
170
0
  }
171
282
  if (SSL_CTX_add_extra_chain_cert(context, certificate) != 1) {
172
0
    X509_free(certificate);
173
0
    return false;
174
0
  }
175
282
  return true;
176
282
}
177
178
/// Parse the checked-in key and profile-selected chain entirely in memory.
179
2.28k
bool LoadCredentials(SSL_CTX* context, curl::fuzzer::proto::TlsCertificateChainProfile certificate_chain) {
180
2.28k
  BIO* certificate_bio = BIO_new_mem_buf(tls_test_credentials::kCertificatePem, -1);
181
2.28k
  BIO* key_bio = BIO_new_mem_buf(tls_test_credentials::kPrivateKeyPem, -1);
182
2.28k
  if (certificate_bio == nullptr || key_bio == nullptr) {
183
0
    BIO_free(certificate_bio);
184
0
    BIO_free(key_bio);
185
0
    return false;
186
0
  }
187
188
2.28k
  X509* certificate = PEM_read_bio_X509(certificate_bio, nullptr, nullptr, nullptr);
189
2.28k
  EVP_PKEY* key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
190
2.28k
  BIO_free(certificate_bio);
191
2.28k
  BIO_free(key_bio);
192
2.28k
  if (certificate == nullptr || key == nullptr) {
193
0
    X509_free(certificate);
194
0
    EVP_PKEY_free(key);
195
0
    return false;
196
0
  }
197
198
2.28k
  const bool loaded = SSL_CTX_use_certificate(context, certificate) == 1 && SSL_CTX_use_PrivateKey(context, key) == 1 &&
199
2.28k
                      SSL_CTX_check_private_key(context) == 1;
200
2.28k
  X509_free(certificate);
201
2.28k
  EVP_PKEY_free(key);
202
2.28k
  if (!loaded) {
203
0
    return false;
204
0
  }
205
206
2.28k
  if (certificate_chain == curl::fuzzer::proto::TLS_CERTIFICATE_CHAIN_ALL_KEY_TYPES) {
207
94
    return AddExtraChainCertificate(context, tls_test_credentials::kRsaCertificatePem) &&
208
94
           AddExtraChainCertificate(context, tls_test_credentials::kDsaCertificatePem) &&
209
94
           AddExtraChainCertificate(context, tls_test_credentials::kDhCertificatePem);
210
94
  }
211
2.19k
  return true;
212
2.28k
}
213
214
/// Create a TLS 1.3 context for ngtcp2's OpenSSL crypto adapter.
215
2.28k
SSL_CTX* CreateTlsContext(curl::fuzzer::proto::TlsCertificateChainProfile certificate_chain) {
216
2.28k
  OpenSslErrorQueueGuard error_guard;
217
2.28k
  SSL_CTX* context = SSL_CTX_new(TLS_server_method());
218
2.28k
  if (context == nullptr || !LoadCredentials(context, certificate_chain)) {
219
0
    SSL_CTX_free(context);
220
0
    return nullptr;
221
0
  }
222
223
2.28k
  if (SSL_CTX_set_min_proto_version(context, TLS1_3_VERSION) != 1 ||
224
2.28k
      SSL_CTX_set_max_proto_version(context, TLS1_3_VERSION) != 1) {
225
0
    SSL_CTX_free(context);
226
0
    return nullptr;
227
0
  }
228
2.28k
  (void)SSL_CTX_set_options(context, SSL_OP_NO_COMPRESSION);
229
2.28k
  SSL_CTX_set_alpn_select_cb(context, &SelectHttp3Alpn, nullptr);
230
2.28k
  return context;
231
2.28k
}
232
233
/// Encode one QUIC variable-length integer in its shortest representation.
234
870
void AppendQuicVarint(std::string* output, std::uint64_t value) {
235
870
  value &= scenario_limits::kMaxQuicVarint;
236
876
  for (std::size_t encoding = 0; encoding < kQuicVarintByteWidths.size(); ++encoding) {
237
876
    const std::size_t byte_width = kQuicVarintByteWidths[encoding];
238
876
    const unsigned int value_bits = static_cast<unsigned int>(byte_width * CHAR_BIT - kQuicVarintTagBits);
239
876
    if (value >= (std::uint64_t{1} << value_bits)) {
240
6
      continue;
241
6
    }
242
243
1.75k
    for (std::size_t byte = byte_width; byte != 0; --byte) {
244
884
      const unsigned int shift = static_cast<unsigned int>((byte - 1) * CHAR_BIT);
245
884
      unsigned char encoded_byte = static_cast<unsigned char>(value >> shift);
246
884
      if (byte == byte_width) {
247
870
        encoded_byte |= static_cast<unsigned char>(encoding << kQuicVarintTagShift);
248
870
      }
249
884
      output->push_back(static_cast<char>(encoded_byte));
250
884
    }
251
870
    return;
252
876
  }
253
870
}
254
255
/// Normalize a header name again at the runtime boundary. Fixed H3 targets
256
/// already run the postprocessor; this also keeps direct unit-test scenarios
257
/// safe to pass to nghttp3.
258
1.45k
std::string NormalizeHeaderName(const std::string& source) {
259
1.45k
  std::string result = source.substr(0, scenario_limits::kMaxHttp3HeaderNameBytes);
260
1.45k
  if (result.empty()) {
261
0
    return "x-fuzz";
262
0
  }
263
17.9k
  for (char& byte : result) {
264
17.9k
    const unsigned char value = static_cast<unsigned char>(byte);
265
17.9k
    const bool lower = value >= 'a' && value <= 'z';
266
17.9k
    const bool upper = value >= 'A' && value <= 'Z';
267
17.9k
    const bool digit = value >= '0' && value <= '9';
268
17.9k
    const bool punctuation = value == '!' || value == '#' || value == '$' || value == '%' || value == '&' ||
269
15.5k
                             value == '\'' || value == '*' || value == '+' || value == '-' || value == '.' ||
270
8.70k
                             value == '^' || value == '_' || value == '`' || value == '|' || value == '~';
271
17.9k
    if (upper) {
272
0
      byte = static_cast<char>(value - 'A' + 'a');
273
17.9k
    } else if (!lower && !digit && !punctuation) {
274
0
      byte = '-';
275
0
    }
276
17.9k
  }
277
1.45k
  return result;
278
1.45k
}
279
280
/// Remove control bytes that would make a structured field value malformed.
281
1.45k
std::string NormalizeHeaderValue(const std::string& source) {
282
1.45k
  std::string result = source.substr(0, scenario_limits::kMaxHttp3HeaderValueBytes);
283
273k
  for (char& byte : result) {
284
273k
    const unsigned char value = static_cast<unsigned char>(byte);
285
273k
    if ((value < 0x20U && value != '\t') || value == 0x7fU) {
286
0
      byte = ' ';
287
0
    }
288
273k
  }
289
1.45k
  return result;
290
1.45k
}
291
292
/// Map a fuzzed status code into the valid HTTP range.
293
1.37k
std::uint32_t NormalizeResponseStatus(std::uint32_t status_code) {
294
1.37k
  return status_code >= 100U && status_code <= 599U ? status_code : 100U + status_code % 500U;
295
1.37k
}
296
297
/// Return ngtcp2's nanosecond-resolution monotonic timestamp.
298
119k
ngtcp2_tstamp QuicNow() {
299
119k
  const auto now = std::chrono::steady_clock::now().time_since_epoch();
300
119k
  return static_cast<ngtcp2_tstamp>(std::chrono::duration_cast<std::chrono::nanoseconds>(now).count());
301
119k
}
302
303
}  // namespace
304
305
/// Private transport and HTTP/3 state. Keeping ngtcp2, OpenSSL, and nghttp3
306
/// out of the public header lets other proto targets compile without their
307
/// include trees.
308
class Http3MockServerImpl {
309
 public:
310
  explicit Http3MockServerImpl(curl::fuzzer::proto::TlsCertificateChainProfile certificate_chain)
311
2.28k
      : context_(CreateTlsContext(certificate_chain)), crypto_connection_ref_{&GetQuicConnection, this} {
312
2.28k
    role_stream_ids_.fill(kNoStreamId);
313
2.28k
    streams_.reserve(kMaxStreams);
314
2.28k
    retained_writes_.reserve(kMaxWritesPerTurn);
315
2.28k
  }
316
317
2.28k
  ~Http3MockServerImpl() {
318
2.28k
    ResetPeer();
319
2.28k
    OpenSslErrorQueueGuard error_guard;
320
2.28k
    SSL_CTX_free(context_);
321
2.28k
  }
322
323
  Http3MockServerImpl(const Http3MockServerImpl&) = delete;
324
  Http3MockServerImpl& operator=(const Http3MockServerImpl&) = delete;
325
326
1.97k
  curl_socket_t OpenSocket(curlsocktype purpose, struct curl_sockaddr* address) {
327
1.97k
    if (purpose != CURLSOCKTYPE_IPCXN || address == nullptr || socket_opened_ || context_ == nullptr) {
328
0
      return CURL_SOCKET_BAD;
329
0
    }
330
1.97k
    socket_opened_ = true;
331
332
1.97k
    struct sockaddr_in listener_address = {};
333
1.97k
    server_fd_ = OpenLoopbackSocket(&listener_address);
334
1.97k
    if (server_fd_ < 0 || !RewriteDestination(address, listener_address)) {
335
0
      ResetPeer();
336
0
      return CURL_SOCKET_BAD;
337
0
    }
338
1.97k
    server_port_ = ntohs(listener_address.sin_port);
339
1.97k
    local_address_ = listener_address;
340
341
1.97k
    const int client_fd = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
342
1.97k
    if (client_fd < 0 || !ConfigureSocket(client_fd)) {
343
0
      if (client_fd >= 0) {
344
0
        (void)::close(client_fd);
345
0
      }
346
0
      ResetPeer();
347
0
      return CURL_SOCKET_BAD;
348
0
    }
349
1.97k
    return static_cast<curl_socket_t>(client_fd);
350
1.97k
  }
351
352
2.21k
  void BeginScenario(const curl::fuzzer::proto::Scenario& scenario) {
353
2.21k
    ResetPeer();
354
2.21k
    scenario_ = &scenario;
355
2.21k
    default_response_.Clear();
356
2.21k
    default_response_.set_status_code(200);
357
2.21k
    default_response_.set_finish_stream(true);
358
2.21k
  }
359
360
47.0k
  std::size_t DrivePeerTurn() {
361
47.0k
    ++peer_turn_;
362
47.0k
    if (server_fd_ < 0 || transport_failed_) {
363
4.00k
      return 0;
364
4.00k
    }
365
366
43.0k
    OpenSslErrorQueueGuard error_guard;
367
43.0k
    std::size_t progress = HandleExpiry();
368
43.0k
    if (transport_failed_) {
369
0
      return progress;
370
0
    }
371
43.0k
    progress += ReadDatagrams();
372
43.0k
    if (quic_connection_ == nullptr || transport_failed_) {
373
76
      return progress;
374
76
    }
375
376
42.9k
    if (handshake_complete_ && !close_requested_ && !close_sent_) {
377
38.7k
      progress += CreateServerStreams();
378
38.7k
      progress += DriveApplicationOutput();
379
38.7k
    }
380
42.9k
    progress += FlushTransportPackets();
381
42.9k
    return progress;
382
43.0k
  }
383
384
2.25k
  bool handshake_complete() const { return handshake_complete_; }
385
386
2.25k
  bool request_headers_received() const { return request_headers_received_; }
387
388
0
  std::size_t request_body_bytes() const { return request_body_bytes_; }
389
390
0
  std::size_t request_body_turns() const { return request_body_turns_; }
391
392
2.25k
  std::size_t executed_action_count() const { return next_action_; }
393
394
2.25k
  std::uint16_t server_port() const { return server_port_; }
395
396
 private:
397
  // ngtcp2 acknowledges QUIC writes by stream offset, while nghttp3 accepts
398
  // acknowledgement only for its own serialized bytes. Track those regions
399
  // separately from deliberately raw script writes.
400
  struct StreamState {
401
    struct ManagedWriteRange {
402
      std::uint64_t begin = 0;
403
      std::uint64_t end = 0;
404
    };
405
406
    std::int64_t id = kNoStreamId;
407
    std::uint64_t write_offset = 0;
408
    std::vector<ManagedWriteRange> managed_write_ranges;
409
    std::vector<std::uint64_t> managed_fin_offsets;
410
    std::size_t next_managed_ack_range = 0;
411
    std::size_t next_managed_fin_offset = 0;
412
  };
413
414
  // Queue at most one application write at a time. The byte string is kept in
415
  // retained_writes_ because ngtcp2 may submit only a prefix on each turn.
416
  struct PendingWrite {
417
    std::int64_t stream_id = kNoStreamId;
418
    const std::string* bytes = nullptr;
419
    std::size_t offset = 0;
420
    bool finish_stream = false;
421
    bool nghttp3_managed = false;
422
    bool completes_action = false;
423
424
91.8k
    bool active() const { return stream_id != kNoStreamId; }
425
426
12.2k
    void Clear() {
427
12.2k
      stream_id = kNoStreamId;
428
12.2k
      bytes = nullptr;
429
12.2k
      offset = 0;
430
12.2k
      finish_stream = false;
431
12.2k
      nghttp3_managed = false;
432
12.2k
      completes_action = false;
433
12.2k
    }
434
  };
435
436
  // nghttp3 pulls response bytes through a callback. This state lets that
437
  // callback preserve the scenario's chunk boundaries and final-stream intent.
438
  struct ResponseBodyState {
439
    std::vector<std::string> chunks;
440
    std::size_t next_chunk = 0;
441
    bool finish_stream = false;
442
    bool has_trailers = false;
443
  };
444
445
  enum class WriteResult {
446
    kComplete,
447
    kBlocked,
448
    kFailed,
449
  };
450
451
  // Tear down in protocol-layer order: HTTP/3 retains references into QUIC,
452
  // and OpenSSL's app data points back to this object until it is cleared.
453
4.49k
  void ResetPeer() {
454
4.49k
    OpenSslErrorQueueGuard error_guard;
455
4.49k
    pending_write_.Clear();
456
4.49k
    nghttp3_conn_del(http3_connection_);
457
4.49k
    http3_connection_ = nullptr;
458
4.49k
    ngtcp2_conn_del(quic_connection_);
459
4.49k
    quic_connection_ = nullptr;
460
4.49k
    if (tls_connection_ != nullptr) {
461
1.96k
      SSL_set_app_data(tls_connection_, nullptr);
462
1.96k
      SSL_free(tls_connection_);
463
1.96k
      tls_connection_ = nullptr;
464
1.96k
    }
465
4.49k
    ngtcp2_crypto_ossl_ctx_del(crypto_context_);
466
4.49k
    crypto_context_ = nullptr;
467
4.49k
    streams_.clear();
468
4.49k
    retained_writes_.clear();
469
4.49k
    if (server_fd_ >= 0) {
470
1.97k
      (void)::close(server_fd_);
471
1.97k
      server_fd_ = -1;
472
1.97k
    }
473
474
4.49k
    scenario_ = nullptr;
475
4.49k
    role_stream_ids_.fill(kNoStreamId);
476
4.49k
    std::memset(&local_address_, 0, sizeof(local_address_));
477
4.49k
    std::memset(&remote_address_, 0, sizeof(remote_address_));
478
4.49k
    ngtcp2_path_storage_zero(&path_storage_);
479
4.49k
    response_body_.chunks.clear();
480
4.49k
    response_body_.next_chunk = 0;
481
4.49k
    response_body_.finish_stream = false;
482
4.49k
    response_body_.has_trailers = false;
483
4.49k
    next_action_ = 0;
484
4.49k
    request_body_bytes_ = 0;
485
4.49k
    request_body_turns_ = 0;
486
4.49k
    last_request_body_turn_ = 0;
487
4.49k
    peer_turn_ = 0;
488
4.49k
    request_stream_finished_ = false;
489
4.49k
    server_port_ = 0;
490
4.49k
    socket_opened_ = false;
491
4.49k
    handshake_complete_ = false;
492
4.49k
    request_headers_received_ = false;
493
4.49k
    server_streams_bound_ = false;
494
4.49k
    bootstrap_drained_ = false;
495
4.49k
    waiting_for_h3_drain_ = false;
496
4.49k
    waiting_drain_completes_action_ = false;
497
4.49k
    final_response_submitted_ = false;
498
4.49k
    default_response_started_ = false;
499
4.49k
    http3_failed_ = false;
500
4.49k
    transport_failed_ = false;
501
4.49k
    close_requested_ = false;
502
4.49k
    close_sent_ = false;
503
4.49k
    close_error_code_ = 0;
504
4.49k
    random_counter_ = 0;
505
4.49k
  }
506
507
  // ngtcp2 calls into this group while it owns QUIC parsing and encryption.
508
  // Each callback bridges a transport event into the separately-owned nghttp3
509
  // connection or records enough state for a later application turn.
510
88.7k
  static ngtcp2_conn* GetQuicConnection(ngtcp2_crypto_conn_ref* connection_ref) {
511
88.7k
    auto* self = static_cast<Http3MockServerImpl*>(connection_ref->user_data);
512
88.7k
    return self == nullptr ? nullptr : self->quic_connection_;
513
88.7k
  }
514
515
1.95k
  static int HandshakeCompleted(ngtcp2_conn* /*connection*/, void* user_data) {
516
1.95k
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
517
1.95k
    if (self == nullptr) {
518
0
      return NGTCP2_ERR_CALLBACK_FAILURE;
519
0
    }
520
1.95k
    self->handshake_complete_ = true;
521
1.95k
    return 0;
522
1.95k
  }
523
524
3.93k
  static int ReceiveTransmitKey(ngtcp2_conn* /*connection*/, ngtcp2_encryption_level level, void* user_data) {
525
3.93k
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
526
3.93k
    if (self == nullptr) {
527
0
      return NGTCP2_ERR_CALLBACK_FAILURE;
528
0
    }
529
3.93k
    if (level != NGTCP2_ENCRYPTION_LEVEL_1RTT || self->server_streams_bound_) {
530
1.96k
      return 0;
531
1.96k
    }
532
    // HTTP/3 application streams become valid only after 1-RTT keys exist.
533
    // Bind its critical streams before allowing script output onto the peer.
534
1.96k
    if (!self->CreateHttp3Connection()) {
535
0
      return NGTCP2_ERR_CALLBACK_FAILURE;
536
0
    }
537
1.96k
    (void)self->CreateServerStreams();
538
1.96k
    return self->server_streams_bound_ ? 0 : NGTCP2_ERR_CALLBACK_FAILURE;
539
1.96k
  }
540
541
  static void GenerateRandomBytes(std::uint8_t* destination, std::size_t length,
542
7.87k
                                  const ngtcp2_rand_ctx* random_context) {
543
7.87k
    if (random_context == nullptr) {
544
0
      std::memset(destination, 0, length);
545
0
      return;
546
0
    }
547
7.87k
    auto* self = static_cast<Http3MockServerImpl*>(random_context->native_handle);
548
7.87k
    if (self == nullptr) {
549
0
      std::memset(destination, 0, length);
550
0
      return;
551
0
    }
552
7.87k
    self->FillRandom(destination, length);
553
7.87k
  }
554
555
  static int GetNewConnectionId(ngtcp2_conn* /*connection*/, ngtcp2_cid* connection_id,
556
                                ngtcp2_stateless_reset_token* reset_token, std::size_t connection_id_length,
557
1.96k
                                void* user_data) {
558
1.96k
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
559
1.96k
    if (self == nullptr || connection_id == nullptr || reset_token == nullptr ||
560
1.96k
        connection_id_length > sizeof(connection_id->data)) {
561
0
      return NGTCP2_ERR_CALLBACK_FAILURE;
562
0
    }
563
1.96k
    connection_id->datalen = connection_id_length;
564
1.96k
    self->FillRandom(connection_id->data, connection_id_length);
565
1.96k
    self->FillRandom(reset_token->data, sizeof(reset_token->data));
566
1.96k
    return 0;
567
1.96k
  }
568
569
7.80k
  static int OpenRemoteStream(ngtcp2_conn* /*connection*/, std::int64_t stream_id, void* user_data) {
570
7.80k
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
571
7.80k
    if (self == nullptr || self->streams_.size() >= kMaxStreams) {
572
0
      return NGTCP2_ERR_CALLBACK_FAILURE;
573
0
    }
574
7.80k
    StreamState state;
575
7.80k
    state.id = stream_id;
576
7.80k
    self->streams_.push_back(state);
577
7.80k
    if (self->role_stream_ids_[kResponseStream] == kNoStreamId && ngtcp2_is_bidi_stream(stream_id)) {
578
1.92k
      self->role_stream_ids_[kResponseStream] = stream_id;
579
1.92k
    }
580
7.80k
    return 0;
581
7.80k
  }
582
583
  // ngtcp2 presents decrypted stream bytes; nghttp3 parses the HTTP/3 layer.
584
  // Extending QUIC's flow-control windows by the consumed amount keeps only
585
  // parsed bytes eligible for further client transmission.
586
  static int ReceiveQuicStreamData(ngtcp2_conn* connection, std::uint32_t flags, std::int64_t stream_id,
587
                                   std::uint64_t /*offset*/, const std::uint8_t* data, std::size_t length,
588
10.7k
                                   void* user_data, void* /*stream_user_data*/) {
589
10.7k
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
590
10.7k
    if (self == nullptr || self->http3_connection_ == nullptr || self->http3_failed_) {
591
0
      return NGTCP2_ERR_CALLBACK_FAILURE;
592
0
    }
593
10.7k
    const nghttp3_ssize consumed =
594
10.7k
        nghttp3_conn_read_stream2(self->http3_connection_, stream_id, data, length, flags & NGTCP2_STREAM_DATA_FLAG_FIN,
595
10.7k
                                  ngtcp2_conn_get_timestamp(connection));
596
10.7k
    if (consumed < 0) {
597
12
      self->http3_failed_ = true;
598
12
      return NGTCP2_ERR_CALLBACK_FAILURE;
599
12
    }
600
10.7k
    ngtcp2_conn_extend_max_stream_offset(connection, stream_id, static_cast<std::uint64_t>(consumed));
601
10.7k
    ngtcp2_conn_extend_max_offset(connection, static_cast<std::uint64_t>(consumed));
602
10.7k
    return 0;
603
10.7k
  }
604
605
  // A transport acknowledgement covers both raw fuzz bytes and nghttp3 output.
606
  // Report only intersecting nghttp3-managed ranges back to nghttp3; otherwise
607
  // its write offsets would advance for bytes it never generated.
608
  static int AckedStreamDataOffset(ngtcp2_conn* /*connection*/, std::int64_t stream_id, std::uint64_t offset,
609
7.01k
                                   std::uint64_t length, void* user_data, void* /*stream_user_data*/) {
610
7.01k
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
611
7.01k
    if (self == nullptr || self->http3_connection_ == nullptr || self->http3_failed_) {
612
0
      return 0;
613
0
    }
614
615
7.01k
    StreamState* stream = self->FindStream(stream_id);
616
7.01k
    if (stream == nullptr || offset > UINT64_MAX - length) {
617
0
      return NGTCP2_ERR_CALLBACK_FAILURE;
618
0
    }
619
620
7.01k
    if (length == 0) {
621
0
      if (stream->next_managed_fin_offset < stream->managed_fin_offsets.size() &&
622
0
          stream->managed_fin_offsets[stream->next_managed_fin_offset] == offset) {
623
0
        ++stream->next_managed_fin_offset;
624
0
        if (nghttp3_conn_add_ack_offset(self->http3_connection_, stream_id, 0) != 0) {
625
0
          self->http3_failed_ = true;
626
0
          return NGTCP2_ERR_CALLBACK_FAILURE;
627
0
        }
628
0
      }
629
0
      return 0;
630
0
    }
631
632
7.01k
    const std::uint64_t end = offset + length;
633
7.01k
    std::uint64_t managed_length = 0;
634
13.6k
    for (std::size_t index = stream->next_managed_ack_range; index < stream->managed_write_ranges.size(); ++index) {
635
7.03k
      const StreamState::ManagedWriteRange& range = stream->managed_write_ranges[index];
636
7.03k
      if (range.end <= offset) {
637
0
        stream->next_managed_ack_range = index + 1;
638
0
        continue;
639
0
      }
640
7.03k
      if (range.begin >= end) {
641
383
        break;
642
383
      }
643
6.65k
      managed_length += std::min(range.end, end) - std::max(range.begin, offset);
644
6.65k
      if (range.end <= end) {
645
6.65k
        stream->next_managed_ack_range = index + 1;
646
6.65k
      }
647
6.65k
    }
648
649
7.01k
    if (managed_length != 0 && nghttp3_conn_add_ack_offset(self->http3_connection_, stream_id, managed_length) != 0) {
650
0
      self->http3_failed_ = true;
651
0
      return NGTCP2_ERR_CALLBACK_FAILURE;
652
0
    }
653
7.01k
    return 0;
654
7.01k
  }
655
656
  // Keep nghttp3's stream lifecycle synchronized with QUIC resets, STOP_SENDING
657
  // events, and close error-code flags.
658
  static int CloseQuicStream(ngtcp2_conn* /*connection*/, std::uint32_t flags, std::int64_t stream_id,
659
                             std::uint64_t receive_error_code, std::uint64_t transmit_error_code, void* user_data,
660
54
                             void* /*stream_user_data*/) {
661
54
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
662
54
    if (self == nullptr || self->http3_connection_ == nullptr || self->http3_failed_) {
663
0
      return 0;
664
0
    }
665
54
    std::uint32_t http3_flags = NGHTTP3_STREAM_CLOSE_FLAG_NONE;
666
54
    if ((flags & NGTCP2_STREAM_CLOSE2_FLAG_RX_APP_ERROR_CODE_SET) != 0) {
667
5
      http3_flags |= NGHTTP3_STREAM_CLOSE_FLAG_RX_APP_ERROR_CODE_SET;
668
5
    }
669
54
    if ((flags & NGTCP2_STREAM_CLOSE2_FLAG_TX_APP_ERROR_CODE_SET) != 0) {
670
12
      http3_flags |= NGHTTP3_STREAM_CLOSE_FLAG_TX_APP_ERROR_CODE_SET;
671
12
    }
672
54
    const int result = nghttp3_conn_close_stream2(self->http3_connection_, http3_flags, stream_id, receive_error_code,
673
54
                                                  transmit_error_code);
674
54
    if (result != 0 && result != NGHTTP3_ERR_STREAM_NOT_FOUND) {
675
0
      self->http3_failed_ = true;
676
0
      return NGTCP2_ERR_CALLBACK_FAILURE;
677
0
    }
678
54
    return 0;
679
54
  }
680
681
  static int ResetQuicStream(ngtcp2_conn* /*connection*/, std::int64_t stream_id, std::uint64_t /*final_size*/,
682
7
                             std::uint64_t /*application_error_code*/, void* user_data, void* /*stream_user_data*/) {
683
7
    return ShutdownHttp3StreamRead(stream_id, user_data);
684
7
  }
685
686
  static int StopSendingQuicStream(ngtcp2_conn* /*connection*/, std::int64_t stream_id,
687
                                   std::uint64_t /*application_error_code*/, void* user_data,
688
0
                                   void* /*stream_user_data*/) {
689
0
    return ShutdownHttp3StreamRead(stream_id, user_data);
690
0
  }
691
692
7
  static int ShutdownHttp3StreamRead(std::int64_t stream_id, void* user_data) {
693
7
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
694
7
    if (self == nullptr || self->http3_connection_ == nullptr || self->http3_failed_) {
695
0
      return 0;
696
0
    }
697
7
    const int result = nghttp3_conn_shutdown_stream_read(self->http3_connection_, stream_id);
698
7
    if (result != 0 && result != NGHTTP3_ERR_STREAM_NOT_FOUND) {
699
0
      self->http3_failed_ = true;
700
0
      return NGTCP2_ERR_CALLBACK_FAILURE;
701
0
    }
702
7
    return 0;
703
7
  }
704
705
  // Create HTTP/3 once the QUIC handshake can carry application traffic.
706
  // Dynamic QPACK is intentionally disabled so scenarios cannot retain table
707
  // state beyond the bounded peer lifetime.
708
1.96k
  bool CreateHttp3Connection() {
709
1.96k
    if (http3_connection_ != nullptr) {
710
0
      return true;
711
0
    }
712
1.96k
    nghttp3_callbacks callbacks = {};
713
1.96k
    callbacks.recv_data = &ReceiveRequestData;
714
1.96k
    callbacks.deferred_consume = &DeferredConsumeRequestData;
715
1.96k
    callbacks.end_headers = &EndRequestHeaders;
716
1.96k
    callbacks.end_stream = &EndRequestStream;
717
1.96k
    nghttp3_settings settings;
718
1.96k
    nghttp3_settings_default(&settings);
719
1.96k
    settings.qpack_max_dtable_capacity = 0;
720
1.96k
    settings.qpack_encoder_max_dtable_capacity = 0;
721
1.96k
    settings.qpack_blocked_streams = 0;
722
1.96k
    if (nghttp3_conn_server_new(&http3_connection_, &callbacks, &settings, nullptr, this) != 0) {
723
0
      http3_failed_ = true;
724
0
      return false;
725
0
    }
726
1.96k
    nghttp3_conn_set_max_concurrent_streams(http3_connection_, kMaxStreams);
727
1.96k
    return true;
728
1.96k
  }
729
730
  // QUIC needs unpredictable-looking connection IDs and reset tokens, but
731
  // fuzzing needs deterministic reruns. This local generator is not used for
732
  // cryptographic secrecy.
733
13.7k
  void FillRandom(std::uint8_t* destination, std::size_t length) {
734
13.7k
    std::uint64_t state = ++random_counter_ * UINT64_C(0x9e3779b97f4a7c15);
735
151k
    for (std::size_t index = 0; index < length; ++index) {
736
137k
      state ^= state >> 12U;
737
137k
      state ^= state << 25U;
738
137k
      state ^= state >> 27U;
739
137k
      destination[index] = static_cast<std::uint8_t>((state * UINT64_C(0x2545f4914f6cdd1d)) >> 56U);
740
137k
    }
741
13.7k
  }
742
743
  // The first valid Initial establishes the sole remote endpoint. Construct
744
  // all three protocol layers here because ngtcp2's crypto callbacks need a
745
  // live server-side SSL object while processing this packet.
746
1.96k
  bool InitializeConnection(const ngtcp2_pkt_hd& header, const struct sockaddr_in& remote_address) {
747
1.96k
    if (quic_connection_ != nullptr || header.type != NGTCP2_PKT_INITIAL) {
748
0
      return false;
749
0
    }
750
751
1.96k
    remote_address_ = remote_address;
752
1.96k
    ngtcp2_path_storage_init(&path_storage_, reinterpret_cast<const ngtcp2_sockaddr*>(&local_address_),
753
1.96k
                             sizeof(local_address_), reinterpret_cast<const ngtcp2_sockaddr*>(&remote_address_),
754
1.96k
                             sizeof(remote_address_), nullptr);
755
756
1.96k
    ngtcp2_callbacks callbacks = {};
757
1.96k
    callbacks.recv_client_initial = ngtcp2_crypto_recv_client_initial_cb;
758
1.96k
    callbacks.recv_crypto_data = ngtcp2_crypto_recv_crypto_data_cb;
759
1.96k
    callbacks.handshake_completed = &HandshakeCompleted;
760
1.96k
    callbacks.encrypt = ngtcp2_crypto_encrypt_cb;
761
1.96k
    callbacks.decrypt = ngtcp2_crypto_decrypt_cb;
762
1.96k
    callbacks.hp_mask = ngtcp2_crypto_hp_mask_cb;
763
1.96k
    callbacks.recv_stream_data = &ReceiveQuicStreamData;
764
1.96k
    callbacks.acked_stream_data_offset = &AckedStreamDataOffset;
765
1.96k
    callbacks.stream_open = &OpenRemoteStream;
766
1.96k
    callbacks.stream_reset = &ResetQuicStream;
767
1.96k
    callbacks.rand = &GenerateRandomBytes;
768
1.96k
    callbacks.update_key = ngtcp2_crypto_update_key_cb;
769
1.96k
    callbacks.delete_crypto_aead_ctx = ngtcp2_crypto_delete_crypto_aead_ctx_cb;
770
1.96k
    callbacks.delete_crypto_cipher_ctx = ngtcp2_crypto_delete_crypto_cipher_ctx_cb;
771
1.96k
    callbacks.stream_stop_sending = &StopSendingQuicStream;
772
1.96k
    callbacks.version_negotiation = ngtcp2_crypto_version_negotiation_cb;
773
1.96k
    callbacks.recv_tx_key = &ReceiveTransmitKey;
774
1.96k
    callbacks.get_new_connection_id2 = &GetNewConnectionId;
775
1.96k
    callbacks.get_path_challenge_data2 = ngtcp2_crypto_get_path_challenge_data2_cb;
776
1.96k
    callbacks.stream_close2 = &CloseQuicStream;
777
778
1.96k
    ngtcp2_settings settings;
779
1.96k
    ngtcp2_settings_default(&settings);
780
1.96k
    settings.initial_ts = QuicNow();
781
1.96k
    settings.rand_ctx.native_handle = this;
782
1.96k
    settings.no_pmtud = 1;
783
1.96k
    settings.max_tx_udp_payload_size = packet_buffer_.size();
784
785
1.96k
    ngtcp2_transport_params parameters;
786
1.96k
    ngtcp2_transport_params_default(&parameters);
787
1.96k
    parameters.initial_max_stream_data_bidi_local = kMaxPendingPlaintextBytes;
788
    // From the server's view, curl opens the remote bidirectional streams.
789
    // Keep the normal receive window on the unidirectional control and QPACK streams.
790
1.96k
    parameters.initial_max_stream_data_bidi_remote =
791
1.96k
        scenario_ != nullptr && scenario_->http3_plan().small_upload_window()
792
1.96k
            ? scenario_limits::kHttp3SmallUploadWindowBytes
793
1.96k
            : kMaxPendingPlaintextBytes;
794
1.96k
    parameters.initial_max_stream_data_uni = kMaxPendingPlaintextBytes;
795
1.96k
    parameters.initial_max_data = kMaxPendingPlaintextBytes * 4U;
796
1.96k
    parameters.initial_max_streams_bidi = kMaxStreams;
797
1.96k
    parameters.initial_max_streams_uni = kMaxStreams;
798
1.96k
    parameters.max_idle_timeout = 5U * NGTCP2_SECONDS;
799
1.96k
    parameters.active_connection_id_limit = 2;
800
1.96k
    parameters.original_dcid = header.dcid;
801
1.96k
    parameters.original_dcid_present = 1;
802
803
1.96k
    ngtcp2_cid server_cid = {};
804
1.96k
    server_cid.datalen = kServerConnectionIdBytes;
805
1.96k
    FillRandom(server_cid.data, server_cid.datalen);
806
1.96k
    if (ngtcp2_conn_server_new(&quic_connection_, &header.scid, &server_cid, &path_storage_.path, header.version,
807
1.96k
                               &callbacks, &settings, &parameters, nullptr, this) != 0) {
808
0
      return false;
809
0
    }
810
811
1.96k
    if (ngtcp2_crypto_ossl_ctx_new(&crypto_context_, nullptr) != 0) {
812
0
      return false;
813
0
    }
814
1.96k
    tls_connection_ = SSL_new(context_);
815
1.96k
    if (tls_connection_ == nullptr) {
816
0
      return false;
817
0
    }
818
1.96k
    ngtcp2_crypto_ossl_ctx_set_ssl(crypto_context_, tls_connection_);
819
1.96k
    if (ngtcp2_crypto_ossl_configure_server_session(tls_connection_) != 0) {
820
0
      return false;
821
0
    }
822
1.96k
    SSL_set_app_data(tls_connection_, &crypto_connection_ref_);
823
1.96k
    SSL_set_accept_state(tls_connection_);
824
1.96k
    ngtcp2_conn_set_tls_native_handle(quic_connection_, crypto_context_);
825
1.96k
    return true;
826
1.96k
  }
827
828
  // Drain a bounded datagram batch. Before connection setup, accept only a
829
  // valid QUIC Initial; afterwards, ignore packets from other UDP endpoints.
830
43.0k
  std::size_t ReadDatagrams() {
831
43.0k
    std::size_t progress = 0;
832
62.4k
    for (std::size_t packet = 0; packet < kMaxDatagramsPerTurn; ++packet) {
833
62.4k
      struct sockaddr_in remote_address = {};
834
62.4k
      socklen_t remote_length = sizeof(remote_address);
835
62.4k
      const ssize_t received = ::recvfrom(server_fd_, receive_buffer_.data(), receive_buffer_.size(), 0,
836
62.4k
                                          reinterpret_cast<struct sockaddr*>(&remote_address), &remote_length);
837
62.4k
      if (received < 0) {
838
42.9k
        if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) {
839
0
          transport_failed_ = true;
840
0
        }
841
42.9k
        break;
842
42.9k
      }
843
19.5k
      if (received == 0 || remote_length != sizeof(remote_address) || remote_address.sin_family != AF_INET) {
844
0
        continue;
845
0
      }
846
19.5k
      ++progress;
847
848
19.5k
      if (quic_connection_ == nullptr) {
849
1.96k
        ngtcp2_pkt_hd header = {};
850
1.96k
        if (ngtcp2_accept(&header, receive_buffer_.data(), static_cast<std::size_t>(received)) != 0) {
851
0
          continue;
852
0
        }
853
1.96k
        if (!InitializeConnection(header, remote_address)) {
854
0
          transport_failed_ = true;
855
0
          return progress;
856
0
        }
857
17.5k
      } else if (remote_address.sin_port != remote_address_.sin_port ||
858
17.5k
                 remote_address.sin_addr.s_addr != remote_address_.sin_addr.s_addr) {
859
0
        continue;
860
0
      }
861
862
19.5k
      ngtcp2_pkt_info packet_info = {};
863
19.5k
      const int result = ngtcp2_conn_read_pkt(quic_connection_, &path_storage_.path, &packet_info,
864
19.5k
                                              receive_buffer_.data(), static_cast<std::size_t>(received), QuicNow());
865
19.5k
      if (result != 0) {
866
72
        transport_failed_ = true;
867
72
        return progress;
868
72
      }
869
19.5k
    }
870
42.9k
    return progress;
871
43.0k
  }
872
873
  // ngtcp2 timers can make handshake, loss-recovery, or close packets ready
874
  // even when curl has not sent a new UDP datagram this turn.
875
43.0k
  std::size_t HandleExpiry() {
876
43.0k
    if (quic_connection_ == nullptr) {
877
1.97k
      return 0;
878
1.97k
    }
879
41.0k
    const ngtcp2_tstamp now = QuicNow();
880
41.0k
    if (ngtcp2_conn_get_expiry2(quic_connection_) > now) {
881
37.1k
      return 0;
882
37.1k
    }
883
3.92k
    const int result = ngtcp2_conn_handle_expiry(quic_connection_, now);
884
3.92k
    if (result != 0) {
885
0
      transport_failed_ = true;
886
0
    }
887
3.92k
    return 1;
888
41.0k
  }
889
890
  // A nonblocking socket can defer a packet without making the peer invalid.
891
  // Hard send errors are terminal because no later turn can repair the path.
892
14.1k
  bool SendPacket(const ngtcp2_path& path, const std::uint8_t* data, std::size_t length) {
893
14.1k
    const ngtcp2_addr* destination = &path.remote;
894
14.1k
    if (destination->addr == nullptr || destination->addrlen == 0) {
895
0
      destination = &path_storage_.path.remote;
896
0
    }
897
14.1k
    const ssize_t sent = ::sendto(server_fd_, data, length, 0,
898
14.1k
                                  reinterpret_cast<const struct sockaddr*>(destination->addr), destination->addrlen);
899
14.1k
    if (sent == static_cast<ssize_t>(length)) {
900
14.1k
      return true;
901
14.1k
    }
902
0
    if (sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) {
903
0
      return false;
904
0
    }
905
0
    transport_failed_ = true;
906
0
    return false;
907
0
  }
908
909
  // Serialize all QUIC control traffic after application writes. A requested
910
  // CONNECTION_CLOSE takes priority and is emitted at most once.
911
42.9k
  std::size_t FlushTransportPackets() {
912
42.9k
    if (quic_connection_ == nullptr || transport_failed_ || close_sent_) {
913
322
      return 0;
914
322
    }
915
916
42.6k
    if (close_requested_) {
917
325
      ngtcp2_ccerr error;
918
325
      ngtcp2_ccerr_default(&error);
919
325
      ngtcp2_ccerr_set_application_error(&error, close_error_code_, nullptr, 0);
920
325
      ngtcp2_path_storage output_path;
921
325
      ngtcp2_path_storage_zero(&output_path);
922
325
      ngtcp2_pkt_info packet_info = {};
923
325
      const ngtcp2_tstamp now = QuicNow();
924
325
      const ngtcp2_ssize written = ngtcp2_conn_write_connection_close(
925
325
          quic_connection_, &output_path.path, &packet_info, packet_buffer_.data(), packet_buffer_.size(), &error, now);
926
325
      if (written < 0) {
927
0
        transport_failed_ = true;
928
0
        return 0;
929
0
      }
930
325
      close_sent_ = true;
931
325
      if (written == 0) {
932
0
        return 1;
933
0
      }
934
325
      ngtcp2_conn_update_pkt_tx_time(quic_connection_, now);
935
325
      (void)SendPacket(output_path.path, packet_buffer_.data(), static_cast<std::size_t>(written));
936
325
      return 1;
937
325
    }
938
939
42.3k
    std::size_t progress = 0;
940
48.4k
    for (std::size_t packet = 0; packet < kMaxWritesPerTurn; ++packet) {
941
48.4k
      ngtcp2_path_storage output_path;
942
48.4k
      ngtcp2_path_storage_zero(&output_path);
943
48.4k
      ngtcp2_pkt_info packet_info = {};
944
48.4k
      const ngtcp2_tstamp now = QuicNow();
945
48.4k
      const ngtcp2_ssize written = ngtcp2_conn_write_pkt(quic_connection_, &output_path.path, &packet_info,
946
48.4k
                                                         packet_buffer_.data(), packet_buffer_.size(), now);
947
48.4k
      if (written < 0) {
948
0
        transport_failed_ = true;
949
0
        break;
950
0
      }
951
48.4k
      if (written == 0) {
952
42.3k
        break;
953
42.3k
      }
954
6.13k
      ngtcp2_conn_update_pkt_tx_time(quic_connection_, now);
955
6.13k
      if (!SendPacket(output_path.path, packet_buffer_.data(), static_cast<std::size_t>(written))) {
956
0
        break;
957
0
      }
958
6.13k
      ++progress;
959
6.13k
    }
960
42.3k
    return progress;
961
42.6k
  }
962
963
  // HTTP/3 requires one control stream and two QPACK streams before it can
964
  // send response metadata. Their stream IDs are retained by role so script
965
  // actions can target them without exposing transport-chosen IDs.
966
40.7k
  std::size_t CreateServerStreams() {
967
40.7k
    if (server_streams_bound_ || quic_connection_ == nullptr || http3_connection_ == nullptr || http3_failed_) {
968
38.7k
      return 0;
969
38.7k
    }
970
971
1.96k
    std::size_t progress = 0;
972
1.96k
    const std::array<StreamRoleIndex, 3> roles = {kControlStream, kQpackEncoderStream, kQpackDecoderStream};
973
5.90k
    for (const StreamRoleIndex role : roles) {
974
5.90k
      if (role_stream_ids_[role] != kNoStreamId) {
975
0
        continue;
976
0
      }
977
5.90k
      const std::int64_t stream_id = OpenUnidirectionalStream();
978
5.90k
      if (stream_id == kNoStreamId) {
979
0
        return progress;
980
0
      }
981
5.90k
      role_stream_ids_[role] = stream_id;
982
5.90k
      ++progress;
983
5.90k
    }
984
985
1.96k
    if (role_stream_ids_[kControlStream] == kNoStreamId || role_stream_ids_[kQpackEncoderStream] == kNoStreamId ||
986
1.96k
        role_stream_ids_[kQpackDecoderStream] == kNoStreamId) {
987
0
      return progress;
988
0
    }
989
1.96k
    if (nghttp3_conn_bind_qpack_streams(http3_connection_, role_stream_ids_[kQpackEncoderStream],
990
1.96k
                                        role_stream_ids_[kQpackDecoderStream]) != 0 ||
991
1.96k
        nghttp3_conn_bind_control_stream(http3_connection_, role_stream_ids_[kControlStream]) != 0) {
992
0
      http3_failed_ = true;
993
0
      return progress;
994
0
    }
995
1.96k
    server_streams_bound_ = true;
996
1.96k
    return progress + 1;
997
1.96k
  }
998
999
6.28k
  std::int64_t OpenUnidirectionalStream() {
1000
6.28k
    if (quic_connection_ == nullptr || streams_.size() >= kMaxStreams) {
1001
0
      return kNoStreamId;
1002
0
    }
1003
6.28k
    std::int64_t stream_id = kNoStreamId;
1004
6.28k
    if (ngtcp2_conn_open_uni_stream(quic_connection_, &stream_id, nullptr) != 0) {
1005
385
      return kNoStreamId;
1006
385
    }
1007
1008
5.90k
    StreamState state;
1009
5.90k
    state.id = stream_id;
1010
5.90k
    streams_.push_back(state);
1011
5.90k
    return stream_id;
1012
6.28k
  }
1013
1014
  // Advance protocol-generated output before one scenario action. This keeps
1015
  // QPACK/control bytes causally ahead of raw writes and makes each turn's
1016
  // work bounded even when the client is blocked.
1017
38.7k
  std::size_t DriveApplicationOutput() {
1018
38.7k
    std::size_t progress = 0;
1019
1020
38.7k
    if (pending_write_.active()) {
1021
871
      const bool completes_action = pending_write_.completes_action;
1022
871
      const WriteResult result = FlushPendingWrite(&progress);
1023
871
      if (result == WriteResult::kBlocked) {
1024
208
        return progress;
1025
208
      }
1026
663
      if (result == WriteResult::kFailed && transport_failed_) {
1027
0
        return progress;
1028
0
      }
1029
663
      if (completes_action) {
1030
621
        ++next_action_;
1031
621
        return progress + 1;
1032
621
      }
1033
42
      if (result == WriteResult::kFailed && waiting_for_h3_drain_) {
1034
0
        waiting_for_h3_drain_ = false;
1035
0
        if (waiting_drain_completes_action_) {
1036
0
          ++next_action_;
1037
0
        }
1038
0
        return progress + 1;
1039
0
      }
1040
42
    }
1041
1042
37.9k
    if (!server_streams_bound_) {
1043
0
      return progress;
1044
0
    }
1045
37.9k
    if (!bootstrap_drained_) {
1046
1.94k
      if (http3_failed_ || PumpNghttp3(&progress)) {
1047
1.94k
        bootstrap_drained_ = true;
1048
1.94k
        ++progress;
1049
1.94k
      }
1050
1.94k
      return progress;
1051
1.94k
    }
1052
35.9k
    if (waiting_for_h3_drain_) {
1053
1.23k
      if (http3_failed_ || PumpNghttp3(&progress)) {
1054
1.19k
        waiting_for_h3_drain_ = false;
1055
1.19k
        if (waiting_drain_completes_action_) {
1056
1.19k
          ++next_action_;
1057
1.19k
        }
1058
1.19k
        waiting_drain_completes_action_ = false;
1059
1.19k
        ++progress;
1060
1.19k
      }
1061
1.23k
      return progress;
1062
1.23k
    }
1063
1064
    // Reading a request can produce QPACK decoder instructions independently
1065
    // of a response action. Keep those ahead of script-controlled raw writes.
1066
34.7k
    if (!http3_failed_ && !PumpNghttp3(&progress)) {
1067
0
      return progress;
1068
0
    }
1069
34.7k
    if (transport_failed_) {
1070
0
      return progress;
1071
0
    }
1072
1073
34.7k
    const bool waiting_for_upload =
1074
34.7k
        scenario_ != nullptr && scenario_->http3_plan().small_upload_window() && !request_stream_finished_;
1075
34.7k
    const std::size_t action_count =
1076
34.7k
        scenario_ == nullptr
1077
34.7k
            ? 0
1078
34.7k
            : std::min<std::size_t>(scenario_limits::kMaxHttp3Actions, scenario_->http3_plan().actions_size());
1079
34.7k
    if (next_action_ >= action_count) {
1080
      // An empty H3 plan still needs one successful response after a request.
1081
31.8k
      if (action_count == 0 && !default_response_started_ && request_headers_received_ && !waiting_for_upload) {
1082
0
        default_response_started_ = true;
1083
0
        if (SubmitStructuredResponse(default_response_)) {
1084
0
          waiting_for_h3_drain_ = true;
1085
0
          waiting_drain_completes_action_ = false;
1086
0
          ++progress;
1087
0
        }
1088
0
      }
1089
31.8k
      return progress;
1090
31.8k
    }
1091
1092
2.95k
    const auto& action = scenario_->http3_plan().actions(static_cast<int>(next_action_));
1093
    // If curl sends Expect: 100-continue, it waits for the interim response
1094
    // before sending the body. Let the next informational response through.
1095
    // Leave other actions queued in order until the request stream ends.
1096
2.95k
    if (waiting_for_upload && (!action.has_structured_response() ||
1097
0
                               NormalizeResponseStatus(action.structured_response().status_code()) >= 200U)) {
1098
0
      return progress;
1099
0
    }
1100
2.95k
    if (action.has_structured_response()) {
1101
1.37k
      if (!request_headers_received_) {
1102
0
        return progress;
1103
0
      }
1104
1.37k
      if (SubmitStructuredResponse(action.structured_response())) {
1105
1.20k
        waiting_for_h3_drain_ = true;
1106
1.20k
        waiting_drain_completes_action_ = true;
1107
1.20k
      } else {
1108
176
        ++next_action_;
1109
176
      }
1110
1.37k
      return progress + 1;
1111
1.37k
    }
1112
1113
1.57k
    if (action.has_stream_write()) {
1114
364
      const auto& write = action.stream_write();
1115
364
      const std::int64_t stream_id = StreamForRole(write.role());
1116
364
      if (stream_id == kNoStreamId) {
1117
0
        return progress;
1118
0
      }
1119
364
      const std::size_t length = std::min<std::size_t>(scenario_limits::kMaxHttp3RawWriteBytes, write.data().size());
1120
364
      QueueWrite(stream_id, write.data().substr(0, length), write.finish_stream(), false, true);
1121
364
      return progress + 1;
1122
364
    }
1123
1124
1.21k
    if (action.has_open_unidirectional_stream()) {
1125
385
      const auto& open = action.open_unidirectional_stream();
1126
385
      const std::int64_t stream_id = OpenUnidirectionalStream();
1127
385
      if (stream_id == kNoStreamId) {
1128
385
        ++next_action_;
1129
385
        return progress + 1;
1130
385
      }
1131
0
      const std::size_t length = std::min<std::size_t>(scenario_limits::kMaxHttp3RawWriteBytes, open.data().size());
1132
0
      QueueWrite(stream_id, open.data().substr(0, length), open.finish_stream(), false, true);
1133
0
      return progress + 1;
1134
385
    }
1135
1136
826
    if (action.has_stream_reset()) {
1137
211
      const auto& reset = action.stream_reset();
1138
211
      const std::int64_t stream_id = StreamForRole(reset.role());
1139
211
      if (stream_id == kNoStreamId) {
1140
0
        return progress;
1141
0
      }
1142
211
      (void)ngtcp2_conn_shutdown_stream_write(quic_connection_, 0, stream_id,
1143
211
                                              reset.application_error_code() & scenario_limits::kMaxQuicVarint);
1144
211
      ++next_action_;
1145
211
      return progress + 1;
1146
211
    }
1147
1148
615
    if (action.has_goaway()) {
1149
290
      const std::int64_t control_stream_id = StreamForRole(curl::fuzzer::proto::HTTP3_STREAM_CONTROL);
1150
290
      if (control_stream_id == kNoStreamId) {
1151
0
        return progress;
1152
0
      }
1153
      // HTTP/3 GOAWAY is a raw control-stream frame so its identifier remains
1154
      // directly mutation-controlled instead of being selected by nghttp3.
1155
290
      std::string payload;
1156
290
      AppendQuicVarint(&payload, action.goaway().id());
1157
290
      std::string frame;
1158
290
      AppendQuicVarint(&frame, 0x07U);
1159
290
      AppendQuicVarint(&frame, payload.size());
1160
290
      frame.append(payload);
1161
290
      QueueWrite(control_stream_id, std::move(frame), false, false, true);
1162
290
      return progress + 1;
1163
290
    }
1164
1165
325
    if (action.has_connection_close()) {
1166
325
      close_error_code_ = action.connection_close().application_error_code() & scenario_limits::kMaxQuicVarint;
1167
325
      close_requested_ = true;
1168
325
      ++next_action_;
1169
325
      return progress + 1;
1170
325
    }
1171
1172
0
    ++next_action_;
1173
0
    return progress + 1;
1174
325
  }
1175
1176
  // Retain script and nghttp3 bytes until ngtcp2 accepts their full prefix.
1177
  // Only one pending write exists, preserving ordering between action types.
1178
  void QueueWrite(std::int64_t stream_id, std::string bytes, bool finish_stream, bool nghttp3_managed,
1179
7.78k
                  bool completes_action) {
1180
7.78k
    retained_writes_.push_back(std::make_unique<std::string>(std::move(bytes)));
1181
7.78k
    pending_write_.stream_id = stream_id;
1182
7.78k
    pending_write_.bytes = retained_writes_.back().get();
1183
7.78k
    pending_write_.offset = 0;
1184
7.78k
    pending_write_.finish_stream = finish_stream;
1185
7.78k
    pending_write_.nghttp3_managed = nghttp3_managed;
1186
7.78k
    pending_write_.completes_action = completes_action;
1187
7.78k
  }
1188
1189
  // Packetize one prefix through ngtcp2. For nghttp3-managed output, record
1190
  // the exact submitted offsets so its acknowledgement accounting can exclude
1191
  // interleaved raw writes on the same QUIC stream.
1192
8.00k
  WriteResult FlushPendingWrite(std::size_t* progress) {
1193
8.00k
    if (!pending_write_.active()) {
1194
0
      return WriteResult::kComplete;
1195
0
    }
1196
1197
8.00k
    if (pending_write_.bytes == nullptr || pending_write_.offset > pending_write_.bytes->size()) {
1198
0
      pending_write_.Clear();
1199
0
      return WriteResult::kFailed;
1200
0
    }
1201
1202
8.00k
    const std::size_t remaining = pending_write_.bytes->size() - pending_write_.offset;
1203
8.00k
    if (remaining == 0 && !pending_write_.finish_stream) {
1204
268
      pending_write_.Clear();
1205
268
      ++*progress;
1206
268
      return WriteResult::kComplete;
1207
268
    }
1208
1209
7.73k
    ngtcp2_vec vector = {};
1210
7.73k
    vector.base =
1211
7.73k
        reinterpret_cast<std::uint8_t*>(const_cast<char*>(pending_write_.bytes->data() + pending_write_.offset));
1212
7.73k
    vector.len = remaining;
1213
7.73k
    const std::size_t vector_count = remaining == 0 ? 0 : 1;
1214
7.73k
    const std::uint32_t flags =
1215
7.73k
        pending_write_.finish_stream ? NGTCP2_WRITE_STREAM_FLAG_FIN : NGTCP2_WRITE_STREAM_FLAG_NONE;
1216
7.73k
    ngtcp2_path_storage output_path;
1217
7.73k
    ngtcp2_path_storage_zero(&output_path);
1218
7.73k
    ngtcp2_pkt_info packet_info = {};
1219
7.73k
    ngtcp2_ssize submitted = -1;
1220
7.73k
    const ngtcp2_tstamp now = QuicNow();
1221
7.73k
    const ngtcp2_ssize packet_length = ngtcp2_conn_writev_stream(
1222
7.73k
        quic_connection_, &output_path.path, &packet_info, packet_buffer_.data(), packet_buffer_.size(), &submitted,
1223
7.73k
        flags, pending_write_.stream_id, vector_count == 0 ? nullptr : &vector, vector_count, now);
1224
7.73k
    if (packet_length == NGTCP2_ERR_STREAM_DATA_BLOCKED) {
1225
0
      return WriteResult::kBlocked;
1226
0
    }
1227
7.73k
    if (packet_length == NGTCP2_ERR_STREAM_SHUT_WR || packet_length == NGTCP2_ERR_STREAM_NOT_FOUND) {
1228
0
      pending_write_.Clear();
1229
0
      return WriteResult::kFailed;
1230
0
    }
1231
7.73k
    if (packet_length < 0) {
1232
0
      transport_failed_ = true;
1233
0
      pending_write_.Clear();
1234
0
      return WriteResult::kFailed;
1235
0
    }
1236
7.73k
    if (packet_length == 0) {
1237
2
      return WriteResult::kBlocked;
1238
2
    }
1239
7.73k
    ngtcp2_conn_update_pkt_tx_time(quic_connection_, now);
1240
7.73k
    (void)SendPacket(output_path.path, packet_buffer_.data(), static_cast<std::size_t>(packet_length));
1241
7.73k
    ++*progress;
1242
7.73k
    if (transport_failed_) {
1243
0
      pending_write_.Clear();
1244
0
      return WriteResult::kFailed;
1245
0
    }
1246
1247
7.73k
    if (submitted >= 0) {
1248
7.73k
      StreamState* stream = FindStream(pending_write_.stream_id);
1249
7.73k
      if (stream == nullptr || static_cast<std::uint64_t>(submitted) > UINT64_MAX - stream->write_offset) {
1250
0
        transport_failed_ = true;
1251
0
        pending_write_.Clear();
1252
0
        return WriteResult::kFailed;
1253
0
      }
1254
7.73k
      const std::uint64_t write_begin = stream->write_offset;
1255
7.73k
      stream->write_offset += static_cast<std::uint64_t>(submitted);
1256
7.73k
      if (pending_write_.nghttp3_managed) {
1257
7.33k
        if (nghttp3_conn_add_write_offset(http3_connection_, pending_write_.stream_id,
1258
7.33k
                                          static_cast<std::uint64_t>(submitted)) != 0) {
1259
0
          http3_failed_ = true;
1260
0
          pending_write_.Clear();
1261
0
          return WriteResult::kFailed;
1262
0
        }
1263
7.33k
        if (submitted != 0) {
1264
7.33k
          stream->managed_write_ranges.push_back({write_begin, stream->write_offset});
1265
7.33k
        } else if (pending_write_.finish_stream && pending_write_.offset == pending_write_.bytes->size()) {
1266
0
          stream->managed_fin_offsets.push_back(write_begin);
1267
0
        }
1268
7.33k
      }
1269
7.73k
      pending_write_.offset += static_cast<std::size_t>(submitted);
1270
7.73k
    }
1271
7.73k
    if (submitted < 0 || pending_write_.offset != pending_write_.bytes->size()) {
1272
248
      return WriteResult::kBlocked;
1273
248
    }
1274
7.48k
    pending_write_.Clear();
1275
7.48k
    return WriteResult::kComplete;
1276
7.73k
  }
1277
1278
  // Let nghttp3 serialize response/control bytes, then feed each generated
1279
  // vector through the same QUIC write path as raw scenario data. Stop when a
1280
  // raw action is pending so it cannot be reordered behind generated output.
1281
37.9k
  bool PumpNghttp3(std::size_t* progress) {
1282
37.9k
    if (http3_connection_ == nullptr || http3_failed_) {
1283
0
      return true;
1284
0
    }
1285
1286
45.0k
    for (std::size_t operation = 0; operation < kMaxWritesPerTurn; ++operation) {
1287
45.0k
      if (pending_write_.active()) {
1288
7.13k
        if (!pending_write_.nghttp3_managed) {
1289
0
          return false;
1290
0
        }
1291
7.13k
        const WriteResult result = FlushPendingWrite(progress);
1292
7.13k
        if (result == WriteResult::kBlocked) {
1293
42
          return false;
1294
42
        }
1295
7.09k
        if (result == WriteResult::kFailed) {
1296
0
          http3_failed_ = true;
1297
0
          return true;
1298
0
        }
1299
7.09k
      }
1300
1301
45.0k
      std::array<nghttp3_vec, 16> vectors;
1302
45.0k
      std::int64_t stream_id = -1;
1303
45.0k
      int finish_stream = 0;
1304
45.0k
      const nghttp3_ssize vector_count =
1305
45.0k
          nghttp3_conn_writev_stream(http3_connection_, &stream_id, &finish_stream, vectors.data(), vectors.size());
1306
45.0k
      if (vector_count < 0) {
1307
0
        http3_failed_ = true;
1308
0
        return true;
1309
0
      }
1310
45.0k
      if (vector_count == 0 && stream_id == -1) {
1311
37.8k
        return true;
1312
37.8k
      }
1313
1314
7.13k
      StreamState* stream = FindStream(stream_id);
1315
7.13k
      if (stream == nullptr) {
1316
0
        http3_failed_ = true;
1317
0
        return true;
1318
0
      }
1319
1320
7.13k
      std::string bytes;
1321
7.13k
      if (vector_count > 0) {
1322
7.13k
        std::size_t total = 0;
1323
14.5k
        for (nghttp3_ssize index = 0; index < vector_count; ++index) {
1324
7.36k
          if (vectors[static_cast<std::size_t>(index)].len > kMaxPendingPlaintextBytes - total) {
1325
0
            http3_failed_ = true;
1326
0
            return true;
1327
0
          }
1328
7.36k
          total += vectors[static_cast<std::size_t>(index)].len;
1329
7.36k
        }
1330
7.13k
        bytes.reserve(total);
1331
14.5k
        for (nghttp3_ssize index = 0; index < vector_count; ++index) {
1332
7.36k
          const nghttp3_vec& vector = vectors[static_cast<std::size_t>(index)];
1333
7.36k
          bytes.append(reinterpret_cast<const char*>(vector.base), vector.len);
1334
7.36k
        }
1335
7.13k
      }
1336
1337
7.13k
      QueueWrite(stream->id, std::move(bytes), finish_stream != 0, true, false);
1338
7.13k
    }
1339
0
    return false;
1340
37.9k
  }
1341
1342
  // Convert a bounded schema response into nghttp3-owned fields and pull-based
1343
  // body state. Interim responses do not consume the single final response.
1344
1.37k
  bool SubmitStructuredResponse(const curl::fuzzer::proto::Http3Response& response) {
1345
1.37k
    if (http3_connection_ == nullptr || http3_failed_ || role_stream_ids_[kResponseStream] == kNoStreamId) {
1346
0
      return false;
1347
0
    }
1348
1349
1.37k
    const std::uint32_t status_code = NormalizeResponseStatus(response.status_code());
1350
1.37k
    std::vector<std::pair<std::string, std::string>> fields;
1351
1.37k
    fields.reserve(1 + std::min<std::size_t>(scenario_limits::kMaxHttp3Headers, response.response_headers_size()));
1352
1.37k
    fields.emplace_back(":status", std::to_string(status_code));
1353
1.37k
    AppendHeaders(&fields, response.response_headers(), scenario_limits::kMaxHttp3Headers);
1354
1.37k
    const std::vector<nghttp3_nv> name_values = MakeNameValues(fields);
1355
1.37k
    const std::int64_t response_stream_id = static_cast<std::int64_t>(role_stream_ids_[kResponseStream]);
1356
1357
1.37k
    if (status_code < 200U) {
1358
559
      return nghttp3_conn_submit_info(http3_connection_, response_stream_id, name_values.data(), name_values.size()) ==
1359
559
             0;
1360
559
    }
1361
817
    if (final_response_submitted_) {
1362
175
      return false;
1363
175
    }
1364
1365
642
    response_body_.chunks.clear();
1366
642
    response_body_.next_chunk = 0;
1367
642
    response_body_.finish_stream = response.finish_stream();
1368
642
    response_body_.has_trailers = response.response_trailers_size() != 0;
1369
642
    std::size_t body_bytes = 0;
1370
642
    const std::size_t body_chunks =
1371
642
        std::min<std::size_t>(scenario_limits::kMaxHttp3BodyChunks, response.body_chunks_size());
1372
642
    response_body_.chunks.reserve(body_chunks);
1373
828
    for (std::size_t index = 0; index < body_chunks && body_bytes < scenario_limits::kMaxHttp3BodyBytes; ++index) {
1374
186
      const std::string& source = response.body_chunks(static_cast<int>(index));
1375
186
      const std::size_t length = std::min(source.size(), scenario_limits::kMaxHttp3BodyBytes - body_bytes);
1376
186
      response_body_.chunks.emplace_back(source.data(), length);
1377
186
      body_bytes += length;
1378
186
    }
1379
1380
642
    nghttp3_data_reader reader = {};
1381
642
    reader.read_data = &ReadResponseBody;
1382
642
    if (nghttp3_conn_submit_response(http3_connection_, response_stream_id, name_values.data(), name_values.size(),
1383
642
                                     &reader) != 0) {
1384
1
      return false;
1385
1
    }
1386
641
    final_response_submitted_ = true;
1387
1388
641
    if (response_body_.has_trailers) {
1389
49
      std::vector<std::pair<std::string, std::string>> trailers;
1390
49
      trailers.reserve(std::min<std::size_t>(scenario_limits::kMaxHttp3Trailers, response.response_trailers_size()));
1391
49
      AppendHeaders(&trailers, response.response_trailers(), scenario_limits::kMaxHttp3Trailers);
1392
49
      const std::vector<nghttp3_nv> trailer_values = MakeNameValues(trailers);
1393
49
      if (nghttp3_conn_submit_trailers(http3_connection_, response_stream_id, trailer_values.data(),
1394
49
                                       trailer_values.size()) != 0) {
1395
0
        http3_failed_ = true;
1396
0
      }
1397
49
    }
1398
641
    return true;
1399
642
  }
1400
1401
  template <typename RepeatedHeaders>
1402
  static void AppendHeaders(std::vector<std::pair<std::string, std::string>>* destination,
1403
1.42k
                            const RepeatedHeaders& source, std::size_t count_limit) {
1404
1.42k
    std::size_t remaining = scenario_limits::kMaxHttp3HeaderBytes;
1405
1.42k
    const std::size_t count = std::min<std::size_t>(count_limit, source.size());
1406
2.88k
    for (std::size_t index = 0; index < count && remaining != 0; ++index) {
1407
1.45k
      std::string name = NormalizeHeaderName(source.Get(static_cast<int>(index)).name());
1408
1.45k
      std::string value = NormalizeHeaderValue(source.Get(static_cast<int>(index)).value());
1409
1.45k
      if (name.size() > remaining) {
1410
0
        name.resize(remaining);
1411
0
        value.clear();
1412
1.45k
      } else if (value.size() > remaining - name.size()) {
1413
0
        value.resize(remaining - name.size());
1414
0
      }
1415
1.45k
      remaining -= name.size() + value.size();
1416
1.45k
      destination->emplace_back(std::move(name), std::move(value));
1417
1.45k
    }
1418
1.42k
  }
1419
1420
1.42k
  static std::vector<nghttp3_nv> MakeNameValues(const std::vector<std::pair<std::string, std::string>>& fields) {
1421
1.42k
    std::vector<nghttp3_nv> name_values;
1422
1.42k
    name_values.reserve(fields.size());
1423
2.83k
    for (const auto& field : fields) {
1424
2.83k
      nghttp3_nv name_value = {};
1425
2.83k
      name_value.name = reinterpret_cast<std::uint8_t*>(const_cast<char*>(field.first.data()));
1426
2.83k
      name_value.value = reinterpret_cast<std::uint8_t*>(const_cast<char*>(field.second.data()));
1427
2.83k
      name_value.namelen = field.first.size();
1428
2.83k
      name_value.valuelen = field.second.size();
1429
2.83k
      name_value.flags = NGHTTP3_NV_FLAG_NONE;
1430
2.83k
      name_values.push_back(name_value);
1431
2.83k
    }
1432
1.42k
    return name_values;
1433
1.42k
  }
1434
1435
21.8k
  StreamState* FindStream(std::int64_t stream_id) {
1436
62.9k
    for (StreamState& stream : streams_) {
1437
62.9k
      if (stream.id == stream_id) {
1438
21.8k
        return &stream;
1439
21.8k
      }
1440
62.9k
    }
1441
0
    return nullptr;
1442
21.8k
  }
1443
1444
865
  std::int64_t StreamForRole(curl::fuzzer::proto::Http3StreamRole role) {
1445
865
    const int role_value = static_cast<int>(role);
1446
865
    if (role_value < 0 || role_value >= static_cast<int>(kStreamRoleCount)) {
1447
0
      return kNoStreamId;
1448
0
    }
1449
865
    return role_stream_ids_[static_cast<std::size_t>(role_value)];
1450
865
  }
1451
1452
  // nghttp3_conn_read_stream2 excludes DATA payload bytes from its consumed
1453
  // byte count. Return stream and connection credit for those bytes here.
1454
  static int ReceiveRequestData(nghttp3_conn* /*connection*/, std::int64_t stream_id, const std::uint8_t* /*data*/,
1455
2.93k
                                std::size_t data_length, void* user_data, void* /*stream_user_data*/) {
1456
2.93k
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
1457
2.93k
    if (self != nullptr && self->quic_connection_ != nullptr) {
1458
      // A turn can deliver several DATA callbacks. Count the turn once so
1459
      // fragmentation within a turn cannot satisfy the multi-turn test.
1460
2.93k
      if (data_length != 0 && self->last_request_body_turn_ != self->peer_turn_) {
1461
640
        ++self->request_body_turns_;
1462
640
        self->last_request_body_turn_ = self->peer_turn_;
1463
640
      }
1464
2.93k
      self->request_body_bytes_ += data_length;
1465
2.93k
      ngtcp2_conn_extend_max_stream_offset(self->quic_connection_, stream_id, data_length);
1466
2.93k
      ngtcp2_conn_extend_max_offset(self->quic_connection_, data_length);
1467
2.93k
    }
1468
2.93k
    return 0;
1469
2.93k
  }
1470
1471
  static int DeferredConsumeRequestData(nghttp3_conn* /*connection*/, std::int64_t stream_id, std::size_t consumed,
1472
0
                                        void* user_data, void* /*stream_user_data*/) {
1473
0
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
1474
0
    if (self != nullptr && self->quic_connection_ != nullptr) {
1475
0
      ngtcp2_conn_extend_max_stream_offset(self->quic_connection_, stream_id, consumed);
1476
0
      ngtcp2_conn_extend_max_offset(self->quic_connection_, consumed);
1477
0
    }
1478
0
    return 0;
1479
0
  }
1480
1481
  static int EndRequestHeaders(nghttp3_conn* /*connection*/, std::int64_t stream_id, int /*finish_stream*/,
1482
1.91k
                               void* user_data, void* /*stream_user_data*/) {
1483
1.91k
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
1484
1.91k
    if (self != nullptr) {
1485
1.91k
      if (self->role_stream_ids_[kResponseStream] == kNoStreamId) {
1486
0
        self->role_stream_ids_[kResponseStream] = stream_id;
1487
0
        if (self->FindStream(stream_id) == nullptr && self->streams_.size() < kMaxStreams) {
1488
0
          StreamState state;
1489
0
          state.id = stream_id;
1490
0
          self->streams_.push_back(state);
1491
0
        }
1492
0
      }
1493
1.91k
      if (self->role_stream_ids_[kResponseStream] == stream_id) {
1494
1.91k
        self->request_headers_received_ = true;
1495
1.91k
      }
1496
1.91k
    }
1497
1.91k
    return 0;
1498
1.91k
  }
1499
1500
  static int EndRequestStream(nghttp3_conn* /*connection*/, std::int64_t stream_id, void* user_data,
1501
1.88k
                              void* /*stream_user_data*/) {
1502
1.88k
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
1503
    // Only FIN on the request selected for the response releases the wait.
1504
    // Curl can finish that request before it uses all the scripted bytes.
1505
1.88k
    if (self != nullptr && self->role_stream_ids_[kResponseStream] == stream_id) {
1506
1.88k
      self->request_stream_finished_ = true;
1507
1.88k
    }
1508
1.88k
    return 0;
1509
1.88k
  }
1510
1511
  // nghttp3 pulls one schema body chunk per call. EOF may keep the stream open
1512
  // for trailers or a deliberate no-FIN response.
1513
  static nghttp3_ssize ReadResponseBody(nghttp3_conn* /*connection*/, std::int64_t /*stream_id*/, nghttp3_vec* vectors,
1514
                                        std::size_t vector_count, std::uint32_t* flags, void* user_data,
1515
736
                                        void* /*stream_user_data*/) {
1516
736
    auto* self = static_cast<Http3MockServerImpl*>(user_data);
1517
736
    if (self == nullptr || vectors == nullptr || vector_count == 0 || flags == nullptr) {
1518
0
      return NGHTTP3_ERR_CALLBACK_FAILURE;
1519
0
    }
1520
1521
772
    while (self->response_body_.next_chunk < self->response_body_.chunks.size() &&
1522
169
           self->response_body_.chunks[self->response_body_.next_chunk].empty()) {
1523
36
      ++self->response_body_.next_chunk;
1524
36
    }
1525
736
    if (self->response_body_.next_chunk == self->response_body_.chunks.size()) {
1526
603
      *flags = NGHTTP3_DATA_FLAG_EOF;
1527
603
      if (!self->response_body_.finish_stream && !self->response_body_.has_trailers) {
1528
76
        *flags |= NGHTTP3_DATA_FLAG_NO_END_STREAM;
1529
76
      }
1530
603
      return 0;
1531
603
    }
1532
1533
133
    const std::string& chunk = self->response_body_.chunks[self->response_body_.next_chunk++];
1534
133
    vectors[0].base = reinterpret_cast<std::uint8_t*>(const_cast<char*>(chunk.data()));
1535
133
    vectors[0].len = chunk.size();
1536
133
    *flags = NGHTTP3_DATA_FLAG_NONE;
1537
133
    if (self->response_body_.next_chunk == self->response_body_.chunks.size()) {
1538
35
      *flags |= NGHTTP3_DATA_FLAG_EOF;
1539
35
      if (!self->response_body_.finish_stream && !self->response_body_.has_trailers) {
1540
19
        *flags |= NGHTTP3_DATA_FLAG_NO_END_STREAM;
1541
19
      }
1542
35
    }
1543
133
    return 1;
1544
736
  }
1545
1546
  // Layer-owned transport state. The destruction order in ResetPeer mirrors
1547
  // these dependencies: HTTP/3, QUIC, TLS adapter, then TLS context/socket.
1548
  SSL_CTX* context_ = nullptr;
1549
  ngtcp2_conn* quic_connection_ = nullptr;
1550
  SSL* tls_connection_ = nullptr;
1551
  ngtcp2_crypto_ossl_ctx* crypto_context_ = nullptr;
1552
  ngtcp2_crypto_conn_ref crypto_connection_ref_;
1553
  nghttp3_conn* http3_connection_ = nullptr;
1554
  const curl::fuzzer::proto::Scenario* scenario_ = nullptr;
1555
  std::vector<StreamState> streams_;
1556
  std::vector<std::unique_ptr<std::string>> retained_writes_;
1557
  std::array<std::int64_t, kStreamRoleCount> role_stream_ids_;
1558
  PendingWrite pending_write_;
1559
  ResponseBodyState response_body_;
1560
  curl::fuzzer::proto::Http3Response default_response_;
1561
  ngtcp2_path_storage path_storage_ = {};
1562
  struct sockaddr_in local_address_ = {};
1563
  struct sockaddr_in remote_address_ = {};
1564
  std::array<std::uint8_t, kReceiveBufferBytes> receive_buffer_ = {};
1565
  std::array<std::uint8_t, NGTCP2_MAX_UDP_PAYLOAD_SIZE> packet_buffer_ = {};
1566
  std::uint64_t random_counter_ = 0;
1567
  std::uint64_t close_error_code_ = 0;
1568
  std::size_t next_action_ = 0;
1569
  std::size_t request_body_bytes_ = 0;
1570
  std::size_t request_body_turns_ = 0;
1571
  std::size_t last_request_body_turn_ = 0;
1572
  std::size_t peer_turn_ = 0;
1573
  int server_fd_ = -1;
1574
  std::uint16_t server_port_ = 0;
1575
  bool socket_opened_ = false;
1576
  bool handshake_complete_ = false;
1577
  bool request_headers_received_ = false;
1578
  bool request_stream_finished_ = false;
1579
  bool server_streams_bound_ = false;
1580
  bool bootstrap_drained_ = false;
1581
  bool waiting_for_h3_drain_ = false;
1582
  bool waiting_drain_completes_action_ = false;
1583
  bool final_response_submitted_ = false;
1584
  bool default_response_started_ = false;
1585
  bool http3_failed_ = false;
1586
  bool transport_failed_ = false;
1587
  bool close_requested_ = false;
1588
  bool close_sent_ = false;
1589
};
1590
1591
/// Construct a peer with the default checked-in EC certificate.
1592
0
Http3MockServer::Http3MockServer() : Http3MockServer(curl::fuzzer::proto::TLS_CERTIFICATE_CHAIN_DEFAULT_EC) {}
1593
1594
/// Construct a peer with a bounded, parseable certificate-chain profile.
1595
/// @param certificate_chain Certificate material presented during QUIC TLS.
1596
Http3MockServer::Http3MockServer(curl::fuzzer::proto::TlsCertificateChainProfile certificate_chain)
1597
2.28k
    : MockServerBase(MultiDrivePolicy::kSocketAction),
1598
2.28k
      impl_(std::make_unique<Http3MockServerImpl>(certificate_chain)) {}
1599
1600
2.28k
Http3MockServer::~Http3MockServer() = default;
1601
1602
/// Install UDP socket callbacks, the local trust anchor, and HTTP/3-only
1603
/// negotiation on an easy handle.
1604
/// @param easy Easy handle that will connect to the in-process QUIC peer.
1605
2.25k
void Http3MockServer::Install(CURL* easy) {
1606
  // Curl trusts the checked-in server certificate directly and must use HTTP/3
1607
  // rather than silently falling back to an HTTP/1 or HTTP/2 code path.
1608
2.25k
  MockServerBase::Install(easy);
1609
2.25k
  struct curl_blob trust_anchor = {const_cast<char*>(tls_test_credentials::kCertificatePem),
1610
2.25k
                                   sizeof(tls_test_credentials::kCertificatePem) - 1, CURL_BLOB_NOCOPY};
1611
2.25k
  (void)curl_easy_setopt(easy, CURLOPT_CAINFO_BLOB, &trust_anchor);
1612
2.25k
  (void)curl_easy_setopt(easy, CURLOPT_SSL_VERIFYPEER, 1L);
1613
2.25k
  (void)curl_easy_setopt(easy, CURLOPT_SSL_VERIFYHOST, 2L);
1614
2.25k
  (void)curl_easy_setopt(easy, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_3ONLY);
1615
2.25k
}
1616
1617
/// @return true after the server has completed a QUIC TLS handshake.
1618
2.25k
bool Http3MockServer::handshake_complete() const { return impl_ != nullptr && impl_->handshake_complete(); }
1619
1620
/// @return true after nghttp3 has decoded a complete request field section.
1621
2.25k
bool Http3MockServer::request_headers_received() const { return impl_ != nullptr && impl_->request_headers_received(); }
1622
1623
/// @return Total request body bytes received on the peer connection.
1624
0
std::size_t Http3MockServer::request_body_bytes() const { return impl_ == nullptr ? 0 : impl_->request_body_bytes(); }
1625
1626
/// @return Number of peer turns in which the connection received request body bytes.
1627
0
std::size_t Http3MockServer::request_body_turns() const { return impl_ == nullptr ? 0 : impl_->request_body_turns(); }
1628
1629
/// @return number of ordered Http3Action entries accepted by the peer.
1630
2.25k
std::size_t Http3MockServer::executed_action_count() const {
1631
2.25k
  return impl_ == nullptr ? 0 : impl_->executed_action_count();
1632
2.25k
}
1633
1634
/// @return kernel-selected UDP port in host byte order, or zero before use.
1635
2.25k
std::uint16_t Http3MockServer::server_port() const { return impl_ == nullptr ? 0 : impl_->server_port(); }
1636
1637
/// Create curl's real UDP descriptor and rewrite its destination to the
1638
/// private loopback QUIC listener.
1639
/// @param purpose Socket purpose supplied by curl's open-socket callback.
1640
/// @param address Mutable destination description supplied by curl.
1641
/// @return client UDP descriptor, or CURL_SOCKET_BAD on setup failure.
1642
1.97k
curl_socket_t Http3MockServer::HandleOpenSocket(curlsocktype purpose, struct curl_sockaddr* address) {
1643
1.97k
  return impl_ == nullptr ? CURL_SOCKET_BAD : impl_->OpenSocket(purpose, address);
1644
1.97k
}
1645
1646
/// HTTP/3 returns an unconnected UDP descriptor, so curl must perform its
1647
/// normal socket setup before using the rewritten loopback destination.
1648
/// @param curlfd Descriptor returned by HandleOpenSocket.
1649
/// @param purpose Role curl assigned to the descriptor.
1650
/// @return Whether curl must perform its normal socket setup.
1651
SocketSetupDisposition Http3MockServer::GetSocketSetupDisposition(curl_socket_t /*curlfd*/,
1652
1.97k
                                                                  curlsocktype /*purpose*/) const {
1653
1.97k
  return SocketSetupDisposition::kNeedsSetup;
1654
1.97k
}
1655
1656
/// Alternate nonblocking curl and QUIC server turns under fixed operation
1657
/// and idle budgets.
1658
/// @param multi Multi handle containing the scenario's easy handle.
1659
/// @param easy Easy handle being driven; all work is reached through multi.
1660
/// @param scenario Scenario whose Http3Plan supplies ordered plaintext work.
1661
2.21k
void Http3MockServer::RunLoop(CURLM* multi, CURL* easy, const curl::fuzzer::proto::Scenario& scenario) {
1662
2.21k
  (void)easy;
1663
2.21k
  if (impl_ == nullptr) {
1664
0
    return;
1665
0
  }
1666
2.21k
  impl_->BeginScenario(scenario);
1667
1668
2.21k
  int still_running = 1;
1669
2.21k
  int idle_iterations = 0;
1670
2.21k
  if (MultiSocketDriver* driver = multi_socket_driver(); driver != nullptr) {
1671
    // Alternate curl readiness processing with one bounded peer turn. Neither
1672
    // side blocks, so an idle limit prevents a malformed case spinning forever.
1673
2.21k
    CURLMcode result = driver->Start(&still_running);
1674
47.0k
    for (int iteration = 0; result == CURLM_OK && iteration < kMaxDriveIterations; ++iteration) {
1675
47.0k
      std::size_t progress = impl_->DrivePeerTurn();
1676
      // Curl can queue the final ACK or reset while completing the transfer.
1677
      // Give the peer its next bounded turn before stopping, without driving
1678
      // curl again or extending the existing operation budget.
1679
47.0k
      if (still_running == 0) {
1680
1.37k
        break;
1681
1.37k
      }
1682
45.6k
      const MultiSocketDriver::DriveResult drive_result = driver->DriveReady(&still_running);
1683
45.6k
      result = drive_result.code;
1684
45.6k
      progress += drive_result.made_progress ? 1U : 0U;
1685
45.6k
      if (progress != 0) {
1686
14.2k
        idle_iterations = 0;
1687
31.3k
      } else {
1688
31.3k
        if (++idle_iterations >= kHttp3IdleIterations) {
1689
817
          break;
1690
817
        }
1691
        // The client can have a positive QUIC timer while waiting for stream
1692
        // credit. A zero-timeout spin exhausts the idle budget before it fires.
1693
30.5k
        (void)::poll(nullptr, 0, 1);
1694
30.5k
      }
1695
45.6k
    }
1696
2.21k
    return;
1697
2.21k
  }
1698
1699
  // The fallback exercises curl's public multi-perform API while preserving
1700
  // the same peer-first/idle-limit behavior as the socket-action driver.
1701
0
  for (int iteration = 0; iteration < kMaxDriveIterations && still_running != 0; ++iteration) {
1702
0
    const int running_before = still_running;
1703
0
    const CURLMcode result = curl_multi_perform(multi, &still_running);
1704
0
    if (result != CURLM_OK) {
1705
0
      break;
1706
0
    }
1707
1708
0
    std::size_t progress = still_running == running_before ? 0U : 1U;
1709
0
    progress += impl_->DrivePeerTurn();
1710
0
    if (progress != 0) {
1711
0
      idle_iterations = 0;
1712
0
    } else if (++idle_iterations >= kHttp3IdleIterations) {
1713
0
      break;
1714
0
    }
1715
0
  }
1716
0
}
1717
1718
/// Retain protocol outcomes in coverage and introspector builds.
1719
2.25k
void Http3MockServer::ObserveState() {
1720
2.25k
#if defined(PROTO_FUZZER_OBSERVE_STATE)
1721
2.25k
  MockServerBase::ObserveState();
1722
2.25k
  const volatile std::size_t http3_observation[] = {handshake_complete(), request_headers_received(),
1723
2.25k
                                                    executed_action_count(), server_port()};
1724
2.25k
  (void)http3_observation;
1725
2.25k
#endif
1726
2.25k
}
1727
1728
}  // namespace proto_fuzzer