Enable tracing of packets that have been sent
[openssl.git] / ssl / quic / quic_record_tx.c
1 /*
2  * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "internal/quic_record_tx.h"
11 #include "internal/bio_addr.h"
12 #include "internal/common.h"
13 #include "quic_record_shared.h"
14 #include "internal/list.h"
15 #include "../ssl_local.h"
16
17 /*
18  * TXE
19  * ===
20  * Encrypted packets awaiting transmission are kept in TX Entries (TXEs), which
21  * are queued in linked lists just like TXEs.
22  */
23 typedef struct txe_st TXE;
24
25 struct txe_st {
26     OSSL_LIST_MEMBER(txe, TXE);
27     size_t              data_len, alloc_len;
28
29     /*
30      * Destination and local addresses, as applicable. Both of these are only
31      * used if the family is not AF_UNSPEC.
32      */
33     BIO_ADDR            peer, local;
34
35     /*
36      * alloc_len allocated bytes (of which data_len bytes are valid) follow this
37      * structure.
38      */
39 };
40
41 DEFINE_LIST_OF(txe, TXE);
42 typedef OSSL_LIST(txe) TXE_LIST;
43
44 static ossl_inline unsigned char *txe_data(const TXE *e)
45 {
46     return (unsigned char *)(e + 1);
47 }
48
49 /*
50  * QTX
51  * ===
52  */
53 struct ossl_qtx_st {
54     OSSL_LIB_CTX               *libctx;
55     const char                 *propq;
56
57     /* Per encryption-level state. */
58     OSSL_QRL_ENC_LEVEL_SET      el_set;
59
60     /* TX BIO. */
61     BIO                        *bio;
62
63     /* TX maximum datagram payload length. */
64     size_t                      mdpl;
65
66     /*
67      * List of TXEs which are not currently in use. These are moved to the
68      * pending list (possibly via tx_cons first) as they are filled.
69      */
70     TXE_LIST                    free;
71
72     /*
73      * List of TXEs which are filled with completed datagrams ready to be
74      * transmitted.
75      */
76     TXE_LIST                    pending;
77     size_t                      pending_count; /* items in list */
78     size_t                      pending_bytes; /* sum(txe->data_len) in pending */
79
80     /*
81      * TXE which is under construction for coalescing purposes, if any.
82      * This TXE is neither on the free nor pending list. Once the datagram
83      * is completed, it is moved to the pending list.
84      */
85     TXE                        *cons;
86     size_t                      cons_count; /* num packets */
87
88     /*
89      * Number of packets transmitted in this key epoch. Used to enforce AEAD
90      * confidentiality limit.
91      */
92     uint64_t                    epoch_pkt_count;
93
94     ossl_mutate_packet_cb mutatecb;
95     ossl_finish_mutate_cb finishmutatecb;
96     void *mutatearg;
97
98     /* Message callback related arguments */
99     ossl_msg_cb msg_callback;
100     void *msg_callback_arg;
101     SSL *msg_callback_s;
102 };
103
104 /* Instantiates a new QTX. */
105 OSSL_QTX *ossl_qtx_new(const OSSL_QTX_ARGS *args)
106 {
107     OSSL_QTX *qtx;
108
109     if (args->mdpl < QUIC_MIN_INITIAL_DGRAM_LEN)
110         return 0;
111
112     qtx = OPENSSL_zalloc(sizeof(OSSL_QTX));
113     if (qtx == NULL)
114         return 0;
115
116     qtx->libctx             = args->libctx;
117     qtx->propq              = args->propq;
118     qtx->bio                = args->bio;
119     qtx->mdpl               = args->mdpl;
120     qtx->msg_callback       = args->msg_callback;
121     qtx->msg_callback_arg   = args->msg_callback_arg;
122     qtx->msg_callback_s     = args->msg_callback_s;
123     return qtx;
124 }
125
126 static void qtx_cleanup_txl(TXE_LIST *l)
127 {
128     TXE *e, *enext;
129
130     for (e = ossl_list_txe_head(l); e != NULL; e = enext) {
131         enext = ossl_list_txe_next(e);
132         OPENSSL_free(e);
133     }
134 }
135
136 /* Frees the QTX. */
137 void ossl_qtx_free(OSSL_QTX *qtx)
138 {
139     uint32_t i;
140
141     if (qtx == NULL)
142         return;
143
144     /* Free TXE queue data. */
145     qtx_cleanup_txl(&qtx->pending);
146     qtx_cleanup_txl(&qtx->free);
147     OPENSSL_free(qtx->cons);
148
149     /* Drop keying material and crypto resources. */
150     for (i = 0; i < QUIC_ENC_LEVEL_NUM; ++i)
151         ossl_qrl_enc_level_set_discard(&qtx->el_set, i);
152
153     OPENSSL_free(qtx);
154 }
155
156 /* Set mutator callbacks for test framework support */
157 void ossl_qtx_set_mutator(OSSL_QTX *qtx, ossl_mutate_packet_cb mutatecb,
158                           ossl_finish_mutate_cb finishmutatecb, void *mutatearg)
159 {
160     qtx->mutatecb       = mutatecb;
161     qtx->finishmutatecb = finishmutatecb;
162     qtx->mutatearg      = mutatearg;
163 }
164
165 int ossl_qtx_provide_secret(OSSL_QTX              *qtx,
166                             uint32_t               enc_level,
167                             uint32_t               suite_id,
168                             EVP_MD                *md,
169                             const unsigned char   *secret,
170                             size_t                 secret_len)
171 {
172     if (enc_level >= QUIC_ENC_LEVEL_NUM)
173         return 0;
174
175     return ossl_qrl_enc_level_set_provide_secret(&qtx->el_set,
176                                                  qtx->libctx,
177                                                  qtx->propq,
178                                                  enc_level,
179                                                  suite_id,
180                                                  md,
181                                                  secret,
182                                                  secret_len,
183                                                  0,
184                                                  /*is_tx=*/1);
185 }
186
187 int ossl_qtx_discard_enc_level(OSSL_QTX *qtx, uint32_t enc_level)
188 {
189     if (enc_level >= QUIC_ENC_LEVEL_NUM)
190         return 0;
191
192     ossl_qrl_enc_level_set_discard(&qtx->el_set, enc_level);
193     return 1;
194 }
195
196 int ossl_qtx_is_enc_level_provisioned(OSSL_QTX *qtx, uint32_t enc_level)
197 {
198     return ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1) != NULL;
199 }
200
201 /* Allocate a new TXE. */
202 static TXE *qtx_alloc_txe(size_t alloc_len)
203 {
204     TXE *txe;
205
206     if (alloc_len >= SIZE_MAX - sizeof(TXE))
207         return NULL;
208
209     txe = OPENSSL_malloc(sizeof(TXE) + alloc_len);
210     if (txe == NULL)
211         return NULL;
212
213     ossl_list_txe_init_elem(txe);
214     txe->alloc_len = alloc_len;
215     txe->data_len = 0;
216     return txe;
217 }
218
219 /*
220  * Ensures there is at least one TXE in the free list, allocating a new entry
221  * if necessary. The returned TXE is in the free list; it is not popped.
222  *
223  * alloc_len is a hint which may be used to determine the TXE size if allocation
224  * is necessary. Returns NULL on allocation failure.
225  */
226 static TXE *qtx_ensure_free_txe(OSSL_QTX *qtx, size_t alloc_len)
227 {
228     TXE *txe;
229
230     txe = ossl_list_txe_head(&qtx->free);
231     if (txe != NULL)
232         return txe;
233
234     txe = qtx_alloc_txe(alloc_len);
235     if (txe == NULL)
236         return NULL;
237
238     ossl_list_txe_insert_tail(&qtx->free, txe);
239     return txe;
240 }
241
242 /*
243  * Resize the data buffer attached to an TXE to be n bytes in size. The address
244  * of the TXE might change; the new address is returned, or NULL on failure, in
245  * which case the original TXE remains valid.
246  */
247 static TXE *qtx_resize_txe(OSSL_QTX *qtx, TXE_LIST *txl, TXE *txe, size_t n)
248 {
249     TXE *txe2, *p;
250
251     /* Should never happen. */
252     if (txe == NULL)
253         return NULL;
254
255     if (n >= SIZE_MAX - sizeof(TXE))
256         return NULL;
257
258     /* Remove the item from the list to avoid accessing freed memory */
259     p = ossl_list_txe_prev(txe);
260     ossl_list_txe_remove(txl, txe);
261
262     /*
263      * NOTE: We do not clear old memory, although it does contain decrypted
264      * data.
265      */
266     txe2 = OPENSSL_realloc(txe, sizeof(TXE) + n);
267     if (txe2 == NULL || txe == txe2) {
268         if (p == NULL)
269             ossl_list_txe_insert_head(txl, txe);
270         else
271             ossl_list_txe_insert_after(txl, p, txe);
272         return txe2;
273     }
274
275     if (p == NULL)
276         ossl_list_txe_insert_head(txl, txe2);
277     else
278         ossl_list_txe_insert_after(txl, p, txe2);
279
280     if (qtx->cons == txe)
281         qtx->cons = txe2;
282
283     txe2->alloc_len = n;
284     return txe2;
285 }
286
287 /*
288  * Ensure the data buffer attached to an TXE is at least n bytes in size.
289  * Returns NULL on failure.
290  */
291 static TXE *qtx_reserve_txe(OSSL_QTX *qtx, TXE_LIST *txl,
292                             TXE *txe, size_t n)
293 {
294     if (txe->alloc_len >= n)
295         return txe;
296
297     return qtx_resize_txe(qtx, txl, txe, n);
298 }
299
300 /* Move a TXE from pending to free. */
301 static void qtx_pending_to_free(OSSL_QTX *qtx)
302 {
303     TXE *txe = ossl_list_txe_head(&qtx->pending);
304
305     assert(txe != NULL);
306     ossl_list_txe_remove(&qtx->pending, txe);
307     --qtx->pending_count;
308     qtx->pending_bytes -= txe->data_len;
309     ossl_list_txe_insert_tail(&qtx->free, txe);
310 }
311
312 /* Add a TXE not currently in any list to the pending list. */
313 static void qtx_add_to_pending(OSSL_QTX *qtx, TXE *txe)
314 {
315     ossl_list_txe_insert_tail(&qtx->pending, txe);
316     ++qtx->pending_count;
317     qtx->pending_bytes += txe->data_len;
318 }
319
320 struct iovec_cur {
321     const OSSL_QTX_IOVEC *iovec;
322     size_t                num_iovec, idx, byte_off, bytes_remaining;
323 };
324
325 static size_t iovec_total_bytes(const OSSL_QTX_IOVEC *iovec,
326                                 size_t num_iovec)
327 {
328     size_t i, l = 0;
329
330     for (i = 0; i < num_iovec; ++i)
331         l += iovec[i].buf_len;
332
333     return l;
334 }
335
336 static void iovec_cur_init(struct iovec_cur *cur,
337                            const OSSL_QTX_IOVEC *iovec,
338                            size_t num_iovec)
339 {
340     cur->iovec              = iovec;
341     cur->num_iovec          = num_iovec;
342     cur->idx                = 0;
343     cur->byte_off           = 0;
344     cur->bytes_remaining    = iovec_total_bytes(iovec, num_iovec);
345 }
346
347 /*
348  * Get an extent of bytes from the iovec cursor. *buf is set to point to the
349  * buffer and the number of bytes in length of the buffer is returned. This
350  * value may be less than the max_buf_len argument. If no more data is
351  * available, returns 0.
352  */
353 static size_t iovec_cur_get_buffer(struct iovec_cur *cur,
354                                    const unsigned char **buf,
355                                    size_t max_buf_len)
356 {
357     size_t l;
358
359     if (max_buf_len == 0) {
360         *buf = NULL;
361         return 0;
362     }
363
364     for (;;) {
365         if (cur->idx >= cur->num_iovec)
366             return 0;
367
368         l = cur->iovec[cur->idx].buf_len - cur->byte_off;
369         if (l > max_buf_len)
370             l = max_buf_len;
371
372         if (l > 0) {
373             *buf = cur->iovec[cur->idx].buf + cur->byte_off;
374             cur->byte_off += l;
375             cur->bytes_remaining -= l;
376             return l;
377         }
378
379         /*
380          * Zero-length iovec entry or we already consumed all of it, try the
381          * next iovec.
382          */
383         ++cur->idx;
384         cur->byte_off = 0;
385     }
386 }
387
388 /* Determines the size of the AEAD output given the input size. */
389 static size_t qtx_inflate_payload_len(OSSL_QTX *qtx, uint32_t enc_level,
390                                       size_t plaintext_len)
391 {
392     OSSL_QRL_ENC_LEVEL *el
393         = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1);
394
395     assert(el != NULL); /* Already checked by caller. */
396
397     /*
398      * We currently only support ciphers with a 1:1 mapping between plaintext
399      * and ciphertext size, save for authentication tag.
400      */
401     return plaintext_len + ossl_qrl_get_suite_cipher_tag_len(el->suite_id);
402 }
403
404 /* Determines the size of the AEAD input given the output size. */
405 int ossl_qtx_calculate_plaintext_payload_len(OSSL_QTX *qtx, uint32_t enc_level,
406                                              size_t ciphertext_len,
407                                              size_t *plaintext_len)
408 {
409     OSSL_QRL_ENC_LEVEL *el
410         = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1);
411     size_t tag_len;
412
413     if (el == NULL) {
414         *plaintext_len = 0;
415         return 0;
416     }
417
418     tag_len = ossl_qrl_get_suite_cipher_tag_len(el->suite_id);
419
420     if (ciphertext_len < tag_len) {
421         *plaintext_len = 0;
422         return 0;
423     }
424
425     *plaintext_len = ciphertext_len - tag_len;
426     return 1;
427 }
428
429 /* Any other error (including packet being too big for MDPL). */
430 #define QTX_FAIL_GENERIC            (-1)
431
432 /*
433  * Returned where there is insufficient room in the datagram to write the
434  * packet.
435  */
436 #define QTX_FAIL_INSUFFICIENT_LEN   (-2)
437
438 static int qtx_write_hdr(OSSL_QTX *qtx, const QUIC_PKT_HDR *hdr, TXE *txe,
439                          QUIC_PKT_HDR_PTRS *ptrs)
440 {
441     WPACKET wpkt;
442     size_t l = 0;
443     unsigned char *data = txe_data(txe) + txe->data_len;
444
445     if (!WPACKET_init_static_len(&wpkt, data, txe->alloc_len - txe->data_len, 0))
446         return 0;
447
448     if (!ossl_quic_wire_encode_pkt_hdr(&wpkt, hdr->dst_conn_id.id_len,
449                                        hdr, ptrs)
450         || !WPACKET_get_total_written(&wpkt, &l)) {
451         WPACKET_finish(&wpkt);
452         return 0;
453     }
454     WPACKET_finish(&wpkt);
455
456     if (qtx->msg_callback != NULL)
457         qtx->msg_callback(1, OSSL_QUIC1_VERSION, SSL3_RT_QUIC_PACKET, data, l,
458                           qtx->msg_callback_s, qtx->msg_callback_arg);
459
460     txe->data_len += l;
461
462     return 1;
463 }
464
465 static int qtx_encrypt_into_txe(OSSL_QTX *qtx, struct iovec_cur *cur, TXE *txe,
466                                 uint32_t enc_level, QUIC_PN pn,
467                                 const unsigned char *hdr, size_t hdr_len,
468                                 QUIC_PKT_HDR_PTRS *ptrs)
469 {
470     int l = 0, l2 = 0;
471     OSSL_QRL_ENC_LEVEL *el
472         = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1);
473     unsigned char nonce[EVP_MAX_IV_LENGTH];
474     size_t nonce_len, i;
475     EVP_CIPHER_CTX *cctx = NULL;
476
477     /* We should not have been called if we do not have key material. */
478     if (!ossl_assert(el != NULL))
479         return 0;
480
481     /*
482      * Have we already encrypted the maximum number of packets using the current
483      * key?
484      */
485     if (el->op_count >= ossl_qrl_get_suite_max_pkt(el->suite_id))
486         return 0;
487
488     /*
489      * TX key update is simpler than for RX; once we initiate a key update, we
490      * never need the old keys, as we never deliberately send a packet with old
491      * keys. Thus the EL always uses keyslot 0 for the TX side.
492      */
493     cctx = el->cctx[0];
494     if (!ossl_assert(cctx != NULL))
495         return 0;
496
497     /* Construct nonce (nonce=IV ^ PN). */
498     nonce_len = EVP_CIPHER_CTX_get_iv_length(cctx);
499     if (!ossl_assert(nonce_len >= sizeof(QUIC_PN)))
500         return 0;
501
502     memcpy(nonce, el->iv[0], nonce_len);
503     for (i = 0; i < sizeof(QUIC_PN); ++i)
504         nonce[nonce_len - i - 1] ^= (unsigned char)(pn >> (i * 8));
505
506     /* type and key will already have been setup; feed the IV. */
507     if (EVP_CipherInit_ex(cctx, NULL, NULL, NULL, nonce, /*enc=*/1) != 1)
508         return 0;
509
510     /* Feed AAD data. */
511     if (EVP_CipherUpdate(cctx, NULL, &l, hdr, hdr_len) != 1)
512         return 0;
513
514     /* Encrypt plaintext directly into TXE. */
515     for (;;) {
516         const unsigned char *src;
517         size_t src_len;
518
519         src_len = iovec_cur_get_buffer(cur, &src, SIZE_MAX);
520         if (src_len == 0)
521             break;
522
523         if (EVP_CipherUpdate(cctx, txe_data(txe) + txe->data_len,
524                              &l, src, src_len) != 1)
525             return 0;
526
527         assert(l > 0 && src_len == (size_t)l);
528         txe->data_len += src_len;
529     }
530
531     /* Finalise and get tag. */
532     if (EVP_CipherFinal_ex(cctx, NULL, &l2) != 1)
533         return 0;
534
535     if (EVP_CIPHER_CTX_ctrl(cctx, EVP_CTRL_AEAD_GET_TAG,
536                             el->tag_len, txe_data(txe) + txe->data_len) != 1)
537         return 0;
538
539     txe->data_len += el->tag_len;
540
541     /* Apply header protection. */
542     if (!ossl_quic_hdr_protector_encrypt(&el->hpr, ptrs))
543         return 0;
544
545     ++el->op_count;
546     return 1;
547 }
548
549 /*
550  * Append a packet to the TXE buffer, serializing and encrypting it in the
551  * process.
552  */
553 static int qtx_write(OSSL_QTX *qtx, const OSSL_QTX_PKT *pkt, TXE *txe,
554                      uint32_t enc_level)
555 {
556     int ret, needs_encrypt;
557     size_t hdr_len, pred_hdr_len, payload_len, pkt_len, space_left;
558     size_t min_len, orig_data_len;
559     struct iovec_cur cur;
560     QUIC_PKT_HDR_PTRS ptrs;
561     unsigned char *hdr_start;
562     OSSL_QRL_ENC_LEVEL *el = NULL;
563     QUIC_PKT_HDR *hdr;
564     const OSSL_QTX_IOVEC *iovec;
565     size_t num_iovec;
566
567     /*
568      * Determine if the packet needs encryption and the minimum conceivable
569      * serialization length.
570      */
571     if (!ossl_quic_pkt_type_is_encrypted(pkt->hdr->type)) {
572         needs_encrypt = 0;
573         min_len = QUIC_MIN_VALID_PKT_LEN;
574     } else {
575         needs_encrypt = 1;
576         min_len = QUIC_MIN_VALID_PKT_LEN_CRYPTO;
577         el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1);
578         if (!ossl_assert(el != NULL)) /* should already have been checked */
579             return 0;
580     }
581
582     orig_data_len = txe->data_len;
583     space_left = txe->alloc_len - txe->data_len;
584     if (space_left < min_len) {
585         /* Not even a possibility of it fitting. */
586         ret = QTX_FAIL_INSUFFICIENT_LEN;
587         goto err;
588     }
589
590     /* Set some fields in the header we are responsible for. */
591     if (pkt->hdr->type == QUIC_PKT_TYPE_1RTT)
592         pkt->hdr->key_phase = (unsigned char)(el->key_epoch & 1);
593
594     /* If we are running tests then mutate_packet may be non NULL */
595     if (qtx->mutatecb != NULL) {
596         if (!qtx->mutatecb(pkt->hdr, pkt->iovec, pkt->num_iovec, &hdr,
597                            &iovec, &num_iovec, qtx->mutatearg)) {
598             ret = QTX_FAIL_GENERIC;
599             goto err;
600         }
601     } else {
602         hdr = pkt->hdr;
603         iovec = pkt->iovec;
604         num_iovec = pkt->num_iovec;
605     }
606
607     /* Walk the iovecs to determine actual input payload length. */
608     iovec_cur_init(&cur, iovec, num_iovec);
609
610     if (cur.bytes_remaining == 0) {
611         /* No zero-length payloads allowed. */
612         ret = QTX_FAIL_GENERIC;
613         goto err;
614     }
615
616     /* Determine encrypted payload length. */
617     payload_len = needs_encrypt ? qtx_inflate_payload_len(qtx, enc_level,
618                                                           cur.bytes_remaining)
619                                 : cur.bytes_remaining;
620
621     /* Determine header length. */
622     hdr->data  = NULL;
623     hdr->len   = payload_len;
624     pred_hdr_len = ossl_quic_wire_get_encoded_pkt_hdr_len(hdr->dst_conn_id.id_len,
625                                                           hdr);
626     if (pred_hdr_len == 0) {
627         ret = QTX_FAIL_GENERIC;
628         goto err;
629     }
630
631     /* We now definitively know our packet length. */
632     pkt_len = pred_hdr_len + payload_len;
633
634     if (pkt_len > space_left) {
635         ret = QTX_FAIL_INSUFFICIENT_LEN;
636         goto err;
637     }
638
639     if (ossl_quic_pkt_type_has_pn(hdr->type)) {
640         if (!ossl_quic_wire_encode_pkt_hdr_pn(pkt->pn,
641                                               hdr->pn,
642                                               hdr->pn_len)) {
643             ret = QTX_FAIL_GENERIC;
644             goto err;
645         }
646     }
647
648     /* Append the header to the TXE. */
649     hdr_start = txe_data(txe) + txe->data_len;
650     if (!qtx_write_hdr(qtx, hdr, txe, &ptrs)) {
651         ret = QTX_FAIL_GENERIC;
652         goto err;
653     }
654
655     hdr_len = (txe_data(txe) + txe->data_len) - hdr_start;
656     assert(hdr_len == pred_hdr_len);
657
658     if (!needs_encrypt) {
659         /* Just copy the payload across. */
660         const unsigned char *src;
661         size_t src_len;
662
663         for (;;) {
664             /* Buffer length has already been checked above. */
665             src_len = iovec_cur_get_buffer(&cur, &src, SIZE_MAX);
666             if (src_len == 0)
667                 break;
668
669             memcpy(txe_data(txe) + txe->data_len, src, src_len);
670             txe->data_len += src_len;
671         }
672     } else {
673         /* Encrypt into TXE. */
674         if (!qtx_encrypt_into_txe(qtx, &cur, txe, enc_level, pkt->pn,
675                                   hdr_start, hdr_len, &ptrs)) {
676             ret = QTX_FAIL_GENERIC;
677             goto err;
678         }
679
680         assert(txe->data_len - orig_data_len == pkt_len);
681     }
682
683     if (qtx->finishmutatecb != NULL)
684         qtx->finishmutatecb(qtx->mutatearg);
685     return 1;
686
687 err:
688     /*
689      * Restore original length so we don't leave a half-written packet in the
690      * TXE.
691      */
692     txe->data_len = orig_data_len;
693     if (qtx->finishmutatecb != NULL)
694         qtx->finishmutatecb(qtx->mutatearg);
695     return ret;
696 }
697
698 static TXE *qtx_ensure_cons(OSSL_QTX *qtx)
699 {
700     TXE *txe = qtx->cons;
701
702     if (txe != NULL)
703         return txe;
704
705     txe = qtx_ensure_free_txe(qtx, qtx->mdpl);
706     if (txe == NULL)
707         return NULL;
708
709     ossl_list_txe_remove(&qtx->free, txe);
710     qtx->cons = txe;
711     qtx->cons_count = 0;
712     txe->data_len = 0;
713     return txe;
714 }
715
716 static int addr_eq(const BIO_ADDR *a, const BIO_ADDR *b)
717 {
718     return ((a == NULL || BIO_ADDR_family(a) == AF_UNSPEC)
719             && (b == NULL || BIO_ADDR_family(b) == AF_UNSPEC))
720         || (a != NULL && b != NULL && memcmp(a, b, sizeof(*a)) == 0);
721 }
722
723 int ossl_qtx_write_pkt(OSSL_QTX *qtx, const OSSL_QTX_PKT *pkt)
724 {
725     int ret;
726     int coalescing = (pkt->flags & OSSL_QTX_PKT_FLAG_COALESCE) != 0;
727     int was_coalescing;
728     TXE *txe;
729     uint32_t enc_level;
730
731     /* Must have EL configured, must have header. */
732     if (pkt->hdr == NULL)
733         return 0;
734
735     enc_level = ossl_quic_pkt_type_to_enc_level(pkt->hdr->type);
736
737     /* Some packet types must be in a packet all by themselves. */
738     if (!ossl_quic_pkt_type_can_share_dgram(pkt->hdr->type))
739         ossl_qtx_finish_dgram(qtx);
740     else if (enc_level >= QUIC_ENC_LEVEL_NUM
741                || ossl_qrl_enc_level_set_have_el(&qtx->el_set, enc_level) != 1) {
742         /* All other packet types are encrypted. */
743         return 0;
744     }
745
746     was_coalescing = (qtx->cons != NULL && qtx->cons->data_len > 0);
747     if (was_coalescing)
748         if (!addr_eq(&qtx->cons->peer, pkt->peer)
749             || !addr_eq(&qtx->cons->local, pkt->local)) {
750             /* Must stop coalescing if addresses have changed */
751             ossl_qtx_finish_dgram(qtx);
752             was_coalescing = 0;
753         }
754
755     for (;;) {
756         /*
757          * Start a new coalescing session or continue using the existing one and
758          * serialize/encrypt the packet. We always encrypt packets as soon as
759          * our caller gives them to us, which relieves the caller of any need to
760          * keep the plaintext around.
761          */
762         txe = qtx_ensure_cons(qtx);
763         if (txe == NULL)
764             return 0; /* allocation failure */
765
766         /*
767          * Ensure TXE has at least MDPL bytes allocated. This should only be
768          * possible if the MDPL has increased.
769          */
770         if (!qtx_reserve_txe(qtx, NULL, txe, qtx->mdpl))
771             return 0;
772
773         if (!was_coalescing) {
774             /* Set addresses in TXE. */
775             if (pkt->peer != NULL)
776                 txe->peer = *pkt->peer;
777             else
778                 BIO_ADDR_clear(&txe->peer);
779
780             if (pkt->local != NULL)
781                 txe->local = *pkt->local;
782             else
783                 BIO_ADDR_clear(&txe->local);
784         }
785
786         ret = qtx_write(qtx, pkt, txe, enc_level);
787         if (ret == 1) {
788             break;
789         } else if (ret == QTX_FAIL_INSUFFICIENT_LEN) {
790             if (was_coalescing) {
791                 /*
792                  * We failed due to insufficient length, so end the current
793                  * datagram and try again.
794                  */
795                 ossl_qtx_finish_dgram(qtx);
796                 was_coalescing = 0;
797             } else {
798                 /*
799                  * We failed due to insufficient length, but we were not
800                  * coalescing/started with an empty datagram, so any future
801                  * attempt to write this packet must also fail.
802                  */
803                 return 0;
804             }
805         } else {
806             return 0; /* other error */
807         }
808     }
809
810     ++qtx->cons_count;
811
812     /*
813      * Some packet types cannot have another packet come after them.
814      */
815     if (ossl_quic_pkt_type_must_be_last(pkt->hdr->type))
816         coalescing = 0;
817
818     if (!coalescing)
819         ossl_qtx_finish_dgram(qtx);
820
821     return 1;
822 }
823
824 /*
825  * Finish any incomplete datagrams for transmission which were flagged for
826  * coalescing. If there is no current coalescing datagram, this is a no-op.
827  */
828 void ossl_qtx_finish_dgram(OSSL_QTX *qtx)
829 {
830     TXE *txe = qtx->cons;
831
832     if (txe == NULL)
833         return;
834
835     if (txe->data_len == 0)
836         /*
837          * If we did not put anything in the datagram, just move it back to the
838          * free list.
839          */
840         ossl_list_txe_insert_tail(&qtx->free, txe);
841     else
842         qtx_add_to_pending(qtx, txe);
843
844     qtx->cons       = NULL;
845     qtx->cons_count = 0;
846 }
847
848 static void txe_to_msg(TXE *txe, BIO_MSG *msg)
849 {
850     msg->data       = txe_data(txe);
851     msg->data_len   = txe->data_len;
852     msg->flags      = 0;
853     msg->peer
854         = BIO_ADDR_family(&txe->peer) != AF_UNSPEC ? &txe->peer : NULL;
855     msg->local
856         = BIO_ADDR_family(&txe->local) != AF_UNSPEC ? &txe->local : NULL;
857 }
858
859 #define MAX_MSGS_PER_SEND   32
860
861 int ossl_qtx_flush_net(OSSL_QTX *qtx)
862 {
863     BIO_MSG msg[MAX_MSGS_PER_SEND];
864     size_t wr, i, total_written = 0;
865     TXE *txe;
866     int res;
867
868     if (ossl_list_txe_head(&qtx->pending) == NULL)
869         return QTX_FLUSH_NET_RES_OK; /* Nothing to send. */
870
871     if (qtx->bio == NULL)
872         return QTX_FLUSH_NET_RES_PERMANENT_FAIL;
873
874     for (;;) {
875         for (txe = ossl_list_txe_head(&qtx->pending), i = 0;
876              txe != NULL && i < OSSL_NELEM(msg);
877              txe = ossl_list_txe_next(txe), ++i)
878             txe_to_msg(txe, &msg[i]);
879
880         if (!i)
881             /* Nothing to send. */
882             break;
883
884         ERR_set_mark();
885         res = BIO_sendmmsg(qtx->bio, msg, sizeof(BIO_MSG), i, 0, &wr);
886         if (res && wr == 0) {
887             /*
888              * Treat 0 messages sent as a transient error and just stop for now.
889              */
890             ERR_clear_last_mark();
891             break;
892         } else if (!res) {
893             /*
894              * We did not get anything, so further calls will probably not
895              * succeed either.
896              */
897             if (BIO_err_is_non_fatal(ERR_peek_last_error())) {
898                 /* Transient error, just stop for now, clearing the error. */
899                 ERR_pop_to_mark();
900                 break;
901             } else {
902                 /* Non-transient error, fail and do not clear the error. */
903                 ERR_clear_last_mark();
904                 return QTX_FLUSH_NET_RES_PERMANENT_FAIL;
905             }
906         }
907
908         ERR_clear_last_mark();
909
910         /*
911          * Remove everything which was successfully sent from the pending queue.
912          */
913         for (i = 0; i < wr; ++i)
914             qtx_pending_to_free(qtx);
915
916         total_written += wr;
917     }
918
919     return total_written > 0
920         ? QTX_FLUSH_NET_RES_OK
921         : QTX_FLUSH_NET_RES_TRANSIENT_FAIL;
922 }
923
924 int ossl_qtx_pop_net(OSSL_QTX *qtx, BIO_MSG *msg)
925 {
926     TXE *txe = ossl_list_txe_head(&qtx->pending);
927
928     if (txe == NULL)
929         return 0;
930
931     txe_to_msg(txe, msg);
932     qtx_pending_to_free(qtx);
933     return 1;
934 }
935
936 void ossl_qtx_set_bio(OSSL_QTX *qtx, BIO *bio)
937 {
938     qtx->bio = bio;
939 }
940
941 int ossl_qtx_set_mdpl(OSSL_QTX *qtx, size_t mdpl)
942 {
943     if (mdpl < QUIC_MIN_INITIAL_DGRAM_LEN)
944         return 0;
945
946     qtx->mdpl = mdpl;
947     return 1;
948 }
949
950 size_t ossl_qtx_get_mdpl(OSSL_QTX *qtx)
951 {
952     return qtx->mdpl;
953 }
954
955 size_t ossl_qtx_get_queue_len_datagrams(OSSL_QTX *qtx)
956 {
957     return qtx->pending_count;
958 }
959
960 size_t ossl_qtx_get_queue_len_bytes(OSSL_QTX *qtx)
961 {
962     return qtx->pending_bytes;
963 }
964
965 size_t ossl_qtx_get_cur_dgram_len_bytes(OSSL_QTX *qtx)
966 {
967     return qtx->cons != NULL ? qtx->cons->data_len : 0;
968 }
969
970 size_t ossl_qtx_get_unflushed_pkt_count(OSSL_QTX *qtx)
971 {
972     return qtx->cons_count;
973 }
974
975 int ossl_qtx_trigger_key_update(OSSL_QTX *qtx)
976 {
977     return ossl_qrl_enc_level_set_key_update(&qtx->el_set,
978                                              QUIC_ENC_LEVEL_1RTT);
979 }
980
981 uint64_t ossl_qtx_get_cur_epoch_pkt_count(OSSL_QTX *qtx, uint32_t enc_level)
982 {
983     OSSL_QRL_ENC_LEVEL *el;
984
985     el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1);
986     if (el == NULL)
987         return UINT64_MAX;
988
989     return el->op_count;
990 }
991
992 uint64_t ossl_qtx_get_max_epoch_pkt_count(OSSL_QTX *qtx, uint32_t enc_level)
993 {
994     OSSL_QRL_ENC_LEVEL *el;
995
996     el = ossl_qrl_enc_level_set_get(&qtx->el_set, enc_level, 1);
997     if (el == NULL)
998         return UINT64_MAX;
999
1000     return ossl_qrl_get_suite_max_pkt(el->suite_id);
1001 }