Coverage Report

Created: 2025-08-28 07:07

/src/openssl34/ssl/quic/quic_channel.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2022-2025 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include <openssl/rand.h>
11
#include <openssl/err.h>
12
#include "internal/quic_channel.h"
13
#include "internal/quic_error.h"
14
#include "internal/quic_rx_depack.h"
15
#include "internal/quic_lcidm.h"
16
#include "internal/quic_srtm.h"
17
#include "internal/qlog_event_helpers.h"
18
#include "../ssl_local.h"
19
#include "quic_channel_local.h"
20
#include "quic_port_local.h"
21
#include "quic_engine_local.h"
22
23
/*
24
 * NOTE: While this channel implementation currently has basic server support,
25
 * this functionality has been implemented for internal testing purposes and is
26
 * not suitable for network use. In particular, it does not implement address
27
 * validation, anti-amplification or retry logic.
28
 *
29
 * TODO(QUIC SERVER): Implement address validation and anti-amplification
30
 * TODO(QUIC SERVER): Implement retry logic
31
 */
32
33
55.6k
#define INIT_CRYPTO_RECV_BUF_LEN    16384
34
55.6k
#define INIT_CRYPTO_SEND_BUF_LEN    16384
35
38.3k
#define INIT_APP_BUF_LEN             8192
36
37
/*
38
 * Interval before we force a PING to ensure NATs don't timeout. This is based
39
 * on the lowest commonly seen value of 30 seconds as cited in RFC 9000 s.
40
 * 10.1.2.
41
 */
42
21.2M
#define MAX_NAT_INTERVAL (ossl_ms2time(25000))
43
44
/*
45
 * Our maximum ACK delay on the TX side. This is up to us to choose. Note that
46
 * this could differ from QUIC_DEFAULT_MAX_DELAY in future as that is a protocol
47
 * value which determines the value of the maximum ACK delay if the
48
 * max_ack_delay transport parameter is not set.
49
 */
50
18.5k
#define DEFAULT_MAX_ACK_DELAY   QUIC_DEFAULT_MAX_ACK_DELAY
51
52
DEFINE_LIST_OF_IMPL(ch, QUIC_CHANNEL);
53
54
static void ch_save_err_state(QUIC_CHANNEL *ch);
55
static int ch_rx(QUIC_CHANNEL *ch, int channel_only);
56
static int ch_tx(QUIC_CHANNEL *ch);
57
static int ch_tick_tls(QUIC_CHANNEL *ch, int channel_only);
58
static void ch_rx_handle_packet(QUIC_CHANNEL *ch, int channel_only);
59
static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch);
60
static int ch_retry(QUIC_CHANNEL *ch,
61
                    const unsigned char *retry_token,
62
                    size_t retry_token_len,
63
                    const QUIC_CONN_ID *retry_scid);
64
static void ch_cleanup(QUIC_CHANNEL *ch);
65
static int ch_generate_transport_params(QUIC_CHANNEL *ch);
66
static int ch_on_transport_params(const unsigned char *params,
67
                                  size_t params_len,
68
                                  void *arg);
69
static int ch_on_handshake_alert(void *arg, unsigned char alert_code);
70
static int ch_on_handshake_complete(void *arg);
71
static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
72
                                        uint32_t suite_id, EVP_MD *md,
73
                                        const unsigned char *secret,
74
                                        size_t secret_len,
75
                                        void *arg);
76
static int ch_on_crypto_recv_record(const unsigned char **buf,
77
                                    size_t *bytes_read, void *arg);
78
static int ch_on_crypto_release_record(size_t bytes_read, void *arg);
79
static int crypto_ensure_empty(QUIC_RSTREAM *rstream);
80
static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
81
                             size_t *consumed, void *arg);
82
static OSSL_TIME get_time(void *arg);
83
static uint64_t get_stream_limit(int uni, void *arg);
84
static int rx_late_validate(QUIC_PN pn, int pn_space, void *arg);
85
static void rxku_detected(QUIC_PN pn, void *arg);
86
static int ch_retry(QUIC_CHANNEL *ch,
87
                    const unsigned char *retry_token,
88
                    size_t retry_token_len,
89
                    const QUIC_CONN_ID *retry_scid);
90
static void ch_update_idle(QUIC_CHANNEL *ch);
91
static int ch_discard_el(QUIC_CHANNEL *ch,
92
                         uint32_t enc_level);
93
static void ch_on_idle_timeout(QUIC_CHANNEL *ch);
94
static void ch_update_idle(QUIC_CHANNEL *ch);
95
static void ch_update_ping_deadline(QUIC_CHANNEL *ch);
96
static void ch_on_terminating_timeout(QUIC_CHANNEL *ch);
97
static void ch_start_terminating(QUIC_CHANNEL *ch,
98
                                 const QUIC_TERMINATE_CAUSE *tcause,
99
                                 int force_immediate);
100
static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space,
101
                             void *arg);
102
static void ch_rx_handle_version_neg(QUIC_CHANNEL *ch, OSSL_QRX_PKT *pkt);
103
static void ch_raise_version_neg_failure(QUIC_CHANNEL *ch);
104
static void ch_record_state_transition(QUIC_CHANNEL *ch, uint32_t new_state);
105
106
DEFINE_LHASH_OF_EX(QUIC_SRT_ELEM);
107
108
QUIC_NEEDS_LOCK
109
static QLOG *ch_get_qlog(QUIC_CHANNEL *ch)
110
2.04M
{
111
2.04M
#ifndef OPENSSL_NO_QLOG
112
2.04M
    QLOG_TRACE_INFO qti = {0};
113
114
2.04M
    if (ch->qlog != NULL)
115
0
        return ch->qlog;
116
117
2.04M
    if (!ch->use_qlog)
118
2.00M
        return NULL;
119
120
37.5k
    if (ch->is_server && ch->init_dcid.id_len == 0)
121
0
        return NULL;
122
123
37.5k
    qti.odcid       = ch->init_dcid;
124
37.5k
    qti.title       = ch->qlog_title;
125
37.5k
    qti.description = NULL;
126
37.5k
    qti.group_id    = NULL;
127
37.5k
    qti.is_server   = ch->is_server;
128
37.5k
    qti.now_cb      = get_time;
129
37.5k
    qti.now_cb_arg  = ch;
130
37.5k
    if ((ch->qlog = ossl_qlog_new_from_env(&qti)) == NULL) {
131
37.5k
        ch->use_qlog = 0; /* don't try again */
132
37.5k
        return NULL;
133
37.5k
    }
134
135
0
    return ch->qlog;
136
#else
137
    return NULL;
138
#endif
139
37.5k
}
140
141
QUIC_NEEDS_LOCK
142
static QLOG *ch_get_qlog_cb(void *arg)
143
1.14M
{
144
1.14M
    QUIC_CHANNEL *ch = arg;
145
146
1.14M
    return ch_get_qlog(ch);
147
1.14M
}
148
149
/*
150
 * QUIC Channel Initialization and Teardown
151
 * ========================================
152
 */
153
37.0k
#define DEFAULT_INIT_CONN_RXFC_WND      (768 * 1024)
154
18.5k
#define DEFAULT_CONN_RXFC_MAX_WND_MUL   20
155
156
55.6k
#define DEFAULT_INIT_STREAM_RXFC_WND    (512 * 1024)
157
100k
#define DEFAULT_STREAM_RXFC_MAX_WND_MUL 12
158
159
37.0k
#define DEFAULT_INIT_CONN_MAX_STREAMS           100
160
161
static int ch_init(QUIC_CHANNEL *ch)
162
18.5k
{
163
18.5k
    OSSL_QUIC_TX_PACKETISER_ARGS txp_args = {0};
164
18.5k
    OSSL_QTX_ARGS qtx_args = {0};
165
18.5k
    OSSL_QRX_ARGS qrx_args = {0};
166
18.5k
    QUIC_TLS_ARGS tls_args = {0};
167
18.5k
    uint32_t pn_space;
168
18.5k
    size_t rx_short_dcid_len;
169
18.5k
    size_t tx_init_dcid_len;
170
171
18.5k
    if (ch->port == NULL || ch->lcidm == NULL || ch->srtm == NULL)
172
0
        goto err;
173
174
18.5k
    rx_short_dcid_len = ossl_quic_port_get_rx_short_dcid_len(ch->port);
175
18.5k
    tx_init_dcid_len = ossl_quic_port_get_tx_init_dcid_len(ch->port);
176
177
    /* For clients, generate our initial DCID. */
178
18.5k
    if (!ch->is_server
179
18.5k
        && !ossl_quic_gen_rand_conn_id(ch->port->engine->libctx, tx_init_dcid_len,
180
18.5k
                                       &ch->init_dcid))
181
0
        goto err;
182
183
    /* We plug in a network write BIO to the QTX later when we get one. */
184
18.5k
    qtx_args.libctx             = ch->port->engine->libctx;
185
18.5k
    qtx_args.get_qlog_cb        = ch_get_qlog_cb;
186
18.5k
    qtx_args.get_qlog_cb_arg    = ch;
187
18.5k
    qtx_args.mdpl               = QUIC_MIN_INITIAL_DGRAM_LEN;
188
18.5k
    ch->rx_max_udp_payload_size = qtx_args.mdpl;
189
190
18.5k
    ch->ping_deadline = ossl_time_infinite();
191
192
18.5k
    ch->qtx = ossl_qtx_new(&qtx_args);
193
18.5k
    if (ch->qtx == NULL)
194
0
        goto err;
195
196
18.5k
    ch->txpim = ossl_quic_txpim_new();
197
18.5k
    if (ch->txpim == NULL)
198
0
        goto err;
199
200
18.5k
    ch->cfq = ossl_quic_cfq_new();
201
18.5k
    if (ch->cfq == NULL)
202
0
        goto err;
203
204
18.5k
    if (!ossl_quic_txfc_init(&ch->conn_txfc, NULL))
205
0
        goto err;
206
207
    /*
208
     * Note: The TP we transmit governs what the peer can transmit and thus
209
     * applies to the RXFC.
210
     */
211
18.5k
    ch->tx_init_max_stream_data_bidi_local  = DEFAULT_INIT_STREAM_RXFC_WND;
212
18.5k
    ch->tx_init_max_stream_data_bidi_remote = DEFAULT_INIT_STREAM_RXFC_WND;
213
18.5k
    ch->tx_init_max_stream_data_uni         = DEFAULT_INIT_STREAM_RXFC_WND;
214
215
18.5k
    if (!ossl_quic_rxfc_init(&ch->conn_rxfc, NULL,
216
18.5k
                             DEFAULT_INIT_CONN_RXFC_WND,
217
18.5k
                             DEFAULT_CONN_RXFC_MAX_WND_MUL *
218
18.5k
                             DEFAULT_INIT_CONN_RXFC_WND,
219
18.5k
                             get_time, ch))
220
0
        goto err;
221
222
74.1k
    for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space)
223
55.6k
        if (!ossl_quic_rxfc_init_standalone(&ch->crypto_rxfc[pn_space],
224
55.6k
                                            INIT_CRYPTO_RECV_BUF_LEN,
225
55.6k
                                            get_time, ch))
226
0
            goto err;
227
228
18.5k
    if (!ossl_quic_rxfc_init_standalone(&ch->max_streams_bidi_rxfc,
229
18.5k
                                        DEFAULT_INIT_CONN_MAX_STREAMS,
230
18.5k
                                        get_time, ch))
231
0
        goto err;
232
233
18.5k
    if (!ossl_quic_rxfc_init_standalone(&ch->max_streams_uni_rxfc,
234
18.5k
                                        DEFAULT_INIT_CONN_MAX_STREAMS,
235
18.5k
                                        get_time, ch))
236
0
        goto err;
237
238
18.5k
    if (!ossl_statm_init(&ch->statm))
239
0
        goto err;
240
241
18.5k
    ch->have_statm = 1;
242
18.5k
    ch->cc_method = &ossl_cc_newreno_method;
243
18.5k
    if ((ch->cc_data = ch->cc_method->new(get_time, ch)) == NULL)
244
0
        goto err;
245
246
18.5k
    if ((ch->ackm = ossl_ackm_new(get_time, ch, &ch->statm,
247
18.5k
                                  ch->cc_method, ch->cc_data,
248
18.5k
                                  ch->is_server)) == NULL)
249
0
        goto err;
250
251
18.5k
    if (!ossl_quic_stream_map_init(&ch->qsm, get_stream_limit, ch,
252
18.5k
                                   &ch->max_streams_bidi_rxfc,
253
18.5k
                                   &ch->max_streams_uni_rxfc,
254
18.5k
                                   ch->is_server))
255
0
        goto err;
256
257
18.5k
    ch->have_qsm = 1;
258
259
18.5k
    if (!ch->is_server
260
18.5k
        && !ossl_quic_lcidm_generate_initial(ch->lcidm, ch, &txp_args.cur_scid))
261
0
        goto err;
262
263
    /* We use a zero-length SCID. */
264
18.5k
    txp_args.cur_dcid               = ch->init_dcid;
265
18.5k
    txp_args.ack_delay_exponent     = 3;
266
18.5k
    txp_args.qtx                    = ch->qtx;
267
18.5k
    txp_args.txpim                  = ch->txpim;
268
18.5k
    txp_args.cfq                    = ch->cfq;
269
18.5k
    txp_args.ackm                   = ch->ackm;
270
18.5k
    txp_args.qsm                    = &ch->qsm;
271
18.5k
    txp_args.conn_txfc              = &ch->conn_txfc;
272
18.5k
    txp_args.conn_rxfc              = &ch->conn_rxfc;
273
18.5k
    txp_args.max_streams_bidi_rxfc  = &ch->max_streams_bidi_rxfc;
274
18.5k
    txp_args.max_streams_uni_rxfc   = &ch->max_streams_uni_rxfc;
275
18.5k
    txp_args.cc_method              = ch->cc_method;
276
18.5k
    txp_args.cc_data                = ch->cc_data;
277
18.5k
    txp_args.now                    = get_time;
278
18.5k
    txp_args.now_arg                = ch;
279
18.5k
    txp_args.get_qlog_cb            = ch_get_qlog_cb;
280
18.5k
    txp_args.get_qlog_cb_arg        = ch;
281
282
74.1k
    for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
283
55.6k
        ch->crypto_send[pn_space] = ossl_quic_sstream_new(INIT_CRYPTO_SEND_BUF_LEN);
284
55.6k
        if (ch->crypto_send[pn_space] == NULL)
285
0
            goto err;
286
287
55.6k
        txp_args.crypto[pn_space] = ch->crypto_send[pn_space];
288
55.6k
    }
289
290
18.5k
    ch->txp = ossl_quic_tx_packetiser_new(&txp_args);
291
18.5k
    if (ch->txp == NULL)
292
0
        goto err;
293
294
18.5k
    ossl_quic_tx_packetiser_set_ack_tx_cb(ch->txp, ch_on_txp_ack_tx, ch);
295
296
18.5k
    qrx_args.libctx             = ch->port->engine->libctx;
297
18.5k
    qrx_args.demux              = ch->port->demux;
298
18.5k
    qrx_args.short_conn_id_len  = rx_short_dcid_len;
299
18.5k
    qrx_args.max_deferred       = 32;
300
301
18.5k
    if ((ch->qrx = ossl_qrx_new(&qrx_args)) == NULL)
302
0
        goto err;
303
304
18.5k
    if (!ossl_qrx_set_late_validation_cb(ch->qrx,
305
18.5k
                                         rx_late_validate,
306
18.5k
                                         ch))
307
0
        goto err;
308
309
18.5k
    if (!ossl_qrx_set_key_update_cb(ch->qrx,
310
18.5k
                                    rxku_detected,
311
18.5k
                                    ch))
312
0
        goto err;
313
314
74.1k
    for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
315
55.6k
        ch->crypto_recv[pn_space] = ossl_quic_rstream_new(NULL, NULL, 0);
316
55.6k
        if (ch->crypto_recv[pn_space] == NULL)
317
0
            goto err;
318
55.6k
    }
319
320
    /* Plug in the TLS handshake layer. */
321
18.5k
    tls_args.s                          = ch->tls;
322
18.5k
    tls_args.crypto_send_cb             = ch_on_crypto_send;
323
18.5k
    tls_args.crypto_send_cb_arg         = ch;
324
18.5k
    tls_args.crypto_recv_rcd_cb         = ch_on_crypto_recv_record;
325
18.5k
    tls_args.crypto_recv_rcd_cb_arg     = ch;
326
18.5k
    tls_args.crypto_release_rcd_cb      = ch_on_crypto_release_record;
327
18.5k
    tls_args.crypto_release_rcd_cb_arg  = ch;
328
18.5k
    tls_args.yield_secret_cb            = ch_on_handshake_yield_secret;
329
18.5k
    tls_args.yield_secret_cb_arg        = ch;
330
18.5k
    tls_args.got_transport_params_cb    = ch_on_transport_params;
331
18.5k
    tls_args.got_transport_params_cb_arg= ch;
332
18.5k
    tls_args.handshake_complete_cb      = ch_on_handshake_complete;
333
18.5k
    tls_args.handshake_complete_cb_arg  = ch;
334
18.5k
    tls_args.alert_cb                   = ch_on_handshake_alert;
335
18.5k
    tls_args.alert_cb_arg               = ch;
336
18.5k
    tls_args.is_server                  = ch->is_server;
337
338
18.5k
    if ((ch->qtls = ossl_quic_tls_new(&tls_args)) == NULL)
339
0
        goto err;
340
341
18.5k
    ch->tx_max_ack_delay        = DEFAULT_MAX_ACK_DELAY;
342
18.5k
    ch->rx_max_ack_delay        = QUIC_DEFAULT_MAX_ACK_DELAY;
343
18.5k
    ch->rx_ack_delay_exp        = QUIC_DEFAULT_ACK_DELAY_EXP;
344
18.5k
    ch->rx_active_conn_id_limit = QUIC_MIN_ACTIVE_CONN_ID_LIMIT;
345
18.5k
    ch->tx_enc_level            = QUIC_ENC_LEVEL_INITIAL;
346
18.5k
    ch->rx_enc_level            = QUIC_ENC_LEVEL_INITIAL;
347
18.5k
    ch->txku_threshold_override = UINT64_MAX;
348
349
18.5k
    ch->max_idle_timeout_local_req  = QUIC_DEFAULT_IDLE_TIMEOUT;
350
18.5k
    ch->max_idle_timeout_remote_req = 0;
351
18.5k
    ch->max_idle_timeout            = ch->max_idle_timeout_local_req;
352
353
18.5k
    ossl_ackm_set_tx_max_ack_delay(ch->ackm, ossl_ms2time(ch->tx_max_ack_delay));
354
18.5k
    ossl_ackm_set_rx_max_ack_delay(ch->ackm, ossl_ms2time(ch->rx_max_ack_delay));
355
356
18.5k
    ch_update_idle(ch);
357
18.5k
    ossl_list_ch_insert_tail(&ch->port->channel_list, ch);
358
18.5k
    ch->on_port_list = 1;
359
18.5k
    return 1;
360
361
0
err:
362
0
    ch_cleanup(ch);
363
0
    return 0;
364
18.5k
}
365
366
static void ch_cleanup(QUIC_CHANNEL *ch)
367
27.3k
{
368
27.3k
    uint32_t pn_space;
369
370
27.3k
    if (ch->ackm != NULL)
371
27.3k
        for (pn_space = QUIC_PN_SPACE_INITIAL;
372
109k
             pn_space < QUIC_PN_SPACE_NUM;
373
82.1k
             ++pn_space)
374
82.1k
            ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
375
376
27.3k
    ossl_quic_lcidm_cull(ch->lcidm, ch);
377
27.3k
    ossl_quic_srtm_cull(ch->srtm, ch);
378
27.3k
    ossl_quic_tx_packetiser_free(ch->txp);
379
27.3k
    ossl_quic_txpim_free(ch->txpim);
380
27.3k
    ossl_quic_cfq_free(ch->cfq);
381
27.3k
    ossl_qtx_free(ch->qtx);
382
27.3k
    if (ch->cc_data != NULL)
383
27.3k
        ch->cc_method->free(ch->cc_data);
384
27.3k
    if (ch->have_statm)
385
27.3k
        ossl_statm_destroy(&ch->statm);
386
27.3k
    ossl_ackm_free(ch->ackm);
387
388
27.3k
    if (ch->have_qsm)
389
27.3k
        ossl_quic_stream_map_cleanup(&ch->qsm);
390
391
109k
    for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
392
82.1k
        ossl_quic_sstream_free(ch->crypto_send[pn_space]);
393
82.1k
        ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
394
82.1k
    }
395
396
27.3k
    ossl_qrx_pkt_release(ch->qrx_pkt);
397
27.3k
    ch->qrx_pkt = NULL;
398
399
27.3k
    ossl_quic_tls_free(ch->qtls);
400
27.3k
    ossl_qrx_free(ch->qrx);
401
27.3k
    OPENSSL_free(ch->local_transport_params);
