Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl33/ssl/quic/quic_txp.c
Line
Count
Source
1
/*
2
 * Copyright 2022-2025 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include "internal/quic_txp.h"
11
#include "internal/quic_fifd.h"
12
#include "internal/quic_stream_map.h"
13
#include "internal/quic_error.h"
14
#include "internal/common.h"
15
#include <openssl/err.h>
16
17
2.21M
#define MIN_CRYPTO_HDR_SIZE 3
18
19
0
#define MIN_FRAME_SIZE_HANDSHAKE_DONE 1
20
0
#define MIN_FRAME_SIZE_MAX_DATA 2
21
101M
#define MIN_FRAME_SIZE_ACK 5
22
2.21M
#define MIN_FRAME_SIZE_CRYPTO (MIN_CRYPTO_HDR_SIZE + 1)
23
7.07k
#define MIN_FRAME_SIZE_STREAM 3 /* minimum useful size (for non-FIN) */
24
0
#define MIN_FRAME_SIZE_MAX_STREAMS_BIDI 2
25
0
#define MIN_FRAME_SIZE_MAX_STREAMS_UNI 2
26
27
/*
28
 * Packet Archetypes
29
 * =================
30
 */
31
32
/* Generate normal packets containing most frame types, subject to EL. */
33
20.3M
#define TX_PACKETISER_ARCHETYPE_NORMAL 0
34
35
/*
36
 * A probe packet is different in that:
37
 *   - It bypasses CC, but *is* counted as in flight for purposes of CC;
38
 *   - It must be ACK-eliciting.
39
 */
40
73.0M
#define TX_PACKETISER_ARCHETYPE_PROBE 1
41
42
/*
43
 * An ACK-only packet is different in that:
44
 *   - It bypasses CC, and is considered a 'non-inflight' packet;
45
 *   - It may not contain anything other than an ACK frame, not even padding.
46
 */
47
51.9M
#define TX_PACKETISER_ARCHETYPE_ACK_ONLY 2
48
49
139M
#define TX_PACKETISER_ARCHETYPE_NUM 3
50
51
struct ossl_quic_tx_packetiser_st {
52
    OSSL_QUIC_TX_PACKETISER_ARGS args;
53
54
    /*
55
     * Opaque initial token blob provided by caller. TXP frees using the
56
     * callback when it is no longer needed.
57
     */
58
    const unsigned char *initial_token;
59
    size_t initial_token_len;
60
    ossl_quic_initial_token_free_fn *initial_token_free_cb;
61
    void *initial_token_free_cb_arg;
62
63
    /* Subcomponents of the TXP that we own. */
64
    QUIC_FIFD fifd; /* QUIC Frame-in-Flight Dispatcher */
65
66
    /* Internal state. */
67
    uint64_t next_pn[QUIC_PN_SPACE_NUM]; /* Next PN to use in given PN space. */
68
    OSSL_TIME last_tx_time; /* Last time a packet was generated, or 0. */
69
70
    /* Internal state - frame (re)generation flags. */
71
    unsigned int want_handshake_done : 1;
72
    unsigned int want_max_data : 1;
73
    unsigned int want_max_streams_bidi : 1;
74
    unsigned int want_max_streams_uni : 1;
75
76
    /* Internal state - frame (re)generation flags - per PN space. */
77
    unsigned int want_ack : QUIC_PN_SPACE_NUM;
78
    unsigned int force_ack_eliciting : QUIC_PN_SPACE_NUM;
79
80
    /*
81
     * Internal state - connection close terminal state.
82
     * Once this is set, it is not unset unlike other want_ flags - we keep
83
     * sending it in every packet.
84
     */
85
    unsigned int want_conn_close : 1;
86
87
    /* Has the handshake been completed? */
88
    unsigned int handshake_complete : 1;
89
90
    OSSL_QUIC_FRAME_CONN_CLOSE conn_close_frame;
91
92
    /*
93
     * Counts of the number of bytes received and sent while in the closing
94
     * state.
95
     */
96
    uint64_t closing_bytes_recv;
97
    uint64_t closing_bytes_xmit;
98
99
    /* Internal state - packet assembly. */
100
    struct txp_el {
101
        unsigned char *scratch; /* scratch buffer for packet assembly */
102
        size_t scratch_len; /* number of bytes allocated for scratch */
103
        OSSL_QTX_IOVEC *iovec; /* scratch iovec array for use with QTX */
104
        size_t alloc_iovec; /* size of iovec array */
105
    } el[QUIC_ENC_LEVEL_NUM];
106
107
    /* Message callback related arguments */
108
    ossl_msg_cb msg_callback;
109
    void *msg_callback_arg;
110
    SSL *msg_callback_ssl;
111
112
    /* Callbacks. */
113
    void (*ack_tx_cb)(const OSSL_QUIC_FRAME_ACK *ack,
114
        uint32_t pn_space,
115
        void *arg);
116
    void *ack_tx_cb_arg;
117
};
118
119
/*
120
 * The TX helper records state used while generating frames into packets. It
121
 * enables serialization into the packet to be done "transactionally" where
122
 * serialization of a frame can be rolled back if it fails midway (e.g. if it
123
 * does not fit).
124
 */
125
struct tx_helper {
126
    OSSL_QUIC_TX_PACKETISER *txp;
127
    /*
128
     * The Maximum Packet Payload Length in bytes. This is the amount of
129
     * space we have to generate frames into.
130
     */
131
    size_t max_ppl;
132
    /*
133
     * Number of bytes we have generated so far.
134
     */
135
    size_t bytes_appended;
136
    /*
137
     * Number of scratch bytes in txp->scratch we have used so far. Some iovecs
138
     * will reference this scratch buffer. When we need to use more of it (e.g.
139
     * when we need to put frame headers somewhere), we append to the scratch
140
     * buffer, resizing if necessary, and increase this accordingly.
141
     */
142
    size_t scratch_bytes;
143
    /*
144
     * Bytes reserved in the MaxPPL budget. We keep this number of bytes spare
145
     * until reserve_allowed is set to 1. Currently this is always at most 1, as
146
     * a PING frame takes up one byte and this mechanism is only used to ensure
147
     * we can encode a PING frame if we have been asked to ensure a packet is
148
     * ACK-eliciting and we are unusure if we are going to add any other
149
     * ACK-eliciting frames before we reach our MaxPPL budget.
150
     */
151
    size_t reserve;
152
    /*
153
     * Number of iovecs we have currently appended. This is the number of
154
     * entries valid in txp->iovec.
155
     */
156
    size_t num_iovec;
157
    /* The EL this TX helper is being used for. */
158
    uint32_t enc_level;
159
    /*
160
     * Whether we are allowed to make use of the reserve bytes in our MaxPPL
161
     * budget. This is used to ensure we have room to append a PING frame later
162
     * if we need to. Once we know we will not need to append a PING frame, this
163
     * is set to 1.
164
     */
165
    unsigned int reserve_allowed : 1;
166
    /*
167
     * Set to 1 if we have appended a STREAM frame with an implicit length. If
168
     * this happens we should never append another frame after that frame as it
169
     * cannot be validly encoded. This is just a safety check.
170
     */
171
    unsigned int done_implicit : 1;
172
    struct {
173
        /*
174
         * The fields in this structure are valid if active is set, which means
175
         * that a serialization transaction is currently in progress.
176
         */
177
        unsigned char *data;
178
        WPACKET wpkt;
179
        unsigned int active : 1;
180
    } txn;
181
};
182
183
static void tx_helper_rollback(struct tx_helper *h);
184
static int txp_el_ensure_iovec(struct txp_el *el, size_t num);
185
186
/* Initialises the TX helper. */
187
static int tx_helper_init(struct tx_helper *h, OSSL_QUIC_TX_PACKETISER *txp,
188
    uint32_t enc_level, size_t max_ppl, size_t reserve)
189
50.6M
{
190
50.6M
    if (reserve > max_ppl)
191
0
        return 0;
192
193
50.6M
    h->txp = txp;
194
50.6M
    h->enc_level = enc_level;
195
50.6M
    h->max_ppl = max_ppl;
196
50.6M
    h->reserve = reserve;
197
50.6M
    h->num_iovec = 0;
198
50.6M
    h->bytes_appended = 0;
199
50.6M
    h->scratch_bytes = 0;
200
50.6M
    h->reserve_allowed = 0;
201
50.6M
    h->done_implicit = 0;
202
50.6M
    h->txn.data = NULL;
203
50.6M
    h->txn.active = 0;
204
205
50.6M
    if (max_ppl > h->txp->el[enc_level].scratch_len) {
206
119k
        unsigned char *scratch;
207
208
119k
        scratch = OPENSSL_realloc(h->txp->el[enc_level].scratch, max_ppl);
209
119k
        if (scratch == NULL)
210
0
            return 0;
211
212
119k
        h->txp->el[enc_level].scratch = scratch;
213
119k
        h->txp->el[enc_level].scratch_len = max_ppl;
214
119k
    }
215
216
50.6M
    return 1;
217
50.6M
}
218
219
static void tx_helper_cleanup(struct tx_helper *h)
220
50.6M
{
221
50.6M
    if (h->txn.active)
222
0
        tx_helper_rollback(h);
223
224
50.6M
    h->txp = NULL;
225
50.6M
}
226
227
static void tx_helper_unrestrict(struct tx_helper *h)
228
51.0M
{
229
51.0M
    h->reserve_allowed = 1;
230
51.0M
}
231
232
/*
233
 * Append an extent of memory to the iovec list. The memory must remain
234
 * allocated until we finish generating the packet and call the QTX.
235
 *
236
 * In general, the buffers passed to this function will be from one of two
237
 * ranges:
238
 *
239
 *   - Application data contained in stream buffers managed elsewhere
240
 *     in the QUIC stack; or
241
 *
242
 *   - Control frame data appended into txp->scratch using tx_helper_begin and
243
 *     tx_helper_commit.
244
 *
245
 */
246
static int tx_helper_append_iovec(struct tx_helper *h,
247
    const unsigned char *buf,
248
    size_t buf_len)
249
9.89M
{
250
9.89M
    struct txp_el *el = &h->txp->el[h->enc_level];
251
252
9.89M
    if (buf_len == 0)
253
0
        return 1;
254
255
9.89M
    if (!ossl_assert(!h->done_implicit))
256
0
        return 0;
257
258
9.89M
    if (!txp_el_ensure_iovec(el, h->num_iovec + 1))
259
0
        return 0;
260
261
9.89M
    el->iovec[h->num_iovec].buf = buf;
262
9.89M
    el->iovec[h->num_iovec].buf_len = buf_len;
263
264
9.89M
    ++h->num_iovec;
265
9.89M
    h->bytes_appended += buf_len;
266
9.89M
    return 1;
267
9.89M
}
268
269
/*
270
 * How many more bytes of space do we have left in our plaintext packet payload?
271
 */
272
static size_t tx_helper_get_space_left(struct tx_helper *h)
273
63.1M
{
274
63.1M
    return h->max_ppl
275
63.1M
        - (h->reserve_allowed ? 0 : h->reserve) - h->bytes_appended;
276
63.1M
}
277
278
/*
279
 * Begin a control frame serialization transaction. This allows the
280
 * serialization of the control frame to be backed out if it turns out it won't
281
 * fit. Write the control frame to the returned WPACKET. Ensure you always
282
 * call tx_helper_rollback or tx_helper_commit (or tx_helper_cleanup). Returns
283
 * NULL on failure.
284
 */
285
static WPACKET *tx_helper_begin(struct tx_helper *h)
286
9.99M
{
287
9.99M
    size_t space_left, len;
288
9.99M
    unsigned char *data;
289
9.99M
    struct txp_el *el = &h->txp->el[h->enc_level];
290
291
9.99M
    if (!ossl_assert(!h->txn.active))
292
0
        return NULL;
293
294
9.99M
    if (!ossl_assert(!h->done_implicit))
295
0
        return NULL;
296
297
9.99M
    data = (unsigned char *)el->scratch + h->scratch_bytes;
298
9.99M
    len = el->scratch_len - h->scratch_bytes;
299
300
9.99M
    space_left = tx_helper_get_space_left(h);
301
9.99M
    if (!ossl_assert(space_left <= len))
302
0
        return NULL;
303
304
9.99M
    if (!WPACKET_init_static_len(&h->txn.wpkt, data, len, 0))
305
0
        return NULL;
306
307
9.99M
    if (!WPACKET_set_max_size(&h->txn.wpkt, space_left)) {
308
0
        WPACKET_cleanup(&h->txn.wpkt);
309
0
        return NULL;
310
0
    }
311
312
9.99M
    h->txn.data = data;
313
9.99M
    h->txn.active = 1;
314
9.99M
    return &h->txn.wpkt;
315
9.99M
}
316
317
static void tx_helper_end(struct tx_helper *h, int success)
318
9.99M
{
319
9.99M
    if (success)
320
9.53M
        WPACKET_finish(&h->txn.wpkt);
321
462k
    else
322
462k
        WPACKET_cleanup(&h->txn.wpkt);
323
324
9.99M
    h->txn.active = 0;
325
9.99M
    h->txn.data = NULL;
326
9.99M
}
327
328
/* Abort a control frame serialization transaction. */
329
static void tx_helper_rollback(struct tx_helper *h)
330
462k
{
331
462k
    if (!h->txn.active)
332
0
        return;
333
334
462k
    tx_helper_end(h, 0);
335
462k
}
336
337
/* Commit a control frame. */
338
static int tx_helper_commit(struct tx_helper *h)
339
9.53M
{
340
9.53M
    size_t l = 0;
341
342
9.53M
    if (!h->txn.active)
343
0
        return 0;
344
345
9.53M
    if (!WPACKET_get_total_written(&h->txn.wpkt, &l)) {
346
0
        tx_helper_end(h, 0);
347
0
        return 0;
348
0
    }
349
350
9.53M
    if (!tx_helper_append_iovec(h, h->txn.data, l)) {
351
0
        tx_helper_end(h, 0);
352
0
        return 0;
353
0
    }
354
355
9.53M
    if (h->txp->msg_callback != NULL && l > 0) {
356
0
        uint64_t ftype;
357
0
        int ctype = SSL3_RT_QUIC_FRAME_FULL;
358
0
        PACKET pkt;
359
360
0
        if (!PACKET_buf_init(&pkt, h->txn.data, l)
361
0
            || !ossl_quic_wire_peek_frame_header(&pkt, &ftype, NULL)) {
362
0
            tx_helper_end(h, 0);
363
0
            return 0;
364
0
        }
365
366
0
        if (ftype == OSSL_QUIC_FRAME_TYPE_PADDING)
367
0
            ctype = SSL3_RT_QUIC_FRAME_PADDING;
368
0
        else if (OSSL_QUIC_FRAME_TYPE_IS_STREAM(ftype)
369
0
            || ftype == OSSL_QUIC_FRAME_TYPE_CRYPTO)
370
0
            ctype = SSL3_RT_QUIC_FRAME_HEADER;
371
372
0
        h->txp->msg_callback(1, OSSL_QUIC1_VERSION, ctype, h->txn.data, l,
373
0
            h->txp->msg_callback_ssl,
374
0
            h->txp->msg_callback_arg);
375
0
    }
376
377
9.53M
    h->scratch_bytes += l;
378
9.53M
    tx_helper_end(h, 1);
379
9.53M
    return 1;
380
9.53M
}
381
382
struct archetype_data {
383
    unsigned int allow_ack : 1;
384
    unsigned int allow_ping : 1;
385
    unsigned int allow_crypto : 1;
386
    unsigned int allow_handshake_done : 1;
387
    unsigned int allow_path_challenge : 1;
388
    unsigned int allow_path_response : 1;
389
    unsigned int allow_new_conn_id : 1;
390
    unsigned int allow_retire_conn_id : 1;
391
    unsigned int allow_stream_rel : 1;
392
    unsigned int allow_conn_fc : 1;
393
    unsigned int allow_conn_close : 1;
394
    unsigned int allow_cfq_other : 1;
395
    unsigned int allow_new_token : 1;
396
    unsigned int allow_force_ack_eliciting : 1;
397
    unsigned int allow_padding : 1;
398
    unsigned int require_ack_eliciting : 1;
399
    unsigned int bypass_cc : 1;
400
};
401
402
struct txp_pkt_geom {
403
    size_t cmpl, cmppl, hwm, pkt_overhead;
404
    uint32_t archetype;
405
    struct archetype_data adata;
406
};
407
408
struct txp_pkt {
409
    struct tx_helper h;
410
    int h_valid;
411
    QUIC_TXPIM_PKT *tpkt;
412
    QUIC_STREAM *stream_head;
413
    QUIC_PKT_HDR phdr;
414
    struct txp_pkt_geom geom;
415
    int force_pad;
416
};
417
418
static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space,
419
    void *arg);
420
static void on_regen_notify(uint64_t frame_type, uint64_t stream_id,
421
    QUIC_TXPIM_PKT *pkt, void *arg);
422
static void on_confirm_notify(uint64_t frame_type, uint64_t stream_id,
423
    QUIC_TXPIM_PKT *pkt, void *arg);
424
static void on_sstream_updated(uint64_t stream_id, void *arg);
425
static int sstream_is_pending(QUIC_SSTREAM *sstream);
426
static int txp_should_try_staging(OSSL_QUIC_TX_PACKETISER *txp,
427
    uint32_t enc_level,
428
    uint32_t archetype,
429
    uint64_t cc_limit,
430
    uint32_t *conn_close_enc_level);
431
static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp);
432
static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp,
433
    size_t pl,
434
    uint32_t enc_level,
435
    size_t hdr_len,
436
    size_t *r);
437
static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp);
438
static int txp_generate_for_el(OSSL_QUIC_TX_PACKETISER *txp,
439
    struct txp_pkt *pkt,
440
    int chosen_for_conn_close);
441
static int txp_pkt_init(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp,
442
    uint32_t enc_level, uint32_t archetype,
443
    size_t running_total);
444
static void txp_pkt_cleanup(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp);
445
static int txp_pkt_postgen_update_pkt_overhead(struct txp_pkt *pkt,
446
    OSSL_QUIC_TX_PACKETISER *txp);
