Coverage Report

Created: 2026-10-31 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/vquic/cf-ngtcp2-cmn.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9
 *
10
 * This software is licensed as described in the file COPYING, which
11
 * you should have received as part of this distribution. The terms
12
 * are also available at https://curl.se/docs/copyright.html.
13
 *
14
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15
 * copies of the Software, and permit persons to whom the Software is
16
 * furnished to do so, under the terms of the COPYING file.
17
 *
18
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19
 * KIND, either express or implied.
20
 *
21
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
26
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NGTCP2) && defined(USE_NGHTTP3)
27
28
#include <ngtcp2/ngtcp2.h>
29
30
#ifdef USE_OPENSSL
31
#include <openssl/err.h>
32
#if defined(OPENSSL_IS_AWSLC) || defined(OPENSSL_IS_BORINGSSL)
33
#include <ngtcp2/ngtcp2_crypto_boringssl.h>
34
#elif defined(OPENSSL_QUIC_API2)
35
#include <ngtcp2/ngtcp2_crypto_ossl.h>
36
#else
37
#include <ngtcp2/ngtcp2_crypto_quictls.h>
38
#endif
39
#include "vtls/openssl.h"
40
#elif defined(USE_GNUTLS)
41
#include <ngtcp2/ngtcp2_crypto_gnutls.h>
42
#include "vtls/gtls.h"
43
#elif defined(USE_WOLFSSL)
44
#include <ngtcp2/ngtcp2_crypto_wolfssl.h>
45
#include "vtls/wolfssl.h"
46
#endif
47
48
#include <nghttp3/nghttp3.h>
49
50
#include "urldata.h"
51
#include "url.h"
52
#include "u32_ptrset.h"
53
#include "curl_trc.h"
54
#include "rand.h"
55
#include "multiif.h"
56
#include "cfilters.h"
57
#include "cf-socket.h"
58
#include "connect.h"
59
#include "progress.h"
60
#include "curlx/win32-fopen.h"
61
#include "curlx/dynbuf.h"
62
#include "http1.h"
63
#include "select.h"
64
#include "sockaddr.h"
65
#include "transfer.h"
66
#include "bufref.h"
67
#include "vdns/cf-dns.h"
68
#include "vquic/vquic.h"
69
#include "vquic/vquic_int.h"
70
#include "vquic/vquic-tls.h"
71
#include "vtls/vtls.h"
72
#include "vtls/vtls_scache.h"
73
#include "vquic/cf-ngtcp2-cmn.h"
74
75
/*
76
 * Store ngtcp2 version info in this buffer.
77
 */
78
void Curl_ngtcp2_ver(char *p, size_t len)
79
0
{
80
0
  const ngtcp2_info *ng2 = ngtcp2_version(0);
81
0
  const nghttp3_info *ht3 = nghttp3_version(0);
82
0
  (void)curl_msnprintf(p, len, "ngtcp2/%s nghttp3/%s",
83
0
                       ng2->version_str, ht3->version_str);
84
0
}
85
86
void Curl_cf_ngtcp2_h3_stream_ctx_free(struct h3_stream_ctx *stream)
87
2.55k
{
88
2.55k
  Curl_bufq_free(&stream->sendbuf);
89
2.55k
  Curl_h1_req_parse_free(&stream->h1);
90
2.55k
  curlx_free(stream);
91
2.55k
}
92
93
static void h3_stream_set_free(uint32_t id, void *stream)
94
2.55k
{
95
2.55k
  (void)id;
96
2.55k
  DEBUGASSERT(stream);
97
2.55k
  Curl_cf_ngtcp2_h3_stream_ctx_free((struct h3_stream_ctx *)stream);
98
2.55k
}
99
100
static bool cf_ngtcp2_h3_err_is_fatal(int code)
101
8
{
102
8
  return (NGHTTP3_ERR_FATAL >= code) ||
103
4
         (NGHTTP3_ERR_H3_CLOSED_CRITICAL_STREAM == code);
104
8
}
105
106
void Curl_cf_ngtcp2_h3_err_set(struct Curl_cfilter *cf,
107
                               struct Curl_easy *data, int code)
108
8
{
109
8
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
110
8
  if(!ctx->last_error.error_code) {
111
8
    ngtcp2_ccerr_set_application_error(&ctx->last_error,
112
8
      nghttp3_err_infer_quic_app_error_code(code), NULL, 0);
113
8
  }
114
8
  if(cf_ngtcp2_h3_err_is_fatal(code))
115
8
    Curl_cf_ngtcp2_cmn_conn_close(cf, data);
116
8
}
117
118
CURLcode Curl_cf_ngtcp2_ctx_init(struct cf_ngtcp2_ctx *ctx,
119
                                 struct Curl_peer *origin,
120
                                 struct Curl_peer *peer,
121
                                 struct ssl_filter_config *sslc,
122
                                 cf_ngtcp2_init_h3_conn *init_h3_conn_cb)
123
3.81k
{
124
3.81k
  DEBUGASSERT(!ctx->initialized);
125
3.81k
  ctx->qlogfd = -1;
126
3.81k
  ctx->tunnel_inbuf = NULL;
127
3.81k
  ctx->tunnel_inbuf_len = 0;
128
3.81k
  ctx->version = NGTCP2_PROTO_VER_MAX;
129
3.81k
  Curl_bufcp_init(&ctx->stream_bufcp, H3_STREAM_CHUNK_SIZE,
130
3.81k
                  H3_STREAM_POOL_SPARES);
131
3.81k
  curlx_dyn_init(&ctx->scratch, CURL_MAX_HTTP_HEADER);
132
3.81k
  Curl_u32_ptrset_init(&ctx->streams, h3_stream_set_free);
133
3.81k
  ctx->init_h3_conn_cb = init_h3_conn_cb;
134
3.81k
  ctx->initialized = TRUE;
135
3.81k
  return Curl_vquic_tls_peer_init(origin, peer, sslc, &ctx->ssl_peer);
136
3.81k
}
137
138
void Curl_cf_ngtcp2_ctx_cleanup(struct cf_ngtcp2_ctx *ctx)
139
3.81k
{
140
3.81k
  if(ctx && ctx->initialized) {
141
3.81k
    if(ctx->qlogfd != -1) {
142
0
      curlx_close(ctx->qlogfd);
143
0
      ctx->qlogfd = -1;
144
0
    }
145
    /* Cleanup TLS instances first as ngtcp2 objects
146
     * might be registered there. */
147
3.81k
    Curl_vquic_tls_cleanup(&ctx->tls);
148
3.81k
    Curl_vquic_ctx_free(&ctx->q);
149
3.81k
    if(ctx->h3conn) {
150
2.58k
      nghttp3_conn_del(ctx->h3conn);
151
2.58k
      ctx->h3conn = NULL;
152
2.58k
    }
153
3.81k
    if(ctx->qconn) {
154
3.78k
      ngtcp2_conn_del(ctx->qconn);
155
3.78k
      ctx->qconn = NULL;
156
3.78k
    }
157
3.81k
#ifdef OPENSSL_QUIC_API2
158
3.81k
    if(ctx->ossl_ctx) {
159
3.78k
      ngtcp2_crypto_ossl_ctx_del(ctx->ossl_ctx);
160
3.78k
      ctx->ossl_ctx = NULL;
161
3.78k
    }
162
3.81k
#endif
163
3.81k
    Curl_bufcp_free(&ctx->stream_bufcp);
164
3.81k
    curlx_dyn_free(&ctx->scratch);
165
3.81k
    Curl_u32_ptrset_clear(&ctx->streams);
166
3.81k
    Curl_ssl_peer_cleanup(&ctx->ssl_peer);
167
3.81k
    curlx_safefree(ctx->tunnel_inbuf);
168
3.81k
    ctx->tunnel_inbuf_len = 0;
169
3.81k
  }
170
3.81k
}
171
172
struct Curl_easy *Curl_cf_ngtcp2_get_xfer(struct Curl_cfilter *cf,
173
                                          void *stream_user_data,
174
                                          struct h3_stream_ctx **pstream)
175
16.7k
{
176
16.7k
  struct h3_stream_ctx *stream = stream_user_data;
177
178
16.7k
  if(pstream)
179
15.3k
    *pstream = stream;
180
16.7k
  if(stream && (stream->mid != UINT32_MAX)) {
181
8.33k
    struct Curl_easy *data, *call_data = CF_DATA_CURRENT(cf);
182
8.33k
    if(!call_data || !call_data->multi) {
183
0
      DEBUGASSERT(0);
184
0
      return NULL;
185
0
    }
186
8.33k
    data = Curl_multi_get_easy(call_data->multi, stream->mid);
187
8.33k
    if(data && (data->id == stream->xfer_id))
188
8.33k
      return data;
189
0
    DEBUGASSERT(0);
190
0
  }
191
8.43k
  return NULL;
192
16.7k
}
193
194
static ngtcp2_conn *get_conn(ngtcp2_crypto_conn_ref *conn_ref)
195
55.2k
{
196
55.2k
  struct Curl_cfilter *cf = conn_ref->user_data;
197
55.2k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
198
55.2k
  return ctx->qconn;
199
55.2k
}
200
201
#ifdef DEBUG_NGTCP2
202
static void quic_printf(void *user_data, const char *fmt, ...)
203
{
204
  va_list ap;
205
  (void)user_data;
206
  va_start(ap, fmt);
207
  curl_mvfprintf(stderr, fmt, ap);
208
  va_end(ap);
209
  curl_mfprintf(stderr, "\n");
210
}
211
#endif
212
213
static void qlog_callback(void *user_data, uint32_t flags,
214
                          const void *data, size_t datalen)
215
0
{
216
0
  struct Curl_cfilter *cf = user_data;
217
0
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
218
0
  (void)flags;
219
0
  if(ctx->qlogfd != -1) {
220
0
    ssize_t rc = write(ctx->qlogfd, data, datalen);
221
0
    if(rc == -1) {
222
      /* on write error, stop further write attempts */
223
0
      curlx_close(ctx->qlogfd);
224
0
      ctx->qlogfd = -1;
225
0
    }
226
0
  }
227
0
}
228
229
static void quic_settings(struct cf_ngtcp2_ctx *ctx,
230
                          struct Curl_easy *data,
231
                          struct cf_ngtcp2_io_ctx *pktx)