402
27.3k
    OPENSSL_free((char *)ch->terminate_cause.reason);
403
27.3k
    OSSL_ERR_STATE_free(ch->err_state);
404
27.3k
    OPENSSL_free(ch->ack_range_scratch);
405
406
27.3k
    if (ch->on_port_list) {
407
27.3k
        ossl_list_ch_remove(&ch->port->channel_list, ch);
408
27.3k
        ch->on_port_list = 0;
409
27.3k
    }
410
411
27.3k
#ifndef OPENSSL_NO_QLOG
412
27.3k
    if (ch->qlog != NULL)
413
0
        ossl_qlog_flush(ch->qlog); /* best effort */
414
415
27.3k
    OPENSSL_free(ch->qlog_title);
416
27.3k
    ossl_qlog_free(ch->qlog);
417
27.3k
#endif
418
27.3k
}
419
420
QUIC_CHANNEL *ossl_quic_channel_new(const QUIC_CHANNEL_ARGS *args)
421
18.5k
{
422
18.5k
    QUIC_CHANNEL *ch = NULL;
423
424
18.5k
    if ((ch = OPENSSL_zalloc(sizeof(*ch))) == NULL)
425
0
        return NULL;
426
427
18.5k
    ch->port        = args->port;
428
18.5k
    ch->is_server   = args->is_server;
429
18.5k
    ch->tls         = args->tls;
430
18.5k
    ch->lcidm       = args->lcidm;
431
18.5k
    ch->srtm        = args->srtm;
432
18.5k
#ifndef OPENSSL_NO_QLOG
433
18.5k
    ch->use_qlog    = args->use_qlog;
434
435
18.5k
    if (ch->use_qlog && args->qlog_title != NULL) {
436
0
        if ((ch->qlog_title = OPENSSL_strdup(args->qlog_title)) == NULL) {
437
0
            OPENSSL_free(ch);
438
0
            return NULL;
439
0
        }
440
0
    }
441
18.5k
#endif
442
443
18.5k
    if (!ch_init(ch)) {
444
0
        OPENSSL_free(ch);
445
0
        return NULL;
446
0
    }
447
448
18.5k
    return ch;
449
18.5k
}
450
451
void ossl_quic_channel_free(QUIC_CHANNEL *ch)
452
48.1k
{
453
48.1k
    if (ch == NULL)
454
0
        return;
455
456
48.1k
    ch_cleanup(ch);
457
48.1k
    OPENSSL_free(ch);
458
48.1k
}
459
460
/* Set mutator callbacks for test framework support */
461
int ossl_quic_channel_set_mutator(QUIC_CHANNEL *ch,
462
                                  ossl_mutate_packet_cb mutatecb,
463
                                  ossl_finish_mutate_cb finishmutatecb,
464
                                  void *mutatearg)
465
0
{
466
0
    if (ch->qtx == NULL)
467
0
        return 0;
468
469
0
    ossl_qtx_set_mutator(ch->qtx, mutatecb, finishmutatecb, mutatearg);
470
0
    return 1;
471
0
}
472
473
int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr)
474
0
{
475
0
    if (!ch->addressed_mode)
476
0
        return 0;
477
478
0
    return BIO_ADDR_copy(peer_addr, &ch->cur_peer_addr);
479
0
}
480
481
int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr)
482
48.1k
{
483
48.1k
    if (ch->state != QUIC_CHANNEL_STATE_IDLE)
484
0
        return 0;
485
486
48.1k
    if (peer_addr == NULL || BIO_ADDR_family(peer_addr) == AF_UNSPEC) {
487
0
        BIO_ADDR_clear(&ch->cur_peer_addr);
488
0
        ch->addressed_mode = 0;
489
0
        return 1;
490
0
    }
491
492
48.1k
    if (!BIO_ADDR_copy(&ch->cur_peer_addr, peer_addr)) {
493
0
        ch->addressed_mode = 0;
494
0
        return 0;
495
0
    }
496
48.1k
    ch->addressed_mode = 1;
497
498
48.1k
    return 1;
499
48.1k
}
500
501
QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch)
502
107M
{
503
107M
    return ossl_quic_port_get0_reactor(ch->port);
504
107M
}
505
506
QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch)
507
28.4M
{
508
28.4M
    return &ch->qsm;
509
28.4M
}
510
511
OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch)
512
82.1k
{
513
82.1k
    return &ch->statm;
514
82.1k
}
515
516
QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch,
517
                                                uint64_t stream_id)
518
0
{
519
0
    return ossl_quic_stream_map_get_by_id(&ch->qsm, stream_id);
520
0
}
521
522
int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch)
523
2.69M
{
524
2.69M
    return ch != NULL && ch->state == QUIC_CHANNEL_STATE_ACTIVE;
525
2.69M
}
526
527
int ossl_quic_channel_is_closing(const QUIC_CHANNEL *ch)
528
351M
{
529
351M
    return ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
530
351M
}
531
532
static int ossl_quic_channel_is_draining(const QUIC_CHANNEL *ch)
533
288M
{
534
288M
    return ch->state == QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
535
288M
}
536
537
static int ossl_quic_channel_is_terminating(const QUIC_CHANNEL *ch)
538
225M
{
539
225M
    return ossl_quic_channel_is_closing(ch)
540
225M
        || ossl_quic_channel_is_draining(ch);
541
225M
}
542
543
int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch)
544
351M
{
545
351M
    return ch->state == QUIC_CHANNEL_STATE_TERMINATED;
546
351M
}
547
548
int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch)
549
100M
{
550
100M
    return ossl_quic_channel_is_terminating(ch)
551
100M
        || ossl_quic_channel_is_terminated(ch);
552
100M
}
553
554
const QUIC_TERMINATE_CAUSE *
555
ossl_quic_channel_get_terminate_cause(const QUIC_CHANNEL *ch)
556
0
{
557
0
    return ossl_quic_channel_is_term_any(ch) ? &ch->terminate_cause : NULL;
558
0
}
559
560
int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch)
561
138M
{
562
138M
    return ch->handshake_complete;
563
138M
}
564
565
int ossl_quic_channel_is_handshake_confirmed(const QUIC_CHANNEL *ch)
566
0
{
567
0
    return ch->handshake_confirmed;
568
0
}
569
570
QUIC_DEMUX *ossl_quic_channel_get0_demux(QUIC_CHANNEL *ch)
571
0
{
572
0
    return ch->port->demux;
573
0
}
574
575
QUIC_PORT *ossl_quic_channel_get0_port(QUIC_CHANNEL *ch)
576
0
{
577
0
    return ch->port;
578
0
}
579
580
QUIC_ENGINE *ossl_quic_channel_get0_engine(QUIC_CHANNEL *ch)
581
0
{
582
0
    return ossl_quic_port_get0_engine(ch->port);
583
0
}
584
585
CRYPTO_MUTEX *ossl_quic_channel_get_mutex(QUIC_CHANNEL *ch)
586
0
{
587
0
    return ossl_quic_port_get0_mutex(ch->port);
588
0
}
589
590
int ossl_quic_channel_has_pending(const QUIC_CHANNEL *ch)
591
0
{
592
0
    return ossl_quic_demux_has_pending(ch->port->demux)
593
0
        || ossl_qrx_processed_read_pending(ch->qrx);
594
0
}
595
596
/*
597
 * QUIC Channel: Callbacks from Miscellaneous Subsidiary Components
598
 * ================================================================
599
 */
600
601
/* Used by various components. */
602
static OSSL_TIME get_time(void *arg)
603
94.7M
{
604
94.7M
    QUIC_CHANNEL *ch = arg;
605
606
94.7M
    return ossl_quic_port_get_time(ch->port);
607
94.7M
}
608
609
/* Used by QSM. */
610
static uint64_t get_stream_limit(int uni, void *arg)
611
69.2k
{
612
69.2k
    QUIC_CHANNEL *ch = arg;
613
614
69.2k
    return uni ? ch->max_local_streams_uni : ch->max_local_streams_bidi;
615
69.2k
}
616
617
/*
618
 * Called by QRX to determine if a packet is potentially invalid before trying
619
 * to decrypt it.
620
 */
621
static int rx_late_validate(QUIC_PN pn, int pn_space, void *arg)
622
757k
{
623
757k
    QUIC_CHANNEL *ch = arg;
624
625
    /* Potential duplicates should not be processed. */
626
757k
    if (!ossl_ackm_is_rx_pn_processable(ch->ackm, pn, pn_space))
627
147k
        return 0;
628
629
609k
    return 1;
630
757k
}
631
632
/*
633
 * Triggers a TXKU (whether spontaneous or solicited). Does not check whether
634
 * spontaneous TXKU is currently allowed.
635
 */
636
QUIC_NEEDS_LOCK
637
static void ch_trigger_txku(QUIC_CHANNEL *ch)
638
16.4k
{
639
16.4k
    uint64_t next_pn
640
16.4k
        = ossl_quic_tx_packetiser_get_next_pn(ch->txp, QUIC_PN_SPACE_APP);
641
642
16.4k
    if (!ossl_quic_pn_valid(next_pn)
643
16.4k
        || !ossl_qtx_trigger_key_update(ch->qtx)) {
644
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0,
645
0
                                               "key update");
646
0
        return;
647
0
    }
648
649
16.4k
    ch->txku_in_progress    = 1;
650
16.4k
    ch->txku_pn             = next_pn;
651
16.4k
    ch->rxku_expected       = ch->ku_locally_initiated;
652
16.4k
}
653
654
QUIC_NEEDS_LOCK
655
static int txku_in_progress(QUIC_CHANNEL *ch)
656
16.8M
{
657
16.8M
    if (ch->txku_in_progress
658
16.8M
        && ossl_ackm_get_largest_acked(ch->ackm, QUIC_PN_SPACE_APP) >= ch->txku_pn) {
659
13.9k
        OSSL_TIME pto = ossl_ackm_get_pto_duration(ch->ackm);
660
661
        /*
662
         * RFC 9001 s. 6.5: Endpoints SHOULD wait three times the PTO before
663
         * initiating a key update after receiving an acknowledgment that
664
         * confirms that the previous key update was received.
665
         *
666
         * Note that by the above wording, this period starts from when we get
667
         * the ack for a TXKU-triggering packet, not when the TXKU is initiated.
668
         * So we defer TXKU cooldown deadline calculation to this point.
669
         */
670
13.9k
        ch->txku_in_progress        = 0;
671
13.9k
        ch->txku_cooldown_deadline  = ossl_time_add(get_time(ch),
672
13.9k
                                                    ossl_time_multiply(pto, 3));
673
13.9k
    }
674
675
16.8M
    return ch->txku_in_progress;
676
16.8M
}
677
678
QUIC_NEEDS_LOCK
679
static int txku_allowed(QUIC_CHANNEL *ch)
680
62.6M
{
681
62.6M
    return ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT /* Sanity check. */
682
        /* Strict RFC 9001 criterion for TXKU. */
683
62.6M
        && ch->handshake_confirmed
684
62.6M
        && !txku_in_progress(ch);
685
62.6M
}
686
687
QUIC_NEEDS_LOCK
688
static int txku_recommendable(QUIC_CHANNEL *ch)
689
62.6M
{
690
62.6M
    if (!txku_allowed(ch))
691
47.5M
        return 0;
692
693
15.0M
    return
694
        /* Recommended RFC 9001 criterion for TXKU. */
695
15.0M
        ossl_time_compare(get_time(ch), ch->txku_cooldown_deadline) >= 0
696
        /* Some additional sensible criteria. */
697
15.0M
        && !ch->rxku_in_progress
698
15.0M
        && !ch->rxku_pending_confirm;
699
62.6M
}
700
701
QUIC_NEEDS_LOCK
702
static int txku_desirable(QUIC_CHANNEL *ch)
703
11.4M
{
704
11.4M
    uint64_t cur_pkt_count, max_pkt_count, thresh_pkt_count;
705
11.4M
    const uint32_t enc_level = QUIC_ENC_LEVEL_1RTT;
706
707
    /* Check AEAD limit to determine if we should perform a spontaneous TXKU. */
708
11.4M
    cur_pkt_count = ossl_qtx_get_cur_epoch_pkt_count(ch->qtx, enc_level);
709
11.4M
    max_pkt_count = ossl_qtx_get_max_epoch_pkt_count(ch->qtx, enc_level);
710
711
11.4M
    thresh_pkt_count = max_pkt_count / 2;
712
11.4M
    if (ch->txku_threshold_override != UINT64_MAX)
713
0
        thresh_pkt_count = ch->txku_threshold_override;
714
715
11.4M
    return cur_pkt_count >= thresh_pkt_count;
716
11.4M
}
717
718
QUIC_NEEDS_LOCK
719
static void ch_maybe_trigger_spontaneous_txku(QUIC_CHANNEL *ch)
720
62.6M
{
721
62.6M
    if (!txku_recommendable(ch) || !txku_desirable(ch))
722
62.6M
        return;
723
724
0
    ch->ku_locally_initiated = 1;
725
0
    ch_trigger_txku(ch);
726
0
}
727
728
QUIC_NEEDS_LOCK
729
static int rxku_allowed(QUIC_CHANNEL *ch)
730
16.6k
{
731
    /*
732
     * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a key update prior to
733
     * having confirmed the handshake (Section 4.1.2).
734
     *
735
     * RFC 9001 s. 6.1: An endpoint MUST NOT initiate a subsequent key update
736
     * unless it has received an acknowledgment for a packet that was sent
737
     * protected with keys from the current key phase.
738
     *
739
     * RFC 9001 s. 6.2: If an endpoint detects a second update before it has
740
     * sent any packets with updated keys containing an acknowledgment for the
741
     * packet that initiated the key update, it indicates that its peer has
742
     * updated keys twice without awaiting confirmation. An endpoint MAY treat
743
     * such consecutive key updates as a connection error of type
744
     * KEY_UPDATE_ERROR.
745
     */
746
16.6k
    return ch->handshake_confirmed && !ch->rxku_pending_confirm;
747
16.6k
}
748
749
/*
750
 * Called when the QRX detects a new RX key update event.
751
 */
752
enum rxku_decision {
753
    DECISION_RXKU_ONLY,
754
    DECISION_PROTOCOL_VIOLATION,
755
    DECISION_SOLICITED_TXKU
756
};
757
758
/* Called when the QRX detects a key update has occurred. */
759
QUIC_NEEDS_LOCK
760
static void rxku_detected(QUIC_PN pn, void *arg)
761
16.6k
{
762
16.6k
    QUIC_CHANNEL *ch = arg;
763
16.6k
    enum rxku_decision decision;
764
16.6k
    OSSL_TIME pto;
765
766
    /*
767
     * Note: rxku_in_progress is always 0 here as an RXKU cannot be detected
768
     * when we are still in UPDATING or COOLDOWN (see quic_record_rx.h).
769
     */
770
16.6k
    assert(!ch->rxku_in_progress);
771
772
16.6k
    if (!rxku_allowed(ch))
773
        /* Is RXKU even allowed at this time? */
774
183
        decision = DECISION_PROTOCOL_VIOLATION;
775
776
16.4k
    else if (ch->ku_locally_initiated)
777
        /*
778
         * If this key update was locally initiated (meaning that this detected
779
         * RXKU event is a result of our own spontaneous TXKU), we do not
780
         * trigger another TXKU; after all, to do so would result in an infinite
781
         * ping-pong of key updates. We still process it as an RXKU.
782
         */
783
0
        decision = DECISION_RXKU_ONLY;
784
785
16.4k
    else
786
        /*
787
         * Otherwise, a peer triggering a KU means we have to trigger a KU also.
788
         */
789
16.4k
        decision = DECISION_SOLICITED_TXKU;
790
791
16.6k
    if (decision == DECISION_PROTOCOL_VIOLATION) {
792
183
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_KEY_UPDATE_ERROR,
793
183
                                               0, "RX key update again too soon");
794
183
        return;
795
183
    }
796
797
16.4k
    pto = ossl_ackm_get_pto_duration(ch->ackm);
798
799
16.4k
    ch->ku_locally_initiated        = 0;
800
16.4k
    ch->rxku_in_progress            = 1;
801
16.4k
    ch->rxku_pending_confirm        = 1;
802
16.4k
    ch->rxku_trigger_pn             = pn;
803
16.4k
    ch->rxku_update_end_deadline    = ossl_time_add(get_time(ch), pto);
804
16.4k
    ch->rxku_expected               = 0;
805
806
16.4k
    if (decision == DECISION_SOLICITED_TXKU)
807
        /* NOT gated by usual txku_allowed() */
808
16.4k
        ch_trigger_txku(ch);
809
810
    /*
811
     * Ordinarily, we only generate ACK when some ACK-eliciting frame has been
812
     * received. In some cases, this may not occur for a long time, for example
813
     * if transmission of application data is going in only one direction and
814
     * nothing else is happening with the connection. However, since the peer
815
     * cannot initiate a subsequent (spontaneous) TXKU until its prior
816
     * (spontaneous or solicited) TXKU has completed - meaning that prior
817
     * TXKU's trigger packet (or subsequent packet) has been acknowledged, this
818
     * can lead to very long times before a TXKU is considered 'completed'.
819
     * Optimise this by forcing ACK generation after triggering TXKU.
820
     * (Basically, we consider a RXKU event something that is 'ACK-eliciting',
821
     * which it more or less should be; it is necessarily separate from ordinary
822
     * processing of ACK-eliciting frames as key update is not indicated via a
823
     * frame.)
824
     */
825
16.4k
    ossl_quic_tx_packetiser_schedule_ack(ch->txp, QUIC_PN_SPACE_APP);
826
16.4k
}
827
828
/* Called per tick to handle RXKU timer events. */
829
QUIC_NEEDS_LOCK
830
static void ch_rxku_tick(QUIC_CHANNEL *ch)
831
62.6M
{
832
62.6M
    if (!ch->rxku_in_progress
833
62.6M
        || ossl_time_compare(get_time(ch), ch->rxku_update_end_deadline) < 0)
834
62.6M
        return;
835
836
13.8k
    ch->rxku_update_end_deadline    = ossl_time_infinite();
837
13.8k
    ch->rxku_in_progress            = 0;
838
839
13.8k
    if (!ossl_qrx_key_update_timeout(ch->qrx, /*normal=*/1))
840
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0,
841
13.8k
                                               "RXKU cooldown internal error");
842
13.8k
}
843
844
QUIC_NEEDS_LOCK
845
static void ch_on_txp_ack_tx(const OSSL_QUIC_FRAME_ACK *ack, uint32_t pn_space,
846
                             void *arg)
847
5.31M
{
848
5.31M
    QUIC_CHANNEL *ch = arg;
849
850
5.31M
    if (pn_space != QUIC_PN_SPACE_APP || !ch->rxku_pending_confirm
851
5.31M
        || !ossl_quic_frame_ack_contains_pn(ack, ch->rxku_trigger_pn))
852
5.26M
        return;
853
854
    /*
855
     * Defer clearing rxku_pending_confirm until TXP generate call returns
856
     * successfully.
857
     */
858
47.8k
    ch->rxku_pending_confirm_done = 1;
859
47.8k
}
860
861
/*
862
 * QUIC Channel: Handshake Layer Event Handling
863
 * ============================================
864
 */
865
static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
866
                             size_t *consumed, void *arg)
867
60.2k
{
868
60.2k
    int ret;
869
60.2k
    QUIC_CHANNEL *ch = arg;
870
60.2k
    uint32_t enc_level = ch->tx_enc_level;
871
60.2k
    uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
872
60.2k
    QUIC_SSTREAM *sstream = ch->crypto_send[pn_space];
873
874
60.2k
    if (!ossl_assert(sstream != NULL))
875
0
        return 0;
876
877
60.2k
    ret = ossl_quic_sstream_append(sstream, buf, buf_len, consumed);
878
60.2k
    return ret;
879
60.2k
}
880
881
static int crypto_ensure_empty(QUIC_RSTREAM *rstream)
882
53.3M
{
883
53.3M
    size_t avail = 0;
884
53.3M
    int is_fin = 0;
885
886
53.3M
    if (rstream == NULL)
887
39.4M
        return 1;
888
889
13.9M
    if (!ossl_quic_rstream_available(rstream, &avail, &is_fin))
890
0
        return 0;
891
892
13.9M
    return avail == 0;
893
13.9M
}
894
895
static int ch_on_crypto_recv_record(const unsigned char **buf,
896
                                    size_t *bytes_read, void *arg)
