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