232
3.79k
{
233
3.79k
  ngtcp2_settings *s = &ctx->settings;
234
3.79k
  ngtcp2_transport_params *t = &ctx->transport_params;
235
236
3.79k
  ngtcp2_settings_default(s);
237
3.79k
  ngtcp2_transport_params_default(t);
238
#ifdef DEBUG_NGTCP2
239
  s->log_printf = quic_printf;
240
#else
241
3.79k
  s->log_printf = NULL;
242
3.79k
#endif
243
244
3.79k
  s->initial_ts = pktx->ts;
245
3.79k
  s->handshake_timeout = (data->set.connecttimeout > 0) ?
246
3.79k
    data->set.connecttimeout * NGTCP2_MILLISECONDS : QUIC_HANDSHAKE_TIMEOUT;
247
3.79k
  s->max_window = H3_CONN_WINDOW_SIZE_MAX;
248
3.79k
  s->max_stream_window = 0; /* disable ngtcp2 auto-tuning of window */
249
3.79k
  s->no_pmtud = FALSE;
250
3.79k
#ifdef NGTCP2_SETTINGS_V3
251
  /* try ten times the ngtcp2 defaults here for problems with Caddy */
252
3.79k
  s->glitch_ratelim_burst = 1000 * 10;
253
3.79k
  s->glitch_ratelim_rate = 33 * 10;
254
3.79k
#endif
255
3.79k
  t->initial_max_data = s->max_window;
256
3.79k
  t->initial_max_stream_data_bidi_local = H3_STREAM_WINDOW_SIZE_INITIAL;
257
3.79k
  t->initial_max_stream_data_bidi_remote = H3_STREAM_WINDOW_SIZE_INITIAL;
258
3.79k
  t->initial_max_stream_data_uni = t->initial_max_data;
259
3.79k
  t->initial_max_streams_bidi = QUIC_MAX_STREAMS;
260
3.79k
  t->initial_max_streams_uni = QUIC_MAX_STREAMS;
261
3.79k
  t->max_idle_timeout = 0; /* no idle timeout from our side */
262
3.79k
  if(ctx->qlogfd != -1) {
263
0
    s->qlog_write = qlog_callback;
264
0
  }
265
3.79k
}
266
267
#if defined(_MSC_VER) && defined(_DLL)
268
#pragma warning(push)
269
#pragma warning(disable:4232) /* MSVC extension, dllimport identity */
270
#endif
271
272
static int cb_ngtcp2_handshake_completed(ngtcp2_conn *tconn, void *user_data)
273
2.58k
{
274
2.58k
  struct Curl_cfilter *cf = user_data;
275
2.58k
  struct cf_ngtcp2_ctx *ctx = cf ? cf->ctx : NULL;
276
2.58k
  struct Curl_easy *data;
277
278
2.58k
  (void)tconn;
279
2.58k
  DEBUGASSERT(ctx);
280
2.58k
  data = CF_DATA_CURRENT(cf);
281
2.58k
  DEBUGASSERT(data);
282
2.58k
  if(!ctx || !data)
283
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
284
285
2.58k
  ctx->handshake_at = *Curl_pgrs_now(data);
286
2.58k
  ctx->tls_handshake_complete = TRUE;
287
2.58k
  Curl_vquic_report_handshake(&ctx->tls, cf, data);
288
289
2.58k
  ctx->tls_vrfy_result = Curl_vquic_tls_verify_peer(&ctx->tls, cf,
290
2.58k
                                                    data, &ctx->ssl_peer);
291
2.58k
  if(ctx->tls_vrfy_result)
292
3
    return NGTCP2_ERR_CALLBACK_FAILURE;
293
294
2.57k
#ifdef CURLVERBOSE
295
2.57k
  if(Curl_trc_is_verbose(data)) {
296
202
    const ngtcp2_transport_params *rp;
297
202
    rp = ngtcp2_conn_get_remote_transport_params(ctx->qconn);
298
202
    CURL_TRC_CF(data, cf, "handshake complete after %" FMT_TIMEDIFF_T
299
202
                "ms, remote transport[max_udp_payload=%" PRIu64
300
202
                ", initial_max_data=%" PRIu64 "]",
301
202
                curlx_ptimediff_ms(&ctx->handshake_at, &ctx->started_at),
302
202
                rp->max_udp_payload_size, rp->initial_max_data);
303
202
  }
304
2.57k
#endif
305
306
  /* In case of earlydata, where we simulate being connected, update
307
   * the handshake time when we really did connect */
308
2.57k
  if(ctx->use_earlydata && !ctx->stats_reported &&
309
0
     !(cf->cft->flags & CF_TYPE_PROXY)) {
310
0
    Curl_pgrsTimeWas(data, TIMER_APPCONNECT, ctx->handshake_at);
311
0
    ctx->stats_reported = TRUE;
312
0
  }
313
2.57k
  if(ctx->use_earlydata) {
314
0
#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_EARLYDATA)
315
    /* Check for bug that OpenSSL did not even send the early data. */
316
0
    if(SSL_get_early_data_status(ctx->tls.ossl.ssl) == SSL_EARLY_DATA_NOT_SENT)
317
0
      CURL_TRC_CF(data, cf, "OpenSSL did not send early data");
318
0
#endif
319
320
0
#if NGTCP2_VERSION_NUM >= 0x011700
321
0
    ctx->earlydata_accepted =
322
0
      !ngtcp2_conn_get_tls_early_data_rejected2(ctx->qconn);
323
#else /* older NGTCP2 */
324
    {
325
#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_EARLYDATA)
326
      int ossl_early_status = SSL_get_early_data_status(ctx->tls.ossl.ssl);
327
      if(ossl_early_status == SSL_EARLY_DATA_NOT_SENT)
328
        CURL_TRC_CF(data, cf, "OpenSSL did not send early data");
329
      ctx->earlydata_accepted = (ossl_early_status == SSL_EARLY_DATA_ACCEPTED);
330
#elif defined(USE_GNUTLS)
331
      int flags = gnutls_session_get_flags(ctx->tls.gtls.session);
332
      ctx->earlydata_accepted = !!(flags & GNUTLS_SFLAGS_EARLY_DATA);
333
#elif defined(USE_WOLFSSL)
334
#ifdef WOLFSSL_EARLY_DATA
335
      ctx->earlydata_accepted =
336
        (wolfSSL_get_early_data_status(ctx->tls.wssl.ssl) !=
337
         WOLFSSL_EARLY_DATA_REJECTED);
338
#else
339
      DEBUGASSERT(0); /* should not come here if ED is disabled. */
340
      ctx->earlydata_accepted = FALSE;
341
#endif /* WOLFSSL_EARLY_DATA */
342
#endif /* OPENSSL or GNUTLS or WOLFSSL */
343
    }
344
#endif /* older NGTCP2 */
345
0
    CURL_TRC_CF(data, cf, "server did%s accept %zu bytes of early data",
346
0
                ctx->earlydata_accepted ? "" : " not", ctx->earlydata_skip);
347
0
    Curl_pgrsEarlyData(data, ctx->earlydata_accepted ?
348
0
                              (curl_off_t)ctx->earlydata_skip :
349
0
                             -(curl_off_t)ctx->earlydata_skip);
350
0
  }
351
2.57k
  return 0;
352
2.58k
}
353
354
static int cb_recv_stream_data(ngtcp2_conn *tconn, uint32_t flags,
355
                               int64_t stream_id, uint64_t offset,
356
                               const uint8_t *buf, size_t buflen,
357
                               void *user_data, void *stream_user_data)
358
9.49k
{
359
9.49k
  struct Curl_cfilter *cf = user_data;
360
9.49k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
361
9.49k
  nghttp3_ssize rc;
362
9.49k
  uint64_t nconsumed;
363
9.49k
  int fin = (flags & NGTCP2_STREAM_DATA_FLAG_FIN) ? 1 : 0;
364
9.49k
  struct h3_stream_ctx *stream;
365
9.49k
  struct Curl_easy *data =
366
9.49k
    Curl_cf_ngtcp2_get_xfer(cf, stream_user_data, &stream);
367
368
9.49k
  (void)offset;
369
9.49k
  rc = nghttp3_conn_read_stream(ctx->h3conn, stream_id, buf, buflen, fin);
370
9.49k
  if(rc < 0) {
371
42
    if(data && stream) {
372
37
      CURL_TRC_CF(data, cf, "[%" PRId64 "] error on known stream, "
373
37
                  "reset=%d, closed=%d",
374
37
                  stream_id, stream->reset, stream->closed);
375
37
    }
376
42
    return NGTCP2_ERR_CALLBACK_FAILURE;
377
42
  }
378
9.44k
  nconsumed = (uint64_t)rc;
379
9.44k
  if(nconsumed) {
380
    /* number of bytes inside buflen which consists of framing overhead
381
     * including QPACK HEADERS. In other words, it does not consume payload of
382
     * DATA frame. */
383
9.42k
    ngtcp2_conn_extend_max_stream_offset(tconn, stream_id, nconsumed);
384
9.42k
    ngtcp2_conn_extend_max_offset(tconn, nconsumed);
385
9.42k
    if(stream) {
386
1.38k
      stream->rx_offset += nconsumed;
387
1.38k
      stream->rx_offset_max += nconsumed;
388
1.38k
    }
389
9.42k
  }
390
9.44k
  return 0;
391
9.49k
}
392
393
static int cb_acked_stream_data_offset(ngtcp2_conn *tconn, int64_t stream_id,
394
                                       uint64_t offset, uint64_t datalen,
395
                                       void *user_data, void *stream_user_data)
396
12.2k
{
397
12.2k
  struct Curl_cfilter *cf = user_data;
398
12.2k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
399
12.2k
  int rv;
400
12.2k
  (void)stream_id;
401
12.2k
  (void)tconn;
402
12.2k
  (void)offset;
403
12.2k
  (void)datalen;
404
12.2k
  (void)stream_user_data;
405
406
12.2k
  rv = nghttp3_conn_add_ack_offset(ctx->h3conn, stream_id, datalen);
407
12.2k
  if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) {
408
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
409
0
  }
410
411
12.2k
  return 0;
412
12.2k
}
413
414
static int cb_stream_close(ngtcp2_conn *tconn, uint32_t flags,
415
                           int64_t stream_id, uint64_t app_error_code,
416
                           void *user_data, void *stream_user_data)
417
0
{
418
0
  struct Curl_cfilter *cf = user_data;
419
0
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
420
0
  struct Curl_easy *data = Curl_cf_ngtcp2_get_xfer(cf, stream_user_data, NULL);
421
0
  int rv;
422
423
0
  (void)tconn;
424
  /* stream is closed... */
425
0
  if(!data)
426
0
    data = CF_DATA_CURRENT(cf);
427
0
  if(!data)
428
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
429
430
0
  if(!(flags & NGTCP2_STREAM_CLOSE_FLAG_APP_ERROR_CODE_SET)) {
431
0
    app_error_code = NGHTTP3_H3_NO_ERROR;
432
0
  }
433
434
0
  rv = nghttp3_conn_close_stream(ctx->h3conn, stream_id, app_error_code);
435
0
  CURL_TRC_CF(data, cf, "[%" PRId64 "] quic close(app_error=%"
436
0
              PRIu64 ") -> %d", stream_id, app_error_code, rv);
437
0
  if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) {
438
0
    Curl_cf_ngtcp2_h3_err_set(cf, data, rv);
439
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
440
0
  }
441
442
0
  return 0;
443
0
}
444
445
#ifdef NGTCP2_CALLBACKS_V5  /* ngtcp2 v1.25.0+ */
446
static int cb_stream_close2(ngtcp2_conn *tconn, uint32_t flags,
447
                           int64_t stream_id,
448
                           uint64_t rx_app_error_code,
449
                           uint64_t tx_app_error_code,
450
                           void *user_data, void *stream_user_data)
451
1.03k
{
452
1.03k
  struct Curl_cfilter *cf = user_data;
453
1.03k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
454
1.03k
  struct Curl_easy *data = Curl_cf_ngtcp2_get_xfer(cf, stream_user_data, NULL);
455
1.03k
  uint64_t h3_app_error_code = NGHTTP3_H3_NO_ERROR;
456
1.03k
  int rv;
457
458
1.03k
  (void)tconn;
459
1.03k
  (void)tx_app_error_code;
460
  /* stream is closed... */
461
1.03k
  if(!data)
462
143
    data = CF_DATA_CURRENT(cf);
463
1.03k
  if(!data)
464
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
465
466
1.03k
  if(flags & NGTCP2_STREAM_CLOSE2_FLAG_RX_APP_ERROR_CODE_SET)
467
381
    h3_app_error_code = rx_app_error_code;
468
469
1.03k
  rv = nghttp3_conn_close_stream(ctx->h3conn, stream_id, h3_app_error_code);
470
1.03k
  CURL_TRC_CF(data, cf, "[%" PRId64 "] quic close(app_error=%"
471
1.03k
              PRIu64 ") -> %d", stream_id, h3_app_error_code, rv);
472
1.03k
  if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) {
473
4
    Curl_cf_ngtcp2_h3_err_set(cf, data, rv);
474
4
    return NGTCP2_ERR_CALLBACK_FAILURE;
475
4
  }
476
477
1.02k
  return 0;
478
1.03k
}
479
#endif
480
481
static int cb_stream_reset(ngtcp2_conn *tconn, int64_t stream_id,
482
                           uint64_t final_size, uint64_t app_error_code,
483
                           void *user_data, void *stream_user_data)
484
386
{
485
386
  struct Curl_cfilter *cf = user_data;
486
386
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
487
386
  struct Curl_easy *data = Curl_cf_ngtcp2_get_xfer(cf, stream_user_data, NULL);
488
386
  int rv;
489
386
  (void)tconn;
490
386
  (void)final_size;
491
386
  (void)app_error_code;
492
493
386
  rv = nghttp3_conn_shutdown_stream_read(ctx->h3conn, stream_id);
494
386
  if(data)
495
279
    CURL_TRC_CF(data, cf, "[%" PRId64 "] reset -> %d", stream_id, rv);
496
386
  if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) {
497
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
498
0
  }
499
500
386
  return 0;
501
386
}
502
503
static int cb_stream_stop_sending(ngtcp2_conn *tconn, int64_t stream_id,
504
                                  uint64_t app_error_code, void *user_data,
505
                                  void *stream_user_data)
506
1.00k
{
507
1.00k
  struct Curl_cfilter *cf = user_data;
508
1.00k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
509
1.00k
  int rv;
510
1.00k
  (void)tconn;
511
1.00k
  (void)app_error_code;
512
1.00k
  (void)stream_user_data;
513
514
1.00k
  rv = nghttp3_conn_shutdown_stream_read(ctx->h3conn, stream_id);
515
1.00k
  if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) {
516
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
517
0
  }
518
519
1.00k
  return 0;
520
1.00k
}
521
522
static int cb_extend_max_local_streams_bidi(ngtcp2_conn *tconn,
523
                                            uint64_t max_streams,
524
                                            void *user_data)
525
2.57k
{
526
2.57k
  struct Curl_cfilter *cf = user_data;
527
2.57k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
528
2.57k
  struct Curl_easy *data = CF_DATA_CURRENT(cf);
529
530
2.57k
  (void)tconn;
531
2.57k
  ctx->max_bidi_streams = max_streams;
532
2.57k
  if(data)
533
2.57k
    CURL_TRC_CF(data, cf, "max bidi streams now %" PRIu64 ", used %" PRIu64,
534
2.57k
                ctx->max_bidi_streams, ctx->used_bidi_streams);
535
2.57k
  return 0;
536
2.57k
}
537
538
static int cb_extend_max_stream_data(ngtcp2_conn *tconn, int64_t stream_id,
539
                                     uint64_t max_data, void *user_data,
540
                                     void *stream_user_data)
541
27
{
542
27
  struct Curl_cfilter *cf = user_data;
543
27
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
544
27
  struct h3_stream_ctx *stream;
545
27
  struct Curl_easy *data =
546
27
    Curl_cf_ngtcp2_get_xfer(cf, stream_user_data, &stream);
547
27
  int rv;
548
27
  (void)tconn;
549
27
  (void)max_data;
550
551
27
  rv = nghttp3_conn_unblock_stream(ctx->h3conn, stream_id);
552
27
  if(rv && rv != NGHTTP3_ERR_STREAM_NOT_FOUND) {
553
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
554
0
  }
555
27
  if(stream && stream->quic_flow_blocked) {
556
0
    CURL_TRC_CF(data, cf, "[%" PRId64 "] unblock quic flow", stream_id);
557
0
    stream->quic_flow_blocked = FALSE;
558
0
    if(data)
559
0
      Curl_multi_mark_dirty(data);
560
0
  }
561
27
  return 0;
562
27
}
563
564
static void cb_rand(uint8_t *dest, size_t destlen,
565
                    const ngtcp2_rand_ctx *rand_ctx)
