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