897
62.7M
{
898
62.7M
    QUIC_CHANNEL *ch = arg;
899
62.7M
    QUIC_RSTREAM *rstream;
900
62.7M
    int is_fin = 0; /* crypto stream is never finished, so we don't use this */
901
62.7M
    uint32_t i;
902
903
    /*
904
     * After we move to a later EL we must not allow our peer to send any new
905
     * bytes in the crypto stream on a previous EL. Retransmissions of old bytes
906
     * are allowed.
907
     *
908
     * In practice we will only move to a new EL when we have consumed all bytes
909
     * which should be sent on the crypto stream at a previous EL. For example,
910
     * the Handshake EL should not be provisioned until we have completely
911
     * consumed a TLS 1.3 ServerHello. Thus when we provision an EL the output
912
     * of ossl_quic_rstream_available() should be 0 for all lower ELs. Thus if a
913
     * given EL is available we simply ensure we have not received any further
914
     * bytes at a lower EL.
915
     */
916
142M
    for (i = QUIC_ENC_LEVEL_INITIAL; i < ch->rx_enc_level; ++i)
917
79.4M
        if (i != QUIC_ENC_LEVEL_0RTT &&
918
79.4M
            !crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
919
            /* Protocol violation (RFC 9001 s. 4.1.3) */
920
14
            ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
921
14
                                                   OSSL_QUIC_FRAME_TYPE_CRYPTO,
922
14
                                                   "crypto stream data in wrong EL");
923
14
            return 0;
924
14
        }
925
926
62.7M
    rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
927
62.7M
    if (rstream == NULL)
928
0
        return 0;
929
930
62.7M
    return ossl_quic_rstream_get_record(rstream, buf, bytes_read,
931
62.7M
                                        &is_fin);
932
62.7M
}
933
934
static int ch_on_crypto_release_record(size_t bytes_read, void *arg)
935
69.5k
{
936
69.5k
    QUIC_CHANNEL *ch = arg;
937
69.5k
    QUIC_RSTREAM *rstream;
938
69.5k
    OSSL_RTT_INFO rtt_info;
939
69.5k
    uint32_t rx_pn_space = ossl_quic_enc_level_to_pn_space(ch->rx_enc_level);
940
941
69.5k
    rstream = ch->crypto_recv[rx_pn_space];
942
69.5k
    if (rstream == NULL)
943
0
        return 0;
944
945
69.5k
    ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(ch), &rtt_info);
946
69.5k
    if (!ossl_quic_rxfc_on_retire(&ch->crypto_rxfc[rx_pn_space], bytes_read,
947
69.5k
                                  rtt_info.smoothed_rtt))
948
0
        return 0;
949
950
69.5k
    return ossl_quic_rstream_release_record(rstream, bytes_read);
951
69.5k
}
952
953
static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
954
                                        uint32_t suite_id, EVP_MD *md,
955
                                        const unsigned char *secret,
956
                                        size_t secret_len,
957
                                        void *arg)
958
43.3k
{
959
43.3k
    QUIC_CHANNEL *ch = arg;
960
43.3k
    uint32_t i;
961
962
43.3k
    if (enc_level < QUIC_ENC_LEVEL_HANDSHAKE || enc_level >= QUIC_ENC_LEVEL_NUM)
963
        /* Invalid EL. */
964
0
        return 0;
965
966
967
43.3k
    if (direction) {
968
        /* TX */
969
21.6k
        if (enc_level <= ch->tx_enc_level)
970
            /*
971
             * Does not make sense for us to try and provision an EL we have already
972
             * attained.
973
             */
974
0
            return 0;
975
976
21.6k
        if (!ossl_qtx_provide_secret(ch->qtx, enc_level,
977
21.6k
                                     suite_id, md,
978
21.6k
                                     secret, secret_len))
979
0
            return 0;
980
981
21.6k
        ch->tx_enc_level = enc_level;
982
21.6k
    } else {
983
        /* RX */
984
21.6k
        if (enc_level <= ch->rx_enc_level)
985
            /*
986
             * Does not make sense for us to try and provision an EL we have already
987
             * attained.
988
             */
989
0
            return 0;
990
991
        /*
992
         * Ensure all crypto streams for previous ELs are now empty of available
993
         * data.
994
         */
995
57.8k
        for (i = QUIC_ENC_LEVEL_INITIAL; i < enc_level; ++i)
996
36.2k
            if (!crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
997
                /* Protocol violation (RFC 9001 s. 4.1.3) */
998
20
                ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
999
20
                                                    OSSL_QUIC_FRAME_TYPE_CRYPTO,
1000
20
                                                    "crypto stream data in wrong EL");
1001
20
                return 0;
1002
20
            }
1003
1004
21.6k
        if (!ossl_qrx_provide_secret(ch->qrx, enc_level,
1005
21.6k
                                     suite_id, md,
1006
21.6k
                                     secret, secret_len))
1007
0
            return 0;
1008
1009
21.6k
        ch->have_new_rx_secret = 1;
1010
21.6k
        ch->rx_enc_level = enc_level;
1011
21.6k
    }
1012
1013
43.2k
    return 1;
1014
43.3k
}
1015
1016
static int ch_on_handshake_complete(void *arg)
1017
7.25k
{
1018
7.25k
    QUIC_CHANNEL *ch = arg;
1019
1020
7.25k
    if (!ossl_assert(!ch->handshake_complete))
1021
0
        return 0; /* this should not happen twice */
1022
1023
7.25k
    if (!ossl_assert(ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT))
1024
0
        return 0;
1025
1026
7.25k
    if (!ch->got_remote_transport_params) {
1027
        /*
1028
         * Was not a valid QUIC handshake if we did not get valid transport
1029
         * params.
1030
         */
1031
59
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_CRYPTO_MISSING_EXT,
1032
59
                                               OSSL_QUIC_FRAME_TYPE_CRYPTO,
1033
59
                                               "no transport parameters received");
1034
59
        return 0;
1035
59
    }
1036
1037
    /* Don't need transport parameters anymore. */
1038
7.19k
    OPENSSL_free(ch->local_transport_params);
1039
7.19k
    ch->local_transport_params = NULL;
1040
1041
    /* Tell the QRX it can now process 1-RTT packets. */
1042
7.19k
    ossl_qrx_allow_1rtt_processing(ch->qrx);
1043
1044
    /* Tell TXP the handshake is complete. */
1045
7.19k
    ossl_quic_tx_packetiser_notify_handshake_complete(ch->txp);
1046
1047
7.19k
    ch->handshake_complete = 1;
1048
1049
7.19k
    if (ch->is_server) {
1050
        /*
1051
         * On the server, the handshake is confirmed as soon as it is complete.
1052
         */
1053
0
        ossl_quic_channel_on_handshake_confirmed(ch);
1054
1055
0
        ossl_quic_tx_packetiser_schedule_handshake_done(ch->txp);
1056
0
    }
1057
1058
7.19k
    ch_record_state_transition(ch, ch->state);
1059
7.19k
    return 1;
1060
7.25k
}
1061
1062
static int ch_on_handshake_alert(void *arg, unsigned char alert_code)
1063
10.6k
{
1064
10.6k
    QUIC_CHANNEL *ch = arg;
1065
1066
    /*
1067
     * RFC 9001 s. 4.4: More specifically, servers MUST NOT send post-handshake
1068
     * TLS CertificateRequest messages, and clients MUST treat receipt of such
1069
     * messages as a connection error of type PROTOCOL_VIOLATION.
1070
     */
1071
10.6k
    if (alert_code == SSL_AD_UNEXPECTED_MESSAGE
1072
10.6k
            && ch->handshake_complete
1073
10.6k
            && ossl_quic_tls_is_cert_request(ch->qtls))
1074
7
        ossl_quic_channel_raise_protocol_error(ch,
1075
10.6k
                                               OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
1076
10.6k
                                               0,
1077
10.6k
                                               "Post-handshake TLS "
1078
10.6k
                                               "CertificateRequest received");
1079
    /*
1080
     * RFC 9001 s. 4.6.1: Servers MUST NOT send the early_data extension with a
1081
     * max_early_data_size field set to any value other than 0xffffffff. A
1082
     * client MUST treat receipt of a NewSessionTicket that contains an
1083
     * early_data extension with any other value as a connection error of type
1084
     * PROTOCOL_VIOLATION.
1085
     */
1086
10.6k
    else if (alert_code == SSL_AD_ILLEGAL_PARAMETER
1087
10.6k
             && ch->handshake_complete
1088
10.6k
             && ossl_quic_tls_has_bad_max_early_data(ch->qtls))
1089
0
        ossl_quic_channel_raise_protocol_error(ch,
1090
10.6k
                                               OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
1091
10.6k
                                               0,
1092
10.6k
                                               "Bad max_early_data received");
1093
10.6k
    else
1094
10.6k
        ossl_quic_channel_raise_protocol_error(ch,
1095
10.6k
                                               OSSL_QUIC_ERR_CRYPTO_ERR_BEGIN
1096
10.6k
                                               + alert_code,
1097
10.6k
                                               0, "handshake alert");
1098
1099
10.6k
    return 1;
1100
10.6k
}
1101
1102
/*
1103
 * QUIC Channel: Transport Parameter Handling
1104
 * ==========================================
1105
 */
1106
1107
/*
1108
 * Called by handshake layer when we receive QUIC Transport Parameters from the
1109
 * peer. Note that these are not authenticated until the handshake is marked
1110
 * as complete.
1111
 */
1112
#define TP_REASON_SERVER_ONLY(x) \
1113
0
    x " may not be sent by a client"
1114
#define TP_REASON_DUP(x) \
1115
53
    x " appears multiple times"
1116
#define TP_REASON_MALFORMED(x) \
1117
223
    x " is malformed"
1118
#define TP_REASON_EXPECTED_VALUE(x) \
1119
28
    x " does not match expected value"
1120
#define TP_REASON_NOT_RETRY(x) \
1121
2
    x " sent when not performing a retry"
1122
#define TP_REASON_REQUIRED(x) \
1123
16
    x " was not sent but is required"
1124
#define TP_REASON_INTERNAL_ERROR(x) \
1125
0
    x " encountered internal error"
1126
1127
static void txfc_bump_cwm_bidi(QUIC_STREAM *s, void *arg)
1128
0
{
1129
0
    if (!ossl_quic_stream_is_bidi(s)
1130
0
        || ossl_quic_stream_is_server_init(s))
1131
0
        return;
1132
1133
0
    ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
1134
0
}
1135
1136
static void txfc_bump_cwm_uni(QUIC_STREAM *s, void *arg)
1137
0
{
1138
0
    if (ossl_quic_stream_is_bidi(s)
1139
0
        || ossl_quic_stream_is_server_init(s))
1140
0
        return;
1141
1142
0
    ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
1143
0
}
1144
1145
static void do_update(QUIC_STREAM *s, void *arg)
1146
0
{
1147
0
    QUIC_CHANNEL *ch = arg;
1148
1149
0
    ossl_quic_stream_map_update_state(&ch->qsm, s);
1150
0
}
1151
1152
static uint64_t min_u64_ignore_0(uint64_t a, uint64_t b)
1153
14.8k
{
1154
14.8k
    if (a == 0)
1155
0
        return b;
1156
14.8k
    if (b == 0)
1157
15
        return a;
1158
1159
14.8k
    return a < b ? a : b;
1160
14.8k
}
1161
1162
static int ch_on_transport_params(const unsigned char *params,
1163
                                  size_t params_len,
1164
                                  void *arg)
1165
7.55k
{
1166
7.55k
    QUIC_CHANNEL *ch = arg;
1167
7.55k
    PACKET pkt;
1168
7.55k
    uint64_t id, v;
1169
7.55k
    size_t len;
1170
7.55k
    const unsigned char *body;
1171
7.55k
    int got_orig_dcid = 0;
1172
7.55k
    int got_initial_scid = 0;
1173
7.55k
    int got_retry_scid = 0;
1174
7.55k
    int got_initial_max_data = 0;
1175
7.55k
    int got_initial_max_stream_data_bidi_local = 0;
1176
7.55k
    int got_initial_max_stream_data_bidi_remote = 0;
1177
7.55k
    int got_initial_max_stream_data_uni = 0;
1178
7.55k
    int got_initial_max_streams_bidi = 0;
1179
7.55k
    int got_initial_max_streams_uni = 0;
1180
7.55k
    int got_stateless_reset_token = 0;
1181
7.55k
    int got_preferred_addr = 0;
1182
7.55k
    int got_ack_delay_exp = 0;
1183
7.55k
    int got_max_ack_delay = 0;
1184
7.55k
    int got_max_udp_payload_size = 0;
1185
7.55k
    int got_max_idle_timeout = 0;
1186
7.55k
    int got_active_conn_id_limit = 0;
1187
7.55k
    int got_disable_active_migration = 0;
1188
7.55k
    QUIC_CONN_ID cid;
1189
7.55k
    const char *reason = "bad transport parameter";
1190
7.55k
    ossl_unused uint64_t rx_max_idle_timeout = 0;
1191
7.55k
    ossl_unused const void *stateless_reset_token_p = NULL;
1192
7.55k
    QUIC_PREFERRED_ADDR pfa;
1193
1194
7.55k
    if (ch->got_remote_transport_params) {
1195
0
        reason = "multiple transport parameter extensions";
1196
0
        goto malformed;
1197
0
    }
1198
1199
7.55k
    if (!PACKET_buf_init(&pkt, params, params_len)) {
1200
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0,
1201
0
                                               "internal error (packet buf init)");
1202
0
        return 0;
1203
0
    }
1204
1205
94.6k
    while (PACKET_remaining(&pkt) > 0) {
1206
87.4k
        if (!ossl_quic_wire_peek_transport_param(&pkt, &id))
1207
2
            goto malformed;
1208
1209
87.4k
        switch (id) {
1210
7.51k
        case QUIC_TPARAM_ORIG_DCID:
1211
7.51k
            if (got_orig_dcid) {
1212
6
                reason = TP_REASON_DUP("ORIG_DCID");
1213
6
                goto malformed;
1214
6
            }
1215
1216
7.50k
            if (ch->is_server) {
1217
0
                reason = TP_REASON_SERVER_ONLY("ORIG_DCID");
1218
0
                goto malformed;
1219
0
            }
1220
1221
7.50k
            if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1222
8
                reason = TP_REASON_MALFORMED("ORIG_DCID");
1223
8
                goto malformed;
1224
8
            }
1225
1226
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
1227
            /* Must match our initial DCID. */
1228
            if (!ossl_quic_conn_id_eq(&ch->init_dcid, &cid)) {
1229
                reason = TP_REASON_EXPECTED_VALUE("ORIG_DCID");
1230
                goto malformed;
1231
            }
1232
#endif
1233
1234
7.49k
            got_orig_dcid = 1;
1235
7.49k
            break;
1236
1237
12
        case QUIC_TPARAM_RETRY_SCID:
1238
12
            if (ch->is_server) {
1239
0
                reason = TP_REASON_SERVER_ONLY("RETRY_SCID");
1240
0
                goto malformed;
1241
0
            }
1242
1243
12
            if (got_retry_scid) {
1244
2
                reason = TP_REASON_DUP("RETRY_SCID");
1245
2
                goto malformed;
1246
2
            }
1247
1248
10
            if (!ch->doing_retry) {
1249
2
                reason = TP_REASON_NOT_RETRY("RETRY_SCID");
1250
2
                goto malformed;
1251
2
            }
1252
1253
8
            if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1254
2
                reason = TP_REASON_MALFORMED("RETRY_SCID");
1255
2
                goto malformed;
1256
2
            }
1257
1258
            /* Must match Retry packet SCID. */
1259
6
            if (!ossl_quic_conn_id_eq(&ch->retry_scid, &cid)) {
1260
4
                reason = TP_REASON_EXPECTED_VALUE("RETRY_SCID");
1261
4
                goto malformed;
1262
4
            }
1263
1264
2
            got_retry_scid = 1;
1265
2
            break;
1266
1267
7.47k
        case QUIC_TPARAM_INITIAL_SCID:
1268
7.47k
            if (got_initial_scid) {
1269
                /* must not appear more than once */
1270
2
                reason = TP_REASON_DUP("INITIAL_SCID");
1271
2
                goto malformed;
1272
2
            }
1273
1274
7.47k
            if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
1275
9
                reason = TP_REASON_MALFORMED("INITIAL_SCID");
1276
9
                goto malformed;
1277
9
            }
1278
1279
            /* Must match SCID of first Initial packet from server. */
1280
7.46k
            if (!ossl_quic_conn_id_eq(&ch->init_scid, &cid)) {
1281
24
                reason = TP_REASON_EXPECTED_VALUE("INITIAL_SCID");
1282
24
                goto malformed;
1283
24
            }
1284
1285
7.43k
            got_initial_scid = 1;
1286
7.43k
            break;
1287
1288
6.76k
        case QUIC_TPARAM_INITIAL_MAX_DATA:
1289
6.76k
            if (got_initial_max_data) {
1290
                /* must not appear more than once */
1291
5
                reason = TP_REASON_DUP("INITIAL_MAX_DATA");
1292
5
                goto malformed;
1293
5
            }
1294
1295
6.76k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1296
11
                reason = TP_REASON_MALFORMED("INITIAL_MAX_DATA");
1297
11
                goto malformed;
1298
11
            }
1299
1300
6.75k
            ossl_quic_txfc_bump_cwm(&ch->conn_txfc, v);
1301
6.75k
            got_initial_max_data = 1;
1302
6.75k
            break;
1303
1304
7.10k
        case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL:
1305
7.10k
            if (got_initial_max_stream_data_bidi_local) {
1306
                /* must not appear more than once */
1307
3
                reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
1308
3
                goto malformed;
1309
3
            }
1310
1311
7.10k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1312
14
                reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
1313
14
                goto malformed;
1314
14
            }
1315
1316
            /*
1317
             * This is correct; the BIDI_LOCAL TP governs streams created by
1318
             * the endpoint which sends the TP, i.e., our peer.
1319
             */
1320
7.09k
            ch->rx_init_max_stream_data_bidi_remote = v;
1321
7.09k
            got_initial_max_stream_data_bidi_local = 1;
1322
7.09k
            break;
1323
1324
7.23k
        case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE:
1325
7.23k
            if (got_initial_max_stream_data_bidi_remote) {
1326
                /* must not appear more than once */
1327
8
                reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
1328
8
                goto malformed;
1329
8
            }
1330
1331
7.22k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1332
12
                reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
1333
12
                goto malformed;
1334
12
            }
1335
1336
            /*
1337
             * This is correct; the BIDI_REMOTE TP governs streams created
1338
             * by the endpoint which receives the TP, i.e., us.
1339
             */
1340
7.21k
            ch->rx_init_max_stream_data_bidi_local = v;
1341
1342
            /* Apply to all existing streams. */
1343
7.21k
            ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_bidi, &v);
1344
7.21k
            got_initial_max_stream_data_bidi_remote = 1;
1345
7.21k
            break;
1346
1347
7.21k
        case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI:
1348
7.21k
            if (got_initial_max_stream_data_uni) {
1349
                /* must not appear more than once */
1350
2
                reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_UNI");
1351
2
                goto malformed;
1352
2
            }
1353
1354
7.21k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1355
7
                reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_UNI");
1356
7
                goto malformed;
1357
7
            }
1358
1359
7.20k
            ch->rx_init_max_stream_data_uni = v;
1360
1361
            /* Apply to all existing streams. */
1362
7.20k
            ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_uni, &v);
1363
7.20k
            got_initial_max_stream_data_uni = 1;
1364
7.20k
            break;
1365
1366
14
        case QUIC_TPARAM_ACK_DELAY_EXP:
1367
14
            if (got_ack_delay_exp) {
1368
                /* must not appear more than once */
1369
2
                reason = TP_REASON_DUP("ACK_DELAY_EXP");
1370
2
                goto malformed;
1371
2
            }
1372
1373
12
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1374
12
                || v > QUIC_MAX_ACK_DELAY_EXP) {
1375
8
                reason = TP_REASON_MALFORMED("ACK_DELAY_EXP");
1376
8
                goto malformed;
1377
8
            }
1378
1379
4
            ch->rx_ack_delay_exp = (unsigned char)v;
1380
4
            got_ack_delay_exp = 1;
1381
4
            break;
1382
1383
92
        case QUIC_TPARAM_MAX_ACK_DELAY:
1384
92
            if (got_max_ack_delay) {
1385
                /* must not appear more than once */
1386
2
                reason = TP_REASON_DUP("MAX_ACK_DELAY");
1387
2
                goto malformed;
1388
2
            }
1389
1390
90
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1391
90
                || v >= (((uint64_t)1) << 14)) {
1392
17
                reason = TP_REASON_MALFORMED("MAX_ACK_DELAY");
1393
17
                goto malformed;
1394
17
            }
1395
1396
73
            ch->rx_max_ack_delay = v;
1397
73
            ossl_ackm_set_rx_max_ack_delay(ch->ackm,
1398
73
                                           ossl_ms2time(ch->rx_max_ack_delay));
1399
1400
73
            got_max_ack_delay = 1;
1401
73
            break;
1402
1403
7.15k
        case QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI:
1404
7.15k
            if (got_initial_max_streams_bidi) {
1405
                /* must not appear more than once */
1406
4
                reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_BIDI");
1407
4
                goto malformed;
1408
4
            }
1409
1410
7.15k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1411
7.15k
                || v > (((uint64_t)1) << 60)) {
1412
25
                reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_BIDI");
1413
25
                goto malformed;
1414
25
            }
1415
1416
7.12k
            assert(ch->max_local_streams_bidi == 0);