566
15.2k
{
567
15.2k
  CURLcode result;
568
15.2k
  (void)rand_ctx;
569
570
15.2k
  result = Curl_rand(NULL, dest, destlen);
571
15.2k
  if(result) {
572
    /* cb_rand is only used for non-cryptographic context. If Curl_rand
573
       failed, fill 0 and call it *random*. */
574
0
    memset(dest, 0, destlen);
575
0
  }
576
15.2k
}
577
578
/* for ngtcp2 <v1.22.0 */
579
static int cb_get_new_connection_id(ngtcp2_conn *tconn, ngtcp2_cid *cid,
580
                                    uint8_t *token, size_t cidlen,
581
                                    void *user_data)
582
0
{
583
0
  CURLcode result;
584
0
  (void)tconn;
585
0
  (void)user_data;
586
587
0
  result = Curl_rand(NULL, cid->data, cidlen);
588
0
  if(result)
589
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
590
0
  cid->datalen = cidlen;
591
592
0
  result = Curl_rand(NULL, token, NGTCP2_STATELESS_RESET_TOKENLEN);
593
0
  if(result)
594
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
595
596
0
  return 0;
597
0
}
598
599
#ifdef NGTCP2_CALLBACKS_V3  /* ngtcp2 v1.22.0+ */
600
static int cb_get_new_connection_id2(
601
  ngtcp2_conn *tconn, ngtcp2_cid *cid,
602
  struct ngtcp2_stateless_reset_token *token, size_t cidlen, void *user_data)
603
2.57k
{
604
2.57k
  CURLcode result;
605
2.57k
  (void)tconn;
606
2.57k
  (void)user_data;
607
608
2.57k
  result = Curl_rand(NULL, cid->data, cidlen);
609
2.57k
  if(result)
610
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
611
2.57k
  cid->datalen = cidlen;
612
613
2.57k
  result = Curl_rand(NULL, token->data, sizeof(token->data));
614
2.57k
  if(result)
615
0
    return NGTCP2_ERR_CALLBACK_FAILURE;
616
617
2.57k
  return 0;
618
2.57k
}
619
#endif
620
621
static int cb_recv_rx_key(ngtcp2_conn *tconn, ngtcp2_encryption_level level,
622
                          void *user_data)
623
5.18k
{
624
5.18k
  struct Curl_cfilter *cf = user_data;
625
5.18k
  struct cf_ngtcp2_ctx *ctx = cf ? cf->ctx : NULL;
626
5.18k
  struct Curl_easy *data = CF_DATA_CURRENT(cf);
627
5.18k
  (void)tconn;
628
629
5.18k
  if(level != NGTCP2_ENCRYPTION_LEVEL_1RTT)
630
2.59k
    return 0;
631
632
2.58k
  DEBUGASSERT(ctx);
633
2.58k
  DEBUGASSERT(data);
634
2.58k
  if(ctx && data && !ctx->h3conn && ctx->init_h3_conn_cb) {
635
2.58k
    if(ctx->init_h3_conn_cb(cf, data, ctx))
636
7
      return NGTCP2_ERR_CALLBACK_FAILURE;
637
2.58k
  }
638
2.58k
  return 0;
639
2.58k
}
640
641
#ifdef CURL_HAVE_DIAG
642
#pragma GCC diagnostic push
643
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
644
#endif
645
static ngtcp2_callbacks ng_callbacks = {
646
  ngtcp2_crypto_client_initial_cb,
647
  NULL, /* recv_client_initial */
648
  ngtcp2_crypto_recv_crypto_data_cb,
649
  cb_ngtcp2_handshake_completed,
650
  NULL, /* recv_version_negotiation */
651
  ngtcp2_crypto_encrypt_cb,
652
  ngtcp2_crypto_decrypt_cb,
653
  ngtcp2_crypto_hp_mask_cb,
654
  cb_recv_stream_data,
655
  cb_acked_stream_data_offset,
656
  NULL, /* stream_open */
657
  cb_stream_close,
658
  NULL, /* recv_stateless_reset */
659
  ngtcp2_crypto_recv_retry_cb,
660
  cb_extend_max_local_streams_bidi,
661
  NULL, /* extend_max_local_streams_uni */
662
  cb_rand,
663
  cb_get_new_connection_id, /* for ngtcp2 <v1.22.0 */
664
  NULL, /* remove_connection_id */
665
  ngtcp2_crypto_update_key_cb, /* update_key */
666
  NULL, /* path_validation */
667
  NULL, /* select_preferred_addr */
668
  cb_stream_reset,
669
  NULL, /* extend_max_remote_streams_bidi */
670
  NULL, /* extend_max_remote_streams_uni */
671
  cb_extend_max_stream_data,
672
  NULL, /* dcid_status */
673
  NULL, /* handshake_confirmed */
674
  NULL, /* recv_new_token */
675
  ngtcp2_crypto_delete_crypto_aead_ctx_cb,
676
  ngtcp2_crypto_delete_crypto_cipher_ctx_cb,
677
  NULL, /* recv_datagram */
678
  NULL, /* ack_datagram */
679
  NULL, /* lost_datagram */
680
  ngtcp2_crypto_get_path_challenge_data_cb,
681
  cb_stream_stop_sending,
682
  NULL, /* version_negotiation */
683
  cb_recv_rx_key,
684
  NULL, /* recv_tx_key */
685
  NULL, /* early_data_rejected */
686
#ifdef NGTCP2_CALLBACKS_V2  /* ngtcp2 v1.14.0+ */
687
  NULL, /* begin_path_validation */
688
#endif
689
#ifdef NGTCP2_CALLBACKS_V3  /* ngtcp2 v1.22.0+ */
690
  NULL, /* recv_stateless_reset2 */
691
  cb_get_new_connection_id2, /* get_new_connection_id2 */
692
  NULL, /* dcid_status2 */
693
  ngtcp2_crypto_get_path_challenge_data2_cb, /* get_path_challenge_data2 */
694
#endif
695
#ifdef NGTCP2_CALLBACKS_V4  /* ngtcp2 v1.24.0+ */
696
  NULL, /* recv_stop_sending */
697
#endif
698
#ifdef NGTCP2_CALLBACKS_V5  /* ngtcp2 v1.25.0+ */
699
  cb_stream_close2, /* is called instead of cb_stream_close when set */
700
#endif
701
};
702
#ifdef CURL_HAVE_DIAG
703
#pragma GCC diagnostic pop
704
#endif
705
706
#if defined(_MSC_VER) && defined(_DLL)
707
#pragma warning(pop)
708
#endif
709
710
#ifdef USE_OPENSSL
711
/* The "new session" callback must return zero if the session can be removed
712
 * or non-zero if the session has been put into the session cache.
713
 */
714
static int quic_ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid)
715
4.99k
{
716
4.99k
  struct Curl_cfilter *cf;
717
4.99k
  struct cf_ngtcp2_ctx *ctx;
718
4.99k
  struct Curl_easy *data;
719
4.99k
  ngtcp2_crypto_conn_ref *cref;
720
721
4.99k
  cref = (ngtcp2_crypto_conn_ref *)SSL_get_app_data(ssl);
722
4.99k
  cf = cref ? cref->user_data : NULL;
723
4.99k
  ctx = cf ? cf->ctx : NULL;
724
4.99k
  data = cf ? CF_DATA_CURRENT(cf) : NULL;
725
4.99k
  if(cf && data && ctx) {
726
4.99k
    unsigned char *quic_tp = NULL;
727
4.99k
    size_t quic_tp_len = 0;
728
4.99k
#ifdef HAVE_OPENSSL_EARLYDATA
729
4.99k
    ngtcp2_ssize tplen;
730
4.99k
    uint8_t tpbuf[256];
731
732
4.99k
    tplen = ngtcp2_conn_encode_0rtt_transport_params(ctx->qconn, tpbuf,
733
4.99k
                                                     sizeof(tpbuf));
734
4.99k
    if(tplen < 0)
735
0
      CURL_TRC_CF(data, cf, "error encoding 0RTT transport data: %s",
736
4.99k
                  ngtcp2_strerror((int)tplen));
737
4.99k
    else {
738
4.99k
      quic_tp = (unsigned char *)tpbuf;
739
4.99k
      quic_tp_len = (size_t)tplen;
740
4.99k
    }
741
4.99k
#endif
742
4.99k
    Curl_ossl_add_session(cf, data, &ctx->tls.ossl, ctx->ssl_peer.scache_key,
743
4.99k
                          ssl_sessionid, "h3", quic_tp, quic_tp_len, NULL);
744
4.99k
  }
745
4.99k
  return 0;
746
4.99k
}
747
#endif /* USE_OPENSSL */
748
749
#ifdef USE_GNUTLS
750
751
#ifdef CURLVERBOSE
752
static const char *gtls_hs_msg_name(int mtype)
753
{
754
  switch(mtype) {
755
  case 1:
756
    return "ClientHello";
757
  case 2:
758
    return "ServerHello";
759
  case 4:
760
    return "SessionTicket";
761
  case 8:
762
    return "EncryptedExtensions";
763
  case 11:
764
    return "Certificate";
765
  case 13:
766
    return "CertificateRequest";
767
  case 15:
768
    return "CertificateVerify";
769
  case 20:
770
    return "Finished";
771
  case 24:
772
    return "KeyUpdate";
773
  case 254:
774
    return "MessageHash";
775
  }
776
  return "Unknown";
777
}
778
#endif
779
780
static int quic_gtls_handshake_cb(gnutls_session_t session, unsigned int htype,
781
                                  unsigned when, unsigned int incoming,
782
                                  const gnutls_datum_t *msg)
783
{
784
  ngtcp2_crypto_conn_ref *conn_ref = gnutls_session_get_ptr(session);
785
  struct Curl_cfilter *cf = conn_ref ? conn_ref->user_data : NULL;
786
  struct cf_ngtcp2_ctx *ctx = cf ? cf->ctx : NULL;
787
788
  (void)msg;
789
  (void)incoming;
790
  if(when && cf && ctx) { /* after message has been processed */
791
    struct Curl_easy *data = CF_DATA_CURRENT(cf);
792
    DEBUGASSERT(data);
793
    if(!data)
794
      return 0;
795
    CURL_TRC_CF(data, cf, "SSL message: %s %s [%u]",
796
                incoming ? "<-" : "->", gtls_hs_msg_name(htype), htype);
797
    switch(htype) {
798
    case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET: {
799
      ngtcp2_ssize tplen;
800
      uint8_t tpbuf[256];
801
      unsigned char *quic_tp = NULL;
802
      size_t quic_tp_len = 0;
803
804
      tplen = ngtcp2_conn_encode_0rtt_transport_params(ctx->qconn, tpbuf,
805
                                                       sizeof(tpbuf));
806
      if(tplen < 0)
807
        CURL_TRC_CF(data, cf, "error encoding 0RTT transport data: %s",
808
                    ngtcp2_strerror((int)tplen));
809
      else {
810
        quic_tp = (unsigned char *)tpbuf;
811
        quic_tp_len = (size_t)tplen;
812
      }
813
      (void)Curl_gtls_cache_session(cf, data, ctx->ssl_peer.scache_key,
814
                                    session, 0, "h3", quic_tp, quic_tp_len,
815
                                    NULL);
816
      break;
817
    }
818
    default:
819
      break;
820
    }
821
  }
822
  return 0;
823
}
824
#endif /* USE_GNUTLS */
825
826
#ifdef USE_WOLFSSL
827
static int wssl_quic_new_session_cb(WOLFSSL *ssl, WOLFSSL_SESSION *session)
828
{
829
  ngtcp2_crypto_conn_ref *conn_ref = wolfSSL_get_app_data(ssl);
830
  struct Curl_cfilter *cf = conn_ref ? conn_ref->user_data : NULL;
831
832
  DEBUGASSERT(cf);
833
  if(cf && session) {
834
    struct cf_ngtcp2_ctx *ctx = cf->ctx;
835
    struct Curl_easy *data = CF_DATA_CURRENT(cf);
836
    DEBUGASSERT(data);
837
    if(data && ctx) {
838
      ngtcp2_ssize tplen;
839
      uint8_t tpbuf[256];
840
      unsigned char *quic_tp = NULL;
841
      size_t quic_tp_len = 0;
842
843
      tplen = ngtcp2_conn_encode_0rtt_transport_params(ctx->qconn, tpbuf,
844
                                                       sizeof(tpbuf));
845
      if(tplen < 0)
846
        CURL_TRC_CF(data, cf, "error encoding 0RTT transport data: %s",
847
                    ngtcp2_strerror((int)tplen));
848
      else {
849
        quic_tp = (unsigned char *)tpbuf;
850
        quic_tp_len = (size_t)tplen;
851
      }
852
      (void)Curl_wssl_cache_session(cf, data, ctx->ssl_peer.scache_key,
853
                                    session, wolfSSL_version(ssl),
854
                                    "h3", quic_tp, quic_tp_len, NULL);
855
    }
856
  }
857
  return 0;
858
}
859
#endif /* USE_WOLFSSL */
860
861
static CURLcode cf_ngtcp2_tls_ctx_setup(struct Curl_cfilter *cf,
862
                                        struct Curl_easy *data,
863
                                        void *user_data)
