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