2 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
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
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>
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.
23 * TODO(QUIC): Implement address validation and anti-amplification
24 * TODO(QUIC): Implement retry logic
27 #define INIT_DCID_LEN 8
28 #define INIT_CRYPTO_BUF_LEN 8192
29 #define INIT_APP_BUF_LEN 8192
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.
36 #define MAX_NAT_INTERVAL (ossl_ms2time(25000))
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,
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,
60 static int ch_on_crypto_recv_record(const unsigned char **buf,
61 size_t *bytes_read, void *arg);
62 static int ch_on_crypto_release_record(size_t bytes_read, void *arg);
63 static int crypto_ensure_empty(QUIC_RSTREAM *rstream);
64 static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
65 size_t *consumed, void *arg);
66 static OSSL_TIME get_time(void *arg);
67 static uint64_t get_stream_limit(int uni, void *arg);
68 static int rx_early_validate(QUIC_PN pn, int pn_space, void *arg);
69 static int ch_retry(QUIC_CHANNEL *ch,
70 const unsigned char *retry_token,
71 size_t retry_token_len,
72 const QUIC_CONN_ID *retry_scid);
73 static void ch_update_idle(QUIC_CHANNEL *ch);
74 static int ch_discard_el(QUIC_CHANNEL *ch,
76 static void ch_on_idle_timeout(QUIC_CHANNEL *ch);
77 static void ch_update_idle(QUIC_CHANNEL *ch);
78 static void ch_update_ping_deadline(QUIC_CHANNEL *ch);
79 static void ch_raise_net_error(QUIC_CHANNEL *ch);
80 static void ch_on_terminating_timeout(QUIC_CHANNEL *ch);
81 static void ch_start_terminating(QUIC_CHANNEL *ch,
82 const QUIC_TERMINATE_CAUSE *tcause,
84 static void ch_default_packet_handler(QUIC_URXE *e, void *arg);
85 static int ch_server_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
86 const QUIC_CONN_ID *peer_scid,
87 const QUIC_CONN_ID *peer_dcid);
89 static int gen_rand_conn_id(OSSL_LIB_CTX *libctx, size_t len, QUIC_CONN_ID *cid)
91 if (len > QUIC_MAX_CONN_ID_LEN)
94 cid->id_len = (unsigned char)len;
96 if (RAND_bytes_ex(libctx, cid->id, len, len * 8) != 1) {
105 * QUIC Channel Initialization and Teardown
106 * ========================================
108 #define DEFAULT_INIT_CONN_RXFC_WND ( 2 * 1024 * 1024)
109 #define DEFAULT_MAX_CONN_RXFC_WND (10 * 1024 * 1024)
111 #define DEFAULT_INIT_STREAM_RXFC_WND ( 2 * 1024 * 1024)
112 #define DEFAULT_MAX_STREAM_RXFC_WND (10 * 1024 * 1024)
114 static int ch_init(QUIC_CHANNEL *ch)
116 OSSL_QUIC_TX_PACKETISER_ARGS txp_args = {0};
117 OSSL_QTX_ARGS qtx_args = {0};
118 OSSL_QRX_ARGS qrx_args = {0};
119 QUIC_TLS_ARGS tls_args = {0};
121 size_t rx_short_cid_len = ch->is_server ? INIT_DCID_LEN : 0;
123 /* For clients, generate our initial DCID. */
125 && !gen_rand_conn_id(ch->libctx, INIT_DCID_LEN, &ch->init_dcid))
128 /* We plug in a network write BIO to the QTX later when we get one. */
129 qtx_args.libctx = ch->libctx;
130 qtx_args.mdpl = QUIC_MIN_INITIAL_DGRAM_LEN;
131 ch->rx_max_udp_payload_size = qtx_args.mdpl;
133 ch->qtx = ossl_qtx_new(&qtx_args);
137 ch->txpim = ossl_quic_txpim_new();
138 if (ch->txpim == NULL)
141 ch->cfq = ossl_quic_cfq_new();
145 if (!ossl_quic_txfc_init(&ch->conn_txfc, NULL))
149 * Note: The TP we transmit governs what the peer can transmit and thus
150 * applies to the RXFC.
152 ch->tx_init_max_stream_data_bidi_local = DEFAULT_INIT_STREAM_RXFC_WND;
153 ch->tx_init_max_stream_data_bidi_remote = DEFAULT_INIT_STREAM_RXFC_WND;
154 ch->tx_init_max_stream_data_uni = DEFAULT_INIT_STREAM_RXFC_WND;
156 if (!ossl_quic_rxfc_init(&ch->conn_rxfc, NULL,
157 DEFAULT_INIT_CONN_RXFC_WND,
158 DEFAULT_MAX_CONN_RXFC_WND,
162 if (!ossl_statm_init(&ch->statm))
166 ch->cc_method = &ossl_cc_newreno_method;
167 if ((ch->cc_data = ch->cc_method->new(get_time, ch)) == NULL)
170 if ((ch->ackm = ossl_ackm_new(get_time, ch, &ch->statm,
171 ch->cc_method, ch->cc_data)) == NULL)
174 if (!ossl_quic_stream_map_init(&ch->qsm, get_stream_limit, ch))
179 /* We use a zero-length SCID. */
180 txp_args.cur_dcid = ch->init_dcid;
181 txp_args.ack_delay_exponent = 3;
182 txp_args.qtx = ch->qtx;
183 txp_args.txpim = ch->txpim;
184 txp_args.cfq = ch->cfq;
185 txp_args.ackm = ch->ackm;
186 txp_args.qsm = &ch->qsm;
187 txp_args.conn_txfc = &ch->conn_txfc;
188 txp_args.conn_rxfc = &ch->conn_rxfc;
189 txp_args.cc_method = ch->cc_method;
190 txp_args.cc_data = ch->cc_data;
191 txp_args.now = get_time;
192 txp_args.now_arg = ch;
193 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
194 ch->crypto_send[pn_space] = ossl_quic_sstream_new(INIT_CRYPTO_BUF_LEN);
195 if (ch->crypto_send[pn_space] == NULL)
198 txp_args.crypto[pn_space] = ch->crypto_send[pn_space];
201 ch->txp = ossl_quic_tx_packetiser_new(&txp_args);
205 if ((ch->demux = ossl_quic_demux_new(/*BIO=*/NULL,
206 /*Short CID Len=*/rx_short_cid_len,
207 get_time, ch)) == NULL)
211 * If we are a server, setup our handler for packets not corresponding to
212 * any known DCID on our end. This is for handling clients establishing new
216 ossl_quic_demux_set_default_handler(ch->demux,
217 ch_default_packet_handler,
220 qrx_args.libctx = ch->libctx;
221 qrx_args.demux = ch->demux;
222 qrx_args.short_conn_id_len = rx_short_cid_len;
223 qrx_args.max_deferred = 32;
225 if ((ch->qrx = ossl_qrx_new(&qrx_args)) == NULL)
228 if (!ossl_qrx_set_early_validation_cb(ch->qrx,
233 if (!ch->is_server && !ossl_qrx_add_dst_conn_id(ch->qrx, &txp_args.cur_scid))
236 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
237 ch->crypto_recv[pn_space] = ossl_quic_rstream_new(NULL, NULL, 0);
238 if (ch->crypto_recv[pn_space] == NULL)
242 /* Plug in the TLS handshake layer. */
243 tls_args.s = ch->tls;
244 tls_args.crypto_send_cb = ch_on_crypto_send;
245 tls_args.crypto_send_cb_arg = ch;
246 tls_args.crypto_recv_rcd_cb = ch_on_crypto_recv_record;
247 tls_args.crypto_recv_rcd_cb_arg = ch;
248 tls_args.crypto_release_rcd_cb = ch_on_crypto_release_record;
249 tls_args.crypto_release_rcd_cb_arg = ch;
250 tls_args.yield_secret_cb = ch_on_handshake_yield_secret;
251 tls_args.yield_secret_cb_arg = ch;
252 tls_args.got_transport_params_cb = ch_on_transport_params;
253 tls_args.got_transport_params_cb_arg= ch;
254 tls_args.handshake_complete_cb = ch_on_handshake_complete;
255 tls_args.handshake_complete_cb_arg = ch;
256 tls_args.alert_cb = ch_on_handshake_alert;
257 tls_args.alert_cb_arg = ch;
258 tls_args.is_server = ch->is_server;
260 if ((ch->qtls = ossl_quic_tls_new(&tls_args)) == NULL)
263 ch->rx_max_ack_delay = QUIC_DEFAULT_MAX_ACK_DELAY;
264 ch->rx_ack_delay_exp = QUIC_DEFAULT_ACK_DELAY_EXP;
265 ch->rx_active_conn_id_limit = QUIC_MIN_ACTIVE_CONN_ID_LIMIT;
266 ch->max_idle_timeout = QUIC_DEFAULT_IDLE_TIMEOUT;
267 ch->tx_enc_level = QUIC_ENC_LEVEL_INITIAL;
268 ch->rx_enc_level = QUIC_ENC_LEVEL_INITIAL;
271 * Determine the QUIC Transport Parameters and serialize the transport
272 * parameters block. (For servers, we do this later as we must defer
273 * generation until we have received the client's transport parameters.)
275 if (!ch->is_server && !ch_generate_transport_params(ch))
279 ossl_quic_reactor_init(&ch->rtor, ch_tick, ch,
280 ch_determine_next_tick_deadline(ch));
288 static void ch_cleanup(QUIC_CHANNEL *ch)
292 if (ch->ackm != NULL)
293 for (pn_space = QUIC_PN_SPACE_INITIAL;
294 pn_space < QUIC_PN_SPACE_NUM;
296 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
298 ossl_quic_tx_packetiser_free(ch->txp);
299 ossl_quic_txpim_free(ch->txpim);
300 ossl_quic_cfq_free(ch->cfq);
301 ossl_qtx_free(ch->qtx);
302 if (ch->cc_data != NULL)
303 ch->cc_method->free(ch->cc_data);
305 ossl_statm_destroy(&ch->statm);
306 ossl_ackm_free(ch->ackm);
309 ossl_quic_stream_map_cleanup(&ch->qsm);
311 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
312 ossl_quic_sstream_free(ch->crypto_send[pn_space]);
313 ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
316 ossl_qrx_pkt_release(ch->qrx_pkt);
319 ossl_quic_tls_free(ch->qtls);
320 ossl_qrx_free(ch->qrx);
321 ossl_quic_demux_free(ch->demux);
322 OPENSSL_free(ch->local_transport_params);
325 QUIC_CHANNEL *ossl_quic_channel_new(const QUIC_CHANNEL_ARGS *args)
327 QUIC_CHANNEL *ch = NULL;
329 if ((ch = OPENSSL_zalloc(sizeof(*ch))) == NULL)
332 ch->libctx = args->libctx;
333 ch->propq = args->propq;
334 ch->is_server = args->is_server;
336 ch->mutex = args->mutex;
337 ch->now_cb = args->now_cb;
338 ch->now_cb_arg = args->now_cb_arg;
348 void ossl_quic_channel_free(QUIC_CHANNEL *ch)
357 /* Set mutator callbacks for test framework support */
358 int ossl_quic_channel_set_mutator(QUIC_CHANNEL *ch,
359 ossl_mutate_packet_cb mutatecb,
360 ossl_finish_mutate_cb finishmutatecb,
366 ossl_qtx_set_mutator(ch->qtx, mutatecb, finishmutatecb, mutatearg);
370 int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr)
372 *peer_addr = ch->cur_peer_addr;
376 int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr)
378 ch->cur_peer_addr = *peer_addr;
382 QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch)
387 QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch)
392 OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch)
397 QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch,
400 return ossl_quic_stream_map_get_by_id(&ch->qsm, stream_id);
403 int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch)
405 return ch != NULL && ch->state == QUIC_CHANNEL_STATE_ACTIVE;
408 int ossl_quic_channel_is_terminating(const QUIC_CHANNEL *ch)
410 if (ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING
411 || ch->state == QUIC_CHANNEL_STATE_TERMINATING_DRAINING)
417 int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch)
419 if (ch->state == QUIC_CHANNEL_STATE_TERMINATED)
425 int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch)
427 return ossl_quic_channel_is_terminating(ch)
428 || ossl_quic_channel_is_terminated(ch);
431 QUIC_TERMINATE_CAUSE ossl_quic_channel_get_terminate_cause(const QUIC_CHANNEL *ch)
433 return ch->terminate_cause;
436 int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch)
438 return ch->handshake_complete;
441 int ossl_quic_channel_is_handshake_confirmed(const QUIC_CHANNEL *ch)
443 return ch->handshake_confirmed;
446 QUIC_DEMUX *ossl_quic_channel_get0_demux(QUIC_CHANNEL *ch)
451 CRYPTO_MUTEX *ossl_quic_channel_get_mutex(QUIC_CHANNEL *ch)
457 * QUIC Channel: Callbacks from Miscellaneous Subsidiary Components
458 * ================================================================
461 /* Used by various components. */
462 static OSSL_TIME get_time(void *arg)
464 QUIC_CHANNEL *ch = arg;
466 if (ch->now_cb == NULL)
467 return ossl_time_now();
469 return ch->now_cb(ch->now_cb_arg);
473 static uint64_t get_stream_limit(int uni, void *arg)
475 QUIC_CHANNEL *ch = arg;
477 return uni ? ch->max_local_streams_uni : ch->max_local_streams_bidi;
481 * Called by QRX to determine if a packet is potentially invalid before trying
484 static int rx_early_validate(QUIC_PN pn, int pn_space, void *arg)
486 QUIC_CHANNEL *ch = arg;
488 /* Potential duplicates should not be processed. */
489 if (!ossl_ackm_is_rx_pn_processable(ch->ackm, pn, pn_space))
496 * QUIC Channel: Handshake Layer Event Handling
497 * ============================================
499 static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
500 size_t *consumed, void *arg)
503 QUIC_CHANNEL *ch = arg;
504 uint32_t enc_level = ch->tx_enc_level;
505 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
506 QUIC_SSTREAM *sstream = ch->crypto_send[pn_space];
508 if (!ossl_assert(sstream != NULL))
511 ret = ossl_quic_sstream_append(sstream, buf, buf_len, consumed);
515 static int crypto_ensure_empty(QUIC_RSTREAM *rstream)
523 if (!ossl_quic_rstream_available(rstream, &avail, &is_fin))
529 static int ch_on_crypto_recv_record(const unsigned char **buf,
530 size_t *bytes_read, void *arg)
532 QUIC_CHANNEL *ch = arg;
533 QUIC_RSTREAM *rstream;
534 int is_fin = 0; /* crypto stream is never finished, so we don't use this */
538 * After we move to a later EL we must not allow our peer to send any new
539 * bytes in the crypto stream on a previous EL. Retransmissions of old bytes
542 * In practice we will only move to a new EL when we have consumed all bytes
543 * which should be sent on the crypto stream at a previous EL. For example,
544 * the Handshake EL should not be provisioned until we have completely
545 * consumed a TLS 1.3 ServerHello. Thus when we provision an EL the output
546 * of ossl_quic_rstream_available() should be 0 for all lower ELs. Thus if a
547 * given EL is available we simply ensure we have not received any further
548 * bytes at a lower EL.
550 for (i = QUIC_ENC_LEVEL_INITIAL; i < ch->rx_enc_level; ++i)
551 if (i != QUIC_ENC_LEVEL_0RTT &&
552 !crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
553 /* Protocol violation (RFC 9001 s. 4.1.3) */
554 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
555 OSSL_QUIC_FRAME_TYPE_CRYPTO,
556 "crypto stream data in wrong EL");
560 rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
564 return ossl_quic_rstream_get_record(rstream, buf, bytes_read,
568 static int ch_on_crypto_release_record(size_t bytes_read, void *arg)
570 QUIC_CHANNEL *ch = arg;
571 QUIC_RSTREAM *rstream;
573 rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
577 return ossl_quic_rstream_release_record(rstream, bytes_read);
580 static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
581 uint32_t suite_id, EVP_MD *md,
582 const unsigned char *secret,
586 QUIC_CHANNEL *ch = arg;
589 if (enc_level < QUIC_ENC_LEVEL_HANDSHAKE || enc_level >= QUIC_ENC_LEVEL_NUM)
596 if (enc_level <= ch->tx_enc_level)
598 * Does not make sense for us to try and provision an EL we have already
603 if (!ossl_qtx_provide_secret(ch->qtx, enc_level,
608 ch->tx_enc_level = enc_level;
611 if (enc_level <= ch->rx_enc_level)
613 * Does not make sense for us to try and provision an EL we have already
619 * Ensure all crypto streams for previous ELs are now empty of available
622 for (i = QUIC_ENC_LEVEL_INITIAL; i < enc_level; ++i)
623 if (!crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
624 /* Protocol violation (RFC 9001 s. 4.1.3) */
625 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
626 OSSL_QUIC_FRAME_TYPE_CRYPTO,
627 "crypto stream data in wrong EL");
631 if (!ossl_qrx_provide_secret(ch->qrx, enc_level,
636 ch->have_new_rx_secret = 1;
637 ch->rx_enc_level = enc_level;
643 static int ch_on_handshake_complete(void *arg)
645 QUIC_CHANNEL *ch = arg;
647 if (!ossl_assert(!ch->handshake_complete))
648 return 0; /* this should not happen twice */
650 if (!ossl_assert(ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT))
653 if (!ch->got_remote_transport_params) {
655 * Was not a valid QUIC handshake if we did not get valid transport
658 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
659 OSSL_QUIC_FRAME_TYPE_CRYPTO,
660 "no transport parameters received");
664 /* Don't need transport parameters anymore. */
665 OPENSSL_free(ch->local_transport_params);
666 ch->local_transport_params = NULL;
668 /* Tell TXP the handshake is complete. */
669 ossl_quic_tx_packetiser_notify_handshake_complete(ch->txp);
671 ch->handshake_complete = 1;
675 * On the server, the handshake is confirmed as soon as it is complete.
677 ossl_quic_channel_on_handshake_confirmed(ch);
679 ossl_quic_tx_packetiser_schedule_handshake_done(ch->txp);
685 static int ch_on_handshake_alert(void *arg, unsigned char alert_code)
687 QUIC_CHANNEL *ch = arg;
689 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_CRYPTO_ERR_BEGIN + alert_code,
690 0, "handshake alert");
695 * QUIC Channel: Transport Parameter Handling
696 * ==========================================
700 * Called by handshake layer when we receive QUIC Transport Parameters from the
701 * peer. Note that these are not authenticated until the handshake is marked
704 #define TP_REASON_SERVER_ONLY(x) \
705 x " may not be sent by a client"
706 #define TP_REASON_DUP(x) \
707 x " appears multiple times"
708 #define TP_REASON_MALFORMED(x) \
710 #define TP_REASON_EXPECTED_VALUE(x) \
711 x " does not match expected value"
712 #define TP_REASON_NOT_RETRY(x) \
713 x " sent when not performing a retry"
714 #define TP_REASON_REQUIRED(x) \
715 x " was not sent but is required"
717 static int ch_on_transport_params(const unsigned char *params,
721 QUIC_CHANNEL *ch = arg;
725 const unsigned char *body;
726 int got_orig_dcid = 0;
727 int got_initial_scid = 0;
728 int got_retry_scid = 0;
729 int got_initial_max_data = 0;
730 int got_initial_max_stream_data_bidi_local = 0;
731 int got_initial_max_stream_data_bidi_remote = 0;
732 int got_initial_max_stream_data_uni = 0;
733 int got_initial_max_streams_bidi = 0;
734 int got_initial_max_streams_uni = 0;
735 int got_ack_delay_exp = 0;
736 int got_max_ack_delay = 0;
737 int got_max_udp_payload_size = 0;
738 int got_max_idle_timeout = 0;
739 int got_active_conn_id_limit = 0;
741 const char *reason = "bad transport parameter";
743 if (ch->got_remote_transport_params)
746 if (!PACKET_buf_init(&pkt, params, params_len))
749 while (PACKET_remaining(&pkt) > 0) {
750 if (!ossl_quic_wire_peek_transport_param(&pkt, &id))
754 case QUIC_TPARAM_ORIG_DCID:
756 reason = TP_REASON_DUP("ORIG_DCID");
761 reason = TP_REASON_SERVER_ONLY("ORIG_DCID");
765 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
766 reason = TP_REASON_MALFORMED("ORIG_DCID");
770 /* Must match our initial DCID. */
771 if (!ossl_quic_conn_id_eq(&ch->init_dcid, &cid)) {
772 reason = TP_REASON_EXPECTED_VALUE("ORIG_DCID");
779 case QUIC_TPARAM_RETRY_SCID:
781 reason = TP_REASON_SERVER_ONLY("RETRY_SCID");
785 if (got_retry_scid) {
786 reason = TP_REASON_DUP("RETRY_SCID");
790 if (!ch->doing_retry) {
791 reason = TP_REASON_NOT_RETRY("RETRY_SCID");
795 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
796 reason = TP_REASON_MALFORMED("RETRY_SCID");
800 /* Must match Retry packet SCID. */
801 if (!ossl_quic_conn_id_eq(&ch->retry_scid, &cid)) {
802 reason = TP_REASON_EXPECTED_VALUE("RETRY_SCID");
809 case QUIC_TPARAM_INITIAL_SCID:
810 if (got_initial_scid) {
811 /* must not appear more than once */
812 reason = TP_REASON_DUP("INITIAL_SCID");
816 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid)) {
817 reason = TP_REASON_MALFORMED("INITIAL_SCID");
821 /* Must match SCID of first Initial packet from server. */
822 if (!ossl_quic_conn_id_eq(&ch->init_scid, &cid)) {
823 reason = TP_REASON_EXPECTED_VALUE("INITIAL_SCID");
827 got_initial_scid = 1;
830 case QUIC_TPARAM_INITIAL_MAX_DATA:
831 if (got_initial_max_data) {
832 /* must not appear more than once */
833 reason = TP_REASON_DUP("INITIAL_MAX_DATA");
837 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
838 reason = TP_REASON_MALFORMED("INITIAL_MAX_DATA");
842 ossl_quic_txfc_bump_cwm(&ch->conn_txfc, v);
843 got_initial_max_data = 1;
846 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL:
847 if (got_initial_max_stream_data_bidi_local) {
848 /* must not appear more than once */
849 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
853 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
854 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_LOCAL");
859 * This is correct; the BIDI_LOCAL TP governs streams created by
860 * the endpoint which sends the TP, i.e., our peer.
862 ch->rx_init_max_stream_data_bidi_remote = v;
863 got_initial_max_stream_data_bidi_local = 1;
866 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE:
867 if (got_initial_max_stream_data_bidi_remote) {
868 /* must not appear more than once */
869 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
873 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
874 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_BIDI_REMOTE");
879 * This is correct; the BIDI_REMOTE TP governs streams created
880 * by the endpoint which receives the TP, i.e., us.
882 ch->rx_init_max_stream_data_bidi_local = v;
884 /* Apply to stream 0. */
885 ossl_quic_txfc_bump_cwm(&ch->stream0->txfc, v);
886 got_initial_max_stream_data_bidi_remote = 1;
889 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI:
890 if (got_initial_max_stream_data_uni) {
891 /* must not appear more than once */
892 reason = TP_REASON_DUP("INITIAL_MAX_STREAM_DATA_UNI");
896 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
897 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAM_DATA_UNI");
901 ch->rx_init_max_stream_data_uni_remote = v;
902 got_initial_max_stream_data_uni = 1;
905 case QUIC_TPARAM_ACK_DELAY_EXP:
906 if (got_ack_delay_exp) {
907 /* must not appear more than once */
908 reason = TP_REASON_DUP("ACK_DELAY_EXP");
912 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
913 || v > QUIC_MAX_ACK_DELAY_EXP) {
914 reason = TP_REASON_MALFORMED("ACK_DELAY_EXP");
918 ch->rx_ack_delay_exp = (unsigned char)v;
919 got_ack_delay_exp = 1;
922 case QUIC_TPARAM_MAX_ACK_DELAY:
923 if (got_max_ack_delay) {
924 /* must not appear more than once */
925 reason = TP_REASON_DUP("MAX_ACK_DELAY");
929 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
930 || v >= (((uint64_t)1) << 14)) {
931 reason = TP_REASON_MALFORMED("MAX_ACK_DELAY");
935 ch->rx_max_ack_delay = v;
936 got_max_ack_delay = 1;
939 case QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI:
940 if (got_initial_max_streams_bidi) {
941 /* must not appear more than once */
942 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_BIDI");
946 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
947 || v > (((uint64_t)1) << 60)) {
948 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_BIDI");
952 assert(ch->max_local_streams_bidi == 0);
953 ch->max_local_streams_bidi = v;
954 got_initial_max_streams_bidi = 1;
957 case QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI:
958 if (got_initial_max_streams_uni) {
959 /* must not appear more than once */
960 reason = TP_REASON_DUP("INITIAL_MAX_STREAMS_UNI");
964 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
965 || v > (((uint64_t)1) << 60)) {
966 reason = TP_REASON_MALFORMED("INITIAL_MAX_STREAMS_UNI");
970 assert(ch->max_local_streams_uni == 0);
971 ch->max_local_streams_uni = v;
972 got_initial_max_streams_uni = 1;
975 case QUIC_TPARAM_MAX_IDLE_TIMEOUT:
976 if (got_max_idle_timeout) {
977 /* must not appear more than once */
978 reason = TP_REASON_DUP("MAX_IDLE_TIMEOUT");
982 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)) {
983 reason = TP_REASON_MALFORMED("MAX_IDLE_TIMEOUT");
987 if (v > 0 && v < ch->max_idle_timeout)
988 ch->max_idle_timeout = v;
991 got_max_idle_timeout = 1;
994 case QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE:
995 if (got_max_udp_payload_size) {
996 /* must not appear more than once */
997 reason = TP_REASON_DUP("MAX_UDP_PAYLOAD_SIZE");
1001 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1002 || v < QUIC_MIN_INITIAL_DGRAM_LEN) {
1003 reason = TP_REASON_MALFORMED("MAX_UDP_PAYLOAD_SIZE");
1007 ch->rx_max_udp_payload_size = v;
1008 got_max_udp_payload_size = 1;
1011 case QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT:
1012 if (got_active_conn_id_limit) {
1013 /* must not appear more than once */
1014 reason = TP_REASON_DUP("ACTIVE_CONN_ID_LIMIT");
1018 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
1019 || v < QUIC_MIN_ACTIVE_CONN_ID_LIMIT) {
1020 reason = TP_REASON_MALFORMED("ACTIVE_CONN_ID_LIMIT");
1024 ch->rx_active_conn_id_limit = v;
1025 got_active_conn_id_limit = 1;
1028 case QUIC_TPARAM_STATELESS_RESET_TOKEN:
1029 /* TODO(QUIC): Handle stateless reset tokens. */
1031 * We ignore these for now, but we must ensure a client doesn't
1034 if (ch->is_server) {
1035 reason = TP_REASON_SERVER_ONLY("STATELESS_RESET_TOKEN");
1039 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1040 if (body == NULL || len != QUIC_STATELESS_RESET_TOKEN_LEN) {
1041 reason = TP_REASON_MALFORMED("STATELESS_RESET_TOKEN");
1047 case QUIC_TPARAM_PREFERRED_ADDR:
1048 /* TODO(QUIC): Handle preferred address. */
1049 if (ch->is_server) {
1050 reason = TP_REASON_SERVER_ONLY("PREFERRED_ADDR");
1054 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id, &len);
1056 reason = TP_REASON_MALFORMED("PREFERRED_ADDR");
1062 case QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION:
1063 /* We do not currently handle migration, so nothing to do. */
1065 /* Skip over and ignore. */
1066 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id,
1075 if (!got_initial_scid) {
1076 reason = TP_REASON_REQUIRED("INITIAL_SCID");
1080 if (!ch->is_server) {
1081 if (!got_orig_dcid) {
1082 reason = TP_REASON_REQUIRED("ORIG_DCID");
1086 if (ch->doing_retry && !got_retry_scid) {
1087 reason = TP_REASON_REQUIRED("RETRY_SCID");
1092 ch->got_remote_transport_params = 1;
1094 if (got_initial_max_data || got_initial_max_stream_data_bidi_remote
1095 || got_initial_max_streams_bidi || got_initial_max_streams_uni)
1096 /* If FC credit was bumped, we may now be able to send. */
1097 ossl_quic_stream_map_update_state(&ch->qsm, ch->stream0);
1099 /* If we are a server, we now generate our own transport parameters. */
1100 if (ch->is_server && !ch_generate_transport_params(ch)) {
1101 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1109 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_TRANSPORT_PARAMETER_ERROR,
1115 * Called when we want to generate transport parameters. This is called
1116 * immediately at instantiation time for a client and after we receive the
1117 * client's transport parameters for a server.
1119 static int ch_generate_transport_params(QUIC_CHANNEL *ch)
1122 BUF_MEM *buf_mem = NULL;
1127 if (ch->local_transport_params != NULL)
1130 if ((buf_mem = BUF_MEM_new()) == NULL)
1133 if (!WPACKET_init(&wpkt, buf_mem))
1138 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION,
1142 if (ch->is_server) {
1143 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_ORIG_DCID,
1147 if (!ossl_quic_wire_encode_transport_param_cid(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1148 &ch->cur_local_dcid))
1151 /* Client always uses an empty SCID. */
1152 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_INITIAL_SCID,
1157 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_IDLE_TIMEOUT,
1158 ch->max_idle_timeout))
1161 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE,
1162 QUIC_MIN_INITIAL_DGRAM_LEN))
1165 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT,
1169 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_DATA,
1170 ossl_quic_rxfc_get_cwm(&ch->conn_rxfc)))
1173 /* Send the default CWM for a new RXFC. */
1174 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
1175 ch->tx_init_max_stream_data_bidi_local))
1178 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
1179 ch->tx_init_max_stream_data_bidi_remote))
1182 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI,
1183 ch->tx_init_max_stream_data_uni))
1186 /* TODO(QUIC): MAX_STREAMS modelling */
1187 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI,
1188 ch->is_server ? 100 : 100))
1191 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI,
1195 if (!WPACKET_get_total_written(&wpkt, &buf_len))
1198 ch->local_transport_params = (unsigned char *)buf_mem->data;
1199 buf_mem->data = NULL;
1201 if (!WPACKET_finish(&wpkt))
1206 if (!ossl_quic_tls_set_transport_params(ch->qtls, ch->local_transport_params,
1213 WPACKET_cleanup(&wpkt);
1214 BUF_MEM_free(buf_mem);
1219 * QUIC Channel: Ticker-Mutator
1220 * ============================
1224 * The central ticker function called by the reactor. This does everything, or
1225 * at least everything network I/O related. Best effort - not allowed to fail
1228 static void ch_tick(QUIC_TICK_RESULT *res, void *arg, uint32_t flags)
1230 OSSL_TIME now, deadline;
1231 QUIC_CHANNEL *ch = arg;
1232 int channel_only = (flags & QUIC_REACTOR_TICK_FLAG_CHANNEL_ONLY) != 0;
1235 * When we tick the QUIC connection, we do everything we need to do
1236 * periodically. In order, we:
1238 * - handle any incoming data from the network;
1239 * - handle any timer events which are due to fire (ACKM, etc.)
1240 * - write any data to the network due to be sent, to the extent
1242 * - determine the time at which we should next be ticked.
1245 /* If we are in the TERMINATED state, there is nothing to do. */
1246 if (ossl_quic_channel_is_terminated(ch)) {
1247 res->net_read_desired = 0;
1248 res->net_write_desired = 0;
1249 res->tick_deadline = ossl_time_infinite();
1254 * If we are in the TERMINATING state, check if the terminating timer has
1257 if (ossl_quic_channel_is_terminating(ch)) {
1260 if (ossl_time_compare(now, ch->terminate_deadline) >= 0) {
1261 ch_on_terminating_timeout(ch);
1262 res->net_read_desired = 0;
1263 res->net_write_desired = 0;
1264 res->tick_deadline = ossl_time_infinite();
1265 return; /* abort normal processing, nothing to do */
1269 /* Handle any incoming data from network. */
1273 /* Process queued incoming packets. */
1277 * Allow the handshake layer to check for any new incoming data and generate
1278 * new outgoing data.
1280 ch->have_new_rx_secret = 0;
1282 ossl_quic_tls_tick(ch->qtls);
1285 * If the handshake layer gave us a new secret, we need to do RX again
1286 * because packets that were not previously processable and were
1287 * deferred might now be processable.
1289 * TODO(QUIC): Consider handling this in the yield_secret callback.
1291 } while (ch->have_new_rx_secret);
1294 * Handle any timer events which are due to fire; namely, the loss detection
1295 * deadline and the idle timeout.
1297 * ACKM ACK generation deadline is polled by TXP, so we don't need to handle
1301 if (ossl_time_compare(now, ch->idle_deadline) >= 0) {
1303 * Idle timeout differs from normal protocol violation because we do not
1304 * send a CONN_CLOSE frame; go straight to TERMINATED.
1306 ch_on_idle_timeout(ch);
1307 res->net_read_desired = 0;
1308 res->net_write_desired = 0;
1309 res->tick_deadline = ossl_time_infinite();
1313 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1314 if (!ossl_time_is_zero(deadline) && ossl_time_compare(now, deadline) >= 0)
1315 ossl_ackm_on_timeout(ch->ackm);
1317 /* If a ping is due, inform TXP. */
1318 if (ossl_time_compare(now, ch->ping_deadline) >= 0) {
1319 int pn_space = ossl_quic_enc_level_to_pn_space(ch->tx_enc_level);
1321 ossl_quic_tx_packetiser_schedule_ack_eliciting(ch->txp, pn_space);
1324 /* Write any data to the network due to be sent. */
1327 /* Determine the time at which we should next be ticked. */
1328 res->tick_deadline = ch_determine_next_tick_deadline(ch);
1331 * Always process network input unless we are now terminated.
1332 * Although we had not terminated at the beginning of this tick, network
1333 * errors in ch_rx_pre() or ch_tx() may have caused us to transition to the
1336 res->net_read_desired = !ossl_quic_channel_is_terminated(ch);
1338 /* We want to write to the network if we have any in our queue. */
1339 res->net_write_desired
1340 = (!ossl_quic_channel_is_terminated(ch)
1341 && ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0);
1344 /* Process incoming datagrams, if any. */
1345 static void ch_rx_pre(QUIC_CHANNEL *ch)
1349 if (!ch->is_server && !ch->have_sent_any_pkt)
1353 * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams
1354 * to the appropriate QRX instance.
1356 ret = ossl_quic_demux_pump(ch->demux);
1357 if (ret == QUIC_DEMUX_PUMP_RES_PERMANENT_FAIL)
1359 * We don't care about transient failure, but permanent failure means we
1360 * should tear down the connection as though a protocol violation
1361 * occurred. Skip straight to the Terminating state as there is no point
1362 * trying to send CONNECTION_CLOSE frames if the network BIO is not
1363 * operating correctly.
1365 ch_raise_net_error(ch);
1368 /* Process queued incoming packets and handle frames, if any. */
1369 static int ch_rx(QUIC_CHANNEL *ch)
1371 int handled_any = 0;
1373 if (!ch->is_server && !ch->have_sent_any_pkt)
1375 * We have not sent anything yet, therefore there is no need to check
1376 * for incoming data.
1381 assert(ch->qrx_pkt == NULL);
1383 if (!ossl_qrx_read_pkt(ch->qrx, &ch->qrx_pkt))
1389 ch_rx_handle_packet(ch); /* best effort */
1392 * Regardless of the outcome of frame handling, unref the packet.
1393 * This will free the packet unless something added another
1394 * reference to it during frame processing.
1396 ossl_qrx_pkt_release(ch->qrx_pkt);
1399 ch->have_sent_ack_eliciting_since_rx = 0;
1404 * When in TERMINATING - CLOSING, generate a CONN_CLOSE frame whenever we
1405 * process one or more incoming packets.
1407 if (handled_any && ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING)
1408 ch->conn_close_queued = 1;
1413 /* Handles the packet currently in ch->qrx_pkt->hdr. */
1414 static void ch_rx_handle_packet(QUIC_CHANNEL *ch)
1418 assert(ch->qrx_pkt != NULL);
1420 if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)) {
1421 if (!ch->have_received_enc_pkt) {
1422 ch->init_scid = ch->qrx_pkt->hdr->src_conn_id;
1423 ch->have_received_enc_pkt = 1;
1426 * We change to using the SCID in the first Initial packet as the
1429 ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->init_scid);
1432 enc_level = ossl_quic_pkt_type_to_enc_level(ch->qrx_pkt->hdr->type);
1433 if ((ch->el_discarded & (1U << enc_level)) != 0)
1434 /* Do not process packets from ELs we have already discarded. */
1438 /* Handle incoming packet. */
1439 switch (ch->qrx_pkt->hdr->type) {
1440 case QUIC_PKT_TYPE_RETRY:
1441 if (ch->doing_retry || ch->is_server)
1443 * It is not allowed to ask a client to do a retry more than
1444 * once. Clients may not send retries.
1448 if (ch->qrx_pkt->hdr->len <= QUIC_RETRY_INTEGRITY_TAG_LEN)
1449 /* Packets with zero-length Retry Tokens are invalid. */
1453 * TODO(QUIC): Theoretically this should probably be in the QRX.
1454 * However because validation is dependent on context (namely the
1455 * client's initial DCID) we can't do this cleanly. In the future we
1456 * should probably add a callback to the QRX to let it call us (via
1457 * the DEMUX) and ask us about the correct original DCID, rather
1458 * than allow the QRX to emit a potentially malformed packet to the
1459 * upper layers. However, special casing this will do for now.
1461 if (!ossl_quic_validate_retry_integrity_tag(ch->libctx,
1465 /* Malformed retry packet, ignore. */
1468 ch_retry(ch, ch->qrx_pkt->hdr->data,
1469 ch->qrx_pkt->hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN,
1470 &ch->qrx_pkt->hdr->src_conn_id);
1473 case QUIC_PKT_TYPE_0RTT:
1475 /* Clients should never receive 0-RTT packets. */
1479 * TODO(QUIC): Implement 0-RTT on the server side. We currently do
1480 * not need to implement this as a client can only do 0-RTT if we
1481 * have given it permission to in a previous session.
1485 case QUIC_PKT_TYPE_INITIAL:
1486 case QUIC_PKT_TYPE_HANDSHAKE:
1487 case QUIC_PKT_TYPE_1RTT:
1488 if (ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE)
1490 * We automatically drop INITIAL EL keys when first successfully
1491 * decrypting a HANDSHAKE packet, as per the RFC.
1493 ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
1495 /* This packet contains frames, pass to the RXDP. */
1496 ossl_quic_handle_frames(ch, ch->qrx_pkt); /* best effort */
1506 * This is called by the demux when we get a packet not destined for any known
1509 static void ch_default_packet_handler(QUIC_URXE *e, void *arg)
1511 QUIC_CHANNEL *ch = arg;
1515 if (!ossl_assert(ch->is_server))
1519 * We only support one connection to our server currently, so if we already
1520 * started one, ignore any new connection attempts.
1522 if (ch->state != QUIC_CHANNEL_STATE_IDLE)
1526 * We have got a packet for an unknown DCID. This might be an attempt to
1527 * open a new connection.
1529 if (e->data_len < QUIC_MIN_INITIAL_DGRAM_LEN)
1532 if (!PACKET_buf_init(&pkt, ossl_quic_urxe_data(e), e->data_len))
1536 * We set short_conn_id_len to SIZE_MAX here which will cause the decode
1537 * operation to fail if we get a 1-RTT packet. This is fine since we only
1538 * care about Initial packets.
1540 if (!ossl_quic_wire_decode_pkt_hdr(&pkt, SIZE_MAX, 1, &hdr, NULL))
1543 switch (hdr.version) {
1544 case QUIC_VERSION_1:
1547 case QUIC_VERSION_NONE:
1549 /* Unknown version or proactive version negotiation request, bail. */
1550 /* TODO(QUIC): Handle version negotiation on server side */
1555 * We only care about Initial packets which might be trying to establish a
1558 if (hdr.type != QUIC_PKT_TYPE_INITIAL)
1562 * Assume this is a valid attempt to initiate a connection.
1564 * We do not register the DCID in the initial packet we received and that
1565 * DCID is not actually used again, thus after provisioning the correct
1566 * Initial keys derived from it (which is done in the call below) we pass
1567 * the received packet directly to the QRX so that it can process it as a
1568 * one-time thing, instead of going through the usual DEMUX DCID-based
1571 if (!ch_server_on_new_conn(ch, &e->peer,
1576 ossl_qrx_inject_urxe(ch->qrx, e);
1580 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1583 ossl_quic_demux_release_urxe(ch->demux, e);
1586 /* Try to generate packets and if possible, flush them to the network. */
1587 static int ch_tx(QUIC_CHANNEL *ch)
1589 int sent_ack_eliciting = 0;
1591 if (ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING) {
1593 * While closing, only send CONN_CLOSE if we've received more traffic
1594 * from the peer. Once we tell the TXP to generate CONN_CLOSE, all
1595 * future calls to it generate CONN_CLOSE frames, so otherwise we would
1596 * just constantly generate CONN_CLOSE frames.
1598 if (!ch->conn_close_queued)
1601 ch->conn_close_queued = 0;
1605 * Send a packet, if we need to. Best effort. The TXP consults the CC and
1606 * applies any limitations imposed by it, so we don't need to do it here.
1608 * Best effort. In particular if TXP fails for some reason we should still
1609 * flush any queued packets which we already generated.
1611 switch (ossl_quic_tx_packetiser_generate(ch->txp,
1612 TX_PACKETISER_ARCHETYPE_NORMAL,
1613 &sent_ack_eliciting)) {
1614 case TX_PACKETISER_RES_SENT_PKT:
1615 ch->have_sent_any_pkt = 1; /* Packet was sent */
1618 * RFC 9000 s. 10.1. 'An endpoint also restarts its idle timer when
1619 * sending an ack-eliciting packet if no other ack-eliciting packets
1620 * have been sent since last receiving and processing a packet.'
1622 if (sent_ack_eliciting && !ch->have_sent_ack_eliciting_since_rx) {
1624 ch->have_sent_ack_eliciting_since_rx = 1;
1627 ch_update_ping_deadline(ch);
1630 case TX_PACKETISER_RES_NO_PKT:
1631 break; /* No packet was sent */
1633 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
1635 break; /* Internal failure (e.g. allocation, assertion) */
1638 /* Flush packets to network. */
1639 switch (ossl_qtx_flush_net(ch->qtx)) {
1640 case QTX_FLUSH_NET_RES_OK:
1641 case QTX_FLUSH_NET_RES_TRANSIENT_FAIL:
1642 /* Best effort, done for now. */
1645 case QTX_FLUSH_NET_RES_PERMANENT_FAIL:
1647 /* Permanent underlying network BIO, start terminating. */
1648 ch_raise_net_error(ch);
1655 /* Determine next tick deadline. */
1656 static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch)
1661 if (ossl_quic_channel_is_terminated(ch))
1662 return ossl_time_infinite();
1664 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1665 if (ossl_time_is_zero(deadline))
1666 deadline = ossl_time_infinite();
1668 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space)
1669 deadline = ossl_time_min(deadline,
1670 ossl_ackm_get_ack_deadline(ch->ackm, pn_space));
1672 /* When will CC let us send more? */
1673 if (ossl_quic_tx_packetiser_has_pending(ch->txp, TX_PACKETISER_ARCHETYPE_NORMAL,
1674 TX_PACKETISER_BYPASS_CC))
1675 deadline = ossl_time_min(deadline,
1676 ch->cc_method->get_wakeup_deadline(ch->cc_data));
1678 /* Is the terminating timer armed? */
1679 if (ossl_quic_channel_is_terminating(ch))
1680 deadline = ossl_time_min(deadline,
1681 ch->terminate_deadline);
1682 else if (!ossl_time_is_infinite(ch->idle_deadline))
1683 deadline = ossl_time_min(deadline,
1687 * When do we need to send an ACK-eliciting packet to reset the idle
1688 * deadline timer for the peer?
1690 if (!ossl_time_is_infinite(ch->ping_deadline))
1691 deadline = ossl_time_min(deadline,
1698 * QUIC Channel: Network BIO Configuration
1699 * =======================================
1702 /* Determines whether we can support a given poll descriptor. */
1703 static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)
1705 if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0)
1711 BIO *ossl_quic_channel_get_net_rbio(QUIC_CHANNEL *ch)
1713 return ch->net_rbio;
1716 BIO *ossl_quic_channel_get_net_wbio(QUIC_CHANNEL *ch)
1718 return ch->net_wbio;
1722 * QUIC_CHANNEL does not ref any BIO it is provided with, nor is any ref
1723 * transferred to it. The caller (i.e., QUIC_CONNECTION) is responsible for
1724 * ensuring the BIO lasts until the channel is freed or the BIO is switched out
1725 * for another BIO by a subsequent successful call to this function.
1727 int ossl_quic_channel_set_net_rbio(QUIC_CHANNEL *ch, BIO *net_rbio)
1729 BIO_POLL_DESCRIPTOR d = {0};
1731 if (ch->net_rbio == net_rbio)
1734 if (net_rbio != NULL) {
1735 if (!BIO_get_rpoll_descriptor(net_rbio, &d))
1736 /* Non-pollable BIO */
1737 d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
1739 if (!validate_poll_descriptor(&d))
1743 ossl_quic_reactor_set_poll_r(&ch->rtor, &d);
1744 ossl_quic_demux_set_bio(ch->demux, net_rbio);
1745 ch->net_rbio = net_rbio;
1749 int ossl_quic_channel_set_net_wbio(QUIC_CHANNEL *ch, BIO *net_wbio)
1751 BIO_POLL_DESCRIPTOR d = {0};
1753 if (ch->net_wbio == net_wbio)
1756 if (net_wbio != NULL) {
1757 if (!BIO_get_wpoll_descriptor(net_wbio, &d))
1758 /* Non-pollable BIO */
1759 d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
1761 if (!validate_poll_descriptor(&d))
1765 ossl_quic_reactor_set_poll_w(&ch->rtor, &d);
1766 ossl_qtx_set_bio(ch->qtx, net_wbio);
1767 ch->net_wbio = net_wbio;
1772 * QUIC Channel: Lifecycle Events
1773 * ==============================
1775 int ossl_quic_channel_start(QUIC_CHANNEL *ch)
1779 * This is not used by the server. The server moves to active
1780 * automatically on receiving an incoming connection.
1784 if (ch->state != QUIC_CHANNEL_STATE_IDLE)
1785 /* Calls to connect are idempotent */
1788 /* Inform QTX of peer address. */
1789 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
1792 /* Plug in secrets for the Initial EL. */
1793 if (!ossl_quic_provide_initial_secret(ch->libctx,
1801 ch->state = QUIC_CHANNEL_STATE_ACTIVE;
1802 ch->doing_proactive_ver_neg = 0; /* not currently supported */
1804 /* Handshake layer: start (e.g. send CH). */
1805 if (!ossl_quic_tls_tick(ch->qtls))
1808 ossl_quic_reactor_tick(&ch->rtor, 0); /* best effort */
1812 /* Start a locally initiated connection shutdown. */
1813 void ossl_quic_channel_local_close(QUIC_CHANNEL *ch, uint64_t app_error_code)
1815 QUIC_TERMINATE_CAUSE tcause = {0};
1817 if (ossl_quic_channel_is_term_any(ch))
1821 tcause.error_code = app_error_code;
1822 ch_start_terminating(ch, &tcause, 0);
1825 static void free_token(const unsigned char *buf, size_t buf_len, void *arg)
1827 OPENSSL_free((unsigned char *)buf);
1830 /* Called when a server asks us to do a retry. */
1831 static int ch_retry(QUIC_CHANNEL *ch,
1832 const unsigned char *retry_token,
1833 size_t retry_token_len,
1834 const QUIC_CONN_ID *retry_scid)
1838 /* We change to using the SCID in the Retry packet as the DCID. */
1839 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, retry_scid))
1843 * Now we retry. We will release the Retry packet immediately, so copy
1846 if ((buf = OPENSSL_memdup(retry_token, retry_token_len)) == NULL)
1849 ossl_quic_tx_packetiser_set_initial_token(ch->txp, buf, retry_token_len,
1852 ch->retry_scid = *retry_scid;
1853 ch->doing_retry = 1;
1856 * We need to stimulate the Initial EL to generate the first CRYPTO frame
1857 * again. We can do this most cleanly by simply forcing the ACKM to consider
1858 * the first Initial packet as lost, which it effectively was as the server
1859 * hasn't processed it. This also maintains the desired behaviour with e.g.
1860 * PNs not resetting and so on.
1862 * The PN we used initially is always zero, because QUIC does not allow
1865 if (!ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL,
1870 * Plug in new secrets for the Initial EL. This is the only time we change
1871 * the secrets for an EL after we already provisioned it.
1873 if (!ossl_quic_provide_initial_secret(ch->libctx,
1883 /* Called when an EL is to be discarded. */
1884 static int ch_discard_el(QUIC_CHANNEL *ch,
1887 if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_1RTT))
1890 if ((ch->el_discarded & (1U << enc_level)) != 0)
1894 /* Best effort for all of these. */
1895 ossl_quic_tx_packetiser_discard_enc_level(ch->txp, enc_level);
1896 ossl_qrx_discard_enc_level(ch->qrx, enc_level);
1897 ossl_qtx_discard_enc_level(ch->qtx, enc_level);
1899 if (enc_level != QUIC_ENC_LEVEL_0RTT) {
1900 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
1902 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
1904 /* We should still have crypto streams at this point. */
1905 if (!ossl_assert(ch->crypto_send[pn_space] != NULL)
1906 || !ossl_assert(ch->crypto_recv[pn_space] != NULL))
1909 /* Get rid of the crypto stream state for the EL. */
1910 ossl_quic_sstream_free(ch->crypto_send[pn_space]);
1911 ch->crypto_send[pn_space] = NULL;
1913 ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
1914 ch->crypto_recv[pn_space] = NULL;
1917 ch->el_discarded |= (1U << enc_level);
1921 /* Intended to be called by the RXDP. */
1922 int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch)
1924 if (ch->handshake_confirmed)
1927 if (!ch->handshake_complete) {
1929 * Does not make sense for handshake to be confirmed before it is
1932 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
1933 OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE,
1934 "handshake cannot be confirmed "
1935 "before it is completed");
1939 ch_discard_el(ch, QUIC_ENC_LEVEL_HANDSHAKE);
1940 ch->handshake_confirmed = 1;
1945 * Master function used when we want to start tearing down a connection:
1947 * - If the connection is still IDLE we can go straight to TERMINATED;
1949 * - If we are already TERMINATED this is a no-op.
1951 * - If we are TERMINATING - CLOSING and we have now got a CONNECTION_CLOSE
1952 * from the peer (tcause->remote == 1), we move to TERMINATING - DRAINING.
1954 * - If we are TERMINATING - DRAINING, we remain here until the terminating
1957 * - Otherwise, we are in ACTIVE and move to TERMINATING - CLOSING.
1958 * if we caused the termination (e.g. we have sent a CONNECTION_CLOSE). Note
1959 * that we are considered to have caused a termination if we sent the first
1960 * CONNECTION_CLOSE frame, even if it is caused by a peer protocol
1961 * violation. If the peer sent the first CONNECTION_CLOSE frame, we move to
1962 * TERMINATING - DRAINING.
1964 * We record the termination cause structure passed on the first call only.
1965 * Any successive calls have their termination cause data discarded;
1966 * once we start sending a CONNECTION_CLOSE frame, we don't change the details
1969 static void ch_start_terminating(QUIC_CHANNEL *ch,
1970 const QUIC_TERMINATE_CAUSE *tcause,
1971 int force_immediate)
1973 switch (ch->state) {
1975 case QUIC_CHANNEL_STATE_IDLE:
1976 ch->terminate_cause = *tcause;
1977 ch_on_terminating_timeout(ch);
1980 case QUIC_CHANNEL_STATE_ACTIVE:
1981 ch->terminate_cause = *tcause;
1983 if (!force_immediate) {
1984 ch->state = tcause->remote ? QUIC_CHANNEL_STATE_TERMINATING_DRAINING
1985 : QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
1986 ch->terminate_deadline
1987 = ossl_time_add(get_time(ch),
1988 ossl_time_multiply(ossl_ackm_get_pto_duration(ch->ackm),
1991 if (!tcause->remote) {
1992 OSSL_QUIC_FRAME_CONN_CLOSE f = {0};
1995 f.error_code = ch->terminate_cause.error_code;
1996 f.frame_type = ch->terminate_cause.frame_type;
1997 f.is_app = ch->terminate_cause.app;
1998 ossl_quic_tx_packetiser_schedule_conn_close(ch->txp, &f);
1999 ch->conn_close_queued = 1;
2002 ch_on_terminating_timeout(ch);
2006 case QUIC_CHANNEL_STATE_TERMINATING_CLOSING:
2007 if (force_immediate)
2008 ch_on_terminating_timeout(ch);
2009 else if (tcause->remote)
2010 ch->state = QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
2014 case QUIC_CHANNEL_STATE_TERMINATING_DRAINING:
2016 * Other than in the force-immediate case, we remain here until the
2019 if (force_immediate)
2020 ch_on_terminating_timeout(ch);
2024 case QUIC_CHANNEL_STATE_TERMINATED:
2031 void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch,
2032 OSSL_QUIC_FRAME_CONN_CLOSE *f)
2034 QUIC_TERMINATE_CAUSE tcause = {0};
2036 if (!ossl_quic_channel_is_active(ch))
2040 tcause.app = f->is_app;
2041 tcause.error_code = f->error_code;
2042 tcause.frame_type = f->frame_type;
2044 ch_start_terminating(ch, &tcause, 0);
2047 static void ch_raise_net_error(QUIC_CHANNEL *ch)
2049 QUIC_TERMINATE_CAUSE tcause = {0};
2051 tcause.error_code = QUIC_ERR_INTERNAL_ERROR;
2054 * Skip Terminating state and go directly to Terminated, no point trying to
2055 * send CONNECTION_CLOSE if we cannot communicate.
2057 ch_start_terminating(ch, &tcause, 1);
2060 void ossl_quic_channel_raise_protocol_error(QUIC_CHANNEL *ch,
2061 uint64_t error_code,
2062 uint64_t frame_type,
2065 QUIC_TERMINATE_CAUSE tcause = {0};
2067 tcause.error_code = error_code;
2068 tcause.frame_type = frame_type;
2070 ch_start_terminating(ch, &tcause, 0);
2074 * Called once the terminating timer expires, meaning we move from TERMINATING
2077 static void ch_on_terminating_timeout(QUIC_CHANNEL *ch)
2079 ch->state = QUIC_CHANNEL_STATE_TERMINATED;
2083 * Updates our idle deadline. Called when an event happens which should bump the
2086 static void ch_update_idle(QUIC_CHANNEL *ch)
2088 if (ch->max_idle_timeout == 0)
2089 ch->idle_deadline = ossl_time_infinite();
2091 ch->idle_deadline = ossl_time_add(get_time(ch),
2092 ossl_ms2time(ch->max_idle_timeout));
2096 * Updates our ping deadline, which determines when we next generate a ping if
2097 * we don't have any other ACK-eliciting frames to send.
2099 static void ch_update_ping_deadline(QUIC_CHANNEL *ch)
2101 if (ch->max_idle_timeout > 0) {
2103 * Maximum amount of time without traffic before we send a PING to keep
2104 * the connection open. Usually we use max_idle_timeout/2, but ensure
2105 * the period never exceeds the assumed NAT interval to ensure NAT
2106 * devices don't have their state time out (RFC 9000 s. 10.1.2).
2109 = ossl_time_divide(ossl_ms2time(ch->max_idle_timeout), 2);
2111 max_span = ossl_time_min(max_span, MAX_NAT_INTERVAL);
2113 ch->ping_deadline = ossl_time_add(get_time(ch), max_span);
2115 ch->ping_deadline = ossl_time_infinite();
2119 /* Called when the idle timeout expires. */
2120 static void ch_on_idle_timeout(QUIC_CHANNEL *ch)
2123 * Idle timeout does not have an error code associated with it because a
2124 * CONN_CLOSE is never sent for it. We shouldn't use this data once we reach
2125 * TERMINATED anyway.
2127 ch->terminate_cause.app = 0;
2128 ch->terminate_cause.error_code = UINT64_MAX;
2129 ch->terminate_cause.frame_type = 0;
2131 ch->state = QUIC_CHANNEL_STATE_TERMINATED;
2134 /* Called when we, as a server, get a new incoming connection. */
2135 static int ch_server_on_new_conn(QUIC_CHANNEL *ch, const BIO_ADDR *peer,
2136 const QUIC_CONN_ID *peer_scid,
2137 const QUIC_CONN_ID *peer_dcid)
2139 if (!ossl_assert(ch->state == QUIC_CHANNEL_STATE_IDLE && ch->is_server))
2142 /* Generate a SCID we will use for the connection. */
2143 if (!gen_rand_conn_id(ch->libctx, INIT_DCID_LEN,
2144 &ch->cur_local_dcid))
2147 /* Note our newly learnt peer address and CIDs. */
2148 ch->cur_peer_addr = *peer;
2149 ch->init_dcid = *peer_dcid;
2150 ch->cur_remote_dcid = *peer_scid;
2152 /* Inform QTX of peer address. */
2153 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
2156 /* Inform TXP of desired CIDs. */
2157 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->cur_remote_dcid))
2160 if (!ossl_quic_tx_packetiser_set_cur_scid(ch->txp, &ch->cur_local_dcid))
2163 /* Plug in secrets for the Initial EL. */
2164 if (!ossl_quic_provide_initial_secret(ch->libctx,
2171 /* Register our local DCID in the DEMUX. */
2172 if (!ossl_qrx_add_dst_conn_id(ch->qrx, &ch->cur_local_dcid))
2176 ch->state = QUIC_CHANNEL_STATE_ACTIVE;
2177 ch->doing_proactive_ver_neg = 0; /* not currently supported */
2181 SSL *ossl_quic_channel_get0_ssl(QUIC_CHANNEL *ch)