864
3.78k
{
865
3.78k
  struct curl_tls_ctx *ctx = user_data;
866
867
3.78k
#ifdef USE_OPENSSL
868
#if defined(OPENSSL_IS_AWSLC) || defined(OPENSSL_IS_BORINGSSL)
869
  if(ngtcp2_crypto_boringssl_configure_client_context(ctx->ossl.ssl_ctx)
870
     != 0) {
871
    failf(data, "ngtcp2_crypto_boringssl_configure_client_context failed");
872
    return CURLE_FAILED_INIT;
873
  }
874
#elif defined(OPENSSL_QUIC_API2)
875
  /* nothing to do */
876
#else
877
  if(ngtcp2_crypto_quictls_configure_client_context(ctx->ossl.ssl_ctx) != 0) {
878
    failf(data, "ngtcp2_crypto_quictls_configure_client_context failed");
879
    return CURLE_FAILED_INIT;
880
  }
881
#endif /* !OPENSSL_IS_AWSLC && !OPENSSL_IS_BORINGSSL */
882
3.78k
  if(Curl_ssl_scache_use(cf, data)) {
883
    /* Enable the session cache because it is a prerequisite for the
884
     * "new session" callback. Use the "external storage" mode to prevent
885
     * OpenSSL from creating an internal session cache.
886
     */
887
3.78k
    SSL_CTX_set_session_cache_mode(ctx->ossl.ssl_ctx,
888
3.78k
                                   SSL_SESS_CACHE_CLIENT |
889
3.78k
                                   SSL_SESS_CACHE_NO_INTERNAL);
890
3.78k
    SSL_CTX_sess_set_new_cb(ctx->ossl.ssl_ctx, quic_ossl_new_session_cb);
891
3.78k
  }
892
893
#elif defined(USE_GNUTLS)
894
  if(ngtcp2_crypto_gnutls_configure_client_session(ctx->gtls.session) != 0) {
895
    failf(data, "ngtcp2_crypto_gnutls_configure_client_session failed");
896
    return CURLE_FAILED_INIT;
897
  }
898
  if(Curl_ssl_scache_use(cf, data)) {
899
    gnutls_handshake_set_hook_function(ctx->gtls.session,
900
                                       GNUTLS_HANDSHAKE_ANY, GNUTLS_HOOK_POST,
901
                                       quic_gtls_handshake_cb);
902
  }
903
904
#elif defined(USE_WOLFSSL)
905
  if(ngtcp2_crypto_wolfssl_configure_client_context(ctx->wssl.ssl_ctx) != 0) {
906
    failf(data, "ngtcp2_crypto_wolfssl_configure_client_context failed");
907
    return CURLE_FAILED_INIT;
908
  }
909
  if(Curl_ssl_scache_use(cf, data)) {
910
    /* Register to get notified when a new session is received */
911
    wolfSSL_CTX_sess_set_new_cb(ctx->wssl.ssl_ctx, wssl_quic_new_session_cb);
912
  }
913
#endif
914
3.78k
  return CURLE_OK;
915
3.78k
}
916
917
static CURLcode cf_ngtcp2_on_session_reuse(struct Curl_cfilter *cf,
918
                                           struct Curl_easy *data,
919
                                           struct alpn_spec *alpns,
920
                                           struct Curl_ssl_session *scs,
921
                                           bool *do_early_data)
922
0
{
923
0
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
924
0
  CURLcode result = CURLE_OK;
925
926
0
  *do_early_data = FALSE;
927
0
#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_EARLYDATA)
928
0
  ctx->earlydata_max = scs->earlydata_max;
929
0
#endif
930
#ifdef USE_GNUTLS
931
  ctx->earlydata_max =
932
    gnutls_record_get_max_early_data_size(ctx->tls.gtls.session);
933
#endif
934
#ifdef USE_WOLFSSL
935
#ifdef WOLFSSL_EARLY_DATA
936
  ctx->earlydata_max = scs->earlydata_max;
937
#else
938
  ctx->earlydata_max = 0;
939
#endif /* WOLFSSL_EARLY_DATA */
940
#endif
941
0
#if defined(USE_GNUTLS) || defined(USE_WOLFSSL) || \
942
0
  (defined(USE_OPENSSL) && defined(HAVE_OPENSSL_EARLYDATA))
943
0
  if(!ctx->earlydata_max) {
944
0
    CURL_TRC_CF(data, cf, "SSL session does not allow earlydata");
945
0
  }
946
0
  else if(!Curl_alpn_contains_proto(alpns, scs->alpn)) {
947
0
    CURL_TRC_CF(data, cf, "SSL session from different ALPN, no early data");
948
0
  }
949
0
  else if(!scs->quic_tp || !scs->quic_tp_len) {
950
0
    CURL_TRC_CF(data, cf, "no 0RTT transport parameters, no early data");
951
0
  }
952
0
  else {
953
0
    int rv;
954
0
    rv = ngtcp2_conn_decode_and_set_0rtt_transport_params(
955
0
      ctx->qconn, (const uint8_t *)scs->quic_tp, scs->quic_tp_len);
956
0
    if(rv)
957
0
      CURL_TRC_CF(data, cf, "no early data, failed to set 0RTT transport "
958
0
                  "parameters: %s", ngtcp2_strerror(rv));
959
0
    else if(ctx->init_h3_conn_cb) {
960
0
      infof(data, "SSL session allows %zu bytes of early data, "
961
0
            "reusing ALPN '%s'", ctx->earlydata_max, scs->alpn);
962
0
      result = ctx->init_h3_conn_cb(cf, data, ctx);
963
0
      if(!result) {
964
0
        ctx->use_earlydata = TRUE;
965
0
        cf->connected = TRUE;
966
0
        *do_early_data = TRUE;
967
0
      }
968
0
    }
969
0
    else { /* init_h3_conn_cb not set, assume done */
970
0
      ctx->use_earlydata = TRUE;
971
0
      cf->connected = TRUE;
972
0
      *do_early_data = TRUE;
973
0
    }
974
0
  }
975
#else /* not supported in the TLS backend */
976
  (void)data;
977
  (void)ctx;
978
  (void)scs;
979
  (void)alpns;
980
#endif
981
0
  return result;
982
0
}
983
984
/*
985
 * Might be called twice for happy eyeballs.
986
 */
987
static CURLcode cf_connect_start(struct Curl_cfilter *cf,
988
                                 struct Curl_easy *data,
989
                                 struct cf_ngtcp2_io_ctx *pktx)
990
3.79k
{
991
3.79k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
992
3.79k
  int rc;
993
3.79k
  int rv;
994
3.79k
  CURLcode result;
995
3.79k
  const struct Curl_sockaddr_ex *sockaddr = NULL;
996
3.79k
  int qfd;
997
3.79k
  static const struct alpn_spec ALPN_SPEC_H3 = { { "h3", "h3-29" }, 2 };
998
999
3.79k
  DEBUGASSERT(ctx->initialized);
1000
3.79k
  ctx->dcid.datalen = NGTCP2_MAX_CIDLEN;
1001
3.79k
  result = Curl_rand(data, ctx->dcid.data, NGTCP2_MAX_CIDLEN);
1002
3.79k
  if(result)
1003
0
    return result;
1004
1005
3.79k
  ctx->scid.datalen = NGTCP2_MAX_CIDLEN;
1006
3.79k
  result = Curl_rand(data, ctx->scid.data, NGTCP2_MAX_CIDLEN);
1007
3.79k
  if(result)
1008
0
    return result;
1009
1010
3.79k
  (void)Curl_qlogdir(data, ctx->scid.data, NGTCP2_MAX_CIDLEN, &qfd);
1011
3.79k
  ctx->qlogfd = qfd; /* -1 if failure above */
1012
3.79k
  quic_settings(ctx, data, pktx);
1013
1014
3.79k
  result = Curl_vquic_ctx_init(data, &ctx->q);
1015
3.79k
  if(result)
1016
0
    return result;
1017
1018
  /* Query socket and remote address from sub-chain */
1019
3.79k
  if(Curl_cf_socket_peek(cf->next, data, &ctx->q.sockfd, &sockaddr, NULL)) {
1020
    /* No direct socket - must be tunneled QUIC (CONNECT-UDP through proxy) */
1021
1.19k
    ctx->q.sockfd = CURL_SOCKET_BAD;
1022
1.19k
  }
1023
1024
3.79k
  if(ctx->q.sockfd != CURL_SOCKET_BAD) {
1025
    /* Direct UDP socket - get local address for ngtcp2 */
1026
2.60k
    ctx->q.local_addrlen = sizeof(ctx->q.local_addr);
1027
2.60k
    rv = getsockname(ctx->q.sockfd, (struct sockaddr *)&ctx->q.local_addr,
1028
2.60k
                     &ctx->q.local_addrlen);
1029
2.60k
    if(rv == -1)
1030
0
      return CURLE_QUIC_CONNECT_ERROR;
1031
1032
2.60k
    ngtcp2_addr_init(&ctx->connected_path.local,
1033
2.60k
                     (struct sockaddr *)&ctx->q.local_addr,
1034
2.60k
                     ctx->q.local_addrlen);
1035
2.60k
    ngtcp2_addr_init(&ctx->connected_path.remote,
1036
2.60k
                     &sockaddr->curl_sa_addr, (socklen_t)sockaddr->addrlen);
1037
2.60k
  }
1038
1.19k
  else {
1039
    /* Tunneled QUIC (e.g. CONNECT-UDP): get remote address
1040
       from the connected filter below */
1041
1.19k
    const struct Curl_sockaddr_ex *remote = NULL;
1042
1.19k
    if(cf->next->cft->query(cf->next, data, CF_QUERY_REMOTE_ADDR, NULL,
1043
1.19k
                            CURL_UNCONST(&remote)))
1044
0
      return CURLE_QUIC_CONNECT_ERROR;
1045
1.19k
    if(!remote)
1046
0
      return CURLE_QUIC_CONNECT_ERROR;
1047
1048
1.19k
    memset(&ctx->q.local_addr, 0, sizeof(ctx->q.local_addr));
1049
1.19k
    switch(remote->family) {
1050
1.19k
    case AF_INET:
1051
1.19k
      ((struct sockaddr_in *)&ctx->q.local_addr)->sin_family = AF_INET;
1052
1.19k
      ctx->q.local_addrlen = sizeof(struct sockaddr_in);
1053
1.19k
      break;
1054
0
#ifdef USE_IPV6
1055
0
    case AF_INET6:
1056
0
      ((struct sockaddr_in6 *)&ctx->q.local_addr)->sin6_family = AF_INET6;
1057
0
      ctx->q.local_addrlen = sizeof(struct sockaddr_in6);
1058
0
      break;
1059
0
#endif
1060
0
    default:
1061
0
      return CURLE_QUIC_CONNECT_ERROR;
1062
1.19k
    }
1063
1064
1.19k
    ngtcp2_addr_init(&ctx->connected_path.local,
1065
1.19k
                     (struct sockaddr *)&ctx->q.local_addr,
1066
1.19k
                     ctx->q.local_addrlen);
1067
1.19k
    ngtcp2_addr_init(&ctx->connected_path.remote,
1068
1.19k
                     &remote->curl_sa_addr,
1069
1.19k
                     (socklen_t)remote->addrlen);
1070
1.19k
  }
1071
1072
3.79k
  rc = ngtcp2_conn_client_new(&ctx->qconn, &ctx->dcid, &ctx->scid,
1073
3.79k
                              &ctx->connected_path,
1074
3.79k
                              NGTCP2_PROTO_VER_V1, &ng_callbacks,
1075
3.79k
                              &ctx->settings, &ctx->transport_params,
1076
3.79k
                              Curl_ngtcp2_mem(), cf);
1077
3.79k
  if(rc)
1078
16
    return CURLE_QUIC_CONNECT_ERROR;
1079
1080
3.78k
  ctx->conn_ref.get_conn = get_conn;
1081
3.78k
  ctx->conn_ref.user_data = cf;
1082
1083
3.78k
  result = Curl_vquic_tls_init(&ctx->tls, cf, data,
1084
3.78k
                               &ctx->ssl_peer, &ALPN_SPEC_H3,
1085
3.78k
                               cf_ngtcp2_tls_ctx_setup, &ctx->tls,
1086
3.78k
                               &ctx->conn_ref,
1087
3.78k
                               cf_ngtcp2_on_session_reuse);
1088
3.78k
  if(result)
1089
0
    return result;
1090
1091
3.78k
#if defined(USE_OPENSSL) && defined(OPENSSL_QUIC_API2)
1092
3.78k
  if(ngtcp2_crypto_ossl_ctx_new(&ctx->ossl_ctx, ctx->tls.ossl.ssl) != 0) {
1093
0
    failf(data, "ngtcp2_crypto_ossl_ctx_new failed");
1094
0
    return CURLE_FAILED_INIT;
1095
0
  }
1096
3.78k
  ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->ossl_ctx);
1097
3.78k
  if(ngtcp2_crypto_ossl_configure_client_session(ctx->tls.ossl.ssl) != 0) {
1098
0
    failf(data, "ngtcp2_crypto_ossl_configure_client_session failed");
1099
0
    return CURLE_FAILED_INIT;
1100
0
  }
1101
#elif defined(USE_OPENSSL)
1102
  SSL_set_quic_use_legacy_codepoint(ctx->tls.ossl.ssl, 0);
1103
  ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->tls.ossl.ssl);
1104
#elif defined(USE_GNUTLS)
1105
  ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->tls.gtls.session);
1106
#elif defined(USE_WOLFSSL)
1107
  ngtcp2_conn_set_tls_native_handle(ctx->qconn, ctx->tls.wssl.ssl);
