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