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_txp.h"
11 #include "internal/quic_fifd.h"
12 #include "internal/quic_stream_map.h"
13 #include "internal/common.h"
14 #include <openssl/err.h>
16 #define MIN_CRYPTO_HDR_SIZE 3
18 #define MIN_FRAME_SIZE_HANDSHAKE_DONE 1
19 #define MIN_FRAME_SIZE_MAX_DATA 2
20 #define MIN_FRAME_SIZE_ACK 5
21 #define MIN_FRAME_SIZE_CRYPTO (MIN_CRYPTO_HDR_SIZE + 1)
22 #define MIN_FRAME_SIZE_STREAM 3 /* minimum useful size (for non-FIN) */
23 #define MIN_FRAME_SIZE_MAX_STREAMS_BIDI 2
24 #define MIN_FRAME_SIZE_MAX_STREAMS_UNI 2
26 struct ossl_quic_tx_packetiser_st {
27 OSSL_QUIC_TX_PACKETISER_ARGS args;
30 * Opaque initial token blob provided by caller. TXP frees using the
31 * callback when it is no longer needed.
33 const unsigned char *initial_token;
34 size_t initial_token_len;
35 ossl_quic_initial_token_free_fn *initial_token_free_cb;
36 void *initial_token_free_cb_arg;
38 /* Subcomponents of the TXP that we own. */
39 QUIC_FIFD fifd; /* QUIC Frame-in-Flight Dispatcher */
42 uint64_t next_pn[QUIC_PN_SPACE_NUM]; /* Next PN to use in given PN space. */
43 OSSL_TIME last_tx_time; /* Last time a packet was generated, or 0. */
45 /* Internal state - frame (re)generation flags. */
46 unsigned int want_handshake_done : 1;
47 unsigned int want_max_data : 1;
48 unsigned int want_max_streams_bidi : 1;
49 unsigned int want_max_streams_uni : 1;
51 /* Internal state - frame (re)generation flags - per PN space. */
52 unsigned int want_ack : QUIC_PN_SPACE_NUM;
53 unsigned int force_ack_eliciting : QUIC_PN_SPACE_NUM;
56 * Internal state - connection close terminal state.
57 * Once this is set, it is not unset unlike other want_ flags - we keep
58 * sending it in every packet.
60 unsigned int want_conn_close : 1;
62 /* Has the handshake been completed? */
63 unsigned int handshake_complete : 1;
65 OSSL_QUIC_FRAME_CONN_CLOSE conn_close_frame;
67 /* Internal state - packet assembly. */
68 unsigned char *scratch; /* scratch buffer for packet assembly */
69 size_t scratch_len; /* number of bytes allocated for scratch */
70 OSSL_QTX_IOVEC *iovec; /* scratch iovec array for use with QTX */
71 size_t alloc_iovec; /* size of iovec array */
75 * The TX helper records state used while generating frames into packets. It
76 * enables serialization into the packet to be done "transactionally" where
77 * serialization of a frame can be rolled back if it fails midway (e.g. if it
81 OSSL_QUIC_TX_PACKETISER *txp;
83 * The Maximum Packet Payload Length in bytes. This is the amount of
84 * space we have to generate frames into.
88 * Number of bytes we have generated so far.
90 size_t bytes_appended;
92 * Number of scratch bytes in txp->scratch we have used so far. Some iovecs
93 * will reference this scratch buffer. When we need to use more of it (e.g.
94 * when we need to put frame headers somewhere), we append to the scratch
95 * buffer, resizing if necessary, and increase this accordingly.
99 * Bytes reserved in the MaxPPL budget. We keep this number of bytes spare
100 * until reserve_allowed is set to 1. Currently this is always at most 1, as
101 * a PING frame takes up one byte and this mechanism is only used to ensure
102 * we can encode a PING frame if we have been asked to ensure a packet is
103 * ACK-eliciting and we are unusure if we are going to add any other
104 * ACK-eliciting frames before we reach our MaxPPL budget.
108 * Number of iovecs we have currently appended. This is the number of
109 * entries valid in txp->iovec.
113 * Whether we are allowed to make use of the reserve bytes in our MaxPPL
114 * budget. This is used to ensure we have room to append a PING frame later
115 * if we need to. Once we know we will not need to append a PING frame, this
118 unsigned int reserve_allowed : 1;
120 * Set to 1 if we have appended a STREAM frame with an implicit length. If
121 * this happens we should never append another frame after that frame as it
122 * cannot be validly encoded. This is just a safety check.
124 unsigned int done_implicit : 1;
127 * The fields in this structure are valid if active is set, which means
128 * that a serialization transaction is currently in progress.
132 unsigned int active : 1;
136 static void tx_helper_rollback(struct tx_helper *h);
137 static int txp_ensure_iovec(OSSL_QUIC_TX_PACKETISER *txp, size_t num);
139 /* Initialises the TX helper. */
140 static int tx_helper_init(struct tx_helper *h, OSSL_QUIC_TX_PACKETISER *txp,
141 size_t max_ppl, size_t reserve)
143 if (reserve > max_ppl)
147 h->max_ppl = max_ppl;
148 h->reserve = reserve;
150 h->bytes_appended = 0;
151 h->scratch_bytes = 0;
152 h->reserve_allowed = 0;
153 h->done_implicit = 0;
157 if (max_ppl > h->txp->scratch_len) {
158 unsigned char *scratch;
160 scratch = OPENSSL_realloc(h->txp->scratch, max_ppl);
164 h->txp->scratch = scratch;
165 h->txp->scratch_len = max_ppl;
171 static void tx_helper_cleanup(struct tx_helper *h)
174 tx_helper_rollback(h);
179 static void tx_helper_unrestrict(struct tx_helper *h)
181 h->reserve_allowed = 1;
185 * Append an extent of memory to the iovec list. The memory must remain
186 * allocated until we finish generating the packet and call the QTX.
188 * In general, the buffers passed to this function will be from one of two
191 * - Application data contained in stream buffers managed elsewhere
192 * in the QUIC stack; or
194 * - Control frame data appended into txp->scratch using tx_helper_begin and
198 static int tx_helper_append_iovec(struct tx_helper *h,
199 const unsigned char *buf,
205 if (!ossl_assert(!h->done_implicit))
208 if (!txp_ensure_iovec(h->txp, h->num_iovec + 1))
211 h->txp->iovec[h->num_iovec].buf = buf;
212 h->txp->iovec[h->num_iovec].buf_len = buf_len;
215 h->bytes_appended += buf_len;
220 * How many more bytes of space do we have left in our plaintext packet payload?
222 static size_t tx_helper_get_space_left(struct tx_helper *h)
225 - (h->reserve_allowed ? 0 : h->reserve) - h->bytes_appended;
229 * Begin a control frame serialization transaction. This allows the
230 * serialization of the control frame to be backed out if it turns out it won't
231 * fit. Write the control frame to the returned WPACKET. Ensure you always
232 * call tx_helper_rollback or tx_helper_commit (or tx_helper_cleanup). Returns
235 static WPACKET *tx_helper_begin(struct tx_helper *h)
237 size_t space_left, len;
240 if (!ossl_assert(!h->txn.active))
243 if (!ossl_assert(!h->done_implicit))
246 data = (unsigned char *)h->txp->scratch + h->scratch_bytes;
247 len = h->txp->scratch_len - h->scratch_bytes;
249 space_left = tx_helper_get_space_left(h);
250 if (!ossl_assert(space_left <= len))
253 if (!WPACKET_init_static_len(&h->txn.wpkt, data, len, 0))
256 if (!WPACKET_set_max_size(&h->txn.wpkt, space_left)) {
257 WPACKET_cleanup(&h->txn.wpkt);
266 static void tx_helper_end(struct tx_helper *h, int success)
269 WPACKET_finish(&h->txn.wpkt);
271 WPACKET_cleanup(&h->txn.wpkt);
277 /* Abort a control frame serialization transaction. */
278 static void tx_helper_rollback(struct tx_helper *h)
286 /* Commit a control frame. */
287 static int tx_helper_commit(struct tx_helper *h)
294 if (!WPACKET_get_total_written(&h->txn.wpkt, &l)) {
299 if (!tx_helper_append_iovec(h, h->txn.data, l)) {
304 h->scratch_bytes += l;
309 static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space,
311 static void on_regen_notify(uint64_t frame_type, uint64_t stream_id,
312 QUIC_TXPIM_PKT *pkt, void *arg);
313 static int sstream_is_pending(QUIC_SSTREAM *sstream);
314 static int txp_el_pending(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level,
316 uint32_t *conn_close_enc_level);
317 static int txp_generate_for_el(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level,
319 char is_last_in_dgram,
320 char dgram_contains_initial,
321 char chosen_for_conn_close);
322 static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp);
323 static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp,
328 static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp);
329 static int txp_generate_for_el_actual(OSSL_QUIC_TX_PACKETISER *txp,
336 char chosen_for_conn_close);
338 OSSL_QUIC_TX_PACKETISER *ossl_quic_tx_packetiser_new(const OSSL_QUIC_TX_PACKETISER_ARGS *args)
340 OSSL_QUIC_TX_PACKETISER *txp;
344 || args->txpim == NULL
346 || args->ackm == NULL
348 || args->conn_txfc == NULL
349 || args->conn_rxfc == NULL) {
350 ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
354 txp = OPENSSL_zalloc(sizeof(*txp));
359 txp->last_tx_time = ossl_time_zero();
361 if (!ossl_quic_fifd_init(&txp->fifd,
362 txp->args.cfq, txp->args.ackm, txp->args.txpim,
363 get_sstream_by_id, txp,
364 on_regen_notify, txp)) {
372 void ossl_quic_tx_packetiser_free(OSSL_QUIC_TX_PACKETISER *txp)
377 ossl_quic_tx_packetiser_set_initial_token(txp, NULL, 0, NULL, NULL);
378 ossl_quic_fifd_cleanup(&txp->fifd);
379 OPENSSL_free(txp->iovec);
380 OPENSSL_free(txp->conn_close_frame.reason);
381 OPENSSL_free(txp->scratch);
385 void ossl_quic_tx_packetiser_set_initial_token(OSSL_QUIC_TX_PACKETISER *txp,
386 const unsigned char *token,
388 ossl_quic_initial_token_free_fn *free_cb,
391 if (txp->initial_token != NULL && txp->initial_token_free_cb != NULL)
392 txp->initial_token_free_cb(txp->initial_token, txp->initial_token_len,
393 txp->initial_token_free_cb_arg);
395 txp->initial_token = token;
396 txp->initial_token_len = token_len;
397 txp->initial_token_free_cb = free_cb;
398 txp->initial_token_free_cb_arg = free_cb_arg;
401 int ossl_quic_tx_packetiser_set_cur_dcid(OSSL_QUIC_TX_PACKETISER *txp,
402 const QUIC_CONN_ID *dcid)
405 ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
409 txp->args.cur_dcid = *dcid;
413 int ossl_quic_tx_packetiser_set_cur_scid(OSSL_QUIC_TX_PACKETISER *txp,
414 const QUIC_CONN_ID *scid)
417 ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
421 txp->args.cur_scid = *scid;
425 /* Change the destination L4 address the TXP uses to send datagrams. */
426 int ossl_quic_tx_packetiser_set_peer(OSSL_QUIC_TX_PACKETISER *txp,
427 const BIO_ADDR *peer)
430 ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
434 txp->args.peer = *peer;
438 int ossl_quic_tx_packetiser_discard_enc_level(OSSL_QUIC_TX_PACKETISER *txp,
441 if (enc_level >= QUIC_ENC_LEVEL_NUM) {
442 ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
446 if (enc_level != QUIC_ENC_LEVEL_0RTT)
447 txp->args.crypto[ossl_quic_enc_level_to_pn_space(enc_level)] = NULL;
452 void ossl_quic_tx_packetiser_notify_handshake_complete(OSSL_QUIC_TX_PACKETISER *txp)
454 txp->handshake_complete = 1;
457 void ossl_quic_tx_packetiser_schedule_handshake_done(OSSL_QUIC_TX_PACKETISER *txp)
459 txp->want_handshake_done = 1;
462 void ossl_quic_tx_packetiser_schedule_ack_eliciting(OSSL_QUIC_TX_PACKETISER *txp,
465 txp->force_ack_eliciting |= (1UL << pn_space);
468 #define TXP_ERR_INTERNAL 0 /* Internal (e.g. alloc) error */
469 #define TXP_ERR_SUCCESS 1 /* Success */
470 #define TXP_ERR_SPACE 2 /* Not enough room for another packet */
471 #define TXP_ERR_INPUT 3 /* Invalid/malformed input */
473 int ossl_quic_tx_packetiser_has_pending(OSSL_QUIC_TX_PACKETISER *txp,
477 uint32_t enc_level, conn_close_enc_level = QUIC_ENC_LEVEL_NUM;
478 int bypass_cc = ((flags & TX_PACKETISER_BYPASS_CC) != 0);
480 if (!bypass_cc && !txp->args.cc_method->can_send(txp->args.cc_data))
483 for (enc_level = QUIC_ENC_LEVEL_INITIAL;
484 enc_level < QUIC_ENC_LEVEL_NUM;
486 if (txp_el_pending(txp, enc_level, archetype, &conn_close_enc_level))
493 * Generates a datagram by polling the various ELs to determine if they want to
494 * generate any frames, and generating a datagram which coalesces packets for
497 int ossl_quic_tx_packetiser_generate(OSSL_QUIC_TX_PACKETISER *txp,
500 uint32_t enc_level, conn_close_enc_level = QUIC_ENC_LEVEL_NUM;
501 char have_pkt_for_el[QUIC_ENC_LEVEL_NUM], is_last_in_dgram;
502 size_t num_el_in_dgram = 0, pkts_done = 0;
505 if (!txp->args.cc_method->can_send(txp->args.cc_data))
506 return TX_PACKETISER_RES_NO_PKT;
508 for (enc_level = QUIC_ENC_LEVEL_INITIAL;
509 enc_level < QUIC_ENC_LEVEL_NUM;
511 have_pkt_for_el[enc_level] = txp_el_pending(txp, enc_level, archetype,
512 &conn_close_enc_level);
513 if (have_pkt_for_el[enc_level])
517 if (num_el_in_dgram == 0)
518 return TX_PACKETISER_RES_NO_PKT;
521 * Should not be needed, but a sanity check in case anyone else has been
524 ossl_qtx_finish_dgram(txp->args.qtx);
526 for (enc_level = QUIC_ENC_LEVEL_INITIAL;
527 enc_level < QUIC_ENC_LEVEL_NUM;
529 if (!have_pkt_for_el[enc_level])
532 is_last_in_dgram = (pkts_done + 1 == num_el_in_dgram);
533 rc = txp_generate_for_el(txp, enc_level, archetype, is_last_in_dgram,
534 have_pkt_for_el[QUIC_ENC_LEVEL_INITIAL],
535 enc_level == conn_close_enc_level);
537 if (rc != TXP_ERR_SUCCESS) {
539 * If we already successfully did at least one, make sure we report
540 * this via the return code.
545 return TX_PACKETISER_RES_FAILURE;
551 ossl_qtx_finish_dgram(txp->args.qtx);
552 return TX_PACKETISER_RES_SENT_PKT;
555 struct archetype_data {
556 unsigned int allow_ack : 1;
557 unsigned int allow_ping : 1;
558 unsigned int allow_crypto : 1;
559 unsigned int allow_handshake_done : 1;
560 unsigned int allow_path_challenge : 1;
561 unsigned int allow_path_response : 1;
562 unsigned int allow_new_conn_id : 1;
563 unsigned int allow_retire_conn_id : 1;
564 unsigned int allow_stream_rel : 1;
565 unsigned int allow_conn_fc : 1;
566 unsigned int allow_conn_close : 1;
567 unsigned int allow_cfq_other : 1;
568 unsigned int allow_new_token : 1;
569 unsigned int allow_force_ack_eliciting : 1;
572 static const struct archetype_data archetypes[QUIC_ENC_LEVEL_NUM][TX_PACKETISER_ARCHETYPE_NUM] = {
575 /* EL 0(INITIAL) - Archetype 0(NORMAL) */
579 /*allow_crypto =*/ 1,
580 /*allow_handshake_done =*/ 0,
581 /*allow_path_challenge =*/ 0,
582 /*allow_path_response =*/ 0,
583 /*allow_new_conn_id =*/ 0,
584 /*allow_retire_conn_id =*/ 0,
585 /*allow_stream_rel =*/ 0,
586 /*allow_conn_fc =*/ 0,
587 /*allow_conn_close =*/ 1,
588 /*allow_cfq_other =*/ 1,
589 /*allow_new_token =*/ 0,
590 /*allow_force_ack_eliciting =*/ 1,
592 /* EL 0(INITIAL) - Archetype 1(ACK_ONLY) */
596 /*allow_crypto =*/ 0,
597 /*allow_handshake_done =*/ 0,
598 /*allow_path_challenge =*/ 0,
599 /*allow_path_response =*/ 0,
600 /*allow_new_conn_id =*/ 0,
601 /*allow_retire_conn_id =*/ 0,
602 /*allow_stream_rel =*/ 0,
603 /*allow_conn_fc =*/ 0,
604 /*allow_conn_close =*/ 0,
605 /*allow_cfq_other =*/ 0,
606 /*allow_new_token =*/ 0,
607 /*allow_force_ack_eliciting =*/ 1,
610 /* EL 1(HANDSHAKE) */
612 /* EL 1(HANDSHAKE) - Archetype 0(NORMAL) */
616 /*allow_crypto =*/ 1,
617 /*allow_handshake_done =*/ 0,
618 /*allow_path_challenge =*/ 0,
619 /*allow_path_response =*/ 0,
620 /*allow_new_conn_id =*/ 0,
621 /*allow_retire_conn_id =*/ 0,
622 /*allow_stream_rel =*/ 0,
623 /*allow_conn_fc =*/ 0,
624 /*allow_conn_close =*/ 1,
625 /*allow_cfq_other =*/ 1,
626 /*allow_new_token =*/ 0,
627 /*allow_force_ack_eliciting =*/ 1,
629 /* EL 1(HANDSHAKE) - Archetype 1(ACK_ONLY) */
633 /*allow_crypto =*/ 0,
634 /*allow_handshake_done =*/ 0,
635 /*allow_path_challenge =*/ 0,
636 /*allow_path_response =*/ 0,
637 /*allow_new_conn_id =*/ 0,
638 /*allow_retire_conn_id =*/ 0,
639 /*allow_stream_rel =*/ 0,
640 /*allow_conn_fc =*/ 0,
641 /*allow_conn_close =*/ 0,
642 /*allow_cfq_other =*/ 0,
643 /*allow_new_token =*/ 0,
644 /*allow_force_ack_eliciting =*/ 1,
649 /* EL 2(0RTT) - Archetype 0(NORMAL) */
653 /*allow_crypto =*/ 0,
654 /*allow_handshake_done =*/ 0,
655 /*allow_path_challenge =*/ 0,
656 /*allow_path_response =*/ 0,
657 /*allow_new_conn_id =*/ 1,
658 /*allow_retire_conn_id =*/ 1,
659 /*allow_stream_rel =*/ 1,
660 /*allow_conn_fc =*/ 1,
661 /*allow_conn_close =*/ 1,
662 /*allow_cfq_other =*/ 0,
663 /*allow_new_token =*/ 0,
664 /*allow_force_ack_eliciting =*/ 0,
666 /* EL 2(0RTT) - Archetype 1(ACK_ONLY) */
670 /*allow_crypto =*/ 0,
671 /*allow_handshake_done =*/ 0,
672 /*allow_path_challenge =*/ 0,
673 /*allow_path_response =*/ 0,
674 /*allow_new_conn_id =*/ 0,
675 /*allow_retire_conn_id =*/ 0,
676 /*allow_stream_rel =*/ 0,
677 /*allow_conn_fc =*/ 0,
678 /*allow_conn_close =*/ 0,
679 /*allow_cfq_other =*/ 0,
680 /*allow_new_token =*/ 0,
681 /*allow_force_ack_eliciting =*/ 0,
686 /* EL 3(1RTT) - Archetype 0(NORMAL) */
690 /*allow_crypto =*/ 1,
691 /*allow_handshake_done =*/ 1,
692 /*allow_path_challenge =*/ 0,
693 /*allow_path_response =*/ 0,
694 /*allow_new_conn_id =*/ 1,
695 /*allow_retire_conn_id =*/ 1,
696 /*allow_stream_rel =*/ 1,
697 /*allow_conn_fc =*/ 1,
698 /*allow_conn_close =*/ 1,
699 /*allow_cfq_other =*/ 1,
700 /*allow_new_token =*/ 1,
701 /*allow_force_ack_eliciting =*/ 1,
703 /* EL 3(1RTT) - Archetype 1(ACK_ONLY) */
707 /*allow_crypto =*/ 0,
708 /*allow_handshake_done =*/ 0,
709 /*allow_path_challenge =*/ 0,
710 /*allow_path_response =*/ 0,
711 /*allow_new_conn_id =*/ 0,
712 /*allow_retire_conn_id =*/ 0,
713 /*allow_stream_rel =*/ 0,
714 /*allow_conn_fc =*/ 0,
715 /*allow_conn_close =*/ 0,
716 /*allow_cfq_other =*/ 0,
717 /*allow_new_token =*/ 0,
718 /*allow_force_ack_eliciting =*/ 1,
723 static int txp_get_archetype_data(uint32_t enc_level,
725 struct archetype_data *a)
727 if (enc_level >= QUIC_ENC_LEVEL_NUM
728 || archetype >= TX_PACKETISER_ARCHETYPE_NUM)
731 /* No need to avoid copying this as it should not exceed one int in size. */
732 *a = archetypes[enc_level][archetype];
737 * Returns 1 if the given EL wants to produce one or more frames.
738 * Always returns 0 if the given EL is discarded.
740 static int txp_el_pending(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level,
742 uint32_t *conn_close_enc_level)
744 struct archetype_data a;
745 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
746 QUIC_CFQ_ITEM *cfq_item;
748 if (!ossl_qtx_is_enc_level_provisioned(txp->args.qtx, enc_level))
751 if (*conn_close_enc_level > enc_level)
752 *conn_close_enc_level = enc_level;
754 if (!txp_get_archetype_data(enc_level, archetype, &a))
757 /* Does the crypto stream for this EL want to produce anything? */
758 if (a.allow_crypto && sstream_is_pending(txp->args.crypto[pn_space]))
761 /* Does the ACKM for this PN space want to produce anything? */
762 if (a.allow_ack && (ossl_ackm_is_ack_desired(txp->args.ackm, pn_space)
763 || (txp->want_ack & (1UL << pn_space)) != 0))
766 /* Do we need to force emission of an ACK-eliciting packet? */
767 if (a.allow_force_ack_eliciting
768 && (txp->force_ack_eliciting & (1UL << pn_space)) != 0)
771 /* Does the connection-level RXFC want to produce a frame? */
772 if (a.allow_conn_fc && (txp->want_max_data
773 || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0)))
776 /* Do we want to produce a MAX_STREAMS frame? */
777 if (a.allow_conn_fc && (txp->want_max_streams_bidi
778 || txp->want_max_streams_uni))
781 /* Do we want to produce a HANDSHAKE_DONE frame? */
782 if (a.allow_handshake_done && txp->want_handshake_done)
785 /* Do we want to produce a CONNECTION_CLOSE frame? */
786 if (a.allow_conn_close && txp->want_conn_close &&
787 *conn_close_enc_level == enc_level)
789 * This is a bit of a special case since CONNECTION_CLOSE can appear in
790 * most packet types, and when we decide we want to send it this status
791 * isn't tied to a specific EL. So if we want to send it, we send it
792 * only on the lowest non-dropped EL.
796 /* Does the CFQ have any frames queued for this PN space? */
797 if (enc_level != QUIC_ENC_LEVEL_0RTT)
798 for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space);
800 cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) {
801 uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item);
803 switch (frame_type) {
804 case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID:
805 if (a.allow_new_conn_id)
808 case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID:
809 if (a.allow_retire_conn_id)
812 case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN:
813 if (a.allow_new_token)
817 if (a.allow_cfq_other)
823 if (a.allow_stream_rel && txp->handshake_complete) {
826 /* If there are any active streams, 0/1-RTT wants to produce a packet.
827 * Whether a stream is on the active list is required to be precise
828 * (i.e., a stream is never on the active list if we cannot produce a
829 * frame for it), and all stream-related frames are governed by
830 * a.allow_stream_rel (i.e., if we can send one type of stream-related
831 * frame, we can send any of them), so we don't need to inspect
832 * individual streams on the active list, just confirm that the active
835 ossl_quic_stream_iter_init(&it, txp->args.qsm, 0);
836 if (it.stream != NULL)
843 static int sstream_is_pending(QUIC_SSTREAM *sstream)
845 OSSL_QUIC_FRAME_STREAM hdr;
846 OSSL_QTX_IOVEC iov[2];
847 size_t num_iov = OSSL_NELEM(iov);
849 return ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov);
853 * Generates a packet for a given EL, coalescing it into the current datagram.
855 * is_last_in_dgram and dgram_contains_initial are used to determine padding
858 * Returns TXP_ERR_* value.
860 static int txp_generate_for_el(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level,
862 char is_last_in_dgram,
863 char dgram_contains_initial,
864 char chosen_for_conn_close)
866 char must_pad = dgram_contains_initial && is_last_in_dgram;
867 size_t min_dpl, min_pl, min_ppl, cmpl, cmppl, running_total;
868 size_t mdpl, hdr_len, pkt_overhead, cc_limit;
871 OSSL_TIME time_since_last;
873 /* Determine the limit CC imposes on what we can send. */
874 if (ossl_time_is_zero(txp->last_tx_time))
875 time_since_last = ossl_time_zero();
877 time_since_last = ossl_time_subtract(txp->args.now(txp->args.now_arg),
880 cc_limit_ = txp->args.cc_method->get_send_allowance(txp->args.cc_data,
882 ossl_time_is_zero(time_since_last));
884 cc_limit = (cc_limit_ > SIZE_MAX ? SIZE_MAX : (size_t)cc_limit_);
886 /* Assemble packet header. */
887 phdr.type = ossl_quic_enc_level_to_pkt_type(enc_level);
889 phdr.pn_len = txp_determine_pn_len(txp);
892 phdr.version = QUIC_VERSION_1;
893 phdr.dst_conn_id = txp->args.cur_dcid;
894 phdr.src_conn_id = txp->args.cur_scid;
897 * We need to know the length of the payload to get an accurate header
898 * length for non-1RTT packets, because the Length field found in
899 * Initial/Handshake/0-RTT packets uses a variable-length encoding. However,
900 * we don't have a good idea of the length of our payload, because the
901 * length of the payload depends on the room in the datagram after fitting
902 * the header, which depends on the size of the header.
904 * In general, it does not matter if a packet is slightly shorter (because
905 * e.g. we predicted use of a 2-byte length field, but ended up only needing
906 * a 1-byte length field). However this does matter for Initial packets
907 * which must be at least 1200 bytes, which is also the assumed default MTU;
908 * therefore in many cases Initial packets will be padded to 1200 bytes,
909 * which means if we overestimated the header size, we will be short by a
910 * few bytes and the server will ignore the packet for being too short. In
911 * this case, however, such packets always *will* be padded to meet 1200
912 * bytes, which requires a 2-byte length field, so we don't actually need to
913 * worry about this. Thus we estimate the header length assuming a 2-byte
914 * length field here, which should in practice work well in all cases.
916 phdr.len = OSSL_QUIC_VLINT_2B_MAX - phdr.pn_len;
918 if (enc_level == QUIC_ENC_LEVEL_INITIAL) {
919 phdr.token = txp->initial_token;
920 phdr.token_len = txp->initial_token_len;
926 hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(phdr.dst_conn_id.id_len,
929 return TXP_ERR_INPUT;
931 /* MinDPL: Minimum total datagram payload length. */
932 min_dpl = must_pad ? QUIC_MIN_INITIAL_DGRAM_LEN : 0;
934 /* How much data is already in the current datagram? */
935 running_total = ossl_qtx_get_cur_dgram_len_bytes(txp->args.qtx);
937 /* MinPL: Minimum length of the fully encoded packet. */
938 min_pl = running_total < min_dpl ? min_dpl - running_total : 0;
939 if ((uint64_t)min_pl > cc_limit)
941 * Congestion control does not allow us to send a packet of adequate
944 return TXP_ERR_SPACE;
946 /* MinPPL: Minimum plaintext payload length needed to meet MinPL. */
947 if (!txp_determine_ppl_from_pl(txp, min_pl, enc_level, hdr_len, &min_ppl))
948 /* MinPL is less than a valid packet size, so just use a MinPPL of 0. */
951 /* MDPL: Maximum datagram payload length. */
952 mdpl = txp_get_mdpl(txp);
955 * CMPL: Maximum encoded packet size we can put into this datagram given any
956 * previous packets coalesced into it.
958 if (running_total > mdpl)
959 /* Should not be possible, but if it happens: */
962 cmpl = mdpl - running_total;
964 /* Clamp CMPL based on congestion control limit. */
968 /* CMPPL: Maximum amount we can put into the current datagram payload. */
969 if (!txp_determine_ppl_from_pl(txp, cmpl, enc_level, hdr_len, &cmppl))
970 return TXP_ERR_SPACE;
972 /* Packet overhead (size of headers, AEAD tag, etc.) */
973 pkt_overhead = cmpl - cmppl;
975 return txp_generate_for_el_actual(txp, enc_level, archetype, min_ppl, cmppl,
977 chosen_for_conn_close);
980 /* Determine how many bytes we should use for the encoded PN. */
981 static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp)
983 return 4; /* TODO(QUIC) */
986 /* Determine plaintext packet payload length from payload length. */
987 static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp,
998 if (!ossl_qtx_calculate_plaintext_payload_len(txp->args.qtx, enc_level,
1006 static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp)
1008 return ossl_qtx_get_mdpl(txp->args.qtx);
1011 static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space,
1014 OSSL_QUIC_TX_PACKETISER *txp = arg;
1017 if (stream_id == UINT64_MAX)
1018 return txp->args.crypto[pn_space];
1020 s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1027 static void on_regen_notify(uint64_t frame_type, uint64_t stream_id,
1028 QUIC_TXPIM_PKT *pkt, void *arg)
1030 OSSL_QUIC_TX_PACKETISER *txp = arg;
1032 switch (frame_type) {
1033 case OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE:
1034 txp->want_handshake_done = 1;
1036 case OSSL_QUIC_FRAME_TYPE_MAX_DATA:
1037 txp->want_max_data = 1;
1039 case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI:
1040 txp->want_max_streams_bidi = 1;
1042 case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI:
1043 txp->want_max_streams_uni = 1;
1045 case OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN:
1046 txp->want_ack |= (1UL << pkt->ackm_pkt.pkt_space);
1048 case OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA:
1051 = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1056 s->want_max_stream_data = 1;
1057 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1060 case OSSL_QUIC_FRAME_TYPE_STOP_SENDING:
1063 = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1068 s->want_stop_sending = 1;
1069 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1072 case OSSL_QUIC_FRAME_TYPE_RESET_STREAM:
1075 = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1080 s->want_reset_stream = 1;
1081 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1090 static int txp_generate_pre_token(OSSL_QUIC_TX_PACKETISER *txp,
1091 struct tx_helper *h,
1092 QUIC_TXPIM_PKT *tpkt,
1094 struct archetype_data *a,
1095 char chosen_for_conn_close)
1097 const OSSL_QUIC_FRAME_ACK *ack;
1098 OSSL_QUIC_FRAME_ACK ack2;
1100 tpkt->ackm_pkt.largest_acked = QUIC_PN_INVALID;
1102 /* ACK Frames (Regenerate) */
1104 && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_ACK
1106 || ossl_ackm_is_ack_desired(txp->args.ackm, pn_space))
1107 && (ack = ossl_ackm_get_ack_frame(txp->args.ackm, pn_space)) != NULL) {
1108 WPACKET *wpkt = tx_helper_begin(h);
1113 /* We do not currently support ECN */
1115 ack2.ecn_present = 0;
1117 if (ossl_quic_wire_encode_frame_ack(wpkt,
1118 txp->args.ack_delay_exponent,
1120 if (!tx_helper_commit(h))
1123 tpkt->had_ack_frame = 1;
1125 if (ack->num_ack_ranges > 0)
1126 tpkt->ackm_pkt.largest_acked = ack->ack_ranges[0].end;
1128 tx_helper_rollback(h);
1132 /* CONNECTION_CLOSE Frames (Regenerate) */
1133 if (a->allow_conn_close && txp->want_conn_close && chosen_for_conn_close) {
1134 WPACKET *wpkt = tx_helper_begin(h);
1139 if (ossl_quic_wire_encode_frame_conn_close(wpkt,
1140 &txp->conn_close_frame)) {
1141 if (!tx_helper_commit(h))
1144 tx_helper_rollback(h);
1151 static int try_len(size_t space_left, size_t orig_len,
1152 size_t base_hdr_len, size_t lenbytes,
1153 uint64_t maxn, size_t *hdr_len, size_t *payload_len)
1156 size_t maxn_ = maxn > SIZE_MAX ? SIZE_MAX : (size_t)maxn;
1158 *hdr_len = base_hdr_len + lenbytes;
1163 if (n + *hdr_len > space_left)
1164 n = (space_left >= *hdr_len) ? space_left - *hdr_len : 0;
1170 static void determine_len(size_t space_left, size_t orig_len,
1171 size_t base_hdr_len,
1172 uint64_t *hlen, uint64_t *len)
1174 size_t chosen_payload_len = 0;
1175 size_t chosen_hdr_len = 0;
1176 size_t payload_len[4], hdr_len[4];
1177 int i, valid[4] = {0};
1179 valid[0] = try_len(space_left, orig_len, base_hdr_len,
1180 1, OSSL_QUIC_VLINT_1B_MAX,
1181 &hdr_len[0], &payload_len[0]);
1182 valid[1] = try_len(space_left, orig_len, base_hdr_len,
1183 2, OSSL_QUIC_VLINT_2B_MAX,
1184 &hdr_len[1], &payload_len[1]);
1185 valid[2] = try_len(space_left, orig_len, base_hdr_len,
1186 4, OSSL_QUIC_VLINT_4B_MAX,
1187 &hdr_len[2], &payload_len[2]);
1188 valid[3] = try_len(space_left, orig_len, base_hdr_len,
1189 8, OSSL_QUIC_VLINT_8B_MAX,
1190 &hdr_len[3], &payload_len[3]);
1192 for (i = OSSL_NELEM(valid) - 1; i >= 0; --i)
1193 if (valid[i] && payload_len[i] >= chosen_payload_len) {
1194 chosen_payload_len = payload_len[i];
1195 chosen_hdr_len = hdr_len[i];
1198 *hlen = chosen_hdr_len;
1199 *len = chosen_payload_len;
1203 * Given a CRYPTO frame header with accurate chdr->len and a budget
1204 * (space_left), try to find the optimal value of chdr->len to fill as much of
1205 * the budget as possible. This is slightly hairy because larger values of
1206 * chdr->len cause larger encoded sizes of the length field of the frame, which
1207 * in turn mean less space available for payload data. We check all possible
1208 * encodings and choose the optimal encoding.
1210 static int determine_crypto_len(struct tx_helper *h,
1211 OSSL_QUIC_FRAME_CRYPTO *chdr,
1217 size_t base_hdr_len; /* CRYPTO header length without length field */
1219 if (chdr->len > SIZE_MAX)
1222 orig_len = (size_t)chdr->len;
1225 base_hdr_len = ossl_quic_wire_get_encoded_frame_len_crypto_hdr(chdr);
1226 chdr->len = orig_len;
1227 if (base_hdr_len == 0)
1232 determine_len(space_left, orig_len, base_hdr_len, hlen, len);
1236 static int determine_stream_len(struct tx_helper *h,
1237 OSSL_QUIC_FRAME_STREAM *shdr,
1243 size_t base_hdr_len; /* STREAM header length without length field */
1245 if (shdr->len > SIZE_MAX)
1248 orig_len = (size_t)shdr->len;
1251 base_hdr_len = ossl_quic_wire_get_encoded_frame_len_stream_hdr(shdr);
1252 shdr->len = orig_len;
1253 if (base_hdr_len == 0)
1256 if (shdr->has_explicit_len)
1259 determine_len(space_left, orig_len, base_hdr_len, hlen, len);
1263 static int txp_generate_crypto_frames(OSSL_QUIC_TX_PACKETISER *txp,
1264 struct tx_helper *h,
1266 QUIC_TXPIM_PKT *tpkt,
1267 char *have_ack_eliciting)
1269 size_t num_stream_iovec;
1270 OSSL_QUIC_FRAME_STREAM shdr = {0};
1271 OSSL_QUIC_FRAME_CRYPTO chdr = {0};
1272 OSSL_QTX_IOVEC iov[2];
1275 QUIC_TXPIM_CHUNK chunk = {0};
1276 size_t i, space_left;
1279 space_left = tx_helper_get_space_left(h);
1281 if (space_left < MIN_FRAME_SIZE_CRYPTO)
1282 return 1; /* no point trying */
1284 /* Do we have any CRYPTO data waiting? */
1285 num_stream_iovec = OSSL_NELEM(iov);
1286 if (!ossl_quic_sstream_get_stream_frame(txp->args.crypto[pn_space],
1289 return 1; /* nothing to do */
1291 /* Convert STREAM frame header to CRYPTO frame header */
1292 chdr.offset = shdr.offset;
1293 chdr.len = shdr.len;
1296 return 1; /* nothing to do */
1298 /* Find best fit (header length, payload length) combination. */
1299 if (!determine_crypto_len(h, &chdr, space_left, &hdr_bytes,
1301 || hdr_bytes == 0 || chdr.len == 0) {
1302 return 1; /* can't fit anything */
1306 * Truncate IOVs to match our chosen length.
1308 * The length cannot be more than SIZE_MAX because this length comes
1309 * from our send stream buffer.
1311 ossl_quic_sstream_adjust_iov((size_t)chdr.len, iov, num_stream_iovec);
1314 * Ensure we have enough iovecs allocated (1 for the header, up to 2 for
1315 * the the stream data.)
1317 if (!txp_ensure_iovec(txp, h->num_iovec + 3))
1318 return 0; /* alloc error */
1320 /* Encode the header. */
1321 wpkt = tx_helper_begin(h);
1323 return 0; /* alloc error */
1325 if (!ossl_quic_wire_encode_frame_crypto_hdr(wpkt, &chdr)) {
1326 tx_helper_rollback(h);
1327 return 1; /* can't fit */
1330 if (!tx_helper_commit(h))
1331 return 0; /* alloc error */
1333 /* Add payload iovecs to the helper (infallible). */
1334 for (i = 0; i < num_stream_iovec; ++i)
1335 tx_helper_append_iovec(h, iov[i].buf, iov[i].buf_len);
1337 *have_ack_eliciting = 1;
1338 tx_helper_unrestrict(h); /* no longer need PING */
1340 /* Log chunk to TXPIM. */
1341 chunk.stream_id = UINT64_MAX; /* crypto stream */
1342 chunk.start = chdr.offset;
1343 chunk.end = chdr.offset + chdr.len - 1;
1344 chunk.has_fin = 0; /* Crypto stream never ends */
1345 if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
1346 return 0; /* alloc error */
1351 OSSL_QUIC_FRAME_STREAM shdr;
1352 OSSL_QTX_IOVEC iov[2];
1353 size_t num_stream_iovec;
1357 static int txp_plan_stream_chunk(OSSL_QUIC_TX_PACKETISER *txp,
1358 struct tx_helper *h,
1359 QUIC_SSTREAM *sstream,
1360 QUIC_TXFC *stream_txfc,
1362 struct chunk_info *chunk)
1364 uint64_t fc_credit, fc_swm, fc_limit;
1366 chunk->num_stream_iovec = OSSL_NELEM(chunk->iov);
1367 chunk->valid = ossl_quic_sstream_get_stream_frame(sstream, skip,
1370 &chunk->num_stream_iovec);
1374 if (!ossl_assert(chunk->shdr.len > 0 || chunk->shdr.is_fin))
1375 /* Should only have 0-length chunk if FIN */
1378 /* Clamp according to connection and stream-level TXFC. */
1379 fc_credit = ossl_quic_txfc_get_credit(stream_txfc);
1380 fc_swm = ossl_quic_txfc_get_swm(stream_txfc);
1381 fc_limit = fc_swm + fc_credit;
1383 if (chunk->shdr.len > 0 && chunk->shdr.offset + chunk->shdr.len > fc_limit) {
1384 chunk->shdr.len = (fc_limit <= chunk->shdr.offset)
1385 ? 0 : fc_limit - chunk->shdr.offset;
1386 chunk->shdr.is_fin = 0;
1389 if (chunk->shdr.len == 0 && !chunk->shdr.is_fin) {
1391 * Nothing to do due to TXFC. Since SSTREAM returns chunks in ascending
1392 * order of offset we don't need to check any later chunks, so stop
1403 * Returns 0 on fatal error (e.g. allocation failure), 1 on success.
1404 * *packet_full is set to 1 if there is no longer enough room for another STREAM
1405 * frame, and *stream_drained is set to 1 if all stream buffers have now been
1408 static int txp_generate_stream_frames(OSSL_QUIC_TX_PACKETISER *txp,
1409 struct tx_helper *h,
1411 QUIC_TXPIM_PKT *tpkt,
1413 QUIC_SSTREAM *sstream,
1414 QUIC_TXFC *stream_txfc,
1415 QUIC_STREAM *next_stream,
1417 char *have_ack_eliciting,
1419 char *stream_drained,
1420 uint64_t *new_credit_consumed)
1423 struct chunk_info chunks[2] = {0};
1425 OSSL_QUIC_FRAME_STREAM *shdr;
1427 QUIC_TXPIM_CHUNK chunk;
1428 size_t i, j, space_left;
1429 int needs_padding_if_implicit, can_fill_payload, use_explicit_len;
1430 int could_have_following_chunk;
1432 uint64_t hdr_len_implicit, payload_len_implicit;
1433 uint64_t hdr_len_explicit, payload_len_explicit;
1434 uint64_t fc_swm, fc_new_hwm;
1436 fc_swm = ossl_quic_txfc_get_swm(stream_txfc);
1437 fc_new_hwm = fc_swm;
1440 * Load the first two chunks if any offered by the send stream. We retrieve
1441 * the next chunk in advance so we can determine if we need to send any more
1442 * chunks from the same stream after this one, which is needed when
1443 * determining when we can use an implicit length in a STREAM frame.
1445 for (i = 0; i < 2; ++i) {
1446 if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i, &chunks[i]))
1449 if (i == 0 && !chunks[i].valid) {
1450 /* No chunks, nothing to do. */
1451 *stream_drained = 1;
1458 space_left = tx_helper_get_space_left(h);
1460 if (space_left < MIN_FRAME_SIZE_STREAM) {
1466 if (!chunks[i % 2].valid) {
1467 /* Out of chunks; we're done. */
1468 *stream_drained = 1;
1473 if (!ossl_assert(!h->done_implicit))
1475 * Logic below should have ensured we didn't append an
1476 * implicit-length unless we filled the packet or didn't have
1477 * another stream to handle, so this should not be possible.
1481 shdr = &chunks[i % 2].shdr;
1482 orig_len = shdr->len;
1484 /* Load next chunk for lookahead. */
1485 if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i + 1,
1486 &chunks[(i + 1) % 2]))
1490 * Find best fit (header length, payload length) combination for if we
1491 * use an implicit length.
1493 shdr->has_explicit_len = 0;
1494 hdr_len_implicit = payload_len_implicit = 0;
1495 if (!determine_stream_len(h, shdr, space_left,
1496 &hdr_len_implicit, &payload_len_implicit)
1497 || hdr_len_implicit == 0 || payload_len_implicit == 0) {
1500 goto err; /* can't fit anything */
1504 * If using the implicit-length representation would need padding, we
1507 needs_padding_if_implicit = (h->bytes_appended + hdr_len_implicit
1508 + payload_len_implicit < min_ppl);
1511 * If there is a next stream, we don't use the implicit length so we can
1512 * add more STREAM frames after this one, unless there is enough data
1513 * for this STREAM frame to fill the packet.
1515 can_fill_payload = (hdr_len_implicit + payload_len_implicit
1519 * Is there is a stream after this one, or another chunk pending
1520 * transmission in this stream?
1522 could_have_following_chunk
1523 = (next_stream != NULL || chunks[(i + 1) % 2].valid);
1525 /* Choose between explicit or implicit length representations. */
1526 use_explicit_len = !((can_fill_payload || !could_have_following_chunk)
1527 && !needs_padding_if_implicit);
1529 if (use_explicit_len) {
1531 * Find best fit (header length, payload length) combination for if
1532 * we use an explicit length.
1534 shdr->has_explicit_len = 1;
1535 hdr_len_explicit = payload_len_explicit = 0;
1536 if (!determine_stream_len(h, shdr, space_left,
1537 &hdr_len_explicit, &payload_len_explicit)
1538 || hdr_len_explicit == 0 || payload_len_explicit == 0) {
1541 goto err; /* can't fit anything */
1544 shdr->len = payload_len_explicit;
1546 shdr->has_explicit_len = 0;
1547 shdr->len = payload_len_implicit;
1550 /* Truncate IOVs to match our chosen length. */
1551 ossl_quic_sstream_adjust_iov((size_t)shdr->len, chunks[i % 2].iov,
1552 chunks[i % 2].num_stream_iovec);
1555 * Ensure we have enough iovecs allocated (1 for the header, up to 2 for
1556 * the the stream data.)
1558 if (!txp_ensure_iovec(txp, h->num_iovec + 3))
1559 goto err; /* alloc error */
1561 /* Encode the header. */
1562 wpkt = tx_helper_begin(h);
1564 goto err; /* alloc error */
1566 shdr->stream_id = id;
1567 if (!ossl_assert(ossl_quic_wire_encode_frame_stream_hdr(wpkt, shdr))) {
1568 /* (Should not be possible.) */
1569 tx_helper_rollback(h);
1572 goto err; /* can't fit */
1575 if (!tx_helper_commit(h))
1576 goto err; /* alloc error */
1578 /* Add payload iovecs to the helper (infallible). */
1579 for (j = 0; j < chunks[i % 2].num_stream_iovec; ++j)
1580 tx_helper_append_iovec(h, chunks[i % 2].iov[j].buf,
1581 chunks[i % 2].iov[j].buf_len);
1583 *have_ack_eliciting = 1;
1584 tx_helper_unrestrict(h); /* no longer need PING */
1585 if (!shdr->has_explicit_len)
1586 h->done_implicit = 1;
1588 /* Log new TXFC credit which was consumed. */
1589 if (shdr->len > 0 && shdr->offset + shdr->len > fc_new_hwm)
1590 fc_new_hwm = shdr->offset + shdr->len;
1592 /* Log chunk to TXPIM. */
1593 chunk.stream_id = shdr->stream_id;
1594 chunk.start = shdr->offset;
1595 chunk.end = shdr->offset + shdr->len - 1;
1596 chunk.has_fin = shdr->is_fin;
1597 chunk.has_stop_sending = 0;
1598 chunk.has_reset_stream = 0;
1599 if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
1600 goto err; /* alloc error */
1602 if (shdr->len < orig_len) {
1604 * If we did not serialize all of this chunk we definitely do not
1605 * want to try the next chunk (and we must not mark the stream
1614 *new_credit_consumed = fc_new_hwm - fc_swm;
1618 static void txp_enlink_tmp(QUIC_STREAM **tmp_head, QUIC_STREAM *stream)
1620 stream->txp_next = *tmp_head;
1624 static int txp_generate_stream_related(OSSL_QUIC_TX_PACKETISER *txp,
1625 struct tx_helper *h,
1627 QUIC_TXPIM_PKT *tpkt,
1629 char *have_ack_eliciting,
1630 QUIC_STREAM **tmp_head)
1632 QUIC_STREAM_ITER it;
1636 QUIC_STREAM *stream, *snext;
1638 for (ossl_quic_stream_iter_init(&it, txp->args.qsm, 1);
1639 it.stream != NULL;) {
1642 ossl_quic_stream_iter_next(&it);
1645 stream->txp_sent_fc = 0;
1646 stream->txp_sent_stop_sending = 0;
1647 stream->txp_sent_reset_stream = 0;
1648 stream->txp_drained = 0;
1649 stream->txp_blocked = 0;
1650 stream->txp_txfc_new_credit_consumed = 0;
1652 rstream = stream->rstream;
1654 /* Stream Abort Frames (STOP_SENDING, RESET_STREAM) */
1655 if (stream->want_stop_sending) {
1656 OSSL_QUIC_FRAME_STOP_SENDING f;
1658 wpkt = tx_helper_begin(h);
1660 return 0; /* alloc error */
1662 f.stream_id = stream->id;
1663 f.app_error_code = stream->stop_sending_aec;
1664 if (!ossl_quic_wire_encode_frame_stop_sending(wpkt, &f)) {
1665 tx_helper_rollback(h); /* can't fit */
1666 txp_enlink_tmp(tmp_head, stream);
1670 if (!tx_helper_commit(h))
1671 return 0; /* alloc error */
1673 *have_ack_eliciting = 1;
1674 tx_helper_unrestrict(h); /* no longer need PING */
1675 stream->txp_sent_stop_sending = 1;
1678 if (stream->want_reset_stream) {
1679 OSSL_QUIC_FRAME_RESET_STREAM f;
1681 wpkt = tx_helper_begin(h);
1683 return 0; /* alloc error */
1685 f.stream_id = stream->id;
1686 f.app_error_code = stream->reset_stream_aec;
1687 f.final_size = ossl_quic_sstream_get_cur_size(stream->sstream);
1688 if (!ossl_quic_wire_encode_frame_reset_stream(wpkt, &f)) {
1689 tx_helper_rollback(h); /* can't fit */
1690 txp_enlink_tmp(tmp_head, stream);
1694 if (!tx_helper_commit(h))
1695 return 0; /* alloc error */
1697 *have_ack_eliciting = 1;
1698 tx_helper_unrestrict(h); /* no longer need PING */
1699 stream->txp_sent_reset_stream = 1;
1702 /* Stream Flow Control Frames (MAX_STREAM_DATA) */
1704 && (stream->want_max_stream_data
1705 || ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 0))) {
1707 wpkt = tx_helper_begin(h);
1709 return 0; /* alloc error */
1711 cwm = ossl_quic_rxfc_get_cwm(&stream->rxfc);
1713 if (!ossl_quic_wire_encode_frame_max_stream_data(wpkt, stream->id,
1715 tx_helper_rollback(h); /* can't fit */
1716 txp_enlink_tmp(tmp_head, stream);
1720 if (!tx_helper_commit(h))
1721 return 0; /* alloc error */
1723 *have_ack_eliciting = 1;
1724 tx_helper_unrestrict(h); /* no longer need PING */
1725 stream->txp_sent_fc = 1;
1728 /* Stream Data Frames (STREAM) */
1729 if (stream->sstream != NULL) {
1730 char packet_full = 0, stream_drained = 0;
1732 if (!txp_generate_stream_frames(txp, h, pn_space, tpkt,
1733 stream->id, stream->sstream,
1739 &stream->txp_txfc_new_credit_consumed)) {
1740 /* Fatal error (allocation, etc.) */
1741 txp_enlink_tmp(tmp_head, stream);
1746 stream->txp_drained = 1;
1749 txp_enlink_tmp(tmp_head, stream);
1754 txp_enlink_tmp(tmp_head, stream);
1761 * Generates a packet for a given EL with the given minimum and maximum
1762 * plaintext packet payload lengths. Returns TXP_ERR_* value.
1764 static int txp_generate_for_el_actual(OSSL_QUIC_TX_PACKETISER *txp,
1769 size_t pkt_overhead,
1771 char chosen_for_conn_close)
1773 int rc = TXP_ERR_SUCCESS;
1774 struct archetype_data a;
1775 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
1777 char have_helper = 0, have_ack_eliciting = 0, done_pre_token = 0;
1778 char require_ack_eliciting;
1779 QUIC_CFQ_ITEM *cfq_item;
1780 QUIC_TXPIM_PKT *tpkt = NULL;
1782 QUIC_STREAM *tmp_head = NULL, *stream;
1784 if (!txp_get_archetype_data(enc_level, archetype, &a))
1787 require_ack_eliciting
1788 = (a.allow_force_ack_eliciting
1789 && (txp->force_ack_eliciting & (1UL << pn_space)));
1791 /* Minimum cannot be bigger than maximum. */
1792 if (min_ppl > max_ppl)
1795 /* Maximum PN reached? */
1796 if (txp->next_pn[pn_space] >= (((QUIC_PN)1) << 62))
1799 if ((tpkt = ossl_quic_txpim_pkt_alloc(txp->args.txpim)) == NULL)
1803 * Initialise TX helper. If we must be ACK eliciting, reserve 1 byte for
1806 if (!tx_helper_init(&h, txp, max_ppl, require_ack_eliciting ? 1 : 0))
1812 * Frame Serialization
1813 * ===================
1815 * We now serialize frames into the packet in descending order of priority.
1818 /* HANDSHAKE_DONE (Regenerate) */
1819 if (a.allow_handshake_done && txp->want_handshake_done
1820 && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_HANDSHAKE_DONE) {
1821 WPACKET *wpkt = tx_helper_begin(&h);
1826 if (ossl_quic_wire_encode_frame_handshake_done(wpkt)) {
1827 tpkt->had_handshake_done_frame = 1;
1828 have_ack_eliciting = 1;
1830 if (!tx_helper_commit(&h))
1833 tx_helper_unrestrict(&h); /* no longer need PING */
1835 tx_helper_rollback(&h);
1839 /* MAX_DATA (Regenerate) */
1841 && (txp->want_max_data
1842 || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0))
1843 && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_MAX_DATA) {
1844 WPACKET *wpkt = tx_helper_begin(&h);
1845 uint64_t cwm = ossl_quic_rxfc_get_cwm(txp->args.conn_rxfc);
1850 if (ossl_quic_wire_encode_frame_max_data(wpkt, cwm)) {
1851 tpkt->had_max_data_frame = 1;
1852 have_ack_eliciting = 1;
1854 if (!tx_helper_commit(&h))
1857 tx_helper_unrestrict(&h); /* no longer need PING */
1859 tx_helper_rollback(&h);
1863 /* MAX_STREAMS_BIDI (Regenerate) */
1865 * TODO(STREAMS): Once we support multiple streams, add stream count FC
1869 && txp->want_max_streams_bidi
1870 && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_MAX_STREAMS_BIDI) {
1871 WPACKET *wpkt = tx_helper_begin(&h);
1872 uint64_t max_streams = 1; /* TODO */
1877 if (ossl_quic_wire_encode_frame_max_streams(wpkt, /*is_uni=*/0,
1879 tpkt->had_max_streams_bidi_frame = 1;
1880 have_ack_eliciting = 1;
1882 if (!tx_helper_commit(&h))
1885 tx_helper_unrestrict(&h); /* no longer need PING */
1887 tx_helper_rollback(&h);
1891 /* MAX_STREAMS_UNI (Regenerate) */
1893 && txp->want_max_streams_uni
1894 && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_MAX_STREAMS_UNI) {
1895 WPACKET *wpkt = tx_helper_begin(&h);
1896 uint64_t max_streams = 0; /* TODO */
1901 if (ossl_quic_wire_encode_frame_max_streams(wpkt, /*is_uni=*/1,
1903 tpkt->had_max_streams_uni_frame = 1;
1904 have_ack_eliciting = 1;
1906 if (!tx_helper_commit(&h))
1909 tx_helper_unrestrict(&h); /* no longer need PING */
1911 tx_helper_rollback(&h);
1916 for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space);
1918 cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) {
1919 uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item);
1920 const unsigned char *encoded = ossl_quic_cfq_item_get_encoded(cfq_item);
1921 size_t encoded_len = ossl_quic_cfq_item_get_encoded_len(cfq_item);
1923 switch (frame_type) {
1924 case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID:
1925 if (!a.allow_new_conn_id)
1928 case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID:
1929 if (!a.allow_retire_conn_id)
1932 case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN:
1933 if (!a.allow_new_token)
1937 * NEW_TOKEN frames are handled via GCR, but some
1938 * Regenerate-strategy frames should come before them (namely
1939 * ACK, CONNECTION_CLOSE, PATH_CHALLENGE and PATH_RESPONSE). If
1940 * we find a NEW_TOKEN frame, do these now. If there are no
1941 * NEW_TOKEN frames in the GCR queue we will handle these below.
1943 if (!done_pre_token)
1944 if (txp_generate_pre_token(txp, &h, tpkt, pn_space, &a,
1945 chosen_for_conn_close))
1950 if (!a.allow_cfq_other)
1956 * If the frame is too big, don't try to schedule any more GCR frames in
1957 * this packet rather than sending subsequent ones out of order.
1959 if (encoded_len > tx_helper_get_space_left(&h))
1962 if (!tx_helper_append_iovec(&h, encoded, encoded_len))
1965 ossl_quic_txpim_pkt_add_cfq_item(tpkt, cfq_item);
1967 if (ossl_quic_frame_type_is_ack_eliciting(frame_type)) {
1968 have_ack_eliciting = 1;
1969 tx_helper_unrestrict(&h); /* no longer need PING */
1974 * If we didn't generate ACK, CONNECTION_CLOSE, PATH_CHALLENGE or
1975 * PATH_RESPONSE (as desired) before, do so now.
1977 if (!done_pre_token)
1978 if (txp_generate_pre_token(txp, &h, tpkt, pn_space, &a,
1979 chosen_for_conn_close))
1984 if (!txp_generate_crypto_frames(txp, &h, pn_space, tpkt,
1985 &have_ack_eliciting))
1988 /* Stream-specific frames */
1989 if (a.allow_stream_rel && txp->handshake_complete)
1990 if (!txp_generate_stream_related(txp, &h, pn_space, tpkt, min_ppl,
1991 &have_ack_eliciting,
1996 tx_helper_unrestrict(&h);
1998 if (require_ack_eliciting && !have_ack_eliciting && a.allow_ping) {
2001 wpkt = tx_helper_begin(&h);
2005 if (!ossl_quic_wire_encode_frame_ping(wpkt)
2006 || !tx_helper_commit(&h))
2008 * We treat a request to be ACK-eliciting as a requirement, so this
2013 have_ack_eliciting = 1;
2017 if (h.bytes_appended < min_ppl) {
2018 WPACKET *wpkt = tx_helper_begin(&h);
2022 if (!ossl_quic_wire_encode_padding(wpkt, min_ppl - h.bytes_appended)
2023 || !tx_helper_commit(&h))
2032 tpkt->ackm_pkt.num_bytes = h.bytes_appended + pkt_overhead;
2033 tpkt->ackm_pkt.pkt_num = txp->next_pn[pn_space];
2034 /* largest_acked is set in txp_generate_pre_token */
2035 tpkt->ackm_pkt.pkt_space = pn_space;
2036 tpkt->ackm_pkt.is_inflight = 1;
2037 tpkt->ackm_pkt.is_ack_eliciting = have_ack_eliciting;
2038 tpkt->ackm_pkt.is_pto_probe = 0;
2039 tpkt->ackm_pkt.is_mtu_probe = 0;
2040 tpkt->ackm_pkt.time = ossl_time_now();
2042 /* Packet Information for QTX */
2044 pkt.iovec = txp->iovec;
2045 pkt.num_iovec = h.num_iovec;
2047 pkt.peer = BIO_ADDR_family(&txp->args.peer) == AF_UNSPEC
2048 ? NULL : &txp->args.peer;
2049 pkt.pn = txp->next_pn[pn_space];
2050 pkt.flags = OSSL_QTX_PKT_FLAG_COALESCE; /* always try to coalesce */
2052 /* Do TX key update if needed. */
2053 if (enc_level == QUIC_ENC_LEVEL_1RTT) {
2054 uint64_t cur_pkt_count, max_pkt_count;
2056 cur_pkt_count = ossl_qtx_get_cur_epoch_pkt_count(txp->args.qtx, enc_level);
2057 max_pkt_count = ossl_qtx_get_max_epoch_pkt_count(txp->args.qtx, enc_level);
2059 if (cur_pkt_count >= max_pkt_count / 2)
2060 if (!ossl_qtx_trigger_key_update(txp->args.qtx))
2064 if (!ossl_assert(h.bytes_appended > 0))
2067 /* Generate TXPIM chunks representing STOP_SENDING and RESET_STREAM frames. */
2068 for (stream = tmp_head; stream != NULL; stream = stream->txp_next)
2069 if (stream->txp_sent_stop_sending || stream->txp_sent_reset_stream) {
2070 /* Log STOP_SENDING chunk to TXPIM. */
2071 QUIC_TXPIM_CHUNK chunk;
2073 chunk.stream_id = stream->id;
2074 chunk.start = UINT64_MAX;
2077 chunk.has_stop_sending = stream->txp_sent_stop_sending;
2078 chunk.has_reset_stream = stream->txp_sent_reset_stream;
2079 if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
2080 return 0; /* alloc error */
2083 /* Dispatch to FIFD. */
2084 if (!ossl_quic_fifd_pkt_commit(&txp->fifd, tpkt))
2087 /* Send the packet. */
2088 if (!ossl_qtx_write_pkt(txp->args.qtx, &pkt))
2091 ++txp->next_pn[pn_space];
2094 * Record FC and stream abort frames as sent; deactivate streams which no
2095 * longer have anything to do.
2097 for (stream = tmp_head; stream != NULL; stream = stream->txp_next) {
2098 if (stream->txp_sent_fc) {
2099 stream->want_max_stream_data = 0;
2100 ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 1);
2103 if (stream->txp_sent_stop_sending)
2104 stream->want_stop_sending = 0;
2106 if (stream->txp_sent_reset_stream)
2107 stream->want_reset_stream = 0;
2109 if (stream->txp_txfc_new_credit_consumed > 0) {
2110 if (!ossl_assert(ossl_quic_txfc_consume_credit(&stream->txfc,
2111 stream->txp_txfc_new_credit_consumed)))
2113 * Should not be possible, but we should continue with our
2114 * bookkeeping as we have already committed the packet to the
2115 * FIFD. Just change the value we return.
2117 rc = TXP_ERR_INTERNAL;
2119 stream->txp_txfc_new_credit_consumed = 0;
2123 * If we no longer need to generate any flow control (MAX_STREAM_DATA),
2124 * STOP_SENDING or RESET_STREAM frames, nor any STREAM frames (because
2125 * the stream is drained of data or TXFC-blocked), we can mark the
2126 * stream as inactive.
2128 ossl_quic_stream_map_update_state(txp->args.qsm, stream);
2130 if (stream->txp_drained)
2131 assert(!ossl_quic_sstream_has_pending(stream->sstream));
2134 /* We have now sent the packet, so update state accordingly. */
2135 if (have_ack_eliciting)
2136 txp->force_ack_eliciting &= ~(1UL << pn_space);
2138 if (tpkt->had_handshake_done_frame)
2139 txp->want_handshake_done = 0;
2141 if (tpkt->had_max_data_frame) {
2142 txp->want_max_data = 0;
2143 ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 1);
2146 if (tpkt->had_max_streams_bidi_frame)
2147 txp->want_max_streams_bidi = 0;
2149 if (tpkt->had_max_streams_uni_frame)
2150 txp->want_max_streams_uni = 0;
2152 if (tpkt->had_ack_frame)
2153 txp->want_ack &= ~(1UL << pn_space);
2156 tx_helper_cleanup(&h);
2161 * Handler for fatal errors, i.e. errors causing us to abort the entire
2162 * packet rather than just one frame. Examples of such errors include
2163 * allocation errors.
2166 tx_helper_cleanup(&h);
2168 ossl_quic_txpim_pkt_release(txp->args.txpim, tpkt);
2169 return TXP_ERR_INTERNAL;
2172 /* Ensure the iovec array is at least num elements long. */
2173 static int txp_ensure_iovec(OSSL_QUIC_TX_PACKETISER *txp, size_t num)
2175 OSSL_QTX_IOVEC *iovec;
2177 if (txp->alloc_iovec >= num)
2180 num = txp->alloc_iovec != 0 ? txp->alloc_iovec * 2 : 8;
2182 iovec = OPENSSL_realloc(txp->iovec, sizeof(OSSL_QTX_IOVEC) * num);
2187 txp->alloc_iovec = num;
2191 int ossl_quic_tx_packetiser_schedule_conn_close(OSSL_QUIC_TX_PACKETISER *txp,
2192 const OSSL_QUIC_FRAME_CONN_CLOSE *f)
2194 char *reason = NULL;
2195 size_t reason_len = f->reason_len;
2196 size_t max_reason_len = txp_get_mdpl(txp) / 2;
2198 if (txp->want_conn_close)
2202 * Arbitrarily limit the length of the reason length string to half of the
2205 if (reason_len > max_reason_len)
2206 reason_len = max_reason_len;
2208 if (reason_len > 0) {
2209 reason = OPENSSL_memdup(f->reason, reason_len);
2214 txp->conn_close_frame = *f;
2215 txp->conn_close_frame.reason = reason;
2216 txp->conn_close_frame.reason_len = reason_len;
2217 txp->want_conn_close = 1;