1417
7.12k
            ch->max_local_streams_bidi = v;
1418
7.12k
            got_initial_max_streams_bidi = 1;
1419
7.12k
            break;
1420
1421
7.16k
        case QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI:
1422
7.16k
            if (got_initial_max_streams_uni) {
1423
                /* must not appear more than once */
1424
4
                reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_UNI");
1425
4
                goto malformed;
1426
4
            }
1427
1428
7.16k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1429
7.16k
                || v > (((uint64_t)1) << 60)) {
1430
32
                reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_UNI");
1431
32
                goto malformed;
1432
32
            }
1433
1434
7.13k
            assert(ch->max_local_streams_uni == 0);
1435
7.13k
            ch->max_local_streams_uni = v;
1436
7.13k
            got_initial_max_streams_uni = 1;
1437
7.13k
            break;
1438
1439
7.43k
        case QUIC_TPARAM_MAX_IDLE_TIMEOUT:
1440
7.43k
            if (got_max_idle_timeout) {
1441
                /* must not appear more than once */
1442
2
                reason = TP_REASON_DUP("MAX_IDLE_TIMEOUT");
1443
2
                goto malformed;
1444
2
            }
1445
1446
7.43k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1447
8
                reason = TP_REASON_MALFORMED("MAX_IDLE_TIMEOUT");
1448
8
                goto malformed;
1449
8
            }
1450
1451
7.42k
            ch->max_idle_timeout_remote_req = v;
1452
1453
7.42k
            ch->max_idle_timeout = min_u64_ignore_0(ch->max_idle_timeout_local_req,
1454
7.42k
                                                    ch->max_idle_timeout_remote_req);
1455
1456
1457
7.42k
            ch_update_idle(ch);
1458
7.42k
            got_max_idle_timeout = 1;
1459
7.42k
            rx_max_idle_timeout = v;
1460
7.42k
            break;
1461
1462
6.91k
        case QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE:
1463
6.91k
            if (got_max_udp_payload_size) {
1464
                /* must not appear more than once */
1465
2
                reason = TP_REASON_DUP("MAX_UDP_PAYLOAD_SIZE");
1466
2
                goto malformed;
1467
2
            }
1468
1469
6.91k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1470
6.91k
                || v < QUIC_MIN_INITIAL_DGRAM_LEN) {
1471
24
                reason = TP_REASON_MALFORMED("MAX_UDP_PAYLOAD_SIZE");
1472
24
                goto malformed;
1473
24
            }
1474
1475
6.88k
            ch->rx_max_udp_payload_size = v;
1476
6.88k
            got_max_udp_payload_size    = 1;
1477
6.88k
            break;
1478
1479
6.77k
        case QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT:
1480
6.77k
            if (got_active_conn_id_limit) {
1481
                /* must not appear more than once */
1482
2
                reason = TP_REASON_DUP("ACTIVE_CONN_ID_LIMIT");
1483
2
                goto malformed;
1484
2
            }
1485
1486
6.76k
            if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1487
6.76k
                || v < QUIC_MIN_ACTIVE_CONN_ID_LIMIT) {
1488
12
                reason = TP_REASON_MALFORMED("ACTIVE_CONN_ID_LIMIT");
1489
12
                goto malformed;
1490
12
            }
1491
1492
6.75k
            ch->rx_active_conn_id_limit = v;
1493
6.75k
            got_active_conn_id_limit = 1;
1494
6.75k
            break;
1495
1496
15
        case QUIC_TPARAM_STATELESS_RESET_TOKEN:
1497
15
            if (got_stateless_reset_token) {
1498
2
                reason = TP_REASON_DUP("STATELESS_RESET_TOKEN");
1499
2
                goto malformed;
1500
2
            }
1501
1502
            /*
1503
             * We must ensure a client doesn't send them because we don't have
1504
             * processing for them.
1505
             *
1506
             * TODO(QUIC SERVER): remove this restriction
1507
             */
1508
13
            if (ch->is_server) {
1509
0
                reason = TP_REASON_SERVER_ONLY("STATELESS_RESET_TOKEN");
1510
0
                goto malformed;
1511
0
            }
1512
1513
13
            body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1514
13
            if (body == NULL || len != QUIC_STATELESS_RESET_TOKEN_LEN) {
1515
9
                reason = TP_REASON_MALFORMED("STATELESS_RESET_TOKEN");
1516
9
                goto malformed;
1517
9
            }
1518
4
            if (!ossl_quic_srtm_add(ch->srtm, ch, ch->cur_remote_seq_num,
1519
4
                                    (const QUIC_STATELESS_RESET_TOKEN *)body)) {
1520
0
                reason = TP_REASON_INTERNAL_ERROR("STATELESS_RESET_TOKEN");
1521
0
                goto malformed;
1522
0
            }
1523
1524
4
            stateless_reset_token_p     = body;
1525
4
            got_stateless_reset_token   = 1;
1526
4
            break;
1527
1528
19
        case QUIC_TPARAM_PREFERRED_ADDR:
1529
            /* TODO(QUIC FUTURE): Handle preferred address. */
1530
19
            if (got_preferred_addr) {
1531
2
                reason = TP_REASON_DUP("PREFERRED_ADDR");
1532
2
                goto malformed;
1533
2
            }
1534
1535
            /*
1536
             * RFC 9000 s. 18.2: "A server that chooses a zero-length
1537
             * connection ID MUST NOT provide a preferred address.
1538
             * Similarly, a server MUST NOT include a zero-length connection
1539
             * ID in this transport parameter. A client MUST treat a
1540
             * violation of these requirements as a connection error of type
1541
             * TRANSPORT_PARAMETER_ERROR."
1542
             */
1543
17
            if (ch->is_server) {
1544
0
                reason = TP_REASON_SERVER_ONLY("PREFERRED_ADDR");
1545
0
                goto malformed;
1546
0
            }
1547
1548
17
            if (ch->cur_remote_dcid.id_len == 0) {
1549
0
                reason = "PREFERRED_ADDR provided for zero-length CID";
1550
0
                goto malformed;
1551
0
            }
1552
1553
17
            if (!ossl_quic_wire_decode_transport_param_preferred_addr(&pkt, &pfa)) {
1554
13
                reason = TP_REASON_MALFORMED("PREFERRED_ADDR");
1555
13
                goto malformed;
1556
13
            }
1557
1558
4
            if (pfa.cid.id_len == 0) {
1559
2
                reason = "zero-length CID in PREFERRED_ADDR";
1560
2
                goto malformed;
1561
2
            }
1562
1563
2
            got_preferred_addr = 1;
1564
2
            break;
1565
1566
7.45k
        case QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION:
1567
            /* We do not currently handle migration, so nothing to do. */
1568
7.45k
            if (got_disable_active_migration) {
1569
                /* must not appear more than once */
1570
3
                reason = TP_REASON_DUP("DISABLE_ACTIVE_MIGRATION");
1571
3
                goto malformed;
1572
3
            }
1573
1574
7.45k
            body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1575
7.45k
            if (body == NULL || len > 0) {
1576
12
                reason = TP_REASON_MALFORMED("DISABLE_ACTIVE_MIGRATION");
1577
12
                goto malformed;
1578
12
            }
1579
1580
7.44k
            got_disable_active_migration = 1;
1581
7.44k
            break;
1582
1583
1.10k
        default:
1584
            /*
1585
             * Skip over and ignore.
1586
             *
1587
             * RFC 9000 s. 7.4: We SHOULD treat duplicated transport parameters
1588
             * as a connection error, but we are not required to. Currently,
1589
             * handle this programmatically by checking for duplicates in the
1590
             * parameters that we recognise, as above, but don't bother
1591
             * maintaining a list of duplicates for anything we don't recognise.
1592
             */
1593
1.10k
            body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id,
1594
1.10k
                                                               &len);
1595
1.10k
            if (body == NULL)
1596
38
                goto malformed;
1597
1598
1.07k
            break;
1599
87.4k
        }
1600
87.4k
    }
1601
1602
7.20k
    if (!got_initial_scid) {
1603
5
        reason = TP_REASON_REQUIRED("INITIAL_SCID");
1604
5
        goto malformed;
1605
5
    }
1606
1607
7.19k
    if (!ch->is_server) {
1608
7.19k
        if (!got_orig_dcid) {
1609
2
            reason = TP_REASON_REQUIRED("ORIG_DCID");
1610
2
            goto malformed;
1611
2
        }
1612
1613
7.19k
        if (ch->doing_retry && !got_retry_scid) {
1614
9
            reason = TP_REASON_REQUIRED("RETRY_SCID");
1615
9
            goto malformed;
1616
9
        }
1617
7.19k
    }
1618
1619
7.18k
    ch->got_remote_transport_params = 1;
1620
1621
7.18k
#ifndef OPENSSL_NO_QLOG
1622
7.18k
    QLOG_EVENT_BEGIN(ch_get_qlog(ch), transport, parameters_set)
1623
0
        QLOG_STR("owner", "remote");
1624
1625
0
        if (got_orig_dcid)
1626
0
            QLOG_CID("original_destination_connection_id",
1627
0
                     &ch->init_dcid);
1628
0
        if (got_initial_scid)
1629
0
            QLOG_CID("original_source_connection_id",
1630
0
                     &ch->init_dcid);
1631
0
        if (got_retry_scid)
1632
0
            QLOG_CID("retry_source_connection_id",
1633
0
                     &ch->retry_scid);
1634
0
        if (got_initial_max_data)
1635
0
            QLOG_U64("initial_max_data",
1636
0
                     ossl_quic_txfc_get_cwm(&ch->conn_txfc));
1637
0
        if (got_initial_max_stream_data_bidi_local)
1638
0
            QLOG_U64("initial_max_stream_data_bidi_local",
1639
0
                     ch->rx_init_max_stream_data_bidi_local);
1640
0
        if (got_initial_max_stream_data_bidi_remote)
1641
0
            QLOG_U64("initial_max_stream_data_bidi_remote",
1642
0
                     ch->rx_init_max_stream_data_bidi_remote);
1643
0
        if (got_initial_max_stream_data_uni)
1644
0
            QLOG_U64("initial_max_stream_data_uni",
1645
0
                     ch->rx_init_max_stream_data_uni);
1646
0
        if (got_initial_max_streams_bidi)
1647
0
            QLOG_U64("initial_max_streams_bidi",
1648
0
                     ch->max_local_streams_bidi);
1649
0
        if (got_initial_max_streams_uni)
1650
0
            QLOG_U64("initial_max_streams_uni",
1651
0
                     ch->max_local_streams_uni);
1652
0
        if (got_ack_delay_exp)
1653
0
            QLOG_U64("ack_delay_exponent", ch->rx_ack_delay_exp);
1654
0
        if (got_max_ack_delay)
1655
0
            QLOG_U64("max_ack_delay", ch->rx_max_ack_delay);
1656
0
        if (got_max_udp_payload_size)
1657
0
            QLOG_U64("max_udp_payload_size", ch->rx_max_udp_payload_size);
1658
0
        if (got_max_idle_timeout)
1659
0
            QLOG_U64("max_idle_timeout", rx_max_idle_timeout);
1660
0
        if (got_active_conn_id_limit)
1661
0
            QLOG_U64("active_connection_id_limit", ch->rx_active_conn_id_limit);
1662
0
        if (got_stateless_reset_token)
1663
0
            QLOG_BIN("stateless_reset_token", stateless_reset_token_p,
1664
0
                     QUIC_STATELESS_RESET_TOKEN_LEN);
1665
0
        if (got_preferred_addr) {
1666
0
            QLOG_BEGIN("preferred_addr")
1667
0
                QLOG_U64("port_v4", pfa.ipv4_port);
1668
0
                QLOG_U64("port_v6", pfa.ipv6_port);
1669
0
                QLOG_BIN("ip_v4", pfa.ipv4, sizeof(pfa.ipv4));
1670
0
                QLOG_BIN("ip_v6", pfa.ipv6, sizeof(pfa.ipv6));
1671
0
                QLOG_BIN("stateless_reset_token", pfa.stateless_reset.token,
1672
0
                         sizeof(pfa.stateless_reset.token));
1673
0
                QLOG_CID("connection_id", &pfa.cid);
1674
0
            QLOG_END()
1675
0
        }
1676
0
        QLOG_BOOL("disable_active_migration", got_disable_active_migration);
1677
0
    QLOG_EVENT_END()
1678
7.18k
#endif
1679
1680
7.18k
    if (got_initial_max_data || got_initial_max_stream_data_bidi_remote
1681
7.18k
        || got_initial_max_streams_bidi || got_initial_max_streams_uni)
1682
        /*
1683
         * If FC credit was bumped, we may now be able to send. Update all
1684
         * streams.
1685
         */
1686
7.18k
        ossl_quic_stream_map_visit(&ch->qsm, do_update, ch);
1687
1688
    /* If we are a server, we now generate our own transport parameters. */
1689
7.18k
    if (ch->is_server && !ch_generate_transport_params(ch)) {
1690
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR, 0,
1691
0
                                               "internal error");
1692
0
        return 0;
1693
0
    }
1694
1695
7.18k
    return 1;
1696
1697
364
malformed:
1698
364
    ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_TRANSPORT_PARAMETER_ERROR,
1699
364
                                           0, reason);
1700
364
    return 0;
1701
7.18k
}
1702
1703
/*
1704
 * Called when we want to generate transport parameters. This is called
1705
 * immediately at instantiation time for a client and after we receive the
1706
 * client's transport parameters for a server.
1707
 */
1708
static int ch_generate_transport_params(QUIC_CHANNEL *ch)
1709
18.5k
{
1710
18.5k
    int ok = 0;
1711
18.5k
    BUF_MEM *buf_mem = NULL;
1712
18.5k
    WPACKET wpkt;
1713
18.5k
    int wpkt_valid = 0;
1714
18.5k
    size_t buf_len = 0;
1715
1716
18.5k
    if (ch->local_transport_params != NULL || ch->got_local_transport_params)
1717
0
        goto err;
1718
1719
18.5k
    if ((buf_mem = BUF_MEM_new()) == NULL)
1720
0
        goto err;
1721
1722
18.5k
    if (!WPACKET_init(&wpkt, buf_mem))
1723
0
        goto err;
1724
1725
18.5k
    wpkt_valid = 1;
1726
1727
18.5k
    if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION,
1728
18.5k
                                                    NULL, 0) == NULL)
1729
0
        goto err;
1730
1731
18.5k
    if (ch->is_server) {
1732
0
        if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_ORIG_DCID,
1733
0
                                                       &ch->init_dcid))
1734
0
            goto err;
1735
1736
0
        if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1737
0
                                                       &ch->cur_local_cid))
1738
0
            goto err;
1739
18.5k
    } else {
1740
        /* Client always uses an empty SCID. */
1741
18.5k
        if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1742
18.5k
                                                        NULL, 0) == NULL)
1743
0
            goto err;
1744
18.5k
    }
1745
1746
18.5k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_IDLE_TIMEOUT,
1747
18.5k
                                                   ch->max_idle_timeout_local_req))
1748
0
        goto err;
1749
1750
18.5k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE,
1751
18.5k
                                                   QUIC_MIN_INITIAL_DGRAM_LEN))
1752
0
        goto err;
1753
1754
18.5k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT,
1755
18.5k
                                                   QUIC_MIN_ACTIVE_CONN_ID_LIMIT))
1756
0
        goto err;
1757
1758
18.5k
    if (ch->tx_max_ack_delay != QUIC_DEFAULT_MAX_ACK_DELAY
1759
18.5k
        && !ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_ACK_DELAY,
1760
0
                                                      ch->tx_max_ack_delay))
1761
0
        goto err;
1762
1763
18.5k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_DATA,
1764
18.5k
                                                   ossl_quic_rxfc_get_cwm(&ch->conn_rxfc)))
1765
0
        goto err;
1766
1767
    /* Send the default CWM for a new RXFC. */
1768
18.5k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
1769
18.5k
                                                   ch->tx_init_max_stream_data_bidi_local))
1770
0
        goto err;
1771
1772
18.5k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
1773
18.5k
                                                   ch->tx_init_max_stream_data_bidi_remote))
1774
0
        goto err;
1775
1776
18.5k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI,
1777
18.5k
                                                   ch->tx_init_max_stream_data_uni))
1778
0
        goto err;
1779
1780
18.5k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI,
1781
18.5k
                                                   ossl_quic_rxfc_get_cwm(&ch->max_streams_bidi_rxfc)))
1782
0
        goto err;
1783
1784
18.5k
    if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI,
1785
18.5k
                                                   ossl_quic_rxfc_get_cwm(&ch->max_streams_uni_rxfc)))
1786
0
        goto err;
1787
1788
18.5k
    if (!WPACKET_finish(&wpkt))
1789
0
        goto err;
1790
1791
18.5k
    wpkt_valid = 0;
1792
1793
18.5k
    if (!WPACKET_get_total_written(&wpkt, &buf_len))
1794
0
        goto err;
1795
1796
18.5k
    ch->local_transport_params = (unsigned char *)buf_mem->data;
1797
18.5k
    buf_mem->data = NULL;
1798
1799
1800
18.5k
    if (!ossl_quic_tls_set_transport_params(ch->qtls, ch->local_transport_params,
1801
18.5k
                                            buf_len))
1802
0
        goto err;
1803
1804
18.5k
#ifndef OPENSSL_NO_QLOG
1805
18.5k
    QLOG_EVENT_BEGIN(ch_get_qlog(ch), transport, parameters_set)
1806
0
        QLOG_STR("owner", "local");
1807
0
        QLOG_BOOL("disable_active_migration", 1);
1808
0
        if (ch->is_server) {
1809
0
            QLOG_CID("original_destination_connection_id", &ch->init_dcid);
1810
0
            QLOG_CID("initial_source_connection_id", &ch->cur_local_cid);
1811
0
        } else {
1812
0
            QLOG_STR("initial_source_connection_id", "");
1813
0
        }
1814
0
        QLOG_U64("max_idle_timeout", ch->max_idle_timeout);
1815
0
        QLOG_U64("max_udp_payload_size", QUIC_MIN_INITIAL_DGRAM_LEN);
1816
0
        QLOG_U64("active_connection_id_limit", QUIC_MIN_ACTIVE_CONN_ID_LIMIT);
1817
0
        QLOG_U64("max_ack_delay", ch->tx_max_ack_delay);
1818
0
        QLOG_U64("initial_max_data", ossl_quic_rxfc_get_cwm(&ch->conn_rxfc));
1819
0
        QLOG_U64("initial_max_stream_data_bidi_local",
1820
0
                 ch->tx_init_max_stream_data_bidi_local);
1821
0
        QLOG_U64("initial_max_stream_data_bidi_remote",
1822
0
                 ch->tx_init_max_stream_data_bidi_remote);
1823
0
        QLOG_U64("initial_max_stream_data_uni",
1824
0
                 ch->tx_init_max_stream_data_uni);
1825
0
        QLOG_U64("initial_max_streams_bidi",
1826
0
                 ossl_quic_rxfc_get_cwm(&ch->max_streams_bidi_rxfc));
1827
0
        QLOG_U64("initial_max_streams_uni",
1828
0
                 ossl_quic_rxfc_get_cwm(&ch->max_streams_uni_rxfc));
1829
0
    QLOG_EVENT_END()
1830
18.5k
#endif
1831
1832
18.5k
    ch->got_local_transport_params = 1;
1833
1834
18.5k
    ok = 1;
1835
18.5k
err:
1836
18.5k
    if (wpkt_valid)
1837
0
        WPACKET_cleanup(&wpkt);
1838
18.5k
    BUF_MEM_free(buf_mem);
1839
18.5k
    return ok;
1840
18.5k
}
1841
1842
/*
1843
 * QUIC Channel: Ticker-Mutator
1844
 * ============================
1845
 */
1846
1847
/*
1848
 * The central ticker function called by the reactor. This does everything, or
1849
 * at least everything network I/O related. Best effort - not allowed to fail
1850
 * "loudly".
1851
 */
1852
void ossl_quic_channel_subtick(QUIC_CHANNEL *ch, QUIC_TICK_RESULT *res,
1853
                               uint32_t flags)
