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