QUIC TXP: Do not generate full-size packets when sending CC-excess probes
[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_AND_PING_ONLY) */
665         {
666             /*allow_ack                       =*/ 1,
667             /*allow_ping                      =*/ 1,
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_AND_PING_ONLY) */
702         {
703             /*allow_ack                       =*/ 1,
704             /*allow_ping                      =*/ 1,
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_AND_PING_ONLY) */
739         {
740             /*allow_ack                       =*/ 0,
741             /*allow_ping                      =*/ 1,
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_AND_PING_ONLY) */
776         {
777             /*allow_ack                       =*/ 1,
778             /*allow_ping                      =*/ 1,
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 to
1003          * generate a probe. In this circumstance, don't clamp based on CC, but
1004          * don't add application data and limit ourselves to generating a small
1005          * packet containing only PING and ACK frames.
1006          */
1007         cc_limit  = SIZE_MAX;
1008         archetype = TX_PACKETISER_ARCHETYPE_ACK_AND_PING_ONLY;
1009     } else {
1010         /* Allow CC to clamp how much we can send. */
1011         cc_limit_ = txp->args.cc_method->get_tx_allowance(txp->args.cc_data);
1012         cc_limit = (cc_limit_ > SIZE_MAX ? SIZE_MAX : (size_t)cc_limit_);
1013     }
1014
1015     /* Assemble packet header. */
1016     phdr.type           = ossl_quic_enc_level_to_pkt_type(enc_level);
1017     phdr.spin_bit       = 0;
1018     phdr.pn_len         = txp_determine_pn_len(txp);
1019     phdr.partial        = 0;
1020     phdr.fixed          = 1;
1021     phdr.reserved       = 0;
1022     phdr.version        = QUIC_VERSION_1;
1023     phdr.dst_conn_id    = txp->args.cur_dcid;
1024     phdr.src_conn_id    = txp->args.cur_scid;
1025
1026     /*
1027      * We need to know the length of the payload to get an accurate header
1028      * length for non-1RTT packets, because the Length field found in
1029      * Initial/Handshake/0-RTT packets uses a variable-length encoding. However,
1030      * we don't have a good idea of the length of our payload, because the
1031      * length of the payload depends on the room in the datagram after fitting
1032      * the header, which depends on the size of the header.
1033      *
1034      * In general, it does not matter if a packet is slightly shorter (because
1035      * e.g. we predicted use of a 2-byte length field, but ended up only needing
1036      * a 1-byte length field). However this does matter for Initial packets
1037      * which must be at least 1200 bytes, which is also the assumed default MTU;
1038      * therefore in many cases Initial packets will be padded to 1200 bytes,
1039      * which means if we overestimated the header size, we will be short by a
1040      * few bytes and the server will ignore the packet for being too short. In
1041      * this case, however, such packets always *will* be padded to meet 1200
1042      * bytes, which requires a 2-byte length field, so we don't actually need to
1043      * worry about this. Thus we estimate the header length assuming a 2-byte
1044      * length field here, which should in practice work well in all cases.
1045      */
1046     phdr.len            = OSSL_QUIC_VLINT_2B_MAX - phdr.pn_len;
1047
1048     if (enc_level == QUIC_ENC_LEVEL_INITIAL) {
1049         phdr.token      = txp->initial_token;
1050         phdr.token_len  = txp->initial_token_len;
1051     } else {
1052         phdr.token      = NULL;
1053         phdr.token_len  = 0;
1054     }
1055
1056     hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(phdr.dst_conn_id.id_len,
1057                                                      &phdr);
1058     if (hdr_len == 0)
1059         return TXP_ERR_INPUT;
1060
1061     /* MinDPL: Minimum total datagram payload length. */
1062     min_dpl = must_pad ? QUIC_MIN_INITIAL_DGRAM_LEN : 0;
1063
1064     /* How much data is already in the current datagram? */
1065     running_total = ossl_qtx_get_cur_dgram_len_bytes(txp->args.qtx);
1066
1067     /* MinPL: Minimum length of the fully encoded packet. */
1068     min_pl = running_total < min_dpl ? min_dpl - running_total : 0;
1069     if ((uint64_t)min_pl > cc_limit)
1070         /*
1071          * Congestion control does not allow us to send a packet of adequate
1072          * size.
1073          */
1074         return TXP_ERR_SPACE;
1075
1076     /* MinPPL: Minimum plaintext payload length needed to meet MinPL. */
1077     if (!txp_determine_ppl_from_pl(txp, min_pl, enc_level, hdr_len, &min_ppl))
1078         /* MinPL is less than a valid packet size, so just use a MinPPL of 0. */
1079         min_ppl = 0;
1080
1081     /* MDPL: Maximum datagram payload length. */
1082     mdpl = txp_get_mdpl(txp);
1083
1084     /*
1085      * CMPL: Maximum encoded packet size we can put into this datagram given any
1086      * previous packets coalesced into it.
1087      */
1088     if (running_total > mdpl)
1089         /* Should not be possible, but if it happens: */
1090         cmpl = 0;
1091     else
1092         cmpl = mdpl - running_total;
1093
1094     /* Clamp CMPL based on congestion control limit. */
1095     if (cmpl > cc_limit)
1096         cmpl = cc_limit;
1097
1098     /* CMPPL: Maximum amount we can put into the current datagram payload. */
1099     if (!txp_determine_ppl_from_pl(txp, cmpl, enc_level, hdr_len, &cmppl))
1100         return TXP_ERR_SPACE;
1101
1102     /* Packet overhead (size of headers, AEAD tag, etc.) */
1103     pkt_overhead = cmpl - cmppl;
1104
1105     return txp_generate_for_el_actual(txp, enc_level, archetype, min_ppl, cmppl,
1106                                       pkt_overhead, &phdr,
1107                                       chosen_for_conn_close,
1108                                       status);
1109 }
1110
1111 /* Determine how many bytes we should use for the encoded PN. */
1112 static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp)
1113 {
1114     return 4; /* TODO(QUIC) */
1115 }
1116
1117 /* Determine plaintext packet payload length from payload length. */
1118 static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp,
1119                                      size_t pl,
1120                                      uint32_t enc_level,
1121                                      size_t hdr_len,
1122                                      size_t *r)
1123 {
1124     if (pl < hdr_len)
1125         return 0;
1126
1127     pl -= hdr_len;
1128
1129     if (!ossl_qtx_calculate_plaintext_payload_len(txp->args.qtx, enc_level,
1130                                                   pl, &pl))
1131         return 0;
1132
1133     *r = pl;
1134     return 1;
1135 }
1136
1137 static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp)
1138 {
1139     return ossl_qtx_get_mdpl(txp->args.qtx);
1140 }
1141
1142 static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space,
1143                                        void *arg)
1144 {
1145     OSSL_QUIC_TX_PACKETISER *txp = arg;
1146     QUIC_STREAM *s;
1147
1148     if (stream_id == UINT64_MAX)
1149         return txp->args.crypto[pn_space];
1150
1151     s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1152     if (s == NULL)
1153         return NULL;
1154
1155     return s->sstream;
1156 }
1157
1158 static void on_regen_notify(uint64_t frame_type, uint64_t stream_id,
1159                             QUIC_TXPIM_PKT *pkt, void *arg)
1160 {
1161     OSSL_QUIC_TX_PACKETISER *txp = arg;
1162
1163     switch (frame_type) {
1164         case OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE:
1165             txp->want_handshake_done = 1;
1166             break;
1167         case OSSL_QUIC_FRAME_TYPE_MAX_DATA:
1168             txp->want_max_data = 1;
1169             break;
1170         case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI:
1171             txp->want_max_streams_bidi = 1;
1172             break;
1173         case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI:
1174             txp->want_max_streams_uni = 1;
1175             break;
1176         case OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN:
1177             txp->want_ack |= (1UL << pkt->ackm_pkt.pkt_space);
1178             break;
1179         case OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA:
1180             {
1181                 QUIC_STREAM *s
1182                     = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1183
1184                 if (s == NULL)
1185                     return;
1186
1187                 s->want_max_stream_data = 1;
1188                 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1189             }
1190             break;
1191         case OSSL_QUIC_FRAME_TYPE_STOP_SENDING:
1192             {
1193                 QUIC_STREAM *s
1194                     = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1195
1196                 if (s == NULL)
1197                     return;
1198
1199                 ossl_quic_stream_map_schedule_stop_sending(txp->args.qsm, s);
1200             }
1201             break;
1202         case OSSL_QUIC_FRAME_TYPE_RESET_STREAM:
1203             {
1204                 QUIC_STREAM *s
1205                     = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1206
1207                 if (s == NULL)
1208                     return;
1209
1210                 s->want_reset_stream = 1;
1211                 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1212             }
1213             break;
1214         default:
1215             assert(0);
1216             break;
1217     }
1218 }
1219
1220 static void on_confirm_notify(uint64_t frame_type, uint64_t stream_id,
1221                               QUIC_TXPIM_PKT *pkt, void *arg)
1222 {
1223     OSSL_QUIC_TX_PACKETISER *txp = arg;
1224
1225     switch (frame_type) {
1226         case OSSL_QUIC_FRAME_TYPE_STOP_SENDING:
1227             {
1228                 QUIC_STREAM *s
1229                     = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1230
1231                 if (s == NULL)
1232                     return;
1233
1234                 s->acked_stop_sending = 1;
1235                 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1236             }
1237             break;
1238         case OSSL_QUIC_FRAME_TYPE_RESET_STREAM:
1239             {
1240                 QUIC_STREAM *s
1241                     = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1242
1243                 if (s == NULL)
1244                     return;
1245
1246                 /*
1247                  * We must already be in RESET_SENT or RESET_RECVD if we are
1248                  * here, so we don't need to check state here.
1249                  */
1250                 ossl_quic_stream_map_notify_reset_stream_acked(txp->args.qsm, s);
1251                 ossl_quic_stream_map_update_state(txp->args.qsm, s);
1252             }
1253             break;
1254         default:
1255             assert(0);
1256             break;
1257     }
1258 }
1259
1260 static void on_sstream_updated(uint64_t stream_id, void *arg)
1261 {
1262     OSSL_QUIC_TX_PACKETISER *txp = arg;
1263     QUIC_STREAM *s;
1264
1265     s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1266     if (s == NULL)
1267         return;
1268
1269     ossl_quic_stream_map_update_state(txp->args.qsm, s);
1270 }
1271
1272 static int txp_generate_pre_token(OSSL_QUIC_TX_PACKETISER *txp,
1273                                   struct tx_helper *h,
1274                                   QUIC_TXPIM_PKT *tpkt,
1275                                   uint32_t pn_space,
1276                                   struct archetype_data *a,
1277                                   int chosen_for_conn_close)
1278 {
1279     const OSSL_QUIC_FRAME_ACK *ack;
1280     OSSL_QUIC_FRAME_ACK ack2;
1281
1282     tpkt->ackm_pkt.largest_acked = QUIC_PN_INVALID;
1283
1284     /* ACK Frames (Regenerate) */
1285     if (a->allow_ack
1286         && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_ACK
1287         && (txp->want_ack
1288             || ossl_ackm_is_ack_desired(txp->args.ackm, pn_space))
1289         && (ack = ossl_ackm_get_ack_frame(txp->args.ackm, pn_space)) != NULL) {
1290         WPACKET *wpkt = tx_helper_begin(h);
1291
1292         if (wpkt == NULL)
1293             return 0;
1294
1295         /* We do not currently support ECN */
1296         ack2 = *ack;
1297         ack2.ecn_present = 0;
1298
1299         if (ossl_quic_wire_encode_frame_ack(wpkt,
1300                                             txp->args.ack_delay_exponent,
1301                                             &ack2)) {
1302             if (!tx_helper_commit(h))
1303                 return 0;
1304
1305             tpkt->had_ack_frame = 1;
1306
1307             if (ack->num_ack_ranges > 0)
1308                 tpkt->ackm_pkt.largest_acked = ack->ack_ranges[0].end;
1309
1310             if (txp->ack_tx_cb != NULL)
1311                 txp->ack_tx_cb(&ack2, pn_space, txp->ack_tx_cb_arg);
1312         } else {
1313             tx_helper_rollback(h);
1314         }
1315     }
1316
1317     /* CONNECTION_CLOSE Frames (Regenerate) */
1318     if (a->allow_conn_close && txp->want_conn_close && chosen_for_conn_close) {
1319         WPACKET *wpkt = tx_helper_begin(h);
1320         OSSL_QUIC_FRAME_CONN_CLOSE f, *pf = &txp->conn_close_frame;
1321
1322         if (wpkt == NULL)
1323             return 0;
1324
1325         /*
1326          * Application CONNECTION_CLOSE frames may only be sent in the
1327          * Application PN space, as otherwise they may be sent before a
1328          * connection is authenticated and leak application data. Therefore, if
1329          * we need to send a CONNECTION_CLOSE frame in another PN space and were
1330          * given an application CONNECTION_CLOSE frame, convert it into a
1331          * transport CONNECTION_CLOSE frame, removing any sensitive application
1332          * data.
1333          *
1334          * RFC 9000 s. 10.2.3: "A CONNECTION_CLOSE of type 0x1d MUST be replaced
1335          * by a CONNECTION_CLOSE of type 0x1c when sending the frame in Initial
1336          * or Handshake packets. Otherwise, information about the application
1337          * state might be revealed. Endpoints MUST clear the value of the Reason
1338          * Phrase field and SHOULD use the APPLICATION_ERROR code when
1339          * converting to a CONNECTION_CLOSE of type 0x1c."
1340          */
1341         if (pn_space != QUIC_PN_SPACE_APP && pf->is_app) {
1342             pf = &f;
1343             pf->is_app      = 0;
1344             pf->frame_type  = 0;
1345             pf->error_code  = QUIC_ERR_APPLICATION_ERROR;
1346             pf->reason      = NULL;
1347             pf->reason_len  = 0;
1348         }
1349
1350         if (ossl_quic_wire_encode_frame_conn_close(wpkt, pf)) {
1351             if (!tx_helper_commit(h))
1352                 return 0;
1353         } else {
1354             tx_helper_rollback(h);
1355         }
1356     }
1357
1358     return 1;
1359 }
1360
1361 static int try_len(size_t space_left, size_t orig_len,
1362                    size_t base_hdr_len, size_t lenbytes,
1363                    uint64_t maxn, size_t *hdr_len, size_t *payload_len)
1364 {
1365     size_t n;
1366     size_t maxn_ = maxn > SIZE_MAX ? SIZE_MAX : (size_t)maxn;
1367
1368     *hdr_len = base_hdr_len + lenbytes;
1369
1370     if (orig_len == 0 && space_left >= *hdr_len) {
1371         *payload_len = 0;
1372         return 1;
1373     }
1374
1375     n = orig_len;
1376     if (n > maxn_)
1377         n = maxn_;
1378     if (n + *hdr_len > space_left)
1379         n = (space_left >= *hdr_len) ? space_left - *hdr_len : 0;
1380
1381     *payload_len = n;
1382     return n > 0;
1383 }
1384
1385 static int determine_len(size_t space_left, size_t orig_len,
1386                          size_t base_hdr_len,
1387                          uint64_t *hlen, uint64_t *len)
1388 {
1389     int ok = 0;
1390     size_t chosen_payload_len = 0;
1391     size_t chosen_hdr_len     = 0;
1392     size_t payload_len[4], hdr_len[4];
1393     int i, valid[4] = {0};
1394
1395     valid[0] = try_len(space_left, orig_len, base_hdr_len,
1396                        1, OSSL_QUIC_VLINT_1B_MAX,
1397                        &hdr_len[0], &payload_len[0]);
1398     valid[1] = try_len(space_left, orig_len, base_hdr_len,
1399                        2, OSSL_QUIC_VLINT_2B_MAX,
1400                        &hdr_len[1], &payload_len[1]);
1401     valid[2] = try_len(space_left, orig_len, base_hdr_len,
1402                        4, OSSL_QUIC_VLINT_4B_MAX,
1403                        &hdr_len[2], &payload_len[2]);
1404     valid[3] = try_len(space_left, orig_len, base_hdr_len,
1405                        8, OSSL_QUIC_VLINT_8B_MAX,
1406                        &hdr_len[3], &payload_len[3]);
1407
1408    for (i = OSSL_NELEM(valid) - 1; i >= 0; --i)
1409         if (valid[i] && payload_len[i] >= chosen_payload_len) {
1410             chosen_payload_len = payload_len[i];
1411             chosen_hdr_len     = hdr_len[i];
1412             ok                 = 1;
1413         }
1414
1415     *hlen = chosen_hdr_len;
1416     *len  = chosen_payload_len;
1417     return ok;
1418 }
1419
1420 /*
1421  * Given a CRYPTO frame header with accurate chdr->len and a budget
1422  * (space_left), try to find the optimal value of chdr->len to fill as much of
1423  * the budget as possible. This is slightly hairy because larger values of
1424  * chdr->len cause larger encoded sizes of the length field of the frame, which
1425  * in turn mean less space available for payload data. We check all possible
1426  * encodings and choose the optimal encoding.
1427  */
1428 static int determine_crypto_len(struct tx_helper *h,
1429                                 OSSL_QUIC_FRAME_CRYPTO *chdr,
1430                                 size_t space_left,
1431                                 uint64_t *hlen,
1432                                 uint64_t *len)
1433 {
1434     size_t orig_len;
1435     size_t base_hdr_len; /* CRYPTO header length without length field */
1436
1437     if (chdr->len > SIZE_MAX)
1438         return 0;
1439
1440     orig_len = (size_t)chdr->len;
1441
1442     chdr->len = 0;
1443     base_hdr_len = ossl_quic_wire_get_encoded_frame_len_crypto_hdr(chdr);
1444     chdr->len = orig_len;
1445     if (base_hdr_len == 0)
1446         return 0;
1447
1448     --base_hdr_len;
1449
1450     return determine_len(space_left, orig_len, base_hdr_len, hlen, len);
1451 }
1452
1453 static int determine_stream_len(struct tx_helper *h,
1454                                 OSSL_QUIC_FRAME_STREAM *shdr,
1455                                 size_t space_left,
1456                                 uint64_t *hlen,
1457                                 uint64_t *len)
1458 {
1459     size_t orig_len;
1460     size_t base_hdr_len; /* STREAM header length without length field */
1461
1462     if (shdr->len > SIZE_MAX)
1463         return 0;
1464
1465     orig_len = (size_t)shdr->len;
1466
1467     shdr->len = 0;
1468     base_hdr_len = ossl_quic_wire_get_encoded_frame_len_stream_hdr(shdr);
1469     shdr->len = orig_len;
1470     if (base_hdr_len == 0)
1471         return 0;
1472
1473     if (shdr->has_explicit_len)
1474         --base_hdr_len;
1475
1476     return determine_len(space_left, orig_len, base_hdr_len, hlen, len);
1477 }
1478
1479 static int txp_generate_crypto_frames(OSSL_QUIC_TX_PACKETISER *txp,
1480                                       struct tx_helper *h,
1481                                       uint32_t pn_space,
1482                                       QUIC_TXPIM_PKT *tpkt,
1483                                       int *have_ack_eliciting)
1484 {
1485     size_t num_stream_iovec;
1486     OSSL_QUIC_FRAME_STREAM shdr = {0};
1487     OSSL_QUIC_FRAME_CRYPTO chdr = {0};
1488     OSSL_QTX_IOVEC iov[2];
1489     uint64_t hdr_bytes;
1490     WPACKET *wpkt;
1491     QUIC_TXPIM_CHUNK chunk = {0};
1492     size_t i, space_left;
1493
1494     for (i = 0;; ++i) {
1495         space_left = tx_helper_get_space_left(h);
1496
1497         if (space_left < MIN_FRAME_SIZE_CRYPTO)
1498             return 1; /* no point trying */
1499
1500         /* Do we have any CRYPTO data waiting? */
1501         num_stream_iovec = OSSL_NELEM(iov);
1502         if (!ossl_quic_sstream_get_stream_frame(txp->args.crypto[pn_space],
1503                                                 i, &shdr, iov,
1504                                                 &num_stream_iovec))
1505             return 1; /* nothing to do */
1506
1507         /* Convert STREAM frame header to CRYPTO frame header */
1508         chdr.offset = shdr.offset;
1509         chdr.len    = shdr.len;
1510
1511         if (chdr.len == 0)
1512             return 1; /* nothing to do */
1513
1514         /* Find best fit (header length, payload length) combination. */
1515         if (!determine_crypto_len(h, &chdr, space_left, &hdr_bytes,
1516                                   &chdr.len))
1517             return 1; /* can't fit anything */
1518
1519         /*
1520          * Truncate IOVs to match our chosen length.
1521          *
1522          * The length cannot be more than SIZE_MAX because this length comes
1523          * from our send stream buffer.
1524          */
1525         ossl_quic_sstream_adjust_iov((size_t)chdr.len, iov, num_stream_iovec);
1526
1527         /*
1528          * Ensure we have enough iovecs allocated (1 for the header, up to 2 for
1529          * the the stream data.)
1530          */
1531         if (!txp_ensure_iovec(txp, h->num_iovec + 3))
1532             return 0; /* alloc error */
1533
1534         /* Encode the header. */
1535         wpkt = tx_helper_begin(h);
1536         if (wpkt == NULL)
1537             return 0; /* alloc error */
1538
1539         if (!ossl_quic_wire_encode_frame_crypto_hdr(wpkt, &chdr)) {
1540             tx_helper_rollback(h);
1541             return 1; /* can't fit */
1542         }
1543
1544         if (!tx_helper_commit(h))
1545             return 0; /* alloc error */
1546
1547         /* Add payload iovecs to the helper (infallible). */
1548         for (i = 0; i < num_stream_iovec; ++i)
1549             tx_helper_append_iovec(h, iov[i].buf, iov[i].buf_len);
1550
1551         *have_ack_eliciting = 1;
1552         tx_helper_unrestrict(h); /* no longer need PING */
1553
1554         /* Log chunk to TXPIM. */
1555         chunk.stream_id = UINT64_MAX; /* crypto stream */
1556         chunk.start     = chdr.offset;
1557         chunk.end       = chdr.offset + chdr.len - 1;
1558         chunk.has_fin   = 0; /* Crypto stream never ends */
1559         if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
1560             return 0; /* alloc error */
1561     }
1562 }
1563
1564 struct chunk_info {
1565     OSSL_QUIC_FRAME_STREAM shdr;
1566     OSSL_QTX_IOVEC iov[2];
1567     size_t num_stream_iovec;
1568     int valid;
1569 };
1570
1571 static int txp_plan_stream_chunk(OSSL_QUIC_TX_PACKETISER *txp,
1572                                  struct tx_helper *h,
1573                                  QUIC_SSTREAM *sstream,
1574                                  QUIC_TXFC *stream_txfc,
1575                                  size_t skip,
1576                                  struct chunk_info *chunk)
1577 {
1578     uint64_t fc_credit, fc_swm, fc_limit;
1579
1580     chunk->num_stream_iovec = OSSL_NELEM(chunk->iov);
1581     chunk->valid = ossl_quic_sstream_get_stream_frame(sstream, skip,
1582                                                       &chunk->shdr,
1583                                                       chunk->iov,
1584                                                       &chunk->num_stream_iovec);
1585     if (!chunk->valid)
1586         return 1;
1587
1588     if (!ossl_assert(chunk->shdr.len > 0 || chunk->shdr.is_fin))
1589         /* Should only have 0-length chunk if FIN */
1590         return 0;
1591
1592     /* Clamp according to connection and stream-level TXFC. */
1593     fc_credit   = ossl_quic_txfc_get_credit(stream_txfc);
1594     fc_swm      = ossl_quic_txfc_get_swm(stream_txfc);
1595     fc_limit    = fc_swm + fc_credit;
1596
1597     if (chunk->shdr.len > 0 && chunk->shdr.offset + chunk->shdr.len > fc_limit) {
1598         chunk->shdr.len = (fc_limit <= chunk->shdr.offset)
1599             ? 0 : fc_limit - chunk->shdr.offset;
1600         chunk->shdr.is_fin = 0;
1601     }
1602
1603     if (chunk->shdr.len == 0 && !chunk->shdr.is_fin) {
1604         /*
1605          * Nothing to do due to TXFC. Since SSTREAM returns chunks in ascending
1606          * order of offset we don't need to check any later chunks, so stop
1607          * iterating here.
1608          */
1609         chunk->valid = 0;
1610         return 1;
1611     }
1612
1613     return 1;
1614 }
1615
1616 /*
1617  * Returns 0 on fatal error (e.g. allocation failure), 1 on success.
1618  * *packet_full is set to 1 if there is no longer enough room for another STREAM
1619  * frame, and *stream_drained is set to 1 if all stream buffers have now been
1620  * sent.
1621  */
1622 static int txp_generate_stream_frames(OSSL_QUIC_TX_PACKETISER *txp,
1623                                       struct tx_helper *h,
1624                                       uint32_t pn_space,
1625                                       QUIC_TXPIM_PKT *tpkt,
1626                                       uint64_t id,
1627                                       QUIC_SSTREAM *sstream,
1628                                       QUIC_TXFC *stream_txfc,
1629                                       QUIC_STREAM *next_stream,
1630                                       size_t min_ppl,
1631                                       int *have_ack_eliciting,
1632                                       int *packet_full,
1633                                       int *stream_drained,
1634                                       uint64_t *new_credit_consumed)
1635 {
1636     int rc = 0;
1637     struct chunk_info chunks[2] = {0};
1638
1639     OSSL_QUIC_FRAME_STREAM *shdr;
1640     WPACKET *wpkt;
1641     QUIC_TXPIM_CHUNK chunk;
1642     size_t i, j, space_left;
1643     int needs_padding_if_implicit, can_fill_payload, use_explicit_len;
1644     int could_have_following_chunk;
1645     uint64_t orig_len;
1646     uint64_t hdr_len_implicit, payload_len_implicit;
1647     uint64_t hdr_len_explicit, payload_len_explicit;
1648     uint64_t fc_swm, fc_new_hwm;
1649
1650     fc_swm      = ossl_quic_txfc_get_swm(stream_txfc);
1651     fc_new_hwm  = fc_swm;
1652
1653     /*
1654      * Load the first two chunks if any offered by the send stream. We retrieve
1655      * the next chunk in advance so we can determine if we need to send any more
1656      * chunks from the same stream after this one, which is needed when
1657      * determining when we can use an implicit length in a STREAM frame.
1658      */
1659     for (i = 0; i < 2; ++i) {
1660         if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i, &chunks[i]))
1661             goto err;
1662
1663         if (i == 0 && !chunks[i].valid) {
1664             /* No chunks, nothing to do. */
1665             *stream_drained = 1;
1666             rc = 1;
1667             goto err;
1668         }
1669     }
1670
1671     for (i = 0;; ++i) {
1672         space_left = tx_helper_get_space_left(h);
1673
1674         if (!chunks[i % 2].valid) {
1675             /* Out of chunks; we're done. */
1676             *stream_drained = 1;
1677             rc = 1;
1678             goto err;
1679         }
1680
1681         if (space_left < MIN_FRAME_SIZE_STREAM) {
1682             *packet_full = 1;
1683             rc = 1;
1684             goto err;
1685         }
1686
1687         if (!ossl_assert(!h->done_implicit))
1688             /*
1689              * Logic below should have ensured we didn't append an
1690              * implicit-length unless we filled the packet or didn't have
1691              * another stream to handle, so this should not be possible.
1692              */
1693             goto err;
1694
1695         shdr = &chunks[i % 2].shdr;
1696         orig_len = shdr->len;
1697         if (i > 0)
1698             /* Load next chunk for lookahead. */
1699             if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i + 1,
1700                                        &chunks[(i + 1) % 2]))
1701                 goto err;
1702
1703         /*
1704          * Find best fit (header length, payload length) combination for if we
1705          * use an implicit length.
1706          */
1707         shdr->has_explicit_len = 0;
1708         hdr_len_implicit = payload_len_implicit = 0;
1709         if (!determine_stream_len(h, shdr, space_left,
1710                                   &hdr_len_implicit, &payload_len_implicit)) {
1711             *packet_full = 1;
1712             rc = 1;
1713             goto err; /* can't fit anything */
1714         }
1715
1716         /*
1717          * If using the implicit-length representation would need padding, we
1718          * can't use it.
1719          */
1720         needs_padding_if_implicit = (h->bytes_appended + hdr_len_implicit
1721                                      + payload_len_implicit < min_ppl);
1722
1723         /*
1724          * If there is a next stream, we don't use the implicit length so we can
1725          * add more STREAM frames after this one, unless there is enough data
1726          * for this STREAM frame to fill the packet.
1727          */
1728         can_fill_payload = (hdr_len_implicit + payload_len_implicit
1729                             >= space_left);
1730
1731         /*
1732          * Is there is a stream after this one, or another chunk pending
1733          * transmission in this stream?
1734          */
1735         could_have_following_chunk
1736             = (next_stream != NULL || chunks[(i + 1) % 2].valid);
1737
1738         /* Choose between explicit or implicit length representations. */
1739         use_explicit_len = !((can_fill_payload || !could_have_following_chunk)
1740                              && !needs_padding_if_implicit);
1741
1742         if (use_explicit_len) {
1743             /*
1744              * Find best fit (header length, payload length) combination for if
1745              * we use an explicit length.
1746              */
1747             shdr->has_explicit_len = 1;
1748             hdr_len_explicit = payload_len_explicit = 0;
1749             if (!determine_stream_len(h, shdr, space_left,
1750                                       &hdr_len_explicit, &payload_len_explicit)) {
1751                 *packet_full = 1;
1752                 rc = 1;
1753                 goto err; /* can't fit anything */
1754             }
1755
1756             shdr->len = payload_len_explicit;
1757         } else {
1758             shdr->has_explicit_len = 0;
1759             shdr->len = payload_len_implicit;
1760         }
1761
1762         /* If this is a FIN, don't keep filling the packet with more FINs. */
1763         if (shdr->is_fin)
1764             chunks[(i + 1) % 2].valid = 0;
1765
1766         /* Truncate IOVs to match our chosen length. */
1767         ossl_quic_sstream_adjust_iov((size_t)shdr->len, chunks[i % 2].iov,
1768                                      chunks[i % 2].num_stream_iovec);
1769
1770         /*
1771          * Ensure we have enough iovecs allocated (1 for the header, up to 2 for
1772          * the the stream data.)
1773          */
1774         if (!txp_ensure_iovec(txp, h->num_iovec + 3))
1775             goto err; /* alloc error */
1776
1777         /* Encode the header. */
1778         wpkt = tx_helper_begin(h);
1779         if (wpkt == NULL)
1780             goto err; /* alloc error */
1781
1782         shdr->stream_id = id;
1783         if (!ossl_assert(ossl_quic_wire_encode_frame_stream_hdr(wpkt, shdr))) {
1784             /* (Should not be possible.) */
1785             tx_helper_rollback(h);
1786             *packet_full = 1;
1787             rc = 1;
1788             goto err; /* can't fit */
1789         }
1790
1791         if (!tx_helper_commit(h))
1792             goto err; /* alloc error */
1793
1794         /* Add payload iovecs to the helper (infallible). */
1795         for (j = 0; j < chunks[i % 2].num_stream_iovec; ++j)
1796             tx_helper_append_iovec(h, chunks[i % 2].iov[j].buf,
1797                                    chunks[i % 2].iov[j].buf_len);
1798
1799         *have_ack_eliciting = 1;
1800         tx_helper_unrestrict(h); /* no longer need PING */
1801         if (!shdr->has_explicit_len)
1802             h->done_implicit = 1;
1803
1804         /* Log new TXFC credit which was consumed. */
1805         if (shdr->len > 0 && shdr->offset + shdr->len > fc_new_hwm)
1806             fc_new_hwm = shdr->offset + shdr->len;
1807
1808         /* Log chunk to TXPIM. */
1809         chunk.stream_id         = shdr->stream_id;
1810         chunk.start             = shdr->offset;
1811         chunk.end               = shdr->offset + shdr->len - 1;
1812         chunk.has_fin           = shdr->is_fin;
1813         chunk.has_stop_sending  = 0;
1814         chunk.has_reset_stream  = 0;
1815         if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
1816             goto err; /* alloc error */
1817
1818         if (shdr->len < orig_len) {
1819             /*
1820              * If we did not serialize all of this chunk we definitely do not
1821              * want to try the next chunk (and we must not mark the stream
1822              * as drained).
1823              */
1824             rc = 1;
1825             goto err;
1826         }
1827     }
1828
1829 err:
1830     *new_credit_consumed = fc_new_hwm - fc_swm;
1831     return rc;
1832 }
1833
1834 static void txp_enlink_tmp(QUIC_STREAM **tmp_head, QUIC_STREAM *stream)
1835 {
1836     stream->txp_next = *tmp_head;
1837     *tmp_head = stream;
1838 }
1839
1840 static int txp_generate_stream_related(OSSL_QUIC_TX_PACKETISER *txp,
1841                                        struct tx_helper *h,
1842                                        uint32_t pn_space,
1843                                        QUIC_TXPIM_PKT *tpkt,
1844                                        size_t min_ppl,
1845                                        int *have_ack_eliciting,
1846                                        QUIC_STREAM **tmp_head)
1847 {
1848     QUIC_STREAM_ITER it;
1849     WPACKET *wpkt;
1850     uint64_t cwm;
1851     QUIC_STREAM *stream, *snext;
1852
1853     for (ossl_quic_stream_iter_init(&it, txp->args.qsm, 1);
1854          it.stream != NULL;) {
1855
1856         stream = it.stream;
1857         ossl_quic_stream_iter_next(&it);
1858         snext = it.stream;
1859
1860         stream->txp_sent_fc                  = 0;
1861         stream->txp_sent_stop_sending        = 0;
1862         stream->txp_sent_reset_stream        = 0;
1863         stream->txp_drained                  = 0;
1864         stream->txp_blocked                  = 0;
1865         stream->txp_txfc_new_credit_consumed = 0;
1866
1867         /* Stream Abort Frames (STOP_SENDING, RESET_STREAM) */
1868         if (stream->want_stop_sending) {
1869             OSSL_QUIC_FRAME_STOP_SENDING f;
1870
1871             wpkt = tx_helper_begin(h);
1872             if (wpkt == NULL)
1873                 return 0; /* alloc error */
1874
1875             f.stream_id         = stream->id;
1876             f.app_error_code    = stream->stop_sending_aec;
1877             if (!ossl_quic_wire_encode_frame_stop_sending(wpkt, &f)) {
1878                 tx_helper_rollback(h); /* can't fit */
1879                 txp_enlink_tmp(tmp_head, stream);
1880                 break;
1881             }
1882
1883             if (!tx_helper_commit(h))
1884                 return 0; /* alloc error */
1885
1886             *have_ack_eliciting = 1;
1887             tx_helper_unrestrict(h); /* no longer need PING */
1888             stream->txp_sent_stop_sending = 1;
1889         }
1890
1891         if (stream->want_reset_stream) {
1892             OSSL_QUIC_FRAME_RESET_STREAM f;
1893
1894             if (!ossl_assert(stream->send_state == QUIC_SSTREAM_STATE_RESET_SENT))
1895                 return 0;
1896
1897             wpkt = tx_helper_begin(h);
1898             if (wpkt == NULL)
1899                 return 0; /* alloc error */
1900
1901             f.stream_id         = stream->id;
1902             f.app_error_code    = stream->reset_stream_aec;
1903             if (!ossl_quic_stream_send_get_final_size(stream, &f.final_size))
1904                 return 0; /* should not be possible */
1905
1906             if (!ossl_quic_wire_encode_frame_reset_stream(wpkt, &f)) {
1907                 tx_helper_rollback(h); /* can't fit */
1908                 txp_enlink_tmp(tmp_head, stream);
1909                 break;
1910             }
1911
1912             if (!tx_helper_commit(h))
1913                 return 0; /* alloc error */
1914
1915             *have_ack_eliciting = 1;
1916             tx_helper_unrestrict(h); /* no longer need PING */
1917             stream->txp_sent_reset_stream = 1;
1918
1919             /*
1920              * The final size of the stream as indicated by RESET_STREAM is used
1921              * to ensure a consistent view of flow control state by both
1922              * parties; if we happen to send a RESET_STREAM that consumes more
1923              * flow control credit, make sure we account for that.
1924              */
1925             if (!ossl_assert(f.final_size <= ossl_quic_txfc_get_swm(&stream->txfc)))
1926                 return 0;
1927
1928             stream->txp_txfc_new_credit_consumed
1929                 = f.final_size - ossl_quic_txfc_get_swm(&stream->txfc);
1930         }
1931
1932         /*
1933          * Stream Flow Control Frames (MAX_STREAM_DATA)
1934          *
1935          * RFC 9000 s. 13.3: "An endpoint SHOULD stop sending MAX_STREAM_DATA
1936          * frames when the receiving part of the stream enters a "Size Known" or
1937          * "Reset Recvd" state." -- In practice, RECV is the only state
1938          * in which it makes sense to generate more MAX_STREAM_DATA frames.
1939          */
1940         if (stream->recv_state == QUIC_RSTREAM_STATE_RECV
1941             && (stream->want_max_stream_data
1942                 || ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 0))) {
1943
1944             wpkt = tx_helper_begin(h);
1945             if (wpkt == NULL)
1946                 return 0; /* alloc error */
1947
1948             cwm = ossl_quic_rxfc_get_cwm(&stream->rxfc);
1949
1950             if (!ossl_quic_wire_encode_frame_max_stream_data(wpkt, stream->id,
1951                                                              cwm)) {
1952                 tx_helper_rollback(h); /* can't fit */
1953                 txp_enlink_tmp(tmp_head, stream);
1954                 break;
1955             }
1956
1957             if (!tx_helper_commit(h))
1958                 return 0; /* alloc error */
1959
1960             *have_ack_eliciting = 1;
1961             tx_helper_unrestrict(h); /* no longer need PING */
1962             stream->txp_sent_fc = 1;
1963         }
1964
1965         /*
1966          * Stream Data Frames (STREAM)
1967          *
1968          * RFC 9000 s. 3.3: A sender MUST NOT send a STREAM [...] frame for a
1969          * stream in the "Reset Sent" state [or any terminal state]. We don't
1970          * send any more STREAM frames if we are sending, have sent, or are
1971          * planning to send, RESET_STREAM. The other terminal state is Data
1972          * Recvd, but txp_generate_stream_frames() is guaranteed to generate
1973          * nothing in this case.
1974          */
1975         if (ossl_quic_stream_has_send_buffer(stream)
1976             && !ossl_quic_stream_send_is_reset(stream)) {
1977             int packet_full = 0, stream_drained = 0;
1978
1979             if (!ossl_assert(!stream->want_reset_stream))
1980                 return 0;
1981
1982             if (!txp_generate_stream_frames(txp, h, pn_space, tpkt,
1983                                             stream->id, stream->sstream,
1984                                             &stream->txfc,
1985                                             snext, min_ppl,
1986                                             have_ack_eliciting,
1987                                             &packet_full,
1988                                             &stream_drained,
1989                                             &stream->txp_txfc_new_credit_consumed)) {
1990                 /* Fatal error (allocation, etc.) */
1991                 txp_enlink_tmp(tmp_head, stream);
1992                 return 0;
1993             }
1994
1995             if (stream_drained)
1996                 stream->txp_drained = 1;
1997
1998             if (packet_full) {
1999                 txp_enlink_tmp(tmp_head, stream);
2000                 break;
2001             }
2002         }
2003
2004         txp_enlink_tmp(tmp_head, stream);
2005     }
2006
2007     return 1;
2008 }
2009
2010 /*
2011  * Generates a packet for a given EL with the given minimum and maximum
2012  * plaintext packet payload lengths. Returns TXP_ERR_* value.
2013  */
2014 static int txp_generate_for_el_actual(OSSL_QUIC_TX_PACKETISER *txp,
2015                                       uint32_t enc_level,
2016                                       uint32_t archetype,
2017                                       size_t min_ppl,
2018                                       size_t max_ppl,
2019                                       size_t pkt_overhead,
2020                                       QUIC_PKT_HDR *phdr,
2021                                       int chosen_for_conn_close,
2022                                       QUIC_TXP_STATUS *status)
2023 {
2024     int rc = TXP_ERR_SUCCESS;
2025     struct archetype_data a;
2026     uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
2027     struct tx_helper h;
2028     int have_helper = 0, have_ack_eliciting = 0, done_pre_token = 0;
2029     int require_ack_eliciting = 0;
2030     QUIC_CFQ_ITEM *cfq_item;
2031     QUIC_TXPIM_PKT *tpkt = NULL;
2032     OSSL_QTX_PKT pkt;
2033     QUIC_STREAM *tmp_head = NULL, *stream;
2034     OSSL_ACKM_PROBE_INFO *probe_info
2035         = ossl_ackm_get0_probe_request(txp->args.ackm);
2036
2037     if (!txp_get_archetype_data(enc_level, archetype, &a))
2038         goto fatal_err;
2039
2040     if (a.allow_force_ack_eliciting) {
2041         /*
2042          * Make this packet ACK-eliciting if it has been explicitly requested,
2043          * or if ACKM has requested a probe for this PN space.
2044          */
2045         if ((txp->force_ack_eliciting & (1UL << pn_space)) != 0
2046             || (enc_level == QUIC_ENC_LEVEL_INITIAL
2047                 && probe_info->anti_deadlock_initial > 0)
2048             || (enc_level == QUIC_ENC_LEVEL_HANDSHAKE
2049                 && probe_info->anti_deadlock_handshake > 0)
2050             || probe_info->pto[pn_space] > 0)
2051             require_ack_eliciting = 1;
2052     }
2053
2054     /* Minimum cannot be bigger than maximum. */
2055     if (min_ppl > max_ppl)
2056         goto fatal_err;
2057
2058     /* Maximum PN reached? */
2059     if (!ossl_quic_pn_valid(txp->next_pn[pn_space]))
2060         goto fatal_err;
2061
2062     if ((tpkt = ossl_quic_txpim_pkt_alloc(txp->args.txpim)) == NULL)
2063         goto fatal_err;
2064
2065     /*
2066      * Initialise TX helper. If we must be ACK eliciting, reserve 1 byte for
2067      * PING.
2068      */
2069     if (!tx_helper_init(&h, txp, max_ppl, require_ack_eliciting ? 1 : 0))
2070         goto fatal_err;
2071
2072     have_helper = 1;
2073
2074     /*
2075      * Frame Serialization
2076      * ===================
2077      *
2078      * We now serialize frames into the packet in descending order of priority.
2079      */
2080
2081     /* HANDSHAKE_DONE (Regenerate) */
2082     if (a.allow_handshake_done && txp->want_handshake_done
2083         && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_HANDSHAKE_DONE) {
2084         WPACKET *wpkt = tx_helper_begin(&h);
2085
2086         if (wpkt == NULL)
2087             goto fatal_err;
2088
2089         if (ossl_quic_wire_encode_frame_handshake_done(wpkt)) {
2090             tpkt->had_handshake_done_frame = 1;
2091             have_ack_eliciting             = 1;
2092
2093             if (!tx_helper_commit(&h))
2094                 goto fatal_err;
2095
2096             tx_helper_unrestrict(&h); /* no longer need PING */
2097         } else {
2098             tx_helper_rollback(&h);
2099         }
2100     }
2101
2102     /* MAX_DATA (Regenerate) */
2103     if (a.allow_conn_fc
2104         && (txp->want_max_data
2105             || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0))
2106         && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_MAX_DATA) {
2107         WPACKET *wpkt = tx_helper_begin(&h);
2108         uint64_t cwm = ossl_quic_rxfc_get_cwm(txp->args.conn_rxfc);
2109
2110         if (wpkt == NULL)
2111             goto fatal_err;
2112
2113         if (ossl_quic_wire_encode_frame_max_data(wpkt, cwm)) {
2114             tpkt->had_max_data_frame = 1;
2115             have_ack_eliciting       = 1;
2116
2117             if (!tx_helper_commit(&h))
2118                 goto fatal_err;
2119
2120             tx_helper_unrestrict(&h); /* no longer need PING */
2121         } else {
2122             tx_helper_rollback(&h);
2123         }
2124     }
2125
2126     /* MAX_STREAMS_BIDI (Regenerate) */
2127     if (a.allow_conn_fc
2128         && (txp->want_max_streams_bidi
2129             || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 0))
2130         && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_MAX_STREAMS_BIDI) {
2131         WPACKET *wpkt = tx_helper_begin(&h);
2132         uint64_t max_streams
2133             = ossl_quic_rxfc_get_cwm(txp->args.max_streams_bidi_rxfc);
2134
2135         if (wpkt == NULL)
2136             goto fatal_err;
2137
2138         if (ossl_quic_wire_encode_frame_max_streams(wpkt, /*is_uni=*/0,
2139                                                     max_streams)) {
2140             tpkt->had_max_streams_bidi_frame = 1;
2141             have_ack_eliciting               = 1;
2142
2143             if (!tx_helper_commit(&h))
2144                 goto fatal_err;
2145
2146             tx_helper_unrestrict(&h); /* no longer need PING */
2147         } else {
2148             tx_helper_rollback(&h);
2149         }
2150     }
2151
2152     /* MAX_STREAMS_UNI (Regenerate) */
2153     if (a.allow_conn_fc
2154         && (txp->want_max_streams_uni
2155             || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 0))
2156         && tx_helper_get_space_left(&h) >= MIN_FRAME_SIZE_MAX_STREAMS_UNI) {
2157         WPACKET *wpkt = tx_helper_begin(&h);
2158         uint64_t max_streams
2159             = ossl_quic_rxfc_get_cwm(txp->args.max_streams_uni_rxfc);
2160
2161         if (wpkt == NULL)
2162             goto fatal_err;
2163
2164         if (ossl_quic_wire_encode_frame_max_streams(wpkt, /*is_uni=*/1,
2165                                                     max_streams)) {
2166             tpkt->had_max_streams_uni_frame = 1;
2167             have_ack_eliciting              = 1;
2168
2169             if (!tx_helper_commit(&h))
2170                 goto fatal_err;
2171
2172             tx_helper_unrestrict(&h); /* no longer need PING */
2173         } else {
2174             tx_helper_rollback(&h);
2175         }
2176     }
2177
2178     /* GCR Frames */
2179     for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space);
2180          cfq_item != NULL;
2181          cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) {
2182         uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item);
2183         const unsigned char *encoded = ossl_quic_cfq_item_get_encoded(cfq_item);
2184         size_t encoded_len = ossl_quic_cfq_item_get_encoded_len(cfq_item);
2185
2186         switch (frame_type) {
2187             case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID:
2188                 if (!a.allow_new_conn_id)
2189                     continue;
2190                 break;
2191             case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID:
2192                 if (!a.allow_retire_conn_id)
2193                     continue;
2194                 break;
2195             case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN:
2196                 if (!a.allow_new_token)
2197                     continue;
2198
2199                 /*
2200                  * NEW_TOKEN frames are handled via GCR, but some
2201                  * Regenerate-strategy frames should come before them (namely
2202                  * ACK, CONNECTION_CLOSE, PATH_CHALLENGE and PATH_RESPONSE). If
2203                  * we find a NEW_TOKEN frame, do these now. If there are no
2204                  * NEW_TOKEN frames in the GCR queue we will handle these below.
2205                  */
2206                 if (!done_pre_token)
2207                     if (txp_generate_pre_token(txp, &h, tpkt, pn_space, &a,
2208                                                chosen_for_conn_close))
2209                         done_pre_token = 1;
2210
2211                 break;
2212             default:
2213                 if (!a.allow_cfq_other)
2214                     continue;
2215                 break;
2216         }
2217
2218         /*
2219          * If the frame is too big, don't try to schedule any more GCR frames in
2220          * this packet rather than sending subsequent ones out of order.
2221          */
2222         if (encoded_len > tx_helper_get_space_left(&h))
2223             break;
2224
2225         if (!tx_helper_append_iovec(&h, encoded, encoded_len))
2226             goto fatal_err;
2227
2228         ossl_quic_txpim_pkt_add_cfq_item(tpkt, cfq_item);
2229
2230         if (ossl_quic_frame_type_is_ack_eliciting(frame_type)) {
2231             have_ack_eliciting = 1;
2232             tx_helper_unrestrict(&h); /* no longer need PING */
2233         }
2234     }
2235
2236     /*
2237      * If we didn't generate ACK, CONNECTION_CLOSE, PATH_CHALLENGE or
2238      * PATH_RESPONSE (as desired) before, do so now.
2239      */
2240     if (!done_pre_token)
2241         if (txp_generate_pre_token(txp, &h, tpkt, pn_space, &a,
2242                                    chosen_for_conn_close))
2243             done_pre_token = 1;
2244
2245     /* CRYPTO Frames */
2246     if (a.allow_crypto)
2247         if (!txp_generate_crypto_frames(txp, &h, pn_space, tpkt,
2248                                         &have_ack_eliciting))
2249             goto fatal_err;
2250
2251     /* Stream-specific frames */
2252     if (a.allow_stream_rel && txp->handshake_complete)
2253         if (!txp_generate_stream_related(txp, &h, pn_space, tpkt, min_ppl,
2254                                          &have_ack_eliciting,
2255                                          &tmp_head))
2256             goto fatal_err;
2257
2258     /* PING */
2259     tx_helper_unrestrict(&h);
2260
2261     if (require_ack_eliciting && !have_ack_eliciting && a.allow_ping) {
2262         WPACKET *wpkt;
2263
2264         wpkt = tx_helper_begin(&h);
2265         if (wpkt == NULL)
2266             goto fatal_err;
2267
2268         if (!ossl_quic_wire_encode_frame_ping(wpkt)
2269             || !tx_helper_commit(&h))
2270             /*
2271              * We treat a request to be ACK-eliciting as a requirement, so this
2272              * is an error.
2273              */
2274             goto fatal_err;
2275
2276         have_ack_eliciting = 1;
2277     }
2278
2279     /* PADDING */
2280     if (h.bytes_appended < min_ppl) {
2281         WPACKET *wpkt = tx_helper_begin(&h);
2282         if (wpkt == NULL)
2283             goto fatal_err;
2284
2285         if (!ossl_quic_wire_encode_padding(wpkt, min_ppl - h.bytes_appended)
2286             || !tx_helper_commit(&h))
2287             goto fatal_err;
2288     }
2289
2290     /*
2291      * Dispatch
2292      * ========
2293      */
2294     /* ACKM Data */
2295     tpkt->ackm_pkt.num_bytes        = h.bytes_appended + pkt_overhead;
2296     tpkt->ackm_pkt.pkt_num          = txp->next_pn[pn_space];
2297     /* largest_acked is set in txp_generate_pre_token */
2298     tpkt->ackm_pkt.pkt_space        = pn_space;
2299     tpkt->ackm_pkt.is_inflight      = 1;
2300     tpkt->ackm_pkt.is_ack_eliciting = have_ack_eliciting;
2301     tpkt->ackm_pkt.is_pto_probe     = 0;
2302     tpkt->ackm_pkt.is_mtu_probe     = 0;
2303     tpkt->ackm_pkt.time             = txp->args.now(txp->args.now_arg);
2304
2305     /* Packet Information for QTX */
2306     pkt.hdr         = phdr;
2307     pkt.iovec       = txp->iovec;
2308     pkt.num_iovec   = h.num_iovec;
2309     pkt.local       = NULL;
2310     pkt.peer        = BIO_ADDR_family(&txp->args.peer) == AF_UNSPEC
2311         ? NULL : &txp->args.peer;
2312     pkt.pn          = txp->next_pn[pn_space];
2313     pkt.flags       = OSSL_QTX_PKT_FLAG_COALESCE; /* always try to coalesce */
2314
2315     if (!ossl_assert(h.bytes_appended > 0))
2316         goto fatal_err;
2317
2318     /* Generate TXPIM chunks representing STOP_SENDING and RESET_STREAM frames. */
2319     for (stream = tmp_head; stream != NULL; stream = stream->txp_next)
2320         if (stream->txp_sent_stop_sending || stream->txp_sent_reset_stream) {
2321             /* Log STOP_SENDING chunk to TXPIM. */
2322             QUIC_TXPIM_CHUNK chunk;
2323
2324             chunk.stream_id         = stream->id;
2325             chunk.start             = UINT64_MAX;
2326             chunk.end               = 0;
2327             chunk.has_fin           = 0;
2328             chunk.has_stop_sending  = stream->txp_sent_stop_sending;
2329             chunk.has_reset_stream  = stream->txp_sent_reset_stream;
2330             if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
2331                 return 0; /* alloc error */
2332         }
2333
2334     /* Dispatch to FIFD. */
2335     if (!ossl_quic_fifd_pkt_commit(&txp->fifd, tpkt))
2336         goto fatal_err;
2337
2338     /* Send the packet. */
2339     if (!ossl_qtx_write_pkt(txp->args.qtx, &pkt))
2340         goto fatal_err;
2341
2342     ++txp->next_pn[pn_space];
2343
2344     /*
2345      * Record FC and stream abort frames as sent; deactivate streams which no
2346      * longer have anything to do.
2347      */
2348     for (stream = tmp_head; stream != NULL; stream = stream->txp_next) {
2349         if (stream->txp_sent_fc) {
2350             stream->want_max_stream_data = 0;
2351             ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 1);
2352         }
2353
2354         if (stream->txp_sent_stop_sending)
2355             stream->want_stop_sending = 0;
2356
2357         if (stream->txp_sent_reset_stream)
2358             stream->want_reset_stream = 0;
2359
2360         if (stream->txp_txfc_new_credit_consumed > 0) {
2361             if (!ossl_assert(ossl_quic_txfc_consume_credit(&stream->txfc,
2362                                                            stream->txp_txfc_new_credit_consumed)))
2363                 /*
2364                  * Should not be possible, but we should continue with our
2365                  * bookkeeping as we have already committed the packet to the
2366                  * FIFD. Just change the value we return.
2367                  */
2368                 rc = TXP_ERR_INTERNAL;
2369
2370             stream->txp_txfc_new_credit_consumed = 0;
2371         }
2372
2373         /*
2374          * If we no longer need to generate any flow control (MAX_STREAM_DATA),
2375          * STOP_SENDING or RESET_STREAM frames, nor any STREAM frames (because
2376          * the stream is drained of data or TXFC-blocked), we can mark the
2377          * stream as inactive.
2378          */
2379         ossl_quic_stream_map_update_state(txp->args.qsm, stream);
2380
2381         if (stream->txp_drained) {
2382             assert(!ossl_quic_sstream_has_pending(stream->sstream));
2383
2384             /*
2385              * Transition to DATA_SENT if stream has a final size and we have
2386              * sent all data.
2387              */
2388             if (ossl_quic_sstream_get_final_size(stream->sstream, NULL))
2389                 ossl_quic_stream_map_notify_all_data_sent(txp->args.qsm, stream);
2390         }
2391     }
2392
2393     /* We have now sent the packet, so update state accordingly. */
2394     if (have_ack_eliciting)
2395         txp->force_ack_eliciting &= ~(1UL << pn_space);
2396
2397     if (tpkt->had_handshake_done_frame)
2398         txp->want_handshake_done = 0;
2399
2400     if (tpkt->had_max_data_frame) {
2401         txp->want_max_data = 0;
2402         ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 1);
2403     }
2404
2405     if (tpkt->had_max_streams_bidi_frame) {
2406         txp->want_max_streams_bidi = 0;
2407         ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 1);
2408     }
2409
2410     if (tpkt->had_max_streams_uni_frame) {
2411         txp->want_max_streams_uni = 0;
2412         ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 1);
2413     }
2414
2415     if (tpkt->had_ack_frame)
2416         txp->want_ack &= ~(1UL << pn_space);
2417
2418     /*
2419      * Decrement probe request counts if we have sent a packet that meets
2420      * the requirement of a probe, namely being ACK-eliciting.
2421      */
2422     if (have_ack_eliciting) {
2423         if (enc_level == QUIC_ENC_LEVEL_INITIAL
2424             && probe_info->anti_deadlock_initial > 0)
2425             --probe_info->anti_deadlock_initial;
2426
2427         if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE
2428             && probe_info->anti_deadlock_handshake > 0)
2429             --probe_info->anti_deadlock_handshake;
2430
2431         if (a.allow_force_ack_eliciting /* (i.e., not for 0-RTT) */
2432             && probe_info->pto[pn_space] > 0)
2433             --probe_info->pto[pn_space];
2434     }
2435
2436     status->sent_ack_eliciting = 1;
2437
2438     /* Done. */
2439     tx_helper_cleanup(&h);
2440     return rc;
2441
2442 fatal_err:
2443     /*
2444      * Handler for fatal errors, i.e. errors causing us to abort the entire
2445      * packet rather than just one frame. Examples of such errors include
2446      * allocation errors.
2447      */
2448     if (have_helper)
2449         tx_helper_cleanup(&h);
2450     if (tpkt != NULL)
2451         ossl_quic_txpim_pkt_release(txp->args.txpim, tpkt);
2452     return TXP_ERR_INTERNAL;
2453 }
2454
2455 /* Ensure the iovec array is at least num elements long. */
2456 static int txp_ensure_iovec(OSSL_QUIC_TX_PACKETISER *txp, size_t num)
2457 {
2458     OSSL_QTX_IOVEC *iovec;
2459
2460     if (txp->alloc_iovec >= num)
2461         return 1;
2462
2463     num = txp->alloc_iovec != 0 ? txp->alloc_iovec * 2 : 8;
2464
2465     iovec = OPENSSL_realloc(txp->iovec, sizeof(OSSL_QTX_IOVEC) * num);
2466     if (iovec == NULL)
2467         return 0;
2468
2469     txp->iovec          = iovec;
2470     txp->alloc_iovec    = num;
2471     return 1;
2472 }
2473
2474 int ossl_quic_tx_packetiser_schedule_conn_close(OSSL_QUIC_TX_PACKETISER *txp,
2475                                                 const OSSL_QUIC_FRAME_CONN_CLOSE *f)
2476 {
2477     char *reason = NULL;
2478     size_t reason_len = f->reason_len;
2479     size_t max_reason_len = txp_get_mdpl(txp) / 2;
2480
2481     if (txp->want_conn_close)
2482         return 0;
2483
2484     /*
2485      * Arbitrarily limit the length of the reason length string to half of the
2486      * MDPL.
2487      */
2488     if (reason_len > max_reason_len)
2489         reason_len = max_reason_len;
2490
2491     if (reason_len > 0) {
2492         reason = OPENSSL_memdup(f->reason, reason_len);
2493         if (reason == NULL)
2494             return 0;
2495     }
2496
2497     txp->conn_close_frame               = *f;
2498     txp->conn_close_frame.reason        = reason;
2499     txp->conn_close_frame.reason_len    = reason_len;
2500     txp->want_conn_close                = 1;
2501     return 1;
2502 }
2503
2504 void ossl_quic_tx_packetiser_set_msg_callback(OSSL_QUIC_TX_PACKETISER *txp,
2505                                               ossl_msg_cb msg_callback,
2506                                               SSL *msg_callback_ssl)
2507 {
2508     txp->msg_callback = msg_callback;
2509     txp->msg_callback_ssl = msg_callback_ssl;
2510 }
2511
2512 void ossl_quic_tx_packetiser_set_msg_callback_arg(OSSL_QUIC_TX_PACKETISER *txp,
2513                                                   void *msg_callback_arg)
2514 {
2515     txp->msg_callback_arg = msg_callback_arg;
2516 }
2517
2518 QUIC_PN ossl_quic_tx_packetiser_get_next_pn(OSSL_QUIC_TX_PACKETISER *txp,
2519                                             uint32_t pn_space)
2520 {
2521     if (pn_space >= QUIC_PN_SPACE_NUM)
2522         return UINT64_MAX;
2523
2524     return txp->next_pn[pn_space];
2525 }