1108
#else
1109
#error "ngtcp2 TLS backend not defined"
1110
#endif
1111
1112
3.78k
#if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_EARLYDATA) && \
1113
3.78k
    defined(OPENSSL_QUIC_API2)
1114
  /* We need to tell OpenSSL to *really* use Early Data for QUIC and
1115
   * this only works *after* ngtcp2 has tweaked all SSL parameters,
1116
   * otherwise OpenSSL does not accept it. */
1117
3.78k
  if(ctx->use_earlydata &&
1118
0
     !SSL_set_quic_tls_early_data_enabled(ctx->tls.ossl.ssl, 1)) {
1119
0
    CURL_TRC_CF(data, cf, "OpenSSL refused to use early data");
1120
0
    ctx->use_earlydata = FALSE;
1121
0
    cf->connected = FALSE;
1122
0
  }
1123
3.78k
#endif
1124
3.78k
  ngtcp2_ccerr_default(&ctx->last_error);
1125
1126
3.78k
  return CURLE_OK;
1127
3.78k
}
1128
1129
CURLcode Curl_cf_ngtcp2_cmn_connect(struct Curl_cfilter *cf,
1130
                                    struct Curl_easy *data,
1131
                                    bool *done)
1132
93.3k
{
1133
93.3k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1134
93.3k
  CURLcode result = CURLE_OK;
1135
93.3k
  struct cf_call_data save;
1136
93.3k
  struct cf_ngtcp2_io_ctx pktx;
1137
1138
93.3k
  if(cf->connected) {
1139
0
    *done = TRUE;
1140
0
    return CURLE_OK;
1141
0
  }
1142
1143
  /* Connect the sub-chain */
1144
93.3k
  if(cf->next && !cf->next->connected) {
1145
3.79k
    result = Curl_conn_cf_connect(cf->next, data, done);
1146
3.79k
    if(result || !*done)
1147
0
      return result;
1148
3.79k
  }
1149
1150
93.3k
  *done = FALSE;
1151
1152
93.3k
  if(Curl_ssl_need_httpsrr(cf) &&
1153
0
     !Curl_conn_dns_resolved_https(data, cf->sockindex, ctx->ssl_peer.peer)) {
1154
0
    CURL_TRC_CF(data, cf, "need HTTPS-RR, delaying connect");
1155
0
    return CURLE_OK;
1156
0
  }
1157
1158
93.3k
  Curl_cf_ngtcp2_io_ctx_init(&pktx, cf, data);
1159
93.3k
  CF_DATA_SAVE(save, cf, data);
1160
1161
93.3k
  if(!ctx->qconn) {
1162
3.79k
    ctx->started_at = *Curl_pgrs_now(data);
1163
3.79k
    result = cf_connect_start(cf, data, &pktx);
1164
3.79k
    if(result)
1165
16
      goto out;
1166
3.78k
    if(cf->connected) {
1167
0
      *done = TRUE;
1168
0
      goto out;
1169
0
    }
1170
3.78k
    result = Curl_cf_ngtcp2_progress_egress(cf, data, &pktx);
1171
    /* we do not expect to be able to recv anything yet */
1172
3.78k
    goto out;
1173
3.78k
  }
1174
1175
89.5k
  result = Curl_cf_ngtcp2_progress_ingress(cf, data, &pktx);
1176
89.5k
  if(result)
1177
484
    goto out;
1178
1179
89.0k
  result = Curl_cf_ngtcp2_progress_egress(cf, data, &pktx);
1180
89.0k
  if(result)
1181
2
    goto out;
1182
1183
89.0k
  if(ngtcp2_conn_get_handshake_completed(ctx->qconn)) {
1184
2.57k
    result = ctx->tls_vrfy_result;
1185
2.57k
    if(!result) {
1186
2.57k
      CURL_TRC_CF(data, cf, "peer verified");
1187
2.57k
      cf->connected = TRUE;
1188
2.57k
      *done = TRUE;
1189
2.57k
    }
1190
2.57k
  }
1191
1192
93.3k
out:
1193
93.3k
  if(ctx->tls_vrfy_result)
1194
3
    result = ctx->tls_vrfy_result;
1195
93.3k
  if(ctx->qconn &&
1196
93.2k
     ((result == CURLE_RECV_ERROR) || (result == CURLE_SEND_ERROR)) &&
1197
481
     ngtcp2_conn_in_draining_period(ctx->qconn)) {
1198
0
    const ngtcp2_ccerr *cerr = ngtcp2_conn_get_ccerr(ctx->qconn);
1199
1200
0
    result = CURLE_COULDNT_CONNECT;
1201
0
    if(cerr) {
1202
0
      CURL_TRC_CF(data, cf, "connect error, type=%d, code=%" PRIu64,
1203
0
                  (int)cerr->type, cerr->error_code);
1204
0
      switch(cerr->type) {
1205
0
      case NGTCP2_CCERR_TYPE_VERSION_NEGOTIATION:
1206
0
        CURL_TRC_CF(data, cf, "error in version negotiation");
1207
0
        break;
1208
0
      default:
1209
0
        if(cerr->error_code >= NGTCP2_CRYPTO_ERROR) {
1210
0
          CURL_TRC_CF(data, cf, "crypto error, tls alert=%u",
1211
0
                      (unsigned int)(cerr->error_code & 0xffU));
1212
0
        }
1213
0
        else if(cerr->error_code == NGTCP2_CONNECTION_REFUSED) {
1214
0
          CURL_TRC_CF(data, cf, "connection refused by server");
1215
          /* When a QUIC server instance is shutting down, it may send us a
1216
           * CONNECTION_CLOSE with this code right away. We want
1217
           * to keep on trying in this case. */
1218
0
          result = CURLE_WEIRD_SERVER_REPLY;
1219
0
        }
1220
0
      }
1221
0
    }
1222
0
  }
1223
1224
93.3k
#ifdef CURLVERBOSE
1225
93.3k
  if(result) {
1226
527
    if(ctx->q.sockfd != CURL_SOCKET_BAD) {
1227
      /* Direct UDP socket - get IP info for error reporting */
1228
25
      struct ip_quadruple ip;
1229
1230
25
      if(!Curl_cf_socket_peek(cf->next, data, NULL, NULL, &ip))
1231
25
        infof(data, "QUIC connect to %s port %u failed: %s",
1232
25
              ip.remote_ip, ip.remote_port, curl_easy_strerror(result));
1233
25
    }
1234
527
  }
1235
93.3k
#endif
1236
93.3k
  if(!result && ctx->qconn) {
1237
92.7k
    result = Curl_cf_ngtcp2_cmn_set_expiry(cf, data, &pktx);
1238
92.7k
  }
1239
93.3k
  if(result || *done)
1240
3.10k
    CURL_TRC_CF(data, cf, "connect -> %d, done=%d", (int)result, *done);
1241
93.3k
  CF_DATA_RESTORE(cf, save);
1242
93.3k
  return result;
1243
93.3k
}
1244
1245
CURLcode Curl_cf_ngtcp2_cmn_shutdown(struct Curl_cfilter *cf,
1246
                                     struct Curl_easy *data, bool *done)
1247
6.36k
{
1248
6.36k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1249
6.36k
  struct cf_call_data save;
1250
6.36k
  struct cf_ngtcp2_io_ctx pktx;
1251
6.36k
  CURLcode result = CURLE_OK;
1252
1253
6.36k
  if(cf->shutdown || !ctx->qconn) {
1254
2.50k
    *done = TRUE;
1255
2.50k
    return CURLE_OK;
1256
2.50k
  }
1257
1258
3.86k
  if(!cf->next) {
1259
1.27k
    Curl_bufq_reset(&ctx->q.sendbuf);
1260
1.27k
    *done = TRUE;
1261
1.27k
    return CURLE_OK;
1262
1.27k
  }
1263
1264
2.58k
  CF_DATA_SAVE(save, cf, data);
1265
2.58k
  *done = FALSE;
1266
2.58k
  Curl_cf_ngtcp2_io_ctx_init(&pktx, cf, data);
1267
1268
2.58k
  if(!ctx->shutdown_started) {
1269
2.58k
    char buffer[NGTCP2_MAX_UDP_PAYLOAD_SIZE];
1270
2.58k
    ngtcp2_ssize nwritten;
1271
1272
2.58k
    if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) {
1273
0
      CURL_TRC_CF(data, cf, "shutdown, flushing sendbuf");
1274
0
      result = Curl_cf_ngtcp2_progress_egress(cf, data, &pktx);
1275
0
      if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) {
1276
0
        CURL_TRC_CF(data, cf, "sending shutdown packets blocked");
1277
0
        result = CURLE_OK;
1278
0
        goto out;
1279
0
      }
1280
0
      else if(result) {
1281
0
        CURL_TRC_CF(data, cf, "shutdown, error %d flushing sendbuf",
1282
0
                    (int)result);
1283
0
        *done = TRUE;
1284
0
        goto out;
1285
0
      }
1286
0
    }
1287
1288
2.58k
    DEBUGASSERT(Curl_bufq_is_empty(&ctx->q.sendbuf));
1289
2.58k
    ctx->shutdown_started = TRUE;
1290
2.58k
    nwritten = ngtcp2_conn_write_connection_close(
1291
2.58k
      ctx->qconn, NULL, /* path */
1292
2.58k
      NULL, /* pkt_info */
1293
2.58k
      (uint8_t *)buffer, sizeof(buffer),
1294
2.58k
      &ctx->last_error, pktx.ts);
1295
2.58k
    CURL_TRC_CF(data, cf, "start shutdown(err_type=%d, err_code=%"
1296
2.58k
                PRIu64 ") -> %zd", (int)ctx->last_error.type,
1297
2.58k
                ctx->last_error.error_code, (ssize_t)nwritten);
1298
    /* there are cases listed in ngtcp2 documentation where this call
1299
     * may fail. Since we are doing a connection shutdown as graceful
1300
     * as we can, such an error is ignored here. */
1301
2.58k
    if(nwritten > 0) {
1302
      /* Ignore amount written. sendbuf was empty and has always room for
1303
       * NGTCP2_MAX_UDP_PAYLOAD_SIZE. It can only completely fail, in which
1304
       * case `result` is set non zero. */
1305
1.96k
      size_t n;
1306
1.96k
      result = Curl_bufq_write(&ctx->q.sendbuf, (const unsigned char *)buffer,
1307
1.96k
                               (size_t)nwritten, &n);
1308
1.96k
      if(result) {
1309
0
        CURL_TRC_CF(data, cf, "error %d adding shutdown packets to sendbuf, "
1310
0
                    "aborting shutdown", (int)result);
1311
0
        goto out;
1312
0
      }
1313
1314
1.96k
      ctx->q.no_gso = TRUE;
1315
1.96k
      ctx->q.gsolen = (size_t)nwritten;
1316
1.96k
      ctx->q.split_len = 0;
1317
1.96k
    }
1318
2.58k
  }
1319
1320
2.58k
  if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) {
1321
1.96k
    CURL_TRC_CF(data, cf, "shutdown, flushing egress");
1322
1.96k
    result = Curl_vquic_flush(cf, data, &ctx->q);
1323
1.96k
    if(result == CURLE_AGAIN) {
1324
0
      CURL_TRC_CF(data, cf, "sending shutdown packets blocked");
1325
0
      result = CURLE_OK;
1326
0
      goto out;
1327
0
    }
1328
1.96k
    else if(result) {
1329
0
      CURL_TRC_CF(data, cf, "shutdown, error %d flushing sendbuf",
1330
0
                  (int)result);
1331
0
      *done = TRUE;
1332
0
      goto out;
1333
0
    }
1334
1.96k
  }
1335
1336
2.58k
  if(Curl_bufq_is_empty(&ctx->q.sendbuf)) {
1337
    /* Sent everything off. ngtcp2 seems to have no support for graceful
1338
     * shutdowns. We are done. */
1339
2.58k
    CURL_TRC_CF(data, cf, "shutdown completely sent off, done");
1340
2.58k
    *done = TRUE;
1341
2.58k
    result = CURLE_OK;
1342
2.58k
  }
1343
2.58k
out:
1344
2.58k
  CF_DATA_RESTORE(cf, save);
1345
2.58k
  return result;
1346
2.58k
}
1347
1348
void Curl_cf_ngtcp2_cmn_conn_close(struct Curl_cfilter *cf,
1349
                                   struct Curl_easy *data)
1350
3.86k
{
1351
3.86k
  bool done;
1352
3.86k
  Curl_cf_ngtcp2_cmn_shutdown(cf, data, &done);
1353
3.86k
}
1354
1355
static bool cf_ngtcp2_err_is_fatal(int code)
1356
2.01k
{
1357
2.01k
  return (NGTCP2_ERR_FATAL >= code) ||
1358
1.94k
         (NGTCP2_ERR_DROP_CONN == code) ||
1359
1.94k
         (NGTCP2_ERR_IDLE_CLOSE == code);
1360
2.01k
}
1361
1362
void Curl_cf_ngtcp2_cmn_err_set(struct Curl_cfilter *cf,
1363
                                struct Curl_easy *data, int code)
1364
2.01k
{
1365
2.01k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1366
2.01k
  if(!ctx->last_error.error_code) {
1367
689
    if(NGTCP2_ERR_CRYPTO == code) {
1368
11
      ngtcp2_ccerr_set_tls_alert(&ctx->last_error,
1369
11
                                 ngtcp2_conn_get_tls_alert(ctx->qconn),
1370
11
                                 NULL, 0);
1371
11
    }
1372
678
    else {
1373
678
      ngtcp2_ccerr_set_liberr(&ctx->last_error, code, NULL, 0);
1374
678
    }
1375
689
  }
1376
2.01k
  if(cf_ngtcp2_err_is_fatal(code))
1377
72
    Curl_cf_ngtcp2_cmn_conn_close(cf, data);
1378
2.01k
}
1379
1380
void Curl_cf_ngtcp2_io_ctx_init(struct cf_ngtcp2_io_ctx *io_ctx,
1381
                                struct Curl_cfilter *cf,
1382
                                struct Curl_easy *data)