447
static int txp_pkt_append_padding(struct txp_pkt *pkt,
448
    OSSL_QUIC_TX_PACKETISER *txp, size_t num_bytes);
449
static int txp_pkt_commit(OSSL_QUIC_TX_PACKETISER *txp, struct txp_pkt *pkt,
450
    uint32_t archetype, int *txpim_pkt_reffed);
451
static uint32_t txp_determine_archetype(OSSL_QUIC_TX_PACKETISER *txp,
452
    uint64_t cc_limit);
453
454
OSSL_QUIC_TX_PACKETISER *ossl_quic_tx_packetiser_new(const OSSL_QUIC_TX_PACKETISER_ARGS *args)
455
20.9k
{
456
20.9k
    OSSL_QUIC_TX_PACKETISER *txp;
457
458
20.9k
    if (args == NULL
459
20.9k
        || args->qtx == NULL
460
20.9k
        || args->txpim == NULL
461
20.9k
        || args->cfq == NULL
462
20.9k
        || args->ackm == NULL
463
20.9k
        || args->qsm == NULL
464
20.9k
        || args->conn_txfc == NULL
465
20.9k
        || args->conn_rxfc == NULL
466
20.9k
        || args->max_streams_bidi_rxfc == NULL
467
20.9k
        || args->max_streams_uni_rxfc == NULL) {
468
0
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
469
0
        return NULL;
470
0
    }
471
472
20.9k
    txp = OPENSSL_zalloc(sizeof(*txp));
473
20.9k
    if (txp == NULL)
474
0
        return NULL;
475
476
20.9k
    txp->args = *args;
477
20.9k
    txp->last_tx_time = ossl_time_zero();
478
479
20.9k
    if (!ossl_quic_fifd_init(&txp->fifd,
480
20.9k
            txp->args.cfq, txp->args.ackm, txp->args.txpim,
481
20.9k
            get_sstream_by_id, txp,
482
20.9k
            on_regen_notify, txp,
483
20.9k
            on_confirm_notify, txp,
484
20.9k
            on_sstream_updated, txp,
485
20.9k
            args->get_qlog_cb,
486
20.9k
            args->get_qlog_cb_arg)) {
487
0
        OPENSSL_free(txp);
488
0
        return NULL;
489
0
    }
490
491
20.9k
    return txp;
492
20.9k
}
493
494
void ossl_quic_tx_packetiser_free(OSSL_QUIC_TX_PACKETISER *txp)
495
50.4k
{
496
50.4k
    uint32_t enc_level;
497
498
50.4k
    if (txp == NULL)
499
0
        return;
500
501
50.4k
    ossl_quic_tx_packetiser_set_initial_token(txp, NULL, 0, NULL, NULL);
502
50.4k
    ossl_quic_fifd_cleanup(&txp->fifd);
503
50.4k
    OPENSSL_free(txp->conn_close_frame.reason);
504
505
50.4k
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
506
252k
        enc_level < QUIC_ENC_LEVEL_NUM;
507
201k
        ++enc_level) {
508
201k
        OPENSSL_free(txp->el[enc_level].iovec);
509
201k
        OPENSSL_free(txp->el[enc_level].scratch);
510
201k
    }
511
512
50.4k
    OPENSSL_free(txp);
513
50.4k
}
514
515
/*
516
 * Determine if an Initial packet token length is reasonable based on the
517
 * current MDPL, returning 1 if it is OK.
518
 *
519
 * The real PMTU to the peer could differ from our (pessimistic) understanding
520
 * of the PMTU, therefore it is possible we could receive an Initial token from
521
 * a server in a Retry packet which is bigger than the MDPL. In this case it is
522
 * impossible for us ever to make forward progress and we need to error out
523
 * and fail the connection attempt.
524
 *
525
 * The specific boundary condition is complex: for example, after the size of
526
 * the Initial token, there are the Initial packet header overheads and then
527
 * encryption/AEAD tag overheads. After that, the minimum room for frame data in
528
 * order to guarantee forward progress must be guaranteed. For example, a crypto
529
 * stream needs to always be able to serialize at least one byte in a CRYPTO
530
 * frame in order to make forward progress. Because the offset field of a CRYPTO
531
 * frame uses a variable-length integer, the number of bytes needed to ensure
532
 * this also varies.
533
 *
534
 * Rather than trying to get this boundary condition check actually right,
535
 * require a reasonable amount of slack to avoid pathological behaviours. (After
536
 * all, transmitting a CRYPTO stream one byte at a time is probably not
537
 * desirable anyway.)
538
 *
539
 * We choose 160 bytes as the required margin, which is double the rough
540
 * estimation of the minimum we would require to guarantee forward progress
541
 * under worst case packet overheads.
542
 */
543
1.75k
#define TXP_REQUIRED_TOKEN_MARGIN 160
544
545
static int txp_check_token_len(size_t token_len, size_t mdpl)
546
51.2k
{
547
51.2k
    if (token_len == 0)
548
50.4k
        return 1;
549
550
885
    if (token_len >= mdpl)
551
6
        return 0;
552
553
879
    if (TXP_REQUIRED_TOKEN_MARGIN >= mdpl)
554
        /* (should not be possible because MDPL must be at least 1200) */
555
0
        return 0;
556
557
879
    if (token_len > mdpl - TXP_REQUIRED_TOKEN_MARGIN)
558
6
        return 0;
559
560
873
    return 1;
561
879
}
562
563
int ossl_quic_tx_packetiser_set_initial_token(OSSL_QUIC_TX_PACKETISER *txp,
564
    const unsigned char *token,
565
    size_t token_len,
566
    ossl_quic_initial_token_free_fn *free_cb,
567
    void *free_cb_arg)
568
51.2k
{
569
51.2k
    if (!txp_check_token_len(token_len, txp_get_mdpl(txp)))
570
12
        return 0;
571
572
51.2k
    if (txp->initial_token != NULL && txp->initial_token_free_cb != NULL)
573
873
        txp->initial_token_free_cb(txp->initial_token, txp->initial_token_len,
574
873
            txp->initial_token_free_cb_arg);
575
576
51.2k
    txp->initial_token = token;
577
51.2k
    txp->initial_token_len = token_len;
578
51.2k
    txp->initial_token_free_cb = free_cb;
579
51.2k
    txp->initial_token_free_cb_arg = free_cb_arg;
580
51.2k
    return 1;
581
51.2k
}
582
583
int ossl_quic_tx_packetiser_set_cur_dcid(OSSL_QUIC_TX_PACKETISER *txp,
584
    const QUIC_CONN_ID *dcid)
585
51.9k
{
586
51.9k
    if (dcid == NULL) {
587
0
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
588
0
        return 0;
589
0
    }
590
591
51.9k
    txp->args.cur_dcid = *dcid;
592
51.9k
    return 1;
593
51.9k
}
594
595
int ossl_quic_tx_packetiser_set_cur_scid(OSSL_QUIC_TX_PACKETISER *txp,
596
    const QUIC_CONN_ID *scid)
597
0
{
598
0
    if (scid == NULL) {
599
0
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
600
0
        return 0;
601
0
    }
602
603
0
    txp->args.cur_scid = *scid;
604
0
    return 1;
605
0
}
606
607
/* Change the destination L4 address the TXP uses to send datagrams. */
608
int ossl_quic_tx_packetiser_set_peer(OSSL_QUIC_TX_PACKETISER *txp,
609
    const BIO_ADDR *peer)
610
50.4k
{
611
50.4k
    if (peer == NULL) {
612
0
        BIO_ADDR_clear(&txp->args.peer);
613
0
        return 1;
614
0
    }
615
616
50.4k
    return BIO_ADDR_copy(&txp->args.peer, peer);
617
50.4k
}
618
619
void ossl_quic_tx_packetiser_set_ack_tx_cb(OSSL_QUIC_TX_PACKETISER *txp,
620
    void (*cb)(const OSSL_QUIC_FRAME_ACK *ack,
621
        uint32_t pn_space,
622
        void *arg),
623
    void *cb_arg)
624
50.4k
{
625
50.4k
    txp->ack_tx_cb = cb;
626
50.4k
    txp->ack_tx_cb_arg = cb_arg;
627
50.4k
}
628
629
void ossl_quic_tx_packetiser_set_qlog_cb(OSSL_QUIC_TX_PACKETISER *txp,
630
    QLOG *(*get_qlog_cb)(void *arg),
631
    void *get_qlog_cb_arg)
632
0
{
633
0
    ossl_quic_fifd_set_qlog_cb(&txp->fifd, get_qlog_cb, get_qlog_cb_arg);
634
0
}
635
636
int ossl_quic_tx_packetiser_discard_enc_level(OSSL_QUIC_TX_PACKETISER *txp,
637
    uint32_t enc_level)
638
28.8k
{
639
28.8k
    if (enc_level >= QUIC_ENC_LEVEL_NUM) {
640
0
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
641
0
        return 0;
642
0
    }
643
644
28.8k
    if (enc_level != QUIC_ENC_LEVEL_0RTT)
645
28.8k
        txp->args.crypto[ossl_quic_enc_level_to_pn_space(enc_level)] = NULL;
646
647
28.8k
    return 1;
648
28.8k
}
649
650
void ossl_quic_tx_packetiser_notify_handshake_complete(OSSL_QUIC_TX_PACKETISER *txp)
651
12.2k
{
652
12.2k
    txp->handshake_complete = 1;
653
12.2k
}
654
655
void ossl_quic_tx_packetiser_schedule_handshake_done(OSSL_QUIC_TX_PACKETISER *txp)
656
0
{
657
0
    txp->want_handshake_done = 1;
658
0
}
659
660
void ossl_quic_tx_packetiser_schedule_ack_eliciting(OSSL_QUIC_TX_PACKETISER *txp,
661
    uint32_t pn_space)
662
25.7M
{
663
25.7M
    txp->force_ack_eliciting |= (1UL << pn_space);
664
25.7M
}
665
666
void ossl_quic_tx_packetiser_schedule_ack(OSSL_QUIC_TX_PACKETISER *txp,
667
    uint32_t pn_space)
668
31.5k
{
669
31.5k
    txp->want_ack |= (1UL << pn_space);
670
31.5k
}
671
672
0
#define TXP_ERR_INTERNAL 0 /* Internal (e.g. alloc) error */
673
75.5M
#define TXP_ERR_SUCCESS 1 /* Success */
674
#define TXP_ERR_SPACE 2 /* Not enough room for another packet */
675
#define TXP_ERR_INPUT 3 /* Invalid/malformed input */
676
677
/*
678
 * Generates a datagram by polling the various ELs to determine if they want to
679
 * generate any frames, and generating a datagram which coalesces packets for
680
 * any ELs which do.
681
 */
682
int ossl_quic_tx_packetiser_generate(OSSL_QUIC_TX_PACKETISER *txp,
683
    QUIC_TXP_STATUS *status)
684
32.7M
{
685
    /*
686
     * Called to generate one or more datagrams, each containing one or more
687
     * packets.
688
     *
689
     * There are some tricky things to note here:
690
     *
691
     *   - The TXP is only concerned with generating encrypted packets;
692
     *     other packets use a different path.
693
     *
694
     *   - Any datagram containing an Initial packet must have a payload length
695
     *     (DPL) of at least 1200 bytes. This padding need not necessarily be
696
     *     found in the Initial packet.
697
     *
698
     *     - It is desirable to be able to coalesce an Initial packet
699
     *       with a Handshake packet. Since, before generating the Handshake
700
     *       packet, we do not know how long it will be, we cannot know the
701
     *       correct amount of padding to ensure a DPL of at least 1200 bytes.
702
     *       Thus this padding must added to the Handshake packet (or whatever
703
     *       packet is the last in the datagram).
704
     *
705
     *     - However, at the time that we generate the Initial packet,
706
     *       we do not actually know for sure that we will be followed
707
     *       in the datagram by another packet. For example, suppose we have
708
     *       some queued data (e.g. crypto stream data for the HANDSHAKE EL)
709
     *       it looks like we will want to send on the HANDSHAKE EL.
710
     *       We could assume padding will be placed in the Handshake packet
711
     *       subsequently and avoid adding any padding to the Initial packet
712
     *       (which would leave no room for the Handshake packet in the
713
     *       datagram).
714
     *
715
     *       However, this is not actually a safe assumption. Suppose that we
716
     *       are using a link with a MDPL of 1200 bytes, the minimum allowed by
717
     *       QUIC. Suppose that the Initial packet consumes 1195 bytes in total.
718
     *       Since it is not possible to fit a Handshake packet in just 5 bytes,
719
     *       upon trying to add a Handshake packet after generating the Initial
720
     *       packet, we will discover we have no room to fit it! This is not a
721
     *       problem in itself as another datagram can be sent subsequently, but
722
     *       it is a problem because we were counting to use that packet to hold
723
     *       the essential padding. But if we have already finished encrypting
724
     *       the Initial packet, we cannot go and add padding to it anymore.
725
     *       This leaves us stuck.
726
     *
727
     * Because of this, we have to plan multiple packets simultaneously, such
728
     * that we can start generating a Handshake (or 0-RTT or 1-RTT, or so on)
729
     * packet while still having the option to go back and add padding to the
730
     * Initial packet if it turns out to be needed.
731
     *
732
     * Trying to predict ahead of time (e.g. during Initial packet generation)
733
     * whether we will successfully generate a subsequent packet is fraught with
734
     * error as it relies on a large number of variables:
735
     *
736
     *   - Do we have room to fit a packet header? (Consider that due to
737
     *     variable-length integer encoding this is highly variable and can even
738
     *     depend on payload length due to a variable-length Length field.)
739
     *
740
     *   - Can we fit even a single one of the frames we want to put in this
741
     *     packet in the packet? (Each frame type has a bespoke encoding. While
742
     *     our encodings of some frame types are adaptive based on the available
743
     *     room - e.g. STREAM frames - ultimately all frame types have some
744
     *     absolute minimum number of bytes to be successfully encoded. For
745
     *     example, if after an Initial packet there is enough room to encode
746
     *     only one byte of frame data, it is quite likely we can't send any of
747
     *     the frames we wanted to send.) While this is not strictly a problem
748
     *     because we could just fill the packet with padding frames, this is a
749
     *     pointless packet and is wasteful.
750
     *
751
     * Thus we adopt a multi-phase architecture:
752
     *
753
     *   1. Archetype Selection: Determine desired packet archetype.
754
     *
755
     *   2. Packet Staging: Generation of packet information and packet payload
756
     *      data (frame data) into staging areas.
757
     *
758
     *   3. Packet Adjustment: Adjustment of staged packets, adding padding to
759
     *      the staged packets if needed.
760
     *
761
     *   4. Commit: The packets are sent to the QTX and recorded as having been
762
     *      sent to the FIFM.
763
     *
764
     */
765
32.7M
    int res = 0, rc;
766
32.7M
    uint32_t archetype, enc_level;
767
32.7M
    uint32_t conn_close_enc_level = QUIC_ENC_LEVEL_NUM;
768
32.7M
    struct txp_pkt pkt[QUIC_ENC_LEVEL_NUM];
769
32.7M
    size_t pkts_done = 0;
770
32.7M
    uint64_t cc_limit = txp->args.cc_method->get_tx_allowance(txp->args.cc_data);
771
32.7M
    int need_padding = 0, txpim_pkt_reffed;
772
773
32.7M
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
774
163M
        enc_level < QUIC_ENC_LEVEL_NUM;
775
130M
        ++enc_level)
776
130M
        pkt[enc_level].h_valid = 0;
777
778
32.7M
    memset(status, 0, sizeof(*status));
779
780
    /*
781
     * Should not be needed, but a sanity check in case anyone else has been
782
     * using the QTX.
783
     */
784
32.7M
    ossl_qtx_finish_dgram(txp->args.qtx);
785
786
    /* 1. Archetype Selection */
787
32.7M
    archetype = txp_determine_archetype(txp, cc_limit);
788
789
    /* 2. Packet Staging */
790
32.7M
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
791
163M
        enc_level < QUIC_ENC_LEVEL_NUM;
792
130M
        ++enc_level) {
793
130M
        size_t running_total = (enc_level > QUIC_ENC_LEVEL_INITIAL)
794
130M
            ? pkt[enc_level - 1].geom.hwm
795
130M
            : 0;
796
797
130M
        pkt[enc_level].geom.hwm = running_total;
798
799
130M
        if (!txp_should_try_staging(txp, enc_level, archetype, cc_limit,
800
130M
                &conn_close_enc_level))
801
105M
            continue;
802
803
24.8M
        if (!txp_pkt_init(&pkt[enc_level], txp, enc_level, archetype,
804
24.8M
                running_total))
805
            /*
806
             * If this fails this is not a fatal error - it means the geometry
807
             * planning determined there was not enough space for another
808
             * packet. So just proceed with what we've already planned for.
809
             */
810
17
            break;
811
812
24.8M
        rc = txp_generate_for_el(txp, &pkt[enc_level],
813
24.8M
            conn_close_enc_level == enc_level);
814
24.8M
        if (rc != TXP_ERR_SUCCESS)
815
0
            goto out;
816
817
24.8M
        if (pkt[enc_level].force_pad)
818
            /*
819
             * txp_generate_for_el emitted a frame which forces packet padding.
820
             */
821
3.85k
            need_padding = 1;
822
823
24.8M
        pkt[enc_level].geom.hwm = running_total
824
24.8M
            + pkt[enc_level].h.bytes_appended
825
24.8M
            + pkt[enc_level].geom.pkt_overhead;
826
24.8M
    }
827
828
    /* 3. Packet Adjustment */
829
32.7M
    if (pkt[QUIC_ENC_LEVEL_INITIAL].h_valid
830
17.2M
        && pkt[QUIC_ENC_LEVEL_INITIAL].h.bytes_appended > 0)
831
        /*
832
         * We have an Initial packet in this datagram, so we need to make sure
833
         * the total size of the datagram is adequate.
834
         */
835
4.59M
        need_padding = 1;
