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