1383
110k
{
1384
110k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1385
1386
110k
  io_ctx->cf = cf;
1387
110k
  io_ctx->data = data;
1388
110k
  io_ctx->now = *Curl_pgrs_now(data);
1389
110k
  ngtcp2_path_storage_zero(&io_ctx->ps);
1390
110k
  Curl_vquic_ctx_set_time(&ctx->q, &io_ctx->now);
1391
110k
  io_ctx->ts = ((ngtcp2_tstamp)io_ctx->now.tv_sec * NGTCP2_SECONDS) +
1392
110k
               ((ngtcp2_tstamp)io_ctx->now.tv_usec * NGTCP2_MICROSECONDS);
1393
110k
}
1394
1395
void Curl_cf_ngtcp2_io_ctx_update_time(struct Curl_easy *data,
1396
                                       struct cf_ngtcp2_io_ctx *io_ctx,
1397
                                       struct Curl_cfilter *cf)
1398
237k
{
1399
237k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1400
1401
237k
  io_ctx->now = *Curl_pgrs_now(data);
1402
237k
  Curl_vquic_ctx_update_time(&ctx->q, &io_ctx->now);
1403
237k
  io_ctx->ts = ((ngtcp2_tstamp)io_ctx->now.tv_sec * NGTCP2_SECONDS) +
1404
237k
               ((ngtcp2_tstamp)io_ctx->now.tv_usec * NGTCP2_MICROSECONDS);
1405
237k
}
1406
1407
#if NGTCP2_VERSION_NUM < 0x011100
1408
struct cf_ngtcp2_sfind_ctx {
1409
  int64_t stream_id;
1410
  struct h3_stream_ctx *stream;
1411
  uint32_t mid;
1412
};
1413
1414
static bool cf_ngtcp2_sfind(uint32_t mid, void *value, void *user_data)
1415
{
1416
  struct cf_ngtcp2_sfind_ctx *fctx = user_data;
1417
  struct h3_stream_ctx *stream = value;
1418
1419
  if(fctx->stream_id == stream->id) {
1420
    fctx->mid = mid;
1421
    fctx->stream = stream;
1422
    return FALSE;
1423
  }
1424
  return TRUE; /* continue */
1425
}
1426
1427
static struct h3_stream_ctx *cf_ngtcp2_get_stream(struct cf_ngtcp2_ctx *ctx,
1428
                                                  int64_t stream_id)
1429
{
1430
  struct cf_ngtcp2_sfind_ctx fctx;
1431
  fctx.stream_id = stream_id;
1432
  fctx.stream = NULL;
1433
  Curl_u32_ptrset_visit(&ctx->streams, cf_ngtcp2_sfind, &fctx);
1434
  return fctx.stream;
1435
}
1436
#else
1437
static struct h3_stream_ctx *cf_ngtcp2_get_stream(struct cf_ngtcp2_ctx *ctx,
1438
                                                  int64_t stream_id)
1439
0
{
1440
0
  return ngtcp2_conn_get_stream_user_data(ctx->qconn, stream_id);
1441
0
}
1442
#endif
1443
1444
/**
1445
 * Read a network packet to send from ngtcp2 into `buf`.
1446
 * Return number of bytes written or -1 with *err set.
1447
 */
1448
static CURLcode read_pkt_to_send(void *userp,
1449
                                 unsigned char *buf, size_t buflen,
1450
                                 size_t *pnread)
1451
135k
{
1452
135k
  struct cf_ngtcp2_io_ctx *x = userp;
1453
135k
  struct cf_ngtcp2_ctx *ctx = x->cf->ctx;
1454
135k
  nghttp3_vec vec[16];
1455
135k
  nghttp3_ssize veccnt;
1456
135k
  ngtcp2_ssize ndatalen;
1457
135k
  uint32_t flags;
1458
135k
  int64_t stream_id;
1459
135k
  int fin;
1460
135k
  ssize_t n;
1461
1462
135k
  *pnread = 0;
1463
135k
  veccnt = 0;
1464
135k
  stream_id = -1;
1465
135k
  fin = 0;
1466
1467
  /* ngtcp2 may want to put several frames from different streams into
1468
   * this packet. `NGTCP2_WRITE_STREAM_FLAG_MORE` tells it to do so.
1469
   * When `NGTCP2_ERR_WRITE_MORE` is returned, we *need* to make
1470
   * another iteration.
1471
   * When ngtcp2 is happy (because it has no other frame that would fit
1472
   * or it has nothing more to send), it returns the total length
1473
   * of the assembled packet. This may be 0 if there was nothing to send. */
1474
147k
  for(;;) {
1475
1476
147k
    if(ctx->h3conn && ngtcp2_conn_get_max_data_left(ctx->qconn)) {
1477
47.0k
      veccnt = nghttp3_conn_writev_stream(ctx->h3conn, &stream_id, &fin, vec,
1478
47.0k
                                          CURL_ARRAYSIZE(vec));
1479
47.0k
      if(veccnt < 0) {
1480
4
        failf(x->data, "nghttp3_conn_writev_stream returned error: %s",
1481
4
              nghttp3_strerror((int)veccnt));
1482
4
        Curl_cf_ngtcp2_h3_err_set(x->cf, x->data, (int)veccnt);
1483
4
        return CURLE_SEND_ERROR;
1484
4
      }
1485
47.0k
    }
1486
1487
147k
    flags = NGTCP2_WRITE_STREAM_FLAG_MORE |
1488
147k
            (fin ? NGTCP2_WRITE_STREAM_FLAG_FIN : 0);
1489
147k
    n = ngtcp2_conn_writev_stream(ctx->qconn, &x->ps.path,
1490
147k
                                  NULL, buf, buflen,
1491
147k
                                  &ndatalen, flags, stream_id,
1492
147k
                                  (const ngtcp2_vec *)vec, veccnt, x->ts);
1493
147k
    if(n == 0) {
1494
      /* nothing to send */
1495
106k
      return CURLE_AGAIN;
1496
106k
    }
1497
41.1k
    else if(n < 0) {
1498
13.5k
      switch(n) {
1499
0
      case NGTCP2_ERR_STREAM_DATA_BLOCKED: {
1500
0
        struct h3_stream_ctx *stream;
1501
0
        DEBUGASSERT(ndatalen == -1);
1502
0
        nghttp3_conn_block_stream(ctx->h3conn, stream_id);
1503
0
        CURL_TRC_CF(x->data, x->cf, "[%" PRId64 "] block quic flow",
1504
0
                    stream_id);
1505
0
        stream = cf_ngtcp2_get_stream(ctx, stream_id);
1506
0
        if(stream) /* it might be not one of our h3 streams? */
1507
0
          stream->quic_flow_blocked = TRUE;
1508
0
        n = 0;
1509
0
        break;
1510
0
      }
1511
92
      case NGTCP2_ERR_STREAM_SHUT_WR:
1512
92
        DEBUGASSERT(ndatalen == -1);
1513
92
        nghttp3_conn_shutdown_stream_write(ctx->h3conn, stream_id);
1514
92
        n = 0;
1515
92
        break;
1516
12.0k
      case NGTCP2_ERR_WRITE_MORE:
1517
        /* ngtcp2 wants to send more. update the flow of the stream whose data
1518
         * is in the buffer and continue */
1519
12.0k
        DEBUGASSERT(ndatalen >= 0);
1520
12.0k
        n = 0;
1521
12.0k
        break;
1522
1.34k
      default:
1523
1.34k
        DEBUGASSERT(ndatalen == -1);
1524
1.34k
        failf(x->data, "ngtcp2_conn_writev_stream returned error: %s",
1525
1.34k
              ngtcp2_strerror((int)n));
1526
1.34k
        Curl_cf_ngtcp2_cmn_err_set(x->cf, x->data, (int)n);
1527
1.34k
        return CURLE_SEND_ERROR;
1528
13.5k
      }
1529
13.5k
    }
1530
1531
39.7k
    if(ndatalen >= 0) {
1532
      /* we add the amount of data bytes to the flow windows */
1533
14.2k
      int rv = nghttp3_conn_add_write_offset(ctx->h3conn, stream_id, ndatalen);
1534
14.2k
      if(rv) {
1535
0
        failf(x->data, "nghttp3_conn_add_write_offset returned error: %s",
1536
0
              nghttp3_strerror(rv));
1537
0
        return CURLE_SEND_ERROR;
1538
0
      }
1539
14.2k
    }
1540
1541
39.7k
    if(n > 0) {
1542
      /* packet assembled, leave */
1543
27.6k
      *pnread = (size_t)n;
1544
27.6k
      return CURLE_OK;
1545
27.6k
    }
1546
39.7k
  }
1547
135k
}
1548
1549
CURLcode Curl_cf_ngtcp2_progress_egress(struct Curl_cfilter *cf,
1550
                                        struct Curl_easy *data,
1551
                                        struct cf_ngtcp2_io_ctx *pktx)
1552
107k
{
1553
107k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1554
107k
  size_t nread;
1555
107k
  size_t max_payload_size, path_max_payload_size;
1556
107k
  size_t pktcnt = 0;
1557
107k
  size_t gsolen = 0;  /* this disables gso until we have a clue */
1558
107k
  size_t send_quantum;
1559
107k
  CURLcode result;
1560
107k
  struct cf_ngtcp2_io_ctx local_pktx;
1561
1562
107k
  if(!pktx) {
1563
1.66k
    Curl_cf_ngtcp2_io_ctx_init(&local_pktx, cf, data);
1564
1.66k
    pktx = &local_pktx;
1565
1.66k
  }
1566
106k
  else {
1567
106k
    Curl_cf_ngtcp2_io_ctx_update_time(data, pktx, cf);
1568
106k
    ngtcp2_path_storage_zero(&pktx->ps);
1569
106k
  }
1570
1571
107k
  result = Curl_vquic_flush(cf, data, &ctx->q);
1572
107k
  if(result) {
1573
0
    if(result == CURLE_AGAIN) {
1574
0
      Curl_expire_set(data, EXPIRE_QUIC, 1, &pktx->now);
1575
0
      return CURLE_OK;
1576
0
    }
1577
0
    return result;
1578
0
  }
1579
1580
  /* In UDP, there is a maximum theoretical packet payload length and
1581
   * a minimum payload length that is "guaranteed" to work.
1582
   * To detect if this minimum payload can be increased, ngtcp2 sends
1583
   * now and then a packet payload larger than the minimum. It that
1584
   * is ACKed by the peer, both parties know that it works and
1585
   * the subsequent packets can use a larger one.
1586
   * This is called PMTUD (Path Maximum Transmission Unit Discovery).
1587
   * Since a PMTUD might be rejected right on send, we do not want it
1588
   * be followed by other packets of lesser size. Because those would
1589
   * also fail then. If we detect a PMTUD while buffering, we flush.
1590
   */
1591
107k
  max_payload_size = ngtcp2_conn_get_max_tx_udp_payload_size(ctx->qconn);
1592
107k
  path_max_payload_size =
1593
107k
    ngtcp2_conn_get_path_max_tx_udp_payload_size(ctx->qconn);
1594
107k
  send_quantum = ngtcp2_conn_get_send_quantum(ctx->qconn);
1595
107k
  CURL_TRC_CF(data, cf, "egress, collect and send packets, quantum=%zu",
1596
107k
              send_quantum);
1597
135k
  for(;;) {
1598
    /* add the next packet to send, if any, to our buffer */
1599
135k
    result = Curl_bufq_sipn(&ctx->q.sendbuf, max_payload_size,
1600
135k
                            read_pkt_to_send, pktx, &nread);
1601
135k
    if(result == CURLE_AGAIN)
1602
106k
      break;
1603
28.9k
    else if(result)
1604
1.35k
      return result;
1605
27.6k
    else {
1606
27.6k
      size_t buflen = Curl_bufq_len(&ctx->q.sendbuf);
1607
27.6k
      if((buflen >= send_quantum) ||
1608
27.6k
         ((buflen + gsolen) >= ctx->q.sendbuf.chunk_size))
1609
8
        break;
1610
27.6k
      DEBUGASSERT(nread > 0);
1611
27.6k
      ++pktcnt;
1612
27.6k
      if(pktcnt == 1) {
1613
        /* first packet in buffer. This is either of a known, "good"
1614
         * payload size or it is a PMTUD. We shall see. */
1615
16.1k
        gsolen = nread;
1616
16.1k
      }
1617
11.4k
      else if(nread > gsolen ||
1618
8.91k
              (gsolen > path_max_payload_size && nread != gsolen)) {
1619
        /* The added packet is a PMTUD *or* the one(s) before the added were
1620
         * PMTUD and the last one is smaller. Flush the buffer before the last
1621
         * add. */
1622
5.07k
        result = Curl_vquic_send_tail_split(cf, data, &ctx->q,
1623
5.07k
                                            gsolen, nread, nread);
1624
5.07k
        if(result) {
1625
0
          if(result == CURLE_AGAIN) {
1626
0
            Curl_expire_set(data, EXPIRE_QUIC, 1, &pktx->now);
1627
0
            return CURLE_OK;
1628
0
          }
1629
0
          return result;
1630
0
        }
1631
5.07k
        pktcnt = 0;
1632
5.07k
      }
1633
6.42k
      else if(nread < gsolen) {
1634
        /* Reached capacity of our buffer *or*
1635
         * last add was shorter than the previous ones, flush */
1636
163
        break;
1637
163
      }
1638
27.6k
    }
1639
135k
  }
1640
1641
106k
  if(!Curl_bufq_is_empty(&ctx->q.sendbuf)) {
1642
    /* time to send */
1643
11.0k
    CURL_TRC_CF(data, cf, "egress, send collected %zu packets in %zu bytes",
1644
11.0k
                pktcnt, Curl_bufq_len(&ctx->q.sendbuf));
1645
11.0k
    result = Curl_vquic_send(cf, data, &ctx->q, gsolen);
1646
11.0k
    if(result) {
1647
2
      if(result == CURLE_AGAIN) {
1648
0
        Curl_expire_set(data, EXPIRE_QUIC, 1, &pktx->now);
1649
0
        return CURLE_OK;
1650
0
      }
1651
2
      return result;
1652
2
    }
1653
11.0k
    Curl_cf_ngtcp2_io_ctx_update_time(data, pktx, cf);
1654
11.0k
    ngtcp2_conn_update_pkt_tx_time(ctx->qconn, pktx->ts);
1655
11.0k
  }
1656
106k
  return CURLE_OK;
1657
106k
}
1658
1659
struct cf_ngtcp2_recv_ctx {
1660
  struct cf_ngtcp2_io_ctx *pktx;
1661
  size_t pkt_count;
1662
};
1663
1664
static CURLcode cf_ngtcp2_recv_pkts(const unsigned char *buf, size_t buflen,
1665
                                    size_t gso_size,
1666
                                    struct sockaddr_storage *remote_addr,
1667
                                    socklen_t remote_addrlen, uint8_t ecn,
1668
                                    void *userp)