836
837
32.7M
    if (need_padding) {
838
4.59M
        size_t total_dgram_size = 0;
839
4.59M
        const size_t min_dpl = QUIC_MIN_INITIAL_DGRAM_LEN;
840
4.59M
        uint32_t pad_el = QUIC_ENC_LEVEL_NUM;
841
842
4.59M
        for (enc_level = QUIC_ENC_LEVEL_INITIAL;
843
22.9M
            enc_level < QUIC_ENC_LEVEL_NUM;
844
18.3M
            ++enc_level)
845
18.3M
            if (pkt[enc_level].h_valid && pkt[enc_level].h.bytes_appended > 0) {
846
4.63M
                if (pad_el == QUIC_ENC_LEVEL_NUM
847
                    /*
848
                     * We might not be able to add padding, for example if we
849
                     * are using the ACK_ONLY archetype.
850
                     */
851
4.62M
                    && pkt[enc_level].geom.adata.allow_padding
852
622k
                    && !pkt[enc_level].h.done_implicit)
853
622k
                    pad_el = enc_level;
854
855
4.63M
                txp_pkt_postgen_update_pkt_overhead(&pkt[enc_level], txp);
856
4.63M
                total_dgram_size += pkt[enc_level].geom.pkt_overhead
857
4.63M
                    + pkt[enc_level].h.bytes_appended;
858
4.63M
            }
859
860
4.59M
        if (pad_el != QUIC_ENC_LEVEL_NUM && total_dgram_size < min_dpl) {
861
621k
            size_t deficit = min_dpl - total_dgram_size;
862
863
621k
            if (!txp_pkt_append_padding(&pkt[pad_el], txp, deficit))
864
2
                goto out;
865
866
621k
            total_dgram_size += deficit;
867
868
            /*
869
             * Padding frames make a packet ineligible for being a non-inflight
870
             * packet.
871
             */
872
621k
            pkt[pad_el].tpkt->ackm_pkt.is_inflight = 1;
873
621k
        }
874
875
        /*
876
         * If we have failed to make a datagram of adequate size, for example
877
         * because we have a padding requirement but are using the ACK_ONLY
878
         * archetype (because we are CC limited), which precludes us from
879
         * sending padding, give up on generating the datagram - there is
880
         * nothing we can do.
881
         */
882
4.59M
        if (total_dgram_size < min_dpl) {
883
3.97M
            res = 1;
884
3.97M
            goto out;
885
3.97M
        }
886
4.59M
    }
887
888
    /* 4. Commit */
889
28.7M
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
890
143M
        enc_level < QUIC_ENC_LEVEL_NUM;
891
114M
        ++enc_level) {
892
893
114M
        if (!pkt[enc_level].h_valid)
894
            /* Did not attempt to generate a packet for this EL. */
895
94.5M
            continue;
896
897
20.4M
        if (pkt[enc_level].h.bytes_appended == 0)
898
            /* Nothing was generated for this EL, so skip. */
899
19.5M
            continue;
900
901
869k
        rc = txp_pkt_commit(txp, &pkt[enc_level], archetype,
902
869k
            &txpim_pkt_reffed);
903
869k
        if (rc) {
904
869k
            status->sent_ack_eliciting
905
869k
                = status->sent_ack_eliciting
906
866k
                || pkt[enc_level].tpkt->ackm_pkt.is_ack_eliciting;
907
908
869k
            if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE)
909
111k
                status->sent_handshake
910
111k
                    = (pkt[enc_level].h_valid
911
111k
                        && pkt[enc_level].h.bytes_appended > 0);
912
869k
        }
913
914
869k
        if (txpim_pkt_reffed)
915
869k
            pkt[enc_level].tpkt = NULL; /* don't free */
916
917
869k
        if (!rc)
918
0
            goto out;
919
920
869k
        ++pkts_done;
921
869k
    }
922
923
    /* Flush & Cleanup */
924
28.7M
    res = 1;
925
32.7M
out:
926
32.7M
    ossl_qtx_finish_dgram(txp->args.qtx);
927
928
32.7M
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
929
163M
        enc_level < QUIC_ENC_LEVEL_NUM;
930
130M
        ++enc_level)
931
130M
        txp_pkt_cleanup(&pkt[enc_level], txp);
932
933
32.7M
    status->sent_pkt = pkts_done;
934
935
32.7M
    return res;
936
28.7M
}
937
938
static const struct archetype_data archetypes[QUIC_ENC_LEVEL_NUM][TX_PACKETISER_ARCHETYPE_NUM] = {
939
    /* EL 0(INITIAL) */
940
    {
941
        /* EL 0(INITIAL) - Archetype 0(NORMAL) */
942
        {
943
            /*allow_ack                       =*/1,
944
            /*allow_ping                      =*/1,
945
            /*allow_crypto                    =*/1,
946
            /*allow_handshake_done            =*/0,
947
            /*allow_path_challenge            =*/0,
948
            /*allow_path_response             =*/0,
949
            /*allow_new_conn_id               =*/0,
950
            /*allow_retire_conn_id            =*/0,
951
            /*allow_stream_rel                =*/0,
952
            /*allow_conn_fc                   =*/0,
953
            /*allow_conn_close                =*/1,
954
            /*allow_cfq_other                 =*/0,
955
            /*allow_new_token                 =*/0,
956
            /*allow_force_ack_eliciting       =*/1,
957
            /*allow_padding                   =*/1,
958
            /*require_ack_eliciting           =*/0,
959
            /*bypass_cc                       =*/0,
960
        },
961
        /* EL 0(INITIAL) - Archetype 1(PROBE) */
962
        {
963
            /*allow_ack                       =*/1,
964
            /*allow_ping                      =*/1,
965
            /*allow_crypto                    =*/1,
966
            /*allow_handshake_done            =*/0,
967
            /*allow_path_challenge            =*/0,
968
            /*allow_path_response             =*/0,
969
            /*allow_new_conn_id               =*/0,
970
            /*allow_retire_conn_id            =*/0,
971
            /*allow_stream_rel                =*/0,
972
            /*allow_conn_fc                   =*/0,
973
            /*allow_conn_close                =*/1,
974
            /*allow_cfq_other                 =*/0,
975
            /*allow_new_token                 =*/0,
976
            /*allow_force_ack_eliciting       =*/1,
977
            /*allow_padding                   =*/1,
978
            /*require_ack_eliciting           =*/1,
979
            /*bypass_cc                       =*/1,
980
        },
981
        /* EL 0(INITIAL) - Archetype 2(ACK_ONLY) */
982
        {
983
            /*allow_ack                       =*/1,
984
            /*allow_ping                      =*/0,
985
            /*allow_crypto                    =*/0,
986
            /*allow_handshake_done            =*/0,
987
            /*allow_path_challenge            =*/0,
988
            /*allow_path_response             =*/0,
989
            /*allow_new_conn_id               =*/0,
990
            /*allow_retire_conn_id            =*/0,
991
            /*allow_stream_rel                =*/0,
992
            /*allow_conn_fc                   =*/0,
993
            /*allow_conn_close                =*/0,
994
            /*allow_cfq_other                 =*/0,
995
            /*allow_new_token                 =*/0,
996
            /*allow_force_ack_eliciting       =*/1,
997
            /*allow_padding                   =*/0,
998
            /*require_ack_eliciting           =*/0,
999
            /*bypass_cc                       =*/1,
1000
        },
1001
    },
1002
    /* EL 1(HANDSHAKE) */
1003
    {
1004
        /* EL 1(HANDSHAKE) - Archetype 0(NORMAL) */
1005
        {
1006
            /*allow_ack                       =*/1,
1007
            /*allow_ping                      =*/1,
1008
            /*allow_crypto                    =*/1,
1009
            /*allow_handshake_done            =*/0,
1010
            /*allow_path_challenge            =*/0,
1011
            /*allow_path_response             =*/0,
1012
            /*allow_new_conn_id               =*/0,
1013
            /*allow_retire_conn_id            =*/0,
1014
            /*allow_stream_rel                =*/0,
1015
            /*allow_conn_fc                   =*/0,
1016
            /*allow_conn_close                =*/1,
1017
            /*allow_cfq_other                 =*/0,
1018
            /*allow_new_token                 =*/0,
1019
            /*allow_force_ack_eliciting       =*/1,
1020
            /*allow_padding                   =*/1,
1021
            /*require_ack_eliciting           =*/0,
1022
            /*bypass_cc                       =*/0,
1023
        },
1024
        /* EL 1(HANDSHAKE) - Archetype 1(PROBE) */
1025
        {
1026
            /*allow_ack                       =*/1,
1027
            /*allow_ping                      =*/1,
1028
            /*allow_crypto                    =*/1,
1029
            /*allow_handshake_done            =*/0,
1030
            /*allow_path_challenge            =*/0,
1031
            /*allow_path_response             =*/0,
1032
            /*allow_new_conn_id               =*/0,
1033
            /*allow_retire_conn_id            =*/0,
1034
            /*allow_stream_rel                =*/0,
1035
            /*allow_conn_fc                   =*/0,
1036
            /*allow_conn_close                =*/1,
1037
            /*allow_cfq_other                 =*/0,
1038
            /*allow_new_token                 =*/0,
1039
            /*allow_force_ack_eliciting       =*/1,
1040
            /*allow_padding                   =*/1,
1041
            /*require_ack_eliciting           =*/1,
1042
            /*bypass_cc                       =*/1,
1043
        },
1044
        /* EL 1(HANDSHAKE) - Archetype 2(ACK_ONLY) */
1045
        {
1046
            /*allow_ack                       =*/1,
1047
            /*allow_ping                      =*/0,
1048
            /*allow_crypto                    =*/0,
1049
            /*allow_handshake_done            =*/0,
1050
            /*allow_path_challenge            =*/0,
1051
            /*allow_path_response             =*/0,
1052
            /*allow_new_conn_id               =*/0,
1053
            /*allow_retire_conn_id            =*/0,
1054
            /*allow_stream_rel                =*/0,
1055
            /*allow_conn_fc                   =*/0,
1056
            /*allow_conn_close                =*/0,
1057
            /*allow_cfq_other                 =*/0,
1058
            /*allow_new_token                 =*/0,
1059
            /*allow_force_ack_eliciting       =*/1,
1060
            /*allow_padding                   =*/0,
1061
            /*require_ack_eliciting           =*/0,
1062
            /*bypass_cc                       =*/1,
1063
        },
1064
    },
1065
    /* EL 2(0RTT) */
1066
    {
1067
        /* EL 2(0RTT) - Archetype 0(NORMAL) */
1068
        {
1069
            /*allow_ack                       =*/0,
1070
            /*allow_ping                      =*/1,
1071
            /*allow_crypto                    =*/0,
1072
            /*allow_handshake_done            =*/0,
1073
            /*allow_path_challenge            =*/0,
1074
            /*allow_path_response             =*/0,
1075
            /*allow_new_conn_id               =*/1,
1076
            /*allow_retire_conn_id            =*/1,
1077
            /*allow_stream_rel                =*/1,
1078
            /*allow_conn_fc                   =*/1,
1079
            /*allow_conn_close                =*/1,
1080
            /*allow_cfq_other                 =*/0,
1081
            /*allow_new_token                 =*/0,
1082
            /*allow_force_ack_eliciting       =*/0,
1083
            /*allow_padding                   =*/1,
1084
            /*require_ack_eliciting           =*/0,
1085
            /*bypass_cc                       =*/0,
1086
        },
1087
        /* EL 2(0RTT) - Archetype 1(PROBE) */
1088
        {
1089
            /*allow_ack                       =*/0,
1090
            /*allow_ping                      =*/1,
1091
            /*allow_crypto                    =*/0,
1092
            /*allow_handshake_done            =*/0,
1093
            /*allow_path_challenge            =*/0,
1094
            /*allow_path_response             =*/0,
1095
            /*allow_new_conn_id               =*/1,
1096
            /*allow_retire_conn_id            =*/1,
1097
            /*allow_stream_rel                =*/1,
1098
            /*allow_conn_fc                   =*/1,
1099
            /*allow_conn_close                =*/1,
1100
            /*allow_cfq_other                 =*/0,
1101
            /*allow_new_token                 =*/0,
1102
            /*allow_force_ack_eliciting       =*/0,
1103
            /*allow_padding                   =*/1,
1104
            /*require_ack_eliciting           =*/1,
1105
            /*bypass_cc                       =*/1,
1106
        },
1107
        /* EL 2(0RTT) - Archetype 2(ACK_ONLY) */
1108
        {
1109
            /*allow_ack                       =*/0,
1110
            /*allow_ping                      =*/0,
1111
            /*allow_crypto                    =*/0,
1112
            /*allow_handshake_done            =*/0,
1113
            /*allow_path_challenge            =*/0,
1114
            /*allow_path_response             =*/0,
1115
            /*allow_new_conn_id               =*/0,
1116
            /*allow_retire_conn_id            =*/0,
1117
            /*allow_stream_rel                =*/0,
1118
            /*allow_conn_fc                   =*/0,
1119
            /*allow_conn_close                =*/0,
1120
            /*allow_cfq_other                 =*/0,
1121
            /*allow_new_token                 =*/0,
1122
            /*allow_force_ack_eliciting       =*/0,
1123
            /*allow_padding                   =*/0,
1124
            /*require_ack_eliciting           =*/0,
1125
            /*bypass_cc                       =*/1,
1126
        },
1127
    },
1128
    /* EL 3(1RTT) */
1129
    {
1130
        /* EL 3(1RTT) - Archetype 0(NORMAL) */
1131
        {
1132
            /*allow_ack                       =*/1,
1133
            /*allow_ping                      =*/1,
1134
            /*allow_crypto                    =*/1,
1135
            /*allow_handshake_done            =*/1,
1136
            /*allow_path_challenge            =*/0,
1137
            /*allow_path_response             =*/1,
1138
            /*allow_new_conn_id               =*/1,
1139
            /*allow_retire_conn_id            =*/1,
1140
            /*allow_stream_rel                =*/1,
1141
            /*allow_conn_fc                   =*/1,
1142
            /*allow_conn_close                =*/1,
1143
            /*allow_cfq_other                 =*/1,
1144
            /*allow_new_token                 =*/1,
1145
            /*allow_force_ack_eliciting       =*/1,
1146
            /*allow_padding                   =*/1,
1147
            /*require_ack_eliciting           =*/0,
1148
            /*bypass_cc                       =*/0,
1149
        },
1150
        /* EL 3(1RTT) - Archetype 1(PROBE) */
1151
        {
1152
            /*allow_ack                       =*/1,
1153
            /*allow_ping                      =*/1,
1154
            /*allow_crypto                    =*/1,
1155
            /*allow_handshake_done            =*/1,
1156
            /*allow_path_challenge            =*/0,
1157
            /*allow_path_response             =*/1,
1158
            /*allow_new_conn_id               =*/1,
1159
            /*allow_retire_conn_id            =*/1,
1160
            /*allow_stream_rel                =*/1,
1161
            /*allow_conn_fc                   =*/1,
1162
            /*allow_conn_close                =*/1,
1163
            /*allow_cfq_other                 =*/1,
1164
            /*allow_new_token                 =*/1,
1165
            /*allow_force_ack_eliciting       =*/1,
1166
            /*allow_padding                   =*/1,
1167
            /*require_ack_eliciting           =*/1,
1168
            /*bypass_cc                       =*/1,
1169
        },
1170
        /* EL 3(1RTT) - Archetype 2(ACK_ONLY) */
1171
        {
1172
            /*allow_ack                       =*/1,
1173
            /*allow_ping                      =*/0,
1174
            /*allow_crypto                    =*/0,
1175
            /*allow_handshake_done            =*/0,
1176
            /*allow_path_challenge            =*/0,
1177
            /*allow_path_response             =*/0,
1178
            /*allow_new_conn_id               =*/0,
1179
            /*allow_retire_conn_id            =*/0,
1180
            /*allow_stream_rel                =*/0,
1181
            /*allow_conn_fc                   =*/0,
1182
            /*allow_conn_close                =*/0,
1183
            /*allow_cfq_other                 =*/0,
1184
            /*allow_new_token                 =*/0,
1185
            /*allow_force_ack_eliciting       =*/1,
1186
            /*allow_padding                   =*/0,
1187
            /*require_ack_eliciting           =*/0,
1188
            /*bypass_cc                       =*/1,
1189
        } }
1190
};
1191
1192
static int txp_get_archetype_data(uint32_t enc_level,
1193
    uint32_t archetype,
1194
    struct archetype_data *a)
1195
139M
{
1196
139M
    if (enc_level >= QUIC_ENC_LEVEL_NUM
1197
139M
        || archetype >= TX_PACKETISER_ARCHETYPE_NUM)
1198
0
        return 0;
1199
1200
    /* No need to avoid copying this as it should not exceed one int in size. */
1201
139M
    *a = archetypes[enc_level][archetype];
1202
139M
    return 1;
1203
139M
}
1204
1205
static int txp_determine_geometry(OSSL_QUIC_TX_PACKETISER *txp,
1206
    uint32_t archetype,
1207
    uint32_t enc_level,
1208
    size_t running_total,
1209
    QUIC_PKT_HDR *phdr,
1210
    struct txp_pkt_geom *geom)