1854
20.0M
{
1855
20.0M
    OSSL_TIME now, deadline;
1856
20.0M
    int channel_only = (flags & QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY) != 0;
1857
1858
    /*
1859
     * When we tick the QUIC connection, we do everything we need to do
1860
     * periodically. Network I/O handling will already have been performed
1861
     * as necessary by the QUIC port. Thus, in order, we:
1862
     *
1863
     *   - handle any packets the DEMUX has queued up for us;
1864
     *   - handle any timer events which are due to fire (ACKM, etc.);
1865
     *   - generate any packets which need to be sent;
1866
     *   - determine the time at which we should next be ticked.
1867
     */
1868
1869
    /* If we are in the TERMINATED state, there is nothing to do. */
1870
20.0M
    if (ossl_quic_channel_is_terminated(ch)) {
1871
0
        res->net_read_desired   = 0;
1872
0
        res->net_write_desired  = 0;
1873
0
        res->tick_deadline      = ossl_time_infinite();
1874
0
        return;
1875
0
    }
1876
1877
    /*
1878
     * If we are in the TERMINATING state, check if the terminating timer has
1879
     * expired.
1880
     */
1881
20.0M
    if (ossl_quic_channel_is_terminating(ch)) {
1882
577
        now = get_time(ch);
1883
1884
577
        if (ossl_time_compare(now, ch->terminate_deadline) >= 0) {
1885
0
            ch_on_terminating_timeout(ch);
1886
0
            res->net_read_desired   = 0;
1887
0
            res->net_write_desired  = 0;
1888
0
            res->tick_deadline      = ossl_time_infinite();
1889
0
            return; /* abort normal processing, nothing to do */
1890
0
        }
1891
577
    }
1892
1893
20.0M
    if (!ch->port->engine->inhibit_tick) {
1894
        /* Handle RXKU timeouts. */
1895
20.0M
        ch_rxku_tick(ch);
1896
1897
20.0M
        do {
1898
            /* Process queued incoming packets. */
1899
20.0M
            ch->did_tls_tick        = 0;
1900
20.0M
            ch->have_new_rx_secret  = 0;
1901
20.0M
            ch_rx(ch, channel_only);
1902
1903
            /*
1904
             * Allow the handshake layer to check for any new incoming data and
1905
             * generate new outgoing data.
1906
             */
1907
20.0M
            if (!ch->did_tls_tick)
1908
20.0M
                ch_tick_tls(ch, channel_only);
1909
1910
            /*
1911
             * If the handshake layer gave us a new secret, we need to do RX
1912
             * again because packets that were not previously processable and
1913
             * were deferred might now be processable.
1914
             *
1915
             * TODO(QUIC FUTURE): Consider handling this in the yield_secret callback.
1916
             */
1917
20.0M
        } while (ch->have_new_rx_secret);
1918
20.0M
    }
1919
1920
    /*
1921
     * Handle any timer events which are due to fire; namely, the loss
1922
     * detection deadline and the idle timeout.
1923
     *
1924
     * ACKM ACK generation deadline is polled by TXP, so we don't need to
1925
     * handle it here.
1926
     */
1927
20.0M
    now = get_time(ch);
1928
20.0M
    if (ossl_time_compare(now, ch->idle_deadline) >= 0) {
1929
        /*
1930
         * Idle timeout differs from normal protocol violation because we do
1931
         * not send a CONN_CLOSE frame; go straight to TERMINATED.
1932
         */
1933
5.38k
        if (!ch->port->engine->inhibit_tick)
1934
5.38k
            ch_on_idle_timeout(ch);
1935
1936
5.38k
        res->net_read_desired   = 0;
1937
5.38k
        res->net_write_desired  = 0;
1938
5.38k
        res->tick_deadline      = ossl_time_infinite();
1939
5.38k
        return;
1940
5.38k
    }
1941
1942
20.0M
    if (!ch->port->engine->inhibit_tick) {
1943
20.0M
        deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1944
20.0M
        if (!ossl_time_is_zero(deadline)
1945
20.0M
            && ossl_time_compare(now, deadline) >= 0)
1946
91.1k
            ossl_ackm_on_timeout(ch->ackm);
1947
1948
        /* If a ping is due, inform TXP. */
1949
20.0M
        if (ossl_time_compare(now, ch->ping_deadline) >= 0) {
1950
1.00M
            int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
1951
1952
1.00M
            ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
1953
1954
            /*
1955
             * If we have no CC budget at this time we cannot process the above
1956
             * PING request immediately. In any case we have scheduled the
1957
             * request so bump the ping deadline. If we don't do this we will
1958
             * busy-loop endlessly as the above deadline comparison condition
1959
             * will still be met.
1960
             */
1961
1.00M
            ch_update_ping_deadline(ch);
1962
1.00M
        }
1963
1964
        /* Queue any data to be sent for transmission. */
1965
20.0M
        ch_tx(ch);
1966
1967
        /* Do stream GC. */
1968
20.0M
        ossl_quic_stream_map_gc(&ch->qsm);
1969
20.0M
    }
1970
1971
    /* Determine the time at which we should next be ticked. */
1972
20.0M
    res->tick_deadline = ch_determine_next_tick_deadline(ch);
1973
1974
    /*
1975
     * Always process network input unless we are now terminated. Although we
1976
     * had not terminated at the beginning of this tick, network errors in
1977
     * ch_tx() may have caused us to transition to the Terminated state.
1978
     */
1979
20.0M
    res->net_read_desired = !ossl_quic_channel_is_terminated(ch);
1980
1981
    /* We want to write to the network if we have any data in our TX queue. */
1982
20.0M
    res->net_write_desired
1983
20.0M
        = (!ossl_quic_channel_is_terminated(ch)
1984
20.0M
           && ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0);
1985
20.0M
}
1986
1987
static int ch_tick_tls(QUIC_CHANNEL *ch, int channel_only)
1988
40.8M
{
1989
40.8M
    uint64_t error_code;
1990
40.8M
    const char *error_msg;
1991
40.8M
    ERR_STATE *error_state = NULL;
1992
1993
40.8M
    if (channel_only)
1994
0
        return 1;
1995
1996
40.8M
    ch->did_tls_tick = 1;
1997
40.8M
    ossl_quic_tls_tick(ch->qtls);
1998
1999
40.8M
    if (ossl_quic_tls_get_error(ch->qtls, &error_code, &error_msg,
2000
40.8M
                                &error_state)) {
2001
10.3k
        ossl_quic_channel_raise_protocol_error_state(ch, error_code, 0,
2002
10.3k
                                                     error_msg, error_state);
2003
10.3k
        return 0;
2004
10.3k
    }
2005
2006
40.8M
    return 1;
2007
40.8M
}
2008
2009
/* Check incoming forged packet limit and terminate connection if needed. */
2010
static void ch_rx_check_forged_pkt_limit(QUIC_CHANNEL *ch)
2011
62.6M
{
2012
62.6M
    uint32_t enc_level;
2013
62.6M
    uint64_t limit = UINT64_MAX, l;
2014
2015
62.6M
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
2016
204M
         enc_level < QUIC_ENC_LEVEL_NUM;
2017
142M
         ++enc_level)
2018
180M
    {
2019
        /*
2020
         * Different ELs can have different AEADs which can in turn impose
2021
         * different limits, so use the lowest value of any currently valid EL.
2022
         */
2023
180M
        if ((ch->el_discarded & (1U << enc_level)) != 0)
2024
39.4M
            continue;
2025
2026
140M
        if (enc_level > ch->rx_enc_level)
2027
37.9M
            break;
2028
2029
102M
        l = ossl_qrx_get_max_forged_pkt_count(ch->qrx, enc_level);
2030
102M
        if (l < limit)
2031
62.8M
            limit = l;
2032
102M
    }
2033
2034
62.6M
    if (ossl_qrx_get_cur_forged_pkt_count(ch->qrx) < limit)
2035
62.6M
        return;
2036
2037
0
    ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_AEAD_LIMIT_REACHED, 0,
2038
0
                                           "forgery limit");
2039
0
}
2040
2041
/* Process queued incoming packets and handle frames, if any. */
2042
static int ch_rx(QUIC_CHANNEL *ch, int channel_only)
2043
40.8M
{
2044
40.8M
    int handled_any = 0;
2045
40.8M
    const int closing = ossl_quic_channel_is_closing(ch);
2046
2047
40.8M
    if (!ch->is_server && !ch->have_sent_any_pkt)
2048
        /*
2049
         * We have not sent anything yet, therefore there is no need to check
2050
         * for incoming data.
2051
         */
2052
29.1k
        return 1;
2053
2054
42.0M
    for (;;) {
2055
42.0M
        assert(ch->qrx_pkt == NULL);
2056
2057
42.0M
        if (!ossl_qrx_read_pkt(ch->qrx, &ch->qrx_pkt))
2058
40.8M
            break;
2059
2060
        /* Track the amount of data received while in the closing state */
2061
1.25M
        if (closing)
2062
0
            ossl_quic_tx_packetiser_record_received_closing_bytes(
2063
0
                    ch->txp, ch->qrx_pkt->hdr->len);
2064
2065
1.25M
        if (!handled_any) {
2066
1.23M
            ch_update_idle(ch);
2067
1.23M
            ch_update_ping_deadline(ch);
2068
1.23M
        }
2069
2070
1.25M
        ch_rx_handle_packet(ch, channel_only); /* best effort */
2071
2072
        /*
2073
         * Regardless of the outcome of frame handling, unref the packet.
2074
         * This will free the packet unless something added another
2075
         * reference to it during frame processing.
2076
         */
2077
1.25M
        ossl_qrx_pkt_release(ch->qrx_pkt);
2078
1.25M
        ch->qrx_pkt = NULL;
2079
2080
1.25M
        ch->have_sent_ack_eliciting_since_rx = 0;
2081
1.25M
        handled_any = 1;
2082
1.25M
    }
2083
2084
40.8M
    ch_rx_check_forged_pkt_limit(ch);
2085
2086
    /*
2087
     * When in TERMINATING - CLOSING, generate a CONN_CLOSE frame whenever we
2088
     * process one or more incoming packets.
2089
     */
2090
40.8M
    if (handled_any && closing)
2091
0
        ch->conn_close_queued = 1;
2092
2093
40.8M
    return 1;
2094
40.8M
}
2095
2096
static int bio_addr_eq(const BIO_ADDR *a, const BIO_ADDR *b)
2097
0
{
2098
0
    if (BIO_ADDR_family(a) != BIO_ADDR_family(b))
2099
0
        return 0;
2100
2101
0
    switch (BIO_ADDR_family(a)) {
2102
0
        case AF_INET:
2103
0
            return !memcmp(&a->s_in.sin_addr,
2104
0
                           &b->s_in.sin_addr,
2105
0
                           sizeof(a->s_in.sin_addr))
2106
0
                && a->s_in.sin_port == b->s_in.sin_port;
2107
0
#if OPENSSL_USE_IPV6
2108
0
        case AF_INET6:
2109
0
            return !memcmp(&a->s_in6.sin6_addr,
2110
0
                           &b->s_in6.sin6_addr,
2111
0
                           sizeof(a->s_in6.sin6_addr))
2112
0
                && a->s_in6.sin6_port == b->s_in6.sin6_port;
2113
0
#endif
2114
0
        default:
2115
0
            return 0; /* not supported */
2116
0
    }
2117
2118
0
    return 1;
2119
0
}
2120
2121
/* Handles the packet currently in ch->qrx_pkt->hdr. */
2122
static void ch_rx_handle_packet(QUIC_CHANNEL *ch, int channel_only)
2123
1.25M
{
2124
1.25M
    uint32_t enc_level;
2125
1.25M
    int old_have_processed_any_pkt = ch->have_processed_any_pkt;
2126
1.25M
    OSSL_QTX_IOVEC iovec;
2127
2128
1.25M
    assert(ch->qrx_pkt != NULL);
2129
2130
    /*
2131
     * RFC 9000 s. 10.2.1 Closing Connection State:
2132
     *      An endpoint that is closing is not required to process any
2133
     *      received frame.
2134
     */
2135
1.25M
    if (!ossl_quic_channel_is_active(ch))
2136
1.07k
        return;
2137
2138
1.25M
    if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)) {
2139
322k
        if (!ch->have_received_enc_pkt) {
2140
25.7k
            ch->cur_remote_dcid = ch->init_scid = ch->qrx_pkt->hdr->src_conn_id;
2141
25.7k
            ch->have_received_enc_pkt = 1;
2142
2143
            /*
2144
             * We change to using the SCID in the first Initial packet as the
2145
             * DCID.
2146
             */
2147
25.7k
            ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->init_scid);
2148
25.7k
        }
2149
2150
322k
        enc_level = ossl_quic_pkt_type_to_enc_level(ch->qrx_pkt->hdr->type);
2151
322k
        if ((ch->el_discarded & (1U << enc_level)) != 0)
2152
            /* Do not process packets from ELs we have already discarded. */
2153
7
            return;
2154
322k
    }
2155
2156
    /*
2157
     * RFC 9000 s. 9.6: "If a client receives packets from a new server address
2158
     * when the client has not initiated a migration to that address, the client
2159
     * SHOULD discard these packets."
2160
     *
2161
     * We need to be a bit careful here as due to the BIO abstraction layer an
2162
     * application is liable to be weird and lie to us about peer addresses.
2163
     * Only apply this check if we actually are using a real AF_INET or AF_INET6
2164
     * address.
2165
     */
2166
1.25M
    if (!ch->is_server
2167
1.25M
        && ch->qrx_pkt->peer != NULL
2168
1.25M
        && (
2169
0
               BIO_ADDR_family(&ch->cur_peer_addr) == AF_INET
2170
0
#if OPENSSL_USE_IPV6
2171
0
            || BIO_ADDR_family(&ch->cur_peer_addr) == AF_INET6
2172
0
#endif
2173
0
        )
2174
1.25M
        && !bio_addr_eq(ch->qrx_pkt->peer, &ch->cur_peer_addr))
2175
0
        return;
2176
2177
1.25M
    if (!ch->is_server
2178
1.25M
        && ch->have_received_enc_pkt
2179
1.25M
        && ossl_quic_pkt_type_has_scid(ch->qrx_pkt->hdr->type)) {
2180
        /*
2181
         * RFC 9000 s. 7.2: "Once a client has received a valid Initial packet
2182
         * from the server, it MUST discard any subsequent packet it receives on
2183
         * that connection with a different SCID."
2184
         */
2185
1.14M
        if (!ossl_quic_conn_id_eq(&ch->qrx_pkt->hdr->src_conn_id,
2186
1.14M
                                  &ch->init_scid))
2187
797k
            return;
2188
1.14M
    }
2189
2190
453k
    if (ossl_quic_pkt_type_has_version(ch->qrx_pkt->hdr->type)
2191
453k
        && ch->qrx_pkt->hdr->version != QUIC_VERSION_1)
2192
        /*
2193
         * RFC 9000 s. 5.2.1: If a client receives a packet that uses a
2194
         * different version than it initially selected, it MUST discard the
2195
         * packet. We only ever use v1, so require it.
2196
         */
2197
0
        return;
2198
2199
453k
    ch->have_processed_any_pkt = 1;
2200
2201
    /*
2202
     * RFC 9000 s. 17.2: "An endpoint MUST treat receipt of a packet that has a
2203
     * non-zero value for [the reserved bits] after removing both packet and
2204
     * header protection as a connection error of type PROTOCOL_VIOLATION."
2205
     */
2206
453k
    if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)
2207
453k
        && ch->qrx_pkt->hdr->reserved != 0) {
2208
194
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
2209
194
                                               0, "packet header reserved bits");
2210
194
        return;
2211
194
    }
2212
2213
453k
    iovec.buf       = ch->qrx_pkt->hdr->data;
2214
453k
    iovec.buf_len   = ch->qrx_pkt->hdr->len;
2215
453k
    ossl_qlog_event_transport_packet_received(ch_get_qlog(ch), ch->qrx_pkt->hdr,
2216
453k
                                              ch->qrx_pkt->pn, &iovec, 1,
2217
453k
                                              ch->qrx_pkt->datagram_id);
2218
2219
    /* Handle incoming packet. */
2220
453k
    switch (ch->qrx_pkt->hdr->type) {
2221
102k
    case QUIC_PKT_TYPE_RETRY:
2222
102k
        if (ch->doing_retry || ch->is_server)
2223
            /*
2224
             * It is not allowed to ask a client to do a retry more than
2225
             * once. Clients may not send retries.
2226
             */
2227
871
            return;
2228
2229
        /*
2230
         * RFC 9000 s 17.2.5.2: After the client has received and processed an
2231
         * Initial or Retry packet from the server, it MUST discard any
2232
         * subsequent Retry packets that it receives.
2233
         */
2234
101k
        if (ch->have_received_enc_pkt)
2235
20.9k
            return;
2236
2237
81.0k
        if (ch->qrx_pkt->hdr->len <= QUIC_RETRY_INTEGRITY_TAG_LEN)
2238
            /* Packets with zero-length Retry Tokens are invalid. */
2239
1.40k
            return;
2240
2241
        /*
2242
         * TODO(QUIC FUTURE): Theoretically this should probably be in the QRX.
2243
         * However because validation is dependent on context (namely the
2244
         * client's initial DCID) we can't do this cleanly. In the future we
2245
         * should probably add a callback to the QRX to let it call us (via
2246
         * the DEMUX) and ask us about the correct original DCID, rather
2247
         * than allow the QRX to emit a potentially malformed packet to the
2248
         * upper layers. However, special casing this will do for now.
2249
         */
2250
79.6k
        if (!ossl_quic_validate_retry_integrity_tag(ch->port->engine->libctx,
2251
79.6k
                                                    ch->port->engine->propq,
2252
79.6k
                                                    ch->qrx_pkt->hdr,
2253
79.6k
                                                    &ch->init_dcid))
2254
            /* Malformed retry packet, ignore. */
2255
79.1k
            return;
2256
2257
469
        if (!ch_retry(ch, ch->qrx_pkt->hdr->data,
2258
469
                      ch->qrx_pkt->hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN,
2259
469
                      &ch->qrx_pkt->hdr->src_conn_id))
2260
9
            ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR,
2261
469
                                                   0, "handling retry packet");
2262
469
        break;
2263
2264
0
    case QUIC_PKT_TYPE_0RTT:
2265
0
        if (!ch->is_server)
2266
            /* Clients should never receive 0-RTT packets. */
2267
0
            return;
2268
2269
        /*
2270
         * TODO(QUIC 0RTT): Implement 0-RTT on the server side. We currently
2271
         * do not need to implement this as a client can only do 0-RTT if we
2272
         * have given it permission to in a previous session.
2273
         */
2274
0
        break;
2275
2276
201k
    case QUIC_PKT_TYPE_INITIAL:
2277
227k
    case QUIC_PKT_TYPE_HANDSHAKE:
2278
248k
    case QUIC_PKT_TYPE_1RTT:
2279
248k
        if (ch->is_server && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE)
2280
            /*
2281
             * We automatically drop INITIAL EL keys when first successfully
2282
             * decrypting a HANDSHAKE packet, as per the RFC.
2283
             */
2284
0
            ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
2285
2286
248k
        if (ch->rxku_in_progress
2287
248k
            && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_1RTT
2288
248k
            && ch->qrx_pkt->pn >= ch->rxku_trigger_pn
2289
248k
            && ch->qrx_pkt->key_epoch < ossl_qrx_get_key_epoch(ch->qrx)) {
2290
            /*
2291
             * RFC 9001 s. 6.4: Packets with higher packet numbers MUST be
2292
             * protected with either the same or newer packet protection keys
2293
             * than packets with lower packet numbers. An endpoint that
2294
             * successfully removes protection with old keys when newer keys
2295
             * were used for packets with lower packet numbers MUST treat this
2296
             * as a connection error of type KEY_UPDATE_ERROR.
2297
             */
2298
1
            ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_KEY_UPDATE_ERROR,
2299
1
                                                   0, "new packet with old keys");
2300
1
            break;
2301
1
        }
2302
2303
248k
        if (!ch->is_server
2304
248k
            && ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_INITIAL
2305
248k
            && ch->qrx_pkt->hdr->token_len > 0) {
2306
            /*
2307
             * RFC 9000 s. 17.2.2: Clients that receive an Initial packet with a
2308
             * non-zero Token Length field MUST either discard the packet or
2309
             * generate a connection error of type PROTOCOL_VIOLATION.
2310
             *
2311
             * TODO(QUIC FUTURE): consider the implications of RFC 9000 s. 10.2.3
2312
             * Immediate Close during the Handshake:
2313
             *      However, at the cost of reducing feedback about
2314
             *      errors for legitimate peers, some forms of denial of
2315
             *      service can be made more difficult for an attacker
2316
             *      if endpoints discard illegal packets rather than
2317
             *      terminating a connection with CONNECTION_CLOSE. For
2318
             *      this reason, endpoints MAY discard packets rather
2319
             *      than immediately close if errors are detected in
2320
             *      packets that lack authentication.
2321
             * I.e. should we drop this packet instead of closing the connection?
2322
             */
2323
44
            ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
2324
44
                                                   0, "client received initial token");
2325
44
            break;
2326
44
        }
2327
2328
        /* This packet contains frames, pass to the RXDP. */
2329
248k
        ossl_quic_handle_frames(ch, ch->qrx_pkt); /* best effort */
2330
2331
248k
        if (ch->did_crypto_frame)
2332
118k
            ch_tick_tls(ch, channel_only);
2333
2334
248k
        break;
2335
2336
102k
    case QUIC_PKT_TYPE_VERSION_NEG:
2337
        /*
2338
         * "A client MUST discard any Version Negotiation packet if it has
2339
         * received and successfully processed any other packet."
2340
         */
2341
102k
        if (!old_have_processed_any_pkt)
2342
135
            ch_rx_handle_version_neg(ch, ch->qrx_pkt);