1669
32.2k
{
1670
32.2k
  struct cf_ngtcp2_recv_ctx *rctx = userp;
1671
32.2k
  struct cf_ngtcp2_io_ctx *pktx = rctx->pktx;
1672
32.2k
  struct cf_ngtcp2_ctx *ctx = pktx->cf->ctx;
1673
32.2k
  ngtcp2_pkt_info pi;
1674
32.2k
  ngtcp2_path path;
1675
32.2k
  size_t offset, pktlen;
1676
32.2k
  int rv;
1677
1678
32.2k
  if(!rctx->pkt_count) {
1679
13.7k
    Curl_cf_ngtcp2_io_ctx_update_time(pktx->data, pktx, pktx->cf);
1680
13.7k
    ngtcp2_path_storage_zero(&pktx->ps);
1681
13.7k
  }
1682
1683
32.2k
  if(ecn)
1684
0
    CURL_TRC_CF(pktx->data, pktx->cf, "vquic_recv(len=%zu, gso=%zu, ecn=%x)",
1685
32.2k
                buflen, gso_size, (unsigned)ecn);
1686
32.2k
  ngtcp2_addr_init(&path.local, (struct sockaddr *)&ctx->q.local_addr,
1687
32.2k
                   ctx->q.local_addrlen);
1688
32.2k
  ngtcp2_addr_init(&path.remote, (struct sockaddr *)remote_addr,
1689
32.2k
                   remote_addrlen);
1690
32.2k
  pi.ecn = (uint8_t)ecn;
1691
1692
63.8k
  for(offset = 0; offset < buflen; offset += gso_size) {
1693
32.2k
    rctx->pkt_count++;
1694
32.2k
    pktlen = ((offset + gso_size) <= buflen) ? gso_size : (buflen - offset);
1695
32.2k
    rv = ngtcp2_conn_read_pkt(ctx->qconn, &path, &pi,
1696
32.2k
                              buf + offset, pktlen, pktx->ts);
1697
32.2k
    if(rv) {
1698
674
      CURL_TRC_CF(pktx->data, pktx->cf, "ingress, read_pkt -> %s (%d)",
1699
674
                  ngtcp2_strerror(rv), rv);
1700
674
      Curl_cf_ngtcp2_cmn_err_set(pktx->cf, pktx->data, rv);
1701
1702
674
      if(rv == NGTCP2_ERR_CRYPTO)
1703
        /* this is a "TLS problem", but a failed certificate verification
1704
           is a common reason for this */
1705
11
        return CURLE_PEER_FAILED_VERIFICATION;
1706
663
      return CURLE_RECV_ERROR;
1707
674
    }
1708
32.2k
  }
1709
31.5k
  return CURLE_OK;
1710
32.2k
}
1711
1712
CURLcode Curl_cf_ngtcp2_progress_ingress(struct Curl_cfilter *cf,
1713
                                         struct Curl_easy *data,
1714
                                         struct cf_ngtcp2_io_ctx *pktx)
1715
102k
{
1716
102k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1717
102k
  struct cf_ngtcp2_io_ctx local_pktx;
1718
102k
  struct cf_ngtcp2_recv_ctx rctx;
1719
102k
  CURLcode result = CURLE_OK;
1720
1721
102k
  if(!pktx) {
1722
0
    Curl_cf_ngtcp2_io_ctx_init(&local_pktx, cf, data);
1723
0
    pktx = &local_pktx;
1724
0
  }
1725
1726
102k
  result = Curl_vquic_tls_before_recv(&ctx->tls, cf, data);
1727
102k
  if(result)
1728
0
    return result;
1729
1730
102k
  rctx.pktx = pktx;
1731
102k
  rctx.pkt_count = 0;
1732
1733
102k
  if(ctx->q.sockfd != CURL_SOCKET_BAD) {
1734
    /* Direct UDP socket (via happy eyeballs) */
1735
18.5k
    CURL_TRC_CF(data, cf, "progress_ingress(socket)");
1736
18.5k
    return Curl_vquic_recv_packets(cf, data, &ctx->q, 1000,
1737
18.5k
                                   cf_ngtcp2_recv_pkts, &rctx);
1738
18.5k
  }
1739
84.3k
  else {
1740
    /* Tunneled QUIC (CONNECT-UDP through proxy) */
1741
84.3k
    unsigned char *buf;
1742
84.3k
    size_t max_udp_payload = QUIC_TUNNEL_INBUF_SIZE;
1743
84.3k
    size_t pkt_limit = QUIC_TUNNEL_INGRESS_PKT_LIMIT;
1744
84.3k
    size_t nread;
1745
84.3k
    struct sockaddr_storage remote_addr;
1746
84.3k
    socklen_t remote_addrlen;
1747
1748
84.3k
    CURL_TRC_CF(data, cf, "progress_ingress(sub-filters)");
1749
84.3k
    if(ctx->qconn) {
1750
84.3k
      size_t max_path_payload;
1751
84.3k
      max_path_payload =
1752
84.3k
        ngtcp2_conn_get_path_max_tx_udp_payload_size(ctx->qconn);
1753
84.3k
      if(max_path_payload > max_udp_payload)
1754
0
        max_udp_payload = max_path_payload;
1755
84.3k
    }
1756
1757
84.3k
    if(ctx->tunnel_inbuf_len < max_udp_payload) {
1758
1.16k
      unsigned char *newbuf = curlx_realloc(ctx->tunnel_inbuf,
1759
1.16k
                                            max_udp_payload);
1760
1.16k
      if(!newbuf)
1761
1
        return CURLE_OUT_OF_MEMORY;
1762
1.16k
      ctx->tunnel_inbuf = newbuf;
1763
1.16k
      ctx->tunnel_inbuf_len = max_udp_payload;
1764
1.16k
    }
1765
84.3k
    buf = ctx->tunnel_inbuf;
1766
1767
99.2k
    while(pkt_limit--) {
1768
99.2k
      result = Curl_conn_cf_recv(cf->next, data, (char *)buf,
1769
99.2k
                                 ctx->tunnel_inbuf_len, &nread);
1770
99.2k
      if(result == CURLE_AGAIN) {
1771
        /* no more data available at the moment */
1772
81.8k
        return CURLE_OK;
1773
81.8k
      }
1774
17.4k
      if(result) {
1775
465
        CURL_TRC_CF(data, cf, "ingress, recv from tunnel failed: %d",
1776
465
                    (int)result);
1777
465
        return result;
1778
465
      }
1779
16.9k
      if(nread == 0) {
1780
        /* tunnel closed */
1781
1.97k
        return CURLE_OK;
1782
1.97k
      }
1783
1784
14.9k
      memcpy(&remote_addr, ctx->connected_path.remote.addr,
1785
14.9k
             ctx->connected_path.remote.addrlen);
1786
14.9k
      remote_addrlen = (socklen_t)ctx->connected_path.remote.addrlen;
1787
14.9k
      result = cf_ngtcp2_recv_pkts(buf, nread, nread, &remote_addr,
1788
14.9k
                                   remote_addrlen, 0, &rctx);
1789
14.9k
      if(result)
1790
2
        return result;
1791
1792
14.9k
      if(!ctx->q.got_first_byte) {
1793
658
        ctx->q.got_first_byte = TRUE;
1794
658
        ctx->q.first_byte_at = ctx->q.last_op;
1795
658
      }
1796
14.9k
      ctx->q.last_io = ctx->q.last_op;
1797
14.9k
    }
1798
10
    return CURLE_OK;
1799
84.3k
  }
1800
102k
}
1801
1802
/**
1803
 * Connection maintenance like timeouts on packet ACKs etc. are done by us, not
1804
 * the OS like for TCP. POLL events on the socket therefore are not
1805
 * sufficient.
1806
 * ngtcp2 tells us when it wants to be invoked again. We handle that via
1807
 * the `Curl_expire()` mechanisms.
1808
 */
1809
CURLcode Curl_cf_ngtcp2_cmn_set_expiry(struct Curl_cfilter *cf,
1810
                                       struct Curl_easy *data,
1811
                                       struct cf_ngtcp2_io_ctx *pktx)
1812
106k
{
1813
106k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1814
106k
  struct cf_ngtcp2_io_ctx local_pktx;
1815
106k
  ngtcp2_tstamp expiry;
1816
1817
106k
  if(!pktx) {
1818
0
    Curl_cf_ngtcp2_io_ctx_init(&local_pktx, cf, data);
1819
0
    pktx = &local_pktx;
1820
0
  }
1821
106k
  else {
1822
106k
    Curl_cf_ngtcp2_io_ctx_update_time(data, pktx, cf);
1823
106k
  }
1824
1825
106k
  expiry = ngtcp2_conn_get_expiry(ctx->qconn);
1826
106k
  if(expiry != UINT64_MAX) {
1827
106k
    if(expiry <= pktx->ts) {
1828
61
      CURLcode result;
1829
61
      int rv = ngtcp2_conn_handle_expiry(ctx->qconn, pktx->ts);
1830
61
      if(rv) {
1831
0
        failf(data, "ngtcp2_conn_handle_expiry returned error: %s",
1832
0
              ngtcp2_strerror(rv));
1833
0
        Curl_cf_ngtcp2_cmn_err_set(cf, data, rv);
1834
0
        return CURLE_SEND_ERROR;
1835
0
      }
1836
61
      result = Curl_cf_ngtcp2_progress_ingress(cf, data, pktx);
1837
61
      if(!result)
1838
61
        result = Curl_cf_ngtcp2_progress_egress(cf, data, pktx);
1839
61
      if(result) {
1840
        /* a verify failure during ingress must win over generic errors */
1841
14
        if(ctx->tls_vrfy_result)
1842
0
          result = ctx->tls_vrfy_result;
1843
14
        return result;
1844
14
      }
1845
      /* ask again, things might have changed */
1846
47
      expiry = ngtcp2_conn_get_expiry(ctx->qconn);
1847
47
    }
1848
1849
106k
    if(expiry > pktx->ts) {
1850
106k
      ngtcp2_duration timeout = expiry - pktx->ts;
1851
106k
      if(timeout % NGTCP2_MILLISECONDS) {
1852
105k
        timeout += NGTCP2_MILLISECONDS;
1853
105k
      }
1854
106k
      Curl_expire_set(data, EXPIRE_QUIC,
1855
106k
                      (timediff_t)(timeout / NGTCP2_MILLISECONDS),
1856
106k
                      &pktx->now);
1857
106k
    }
1858
106k
  }
1859
106k
  return CURLE_OK;
1860
106k
}
1861
1862
static void cf_ngtcp2_setup_keep_alive(struct Curl_cfilter *cf,
1863
                                       struct Curl_easy *data)