1211
50.6M
{
1212
50.6M
    size_t mdpl, cmpl, hdr_len;
1213
1214
    /* Get information about packet archetype. */
1215
50.6M
    if (!txp_get_archetype_data(enc_level, archetype, &geom->adata))
1216
0
        return 0;
1217
1218
    /* Assemble packet header. */
1219
50.6M
    phdr->type = ossl_quic_enc_level_to_pkt_type(enc_level);
1220
50.6M
    phdr->spin_bit = 0;
1221
50.6M
    phdr->pn_len = txp_determine_pn_len(txp);
1222
50.6M
    phdr->partial = 0;
1223
50.6M
    phdr->fixed = 1;
1224
50.6M
    phdr->reserved = 0;
1225
50.6M
    phdr->version = QUIC_VERSION_1;
1226
50.6M
    phdr->dst_conn_id = txp->args.cur_dcid;
1227
50.6M
    phdr->src_conn_id = txp->args.cur_scid;
1228
1229
    /*
1230
     * We need to know the length of the payload to get an accurate header
1231
     * length for non-1RTT packets, because the Length field found in
1232
     * Initial/Handshake/0-RTT packets uses a variable-length encoding. However,
1233
     * we don't have a good idea of the length of our payload, because the
1234
     * length of the payload depends on the room in the datagram after fitting
1235
     * the header, which depends on the size of the header.
1236
     *
1237
     * In general, it does not matter if a packet is slightly shorter (because
1238
     * e.g. we predicted use of a 2-byte length field, but ended up only needing
1239
     * a 1-byte length field). However this does matter for Initial packets
1240
     * which must be at least 1200 bytes, which is also the assumed default MTU;
1241
     * therefore in many cases Initial packets will be padded to 1200 bytes,
1242
     * which means if we overestimated the header size, we will be short by a
1243
     * few bytes and the server will ignore the packet for being too short. In
1244
     * this case, however, such packets always *will* be padded to meet 1200
1245
     * bytes, which requires a 2-byte length field, so we don't actually need to
1246
     * worry about this. Thus we estimate the header length assuming a 2-byte
1247
     * length field here, which should in practice work well in all cases.
1248
     */
1249
50.6M
    phdr->len = OSSL_QUIC_VLINT_2B_MAX - phdr->pn_len;
1250
1251
50.6M
    if (enc_level == QUIC_ENC_LEVEL_INITIAL) {
1252
35.7M
        phdr->token = txp->initial_token;
1253
35.7M
        phdr->token_len = txp->initial_token_len;
1254
35.7M
    } else {
1255
14.9M
        phdr->token = NULL;
1256
14.9M
        phdr->token_len = 0;
1257
14.9M
    }
1258
1259
50.6M
    hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(phdr->dst_conn_id.id_len,
1260
50.6M
        phdr);
1261
50.6M
    if (hdr_len == 0)
1262
0
        return 0;
1263
1264
    /* MDPL: Maximum datagram payload length. */
1265
50.6M
    mdpl = txp_get_mdpl(txp);
1266
1267
    /*
1268
     * CMPL: Maximum encoded packet size we can put into this datagram given any
1269
     * previous packets coalesced into it.
1270
     */
1271
50.6M
    if (running_total > mdpl)
1272
        /* Should not be possible, but if it happens: */
1273
0
        cmpl = 0;
1274
50.6M
    else
1275
50.6M
        cmpl = mdpl - running_total;
1276
1277
    /* CMPPL: Maximum amount we can put into the current packet payload */
1278
50.6M
    if (!txp_determine_ppl_from_pl(txp, cmpl, enc_level, hdr_len, &geom->cmppl))
1279
132
        return 0;
1280
1281
50.6M
    geom->cmpl = cmpl;
1282
50.6M
    geom->pkt_overhead = cmpl - geom->cmppl;
1283
50.6M
    geom->archetype = archetype;
1284
50.6M
    return 1;
1285
50.6M
}
1286
1287
static uint32_t txp_determine_archetype(OSSL_QUIC_TX_PACKETISER *txp,
1288
    uint64_t cc_limit)
1289
72.6M
{
1290
72.6M
    OSSL_ACKM_PROBE_INFO *probe_info
1291
72.6M
        = ossl_ackm_get0_probe_request(txp->args.ackm);
1292
72.6M
    uint32_t pn_space;
1293
1294
    /*
1295
     * If ACKM has requested probe generation (e.g. due to PTO), we generate a
1296
     * Probe-archetype packet. Actually, we determine archetype on a
1297
     * per-datagram basis, so if any EL wants a probe, do a pass in which
1298
     * we try and generate a probe (if needed) for all ELs.
1299
     */
1300
72.6M
    if (probe_info->anti_deadlock_initial > 0
1301
72.6M
        || probe_info->anti_deadlock_handshake > 0)
1302
2.76k
        return TX_PACKETISER_ARCHETYPE_PROBE;
1303
1304
72.6M
    for (pn_space = QUIC_PN_SPACE_INITIAL;
1305
289M
        pn_space < QUIC_PN_SPACE_NUM;
1306
217M
        ++pn_space)
1307
217M
        if (probe_info->pto[pn_space] > 0)
1308
359k
            return TX_PACKETISER_ARCHETYPE_PROBE;
1309
1310
    /*
1311
     * If we are out of CC budget, we cannot send a normal packet,
1312
     * but we can do an ACK-only packet (potentially, if we
1313
     * want to send an ACK).
1314
     */
1315
72.3M
    if (cc_limit == 0)
1316
51.9M
        return TX_PACKETISER_ARCHETYPE_ACK_ONLY;
1317
1318
    /* All other packets. */
1319
20.3M
    return TX_PACKETISER_ARCHETYPE_NORMAL;
1320
72.3M
}
1321
1322
static int txp_should_try_staging(OSSL_QUIC_TX_PACKETISER *txp,
1323
    uint32_t enc_level,
1324
    uint32_t archetype,
1325
    uint64_t cc_limit,
1326
    uint32_t *conn_close_enc_level)
1327
290M
{
1328
290M
    struct archetype_data a;
1329
290M
    uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
1330
290M
    QUIC_CFQ_ITEM *cfq_item;
1331
1332
290M
    if (!ossl_qtx_is_enc_level_provisioned(txp->args.qtx, enc_level))
1333
204M
        return 0;
1334
1335
86.5M
    if (!txp_get_archetype_data(enc_level, archetype, &a))
1336
0
        return 0;
1337
1338
86.5M
    if (!a.bypass_cc && cc_limit == 0)
1339
        /* CC not allowing us to send. */
1340
0
        return 0;
1341
1342
    /*
1343
     * We can produce CONNECTION_CLOSE frames on any EL in principle, which
1344
     * means we need to choose which EL we would prefer to use. After a
1345
     * connection is fully established we have only one provisioned EL and this
1346
     * is a non-issue. Where multiple ELs are provisioned, it is possible the
1347
     * peer does not have the keys for the EL yet, which suggests in general it
1348
     * is preferable to use the lowest EL which is still provisioned.
1349
     *
1350
     * However (RFC 9000 s. 10.2.3 & 12.5) we are also required to not send
1351
     * application CONNECTION_CLOSE frames in non-1-RTT ELs, so as to not
1352
     * potentially leak application data on a connection which has yet to be
1353
     * authenticated. Thus when we have an application CONNECTION_CLOSE frame
1354
     * queued and need to send it on a non-1-RTT EL, we have to convert it
1355
     * into a transport CONNECTION_CLOSE frame which contains no application
1356
     * data. Since this loses information, it suggests we should use the 1-RTT
1357
     * EL to avoid this if possible, even if a lower EL is also available.
1358
     *
1359
     * At the same time, just because we have the 1-RTT EL provisioned locally
1360
     * does not necessarily mean the peer does, for example if a handshake
1361
     * CRYPTO frame has been lost. It is fairly important that CONNECTION_CLOSE
1362
     * is signalled in a way we know our peer can decrypt, as we stop processing
1363
     * connection retransmission logic for real after connection close and
1364
     * simply 'blindly' retransmit the same CONNECTION_CLOSE frame.
1365
     *
1366
     * This is not a major concern for clients, since if a client has a 1-RTT EL
1367
     * provisioned the server is guaranteed to also have a 1-RTT EL provisioned.
1368
     *
1369
     * TODO(QUIC SERVER): Revisit this when server support is added.
1370
     */
1371
86.5M
    if (*conn_close_enc_level > enc_level
1372
72.6M
        && *conn_close_enc_level != QUIC_ENC_LEVEL_1RTT)
1373
72.6M
        *conn_close_enc_level = enc_level;
1374
1375
    /* Do we need to send a PTO probe? */
1376
86.5M
    if (a.allow_force_ack_eliciting) {
1377
86.5M
        OSSL_ACKM_PROBE_INFO *probe_info
1378
86.5M
            = ossl_ackm_get0_probe_request(txp->args.ackm);
1379
1380
86.5M
        if ((enc_level == QUIC_ENC_LEVEL_INITIAL
1381
54.2M
                && probe_info->anti_deadlock_initial > 0)
1382
86.5M
            || (enc_level == QUIC_ENC_LEVEL_HANDSHAKE
1383
9.30M
                && probe_info->anti_deadlock_handshake > 0)
1384
86.5M
            || probe_info->pto[pn_space] > 0)
1385
362k
            return 1;
1386
86.5M
    }
1387
1388
    /* Does the crypto stream for this EL want to produce anything? */
1389
86.2M
    if (a.allow_crypto && sstream_is_pending(txp->args.crypto[pn_space]))
1390
99.0k
        return 1;
1391
1392
    /* Does the ACKM for this PN space want to produce anything? */
1393
86.1M
    if (a.allow_ack && (ossl_ackm_is_ack_desired(txp->args.ackm, pn_space) || (txp->want_ack & (1UL << pn_space)) != 0))
1394
6.57M
        return 1;
1395
1396
    /* Do we need to force emission of an ACK-eliciting packet? */
1397
79.5M
    if (a.allow_force_ack_eliciting
1398
79.5M
        && (txp->force_ack_eliciting & (1UL << pn_space)) != 0)
1399
43.6M
        return 1;
1400
1401
    /* Does the connection-level RXFC want to produce a frame? */
1402
35.8M
    if (a.allow_conn_fc && (txp->want_max_data || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0)))
1403
0
        return 1;
1404
1405
    /* Do we want to produce a MAX_STREAMS frame? */
1406
35.8M
    if (a.allow_conn_fc
1407
9.50M
        && (txp->want_max_streams_bidi
1408
9.50M
            || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc,
1409
9.50M
                0)
1410
9.50M
            || txp->want_max_streams_uni
1411
9.50M
            || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc,
1412
9.50M
                0)))
1413
0
        return 1;
1414
1415
    /* Do we want to produce a HANDSHAKE_DONE frame? */
1416
35.8M
    if (a.allow_handshake_done && txp->want_handshake_done)
1417
0
        return 1;
1418
1419
    /* Do we want to produce a CONNECTION_CLOSE frame? */
1420
35.8M
    if (a.allow_conn_close && txp->want_conn_close && *conn_close_enc_level == enc_level)
1421
        /*
1422
         * This is a bit of a special case since CONNECTION_CLOSE can appear in
1423
         * most packet types, and when we decide we want to send it this status
1424
         * isn't tied to a specific EL. So if we want to send it, we send it
1425
         * only on the lowest non-dropped EL.
1426
         */
1427
10.0k
        return 1;
1428
1429
    /* Does the CFQ have any frames queued for this PN space? */
1430
35.8M
    if (enc_level != QUIC_ENC_LEVEL_0RTT)
1431
35.8M
        for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space);
1432
43.2M
            cfq_item != NULL;
1433
35.8M
            cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) {
1434
7.36M
            uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item);
1435
1436
7.36M
            switch (frame_type) {
1437
0
            case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID:
1438
0
                if (a.allow_new_conn_id)
1439
0
                    return 1;
1440
0
                break;
1441
35.2k
            case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID:
1442
35.2k
                if (a.allow_retire_conn_id)
1443
762
                    return 1;
1444
34.4k
                break;
1445
34.4k
            case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN:
1446
0
                if (a.allow_new_token)
1447
0
                    return 1;
1448
0
                break;
1449
7.32M
            case OSSL_QUIC_FRAME_TYPE_PATH_RESPONSE:
1450
7.32M
                if (a.allow_path_response)
1451
1.23k
                    return 1;
1452
7.32M
                break;
1453
7.32M
            default:
1454
0
                if (a.allow_cfq_other)
1455
0
                    return 1;
1456
0
                break;
1457
7.36M
            }
1458
7.36M
        }
1459
1460
35.8M
    if (a.allow_stream_rel && txp->handshake_complete) {
1461
9.50M
        QUIC_STREAM_ITER it;
1462
1463
        /* If there are any active streams, 0/1-RTT wants to produce a packet.
1464
         * Whether a stream is on the active list is required to be precise
1465
         * (i.e., a stream is never on the active list if we cannot produce a
1466
         * frame for it), and all stream-related frames are governed by
1467
         * a.allow_stream_rel (i.e., if we can send one type of stream-related
1468
         * frame, we can send any of them), so we don't need to inspect
1469
         * individual streams on the active list, just confirm that the active
1470
         * list is non-empty.
1471
         */
1472
9.50M
        ossl_quic_stream_iter_init(&it, txp->args.qsm, 0);
1473
9.50M
        if (it.stream != NULL)
1474
7.84k
            return 1;
1475
9.50M
    }
1476
1477
35.8M
    return 0;
1478
35.8M
}
1479
1480
static int sstream_is_pending(QUIC_SSTREAM *sstream)
1481
23.0M
{
1482
23.0M
    OSSL_QUIC_FRAME_STREAM hdr;
1483
23.0M
    OSSL_QTX_IOVEC iov[2];
1484
23.0M
    size_t num_iov = OSSL_NELEM(iov);
1485
1486
23.0M
    return ossl_quic_sstream_get_stream_frame(sstream, 0, &hdr, iov, &num_iov);
1487
23.0M
}
1488
1489
/* Determine how many bytes we should use for the encoded PN. */
1490
static size_t txp_determine_pn_len(OSSL_QUIC_TX_PACKETISER *txp)
1491
50.6M
{
1492
50.6M
    return 4; /* TODO(QUIC FUTURE) */
1493
50.6M
}
1494
1495
/* Determine plaintext packet payload length from payload length. */
1496
static int txp_determine_ppl_from_pl(OSSL_QUIC_TX_PACKETISER *txp,
1497
    size_t pl,
1498
    uint32_t enc_level,
1499
    size_t hdr_len,
1500
    size_t *r)
1501
50.6M
{
1502
50.6M
    if (pl < hdr_len)
1503
121
        return 0;
1504
1505
50.6M
    pl -= hdr_len;
1506
1507
50.6M
    if (!ossl_qtx_calculate_plaintext_payload_len(txp->args.qtx, enc_level,
1508
50.6M
            pl, &pl))
1509
11
        return 0;
1510
1511
50.6M
    *r = pl;
1512
50.6M
    return 1;
1513
50.6M
}
1514
1515
static size_t txp_get_mdpl(OSSL_QUIC_TX_PACKETISER *txp)
1516
50.7M
{
1517
50.7M
    return ossl_qtx_get_mdpl(txp->args.qtx);
1518
50.7M
}
1519
1520
static QUIC_SSTREAM *get_sstream_by_id(uint64_t stream_id, uint32_t pn_space,
1521
    void *arg)
1522
160k
{
1523
160k
    OSSL_QUIC_TX_PACKETISER *txp = arg;
1524
160k
    QUIC_STREAM *s;
1525
1526
160k
    if (stream_id == UINT64_MAX)
1527
141k
        return txp->args.crypto[pn_space];
1528
1529
18.6k
    s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1530
18.6k
    if (s == NULL)
1531
0
        return NULL;
1532
1533
18.6k
    return s->sstream;
1534
18.6k
}
1535
1536
static void on_regen_notify(uint64_t frame_type, uint64_t stream_id,
1537
    QUIC_TXPIM_PKT *pkt, void *arg)
1538
27.0k
{
1539
27.0k
    OSSL_QUIC_TX_PACKETISER *txp = arg;
1540
1541
27.0k
    switch (frame_type) {
1542
0
    case OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE:
1543
0
        txp->want_handshake_done = 1;
1544
0
        break;
1545
0
    case OSSL_QUIC_FRAME_TYPE_MAX_DATA:
1546
0
        txp->want_max_data = 1;
1547
0
        break;
1548
0
    case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_BIDI:
1549
0
        txp->want_max_streams_bidi = 1;
1550
0
        break;
1551
0
    case OSSL_QUIC_FRAME_TYPE_MAX_STREAMS_UNI:
1552
0
        txp->want_max_streams_uni = 1;
1553
0
        break;
1554
17.0k
    case OSSL_QUIC_FRAME_TYPE_ACK_WITH_ECN:
1555
17.0k
        txp->want_ack |= (1UL << pkt->ackm_pkt.pkt_space);
1556
17.0k
        break;
1557
10.0k
    case OSSL_QUIC_FRAME_TYPE_MAX_STREAM_DATA: {
1558
10.0k
        QUIC_STREAM *s
1559
10.0k
            = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1560
1561
10.0k
        if (s == NULL)
1562
7.99k
            return;
1563
1564
2.04k
        s->want_max_stream_data = 1;
1565
2.04k
        ossl_quic_stream_map_update_state(txp->args.qsm, s);
1566
2.04k
    } break;
1567
0
    case OSSL_QUIC_FRAME_TYPE_STOP_SENDING: {
1568
0
        QUIC_STREAM *s
1569
0
            = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1570
1571
0
        if (s == NULL)
1572
0
            return;
1573
1574
0
        ossl_quic_stream_map_schedule_stop_sending(txp->args.qsm, s);
1575
0
    } break;
1576
0
    case OSSL_QUIC_FRAME_TYPE_RESET_STREAM: {
1577
0
        QUIC_STREAM *s
1578
0
            = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1579
1580
0
        if (s == NULL)
1581
0
            return;
1582
1583
0
        s->want_reset_stream = 1;
1584
0
        ossl_quic_stream_map_update_state(txp->args.qsm, s);
1585
0
    } break;
1586
0
    default:
1587
0
        assert(0);
1588
0
        break;
1589
27.0k
    }
1590
27.0k
}
1591
1592
static int txp_need_ping(OSSL_QUIC_TX_PACKETISER *txp,
1593
    uint32_t pn_space,
1594
    const struct archetype_data *adata)
1595
101M
{
1596
101M
    return adata->allow_ping
1597
4.10M
        && (adata->require_ack_eliciting
1598
3.36M
            || (txp->force_ack_eliciting & (1UL << pn_space)) != 0);
1599
101M
}
1600
1601
static int txp_pkt_init(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp,
1602
    uint32_t enc_level, uint32_t archetype,
1603
    size_t running_total)