2343
2344
102k
        break;
2345
2346
0
    default:
2347
0
        assert(0);
2348
0
        break;
2349
453k
    }
2350
453k
}
2351
2352
static void ch_rx_handle_version_neg(QUIC_CHANNEL *ch, OSSL_QRX_PKT *pkt)
2353
135
{
2354
    /*
2355
     * We do not support version negotiation at this time. As per RFC 9000 s.
2356
     * 6.2., we MUST abandon the connection attempt if we receive a Version
2357
     * Negotiation packet, unless we have already successfully processed another
2358
     * incoming packet, or the packet lists the QUIC version we want to use.
2359
     */
2360
135
    PACKET vpkt;
2361
135
    unsigned long v;
2362
2363
135
    if (!PACKET_buf_init(&vpkt, pkt->hdr->data, pkt->hdr->len))
2364
0
        return;
2365
2366
1.31k
    while (PACKET_remaining(&vpkt) > 0) {
2367
1.26k
        if (!PACKET_get_net_4(&vpkt, &v))
2368
0
            break;
2369
2370
1.26k
        if ((uint32_t)v == QUIC_VERSION_1)
2371
88
            return;
2372
1.26k
    }
2373
2374
    /* No match, this is a failure case. */
2375
47
    ch_raise_version_neg_failure(ch);
2376
47
}
2377
2378
static void ch_raise_version_neg_failure(QUIC_CHANNEL *ch)
2379
47
{
2380
47
    QUIC_TERMINATE_CAUSE tcause = {0};
2381
2382
47
    tcause.error_code = OSSL_QUIC_ERR_CONNECTION_REFUSED;
2383
47
    tcause.reason     = "version negotiation failure";
2384
47
    tcause.reason_len = strlen(tcause.reason);
2385
2386
    /*
2387
     * Skip TERMINATING state; this is not considered a protocol error and we do
2388
     * not send CONNECTION_CLOSE.
2389
     */
2390
47
    ch_start_terminating(ch, &tcause, 1);
2391
47
}
2392
2393
/* Try to generate packets and if possible, flush them to the network. */
2394
static int ch_tx(QUIC_CHANNEL *ch)
2395
40.8M
{
2396
40.8M
    QUIC_TXP_STATUS status;
2397
40.8M
    int res;
2398
2399
    /*
2400
     * RFC 9000 s. 10.2.2: Draining Connection State:
2401
     *      While otherwise identical to the closing state, an endpoint
2402
     *      in the draining state MUST NOT send any packets.
2403
     * and:
2404
     *      An endpoint MUST NOT send further packets.
2405
     */
2406
40.8M
    if (ossl_quic_channel_is_draining(ch))
2407
629
        return 0;
2408
2409
40.8M
    if (ossl_quic_channel_is_closing(ch)) {
2410
        /*
2411
         * While closing, only send CONN_CLOSE if we've received more traffic
2412
         * from the peer. Once we tell the TXP to generate CONN_CLOSE, all
2413
         * future calls to it generate CONN_CLOSE frames, so otherwise we would
2414
         * just constantly generate CONN_CLOSE frames.
2415
         *
2416
         * Confirming to RFC 9000 s. 10.2.1 Closing Connection State:
2417
         *      An endpoint SHOULD limit the rate at which it generates
2418
         *      packets in the closing state.
2419
         */
2420
15.4k
        if (!ch->conn_close_queued)
2421
863
            return 0;
2422
2423
14.5k
        ch->conn_close_queued = 0;
2424
14.5k
    }
2425
2426
    /* Do TXKU if we need to. */
2427
40.8M
    ch_maybe_trigger_spontaneous_txku(ch);
2428
2429
40.8M
    ch->rxku_pending_confirm_done = 0;
2430
2431
    /* Loop until we stop generating packets to send */
2432
41.5M
    do {
2433
        /*
2434
        * Send packet, if we need to. Best effort. The TXP consults the CC and
2435
        * applies any limitations imposed by it, so we don't need to do it here.
2436
        *
2437
        * Best effort. In particular if TXP fails for some reason we should
2438
        * still flush any queued packets which we already generated.
2439
        */
2440
41.5M
        res = ossl_quic_tx_packetiser_generate(ch->txp, &status);
2441
41.5M
        if (status.sent_pkt > 0) {
2442
775k
            ch->have_sent_any_pkt = 1; /* Packet(s) were sent */
2443
775k
            ch->port->have_sent_any_pkt = 1;
2444
2445
            /*
2446
            * RFC 9000 s. 10.1. 'An endpoint also restarts its idle timer when
2447
            * sending an ack-eliciting packet if no other ack-eliciting packets
2448
            * have been sent since last receiving and processing a packet.'
2449
            */
2450
775k
            if (status.sent_ack_eliciting
2451
775k
                    && !ch->have_sent_ack_eliciting_since_rx) {
2452
352k
                ch_update_idle(ch);
2453
352k
                ch->have_sent_ack_eliciting_since_rx = 1;
2454
352k
            }
2455
2456
775k
            if (!ch->is_server && status.sent_handshake)
2457
                /*
2458
                * RFC 9001 s. 4.9.1: A client MUST discard Initial keys when it
2459
                * first sends a Handshake packet.
2460
                */
2461
144k
                ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
2462
2463
775k
            if (ch->rxku_pending_confirm_done)
2464
7.23k
                ch->rxku_pending_confirm = 0;
2465
2466
775k
            ch_update_ping_deadline(ch);
2467
775k
        }
2468
2469
41.5M
        if (!res) {
2470
            /*
2471
            * One case where TXP can fail is if we reach a TX PN of 2**62 - 1.
2472
            * As per RFC 9000 s. 12.3, if this happens we MUST close the
2473
            * connection without sending a CONNECTION_CLOSE frame. This is
2474
            * actually handled as an emergent consequence of our design, as the
2475
            * TX packetiser will never transmit another packet when the TX PN
2476
            * reaches the limit.
2477
            *
2478
            * Calling the below function terminates the connection; its attempt
2479
            * to schedule a CONNECTION_CLOSE frame will not actually cause a
2480
            * packet to be transmitted for this reason.
2481
            */
2482
1
            ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INTERNAL_ERROR,
2483
1
                                                   0,
2484
1
                                                   "internal error (txp generate)");
2485
1
            break;
2486
1
        }
2487
41.5M
    } while (status.sent_pkt > 0);
2488
2489
    /* Flush packets to network. */
2490
0
    switch (ossl_qtx_flush_net(ch->qtx)) {
2491
40.8M
    case QTX_FLUSH_NET_RES_OK:
2492
40.8M
    case QTX_FLUSH_NET_RES_TRANSIENT_FAIL:
2493
        /* Best effort, done for now. */
2494
40.8M
        break;
2495
2496
0
    case QTX_FLUSH_NET_RES_PERMANENT_FAIL:
2497
0
    default:
2498
        /* Permanent underlying network BIO, start terminating. */
2499
0
        ossl_quic_port_raise_net_error(ch->port, ch);
2500
0
        break;
2501
40.8M
    }
2502
2503
40.8M
    return 1;
2504
40.8M
}
2505
2506
/* Determine next tick deadline. */
2507
static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch)
2508
62.6M
{
2509
62.6M
    OSSL_TIME deadline;
2510
62.6M
    int i;
2511
2512
62.6M
    if (ossl_quic_channel_is_terminated(ch))
2513
48
        return ossl_time_infinite();
2514
2515
62.6M
    deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
2516
62.6M
    if (ossl_time_is_zero(deadline))
2517
99.2k
        deadline = ossl_time_infinite();
2518
2519
    /*
2520
     * Check the ack deadline for all enc_levels that are actually provisioned.
2521
     * ACKs aren't restricted by CC.
2522
     */
2523
313M
    for (i = 0; i < QUIC_ENC_LEVEL_NUM; i++) {
2524
250M
        if (ossl_qtx_is_enc_level_provisioned(ch->qtx, i)) {
2525
76.3M
            deadline = ossl_time_min(deadline,
2526
76.3M
                                     ossl_ackm_get_ack_deadline(ch->ackm,
2527
76.3M
                                                                ossl_quic_enc_level_to_pn_space(i)));
2528
76.3M
        }
2529
250M
    }
2530
2531
    /*
2532
     * When do we need to send an ACK-eliciting packet to reset the idle
2533
     * deadline timer for the peer?
2534
     */
2535
62.6M
    if (!ossl_time_is_infinite(ch->ping_deadline))
2536
62.6M
        deadline = ossl_time_min(deadline, ch->ping_deadline);
2537
2538
    /* Apply TXP wakeup deadline. */
2539
62.6M
    deadline = ossl_time_min(deadline,
2540
62.6M
                             ossl_quic_tx_packetiser_get_deadline(ch->txp));
2541
2542
    /* Is the terminating timer armed? */
2543
62.6M
    if (ossl_quic_channel_is_terminating(ch))
2544
25.8k
        deadline = ossl_time_min(deadline,
2545
25.8k
                                 ch->terminate_deadline);
2546
62.6M
    else if (!ossl_time_is_infinite(ch->idle_deadline))
2547
62.6M
        deadline = ossl_time_min(deadline,
2548
62.6M
                                 ch->idle_deadline);
2549
2550
    /* When does the RXKU process complete? */
2551
62.6M
    if (ch->rxku_in_progress)
2552
2.49M
        deadline = ossl_time_min(deadline, ch->rxku_update_end_deadline);
2553
2554
62.6M
    return deadline;
2555
62.6M
}
2556
2557
/*
2558
 * QUIC Channel: Lifecycle Events
2559
 * ==============================
2560
 */
2561
2562
/*
2563
 * Record a state transition. This is not necessarily a change to ch->state but
2564
 * also includes the handshake becoming complete or confirmed, etc.
2565
 */
2566
static void ch_record_state_transition(QUIC_CHANNEL *ch, uint32_t new_state)
2567
82.9k
{
2568
82.9k
    uint32_t old_state = ch->state;
2569
2570
82.9k
    ch->state = new_state;
2571
2572
82.9k
    ossl_qlog_event_connectivity_connection_state_updated(ch_get_qlog(ch),
2573
82.9k
                                                          old_state,
2574
82.9k
                                                          new_state,
2575
82.9k
                                                          ch->handshake_complete,
2576
82.9k
                                                          ch->handshake_confirmed);
2577
82.9k
}
2578
2579
int ossl_quic_channel_start(QUIC_CHANNEL *ch)
2580
18.5k
{
2581
18.5k
    if (ch->is_server)
2582
        /*
2583
         * This is not used by the server. The server moves to active
2584
         * automatically on receiving an incoming connection.
2585
         */
2586
0
        return 0;
2587
2588
18.5k
    if (ch->state != QUIC_CHANNEL_STATE_IDLE)
2589
        /* Calls to connect are idempotent */
2590
0
        return 1;
2591
2592
    /* Inform QTX of peer address. */
2593
18.5k
    if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
2594
0
        return 0;
2595
2596
    /* Plug in secrets for the Initial EL. */
2597
18.5k
    if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx,
2598
18.5k
                                          ch->port->engine->propq,
2599
18.5k
                                          &ch->init_dcid,
2600
18.5k
                                          ch->is_server,
2601
18.5k
                                          ch->qrx, ch->qtx))
2602
0
        return 0;
2603
2604
    /*
2605
     * Determine the QUIC Transport Parameters and serialize the transport
2606
     * parameters block. (For servers, we do this later as we must defer
2607
     * generation until we have received the client's transport parameters.)
2608
     */
2609
18.5k
    if (!ch->is_server && !ch->got_local_transport_params
2610
18.5k
        && !ch_generate_transport_params(ch))
2611
0
        return 0;
2612
2613
    /* Change state. */
2614
18.5k
    ch_record_state_transition(ch, QUIC_CHANNEL_STATE_ACTIVE);
2615
18.5k
    ch->doing_proactive_ver_neg = 0; /* not currently supported */
2616
2617
18.5k
    ossl_qlog_event_connectivity_connection_started(ch_get_qlog(ch),
2618
18.5k
                                                    &ch->init_dcid);
2619
2620
    /* Handshake layer: start (e.g. send CH). */
2621
18.5k
    if (!ch_tick_tls(ch, /*channel_only=*/0))
2622
0
        return 0;
2623
2624
18.5k
    ossl_quic_reactor_tick(ossl_quic_port_get0_reactor(ch->port), 0); /* best effort */
2625
18.5k
    return 1;
2626
18.5k
}
2627
2628
/* Start a locally initiated connection shutdown. */
2629
void ossl_quic_channel_local_close(QUIC_CHANNEL *ch, uint64_t app_error_code,
2630
                                   const char *app_reason)
2631
0
{
2632
0
    QUIC_TERMINATE_CAUSE tcause = {0};
2633
2634
0
    if (ossl_quic_channel_is_term_any(ch))
2635
0
        return;
2636
2637
0
    tcause.app          = 1;
2638
0
    tcause.error_code   = app_error_code;
2639
0
    tcause.reason       = app_reason;
2640
0
    tcause.reason_len   = app_reason != NULL ? strlen(app_reason) : 0;
2641
0
    ch_start_terminating(ch, &tcause, 0);
2642
0
}
2643
2644
static void free_token(const unsigned char *buf, size_t buf_len, void *arg)
2645
881
{
2646
881
    OPENSSL_free((unsigned char *)buf);
2647
881
}
2648
2649
/* Called when a server asks us to do a retry. */
2650
static int ch_retry(QUIC_CHANNEL *ch,
2651
                    const unsigned char *retry_token,
2652
                    size_t retry_token_len,
2653
                    const QUIC_CONN_ID *retry_scid)
2654
469
{
2655
469
    void *buf;
2656
2657
    /*
2658
     * RFC 9000 s. 17.2.5.1: "A client MUST discard a Retry packet that contains
2659
     * a SCID field that is identical to the DCID field of its initial packet."
2660
     */
2661
469
    if (ossl_quic_conn_id_eq(&ch->init_dcid, retry_scid))
2662
0
        return 1;
2663
2664
    /* We change to using the SCID in the Retry packet as the DCID. */
2665
469
    if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, retry_scid))
2666
0
        return 0;
2667
2668
    /*
2669
     * Now we retry. We will release the Retry packet immediately, so copy
2670
     * the token.
2671
     */
2672
469
    if ((buf = OPENSSL_memdup(retry_token, retry_token_len)) == NULL)
2673
0
        return 0;
2674
2675
469
    if (!ossl_quic_tx_packetiser_set_initial_token(ch->txp, buf,
2676
469
                                                   retry_token_len,
2677
469
                                                   free_token, NULL)) {
2678
        /*
2679
         * This may fail if the token we receive is too big for us to ever be
2680
         * able to transmit in an outgoing Initial packet.
2681
         */
2682
9
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_INVALID_TOKEN, 0,
2683
9
                                               "received oversize token");
2684
9
        OPENSSL_free(buf);
2685
9
        return 0;
2686
9
    }
2687
2688
460
    ch->retry_scid  = *retry_scid;
2689
460
    ch->doing_retry = 1;
2690
2691
    /*
2692
     * We need to stimulate the Initial EL to generate the first CRYPTO frame
2693
     * again. We can do this most cleanly by simply forcing the ACKM to consider
2694
     * the first Initial packet as lost, which it effectively was as the server
2695
     * hasn't processed it. This also maintains the desired behaviour with e.g.
2696
     * PNs not resetting and so on.
2697
     *
2698
     * The PN we used initially is always zero, because QUIC does not allow
2699
     * repeated retries.
2700
     */
2701
460
    if (!ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL,
2702
460
                                           /*PN=*/0))
2703
0
        return 0;
2704
2705
    /*
2706
     * Plug in new secrets for the Initial EL. This is the only time we change
2707
     * the secrets for an EL after we already provisioned it.
2708
     */
2709
460
    if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx,
2710
460
                                          ch->port->engine->propq,
2711
460
                                          &ch->retry_scid,
2712
460
                                          /*is_server=*/0,
2713
460
                                          ch->qrx, ch->qtx))
2714
0
        return 0;
2715
2716
460
    return 1;
2717
460
}
2718
2719
/* Called when an EL is to be discarded. */
2720
static int ch_discard_el(QUIC_CHANNEL *ch,
2721
                         uint32_t enc_level)
2722
253k
{
2723
253k
    if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_1RTT))
2724
0
        return 0;
2725
2726
253k
    if ((ch->el_discarded & (1U << enc_level)) != 0)
2727
        /* Already done. */
2728
225k
        return 1;
2729
2730
    /* Best effort for all of these. */
2731
27.5k
    ossl_quic_tx_packetiser_discard_enc_level(ch->txp, enc_level);
2732
27.5k
    ossl_qrx_discard_enc_level(ch->qrx, enc_level);
2733
27.5k
    ossl_qtx_discard_enc_level(ch->qtx, enc_level);
2734
2735
27.5k
    if (enc_level != QUIC_ENC_LEVEL_0RTT) {
2736
27.5k
        uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
2737
2738
27.5k
        ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
2739
2740
        /* We should still have crypto streams at this point. */
2741
27.5k
        if (!ossl_assert(ch->crypto_send[pn_space] != NULL)
2742
27.5k
            || !ossl_assert(ch->crypto_recv[pn_space] != NULL))
2743
0
            return 0;
2744
2745
        /* Get rid of the crypto stream state for the EL. */
2746
27.5k
        ossl_quic_sstream_free(ch->crypto_send[pn_space]);
2747
27.5k
        ch->crypto_send[pn_space] = NULL;
2748
2749
27.5k
        ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
2750
27.5k
        ch->crypto_recv[pn_space] = NULL;
2751
27.5k
    }
2752
2753
27.5k
    ch->el_discarded |= (1U << enc_level);
2754
27.5k
    return 1;
2755
27.5k
}
2756
2757
/* Intended to be called by the RXDP. */
2758
int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch)
2759
226k
{
2760
226k
    if (ch->handshake_confirmed)
2761
219k
        return 1;
2762
2763
6.14k
    if (!ch->handshake_complete) {
2764
        /*
2765
         * Does not make sense for handshake to be confirmed before it is
2766
         * completed.
2767
         */
2768
0
        ossl_quic_channel_raise_protocol_error(ch, OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
2769
0
                                               OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE,
2770
0
                                               "handshake cannot be confirmed "
2771
0
                                               "before it is completed");
2772
0
        return 0;
2773
0
    }
2774
2775
6.14k
    ch_discard_el(ch, QUIC_ENC_LEVEL_HANDSHAKE);
2776
6.14k
    ch->handshake_confirmed = 1;
2777
6.14k
    ch_record_state_transition(ch, ch->state);
2778
6.14k
    ossl_ackm_on_handshake_confirmed(ch->ackm);
2779
6.14k
    return 1;
2780
6.14k
}
2781
2782
/*
2783
 * Master function used when we want to start tearing down a connection:
2784
 *
2785
 *   - If the connection is still IDLE we can go straight to TERMINATED;
2786
 *
2787
 *   - If we are already TERMINATED this is a no-op.
2788
 *
2789
 *   - If we are TERMINATING - CLOSING and we have now got a CONNECTION_CLOSE
2790
 *     from the peer (tcause->remote == 1), we move to TERMINATING - DRAINING.
2791
 *
2792
 *   - If we are TERMINATING - DRAINING, we remain here until the terminating
2793
 *     timer expires.
2794
 *
2795
 *   - Otherwise, we are in ACTIVE and move to TERMINATING - CLOSING.
2796
 *     if we caused the termination (e.g. we have sent a CONNECTION_CLOSE). Note
2797
 *     that we are considered to have caused a termination if we sent the first
2798
 *     CONNECTION_CLOSE frame, even if it is caused by a peer protocol
2799
 *     violation. If the peer sent the first CONNECTION_CLOSE frame, we move to
2800
 *     TERMINATING - DRAINING.
2801
 *
2802
 * We record the termination cause structure passed on the first call only.
2803
 * Any successive calls have their termination cause data discarded;
2804
 * once we start sending a CONNECTION_CLOSE frame, we don't change the details
2805
 * in it.
2806
 *
2807
 * This conforms to RFC 9000 s. 10.2.1: Closing Connection State:
2808
 *      To minimize the state that an endpoint maintains for a closing
2809
 *      connection, endpoints MAY send the exact same packet in response
2810
 *      to any received packet.
2811
 *
2812
 * We don't drop any connection state (specifically packet protection keys)
2813
 * even though we are permitted to.  This conforms to RFC 9000 s. 10.2.1:
2814
 * Closing Connection State:
2815
 *       An endpoint MAY retain packet protection keys for incoming
2816
 *       packets to allow it to read and process a CONNECTION_CLOSE frame.
2817
 *
2818
 * Note that we do not conform to these two from the same section:
2819
 *      An endpoint's selected connection ID and the QUIC version
2820
 *      are sufficient information to identify packets for a closing
2821
 *      connection; the endpoint MAY discard all other connection state.
2822
 * and:
2823
 *      An endpoint MAY drop packet protection keys when entering the
2824
 *      closing state and send a packet containing a CONNECTION_CLOSE
2825
 *      frame in response to any UDP datagram that is received.
2826
 */
