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