QUIC CHANNEL: Handle any number of streams
[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 "internal/quic_channel.h"
11 #include "internal/quic_error.h"
12 #include "internal/quic_rx_depack.h"
13 #include "../ssl_local.h"
14 #include "quic_channel_local.h"
15 #include <openssl/rand.h>
16
17 /*
18  * NOTE: While this channel implementation currently has basic server support,
19  * this functionality has been implemented for internal testing purposes and is
20  * not suitable for network use. In particular, it does not implement address
21  * validation, anti-amplification or retry logic.
22  *
23  * TODO(QUIC): Implement address validation and anti-amplification
24  * TODO(QUIC): Implement retry logic
25  */
26
27 #define INIT_DCID_LEN           8
28 #define INIT_CRYPTO_BUF_LEN     8192
29 #define INIT_APP_BUF_LEN        8192
30
31 /*
32  * Interval before we force a PING to ensure NATs don't timeout. This is based
33  * on the lowest commonly seen value of 30 seconds as cited in RFC 9000 s.
34  * 10.1.2.
35  */
36 #define MAX_NAT_INTERVAL (ossl_ms2time(25000))
37
38 static void ch_rx_pre(QUIC_CHANNEL *ch);
39 static int ch_rx(QUIC_CHANNEL *ch);
40 static int ch_tx(QUIC_CHANNEL *ch);
41 static void ch_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags);
42 static void ch_rx_handle_packet(QUIC_CHANNEL *ch);
43 static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch);
44 static int ch_retry(QUIC_CHANNEL *ch,
45                     const unsigned char *retry_token,
46                     size_t retry_token_len,
47                     const QUIC_CONN_ID *retry_scid);
48 static void ch_cleanup(QUIC_CHANNEL *ch);
49 static int ch_generate_transport_params(QUIC_CHANNEL *ch);
50 static int ch_on_transport_params(const unsigned char *params,
51                                   size_t params_len,
52                                   void *arg);
53 static int ch_on_handshake_alert(void *arg, unsigned char alert_code);
54 static int ch_on_handshake_complete(void *arg);
55 static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
56                                         uint32_t suite_id, EVP_MD *md,
57                                         const unsigned char *secret,
58                                         size_t secret_len,
59                                         void *arg);
60 static int ch_on_crypto_recv_record(const unsigned char **buf,
61                                     size_t *bytes_read, void *arg);
62 static int ch_on_crypto_release_record(size_t bytes_read, void *arg);
63 static int crypto_ensure_empty(QUIC_RSTREAM *rstream);
64 static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
65                              size_t *consumed, void *arg);
66 static OSSL_TIME get_time(void *arg);
67 static uint64_t get_stream_limit(int uni, void *arg);
68 static int rx_early_validate(QUIC_PN pn, int pn_space, void *arg);
69 static int ch_retry(QUIC_CHANNEL *ch,
70                     const unsigned char *retry_token,
71                     size_t retry_token_len,
72                     const QUIC_CONN_ID *retry_scid);
73 static void ch_update_idle(QUIC_CHANNEL *ch);
74 static int ch_discard_el(QUIC_CHANNEL *ch,
75                          uint32_t enc_level);
76 static void ch_on_idle_timeout(QUIC_CHANNEL *ch);
77 static void ch_update_idle(QUIC_CHANNEL *ch);
78 static void ch_update_ping_deadline(QUIC_CHANNEL *ch);
79 static void ch_raise_net_error(QUIC_CHANNEL *ch);
80 static void ch_on_terminating_timeout(QUIC_CHANNEL *ch);
81 static void ch_start_terminating(QUIC_CHANNEL *ch,
82                                  const QUIC_TERMINATE_CAUSE *tcause,
83                                  int force_immediate);
84 static void ch_default_packet_handler(QUIC_URXE *e, void *arg);
85 static int ch_server_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
86                                  const QUIC_CONN_ID *peer_scid,
87                                  const QUIC_CONN_ID *peer_dcid);
88
89 static int gen_rand_conn_id(OSSL_LIB_CTX *libctx, size_t len, QUIC_CONN_ID *cid)
90 {
91     if (len > QUIC_MAX_CONN_ID_LEN)
92         return 0;
93
94     cid->id_len = (unsigned char)len;
95
96     if (RAND_bytes_ex(libctx, cid->id, len, len * 8) != 1) {
97         cid->id_len = 0;
98         return 0;
99     }
100
101     return 1;
102 }
103
104 /*
105  * QUIC Channel Initialization and Teardown
106  * ========================================
107  */
108 #define DEFAULT_INIT_CONN_RXFC_WND      ( 2 * 1024 * 1024)
109 #define DEFAULT_MAX_CONN_RXFC_WND       (10 * 1024 * 1024)
110
111 #define DEFAULT_INIT_STREAM_RXFC_WND    ( 2 * 1024 * 1024)
112 #define DEFAULT_MAX_STREAM_RXFC_WND     (10 * 1024 * 1024)
113
114 static int ch_init(QUIC_CHANNEL *ch)
115 {
116     OSSL_QUIC_TX_PACKETISER_ARGS txp_args = {0};
117     OSSL_QTX_ARGS qtx_args = {0};
118     OSSL_QRX_ARGS qrx_args = {0};
119     QUIC_TLS_ARGS tls_args = {0};
120     uint32_t pn_space;
121     size_t rx_short_cid_len = ch->is_server ? INIT_DCID_LEN : 0;
122
123     /* For clients, generate our initial DCID. */
124     if (!ch->is_server
125         && !gen_rand_conn_id(ch->libctx, INIT_DCID_LEN, &ch->init_dcid))
126         goto err;
127
128     /* We plug in a network write BIO to the QTX later when we get one. */
129     qtx_args.libctx = ch->libctx;
130     qtx_args.mdpl = QUIC_MIN_INITIAL_DGRAM_LEN;
131     ch->rx_max_udp_payload_size = qtx_args.mdpl;
132
133     ch->qtx = ossl_qtx_new(&qtx_args);
134     if (ch->qtx == NULL)
135         goto err;
136
137     ch->txpim = ossl_quic_txpim_new();
138     if (ch->txpim == NULL)
139         goto err;
140
141     ch->cfq = ossl_quic_cfq_new();
142     if (ch->cfq == NULL)
143         goto err;
144
145     if (!ossl_quic_txfc_init(&ch->conn_txfc, NULL))
146         goto err;
147
148     /*
149      * Note: The TP we transmit governs what the peer can transmit and thus
150      * applies to the RXFC.
151      */
152     ch->tx_init_max_stream_data_bidi_local  = DEFAULT_INIT_STREAM_RXFC_WND;
153     ch->tx_init_max_stream_data_bidi_remote = DEFAULT_INIT_STREAM_RXFC_WND;
154     ch->tx_init_max_stream_data_uni         = DEFAULT_INIT_STREAM_RXFC_WND;
155
156     if (!ossl_quic_rxfc_init(&ch->conn_rxfc, NULL,
157                              DEFAULT_INIT_CONN_RXFC_WND,
158                              DEFAULT_MAX_CONN_RXFC_WND,
159                              get_time, ch))
160         goto err;
161
162     if (!ossl_statm_init(&ch->statm))
163         goto err;
164
165     ch->have_statm = 1;
166     ch->cc_method = &ossl_cc_newreno_method;
167     if ((ch->cc_data = ch->cc_method->new(get_time, ch)) == NULL)
168         goto err;
169
170     if ((ch->ackm = ossl_ackm_new(get_time, ch, &ch->statm,
171                                   ch->cc_method, ch->cc_data)) == NULL)
172         goto err;
173
174     if (!ossl_quic_stream_map_init(&ch->qsm, get_stream_limit, ch))
175         goto err;
176
177     ch->have_qsm = 1;
178
179     /* We use a zero-length SCID. */
180     txp_args.cur_dcid           = ch->init_dcid;
181     txp_args.ack_delay_exponent = 3;
182     txp_args.qtx                = ch->qtx;
183     txp_args.txpim              = ch->txpim;
184     txp_args.cfq                = ch->cfq;
185     txp_args.ackm               = ch->ackm;
186     txp_args.qsm                = &ch->qsm;
187     txp_args.conn_txfc          = &ch->conn_txfc;
188     txp_args.conn_rxfc          = &ch->conn_rxfc;
189     txp_args.cc_method          = ch->cc_method;
190     txp_args.cc_data            = ch->cc_data;
191     txp_args.now                = get_time;
192     txp_args.now_arg            = ch;
193     for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
194         ch->crypto_send[pn_space] = ossl_quic_sstream_new(INIT_CRYPTO_BUF_LEN);
195         if (ch->crypto_send[pn_space] == NULL)
196             goto err;
197
198         txp_args.crypto[pn_space] = ch->crypto_send[pn_space];
199     }
200
201     ch->txp = ossl_quic_tx_packetiser_new(&txp_args);
202     if (ch->txp == NULL)
203         goto err;
204
205     if ((ch->demux = ossl_quic_demux_new(/*BIO=*/NULL,
206                                          /*Short CID Len=*/rx_short_cid_len,
207                                          get_time, ch)) == NULL)
208         goto err;
209
210     /*
211      * If we are a server, setup our handler for packets not corresponding to
212      * any known DCID on our end. This is for handling clients establishing new
213      * connections.
214      */
215     if (ch->is_server)
216         ossl_quic_demux_set_default_handler(ch->demux,
217                                             ch_default_packet_handler,
218                                             ch);
219
220     qrx_args.libctx             = ch->libctx;
221     qrx_args.demux              = ch->demux;
222     qrx_args.short_conn_id_len  = rx_short_cid_len;
223     qrx_args.max_deferred       = 32;
224
225     if ((ch->qrx = ossl_qrx_new(&qrx_args)) == NULL)
226         goto err;
227
228     if (!ossl_qrx_set_early_validation_cb(ch->qrx,
229                                           rx_early_validate,
230                                           ch))
231         goto err;
232
233     if (!ch->is_server && !ossl_qrx_add_dst_conn_id(ch->qrx, &txp_args.cur_scid))
234         goto err;
235
236     for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
237         ch->crypto_recv[pn_space] = ossl_quic_rstream_new(NULL, NULL, 0);
238         if (ch->crypto_recv[pn_space] == NULL)
239             goto err;
240     }
241
242     /* Plug in the TLS handshake layer. */
243     tls_args.s                          = ch->tls;
244     tls_args.crypto_send_cb             = ch_on_crypto_send;
245     tls_args.crypto_send_cb_arg         = ch;
246     tls_args.crypto_recv_rcd_cb         = ch_on_crypto_recv_record;
247     tls_args.crypto_recv_rcd_cb_arg     = ch;
248     tls_args.crypto_release_rcd_cb      = ch_on_crypto_release_record;
249     tls_args.crypto_release_rcd_cb_arg  = ch;
250     tls_args.yield_secret_cb            = ch_on_handshake_yield_secret;
251     tls_args.yield_secret_cb_arg        = ch;
252     tls_args.got_transport_params_cb    = ch_on_transport_params;
253     tls_args.got_transport_params_cb_arg= ch;
254     tls_args.handshake_complete_cb      = ch_on_handshake_complete;
255     tls_args.handshake_complete_cb_arg  = ch;
256     tls_args.alert_cb                   = ch_on_handshake_alert;
257     tls_args.alert_cb_arg               = ch;
258     tls_args.is_server                  = ch->is_server;
259
260     if ((ch->qtls = ossl_quic_tls_new(&tls_args)) == NULL)
261         goto err;
262
263     ch->rx_max_ack_delay        = QUIC_DEFAULT_MAX_ACK_DELAY;
264     ch->rx_ack_delay_exp        = QUIC_DEFAULT_ACK_DELAY_EXP;
265     ch->rx_active_conn_id_limit = QUIC_MIN_ACTIVE_CONN_ID_LIMIT;
266     ch->max_idle_timeout        = QUIC_DEFAULT_IDLE_TIMEOUT;
267     ch->tx_enc_level            = QUIC_ENC_LEVEL_INITIAL;
268     ch->rx_enc_level            = QUIC_ENC_LEVEL_INITIAL;
269
270     /*
271      * Determine the QUIC Transport Parameters and serialize the transport
272      * parameters block. (For servers, we do this later as we must defer
273      * generation until we have received the client's transport parameters.)
274      */
275     if (!ch->is_server && !ch_generate_transport_params(ch))
276         goto err;
277
278     ch_update_idle(ch);
279     ossl_quic_reactor_init(&ch->rtor, ch_tick, ch,
280                            ch_determine_next_tick_deadline(ch));
281     return 1;
282
283 err:
284     ch_cleanup(ch);
285     return 0;
286 }
287
288 static void ch_cleanup(QUIC_CHANNEL *ch)
289 {
290     uint32_t pn_space;
291
292     if (ch->ackm != NULL)
293         for (pn_space = QUIC_PN_SPACE_INITIAL;
294              pn_space < QUIC_PN_SPACE_NUM;
295              ++pn_space)
296             ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
297
298     ossl_quic_tx_packetiser_free(ch->txp);
299     ossl_quic_txpim_free(ch->txpim);
300     ossl_quic_cfq_free(ch->cfq);
301     ossl_qtx_free(ch->qtx);
302     if (ch->cc_data != NULL)
303         ch->cc_method->free(ch->cc_data);
304     if (ch->have_statm)
305         ossl_statm_destroy(&ch->statm);
306     ossl_ackm_free(ch->ackm);
307
308     if (ch->have_qsm)
309         ossl_quic_stream_map_cleanup(&ch->qsm);
310
311     for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
312         ossl_quic_sstream_free(ch->crypto_send[pn_space]);
313         ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
314     }
315
316     ossl_qrx_pkt_release(ch->qrx_pkt);
317     ch->qrx_pkt = NULL;
318
319     ossl_quic_tls_free(ch->qtls);
320     ossl_qrx_free(ch->qrx);
321     ossl_quic_demux_free(ch->demux);
322     OPENSSL_free(ch->local_transport_params);
323 }
324
325 QUIC_CHANNEL *ossl_quic_channel_new(const QUIC_CHANNEL_ARGS *args)
326 {
327     QUIC_CHANNEL *ch = NULL;
328
329     if ((ch = OPENSSL_zalloc(sizeof(*ch))) == NULL)
330         return NULL;
331
332     ch->libctx      = args->libctx;
333     ch->propq       = args->propq;
334     ch->is_server   = args->is_server;
335     ch->tls         = args->tls;
336     ch->mutex       = args->mutex;
337     ch->now_cb      = args->now_cb;
338     ch->now_cb_arg  = args->now_cb_arg;
339
340     if (!ch_init(ch)) {
341         OPENSSL_free(ch);
342         return NULL;
343     }
344
345     return ch;
346 }
347
348 void ossl_quic_channel_free(QUIC_CHANNEL *ch)
349 {
350     if (ch == NULL)
351         return;
352
353     ch_cleanup(ch);
354     OPENSSL_free(ch);
355 }
356
357 /* Set mutator callbacks for test framework support */
358 int ossl_quic_channel_set_mutator(QUIC_CHANNEL *ch,
359                                   ossl_mutate_packet_cb mutatecb,
360                                   ossl_finish_mutate_cb finishmutatecb,
361                                   void *mutatearg)
362 {
363     if (ch->qtx == NULL)
364         return 0;
365
366     ossl_qtx_set_mutator(ch->qtx, mutatecb, finishmutatecb, mutatearg);
367     return 1;
368 }
369
370 int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr)
371 {
372     *peer_addr = ch->cur_peer_addr;
373     return 1;
374 }
375
376 int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr)
377 {
378     ch->cur_peer_addr = *peer_addr;
379     return 1;
380 }
381
382 QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch)
383 {
384     return &ch->rtor;
385 }
386
387 QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch)
388 {
389     return &ch->qsm;
390 }
391
392 OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch)
393 {
394     return &ch->statm;
395 }
396
397 QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch,
398                                                 uint64_t stream_id)
399 {
400     return ossl_quic_stream_map_get_by_id(&ch->qsm, stream_id);
401 }
402
403 int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch)
404 {
405     return ch != NULL && ch->state == QUIC_CHANNEL_STATE_ACTIVE;
406 }
407
408 int ossl_quic_channel_is_terminating(const QUIC_CHANNEL *ch)
409 {
410     if (ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING
411             || ch->state == QUIC_CHANNEL_STATE_TERMINATING_DRAINING)
412         return 1;
413
414     return 0;
415 }
416
417 int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch)
418 {
419     if (ch->state == QUIC_CHANNEL_STATE_TERMINATED)
420         return 1;
421
422     return 0;
423 }
424
425 int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch)
426 {
427     return ossl_quic_channel_is_terminating(ch)
428         || ossl_quic_channel_is_terminated(ch);
429 }
430
431 QUIC_TERMINATE_CAUSE ossl_quic_channel_get_terminate_cause(const QUIC_CHANNEL *ch)
432 {
433     return ch->terminate_cause;
434 }
435
436 int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch)
437 {
438     return ch->handshake_complete;
439 }
440
441 int ossl_quic_channel_is_handshake_confirmed(const QUIC_CHANNEL *ch)
442 {
443     return ch->handshake_confirmed;
444 }
445
446 QUIC_DEMUX *ossl_quic_channel_get0_demux(QUIC_CHANNEL *ch)
447 {
448     return ch->demux;
449 }
450
451 CRYPTO_MUTEX *ossl_quic_channel_get_mutex(QUIC_CHANNEL *ch)
452 {
453     return ch->mutex;
454 }
455
456 /*
457  * QUIC Channel: Callbacks from Miscellaneous Subsidiary Components
458  * ================================================================
459  */
460
461 /* Used by various components. */
462 static OSSL_TIME get_time(void *arg)
463 {
464     QUIC_CHANNEL *ch = arg;
465
466     if (ch->now_cb == NULL)
467         return ossl_time_now();
468
469     return ch->now_cb(ch->now_cb_arg);
470 }
471
472 /* Used by QSM. */
473 static uint64_t get_stream_limit(int uni, void *arg)
474 {
475     QUIC_CHANNEL *ch = arg;
476
477     return uni ? ch->max_local_streams_uni : ch->max_local_streams_bidi;
478 }
479
480 /*
481  * Called by QRX to determine if a packet is potentially invalid before trying
482  * to decrypt it.
483  */
484 static int rx_early_validate(QUIC_PN pn, int pn_space, void *arg)
485 {
486     QUIC_CHANNEL *ch = arg;
487
488     /* Potential duplicates should not be processed. */
489     if (!ossl_ackm_is_rx_pn_processable(ch->ackm, pn, pn_space))
490         return 0;
491
492     return 1;
493 }
494
495 /*
496  * QUIC Channel: Handshake Layer Event Handling
497  * ============================================
498  */
499 static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
500                              size_t *consumed, void *arg)
501 {
502     int ret;
503     QUIC_CHANNEL *ch = arg;
504     uint32_t enc_level = ch->tx_enc_level;
505     uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
506     QUIC_SSTREAM *sstream = ch->crypto_send[pn_space];
507
508     if (!ossl_assert(sstream != NULL))
509         return 0;
510
511     ret = ossl_quic_sstream_append(sstream, buf, buf_len, consumed);
512     return ret;
513 }
514
515 static int crypto_ensure_empty(QUIC_RSTREAM *rstream)
516 {
517     size_t avail = 0;
518     int is_fin = 0;
519
520     if (rstream == NULL)
521         return 1;
522
523     if (!ossl_quic_rstream_available(rstream, &avail, &is_fin))
524         return 0;
525
526     return avail == 0;
527 }
528
529 static int ch_on_crypto_recv_record(const unsigned char **buf,
530                                     size_t *bytes_read, void *arg)
531 {
532     QUIC_CHANNEL *ch = arg;
533     QUIC_RSTREAM *rstream;
534     int is_fin = 0; /* crypto stream is never finished, so we don't use this */
535     uint32_t i;
536
537     /*
538      * After we move to a later EL we must not allow our peer to send any new
539      * bytes in the crypto stream on a previous EL. Retransmissions of old bytes
540      * are allowed.
541      *
542      * In practice we will only move to a new EL when we have consumed all bytes
543      * which should be sent on the crypto stream at a previous EL. For example,
544      * the Handshake EL should not be provisioned until we have completely
545      * consumed a TLS 1.3 ServerHello. Thus when we provision an EL the output
546      * of ossl_quic_rstream_available() should be 0 for all lower ELs. Thus if a
547      * given EL is available we simply ensure we have not received any further
548      * bytes at a lower EL.
549      */
550     for (i = QUIC_ENC_LEVEL_INITIAL; i < ch->rx_enc_level; ++i)
551         if (i != QUIC_ENC_LEVEL_0RTT &&
552             !crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
553             /* Protocol violation (RFC 9001 s. 4.1.3) */
554             ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
555                                                    OSSL_QUIC_FRAME_TYPE_CRYPTO,
556                                                    "crypto stream data in wrong EL");
557             return 0;
558         }
559
560     rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
561     if (rstream == NULL)
562         return 0;
563
564     return ossl_quic_rstream_get_record(rstream, buf, bytes_read,
565                                         &is_fin);
566 }
567
568 static int ch_on_crypto_release_record(size_t bytes_read, void *arg)
569 {
570     QUIC_CHANNEL *ch = arg;
571     QUIC_RSTREAM *rstream;
572
573     rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
574     if (rstream == NULL)
575         return 0;
576
577     return ossl_quic_rstream_release_record(rstream, bytes_read);
578 }
579
580 static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
581                                         uint32_t suite_id, EVP_MD *md,
582                                         const unsigned char *secret,
583                                         size_t secret_len,
584                                         void *arg)
585 {
586     QUIC_CHANNEL *ch = arg;
587     uint32_t i;
588
589     if (enc_level < QUIC_ENC_LEVEL_HANDSHAKE || enc_level >= QUIC_ENC_LEVEL_NUM)
590         /* Invalid EL. */
591         return 0;
592
593
594     if (direction) {
595         /* TX */
596         if (enc_level <= ch->tx_enc_level)
597             /*
598              * Does not make sense for us to try and provision an EL we have already
599              * attained.
600              */
601             return 0;
602
603         if (!ossl_qtx_provide_secret(ch->qtx, enc_level,
604                                      suite_id, md,
605                                      secret, secret_len))
606             return 0;
607
608         ch->tx_enc_level = enc_level;
609     } else {
610         /* RX */
611         if (enc_level <= ch->rx_enc_level)
612             /*
613              * Does not make sense for us to try and provision an EL we have already
614              * attained.
615              */
616             return 0;
617
618         /*
619          * Ensure all crypto streams for previous ELs are now empty of available
620          * data.
621          */
622         for (i = QUIC_ENC_LEVEL_INITIAL; i < enc_level; ++i)
623             if (!crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
624                 /* Protocol violation (RFC 9001 s. 4.1.3) */
625                 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
626                                                     OSSL_QUIC_FRAME_TYPE_CRYPTO,
627                                                     "crypto stream data in wrong EL");
628                 return 0;
629             }
630
631         if (!ossl_qrx_provide_secret(ch->qrx, enc_level,
632                                      suite_id, md,
633                                      secret, secret_len))
634             return 0;
635
636         ch->have_new_rx_secret = 1;
637         ch->rx_enc_level = enc_level;
638     }
639
640     return 1;
641 }
642
643 static int ch_on_handshake_complete(void *arg)
644 {
645     QUIC_CHANNEL *ch = arg;
646
647     if (!ossl_assert(!ch->handshake_complete))
648         return 0; /* this should not happen twice */
649
650     if (!ossl_assert(ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT))
651         return 0;
652
653     if (!ch->got_remote_transport_params) {
654         /*
655          * Was not a valid QUIC handshake if we did not get valid transport
656          * params.
657          */
658         ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
659                                                OSSL_QUIC_FRAME_TYPE_CRYPTO,
660                                                "no transport parameters received");
661         return 0;
662     }
663
664     /* Don't need transport parameters anymore. */
665     OPENSSL_free(ch->local_transport_params);
666     ch->local_transport_params = NULL;
667
668     /* Tell TXP the handshake is complete. */
669     ossl_quic_tx_packetiser_notify_handshake_complete(ch->txp);
670
671     ch->handshake_complete = 1;
672
673     if (ch->is_server) {
674         /*
675          * On the server, the handshake is confirmed as soon as it is complete.
676          */
677         ossl_quic_channel_on_handshake_confirmed(ch);
678
679         ossl_quic_tx_packetiser_schedule_handshake_done(ch->txp);
680     }
681
682     return 1;
683 }
684
685 static int ch_on_handshake_alert(void *arg, unsigned char alert_code)
686 {
687     QUIC_CHANNEL *ch = arg;
688
689     ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_CRYPTO_ERR_BEGIN + alert_code,
690                                            0, "handshake alert");
691     return 1;
692 }
693
694 /*
695  * QUIC Channel: Transport Parameter Handling
696  * ==========================================
697  */
698
699 /*
700  * Called by handshake layer when we receive QUIC Transport Parameters from the
701  * peer. Note that these are not authenticated until the handshake is marked
702  * as complete.
703  */
704 #define TP_REASON_SERVER_ONLY(x) \
705     x " may not be sent by a client"
706 #define TP_REASON_DUP(x) \
707     x " appears multiple times"
708 #define TP_REASON_MALFORMED(x) \
709     x " is malformed"
710 #define TP_REASON_EXPECTED_VALUE(x) \
711     x " does not match expected value"
712 #define TP_REASON_NOT_RETRY(x) \
713     x " sent when not performing a retry"
714 #define TP_REASON_REQUIRED(x) \
715     x " was not sent but is required"
716
717 static void txfc_bump_cwm_bidi(QUIC_STREAM *s, void *arg)
718 {
719     if (!ossl_quic_stream_is_bidi(s)
720         || ossl_quic_stream_is_server_init(s))
721         return;
722
723     ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
724 }
725
726 static void txfc_bump_cwm_uni(QUIC_STREAM *s, void *arg)
727 {
728     if (ossl_quic_stream_is_bidi(s)
729         || ossl_quic_stream_is_server_init(s))
730         return;
731
732     ossl_quic_txfc_bump_cwm(&s->txfc, *(uint64_t *)arg);
733 }
734
735 static void do_update(QUIC_STREAM *s, void *arg)
736 {
737     QUIC_CHANNEL *ch = arg;
738
739     ossl_quic_stream_map_update_state(&ch->qsm, s);
740 }
741
742 static int ch_on_transport_params(const unsigned char *params,
743                                   size_t params_len,
744                                   void *arg)
745 {
746     QUIC_CHANNEL *ch = arg;
747     PACKET pkt;
748     uint64_t id, v;
749     size_t len;
750     const unsigned char *body;
751     int got_orig_dcid = 0;
752     int got_initial_scid = 0;
753     int got_retry_scid = 0;
754     int got_initial_max_data = 0;
755     int got_initial_max_stream_data_bidi_local = 0;
756     int got_initial_max_stream_data_bidi_remote = 0;
757     int got_initial_max_stream_data_uni = 0;
758     int got_initial_max_streams_bidi = 0;
759     int got_initial_max_streams_uni = 0;
760     int got_ack_delay_exp = 0;
761     int got_max_ack_delay = 0;
762     int got_max_udp_payload_size = 0;
763     int got_max_idle_timeout = 0;
764     int got_active_conn_id_limit = 0;
765     QUIC_CONN_ID cid;
766     const char *reason = "bad transport parameter";
767
768     if (ch->got_remote_transport_params)
769         goto malformed;
770
771     if (!PACKET_buf_init(&pkt, params, params_len))
772         return 0;
773
774     while (PACKET_remaining(&pkt) > 0) {
775         if (!ossl_quic_wire_peek_transport_param(&pkt, &id))
776             goto malformed;
777
778         switch (id) {
779         case QUIC_TPARAM_ORIG_DCID:
780             if (got_orig_dcid) {
781                 reason = TP_REASON_DUP("ORIG_DCID");
782                 goto malformed;
783             }
784
785             if (ch->is_server) {
786                 reason = TP_REASON_SERVER_ONLY("ORIG_DCID");
787                 goto malformed;
788             }
789
790             if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
791                 reason = TP_REASON_MALFORMED("ORIG_DCID");
792                 goto malformed;
793             }
794
795             /* Must match our initial DCID. */
796             if (!ossl_quic_conn_id_eq(&ch->init_dcid, &cid)) {
797                 reason = TP_REASON_EXPECTED_VALUE("ORIG_DCID");
798                 goto malformed;
799             }
800
801             got_orig_dcid = 1;
802             break;
803
804         case QUIC_TPARAM_RETRY_SCID:
805             if (ch->is_server) {
806                 reason = TP_REASON_SERVER_ONLY("RETRY_SCID");
807                 goto malformed;
808             }
809
810             if (got_retry_scid) {
811                 reason = TP_REASON_DUP("RETRY_SCID");
812                 goto malformed;
813             }
814
815             if (!ch->doing_retry) {
816                 reason = TP_REASON_NOT_RETRY("RETRY_SCID");
817                 goto malformed;
818             }
819
820             if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
821                 reason = TP_REASON_MALFORMED("RETRY_SCID");
822                 goto malformed;
823             }
824
825             /* Must match Retry packet SCID. */
826             if (!ossl_quic_conn_id_eq(&ch->retry_scid, &cid)) {
827                 reason = TP_REASON_EXPECTED_VALUE("RETRY_SCID");
828                 goto malformed;
829             }
830
831             got_retry_scid = 1;
832             break;
833
834         case QUIC_TPARAM_INITIAL_SCID:
835             if (got_initial_scid) {
836                 /* must not appear more than once */
837                 reason = TP_REASON_DUP("INITIAL_SCID");
838                 goto malformed;
839             }
840
841             if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
842                 reason = TP_REASON_MALFORMED("INITIAL_SCID");
843                 goto malformed;
844             }
845
846             /* Must match SCID of first Initial packet from server. */
847             if (!ossl_quic_conn_id_eq(&ch->init_scid, &cid)) {
848                 reason = TP_REASON_EXPECTED_VALUE("INITIAL_SCID");
849                 goto malformed;
850             }
851
852             got_initial_scid = 1;
853             break;
854
855         case QUIC_TPARAM_INITIAL_MAX_DATA:
856             if (got_initial_max_data) {
857                 /* must not appear more than once */
858                 reason = TP_REASON_DUP("INITIAL_MAX_DATA");
859                 goto malformed;
860             }
861
862             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
863                 reason = TP_REASON_MALFORMED("INITIAL_MAX_DATA");
864                 goto malformed;
865             }
866
867             ossl_quic_txfc_bump_cwm(&ch->conn_txfc, v);
868             got_initial_max_data = 1;
869             break;
870
871         case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL:
872             if (got_initial_max_stream_data_bidi_local) {
873                 /* must not appear more than once */
874                 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
875                 goto malformed;
876             }
877
878             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
879                 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
880                 goto malformed;
881             }
882
883             /*
884              * This is correct; the BIDI_LOCAL TP governs streams created by
885              * the endpoint which sends the TP, i.e., our peer.
886              */
887             ch->rx_init_max_stream_data_bidi_remote = v;
888             got_initial_max_stream_data_bidi_local = 1;
889             break;
890
891         case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE:
892             if (got_initial_max_stream_data_bidi_remote) {
893                 /* must not appear more than once */
894                 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
895                 goto malformed;
896             }
897
898             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
899                 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
900                 goto malformed;
901             }
902
903             /*
904              * This is correct; the BIDI_REMOTE TP governs streams created
905              * by the endpoint which receives the TP, i.e., us.
906              */
907             ch->rx_init_max_stream_data_bidi_local = v;
908
909             /* Apply to all existing streams. */
910             ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_bidi, &v);
911             got_initial_max_stream_data_bidi_remote = 1;
912             break;
913
914         case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI:
915             if (got_initial_max_stream_data_uni) {
916                 /* must not appear more than once */
917                 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_UNI");
918                 goto malformed;
919             }
920
921             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
922                 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_UNI");
923                 goto malformed;
924             }
925
926             ch->rx_init_max_stream_data_uni_remote = v;
927
928             /* Apply to all existing streams. */
929             ossl_quic_stream_map_visit(&ch->qsm, txfc_bump_cwm_uni, &v);
930             got_initial_max_stream_data_uni = 1;
931             break;
932
933         case QUIC_TPARAM_ACK_DELAY_EXP:
934             if (got_ack_delay_exp) {
935                 /* must not appear more than once */
936                 reason = TP_REASON_DUP("ACK_DELAY_EXP");
937                 goto malformed;
938             }
939
940             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
941                 || v > QUIC_MAX_ACK_DELAY_EXP) {
942                 reason = TP_REASON_MALFORMED("ACK_DELAY_EXP");
943                 goto malformed;
944             }
945
946             ch->rx_ack_delay_exp = (unsigned char)v;
947             got_ack_delay_exp = 1;
948             break;
949
950         case QUIC_TPARAM_MAX_ACK_DELAY:
951             if (got_max_ack_delay) {
952                 /* must not appear more than once */
953                 reason = TP_REASON_DUP("MAX_ACK_DELAY");
954                 return 0;
955             }
956
957             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
958                 || v >= (((uint64_t)1) << 14)) {
959                 reason = TP_REASON_MALFORMED("MAX_ACK_DELAY");
960                 goto malformed;
961             }
962
963             ch->rx_max_ack_delay = v;
964             got_max_ack_delay = 1;
965             break;
966
967         case QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI:
968             if (got_initial_max_streams_bidi) {
969                 /* must not appear more than once */
970                 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_BIDI");
971                 return 0;
972             }
973
974             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
975                 || v > (((uint64_t)1) << 60)) {
976                 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_BIDI");
977                 goto malformed;
978             }
979
980             assert(ch->max_local_streams_bidi == 0);
981             ch->max_local_streams_bidi = v;
982             got_initial_max_streams_bidi = 1;
983             break;
984
985         case QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI:
986             if (got_initial_max_streams_uni) {
987                 /* must not appear more than once */
988                 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_UNI");
989                 goto malformed;
990             }
991
992             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
993                 || v > (((uint64_t)1) << 60)) {
994                 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_UNI");
995                 goto malformed;
996             }
997
998             assert(ch->max_local_streams_uni == 0);
999             ch->max_local_streams_uni = v;
1000             got_initial_max_streams_uni = 1;
1001             break;
1002
1003         case QUIC_TPARAM_MAX_IDLE_TIMEOUT:
1004             if (got_max_idle_timeout) {
1005                 /* must not appear more than once */
1006                 reason = TP_REASON_DUP("MAX_IDLE_TIMEOUT");
1007                 goto malformed;
1008             }
1009
1010             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
1011                 reason = TP_REASON_MALFORMED("MAX_IDLE_TIMEOUT");
1012                 goto malformed;
1013             }
1014
1015             if (v > 0 && v < ch->max_idle_timeout)
1016                 ch->max_idle_timeout = v;
1017
1018             ch_update_idle(ch);
1019             got_max_idle_timeout = 1;
1020             break;
1021
1022         case QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE:
1023             if (got_max_udp_payload_size) {
1024                 /* must not appear more than once */
1025                 reason = TP_REASON_DUP("MAX_UDP_PAYLOAD_SIZE");
1026                 goto malformed;
1027             }
1028
1029             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1030                 || v < QUIC_MIN_INITIAL_DGRAM_LEN) {
1031                 reason = TP_REASON_MALFORMED("MAX_UDP_PAYLOAD_SIZE");
1032                 goto malformed;
1033             }
1034
1035             ch->rx_max_udp_payload_size = v;
1036             got_max_udp_payload_size    = 1;
1037             break;
1038
1039         case QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT:
1040             if (got_active_conn_id_limit) {
1041                 /* must not appear more than once */
1042                 reason = TP_REASON_DUP("ACTIVE_CONN_ID_LIMIT");
1043                 goto malformed;
1044             }
1045
1046             if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1047                 || v < QUIC_MIN_ACTIVE_CONN_ID_LIMIT) {
1048                 reason = TP_REASON_MALFORMED("ACTIVE_CONN_ID_LIMIT");
1049                 goto malformed;
1050             }
1051
1052             ch->rx_active_conn_id_limit = v;
1053             got_active_conn_id_limit = 1;
1054             break;
1055
1056         case QUIC_TPARAM_STATELESS_RESET_TOKEN:
1057             /* TODO(QUIC): Handle stateless reset tokens. */
1058             /*
1059              * We ignore these for now, but we must ensure a client doesn't
1060              * send them.
1061              */
1062             if (ch->is_server) {
1063                 reason = TP_REASON_SERVER_ONLY("STATELESS_RESET_TOKEN");
1064                 goto malformed;
1065             }
1066
1067             body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1068             if (body == NULL || len != QUIC_STATELESS_RESET_TOKEN_LEN) {
1069                 reason = TP_REASON_MALFORMED("STATELESS_RESET_TOKEN");
1070                 goto malformed;
1071             }
1072
1073             break;
1074
1075         case QUIC_TPARAM_PREFERRED_ADDR:
1076             /* TODO(QUIC): Handle preferred address. */
1077             if (ch->is_server) {
1078                 reason = TP_REASON_SERVER_ONLY("PREFERRED_ADDR");
1079                 goto malformed;
1080             }
1081
1082             body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1083             if (body == NULL) {
1084                 reason = TP_REASON_MALFORMED("PREFERRED_ADDR");
1085                 goto malformed;
1086             }
1087
1088             break;
1089
1090         case QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION:
1091             /* We do not currently handle migration, so nothing to do. */
1092         default:
1093             /* Skip over and ignore. */
1094             body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id,
1095                                                                &len);
1096             if (body == NULL)
1097                 goto malformed;
1098
1099             break;
1100         }
1101     }
1102
1103     if (!got_initial_scid) {
1104         reason = TP_REASON_REQUIRED("INITIAL_SCID");
1105         goto malformed;
1106     }
1107
1108     if (!ch->is_server) {
1109         if (!got_orig_dcid) {
1110             reason = TP_REASON_REQUIRED("ORIG_DCID");
1111             goto malformed;
1112         }
1113
1114         if (ch->doing_retry && !got_retry_scid) {
1115             reason = TP_REASON_REQUIRED("RETRY_SCID");
1116             goto malformed;
1117         }
1118     }
1119
1120     ch->got_remote_transport_params = 1;
1121
1122     if (got_initial_max_data || got_initial_max_stream_data_bidi_remote
1123         || got_initial_max_streams_bidi || got_initial_max_streams_uni)
1124         /*
1125          * If FC credit was bumped, we may now be able to send. Update all
1126          * streams.
1127          */
1128         ossl_quic_stream_map_visit(&ch->qsm, do_update, ch);
1129
1130     /* If we are a server, we now generate our own transport parameters. */
1131     if (ch->is_server && !ch_generate_transport_params(ch)) {
1132         ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1133                                                "internal error");
1134         return 0;
1135     }
1136
1137     return 1;
1138
1139 malformed:
1140     ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_TRANSPORT_PARAMETER_ERROR,
1141                                            0, reason);
1142     return 0;
1143 }
1144
1145 /*
1146  * Called when we want to generate transport parameters. This is called
1147  * immediately at instantiation time for a client and after we receive the
1148  * client's transport parameters for a server.
1149  */
1150 static int ch_generate_transport_params(QUIC_CHANNEL *ch)
1151 {
1152     int ok = 0;
1153     BUF_MEM *buf_mem = NULL;
1154     WPACKET wpkt;
1155     int wpkt_valid = 0;
1156     size_t buf_len = 0;
1157
1158     if (ch->local_transport_params != NULL)
1159         goto err;
1160
1161     if ((buf_mem = BUF_MEM_new()) == NULL)
1162         goto err;
1163
1164     if (!WPACKET_init(&wpkt, buf_mem))
1165         goto err;
1166
1167     wpkt_valid = 1;
1168
1169     if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION,
1170                                                     NULL, 0) == NULL)
1171         goto err;
1172
1173     if (ch->is_server) {
1174         if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_ORIG_DCID,
1175                                                        &ch->init_dcid))
1176             goto err;
1177
1178         if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1179                                                        &ch->cur_local_dcid))
1180             goto err;
1181     } else {
1182         /* Client always uses an empty SCID. */
1183         if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1184                                                         NULL, 0) == NULL)
1185             goto err;
1186     }
1187
1188     if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_IDLE_TIMEOUT,
1189                                                    ch->max_idle_timeout))
1190         goto err;
1191
1192     if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE,
1193                                                    QUIC_MIN_INITIAL_DGRAM_LEN))
1194         goto err;
1195
1196     if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT,
1197                                                    4))
1198         goto err;
1199
1200     if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_DATA,
1201                                                    ossl_quic_rxfc_get_cwm(&ch->conn_rxfc)))
1202         goto err;
1203
1204     /* Send the default CWM for a new RXFC. */
1205     if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
1206                                                    ch->tx_init_max_stream_data_bidi_local))
1207         goto err;
1208
1209     if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
1210                                                    ch->tx_init_max_stream_data_bidi_remote))
1211         goto err;
1212
1213     if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI,
1214                                                    ch->tx_init_max_stream_data_uni))
1215         goto err;
1216
1217     /* TODO(QUIC): MAX_STREAMS modelling */
1218     if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI,
1219                                                    ch->is_server ? 100 : 100))
1220         goto err;
1221
1222     if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI,
1223                                                    100))
1224         goto err;
1225
1226     if (!WPACKET_get_total_written(&wpkt, &buf_len))
1227         goto err;
1228
1229     ch->local_transport_params = (unsigned char *)buf_mem->data;
1230     buf_mem->data = NULL;
1231
1232     if (!WPACKET_finish(&wpkt))
1233         goto err;
1234
1235     wpkt_valid = 0;
1236
1237     if (!ossl_quic_tls_set_transport_params(ch->qtls, ch->local_transport_params,
1238                                             buf_len))
1239         goto err;
1240
1241     ok = 1;
1242 err:
1243     if (wpkt_valid)
1244         WPACKET_cleanup(&wpkt);
1245     BUF_MEM_free(buf_mem);
1246     return ok;
1247 }
1248
1249 /*
1250  * QUIC Channel: Ticker-Mutator
1251  * ============================
1252  */
1253
1254 /*
1255  * The central ticker function called by the reactor. This does everything, or
1256  * at least everything network I/O related. Best effort - not allowed to fail
1257  * "loudly".
1258  */
1259 static void ch_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags)
1260 {
1261     OSSL_TIME now, deadline;
1262     QUIC_CHANNEL *ch = arg;
1263     int channel_only = (flags & QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY) != 0;
1264
1265     /*
1266      * When we tick the QUIC connection, we do everything we need to do
1267      * periodically. In order, we:
1268      *
1269      *   - handle any incoming data from the network;
1270      *   - handle any timer events which are due to fire (ACKM, etc.)
1271      *   - write any data to the network due to be sent, to the extent
1272      *     possible;
1273      *   - determine the time at which we should next be ticked.
1274      */
1275
1276     /* If we are in the TERMINATED state, there is nothing to do. */
1277     if (ossl_quic_channel_is_terminated(ch)) {
1278         res->net_read_desired   = 0;
1279         res->net_write_desired  = 0;
1280         res->tick_deadline      = ossl_time_infinite();
1281         return;
1282     }
1283
1284     /*
1285      * If we are in the TERMINATING state, check if the terminating timer has
1286      * expired.
1287      */
1288     if (ossl_quic_channel_is_terminating(ch)) {
1289         now = get_time(ch);
1290
1291         if (ossl_time_compare(now, ch->terminate_deadline) >= 0) {
1292             ch_on_terminating_timeout(ch);
1293             res->net_read_desired   = 0;
1294             res->net_write_desired  = 0;
1295             res->tick_deadline      = ossl_time_infinite();
1296             return; /* abort normal processing, nothing to do */
1297         }
1298     }
1299
1300     /* Handle any incoming data from network. */
1301     ch_rx_pre(ch);
1302
1303     do {
1304         /* Process queued incoming packets. */
1305         ch_rx(ch);
1306
1307         /*
1308          * Allow the handshake layer to check for any new incoming data and generate
1309          * new outgoing data.
1310          */
1311         ch->have_new_rx_secret = 0;
1312         if (!channel_only)
1313             ossl_quic_tls_tick(ch->qtls);
1314
1315         /*
1316          * If the handshake layer gave us a new secret, we need to do RX again
1317          * because packets that were not previously processable and were
1318          * deferred might now be processable.
1319          *
1320          * TODO(QUIC): Consider handling this in the yield_secret callback.
1321          */
1322     } while (ch->have_new_rx_secret);
1323
1324     /*
1325      * Handle any timer events which are due to fire; namely, the loss detection
1326      * deadline and the idle timeout.
1327      *
1328      * ACKM ACK generation deadline is polled by TXP, so we don't need to handle
1329      * it here.
1330      */
1331     now = get_time(ch);
1332     if (ossl_time_compare(now, ch->idle_deadline) >= 0) {
1333         /*
1334          * Idle timeout differs from normal protocol violation because we do not
1335          * send a CONN_CLOSE frame; go straight to TERMINATED.
1336          */
1337         ch_on_idle_timeout(ch);
1338         res->net_read_desired   = 0;
1339         res->net_write_desired  = 0;
1340         res->tick_deadline      = ossl_time_infinite();
1341         return;
1342     }
1343
1344     deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1345     if (!ossl_time_is_zero(deadline) && ossl_time_compare(now, deadline) >= 0)
1346         ossl_ackm_on_timeout(ch->ackm);
1347
1348     /* If a ping is due, inform TXP. */
1349     if (ossl_time_compare(now, ch->ping_deadline) >= 0) {
1350         int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
1351
1352         ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
1353     }
1354
1355     /* Write any data to the network due to be sent. */
1356     ch_tx(ch);
1357
1358     /* Determine the time at which we should next be ticked. */
1359     res->tick_deadline = ch_determine_next_tick_deadline(ch);
1360
1361     /*
1362      * Always process network input unless we are now terminated.
1363      * Although we had not terminated at the beginning of this tick, network
1364      * errors in ch_rx_pre() or ch_tx() may have caused us to transition to the
1365      * Terminated state.
1366      */
1367     res->net_read_desired = !ossl_quic_channel_is_terminated(ch);
1368
1369     /* We want to write to the network if we have any in our queue. */
1370     res->net_write_desired
1371         = (!ossl_quic_channel_is_terminated(ch)
1372            && ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0);
1373 }
1374
1375 /* Process incoming datagrams, if any. */
1376 static void ch_rx_pre(QUIC_CHANNEL *ch)
1377 {
1378     int ret;
1379
1380     if (!ch->is_server && !ch->have_sent_any_pkt)
1381         return;
1382
1383     /*
1384      * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams
1385      * to the appropriate QRX instance.
1386      */
1387     ret = ossl_quic_demux_pump(ch->demux);
1388     if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL)
1389         /*
1390          * We don't care about transient failure, but permanent failure means we
1391          * should tear down the connection as though a protocol violation
1392          * occurred. Skip straight to the Terminating state as there is no point
1393          * trying to send CONNECTION_CLOSE frames if the network BIO is not
1394          * operating correctly.
1395          */
1396         ch_raise_net_error(ch);
1397 }
1398
1399 /* Process queued incoming packets and handle frames, if any. */
1400 static int ch_rx(QUIC_CHANNEL *ch)
1401 {
1402     int handled_any = 0;
1403
1404     if (!ch->is_server && !ch->have_sent_any_pkt)
1405         /*
1406          * We have not sent anything yet, therefore there is no need to check
1407          * for incoming data.
1408          */
1409         return 1;
1410
1411     for (;;) {
1412         assert(ch->qrx_pkt == NULL);
1413
1414         if (!ossl_qrx_read_pkt(ch->qrx, &ch->qrx_pkt))
1415             break;
1416
1417         if (!handled_any)
1418             ch_update_idle(ch);
1419
1420         ch_rx_handle_packet(ch); /* best effort */
1421
1422         /*
1423          * Regardless of the outcome of frame handling, unref the packet.
1424          * This will free the packet unless something added another
1425          * reference to it during frame processing.
1426          */
1427         ossl_qrx_pkt_release(ch->qrx_pkt);
1428         ch->qrx_pkt = NULL;
1429
1430         ch->have_sent_ack_eliciting_since_rx = 0;
1431         handled_any = 1;
1432     }
1433
1434     /*
1435      * When in TERMINATING - CLOSING, generate a CONN_CLOSE frame whenever we
1436      * process one or more incoming packets.
1437      */
1438     if (handled_any && ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING)
1439         ch->conn_close_queued = 1;
1440
1441     return 1;
1442 }
1443
1444 /* Handles the packet currently in ch->qrx_pkt->hdr. */
1445 static void ch_rx_handle_packet(QUIC_CHANNEL *ch)
1446 {
1447     uint32_t enc_level;
1448
1449     assert(ch->qrx_pkt != NULL);
1450
1451     if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)) {
1452         if (!ch->have_received_enc_pkt) {
1453             ch->init_scid = ch->qrx_pkt->hdr->src_conn_id;
1454             ch->have_received_enc_pkt = 1;
1455
1456             /*
1457              * We change to using the SCID in the first Initial packet as the
1458              * DCID.
1459              */
1460             ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->init_scid);
1461         }
1462
1463         enc_level = ossl_quic_pkt_type_to_enc_level(ch->qrx_pkt->hdr->type);
1464         if ((ch->el_discarded & (1U << enc_level)) != 0)
1465             /* Do not process packets from ELs we have already discarded. */
1466             return;
1467     }
1468
1469     /* Handle incoming packet. */
1470     switch (ch->qrx_pkt->hdr->type) {
1471     case QUIC_PKT_TYPE_RETRY:
1472         if (ch->doing_retry || ch->is_server)
1473             /*
1474              * It is not allowed to ask a client to do a retry more than
1475              * once. Clients may not send retries.
1476              */
1477             return;
1478
1479         if (ch->qrx_pkt->hdr->len <= QUIC_RETRY_INTEGRITY_TAG_LEN)
1480             /* Packets with zero-length Retry Tokens are invalid. */
1481             return;
1482
1483         /*
1484          * TODO(QUIC): Theoretically this should probably be in the QRX.
1485          * However because validation is dependent on context (namely the
1486          * client's initial DCID) we can't do this cleanly. In the future we
1487          * should probably add a callback to the QRX to let it call us (via
1488          * the DEMUX) and ask us about the correct original DCID, rather
1489          * than allow the QRX to emit a potentially malformed packet to the
1490          * upper layers. However, special casing this will do for now.
1491          */
1492         if (!ossl_quic_validate_retry_integrity_tag(ch->libctx,
1493                                                     ch->propq,
1494                                                     ch->qrx_pkt->hdr,
1495                                                     &ch->init_dcid))
1496             /* Malformed retry packet, ignore. */
1497             return;
1498
1499         ch_retry(ch, ch->qrx_pkt->hdr->data,
1500                  ch->qrx_pkt->hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN,
1501                  &ch->qrx_pkt->hdr->src_conn_id);
1502         break;
1503
1504     case QUIC_PKT_TYPE_0RTT:
1505         if (!ch->is_server)
1506             /* Clients should never receive 0-RTT packets. */
1507             return;
1508
1509         /*
1510          * TODO(QUIC): Implement 0-RTT on the server side. We currently do
1511          * not need to implement this as a client can only do 0-RTT if we
1512          * have given it permission to in a previous session.
1513          */
1514         break;
1515
1516     case QUIC_PKT_TYPE_INITIAL:
1517     case QUIC_PKT_TYPE_HANDSHAKE:
1518     case QUIC_PKT_TYPE_1RTT:
1519         if (ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE)
1520             /*
1521              * We automatically drop INITIAL EL keys when first successfully
1522              * decrypting a HANDSHAKE packet, as per the RFC.
1523              */
1524             ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
1525
1526         /* This packet contains frames, pass to the RXDP. */
1527         ossl_quic_handle_frames(ch, ch->qrx_pkt); /* best effort */
1528         break;
1529
1530     default:
1531         assert(0);
1532         break;
1533     }
1534 }
1535
1536 /*
1537  * This is called by the demux when we get a packet not destined for any known
1538  * DCID.
1539  */
1540 static void ch_default_packet_handler(QUIC_URXE *e, void *arg)
1541 {
1542     QUIC_CHANNEL *ch = arg;
1543     PACKET pkt;
1544     QUIC_PKT_HDR hdr;
1545
1546     if (!ossl_assert(ch->is_server))
1547         goto undesirable;
1548
1549     /*
1550      * We only support one connection to our server currently, so if we already
1551      * started one, ignore any new connection attempts.
1552      */
1553     if (ch->state != QUIC_CHANNEL_STATE_IDLE)
1554         goto undesirable;
1555
1556     /*
1557      * We have got a packet for an unknown DCID. This might be an attempt to
1558      * open a new connection.
1559      */
1560     if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN)
1561         goto undesirable;
1562
1563     if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len))
1564         goto err;
1565
1566     /*
1567      * We set short_conn_id_len to SIZE_MAX here which will cause the decode
1568      * operation to fail if we get a 1-RTT packet. This is fine since we only
1569      * care about Initial packets.
1570      */
1571     if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, &hdr, NULL))
1572         goto undesirable;
1573
1574     switch (hdr.version) {
1575         case QUIC_VERSION_1:
1576             break;
1577
1578         case QUIC_VERSION_NONE:
1579         default:
1580             /* Unknown version or proactive version negotiation request, bail. */
1581             /* TODO(QUIC): Handle version negotiation on server side */
1582             goto undesirable;
1583     }
1584
1585     /*
1586      * We only care about Initial packets which might be trying to establish a
1587      * connection.
1588      */
1589     if (hdr.type != QUIC_PKT_TYPE_INITIAL)
1590         goto undesirable;
1591
1592     /*
1593      * Assume this is a valid attempt to initiate a connection.
1594      *
1595      * We do not register the DCID in the initial packet we received and that
1596      * DCID is not actually used again, thus after provisioning the correct
1597      * Initial keys derived from it (which is done in the call below) we pass
1598      * the received packet directly to the QRX so that it can process it as a
1599      * one-time thing, instead of going through the usual DEMUX DCID-based
1600      * routing.
1601      */
1602     if (!ch_server_on_new_conn(ch, &e->peer,
1603                                &hdr.src_conn_id,
1604                                &hdr.dst_conn_id))
1605         goto err;
1606
1607     ossl_qrx_inject_urxe(ch->qrx, e);
1608     return;
1609
1610 err:
1611     ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1612                                            "internal error");
1613 undesirable:
1614     ossl_quic_demux_release_urxe(ch->demux, e);
1615 }
1616
1617 /* Try to generate packets and if possible, flush them to the network. */
1618 static int ch_tx(QUIC_CHANNEL *ch)
1619 {
1620     int sent_ack_eliciting = 0;
1621
1622     if (ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING) {
1623         /*
1624          * While closing, only send CONN_CLOSE if we've received more traffic
1625          * from the peer. Once we tell the TXP to generate CONN_CLOSE, all
1626          * future calls to it generate CONN_CLOSE frames, so otherwise we would
1627          * just constantly generate CONN_CLOSE frames.
1628          */
1629         if (!ch->conn_close_queued)
1630             return 0;
1631
1632         ch->conn_close_queued = 0;
1633     }
1634
1635     /*
1636      * Send a packet, if we need to. Best effort. The TXP consults the CC and
1637      * applies any limitations imposed by it, so we don't need to do it here.
1638      *
1639      * Best effort. In particular if TXP fails for some reason we should still
1640      * flush any queued packets which we already generated.
1641      */
1642     switch (ossl_quic_tx_packetiser_generate(ch->txp,
1643                                              TX_PACKETISER_ARCHETYPE_NORMAL,
1644                                              &sent_ack_eliciting)) {
1645     case TX_PACKETISER_RES_SENT_PKT:
1646         ch->have_sent_any_pkt = 1; /* Packet was sent */
1647
1648         /*
1649          * RFC 9000 s. 10.1. 'An endpoint also restarts its idle timer when
1650          * sending an ack-eliciting packet if no other ack-eliciting packets
1651          * have been sent since last receiving and processing a packet.'
1652          */
1653         if (sent_ack_eliciting && !ch->have_sent_ack_eliciting_since_rx) {
1654             ch_update_idle(ch);
1655             ch->have_sent_ack_eliciting_since_rx = 1;
1656         }
1657
1658         ch_update_ping_deadline(ch);
1659         break;
1660
1661     case TX_PACKETISER_RES_NO_PKT:
1662         break; /* No packet was sent */
1663     default:
1664         ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1665                                                "internal error");
1666         break; /* Internal failure (e.g.  allocation, assertion) */
1667     }
1668
1669     /* Flush packets to network. */
1670     switch (ossl_qtx_flush_net(ch->qtx)) {
1671     case QTX_FLUSH_NET_RES_OK:
1672     case QTX_FLUSH_NET_RES_TRANSIENT_FAIL:
1673         /* Best effort, done for now. */
1674         break;
1675
1676     case QTX_FLUSH_NET_RES_PERMANENT_FAIL:
1677     default:
1678         /* Permanent underlying network BIO, start terminating. */
1679         ch_raise_net_error(ch);
1680         break;
1681     }
1682
1683     return 1;
1684 }
1685
1686 /* Determine next tick deadline. */
1687 static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch)
1688 {
1689     OSSL_TIME deadline;
1690     uint32_t pn_space;
1691
1692     if (ossl_quic_channel_is_terminated(ch))
1693         return ossl_time_infinite();
1694
1695     deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1696     if (ossl_time_is_zero(deadline))
1697         deadline = ossl_time_infinite();
1698
1699     for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space)
1700         deadline = ossl_time_min(deadline,
1701                                  ossl_ackm_get_ack_deadline(ch->ackm, pn_space));
1702
1703     /* When will CC let us send more? */
1704     if (ossl_quic_tx_packetiser_has_pending(ch->txp, TX_PACKETISER_ARCHETYPE_NORMAL,
1705                                             TX_PACKETISER_BYPASS_CC))
1706         deadline = ossl_time_min(deadline,
1707                                  ch->cc_method->get_wakeup_deadline(ch->cc_data));
1708
1709     /* Is the terminating timer armed? */
1710     if (ossl_quic_channel_is_terminating(ch))
1711         deadline = ossl_time_min(deadline,
1712                                  ch->terminate_deadline);
1713     else if (!ossl_time_is_infinite(ch->idle_deadline))
1714         deadline = ossl_time_min(deadline,
1715                                  ch->idle_deadline);
1716
1717     /*
1718      * When do we need to send an ACK-eliciting packet to reset the idle
1719      * deadline timer for the peer?
1720      */
1721     if (!ossl_time_is_infinite(ch->ping_deadline))
1722         deadline = ossl_time_min(deadline,
1723                                  ch->ping_deadline);
1724
1725     return deadline;
1726 }
1727
1728 /*
1729  * QUIC Channel: Network BIO Configuration
1730  * =======================================
1731  */
1732
1733 /* Determines whether we can support a given poll descriptor. */
1734 static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)
1735 {
1736     if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0)
1737         return 0;
1738
1739     return 1;
1740 }
1741
1742 BIO *ossl_quic_channel_get_net_rbio(QUIC_CHANNEL *ch)
1743 {
1744     return ch->net_rbio;
1745 }
1746
1747 BIO *ossl_quic_channel_get_net_wbio(QUIC_CHANNEL *ch)
1748 {
1749     return ch->net_wbio;
1750 }
1751
1752 /*
1753  * QUIC_CHANNEL does not ref any BIO it is provided with, nor is any ref
1754  * transferred to it. The caller (i.e., QUIC_CONNECTION) is responsible for
1755  * ensuring the BIO lasts until the channel is freed or the BIO is switched out
1756  * for another BIO by a subsequent successful call to this function.
1757  */
1758 int ossl_quic_channel_set_net_rbio(QUIC_CHANNEL *ch, BIO *net_rbio)
1759 {
1760     BIO_POLL_DESCRIPTOR d = {0};
1761
1762     if (ch->net_rbio == net_rbio)
1763         return 1;
1764
1765     if (net_rbio != NULL) {
1766         if (!BIO_get_rpoll_descriptor(net_rbio, &d))
1767             /* Non-pollable BIO */
1768             d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
1769
1770         if (!validate_poll_descriptor(&d))
1771             return 0;
1772     }
1773
1774     ossl_quic_reactor_set_poll_r(&ch->rtor, &d);
1775     ossl_quic_demux_set_bio(ch->demux, net_rbio);
1776     ch->net_rbio = net_rbio;
1777     return 1;
1778 }
1779
1780 int ossl_quic_channel_set_net_wbio(QUIC_CHANNEL *ch, BIO *net_wbio)
1781 {
1782     BIO_POLL_DESCRIPTOR d = {0};
1783
1784     if (ch->net_wbio == net_wbio)
1785         return 1;
1786
1787     if (net_wbio != NULL) {
1788         if (!BIO_get_wpoll_descriptor(net_wbio, &d))
1789             /* Non-pollable BIO */
1790             d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
1791
1792         if (!validate_poll_descriptor(&d))
1793             return 0;
1794     }
1795
1796     ossl_quic_reactor_set_poll_w(&ch->rtor, &d);
1797     ossl_qtx_set_bio(ch->qtx, net_wbio);
1798     ch->net_wbio = net_wbio;
1799     return 1;
1800 }
1801
1802 /*
1803  * QUIC Channel: Lifecycle Events
1804  * ==============================
1805  */
1806 int ossl_quic_channel_start(QUIC_CHANNEL *ch)
1807 {
1808     if (ch->is_server)
1809         /*
1810          * This is not used by the server. The server moves to active
1811          * automatically on receiving an incoming connection.
1812          */
1813         return 0;
1814
1815     if (ch->state != QUIC_CHANNEL_STATE_IDLE)
1816         /* Calls to connect are idempotent */
1817         return 1;
1818
1819     /* Inform QTX of peer address. */
1820     if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
1821         return 0;
1822
1823     /* Plug in secrets for the Initial EL. */
1824     if (!ossl_quic_provide_initial_secret(ch->libctx,
1825                                           ch->propq,
1826                                           &ch->init_dcid,
1827                                           ch->is_server,
1828                                           ch->qrx, ch->qtx))
1829         return 0;
1830
1831     /* Change state. */
1832     ch->state                   = QUIC_CHANNEL_STATE_ACTIVE;
1833     ch->doing_proactive_ver_neg = 0; /* not currently supported */
1834
1835     /* Handshake layer: start (e.g. send CH). */
1836     if (!ossl_quic_tls_tick(ch->qtls))
1837         return 0;
1838
1839     ossl_quic_reactor_tick(&ch->rtor, 0); /* best effort */
1840     return 1;
1841 }
1842
1843 /* Start a locally initiated connection shutdown. */
1844 void ossl_quic_channel_local_close(QUIC_CHANNEL *ch, uint64_t app_error_code)
1845 {
1846     QUIC_TERMINATE_CAUSE tcause = {0};
1847
1848     if (ossl_quic_channel_is_term_any(ch))
1849         return;
1850
1851     tcause.app          = 1;
1852     tcause.error_code   = app_error_code;
1853     ch_start_terminating(ch, &tcause, 0);
1854 }
1855
1856 static void free_token(const unsigned char *buf, size_t buf_len, void *arg)
1857 {
1858     OPENSSL_free((unsigned char *)buf);
1859 }
1860
1861 /* Called when a server asks us to do a retry. */
1862 static int ch_retry(QUIC_CHANNEL *ch,
1863                     const unsigned char *retry_token,
1864                     size_t retry_token_len,
1865                     const QUIC_CONN_ID *retry_scid)
1866 {
1867     void *buf;
1868
1869     /* We change to using the SCID in the Retry packet as the DCID. */
1870     if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, retry_scid))
1871         return 0;
1872
1873     /*
1874      * Now we retry. We will release the Retry packet immediately, so copy
1875      * the token.
1876      */
1877     if ((buf = OPENSSL_memdup(retry_token, retry_token_len)) == NULL)
1878         return 0;
1879
1880     ossl_quic_tx_packetiser_set_initial_token(ch->txp, buf, retry_token_len,
1881                                               free_token, NULL);
1882
1883     ch->retry_scid  = *retry_scid;
1884     ch->doing_retry = 1;
1885
1886     /*
1887      * We need to stimulate the Initial EL to generate the first CRYPTO frame
1888      * again. We can do this most cleanly by simply forcing the ACKM to consider
1889      * the first Initial packet as lost, which it effectively was as the server
1890      * hasn't processed it. This also maintains the desired behaviour with e.g.
1891      * PNs not resetting and so on.
1892      *
1893      * The PN we used initially is always zero, because QUIC does not allow
1894      * repeated retries.
1895      */
1896     if (!ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL,
1897                                            /*PN=*/0))
1898         return 0;
1899
1900     /*
1901      * Plug in new secrets for the Initial EL. This is the only time we change
1902      * the secrets for an EL after we already provisioned it.
1903      */
1904     if (!ossl_quic_provide_initial_secret(ch->libctx,
1905                                           ch->propq,
1906                                           &ch->retry_scid,
1907                                           /*is_server=*/0,
1908                                           ch->qrx, ch->qtx))
1909         return 0;
1910
1911     return 1;
1912 }
1913
1914 /* Called when an EL is to be discarded. */
1915 static int ch_discard_el(QUIC_CHANNEL *ch,
1916                          uint32_t enc_level)
1917 {
1918     if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_1RTT))
1919         return 0;
1920
1921     if ((ch->el_discarded & (1U << enc_level)) != 0)
1922         /* Already done. */
1923         return 1;
1924
1925     /* Best effort for all of these. */
1926     ossl_quic_tx_packetiser_discard_enc_level(ch->txp, enc_level);
1927     ossl_qrx_discard_enc_level(ch->qrx, enc_level);
1928     ossl_qtx_discard_enc_level(ch->qtx, enc_level);
1929
1930     if (enc_level != QUIC_ENC_LEVEL_0RTT) {
1931         uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
1932
1933         ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
1934
1935         /* We should still have crypto streams at this point. */
1936         if (!ossl_assert(ch->crypto_send[pn_space] != NULL)
1937             || !ossl_assert(ch->crypto_recv[pn_space] != NULL))
1938             return 0;
1939
1940         /* Get rid of the crypto stream state for the EL. */
1941         ossl_quic_sstream_free(ch->crypto_send[pn_space]);
1942         ch->crypto_send[pn_space] = NULL;
1943
1944         ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
1945         ch->crypto_recv[pn_space] = NULL;
1946     }
1947
1948     ch->el_discarded |= (1U << enc_level);
1949     return 1;
1950 }
1951
1952 /* Intended to be called by the RXDP. */
1953 int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch)
1954 {
1955     if (ch->handshake_confirmed)
1956         return 1;
1957
1958     if (!ch->handshake_complete) {
1959         /*
1960          * Does not make sense for handshake to be confirmed before it is
1961          * completed.
1962          */
1963         ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
1964                                                OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE,
1965                                                "handshake cannot be confirmed "
1966                                                "before it is completed");
1967         return 0;
1968     }
1969
1970     ch_discard_el(ch, QUIC_ENC_LEVEL_HANDSHAKE);
1971     ch->handshake_confirmed = 1;
1972     return 1;
1973 }
1974
1975 /*
1976  * Master function used when we want to start tearing down a connection:
1977  *
1978  *   - If the connection is still IDLE we can go straight to TERMINATED;
1979  *
1980  *   - If we are already TERMINATED this is a no-op.
1981  *
1982  *   - If we are TERMINATING - CLOSING and we have now got a CONNECTION_CLOSE
1983  *     from the peer (tcause->remote == 1), we move to TERMINATING - DRAINING.
1984  *
1985  *   - If we are TERMINATING - DRAINING, we remain here until the terminating
1986  *     timer expires.
1987  *
1988  *   - Otherwise, we are in ACTIVE and move to TERMINATING - CLOSING.
1989  *     if we caused the termination (e.g. we have sent a CONNECTION_CLOSE). Note
1990  *     that we are considered to have caused a termination if we sent the first
1991  *     CONNECTION_CLOSE frame, even if it is caused by a peer protocol
1992  *     violation. If the peer sent the first CONNECTION_CLOSE frame, we move to
1993  *     TERMINATING - DRAINING.
1994  *
1995  * We record the termination cause structure passed on the first call only.
1996  * Any successive calls have their termination cause data discarded;
1997  * once we start sending a CONNECTION_CLOSE frame, we don't change the details
1998  * in it.
1999  */
2000 static void ch_start_terminating(QUIC_CHANNEL *ch,
2001                                  const QUIC_TERMINATE_CAUSE *tcause,
2002                                  int force_immediate)
2003 {
2004     switch (ch->state) {
2005     default:
2006     case QUIC_CHANNEL_STATE_IDLE:
2007         ch->terminate_cause = *tcause;
2008         ch_on_terminating_timeout(ch);
2009         break;
2010
2011     case QUIC_CHANNEL_STATE_ACTIVE:
2012         ch->terminate_cause = *tcause;
2013
2014         if (!force_immediate) {
2015             ch->state = tcause->remote ? QUIC_CHANNEL_STATE_TERMINATING_DRAINING
2016                                        : QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
2017             ch->terminate_deadline
2018                 = ossl_time_add(get_time(ch),
2019                                 ossl_time_multiply(ossl_ackm_get_pto_duration(ch->ackm),
2020                                                    3));
2021
2022             if (!tcause->remote) {
2023                 OSSL_QUIC_FRAME_CONN_CLOSE f = {0};
2024
2025                 /* best effort */
2026                 f.error_code = ch->terminate_cause.error_code;
2027                 f.frame_type = ch->terminate_cause.frame_type;
2028                 f.is_app     = ch->terminate_cause.app;
2029                 ossl_quic_tx_packetiser_schedule_conn_close(ch->txp, &f);
2030                 ch->conn_close_queued = 1;
2031             }
2032         } else {
2033             ch_on_terminating_timeout(ch);
2034         }
2035         break;
2036
2037     case QUIC_CHANNEL_STATE_TERMINATING_CLOSING:
2038         if (force_immediate)
2039             ch_on_terminating_timeout(ch);
2040         else if (tcause->remote)
2041             ch->state = QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
2042
2043         break;
2044
2045     case QUIC_CHANNEL_STATE_TERMINATING_DRAINING:
2046         /*
2047          * Other than in the force-immediate case, we remain here until the
2048          * timout expires.
2049          */
2050         if (force_immediate)
2051             ch_on_terminating_timeout(ch);
2052
2053         break;
2054
2055     case QUIC_CHANNEL_STATE_TERMINATED:
2056         /* No-op. */
2057         break;
2058     }
2059 }
2060
2061 /* For RXDP use. */
2062 void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch,
2063                                             OSSL_QUIC_FRAME_CONN_CLOSE *f)
2064 {
2065     QUIC_TERMINATE_CAUSE tcause = {0};
2066
2067     if (!ossl_quic_channel_is_active(ch))
2068         return;
2069
2070     tcause.remote     = 1;
2071     tcause.app        = f->is_app;
2072     tcause.error_code = f->error_code;
2073     tcause.frame_type = f->frame_type;
2074
2075     ch_start_terminating(ch, &tcause, 0);
2076 }
2077
2078 static void ch_raise_net_error(QUIC_CHANNEL *ch)
2079 {
2080     QUIC_TERMINATE_CAUSE tcause = {0};
2081
2082     tcause.error_code = QUIC_ERR_INTERNAL_ERROR;
2083
2084     /*
2085      * Skip Terminating state and go directly to Terminated, no point trying to
2086      * send CONNECTION_CLOSE if we cannot communicate.
2087      */
2088     ch_start_terminating(ch, &tcause, 1);
2089 }
2090
2091 void ossl_quic_channel_raise_protocol_error(QUIC_CHANNEL *ch,
2092                                             uint64_t error_code,
2093                                             uint64_t frame_type,
2094                                             const char *reason)
2095 {
2096     QUIC_TERMINATE_CAUSE tcause = {0};
2097
2098     tcause.error_code = error_code;
2099     tcause.frame_type = frame_type;
2100
2101     ch_start_terminating(ch, &tcause, 0);
2102 }
2103
2104 /*
2105  * Called once the terminating timer expires, meaning we move from TERMINATING
2106  * to TERMINATED.
2107  */
2108 static void ch_on_terminating_timeout(QUIC_CHANNEL *ch)
2109 {
2110     ch->state = QUIC_CHANNEL_STATE_TERMINATED;
2111 }
2112
2113 /*
2114  * Updates our idle deadline. Called when an event happens which should bump the
2115  * idle timeout.
2116  */
2117 static void ch_update_idle(QUIC_CHANNEL *ch)
2118 {
2119     if (ch->max_idle_timeout == 0)
2120         ch->idle_deadline = ossl_time_infinite();
2121     else
2122         ch->idle_deadline = ossl_time_add(get_time(ch),
2123             ossl_ms2time(ch->max_idle_timeout));
2124 }
2125
2126 /*
2127  * Updates our ping deadline, which determines when we next generate a ping if
2128  * we don't have any other ACK-eliciting frames to send.
2129  */
2130 static void ch_update_ping_deadline(QUIC_CHANNEL *ch)
2131 {
2132     if (ch->max_idle_timeout > 0) {
2133         /*
2134          * Maximum amount of time without traffic before we send a PING to keep
2135          * the connection open. Usually we use max_idle_timeout/2, but ensure
2136          * the period never exceeds the assumed NAT interval to ensure NAT
2137          * devices don't have their state time out (RFC 9000 s. 10.1.2).
2138          */
2139         OSSL_TIME max_span
2140             = ossl_time_divide(ossl_ms2time(ch->max_idle_timeout), 2);
2141
2142         max_span = ossl_time_min(max_span, MAX_NAT_INTERVAL);
2143
2144         ch->ping_deadline = ossl_time_add(get_time(ch), max_span);
2145     } else {
2146         ch->ping_deadline = ossl_time_infinite();
2147     }
2148 }
2149
2150 /* Called when the idle timeout expires. */
2151 static void ch_on_idle_timeout(QUIC_CHANNEL *ch)
2152 {
2153     /*
2154      * Idle timeout does not have an error code associated with it because a
2155      * CONN_CLOSE is never sent for it. We shouldn't use this data once we reach
2156      * TERMINATED anyway.
2157      */
2158     ch->terminate_cause.app         = 0;
2159     ch->terminate_cause.error_code  = UINT64_MAX;
2160     ch->terminate_cause.frame_type  = 0;
2161
2162     ch->state = QUIC_CHANNEL_STATE_TERMINATED;
2163 }
2164
2165 /* Called when we, as a server, get a new incoming connection. */
2166 static int ch_server_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
2167                                  const QUIC_CONN_ID *peer_scid,
2168                                  const QUIC_CONN_ID *peer_dcid)
2169 {
2170     if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server))
2171         return 0;
2172
2173     /* Generate a SCID we will use for the connection. */
2174     if (!gen_rand_conn_id(ch->libctx, INIT_DCID_LEN,
2175                           &ch->cur_local_dcid))
2176         return 0;
2177
2178     /* Note our newly learnt peer address and CIDs. */
2179     ch->cur_peer_addr   = *peer;
2180     ch->init_dcid       = *peer_dcid;
2181     ch->cur_remote_dcid = *peer_scid;
2182
2183     /* Inform QTX of peer address. */
2184     if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
2185         return 0;
2186
2187     /* Inform TXP of desired CIDs. */
2188     if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid))
2189         return 0;
2190
2191     if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_dcid))
2192         return 0;
2193
2194     /* Plug in secrets for the Initial EL. */
2195     if (!ossl_quic_provide_initial_secret(ch->libctx,
2196                                           ch->propq,
2197                                           &ch->init_dcid,
2198                                           /*is_server=*/1,
2199                                           ch->qrx, ch->qtx))
2200         return 0;
2201
2202     /* Register our local DCID in the DEMUX. */
2203     if (!ossl_qrx_add_dst_conn_id(ch->qrx, &ch->cur_local_dcid))
2204         return 0;
2205
2206     /* Change state. */
2207     ch->state                   = QUIC_CHANNEL_STATE_ACTIVE;
2208     ch->doing_proactive_ver_neg = 0; /* not currently supported */
2209     return 1;
2210 }
2211
2212 SSL *ossl_quic_channel_get0_ssl(QUIC_CHANNEL *ch)
2213 {
2214     return ch->tls;
2215 }