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