Coverage Report

Created: 2026-10-28 06:28

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