1604
50.6M
{
1605
50.6M
    uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
1606
1607
50.6M
    if (!txp_determine_geometry(txp, archetype, enc_level,
1608
50.6M
            running_total, &pkt->phdr, &pkt->geom))
1609
132
        return 0;
1610
1611
    /*
1612
     * Initialise TX helper. If we must be ACK eliciting, reserve 1 byte for
1613
     * PING.
1614
     */
1615
50.6M
    if (!tx_helper_init(&pkt->h, txp, enc_level,
1616
50.6M
            pkt->geom.cmppl,
1617
50.6M
            txp_need_ping(txp, pn_space, &pkt->geom.adata) ? 1 : 0))
1618
0
        return 0;
1619
1620
50.6M
    pkt->h_valid = 1;
1621
50.6M
    pkt->tpkt = NULL;
1622
50.6M
    pkt->stream_head = NULL;
1623
50.6M
    pkt->force_pad = 0;
1624
50.6M
    return 1;
1625
50.6M
}
1626
1627
static void txp_pkt_cleanup(struct txp_pkt *pkt, OSSL_QUIC_TX_PACKETISER *txp)
1628
290M
{
1629
290M
    if (!pkt->h_valid)
1630
239M
        return;
1631
1632
50.6M
    tx_helper_cleanup(&pkt->h);
1633
50.6M
    pkt->h_valid = 0;
1634
1635
50.6M
    if (pkt->tpkt != NULL) {
1636
48.6M
        ossl_quic_txpim_pkt_release(txp->args.txpim, pkt->tpkt);
1637
48.6M
        pkt->tpkt = NULL;
1638
48.6M
    }
1639
50.6M
}
1640
1641
static int txp_pkt_postgen_update_pkt_overhead(struct txp_pkt *pkt,
1642
    OSSL_QUIC_TX_PACKETISER *txp)
1643
7.39M
{
1644
    /*
1645
     * After we have staged and generated our packets, but before we commit
1646
     * them, it is possible for the estimated packet overhead (packet header +
1647
     * AEAD tag size) to shrink slightly because we generated a short packet
1648
     * whose which can be represented in fewer bytes as a variable-length
1649
     * integer than we were (pessimistically) budgeting for. We need to account
1650
     * for this to ensure that we get our padding calculation exactly right.
1651
     *
1652
     * Update pkt_overhead to be accurate now that we know how much data is
1653
     * going in a packet.
1654
     */
1655
7.39M
    size_t hdr_len, ciphertext_len;
1656
1657
7.39M
    if (pkt->h.enc_level == QUIC_ENC_LEVEL_INITIAL)
1658
        /*
1659
         * Don't update overheads for the INITIAL EL - we have not finished
1660
         * appending padding to it and would potentially miscalculate the
1661
         * correct padding if we now update the pkt_overhead field to switch to
1662
         * e.g. a 1-byte length field in the packet header. Since we are padding
1663
         * to QUIC_MIN_INITIAL_DGRAM_LEN which requires a 2-byte length field,
1664
         * this is guaranteed to be moot anyway. See comment in
1665
         * txp_determine_geometry for more information.
1666
         */
1667
7.32M
        return 1;
1668
1669
62.3k
    if (!ossl_qtx_calculate_ciphertext_payload_len(txp->args.qtx, pkt->h.enc_level,
1670
62.3k
            pkt->h.bytes_appended,
1671
62.3k
            &ciphertext_len))
1672
0
        return 0;
1673
1674
62.3k
    pkt->phdr.len = ciphertext_len;
1675
1676
62.3k
    hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(pkt->phdr.dst_conn_id.id_len,
1677
62.3k
        &pkt->phdr);
1678
1679
62.3k
    pkt->geom.pkt_overhead = hdr_len + ciphertext_len - pkt->h.bytes_appended;
1680
62.3k
    return 1;
1681
62.3k
}
1682
1683
static void on_confirm_notify(uint64_t frame_type, uint64_t stream_id,
1684
    QUIC_TXPIM_PKT *pkt, void *arg)
1685
0
{
1686
0
    OSSL_QUIC_TX_PACKETISER *txp = arg;
1687
1688
0
    switch (frame_type) {
1689
0
    case OSSL_QUIC_FRAME_TYPE_STOP_SENDING: {
1690
0
        QUIC_STREAM *s
1691
0
            = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1692
1693
0
        if (s == NULL)
1694
0
            return;
1695
1696
0
        s->acked_stop_sending = 1;
1697
0
        ossl_quic_stream_map_update_state(txp->args.qsm, s);
1698
0
    } break;
1699
0
    case OSSL_QUIC_FRAME_TYPE_RESET_STREAM: {
1700
0
        QUIC_STREAM *s
1701
0
            = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1702
1703
0
        if (s == NULL)
1704
0
            return;
1705
1706
        /*
1707
         * We must already be in RESET_SENT or RESET_RECVD if we are
1708
         * here, so we don't need to check state here.
1709
         */
1710
0
        ossl_quic_stream_map_notify_reset_stream_acked(txp->args.qsm, s);
1711
0
        ossl_quic_stream_map_update_state(txp->args.qsm, s);
1712
0
    } break;
1713
0
    default:
1714
0
        assert(0);
1715
0
        break;
1716
0
    }
1717
0
}
1718
1719
static int txp_pkt_append_padding(struct txp_pkt *pkt,
1720
    OSSL_QUIC_TX_PACKETISER *txp, size_t num_bytes)
1721
1.43M
{
1722
1.43M
    WPACKET *wpkt;
1723
1724
1.43M
    if (num_bytes == 0)
1725
0
        return 1;
1726
1727
1.43M
    if (!ossl_assert(pkt->h_valid))
1728
0
        return 0;
1729
1730
1.43M
    if (!ossl_assert(pkt->tpkt != NULL))
1731
0
        return 0;
1732
1733
1.43M
    wpkt = tx_helper_begin(&pkt->h);
1734
1.43M
    if (wpkt == NULL)
1735
0
        return 0;
1736
1737
1.43M
    if (!ossl_quic_wire_encode_padding(wpkt, num_bytes)) {
1738
4
        tx_helper_rollback(&pkt->h);
1739
4
        return 0;
1740
4
    }
1741
1742
1.43M
    if (!tx_helper_commit(&pkt->h))
1743
0
        return 0;
1744
1745
1.43M
    pkt->tpkt->ackm_pkt.num_bytes += num_bytes;
1746
    /* Cannot be non-inflight if we have a PADDING frame */
1747
1.43M
    pkt->tpkt->ackm_pkt.is_inflight = 1;
1748
1.43M
    return 1;
1749
1.43M
}
1750
1751
static void on_sstream_updated(uint64_t stream_id, void *arg)
1752
17.5k
{
1753
17.5k
    OSSL_QUIC_TX_PACKETISER *txp = arg;
1754
17.5k
    QUIC_STREAM *s;
1755
1756
17.5k
    s = ossl_quic_stream_map_get_by_id(txp->args.qsm, stream_id);
1757
17.5k
    if (s == NULL)
1758
15.4k
        return;
1759
1760
2.13k
    ossl_quic_stream_map_update_state(txp->args.qsm, s);
1761
2.13k
}
1762
1763
/*
1764
 * Returns 1 if we can send that many bytes in closing state, 0 otherwise.
1765
 * Also maintains the bytes sent state if it returns a success.
1766
 */
1767
static int try_commit_conn_close(OSSL_QUIC_TX_PACKETISER *txp, size_t n)
1768
24.1k
{
1769
24.1k
    int res;
1770
1771
    /* We can always send the first connection close frame */
1772
24.1k
    if (txp->closing_bytes_recv == 0)
1773
24.1k
        return 1;
1774
1775
    /*
1776
     * RFC 9000 s. 10.2.1 Closing Connection State:
1777
     *      To avoid being used for an amplification attack, such
1778
     *      endpoints MUST limit the cumulative size of packets it sends
1779
     *      to three times the cumulative size of the packets that are
1780
     *      received and attributed to the connection.
1781
     * and:
1782
     *      An endpoint in the closing state MUST either discard packets
1783
     *      received from an unvalidated address or limit the cumulative
1784
     *      size of packets it sends to an unvalidated address to three
1785
     *      times the size of packets it receives from that address.
1786
     */
1787
0
    res = txp->closing_bytes_xmit + n <= txp->closing_bytes_recv * 3;
1788
1789
    /*
1790
     * Attribute the bytes to the connection, if we are allowed to send them
1791
     * and this isn't the first closing frame.
1792
     */
1793
0
    if (res && txp->closing_bytes_recv != 0)
1794
0
        txp->closing_bytes_xmit += n;
1795
0
    return res;
1796
24.1k
}
1797
1798
void ossl_quic_tx_packetiser_record_received_closing_bytes(
1799
    OSSL_QUIC_TX_PACKETISER *txp, size_t n)
1800
53
{
1801
53
    txp->closing_bytes_recv += n;
1802
53
}
1803
1804
static int txp_generate_pre_token(OSSL_QUIC_TX_PACKETISER *txp,
1805
    struct txp_pkt *pkt,
1806
    int chosen_for_conn_close,
1807
    int *can_be_non_inflight)
1808
50.6M
{
1809
50.6M
    const uint32_t enc_level = pkt->h.enc_level;
1810
50.6M
    const uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
1811
50.6M
    const struct archetype_data *a = &pkt->geom.adata;
1812
50.6M
    QUIC_TXPIM_PKT *tpkt = pkt->tpkt;
1813
50.6M
    struct tx_helper *h = &pkt->h;
1814
50.6M
    const OSSL_QUIC_FRAME_ACK *ack;
1815
50.6M
    OSSL_QUIC_FRAME_ACK ack2;
1816
1817
50.6M
    tpkt->ackm_pkt.largest_acked = QUIC_PN_INVALID;
1818
1819
    /* ACK Frames (Regenerate) */
1820
50.6M
    if (a->allow_ack
1821
50.6M
        && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_ACK
1822
50.6M
        && (((txp->want_ack & (1UL << pn_space)) != 0)
1823
44.4M
            || ossl_ackm_is_ack_desired(txp->args.ackm, pn_space))
1824
6.58M
        && (ack = ossl_ackm_get_ack_frame(txp->args.ackm, pn_space)) != NULL) {
1825
6.58M
        WPACKET *wpkt = tx_helper_begin(h);
1826
1827
6.58M
        if (wpkt == NULL)
1828
0
            return 0;
1829
1830
        /* We do not currently support ECN */
1831
6.58M
        ack2 = *ack;
1832
6.58M
        ack2.ecn_present = 0;
1833
1834
6.58M
        if (ossl_quic_wire_encode_frame_ack(wpkt,
1835
6.58M
                txp->args.ack_delay_exponent,
1836
6.58M
                &ack2)) {
1837
6.12M
            if (!tx_helper_commit(h))
1838
0
                return 0;
1839
1840
6.12M
            tpkt->had_ack_frame = 1;
1841
1842
6.12M
            if (ack->num_ack_ranges > 0)
1843
6.12M
                tpkt->ackm_pkt.largest_acked = ack->ack_ranges[0].end;
1844
1845
6.12M
            if (txp->ack_tx_cb != NULL)
1846
6.12M
                txp->ack_tx_cb(&ack2, pn_space, txp->ack_tx_cb_arg);
1847
6.12M
        } else {
1848
462k
            tx_helper_rollback(h);
1849
462k
        }
1850
6.58M
    }
1851
1852
    /* CONNECTION_CLOSE Frames (Regenerate) */
1853
50.6M
    if (a->allow_conn_close && txp->want_conn_close && chosen_for_conn_close) {
1854
24.3k
        WPACKET *wpkt = tx_helper_begin(h);
1855
24.3k
        OSSL_QUIC_FRAME_CONN_CLOSE f, *pf = &txp->conn_close_frame;
1856
24.3k
        size_t l;
1857
1858
24.3k
        if (wpkt == NULL)
1859
0
            return 0;
1860
1861
        /*
1862
         * Application CONNECTION_CLOSE frames may only be sent in the
1863
         * Application PN space, as otherwise they may be sent before a
1864
         * connection is authenticated and leak application data. Therefore, if
1865
         * we need to send a CONNECTION_CLOSE frame in another PN space and were
1866
         * given an application CONNECTION_CLOSE frame, convert it into a
1867
         * transport CONNECTION_CLOSE frame, removing any sensitive application
1868
         * data.
1869
         *
1870
         * RFC 9000 s. 10.2.3: "A CONNECTION_CLOSE of type 0x1d MUST be replaced
1871
         * by a CONNECTION_CLOSE of type 0x1c when sending the frame in Initial
1872
         * or Handshake packets. Otherwise, information about the application
1873
         * state might be revealed. Endpoints MUST clear the value of the Reason
1874
         * Phrase field and SHOULD use the APPLICATION_ERROR code when
1875
         * converting to a CONNECTION_CLOSE of type 0x1c."
1876
         */
1877
24.3k
        if (pn_space != QUIC_PN_SPACE_APP && pf->is_app) {
1878
0
            pf = &f;
1879
0
            pf->is_app = 0;
1880
0
            pf->frame_type = 0;
1881
0
            pf->error_code = OSSL_QUIC_ERR_APPLICATION_ERROR;
1882
0
            pf->reason = NULL;
1883
0
            pf->reason_len = 0;
1884
0
        }
1885
1886
24.3k
        if (ossl_quic_wire_encode_frame_conn_close(wpkt, pf)
1887
24.1k
            && WPACKET_get_total_written(wpkt, &l)
1888
24.1k
            && try_commit_conn_close(txp, l)) {
1889
24.1k
            if (!tx_helper_commit(h))
1890
0
                return 0;
1891
1892
24.1k
            tpkt->had_conn_close = 1;
1893
24.1k
            *can_be_non_inflight = 0;
1894
24.1k
        } else {
1895
217
            tx_helper_rollback(h);
1896
217
        }
1897
24.3k
    }
1898
1899
50.6M
    return 1;
1900
50.6M
}
1901
1902
static int try_len(size_t space_left, size_t orig_len,
1903
    size_t base_hdr_len, size_t lenbytes,
1904
    uint64_t maxn, size_t *hdr_len, size_t *payload_len)
1905
434k
{
1906
434k
    size_t n;
1907
434k
    size_t maxn_ = maxn > SIZE_MAX ? SIZE_MAX : (size_t)maxn;
1908
1909
434k
    *hdr_len = base_hdr_len + lenbytes;
1910
1911
434k
    if (orig_len == 0 && space_left >= *hdr_len) {
1912
0
        *payload_len = 0;
1913
0
        return 1;
1914
0
    }
1915
1916
434k
    n = orig_len;
1917
434k
    if (n > maxn_)
1918
93.7k
        n = maxn_;
1919
434k
    if (n + *hdr_len > space_left)
1920
103k
        n = (space_left >= *hdr_len) ? space_left - *hdr_len : 0;
1921
1922
434k
    *payload_len = n;
1923
434k
    return n > 0;
1924
434k
}
1925
1926
static int determine_len(size_t space_left, size_t orig_len,
1927
    size_t base_hdr_len,
1928
    uint64_t *hlen, uint64_t *len)
1929
108k
{
1930
108k
    int ok = 0;
1931
108k
    size_t chosen_payload_len = 0;
1932
108k
    size_t chosen_hdr_len = 0;
1933
108k
    size_t payload_len[4], hdr_len[4];
1934
108k
    int i, valid[4] = { 0 };
1935
1936
108k
    valid[0] = try_len(space_left, orig_len, base_hdr_len,
1937
108k
        1, OSSL_QUIC_VLINT_1B_MAX,
1938
108k
        &hdr_len[0], &payload_len[0]);
1939
108k
    valid[1] = try_len(space_left, orig_len, base_hdr_len,
1940
108k
        2, OSSL_QUIC_VLINT_2B_MAX,
1941
108k
        &hdr_len[1], &payload_len[1]);
1942
108k
    valid[2] = try_len(space_left, orig_len, base_hdr_len,
1943
108k
        4, OSSL_QUIC_VLINT_4B_MAX,
1944
108k
        &hdr_len[2], &payload_len[2]);
1945
108k
    valid[3] = try_len(space_left, orig_len, base_hdr_len,
1946
108k
        8, OSSL_QUIC_VLINT_8B_MAX,
1947
108k
        &hdr_len[3], &payload_len[3]);
1948
1949
543k
    for (i = OSSL_NELEM(valid) - 1; i >= 0; --i)
1950
434k
        if (valid[i] && payload_len[i] >= chosen_payload_len) {
1951
340k
            chosen_payload_len = payload_len[i];
1952
340k
            chosen_hdr_len = hdr_len[i];
1953
340k
            ok = 1;
1954
340k
        }
1955
1956
108k
    *hlen = chosen_hdr_len;
1957
108k
    *len = chosen_payload_len;
1958
108k
    return ok;
1959
108k
}
1960
1961
/*
1962
 * Given a CRYPTO frame header with accurate chdr->len and a budget
1963
 * (space_left), try to find the optimal value of chdr->len to fill as much of
1964
 * the budget as possible. This is slightly hairy because larger values of
1965
 * chdr->len cause larger encoded sizes of the length field of the frame, which
1966
 * in turn mean less space available for payload data. We check all possible
1967
 * encodings and choose the optimal encoding.
1968
 */
1969
static int determine_crypto_len(struct tx_helper *h,
1970
    OSSL_QUIC_FRAME_CRYPTO *chdr,
1971
    size_t space_left,
1972
    uint64_t *hlen,
1973
    uint64_t *len)
1974
99.6k
{
1975
99.6k
    size_t orig_len;
1976
99.6k
    size_t base_hdr_len; /* CRYPTO header length without length field */
1977
1978
99.6k
    if (chdr->len > SIZE_MAX)
1979
0
        return 0;
1980
1981
99.6k
    orig_len = (size_t)chdr->len;
1982
1983
99.6k
    chdr->len = 0;
1984
99.6k
    base_hdr_len = ossl_quic_wire_get_encoded_frame_len_crypto_hdr(chdr);
1985
99.6k
    chdr->len = orig_len;
1986
99.6k
    if (base_hdr_len == 0)
1987
0
        return 0;
1988
1989
99.6k
    --base_hdr_len;
1990
1991
99.6k
    return determine_len(space_left, orig_len, base_hdr_len, hlen, len);
1992
99.6k
}
1993
1994
static int determine_stream_len(struct tx_helper *h,
1995
    OSSL_QUIC_FRAME_STREAM *shdr,
1996
    size_t space_left,
1997
    uint64_t *hlen,
1998
    uint64_t *len)
