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