1864
5.11k
{
1865
5.11k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1866
5.11k
  const ngtcp2_transport_params *rp;
1867
  /* Peer should have sent us its transport parameters. If it
1868
   * announces a positive `max_idle_timeout` it closes the
1869
   * connection when it does not hear from us for that time.
1870
   *
1871
   * Some servers use this as a keep-alive timer at a rather low
1872
   * value. We are doing HTTP/3 here and waiting for the response
1873
   * to a request may take a considerable amount of time. We need
1874
   * to prevent the peer's QUIC stack from closing in this case.
1875
   */
1876
5.11k
  if(!ctx->qconn)
1877
0
    return;
1878
1879
5.11k
  rp = ngtcp2_conn_get_remote_transport_params(ctx->qconn);
1880
5.11k
  if(!rp || !rp->max_idle_timeout) {
1881
0
    ngtcp2_conn_set_keep_alive_timeout(ctx->qconn, UINT64_MAX);
1882
0
    CURL_TRC_CF(data, cf, "no peer idle timeout, unset keep-alive");
1883
0
  }
1884
5.11k
  else if(!Curl_u32_ptrset_count(&ctx->streams)) {
1885
2.55k
    ngtcp2_conn_set_keep_alive_timeout(ctx->qconn, UINT64_MAX);
1886
2.55k
    CURL_TRC_CF(data, cf, "no active streams, unset keep-alive");
1887
2.55k
  }
1888
2.55k
  else {
1889
2.55k
    ngtcp2_duration keep_ns;
1890
2.55k
    keep_ns = (rp->max_idle_timeout > 1) ? (rp->max_idle_timeout / 2) : 1;
1891
2.55k
    ngtcp2_conn_set_keep_alive_timeout(ctx->qconn, keep_ns);
1892
2.55k
    CURL_TRC_CF(data, cf, "peer idle timeout is %" PRIu64 "ms, "
1893
2.55k
                "set keep-alive to %" PRIu64 " ms.",
1894
2.55k
                (rp->max_idle_timeout / NGTCP2_MILLISECONDS),
1895
2.55k
                (keep_ns / NGTCP2_MILLISECONDS));
1896
2.55k
  }
1897
5.11k
}
1898
1899
CURLcode Curl_cf_ngtcp2_h3_stream_setup(struct Curl_cfilter *cf,
1900
                                        struct Curl_easy *data,
1901
                                        struct h3_stream_ctx **pstream)
1902
2.55k
{
1903
2.55k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1904
2.55k
  struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data);
1905
1906
2.55k
  *pstream = NULL;
1907
2.55k
  if(!data)
1908
0
    return CURLE_FAILED_INIT;
1909
1910
2.55k
  if(stream) {
1911
0
    *pstream = stream;
1912
0
    return CURLE_OK;
1913
0
  }
1914
1915
2.55k
  stream = curlx_calloc(1, sizeof(*stream));
1916
2.55k
  if(!stream)
1917
0
    return CURLE_OUT_OF_MEMORY;
1918
1919
2.55k
  stream->id = -1;
1920
2.55k
  stream->xfer_id = data->id;
1921
2.55k
  stream->mid = data->mid;
1922
2.55k
  stream->rx_offset = 0;
1923
2.55k
  stream->rx_offset_max = H3_STREAM_WINDOW_SIZE_INITIAL;
1924
2.55k
  stream->tx_in_flight_ideal = H3_STREAM_SEND_BUF_INITIAL;
1925
1926
  /* on send, we control how much we put into the buffer */
1927
2.55k
  Curl_bufq_initp(&stream->sendbuf, &ctx->stream_bufcp,
1928
2.55k
                  H3_STREAM_SEND_CHUNKS, BUFQ_OPT_NONE);
1929
2.55k
  stream->tx_in_flight_size = 0;
1930
2.55k
  Curl_h1_req_parse_init(&stream->h1, H1_PARSE_DEFAULT_MAX_LINE_LEN);
1931
1932
2.55k
  if(Curl_u32_ptrset_set(&ctx->streams, data->mid, stream)) {
1933
0
    Curl_cf_ngtcp2_h3_stream_ctx_free(stream);
1934
0
    return CURLE_OUT_OF_MEMORY;
1935
0
  }
1936
1937
2.55k
  if(Curl_u32_ptrset_count(&ctx->streams) == 1)
1938
2.55k
    cf_ngtcp2_setup_keep_alive(cf, data);
1939
1940
2.55k
  *pstream = stream;
1941
2.55k
  return CURLE_OK;
1942
2.55k
}
1943
1944
void Curl_cf_ngtcp2_h3_stream_close(struct Curl_cfilter *cf,
1945
                                    struct Curl_easy *data,
1946
                                    struct h3_stream_ctx *stream)
1947
2.56k
{
1948
2.56k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1949
2.56k
  DEBUGASSERT(data);
1950
2.56k
  DEBUGASSERT(stream);
1951
2.56k
  if(!stream->closed && ctx->qconn && ctx->h3conn) {
1952
1.66k
    CURLcode result;
1953
1954
1.66k
    nghttp3_conn_set_stream_user_data(ctx->h3conn, stream->id, NULL);
1955
1.66k
    ngtcp2_conn_set_stream_user_data(ctx->qconn, stream->id, NULL);
1956
1.66k
    stream->closed = TRUE;
1957
1.66k
    (void)ngtcp2_conn_shutdown_stream(ctx->qconn, 0, stream->id,
1958
1.66k
                                      NGHTTP3_H3_REQUEST_CANCELLED);
1959
1.66k
    result = Curl_cf_ngtcp2_progress_egress(cf, data, NULL);
1960
1.66k
    if(result)
1961
660
      CURL_TRC_CF(data, cf, "[%" PRId64 "] cancel stream -> %d",
1962
1.66k
                  stream->id, (int)result);
1963
1.66k
  }
1964
2.56k
}
1965
1966
void Curl_cf_ngtcp2_h3_stream_done(struct Curl_cfilter *cf,
1967
                                   struct Curl_easy *data)
1968
3.27k
{
1969
3.27k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1970
3.27k
  struct h3_stream_ctx *stream = H3_STREAM_CTX(ctx, data);
1971
3.27k
  (void)cf;
1972
3.27k
  if(stream) {
1973
2.55k
    CURL_TRC_CF(data, cf, "[%" PRId64 "] easy handle is done", stream->id);
1974
2.55k
    Curl_cf_ngtcp2_h3_stream_close(cf, data, stream);
1975
2.55k
    Curl_u32_ptrset_unset(&ctx->streams, data->mid);
1976
2.55k
    if(!Curl_u32_ptrset_count(&ctx->streams))
1977
2.55k
      cf_ngtcp2_setup_keep_alive(cf, data);
1978
2.55k
  }
1979
3.27k
}
1980
1981
bool Curl_cf_ngtcp2_cmn_conn_is_alive(struct Curl_cfilter *cf,
1982
                                      struct Curl_easy *data,
1983
                                      bool *input_pending)
1984
0
{
1985
0
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
1986
0
  bool alive = FALSE;
1987
0
  const ngtcp2_transport_params *rp;
1988
0
  struct cf_call_data save;
1989
1990
0
  CF_DATA_SAVE(save, cf, data);
1991
0
  *input_pending = FALSE;
1992
0
  if(!ctx->qconn || ctx->shutdown_started)
1993
0
    goto out;
1994
1995
  /* We do not announce a max idle timeout, but when the peer does
1996
   * it closes the connection when it expires. */
1997
0
  rp = ngtcp2_conn_get_remote_transport_params(ctx->qconn);
1998
0
  if(rp && rp->max_idle_timeout) {
1999
0
    timediff_t idletime_ms =
2000
0
      curlx_ptimediff_ms(Curl_pgrs_now(data), &ctx->q.last_io);
2001
0
    if(idletime_ms > 0) {
2002
0
      uint64_t max_idle_ms =
2003
0
        (uint64_t)(rp->max_idle_timeout / NGTCP2_MILLISECONDS);
2004
0
      if((uint64_t)idletime_ms > max_idle_ms)
2005
0
        goto out;
2006
0
    }
2007
0
  }
2008
2009
0
  if(!cf->next || !cf->next->cft->is_alive(cf->next, data, input_pending))
2010
0
    goto out;
2011
2012
0
  alive = TRUE;
2013
0
  if(*input_pending) {
2014
0
    CURLcode result;
2015
    /* This happens before we have sent off a request and the connection is
2016
       not in use by any other transfer, there should not be any data here,
2017
       only "protocol frames" */
2018
0
    *input_pending = FALSE;
2019
0
    result = Curl_cf_ngtcp2_progress_ingress(cf, data, NULL);
2020
0
    CURL_TRC_CF(data, cf, "is_alive, progress ingress -> %d", (int)result);
2021
0
    alive = result ? FALSE : TRUE;
2022
0
  }
2023
2024
0
out:
2025
0
  CF_DATA_RESTORE(cf, save);
2026
0
  return alive;
2027
0
}
2028
2029
CURLcode Curl_cf_ngtcp2_h3_init_ctrls(struct cf_ngtcp2_ctx *ctx,
2030
                                      struct Curl_easy *data)
2031
2.58k
{
2032
2.58k
  int64_t ctrl_stream_id, qpack_enc_stream_id, qpack_dec_stream_id;
2033
2.58k
  int rc;
2034
2035
2.58k
  rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &ctrl_stream_id, NULL);
2036
2.58k
  if(rc) {
2037
2
    failf(data, "error creating HTTP/3 control stream: %s",
2038
2
          ngtcp2_strerror(rc));
2039
2
    return CURLE_QUIC_CONNECT_ERROR;
2040
2
  }
2041
2.58k
  rc = nghttp3_conn_bind_control_stream(ctx->h3conn, ctrl_stream_id);
2042
2.58k
  if(rc) {
2043
4
    failf(data, "error binding HTTP/3 control stream: %s",
2044
4
          ngtcp2_strerror(rc));
2045
4
    return CURLE_QUIC_CONNECT_ERROR;
2046
4
  }
2047
2.58k
  rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &qpack_enc_stream_id, NULL);
2048
2.58k
  if(rc) {
2049
0
    failf(data, "error creating HTTP/3 qpack encoding stream: %s",
2050
0
          ngtcp2_strerror(rc));
2051
0
    return CURLE_QUIC_CONNECT_ERROR;
2052
0
  }
2053
2.58k
  rc = ngtcp2_conn_open_uni_stream(ctx->qconn, &qpack_dec_stream_id, NULL);
2054
2.58k
  if(rc) {
2055
0
    failf(data, "error creating HTTP/3 qpack decoding stream: %s",
2056
0
          ngtcp2_strerror(rc));
2057
0
    return CURLE_QUIC_CONNECT_ERROR;
2058
0
  }
2059
2.58k
  rc = nghttp3_conn_bind_qpack_streams(ctx->h3conn, qpack_enc_stream_id,
2060
2.58k
                                       qpack_dec_stream_id);
2061
2.58k
  if(rc) {
2062
1
    failf(data, "error binding HTTP/3 qpack streams: %s", ngtcp2_strerror(rc));
2063
1
    return CURLE_QUIC_CONNECT_ERROR;
2064
1
  }
2065
2.58k
  return CURLE_OK;
2066
2.58k
}
2067
2068
CURLcode Curl_cf_ngtcp2_cmn_query(struct Curl_cfilter *cf,
2069
                                  struct Curl_easy *data,
2070
                                  int query, int *pres1, void *pres2)
2071
142k
{
2072
142k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
2073
2074
142k
  switch(query) {
2075
0
  case CF_QUERY_CONNECT_REPLY_MS:
2076
0
    if((ctx->q.sockfd != CURL_SOCKET_BAD) && ctx->q.got_first_byte) {
2077
0
      timediff_t ms = curlx_ptimediff_ms(&ctx->q.first_byte_at,
2078
0
                                         &ctx->started_at);
2079
0
      *pres1 = (ms < INT_MAX) ? (int)ms : INT_MAX;
2080
0
      return CURLE_OK;
2081
0
    }
2082
0
    break;
2083
1.00k
  case CF_QUERY_REALLY_CONNECTED:
2084
1.00k
    if(ctx->q.sockfd != CURL_SOCKET_BAD) {
2085
0
      *pres1 = ctx->q.got_first_byte;
2086
0
      return CURLE_OK;
2087
0
    }
2088
1.00k
    break;
2089
141k
  default:
2090
141k
    break;
2091
142k
  }
2092
142k
  return cf->next ?
2093
142k
    cf->next->cft->query(cf->next, data, query, pres1, pres2) :
2094
142k
    CURLE_UNKNOWN_OPTION;
2095
142k
}
2096
2097
CURLcode Curl_cf_ngtcp2_cmn_cntrl(struct Curl_cfilter *cf,
2098
                                  struct Curl_easy *data,
2099
                                  int event, int arg1, void *arg2)
2100
7.97k
{
2101
7.97k
  struct cf_ngtcp2_ctx *ctx = cf->ctx;
2102
7.97k
  CURLcode result = CURLE_OK;
2103
2104
7.97k
  (void)arg1;
2105
7.97k
  (void)arg2;
2106
7.97k
  switch(event) {
2107
3.07k
  case CF_CTRL_REPORT_STATS:
2108
3.07k
    if(cf->connected && !ctx->stats_reported) {
2109
2.57k
      if((cf->cft->flags & CF_TYPE_PROXY) &&
2110
0
         (ctx->q.sockfd != CURL_SOCKET_BAD) && ctx->q.got_first_byte) {
2111
0
        Curl_pgrsTimeWas(data, TIMER_CONNECT, ctx->q.first_byte_at);
2112
0
        ctx->stats_reported = TRUE;
2113
0
      }
2114
2.57k
      else if(ctx->handshake_at.tv_sec || ctx->handshake_at.tv_usec) {
2115
2.57k
        if(ctx->q.sockfd != CURL_SOCKET_BAD)
2116
2.57k
          Curl_pgrsTimeWas(data, TIMER_CONNECT, ctx->q.first_byte_at);
2117
2.57k
        Curl_pgrsTimeWas(data, TIMER_APPCONNECT, ctx->handshake_at);
2118
2.57k
        ctx->stats_reported = TRUE;
2119
2.57k
      }
2120
2.57k
    }
2121
3.07k
    break;
2122
4.89k
  default:
2123
4.89k
    break;
2124
7.97k
  }
2125
7.97k
  return result;
2126
7.97k
}
2127
2128
#endif /* !CURL_DISABLE_HTTP && USE_NGTCP2 && USE_NGHTTP3 */