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