1999
9.00k
{
2000
9.00k
    size_t orig_len;
2001
9.00k
    size_t base_hdr_len; /* STREAM header length without length field */
2002
2003
9.00k
    if (shdr->len > SIZE_MAX)
2004
0
        return 0;
2005
2006
9.00k
    orig_len = (size_t)shdr->len;
2007
2008
9.00k
    shdr->len = 0;
2009
9.00k
    base_hdr_len = ossl_quic_wire_get_encoded_frame_len_stream_hdr(shdr);
2010
9.00k
    shdr->len = orig_len;
2011
9.00k
    if (base_hdr_len == 0)
2012
0
        return 0;
2013
2014
9.00k
    if (shdr->has_explicit_len)
2015
2.08k
        --base_hdr_len;
2016
2017
9.00k
    return determine_len(space_left, orig_len, base_hdr_len, hlen, len);
2018
9.00k
}
2019
2020
static int txp_generate_crypto_frames(OSSL_QUIC_TX_PACKETISER *txp,
2021
    struct txp_pkt *pkt,
2022
    int *have_ack_eliciting)
2023
2.11M
{
2024
2.11M
    const uint32_t enc_level = pkt->h.enc_level;
2025
2.11M
    const uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
2026
2.11M
    QUIC_TXPIM_PKT *tpkt = pkt->tpkt;
2027
2.11M
    struct tx_helper *h = &pkt->h;
2028
2.11M
    size_t num_stream_iovec;
2029
2.11M
    OSSL_QUIC_FRAME_STREAM shdr = { 0 };
2030
2.11M
    OSSL_QUIC_FRAME_CRYPTO chdr = { 0 };
2031
2.11M
    OSSL_QTX_IOVEC iov[2];
2032
2.11M
    uint64_t hdr_bytes;
2033
2.11M
    WPACKET *wpkt;
2034
2.11M
    QUIC_TXPIM_CHUNK chunk = { 0 };
2035
2.11M
    size_t i, space_left;
2036
2037
2.21M
    for (i = 0;; ++i) {
2038
2.21M
        space_left = tx_helper_get_space_left(h);
2039
2040
2.21M
        if (space_left < MIN_FRAME_SIZE_CRYPTO)
2041
33.0k
            return 1; /* no point trying */
2042
2043
        /* Do we have any CRYPTO data waiting? */
2044
2.17M
        num_stream_iovec = OSSL_NELEM(iov);
2045
2.17M
        if (!ossl_quic_sstream_get_stream_frame(txp->args.crypto[pn_space],
2046
2.17M
                i, &shdr, iov,
2047
2.17M
                &num_stream_iovec))
2048
2.07M
            return 1; /* nothing to do */
2049
2050
        /* Convert STREAM frame header to CRYPTO frame header */
2051
99.6k
        chdr.offset = shdr.offset;
2052
99.6k
        chdr.len = shdr.len;
2053
2054
99.6k
        if (chdr.len == 0)
2055
0
            return 1; /* nothing to do */
2056
2057
        /* Find best fit (header length, payload length) combination. */
2058
99.6k
        if (!determine_crypto_len(h, &chdr, space_left, &hdr_bytes,
2059
99.6k
                &chdr.len))
2060
3
            return 1; /* can't fit anything */
2061
2062
        /*
2063
         * Truncate IOVs to match our chosen length.
2064
         *
2065
         * The length cannot be more than SIZE_MAX because this length comes
2066
         * from our send stream buffer.
2067
         */
2068
99.6k
        ossl_quic_sstream_adjust_iov((size_t)chdr.len, iov, num_stream_iovec);
2069
2070
        /*
2071
         * Ensure we have enough iovecs allocated (1 for the header, up to 2 for
2072
         * the stream data.)
2073
         */
2074
99.6k
        if (!txp_el_ensure_iovec(&txp->el[enc_level], h->num_iovec + 3))
2075
0
            return 0; /* alloc error */
2076
2077
        /* Encode the header. */
2078
99.6k
        wpkt = tx_helper_begin(h);
2079
99.6k
        if (wpkt == NULL)
2080
0
            return 0; /* alloc error */
2081
2082
99.6k
        if (!ossl_quic_wire_encode_frame_crypto_hdr(wpkt, &chdr)) {
2083
0
            tx_helper_rollback(h);
2084
0
            return 1; /* can't fit */
2085
0
        }
2086
2087
99.6k
        if (!tx_helper_commit(h))
2088
0
            return 0; /* alloc error */
2089
2090
        /* Add payload iovecs to the helper (infallible). */
2091
199k
        for (i = 0; i < num_stream_iovec; ++i)
2092
99.6k
            tx_helper_append_iovec(h, iov[i].buf, iov[i].buf_len);
2093
2094
99.6k
        *have_ack_eliciting = 1;
2095
99.6k
        tx_helper_unrestrict(h); /* no longer need PING */
2096
2097
        /* Log chunk to TXPIM. */
2098
99.6k
        chunk.stream_id = UINT64_MAX; /* crypto stream */
2099
99.6k
        chunk.start = chdr.offset;
2100
99.6k
        chunk.end = chdr.offset + chdr.len - 1;
2101
99.6k
        chunk.has_fin = 0; /* Crypto stream never ends */
2102
99.6k
        if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
2103
0
            return 0; /* alloc error */
2104
99.6k
    }
2105
2.11M
}
2106
2107
struct chunk_info {
2108
    OSSL_QUIC_FRAME_STREAM shdr;
2109
    uint64_t orig_len;
2110
    OSSL_QTX_IOVEC iov[2];
2111
    size_t num_stream_iovec;
2112
    int valid;
2113
};
2114
2115
static int txp_plan_stream_chunk(OSSL_QUIC_TX_PACKETISER *txp,
2116
    struct tx_helper *h,
2117
    QUIC_SSTREAM *sstream,
2118
    QUIC_TXFC *stream_txfc,
2119
    size_t skip,
2120
    struct chunk_info *chunk,
2121
    uint64_t consumed)
2122
18.9k
{
2123
18.9k
    uint64_t fc_credit, fc_swm, fc_limit;
2124
2125
18.9k
    chunk->num_stream_iovec = OSSL_NELEM(chunk->iov);
2126
18.9k
    chunk->valid = ossl_quic_sstream_get_stream_frame(sstream, skip,
2127
18.9k
        &chunk->shdr,
2128
18.9k
        chunk->iov,
2129
18.9k
        &chunk->num_stream_iovec);
2130
18.9k
    if (!chunk->valid)
2131
6.73k
        return 1;
2132
2133
12.2k
    if (!ossl_assert(chunk->shdr.len > 0 || chunk->shdr.is_fin))
2134
        /* Should only have 0-length chunk if FIN */
2135
0
        return 0;
2136
2137
12.2k
    chunk->orig_len = chunk->shdr.len;
2138
2139
    /* Clamp according to connection and stream-level TXFC. */
2140
12.2k
    fc_credit = ossl_quic_txfc_get_credit(stream_txfc, consumed);
2141
12.2k
    fc_swm = ossl_quic_txfc_get_swm(stream_txfc);
2142
12.2k
    fc_limit = fc_swm + fc_credit;
2143
2144
12.2k
    if (chunk->shdr.len > 0 && chunk->shdr.offset + chunk->shdr.len > fc_limit) {
2145
5.81k
        chunk->shdr.len = (fc_limit <= chunk->shdr.offset)
2146
5.81k
            ? 0
2147
5.81k
            : fc_limit - chunk->shdr.offset;
2148
5.81k
        chunk->shdr.is_fin = 0;
2149
5.81k
    }
2150
2151
12.2k
    if (chunk->shdr.len == 0 && !chunk->shdr.is_fin) {
2152
        /*
2153
         * Nothing to do due to TXFC. Since SSTREAM returns chunks in ascending
2154
         * order of offset we don't need to check any later chunks, so stop
2155
         * iterating here.
2156
         */
2157
5.14k
        chunk->valid = 0;
2158
5.14k
        return 1;
2159
5.14k
    }
2160
2161
7.12k
    return 1;
2162
12.2k
}
2163
2164
/*
2165
 * Returns 0 on fatal error (e.g. allocation failure), 1 on success.
2166
 * *packet_full is set to 1 if there is no longer enough room for another STREAM
2167
 * frame.
2168
 */
2169
static int txp_generate_stream_frames(OSSL_QUIC_TX_PACKETISER *txp,
2170
    struct txp_pkt *pkt,
2171
    uint64_t id,
2172
    QUIC_SSTREAM *sstream,
2173
    QUIC_TXFC *stream_txfc,
2174
    QUIC_STREAM *next_stream,
2175
    int *have_ack_eliciting,
2176
    int *packet_full,
2177
    uint64_t *new_credit_consumed,
2178
    uint64_t conn_consumed)
2179
11.9k
{
2180
11.9k
    int rc = 0;
2181
11.9k
    struct chunk_info chunks[2] = { 0 };
2182
11.9k
    const uint32_t enc_level = pkt->h.enc_level;
2183
11.9k
    QUIC_TXPIM_PKT *tpkt = pkt->tpkt;
2184
11.9k
    struct tx_helper *h = &pkt->h;
2185
11.9k
    OSSL_QUIC_FRAME_STREAM *shdr;
2186
11.9k
    WPACKET *wpkt;
2187
11.9k
    QUIC_TXPIM_CHUNK chunk;
2188
11.9k
    size_t i, j, space_left;
2189
11.9k
    int can_fill_payload, use_explicit_len;
2190
11.9k
    int could_have_following_chunk;
2191
11.9k
    uint64_t orig_len;
2192
11.9k
    uint64_t hdr_len_implicit, payload_len_implicit;
2193
11.9k
    uint64_t hdr_len_explicit, payload_len_explicit;
2194
11.9k
    uint64_t fc_swm, fc_new_hwm;
2195
2196
11.9k
    fc_swm = ossl_quic_txfc_get_swm(stream_txfc);
2197
11.9k
    fc_new_hwm = fc_swm;
2198
2199
    /*
2200
     * Load the first two chunks if any offered by the send stream. We retrieve
2201
     * the next chunk in advance so we can determine if we need to send any more
2202
     * chunks from the same stream after this one, which is needed when
2203
     * determining when we can use an implicit length in a STREAM frame.
2204
     */
2205
25.5k
    for (i = 0; i < 2; ++i) {
2206
18.7k
        if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i, &chunks[i],
2207
18.7k
                conn_consumed))
2208
0
            goto err;
2209
2210
18.7k
        if (i == 0 && !chunks[i].valid) {
2211
            /* No chunks, nothing to do. */
2212
5.09k
            rc = 1;
2213
5.09k
            goto err;
2214
5.09k
        }
2215
13.6k
        chunks[i].shdr.stream_id = id;
2216
13.6k
    }
2217
2218
12.0k
    for (i = 0;; ++i) {
2219
12.0k
        space_left = tx_helper_get_space_left(h);
2220
2221
12.0k
        if (!chunks[i % 2].valid) {
2222
            /* Out of chunks; we're done. */
2223
5.00k
            rc = 1;
2224
5.00k
            goto err;
2225
5.00k
        }
2226
2227
7.07k
        if (space_left < MIN_FRAME_SIZE_STREAM) {
2228
151
            *packet_full = 1;
2229
151
            rc = 1;
2230
151
            goto err;
2231
151
        }
2232
2233
6.91k
        if (!ossl_assert(!h->done_implicit))
2234
            /*
2235
             * Logic below should have ensured we didn't append an
2236
             * implicit-length unless we filled the packet or didn't have
2237
             * another stream to handle, so this should not be possible.
2238
             */
2239
0
            goto err;
2240
2241
6.91k
        shdr = &chunks[i % 2].shdr;
2242
6.91k
        orig_len = chunks[i % 2].orig_len;
2243
6.91k
        if (i > 0)
2244
            /* Load next chunk for lookahead. */
2245
235
            if (!txp_plan_stream_chunk(txp, h, sstream, stream_txfc, i + 1,
2246
235
                    &chunks[(i + 1) % 2], conn_consumed))
2247
0
                goto err;
2248
2249
        /*
2250
         * Find best fit (header length, payload length) combination for if we
2251
         * use an implicit length.
2252
         */
2253
6.91k
        shdr->has_explicit_len = 0;
2254
6.91k
        hdr_len_implicit = payload_len_implicit = 0;
2255
6.91k
        if (!determine_stream_len(h, shdr, space_left,
2256
6.91k
                &hdr_len_implicit, &payload_len_implicit)) {
2257
36
            *packet_full = 1;
2258
36
            rc = 1;
2259
36
            goto err; /* can't fit anything */
2260
36
        }
2261
2262
        /*
2263
         * If there is a next stream, we don't use the implicit length so we can
2264
         * add more STREAM frames after this one, unless there is enough data
2265
         * for this STREAM frame to fill the packet.
2266
         */
2267
6.88k
        can_fill_payload = (hdr_len_implicit + payload_len_implicit
2268
6.88k
            >= space_left);
2269
2270
        /*
2271
         * Is there is a stream after this one, or another chunk pending
2272
         * transmission in this stream?
2273
         */
2274
6.88k
        could_have_following_chunk
2275
6.88k
            = (next_stream != NULL || chunks[(i + 1) % 2].valid);
2276
2277
        /* Choose between explicit or implicit length representations. */
2278
6.88k
        use_explicit_len = !((can_fill_payload || !could_have_following_chunk)
2279
6.07k
            && !pkt->force_pad);
2280
2281
6.88k
        if (use_explicit_len) {
2282
            /*
2283
             * Find best fit (header length, payload length) combination for if
2284
             * we use an explicit length.
2285
             */
2286
2.08k
            shdr->has_explicit_len = 1;
2287
2.08k
            hdr_len_explicit = payload_len_explicit = 0;
2288
2.08k
            if (!determine_stream_len(h, shdr, space_left,
2289
2.08k
                    &hdr_len_explicit, &payload_len_explicit)) {
2290
0
                *packet_full = 1;
2291
0
                rc = 1;
2292
0
                goto err; /* can't fit anything */
2293
0
            }
2294
2295
2.08k
            shdr->len = payload_len_explicit;
2296
4.80k
        } else {
2297
4.80k
            *packet_full = 1;
2298
4.80k
            shdr->has_explicit_len = 0;
2299
4.80k
            shdr->len = payload_len_implicit;
2300
4.80k
        }
2301
2302
        /* If this is a FIN, don't keep filling the packet with more FINs. */
2303
6.88k
        if (shdr->is_fin)
2304
0
            chunks[(i + 1) % 2].valid = 0;
2305
2306
        /*
2307
         * We are now committed to our length (shdr->len can't change).
2308
         * If we truncated the chunk, clear the FIN bit.
2309
         */
2310
6.88k
        if (shdr->len < orig_len)
2311
1.64k
            shdr->is_fin = 0;
2312
2313
        /* Truncate IOVs to match our chosen length. */
2314
6.88k
        ossl_quic_sstream_adjust_iov((size_t)shdr->len, chunks[i % 2].iov,
2315
6.88k
            chunks[i % 2].num_stream_iovec);
2316
2317
        /*
2318
         * Ensure we have enough iovecs allocated (1 for the header, up to 2 for
2319
         * the stream data.)
2320
         */
2321
6.88k
        if (!txp_el_ensure_iovec(&txp->el[enc_level], h->num_iovec + 3))
2322
0
            goto err; /* alloc error */
2323
2324
        /* Encode the header. */
2325
6.88k
        wpkt = tx_helper_begin(h);
2326
6.88k
        if (wpkt == NULL)
2327
0
            goto err; /* alloc error */
2328
2329
6.88k
        if (!ossl_assert(ossl_quic_wire_encode_frame_stream_hdr(wpkt, shdr))) {
2330
            /* (Should not be possible.) */
2331
0
            tx_helper_rollback(h);
2332
0
            *packet_full = 1;
2333
0
            rc = 1;
2334
0
            goto err; /* can't fit */
2335
0
        }
2336
2337
6.88k
        if (!tx_helper_commit(h))
2338
0
            goto err; /* alloc error */
2339
2340
        /* Add payload iovecs to the helper (infallible). */
2341
13.7k
        for (j = 0; j < chunks[i % 2].num_stream_iovec; ++j)
2342
6.88k
            tx_helper_append_iovec(h, chunks[i % 2].iov[j].buf,
2343
6.88k
                chunks[i % 2].iov[j].buf_len);
2344
2345
6.88k
        *have_ack_eliciting = 1;
2346
6.88k
        tx_helper_unrestrict(h); /* no longer need PING */
2347
6.88k
        if (!shdr->has_explicit_len)
2348
4.80k
            h->done_implicit = 1;
2349
2350
        /* Log new TXFC credit which was consumed. */
2351
6.88k
        if (shdr->len > 0 && shdr->offset + shdr->len > fc_new_hwm)
2352
4.98k
            fc_new_hwm = shdr->offset + shdr->len;
2353
2354
        /* Log chunk to TXPIM. */
2355
6.88k
        chunk.stream_id = shdr->stream_id;
2356
6.88k
        chunk.start = shdr->offset;
2357
6.88k
        chunk.end = shdr->offset + shdr->len - 1;
2358
6.88k
        chunk.has_fin = shdr->is_fin;
2359
6.88k
        chunk.has_stop_sending = 0;
2360
6.88k
        chunk.has_reset_stream = 0;
2361
6.88k
        if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
2362
0
            goto err; /* alloc error */
2363
2364
6.88k
        if (shdr->len < orig_len) {
2365
            /*
2366
             * If we did not serialize all of this chunk we definitely do not
2367
             * want to try the next chunk
2368
             */
2369
1.64k
            rc = 1;
2370
1.64k
            goto err;
2371
1.64k
        }
2372
6.88k
    }
2373
2374
11.9k
err:
2375
11.9k
    *new_credit_consumed = fc_new_hwm - fc_swm;
2376
11.9k
    return rc;
2377
6.83k
}
2378
2379
static void txp_enlink_tmp(QUIC_STREAM **tmp_head, QUIC_STREAM *stream)
2380
18.5k
{
2381
18.5k
    stream->txp_next = *tmp_head;
2382
18.5k
    *tmp_head = stream;
2383
18.5k
}
2384
2385
static int txp_generate_stream_related(OSSL_QUIC_TX_PACKETISER *txp,
2386
    struct txp_pkt *pkt,
2387
    int *have_ack_eliciting,
2388
    QUIC_STREAM **tmp_head)
