]> git.ipfire.org Git - thirdparty/openssl.git/blame - ssl/quic/quic_txp.c
QUIC RX: Refactor key update callback to provide PN
[thirdparty/openssl.git] / ssl / quic / quic_txp.c
CommitLineData
a73078b7
HL
1/*
2 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10#include "internal/quic_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>
15
16#define MIN_CRYPTO_HDR_SIZE 3
17
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
25
26struct ossl_quic_tx_packetiser_st {
27 OSSL_QUIC_TX_PACKETISER_ARGS args;
28
29 /*
30 * Opaque initial token blob provided by caller. TXP frees using the
31 * callback when it is no longer needed.
32 */
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;
37
38 /* Subcomponents of the TXP that we own. */
39 QUIC_FIFD fifd; /* QUIC Frame-in-Flight Dispatcher */
40
41 /* Internal state. */
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. */
44
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;
50
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;
54
55 /*
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.
59 */
60 unsigned int want_conn_close : 1;
61
cda88baf
HL
62 /* Has the handshake been completed? */
63 unsigned int handshake_complete : 1;
64
a73078b7
HL
65 OSSL_QUIC_FRAME_CONN_CLOSE conn_close_frame;
66
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 */
5cf99b40
MC
72
73 /* Message callback related arguments */
74 ossl_msg_cb msg_callback;
75 void *msg_callback_arg;
c2786c8e 76 SSL *msg_callback_ssl;
5cf99b40 77
a73078b7
HL
78};
79
80/*
81 * The TX helper records state used while generating frames into packets. It
82 * enables serialization into the packet to be done "transactionally" where
83 * serialization of a frame can be rolled back if it fails midway (e.g. if it
84 * does not fit).
85 */
86struct tx_helper {
87 OSSL_QUIC_TX_PACKETISER *txp;
88 /*
89 * The Maximum Packet Payload Length in bytes. This is the amount of
90 * space we have to generate frames into.
91 */
92 size_t max_ppl;
93 /*
94 * Number of bytes we have generated so far.
95 */
96 size_t bytes_appended;
97 /*
98 * Number of scratch bytes in txp->scratch we have used so far. Some iovecs
99 * will reference this scratch buffer. When we need to use more of it (e.g.
100 * when we need to put frame headers somewhere), we append to the scratch
101 * buffer, resizing if necessary, and increase this accordingly.
102 */
103 size_t scratch_bytes;
104 /*
105 * Bytes reserved in the MaxPPL budget. We keep this number of bytes spare
106 * until reserve_allowed is set to 1. Currently this is always at most 1, as
107 * a PING frame takes up one byte and this mechanism is only used to ensure
108 * we can encode a PING frame if we have been asked to ensure a packet is
109 * ACK-eliciting and we are unusure if we are going to add any other
110 * ACK-eliciting frames before we reach our MaxPPL budget.
111 */
112 size_t reserve;
113 /*
114 * Number of iovecs we have currently appended. This is the number of
115 * entries valid in txp->iovec.
116 */
117 size_t num_iovec;
118 /*
119 * Whether we are allowed to make use of the reserve bytes in our MaxPPL
120 * budget. This is used to ensure we have room to append a PING frame later
121 * if we need to. Once we know we will not need to append a PING frame, this
122 * is set to 1.
123 */
124 unsigned int reserve_allowed : 1;
125 /*
126 * Set to 1 if we have appended a STREAM frame with an implicit length. If
127 * this happens we should never append another frame after that frame as it
128 * cannot be validly encoded. This is just a safety check.
129 */
130 unsigned int done_implicit : 1;
131 struct {
132 /*
133 * The fields in this structure are valid if active is set, which means
134 * that a serialization transaction is currently in progress.
135 */
136 unsigned char *data;
137 WPACKET wpkt;
138 unsigned int active : 1;
139 } txn;
140};
141
142static void tx_helper_rollback(struct tx_helper *h);
143static int txp_ensure_iovec(OSSL_QUIC_TX_PACKETISER *txp, size_t num);
144
145/* Initialises the TX helper. */
146static int tx_helper_init(struct tx_helper *h, OSSL_QUIC_TX_PACKETISER *txp,
147 size_t max_ppl, size_t reserve)
148{
149 if (reserve > max_ppl)
150 return 0;
151
152 h->txp = txp;
153 h->max_ppl = max_ppl;
154 h->reserve = reserve;
155 h->num_iovec = 0;
156 h->bytes_appended = 0;
157 h->scratch_bytes = 0;
158 h->reserve_allowed = 0;
159 h->done_implicit = 0;
160 h->txn.data = NULL;
161 h->txn.active = 0;
162
163 if (max_ppl > h->txp->scratch_len) {
164 unsigned char *scratch;
165
166 scratch = OPENSSL_realloc(h->txp->scratch, max_ppl);
167 if (scratch == NULL)
168 return 0;
169
170 h->txp->scratch = scratch;
171 h->txp->scratch_len = max_ppl;
172 }
173
174 return 1;
175}
176
177static void tx_helper_cleanup(struct tx_helper *h)
178{
179 if (h->txn.active)
180 tx_helper_rollback(h);
181
182 h->txp = NULL;
183}
184
185static void tx_helper_unrestrict(struct tx_helper *h)
186{
187 h->reserve_allowed = 1;
188}
189
190/*
191 * Append an extent of memory to the iovec list. The memory must remain
192 * allocated until we finish generating the packet and call the QTX.
193 *
194 * In general, the buffers passed to this function will be from one of two
195 * ranges:
196 *
197 * - Application data contained in stream buffers managed elsewhere
198 * in the QUIC stack; or
199 *
200 * - Control frame data appended into txp->scratch using tx_helper_begin and
201 * tx_helper_commit.
202 *
203 */
204static int tx_helper_append_iovec(struct tx_helper *h,
205 const unsigned char *buf,
206 size_t buf_len)
207{
208 if (buf_len == 0)
209 return 1;
210
211 if (!ossl_assert(!h->done_implicit))
212 return 0;
213
214 if (!txp_ensure_iovec(h->txp, h->num_iovec + 1))
215 return 0;
216
217 h->txp->iovec[h->num_iovec].buf = buf;
218 h->txp->iovec[h->num_iovec].buf_len = buf_len;
219
220 ++h->num_iovec;
221 h->bytes_appended += buf_len;
222 return 1;
223}
224
225/*
226 * How many more bytes of space do we have left in our plaintext packet payload?
227 */
228static size_t tx_helper_get_space_left(struct tx_helper *h)
229{
230 return h->max_ppl
231 - (h->reserve_allowed ? 0 : h->reserve) - h->bytes_appended;
232}
233
234/*
235 * Begin a control frame serialization transaction. This allows the
236 * serialization of the control frame to be backed out if it turns out it won't
237 * fit. Write the control frame to the returned WPACKET. Ensure you always
238 * call tx_helper_rollback or tx_helper_commit (or tx_helper_cleanup). Returns
239 * NULL on failure.
240 */
241static WPACKET *tx_helper_begin(struct tx_helper *h)
242{
243 size_t space_left, len;
244 unsigned char *data;
245
246 if (!ossl_assert(!h->txn.active))
247 return NULL;
248
249 if (!ossl_assert(!h->done_implicit))
250 return NULL;
251
252 data = (unsigned char *)h->txp->scratch + h->scratch_bytes;
253 len = h->txp->scratch_len - h->scratch_bytes;
254
255 space_left = tx_helper_get_space_left(h);
256 if (!ossl_assert(space_left <= len))
257 return NULL;
258
259 if (!WPACKET_init_static_len(&h->txn.wpkt, data, len, 0))
260 return NULL;
261
262 if (!WPACKET_set_max_size(&h->txn.wpkt, space_left)) {
263 WPACKET_cleanup(&h->txn.wpkt);
264 return NULL;
265 }
266
267 h->txn.data = data;
268 h->txn.active = 1;
269 return &h->txn.wpkt;
270}
271
272static void tx_helper_end(struct tx_helper *h, int success)
273{
274 if (success)
275 WPACKET_finish(&h->txn.wpkt);
276 else
277 WPACKET_cleanup(&h->txn.wpkt);
278
279 h->txn.active = 0;
280 h->txn.data = NULL;
281}
282
283/* Abort a control frame serialization transaction. */
284static void tx_helper_rollback(struct tx_helper *h)
285{
286 if (!h->txn.active)
287 return;
288
289 tx_helper_end(h, 0);
290}
291
292/* Commit a control frame. */
293static int tx_helper_commit(struct tx_helper *h)
294{
295 size_t l = 0;
296
297 if (!h->txn.active)
298 return 0;
299
300 if (!WPACKET_get_total_written(&h->txn.wpkt, &l)) {
301 tx_helper_end(h, 0);
302 return 0;
303 }
304
305 if (!tx_helper_append_iovec(h, h->txn.data, l)) {
306 tx_helper_end(h, 0);
307 return 0;
308 }
309
5cf99b40 310 if (h->txp->msg_callback != NULL && l > 0) {
45454ccc
MC
311 uint64_t ftype;
312 int ctype = SSL3_RT_QUIC_FRAME_FULL;
313 PACKET pkt;
314
315 if (!PACKET_buf_init(&pkt, h->txn.data, l)
316 || !ossl_quic_wire_peek_frame_header(&pkt, &ftype)) {
317 tx_helper_end(h, 0);
318 return 0;
319 }
320
321 if (ftype == OSSL_QUIC_FRAME_TYPE_PADDING)
322 ctype = SSL3_RT_QUIC_FRAME_PADDING;
323 else if (OSSL_QUIC_FRAME_TYPE_IS_STREAM(ftype)
324 || ftype == OSSL_QUIC_FRAME_TYPE_CRYPTO)
325 ctype = SSL3_RT_QUIC_FRAME_HEADER;
326
5cf99b40 327 h->txp->msg_callback(1, OSSL_QUIC1_VERSION, ctype, h->txn.data, l,
c2786c8e 328 h->txp->msg_callback_ssl,
5cf99b40 329 h->txp->msg_callback_arg);
45454ccc
MC
330 }
331
a73078b7
HL
332 h->scratch_bytes += l;
333 tx_helper_end(h, 1);
334 return 1;
335}
336
337static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space,
338 void *arg);
339static void on_regen_notify(uint64_t frame_type, uint64_t stream_id,
340 QUIC_TXPIM_PKT *pkt, void *arg);
9cacba43
HL
341static void on_confirm_notify(uint64_t frame_type, uint64_t stream_id,
342 QUIC_TXPIM_PKT *pkt, void *arg);
5d27e7e9 343static void on_sstream_updated(uint64_t stream_id, void *arg);
a73078b7
HL
344static int sstream_is_pending(QUIC_SSTREAM *sstream);
345static int txp_el_pending(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level,
7f9d1249 346 uint32_t archetype,
fee8f48e 347 int cc_can_send,
7f9d1249 348 uint32_t *conn_close_enc_level);
a73078b7
HL
349static int txp_generate_for_el(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level,
350 uint32_t archetype,
fee8f48e 351 int cc_can_send,
091f532e
HL
352 int is_last_in_dgram,
353 int dgram_contains_initial,
134b79c0 354 int chosen_for_conn_close,
a3a51d6e 355 QUIC_TXP_STATUS *status);
a73078b7
HL
356static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp);
357static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp,
358 size_t pl,
359 uint32_t enc_level,
360 size_t hdr_len,
361 size_t *r);
362static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp);
363static int txp_generate_for_el_actual(OSSL_QUIC_TX_PACKETISER *txp,
364 uint32_t enc_level,
365 uint32_t archetype,
366 size_t min_ppl,
367 size_t max_ppl,
368 size_t pkt_overhead,
7f9d1249 369 QUIC_PKT_HDR *phdr,
134b79c0 370 int chosen_for_conn_close,
a3a51d6e 371 QUIC_TXP_STATUS *status);
a73078b7
HL
372
373OSSL_QUIC_TX_PACKETISER *ossl_quic_tx_packetiser_new(const OSSL_QUIC_TX_PACKETISER_ARGS *args)
374{
375 OSSL_QUIC_TX_PACKETISER *txp;
376
377 if (args == NULL
378 || args->qtx == NULL
379 || args->txpim == NULL
380 || args->cfq == NULL
381 || args->ackm == NULL
382 || args->qsm == NULL
383 || args->conn_txfc == NULL
a6b6ea17
HL
384 || args->conn_rxfc == NULL
385 || args->max_streams_bidi_rxfc == NULL
386 || args->max_streams_uni_rxfc == NULL) {
a73078b7
HL
387 ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
388 return NULL;
389 }
390
391 txp = OPENSSL_zalloc(sizeof(*txp));
392 if (txp == NULL)
393 return NULL;
394
395 txp->args = *args;
396 txp->last_tx_time = ossl_time_zero();
397
398 if (!ossl_quic_fifd_init(&txp->fifd,
399 txp->args.cfq, txp->args.ackm, txp->args.txpim,
400 get_sstream_by_id, txp,
5d27e7e9 401 on_regen_notify, txp,
9cacba43 402 on_confirm_notify, txp,
5d27e7e9 403 on_sstream_updated, txp)) {
a73078b7
HL
404 OPENSSL_free(txp);
405 return NULL;
406 }
407
408 return txp;
409}
410
411void ossl_quic_tx_packetiser_free(OSSL_QUIC_TX_PACKETISER *txp)
412{
413 if (txp == NULL)
414 return;
415
416 ossl_quic_tx_packetiser_set_initial_token(txp, NULL, 0, NULL, NULL);
417 ossl_quic_fifd_cleanup(&txp->fifd);
418 OPENSSL_free(txp->iovec);
419 OPENSSL_free(txp->conn_close_frame.reason);
420 OPENSSL_free(txp->scratch);
421 OPENSSL_free(txp);
422}
423
424void ossl_quic_tx_packetiser_set_initial_token(OSSL_QUIC_TX_PACKETISER *txp,
425 const unsigned char *token,
426 size_t token_len,
427 ossl_quic_initial_token_free_fn *free_cb,
428 void *free_cb_arg)
429{
430 if (txp->initial_token != NULL && txp->initial_token_free_cb != NULL)
431 txp->initial_token_free_cb(txp->initial_token, txp->initial_token_len,
432 txp->initial_token_free_cb_arg);
433
434 txp->initial_token = token;
435 txp->initial_token_len = token_len;
436 txp->initial_token_free_cb = free_cb;
437 txp->initial_token_free_cb_arg = free_cb_arg;
438}
439
440int ossl_quic_tx_packetiser_set_cur_dcid(OSSL_QUIC_TX_PACKETISER *txp,
441 const QUIC_CONN_ID *dcid)
442{
443 if (dcid == NULL) {
444 ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
445 return 0;
446 }
447
448 txp->args.cur_dcid = *dcid;
449 return 1;
450}
451
452int ossl_quic_tx_packetiser_set_cur_scid(OSSL_QUIC_TX_PACKETISER *txp,
453 const QUIC_CONN_ID *scid)
454{
455 if (scid == NULL) {
456 ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
457 return 0;
458 }
459
460 txp->args.cur_scid = *scid;
461 return 1;
462}
463
464/* Change the destination L4 address the TXP uses to send datagrams. */
465int ossl_quic_tx_packetiser_set_peer(OSSL_QUIC_TX_PACKETISER *txp,
466 const BIO_ADDR *peer)
467{
468 if (peer == NULL) {
469 ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
470 return 0;
471 }
472
473 txp->args.peer = *peer;
474 return 1;
475}
476
477int ossl_quic_tx_packetiser_discard_enc_level(OSSL_QUIC_TX_PACKETISER *txp,
478 uint32_t enc_level)
479{
480 if (enc_level >= QUIC_ENC_LEVEL_NUM) {
481 ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
482 return 0;
483 }
484
485 if (enc_level != QUIC_ENC_LEVEL_0RTT)
486 txp->args.crypto[ossl_quic_enc_level_to_pn_space(enc_level)] = NULL;
487
a73078b7
HL
488 return 1;
489}
490
cda88baf
HL
491void ossl_quic_tx_packetiser_notify_handshake_complete(OSSL_QUIC_TX_PACKETISER *txp)
492{
493 txp->handshake_complete = 1;
494}
495
a73078b7
HL
496void ossl_quic_tx_packetiser_schedule_handshake_done(OSSL_QUIC_TX_PACKETISER *txp)
497{
498 txp->want_handshake_done = 1;
499}
500
501void ossl_quic_tx_packetiser_schedule_ack_eliciting(OSSL_QUIC_TX_PACKETISER *txp,
502 uint32_t pn_space)
503{
504 txp->force_ack_eliciting |= (1UL << pn_space);
505}
506
507#define TXP_ERR_INTERNAL 0 /* Internal (e.g. alloc) error */
508#define TXP_ERR_SUCCESS 1 /* Success */
509#define TXP_ERR_SPACE 2 /* Not enough room for another packet */
510#define TXP_ERR_INPUT 3 /* Invalid/malformed input */
511
04e5226f
HL
512int ossl_quic_tx_packetiser_has_pending(OSSL_QUIC_TX_PACKETISER *txp,
513 uint32_t archetype,
514 uint32_t flags)
515{
7f9d1249 516 uint32_t enc_level, conn_close_enc_level = QUIC_ENC_LEVEL_NUM;
04e5226f 517 int bypass_cc = ((flags & TX_PACKETISER_BYPASS_CC) != 0);
fee8f48e 518 int cc_can_send;
04e5226f 519
fee8f48e 520 cc_can_send
90699176
HL
521 = (bypass_cc
522 || txp->args.cc_method->get_tx_allowance(txp->args.cc_data) > 0);
04e5226f
HL
523
524 for (enc_level = QUIC_ENC_LEVEL_INITIAL;
525 enc_level < QUIC_ENC_LEVEL_NUM;
526 ++enc_level)
fee8f48e
HL
527 if (txp_el_pending(txp, enc_level, archetype, cc_can_send,
528 &conn_close_enc_level))
04e5226f
HL
529 return 1;
530
531 return 0;
532}
533
a73078b7
HL
534/*
535 * Generates a datagram by polling the various ELs to determine if they want to
536 * generate any frames, and generating a datagram which coalesces packets for
537 * any ELs which do.
538 */
539int ossl_quic_tx_packetiser_generate(OSSL_QUIC_TX_PACKETISER *txp,
134b79c0 540 uint32_t archetype,
a3a51d6e 541 QUIC_TXP_STATUS *status)
a73078b7 542{
7f9d1249 543 uint32_t enc_level, conn_close_enc_level = QUIC_ENC_LEVEL_NUM;
fee8f48e 544 int have_pkt_for_el[QUIC_ENC_LEVEL_NUM], is_last_in_dgram, cc_can_send;
a73078b7
HL
545 size_t num_el_in_dgram = 0, pkts_done = 0;
546 int rc;
547
a3a51d6e
HL
548 status->sent_ack_eliciting = 0;
549
fee8f48e
HL
550 /*
551 * If CC says we cannot send we still may be able to send any queued probes.
552 */
90699176 553 cc_can_send = (txp->args.cc_method->get_tx_allowance(txp->args.cc_data) > 0);
a73078b7
HL
554
555 for (enc_level = QUIC_ENC_LEVEL_INITIAL;
556 enc_level < QUIC_ENC_LEVEL_NUM;
557 ++enc_level) {
7f9d1249 558 have_pkt_for_el[enc_level] = txp_el_pending(txp, enc_level, archetype,
fee8f48e 559 cc_can_send,
7f9d1249 560 &conn_close_enc_level);
a73078b7
HL
561 if (have_pkt_for_el[enc_level])
562 ++num_el_in_dgram;
563 }
564
565 if (num_el_in_dgram == 0)
566 return TX_PACKETISER_RES_NO_PKT;
567
568 /*
569 * Should not be needed, but a sanity check in case anyone else has been
570 * using the QTX.
571 */
572 ossl_qtx_finish_dgram(txp->args.qtx);
573
574 for (enc_level = QUIC_ENC_LEVEL_INITIAL;
575 enc_level < QUIC_ENC_LEVEL_NUM;
576 ++enc_level) {
577 if (!have_pkt_for_el[enc_level])
578 continue;
579
580 is_last_in_dgram = (pkts_done + 1 == num_el_in_dgram);
fee8f48e
HL
581 rc = txp_generate_for_el(txp, enc_level, archetype, cc_can_send,
582 is_last_in_dgram,
7f9d1249 583 have_pkt_for_el[QUIC_ENC_LEVEL_INITIAL],
134b79c0 584 enc_level == conn_close_enc_level,
a3a51d6e 585 status);
a73078b7
HL
586
587 if (rc != TXP_ERR_SUCCESS) {
588 /*
589 * If we already successfully did at least one, make sure we report
590 * this via the return code.
591 */
592 if (pkts_done > 0)
593 break;
594 else
595 return TX_PACKETISER_RES_FAILURE;
596 }
597
598 ++pkts_done;
599 }
600
601 ossl_qtx_finish_dgram(txp->args.qtx);
602 return TX_PACKETISER_RES_SENT_PKT;
603}
604
605struct archetype_data {
606 unsigned int allow_ack : 1;
607 unsigned int allow_ping : 1;
608 unsigned int allow_crypto : 1;
609 unsigned int allow_handshake_done : 1;
610 unsigned int allow_path_challenge : 1;
611 unsigned int allow_path_response : 1;
612 unsigned int allow_new_conn_id : 1;
613 unsigned int allow_retire_conn_id : 1;
614 unsigned int allow_stream_rel : 1;
615 unsigned int allow_conn_fc : 1;
616 unsigned int allow_conn_close : 1;
617 unsigned int allow_cfq_other : 1;
618 unsigned int allow_new_token : 1;
619 unsigned int allow_force_ack_eliciting : 1;
620};
621
622static const struct archetype_data archetypes[QUIC_ENC_LEVEL_NUM][TX_PACKETISER_ARCHETYPE_NUM] = {
623 /* EL 0(INITIAL) */
624 {
625 /* EL 0(INITIAL) - Archetype 0(NORMAL) */
626 {
627 /*allow_ack =*/ 1,
628 /*allow_ping =*/ 1,
629 /*allow_crypto =*/ 1,
630 /*allow_handshake_done =*/ 0,
631 /*allow_path_challenge =*/ 0,
632 /*allow_path_response =*/ 0,
633 /*allow_new_conn_id =*/ 0,
634 /*allow_retire_conn_id =*/ 0,
635 /*allow_stream_rel =*/ 0,
636 /*allow_conn_fc =*/ 0,
637 /*allow_conn_close =*/ 1,
638 /*allow_cfq_other =*/ 1,
639 /*allow_new_token =*/ 0,
640 /*allow_force_ack_eliciting =*/ 1,
641 },
642 /* EL 0(INITIAL) - Archetype 1(ACK_ONLY) */
643 {
644 /*allow_ack =*/ 1,
645 /*allow_ping =*/ 0,
646 /*allow_crypto =*/ 0,
647 /*allow_handshake_done =*/ 0,
648 /*allow_path_challenge =*/ 0,
649 /*allow_path_response =*/ 0,
650 /*allow_new_conn_id =*/ 0,
651 /*allow_retire_conn_id =*/ 0,
652 /*allow_stream_rel =*/ 0,
653 /*allow_conn_fc =*/ 0,
654 /*allow_conn_close =*/ 0,
655 /*allow_cfq_other =*/ 0,
656 /*allow_new_token =*/ 0,
657 /*allow_force_ack_eliciting =*/ 1,
658 },
659 },
660 /* EL 1(HANDSHAKE) */
661 {
662 /* EL 1(HANDSHAKE) - Archetype 0(NORMAL) */
663 {
664 /*allow_ack =*/ 1,
665 /*allow_ping =*/ 1,
666 /*allow_crypto =*/ 1,
667 /*allow_handshake_done =*/ 0,
668 /*allow_path_challenge =*/ 0,
669 /*allow_path_response =*/ 0,
670 /*allow_new_conn_id =*/ 0,
671 /*allow_retire_conn_id =*/ 0,
672 /*allow_stream_rel =*/ 0,
673 /*allow_conn_fc =*/ 0,
674 /*allow_conn_close =*/ 1,
675 /*allow_cfq_other =*/ 1,
676 /*allow_new_token =*/ 0,
677 /*allow_force_ack_eliciting =*/ 1,
678 },
679 /* EL 1(HANDSHAKE) - Archetype 1(ACK_ONLY) */
680 {
681 /*allow_ack =*/ 1,
682 /*allow_ping =*/ 0,
683 /*allow_crypto =*/ 0,
684 /*allow_handshake_done =*/ 0,
685 /*allow_path_challenge =*/ 0,
686 /*allow_path_response =*/ 0,
687 /*allow_new_conn_id =*/ 0,
688 /*allow_retire_conn_id =*/ 0,
689 /*allow_stream_rel =*/ 0,
690 /*allow_conn_fc =*/ 0,
691 /*allow_conn_close =*/ 0,
692 /*allow_cfq_other =*/ 0,
693 /*allow_new_token =*/ 0,
694 /*allow_force_ack_eliciting =*/ 1,
695 },
696 },
697 /* EL 2(0RTT) */
698 {
699 /* EL 2(0RTT) - Archetype 0(NORMAL) */
700 {
701 /*allow_ack =*/ 0,
702 /*allow_ping =*/ 1,
703 /*allow_crypto =*/ 0,
704 /*allow_handshake_done =*/ 0,
705 /*allow_path_challenge =*/ 0,
706 /*allow_path_response =*/ 0,
707 /*allow_new_conn_id =*/ 1,
708 /*allow_retire_conn_id =*/ 1,
709 /*allow_stream_rel =*/ 1,
710 /*allow_conn_fc =*/ 1,
711 /*allow_conn_close =*/ 1,
712 /*allow_cfq_other =*/ 0,
713 /*allow_new_token =*/ 0,
714 /*allow_force_ack_eliciting =*/ 0,
715 },
716 /* EL 2(0RTT) - Archetype 1(ACK_ONLY) */
717 {
718 /*allow_ack =*/ 0,
719 /*allow_ping =*/ 0,
720 /*allow_crypto =*/ 0,
721 /*allow_handshake_done =*/ 0,
722 /*allow_path_challenge =*/ 0,
723 /*allow_path_response =*/ 0,
724 /*allow_new_conn_id =*/ 0,
725 /*allow_retire_conn_id =*/ 0,
726 /*allow_stream_rel =*/ 0,
727 /*allow_conn_fc =*/ 0,
728 /*allow_conn_close =*/ 0,
729 /*allow_cfq_other =*/ 0,
730 /*allow_new_token =*/ 0,
731 /*allow_force_ack_eliciting =*/ 0,
732 },
733 },
734 /* EL 3(1RTT) */
735 {
736 /* EL 3(1RTT) - Archetype 0(NORMAL) */
737 {
738 /*allow_ack =*/ 1,
739 /*allow_ping =*/ 1,
740 /*allow_crypto =*/ 1,
741 /*allow_handshake_done =*/ 1,
742 /*allow_path_challenge =*/ 0,
743 /*allow_path_response =*/ 0,
744 /*allow_new_conn_id =*/ 1,
745 /*allow_retire_conn_id =*/ 1,
746 /*allow_stream_rel =*/ 1,
747 /*allow_conn_fc =*/ 1,
748 /*allow_conn_close =*/ 1,
749 /*allow_cfq_other =*/ 1,
750 /*allow_new_token =*/ 1,
751 /*allow_force_ack_eliciting =*/ 1,
752 },
753 /* EL 3(1RTT) - Archetype 1(ACK_ONLY) */
754 {
755 /*allow_ack =*/ 1,
756 /*allow_ping =*/ 0,
757 /*allow_crypto =*/ 0,
758 /*allow_handshake_done =*/ 0,
759 /*allow_path_challenge =*/ 0,
760 /*allow_path_response =*/ 0,
761 /*allow_new_conn_id =*/ 0,
762 /*allow_retire_conn_id =*/ 0,
763 /*allow_stream_rel =*/ 0,
764 /*allow_conn_fc =*/ 0,
765 /*allow_conn_close =*/ 0,
766 /*allow_cfq_other =*/ 0,
767 /*allow_new_token =*/ 0,
768 /*allow_force_ack_eliciting =*/ 1,
769 }
770 }
771};
772
773static int txp_get_archetype_data(uint32_t enc_level,
774 uint32_t archetype,
775 struct archetype_data *a)
776{
777 if (enc_level >= QUIC_ENC_LEVEL_NUM
778 || archetype >= TX_PACKETISER_ARCHETYPE_NUM)
779 return 0;
780
781 /* No need to avoid copying this as it should not exceed one int in size. */
782 *a = archetypes[enc_level][archetype];
783 return 1;
784}
785
786/*
787 * Returns 1 if the given EL wants to produce one or more frames.
788 * Always returns 0 if the given EL is discarded.
789 */
790static int txp_el_pending(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level,
7f9d1249 791 uint32_t archetype,
fee8f48e 792 int cc_can_send,
7f9d1249 793 uint32_t *conn_close_enc_level)
a73078b7
HL
794{
795 struct archetype_data a;
796 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
797 QUIC_CFQ_ITEM *cfq_item;
798
799 if (!ossl_qtx_is_enc_level_provisioned(txp->args.qtx, enc_level))
800 return 0;
801
7f9d1249
HL
802 if (*conn_close_enc_level > enc_level)
803 *conn_close_enc_level = enc_level;
804
a73078b7
HL
805 if (!txp_get_archetype_data(enc_level, archetype, &a))
806 return 0;
807
fee8f48e
HL
808 /* Do we need to send a PTO probe? */
809 if (a.allow_force_ack_eliciting) {
810 OSSL_ACKM_PROBE_INFO *probe_info
2477e99f 811 = ossl_ackm_get0_probe_request(txp->args.ackm);
fee8f48e
HL
812
813 if ((enc_level == QUIC_ENC_LEVEL_INITIAL
814 && probe_info->anti_deadlock_initial > 0)
815 || (enc_level == QUIC_ENC_LEVEL_HANDSHAKE
816 && probe_info->anti_deadlock_handshake > 0)
817 || probe_info->pto[pn_space] > 0)
818 return 1;
819 }
820
821 if (!cc_can_send)
822 /* If CC says we cannot currently send, we can only send probes. */
823 return 0;
824
a73078b7
HL
825 /* Does the crypto stream for this EL want to produce anything? */
826 if (a.allow_crypto && sstream_is_pending(txp->args.crypto[pn_space]))
827 return 1;
828
829 /* Does the ACKM for this PN space want to produce anything? */
830 if (a.allow_ack && (ossl_ackm_is_ack_desired(txp->args.ackm, pn_space)
831 || (txp->want_ack & (1UL << pn_space)) != 0))
832 return 1;
833
834 /* Do we need to force emission of an ACK-eliciting packet? */
835 if (a.allow_force_ack_eliciting
836 && (txp->force_ack_eliciting & (1UL << pn_space)) != 0)
837 return 1;
838
839 /* Does the connection-level RXFC want to produce a frame? */
840 if (a.allow_conn_fc && (txp->want_max_data
841 || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0)))
842 return 1;
843
844 /* Do we want to produce a MAX_STREAMS frame? */
a6b6ea17
HL
845 if (a.allow_conn_fc
846 && (txp->want_max_streams_bidi
847 || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc,
848 0)
849 || txp->want_max_streams_uni
850 || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc,
851 0)))
a73078b7
HL
852 return 1;
853
854 /* Do we want to produce a HANDSHAKE_DONE frame? */
855 if (a.allow_handshake_done && txp->want_handshake_done)
856 return 1;
857
858 /* Do we want to produce a CONNECTION_CLOSE frame? */
7f9d1249
HL
859 if (a.allow_conn_close && txp->want_conn_close &&
860 *conn_close_enc_level == enc_level)
861 /*
862 * This is a bit of a special case since CONNECTION_CLOSE can appear in
863 * most packet types, and when we decide we want to send it this status
864 * isn't tied to a specific EL. So if we want to send it, we send it
865 * only on the lowest non-dropped EL.
866 */
a73078b7
HL
867 return 1;
868
869 /* Does the CFQ have any frames queued for this PN space? */
870 if (enc_level != QUIC_ENC_LEVEL_0RTT)
871 for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space);
872 cfq_item != NULL;
873 cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) {
874 uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item);
875
876 switch (frame_type) {
877 case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID:
878 if (a.allow_new_conn_id)
879 return 1;
880 break;
881 case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID:
882 if (a.allow_retire_conn_id)
883 return 1;
884 break;
885 case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN:
886 if (a.allow_new_token)
887 return 1;
888 break;
889 default:
890 if (a.allow_cfq_other)
891 return 1;
892 break;
893 }
894 }
895
cda88baf 896 if (a.allow_stream_rel && txp->handshake_complete) {
a73078b7
HL
897 QUIC_STREAM_ITER it;
898
899 /* If there are any active streams, 0/1-RTT wants to produce a packet.
900 * Whether a stream is on the active list is required to be precise
901 * (i.e., a stream is never on the active list if we cannot produce a
902 * frame for it), and all stream-related frames are governed by
903 * a.allow_stream_rel (i.e., if we can send one type of stream-related
904 * frame, we can send any of them), so we don't need to inspect
905 * individual streams on the active list, just confirm that the active
906 * list is non-empty.
907 */
908 ossl_quic_stream_iter_init(&it, txp->args.qsm, 0);
909 if (it.stream != NULL)
910 return 1;
911 }
912
913 return 0;
914}
915
916static int sstream_is_pending(QUIC_SSTREAM *sstream)
917{
918 OSSL_QUIC_FRAME_STREAM hdr;
919 OSSL_QTX_IOVEC iov[2];
920 size_t num_iov = OSSL_NELEM(iov);
921
922 return ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov);
923}
924
925/*
926 * Generates a packet for a given EL, coalescing it into the current datagram.
927 *
928 * is_last_in_dgram and dgram_contains_initial are used to determine padding
929 * requirements.
930 *
931 * Returns TXP_ERR_* value.
932 */
933static int txp_generate_for_el(OSSL_QUIC_TX_PACKETISER *txp, uint32_t enc_level,
934 uint32_t archetype,
fee8f48e 935 int cc_can_send,
091f532e
HL
936 int is_last_in_dgram,
937 int dgram_contains_initial,
134b79c0 938 int chosen_for_conn_close,
a3a51d6e 939 QUIC_TXP_STATUS *status)
a73078b7 940{
091f532e 941 int must_pad = dgram_contains_initial && is_last_in_dgram;
a73078b7
HL
942 size_t min_dpl, min_pl, min_ppl, cmpl, cmppl, running_total;
943 size_t mdpl, hdr_len, pkt_overhead, cc_limit;
944 uint64_t cc_limit_;
945 QUIC_PKT_HDR phdr;
a73078b7
HL
946
947 /* Determine the limit CC imposes on what we can send. */
fee8f48e
HL
948 if (!cc_can_send) {
949 /*
950 * If we are called when we cannot send, this must be because we want
951 * to generate a probe. In this circumstance, don't clamp based on CC.
952 */
953 cc_limit = SIZE_MAX;
954 } else {
955 /* Allow CC to clamp how much we can send. */
90699176 956 cc_limit_ = txp->args.cc_method->get_tx_allowance(txp->args.cc_data);
fee8f48e
HL
957 cc_limit = (cc_limit_ > SIZE_MAX ? SIZE_MAX : (size_t)cc_limit_);
958 }
a73078b7
HL
959
960 /* Assemble packet header. */
961 phdr.type = ossl_quic_enc_level_to_pkt_type(enc_level);
962 phdr.spin_bit = 0;
963 phdr.pn_len = txp_determine_pn_len(txp);
964 phdr.partial = 0;
965 phdr.fixed = 1;
966 phdr.version = QUIC_VERSION_1;
967 phdr.dst_conn_id = txp->args.cur_dcid;
968 phdr.src_conn_id = txp->args.cur_scid;
969
970 /*
971 * We need to know the length of the payload to get an accurate header
972 * length for non-1RTT packets, because the Length field found in
973 * Initial/Handshake/0-RTT packets uses a variable-length encoding. However,
974 * we don't have a good idea of the length of our payload, because the
975 * length of the payload depends on the room in the datagram after fitting
976 * the header, which depends on the size of the header.
977 *
978 * In general, it does not matter if a packet is slightly shorter (because
979 * e.g. we predicted use of a 2-byte length field, but ended up only needing
980 * a 1-byte length field). However this does matter for Initial packets
981 * which must be at least 1200 bytes, which is also the assumed default MTU;
982 * therefore in many cases Initial packets will be padded to 1200 bytes,
983 * which means if we overestimated the header size, we will be short by a
984 * few bytes and the server will ignore the packet for being too short. In
985 * this case, however, such packets always *will* be padded to meet 1200
986 * bytes, which requires a 2-byte length field, so we don't actually need to
987 * worry about this. Thus we estimate the header length assuming a 2-byte
988 * length field here, which should in practice work well in all cases.
989 */
990 phdr.len = OSSL_QUIC_VLINT_2B_MAX - phdr.pn_len;
991
992 if (enc_level == QUIC_ENC_LEVEL_INITIAL) {
993 phdr.token = txp->initial_token;
994 phdr.token_len = txp->initial_token_len;
995 } else {
996 phdr.token = NULL;
997 phdr.token_len = 0;
998 }
999
1000 hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(phdr.dst_conn_id.id_len,
1001 &phdr);
1002 if (hdr_len == 0)
1003 return TXP_ERR_INPUT;
1004
1005 /* MinDPL: Minimum total datagram payload length. */
1006 min_dpl = must_pad ? QUIC_MIN_INITIAL_DGRAM_LEN : 0;
1007
1008 /* How much data is already in the current datagram? */
1009 running_total = ossl_qtx_get_cur_dgram_len_bytes(txp->args.qtx);
1010
1011 /* MinPL: Minimum length of the fully encoded packet. */
1012 min_pl = running_total < min_dpl ? min_dpl - running_total : 0;
1013 if ((uint64_t)min_pl > cc_limit)
1014 /*
1015 * Congestion control does not allow us to send a packet of adequate
1016 * size.
1017 */
1018 return TXP_ERR_SPACE;
1019
1020 /* MinPPL: Minimum plaintext payload length needed to meet MinPL. */
1021 if (!txp_determine_ppl_from_pl(txp, min_pl, enc_level, hdr_len, &min_ppl))
1022 /* MinPL is less than a valid packet size, so just use a MinPPL of 0. */
1023 min_ppl = 0;
1024
1025 /* MDPL: Maximum datagram payload length. */
1026 mdpl = txp_get_mdpl(txp);
1027
1028 /*
1029 * CMPL: Maximum encoded packet size we can put into this datagram given any
1030 * previous packets coalesced into it.
1031 */
1032 if (running_total > mdpl)
1033 /* Should not be possible, but if it happens: */
1034 cmpl = 0;
1035 else
1036 cmpl = mdpl - running_total;
1037
1038 /* Clamp CMPL based on congestion control limit. */
1039 if (cmpl > cc_limit)
1040 cmpl = cc_limit;
1041
1042 /* CMPPL: Maximum amount we can put into the current datagram payload. */
1043 if (!txp_determine_ppl_from_pl(txp, cmpl, enc_level, hdr_len, &cmppl))
1044 return TXP_ERR_SPACE;
1045
1046 /* Packet overhead (size of headers, AEAD tag, etc.) */
1047 pkt_overhead = cmpl - cmppl;
1048
1049 return txp_generate_for_el_actual(txp, enc_level, archetype, min_ppl, cmppl,
7f9d1249 1050 pkt_overhead, &phdr,
134b79c0 1051 chosen_for_conn_close,
a3a51d6e 1052 status);
a73078b7
HL
1053}
1054
1055/* Determine how many bytes we should use for the encoded PN. */
1056static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp)
1057{
1058 return 4; /* TODO(QUIC) */
1059}
1060
1061/* Determine plaintext packet payload length from payload length. */
1062static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp,
1063 size_t pl,
1064 uint32_t enc_level,
1065 size_t hdr_len,
1066 size_t *r)
1067{
1068 if (pl < hdr_len)
1069 return 0;
1070
1071 pl -= hdr_len;
1072
1073 if (!ossl_qtx_calculate_plaintext_payload_len(txp->args.qtx, enc_level,
1074 pl, &pl))
1075 return 0;
1076
1077 *r = pl;
1078 return 1;
1079}
1080
1081static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp)
1082{
1083 return ossl_qtx_get_mdpl(txp->args.qtx);
1084}
1085
1086static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space,
1087 void *arg)
1088{
1089 OSSL_QUIC_TX_PACKETISER *txp = arg;
1090 QUIC_STREAM *s;
1091
1092 if (stream_id == UINT64_MAX)
1093 return txp->args.crypto[pn_space];
1094
1095 s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1096 if (s == NULL)
1097 return NULL;
1098
1099 return s->sstream;
1100}
1101
1102static void on_regen_notify(uint64_t frame_type, uint64_t stream_id,
1103 QUIC_TXPIM_PKT *pkt, void *arg)
1104{
1105 OSSL_QUIC_TX_PACKETISER *txp = arg;
1106
1107 switch (frame_type) {
1108 case OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE:
1109 txp->want_handshake_done = 1;
1110 break;
1111 case OSSL_QUIC_FRAME_TYPE_MAX_DATA:
1112 txp->want_max_data = 1;
1113 break;
1114 case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI:
1115 txp->want_max_streams_bidi = 1;
1116 break;
1117 case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI:
1118 txp->want_max_streams_uni = 1;
1119 break;
1120 case OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN:
1121 txp->want_ack |= (1UL << pkt->ackm_pkt.pkt_space);
1122 break;
1123 case OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA:
1124 {
1125 QUIC_STREAM *s
1126 = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1127
1128 if (s == NULL)
1129 return;
1130
1131 s->want_max_stream_data = 1;
1132 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1133 }
1134 break;
1135 case OSSL_QUIC_FRAME_TYPE_STOP_SENDING:
1136 {
1137 QUIC_STREAM *s
1138 = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1139
1140 if (s == NULL)
1141 return;
1142
1143 s->want_stop_sending = 1;
1144 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1145 }
1146 break;
1147 case OSSL_QUIC_FRAME_TYPE_RESET_STREAM:
1148 {
1149 QUIC_STREAM *s
1150 = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1151
1152 if (s == NULL)
1153 return;
1154
1155 s->want_reset_stream = 1;
1156 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1157 }
1158 break;
1159 default:
1160 assert(0);
1161 break;
1162 }
1163}
1164
9cacba43
HL
1165static void on_confirm_notify(uint64_t frame_type, uint64_t stream_id,
1166 QUIC_TXPIM_PKT *pkt, void *arg)
1167{
1168 OSSL_QUIC_TX_PACKETISER *txp = arg;
1169
1170 switch (frame_type) {
1171 case OSSL_QUIC_FRAME_TYPE_STOP_SENDING:
1172 {
1173 QUIC_STREAM *s
1174 = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1175
1176 if (s == NULL)
1177 return;
1178
1179 s->acked_stop_sending = 1;
1180 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1181 }
1182 break;
1183 case OSSL_QUIC_FRAME_TYPE_RESET_STREAM:
1184 {
1185 QUIC_STREAM *s
1186 = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1187
1188 if (s == NULL)
1189 return;
1190
1191 s->acked_reset_stream = 1;
1192 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1193 }
1194 break;
1195 default:
1196 assert(0);
1197 break;
1198 }
1199}
1200
5d27e7e9
HL
1201static void on_sstream_updated(uint64_t stream_id, void *arg)
1202{
1203 OSSL_QUIC_TX_PACKETISER *txp = arg;
1204 QUIC_STREAM *s;
1205
1206 s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1207 if (s == NULL)
1208 return;
1209
1210 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1211}
1212
a73078b7
HL
1213static int txp_generate_pre_token(OSSL_QUIC_TX_PACKETISER *txp,
1214 struct tx_helper *h,
1215 QUIC_TXPIM_PKT *tpkt,
1216 uint32_t pn_space,
7f9d1249 1217 struct archetype_data *a,
091f532e 1218 int chosen_for_conn_close)
a73078b7
HL
1219{
1220 const OSSL_QUIC_FRAME_ACK *ack;
1221 OSSL_QUIC_FRAME_ACK ack2;
1222
1223 tpkt->ackm_pkt.largest_acked = QUIC_PN_INVALID;
1224
1225 /* ACK Frames (Regenerate) */
1226 if (a->allow_ack
1227 && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_ACK
1228 && (txp->want_ack
1229 || ossl_ackm_is_ack_desired(txp->args.ackm, pn_space))
1230 && (ack = ossl_ackm_get_ack_frame(txp->args.ackm, pn_space)) != NULL) {
1231 WPACKET *wpkt = tx_helper_begin(h);
1232
1233 if (wpkt == NULL)
1234 return 0;
1235
1236 /* We do not currently support ECN */
1237 ack2 = *ack;
1238 ack2.ecn_present = 0;
1239
1240 if (ossl_quic_wire_encode_frame_ack(wpkt,
1241 txp->args.ack_delay_exponent,
1242 &ack2)) {
1243 if (!tx_helper_commit(h))
1244 return 0;
1245
1246 tpkt->had_ack_frame = 1;
1247
1248 if (ack->num_ack_ranges > 0)
1249 tpkt->ackm_pkt.largest_acked = ack->ack_ranges[0].end;
1250 } else {
1251 tx_helper_rollback(h);
1252 }
1253 }
1254
1255 /* CONNECTION_CLOSE Frames (Regenerate) */
7f9d1249 1256 if (a->allow_conn_close && txp->want_conn_close && chosen_for_conn_close) {
a73078b7
HL
1257 WPACKET *wpkt = tx_helper_begin(h);
1258
1259 if (wpkt == NULL)
1260 return 0;
1261
1262 if (ossl_quic_wire_encode_frame_conn_close(wpkt,
1263 &txp->conn_close_frame)) {
1264 if (!tx_helper_commit(h))
1265 return 0;
1266 } else {
1267 tx_helper_rollback(h);
1268 }
1269 }
1270
1271 return 1;
1272}
1273
1274static int try_len(size_t space_left, size_t orig_len,
1275 size_t base_hdr_len, size_t lenbytes,
1276 uint64_t maxn, size_t *hdr_len, size_t *payload_len)
1277{
1278 size_t n;
1279 size_t maxn_ = maxn > SIZE_MAX ? SIZE_MAX : (size_t)maxn;
1280
1281 *hdr_len = base_hdr_len + lenbytes;
1282
cf06f347
HL
1283 if (orig_len == 0 && space_left >= *hdr_len) {
1284 *payload_len = 0;
1285 return 1;
1286 }
1287
a73078b7
HL
1288 n = orig_len;
1289 if (n > maxn_)
1290 n = maxn_;
1291 if (n + *hdr_len > space_left)
1292 n = (space_left >= *hdr_len) ? space_left - *hdr_len : 0;
1293
1294 *payload_len = n;
1295 return n > 0;
1296}
1297
cf06f347
HL
1298static int determine_len(size_t space_left, size_t orig_len,
1299 size_t base_hdr_len,
1300 uint64_t *hlen, uint64_t *len)
a73078b7 1301{
cf06f347 1302 int ok = 0;
a73078b7
HL
1303 size_t chosen_payload_len = 0;
1304 size_t chosen_hdr_len = 0;
1305 size_t payload_len[4], hdr_len[4];
1306 int i, valid[4] = {0};
1307
1308 valid[0] = try_len(space_left, orig_len, base_hdr_len,
1309 1, OSSL_QUIC_VLINT_1B_MAX,
1310 &hdr_len[0], &payload_len[0]);
1311 valid[1] = try_len(space_left, orig_len, base_hdr_len,
1312 2, OSSL_QUIC_VLINT_2B_MAX,
1313 &hdr_len[1], &payload_len[1]);
1314 valid[2] = try_len(space_left, orig_len, base_hdr_len,
1315 4, OSSL_QUIC_VLINT_4B_MAX,
1316 &hdr_len[2], &payload_len[2]);
1317 valid[3] = try_len(space_left, orig_len, base_hdr_len,
1318 8, OSSL_QUIC_VLINT_8B_MAX,
1319 &hdr_len[3], &payload_len[3]);
1320
1321 for (i = OSSL_NELEM(valid) - 1; i >= 0; --i)
1322 if (valid[i] && payload_len[i] >= chosen_payload_len) {
1323 chosen_payload_len = payload_len[i];
1324 chosen_hdr_len = hdr_len[i];
cf06f347 1325 ok = 1;
a73078b7
HL
1326 }
1327
1328 *hlen = chosen_hdr_len;
1329 *len = chosen_payload_len;
cf06f347 1330 return ok;
a73078b7
HL
1331}
1332
1333/*
1334 * Given a CRYPTO frame header with accurate chdr->len and a budget
1335 * (space_left), try to find the optimal value of chdr->len to fill as much of
1336 * the budget as possible. This is slightly hairy because larger values of
1337 * chdr->len cause larger encoded sizes of the length field of the frame, which
1338 * in turn mean less space available for payload data. We check all possible
1339 * encodings and choose the optimal encoding.
1340 */
1341static int determine_crypto_len(struct tx_helper *h,
1342 OSSL_QUIC_FRAME_CRYPTO *chdr,
1343 size_t space_left,
1344 uint64_t *hlen,
1345 uint64_t *len)
1346{
1347 size_t orig_len;
1348 size_t base_hdr_len; /* CRYPTO header length without length field */
1349
1350 if (chdr->len > SIZE_MAX)
1351 return 0;
1352
1353 orig_len = (size_t)chdr->len;
1354
1355 chdr->len = 0;
1356 base_hdr_len = ossl_quic_wire_get_encoded_frame_len_crypto_hdr(chdr);
1357 chdr->len = orig_len;
1358 if (base_hdr_len == 0)
1359 return 0;
1360
1361 --base_hdr_len;
1362
cf06f347 1363 return determine_len(space_left, orig_len, base_hdr_len, hlen, len);
a73078b7
HL
1364}
1365
1366static int determine_stream_len(struct tx_helper *h,
1367 OSSL_QUIC_FRAME_STREAM *shdr,
1368 size_t space_left,
1369 uint64_t *hlen,
1370 uint64_t *len)
1371{
1372 size_t orig_len;
1373 size_t base_hdr_len; /* STREAM header length without length field */
1374
1375 if (shdr->len > SIZE_MAX)
1376 return 0;
1377
1378 orig_len = (size_t)shdr->len;
1379
1380 shdr->len = 0;
1381 base_hdr_len = ossl_quic_wire_get_encoded_frame_len_stream_hdr(shdr);
1382 shdr->len = orig_len;
1383 if (base_hdr_len == 0)
1384 return 0;
1385
1386 if (shdr->has_explicit_len)
1387 --base_hdr_len;
1388
cf06f347 1389 return determine_len(space_left, orig_len, base_hdr_len, hlen, len);
a73078b7
HL
1390}
1391
1392static int txp_generate_crypto_frames(OSSL_QUIC_TX_PACKETISER *txp,
1393 struct tx_helper *h,
1394 uint32_t pn_space,
1395 QUIC_TXPIM_PKT *tpkt,
091f532e 1396 int *have_ack_eliciting)
a73078b7
HL
1397{
1398 size_t num_stream_iovec;
1399 OSSL_QUIC_FRAME_STREAM shdr = {0};
1400 OSSL_QUIC_FRAME_CRYPTO chdr = {0};
1401 OSSL_QTX_IOVEC iov[2];
1402 uint64_t hdr_bytes;
1403 WPACKET *wpkt;
24c1be5c 1404 QUIC_TXPIM_CHUNK chunk = {0};
a73078b7
HL
1405 size_t i, space_left;
1406
1407 for (i = 0;; ++i) {
1408 space_left = tx_helper_get_space_left(h);
1409
1410 if (space_left < MIN_FRAME_SIZE_CRYPTO)
1411 return 1; /* no point trying */
1412
1413 /* Do we have any CRYPTO data waiting? */
1414 num_stream_iovec = OSSL_NELEM(iov);
1415 if (!ossl_quic_sstream_get_stream_frame(txp->args.crypto[pn_space],
1416 i, &shdr, iov,
1417 &num_stream_iovec))
1418 return 1; /* nothing to do */
1419
1420 /* Convert STREAM frame header to CRYPTO frame header */
1421 chdr.offset = shdr.offset;
1422 chdr.len = shdr.len;
1423
1424 if (chdr.len == 0)
1425 return 1; /* nothing to do */
1426
1427 /* Find best fit (header length, payload length) combination. */
1428 if (!determine_crypto_len(h, &chdr, space_left, &hdr_bytes,
cf06f347 1429 &chdr.len))
a73078b7 1430 return 1; /* can't fit anything */
a73078b7
HL
1431
1432 /*
1433 * Truncate IOVs to match our chosen length.
1434 *
1435 * The length cannot be more than SIZE_MAX because this length comes
1436 * from our send stream buffer.
1437 */
1438 ossl_quic_sstream_adjust_iov((size_t)chdr.len, iov, num_stream_iovec);
1439
1440 /*
1441 * Ensure we have enough iovecs allocated (1 for the header, up to 2 for
1442 * the the stream data.)
1443 */
1444 if (!txp_ensure_iovec(txp, h->num_iovec + 3))
1445 return 0; /* alloc error */
1446
1447 /* Encode the header. */
1448 wpkt = tx_helper_begin(h);
1449 if (wpkt == NULL)
1450 return 0; /* alloc error */
1451
1452 if (!ossl_quic_wire_encode_frame_crypto_hdr(wpkt, &chdr)) {
1453 tx_helper_rollback(h);
1454 return 1; /* can't fit */
1455 }
1456
1457 if (!tx_helper_commit(h))
1458 return 0; /* alloc error */
1459
1460 /* Add payload iovecs to the helper (infallible). */
1461 for (i = 0; i < num_stream_iovec; ++i)
1462 tx_helper_append_iovec(h, iov[i].buf, iov[i].buf_len);
1463
1464 *have_ack_eliciting = 1;
1465 tx_helper_unrestrict(h); /* no longer need PING */
1466
1467 /* Log chunk to TXPIM. */
1468 chunk.stream_id = UINT64_MAX; /* crypto stream */
1469 chunk.start = chdr.offset;
1470 chunk.end = chdr.offset + chdr.len - 1;
1471 chunk.has_fin = 0; /* Crypto stream never ends */
1472 if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
1473 return 0; /* alloc error */
1474 }
1475}
1476
1477struct chunk_info {
1478 OSSL_QUIC_FRAME_STREAM shdr;
1479 OSSL_QTX_IOVEC iov[2];
1480 size_t num_stream_iovec;
091f532e 1481 int valid;
a73078b7
HL
1482};
1483
1484static int txp_plan_stream_chunk(OSSL_QUIC_TX_PACKETISER *txp,
1485 struct tx_helper *h,
1486 QUIC_SSTREAM *sstream,
1487 QUIC_TXFC *stream_txfc,
1488 size_t skip,
1489 struct chunk_info *chunk)
1490{
1491 uint64_t fc_credit, fc_swm, fc_limit;
1492
1493 chunk->num_stream_iovec = OSSL_NELEM(chunk->iov);
1494 chunk->valid = ossl_quic_sstream_get_stream_frame(sstream, skip,
1495 &chunk->shdr,
1496 chunk->iov,
1497 &chunk->num_stream_iovec);
1498 if (!chunk->valid)
1499 return 1;
1500
1501 if (!ossl_assert(chunk->shdr.len > 0 || chunk->shdr.is_fin))
1502 /* Should only have 0-length chunk if FIN */
1503 return 0;
1504
1505 /* Clamp according to connection and stream-level TXFC. */
1506 fc_credit = ossl_quic_txfc_get_credit(stream_txfc);
1507 fc_swm = ossl_quic_txfc_get_swm(stream_txfc);
1508 fc_limit = fc_swm + fc_credit;
1509
1510 if (chunk->shdr.len > 0 && chunk->shdr.offset + chunk->shdr.len > fc_limit) {
1511 chunk->shdr.len = (fc_limit <= chunk->shdr.offset)
1512 ? 0 : fc_limit - chunk->shdr.offset;
1513 chunk->shdr.is_fin = 0;
1514 }
1515
1516 if (chunk->shdr.len == 0 && !chunk->shdr.is_fin) {
1517 /*
1518 * Nothing to do due to TXFC. Since SSTREAM returns chunks in ascending
1519 * order of offset we don't need to check any later chunks, so stop
1520 * iterating here.
1521 */
1522 chunk->valid = 0;
1523 return 1;
1524 }
1525
1526 return 1;
1527}
1528
1529/*
1530 * Returns 0 on fatal error (e.g. allocation failure), 1 on success.
1531 * *packet_full is set to 1 if there is no longer enough room for another STREAM
1532 * frame, and *stream_drained is set to 1 if all stream buffers have now been
1533 * sent.
1534 */
1535static int txp_generate_stream_frames(OSSL_QUIC_TX_PACKETISER *txp,
1536 struct tx_helper *h,
1537 uint32_t pn_space,
1538 QUIC_TXPIM_PKT *tpkt,
1539 uint64_t id,
1540 QUIC_SSTREAM *sstream,
1541 QUIC_TXFC *stream_txfc,
1542 QUIC_STREAM *next_stream,
1543 size_t min_ppl,
091f532e
HL
1544 int *have_ack_eliciting,
1545 int *packet_full,
1546 int *stream_drained,
a73078b7
HL
1547 uint64_t *new_credit_consumed)
1548{
1549 int rc = 0;
1550 struct chunk_info chunks[2] = {0};
1551
1552 OSSL_QUIC_FRAME_STREAM *shdr;
1553 WPACKET *wpkt;
1554 QUIC_TXPIM_CHUNK chunk;
1555 size_t i, j, space_left;
1556 int needs_padding_if_implicit, can_fill_payload, use_explicit_len;
1557 int could_have_following_chunk;
05f97354 1558 uint64_t orig_len;
a73078b7
HL
1559 uint64_t hdr_len_implicit, payload_len_implicit;
1560 uint64_t hdr_len_explicit, payload_len_explicit;
1561 uint64_t fc_swm, fc_new_hwm;
1562
1563 fc_swm = ossl_quic_txfc_get_swm(stream_txfc);
1564 fc_new_hwm = fc_swm;
1565
1566 /*
1567 * Load the first two chunks if any offered by the send stream. We retrieve
1568 * the next chunk in advance so we can determine if we need to send any more
1569 * chunks from the same stream after this one, which is needed when
1570 * determining when we can use an implicit length in a STREAM frame.
1571 */
1572 for (i = 0; i < 2; ++i) {
1573 if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i, &chunks[i]))
1574 goto err;
1575
1576 if (i == 0 && !chunks[i].valid) {
1577 /* No chunks, nothing to do. */
1578 *stream_drained = 1;
1579 rc = 1;
1580 goto err;
1581 }
1582 }
1583
1584 for (i = 0;; ++i) {
1585 space_left = tx_helper_get_space_left(h);
1586
cf06f347
HL
1587 if (!chunks[i % 2].valid) {
1588 /* Out of chunks; we're done. */
1589 *stream_drained = 1;
a73078b7
HL
1590 rc = 1;
1591 goto err;
1592 }
1593
cf06f347
HL
1594 if (space_left < MIN_FRAME_SIZE_STREAM) {
1595 *packet_full = 1;
a73078b7
HL
1596 rc = 1;
1597 goto err;
1598 }
1599
1600 if (!ossl_assert(!h->done_implicit))
1601 /*
1602 * Logic below should have ensured we didn't append an
1603 * implicit-length unless we filled the packet or didn't have
1604 * another stream to handle, so this should not be possible.
1605 */
1606 goto err;
1607
1608 shdr = &chunks[i % 2].shdr;
05f97354 1609 orig_len = shdr->len;
a73078b7
HL
1610 if (i > 0)
1611 /* Load next chunk for lookahead. */
1612 if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i + 1,
1613 &chunks[(i + 1) % 2]))
1614 goto err;
1615
1616 /*
1617 * Find best fit (header length, payload length) combination for if we
1618 * use an implicit length.
1619 */
1620 shdr->has_explicit_len = 0;
1621 hdr_len_implicit = payload_len_implicit = 0;
1622 if (!determine_stream_len(h, shdr, space_left,
cf06f347 1623 &hdr_len_implicit, &payload_len_implicit)) {
a73078b7
HL
1624 *packet_full = 1;
1625 rc = 1;
1626 goto err; /* can't fit anything */
1627 }
1628
1629 /*
1630 * If using the implicit-length representation would need padding, we
1631 * can't use it.
1632 */
1633 needs_padding_if_implicit = (h->bytes_appended + hdr_len_implicit
1634 + payload_len_implicit < min_ppl);
1635
1636 /*
1637 * If there is a next stream, we don't use the implicit length so we can
1638 * add more STREAM frames after this one, unless there is enough data
1639 * for this STREAM frame to fill the packet.
1640 */
1641 can_fill_payload = (hdr_len_implicit + payload_len_implicit
1642 >= space_left);
1643
1644 /*
1645 * Is there is a stream after this one, or another chunk pending
1646 * transmission in this stream?
1647 */
1648 could_have_following_chunk
1649 = (next_stream != NULL || chunks[(i + 1) % 2].valid);
1650
1651 /* Choose between explicit or implicit length representations. */
1652 use_explicit_len = !((can_fill_payload || !could_have_following_chunk)
1653 && !needs_padding_if_implicit);
1654
1655 if (use_explicit_len) {
1656 /*
1657 * Find best fit (header length, payload length) combination for if
1658 * we use an explicit length.
1659 */
1660 shdr->has_explicit_len = 1;
1661 hdr_len_explicit = payload_len_explicit = 0;
1662 if (!determine_stream_len(h, shdr, space_left,
cf06f347 1663 &hdr_len_explicit, &payload_len_explicit)) {
a73078b7
HL
1664 *packet_full = 1;
1665 rc = 1;
1666 goto err; /* can't fit anything */
1667 }
1668
1669 shdr->len = payload_len_explicit;
1670 } else {
1671 shdr->has_explicit_len = 0;
1672 shdr->len = payload_len_implicit;
1673 }
1674
cf06f347
HL
1675 /* If this is a FIN, don't keep filling the packet with more FINs. */
1676 if (shdr->is_fin)
1677 chunks[(i + 1) % 2].valid = 0;
1678
a73078b7
HL
1679 /* Truncate IOVs to match our chosen length. */
1680 ossl_quic_sstream_adjust_iov((size_t)shdr->len, chunks[i % 2].iov,
1681 chunks[i % 2].num_stream_iovec);
1682
1683 /*
1684 * Ensure we have enough iovecs allocated (1 for the header, up to 2 for
1685 * the the stream data.)
1686 */
1687 if (!txp_ensure_iovec(txp, h->num_iovec + 3))
1688 goto err; /* alloc error */
1689
1690 /* Encode the header. */
1691 wpkt = tx_helper_begin(h);
1692 if (wpkt == NULL)
1693 goto err; /* alloc error */
1694
1695 shdr->stream_id = id;
1696 if (!ossl_assert(ossl_quic_wire_encode_frame_stream_hdr(wpkt, shdr))) {
1697 /* (Should not be possible.) */
1698 tx_helper_rollback(h);
1699 *packet_full = 1;
1700 rc = 1;
1701 goto err; /* can't fit */
1702 }
1703
1704 if (!tx_helper_commit(h))
1705 goto err; /* alloc error */
1706
1707 /* Add payload iovecs to the helper (infallible). */
1708 for (j = 0; j < chunks[i % 2].num_stream_iovec; ++j)
1709 tx_helper_append_iovec(h, chunks[i % 2].iov[j].buf,
1710 chunks[i % 2].iov[j].buf_len);
1711
1712 *have_ack_eliciting = 1;
1713 tx_helper_unrestrict(h); /* no longer need PING */
1714 if (!shdr->has_explicit_len)
1715 h->done_implicit = 1;
1716
1717 /* Log new TXFC credit which was consumed. */
1718 if (shdr->len > 0 && shdr->offset + shdr->len > fc_new_hwm)
1719 fc_new_hwm = shdr->offset + shdr->len;
1720
1721 /* Log chunk to TXPIM. */
1722 chunk.stream_id = shdr->stream_id;
1723 chunk.start = shdr->offset;
1724 chunk.end = shdr->offset + shdr->len - 1;
1725 chunk.has_fin = shdr->is_fin;
1726 chunk.has_stop_sending = 0;
1727 chunk.has_reset_stream = 0;
1728 if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
1729 goto err; /* alloc error */
05f97354
HL
1730
1731 if (shdr->len < orig_len) {
1732 /*
1733 * If we did not serialize all of this chunk we definitely do not
1734 * want to try the next chunk (and we must not mark the stream
1735 * as drained).
1736 */
1737 rc = 1;
1738 goto err;
1739 }
a73078b7
HL
1740 }
1741
1742err:
1743 *new_credit_consumed = fc_new_hwm - fc_swm;
1744 return rc;
1745}
1746
1747static void txp_enlink_tmp(QUIC_STREAM **tmp_head, QUIC_STREAM *stream)
1748{
1749 stream->txp_next = *tmp_head;
1750 *tmp_head = stream;
1751}
1752
1753static int txp_generate_stream_related(OSSL_QUIC_TX_PACKETISER *txp,
1754 struct tx_helper *h,
1755 uint32_t pn_space,
1756 QUIC_TXPIM_PKT *tpkt,
1757 size_t min_ppl,
091f532e 1758 int *have_ack_eliciting,
a73078b7
HL
1759 QUIC_STREAM **tmp_head)
1760{
1761 QUIC_STREAM_ITER it;
1762 void *rstream;
1763 WPACKET *wpkt;
1764 uint64_t cwm;
1765 QUIC_STREAM *stream, *snext;
1766
1767 for (ossl_quic_stream_iter_init(&it, txp->args.qsm, 1);
1768 it.stream != NULL;) {
1769
1770 stream = it.stream;
1771 ossl_quic_stream_iter_next(&it);
1772 snext = it.stream;
1773
1774 stream->txp_sent_fc = 0;
1775 stream->txp_sent_stop_sending = 0;
1776 stream->txp_sent_reset_stream = 0;
1777 stream->txp_drained = 0;
1778 stream->txp_blocked = 0;
1779 stream->txp_txfc_new_credit_consumed = 0;
1780
1781 rstream = stream->rstream;
1782
1783 /* Stream Abort Frames (STOP_SENDING, RESET_STREAM) */
1784 if (stream->want_stop_sending) {
1785 OSSL_QUIC_FRAME_STOP_SENDING f;
1786
1787 wpkt = tx_helper_begin(h);
1788 if (wpkt == NULL)
1789 return 0; /* alloc error */
1790
1791 f.stream_id = stream->id;
1792 f.app_error_code = stream->stop_sending_aec;
1793 if (!ossl_quic_wire_encode_frame_stop_sending(wpkt, &f)) {
1794 tx_helper_rollback(h); /* can't fit */
1795 txp_enlink_tmp(tmp_head, stream);
1796 break;
1797 }
1798
1799 if (!tx_helper_commit(h))
1800 return 0; /* alloc error */
1801
1802 *have_ack_eliciting = 1;
1803 tx_helper_unrestrict(h); /* no longer need PING */
1804 stream->txp_sent_stop_sending = 1;
1805 }
1806
1807 if (stream->want_reset_stream) {
1808 OSSL_QUIC_FRAME_RESET_STREAM f;
1809
1810 wpkt = tx_helper_begin(h);
1811 if (wpkt == NULL)
1812 return 0; /* alloc error */
1813
1814 f.stream_id = stream->id;
1815 f.app_error_code = stream->reset_stream_aec;
1816 f.final_size = ossl_quic_sstream_get_cur_size(stream->sstream);
1817 if (!ossl_quic_wire_encode_frame_reset_stream(wpkt, &f)) {
1818 tx_helper_rollback(h); /* can't fit */
1819 txp_enlink_tmp(tmp_head, stream);
1820 break;
1821 }
1822
1823 if (!tx_helper_commit(h))
1824 return 0; /* alloc error */
1825
1826 *have_ack_eliciting = 1;
1827 tx_helper_unrestrict(h); /* no longer need PING */
1828 stream->txp_sent_reset_stream = 1;
1829 }
1830
1831 /* Stream Flow Control Frames (MAX_STREAM_DATA) */
1832 if (rstream != NULL
1833 && (stream->want_max_stream_data
1834 || ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 0))) {
1835
1836 wpkt = tx_helper_begin(h);
1837 if (wpkt == NULL)
1838 return 0; /* alloc error */
1839
1840 cwm = ossl_quic_rxfc_get_cwm(&stream->rxfc);
1841
1842 if (!ossl_quic_wire_encode_frame_max_stream_data(wpkt, stream->id,
1843 cwm)) {
1844 tx_helper_rollback(h); /* can't fit */
1845 txp_enlink_tmp(tmp_head, stream);
1846 break;
1847 }
1848
1849 if (!tx_helper_commit(h))
1850 return 0; /* alloc error */
1851
1852 *have_ack_eliciting = 1;
1853 tx_helper_unrestrict(h); /* no longer need PING */
1854 stream->txp_sent_fc = 1;
1855 }
1856
1857 /* Stream Data Frames (STREAM) */
1858 if (stream->sstream != NULL) {
091f532e 1859 int packet_full = 0, stream_drained = 0;
a73078b7
HL
1860
1861 if (!txp_generate_stream_frames(txp, h, pn_space, tpkt,
1862 stream->id, stream->sstream,
1863 &stream->txfc,
1864 snext, min_ppl,
1865 have_ack_eliciting,
1866 &packet_full,
1867 &stream_drained,
1868 &stream->txp_txfc_new_credit_consumed)) {
1869 /* Fatal error (allocation, etc.) */
1870 txp_enlink_tmp(tmp_head, stream);
1871 return 0;
1872 }
1873
1874 if (stream_drained)
1875 stream->txp_drained = 1;
1876
1877 if (packet_full) {
1878 txp_enlink_tmp(tmp_head, stream);
1879 break;
1880 }
1881 }
1882
1883 txp_enlink_tmp(tmp_head, stream);
1884 }
1885
1886 return 1;
1887}
1888
1889/*
1890 * Generates a packet for a given EL with the given minimum and maximum
1891 * plaintext packet payload lengths. Returns TXP_ERR_* value.
1892 */
1893static int txp_generate_for_el_actual(OSSL_QUIC_TX_PACKETISER *txp,
1894 uint32_t enc_level,
1895 uint32_t archetype,
1896 size_t min_ppl,
1897 size_t max_ppl,
1898 size_t pkt_overhead,
7f9d1249 1899 QUIC_PKT_HDR *phdr,
134b79c0 1900 int chosen_for_conn_close,
a3a51d6e 1901 QUIC_TXP_STATUS *status)
a73078b7
HL
1902{
1903 int rc = TXP_ERR_SUCCESS;
1904 struct archetype_data a;
1905 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
1906 struct tx_helper h;
091f532e 1907 int have_helper = 0, have_ack_eliciting = 0, done_pre_token = 0;
fee8f48e 1908 int require_ack_eliciting = 0;
a73078b7
HL
1909 QUIC_CFQ_ITEM *cfq_item;
1910 QUIC_TXPIM_PKT *tpkt = NULL;
1911 OSSL_QTX_PKT pkt;
1912 QUIC_STREAM *tmp_head = NULL, *stream;
fee8f48e 1913 OSSL_ACKM_PROBE_INFO *probe_info
2477e99f 1914 = ossl_ackm_get0_probe_request(txp->args.ackm);
a73078b7
HL
1915
1916 if (!txp_get_archetype_data(enc_level, archetype, &a))
1917 goto fatal_err;
1918
fee8f48e
HL
1919 if (a.allow_force_ack_eliciting) {
1920 /*
1921 * Make this packet ACK-eliciting if it has been explicitly requested,
1922 * or if ACKM has requested a probe for this PN space.
1923 */
1924 if ((txp->force_ack_eliciting & (1UL << pn_space)) != 0
1925 || (enc_level == QUIC_ENC_LEVEL_INITIAL
1926 && probe_info->anti_deadlock_initial > 0)
1927 || (enc_level == QUIC_ENC_LEVEL_HANDSHAKE
1928 && probe_info->anti_deadlock_handshake > 0)
1929 || probe_info->pto[pn_space] > 0)
1930 require_ack_eliciting = 1;
1931 }
a73078b7
HL
1932
1933 /* Minimum cannot be bigger than maximum. */
1934 if (min_ppl > max_ppl)
1935 goto fatal_err;
1936
1937 /* Maximum PN reached? */
b65b0d4e 1938 if (!ossl_quic_pn_valid(txp->next_pn[pn_space]))
a73078b7
HL
1939 goto fatal_err;
1940
1941 if ((tpkt = ossl_quic_txpim_pkt_alloc(txp->args.txpim)) == NULL)
1942 goto fatal_err;
1943
1944 /*
1945 * Initialise TX helper. If we must be ACK eliciting, reserve 1 byte for
1946 * PING.
1947 */
1948 if (!tx_helper_init(&h, txp, max_ppl, require_ack_eliciting ? 1 : 0))
1949 goto fatal_err;
1950
1951 have_helper = 1;
1952
1953 /*
1954 * Frame Serialization
1955 * ===================
1956 *
1957 * We now serialize frames into the packet in descending order of priority.
1958 */
1959
1960 /* HANDSHAKE_DONE (Regenerate) */
1961 if (a.allow_handshake_done && txp->want_handshake_done
1962 && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_HANDSHAKE_DONE) {
1963 WPACKET *wpkt = tx_helper_begin(&h);
1964
1965 if (wpkt == NULL)
1966 goto fatal_err;
1967
1968 if (ossl_quic_wire_encode_frame_handshake_done(wpkt)) {
1969 tpkt->had_handshake_done_frame = 1;
1970 have_ack_eliciting = 1;
1971
1972 if (!tx_helper_commit(&h))
1973 goto fatal_err;
1974
1975 tx_helper_unrestrict(&h); /* no longer need PING */
1976 } else {
1977 tx_helper_rollback(&h);
1978 }
1979 }
1980
1981 /* MAX_DATA (Regenerate) */
1982 if (a.allow_conn_fc
1983 && (txp->want_max_data
1984 || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0))
1985 && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_MAX_DATA) {
1986 WPACKET *wpkt = tx_helper_begin(&h);
1987 uint64_t cwm = ossl_quic_rxfc_get_cwm(txp->args.conn_rxfc);
1988
1989 if (wpkt == NULL)
1990 goto fatal_err;
1991
1992 if (ossl_quic_wire_encode_frame_max_data(wpkt, cwm)) {
1993 tpkt->had_max_data_frame = 1;
1994 have_ack_eliciting = 1;
1995
1996 if (!tx_helper_commit(&h))
1997 goto fatal_err;
1998
1999 tx_helper_unrestrict(&h); /* no longer need PING */
2000 } else {
2001 tx_helper_rollback(&h);
2002 }
2003 }
2004
2005 /* MAX_STREAMS_BIDI (Regenerate) */
a73078b7 2006 if (a.allow_conn_fc
a6b6ea17
HL
2007 && (txp->want_max_streams_bidi
2008 || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 0))
a73078b7
HL
2009 && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_MAX_STREAMS_BIDI) {
2010 WPACKET *wpkt = tx_helper_begin(&h);
a6b6ea17
HL
2011 uint64_t max_streams
2012 = ossl_quic_rxfc_get_cwm(txp->args.max_streams_bidi_rxfc);
a73078b7
HL
2013
2014 if (wpkt == NULL)
2015 goto fatal_err;
2016
2017 if (ossl_quic_wire_encode_frame_max_streams(wpkt, /*is_uni=*/0,
2018 max_streams)) {
2019 tpkt->had_max_streams_bidi_frame = 1;
2020 have_ack_eliciting = 1;
2021
2022 if (!tx_helper_commit(&h))
2023 goto fatal_err;
2024
2025 tx_helper_unrestrict(&h); /* no longer need PING */
2026 } else {
2027 tx_helper_rollback(&h);
2028 }
2029 }
2030
2031 /* MAX_STREAMS_UNI (Regenerate) */
2032 if (a.allow_conn_fc
a6b6ea17
HL
2033 && (txp->want_max_streams_uni
2034 || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 0))
a73078b7
HL
2035 && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_MAX_STREAMS_UNI) {
2036 WPACKET *wpkt = tx_helper_begin(&h);
a6b6ea17
HL
2037 uint64_t max_streams
2038 = ossl_quic_rxfc_get_cwm(txp->args.max_streams_uni_rxfc);
a73078b7
HL
2039
2040 if (wpkt == NULL)
2041 goto fatal_err;
2042
2043 if (ossl_quic_wire_encode_frame_max_streams(wpkt, /*is_uni=*/1,
2044 max_streams)) {
2045 tpkt->had_max_streams_uni_frame = 1;
2046 have_ack_eliciting = 1;
2047
2048 if (!tx_helper_commit(&h))
2049 goto fatal_err;
2050
2051 tx_helper_unrestrict(&h); /* no longer need PING */
2052 } else {
2053 tx_helper_rollback(&h);
2054 }
2055 }
2056
2057 /* GCR Frames */
2058 for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space);
2059 cfq_item != NULL;
2060 cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) {
2061 uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item);
2062 const unsigned char *encoded = ossl_quic_cfq_item_get_encoded(cfq_item);
2063 size_t encoded_len = ossl_quic_cfq_item_get_encoded_len(cfq_item);
2064
2065 switch (frame_type) {
2066 case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID:
2067 if (!a.allow_new_conn_id)
2068 continue;
2069 break;
2070 case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID:
2071 if (!a.allow_retire_conn_id)
2072 continue;
2073 break;
2074 case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN:
2075 if (!a.allow_new_token)
2076 continue;
2077
2078 /*
2079 * NEW_TOKEN frames are handled via GCR, but some
2080 * Regenerate-strategy frames should come before them (namely
2081 * ACK, CONNECTION_CLOSE, PATH_CHALLENGE and PATH_RESPONSE). If
2082 * we find a NEW_TOKEN frame, do these now. If there are no
2083 * NEW_TOKEN frames in the GCR queue we will handle these below.
2084 */
2085 if (!done_pre_token)
7f9d1249
HL
2086 if (txp_generate_pre_token(txp, &h, tpkt, pn_space, &a,
2087 chosen_for_conn_close))
a73078b7
HL
2088 done_pre_token = 1;
2089
2090 break;
2091 default:
2092 if (!a.allow_cfq_other)
2093 continue;
2094 break;
2095 }
2096
2097 /*
2098 * If the frame is too big, don't try to schedule any more GCR frames in
2099 * this packet rather than sending subsequent ones out of order.
2100 */
2101 if (encoded_len > tx_helper_get_space_left(&h))
2102 break;
2103
2104 if (!tx_helper_append_iovec(&h, encoded, encoded_len))
2105 goto fatal_err;
2106
2107 ossl_quic_txpim_pkt_add_cfq_item(tpkt, cfq_item);
2108
2109 if (ossl_quic_frame_type_is_ack_eliciting(frame_type)) {
2110 have_ack_eliciting = 1;
2111 tx_helper_unrestrict(&h); /* no longer need PING */
2112 }
2113 }
2114
2115 /*
2116 * If we didn't generate ACK, CONNECTION_CLOSE, PATH_CHALLENGE or
2117 * PATH_RESPONSE (as desired) before, do so now.
2118 */
2119 if (!done_pre_token)
7f9d1249
HL
2120 if (txp_generate_pre_token(txp, &h, tpkt, pn_space, &a,
2121 chosen_for_conn_close))
a73078b7
HL
2122 done_pre_token = 1;
2123
2124 /* CRYPTO Frames */
2125 if (a.allow_crypto)
2126 if (!txp_generate_crypto_frames(txp, &h, pn_space, tpkt,
2127 &have_ack_eliciting))
2128 goto fatal_err;
2129
2130 /* Stream-specific frames */
cda88baf 2131 if (a.allow_stream_rel && txp->handshake_complete)
a73078b7
HL
2132 if (!txp_generate_stream_related(txp, &h, pn_space, tpkt, min_ppl,
2133 &have_ack_eliciting,
2134 &tmp_head))
2135 goto fatal_err;
2136
2137 /* PING */
2138 tx_helper_unrestrict(&h);
2139
2140 if (require_ack_eliciting && !have_ack_eliciting && a.allow_ping) {
2141 WPACKET *wpkt;
2142
2143 wpkt = tx_helper_begin(&h);
2144 if (wpkt == NULL)
2145 goto fatal_err;
2146
2147 if (!ossl_quic_wire_encode_frame_ping(wpkt)
2148 || !tx_helper_commit(&h))
2149 /*
2150 * We treat a request to be ACK-eliciting as a requirement, so this
2151 * is an error.
2152 */
2153 goto fatal_err;
2154
2155 have_ack_eliciting = 1;
2156 }
2157
2158 /* PADDING */
2159 if (h.bytes_appended < min_ppl) {
2160 WPACKET *wpkt = tx_helper_begin(&h);
2161 if (wpkt == NULL)
2162 goto fatal_err;
2163
2164 if (!ossl_quic_wire_encode_padding(wpkt, min_ppl - h.bytes_appended)
2165 || !tx_helper_commit(&h))
2166 goto fatal_err;
2167 }
2168
2169 /*
2170 * Dispatch
2171 * ========
2172 */
2173 /* ACKM Data */
2174 tpkt->ackm_pkt.num_bytes = h.bytes_appended + pkt_overhead;
2175 tpkt->ackm_pkt.pkt_num = txp->next_pn[pn_space];
2176 /* largest_acked is set in txp_generate_pre_token */
2177 tpkt->ackm_pkt.pkt_space = pn_space;
2178 tpkt->ackm_pkt.is_inflight = 1;
2179 tpkt->ackm_pkt.is_ack_eliciting = have_ack_eliciting;
2180 tpkt->ackm_pkt.is_pto_probe = 0;
2181 tpkt->ackm_pkt.is_mtu_probe = 0;
2182 tpkt->ackm_pkt.time = ossl_time_now();
2183
2184 /* Packet Information for QTX */
2185 pkt.hdr = phdr;
2186 pkt.iovec = txp->iovec;
2187 pkt.num_iovec = h.num_iovec;
2188 pkt.local = NULL;
2189 pkt.peer = BIO_ADDR_family(&txp->args.peer) == AF_UNSPEC
2190 ? NULL : &txp->args.peer;
2191 pkt.pn = txp->next_pn[pn_space];
2192 pkt.flags = OSSL_QTX_PKT_FLAG_COALESCE; /* always try to coalesce */
2193
a73078b7
HL
2194 if (!ossl_assert(h.bytes_appended > 0))
2195 goto fatal_err;
2196
2197 /* Generate TXPIM chunks representing STOP_SENDING and RESET_STREAM frames. */
2198 for (stream = tmp_head; stream != NULL; stream = stream->txp_next)
2199 if (stream->txp_sent_stop_sending || stream->txp_sent_reset_stream) {
2200 /* Log STOP_SENDING chunk to TXPIM. */
2201 QUIC_TXPIM_CHUNK chunk;
2202
2203 chunk.stream_id = stream->id;
2204 chunk.start = UINT64_MAX;
2205 chunk.end = 0;
2206 chunk.has_fin = 0;
2207 chunk.has_stop_sending = stream->txp_sent_stop_sending;
2208 chunk.has_reset_stream = stream->txp_sent_reset_stream;
2209 if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
2210 return 0; /* alloc error */
2211 }
2212
2213 /* Dispatch to FIFD. */
2214 if (!ossl_quic_fifd_pkt_commit(&txp->fifd, tpkt))
2215 goto fatal_err;
2216
2217 /* Send the packet. */
2218 if (!ossl_qtx_write_pkt(txp->args.qtx, &pkt))
2219 goto fatal_err;
2220
2221 ++txp->next_pn[pn_space];
2222
2223 /*
2224 * Record FC and stream abort frames as sent; deactivate streams which no
2225 * longer have anything to do.
2226 */
2227 for (stream = tmp_head; stream != NULL; stream = stream->txp_next) {
2228 if (stream->txp_sent_fc) {
2229 stream->want_max_stream_data = 0;
2230 ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 1);
2231 }
2232
2233 if (stream->txp_sent_stop_sending)
2234 stream->want_stop_sending = 0;
2235
2236 if (stream->txp_sent_reset_stream)
2237 stream->want_reset_stream = 0;
2238
2239 if (stream->txp_txfc_new_credit_consumed > 0) {
2240 if (!ossl_assert(ossl_quic_txfc_consume_credit(&stream->txfc,
2241 stream->txp_txfc_new_credit_consumed)))
2242 /*
2243 * Should not be possible, but we should continue with our
2244 * bookkeeping as we have already committed the packet to the
2245 * FIFD. Just change the value we return.
2246 */
2247 rc = TXP_ERR_INTERNAL;
2248
2249 stream->txp_txfc_new_credit_consumed = 0;
2250 }
2251
2252 /*
2253 * If we no longer need to generate any flow control (MAX_STREAM_DATA),
2254 * STOP_SENDING or RESET_STREAM frames, nor any STREAM frames (because
2255 * the stream is drained of data or TXFC-blocked), we can mark the
2256 * stream as inactive.
2257 */
2258 ossl_quic_stream_map_update_state(txp->args.qsm, stream);
2259
05f97354
HL
2260 if (stream->txp_drained)
2261 assert(!ossl_quic_sstream_has_pending(stream->sstream));
a73078b7
HL
2262 }
2263
2264 /* We have now sent the packet, so update state accordingly. */
2265 if (have_ack_eliciting)
2266 txp->force_ack_eliciting &= ~(1UL << pn_space);
2267
2268 if (tpkt->had_handshake_done_frame)
2269 txp->want_handshake_done = 0;
2270
2271 if (tpkt->had_max_data_frame) {
2272 txp->want_max_data = 0;
2273 ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 1);
2274 }
2275
a6b6ea17 2276 if (tpkt->had_max_streams_bidi_frame) {
a73078b7 2277 txp->want_max_streams_bidi = 0;
a6b6ea17
HL
2278 ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 1);
2279 }
a73078b7 2280
a6b6ea17 2281 if (tpkt->had_max_streams_uni_frame) {
a73078b7 2282 txp->want_max_streams_uni = 0;
a6b6ea17
HL
2283 ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 1);
2284 }
a73078b7
HL
2285
2286 if (tpkt->had_ack_frame)
2287 txp->want_ack &= ~(1UL << pn_space);
2288
fee8f48e
HL
2289 /*
2290 * Decrement probe request counts if we have sent a packet that meets
2291 * the requirement of a probe, namely being ACK-eliciting.
2292 */
2293 if (have_ack_eliciting) {
2294 if (enc_level == QUIC_ENC_LEVEL_INITIAL
2295 && probe_info->anti_deadlock_initial > 0)
2296 --probe_info->anti_deadlock_initial;
2297
2298 if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE
2299 && probe_info->anti_deadlock_handshake > 0)
2300 --probe_info->anti_deadlock_handshake;
2301
2302 if (a.allow_force_ack_eliciting /* (i.e., not for 0-RTT) */
2303 && probe_info->pto[pn_space] > 0)
2304 --probe_info->pto[pn_space];
2305 }
2306
a3a51d6e 2307 status->sent_ack_eliciting = 1;
134b79c0 2308
a73078b7
HL
2309 /* Done. */
2310 tx_helper_cleanup(&h);
2311 return rc;
2312
2313fatal_err:
2314 /*
2315 * Handler for fatal errors, i.e. errors causing us to abort the entire
2316 * packet rather than just one frame. Examples of such errors include
2317 * allocation errors.
2318 */
2319 if (have_helper)
2320 tx_helper_cleanup(&h);
2321 if (tpkt != NULL)
2322 ossl_quic_txpim_pkt_release(txp->args.txpim, tpkt);
2323 return TXP_ERR_INTERNAL;
2324}
2325
2326/* Ensure the iovec array is at least num elements long. */
2327static int txp_ensure_iovec(OSSL_QUIC_TX_PACKETISER *txp, size_t num)
2328{
2329 OSSL_QTX_IOVEC *iovec;
2330
2331 if (txp->alloc_iovec >= num)
2332 return 1;
2333
2334 num = txp->alloc_iovec != 0 ? txp->alloc_iovec * 2 : 8;
2335
2336 iovec = OPENSSL_realloc(txp->iovec, sizeof(OSSL_QTX_IOVEC) * num);
2337 if (iovec == NULL)
2338 return 0;
2339
2340 txp->iovec = iovec;
2341 txp->alloc_iovec = num;
2342 return 1;
2343}
2344
2345int ossl_quic_tx_packetiser_schedule_conn_close(OSSL_QUIC_TX_PACKETISER *txp,
2346 const OSSL_QUIC_FRAME_CONN_CLOSE *f)
2347{
2348 char *reason = NULL;
2349 size_t reason_len = f->reason_len;
2350 size_t max_reason_len = txp_get_mdpl(txp) / 2;
2351
2352 if (txp->want_conn_close)
2353 return 0;
2354
2355 /*
2356 * Arbitrarily limit the length of the reason length string to half of the
2357 * MDPL.
2358 */
2359 if (reason_len > max_reason_len)
2360 reason_len = max_reason_len;
2361
2362 if (reason_len > 0) {
2363 reason = OPENSSL_memdup(f->reason, reason_len);
2364 if (reason == NULL)
2365 return 0;
2366 }
2367
2368 txp->conn_close_frame = *f;
2369 txp->conn_close_frame.reason = reason;
2370 txp->conn_close_frame.reason_len = reason_len;
2371 txp->want_conn_close = 1;
2372 return 1;
2373}
5cf99b40
MC
2374
2375void ossl_quic_tx_packetiser_set_msg_callback(OSSL_QUIC_TX_PACKETISER *txp,
2376 ossl_msg_cb msg_callback,
c2786c8e 2377 SSL *msg_callback_ssl)
5cf99b40
MC
2378{
2379 txp->msg_callback = msg_callback;
c2786c8e 2380 txp->msg_callback_ssl = msg_callback_ssl;
5cf99b40
MC
2381}
2382
2383void ossl_quic_tx_packetiser_set_msg_callback_arg(OSSL_QUIC_TX_PACKETISER *txp,
2384 void *msg_callback_arg)
2385{
2386 txp->msg_callback_arg = msg_callback_arg;
2387}