2827
static void copy_tcause(QUIC_TERMINATE_CAUSE *dst,
2828
                        const QUIC_TERMINATE_CAUSE *src)
2829
19.8k
{
2830
19.8k
    dst->error_code = src->error_code;
2831
19.8k
    dst->frame_type = src->frame_type;
2832
19.8k
    dst->app        = src->app;
2833
19.8k
    dst->remote     = src->remote;
2834
2835
19.8k
    dst->reason     = NULL;
2836
19.8k
    dst->reason_len = 0;
2837
2838
19.8k
    if (src->reason != NULL && src->reason_len > 0) {
2839
19.5k
        size_t l = src->reason_len;
2840
19.5k
        char *r;
2841
2842
19.5k
        if (l >= SIZE_MAX)
2843
0
            --l;
2844
2845
        /*
2846
         * If this fails, dst->reason becomes NULL and we simply do not use a
2847
         * reason. This ensures termination is infallible.
2848
         */
2849
19.5k
        dst->reason = r = OPENSSL_memdup(src->reason, l + 1);
2850
19.5k
        if (r == NULL)
2851
0
            return;
2852
2853
19.5k
        r[l]  = '\0';
2854
19.5k
        dst->reason_len = l;
2855
19.5k
    }
2856
19.8k
}
2857
2858
static void ch_start_terminating(QUIC_CHANNEL *ch,
2859
                                 const QUIC_TERMINATE_CAUSE *tcause,
2860
                                 int force_immediate)
2861
20.2k
{
2862
    /* No point sending anything if we haven't sent anything yet. */
2863
20.2k
    if (!ch->have_sent_any_pkt)
2864
0
        force_immediate = 1;
2865
2866
20.2k
    switch (ch->state) {
2867
0
    default:
2868
0
    case QUIC_CHANNEL_STATE_IDLE:
2869
0
        copy_tcause(&ch->terminate_cause, tcause);
2870
0
        ch_on_terminating_timeout(ch);
2871
0
        break;
2872
2873
19.8k
    case QUIC_CHANNEL_STATE_ACTIVE:
2874
19.8k
        copy_tcause(&ch->terminate_cause, tcause);
2875
2876
19.8k
        ossl_qlog_event_connectivity_connection_closed(ch_get_qlog(ch), tcause);
2877
2878
19.8k
        if (!force_immediate) {
2879
19.8k
            ch_record_state_transition(ch, tcause->remote
2880
19.8k
                                           ? QUIC_CHANNEL_STATE_TERMINATING_DRAINING
2881
19.8k
                                           : QUIC_CHANNEL_STATE_TERMINATING_CLOSING);
2882
            /*
2883
             * RFC 9000 s. 10.2 Immediate Close
2884
             *  These states SHOULD persist for at least three times
2885
             *  the current PTO interval as defined in [QUIC-RECOVERY].
2886
             */
2887
19.8k
            ch->terminate_deadline
2888
19.8k
                = ossl_time_add(get_time(ch),
2889
19.8k
                                ossl_time_multiply(ossl_ackm_get_pto_duration(ch->ackm),
2890
19.8k
                                                   3));
2891
2892
19.8k
            if (!tcause->remote) {
2893
19.1k
                OSSL_QUIC_FRAME_CONN_CLOSE f = {0};
2894
2895
                /* best effort */
2896
19.1k
                f.error_code = ch->terminate_cause.error_code;
2897
19.1k
                f.frame_type = ch->terminate_cause.frame_type;
2898
19.1k
                f.is_app     = ch->terminate_cause.app;
2899
19.1k
                f.reason     = (char *)ch->terminate_cause.reason;
2900
19.1k
                f.reason_len = ch->terminate_cause.reason_len;
2901
19.1k
                ossl_quic_tx_packetiser_schedule_conn_close(ch->txp, &f);
2902
                /*
2903
                 * RFC 9000 s. 10.2.2 Draining Connection State:
2904
                 *  An endpoint that receives a CONNECTION_CLOSE frame MAY
2905
                 *  send a single packet containing a CONNECTION_CLOSE
2906
                 *  frame before entering the draining state, using a
2907
                 *  NO_ERROR code if appropriate
2908
                 */
2909
19.1k
                ch->conn_close_queued = 1;
2910
19.1k
            }
2911
19.8k
        } else {
2912
48
            ch_on_terminating_timeout(ch);
2913
48
        }
2914
19.8k
        break;
2915
2916
0
    case QUIC_CHANNEL_STATE_TERMINATING_CLOSING:
2917
0
        if (force_immediate)
2918
0
            ch_on_terminating_timeout(ch);
2919
0
        else if (tcause->remote)
2920
            /*
2921
             * RFC 9000 s. 10.2.2 Draining Connection State:
2922
             *  An endpoint MAY enter the draining state from the
2923
             *  closing state if it receives a CONNECTION_CLOSE frame,
2924
             *  which indicates that the peer is also closing or draining.
2925
             */
2926
0
            ch_record_state_transition(ch, QUIC_CHANNEL_STATE_TERMINATING_DRAINING);
2927
2928
0
        break;
2929
2930
433
    case QUIC_CHANNEL_STATE_TERMINATING_DRAINING:
2931
        /*
2932
         * Other than in the force-immediate case, we remain here until the
2933
         * timeout expires.
2934
         */
2935
433
        if (force_immediate)
2936
0
            ch_on_terminating_timeout(ch);
2937
2938
433
        break;
2939
2940
0
    case QUIC_CHANNEL_STATE_TERMINATED:
2941
        /* No-op. */
2942
0
        break;
2943
20.2k
    }
2944
20.2k
}
2945
2946
/* For RXDP use. */
2947
void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch,
2948
                                            OSSL_QUIC_FRAME_CONN_CLOSE *f)
2949
1.85k
{
2950
1.85k
    QUIC_TERMINATE_CAUSE tcause = {0};
2951
2952
1.85k
    if (!ossl_quic_channel_is_active(ch))
2953
1.03k
        return;
2954
2955
817
    tcause.remote     = 1;
2956
817
    tcause.app        = f->is_app;
2957
817
    tcause.error_code = f->error_code;
2958
817
    tcause.frame_type = f->frame_type;
2959
817
    tcause.reason     = f->reason;
2960
817
    tcause.reason_len = f->reason_len;
2961
817
    ch_start_terminating(ch, &tcause, 0);
2962
817
}
2963
2964
static void free_frame_data(unsigned char *buf, size_t buf_len, void *arg)
2965
11.1k
{
2966
11.1k
    OPENSSL_free(buf);
2967
11.1k
}
2968
2969
static int ch_enqueue_retire_conn_id(QUIC_CHANNEL *ch, uint64_t seq_num)
2970
11.1k
{
2971
11.1k
    BUF_MEM *buf_mem = NULL;
2972
11.1k
    WPACKET wpkt;
2973
11.1k
    size_t l;
2974
2975
11.1k
    ossl_quic_srtm_remove(ch->srtm, ch, seq_num);
2976
2977
11.1k
    if ((buf_mem = BUF_MEM_new()) == NULL)
2978
0
        goto err;
2979
2980
11.1k
    if (!WPACKET_init(&wpkt, buf_mem))
2981
0
        goto err;
2982
2983
11.1k
    if (!ossl_quic_wire_encode_frame_retire_conn_id(&wpkt, seq_num)) {
2984
0
        WPACKET_cleanup(&wpkt);
2985
0
        goto err;
2986
0
    }
2987
2988
11.1k
    WPACKET_finish(&wpkt);
2989
11.1k
    if (!WPACKET_get_total_written(&wpkt, &l))
2990
0
        goto err;
2991
2992
11.1k
    if (ossl_quic_cfq_add_frame(ch->cfq, 1, QUIC_PN_SPACE_APP,
2993
11.1k
                                OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID, 0,
2994
11.1k
                                (unsigned char *)buf_mem->data, l,
2995
11.1k
                                free_frame_data, NULL) == NULL)
2996
0
        goto err;
2997
2998
11.1k
    buf_mem->data = NULL;
2999
11.1k
    BUF_MEM_free(buf_mem);
3000
11.1k
    return 1;
3001
3002
0
err:
3003
0
    ossl_quic_channel_raise_protocol_error(ch,
3004
0
                                           OSSL_QUIC_ERR_INTERNAL_ERROR,
3005
0
                                           OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
3006
0
                                           "internal error enqueueing retire conn id");
3007
0
    BUF_MEM_free(buf_mem);
3008
0
    return 0;
3009
11.1k
}
3010
3011
void ossl_quic_channel_on_new_conn_id(QUIC_CHANNEL *ch,
3012
                                      OSSL_QUIC_FRAME_NEW_CONN_ID *f)
3013
13.3k
{
3014
13.3k
    uint64_t new_remote_seq_num = ch->cur_remote_seq_num;
3015
13.3k
    uint64_t new_retire_prior_to = ch->cur_retire_prior_to;
3016
3017
13.3k
    if (!ossl_quic_channel_is_active(ch))
3018
410
        return;
3019
3020
    /* We allow only two active connection ids; first check some constraints */
3021
12.9k
    if (ch->cur_remote_dcid.id_len == 0) {
3022
        /* Changing from 0 length connection id is disallowed */
3023
0
        ossl_quic_channel_raise_protocol_error(ch,
3024
0
                                               OSSL_QUIC_ERR_PROTOCOL_VIOLATION,
3025
0
                                               OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
3026
0
                                               "zero length connection id in use");
3027
3028
0
        return;
3029
0
    }
3030
3031
12.9k
    if (f->seq_num > new_remote_seq_num)
3032
6.33k
        new_remote_seq_num = f->seq_num;
3033
12.9k
    if (f->retire_prior_to > new_retire_prior_to)
3034
5.93k
        new_retire_prior_to = f->retire_prior_to;
3035
3036
    /*
3037
     * RFC 9000-5.1.1: An endpoint MUST NOT provide more connection IDs
3038
     * than the peer's limit.
3039
     *
3040
     * After processing a NEW_CONNECTION_ID frame and adding and retiring
3041
     * active connection IDs, if the number of active connection IDs exceeds
3042
     * the value advertised in its active_connection_id_limit transport
3043
     * parameter, an endpoint MUST close the connection with an error of
3044
     * type CONNECTION_ID_LIMIT_ERROR.
3045
     */
3046
12.9k
    if (new_remote_seq_num - new_retire_prior_to > 1) {
3047
340
        ossl_quic_channel_raise_protocol_error(ch,
3048
340
                                               OSSL_QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
3049
340
                                               OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
3050
340
                                               "active_connection_id limit violated");
3051
340
        return;
3052
340
    }
3053
3054
    /*
3055
     * RFC 9000-5.1.1: An endpoint MAY send connection IDs that temporarily
3056
     * exceed a peer's limit if the NEW_CONNECTION_ID frame also requires
3057
     * the retirement of any excess, by including a sufficiently large
3058
     * value in the Retire Prior To field.
3059
     *
3060
     * RFC 9000-5.1.2: An endpoint SHOULD allow for sending and tracking
3061
     * a number of RETIRE_CONNECTION_ID frames of at least twice the value
3062
     * of the active_connection_id_limit transport parameter.  An endpoint
3063
     * MUST NOT forget a connection ID without retiring it, though it MAY
3064
     * choose to treat having connection IDs in need of retirement that
3065
     * exceed this limit as a connection error of type CONNECTION_ID_LIMIT_ERROR.
3066
     *
3067
     * We are a little bit more liberal than the minimum mandated.
3068
     */
3069
12.5k
    if (new_retire_prior_to - ch->cur_retire_prior_to > 10) {
3070
42
        ossl_quic_channel_raise_protocol_error(ch,
3071
42
                                               OSSL_QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
3072
42
                                               OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
3073
42
                                               "retiring connection id limit violated");
3074
3075
42
        return;
3076
42
    }
3077
3078
12.5k
    if (new_remote_seq_num > ch->cur_remote_seq_num) {
3079
        /* Add new stateless reset token */
3080
5.95k
        if (!ossl_quic_srtm_add(ch->srtm, ch, new_remote_seq_num,
3081
5.95k
                                &f->stateless_reset)) {
3082
0
            ossl_quic_channel_raise_protocol_error(
3083
0
                    ch, OSSL_QUIC_ERR_CONNECTION_ID_LIMIT_ERROR,
3084
0
                    OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID,
3085
0
                    "unable to store stateless reset token");
3086
3087
0
            return;
3088
0
        }
3089
5.95k
        ch->cur_remote_seq_num = new_remote_seq_num;
3090
5.95k
        ch->cur_remote_dcid = f->conn_id;
3091
5.95k
        ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid);
3092
5.95k
    }
3093
3094
    /*
3095
     * RFC 9000-5.1.2: Upon receipt of an increased Retire Prior To
3096
     * field, the peer MUST stop using the corresponding connection IDs
3097
     * and retire them with RETIRE_CONNECTION_ID frames before adding the
3098
     * newly provided connection ID to the set of active connection IDs.
3099
     */
3100
3101
    /*
3102
     * Note: RFC 9000 s. 19.15 says:
3103
     *   "An endpoint that receives a NEW_CONNECTION_ID frame with a sequence
3104
     *    number smaller than the Retire Prior To field of a previously received
3105
     *    NEW_CONNECTION_ID frame MUST send a corresponding
3106
     *    RETIRE_CONNECTION_ID frame that retires the newly received connection
3107
     *    ID, unless it has already done so for that sequence number."
3108
     *
3109
     * Since we currently always queue RETIRE_CONN_ID frames based on the Retire
3110
     * Prior To field of a NEW_CONNECTION_ID frame immediately upon receiving
3111
     * that NEW_CONNECTION_ID frame, by definition this will always be met.
3112
     * This may change in future when we change our CID handling.
3113
     */
3114
23.7k
    while (new_retire_prior_to > ch->cur_retire_prior_to) {
3115
11.1k
        if (!ch_enqueue_retire_conn_id(ch, ch->cur_retire_prior_to))
3116
0
            break;
3117
11.1k
        ++ch->cur_retire_prior_to;
3118
11.1k
    }
3119
12.5k
}
3120
3121
static void ch_save_err_state(QUIC_CHANNEL *ch)
3122
24.3k
{
3123
24.3k
    if (ch->err_state == NULL)
3124
24.3k
        ch->err_state = OSSL_ERR_STATE_new();
3125
3126
24.3k
    if (ch->err_state == NULL)
3127
0
        return;
3128
3129
24.3k
    OSSL_ERR_STATE_save(ch->err_state);
3130
24.3k
}
3131
3132
void ossl_quic_channel_inject(QUIC_CHANNEL *ch, QUIC_URXE *e)
3133
2.19M
{
3134
2.19M
    ossl_qrx_inject_urxe(ch->qrx, e);
3135
2.19M
}
3136
3137
void ossl_quic_channel_on_stateless_reset(QUIC_CHANNEL *ch)
3138
14
{
3139
14
    QUIC_TERMINATE_CAUSE tcause = {0};
3140
3141
14
    tcause.error_code   = OSSL_QUIC_ERR_NO_ERROR;
3142
14
    tcause.remote       = 1;
3143
14
    ch_start_terminating(ch, &tcause, 0);
3144
14
}
3145
3146
void ossl_quic_channel_raise_net_error(QUIC_CHANNEL *ch)
3147
0
{
3148
0
    QUIC_TERMINATE_CAUSE tcause = {0};
3149
3150
0
    if (ch->net_error)
3151
0
        return;
3152
3153
0
    ch->net_error = 1;
3154
3155
0
    tcause.error_code = OSSL_QUIC_ERR_INTERNAL_ERROR;
3156
0
    tcause.reason     = "network BIO I/O error";
3157
0
    tcause.reason_len = strlen(tcause.reason);
3158
3159
    /*
3160
     * Skip Terminating state and go directly to Terminated, no point trying to
3161
     * send CONNECTION_CLOSE if we cannot communicate.
3162
     */
3163
0
    ch_start_terminating(ch, &tcause, 1);
3164
0
}
3165
3166
int ossl_quic_channel_net_error(QUIC_CHANNEL *ch)
3167
62.5M
{
3168
62.5M
    return ch->net_error;
3169
62.5M
}
3170
3171
void ossl_quic_channel_restore_err_state(QUIC_CHANNEL *ch)
3172
29.9k
{
3173
29.9k
    if (ch == NULL)
3174
0
        return;
3175
3176
29.9k
    if (!ossl_quic_port_is_running(ch->port))
3177
0
        ossl_quic_port_restore_err_state(ch->port);
3178
29.9k
    else
3179
29.9k
        OSSL_ERR_STATE_restore(ch->err_state);
3180
29.9k
}
3181
3182
void ossl_quic_channel_raise_protocol_error_loc(QUIC_CHANNEL *ch,
3183
                                                uint64_t error_code,
3184
                                                uint64_t frame_type,
3185
                                                const char *reason,
3186
                                                ERR_STATE *err_state,
3187
                                                const char *src_file,
3188
                                                int src_line,
3189
                                                const char *src_func)
3190
45.2k
{
3191
45.2k
    QUIC_TERMINATE_CAUSE tcause = {0};
3192
45.2k
    int err_reason = error_code == OSSL_QUIC_ERR_INTERNAL_ERROR
3193
45.2k
                     ? ERR_R_INTERNAL_ERROR : SSL_R_QUIC_PROTOCOL_ERROR;
3194
45.2k
    const char *err_str = ossl_quic_err_to_string(error_code);
3195
45.2k
    const char *err_str_pfx = " (", *err_str_sfx = ")";
3196
45.2k
    const char *ft_str = NULL;
3197
45.2k
    const char *ft_str_pfx = " (", *ft_str_sfx = ")";
3198
3199
45.2k
    if (ch->protocol_error)
3200
        /* Only the first call to this function matters. */
3201
20.9k
        return;
3202
3203
24.3k
    if (err_str == NULL) {
3204
8.38k
        err_str     = "";
3205
8.38k
        err_str_pfx = "";
3206
8.38k
        err_str_sfx = "";
3207
8.38k
    }
3208
3209
    /*
3210
     * If we were provided an underlying error state, restore it and then append
3211
     * our ERR on top as a "cover letter" error.
3212
     */
3213
24.3k
    if (err_state != NULL)
3214
59
        OSSL_ERR_STATE_restore(err_state);
3215
3216
24.3k
    if (frame_type != 0) {
3217
13.5k
        ft_str = ossl_quic_frame_type_to_string(frame_type);
3218
13.5k
        if (ft_str == NULL) {
3219
5.15k
            ft_str      = "";
3220
5.15k
            ft_str_pfx  = "";
3221
5.15k
            ft_str_sfx  = "";
3222
5.15k
        }
3223
3224
13.5k
        ERR_raise_data(ERR_LIB_SSL, err_reason,
3225
13.5k
                       "QUIC error code: 0x%llx%s%s%s "
3226
13.5k
                       "(triggered by frame type: 0x%llx%s%s%s), reason: \"%s\"",
3227
13.5k
                       (unsigned long long) error_code,
3228
13.5k
                       err_str_pfx, err_str, err_str_sfx,
3229
13.5k
                       (unsigned long long) frame_type,
3230
13.5k
                       ft_str_pfx, ft_str, ft_str_sfx,
3231
13.5k
                       reason);
3232
13.5k
    } else {
3233
10.7k
        ERR_raise_data(ERR_LIB_SSL, err_reason,
3234
10.7k
                       "QUIC error code: 0x%llx%s%s%s, reason: \"%s\"",
3235
10.7k
                       (unsigned long long) error_code,
3236
10.7k
                       err_str_pfx, err_str, err_str_sfx,
3237
10.7k
                       reason);
3238
10.7k
    }
3239
3240
24.3k
    if (src_file != NULL)
3241
24.3k
        ERR_set_debug(src_file, src_line, src_func);
3242
3243
24.3k
    ch_save_err_state(ch);
3244
3245
24.3k
    tcause.error_code = error_code;
3246
24.3k
    tcause.frame_type = frame_type;
3247
24.3k
    tcause.reason     = reason;
3248
24.3k
    tcause.reason_len = strlen(reason);
3249
3250
24.3k
    ch->protocol_error = 1;
3251
24.3k
    ch_start_terminating(ch, &tcause, 0);
3252
24.3k
}
3253
3254
/*
3255
 * Called once the terminating timer expires, meaning we move from TERMINATING
3256
 * to TERMINATED.
3257
 */
3258
static void ch_on_terminating_timeout(QUIC_CHANNEL *ch)
3259
50
{
3260
50
    ch_record_state_transition(ch, QUIC_CHANNEL_STATE_TERMINATED);
3261
50
}
3262
3263
/*
3264
 * Determines the effective idle timeout duration. This is based on the idle
3265
 * timeout values that we and our peer signalled in transport parameters
3266
 * but have some limits applied.
3267
 */
