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