2389
399k
{
2390
399k
    QUIC_STREAM_ITER it;
2391
399k
    WPACKET *wpkt;
2392
399k
    uint64_t cwm;
2393
399k
    QUIC_STREAM *stream, *snext;
2394
399k
    struct tx_helper *h = &pkt->h;
2395
399k
    uint64_t conn_consumed = 0;
2396
2397
399k
    for (ossl_quic_stream_iter_init(&it, txp->args.qsm, 1);
2398
412k
        it.stream != NULL;) {
2399
2400
18.5k
        stream = it.stream;
2401
18.5k
        ossl_quic_stream_iter_next(&it);
2402
18.5k
        snext = it.stream;
2403
2404
18.5k
        stream->txp_sent_fc = 0;
2405
18.5k
        stream->txp_sent_stop_sending = 0;
2406
18.5k
        stream->txp_sent_reset_stream = 0;
2407
18.5k
        stream->txp_blocked = 0;
2408
18.5k
        stream->txp_txfc_new_credit_consumed = 0;
2409
2410
        /* Stream Abort Frames (STOP_SENDING, RESET_STREAM) */
2411
18.5k
        if (stream->want_stop_sending) {
2412
0
            OSSL_QUIC_FRAME_STOP_SENDING f;
2413
2414
0
            wpkt = tx_helper_begin(h);
2415
0
            if (wpkt == NULL)
2416
0
                return 0; /* alloc error */
2417
2418
0
            f.stream_id = stream->id;
2419
0
            f.app_error_code = stream->stop_sending_aec;
2420
0
            if (!ossl_quic_wire_encode_frame_stop_sending(wpkt, &f)) {
2421
0
                tx_helper_rollback(h); /* can't fit */
2422
0
                txp_enlink_tmp(tmp_head, stream);
2423
0
                break;
2424
0
            }
2425
2426
0
            if (!tx_helper_commit(h))
2427
0
                return 0; /* alloc error */
2428
2429
0
            *have_ack_eliciting = 1;
2430
0
            tx_helper_unrestrict(h); /* no longer need PING */
2431
0
            stream->txp_sent_stop_sending = 1;
2432
0
        }
2433
2434
18.5k
        if (stream->want_reset_stream) {
2435
6.47k
            OSSL_QUIC_FRAME_RESET_STREAM f;
2436
2437
6.47k
            if (!ossl_assert(stream->send_state == QUIC_SSTREAM_STATE_RESET_SENT))
2438
0
                return 0;
2439
2440
6.47k
            wpkt = tx_helper_begin(h);
2441
6.47k
            if (wpkt == NULL)
2442
0
                return 0; /* alloc error */
2443
2444
6.47k
            f.stream_id = stream->id;
2445
6.47k
            f.app_error_code = stream->reset_stream_aec;
2446
6.47k
            if (!ossl_quic_stream_send_get_final_size(stream, &f.final_size))
2447
0
                return 0; /* should not be possible */
2448
2449
6.47k
            if (!ossl_quic_wire_encode_frame_reset_stream(wpkt, &f)) {
2450
369
                tx_helper_rollback(h); /* can't fit */
2451
369
                txp_enlink_tmp(tmp_head, stream);
2452
369
                break;
2453
369
            }
2454
2455
6.10k
            if (!tx_helper_commit(h))
2456
0
                return 0; /* alloc error */
2457
2458
6.10k
            *have_ack_eliciting = 1;
2459
6.10k
            tx_helper_unrestrict(h); /* no longer need PING */
2460
6.10k
            stream->txp_sent_reset_stream = 1;
2461
2462
            /*
2463
             * The final size of the stream as indicated by RESET_STREAM is used
2464
             * to ensure a consistent view of flow control state by both
2465
             * parties; if we happen to send a RESET_STREAM that consumes more
2466
             * flow control credit, make sure we account for that.
2467
             */
2468
6.10k
            if (!ossl_assert(f.final_size <= ossl_quic_txfc_get_swm(&stream->txfc)))
2469
0
                return 0;
2470
2471
6.10k
            stream->txp_txfc_new_credit_consumed
2472
6.10k
                = f.final_size - ossl_quic_txfc_get_swm(&stream->txfc);
2473
6.10k
        }
2474
2475
        /*
2476
         * Stream Flow Control Frames (MAX_STREAM_DATA)
2477
         *
2478
         * RFC 9000 s. 13.3: "An endpoint SHOULD stop sending MAX_STREAM_DATA
2479
         * frames when the receiving part of the stream enters a "Size Known" or
2480
         * "Reset Recvd" state." -- In practice, RECV is the only state
2481
         * in which it makes sense to generate more MAX_STREAM_DATA frames.
2482
         */
2483
18.2k
        if (stream->recv_state == QUIC_RSTREAM_STATE_RECV
2484
16.3k
            && (stream->want_max_stream_data
2485
14.8k
                || ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 0))) {
2486
2487
1.44k
            wpkt = tx_helper_begin(h);
2488
1.44k
            if (wpkt == NULL)
2489
0
                return 0; /* alloc error */
2490
2491
1.44k
            cwm = ossl_quic_rxfc_get_cwm(&stream->rxfc);
2492
2493
1.44k
            if (!ossl_quic_wire_encode_frame_max_stream_data(wpkt, stream->id,
2494
1.44k
                    cwm)) {
2495
176
                tx_helper_rollback(h); /* can't fit */
2496
176
                txp_enlink_tmp(tmp_head, stream);
2497
176
                break;
2498
176
            }
2499
2500
1.26k
            if (!tx_helper_commit(h))
2501
0
                return 0; /* alloc error */
2502
2503
1.26k
            *have_ack_eliciting = 1;
2504
1.26k
            tx_helper_unrestrict(h); /* no longer need PING */
2505
1.26k
            stream->txp_sent_fc = 1;
2506
1.26k
        }
2507
2508
        /*
2509
         * Stream Data Frames (STREAM)
2510
         *
2511
         * RFC 9000 s. 3.3: A sender MUST NOT send a STREAM [...] frame for a
2512
         * stream in the "Reset Sent" state [or any terminal state]. We don't
2513
         * send any more STREAM frames if we are sending, have sent, or are
2514
         * planning to send, RESET_STREAM. The other terminal state is Data
2515
         * Recvd, but txp_generate_stream_frames() is guaranteed to generate
2516
         * nothing in this case.
2517
         */
2518
18.0k
        if (ossl_quic_stream_has_send_buffer(stream)
2519
11.9k
            && !ossl_quic_stream_send_is_reset(stream)) {
2520
11.9k
            int packet_full = 0;
2521
2522
11.9k
            if (!ossl_assert(!stream->want_reset_stream))
2523
0
                return 0;
2524
2525
11.9k
            if (!txp_generate_stream_frames(txp, pkt,
2526
11.9k
                    stream->id, stream->sstream,
2527
11.9k
                    &stream->txfc,
2528
11.9k
                    snext,
2529
11.9k
                    have_ack_eliciting,
2530
11.9k
                    &packet_full,
2531
11.9k
                    &stream->txp_txfc_new_credit_consumed,
2532
11.9k
                    conn_consumed)) {
2533
                /* Fatal error (allocation, etc.) */
2534
0
                txp_enlink_tmp(tmp_head, stream);
2535
0
                return 0;
2536
0
            }
2537
11.9k
            conn_consumed += stream->txp_txfc_new_credit_consumed;
2538
2539
11.9k
            if (packet_full) {
2540
4.98k
                txp_enlink_tmp(tmp_head, stream);
2541
4.98k
                break;
2542
4.98k
            }
2543
11.9k
        }
2544
2545
13.0k
        txp_enlink_tmp(tmp_head, stream);
2546
13.0k
    }
2547
2548
399k
    return 1;
2549
399k
}
2550
2551
static int txp_generate_for_el(OSSL_QUIC_TX_PACKETISER *txp,
2552
    struct txp_pkt *pkt,
2553
    int chosen_for_conn_close)
2554
50.6M
{
2555
50.6M
    int rc = TXP_ERR_SUCCESS;
2556
50.6M
    const uint32_t enc_level = pkt->h.enc_level;
2557
50.6M
    const uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
2558
50.6M
    int have_ack_eliciting = 0, done_pre_token = 0;
2559
50.6M
    const struct archetype_data a = pkt->geom.adata;
2560
    /*
2561
     * Cleared if we encode any non-ACK-eliciting frame type which rules out the
2562
     * packet being a non-inflight frame. This means any non-ACK ACK-eliciting
2563
     * frame, even PADDING frames. ACK eliciting frames always cause a packet to
2564
     * become ineligible for non-inflight treatment so it is not necessary to
2565
     * clear this in cases where have_ack_eliciting is set, as it is ignored in
2566
     * that case.
2567
     */
2568
50.6M
    int can_be_non_inflight = 1;
2569
50.6M
    QUIC_CFQ_ITEM *cfq_item;
2570
50.6M
    QUIC_TXPIM_PKT *tpkt = NULL;
2571
50.6M
    struct tx_helper *h = &pkt->h;
2572
2573
    /* Maximum PN reached? */
2574
50.6M
    if (!ossl_quic_pn_valid(txp->next_pn[pn_space]))
2575
0
        goto fatal_err;
2576
2577
50.6M
    if (!ossl_assert(pkt->tpkt == NULL))
2578
0
        goto fatal_err;
2579
2580
50.6M
    if ((pkt->tpkt = tpkt = ossl_quic_txpim_pkt_alloc(txp->args.txpim)) == NULL)
2581
0
        goto fatal_err;
2582
2583
    /*
2584
     * Frame Serialization
2585
     * ===================
2586
     *
2587
     * We now serialize frames into the packet in descending order of priority.
2588
     */
2589
2590
    /* HANDSHAKE_DONE (Regenerate) */
2591
50.6M
    if (a.allow_handshake_done && txp->want_handshake_done
2592
0
        && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_HANDSHAKE_DONE) {
2593
0
        WPACKET *wpkt = tx_helper_begin(h);
2594
2595
0
        if (wpkt == NULL)
2596
0
            goto fatal_err;
2597
2598
0
        if (ossl_quic_wire_encode_frame_handshake_done(wpkt)) {
2599
0
            tpkt->had_handshake_done_frame = 1;
2600
0
            have_ack_eliciting = 1;
2601
2602
0
            if (!tx_helper_commit(h))
2603
0
                goto fatal_err;
2604
2605
0
            tx_helper_unrestrict(h); /* no longer need PING */
2606
0
        } else {
2607
0
            tx_helper_rollback(h);
2608
0
        }
2609
0
    }
2610
2611
    /* MAX_DATA (Regenerate) */
2612
50.6M
    if (a.allow_conn_fc
2613
399k
        && (txp->want_max_data
2614
399k
            || ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 0))
2615
0
        && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_MAX_DATA) {
2616
0
        WPACKET *wpkt = tx_helper_begin(h);
2617
0
        uint64_t cwm = ossl_quic_rxfc_get_cwm(txp->args.conn_rxfc);
2618
2619
0
        if (wpkt == NULL)
2620
0
            goto fatal_err;
2621
2622
0
        if (ossl_quic_wire_encode_frame_max_data(wpkt, cwm)) {
2623
0
            tpkt->had_max_data_frame = 1;
2624
0
            have_ack_eliciting = 1;
2625
2626
0
            if (!tx_helper_commit(h))
2627
0
                goto fatal_err;
2628
2629
0
            tx_helper_unrestrict(h); /* no longer need PING */
2630
0
        } else {
2631
0
            tx_helper_rollback(h);
2632
0
        }
2633
0
    }
2634
2635
    /* MAX_STREAMS_BIDI (Regenerate) */
2636
50.6M
    if (a.allow_conn_fc
2637
399k
        && (txp->want_max_streams_bidi
2638
399k
            || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 0))
2639
0
        && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_MAX_STREAMS_BIDI) {
2640
0
        WPACKET *wpkt = tx_helper_begin(h);
2641
0
        uint64_t max_streams
2642
0
            = ossl_quic_rxfc_get_cwm(txp->args.max_streams_bidi_rxfc);
2643
2644
0
        if (wpkt == NULL)
2645
0
            goto fatal_err;
2646
2647
0
        if (ossl_quic_wire_encode_frame_max_streams(wpkt, /*is_uni=*/0,
2648
0
                max_streams)) {
2649
0
            tpkt->had_max_streams_bidi_frame = 1;
2650
0
            have_ack_eliciting = 1;
2651
2652
0
            if (!tx_helper_commit(h))
2653
0
                goto fatal_err;
2654
2655
0
            tx_helper_unrestrict(h); /* no longer need PING */
2656
0
        } else {
2657
0
            tx_helper_rollback(h);
2658
0
        }
2659
0
    }
2660
2661
    /* MAX_STREAMS_UNI (Regenerate) */
2662
50.6M
    if (a.allow_conn_fc
2663
399k
        && (txp->want_max_streams_uni
2664
399k
            || ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 0))
2665
0
        && tx_helper_get_space_left(h) >= MIN_FRAME_SIZE_MAX_STREAMS_UNI) {
2666
0
        WPACKET *wpkt = tx_helper_begin(h);
2667
0
        uint64_t max_streams
2668
0
            = ossl_quic_rxfc_get_cwm(txp->args.max_streams_uni_rxfc);
2669
2670
0
        if (wpkt == NULL)
2671
0
            goto fatal_err;
2672
2673
0
        if (ossl_quic_wire_encode_frame_max_streams(wpkt, /*is_uni=*/1,
2674
0
                max_streams)) {
2675
0
            tpkt->had_max_streams_uni_frame = 1;
2676
0
            have_ack_eliciting = 1;
2677
2678
0
            if (!tx_helper_commit(h))
2679
0
                goto fatal_err;
2680
2681
0
            tx_helper_unrestrict(h); /* no longer need PING */
2682
0
        } else {
2683
0
            tx_helper_rollback(h);
2684
0
        }
2685
0
    }
2686
2687
    /* GCR Frames */
2688
50.6M
    for (cfq_item = ossl_quic_cfq_get_priority_head(txp->args.cfq, pn_space);
2689
262M
        cfq_item != NULL;
2690
212M
        cfq_item = ossl_quic_cfq_item_get_priority_next(cfq_item, pn_space)) {
2691
212M
        uint64_t frame_type = ossl_quic_cfq_item_get_frame_type(cfq_item);
2692
212M
        const unsigned char *encoded = ossl_quic_cfq_item_get_encoded(cfq_item);
2693
212M
        size_t encoded_len = ossl_quic_cfq_item_get_encoded_len(cfq_item);
2694
2695
212M
        switch (frame_type) {
2696
0
        case OSSL_QUIC_FRAME_TYPE_NEW_CONN_ID:
2697
0
            if (!a.allow_new_conn_id)
2698
0
                continue;
2699
0
            break;
2700
1.22M
        case OSSL_QUIC_FRAME_TYPE_RETIRE_CONN_ID:
2701
1.22M
            if (!a.allow_retire_conn_id)
2702
1.20M
                continue;
2703
17.2k
            break;
2704
17.2k
        case OSSL_QUIC_FRAME_TYPE_NEW_TOKEN:
2705
0
            if (!a.allow_new_token)
2706
0
                continue;
2707
2708
            /*
2709
             * NEW_TOKEN frames are handled via GCR, but some
2710
             * Regenerate-strategy frames should come before them (namely
2711
             * ACK, CONNECTION_CLOSE, PATH_CHALLENGE and PATH_RESPONSE). If
2712
             * we find a NEW_TOKEN frame, do these now. If there are no
2713
             * NEW_TOKEN frames in the GCR queue we will handle these below.
2714
             */
2715
0
            if (!done_pre_token)
2716
0
                if (txp_generate_pre_token(txp, pkt,
2717
0
                        chosen_for_conn_close,
2718
0
                        &can_be_non_inflight))
2719
0
                    done_pre_token = 1;
2720
2721
0
            break;
2722
210M
        case OSSL_QUIC_FRAME_TYPE_PATH_RESPONSE:
2723
210M
            if (!a.allow_path_response)
2724
210M
                continue;
2725
2726
            /*
2727
             * RFC 9000 s. 8.2.2: An endpoint MUST expand datagrams that
2728
             * contain a PATH_RESPONSE frame to at least the smallest
2729
             * allowed maximum datagram size of 1200 bytes.
2730
             */
2731
232k
            pkt->force_pad = 1;
2732
232k
            break;
2733
0
        default:
2734
0
            if (!a.allow_cfq_other)
2735
0
                continue;
2736
0
            break;
2737
212M
        }
2738
2739
        /*
2740
         * If the frame is too big, don't try to schedule any more GCR frames in
2741
         * this packet rather than sending subsequent ones out of order.
2742
         */
2743
249k
        if (encoded_len > tx_helper_get_space_left(h))
2744
765
            break;
2745
2746
249k
        if (!tx_helper_append_iovec(h, encoded, encoded_len))
2747
0
            goto fatal_err;
2748
2749
249k
        ossl_quic_txpim_pkt_add_cfq_item(tpkt, cfq_item);
2750
2751
249k
        if (ossl_quic_frame_type_is_ack_eliciting(frame_type)) {
2752
249k
            have_ack_eliciting = 1;
2753
249k
            tx_helper_unrestrict(h); /* no longer need PING */
2754
249k
        }
2755
249k
    }
2756
2757
    /*
2758
     * If we didn't generate ACK, CONNECTION_CLOSE, PATH_CHALLENGE or
2759
     * PATH_RESPONSE (as desired) before, do so now.
2760
     */
2761
50.6M
    if (!done_pre_token)
2762
50.6M
        if (txp_generate_pre_token(txp, pkt,
2763
50.6M
                chosen_for_conn_close,
2764
50.6M
                &can_be_non_inflight))
2765
50.6M
            done_pre_token = 1;
2766
2767
    /* CRYPTO Frames */
2768
50.6M
    if (a.allow_crypto)