3268
static OSSL_TIME ch_get_effective_idle_timeout_duration(QUIC_CHANNEL *ch)
3269
24.6M
{
3270
24.6M
    OSSL_TIME pto;
3271
3272
24.6M
    if (ch->max_idle_timeout == 0)
3273
0
        return ossl_time_infinite();
3274
3275
    /*
3276
     * RFC 9000 s. 10.1: Idle Timeout
3277
     *  To avoid excessively small idle timeout periods, endpoints
3278
     *  MUST increase the idle timeout period to be at least three
3279
     *  times the current Probe Timeout (PTO). This allows for
3280
     *  multiple PTOs to expire, and therefore multiple probes to
3281
     *  be sent and lost, prior to idle timeout.
3282
     */
3283
24.6M
    pto = ossl_ackm_get_pto_duration(ch->ackm);
3284
24.6M
    return ossl_time_max(ossl_ms2time(ch->max_idle_timeout),
3285
24.6M
                                      ossl_time_multiply(pto, 3));
3286
24.6M
}
3287
3288
/*
3289
 * Updates our idle deadline. Called when an event happens which should bump the
3290
 * idle timeout.
3291
 */
3292
static void ch_update_idle(QUIC_CHANNEL *ch)
3293
3.40M
{
3294
3.40M
    ch->idle_deadline = ossl_time_add(get_time(ch),
3295
3.40M
                                      ch_get_effective_idle_timeout_duration(ch));
3296
3.40M
}
3297
3298
/*
3299
 * Updates our ping deadline, which determines when we next generate a ping if
3300
 * we don't have any other ACK-eliciting frames to send.
3301
 */
3302
static void ch_update_ping_deadline(QUIC_CHANNEL *ch)
3303
21.2M
{
3304
21.2M
    OSSL_TIME max_span, idle_duration;
3305
3306
21.2M
    idle_duration = ch_get_effective_idle_timeout_duration(ch);
3307
21.2M
    if (ossl_time_is_infinite(idle_duration)) {
3308
0
        ch->ping_deadline = ossl_time_infinite();
3309
0
        return;
3310
0
    }
3311
3312
    /*
3313
     * Maximum amount of time without traffic before we send a PING to keep
3314
     * the connection open. Usually we use max_idle_timeout/2, but ensure
3315
     * the period never exceeds the assumed NAT interval to ensure NAT
3316
     * devices don't have their state time out (RFC 9000 s. 10.1.2).
3317
     */
3318
21.2M
    max_span = ossl_time_divide(idle_duration, 2);
3319
21.2M
    max_span = ossl_time_min(max_span, MAX_NAT_INTERVAL);
3320
21.2M
    ch->ping_deadline = ossl_time_add(get_time(ch), max_span);
3321
21.2M
}
3322
3323
/* Called when the idle timeout expires. */
3324
static void ch_on_idle_timeout(QUIC_CHANNEL *ch)
3325
15.6k
{
3326
    /*
3327
     * Idle timeout does not have an error code associated with it because a
3328
     * CONN_CLOSE is never sent for it. We shouldn't use this data once we reach
3329
     * TERMINATED anyway.
3330
     */
3331
15.6k
    ch->terminate_cause.app         = 0;
3332
15.6k
    ch->terminate_cause.error_code  = OSSL_QUIC_LOCAL_ERR_IDLE_TIMEOUT;
3333
15.6k
    ch->terminate_cause.frame_type  = 0;
3334
3335
15.6k
    ch_record_state_transition(ch, QUIC_CHANNEL_STATE_TERMINATED);
3336
15.6k
}
3337
3338
/* Called when we, as a server, get a new incoming connection. */
3339
int ossl_quic_channel_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
3340
                                  const QUIC_CONN_ID *peer_scid,
3341
                                  const QUIC_CONN_ID *peer_dcid)
3342
0
{
3343
0
    if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server))
3344
0
        return 0;
3345
3346
    /* Generate an Initial LCID we will use for the connection. */
3347
0
    if (!ossl_quic_lcidm_generate_initial(ch->lcidm, ch, &ch->cur_local_cid))
3348
0
        return 0;
3349
3350
    /* Note our newly learnt peer address and CIDs. */
3351
0
    if (!BIO_ADDR_copy(&ch->cur_peer_addr, peer))
3352
0
        return 0;
3353
3354
0
    ch->init_dcid       = *peer_dcid;
3355
0
    ch->cur_remote_dcid = *peer_scid;
3356
3357
    /* Inform QTX of peer address. */
3358
0
    if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
3359
0
        return 0;
3360
3361
    /* Inform TXP of desired CIDs. */
3362
0
    if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid))
3363
0
        return 0;
3364
3365
0
    if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid))
3366
0
        return 0;
3367
3368
    /* Setup QLOG, which did not happen earlier due to lacking an Initial ODCID. */
3369
0
    ossl_qtx_set_qlog_cb(ch->qtx, ch_get_qlog_cb, ch);
3370
0
    ossl_quic_tx_packetiser_set_qlog_cb(ch->txp, ch_get_qlog_cb, ch);
3371
3372
    /* Plug in secrets for the Initial EL. */
3373
0
    if (!ossl_quic_provide_initial_secret(ch->port->engine->libctx,
3374
0
                                          ch->port->engine->propq,
3375
0
                                          &ch->init_dcid,
3376
0
                                          /*is_server=*/1,
3377
0
                                          ch->qrx, ch->qtx))
3378
0
        return 0;
3379
3380
    /* Register the peer ODCID in the LCIDM. */
3381
0
    if (!ossl_quic_lcidm_enrol_odcid(ch->lcidm, ch, &ch->init_dcid))
3382
0
        return 0;
3383
3384
    /* Change state. */
3385
0
    ch_record_state_transition(ch, QUIC_CHANNEL_STATE_ACTIVE);
3386
0
    ch->doing_proactive_ver_neg = 0; /* not currently supported */
3387
0
    return 1;
3388
0
}
3389
3390
SSL *ossl_quic_channel_get0_ssl(QUIC_CHANNEL *ch)
3391
0
{
3392
0
    return ch->tls;
3393
0
}
3394
3395
static int ch_init_new_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs,
3396
                              int can_send, int can_recv)
3397
100k
{
3398
100k
    uint64_t rxfc_wnd;
3399
100k
    int server_init = ossl_quic_stream_is_server_init(qs);
3400
100k
    int local_init = (ch->is_server == server_init);
3401
100k
    int is_uni = !ossl_quic_stream_is_bidi(qs);
3402
3403
100k
    if (can_send)
3404
38.3k
        if ((qs->sstream = ossl_quic_sstream_new(INIT_APP_BUF_LEN)) == NULL)
3405
0
            goto err;
3406
3407
100k
    if (can_recv)
3408
100k
        if ((qs->rstream = ossl_quic_rstream_new(NULL, NULL, 0)) == NULL)
3409
0
            goto err;
3410
3411
    /* TXFC */
3412
100k
    if (!ossl_quic_txfc_init(&qs->txfc, &ch->conn_txfc))
3413
0
        goto err;
3414
3415
100k
    if (ch->got_remote_transport_params) {
3416
        /*
3417
         * If we already got peer TPs we need to apply the initial CWM credit
3418
         * now. If we didn't already get peer TPs this will be done
3419
         * automatically for all extant streams when we do.
3420
         */
3421
100k
        if (can_send) {
3422
38.3k
            uint64_t cwm;
3423
3424
38.3k
            if (is_uni)
3425
0
                cwm = ch->rx_init_max_stream_data_uni;
3426
38.3k
            else if (local_init)
3427
5.21k
                cwm = ch->rx_init_max_stream_data_bidi_local;
3428
33.1k
            else
3429
33.1k
                cwm = ch->rx_init_max_stream_data_bidi_remote;
3430
3431
38.3k
            ossl_quic_txfc_bump_cwm(&qs->txfc, cwm);
3432
38.3k
        }
3433
100k
    }
3434
3435
    /* RXFC */
3436
100k
    if (!can_recv)
3437
0
        rxfc_wnd = 0;
3438
100k
    else if (is_uni)
3439
62.5k
        rxfc_wnd = ch->tx_init_max_stream_data_uni;
3440
38.3k
    else if (local_init)
3441
5.21k
        rxfc_wnd = ch->tx_init_max_stream_data_bidi_local;
3442
33.1k
    else
3443
33.1k
        rxfc_wnd = ch->tx_init_max_stream_data_bidi_remote;
3444
3445
100k
    if (!ossl_quic_rxfc_init(&qs->rxfc, &ch->conn_rxfc,
3446
100k
                             rxfc_wnd,
3447
100k
                             DEFAULT_STREAM_RXFC_MAX_WND_MUL * rxfc_wnd,
3448
100k
                             get_time, ch))
3449
0
        goto err;
3450
3451
100k
    return 1;
3452
3453
0
err:
3454
0
    ossl_quic_sstream_free(qs->sstream);
3455
0
    qs->sstream = NULL;
3456
0
    ossl_quic_rstream_free(qs->rstream);
3457
0
    qs->rstream = NULL;
3458
0
    return 0;
3459
100k
}
3460
3461
static uint64_t *ch_get_local_stream_next_ordinal_ptr(QUIC_CHANNEL *ch,
3462
                                                      int is_uni)
3463
13.0k
{
3464
13.0k
    return is_uni ? &ch->next_local_stream_ordinal_uni
3465
13.0k
                  : &ch->next_local_stream_ordinal_bidi;
3466
13.0k
}
3467
3468
static const uint64_t *ch_get_local_stream_max_ptr(const QUIC_CHANNEL *ch,
3469
                                                   int is_uni)
3470
0
{
3471
0
    return is_uni ? &ch->max_local_streams_uni
3472
0
                  : &ch->max_local_streams_bidi;
3473
0
}
3474
3475
static const QUIC_RXFC *ch_get_remote_stream_count_rxfc(const QUIC_CHANNEL *ch,
3476
                                                        int is_uni)
3477
0
{
3478
0
    return is_uni ? &ch->max_streams_uni_rxfc
3479
0
                  : &ch->max_streams_bidi_rxfc;
3480
0
}
3481
3482
int ossl_quic_channel_is_new_local_stream_admissible(QUIC_CHANNEL *ch,
3483
                                                     int is_uni)
3484
7.81k
{
3485
7.81k
    const uint64_t *p_next_ordinal = ch_get_local_stream_next_ordinal_ptr(ch, is_uni);
3486
3487
7.81k
    return ossl_quic_stream_map_is_local_allowed_by_stream_limit(&ch->qsm,
3488
7.81k
                                                                 *p_next_ordinal,
3489
7.81k
                                                                 is_uni);
3490
7.81k
}
3491
3492
uint64_t ossl_quic_channel_get_local_stream_count_avail(const QUIC_CHANNEL *ch,
3493
                                                        int is_uni)
3494
0
{
3495
0
    const uint64_t *p_next_ordinal, *p_max;
3496
3497
0
    p_next_ordinal  = ch_get_local_stream_next_ordinal_ptr((QUIC_CHANNEL *)ch,
3498
0
                                                           is_uni);
3499
0
    p_max           = ch_get_local_stream_max_ptr(ch, is_uni);
3500
3501
0
    return *p_max - *p_next_ordinal;
3502
0
}
3503
3504
uint64_t ossl_quic_channel_get_remote_stream_count_avail(const QUIC_CHANNEL *ch,
3505
                                                         int is_uni)
3506
0
{
3507
0
    return ossl_quic_rxfc_get_credit(ch_get_remote_stream_count_rxfc(ch, is_uni));
3508
0
}
3509
3510
QUIC_STREAM *ossl_quic_channel_new_stream_local(QUIC_CHANNEL *ch, int is_uni)
3511
5.21k
{
3512
5.21k
    QUIC_STREAM *qs;
3513
5.21k
    int type;
3514
5.21k
    uint64_t stream_id;
3515
5.21k
    uint64_t *p_next_ordinal;
3516
3517
5.21k
    type = ch->is_server ? QUIC_STREAM_INITIATOR_SERVER
3518
5.21k
                         : QUIC_STREAM_INITIATOR_CLIENT;
3519
3520
5.21k
    p_next_ordinal = ch_get_local_stream_next_ordinal_ptr(ch, is_uni);
3521
3522
5.21k
    if (is_uni)
3523
0
        type |= QUIC_STREAM_DIR_UNI;
3524
5.21k
    else
3525
5.21k
        type |= QUIC_STREAM_DIR_BIDI;
3526
3527
5.21k
    if (*p_next_ordinal >= ((uint64_t)1) << 62)
3528
0
        return NULL;
3529
3530
5.21k
    stream_id = ((*p_next_ordinal) << 2) | type;
3531
3532
5.21k
    if ((qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id, type)) == NULL)
3533
0
        return NULL;
3534
3535
    /* Locally-initiated stream, so we always want a send buffer. */
3536
5.21k
    if (!ch_init_new_stream(ch, qs, /*can_send=*/1, /*can_recv=*/!is_uni))
3537
0
        goto err;
3538
3539
5.21k
    ++*p_next_ordinal;
3540
5.21k
    return qs;
3541
3542
0
err:
3543
0
    ossl_quic_stream_map_release(&ch->qsm, qs);
3544
0
    return NULL;
3545
5.21k
}
3546
3547
QUIC_STREAM *ossl_quic_channel_new_stream_remote(QUIC_CHANNEL *ch,
3548
                                                 uint64_t stream_id)
3549
95.6k
{
3550
95.6k
    uint64_t peer_role;
3551
95.6k
    int is_uni;
3552
95.6k
    QUIC_STREAM *qs;
3553
3554
95.6k
    peer_role = ch->is_server
3555
95.6k
        ? QUIC_STREAM_INITIATOR_CLIENT
3556
95.6k
        : QUIC_STREAM_INITIATOR_SERVER;
3557
3558
95.6k
    if ((stream_id & QUIC_STREAM_INITIATOR_MASK) != peer_role)
3559
0
        return NULL;
3560
3561
95.6k
    is_uni = ((stream_id & QUIC_STREAM_DIR_MASK) == QUIC_STREAM_DIR_UNI);
3562
3563
95.6k
    qs = ossl_quic_stream_map_alloc(&ch->qsm, stream_id,
3564
95.6k
                                    stream_id & (QUIC_STREAM_INITIATOR_MASK
3565
95.6k
                                                 | QUIC_STREAM_DIR_MASK));
3566
95.6k
    if (qs == NULL)
3567
0
        return NULL;
3568
3569
95.6k
    if (!ch_init_new_stream(ch, qs, /*can_send=*/!is_uni, /*can_recv=*/1))
3570
0
        goto err;
3571
3572
95.6k
    if (ch->incoming_stream_auto_reject)
3573
0
        ossl_quic_channel_reject_stream(ch, qs);
3574
95.6k
    else
3575
95.6k
        ossl_quic_stream_map_push_accept_queue(&ch->qsm, qs);
3576
3577
95.6k
    return qs;
3578
3579
0
err:
3580
0
    ossl_quic_stream_map_release(&ch->qsm, qs);
3581
0
    return NULL;
3582
95.6k
}
3583
3584
void ossl_quic_channel_set_incoming_stream_auto_reject(QUIC_CHANNEL *ch,
3585
                                                       int enable,
3586
                                                       uint64_t aec)
3587
108k
{
3588
108k
    ch->incoming_stream_auto_reject     = (enable != 0);
3589
108k
    ch->incoming_stream_auto_reject_aec = aec;
3590
108k
}
3591
3592
void ossl_quic_channel_reject_stream(QUIC_CHANNEL *ch, QUIC_STREAM *qs)
3593
0
{
3594
0
    ossl_quic_stream_map_stop_sending_recv_part(&ch->qsm, qs,
3595
0
                                                ch->incoming_stream_auto_reject_aec);
3596
3597
0
    ossl_quic_stream_map_reset_stream_send_part(&ch->qsm, qs,
3598
0
                                                ch->incoming_stream_auto_reject_aec);
3599
0
    qs->deleted = 1;
3600
3601
0
    ossl_quic_stream_map_update_state(&ch->qsm, qs);
3602
0
}
3603
3604
/* Replace local connection ID in TXP and DEMUX for testing purposes. */
3605
int ossl_quic_channel_replace_local_cid(QUIC_CHANNEL *ch,
3606
                                        const QUIC_CONN_ID *conn_id)
3607
0
{
3608
    /* Remove the current LCID from the LCIDM. */
3609
0
    if (!ossl_quic_lcidm_debug_remove(ch->lcidm, &ch->cur_local_cid))
3610
0
        return 0;
3611
0
    ch->cur_local_cid = *conn_id;
3612
    /* Set in the TXP, used only for long header packets. */
3613
0
    if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_cid))
3614
0
        return 0;
3615
    /* Add the new LCID to the LCIDM. */
3616
0
    if (!ossl_quic_lcidm_debug_add(ch->lcidm, ch, &ch->cur_local_cid,
3617
0
                                   100))
3618
0
        return 0;
3619
0
    return 1;
3620
0
}
3621
3622
void ossl_quic_channel_set_msg_callback(QUIC_CHANNEL *ch,
3623
                                        ossl_msg_cb msg_callback,
3624
                                        SSL *msg_callback_ssl)
3625
29.1k
{
3626
29.1k
    ch->msg_callback = msg_callback;
3627
29.1k
    ch->msg_callback_ssl = msg_callback_ssl;
3628
29.1k
    ossl_qtx_set_msg_callback(ch->qtx, msg_callback, msg_callback_ssl);
3629
29.1k
    ossl_quic_tx_packetiser_set_msg_callback(ch->txp, msg_callback,
3630
29.1k
                                             msg_callback_ssl);
3631
29.1k
    ossl_qrx_set_msg_callback(ch->qrx, msg_callback, msg_callback_ssl);
3632
29.1k
}
3633
3634
void ossl_quic_channel_set_msg_callback_arg(QUIC_CHANNEL *ch,
3635
                                            void *msg_callback_arg)
3636
29.1k
{
3637
29.1k
    ch->msg_callback_arg = msg_callback_arg;
3638
29.1k
    ossl_qtx_set_msg_callback_arg(ch->qtx, msg_callback_arg);
3639
29.1k
    ossl_quic_tx_packetiser_set_msg_callback_arg(ch->txp, msg_callback_arg);
3640
29.1k
    ossl_qrx_set_msg_callback_arg(ch->qrx, msg_callback_arg);
3641
29.1k
}
3642
3643
void ossl_quic_channel_set_txku_threshold_override(QUIC_CHANNEL *ch,
3644
                                                   uint64_t tx_pkt_threshold)
3645
0
{
3646
0
    ch->txku_threshold_override = tx_pkt_threshold;
3647
0
}
3648
3649
uint64_t ossl_quic_channel_get_tx_key_epoch(QUIC_CHANNEL *ch)
3650
0
{
3651
0
    return ossl_qtx_get_key_epoch(ch->qtx);
3652
0
}
3653
3654
uint64_t ossl_quic_channel_get_rx_key_epoch(QUIC_CHANNEL *ch)
3655
0
{
3656
0
    return ossl_qrx_get_key_epoch(ch->qrx);
3657
0
}
3658
3659
int ossl_quic_channel_trigger_txku(QUIC_CHANNEL *ch)
3660
0
{
3661
0
    if (!txku_allowed(ch))
3662
0
        return 0;
3663
3664
0
    ch->ku_locally_initiated = 1;
3665
0
    ch_trigger_txku(ch);
3666
0
    return 1;
3667
0
}
3668
3669
int ossl_quic_channel_ping(QUIC_CHANNEL *ch)
3670
0
{
3671
0
    int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
3672
3673
0
    ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
3674
3675
0
    return 1;
3676
0
}
3677
3678
uint16_t ossl_quic_channel_get_diag_num_rx_ack(QUIC_CHANNEL *ch)
3679
0
{
3680
0
    return ch->diag_num_rx_ack;
3681
0
}
3682
3683
void ossl_quic_channel_get_diag_local_cid(QUIC_CHANNEL *ch, QUIC_CONN_ID *cid)
3684
0
{
3685
0
    *cid = ch->cur_local_cid;
3686
0
}
3687
3688
int ossl_quic_channel_have_generated_transport_params(const QUIC_CHANNEL *ch)
3689
0
{
3690
0
    return ch->got_local_transport_params;
3691
0
}
3692
3693
void ossl_quic_channel_set_max_idle_timeout_request(QUIC_CHANNEL *ch, uint64_t ms)
3694
0
{
3695
0
    ch->max_idle_timeout_local_req = ms;
3696
0
}
3697
uint64_t ossl_quic_channel_get_max_idle_timeout_request(const QUIC_CHANNEL *ch)
3698
0
{
3699
0
    return ch->max_idle_timeout_local_req;
3700
0
}
3701
3702
uint64_t ossl_quic_channel_get_max_idle_timeout_peer_request(const QUIC_CHANNEL *ch)
3703
0
{
3704
0
    return ch->max_idle_timeout_remote_req;
3705
0
}
3706
3707
uint64_t ossl_quic_channel_get_max_idle_timeout_actual(const QUIC_CHANNEL *ch)
3708
0
{
3709
0
    return ch->max_idle_timeout;
3710
0
}