2769
2.11M
        if (!txp_generate_crypto_frames(txp, pkt, &have_ack_eliciting))
2770
0
            goto fatal_err;
2771
2772
    /* Stream-specific frames */
2773
50.6M
    if (a.allow_stream_rel && txp->handshake_complete)
2774
399k
        if (!txp_generate_stream_related(txp, pkt,
2775
399k
                &have_ack_eliciting,
2776
399k
                &pkt->stream_head))
2777
0
            goto fatal_err;
2778
2779
    /* PING */
2780
50.6M
    tx_helper_unrestrict(h);
2781
2782
50.6M
    if (!have_ack_eliciting && txp_need_ping(txp, pn_space, &a)) {
2783
1.83M
        WPACKET *wpkt;
2784
2785
1.83M
        assert(h->reserve > 0);
2786
1.83M
        wpkt = tx_helper_begin(h);
2787
1.83M
        if (wpkt == NULL)
2788
0
            goto fatal_err;
2789
2790
1.83M
        if (!ossl_quic_wire_encode_frame_ping(wpkt)
2791
1.83M
            || !tx_helper_commit(h))
2792
            /*
2793
             * We treat a request to be ACK-eliciting as a requirement, so this
2794
             * is an error.
2795
             */
2796
0
            goto fatal_err;
2797
2798
1.83M
        have_ack_eliciting = 1;
2799
1.83M
    }
2800
2801
    /* PADDING is added by ossl_quic_tx_packetiser_generate(). */
2802
2803
    /*
2804
     * ACKM Data
2805
     * =========
2806
     */
2807
50.6M
    if (have_ack_eliciting)
2808
1.94M
        can_be_non_inflight = 0;
2809
2810
    /* ACKM Data */
2811
50.6M
    tpkt->ackm_pkt.num_bytes = h->bytes_appended + pkt->geom.pkt_overhead;
2812
50.6M
    tpkt->ackm_pkt.pkt_num = txp->next_pn[pn_space];
2813
    /* largest_acked is set in txp_generate_pre_token */
2814
50.6M
    tpkt->ackm_pkt.pkt_space = pn_space;
2815
50.6M
    tpkt->ackm_pkt.is_inflight = !can_be_non_inflight;
2816
50.6M
    tpkt->ackm_pkt.is_ack_eliciting = have_ack_eliciting;
2817
50.6M
    tpkt->ackm_pkt.is_pto_probe = 0;
2818
50.6M
    tpkt->ackm_pkt.is_mtu_probe = 0;
2819
50.6M
    tpkt->ackm_pkt.time = txp->args.now(txp->args.now_arg);
2820
50.6M
    tpkt->pkt_type = pkt->phdr.type;
2821
2822
    /* Done. */
2823
50.6M
    return rc;
2824
2825
0
fatal_err:
2826
    /*
2827
     * Handler for fatal errors, i.e. errors causing us to abort the entire
2828
     * packet rather than just one frame. Examples of such errors include
2829
     * allocation errors.
2830
     */
2831
0
    if (tpkt != NULL) {
2832
0
        ossl_quic_txpim_pkt_release(txp->args.txpim, tpkt);
2833
0
        pkt->tpkt = NULL;
2834
0
    }
2835
0
    return TXP_ERR_INTERNAL;
2836
50.6M
}
2837
2838
/*
2839
 * Commits and queues a packet for transmission. There is no backing out after
2840
 * this.
2841
 *
2842
 * This:
2843
 *
2844
 *   - Sends the packet to the QTX for encryption and transmission;
2845
 *
2846
 *   - Records the packet as having been transmitted in FIFM. ACKM is informed,
2847
 *     etc. and the TXPIM record is filed.
2848
 *
2849
 *   - Informs various subsystems of frames that were sent and clears frame
2850
 *     wanted flags so that we do not generate the same frames again.
2851
 *
2852
 * Assumptions:
2853
 *
2854
 *   - pkt is a txp_pkt for the correct EL;
2855
 *
2856
 *   - pkt->tpkt is valid;
2857
 *
2858
 *   - pkt->tpkt->ackm_pkt has been fully filled in;
2859
 *
2860
 *   - Stream chunk records have been appended to pkt->tpkt for STREAM and
2861
 *     CRYPTO frames, but not for RESET_STREAM or STOP_SENDING frames;
2862
 *
2863
 *   - The chosen stream list for the packet can be fully walked from
2864
 *     pkt->stream_head using stream->txp_next;
2865
 *
2866
 *   - pkt->has_ack_eliciting is set correctly.
2867
 *
2868
 */
2869
static int txp_pkt_commit(OSSL_QUIC_TX_PACKETISER *txp,
2870
    struct txp_pkt *pkt,
2871
    uint32_t archetype,
2872
    int *txpim_pkt_reffed)
2873
2.07M
{
2874
2.07M
    int rc = 1;
2875
2.07M
    uint32_t enc_level = pkt->h.enc_level;
2876
2.07M
    uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
2877
2.07M
    QUIC_TXPIM_PKT *tpkt = pkt->tpkt;
2878
2.07M
    QUIC_STREAM *stream;
2879
2.07M
    OSSL_QTX_PKT txpkt;
2880
2.07M
    struct archetype_data a;
2881
2882
2.07M
    *txpim_pkt_reffed = 0;
2883
2884
    /* Cannot send a packet with an empty payload. */
2885
2.07M
    if (pkt->h.bytes_appended == 0)
2886
0
        return 0;
2887
2888
2.07M
    if (!txp_get_archetype_data(enc_level, archetype, &a))
2889
0
        return 0;
2890
2891
    /* Packet Information for QTX */
2892
2.07M
    txpkt.hdr = &pkt->phdr;
2893
2.07M
    txpkt.iovec = txp->el[enc_level].iovec;
2894
2.07M
    txpkt.num_iovec = pkt->h.num_iovec;
2895
2.07M
    txpkt.local = NULL;
2896
2.07M
    txpkt.peer = BIO_ADDR_family(&txp->args.peer) == AF_UNSPEC
2897
2.07M
        ? NULL
2898
2.07M
        : &txp->args.peer;
2899
2.07M
    txpkt.pn = txp->next_pn[pn_space];
2900
2.07M
    txpkt.flags = OSSL_QTX_PKT_FLAG_COALESCE; /* always try to coalesce */
2901
2902
    /* Generate TXPIM chunks representing STOP_SENDING and RESET_STREAM frames. */
2903
2.08M
    for (stream = pkt->stream_head; stream != NULL; stream = stream->txp_next)
2904
13.6k
        if (stream->txp_sent_stop_sending || stream->txp_sent_reset_stream) {
2905
            /* Log STOP_SENDING/RESET_STREAM chunk to TXPIM. */
2906
6.10k
            QUIC_TXPIM_CHUNK chunk;
2907
2908
6.10k
            chunk.stream_id = stream->id;
2909
6.10k
            chunk.start = UINT64_MAX;
2910
6.10k
            chunk.end = 0;
2911
6.10k
            chunk.has_fin = 0;
2912
6.10k
            chunk.has_stop_sending = stream->txp_sent_stop_sending;
2913
6.10k
            chunk.has_reset_stream = stream->txp_sent_reset_stream;
2914
6.10k
            if (!ossl_quic_txpim_pkt_append_chunk(tpkt, &chunk))
2915
0
                return 0; /* alloc error */
2916
6.10k
        }
2917
2918
    /* Dispatch to FIFD. */
2919
2.07M
    if (!ossl_quic_fifd_pkt_commit(&txp->fifd, tpkt))
2920
0
        return 0;
2921
2922
    /*
2923
     * Transmission and Post-Packet Generation Bookkeeping
2924
     * ===================================================
2925
     *
2926
     * No backing out anymore - at this point the ACKM has recorded the packet
2927
     * as having been sent, so we need to increment our next PN counter, or
2928
     * the ACKM will complain when we try to record a duplicate packet with
2929
     * the same PN later. At this point actually sending the packet may still
2930
     * fail. In this unlikely event it will simply be handled as though it
2931
     * were a lost packet.
2932
     */
2933
2.07M
    ++txp->next_pn[pn_space];
2934
2.07M
    *txpim_pkt_reffed = 1;
2935
2936
    /* Send the packet. */
2937
2.07M
    if (!ossl_qtx_write_pkt(txp->args.qtx, &txpkt))
2938
0
        return 0;
2939
2940
    /*
2941
     * Record FC and stream abort frames as sent; deactivate streams which no
2942
     * longer have anything to do.
2943
     */
2944
2.08M
    for (stream = pkt->stream_head; stream != NULL; stream = stream->txp_next) {
2945
13.6k
        if (stream->txp_sent_fc) {
2946
1.26k
            stream->want_max_stream_data = 0;
2947
1.26k
            ossl_quic_rxfc_has_cwm_changed(&stream->rxfc, 1);
2948
1.26k
        }
2949
2950
13.6k
        if (stream->txp_sent_stop_sending)
2951
0
            stream->want_stop_sending = 0;
2952
2953
13.6k
        if (stream->txp_sent_reset_stream)
2954
6.10k
            stream->want_reset_stream = 0;
2955
2956
13.6k
        if (stream->txp_txfc_new_credit_consumed > 0) {
2957
4.98k
            if (!ossl_assert(ossl_quic_txfc_consume_credit(&stream->txfc,
2958
4.98k
                    stream->txp_txfc_new_credit_consumed)))
2959
                /*
2960
                 * Should not be possible, but we should continue with our
2961
                 * bookkeeping as we have already committed the packet to the
2962
                 * FIFD. Just change the value we return.
2963
                 */
2964
0
                rc = 0;
2965
2966
4.98k
            stream->txp_txfc_new_credit_consumed = 0;
2967
4.98k
        }
2968
2969
        /*
2970
         * If we no longer need to generate any flow control (MAX_STREAM_DATA),
2971
         * STOP_SENDING or RESET_STREAM frames, nor any STREAM frames (because
2972
         * the stream is drained of data or TXFC-blocked), we can mark the
2973
         * stream as inactive.
2974
         */
2975
13.6k
        ossl_quic_stream_map_update_state(txp->args.qsm, stream);
2976
2977
13.6k
        if (ossl_quic_stream_has_send_buffer(stream)
2978
7.14k
            && !ossl_quic_sstream_has_pending(stream->sstream)
2979
4.95k
            && ossl_quic_sstream_get_final_size(stream->sstream, NULL))
2980
            /*
2981
             * Transition to DATA_SENT if stream has a final size and we have
2982
             * sent all data.
2983
             */
2984
0
            ossl_quic_stream_map_notify_all_data_sent(txp->args.qsm, stream);
2985
13.6k
    }
2986
2987
    /* We have now sent the packet, so update state accordingly. */
2988
2.07M
    if (tpkt->ackm_pkt.is_ack_eliciting)
2989
1.94M
        txp->force_ack_eliciting &= ~(1UL << pn_space);
2990
2991
2.07M
    if (tpkt->had_handshake_done_frame)
2992
0
        txp->want_handshake_done = 0;
2993
2994
2.07M
    if (tpkt->had_max_data_frame) {
2995
0
        txp->want_max_data = 0;
2996
0
        ossl_quic_rxfc_has_cwm_changed(txp->args.conn_rxfc, 1);
2997
0
    }
2998
2999
2.07M
    if (tpkt->had_max_streams_bidi_frame) {
3000
0
        txp->want_max_streams_bidi = 0;
3001
0
        ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_bidi_rxfc, 1);
3002
0
    }
3003
3004
2.07M
    if (tpkt->had_max_streams_uni_frame) {
3005
0
        txp->want_max_streams_uni = 0;
3006
0
        ossl_quic_rxfc_has_cwm_changed(txp->args.max_streams_uni_rxfc, 1);
3007
0
    }
3008
3009
2.07M
    if (tpkt->had_ack_frame)
3010
232k
        txp->want_ack &= ~(1UL << pn_space);
3011
3012
2.07M
    if (tpkt->had_conn_close)
3013
24.1k
        txp->want_conn_close = 0;
3014
3015
    /*
3016
     * Decrement probe request counts if we have sent a packet that meets
3017
     * the requirement of a probe, namely being ACK-eliciting.
3018
     */
3019
2.07M
    if (tpkt->ackm_pkt.is_ack_eliciting) {
3020
1.94M
        OSSL_ACKM_PROBE_INFO *probe_info
3021
1.94M
            = ossl_ackm_get0_probe_request(txp->args.ackm);
3022
3023
1.94M
        if (enc_level == QUIC_ENC_LEVEL_INITIAL
3024
1.41M
            && probe_info->anti_deadlock_initial > 0)
3025
1.27k
            --probe_info->anti_deadlock_initial;
3026
3027
1.94M
        if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE
3028
217k
            && probe_info->anti_deadlock_handshake > 0)
3029
1.49k
            --probe_info->anti_deadlock_handshake;
3030
3031
1.94M
        if (a.allow_force_ack_eliciting /* (i.e., not for 0-RTT) */
3032
1.94M
            && probe_info->pto[pn_space] > 0)
3033
359k
            --probe_info->pto[pn_space];
3034
1.94M
    }
3035
3036
2.07M
    return rc;
3037
2.07M
}
3038
3039
/* Ensure the iovec array is at least num elements long. */
3040
static int txp_el_ensure_iovec(struct txp_el *el, size_t num)
3041
9.99M
{
3042
9.99M
    OSSL_QTX_IOVEC *iovec;
3043
3044
9.99M
    if (el->alloc_iovec >= num)
3045
9.90M
        return 1;
3046
3047
90.3k
    num = el->alloc_iovec != 0 ? el->alloc_iovec * 2 : 8;
3048
3049
90.3k
    iovec = OPENSSL_realloc(el->iovec, sizeof(OSSL_QTX_IOVEC) * num);
3050
90.3k
    if (iovec == NULL)
3051
0
        return 0;
3052
3053
90.3k
    el->iovec = iovec;
3054
90.3k
    el->alloc_iovec = num;
3055
90.3k
    return 1;
3056
90.3k
}
3057
3058
int ossl_quic_tx_packetiser_schedule_conn_close(OSSL_QUIC_TX_PACKETISER *txp,
3059
    const OSSL_QUIC_FRAME_CONN_CLOSE *f)
3060
24.8k
{
3061
24.8k
    char *reason = NULL;
3062
24.8k
    size_t reason_len = f->reason_len;
3063
24.8k
    size_t max_reason_len = txp_get_mdpl(txp) / 2;
3064
3065
24.8k
    if (txp->want_conn_close)
3066
0
        return 0;
3067
3068
    /*
3069
     * Arbitrarily limit the length of the reason length string to half of the
3070
     * MDPL.
3071
     */
3072
24.8k
    if (reason_len > max_reason_len)
3073
0
        reason_len = max_reason_len;
3074
3075
24.8k
    if (reason_len > 0) {
3076
24.8k
        reason = OPENSSL_memdup(f->reason, reason_len);
3077
24.8k
        if (reason == NULL)
3078
0
            return 0;
3079
24.8k
    }
3080
3081
24.8k
    txp->conn_close_frame = *f;
3082
24.8k
    txp->conn_close_frame.reason = reason;
3083
24.8k
    txp->conn_close_frame.reason_len = reason_len;
3084
24.8k
    txp->want_conn_close = 1;
3085
24.8k
    return 1;
3086
24.8k
}
3087
3088
void ossl_quic_tx_packetiser_set_msg_callback(OSSL_QUIC_TX_PACKETISER *txp,
3089
    ossl_msg_cb msg_callback,
3090
    SSL *msg_callback_ssl)
3091
50.4k
{
3092
50.4k
    txp->msg_callback = msg_callback;
3093
50.4k
    txp->msg_callback_ssl = msg_callback_ssl;
3094
50.4k
}
3095
3096
void ossl_quic_tx_packetiser_set_msg_callback_arg(OSSL_QUIC_TX_PACKETISER *txp,
3097
    void *msg_callback_arg)
3098
50.4k
{
3099
50.4k
    txp->msg_callback_arg = msg_callback_arg;
3100
50.4k
}
3101
3102
QUIC_PN ossl_quic_tx_packetiser_get_next_pn(OSSL_QUIC_TX_PACKETISER *txp,
3103
    uint32_t pn_space)
3104
31.5k
{
3105
31.5k
    if (pn_space >= QUIC_PN_SPACE_NUM)
3106
0
        return UINT64_MAX;
3107
3108
31.5k
    return txp->next_pn[pn_space];
3109
31.5k
}
3110
3111
OSSL_TIME ossl_quic_tx_packetiser_get_deadline(OSSL_QUIC_TX_PACKETISER *txp)
3112
70.6M
{
3113
    /*
3114
     * TXP-specific deadline computations which rely on TXP innards. This is in
3115
     * turn relied on by the QUIC_CHANNEL code to determine the channel event
3116
     * handling deadline.
3117
     */
3118
70.6M
    OSSL_TIME deadline = ossl_time_infinite();
3119
70.6M
    uint32_t enc_level, pn_space;
3120
3121
    /*
3122
     * ACK generation is not CC-gated - packets containing only ACKs are allowed
3123
     * to bypass CC. We want to generate ACK frames even if we are currently
3124
     * restricted by CC so the peer knows we have received data. The generate
3125
     * call will take care of selecting the correct packet archetype.
3126
     */
3127
70.6M
    for (enc_level = QUIC_ENC_LEVEL_INITIAL;
3128
353M
        enc_level < QUIC_ENC_LEVEL_NUM;
3129
282M
        ++enc_level)
3130
282M
        if (ossl_qtx_is_enc_level_provisioned(txp->args.qtx, enc_level)) {
3131
84.3M
            pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
3132
84.3M
            deadline = ossl_time_min(deadline,
3133
84.3M
                ossl_ackm_get_ack_deadline(txp->args.ackm, pn_space));
3134
84.3M
        }
3135
3136
    /* When will CC let us send more? */
3137
70.6M
    if (txp->args.cc_method->get_tx_allowance(txp->args.cc_data) == 0)
3138
51.9M
        deadline = ossl_time_min(deadline,
3139
51.9M
            txp->args.cc_method->get_wakeup_deadline(txp->args.cc_data));
3140
3141
70.6M
    return deadline;
3142
70.6M
}