blob: 6fd8412f2f0a7c65b5cd3f00852bb79bd24031f2 [file] [log] [blame]
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001/*
2 * QUIC protocol implementation. Lower layer with internal features implemented
3 * here such as QUIC encryption, idle timeout, acknowledgement and
4 * retransmission.
5 *
6 * Copyright 2020 HAProxy Technologies, Frederic Lecaille <flecaille@haproxy.com>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version
11 * 2 of the License, or (at your option) any later version.
12 *
13 */
14
15#include <haproxy/quic_conn.h>
16
17#define _GNU_SOURCE
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020018#include <stdio.h>
19#include <stdlib.h>
20
21#include <sys/socket.h>
22#include <sys/stat.h>
23#include <sys/types.h>
24
25#include <netinet/tcp.h>
26
27#include <import/ebmbtree.h>
28
29#include <haproxy/buf-t.h>
30#include <haproxy/compat.h>
31#include <haproxy/api.h>
32#include <haproxy/debug.h>
33#include <haproxy/tools.h>
34#include <haproxy/ticks.h>
35
Amaury Denoyelle15c74702023-02-01 10:18:26 +010036#include <haproxy/applet-t.h>
37#include <haproxy/cli.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020038#include <haproxy/connection.h>
39#include <haproxy/fd.h>
40#include <haproxy/freq_ctr.h>
41#include <haproxy/global.h>
42#include <haproxy/h3.h>
43#include <haproxy/hq_interop.h>
44#include <haproxy/log.h>
45#include <haproxy/mux_quic.h>
46#include <haproxy/ncbuf.h>
47#include <haproxy/pipe.h>
48#include <haproxy/proxy.h>
49#include <haproxy/quic_cc.h>
50#include <haproxy/quic_frame.h>
51#include <haproxy/quic_enc.h>
52#include <haproxy/quic_loss.h>
53#include <haproxy/quic_sock.h>
54#include <haproxy/quic_stats.h>
55#include <haproxy/quic_stream.h>
56#include <haproxy/quic_tp.h>
57#include <haproxy/cbuf.h>
58#include <haproxy/proto_quic.h>
59#include <haproxy/quic_tls.h>
60#include <haproxy/ssl_sock.h>
61#include <haproxy/task.h>
Amaury Denoyelle15c74702023-02-01 10:18:26 +010062#include <haproxy/thread.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020063#include <haproxy/trace.h>
64
Amaury Denoyelle15c74702023-02-01 10:18:26 +010065/* incremented by each "show quic". */
66static unsigned int qc_epoch = 0;
67
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020068/* list of supported QUIC versions by this implementation */
69const struct quic_version quic_versions[] = {
70 {
71 .num = QUIC_PROTOCOL_VERSION_DRAFT_29,
72 .initial_salt = initial_salt_draft_29,
73 .initial_salt_len = sizeof initial_salt_draft_29,
74 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V1,
75 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V1) - 1,
76 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V1,
77 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V1) - 1,
78 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V1,
79 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V1) - 1,
80 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V1,
81 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V1) - 1,
82 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_DRAFT,
83 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_DRAFT,
84 },
85 {
86 .num = QUIC_PROTOCOL_VERSION_1,
87 .initial_salt = initial_salt_v1,
88 .initial_salt_len = sizeof initial_salt_v1,
89 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V1,
90 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V1) - 1,
91 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V1,
92 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V1) - 1,
93 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V1,
94 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V1) - 1,
95 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V1,
96 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V1) - 1,
97 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V1,
98 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V1,
99 },
100 {
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +0100101 .num = QUIC_PROTOCOL_VERSION_2,
102 .initial_salt = initial_salt_v2,
103 .initial_salt_len = sizeof initial_salt_v2,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200104 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V2,
105 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V2) - 1,
106 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V2,
107 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V2) - 1,
108 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V2,
109 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V2) - 1,
110 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V2,
111 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V2) - 1,
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +0100112 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V2,
113 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V2,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200114 },
115};
116
117/* The total number of supported versions */
118const size_t quic_versions_nb = sizeof quic_versions / sizeof *quic_versions;
119/* Listener only preferred version */
120const struct quic_version *preferred_version;
121
122/* trace source and events */
123static void quic_trace(enum trace_level level, uint64_t mask, \
124 const struct trace_source *src,
125 const struct ist where, const struct ist func,
126 const void *a1, const void *a2, const void *a3, const void *a4);
127
128static const struct trace_event quic_trace_events[] = {
129 { .mask = QUIC_EV_CONN_NEW, .name = "new_conn", .desc = "new QUIC connection" },
130 { .mask = QUIC_EV_CONN_INIT, .name = "new_conn_init", .desc = "new QUIC connection initialization" },
131 { .mask = QUIC_EV_CONN_ISEC, .name = "init_secs", .desc = "initial secrets derivation" },
132 { .mask = QUIC_EV_CONN_RSEC, .name = "read_secs", .desc = "read secrets derivation" },
133 { .mask = QUIC_EV_CONN_WSEC, .name = "write_secs", .desc = "write secrets derivation" },
134 { .mask = QUIC_EV_CONN_LPKT, .name = "lstnr_packet", .desc = "new listener received packet" },
135 { .mask = QUIC_EV_CONN_SPKT, .name = "srv_packet", .desc = "new server received packet" },
136 { .mask = QUIC_EV_CONN_ENCPKT, .name = "enc_hdshk_pkt", .desc = "handhshake packet encryption" },
137 { .mask = QUIC_EV_CONN_TXPKT, .name = "tx_pkt", .desc = "TX packet" },
138 { .mask = QUIC_EV_CONN_PAPKT, .name = "phdshk_apkt", .desc = "post handhshake application packet preparation" },
139 { .mask = QUIC_EV_CONN_PAPKTS, .name = "phdshk_apkts", .desc = "post handhshake application packets preparation" },
140 { .mask = QUIC_EV_CONN_IO_CB, .name = "qc_io_cb", .desc = "QUIC conn. I/O processing" },
141 { .mask = QUIC_EV_CONN_RMHP, .name = "rm_hp", .desc = "Remove header protection" },
142 { .mask = QUIC_EV_CONN_PRSHPKT, .name = "parse_hpkt", .desc = "parse handshake packet" },
143 { .mask = QUIC_EV_CONN_PRSAPKT, .name = "parse_apkt", .desc = "parse application packet" },
144 { .mask = QUIC_EV_CONN_PRSFRM, .name = "parse_frm", .desc = "parse frame" },
145 { .mask = QUIC_EV_CONN_PRSAFRM, .name = "parse_ack_frm", .desc = "parse ACK frame" },
146 { .mask = QUIC_EV_CONN_BFRM, .name = "build_frm", .desc = "build frame" },
147 { .mask = QUIC_EV_CONN_PHPKTS, .name = "phdshk_pkts", .desc = "handhshake packets preparation" },
148 { .mask = QUIC_EV_CONN_TRMHP, .name = "rm_hp_try", .desc = "header protection removing try" },
149 { .mask = QUIC_EV_CONN_ELRMHP, .name = "el_rm_hp", .desc = "handshake enc. level header protection removing" },
150 { .mask = QUIC_EV_CONN_RXPKT, .name = "rx_pkt", .desc = "RX packet" },
151 { .mask = QUIC_EV_CONN_SSLDATA, .name = "ssl_provide_data", .desc = "CRYPTO data provision to TLS stack" },
152 { .mask = QUIC_EV_CONN_RXCDATA, .name = "el_treat_rx_cfrms",.desc = "enc. level RX CRYPTO frames processing"},
153 { .mask = QUIC_EV_CONN_ADDDATA, .name = "add_hdshk_data", .desc = "TLS stack ->add_handshake_data() call"},
154 { .mask = QUIC_EV_CONN_FFLIGHT, .name = "flush_flight", .desc = "TLS stack ->flush_flight() call"},
155 { .mask = QUIC_EV_CONN_SSLALERT, .name = "send_alert", .desc = "TLS stack ->send_alert() call"},
156 { .mask = QUIC_EV_CONN_RTTUPDT, .name = "rtt_updt", .desc = "RTT sampling" },
157 { .mask = QUIC_EV_CONN_SPPKTS, .name = "sppkts", .desc = "send prepared packets" },
158 { .mask = QUIC_EV_CONN_PKTLOSS, .name = "pktloss", .desc = "detect packet loss" },
159 { .mask = QUIC_EV_CONN_STIMER, .name = "stimer", .desc = "set timer" },
160 { .mask = QUIC_EV_CONN_PTIMER, .name = "ptimer", .desc = "process timer" },
161 { .mask = QUIC_EV_CONN_SPTO, .name = "spto", .desc = "set PTO" },
162 { .mask = QUIC_EV_CONN_BCFRMS, .name = "bcfrms", .desc = "build CRYPTO data frames" },
163 { .mask = QUIC_EV_CONN_XPRTSEND, .name = "xprt_send", .desc = "sending XRPT subscription" },
164 { .mask = QUIC_EV_CONN_XPRTRECV, .name = "xprt_recv", .desc = "receiving XRPT subscription" },
165 { .mask = QUIC_EV_CONN_FREED, .name = "conn_freed", .desc = "releasing conn. memory" },
166 { .mask = QUIC_EV_CONN_CLOSE, .name = "conn_close", .desc = "closing conn." },
167 { .mask = QUIC_EV_CONN_ACKSTRM, .name = "ack_strm", .desc = "STREAM ack."},
168 { .mask = QUIC_EV_CONN_FRMLIST, .name = "frm_list", .desc = "frame list"},
169 { .mask = QUIC_EV_STATELESS_RST, .name = "stateless_reset", .desc = "stateless reset sent"},
170 { .mask = QUIC_EV_TRANSP_PARAMS, .name = "transport_params", .desc = "transport parameters"},
171 { .mask = QUIC_EV_CONN_IDLE_TIMER, .name = "idle_timer", .desc = "idle timer task"},
172 { .mask = QUIC_EV_CONN_SUB, .name = "xprt_sub", .desc = "RX/TX subcription or unsubscription to QUIC xprt"},
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200173 { .mask = QUIC_EV_CONN_RCV, .name = "conn_recv", .desc = "RX on connection" },
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200174 { /* end */ }
175};
176
177static const struct name_desc quic_trace_lockon_args[4] = {
178 /* arg1 */ { /* already used by the connection */ },
179 /* arg2 */ { .name="quic", .desc="QUIC transport" },
180 /* arg3 */ { },
181 /* arg4 */ { }
182};
183
184static const struct name_desc quic_trace_decoding[] = {
185#define QUIC_VERB_CLEAN 1
186 { .name="clean", .desc="only user-friendly stuff, generally suitable for level \"user\"" },
187 { /* end */ }
188};
189
190
191struct trace_source trace_quic = {
192 .name = IST("quic"),
193 .desc = "QUIC xprt",
194 .arg_def = TRC_ARG1_QCON, /* TRACE()'s first argument is always a quic_conn */
195 .default_cb = quic_trace,
196 .known_events = quic_trace_events,
197 .lockon_args = quic_trace_lockon_args,
198 .decoding = quic_trace_decoding,
199 .report_events = ~0, /* report everything by default */
200};
201
202#define TRACE_SOURCE &trace_quic
203INITCALL1(STG_REGISTER, trace_register_source, TRACE_SOURCE);
204
205static BIO_METHOD *ha_quic_meth;
206
207DECLARE_POOL(pool_head_quic_tx_ring, "quic_tx_ring", QUIC_TX_RING_BUFSZ);
208DECLARE_POOL(pool_head_quic_conn_rxbuf, "quic_conn_rxbuf", QUIC_CONN_RX_BUFSZ);
209DECLARE_STATIC_POOL(pool_head_quic_conn_ctx,
210 "quic_conn_ctx", sizeof(struct ssl_sock_ctx));
211DECLARE_STATIC_POOL(pool_head_quic_conn, "quic_conn", sizeof(struct quic_conn));
212DECLARE_POOL(pool_head_quic_connection_id,
213 "quic_connnection_id", sizeof(struct quic_connection_id));
214DECLARE_POOL(pool_head_quic_dgram, "quic_dgram", sizeof(struct quic_dgram));
215DECLARE_POOL(pool_head_quic_rx_packet, "quic_rx_packet", sizeof(struct quic_rx_packet));
216DECLARE_POOL(pool_head_quic_tx_packet, "quic_tx_packet", sizeof(struct quic_tx_packet));
217DECLARE_STATIC_POOL(pool_head_quic_rx_crypto_frm, "quic_rx_crypto_frm", sizeof(struct quic_rx_crypto_frm));
218DECLARE_STATIC_POOL(pool_head_quic_crypto_buf, "quic_crypto_buf", sizeof(struct quic_crypto_buf));
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +0200219DECLARE_STATIC_POOL(pool_head_quic_cstream, "quic_cstream", sizeof(struct quic_cstream));
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200220DECLARE_POOL(pool_head_quic_frame, "quic_frame", sizeof(struct quic_frame));
221DECLARE_STATIC_POOL(pool_head_quic_arng, "quic_arng", sizeof(struct quic_arng_node));
222
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +0100223static struct quic_connection_id *new_quic_cid(struct eb_root *root,
224 struct quic_conn *qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200225static struct quic_tx_packet *qc_build_pkt(unsigned char **pos, const unsigned char *buf_end,
226 struct quic_enc_level *qel, struct quic_tls_ctx *ctx,
227 struct list *frms, struct quic_conn *qc,
228 const struct quic_version *ver, size_t dglen, int pkt_type,
229 int force_ack, int padding, int probe, int cc, int *err);
230struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state);
231static void qc_idle_timer_do_rearm(struct quic_conn *qc);
232static void qc_idle_timer_rearm(struct quic_conn *qc, int read);
233static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc);
234static int quic_conn_init_timer(struct quic_conn *qc);
235static int quic_conn_init_idle_timer_task(struct quic_conn *qc);
236
237/* Only for debug purpose */
238struct enc_debug_info {
239 unsigned char *payload;
240 size_t payload_len;
241 unsigned char *aad;
242 size_t aad_len;
243 uint64_t pn;
244};
245
246/* Initializes a enc_debug_info struct (only for debug purpose) */
247static inline void enc_debug_info_init(struct enc_debug_info *edi,
248 unsigned char *payload, size_t payload_len,
249 unsigned char *aad, size_t aad_len, uint64_t pn)
250{
251 edi->payload = payload;
252 edi->payload_len = payload_len;
253 edi->aad = aad;
254 edi->aad_len = aad_len;
255 edi->pn = pn;
256}
257
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100258/* Used only for QUIC TLS key phase traces */
259struct quic_kp_trace {
260 const unsigned char *rx_sec;
261 size_t rx_seclen;
262 const struct quic_tls_kp *rx;
263 const unsigned char *tx_sec;
264 size_t tx_seclen;
265 const struct quic_tls_kp *tx;
266};
267
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200268/* Trace callback for QUIC.
269 * These traces always expect that arg1, if non-null, is of type connection.
270 */
271static void quic_trace(enum trace_level level, uint64_t mask, const struct trace_source *src,
272 const struct ist where, const struct ist func,
273 const void *a1, const void *a2, const void *a3, const void *a4)
274{
275 const struct quic_conn *qc = a1;
276
277 if (qc) {
278 const struct quic_tls_ctx *tls_ctx;
279
280 chunk_appendf(&trace_buf, " : qc@%p", qc);
281 if (mask & QUIC_EV_CONN_INIT) {
282 chunk_appendf(&trace_buf, "\n odcid");
283 quic_cid_dump(&trace_buf, &qc->odcid);
284 chunk_appendf(&trace_buf, "\n dcid");
285 quic_cid_dump(&trace_buf, &qc->dcid);
286 chunk_appendf(&trace_buf, "\n scid");
287 quic_cid_dump(&trace_buf, &qc->scid);
288 }
289
290 if (mask & QUIC_EV_TRANSP_PARAMS) {
291 const struct quic_transport_params *p = a2;
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100292
293 if (p)
294 quic_transport_params_dump(&trace_buf, qc, p);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200295 }
296
297 if (mask & QUIC_EV_CONN_ADDDATA) {
298 const enum ssl_encryption_level_t *level = a2;
299 const size_t *len = a3;
300
301 if (level) {
302 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
303
304 chunk_appendf(&trace_buf, " el=%c(%d)", quic_enc_level_char(lvl), lvl);
305 }
306 if (len)
307 chunk_appendf(&trace_buf, " len=%llu", (unsigned long long)*len);
308 }
309 if ((mask & QUIC_EV_CONN_ISEC) && qc) {
310 /* Initial read & write secrets. */
311 enum quic_tls_enc_level level = QUIC_TLS_ENC_LEVEL_INITIAL;
312 const unsigned char *rx_sec = a2;
313 const unsigned char *tx_sec = a3;
314
315 tls_ctx = &qc->els[level].tls_ctx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200316 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(level));
317 if (rx_sec)
318 quic_tls_secret_hexdump(&trace_buf, rx_sec, 32);
319 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
320 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(level));
321 if (tx_sec)
322 quic_tls_secret_hexdump(&trace_buf, tx_sec, 32);
323 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200324 }
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100325
326 if ((mask & QUIC_EV_CONN_KP) && qc) {
327 /* Initial read & write secrets. */
328 const struct quic_kp_trace *kp = a2;
329
330 if (kp) {
331 if (kp->rx) {
332 chunk_appendf(&trace_buf, "\n RX kp");
333 if (kp->rx_sec)
334 quic_tls_secret_hexdump(&trace_buf, kp->rx_sec, kp->rx_seclen);
335 quic_tls_kp_keys_hexdump(&trace_buf, kp->rx);
336 }
337 if (kp->tx) {
338 chunk_appendf(&trace_buf, "\n TX kp");
339 if (kp->tx_sec)
340 quic_tls_secret_hexdump(&trace_buf, kp->tx_sec, kp->tx_seclen);
341 quic_tls_kp_keys_hexdump(&trace_buf, kp->tx);
342 }
343 }
344 }
345
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200346 if (mask & (QUIC_EV_CONN_RSEC|QUIC_EV_CONN_RWSEC)) {
347 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200348
349 if (level) {
350 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
351
352 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200353 if (quic_tls_has_rx_sec(&qc->els[lvl])) {
354 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200355 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200356 }
357 else
358 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200359 }
360 }
361
362 if (mask & (QUIC_EV_CONN_WSEC|QUIC_EV_CONN_RWSEC)) {
363 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200364
365 if (level) {
366 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
367
368 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200369 if (quic_tls_has_tx_sec(&qc->els[lvl])) {
370 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200371 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200372 }
373 else
374 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200375 }
376
377 }
378
379 if (mask & QUIC_EV_CONN_FRMLIST) {
380 const struct list *l = a2;
381
382 if (l) {
383 const struct quic_frame *frm;
384 list_for_each_entry(frm, l, list) {
385 chunk_appendf(&trace_buf, " frm@%p", frm);
386 chunk_frm_appendf(&trace_buf, frm);
387 }
388 }
389 }
390
391 if (mask & (QUIC_EV_CONN_TXPKT|QUIC_EV_CONN_PAPKT)) {
392 const struct quic_tx_packet *pkt = a2;
393 const struct quic_enc_level *qel = a3;
394 const ssize_t *room = a4;
395
396 if (qel) {
397 const struct quic_pktns *pktns = qel->pktns;
Frédéric Lécaille45400532023-02-13 18:39:19 +0100398 chunk_appendf(&trace_buf, " qel=%c pto_count=%d cwnd=%llu ppif=%lld pif=%llu "
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200399 "if=%llu pp=%u",
400 quic_enc_level_char_from_qel(qel, qc),
Frédéric Lécaille45400532023-02-13 18:39:19 +0100401 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200402 (unsigned long long)qc->path->cwnd,
403 (unsigned long long)qc->path->prep_in_flight,
404 (unsigned long long)qc->path->in_flight,
405 (unsigned long long)pktns->tx.in_flight,
406 pktns->tx.pto_probe);
407 }
408 if (pkt) {
409 const struct quic_frame *frm;
410 if (pkt->pn_node.key != (uint64_t)-1)
411 chunk_appendf(&trace_buf, " pn=%llu",(ull)pkt->pn_node.key);
412 list_for_each_entry(frm, &pkt->frms, list) {
413 chunk_appendf(&trace_buf, " frm@%p", frm);
414 chunk_frm_appendf(&trace_buf, frm);
415 }
416 }
417
418 if (room) {
419 chunk_appendf(&trace_buf, " room=%lld", (long long)*room);
420 chunk_appendf(&trace_buf, " dcid.len=%llu scid.len=%llu",
421 (unsigned long long)qc->dcid.len, (unsigned long long)qc->scid.len);
422 }
423 }
424
425 if (mask & QUIC_EV_CONN_IO_CB) {
426 const enum quic_handshake_state *state = a2;
427 const int *err = a3;
428
429 if (state)
430 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(*state));
431 if (err)
432 chunk_appendf(&trace_buf, " err=%s", ssl_error_str(*err));
433 }
434
435 if (mask & (QUIC_EV_CONN_TRMHP|QUIC_EV_CONN_ELRMHP|QUIC_EV_CONN_SPKT)) {
436 const struct quic_rx_packet *pkt = a2;
437 const unsigned long *pktlen = a3;
438 const SSL *ssl = a4;
439
440 if (pkt) {
441 chunk_appendf(&trace_buf, " pkt@%p", pkt);
442 if (pkt->type == QUIC_PACKET_TYPE_SHORT && pkt->data)
443 chunk_appendf(&trace_buf, " kp=%d",
444 !!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT));
445 chunk_appendf(&trace_buf, " el=%c",
446 quic_packet_type_enc_level_char(pkt->type));
447 if (pkt->pnl)
448 chunk_appendf(&trace_buf, " pnl=%u pn=%llu", pkt->pnl,
449 (unsigned long long)pkt->pn);
450 if (pkt->token_len)
451 chunk_appendf(&trace_buf, " toklen=%llu",
452 (unsigned long long)pkt->token_len);
453 if (pkt->aad_len)
454 chunk_appendf(&trace_buf, " aadlen=%llu",
455 (unsigned long long)pkt->aad_len);
456 chunk_appendf(&trace_buf, " flags=0x%x len=%llu",
457 pkt->flags, (unsigned long long)pkt->len);
458 }
459 if (pktlen)
460 chunk_appendf(&trace_buf, " (%ld)", *pktlen);
461 if (ssl) {
462 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
463 chunk_appendf(&trace_buf, " el=%c",
464 quic_enc_level_char(ssl_to_quic_enc_level(level)));
465 }
466 }
467
468 if (mask & (QUIC_EV_CONN_RXPKT|QUIC_EV_CONN_PRSHPKT|QUIC_EV_CONN_SSLDATA)) {
469 const struct quic_rx_packet *pkt = a2;
470 const struct quic_rx_crypto_frm *cf = a3;
471 const SSL *ssl = a4;
472
473 if (pkt)
474 chunk_appendf(&trace_buf, " pkt@%p el=%c pn=%llu", pkt,
475 quic_packet_type_enc_level_char(pkt->type),
476 (unsigned long long)pkt->pn);
477 if (cf)
478 chunk_appendf(&trace_buf, " cfoff=%llu cflen=%llu",
479 (unsigned long long)cf->offset_node.key,
480 (unsigned long long)cf->len);
481 if (ssl) {
482 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
483 chunk_appendf(&trace_buf, " rel=%c",
484 quic_enc_level_char(ssl_to_quic_enc_level(level)));
485 }
486
487 if (qc->err.code)
488 chunk_appendf(&trace_buf, " err_code=0x%llx", (ull)qc->err.code);
489 }
490
491 if (mask & (QUIC_EV_CONN_PRSFRM|QUIC_EV_CONN_BFRM)) {
492 const struct quic_frame *frm = a2;
493
494 if (frm)
495 chunk_appendf(&trace_buf, " %s", quic_frame_type_string(frm->type));
496 }
497
498 if (mask & QUIC_EV_CONN_PHPKTS) {
499 const struct quic_enc_level *qel = a2;
500
501 if (qel) {
502 const struct quic_pktns *pktns = qel->pktns;
503 chunk_appendf(&trace_buf,
Frédéric Lécaille45400532023-02-13 18:39:19 +0100504 " qel=%c state=%s ack?%d pto_count=%d cwnd=%llu ppif=%lld pif=%llu if=%llu pp=%u off=%llu",
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200505 quic_enc_level_char_from_qel(qel, qc),
506 quic_hdshk_state_str(qc->state),
507 !!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED),
Frédéric Lécaille45400532023-02-13 18:39:19 +0100508 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200509 (unsigned long long)qc->path->cwnd,
510 (unsigned long long)qc->path->prep_in_flight,
511 (unsigned long long)qc->path->in_flight,
512 (unsigned long long)pktns->tx.in_flight,
Amaury Denoyelle2f668f02022-11-18 15:24:08 +0100513 pktns->tx.pto_probe,
514 qel->cstream ? (unsigned long long)qel->cstream->rx.offset : 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200515 }
516 }
517
518 if (mask & QUIC_EV_CONN_ENCPKT) {
519 const struct enc_debug_info *edi = a2;
520
521 if (edi)
522 chunk_appendf(&trace_buf,
523 " payload=@%p payload_len=%llu"
524 " aad=@%p aad_len=%llu pn=%llu",
525 edi->payload, (unsigned long long)edi->payload_len,
526 edi->aad, (unsigned long long)edi->aad_len,
527 (unsigned long long)edi->pn);
528 }
529
530 if (mask & QUIC_EV_CONN_RMHP) {
531 const struct quic_rx_packet *pkt = a2;
532
533 if (pkt) {
534 const int *ret = a3;
535
536 chunk_appendf(&trace_buf, " pkt@%p", pkt);
537 if (ret && *ret)
538 chunk_appendf(&trace_buf, " pnl=%u pn=%llu",
539 pkt->pnl, (unsigned long long)pkt->pn);
540 }
541 }
542
543 if (mask & QUIC_EV_CONN_PRSAFRM) {
544 const struct quic_frame *frm = a2;
545 const unsigned long *val1 = a3;
546 const unsigned long *val2 = a4;
547
548 if (frm) {
549 chunk_appendf(&trace_buf, " frm@%p", frm);
550 chunk_frm_appendf(&trace_buf, frm);
551 }
552 if (val1)
553 chunk_appendf(&trace_buf, " %lu", *val1);
554 if (val2)
555 chunk_appendf(&trace_buf, "..%lu", *val2);
556 }
557
558 if (mask & QUIC_EV_CONN_ACKSTRM) {
559 const struct quic_stream *s = a2;
560 const struct qc_stream_desc *stream = a3;
561
562 if (s)
563 chunk_appendf(&trace_buf, " off=%llu len=%llu", (ull)s->offset.key, (ull)s->len);
564 if (stream)
565 chunk_appendf(&trace_buf, " ack_offset=%llu", (ull)stream->ack_offset);
566 }
567
568 if (mask & QUIC_EV_CONN_RTTUPDT) {
569 const unsigned int *rtt_sample = a2;
570 const unsigned int *ack_delay = a3;
571 const struct quic_loss *ql = a4;
572
573 if (rtt_sample)
574 chunk_appendf(&trace_buf, " rtt_sample=%ums", *rtt_sample);
575 if (ack_delay)
576 chunk_appendf(&trace_buf, " ack_delay=%ums", *ack_delay);
577 if (ql)
578 chunk_appendf(&trace_buf,
579 " srtt=%ums rttvar=%ums min_rtt=%ums",
580 ql->srtt >> 3, ql->rtt_var >> 2, ql->rtt_min);
581 }
582 if (mask & QUIC_EV_CONN_CC) {
583 const struct quic_cc_event *ev = a2;
584 const struct quic_cc *cc = a3;
585
586 if (a2)
587 quic_cc_event_trace(&trace_buf, ev);
588 if (a3)
589 quic_cc_state_trace(&trace_buf, cc);
590 }
591
592 if (mask & QUIC_EV_CONN_PKTLOSS) {
593 const struct quic_pktns *pktns = a2;
594 const struct list *lost_pkts = a3;
595
596 if (pktns) {
597 chunk_appendf(&trace_buf, " pktns=%s",
598 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
599 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H");
600 if (pktns->tx.loss_time)
601 chunk_appendf(&trace_buf, " loss_time=%dms",
602 TICKS_TO_MS(tick_remain(now_ms, pktns->tx.loss_time)));
603 }
604 if (lost_pkts && !LIST_ISEMPTY(lost_pkts)) {
605 struct quic_tx_packet *pkt;
606
607 chunk_appendf(&trace_buf, " lost_pkts:");
608 list_for_each_entry(pkt, lost_pkts, list)
609 chunk_appendf(&trace_buf, " %lu", (unsigned long)pkt->pn_node.key);
610 }
611 }
612
613 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_PTIMER|QUIC_EV_CONN_SPTO)) {
614 const struct quic_pktns *pktns = a2;
615 const int *duration = a3;
616 const uint64_t *ifae_pkts = a4;
617
618 if (ifae_pkts)
619 chunk_appendf(&trace_buf, " ifae_pkts=%llu",
620 (unsigned long long)*ifae_pkts);
621 if (pktns) {
622 chunk_appendf(&trace_buf, " pktns=%s pp=%d",
623 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
624 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
625 pktns->tx.pto_probe);
626 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_SPTO)) {
627 if (pktns->tx.in_flight)
628 chunk_appendf(&trace_buf, " if=%llu", (ull)pktns->tx.in_flight);
629 if (pktns->tx.loss_time)
630 chunk_appendf(&trace_buf, " loss_time=%dms",
631 TICKS_TO_MS(pktns->tx.loss_time - now_ms));
632 }
633 if (mask & QUIC_EV_CONN_SPTO) {
634 if (pktns->tx.time_of_last_eliciting)
635 chunk_appendf(&trace_buf, " tole=%dms",
636 TICKS_TO_MS(pktns->tx.time_of_last_eliciting - now_ms));
637 if (duration)
638 chunk_appendf(&trace_buf, " dur=%dms", TICKS_TO_MS(*duration));
639 }
640 }
641
642 if (!(mask & (QUIC_EV_CONN_SPTO|QUIC_EV_CONN_PTIMER)) && qc->timer_task) {
643 chunk_appendf(&trace_buf,
644 " expire=%dms", TICKS_TO_MS(qc->timer - now_ms));
645 }
646 }
647
648 if (mask & QUIC_EV_CONN_SPPKTS) {
649 const struct quic_tx_packet *pkt = a2;
650
Frédéric Lécaille45400532023-02-13 18:39:19 +0100651 chunk_appendf(&trace_buf, " pto_count=%d cwnd=%llu ppif=%llu pif=%llu",
652 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200653 (unsigned long long)qc->path->cwnd,
654 (unsigned long long)qc->path->prep_in_flight,
655 (unsigned long long)qc->path->in_flight);
656 if (pkt) {
657 const struct quic_frame *frm;
658 chunk_appendf(&trace_buf, " pn=%lu(%s) iflen=%llu",
659 (unsigned long)pkt->pn_node.key,
660 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
661 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
662 (unsigned long long)pkt->in_flight_len);
663 chunk_appendf(&trace_buf, " rx.bytes=%llu tx.bytes=%llu",
664 (unsigned long long)qc->rx.bytes,
665 (unsigned long long)qc->tx.bytes);
666 list_for_each_entry(frm, &pkt->frms, list) {
667 chunk_appendf(&trace_buf, " frm@%p", frm);
668 chunk_frm_appendf(&trace_buf, frm);
669 }
Frédéric Lécaillebc09f742023-02-13 17:45:36 +0100670
671 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
672 chunk_appendf(&trace_buf, " with scid");
673 quic_cid_dump(&trace_buf, &qc->scid);
674 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200675 }
676 }
677
678 if (mask & QUIC_EV_CONN_SSLALERT) {
679 const uint8_t *alert = a2;
680 const enum ssl_encryption_level_t *level = a3;
681
682 if (alert)
683 chunk_appendf(&trace_buf, " alert=0x%02x", *alert);
684 if (level)
685 chunk_appendf(&trace_buf, " el=%c",
686 quic_enc_level_char(ssl_to_quic_enc_level(*level)));
687 }
688
689 if (mask & QUIC_EV_CONN_BCFRMS) {
690 const size_t *sz1 = a2;
691 const size_t *sz2 = a3;
692 const size_t *sz3 = a4;
693
694 if (sz1)
695 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz1);
696 if (sz2)
697 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz2);
698 if (sz3)
699 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz3);
700 }
701
702 if (mask & QUIC_EV_CONN_PSTRM) {
703 const struct quic_frame *frm = a2;
704
705 if (frm) {
706 chunk_appendf(&trace_buf, " frm@%p", frm);
707 chunk_frm_appendf(&trace_buf, frm);
708 }
709 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +0200710
711 if (mask & QUIC_EV_CONN_ELEVELSEL) {
712 const enum quic_handshake_state *state = a2;
713 const enum quic_tls_enc_level *level = a3;
714 const enum quic_tls_enc_level *next_level = a4;
715
716 if (state)
717 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(qc->state));
718 if (level)
719 chunk_appendf(&trace_buf, " level=%c", quic_enc_level_char(*level));
720 if (next_level)
721 chunk_appendf(&trace_buf, " next_level=%c", quic_enc_level_char(*next_level));
722
723 }
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200724
725 if (mask & QUIC_EV_CONN_RCV) {
726 const struct quic_dgram *dgram = a2;
727
728 if (dgram)
729 chunk_appendf(&trace_buf, " dgram.len=%zu", dgram->len);
730 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200731 }
732 if (mask & QUIC_EV_CONN_LPKT) {
733 const struct quic_rx_packet *pkt = a2;
734 const uint64_t *len = a3;
735 const struct quic_version *ver = a4;
736
737 if (pkt) {
738 chunk_appendf(&trace_buf, " pkt@%p type=0x%02x %s",
739 pkt, pkt->type, qc_pkt_long(pkt) ? "long" : "short");
740 if (pkt->pn_node.key != (uint64_t)-1)
741 chunk_appendf(&trace_buf, " pn=%llu", pkt->pn_node.key);
742 }
743
744 if (len)
745 chunk_appendf(&trace_buf, " len=%llu", (ull)*len);
746
747 if (ver)
748 chunk_appendf(&trace_buf, " ver=0x%08x", ver->num);
749 }
750
751 if (mask & QUIC_EV_STATELESS_RST) {
752 const struct quic_cid *cid = a2;
753
754 if (cid)
755 quic_cid_dump(&trace_buf, cid);
756 }
757
758}
759
760/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
761static inline int quic_peer_validated_addr(struct quic_conn *qc)
762{
763 struct quic_pktns *hdshk_pktns, *app_pktns;
764
765 if (!qc_is_listener(qc))
766 return 1;
767
768 hdshk_pktns = qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns;
769 app_pktns = qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns;
770 if ((hdshk_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
771 (app_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
772 qc->state >= QUIC_HS_ST_COMPLETE)
773 return 1;
774
775 return 0;
776}
777
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100778/* To be called to kill a connection as soon as possible (without sending any packet). */
779void qc_kill_conn(struct quic_conn *qc)
780{
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100781 TRACE_ENTER(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100782 qc->flags |= QUIC_FL_CONN_TO_KILL;
783 task_wakeup(qc->idle_timer_task, TASK_WOKEN_OTHER);
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100784 TRACE_LEAVE(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100785}
786
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200787/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
788 * both loss detection and PTO and schedule the task assiated to this timer if needed.
789 */
790static inline void qc_set_timer(struct quic_conn *qc)
791{
792 struct quic_pktns *pktns;
793 unsigned int pto;
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100794 int handshake_confirmed;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200795
796 TRACE_ENTER(QUIC_EV_CONN_STIMER, qc,
797 NULL, NULL, &qc->path->ifae_pkts);
798
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100799 pktns = NULL;
800 if (!qc->timer_task) {
801 TRACE_PROTO("already released timer task", QUIC_EV_CONN_STIMER, qc);
802 goto leave;
803 }
804
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200805 pktns = quic_loss_pktns(qc);
806 if (tick_isset(pktns->tx.loss_time)) {
807 qc->timer = pktns->tx.loss_time;
808 goto out;
809 }
810
811 /* anti-amplification: the timer must be
812 * cancelled for a server which reached the anti-amplification limit.
813 */
814 if (!quic_peer_validated_addr(qc) &&
815 (qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
816 TRACE_PROTO("anti-amplification reached", QUIC_EV_CONN_STIMER, qc);
817 qc->timer = TICK_ETERNITY;
818 goto out;
819 }
820
821 if (!qc->path->ifae_pkts && quic_peer_validated_addr(qc)) {
822 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, qc);
823 /* Timer cancellation. */
824 qc->timer = TICK_ETERNITY;
825 goto out;
826 }
827
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100828 handshake_confirmed = qc->state >= QUIC_HS_ST_CONFIRMED;
829 pktns = quic_pto_pktns(qc, handshake_confirmed, &pto);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200830 if (tick_isset(pto))
831 qc->timer = pto;
832 out:
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100833 if (qc->timer == TICK_ETERNITY) {
834 qc->timer_task->expire = TICK_ETERNITY;
835 }
836 else if (tick_is_expired(qc->timer, now_ms)) {
837 TRACE_DEVEL("wakeup asap timer task", QUIC_EV_CONN_STIMER, qc);
838 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
839 }
840 else {
841 TRACE_DEVEL("timer task scheduling", QUIC_EV_CONN_STIMER, qc);
842 task_schedule(qc->timer_task, qc->timer);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200843 }
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100844 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200845 TRACE_LEAVE(QUIC_EV_CONN_STIMER, qc, pktns);
846}
847
848/* Derive new keys and ivs required for Key Update feature for <qc> QUIC
849 * connection.
850 * Return 1 if succeeded, 0 if not.
851 */
852static int quic_tls_key_update(struct quic_conn *qc)
853{
854 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100855 struct quic_tls_secrets *rx = &tls_ctx->rx;
856 struct quic_tls_secrets *tx = &tls_ctx->tx;
857 /* Used only for the traces */
858 struct quic_kp_trace kp_trace = {
859 .rx_sec = rx->secret,
860 .rx_seclen = rx->secretlen,
861 .tx_sec = tx->secret,
862 .tx_seclen = tx->secretlen,
863 };
864 /* The next key phase secrets to be derived */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200865 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
866 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
867 const struct quic_version *ver =
868 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
869 int ret = 0;
870
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100871 TRACE_ENTER(QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200872
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200873 nxt_rx = &qc->ku.nxt_rx;
874 nxt_tx = &qc->ku.nxt_tx;
875
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100876 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
877 "nxt_rx->secretlen=%llu rx->secretlen=%llu",
878 (ull)nxt_rx->secretlen, (ull)rx->secretlen);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200879 /* Prepare new RX secrets */
880 if (!quic_tls_sec_update(rx->md, ver, nxt_rx->secret, nxt_rx->secretlen,
881 rx->secret, rx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100882 TRACE_ERROR("New RX secret update failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200883 goto leave;
884 }
885
886 if (!quic_tls_derive_keys(rx->aead, NULL, rx->md, ver,
887 nxt_rx->key, nxt_rx->keylen,
888 nxt_rx->iv, nxt_rx->ivlen, NULL, 0,
889 nxt_rx->secret, nxt_rx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100890 TRACE_ERROR("New RX key derivation failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200891 goto leave;
892 }
893
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100894 kp_trace.rx = nxt_rx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200895 /* Prepare new TX secrets */
896 if (!quic_tls_sec_update(tx->md, ver, nxt_tx->secret, nxt_tx->secretlen,
897 tx->secret, tx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100898 TRACE_ERROR("New TX secret update failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200899 goto leave;
900 }
901
902 if (!quic_tls_derive_keys(tx->aead, NULL, tx->md, ver,
903 nxt_tx->key, nxt_tx->keylen,
904 nxt_tx->iv, nxt_tx->ivlen, NULL, 0,
905 nxt_tx->secret, nxt_tx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100906 TRACE_ERROR("New TX key derivation failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200907 goto leave;
908 }
909
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100910 kp_trace.tx = nxt_tx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200911 if (nxt_rx->ctx) {
912 EVP_CIPHER_CTX_free(nxt_rx->ctx);
913 nxt_rx->ctx = NULL;
914 }
915
916 if (!quic_tls_rx_ctx_init(&nxt_rx->ctx, tls_ctx->rx.aead, nxt_rx->key)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100917 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200918 goto leave;
919 }
920
921 if (nxt_tx->ctx) {
922 EVP_CIPHER_CTX_free(nxt_tx->ctx);
923 nxt_tx->ctx = NULL;
924 }
925
926 if (!quic_tls_rx_ctx_init(&nxt_tx->ctx, tls_ctx->tx.aead, nxt_tx->key)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100927 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200928 goto leave;
929 }
930
931 ret = 1;
932 leave:
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100933 TRACE_LEAVE(QUIC_EV_CONN_KP, qc, &kp_trace);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200934 return ret;
935}
936
937/* Rotate the Key Update information for <qc> QUIC connection.
938 * Must be used after having updated them.
939 * Always succeeds.
940 */
941static void quic_tls_rotate_keys(struct quic_conn *qc)
942{
943 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
944 unsigned char *curr_secret, *curr_iv, *curr_key;
945 EVP_CIPHER_CTX *curr_ctx;
946
947 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
948
949 /* Rotate the RX secrets */
950 curr_ctx = tls_ctx->rx.ctx;
951 curr_secret = tls_ctx->rx.secret;
952 curr_iv = tls_ctx->rx.iv;
953 curr_key = tls_ctx->rx.key;
954
955 tls_ctx->rx.ctx = qc->ku.nxt_rx.ctx;
956 tls_ctx->rx.secret = qc->ku.nxt_rx.secret;
957 tls_ctx->rx.iv = qc->ku.nxt_rx.iv;
958 tls_ctx->rx.key = qc->ku.nxt_rx.key;
959
960 qc->ku.nxt_rx.ctx = qc->ku.prv_rx.ctx;
961 qc->ku.nxt_rx.secret = qc->ku.prv_rx.secret;
962 qc->ku.nxt_rx.iv = qc->ku.prv_rx.iv;
963 qc->ku.nxt_rx.key = qc->ku.prv_rx.key;
964
965 qc->ku.prv_rx.ctx = curr_ctx;
966 qc->ku.prv_rx.secret = curr_secret;
967 qc->ku.prv_rx.iv = curr_iv;
968 qc->ku.prv_rx.key = curr_key;
969 qc->ku.prv_rx.pn = tls_ctx->rx.pn;
970
971 /* Update the TX secrets */
972 curr_ctx = tls_ctx->tx.ctx;
973 curr_secret = tls_ctx->tx.secret;
974 curr_iv = tls_ctx->tx.iv;
975 curr_key = tls_ctx->tx.key;
976
977 tls_ctx->tx.ctx = qc->ku.nxt_tx.ctx;
978 tls_ctx->tx.secret = qc->ku.nxt_tx.secret;
979 tls_ctx->tx.iv = qc->ku.nxt_tx.iv;
980 tls_ctx->tx.key = qc->ku.nxt_tx.key;
981
982 qc->ku.nxt_tx.ctx = curr_ctx;
983 qc->ku.nxt_tx.secret = curr_secret;
984 qc->ku.nxt_tx.iv = curr_iv;
985 qc->ku.nxt_tx.key = curr_key;
986
987 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
988}
989
990/* returns 0 on error, 1 on success */
991int ha_quic_set_encryption_secrets(SSL *ssl, enum ssl_encryption_level_t level,
992 const uint8_t *read_secret,
993 const uint8_t *write_secret, size_t secret_len)
994{
995 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
996 struct quic_tls_ctx *tls_ctx = &qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
997 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200998 struct quic_tls_secrets *rx = NULL, *tx = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200999 const struct quic_version *ver =
1000 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
1001 int ret = 0;
1002
1003 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
1004 BUG_ON(secret_len > QUIC_TLS_SECRET_LEN);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01001005
1006 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
1007 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
1008 goto out;
1009 }
1010
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001011 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
1012 TRACE_PROTO("CC required", QUIC_EV_CONN_RWSEC, qc);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001013 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001014 }
1015
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001016 if (!read_secret)
1017 goto write;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001018
1019 rx = &tls_ctx->rx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001020 if (!quic_tls_secrets_keys_alloc(rx)) {
1021 TRACE_ERROR("RX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
1022 goto leave;
1023 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001024
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001025 rx->aead = tls_aead(cipher);
1026 rx->md = tls_md(cipher);
1027 rx->hp = tls_hp(cipher);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001028
1029 if (!quic_tls_derive_keys(rx->aead, rx->hp, rx->md, ver, rx->key, rx->keylen,
1030 rx->iv, rx->ivlen, rx->hp_key, sizeof rx->hp_key,
1031 read_secret, secret_len)) {
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001032 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001033 goto leave;
1034 }
1035
1036 if (!quic_tls_rx_ctx_init(&rx->ctx, rx->aead, rx->key)) {
1037 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
1038 goto leave;
1039 }
1040
1041 if (!quic_tls_dec_aes_ctx_init(&rx->hp_ctx, rx->hp, rx->hp_key)) {
1042 TRACE_ERROR("could not initial RX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
1043 goto leave;
1044 }
1045
1046 /* Enqueue this connection asap if we could derive O-RTT secrets as
1047 * listener. Note that a listener derives only RX secrets for this
1048 * level.
1049 */
1050 if (qc_is_listener(qc) && level == ssl_encryption_early_data) {
1051 TRACE_DEVEL("pushing connection into accept queue", QUIC_EV_CONN_RWSEC, qc);
1052 quic_accept_push_qc(qc);
1053 }
1054
1055write:
1056
1057 if (!write_secret)
1058 goto out;
1059
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001060 tx = &tls_ctx->tx;
1061 if (!quic_tls_secrets_keys_alloc(tx)) {
1062 TRACE_ERROR("TX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
1063 goto leave;
1064 }
1065
1066 tx->aead = tls_aead(cipher);
1067 tx->md = tls_md(cipher);
1068 tx->hp = tls_hp(cipher);
1069
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001070 if (!quic_tls_derive_keys(tx->aead, tx->hp, tx->md, ver, tx->key, tx->keylen,
1071 tx->iv, tx->ivlen, tx->hp_key, sizeof tx->hp_key,
1072 write_secret, secret_len)) {
1073 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
1074 goto leave;
1075 }
1076
1077 if (!quic_tls_tx_ctx_init(&tx->ctx, tx->aead, tx->key)) {
1078 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
1079 goto leave;
1080 }
1081
1082 if (!quic_tls_enc_aes_ctx_init(&tx->hp_ctx, tx->hp, tx->hp_key)) {
1083 TRACE_ERROR("could not initial TX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
1084 goto leave;
1085 }
1086
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01001087 if (level == ssl_encryption_handshake && qc_is_listener(qc)) {
1088 qc->enc_params_len =
1089 quic_transport_params_encode(qc->enc_params,
1090 qc->enc_params + sizeof qc->enc_params,
1091 &qc->rx.params, ver, 1);
1092 if (!qc->enc_params_len) {
1093 TRACE_ERROR("quic_transport_params_encode() failed", QUIC_EV_CONN_RWSEC);
1094 goto leave;
1095 }
1096
1097 if (!SSL_set_quic_transport_params(qc->xprt_ctx->ssl, qc->enc_params, qc->enc_params_len)) {
1098 TRACE_ERROR("SSL_set_quic_transport_params() failed", QUIC_EV_CONN_RWSEC);
1099 goto leave;
1100 }
1101 }
1102
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001103 if (level == ssl_encryption_application) {
1104 struct quic_tls_kp *prv_rx = &qc->ku.prv_rx;
1105 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
1106 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
1107
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001108 if (rx) {
1109 if (!(rx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1110 TRACE_ERROR("Could not allocate RX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1111 goto leave;
1112 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001113
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001114 memcpy(rx->secret, read_secret, secret_len);
1115 rx->secretlen = secret_len;
1116 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001117
1118 if (tx) {
1119 if (!(tx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1120 TRACE_ERROR("Could not allocate TX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1121 goto leave;
1122 }
1123
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001124 memcpy(tx->secret, write_secret, secret_len);
1125 tx->secretlen = secret_len;
1126 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001127
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001128 /* Initialize all the secret keys lengths */
1129 prv_rx->secretlen = nxt_rx->secretlen = nxt_tx->secretlen = secret_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001130 }
1131
1132 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001133 ret = 1;
1134 leave:
1135 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc, &level);
1136 return ret;
1137}
1138
1139/* This function copies the CRYPTO data provided by the TLS stack found at <data>
1140 * with <len> as size in CRYPTO buffers dedicated to store the information about
1141 * outgoing CRYPTO frames so that to be able to replay the CRYPTO data streams.
1142 * It fails (returns 0) only if it could not managed to allocate enough CRYPTO
1143 * buffers to store all the data.
1144 * Note that CRYPTO data may exist at any encryption level except at 0-RTT.
1145 */
1146static int quic_crypto_data_cpy(struct quic_conn *qc, struct quic_enc_level *qel,
1147 const unsigned char *data, size_t len)
1148{
1149 struct quic_crypto_buf **qcb;
1150 /* The remaining byte to store in CRYPTO buffers. */
1151 size_t cf_offset, cf_len, *nb_buf;
1152 unsigned char *pos;
1153 int ret = 0;
1154
1155 nb_buf = &qel->tx.crypto.nb_buf;
1156 qcb = &qel->tx.crypto.bufs[*nb_buf - 1];
1157 cf_offset = (*nb_buf - 1) * QUIC_CRYPTO_BUF_SZ + (*qcb)->sz;
1158 cf_len = len;
1159
1160 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1161
1162 while (len) {
1163 size_t to_copy, room;
1164
1165 pos = (*qcb)->data + (*qcb)->sz;
1166 room = QUIC_CRYPTO_BUF_SZ - (*qcb)->sz;
1167 to_copy = len > room ? room : len;
1168 if (to_copy) {
1169 memcpy(pos, data, to_copy);
1170 /* Increment the total size of this CRYPTO buffers by <to_copy>. */
1171 qel->tx.crypto.sz += to_copy;
1172 (*qcb)->sz += to_copy;
1173 len -= to_copy;
1174 data += to_copy;
1175 }
1176 else {
1177 struct quic_crypto_buf **tmp;
1178
1179 // FIXME: realloc!
1180 tmp = realloc(qel->tx.crypto.bufs,
1181 (*nb_buf + 1) * sizeof *qel->tx.crypto.bufs);
1182 if (tmp) {
1183 qel->tx.crypto.bufs = tmp;
1184 qcb = &qel->tx.crypto.bufs[*nb_buf];
1185 *qcb = pool_alloc(pool_head_quic_crypto_buf);
1186 if (!*qcb) {
1187 TRACE_ERROR("Could not allocate crypto buf", QUIC_EV_CONN_ADDDATA, qc);
1188 goto leave;
1189 }
1190
1191 (*qcb)->sz = 0;
1192 ++*nb_buf;
1193 }
1194 else {
1195 break;
1196 }
1197 }
1198 }
1199
1200 /* Allocate a TX CRYPTO frame only if all the CRYPTO data
1201 * have been buffered.
1202 */
1203 if (!len) {
1204 struct quic_frame *frm;
1205 struct quic_frame *found = NULL;
1206
1207 /* There is at most one CRYPTO frame in this packet number
1208 * space. Let's look for it.
1209 */
1210 list_for_each_entry(frm, &qel->pktns->tx.frms, list) {
1211 if (frm->type != QUIC_FT_CRYPTO)
1212 continue;
1213
1214 /* Found */
1215 found = frm;
1216 break;
1217 }
1218
1219 if (found) {
1220 found->crypto.len += cf_len;
1221 }
1222 else {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01001223 frm = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001224 if (!frm) {
1225 TRACE_ERROR("Could not allocate quic frame", QUIC_EV_CONN_ADDDATA, qc);
1226 goto leave;
1227 }
1228
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001229 frm->crypto.offset = cf_offset;
1230 frm->crypto.len = cf_len;
1231 frm->crypto.qel = qel;
1232 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
1233 }
1234 }
1235 ret = len == 0;
1236 leave:
1237 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1238 return ret;
1239}
1240
1241/* Prepare the emission of CONNECTION_CLOSE with error <err>. All send/receive
1242 * activity for <qc> will be interrupted.
1243 */
1244void quic_set_connection_close(struct quic_conn *qc, const struct quic_err err)
1245{
1246 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1247 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)
1248 goto leave;
1249
1250 TRACE_STATE("setting immediate close", QUIC_EV_CONN_CLOSE, qc);
1251 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
1252 qc->err.code = err.code;
1253 qc->err.app = err.app;
1254 leave:
1255 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1256}
1257
1258/* Set <alert> TLS alert as QUIC CRYPTO_ERROR error */
1259void quic_set_tls_alert(struct quic_conn *qc, int alert)
1260{
1261 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1262
1263 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
1264 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
1265 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
1266 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
1267 }
1268 quic_set_connection_close(qc, quic_err_tls(alert));
1269 qc->flags |= QUIC_FL_CONN_TLS_ALERT;
1270 TRACE_STATE("Alert set", QUIC_EV_CONN_SSLALERT, qc);
1271
1272 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1273}
1274
1275/* Set the application for <qc> QUIC connection.
1276 * Return 1 if succeeded, 0 if not.
1277 */
1278int quic_set_app_ops(struct quic_conn *qc, const unsigned char *alpn, size_t alpn_len)
1279{
1280 if (alpn_len >= 2 && memcmp(alpn, "h3", 2) == 0)
1281 qc->app_ops = &h3_ops;
1282 else if (alpn_len >= 10 && memcmp(alpn, "hq-interop", 10) == 0)
1283 qc->app_ops = &hq_interop_ops;
1284 else
1285 return 0;
1286
1287 return 1;
1288}
1289
1290/* ->add_handshake_data QUIC TLS callback used by the QUIC TLS stack when it
1291 * wants to provide the QUIC layer with CRYPTO data.
1292 * Returns 1 if succeeded, 0 if not.
1293 */
1294int ha_quic_add_handshake_data(SSL *ssl, enum ssl_encryption_level_t level,
1295 const uint8_t *data, size_t len)
1296{
1297 struct quic_conn *qc;
1298 enum quic_tls_enc_level tel;
1299 struct quic_enc_level *qel;
1300 int ret = 0;
1301
1302 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1303 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1304
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01001305 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
1306 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
1307 goto out;
1308 }
1309
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001310 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
1311 TRACE_PROTO("CC required", QUIC_EV_CONN_ADDDATA, qc);
1312 goto out;
1313 }
1314
1315 tel = ssl_to_quic_enc_level(level);
1316 if (tel == -1) {
1317 TRACE_ERROR("Wrong encryption level", QUIC_EV_CONN_ADDDATA, qc);
1318 goto leave;
1319 }
1320
1321 qel = &qc->els[tel];
1322 if (!quic_crypto_data_cpy(qc, qel, data, len)) {
1323 TRACE_ERROR("Could not bufferize", QUIC_EV_CONN_ADDDATA, qc);
1324 goto leave;
1325 }
1326
1327 TRACE_DEVEL("CRYPTO data buffered", QUIC_EV_CONN_ADDDATA,
1328 qc, &level, &len);
1329 out:
1330 ret = 1;
1331 leave:
1332 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1333 return ret;
1334}
1335
1336int ha_quic_flush_flight(SSL *ssl)
1337{
1338 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1339
1340 TRACE_ENTER(QUIC_EV_CONN_FFLIGHT, qc);
1341 TRACE_LEAVE(QUIC_EV_CONN_FFLIGHT, qc);
1342
1343 return 1;
1344}
1345
1346int ha_quic_send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
1347{
1348 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1349
1350 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1351
1352 TRACE_PROTO("Received TLS alert", QUIC_EV_CONN_SSLALERT, qc, &alert, &level);
1353
1354 quic_set_tls_alert(qc, alert);
1355 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1356 return 1;
1357}
1358
1359/* QUIC TLS methods */
1360static SSL_QUIC_METHOD ha_quic_method = {
1361 .set_encryption_secrets = ha_quic_set_encryption_secrets,
1362 .add_handshake_data = ha_quic_add_handshake_data,
1363 .flush_flight = ha_quic_flush_flight,
1364 .send_alert = ha_quic_send_alert,
1365};
1366
1367/* Initialize the TLS context of a listener with <bind_conf> as configuration.
1368 * Returns an error count.
1369 */
1370int ssl_quic_initial_ctx(struct bind_conf *bind_conf)
1371{
1372 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
1373 int cfgerr = 0;
1374
1375 long options =
1376 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1377 SSL_OP_SINGLE_ECDH_USE |
1378 SSL_OP_CIPHER_SERVER_PREFERENCE;
1379 SSL_CTX *ctx;
1380
1381 ctx = SSL_CTX_new(TLS_server_method());
1382 bind_conf->initial_ctx = ctx;
1383
1384 SSL_CTX_set_options(ctx, options);
1385 SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
1386 SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
1387 SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
1388
1389#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1390# if defined(HAVE_SSL_CLIENT_HELLO_CB)
1391# if defined(SSL_OP_NO_ANTI_REPLAY)
1392 if (bind_conf->ssl_conf.early_data) {
1393 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
1394 SSL_CTX_set_max_early_data(ctx, 0xffffffff);
1395 }
1396# endif /* !SSL_OP_NO_ANTI_REPLAY */
1397 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
1398 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
1399# else /* ! HAVE_SSL_CLIENT_HELLO_CB */
1400 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
1401# endif
1402 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
1403#endif
1404 SSL_CTX_set_quic_method(ctx, &ha_quic_method);
1405
1406 return cfgerr;
1407}
1408
1409/* Decode an expected packet number from <truncated_on> its truncated value,
1410 * depending on <largest_pn> the largest received packet number, and <pn_nbits>
1411 * the number of bits used to encode this packet number (its length in bytes * 8).
1412 * See https://quicwg.org/base-drafts/draft-ietf-quic-transport.html#packet-encoding
1413 */
1414static uint64_t decode_packet_number(uint64_t largest_pn,
1415 uint32_t truncated_pn, unsigned int pn_nbits)
1416{
1417 uint64_t expected_pn = largest_pn + 1;
1418 uint64_t pn_win = (uint64_t)1 << pn_nbits;
1419 uint64_t pn_hwin = pn_win / 2;
1420 uint64_t pn_mask = pn_win - 1;
1421 uint64_t candidate_pn;
1422
1423
1424 candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
1425 /* Note that <pn_win> > <pn_hwin>. */
1426 if (candidate_pn < QUIC_MAX_PACKET_NUM - pn_win &&
1427 candidate_pn + pn_hwin <= expected_pn)
1428 return candidate_pn + pn_win;
1429
1430 if (candidate_pn > expected_pn + pn_hwin && candidate_pn >= pn_win)
1431 return candidate_pn - pn_win;
1432
1433 return candidate_pn;
1434}
1435
1436/* Remove the header protection of <pkt> QUIC packet using <tls_ctx> as QUIC TLS
1437 * cryptographic context.
1438 * <largest_pn> is the largest received packet number and <pn> the address of
1439 * the packet number field for this packet with <byte0> address of its first byte.
1440 * <end> points to one byte past the end of this packet.
1441 * Returns 1 if succeeded, 0 if not.
1442 */
1443static int qc_do_rm_hp(struct quic_conn *qc,
1444 struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx,
1445 int64_t largest_pn, unsigned char *pn, unsigned char *byte0)
1446{
1447 int ret, i, pnlen;
1448 uint64_t packet_number;
1449 uint32_t truncated_pn = 0;
1450 unsigned char mask[5] = {0};
1451 unsigned char *sample;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001452
1453 TRACE_ENTER(QUIC_EV_CONN_RMHP, qc);
1454
1455 ret = 0;
1456
1457 /* Check there is enough data in this packet. */
1458 if (pkt->len - (pn - byte0) < QUIC_PACKET_PN_MAXLEN + sizeof mask) {
1459 TRACE_PROTO("too short packet", QUIC_EV_CONN_RMHP, qc, pkt);
1460 goto leave;
1461 }
1462
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001463 sample = pn + QUIC_PACKET_PN_MAXLEN;
1464
1465 if (!quic_tls_aes_decrypt(mask, sample, sizeof mask, tls_ctx->rx.hp_ctx)) {
1466 TRACE_ERROR("HP removing failed", QUIC_EV_CONN_RMHP, qc, pkt);
1467 goto leave;
1468 }
1469
1470 *byte0 ^= mask[0] & (*byte0 & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
1471 pnlen = (*byte0 & QUIC_PACKET_PNL_BITMASK) + 1;
1472 for (i = 0; i < pnlen; i++) {
1473 pn[i] ^= mask[i + 1];
1474 truncated_pn = (truncated_pn << 8) | pn[i];
1475 }
1476
1477 packet_number = decode_packet_number(largest_pn, truncated_pn, pnlen * 8);
1478 /* Store remaining information for this unprotected header */
1479 pkt->pn = packet_number;
1480 pkt->pnl = pnlen;
1481
1482 ret = 1;
1483 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001484 TRACE_LEAVE(QUIC_EV_CONN_RMHP, qc);
1485 return ret;
1486}
1487
1488/* Encrypt the payload of a QUIC packet with <pn> as number found at <payload>
1489 * address, with <payload_len> as payload length, <aad> as address of
1490 * the ADD and <aad_len> as AAD length depending on the <tls_ctx> QUIC TLS
1491 * context.
1492 * Returns 1 if succeeded, 0 if not.
1493 */
1494static int quic_packet_encrypt(unsigned char *payload, size_t payload_len,
1495 unsigned char *aad, size_t aad_len, uint64_t pn,
1496 struct quic_tls_ctx *tls_ctx, struct quic_conn *qc)
1497{
1498 int ret = 0;
1499 unsigned char iv[QUIC_TLS_IV_LEN];
1500 unsigned char *tx_iv = tls_ctx->tx.iv;
1501 size_t tx_iv_sz = tls_ctx->tx.ivlen;
1502 struct enc_debug_info edi;
1503
1504 TRACE_ENTER(QUIC_EV_CONN_ENCPKT, qc);
1505
1506 if (!quic_aead_iv_build(iv, sizeof iv, tx_iv, tx_iv_sz, pn)) {
1507 TRACE_ERROR("AEAD IV building for encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1508 goto err;
1509 }
1510
1511 if (!quic_tls_encrypt(payload, payload_len, aad, aad_len,
1512 tls_ctx->tx.ctx, tls_ctx->tx.aead, tls_ctx->tx.key, iv)) {
1513 TRACE_ERROR("QUIC packet encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1514 goto err;
1515 }
1516
1517 ret = 1;
1518 leave:
1519 TRACE_LEAVE(QUIC_EV_CONN_ENCPKT, qc);
1520 return ret;
1521
1522 err:
1523 enc_debug_info_init(&edi, payload, payload_len, aad, aad_len, pn);
1524 goto leave;
1525}
1526
Frédéric Lécaille72027782023-02-22 16:20:09 +01001527/* Select the correct TLS cipher context to used to decipher <pkt> packet
1528 * attached to <qc> connection from <qel> encryption level.
1529 */
1530static inline struct quic_tls_ctx *qc_select_tls_ctx(struct quic_conn *qc,
1531 struct quic_enc_level *qel,
1532 struct quic_rx_packet *pkt)
1533{
1534 return pkt->type != QUIC_PACKET_TYPE_INITIAL ? &qel->tls_ctx :
1535 pkt->version == qc->negotiated_version ? &qc->negotiated_ictx : &qel->tls_ctx;
1536}
1537
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001538/* Decrypt <pkt> packet using encryption level <qel> for <qc> connection.
1539 * Decryption is done in place in packet buffer.
1540 *
Ilya Shipitsin5fa29b82022-12-07 09:46:19 +05001541 * Returns 1 on success else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001542 */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001543static int qc_pkt_decrypt(struct quic_conn *qc, struct quic_enc_level *qel,
1544 struct quic_rx_packet *pkt)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001545{
1546 int ret, kp_changed;
1547 unsigned char iv[QUIC_TLS_IV_LEN];
Frédéric Lécaille72027782023-02-22 16:20:09 +01001548 struct quic_tls_ctx *tls_ctx = qc_select_tls_ctx(qc, qel, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001549 EVP_CIPHER_CTX *rx_ctx = tls_ctx->rx.ctx;
1550 unsigned char *rx_iv = tls_ctx->rx.iv;
1551 size_t rx_iv_sz = tls_ctx->rx.ivlen;
1552 unsigned char *rx_key = tls_ctx->rx.key;
1553
1554 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
1555
1556 ret = 0;
1557 kp_changed = 0;
1558
1559 if (pkt->type == QUIC_PACKET_TYPE_SHORT) {
1560 /* The two tested bits are not at the same position,
1561 * this is why they are first both inversed.
1562 */
1563 if (!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT) ^ !(tls_ctx->flags & QUIC_FL_TLS_KP_BIT_SET)) {
1564 if (pkt->pn < tls_ctx->rx.pn) {
1565 /* The lowest packet number of a previous key phase
1566 * cannot be null if it really stores previous key phase
1567 * secrets.
1568 */
1569 // TODO: check if BUG_ON() more suitable
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001570 if (!qc->ku.prv_rx.pn) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001571 TRACE_ERROR("null previous packet number", QUIC_EV_CONN_RXPKT, qc);
1572 goto leave;
1573 }
1574
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001575 rx_ctx = qc->ku.prv_rx.ctx;
1576 rx_iv = qc->ku.prv_rx.iv;
1577 rx_key = qc->ku.prv_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001578 }
1579 else if (pkt->pn > qel->pktns->rx.largest_pn) {
1580 /* Next key phase */
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +01001581 TRACE_PROTO("Key phase changed", QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001582 kp_changed = 1;
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001583 rx_ctx = qc->ku.nxt_rx.ctx;
1584 rx_iv = qc->ku.nxt_rx.iv;
1585 rx_key = qc->ku.nxt_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001586 }
1587 }
1588 }
1589
1590 if (!quic_aead_iv_build(iv, sizeof iv, rx_iv, rx_iv_sz, pkt->pn)) {
1591 TRACE_ERROR("quic_aead_iv_build() failed", QUIC_EV_CONN_RXPKT, qc);
1592 goto leave;
1593 }
1594
1595 ret = quic_tls_decrypt(pkt->data + pkt->aad_len, pkt->len - pkt->aad_len,
1596 pkt->data, pkt->aad_len,
1597 rx_ctx, tls_ctx->rx.aead, rx_key, iv);
1598 if (!ret) {
1599 TRACE_ERROR("quic_tls_decrypt() failed", QUIC_EV_CONN_RXPKT, qc);
1600 goto leave;
1601 }
1602
1603 /* Update the keys only if the packet decryption succeeded. */
1604 if (kp_changed) {
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001605 quic_tls_rotate_keys(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001606 /* Toggle the Key Phase bit */
1607 tls_ctx->flags ^= QUIC_FL_TLS_KP_BIT_SET;
1608 /* Store the lowest packet number received for the current key phase */
1609 tls_ctx->rx.pn = pkt->pn;
1610 /* Prepare the next key update */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001611 if (!quic_tls_key_update(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001612 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_RXPKT, qc);
1613 goto leave;
1614 }
1615 }
1616
1617 /* Update the packet length (required to parse the frames). */
1618 pkt->len -= QUIC_TLS_TAG_LEN;
1619 ret = 1;
1620 leave:
1621 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
1622 return ret;
1623}
1624
1625
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001626/* Release <frm> frame and mark its copies as acknowledged */
1627void qc_release_frm(struct quic_conn *qc, struct quic_frame *frm)
1628{
1629 uint64_t pn;
1630 struct quic_frame *origin, *f, *tmp;
1631
1632 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1633
1634 /* Identify this frame: a frame copy or one of its copies */
1635 origin = frm->origin ? frm->origin : frm;
1636 /* Ensure the source of the copies is flagged as acked, <frm> being
1637 * possibly a copy of <origin>
1638 */
1639 origin->flags |= QUIC_FL_TX_FRAME_ACKED;
1640 /* Mark all the copy of <origin> as acknowledged. We must
1641 * not release the packets (releasing the frames) at this time as
1642 * they are possibly also to be acknowledged alongside the
1643 * the current one.
1644 */
1645 list_for_each_entry_safe(f, tmp, &origin->reflist, ref) {
1646 if (f->pkt) {
1647 f->flags |= QUIC_FL_TX_FRAME_ACKED;
1648 f->origin = NULL;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001649 LIST_DEL_INIT(&f->ref);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001650 pn = f->pkt->pn_node.key;
1651 TRACE_DEVEL("mark frame as acked from packet",
1652 QUIC_EV_CONN_PRSAFRM, qc, f, &pn);
1653 }
1654 else {
1655 TRACE_DEVEL("freeing unsent frame",
1656 QUIC_EV_CONN_PRSAFRM, qc, f);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001657 LIST_DEL_INIT(&f->ref);
1658 qc_frm_free(&f);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001659 }
1660 }
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001661 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001662 pn = frm->pkt->pn_node.key;
1663 quic_tx_packet_refdec(frm->pkt);
1664 TRACE_DEVEL("freeing frame from packet",
1665 QUIC_EV_CONN_PRSAFRM, qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001666 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001667
1668 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1669}
1670
1671/* Schedule a CONNECTION_CLOSE emission on <qc> if the MUX has been released
1672 * and all STREAM data are acknowledged. The MUX is responsible to have set
1673 * <qc.err> before as it is reused for the CONNECTION_CLOSE frame.
1674 *
1675 * TODO this should also be called on lost packet detection
1676 */
1677void qc_check_close_on_released_mux(struct quic_conn *qc)
1678{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001679 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1680
1681 if (qc->mux_state == QC_MUX_RELEASED && eb_is_empty(&qc->streams_by_id)) {
1682 /* Reuse errcode which should have been previously set by the MUX on release. */
1683 quic_set_connection_close(qc, qc->err);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02001684 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001685 }
1686
1687 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1688}
1689
1690/* Remove from <stream> the acknowledged frames.
1691 *
1692 * Returns 1 if at least one frame was removed else 0.
1693 */
1694static int quic_stream_try_to_consume(struct quic_conn *qc,
1695 struct qc_stream_desc *stream)
1696{
1697 int ret;
1698 struct eb64_node *frm_node;
1699
1700 TRACE_ENTER(QUIC_EV_CONN_ACKSTRM, qc);
1701
1702 ret = 0;
1703 frm_node = eb64_first(&stream->acked_frms);
1704 while (frm_node) {
1705 struct quic_stream *strm;
1706 struct quic_frame *frm;
1707 size_t offset, len;
1708
1709 strm = eb64_entry(frm_node, struct quic_stream, offset);
1710 offset = strm->offset.key;
1711 len = strm->len;
1712
1713 if (offset > stream->ack_offset)
1714 break;
1715
1716 if (qc_stream_desc_ack(&stream, offset, len)) {
1717 /* cf. next comment : frame may be freed at this stage. */
1718 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1719 qc, stream ? strm : NULL, stream);
1720 ret = 1;
1721 }
1722
1723 /* If stream is NULL after qc_stream_desc_ack(), it means frame
1724 * has been freed. with the stream frames tree. Nothing to do
1725 * anymore in here.
1726 */
1727 if (!stream) {
1728 qc_check_close_on_released_mux(qc);
1729 ret = 1;
1730 goto leave;
1731 }
1732
1733 frm_node = eb64_next(frm_node);
1734 eb64_delete(&strm->offset);
1735
1736 frm = container_of(strm, struct quic_frame, stream);
1737 qc_release_frm(qc, frm);
1738 }
1739
1740 leave:
1741 TRACE_LEAVE(QUIC_EV_CONN_ACKSTRM, qc);
1742 return ret;
1743}
1744
1745/* Treat <frm> frame whose packet it is attached to has just been acknowledged. */
1746static inline void qc_treat_acked_tx_frm(struct quic_conn *qc,
1747 struct quic_frame *frm)
1748{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001749 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc, frm);
1750
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001751 switch (frm->type) {
1752 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1753 {
1754 struct quic_stream *strm_frm = &frm->stream;
1755 struct eb64_node *node = NULL;
1756 struct qc_stream_desc *stream = NULL;
1757 const size_t offset = strm_frm->offset.key;
1758 const size_t len = strm_frm->len;
1759
1760 /* do not use strm_frm->stream as the qc_stream_desc instance
1761 * might be freed at this stage. Use the id to do a proper
1762 * lookup.
1763 *
1764 * TODO if lookup operation impact on the perf is noticeable,
1765 * implement a refcount on qc_stream_desc instances.
1766 */
1767 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1768 if (!node) {
1769 TRACE_DEVEL("acked stream for released stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm);
1770 qc_release_frm(qc, frm);
1771 /* early return */
1772 goto leave;
1773 }
1774 stream = eb64_entry(node, struct qc_stream_desc, by_id);
1775
1776 TRACE_DEVEL("acked stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm, stream);
1777 if (offset <= stream->ack_offset) {
1778 if (qc_stream_desc_ack(&stream, offset, len)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001779 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1780 qc, strm_frm, stream);
1781 }
1782
1783 if (!stream) {
1784 /* no need to continue if stream freed. */
1785 TRACE_DEVEL("stream released and freed", QUIC_EV_CONN_ACKSTRM, qc);
1786 qc_release_frm(qc, frm);
1787 qc_check_close_on_released_mux(qc);
1788 break;
1789 }
1790
1791 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1792 qc, strm_frm, stream);
1793 qc_release_frm(qc, frm);
1794 }
1795 else {
1796 eb64_insert(&stream->acked_frms, &strm_frm->offset);
1797 }
1798
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01001799 quic_stream_try_to_consume(qc, stream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001800 }
1801 break;
1802 default:
1803 qc_release_frm(qc, frm);
1804 }
1805
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001806 leave:
1807 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1808}
1809
1810/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1811 * deallocating them, and their TX frames.
1812 * Returns the last node reached to be used for the next range.
1813 * May be NULL if <largest> node could not be found.
1814 */
1815static inline struct eb64_node *qc_ackrng_pkts(struct quic_conn *qc,
1816 struct eb_root *pkts,
1817 unsigned int *pkt_flags,
1818 struct list *newly_acked_pkts,
1819 struct eb64_node *largest_node,
1820 uint64_t largest, uint64_t smallest)
1821{
1822 struct eb64_node *node;
1823 struct quic_tx_packet *pkt;
1824
1825 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1826
1827 node = largest_node ? largest_node : eb64_lookup_le(pkts, largest);
1828 while (node && node->key >= smallest) {
1829 struct quic_frame *frm, *frmbak;
1830
1831 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
1832 *pkt_flags |= pkt->flags;
1833 LIST_INSERT(newly_acked_pkts, &pkt->list);
1834 TRACE_DEVEL("Removing packet #", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
1835 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1836 qc_treat_acked_tx_frm(qc, frm);
Frédéric Lécaille814645f2022-11-18 18:15:28 +01001837 /* If there are others packet in the same datagram <pkt> is attached to,
1838 * detach the previous one and the next one from <pkt>.
1839 */
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01001840 quic_tx_packet_dgram_detach(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001841 node = eb64_prev(node);
1842 eb64_delete(&pkt->pn_node);
1843 }
1844
1845 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1846 return node;
1847}
1848
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001849/* Remove all frames from <pkt_frm_list> and reinsert them in the same order
1850 * they have been sent into <pktns_frm_list>. The loss counter of each frame is
1851 * incremented and checked if it does not exceed retransmission limit.
1852 *
1853 * Returns 1 on success, 0 if a frame loss limit is exceeded. A
1854 * CONNECTION_CLOSE is scheduled in this case.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001855 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001856static inline int qc_requeue_nacked_pkt_tx_frms(struct quic_conn *qc,
1857 struct quic_tx_packet *pkt,
1858 struct list *pktns_frm_list)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001859{
1860 struct quic_frame *frm, *frmbak;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001861 struct list *pkt_frm_list = &pkt->frms;
1862 uint64_t pn = pkt->pn_node.key;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001863 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001864
1865 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1866
1867 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
1868 /* First remove this frame from the packet it was attached to */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001869 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001870 quic_tx_packet_refdec(pkt);
1871 /* At this time, this frame is not freed but removed from its packet */
1872 frm->pkt = NULL;
1873 /* Remove any reference to this frame */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001874 qc_frm_unref(frm, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001875 switch (frm->type) {
1876 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1877 {
1878 struct quic_stream *strm_frm = &frm->stream;
1879 struct eb64_node *node = NULL;
1880 struct qc_stream_desc *stream_desc;
1881
1882 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1883 if (!node) {
1884 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
1885 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1886 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001887 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001888 continue;
1889 }
1890
1891 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
1892 /* Do not resend this frame if in the "already acked range" */
1893 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
1894 TRACE_DEVEL("ignored frame in already acked range",
1895 QUIC_EV_CONN_PRSAFRM, qc, frm);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001896 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001897 continue;
1898 }
1899 else if (strm_frm->offset.key < stream_desc->ack_offset) {
1900 strm_frm->offset.key = stream_desc->ack_offset;
Frédéric Lécaillefc546ab2023-03-16 12:30:36 +01001901 strm_frm->len -= stream_desc->ack_offset - strm_frm->offset.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001902 TRACE_DEVEL("updated partially acked frame",
1903 QUIC_EV_CONN_PRSAFRM, qc, frm);
1904 }
1905 break;
1906 }
1907
1908 default:
1909 break;
1910 }
1911
1912 /* Do not resend probing packet with old data */
1913 if (pkt->flags & QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA) {
1914 TRACE_DEVEL("ignored frame with old data from packet", QUIC_EV_CONN_PRSAFRM,
1915 qc, frm, &pn);
1916 if (frm->origin)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001917 LIST_DEL_INIT(&frm->ref);
1918 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001919 continue;
1920 }
1921
1922 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
1923 TRACE_DEVEL("already acked frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
1924 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1925 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001926 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001927 }
1928 else {
Amaury Denoyelle24d5b722023-01-31 11:44:50 +01001929 if (++frm->loss_count >= global.tune.quic_max_frame_loss) {
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001930 TRACE_ERROR("retransmission limit reached, closing the connection", QUIC_EV_CONN_PRSAFRM, qc);
1931 quic_set_connection_close(qc, quic_err_transport(QC_ERR_INTERNAL_ERROR));
1932 close = 1;
1933 }
1934
Frédéric Lécaillebe795ce2023-03-08 18:23:13 +01001935 LIST_APPEND(pktns_frm_list, &frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001936 TRACE_DEVEL("frame requeued", QUIC_EV_CONN_PRSAFRM, qc, frm);
1937 }
1938 }
1939
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001940 end:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001941 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001942 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001943}
1944
1945/* Free <pkt> TX packet and its attached frames.
1946 * This is the responsibility of the caller to remove this packet of
1947 * any data structure it was possibly attached to.
1948 */
1949static inline void free_quic_tx_packet(struct quic_conn *qc,
1950 struct quic_tx_packet *pkt)
1951{
1952 struct quic_frame *frm, *frmbak;
1953
1954 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1955
1956 if (!pkt)
1957 goto leave;
1958
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001959 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1960 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001961 pool_free(pool_head_quic_tx_packet, pkt);
1962
1963 leave:
1964 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1965}
1966
1967/* Free the TX packets of <pkts> list */
1968static inline void free_quic_tx_pkts(struct quic_conn *qc, struct list *pkts)
1969{
1970 struct quic_tx_packet *pkt, *tmp;
1971
1972 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1973
1974 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1975 LIST_DELETE(&pkt->list);
1976 eb64_delete(&pkt->pn_node);
1977 free_quic_tx_packet(qc, pkt);
1978 }
1979
1980 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1981}
1982
1983/* Remove already sent ranges of acknowledged packet numbers from
1984 * <pktns> packet number space tree below <largest_acked_pn> possibly
1985 * updating the range which contains <largest_acked_pn>.
1986 * Never fails.
1987 */
1988static void qc_treat_ack_of_ack(struct quic_conn *qc,
1989 struct quic_pktns *pktns,
1990 int64_t largest_acked_pn)
1991{
1992 struct eb64_node *ar, *next_ar;
1993 struct quic_arngs *arngs = &pktns->rx.arngs;
1994
1995 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1996
1997 ar = eb64_first(&arngs->root);
1998 while (ar) {
1999 struct quic_arng_node *ar_node;
2000
2001 next_ar = eb64_next(ar);
2002 ar_node = eb64_entry(ar, struct quic_arng_node, first);
2003
2004 if ((int64_t)ar_node->first.key > largest_acked_pn) {
2005 TRACE_DEVEL("first.key > largest", QUIC_EV_CONN_PRSAFRM, qc);
2006 break;
2007 }
2008
2009 if (largest_acked_pn < ar_node->last) {
2010 eb64_delete(ar);
2011 ar_node->first.key = largest_acked_pn + 1;
2012 eb64_insert(&arngs->root, ar);
2013 break;
2014 }
2015
2016 eb64_delete(ar);
2017 pool_free(pool_head_quic_arng, ar_node);
2018 arngs->sz--;
2019 ar = next_ar;
2020 }
2021
2022 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2023}
2024
2025/* Send a packet ack event nofication for each newly acked packet of
2026 * <newly_acked_pkts> list and free them.
2027 * Always succeeds.
2028 */
2029static inline void qc_treat_newly_acked_pkts(struct quic_conn *qc,
2030 struct list *newly_acked_pkts)
2031{
2032 struct quic_tx_packet *pkt, *tmp;
2033 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
2034
2035 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2036
2037 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
2038 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2039 qc->path->prep_in_flight -= pkt->in_flight_len;
2040 qc->path->in_flight -= pkt->in_flight_len;
2041 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2042 qc->path->ifae_pkts--;
2043 /* If this packet contained an ACK frame, proceed to the
2044 * acknowledging of range of acks from the largest acknowledged
2045 * packet number which was sent in an ACK frame by this packet.
2046 */
2047 if (pkt->largest_acked_pn != -1)
2048 qc_treat_ack_of_ack(qc, pkt->pktns, pkt->largest_acked_pn);
2049 ev.ack.acked = pkt->in_flight_len;
2050 ev.ack.time_sent = pkt->time_sent;
2051 quic_cc_event(&qc->path->cc, &ev);
2052 LIST_DELETE(&pkt->list);
2053 eb64_delete(&pkt->pn_node);
2054 quic_tx_packet_refdec(pkt);
2055 }
2056
2057 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2058
2059}
2060
2061/* Release all the frames attached to <pktns> packet number space */
2062static inline void qc_release_pktns_frms(struct quic_conn *qc,
2063 struct quic_pktns *pktns)
2064{
2065 struct quic_frame *frm, *frmbak;
2066
2067 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
2068
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01002069 list_for_each_entry_safe(frm, frmbak, &pktns->tx.frms, list)
2070 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002071
2072 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
2073}
2074
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002075/* Handle <pkts> list of lost packets detected at <now_us> handling their TX
2076 * frames. Send a packet loss event to the congestion controller if in flight
2077 * packet have been lost. Also frees the packet in <pkts> list.
2078 *
2079 * Returns 1 on success else 0 if loss limit has been exceeded. A
2080 * CONNECTION_CLOSE was prepared to close the connection ASAP.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002081 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002082static inline int qc_release_lost_pkts(struct quic_conn *qc,
2083 struct quic_pktns *pktns,
2084 struct list *pkts,
2085 uint64_t now_us)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002086{
2087 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002088 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002089
2090 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2091
2092 if (LIST_ISEMPTY(pkts))
2093 goto leave;
2094
2095 oldest_lost = newest_lost = NULL;
2096 list_for_each_entry_safe(pkt, tmp, pkts, list) {
2097 struct list tmp = LIST_HEAD_INIT(tmp);
2098
2099 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2100 qc->path->prep_in_flight -= pkt->in_flight_len;
2101 qc->path->in_flight -= pkt->in_flight_len;
2102 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2103 qc->path->ifae_pkts--;
2104 /* Treat the frames of this lost packet. */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002105 if (!qc_requeue_nacked_pkt_tx_frms(qc, pkt, &pktns->tx.frms))
2106 close = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002107 LIST_DELETE(&pkt->list);
2108 if (!oldest_lost) {
2109 oldest_lost = newest_lost = pkt;
2110 }
2111 else {
2112 if (newest_lost != oldest_lost)
2113 quic_tx_packet_refdec(newest_lost);
2114 newest_lost = pkt;
2115 }
2116 }
2117
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002118 if (!close) {
2119 if (newest_lost) {
2120 /* Sent a congestion event to the controller */
2121 struct quic_cc_event ev = { };
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002122
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002123 ev.type = QUIC_CC_EVT_LOSS;
2124 ev.loss.time_sent = newest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002125
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002126 quic_cc_event(&qc->path->cc, &ev);
2127 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002128
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002129 /* If an RTT have been already sampled, <rtt_min> has been set.
2130 * We must check if we are experiencing a persistent congestion.
2131 * If this is the case, the congestion controller must re-enter
2132 * slow start state.
2133 */
2134 if (qc->path->loss.rtt_min && newest_lost != oldest_lost) {
2135 unsigned int period = newest_lost->time_sent - oldest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002136
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002137 if (quic_loss_persistent_congestion(&qc->path->loss, period,
2138 now_ms, qc->max_ack_delay))
2139 qc->path->cc.algo->slow_start(&qc->path->cc);
2140 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002141 }
2142
Amaury Denoyelle3a72ba22022-11-14 11:41:34 +01002143 /* <oldest_lost> cannot be NULL at this stage because we have ensured
2144 * that <pkts> list is not empty. Without this, GCC 12.2.0 reports a
2145 * possible overflow on a 0 byte region with O2 optimization.
2146 */
2147 ALREADY_CHECKED(oldest_lost);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002148 quic_tx_packet_refdec(oldest_lost);
2149 if (newest_lost != oldest_lost)
2150 quic_tx_packet_refdec(newest_lost);
2151
2152 leave:
2153 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002154 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002155}
2156
2157/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
2158 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
2159 * if the largest acked packet was newly acked and if there was at least one newly
2160 * acked ack-eliciting packet.
2161 * Return 1, if succeeded, 0 if not.
2162 */
2163static inline int qc_parse_ack_frm(struct quic_conn *qc,
2164 struct quic_frame *frm,
2165 struct quic_enc_level *qel,
2166 unsigned int *rtt_sample,
2167 const unsigned char **pos, const unsigned char *end)
2168{
2169 struct quic_ack *ack = &frm->ack;
2170 uint64_t smallest, largest;
2171 struct eb_root *pkts;
2172 struct eb64_node *largest_node;
2173 unsigned int time_sent, pkt_flags;
2174 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
2175 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2176 int ret = 0;
2177
2178 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2179
2180 if (ack->largest_ack > qel->pktns->tx.next_pn) {
2181 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
2182 qc, NULL, &ack->largest_ack);
2183 goto err;
2184 }
2185
2186 if (ack->first_ack_range > ack->largest_ack) {
2187 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
2188 qc, NULL, &ack->first_ack_range);
2189 goto err;
2190 }
2191
2192 largest = ack->largest_ack;
2193 smallest = largest - ack->first_ack_range;
2194 pkts = &qel->pktns->tx.pkts;
2195 pkt_flags = 0;
2196 largest_node = NULL;
2197 time_sent = 0;
2198
2199 if ((int64_t)ack->largest_ack > qel->pktns->rx.largest_acked_pn) {
2200 largest_node = eb64_lookup(pkts, largest);
2201 if (!largest_node) {
2202 TRACE_DEVEL("Largest acked packet not found",
2203 QUIC_EV_CONN_PRSAFRM, qc);
2204 }
2205 else {
2206 time_sent = eb64_entry(largest_node,
2207 struct quic_tx_packet, pn_node)->time_sent;
2208 }
2209 }
2210
2211 TRACE_PROTO("rcvd ack range", QUIC_EV_CONN_PRSAFRM,
2212 qc, NULL, &largest, &smallest);
2213 do {
2214 uint64_t gap, ack_range;
2215
2216 qc_ackrng_pkts(qc, pkts, &pkt_flags, &newly_acked_pkts,
2217 largest_node, largest, smallest);
2218 if (!ack->ack_range_num--)
2219 break;
2220
2221 if (!quic_dec_int(&gap, pos, end)) {
2222 TRACE_ERROR("quic_dec_int(gap) failed", QUIC_EV_CONN_PRSAFRM, qc);
2223 goto err;
2224 }
2225
2226 if (smallest < gap + 2) {
2227 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
2228 qc, NULL, &gap, &smallest);
2229 goto err;
2230 }
2231
2232 largest = smallest - gap - 2;
2233 if (!quic_dec_int(&ack_range, pos, end)) {
2234 TRACE_ERROR("quic_dec_int(ack_range) failed", QUIC_EV_CONN_PRSAFRM, qc);
2235 goto err;
2236 }
2237
2238 if (largest < ack_range) {
2239 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
2240 qc, NULL, &largest, &ack_range);
2241 goto err;
2242 }
2243
2244 /* Do not use this node anymore. */
2245 largest_node = NULL;
2246 /* Next range */
2247 smallest = largest - ack_range;
2248
2249 TRACE_PROTO("rcvd next ack range", QUIC_EV_CONN_PRSAFRM,
2250 qc, NULL, &largest, &smallest);
2251 } while (1);
2252
2253 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
2254 *rtt_sample = tick_remain(time_sent, now_ms);
2255 qel->pktns->rx.largest_acked_pn = ack->largest_ack;
2256 }
2257
2258 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
2259 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
2260 qc_packet_loss_lookup(qel->pktns, qc, &lost_pkts);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002261 if (!qc_release_lost_pkts(qc, qel->pktns, &lost_pkts, now_ms))
2262 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002263 }
2264 qc_treat_newly_acked_pkts(qc, &newly_acked_pkts);
2265 if (quic_peer_validated_addr(qc))
2266 qc->path->loss.pto_count = 0;
2267 qc_set_timer(qc);
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01002268 qc_notify_send(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002269 }
2270
2271 ret = 1;
2272 leave:
2273 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2274 return ret;
2275
2276 err:
2277 free_quic_tx_pkts(qc, &newly_acked_pkts);
2278 goto leave;
2279}
2280
2281/* This function gives the detail of the SSL error. It is used only
2282 * if the debug mode and the verbose mode are activated. It dump all
2283 * the SSL error until the stack was empty.
2284 */
2285static forceinline void qc_ssl_dump_errors(struct connection *conn)
2286{
2287 if (unlikely(global.mode & MODE_DEBUG)) {
2288 while (1) {
2289 const char *func = NULL;
2290 unsigned long ret;
2291
2292 ERR_peek_error_func(&func);
2293 ret = ERR_get_error();
2294 if (!ret)
2295 return;
2296
2297 fprintf(stderr, "conn. @%p OpenSSL error[0x%lx] %s: %s\n", conn, ret,
2298 func, ERR_reason_error_string(ret));
2299 }
2300 }
2301}
2302
2303int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx,
2304 const char **str, int *len);
2305
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002306/* Finalize <qc> QUIC connection:
2307 * - initialize the Initial QUIC TLS context for negotiated version,
2308 * - derive the secrets for this context,
2309 * - set them into the TLS stack,
2310 *
2311 * MUST be called after having received the remote transport parameters which
2312 * are parsed when the TLS callback for the ClientHello message is called upon
2313 * SSL_do_handshake() calls, not necessarily at the first time as this TLS
2314 * message may be splitted between packets
2315 * Return 1 if succeeded, 0 if not.
2316 */
2317static int qc_conn_finalize(struct quic_conn *qc, int server)
2318{
2319 int ret = 0;
2320
2321 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
2322
2323 if (qc->flags & QUIC_FL_CONN_FINALIZED)
2324 goto finalized;
2325
2326 if (qc->negotiated_version &&
2327 !qc_new_isecs(qc, &qc->negotiated_ictx, qc->negotiated_version,
2328 qc->odcid.data, qc->odcid.len, server))
2329 goto out;
2330
2331 /* This connection is functional (ready to send/receive) */
2332 qc->flags |= QUIC_FL_CONN_FINALIZED;
2333
2334 finalized:
2335 ret = 1;
2336 out:
2337 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
2338 return ret;
2339}
2340
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002341/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
2342 * from <qel> encryption level with <ctx> as QUIC connection context.
2343 * Remaining parameter are there for debugging purposes.
2344 * Return 1 if succeeded, 0 if not.
2345 */
2346static inline int qc_provide_cdata(struct quic_enc_level *el,
2347 struct ssl_sock_ctx *ctx,
2348 const unsigned char *data, size_t len,
2349 struct quic_rx_packet *pkt,
2350 struct quic_rx_crypto_frm *cf)
2351{
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002352#ifdef DEBUG_STRICT
2353 enum ncb_ret ncb_ret;
2354#endif
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002355 int ssl_err, state;
2356 struct quic_conn *qc;
2357 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002358 struct ncbuf *ncbuf = &el->cstream->rx.ncbuf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002359
2360 ssl_err = SSL_ERROR_NONE;
2361 qc = ctx->qc;
2362
2363 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, qc);
2364
2365 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
2366 TRACE_ERROR("SSL_provide_quic_data() error",
2367 QUIC_EV_CONN_SSLDATA, qc, pkt, cf, ctx->ssl);
2368 goto leave;
2369 }
2370
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002371 TRACE_PROTO("in order CRYPTO data",
2372 QUIC_EV_CONN_SSLDATA, qc, NULL, cf, ctx->ssl);
2373
2374 state = qc->state;
2375 if (state < QUIC_HS_ST_COMPLETE) {
2376 ssl_err = SSL_do_handshake(ctx->ssl);
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002377
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01002378 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
2379 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
2380 goto leave;
2381 }
2382
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002383 /* Finalize the connection as soon as possible if the peer transport parameters
2384 * have been received. This may be useful to send packets even if this
2385 * handshake fails.
2386 */
2387 if ((qc->flags & QUIC_FL_CONN_TX_TP_RECEIVED) && !qc_conn_finalize(qc, 1)) {
2388 TRACE_ERROR("connection finalization failed", QUIC_EV_CONN_IO_CB, qc, &state);
2389 goto leave;
2390 }
2391
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002392 if (ssl_err != 1) {
2393 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2394 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2395 TRACE_PROTO("SSL handshake in progress",
2396 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2397 goto out;
2398 }
2399
2400 /* TODO: Should close the connection asap */
2401 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2402 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2403 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2404 HA_ATOMIC_INC(&qc->prx_counters->hdshk_fail);
2405 }
2406 TRACE_ERROR("SSL handshake error", QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2407 qc_ssl_dump_errors(ctx->conn);
2408 ERR_clear_error();
2409 goto leave;
2410 }
2411
2412 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_IO_CB, qc, &state);
2413
2414 /* Check the alpn could be negotiated */
2415 if (!qc->app_ops) {
2416 TRACE_ERROR("No negotiated ALPN", QUIC_EV_CONN_IO_CB, qc, &state);
2417 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
2418 goto leave;
2419 }
2420
2421 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2422 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_IO_CB, qc, &state);
2423 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2424 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2425 }
2426 /* I/O callback switch */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002427 qc->wait_event.tasklet->process = quic_conn_app_io_cb;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002428 if (qc_is_listener(ctx->qc)) {
2429 qc->state = QUIC_HS_ST_CONFIRMED;
2430 /* The connection is ready to be accepted. */
2431 quic_accept_push_qc(qc);
2432 }
2433 else {
2434 qc->state = QUIC_HS_ST_COMPLETE;
2435 }
2436
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02002437 /* Prepare the next key update */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002438 if (!quic_tls_key_update(qc)) {
2439 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_IO_CB, qc);
2440 goto leave;
2441 }
2442 } else {
2443 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
2444 if (ssl_err != 1) {
2445 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2446 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2447 TRACE_PROTO("SSL post handshake in progress",
2448 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2449 goto out;
2450 }
2451
2452 TRACE_ERROR("SSL post handshake error",
2453 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2454 goto leave;
2455 }
2456
2457 TRACE_STATE("SSL post handshake succeeded", QUIC_EV_CONN_IO_CB, qc, &state);
2458 }
2459
2460 out:
2461 ret = 1;
2462 leave:
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002463 /* The CRYPTO data are consumed even in case of an error to release
2464 * the memory asap.
2465 */
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002466 if (!ncb_is_null(ncbuf)) {
2467#ifdef DEBUG_STRICT
2468 ncb_ret = ncb_advance(ncbuf, len);
2469 /* ncb_advance() must always succeed. This is guaranteed as
2470 * this is only done inside a data block. If false, this will
2471 * lead to handshake failure with quic_enc_level offset shifted
2472 * from buffer data.
2473 */
2474 BUG_ON(ncb_ret != NCB_RET_OK);
2475#else
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002476 ncb_advance(ncbuf, len);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002477#endif
2478 }
2479
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002480 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, qc);
2481 return ret;
2482}
2483
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002484/* Parse a STREAM frame <strm_frm> received in <pkt> packet for <qc>
2485 * connection. <fin> is true if FIN bit is set on frame type.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002486 *
2487 * Return 1 on success. On error, 0 is returned. In this case, the packet
2488 * containing the frame must not be acknowledged.
2489 */
2490static inline int qc_handle_strm_frm(struct quic_rx_packet *pkt,
2491 struct quic_stream *strm_frm,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002492 struct quic_conn *qc, char fin)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002493{
2494 int ret;
2495
2496 /* RFC9000 13.1. Packet Processing
2497 *
2498 * A packet MUST NOT be acknowledged until packet protection has been
2499 * successfully removed and all frames contained in the packet have
2500 * been processed. For STREAM frames, this means the data has been
2501 * enqueued in preparation to be received by the application protocol,
2502 * but it does not require that data be delivered and consumed.
2503 */
2504 TRACE_ENTER(QUIC_EV_CONN_PRSFRM, qc);
2505
2506 ret = qcc_recv(qc->qcc, strm_frm->id, strm_frm->len,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002507 strm_frm->offset.key, fin, (char *)strm_frm->data);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002508
2509 /* frame rejected - packet must not be acknowledeged */
2510 TRACE_LEAVE(QUIC_EV_CONN_PRSFRM, qc);
2511 return !ret;
2512}
2513
2514/* Duplicate all frames from <pkt_frm_list> list into <out_frm_list> list
2515 * for <qc> QUIC connection.
2516 * This is a best effort function which never fails even if no memory could be
2517 * allocated to duplicate these frames.
2518 */
2519static void qc_dup_pkt_frms(struct quic_conn *qc,
2520 struct list *pkt_frm_list, struct list *out_frm_list)
2521{
2522 struct quic_frame *frm, *frmbak;
2523 struct list tmp = LIST_HEAD_INIT(tmp);
2524
2525 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2526
2527 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
2528 struct quic_frame *dup_frm, *origin;
2529
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002530 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
2531 TRACE_DEVEL("already acknowledged frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2532 continue;
2533 }
2534
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002535 switch (frm->type) {
2536 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2537 {
2538 struct quic_stream *strm_frm = &frm->stream;
2539 struct eb64_node *node = NULL;
2540 struct qc_stream_desc *stream_desc;
2541
2542 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
2543 if (!node) {
2544 TRACE_DEVEL("ignored frame for a released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
2545 continue;
2546 }
2547
2548 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
2549 /* Do not resend this frame if in the "already acked range" */
2550 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
2551 TRACE_DEVEL("ignored frame in already acked range",
2552 QUIC_EV_CONN_PRSAFRM, qc, frm);
2553 continue;
2554 }
2555 else if (strm_frm->offset.key < stream_desc->ack_offset) {
2556 strm_frm->offset.key = stream_desc->ack_offset;
Frédéric Lécaillefc546ab2023-03-16 12:30:36 +01002557 strm_frm->len -= stream_desc->ack_offset - strm_frm->offset.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002558 TRACE_DEVEL("updated partially acked frame",
2559 QUIC_EV_CONN_PRSAFRM, qc, frm);
2560 }
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01002561
2562 strm_frm->dup = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002563 break;
2564 }
2565
2566 default:
2567 break;
2568 }
2569
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002570 /* If <frm> is already a copy of another frame, we must take
2571 * its original frame as source for the copy.
2572 */
2573 origin = frm->origin ? frm->origin : frm;
2574 dup_frm = qc_frm_dup(origin);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002575 if (!dup_frm) {
2576 TRACE_ERROR("could not duplicate frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2577 break;
2578 }
2579
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002580 TRACE_DEVEL("built probing frame", QUIC_EV_CONN_PRSAFRM, qc, origin);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002581 if (origin->pkt) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002582 TRACE_DEVEL("duplicated from packet", QUIC_EV_CONN_PRSAFRM,
2583 qc, NULL, &origin->pkt->pn_node.key);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002584 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002585 else {
2586 /* <origin> is a frame which was sent from a packet detected as lost. */
2587 TRACE_DEVEL("duplicated from lost packet", QUIC_EV_CONN_PRSAFRM, qc);
2588 }
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002589
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002590 LIST_APPEND(&tmp, &dup_frm->list);
2591 }
2592
2593 LIST_SPLICE(out_frm_list, &tmp);
2594
2595 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2596}
2597
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002598/* Boolean function which return 1 if <pkt> TX packet is only made of
2599 * already acknowledged frame.
2600 */
2601static inline int qc_pkt_with_only_acked_frms(struct quic_tx_packet *pkt)
2602{
2603 struct quic_frame *frm;
2604
2605 list_for_each_entry(frm, &pkt->frms, list)
2606 if (!(frm->flags & QUIC_FL_TX_FRAME_ACKED))
2607 return 0;
2608
2609 return 1;
2610}
2611
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002612/* Prepare a fast retransmission from <qel> encryption level */
2613static void qc_prep_fast_retrans(struct quic_conn *qc,
2614 struct quic_enc_level *qel,
2615 struct list *frms1, struct list *frms2)
2616{
2617 struct eb_root *pkts = &qel->pktns->tx.pkts;
2618 struct list *frms = frms1;
2619 struct eb64_node *node;
2620 struct quic_tx_packet *pkt;
2621
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002622 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002623
2624 BUG_ON(frms1 == frms2);
2625
2626 pkt = NULL;
2627 node = eb64_first(pkts);
2628 start:
2629 while (node) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002630 struct quic_tx_packet *p;
2631
2632 p = eb64_entry(node, struct quic_tx_packet, pn_node);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002633 node = eb64_next(node);
2634 /* Skip the empty and coalesced packets */
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002635 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002636 "--> pn=%llu (%d %d %d)", (ull)p->pn_node.key,
2637 LIST_ISEMPTY(&p->frms), !!(p->flags & QUIC_FL_TX_PACKET_COALESCED),
2638 qc_pkt_with_only_acked_frms(p));
2639 if (!LIST_ISEMPTY(&p->frms) && !qc_pkt_with_only_acked_frms(p)) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002640 pkt = p;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002641 break;
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002642 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002643 }
2644
2645 if (!pkt)
2646 goto leave;
2647
2648 /* When building a packet from another one, the field which may increase the
2649 * packet size is the packet number. And the maximum increase is 4 bytes.
2650 */
2651 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2652 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01002653 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002654 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2655 goto leave;
2656 }
2657
2658 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_SPPKTS, qc, pkt);
2659 qc_dup_pkt_frms(qc, &pkt->frms, frms);
2660 if (frms == frms1 && frms2) {
2661 frms = frms2;
2662 goto start;
2663 }
2664 leave:
2665 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
2666}
2667
2668/* Prepare a fast retransmission during a handshake after a client
2669 * has resent Initial packets. According to the RFC a server may retransmit
2670 * Initial packets send them coalescing with others (Handshake here).
2671 * (Listener only function).
2672 */
2673static void qc_prep_hdshk_fast_retrans(struct quic_conn *qc,
2674 struct list *ifrms, struct list *hfrms)
2675{
2676 struct list itmp = LIST_HEAD_INIT(itmp);
2677 struct list htmp = LIST_HEAD_INIT(htmp);
2678
2679 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2680 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2681 struct quic_enc_level *qel = iqel;
2682 struct eb_root *pkts;
2683 struct eb64_node *node;
2684 struct quic_tx_packet *pkt;
2685 struct list *tmp = &itmp;
2686
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002687 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002688 start:
2689 pkt = NULL;
2690 pkts = &qel->pktns->tx.pkts;
2691 node = eb64_first(pkts);
2692 /* Skip the empty packet (they have already been retransmitted) */
2693 while (node) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002694 struct quic_tx_packet *p;
2695
2696 p = eb64_entry(node, struct quic_tx_packet, pn_node);
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002697 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002698 "--> pn=%llu (%d %d)", (ull)p->pn_node.key,
2699 LIST_ISEMPTY(&p->frms), !!(p->flags & QUIC_FL_TX_PACKET_COALESCED));
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002700 if (!LIST_ISEMPTY(&p->frms) && !(p->flags & QUIC_FL_TX_PACKET_COALESCED) &&
2701 !qc_pkt_with_only_acked_frms(p)) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002702 pkt = p;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002703 break;
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002704 }
2705
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002706 node = eb64_next(node);
2707 }
2708
2709 if (!pkt)
2710 goto end;
2711
2712 /* When building a packet from another one, the field which may increase the
2713 * packet size is the packet number. And the maximum increase is 4 bytes.
2714 */
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002715 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
2716 size_t dglen = pkt->len + 4;
2717
2718 dglen += pkt->next ? pkt->next->len + 4 : 0;
2719 if (dglen > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01002720 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002721 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2722 if (pkt->next)
2723 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt->next);
2724 goto end;
2725 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002726 }
2727
2728 qel->pktns->tx.pto_probe += 1;
2729
2730 /* No risk to loop here, #packet per datagram is bounded */
2731 requeue:
2732 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
2733 qc_dup_pkt_frms(qc, &pkt->frms, tmp);
2734 if (qel == iqel) {
2735 if (pkt->next && pkt->next->type == QUIC_PACKET_TYPE_HANDSHAKE) {
2736 pkt = pkt->next;
2737 tmp = &htmp;
2738 hqel->pktns->tx.pto_probe += 1;
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002739 TRACE_DEVEL("looping for next packet", QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002740 goto requeue;
2741 }
2742 }
2743
2744 end:
2745 LIST_SPLICE(ifrms, &itmp);
2746 LIST_SPLICE(hfrms, &htmp);
2747
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002748 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002749}
2750
2751static void qc_cc_err_count_inc(struct quic_conn *qc, struct quic_frame *frm)
2752{
2753 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
2754
2755 if (frm->type == QUIC_FT_CONNECTION_CLOSE)
2756 quic_stats_transp_err_count_inc(qc->prx_counters, frm->connection_close.error_code);
2757 else if (frm->type == QUIC_FT_CONNECTION_CLOSE_APP) {
2758 if (qc->mux_state != QC_MUX_READY || !qc->qcc->app_ops->inc_err_cnt)
2759 goto out;
2760
2761 qc->qcc->app_ops->inc_err_cnt(qc->qcc->ctx, frm->connection_close_app.error_code);
2762 }
2763
2764 out:
2765 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
2766}
2767
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002768/* Cancel a request on connection <qc> for stream id <id>. This is useful when
2769 * the client opens a new stream but the MUX has already been released. A
Amaury Denoyelle75463012023-02-20 10:31:27 +01002770 * STOP_SENDING + RESET_STREAM frames are prepared for emission.
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002771 *
2772 * TODO this function is closely related to H3. Its place should be in H3 layer
2773 * instead of quic-conn but this requires an architecture adjustment.
2774 *
2775 * Returns 1 on sucess else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002776 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002777static int qc_h3_request_reject(struct quic_conn *qc, uint64_t id)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002778{
2779 int ret = 0;
Amaury Denoyelle75463012023-02-20 10:31:27 +01002780 struct quic_frame *ss, *rs;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002781 struct quic_enc_level *qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002782 const uint64_t app_error_code = H3_REQUEST_REJECTED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002783
2784 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2785
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002786 /* Do not emit rejection for unknown unidirectional stream as it is
2787 * forbidden to close some of them (H3 control stream and QPACK
2788 * encoder/decoder streams).
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002789 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002790 if (quic_stream_is_uni(id)) {
2791 ret = 1;
2792 goto out;
2793 }
2794
Amaury Denoyelle75463012023-02-20 10:31:27 +01002795 ss = qc_frm_alloc(QUIC_FT_STOP_SENDING);
2796 if (!ss) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002797 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2798 goto out;
2799 }
2800
Amaury Denoyelle75463012023-02-20 10:31:27 +01002801 ss->stop_sending.id = id;
2802 ss->stop_sending.app_error_code = app_error_code;
2803
2804 rs = qc_frm_alloc(QUIC_FT_RESET_STREAM);
2805 if (!rs) {
2806 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2807 qc_frm_free(&ss);
2808 goto out;
2809 }
2810
2811 rs->reset_stream.id = id;
2812 rs->reset_stream.app_error_code = app_error_code;
2813 rs->reset_stream.final_size = 0;
2814
2815 LIST_APPEND(&qel->pktns->tx.frms, &ss->list);
2816 LIST_APPEND(&qel->pktns->tx.frms, &rs->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002817 ret = 1;
2818 out:
2819 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2820 return ret;
2821}
2822
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002823/* Release the underlying memory use by <ncbuf> non-contiguous buffer */
2824static void quic_free_ncbuf(struct ncbuf *ncbuf)
2825{
2826 struct buffer buf;
2827
2828 if (ncb_is_null(ncbuf))
2829 return;
2830
2831 buf = b_make(ncbuf->area, ncbuf->size, 0, 0);
2832 b_free(&buf);
2833 offer_buffers(NULL, 1);
2834
2835 *ncbuf = NCBUF_NULL;
2836}
2837
2838/* Allocate the underlying required memory for <ncbuf> non-contiguous buffer */
2839static struct ncbuf *quic_get_ncbuf(struct ncbuf *ncbuf)
2840{
2841 struct buffer buf = BUF_NULL;
2842
2843 if (!ncb_is_null(ncbuf))
2844 return ncbuf;
2845
2846 b_alloc(&buf);
2847 BUG_ON(b_is_null(&buf));
2848
2849 *ncbuf = ncb_make(buf.area, buf.size, 0);
2850 ncb_init(ncbuf, 0);
2851
2852 return ncbuf;
2853}
2854
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002855/* Parse <frm> CRYPTO frame coming with <pkt> packet at <qel> <qc> connectionn.
2856 * Returns 1 if succeeded, 0 if not. Also set <*fast_retrans> to 1 if the
2857 * speed up handshake completion may be run after having received duplicated
2858 * CRYPTO data.
2859 */
2860static int qc_handle_crypto_frm(struct quic_conn *qc,
2861 struct quic_crypto *frm, struct quic_rx_packet *pkt,
2862 struct quic_enc_level *qel, int *fast_retrans)
2863{
2864 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002865 enum ncb_ret ncb_ret;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002866 /* XXX TO DO: <cfdebug> is used only for the traces. */
2867 struct quic_rx_crypto_frm cfdebug = {
2868 .offset_node.key = frm->offset,
2869 .len = frm->len,
2870 };
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002871 struct quic_cstream *cstream = qel->cstream;
2872 struct ncbuf *ncbuf = &qel->cstream->rx.ncbuf;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002873
2874 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2875 if (unlikely(qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD)) {
2876 TRACE_PROTO("CRYPTO data discarded",
2877 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2878 goto done;
2879 }
2880
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002881 if (unlikely(frm->offset < cstream->rx.offset)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002882 size_t diff;
2883
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002884 if (frm->offset + frm->len <= cstream->rx.offset) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002885 /* Nothing to do */
2886 TRACE_PROTO("Already received CRYPTO data",
2887 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2888 if (qc_is_listener(qc) && qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] &&
2889 !(qc->flags & QUIC_FL_CONN_HANDSHAKE_SPEED_UP))
2890 *fast_retrans = 1;
2891 goto done;
2892 }
2893
2894 TRACE_PROTO("Partially already received CRYPTO data",
2895 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2896
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002897 diff = cstream->rx.offset - frm->offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002898 frm->len -= diff;
2899 frm->data += diff;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002900 frm->offset = cstream->rx.offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002901 }
2902
Amaury Denoyelleff95f2d2022-11-18 14:50:06 +01002903 if (frm->offset == cstream->rx.offset && ncb_is_empty(ncbuf)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002904 if (!qc_provide_cdata(qel, qc->xprt_ctx, frm->data, frm->len,
2905 pkt, &cfdebug)) {
2906 // trace already emitted by function above
2907 goto leave;
2908 }
2909
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002910 cstream->rx.offset += frm->len;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002911 TRACE_DEVEL("increment crypto level offset", QUIC_EV_CONN_PHPKTS, qc, qel);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002912 goto done;
2913 }
2914
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002915 if (!quic_get_ncbuf(ncbuf) ||
2916 ncb_is_null(ncbuf)) {
2917 TRACE_ERROR("CRYPTO ncbuf allocation failed", QUIC_EV_CONN_PRSHPKT, qc);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002918 goto leave;
2919 }
2920
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002921 /* frm->offset > cstream-trx.offset */
2922 ncb_ret = ncb_add(ncbuf, frm->offset - cstream->rx.offset,
2923 (const char *)frm->data, frm->len, NCB_ADD_COMPARE);
2924 if (ncb_ret != NCB_RET_OK) {
2925 if (ncb_ret == NCB_RET_DATA_REJ) {
2926 TRACE_ERROR("overlapping data rejected", QUIC_EV_CONN_PRSHPKT, qc);
2927 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
2928 }
2929 else if (ncb_ret == NCB_RET_GAP_SIZE) {
2930 TRACE_ERROR("cannot bufferize frame due to gap size limit",
2931 QUIC_EV_CONN_PRSHPKT, qc);
2932 }
2933 goto leave;
2934 }
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002935
2936 done:
2937 ret = 1;
2938 leave:
2939 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2940 return ret;
2941}
2942
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002943/* Allocate a new connection ID for <qc> connection and build a NEW_CONNECTION_ID
2944 * frame to be sent.
2945 * Return 1 if succeeded, 0 if not.
2946 */
2947static int qc_build_new_connection_id_frm(struct quic_conn *qc,
2948 struct quic_connection_id *cid)
2949{
2950 int ret = 0;
2951 struct quic_frame *frm;
2952 struct quic_enc_level *qel;
2953
2954 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2955
2956 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
2957 frm = qc_frm_alloc(QUIC_FT_NEW_CONNECTION_ID);
2958 if (!frm) {
2959 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
2960 goto leave;
2961 }
2962
2963 quic_connection_id_to_frm_cpy(frm, cid);
2964 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
2965 ret = 1;
2966 leave:
2967 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2968 return ret;
2969}
2970
2971
2972/* Handle RETIRE_CONNECTION_ID frame from <frm> frame.
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002973 * Return 1 if succeeded, 0 if not. If succeeded, also set <cid_to_retire>
2974 * to the CID to be retired if not already retired.
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002975 */
2976static int qc_handle_retire_connection_id_frm(struct quic_conn *qc,
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002977 struct quic_frame *frm,
2978 struct quic_cid *dcid,
2979 struct quic_connection_id **cid_to_retire)
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002980{
2981 int ret = 0;
2982 struct quic_retire_connection_id *rcid = &frm->retire_connection_id;
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002983 struct eb64_node *node;
2984 struct quic_connection_id *cid;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002985
2986 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2987
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002988 /* RFC 9000 19.16. RETIRE_CONNECTION_ID Frames:
2989 * Receipt of a RETIRE_CONNECTION_ID frame containing a sequence number greater
2990 * than any previously sent to the peer MUST be treated as a connection error
2991 * of type PROTOCOL_VIOLATION.
2992 */
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002993 if (rcid->seq_num >= qc->next_cid_seq_num) {
2994 TRACE_PROTO("CID seq. number too big", QUIC_EV_CONN_PSTRM, qc, frm);
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002995 goto protocol_violation;
2996 }
2997
2998 /* RFC 9000 19.16. RETIRE_CONNECTION_ID Frames:
2999 * The sequence number specified in a RETIRE_CONNECTION_ID frame MUST NOT refer to
3000 * the Destination Connection ID field of the packet in which the frame is contained.
3001 * The peer MAY treat this as a connection error of type PROTOCOL_VIOLATION.
3002 */
3003 node = eb64_lookup(&qc->cids, rcid->seq_num);
3004 if (!node) {
3005 TRACE_PROTO("CID already retired", QUIC_EV_CONN_PSTRM, qc, frm);
3006 goto out;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003007 }
3008
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003009 cid = eb64_entry(node, struct quic_connection_id, seq_num);
3010 /* Note that the length of <dcid> has already been checked. It must match the
3011 * length of the CIDs which have been provided to the peer.
3012 */
3013 if (!memcmp(dcid->data, cid->cid.data, QUIC_HAP_CID_LEN)) {
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003014 TRACE_PROTO("cannot retire the current CID", QUIC_EV_CONN_PSTRM, qc, frm);
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003015 goto protocol_violation;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003016 }
3017
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003018 *cid_to_retire = cid;
3019 out:
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003020 ret = 1;
3021 leave:
3022 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
3023 return ret;
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003024 protocol_violation:
3025 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
3026 goto leave;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003027}
3028
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01003029/* Remove a <qc> quic-conn from its ha_thread_ctx list. If <closing> is true,
3030 * it will immediately be reinserted in the ha_thread_ctx quic_conns_clo list.
3031 */
3032static void qc_detach_th_ctx_list(struct quic_conn *qc, int closing)
3033{
3034 struct bref *bref, *back;
3035
3036 /* Detach CLI context watchers currently dumping this connection.
3037 * Reattach them to the next quic_conn instance.
3038 */
3039 list_for_each_entry_safe(bref, back, &qc->back_refs, users) {
3040 /* Remove watcher from this quic_conn instance. */
3041 LIST_DEL_INIT(&bref->users);
3042
3043 /* Attach it to next instance unless it was the last list element. */
3044 if (qc->el_th_ctx.n != &th_ctx->quic_conns &&
3045 qc->el_th_ctx.n != &th_ctx->quic_conns_clo) {
3046 struct quic_conn *next = LIST_NEXT(&qc->el_th_ctx,
3047 struct quic_conn *,
3048 el_th_ctx);
3049 LIST_APPEND(&next->back_refs, &bref->users);
3050 }
3051 bref->ref = qc->el_th_ctx.n;
3052 __ha_barrier_store();
3053 }
3054
3055 /* Remove quic_conn from global ha_thread_ctx list. */
3056 LIST_DEL_INIT(&qc->el_th_ctx);
3057
3058 if (closing)
3059 LIST_APPEND(&th_ctx->quic_conns_clo, &qc->el_th_ctx);
3060}
3061
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003062/* Parse all the frames of <pkt> QUIC packet for QUIC connection <qc> and <qel>
3063 * as encryption level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003064 * Returns 1 if succeeded, 0 if failed.
3065 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003066static int qc_parse_pkt_frms(struct quic_conn *qc, struct quic_rx_packet *pkt,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003067 struct quic_enc_level *qel)
3068{
3069 struct quic_frame frm;
3070 const unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003071 int fast_retrans = 0, ret = 0;
3072
3073 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
3074 /* Skip the AAD */
3075 pos = pkt->data + pkt->aad_len;
3076 end = pkt->data + pkt->len;
3077
3078 while (pos < end) {
3079 if (!qc_parse_frm(&frm, pkt, &pos, end, qc)) {
3080 // trace already emitted by function above
3081 goto leave;
3082 }
3083
3084 TRACE_PROTO("RX frame", QUIC_EV_CONN_PSTRM, qc, &frm);
3085 switch (frm.type) {
3086 case QUIC_FT_PADDING:
3087 break;
3088 case QUIC_FT_PING:
3089 break;
3090 case QUIC_FT_ACK:
3091 {
3092 unsigned int rtt_sample;
3093
3094 rtt_sample = 0;
3095 if (!qc_parse_ack_frm(qc, &frm, qel, &rtt_sample, &pos, end)) {
3096 // trace already emitted by function above
3097 goto leave;
3098 }
3099
3100 if (rtt_sample) {
3101 unsigned int ack_delay;
3102
3103 ack_delay = !quic_application_pktns(qel->pktns, qc) ? 0 :
3104 qc->state >= QUIC_HS_ST_CONFIRMED ?
3105 MS_TO_TICKS(QUIC_MIN(quic_ack_delay_ms(&frm.ack, qc), qc->max_ack_delay)) :
3106 MS_TO_TICKS(quic_ack_delay_ms(&frm.ack, qc));
3107 quic_loss_srtt_update(&qc->path->loss, rtt_sample, ack_delay, qc);
3108 }
3109 break;
3110 }
3111 case QUIC_FT_RESET_STREAM:
Amaury Denoyelle5854fc02022-12-09 16:25:48 +01003112 if (qc->mux_state == QC_MUX_READY) {
3113 struct quic_reset_stream *rs = &frm.reset_stream;
3114 qcc_recv_reset_stream(qc->qcc, rs->id, rs->app_error_code, rs->final_size);
3115 }
3116 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003117 case QUIC_FT_STOP_SENDING:
3118 {
3119 struct quic_stop_sending *stop_sending = &frm.stop_sending;
3120 if (qc->mux_state == QC_MUX_READY) {
3121 if (qcc_recv_stop_sending(qc->qcc, stop_sending->id,
3122 stop_sending->app_error_code)) {
3123 TRACE_ERROR("qcc_recv_stop_sending() failed", QUIC_EV_CONN_PRSHPKT, qc);
3124 goto leave;
3125 }
3126 }
3127 break;
3128 }
3129 case QUIC_FT_CRYPTO:
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02003130 if (!qc_handle_crypto_frm(qc, &frm.crypto, pkt, qel, &fast_retrans))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003131 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003132 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003133 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
3134 {
3135 struct quic_stream *stream = &frm.stream;
3136 unsigned nb_streams = qc->rx.strms[qcs_id_type(stream->id)].nb_streams;
Amaury Denoyelle2216b082023-02-02 14:59:36 +01003137 const char fin = frm.type & QUIC_STREAM_FRAME_TYPE_FIN_BIT;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003138
3139 /* The upper layer may not be allocated. */
3140 if (qc->mux_state != QC_MUX_READY) {
3141 if ((stream->id >> QCS_ID_TYPE_SHIFT) < nb_streams) {
3142 TRACE_DATA("Already closed stream", QUIC_EV_CONN_PRSHPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003143 }
3144 else {
3145 TRACE_DEVEL("No mux for new stream", QUIC_EV_CONN_PRSHPKT, qc);
Amaury Denoyelle38836b62023-02-07 14:24:54 +01003146 if (qc->app_ops == &h3_ops) {
Amaury Denoyelle156a89a2023-02-20 10:32:16 +01003147 if (!qc_h3_request_reject(qc, stream->id)) {
3148 TRACE_ERROR("error on request rejection", QUIC_EV_CONN_PRSHPKT, qc);
3149 /* This packet will not be acknowledged */
3150 goto leave;
3151 }
3152 }
3153 else {
3154 /* This packet will not be acknowledged */
3155 goto leave;
Frédéric Lécailled18025e2023-01-20 15:33:50 +01003156 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003157 }
Amaury Denoyelle315a4f62023-03-06 09:10:53 +01003158
3159 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003160 }
3161
Amaury Denoyelle2216b082023-02-02 14:59:36 +01003162 if (!qc_handle_strm_frm(pkt, stream, qc, fin)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003163 TRACE_ERROR("qc_handle_strm_frm() failed", QUIC_EV_CONN_PRSHPKT, qc);
3164 goto leave;
3165 }
3166
3167 break;
3168 }
3169 case QUIC_FT_MAX_DATA:
3170 if (qc->mux_state == QC_MUX_READY) {
3171 struct quic_max_data *data = &frm.max_data;
3172 qcc_recv_max_data(qc->qcc, data->max_data);
3173 }
3174 break;
3175 case QUIC_FT_MAX_STREAM_DATA:
3176 if (qc->mux_state == QC_MUX_READY) {
3177 struct quic_max_stream_data *data = &frm.max_stream_data;
3178 if (qcc_recv_max_stream_data(qc->qcc, data->id,
3179 data->max_stream_data)) {
3180 TRACE_ERROR("qcc_recv_max_stream_data() failed", QUIC_EV_CONN_PRSHPKT, qc);
3181 goto leave;
3182 }
3183 }
3184 break;
3185 case QUIC_FT_MAX_STREAMS_BIDI:
3186 case QUIC_FT_MAX_STREAMS_UNI:
3187 break;
3188 case QUIC_FT_DATA_BLOCKED:
3189 HA_ATOMIC_INC(&qc->prx_counters->data_blocked);
3190 break;
3191 case QUIC_FT_STREAM_DATA_BLOCKED:
3192 HA_ATOMIC_INC(&qc->prx_counters->stream_data_blocked);
3193 break;
3194 case QUIC_FT_STREAMS_BLOCKED_BIDI:
3195 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_bidi);
3196 break;
3197 case QUIC_FT_STREAMS_BLOCKED_UNI:
3198 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_uni);
3199 break;
3200 case QUIC_FT_NEW_CONNECTION_ID:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003201 /* XXX TO DO XXX */
3202 break;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003203 case QUIC_FT_RETIRE_CONNECTION_ID:
3204 {
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003205 struct quic_connection_id *cid = NULL;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003206
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003207 if (!qc_handle_retire_connection_id_frm(qc, &frm, &pkt->dcid, &cid))
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003208 goto leave;
3209
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003210 if (!cid)
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003211 break;
3212
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003213 ebmb_delete(&cid->node);
3214 eb64_delete(&cid->seq_num);
3215 pool_free(pool_head_quic_connection_id, cid);
3216 TRACE_PROTO("CID retired", QUIC_EV_CONN_PSTRM, qc);
3217
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003218 cid = new_quic_cid(&qc->cids, qc);
3219 if (!cid) {
3220 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3221 }
3222 else {
3223 /* insert the allocated CID in the receiver datagram handler tree */
3224 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3225 qc_build_new_connection_id_frm(qc, cid);
3226 }
3227 break;
3228 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003229 case QUIC_FT_CONNECTION_CLOSE:
3230 case QUIC_FT_CONNECTION_CLOSE_APP:
3231 /* Increment the error counters */
3232 qc_cc_err_count_inc(qc, &frm);
3233 if (!(qc->flags & QUIC_FL_CONN_DRAINING)) {
3234 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
3235 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
3236 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
3237 }
3238 TRACE_STATE("Entering draining state", QUIC_EV_CONN_PRSHPKT, qc);
3239 /* RFC 9000 10.2. Immediate Close:
3240 * The closing and draining connection states exist to ensure
3241 * that connections close cleanly and that delayed or reordered
3242 * packets are properly discarded. These states SHOULD persist
3243 * for at least three times the current PTO interval...
3244 *
3245 * Rearm the idle timeout only one time when entering draining
3246 * state.
3247 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003248 qc->flags |= QUIC_FL_CONN_DRAINING|QUIC_FL_CONN_IMMEDIATE_CLOSE;
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01003249 qc_detach_th_ctx_list(qc, 1);
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01003250 qc_idle_timer_do_rearm(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003251 qc_notify_close(qc);
3252 }
3253 break;
3254 case QUIC_FT_HANDSHAKE_DONE:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003255 if (qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003256 TRACE_ERROR("non accepted QUIC_FT_HANDSHAKE_DONE frame",
3257 QUIC_EV_CONN_PRSHPKT, qc);
3258 goto leave;
3259 }
3260
3261 qc->state = QUIC_HS_ST_CONFIRMED;
3262 break;
3263 default:
3264 TRACE_ERROR("unknosw frame type", QUIC_EV_CONN_PRSHPKT, qc);
3265 goto leave;
3266 }
3267 }
3268
3269 /* Flag this packet number space as having received a packet. */
3270 qel->pktns->flags |= QUIC_FL_PKTNS_PKT_RECEIVED;
3271
3272 if (fast_retrans) {
3273 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
3274 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
3275
3276 TRACE_PROTO("speeding up handshake completion", QUIC_EV_CONN_PRSHPKT, qc);
3277 qc_prep_hdshk_fast_retrans(qc, &iqel->pktns->tx.frms, &hqel->pktns->tx.frms);
3278 qc->flags |= QUIC_FL_CONN_HANDSHAKE_SPEED_UP;
3279 }
3280
3281 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
3282 * has successfully parse a Handshake packet. The Initial encryption must also
3283 * be discarded.
3284 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003285 if (pkt->type == QUIC_PACKET_TYPE_HANDSHAKE && qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003286 if (qc->state >= QUIC_HS_ST_SERVER_INITIAL) {
3287 if (!(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx.flags &
3288 QUIC_FL_TLS_SECRETS_DCD)) {
3289 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3290 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PRSHPKT, qc);
3291 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003292 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003293 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3294 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3295 }
3296 if (qc->state < QUIC_HS_ST_SERVER_HANDSHAKE)
3297 qc->state = QUIC_HS_ST_SERVER_HANDSHAKE;
3298 }
3299 }
3300
3301 ret = 1;
3302 leave:
3303 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
3304 return ret;
3305}
3306
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003307
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003308/* Allocate Tx buffer from <qc> quic-conn if needed.
3309 *
3310 * Returns allocated buffer or NULL on error.
3311 */
3312static struct buffer *qc_txb_alloc(struct quic_conn *qc)
3313{
3314 struct buffer *buf = &qc->tx.buf;
3315 if (!b_alloc(buf))
3316 return NULL;
3317
3318 return buf;
3319}
3320
3321/* Free Tx buffer from <qc> if it is empty. */
3322static void qc_txb_release(struct quic_conn *qc)
3323{
3324 struct buffer *buf = &qc->tx.buf;
3325
3326 /* For the moment sending function is responsible to purge the buffer
3327 * entirely. It may change in the future but this requires to be able
3328 * to reuse old data.
Frédéric Lécaillebbf86be2023-02-20 09:28:58 +01003329 * For the momemt we do not care to leave data in the buffer for
3330 * a connection which is supposed to be killed asap.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003331 */
3332 BUG_ON_HOT(buf && b_data(buf));
3333
3334 if (!b_data(buf)) {
3335 b_free(buf);
3336 offer_buffers(NULL, 1);
3337 }
3338}
3339
3340/* Commit a datagram payload written into <buf> of length <length>. <first_pkt>
3341 * must contains the address of the first packet stored in the payload.
3342 *
3343 * Caller is responsible that there is enough space in the buffer.
3344 */
3345static void qc_txb_store(struct buffer *buf, uint16_t length,
3346 struct quic_tx_packet *first_pkt)
3347{
3348 const size_t hdlen = sizeof(uint16_t) + sizeof(void *);
3349 BUG_ON_HOT(b_contig_space(buf) < hdlen); /* this must not happen */
3350
3351 write_u16(b_tail(buf), length);
3352 write_ptr(b_tail(buf) + sizeof(length), first_pkt);
3353 b_add(buf, hdlen + length);
3354}
3355
3356/* Returns 1 if a packet may be built for <qc> from <qel> encryption level
3357 * with <frms> as ack-eliciting frame list to send, 0 if not.
3358 * <cc> must equal to 1 if an immediate close was asked, 0 if not.
3359 * <probe> must equalt to 1 if a probing packet is required, 0 if not.
3360 * <force_ack> may be set to 1 if you want to force an ack.
3361 */
3362static int qc_may_build_pkt(struct quic_conn *qc, struct list *frms,
3363 struct quic_enc_level *qel, int cc, int probe, int force_ack)
3364{
3365 unsigned int must_ack = force_ack ||
3366 (LIST_ISEMPTY(frms) && (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED));
3367
3368 /* Do not build any more packet if the TX secrets are not available or
3369 * if there is nothing to send, i.e. if no CONNECTION_CLOSE or ACK are required
3370 * and if there is no more packets to send upon PTO expiration
3371 * and if there is no more ack-eliciting frames to send or in flight
3372 * congestion control limit is reached for prepared data
3373 */
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02003374 if (!quic_tls_has_tx_sec(qel) ||
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003375 (!cc && !probe && !must_ack &&
3376 (LIST_ISEMPTY(frms) || qc->path->prep_in_flight >= qc->path->cwnd))) {
3377 return 0;
3378 }
3379
3380 return 1;
3381}
3382
3383/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3384 * <frms>. Each packet is stored in a distinct datagram written to <buf>.
3385 *
3386 * Each datagram is prepended by a two fields header : the datagram length and
3387 * the address of the packet contained in the datagram.
3388 *
3389 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3390 * -1 if something wrong happened.
3391 */
3392static int qc_prep_app_pkts(struct quic_conn *qc, struct buffer *buf,
3393 struct list *frms)
3394{
3395 int ret = -1;
3396 struct quic_enc_level *qel;
3397 unsigned char *end, *pos;
3398 struct quic_tx_packet *pkt;
3399 size_t total;
3400 /* Each datagram is prepended with its length followed by the address
3401 * of the first packet in the datagram.
3402 */
3403 const size_t dg_headlen = sizeof(uint16_t) + sizeof(pkt);
3404
3405 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3406
3407 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3408 total = 0;
3409 pos = (unsigned char *)b_tail(buf);
3410 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen) {
3411 int err, probe, cc;
3412
3413 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3414 probe = 0;
3415 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3416 /* We do not probe if an immediate close was asked */
3417 if (!cc)
3418 probe = qel->pktns->tx.pto_probe;
3419
3420 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, 0))
3421 break;
3422
3423 /* Leave room for the datagram header */
3424 pos += dg_headlen;
3425 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3426 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3427 }
3428 else {
3429 end = pos + qc->path->mtu;
3430 }
3431
3432 pkt = qc_build_pkt(&pos, end, qel, &qel->tls_ctx, frms, qc, NULL, 0,
3433 QUIC_PACKET_TYPE_SHORT, 0, 0, probe, cc, &err);
3434 switch (err) {
3435 case -2:
3436 // trace already emitted by function above
3437 goto leave;
3438 case -1:
3439 /* As we provide qc_build_pkt() with an enough big buffer to fulfill an
3440 * MTU, we are here because of the congestion control window. There is
3441 * no need to try to reuse this buffer.
3442 */
3443 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3444 goto out;
3445 default:
3446 break;
3447 }
3448
3449 /* This is to please to GCC. We cannot have (err >= 0 && !pkt) */
3450 BUG_ON(!pkt);
3451
3452 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3453 pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3454
3455 total += pkt->len;
3456
3457 /* Write datagram header. */
3458 qc_txb_store(buf, pkt->len, pkt);
3459 }
3460
3461 out:
3462 ret = total;
3463 leave:
3464 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3465 return ret;
3466}
3467
3468/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3469 * <frms>. Several packets can be regrouped in a single datagram. The result is
3470 * written into <buf>.
3471 *
3472 * Each datagram is prepended by a two fields header : the datagram length and
3473 * the address of first packet in the datagram.
3474 *
3475 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3476 * -1 if something wrong happened.
3477 */
3478static int qc_prep_pkts(struct quic_conn *qc, struct buffer *buf,
3479 enum quic_tls_enc_level tel, struct list *tel_frms,
3480 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
3481{
3482 struct quic_enc_level *qel;
3483 unsigned char *end, *pos;
3484 struct quic_tx_packet *first_pkt, *cur_pkt, *prv_pkt;
3485 /* length of datagrams */
3486 uint16_t dglen;
3487 size_t total;
3488 int ret = -1, padding;
3489 /* Each datagram is prepended with its length followed by the address
3490 * of the first packet in the datagram.
3491 */
3492 const size_t dg_headlen = sizeof(uint16_t) + sizeof(first_pkt);
3493 struct list *frms;
3494
3495 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3496
3497 /* Currently qc_prep_pkts() does not handle buffer wrapping so the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003498 * caller must ensure that buf is reset.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003499 */
3500 BUG_ON_HOT(buf->head || buf->data);
3501
3502 total = 0;
3503 qel = &qc->els[tel];
3504 frms = tel_frms;
3505 dglen = 0;
3506 padding = 0;
3507 pos = (unsigned char *)b_head(buf);
3508 first_pkt = prv_pkt = NULL;
3509 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen || prv_pkt) {
3510 int err, probe, cc;
3511 enum quic_pkt_type pkt_type;
3512 struct quic_tls_ctx *tls_ctx;
3513 const struct quic_version *ver;
3514 int force_ack = (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3515 (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
3516 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
3517
3518 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3519 probe = 0;
3520 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3521 /* We do not probe if an immediate close was asked */
3522 if (!cc)
3523 probe = qel->pktns->tx.pto_probe;
3524
3525 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, force_ack)) {
3526 if (prv_pkt)
3527 qc_txb_store(buf, dglen, first_pkt);
3528 /* Let's select the next encryption level */
3529 if (tel != next_tel && next_tel != QUIC_TLS_ENC_LEVEL_NONE) {
3530 tel = next_tel;
3531 frms = next_tel_frms;
3532 qel = &qc->els[tel];
3533 /* Build a new datagram */
3534 prv_pkt = NULL;
3535 TRACE_DEVEL("next encryption level selected", QUIC_EV_CONN_PHPKTS, qc);
3536 continue;
3537 }
3538 break;
3539 }
3540
3541 pkt_type = quic_tls_level_pkt_type(tel);
3542 if (!prv_pkt) {
3543 /* Leave room for the datagram header */
3544 pos += dg_headlen;
3545 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3546 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3547 }
3548 else {
3549 end = pos + qc->path->mtu;
3550 }
3551 }
3552
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003553 /* RFC 9000 14.1 Initial datagram size
3554 * a server MUST expand the payload of all UDP datagrams carrying ack-eliciting
3555 * Initial packets to at least the smallest allowed maximum datagram size of
3556 * 1200 bytes.
3557 *
3558 * Ensure that no ack-eliciting packets are sent into too small datagrams
3559 */
3560 if (pkt_type == QUIC_PACKET_TYPE_INITIAL && !LIST_ISEMPTY(tel_frms)) {
3561 if (end - pos < QUIC_INITIAL_PACKET_MINLEN) {
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01003562 TRACE_PROTO("No more enough room to build an Initial packet",
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003563 QUIC_EV_CONN_PHPKTS, qc);
3564 goto out;
3565 }
3566
3567 /* Pad this Initial packet if there is no ack-eliciting frames to send from
3568 * the next packet number space.
3569 */
Frédéric Lécailleec937212023-03-03 17:34:41 +01003570 if (!next_tel_frms || LIST_ISEMPTY(next_tel_frms))
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003571 padding = 1;
3572 }
3573
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003574 if (qc->negotiated_version) {
3575 ver = qc->negotiated_version;
3576 if (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL])
3577 tls_ctx = &qc->negotiated_ictx;
3578 else
3579 tls_ctx = &qel->tls_ctx;
3580 }
3581 else {
3582 ver = qc->original_version;
3583 tls_ctx = &qel->tls_ctx;
3584 }
3585
3586 cur_pkt = qc_build_pkt(&pos, end, qel, tls_ctx, frms,
3587 qc, ver, dglen, pkt_type,
3588 force_ack, padding, probe, cc, &err);
3589 switch (err) {
3590 case -2:
3591 // trace already emitted by function above
3592 goto leave;
3593 case -1:
3594 /* If there was already a correct packet present, set the
3595 * current datagram as prepared into <cbuf>.
3596 */
3597 if (prv_pkt)
3598 qc_txb_store(buf, dglen, first_pkt);
3599 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3600 goto out;
3601 default:
3602 break;
3603 }
3604
3605 /* This is to please to GCC. We cannot have (err >= 0 && !cur_pkt) */
3606 BUG_ON(!cur_pkt);
3607
3608 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3609 cur_pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3610
3611 total += cur_pkt->len;
3612 /* keep trace of the first packet in the datagram */
3613 if (!first_pkt)
3614 first_pkt = cur_pkt;
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01003615 /* Attach the current one to the previous one and vice versa */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003616 if (prv_pkt) {
3617 prv_pkt->next = cur_pkt;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01003618 cur_pkt->prev = prv_pkt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003619 cur_pkt->flags |= QUIC_FL_TX_PACKET_COALESCED;
3620 }
3621 /* Let's say we have to build a new dgram */
3622 prv_pkt = NULL;
3623 dglen += cur_pkt->len;
3624 /* Client: discard the Initial encryption keys as soon as
3625 * a handshake packet could be built.
3626 */
3627 if (qc->state == QUIC_HS_ST_CLIENT_INITIAL &&
3628 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
3629 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3630 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PHPKTS, qc);
3631 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
3632 qc_set_timer(qc);
3633 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3634 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3635 qc->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
3636 }
3637 /* If the data for the current encryption level have all been sent,
3638 * select the next level.
3639 */
3640 if ((tel == QUIC_TLS_ENC_LEVEL_INITIAL || tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE) &&
3641 next_tel != QUIC_TLS_ENC_LEVEL_NONE && (LIST_ISEMPTY(frms) && !qel->pktns->tx.pto_probe)) {
3642 /* If QUIC_TLS_ENC_LEVEL_HANDSHAKE was already reached let's try QUIC_TLS_ENC_LEVEL_APP */
3643 if (tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE && next_tel == tel)
3644 next_tel = QUIC_TLS_ENC_LEVEL_APP;
3645 tel = next_tel;
3646 if (tel == QUIC_TLS_ENC_LEVEL_APP)
3647 frms = &qc->els[tel].pktns->tx.frms;
3648 else
3649 frms = next_tel_frms;
3650 qel = &qc->els[tel];
3651 if (!LIST_ISEMPTY(frms)) {
3652 /* If there is data for the next level, do not
3653 * consume a datagram.
3654 */
3655 prv_pkt = cur_pkt;
3656 }
3657 }
3658
3659 /* If we have to build a new datagram, set the current datagram as
3660 * prepared into <cbuf>.
3661 */
3662 if (!prv_pkt) {
3663 qc_txb_store(buf, dglen, first_pkt);
3664 first_pkt = NULL;
3665 dglen = 0;
3666 padding = 0;
3667 }
3668 else if (prv_pkt->type == QUIC_TLS_ENC_LEVEL_INITIAL &&
3669 (!qc_is_listener(qc) ||
3670 prv_pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
3671 padding = 1;
3672 }
3673 }
3674
3675 out:
3676 ret = total;
3677 leave:
3678 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3679 return ret;
3680}
3681
3682/* Send datagrams stored in <buf>.
3683 *
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003684 * This function returns 1 for success. On error, there is several behavior
3685 * depending on underlying sendto() error :
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003686 * - for an unrecoverable error, 0 is returned and connection is killed.
3687 * - a transient error is handled differently if connection has its owned
3688 * socket. If this is the case, 0 is returned and socket is subscribed on the
3689 * poller. The other case is assimilated to a success case with 1 returned.
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003690 * Remaining data are purged from the buffer and will eventually be detected
3691 * as lost which gives the opportunity to retry sending.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003692 */
3693int qc_send_ppkts(struct buffer *buf, struct ssl_sock_ctx *ctx)
3694{
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003695 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003696 struct quic_conn *qc;
3697 char skip_sendto = 0;
3698
3699 qc = ctx->qc;
3700 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
3701 while (b_contig_data(buf, 0)) {
3702 unsigned char *pos;
3703 struct buffer tmpbuf = { };
3704 struct quic_tx_packet *first_pkt, *pkt, *next_pkt;
3705 uint16_t dglen;
3706 size_t headlen = sizeof dglen + sizeof first_pkt;
3707 unsigned int time_sent;
3708
3709 pos = (unsigned char *)b_head(buf);
3710 dglen = read_u16(pos);
3711 BUG_ON_HOT(!dglen); /* this should not happen */
3712
3713 pos += sizeof dglen;
3714 first_pkt = read_ptr(pos);
3715 pos += sizeof first_pkt;
3716 tmpbuf.area = (char *)pos;
3717 tmpbuf.size = tmpbuf.data = dglen;
3718
3719 TRACE_DATA("send dgram", QUIC_EV_CONN_SPPKTS, qc);
3720 /* If sendto is on error just skip the call to it for the rest
3721 * of the loop but continue to purge the buffer. Data will be
3722 * transmitted when QUIC packets are detected as lost on our
3723 * side.
3724 *
3725 * TODO use fd-monitoring to detect when send operation can be
3726 * retry. This should improve the bandwidth without relying on
3727 * retransmission timer. However, it requires a major rework on
3728 * quic-conn fd management.
3729 */
3730 if (!skip_sendto) {
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003731 int ret = qc_snd_buf(qc, &tmpbuf, tmpbuf.data, 0);
3732 if (ret < 0) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003733 TRACE_ERROR("sendto fatal error", QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003734 qc_kill_conn(qc);
3735 b_del(buf, buf->data);
3736 goto leave;
3737 }
3738 else if (!ret) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003739 /* Connection owned socket : poller will wake us up when transient error is cleared. */
3740 if (qc_test_fd(qc)) {
3741 TRACE_ERROR("sendto error, subscribe to poller", QUIC_EV_CONN_SPPKTS, qc);
3742 goto leave;
3743 }
3744
3745 /* No connection owned-socket : rely on retransmission to retry sending. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003746 skip_sendto = 1;
3747 TRACE_ERROR("sendto error, simulate sending for the rest of data", QUIC_EV_CONN_SPPKTS, qc);
3748 }
3749 }
3750
3751 b_del(buf, dglen + headlen);
3752 qc->tx.bytes += tmpbuf.data;
3753 time_sent = now_ms;
3754
3755 for (pkt = first_pkt; pkt; pkt = next_pkt) {
Frédéric Lécailleceb88b82023-02-20 14:43:55 +01003756 /* RFC 9000 14.1 Initial datagram size
3757 * a server MUST expand the payload of all UDP datagrams carrying ack-eliciting
3758 * Initial packets to at least the smallest allowed maximum datagram size of
3759 * 1200 bytes.
3760 */
3761 BUG_ON_HOT(pkt->type == QUIC_PACKET_TYPE_INITIAL &&
3762 (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) &&
3763 dglen < QUIC_INITIAL_PACKET_MINLEN);
3764
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003765 pkt->time_sent = time_sent;
3766 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
3767 pkt->pktns->tx.time_of_last_eliciting = time_sent;
3768 qc->path->ifae_pkts++;
3769 if (qc->flags & QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ)
3770 qc_idle_timer_rearm(qc, 0);
3771 }
3772 if (!(qc->flags & QUIC_FL_CONN_CLOSING) &&
3773 (pkt->flags & QUIC_FL_TX_PACKET_CC)) {
3774 qc->flags |= QUIC_FL_CONN_CLOSING;
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01003775 qc_detach_th_ctx_list(qc, 1);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003776 qc_notify_close(qc);
3777
3778 /* RFC 9000 10.2. Immediate Close:
3779 * The closing and draining connection states exist to ensure
3780 * that connections close cleanly and that delayed or reordered
3781 * packets are properly discarded. These states SHOULD persist
3782 * for at least three times the current PTO interval...
3783 *
3784 * Rearm the idle timeout only one time when entering closing
3785 * state.
3786 */
3787 qc_idle_timer_do_rearm(qc);
3788 if (qc->timer_task) {
3789 task_destroy(qc->timer_task);
3790 qc->timer_task = NULL;
3791 }
3792 }
3793 qc->path->in_flight += pkt->in_flight_len;
3794 pkt->pktns->tx.in_flight += pkt->in_flight_len;
3795 if (pkt->in_flight_len)
3796 qc_set_timer(qc);
3797 TRACE_DATA("sent pkt", QUIC_EV_CONN_SPPKTS, qc, pkt);
3798 next_pkt = pkt->next;
3799 quic_tx_packet_refinc(pkt);
3800 eb64_insert(&pkt->pktns->tx.pkts, &pkt->pn_node);
3801 }
3802 }
3803
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003804 ret = 1;
3805leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003806 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
3807
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003808 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003809}
3810
3811/* Copy into <buf> buffer a stateless reset token depending on the
3812 * <salt> salt input. This is the cluster secret which will be derived
3813 * as HKDF input secret to generate this token.
3814 * Return 1 if succeeded, 0 if not.
3815 */
3816static int quic_stateless_reset_token_cpy(struct quic_conn *qc,
3817 unsigned char *buf, size_t len,
3818 const unsigned char *salt, size_t saltlen)
3819{
3820 /* Input secret */
3821 const unsigned char *key = (const unsigned char *)global.cluster_secret;
3822 size_t keylen = strlen(global.cluster_secret);
3823 /* Info */
3824 const unsigned char label[] = "stateless token";
3825 size_t labellen = sizeof label - 1;
3826 int ret;
3827
3828 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3829
3830 ret = quic_hkdf_extract_and_expand(EVP_sha256(), buf, len,
3831 key, keylen, salt, saltlen, label, labellen);
3832 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3833 return ret;
3834}
3835
3836/* Initialize the stateless reset token attached to <cid> connection ID.
3837 * Returns 1 if succeeded, 0 if not.
3838 */
3839static int quic_stateless_reset_token_init(struct quic_conn *qc,
3840 struct quic_connection_id *quic_cid)
3841{
3842 int ret;
3843
3844 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3845
3846 if (global.cluster_secret) {
3847 /* Output secret */
3848 unsigned char *token = quic_cid->stateless_reset_token;
3849 size_t tokenlen = sizeof quic_cid->stateless_reset_token;
3850 /* Salt */
3851 const unsigned char *cid = quic_cid->cid.data;
3852 size_t cidlen = quic_cid->cid.len;
3853
3854 ret = quic_stateless_reset_token_cpy(qc, token, tokenlen, cid, cidlen);
3855 }
3856 else {
3857 /* TODO: RAND_bytes() should be replaced */
3858 ret = RAND_bytes(quic_cid->stateless_reset_token,
3859 sizeof quic_cid->stateless_reset_token) == 1;
3860 }
3861
3862 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3863 return ret;
3864}
3865
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003866/* Allocate a new CID and attach it to <root> ebtree.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003867 *
3868 * The CID is randomly generated in part with the result altered to be
3869 * associated with the current thread ID. This means this function must only
3870 * be called by the quic_conn thread.
3871 *
3872 * Returns the new CID if succeeded, NULL if not.
3873 */
3874static struct quic_connection_id *new_quic_cid(struct eb_root *root,
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003875 struct quic_conn *qc)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003876{
3877 struct quic_connection_id *cid;
3878
3879 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3880
3881 cid = pool_alloc(pool_head_quic_connection_id);
3882 if (!cid) {
3883 TRACE_ERROR("cid allocation failed", QUIC_EV_CONN_TXPKT, qc);
3884 goto err;
3885 }
3886
3887 cid->cid.len = QUIC_HAP_CID_LEN;
3888 /* TODO: RAND_bytes() should be replaced */
3889 if (RAND_bytes(cid->cid.data, cid->cid.len) != 1) {
3890 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT, qc);
3891 goto err;
3892 }
3893
3894 quic_pin_cid_to_tid(cid->cid.data, tid);
3895 if (quic_stateless_reset_token_init(qc, cid) != 1) {
3896 TRACE_ERROR("quic_stateless_reset_token_init() failed", QUIC_EV_CONN_TXPKT, qc);
3897 goto err;
3898 }
3899
3900 cid->qc = qc;
3901
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003902 cid->seq_num.key = qc->next_cid_seq_num++;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003903 cid->retire_prior_to = 0;
3904 /* insert the allocated CID in the quic_conn tree */
3905 eb64_insert(root, &cid->seq_num);
3906
3907 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3908 return cid;
3909
3910 err:
3911 pool_free(pool_head_quic_connection_id, cid);
3912 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3913 return NULL;
3914}
3915
3916/* Build all the frames which must be sent just after the handshake have succeeded.
3917 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
3918 * a HANDSHAKE_DONE frame.
3919 * Return 1 if succeeded, 0 if not.
3920 */
3921static int quic_build_post_handshake_frames(struct quic_conn *qc)
3922{
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003923 int ret = 0, max;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003924 struct quic_enc_level *qel;
3925 struct quic_frame *frm, *frmbak;
3926 struct list frm_list = LIST_HEAD_INIT(frm_list);
3927 struct eb64_node *node;
3928
3929 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
3930
3931 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3932 /* Only servers must send a HANDSHAKE_DONE frame. */
3933 if (qc_is_listener(qc)) {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003934 frm = qc_frm_alloc(QUIC_FT_HANDSHAKE_DONE);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003935 if (!frm) {
3936 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3937 goto leave;
3938 }
3939
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003940 LIST_APPEND(&frm_list, &frm->list);
3941 }
3942
3943 /* Initialize <max> connection IDs minus one: there is
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003944 * already one connection ID used for the current connection. Also limit
3945 * the number of connection IDs sent to the peer to 4 (3 from this function
3946 * plus 1 for the current connection.
3947 * Note that active_connection_id_limit >= 2: this has been already checked
3948 * when receiving this parameter.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003949 */
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003950 max = QUIC_MIN(qc->tx.params.active_connection_id_limit - 1, (uint64_t)3);
3951 while (max--) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003952 struct quic_connection_id *cid;
3953
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003954 frm = qc_frm_alloc(QUIC_FT_NEW_CONNECTION_ID);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003955 if (!frm) {
3956 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3957 goto err;
3958 }
3959
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003960 cid = new_quic_cid(&qc->cids, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003961 if (!cid) {
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003962 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003963 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3964 goto err;
3965 }
3966
3967 /* insert the allocated CID in the receiver datagram handler tree */
3968 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3969
3970 quic_connection_id_to_frm_cpy(frm, cid);
3971 LIST_APPEND(&frm_list, &frm->list);
3972 }
3973
3974 LIST_SPLICE(&qel->pktns->tx.frms, &frm_list);
3975 qc->flags |= QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT;
3976
3977 ret = 1;
3978 leave:
3979 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
3980 return ret;
3981
3982 err:
3983 /* free the frames */
3984 list_for_each_entry_safe(frm, frmbak, &frm_list, list)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003985 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003986
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003987 /* The first CID sequence number value used to allocated CIDs by this function is 1,
3988 * 0 being the sequence number of the CID for this connection.
3989 */
3990 node = eb64_lookup_ge(&qc->cids, 1);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003991 while (node) {
3992 struct quic_connection_id *cid;
3993
3994 cid = eb64_entry(node, struct quic_connection_id, seq_num);
3995 if (cid->seq_num.key >= max)
3996 break;
3997
3998 node = eb64_next(node);
3999 ebmb_delete(&cid->node);
4000 eb64_delete(&cid->seq_num);
4001 pool_free(pool_head_quic_connection_id, cid);
4002 }
4003 goto leave;
4004}
4005
4006/* Deallocate <l> list of ACK ranges. */
4007void quic_free_arngs(struct quic_conn *qc, struct quic_arngs *arngs)
4008{
4009 struct eb64_node *n;
4010 struct quic_arng_node *ar;
4011
4012 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4013
4014 n = eb64_first(&arngs->root);
4015 while (n) {
4016 struct eb64_node *next;
4017
4018 ar = eb64_entry(n, struct quic_arng_node, first);
4019 next = eb64_next(n);
4020 eb64_delete(n);
4021 pool_free(pool_head_quic_arng, ar);
4022 n = next;
4023 }
4024
4025 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4026}
4027
4028/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
4029 * descending order.
4030 */
4031static inline size_t sack_gap(struct quic_arng_node *p,
4032 struct quic_arng_node *q)
4033{
4034 return p->first.key - q->last - 2;
4035}
4036
4037
4038/* Remove the last elements of <ack_ranges> list of ack range updating its
4039 * encoded size until it goes below <limit>.
4040 * Returns 1 if succeeded, 0 if not (no more element to remove).
4041 */
4042static int quic_rm_last_ack_ranges(struct quic_conn *qc,
4043 struct quic_arngs *arngs, size_t limit)
4044{
4045 int ret = 0;
4046 struct eb64_node *last, *prev;
4047
4048 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4049
4050 last = eb64_last(&arngs->root);
4051 while (last && arngs->enc_sz > limit) {
4052 struct quic_arng_node *last_node, *prev_node;
4053
4054 prev = eb64_prev(last);
4055 if (!prev) {
4056 TRACE_DEVEL("<last> not found", QUIC_EV_CONN_TXPKT, qc);
4057 goto out;
4058 }
4059
4060 last_node = eb64_entry(last, struct quic_arng_node, first);
4061 prev_node = eb64_entry(prev, struct quic_arng_node, first);
4062 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
4063 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
4064 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
4065 --arngs->sz;
4066 eb64_delete(last);
4067 pool_free(pool_head_quic_arng, last);
4068 last = prev;
4069 }
4070
4071 ret = 1;
4072 out:
4073 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4074 return ret;
4075}
4076
4077/* Set the encoded size of <arngs> QUIC ack ranges. */
4078static void quic_arngs_set_enc_sz(struct quic_conn *qc, struct quic_arngs *arngs)
4079{
4080 struct eb64_node *node, *next;
4081 struct quic_arng_node *ar, *ar_next;
4082
4083 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4084
4085 node = eb64_last(&arngs->root);
4086 if (!node)
4087 goto leave;
4088
4089 ar = eb64_entry(node, struct quic_arng_node, first);
4090 arngs->enc_sz = quic_int_getsize(ar->last) +
4091 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
4092
4093 while ((next = eb64_prev(node))) {
4094 ar_next = eb64_entry(next, struct quic_arng_node, first);
4095 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
4096 quic_int_getsize(ar_next->last - ar_next->first.key);
4097 node = next;
4098 ar = eb64_entry(node, struct quic_arng_node, first);
4099 }
4100
4101 leave:
4102 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4103}
4104
4105/* Insert <ar> ack range into <argns> tree of ack ranges.
4106 * Returns the ack range node which has been inserted if succeeded, NULL if not.
4107 */
4108static inline
4109struct quic_arng_node *quic_insert_new_range(struct quic_conn *qc,
4110 struct quic_arngs *arngs,
4111 struct quic_arng *ar)
4112{
4113 struct quic_arng_node *new_ar;
4114
4115 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
4116
4117 new_ar = pool_alloc(pool_head_quic_arng);
4118 if (!new_ar) {
4119 TRACE_ERROR("ack range allocation failed", QUIC_EV_CONN_RXPKT, qc);
4120 goto leave;
4121 }
4122
4123 new_ar->first.key = ar->first;
4124 new_ar->last = ar->last;
4125 eb64_insert(&arngs->root, &new_ar->first);
4126 arngs->sz++;
4127
4128 leave:
4129 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
4130 return new_ar;
4131}
4132
4133/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
4134 * Note that this function computes the number of bytes required to encode
4135 * this tree of ACK ranges in descending order.
4136 *
4137 * Descending order
4138 * ------------->
4139 * range1 range2
4140 * ..........|--------|..............|--------|
4141 * ^ ^ ^ ^
4142 * | | | |
4143 * last1 first1 last2 first2
4144 * ..........+--------+--------------+--------+......
4145 * diff1 gap12 diff2
4146 *
4147 * To encode the previous list of ranges we must encode integers as follows in
4148 * descending order:
4149 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
4150 * with diff1 = last1 - first1
4151 * diff2 = last2 - first2
4152 * gap12 = first1 - last2 - 2 (>= 0)
4153 *
4154
4155returns 0 on error
4156
4157 */
4158int quic_update_ack_ranges_list(struct quic_conn *qc,
4159 struct quic_arngs *arngs,
4160 struct quic_arng *ar)
4161{
4162 int ret = 0;
4163 struct eb64_node *le;
4164 struct quic_arng_node *new_node;
4165 struct eb64_node *new;
4166
4167 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
4168
4169 new = NULL;
4170 if (eb_is_empty(&arngs->root)) {
4171 new_node = quic_insert_new_range(qc, arngs, ar);
4172 if (new_node)
4173 ret = 1;
4174
4175 goto leave;
4176 }
4177
4178 le = eb64_lookup_le(&arngs->root, ar->first);
4179 if (!le) {
4180 new_node = quic_insert_new_range(qc, arngs, ar);
4181 if (!new_node)
4182 goto leave;
4183
4184 new = &new_node->first;
4185 }
4186 else {
4187 struct quic_arng_node *le_ar =
4188 eb64_entry(le, struct quic_arng_node, first);
4189
4190 /* Already existing range */
4191 if (le_ar->last >= ar->last) {
4192 ret = 1;
4193 }
4194 else if (le_ar->last + 1 >= ar->first) {
4195 le_ar->last = ar->last;
4196 new = le;
4197 new_node = le_ar;
4198 }
4199 else {
4200 new_node = quic_insert_new_range(qc, arngs, ar);
4201 if (!new_node)
4202 goto leave;
4203
4204 new = &new_node->first;
4205 }
4206 }
4207
4208 /* Verify that the new inserted node does not overlap the nodes
4209 * which follow it.
4210 */
4211 if (new) {
4212 struct eb64_node *next;
4213 struct quic_arng_node *next_node;
4214
4215 while ((next = eb64_next(new))) {
4216 next_node =
4217 eb64_entry(next, struct quic_arng_node, first);
4218 if (new_node->last + 1 < next_node->first.key)
4219 break;
4220
4221 if (next_node->last > new_node->last)
4222 new_node->last = next_node->last;
4223 eb64_delete(next);
4224 pool_free(pool_head_quic_arng, next_node);
4225 /* Decrement the size of these ranges. */
4226 arngs->sz--;
4227 }
4228 }
4229
4230 ret = 1;
4231 leave:
4232 quic_arngs_set_enc_sz(qc, arngs);
4233 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
4234 return ret;
4235}
Frédéric Lécailleece86e62023-03-07 11:53:43 +01004236
4237/* Detect the value of the spin bit to be used. */
4238static inline void qc_handle_spin_bit(struct quic_conn *qc, struct quic_rx_packet *pkt,
4239 struct quic_enc_level *qel)
4240{
4241 uint64_t largest_pn = qel->pktns->rx.largest_pn;
4242
4243 if (qel != &qc->els[QUIC_TLS_ENC_LEVEL_APP] || largest_pn == -1 ||
4244 pkt->pn <= largest_pn)
4245 return;
4246
4247 if (qc_is_listener(qc)) {
4248 if (pkt->flags & QUIC_FL_RX_PACKET_SPIN_BIT)
4249 qc->flags |= QUIC_FL_CONN_SPIN_BIT;
4250 else
4251 qc->flags &= ~QUIC_FL_CONN_SPIN_BIT;
4252 }
4253 else {
4254 if (pkt->flags & QUIC_FL_RX_PACKET_SPIN_BIT)
4255 qc->flags &= ~QUIC_FL_CONN_SPIN_BIT;
4256 else
4257 qc->flags |= QUIC_FL_CONN_SPIN_BIT;
4258 }
4259}
4260
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004261/* Remove the header protection of packets at <el> encryption level.
4262 * Always succeeds.
4263 */
4264static inline void qc_rm_hp_pkts(struct quic_conn *qc, struct quic_enc_level *el)
4265{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004266 struct quic_rx_packet *pqpkt, *pkttmp;
4267 struct quic_enc_level *app_qel;
4268
4269 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, qc);
4270 app_qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4271 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
4272 if (el == app_qel && qc_is_listener(qc) && qc->state < QUIC_HS_ST_COMPLETE) {
4273 TRACE_DEVEL("hp not removed (handshake not completed)",
4274 QUIC_EV_CONN_ELRMHP, qc);
4275 goto out;
4276 }
Frédéric Lécaille72027782023-02-22 16:20:09 +01004277
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004278 list_for_each_entry_safe(pqpkt, pkttmp, &el->rx.pqpkts, list) {
Frédéric Lécaille72027782023-02-22 16:20:09 +01004279 struct quic_tls_ctx *tls_ctx;
4280
4281 tls_ctx = qc_select_tls_ctx(qc, el, pqpkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004282 if (!qc_do_rm_hp(qc, pqpkt, tls_ctx, el->pktns->rx.largest_pn,
4283 pqpkt->data + pqpkt->pn_offset, pqpkt->data)) {
4284 TRACE_ERROR("hp removing error", QUIC_EV_CONN_ELRMHP, qc);
4285 }
4286 else {
Frédéric Lécailleece86e62023-03-07 11:53:43 +01004287 qc_handle_spin_bit(qc, pqpkt, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004288 /* The AAD includes the packet number field */
4289 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
4290 /* Store the packet into the tree of packets to decrypt. */
4291 pqpkt->pn_node.key = pqpkt->pn;
4292 eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
4293 quic_rx_packet_refinc(pqpkt);
4294 TRACE_DEVEL("hp removed", QUIC_EV_CONN_ELRMHP, qc, pqpkt);
4295 }
4296 LIST_DELETE(&pqpkt->list);
4297 quic_rx_packet_refdec(pqpkt);
4298 }
4299
4300 out:
4301 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, qc);
4302}
4303
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004304/* Process all the CRYPTO frame at <el> encryption level. This is the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004305 * responsibility of the called to ensure there exists a CRYPTO data
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004306 * stream for this level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004307 * Return 1 if succeeded, 0 if not.
4308 */
4309static inline int qc_treat_rx_crypto_frms(struct quic_conn *qc,
4310 struct quic_enc_level *el,
4311 struct ssl_sock_ctx *ctx)
4312{
4313 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004314 struct ncbuf *ncbuf;
4315 struct quic_cstream *cstream = el->cstream;
4316 ncb_sz_t data;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004317
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004318 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004319
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004320 BUG_ON(!cstream);
4321 ncbuf = &cstream->rx.ncbuf;
4322 if (ncb_is_null(ncbuf))
4323 goto done;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004324
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004325 /* TODO not working if buffer is wrapping */
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004326 while ((data = ncb_data(ncbuf, 0))) {
4327 const unsigned char *cdata = (const unsigned char *)ncb_head(ncbuf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004328
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004329 if (!qc_provide_cdata(el, ctx, cdata, data, NULL, NULL))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004330 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004331
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004332 cstream->rx.offset += data;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004333 TRACE_DEVEL("buffered crypto data were provided to TLS stack",
4334 QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004335 }
4336
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004337 done:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004338 ret = 1;
4339 leave:
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004340 if (!ncb_is_null(ncbuf) && ncb_is_empty(ncbuf)) {
4341 TRACE_DEVEL("freeing crypto buf", QUIC_EV_CONN_PHPKTS, qc, el);
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004342 quic_free_ncbuf(ncbuf);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004343 }
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004344 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004345 return ret;
4346}
4347
4348/* Process all the packets at <el> and <next_el> encryption level.
4349 * This is the caller responsibility to check that <cur_el> is different of <next_el>
4350 * as pointer value.
4351 * Return 1 if succeeded, 0 if not.
4352 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004353int qc_treat_rx_pkts(struct quic_conn *qc, struct quic_enc_level *cur_el,
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004354 struct quic_enc_level *next_el)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004355{
4356 int ret = 0;
4357 struct eb64_node *node;
4358 int64_t largest_pn = -1;
4359 unsigned int largest_pn_time_received = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004360 struct quic_enc_level *qel = cur_el;
4361
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004362 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004363 qel = cur_el;
4364 next_tel:
4365 if (!qel)
4366 goto out;
4367
4368 node = eb64_first(&qel->rx.pkts);
4369 while (node) {
4370 struct quic_rx_packet *pkt;
4371
4372 pkt = eb64_entry(node, struct quic_rx_packet, pn_node);
4373 TRACE_DATA("new packet", QUIC_EV_CONN_RXPKT,
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004374 qc, pkt, NULL, qc->xprt_ctx->ssl);
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01004375 if (!qc_pkt_decrypt(qc, qel, pkt)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004376 /* Drop the packet */
4377 TRACE_ERROR("packet decryption failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004378 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004379 }
4380 else {
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004381 if (!qc_parse_pkt_frms(qc, pkt, qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004382 /* Drop the packet */
4383 TRACE_ERROR("packet parsing failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004384 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004385 HA_ATOMIC_INC(&qc->prx_counters->dropped_parsing);
4386 }
4387 else {
4388 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
4389
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004390 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004391 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
4392 qel->pktns->rx.nb_aepkts_since_last_ack++;
4393 qc_idle_timer_rearm(qc, 1);
4394 }
4395 if (pkt->pn > largest_pn) {
4396 largest_pn = pkt->pn;
4397 largest_pn_time_received = pkt->time_received;
4398 }
4399 /* Update the list of ranges to acknowledge. */
4400 if (!quic_update_ack_ranges_list(qc, &qel->pktns->rx.arngs, &ar))
4401 TRACE_ERROR("Could not update ack range list",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004402 QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004403 }
4404 }
4405 node = eb64_next(node);
4406 eb64_delete(&pkt->pn_node);
4407 quic_rx_packet_refdec(pkt);
4408 }
4409
4410 if (largest_pn != -1 && largest_pn > qel->pktns->rx.largest_pn) {
4411 /* Update the largest packet number. */
4412 qel->pktns->rx.largest_pn = largest_pn;
4413 /* Update the largest acknowledged packet timestamps */
4414 qel->pktns->rx.largest_time_received = largest_pn_time_received;
4415 qel->pktns->flags |= QUIC_FL_PKTNS_NEW_LARGEST_PN;
4416 }
4417
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004418 if (qel->cstream && !qc_treat_rx_crypto_frms(qc, qel, qc->xprt_ctx)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004419 // trace already emitted by function above
4420 goto leave;
4421 }
4422
4423 if (qel == cur_el) {
4424 BUG_ON(qel == next_el);
4425 qel = next_el;
4426 largest_pn = -1;
4427 goto next_tel;
4428 }
4429
4430 out:
4431 ret = 1;
4432 leave:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004433 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004434 return ret;
4435}
4436
4437/* Check if it's possible to remove header protection for packets related to
4438 * encryption level <qel>. If <qel> is NULL, assume it's false.
4439 *
4440 * Return true if the operation is possible else false.
4441 */
4442static int qc_qel_may_rm_hp(struct quic_conn *qc, struct quic_enc_level *qel)
4443{
4444 int ret = 0;
4445 enum quic_tls_enc_level tel;
4446
4447 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
4448
4449 if (!qel)
4450 goto cant_rm_hp;
4451
4452 tel = ssl_to_quic_enc_level(qel->level);
4453
4454 /* check if tls secrets are available */
4455 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
4456 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, qc);
4457 goto cant_rm_hp;
4458 }
4459
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004460 if (!quic_tls_has_rx_sec(qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004461 TRACE_DEVEL("non available secrets", QUIC_EV_CONN_TRMHP, qc);
4462 goto cant_rm_hp;
4463 }
4464
Frédéric Lécaille8417beb2023-02-01 10:31:35 +01004465 if (tel == QUIC_TLS_ENC_LEVEL_APP && qc->state < QUIC_HS_ST_COMPLETE) {
4466 TRACE_DEVEL("handshake not complete", QUIC_EV_CONN_TRMHP, qc);
4467 goto cant_rm_hp;
4468 }
4469
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004470 /* check if the connection layer is ready before using app level */
4471 if ((tel == QUIC_TLS_ENC_LEVEL_APP || tel == QUIC_TLS_ENC_LEVEL_EARLY_DATA) &&
4472 qc->mux_state == QC_MUX_NULL) {
4473 TRACE_DEVEL("connection layer not ready", QUIC_EV_CONN_TRMHP, qc);
4474 goto cant_rm_hp;
4475 }
4476
4477 ret = 1;
4478 cant_rm_hp:
4479 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc);
4480 return ret;
4481}
4482
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004483/* Flush txbuf for <qc> connection. This must be called prior to a packet
4484 * preparation when txbuf contains older data. A send will be conducted for
4485 * these data.
4486 *
4487 * Returns 1 on success : buffer is empty and can be use for packet
4488 * preparation. On error 0 is returned.
4489 */
4490static int qc_purge_txbuf(struct quic_conn *qc, struct buffer *buf)
4491{
4492 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4493
4494 /* This operation can only be conducted if txbuf is not empty. This
4495 * case only happens for connection with their owned socket due to an
4496 * older transient sendto() error.
4497 */
4498 BUG_ON(!qc_test_fd(qc));
4499
4500 if (b_data(buf) && !qc_send_ppkts(buf, qc->xprt_ctx)) {
4501 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4502 qc_txb_release(qc);
4503 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TXPKT, qc);
4504 return 0;
4505 }
4506
4507 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4508 return 1;
4509}
4510
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004511/* Try to send application frames from list <frms> on connection <qc>.
4512 *
4513 * Use qc_send_app_probing wrapper when probing with old data.
4514 *
4515 * Returns 1 on success. Some data might not have been sent due to congestion,
4516 * in this case they are left in <frms> input list. The caller may subscribe on
4517 * quic-conn to retry later.
4518 *
4519 * Returns 0 on critical error.
4520 * TODO review and classify more distinctly transient from definitive errors to
4521 * allow callers to properly handle it.
4522 */
4523static int qc_send_app_pkts(struct quic_conn *qc, struct list *frms)
4524{
4525 int status = 0;
4526 struct buffer *buf;
4527
4528 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4529
4530 buf = qc_txb_alloc(qc);
4531 if (!buf) {
4532 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004533 goto err;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004534 }
4535
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004536 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4537 goto err;
4538
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004539 /* Prepare and send packets until we could not further prepare packets. */
4540 while (1) {
4541 int ret;
4542 /* Currently buf cannot be non-empty at this stage. Even if a
4543 * previous sendto() has failed it is emptied to simulate
4544 * packet emission and rely on QUIC lost detection to try to
4545 * emit it.
4546 */
4547 BUG_ON_HOT(b_data(buf));
4548 b_reset(buf);
4549
4550 ret = qc_prep_app_pkts(qc, buf, frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004551 if (ret == -1) {
4552 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004553 goto err;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004554 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004555
Amaury Denoyelle37333862023-02-28 11:53:48 +01004556 if (!ret)
4557 break;
4558
4559 if (!qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004560 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4561 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004562 goto err;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004563 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004564 }
4565
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004566 status = 1;
4567 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004568 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4569 return status;
4570
4571 err:
Amaury Denoyelle37333862023-02-28 11:53:48 +01004572 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TXPKT, qc);
4573 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004574}
4575
4576/* Try to send application frames from list <frms> on connection <qc>. Use this
4577 * function when probing is required.
4578 *
4579 * Returns the result from qc_send_app_pkts function.
4580 */
4581static forceinline int qc_send_app_probing(struct quic_conn *qc,
4582 struct list *frms)
4583{
4584 int ret;
4585
4586 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4587
4588 TRACE_STATE("preparing old data (probing)", QUIC_EV_CONN_TXPKT, qc);
4589 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4590 ret = qc_send_app_pkts(qc, frms);
4591 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4592
4593 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4594 return ret;
4595}
4596
4597/* Try to send application frames from list <frms> on connection <qc>. This
4598 * function is provided for MUX upper layer usage only.
4599 *
4600 * Returns the result from qc_send_app_pkts function.
4601 */
4602int qc_send_mux(struct quic_conn *qc, struct list *frms)
4603{
4604 int ret;
4605
4606 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4607 BUG_ON(qc->mux_state != QC_MUX_READY); /* Only MUX can uses this function so it must be ready. */
4608
4609 TRACE_STATE("preparing data (from MUX)", QUIC_EV_CONN_TXPKT, qc);
4610 qc->flags |= QUIC_FL_CONN_TX_MUX_CONTEXT;
4611 ret = qc_send_app_pkts(qc, frms);
4612 qc->flags &= ~QUIC_FL_CONN_TX_MUX_CONTEXT;
4613
4614 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4615 return ret;
4616}
4617
4618/* Sends handshake packets from up to two encryption levels <tel> and <next_te>
4619 * with <tel_frms> and <next_tel_frms> as frame list respectively for <qc>
4620 * QUIC connection. <old_data> is used as boolean to send data already sent but
4621 * not already acknowledged (in flight).
4622 * Returns 1 if succeeded, 0 if not.
4623 */
4624int qc_send_hdshk_pkts(struct quic_conn *qc, int old_data,
4625 enum quic_tls_enc_level tel, struct list *tel_frms,
4626 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
4627{
4628 int ret, status = 0;
4629 struct buffer *buf = qc_txb_alloc(qc);
4630
4631 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4632
4633 if (!buf) {
4634 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4635 goto leave;
4636 }
4637
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004638 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4639 goto out;
4640
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004641 /* Currently buf cannot be non-empty at this stage. Even if a previous
4642 * sendto() has failed it is emptied to simulate packet emission and
4643 * rely on QUIC lost detection to try to emit it.
4644 */
4645 BUG_ON_HOT(b_data(buf));
4646 b_reset(buf);
4647
4648 if (old_data) {
4649 TRACE_STATE("old data for probing asked", QUIC_EV_CONN_TXPKT, qc);
4650 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4651 }
4652
4653 ret = qc_prep_pkts(qc, buf, tel, tel_frms, next_tel, next_tel_frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004654 if (ret == -1) {
4655 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004656 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004657 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004658
Amaury Denoyelle37333862023-02-28 11:53:48 +01004659 if (ret && !qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004660 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4661 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004662 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004663 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004664
Amaury Denoyelle37333862023-02-28 11:53:48 +01004665 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004666 status = 1;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004667
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004668 out:
4669 TRACE_STATE("no more need old data for probing", QUIC_EV_CONN_TXPKT, qc);
4670 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004671 leave:
4672 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4673 return status;
4674}
4675
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004676/* Retransmit up to two datagrams depending on packet number space.
4677 * Return 0 when failed, 0 if not.
4678 */
4679static int qc_dgrams_retransmit(struct quic_conn *qc)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004680{
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004681 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004682 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4683 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4684 struct quic_enc_level *aqel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4685
4686 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4687
4688 if (iqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004689 int i;
4690
4691 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
4692 struct list ifrms = LIST_HEAD_INIT(ifrms);
4693 struct list hfrms = LIST_HEAD_INIT(hfrms);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004694
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004695 qc_prep_hdshk_fast_retrans(qc, &ifrms, &hfrms);
4696 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &ifrms);
4697 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4698 if (!LIST_ISEMPTY(&ifrms)) {
4699 iqel->pktns->tx.pto_probe = 1;
4700 if (!LIST_ISEMPTY(&hfrms))
4701 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004702 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4703 QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms))
4704 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004705 /* Put back unsent frames in their packet number spaces */
4706 LIST_SPLICE(&iqel->pktns->tx.frms, &ifrms);
4707 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4708 }
Frédéric Lécailleec937212023-03-03 17:34:41 +01004709 else {
4710 if (!(qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
4711 iqel->pktns->tx.pto_probe = 1;
4712 if (!qc_send_hdshk_pkts(qc, 0, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4713 QUIC_TLS_ENC_LEVEL_NONE, NULL))
4714 goto leave;
4715 }
4716 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004717 }
4718 TRACE_STATE("no more need to probe Initial packet number space",
4719 QUIC_EV_CONN_TXPKT, qc);
4720 iqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004721 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004722 }
4723 else {
4724 int i;
4725
4726 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004727 hqel->pktns->tx.pto_probe = 0;
4728 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
Frédéric Lécaille7b5d9b12022-11-28 17:21:45 +01004729 struct list frms1 = LIST_HEAD_INIT(frms1);
4730
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004731 qc_prep_fast_retrans(qc, hqel, &frms1, NULL);
4732 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4733 if (!LIST_ISEMPTY(&frms1)) {
4734 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004735 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &frms1,
4736 QUIC_TLS_ENC_LEVEL_NONE, NULL))
4737 goto leave;
4738
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004739 /* Put back unsent frames into their packet number spaces */
4740 LIST_SPLICE(&hqel->pktns->tx.frms, &frms1);
4741 }
4742 }
4743 TRACE_STATE("no more need to probe Handshake packet number space",
4744 QUIC_EV_CONN_TXPKT, qc);
4745 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4746 }
4747 else if (aqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4748 struct list frms2 = LIST_HEAD_INIT(frms2);
4749 struct list frms1 = LIST_HEAD_INIT(frms1);
4750
4751 aqel->pktns->tx.pto_probe = 0;
4752 qc_prep_fast_retrans(qc, aqel, &frms1, &frms2);
4753 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4754 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms2);
4755 if (!LIST_ISEMPTY(&frms1)) {
4756 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004757 if (!qc_send_app_probing(qc, &frms1))
4758 goto leave;
4759
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004760 /* Put back unsent frames into their packet number spaces */
4761 LIST_SPLICE(&aqel->pktns->tx.frms, &frms1);
4762 }
4763 if (!LIST_ISEMPTY(&frms2)) {
4764 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004765 if (!qc_send_app_probing(qc, &frms2))
4766 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004767 /* Put back unsent frames into their packet number spaces */
4768 LIST_SPLICE(&aqel->pktns->tx.frms, &frms2);
4769 }
4770 TRACE_STATE("no more need to probe 01RTT packet number space",
4771 QUIC_EV_CONN_TXPKT, qc);
4772 aqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4773 }
4774 }
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004775
4776 ret = 1;
4777 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004778 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004779 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004780}
4781
4782/* QUIC connection packet handler task (post handshake) */
4783struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state)
4784{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004785 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004786 struct quic_enc_level *qel;
4787
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004788 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4789
4790 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
4791 TRACE_STATE("connection handshake state", QUIC_EV_CONN_IO_CB, qc, &qc->state);
4792
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004793 if (qc_test_fd(qc))
4794 qc_rcv_buf(qc);
4795
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004796 /* Retranmissions */
4797 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4798 TRACE_STATE("retransmission needed", QUIC_EV_CONN_IO_CB, qc);
4799 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004800 if (!qc_dgrams_retransmit(qc))
4801 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004802 }
4803
4804 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4805 qc_rm_hp_pkts(qc, qel);
4806
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004807 if (!qc_treat_rx_pkts(qc, qel, NULL)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004808 TRACE_DEVEL("qc_treat_rx_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4809 goto out;
4810 }
4811
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004812 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4813 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
4814 goto out;
4815 }
4816
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004817 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4818 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)) {
4819 TRACE_STATE("draining connection (must not send packets)", QUIC_EV_CONN_IO_CB, qc);
4820 goto out;
4821 }
4822
4823 /* XXX TODO: how to limit the list frames to send */
4824 if (!qc_send_app_pkts(qc, &qel->pktns->tx.frms)) {
4825 TRACE_DEVEL("qc_send_app_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4826 goto out;
4827 }
4828
4829 out:
4830 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
4831 return t;
4832}
4833
4834/* Returns a boolean if <qc> needs to emit frames for <qel> encryption level. */
4835static int qc_need_sending(struct quic_conn *qc, struct quic_enc_level *qel)
4836{
4837 return (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) ||
4838 (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) ||
4839 qel->pktns->tx.pto_probe ||
4840 !LIST_ISEMPTY(&qel->pktns->tx.frms);
4841}
4842
4843/* QUIC connection packet handler task. */
4844struct task *quic_conn_io_cb(struct task *t, void *context, unsigned int state)
4845{
4846 int ret, ssl_err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004847 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004848 enum quic_tls_enc_level tel, next_tel;
4849 struct quic_enc_level *qel, *next_qel;
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004850 /* Early-data encryption level */
4851 struct quic_enc_level *eqel;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004852 struct buffer *buf = NULL;
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004853 int st, zero_rtt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004854
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004855 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004856 eqel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004857 st = qc->state;
4858 TRACE_PROTO("connection state", QUIC_EV_CONN_IO_CB, qc, &st);
4859
4860 /* Retranmissions */
4861 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4862 TRACE_DEVEL("retransmission needed", QUIC_EV_CONN_PHPKTS, qc);
4863 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004864 if (!qc_dgrams_retransmit(qc))
4865 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004866 }
4867
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004868 ssl_err = SSL_ERROR_NONE;
4869 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004870 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004871 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004872
4873 if (qc_test_fd(qc))
4874 qc_rcv_buf(qc);
4875
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004876 if (st >= QUIC_HS_ST_COMPLETE &&
4877 qc_el_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
4878 TRACE_DEVEL("remaining Handshake packets", QUIC_EV_CONN_PHPKTS, qc);
4879 /* There may be remaining Handshake packets to treat and acknowledge. */
4880 tel = QUIC_TLS_ENC_LEVEL_HANDSHAKE;
4881 next_tel = QUIC_TLS_ENC_LEVEL_APP;
4882 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004883 else if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, zero_rtt))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004884 goto out;
4885
4886 qel = &qc->els[tel];
4887 next_qel = next_tel == QUIC_TLS_ENC_LEVEL_NONE ? NULL : &qc->els[next_tel];
4888
4889 next_level:
4890 /* Treat packets waiting for header packet protection decryption */
4891 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4892 qc_rm_hp_pkts(qc, qel);
4893
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004894 if (!qc_treat_rx_pkts(qc, qel, next_qel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004895 goto out;
4896
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004897 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4898 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_PHPKTS, qc);
4899 goto out;
4900 }
4901
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004902 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4903 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE))
4904 goto out;
4905
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004906 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004907 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004908 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
4909 if (next_qel && next_qel == eqel && zero_rtt) {
4910 TRACE_DEVEL("select 0RTT as next encryption level",
4911 QUIC_EV_CONN_PHPKTS, qc);
4912 qel = next_qel;
4913 next_qel = NULL;
4914 goto next_level;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004915 }
4916
4917 st = qc->state;
4918 if (st >= QUIC_HS_ST_COMPLETE) {
4919 if (!(qc->flags & QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT) &&
4920 !quic_build_post_handshake_frames(qc))
4921 goto out;
4922
4923 if (!(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].tls_ctx.flags &
4924 QUIC_FL_TLS_SECRETS_DCD)) {
4925 /* Discard the Handshake keys. */
4926 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4927 TRACE_PROTO("discarding Handshake pktns", QUIC_EV_CONN_PHPKTS, qc);
4928 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, qc);
4929 qc_set_timer(qc);
4930 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4931 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns);
4932 }
4933
4934 if (qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) {
4935 /* There may be remaining handshake to build (acks) */
4936 st = QUIC_HS_ST_SERVER_HANDSHAKE;
4937 }
4938 }
4939
4940 /* A listener does not send any O-RTT packet. O-RTT packet number space must not
4941 * be considered.
4942 */
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004943 if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, 0))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004944 goto out;
4945
4946 if (!qc_need_sending(qc, qel) &&
4947 (!next_qel || !qc_need_sending(qc, next_qel))) {
4948 goto skip_send;
4949 }
4950
4951 buf = qc_txb_alloc(qc);
4952 if (!buf)
4953 goto out;
4954
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004955 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4956 goto skip_send;
4957
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004958 /* Currently buf cannot be non-empty at this stage. Even if a previous
4959 * sendto() has failed it is emptied to simulate packet emission and
4960 * rely on QUIC lost detection to try to emit it.
4961 */
4962 BUG_ON_HOT(b_data(buf));
4963 b_reset(buf);
4964
4965 ret = qc_prep_pkts(qc, buf, tel, &qc->els[tel].pktns->tx.frms,
4966 next_tel, &qc->els[next_tel].pktns->tx.frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004967 if (ret == -1) {
4968 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004969 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004970 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004971
Amaury Denoyelle37333862023-02-28 11:53:48 +01004972 if (ret && !qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004973 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4974 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004975 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004976 }
4977
4978 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004979
4980 skip_send:
4981 /* Check if there is something to do for the next level.
4982 */
4983 if (next_qel && next_qel != qel &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004984 quic_tls_has_rx_sec(next_qel) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004985 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || qc_el_rx_pkts(next_qel))) {
4986 qel = next_qel;
4987 next_qel = NULL;
4988 goto next_level;
4989 }
4990
4991 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004992 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc, &st, &ssl_err);
4993 return t;
4994}
4995
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004996/* Release the memory allocated for <cs> CRYPTO stream */
4997void quic_cstream_free(struct quic_cstream *cs)
4998{
4999 if (!cs) {
5000 /* This is the case for ORTT encryption level */
5001 return;
5002 }
5003
Amaury Denoyellebc174b22022-11-17 10:12:52 +01005004 quic_free_ncbuf(&cs->rx.ncbuf);
5005
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02005006 qc_stream_desc_release(cs->desc);
5007 pool_free(pool_head_quic_cstream, cs);
5008}
5009
5010/* Allocate a new QUIC stream for <qc>.
5011 * Return it if succeeded, NULL if not.
5012 */
5013struct quic_cstream *quic_cstream_new(struct quic_conn *qc)
5014{
5015 struct quic_cstream *cs, *ret_cs = NULL;
5016
5017 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5018 cs = pool_alloc(pool_head_quic_cstream);
5019 if (!cs) {
5020 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
5021 goto leave;
5022 }
5023
5024 cs->rx.offset = 0;
5025 cs->rx.ncbuf = NCBUF_NULL;
5026 cs->rx.offset = 0;
5027
5028 cs->tx.offset = 0;
5029 cs->tx.sent_offset = 0;
5030 cs->tx.buf = BUF_NULL;
5031 cs->desc = qc_stream_desc_new((uint64_t)-1, -1, cs, qc);
5032 if (!cs->desc) {
5033 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
5034 goto err;
5035 }
5036
5037 ret_cs = cs;
5038 leave:
5039 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5040 return ret_cs;
5041
5042 err:
5043 pool_free(pool_head_quic_cstream, cs);
5044 goto leave;
5045}
5046
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005047/* Uninitialize <qel> QUIC encryption level. Never fails. */
5048static void quic_conn_enc_level_uninit(struct quic_conn *qc, struct quic_enc_level *qel)
5049{
5050 int i;
5051
5052 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5053
5054 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
5055 if (qel->tx.crypto.bufs[i]) {
5056 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
5057 qel->tx.crypto.bufs[i] = NULL;
5058 }
5059 }
5060 ha_free(&qel->tx.crypto.bufs);
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02005061 quic_cstream_free(qel->cstream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005062
5063 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5064}
5065
5066/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
5067 * connection allocating everything needed.
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005068 *
5069 * Returns 1 if succeeded, 0 if not. On error the caller is responsible to use
5070 * quic_conn_enc_level_uninit() to cleanup partially allocated content.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005071 */
5072static int quic_conn_enc_level_init(struct quic_conn *qc,
5073 enum quic_tls_enc_level level)
5074{
5075 int ret = 0;
5076 struct quic_enc_level *qel;
5077
5078 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5079
5080 qel = &qc->els[level];
5081 qel->level = quic_to_ssl_enc_level(level);
5082 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
5083 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
5084 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
5085 qel->tls_ctx.flags = 0;
5086
5087 qel->rx.pkts = EB_ROOT;
5088 LIST_INIT(&qel->rx.pqpkts);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005089
5090 /* Allocate only one buffer. */
5091 /* TODO: use a pool */
5092 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
5093 if (!qel->tx.crypto.bufs)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005094 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005095
5096 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
5097 if (!qel->tx.crypto.bufs[0])
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005098 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005099
5100 qel->tx.crypto.bufs[0]->sz = 0;
5101 qel->tx.crypto.nb_buf = 1;
5102
5103 qel->tx.crypto.sz = 0;
5104 qel->tx.crypto.offset = 0;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02005105 /* No CRYPTO data for early data TLS encryption level */
5106 if (level == QUIC_TLS_ENC_LEVEL_EARLY_DATA)
5107 qel->cstream = NULL;
5108 else {
5109 qel->cstream = quic_cstream_new(qc);
5110 if (!qel->cstream)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005111 goto leave;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02005112 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005113
5114 ret = 1;
5115 leave:
5116 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5117 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005118}
5119
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005120/* Return 1 if <qc> connection may probe the Initial packet number space, 0 if not.
5121 * This is not the case if the remote peer address is not validated and if
5122 * it cannot send at least QUIC_INITIAL_PACKET_MINLEN bytes.
5123 */
5124static int qc_may_probe_ipktns(struct quic_conn *qc)
5125{
5126 return quic_peer_validated_addr(qc) ||
5127 (int)(3 * qc->rx.bytes - qc->tx.prep_bytes) >= QUIC_INITIAL_PACKET_MINLEN;
5128}
5129
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005130/* Callback called upon loss detection and PTO timer expirations. */
5131struct task *qc_process_timer(struct task *task, void *ctx, unsigned int state)
5132{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005133 struct quic_conn *qc = ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005134 struct quic_pktns *pktns;
5135
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005136 TRACE_ENTER(QUIC_EV_CONN_PTIMER, qc,
5137 NULL, NULL, &qc->path->ifae_pkts);
5138 task->expire = TICK_ETERNITY;
5139 pktns = quic_loss_pktns(qc);
5140 if (tick_isset(pktns->tx.loss_time)) {
5141 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
5142
5143 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
5144 if (!LIST_ISEMPTY(&lost_pkts))
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005145 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01005146 if (qc_release_lost_pkts(qc, pktns, &lost_pkts, now_ms))
5147 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005148 goto out;
5149 }
5150
5151 if (qc->path->in_flight) {
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +01005152 pktns = quic_pto_pktns(qc, qc->state >= QUIC_HS_ST_CONFIRMED, NULL);
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01005153 if (!qc_notify_send(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005154 if (pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL]) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005155 if (qc_may_probe_ipktns(qc)) {
5156 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5157 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
5158 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5159 }
5160 else {
5161 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5162 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005163 if (qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].tx.in_flight) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005164 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005165 qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
5166 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
5167 }
5168 }
5169 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE]) {
5170 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005171 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5172 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01005173 if (qc->pktns[QUIC_TLS_PKTNS_INITIAL].tx.in_flight) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005174 if (qc_may_probe_ipktns(qc)) {
5175 qc->pktns[QUIC_TLS_PKTNS_INITIAL].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
5176 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5177 }
5178 else {
5179 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5180 }
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01005181 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005182 }
5183 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT]) {
5184 TRACE_STATE("needs to probe 01RTT packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005185 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5186 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005187 }
5188 }
5189 }
5190 else if (!qc_is_listener(qc) && qc->state <= QUIC_HS_ST_COMPLETE) {
5191 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
5192 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
5193
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02005194 if (quic_tls_has_tx_sec(hel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005195 hel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02005196 if (quic_tls_has_tx_sec(iel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005197 iel->pktns->tx.pto_probe = 1;
5198 }
5199
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005200 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005201 qc->path->loss.pto_count++;
5202
5203 out:
5204 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, qc, pktns);
5205
5206 return task;
5207}
5208
5209/* Parse the Retry token from buffer <token> with <end> a pointer to
5210 * one byte past the end of this buffer. This will extract the ODCID
5211 * which will be stored into <odcid>
5212 *
5213 * Returns 0 on success else non-zero.
5214 */
5215static int parse_retry_token(struct quic_conn *qc,
5216 const unsigned char *token, const unsigned char *end,
5217 struct quic_cid *odcid)
5218{
5219 int ret = 0;
5220 uint64_t odcid_len;
5221 uint32_t timestamp;
5222
5223 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5224
5225 if (!quic_dec_int(&odcid_len, &token, end)) {
5226 TRACE_ERROR("quic_dec_int() error", QUIC_EV_CONN_LPKT, qc);
5227 goto leave;
5228 }
5229
5230 /* RFC 9000 7.2. Negotiating Connection IDs:
5231 * When an Initial packet is sent by a client that has not previously
5232 * received an Initial or Retry packet from the server, the client
5233 * populates the Destination Connection ID field with an unpredictable
5234 * value. This Destination Connection ID MUST be at least 8 bytes in length.
5235 */
5236 if (odcid_len < QUIC_ODCID_MINLEN || odcid_len > QUIC_CID_MAXLEN) {
5237 TRACE_ERROR("wrong ODCID length", QUIC_EV_CONN_LPKT, qc);
5238 goto leave;
5239 }
5240
5241 if (end - token < odcid_len + sizeof timestamp) {
5242 TRACE_ERROR("too long ODCID length", QUIC_EV_CONN_LPKT, qc);
5243 goto leave;
5244 }
5245
5246 timestamp = ntohl(read_u32(token + odcid_len));
5247 if (timestamp + MS_TO_TICKS(QUIC_RETRY_DURATION_MS) <= now_ms) {
5248 TRACE_ERROR("token has expired", QUIC_EV_CONN_LPKT, qc);
5249 goto leave;
5250 }
5251
5252 ret = 1;
5253 memcpy(odcid->data, token, odcid_len);
5254 odcid->len = odcid_len;
5255 leave:
5256 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5257 return !ret;
5258}
5259
5260/* Allocate a new QUIC connection with <version> as QUIC version. <ipv4>
5261 * boolean is set to 1 for IPv4 connection, 0 for IPv6. <server> is set to 1
5262 * for QUIC servers (or haproxy listeners).
5263 * <dcid> is the destination connection ID, <scid> is the source connection ID,
5264 * <token> the token found to be used for this connection with <token_len> as
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005265 * length. Endpoints addresses are specified via <local_addr> and <peer_addr>.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005266 * Returns the connection if succeeded, NULL if not.
5267 */
5268static struct quic_conn *qc_new_conn(const struct quic_version *qv, int ipv4,
5269 struct quic_cid *dcid, struct quic_cid *scid,
5270 const struct quic_cid *token_odcid,
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005271 struct sockaddr_storage *local_addr,
5272 struct sockaddr_storage *peer_addr,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005273 int server, int token, void *owner)
5274{
5275 int i;
5276 struct quic_conn *qc;
5277 /* Initial CID. */
5278 struct quic_connection_id *icid;
5279 char *buf_area = NULL;
5280 struct listener *l = NULL;
5281 struct quic_cc_algo *cc_algo = NULL;
5282 struct quic_tls_ctx *ictx;
5283 TRACE_ENTER(QUIC_EV_CONN_INIT);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005284 /* TODO replace pool_zalloc by pool_alloc(). This requires special care
5285 * to properly initialized internal quic_conn members to safely use
5286 * quic_conn_release() on alloc failure.
5287 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005288 qc = pool_zalloc(pool_head_quic_conn);
5289 if (!qc) {
5290 TRACE_ERROR("Could not allocate a new connection", QUIC_EV_CONN_INIT);
5291 goto err;
5292 }
5293
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005294 /* Initialize in priority qc members required for a safe dealloc. */
5295
5296 /* required to use MTLIST_IN_LIST */
5297 MT_LIST_INIT(&qc->accept_list);
5298
5299 LIST_INIT(&qc->rx.pkt_list);
5300
Amaury Denoyelle42448332022-12-12 11:24:05 +01005301 qc_init_fd(qc);
5302
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005303 LIST_INIT(&qc->back_refs);
5304
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005305 /* Now proceeds to allocation of qc members. */
5306
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005307 buf_area = pool_alloc(pool_head_quic_conn_rxbuf);
5308 if (!buf_area) {
5309 TRACE_ERROR("Could not allocate a new RX buffer", QUIC_EV_CONN_INIT, qc);
5310 goto err;
5311 }
5312
5313 qc->cids = EB_ROOT;
5314 /* QUIC Server (or listener). */
5315 if (server) {
5316 struct proxy *prx;
5317
5318 l = owner;
5319 prx = l->bind_conf->frontend;
5320 cc_algo = l->bind_conf->quic_cc_algo;
5321
5322 qc->prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe,
5323 &quic_stats_module);
5324 qc->flags |= QUIC_FL_CONN_LISTENER;
5325 qc->state = QUIC_HS_ST_SERVER_INITIAL;
5326 /* Copy the initial DCID with the address. */
5327 qc->odcid.len = dcid->len;
5328 qc->odcid.addrlen = dcid->addrlen;
5329 memcpy(qc->odcid.data, dcid->data, dcid->len + dcid->addrlen);
5330
5331 /* copy the packet SCID to reuse it as DCID for sending */
5332 if (scid->len)
5333 memcpy(qc->dcid.data, scid->data, scid->len);
5334 qc->dcid.len = scid->len;
5335 qc->tx.buf = BUF_NULL;
5336 qc->li = l;
5337 }
5338 /* QUIC Client (outgoing connection to servers) */
5339 else {
5340 qc->state = QUIC_HS_ST_CLIENT_INITIAL;
5341 if (dcid->len)
5342 memcpy(qc->dcid.data, dcid->data, dcid->len);
5343 qc->dcid.len = dcid->len;
5344 }
5345 qc->mux_state = QC_MUX_NULL;
5346 qc->err = quic_err_transport(QC_ERR_NO_ERROR);
5347
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01005348 /* Initialize the next CID sequence number to be used for this connection. */
5349 qc->next_cid_seq_num = 0;
5350 /* Insert the CID for this connection with 0 as sequence number. */
5351 icid = new_quic_cid(&qc->cids, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005352 if (!icid) {
5353 TRACE_ERROR("Could not allocate a new connection ID", QUIC_EV_CONN_INIT, qc);
5354 goto err;
5355 }
5356
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005357 if ((global.tune.options & GTUNE_QUIC_SOCK_PER_CONN) &&
5358 is_addr(local_addr)) {
5359 TRACE_USER("Allocate a socket for QUIC connection", QUIC_EV_CONN_INIT, qc);
5360 qc_alloc_fd(qc, local_addr, peer_addr);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005361
5362 /* haproxy soft-stop is supported only for QUIC connections
5363 * with their owned socket.
5364 */
5365 if (qc_test_fd(qc))
5366 _HA_ATOMIC_INC(&jobs);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005367 }
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005368
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005369 /* insert the allocated CID in the receiver datagram handler tree */
5370 if (server)
5371 ebmb_insert(&quic_dghdlrs[tid].cids, &icid->node, icid->cid.len);
5372
5373 /* Select our SCID which is the first CID with 0 as sequence number. */
5374 qc->scid = icid->cid;
5375
5376 /* Packet number spaces initialization. */
5377 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
5378 quic_pktns_init(&qc->pktns[i]);
5379 /* QUIC encryption level context initialization. */
5380 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5381 if (!quic_conn_enc_level_init(qc, i)) {
5382 TRACE_ERROR("Could not initialize an encryption level", QUIC_EV_CONN_INIT, qc);
5383 goto err;
5384 }
5385 /* Initialize the packet number space. */
5386 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
5387 }
5388
5389 qc->original_version = qv;
5390 qc->tps_tls_ext = (qc->original_version->num & 0xff000000) == 0xff000000 ?
5391 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS_DRAFT:
5392 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS;
5393 /* TX part. */
5394 LIST_INIT(&qc->tx.frms_to_send);
5395 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
5396 qc->tx.wbuf = qc->tx.rbuf = 0;
5397 qc->tx.bytes = 0;
5398 qc->tx.buf = BUF_NULL;
5399 /* RX part. */
5400 qc->rx.bytes = 0;
5401 qc->rx.buf = b_make(buf_area, QUIC_CONN_RX_BUFSZ, 0, 0);
5402 for (i = 0; i < QCS_MAX_TYPES; i++)
5403 qc->rx.strms[i].nb_streams = 0;
5404
5405 qc->nb_pkt_for_cc = 1;
5406 qc->nb_pkt_since_cc = 0;
5407
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005408 if (!quic_tls_ku_init(qc)) {
5409 TRACE_ERROR("Key update initialization failed", QUIC_EV_CONN_INIT, qc);
5410 goto err;
5411 }
5412
5413 /* XXX TO DO: Only one path at this time. */
5414 qc->path = &qc->paths[0];
5415 quic_path_init(qc->path, ipv4, cc_algo ? cc_algo : default_quic_cc_algo, qc);
5416
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005417 qc->streams_by_id = EB_ROOT_UNIQUE;
5418 qc->stream_buf_count = 0;
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005419 memcpy(&qc->local_addr, local_addr, sizeof(qc->local_addr));
5420 memcpy(&qc->peer_addr, peer_addr, sizeof qc->peer_addr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005421
5422 if (server && !qc_lstnr_params_init(qc, &l->bind_conf->quic_params,
5423 icid->stateless_reset_token,
5424 dcid->data, dcid->len,
5425 qc->scid.data, qc->scid.len, token_odcid))
5426 goto err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005427
5428 qc->wait_event.tasklet = tasklet_new();
5429 if (!qc->wait_event.tasklet) {
5430 TRACE_ERROR("tasklet_new() failed", QUIC_EV_CONN_TXPKT);
5431 goto err;
5432 }
5433 qc->wait_event.tasklet->process = quic_conn_io_cb;
5434 qc->wait_event.tasklet->context = qc;
5435 qc->wait_event.events = 0;
5436 /* Set tasklet tid based on the SCID selected by us for this
5437 * connection. The upper layer will also be binded on the same thread.
5438 */
Willy Tarreaueed78262022-12-21 09:09:19 +01005439 qc->tid = quic_get_cid_tid(qc->scid.data, &l->rx);
Willy Tarreauf5a0c8a2022-10-13 16:14:11 +02005440 qc->wait_event.tasklet->tid = qc->tid;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02005441 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005442
5443 if (qc_conn_alloc_ssl_ctx(qc) ||
5444 !quic_conn_init_timer(qc) ||
5445 !quic_conn_init_idle_timer_task(qc))
5446 goto err;
5447
5448 ictx = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
5449 if (!qc_new_isecs(qc, ictx,qc->original_version, dcid->data, dcid->len, 1))
5450 goto err;
5451
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005452 LIST_APPEND(&th_ctx->quic_conns, &qc->el_th_ctx);
5453 qc->qc_epoch = HA_ATOMIC_LOAD(&qc_epoch);
5454
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005455 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc);
5456
5457 return qc;
5458
5459 err:
5460 pool_free(pool_head_quic_conn_rxbuf, buf_area);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005461 if (qc) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005462 qc->rx.buf.area = NULL;
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005463 quic_conn_release(qc);
5464 }
5465 TRACE_LEAVE(QUIC_EV_CONN_INIT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005466 return NULL;
5467}
5468
5469/* Release the quic_conn <qc>. The connection is removed from the CIDs tree.
5470 * The connection tasklet is killed.
5471 *
5472 * This function must only be called by the thread responsible of the quic_conn
5473 * tasklet.
5474 */
5475void quic_conn_release(struct quic_conn *qc)
5476{
5477 int i;
5478 struct ssl_sock_ctx *conn_ctx;
5479 struct eb64_node *node;
5480 struct quic_tls_ctx *app_tls_ctx;
5481 struct quic_rx_packet *pkt, *pktback;
5482
5483 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5484
5485 /* We must not free the quic-conn if the MUX is still allocated. */
5486 BUG_ON(qc->mux_state == QC_MUX_READY);
5487
Amaury Denoyellefb375572023-02-01 09:28:32 +01005488 if (qc_test_fd(qc))
5489 _HA_ATOMIC_DEC(&jobs);
5490
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005491 /* Close quic-conn socket fd. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01005492 qc_release_fd(qc, 0);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005493
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005494 /* in the unlikely (but possible) case the connection was just added to
5495 * the accept_list we must delete it from there.
5496 */
5497 MT_LIST_DELETE(&qc->accept_list);
5498
5499 /* free remaining stream descriptors */
5500 node = eb64_first(&qc->streams_by_id);
5501 while (node) {
5502 struct qc_stream_desc *stream;
5503
5504 stream = eb64_entry(node, struct qc_stream_desc, by_id);
5505 node = eb64_next(node);
5506
5507 /* all streams attached to the quic-conn are released, so
5508 * qc_stream_desc_free will liberate the stream instance.
5509 */
5510 BUG_ON(!stream->release);
5511 qc_stream_desc_free(stream, 1);
5512 }
5513
5514 /* Purge Rx packet list. */
5515 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
5516 LIST_DELETE(&pkt->qc_rx_pkt_list);
5517 pool_free(pool_head_quic_rx_packet, pkt);
5518 }
5519
5520 if (qc->idle_timer_task) {
5521 task_destroy(qc->idle_timer_task);
5522 qc->idle_timer_task = NULL;
5523 }
5524
5525 if (qc->timer_task) {
5526 task_destroy(qc->timer_task);
5527 qc->timer_task = NULL;
5528 }
5529
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005530 if (qc->wait_event.tasklet)
5531 tasklet_free(qc->wait_event.tasklet);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005532
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005533 /* remove the connection from receiver cids trees */
5534 ebmb_delete(&qc->odcid_node);
5535 ebmb_delete(&qc->scid_node);
5536 free_quic_conn_cids(qc);
5537
5538 conn_ctx = qc->xprt_ctx;
5539 if (conn_ctx) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005540 SSL_free(conn_ctx->ssl);
5541 pool_free(pool_head_quic_conn_ctx, conn_ctx);
5542 }
5543
5544 quic_tls_ku_free(qc);
5545 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5546 quic_tls_ctx_secs_free(&qc->els[i].tls_ctx);
5547 quic_conn_enc_level_uninit(qc, &qc->els[i]);
5548 }
5549 quic_tls_ctx_secs_free(&qc->negotiated_ictx);
5550
5551 app_tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
5552 pool_free(pool_head_quic_tls_secret, app_tls_ctx->rx.secret);
5553 pool_free(pool_head_quic_tls_secret, app_tls_ctx->tx.secret);
5554
5555 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++) {
5556 quic_pktns_tx_pkts_release(&qc->pktns[i], qc);
5557 quic_free_arngs(qc, &qc->pktns[i].rx.arngs);
5558 }
5559
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01005560 qc_detach_th_ctx_list(qc, 0);
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005561
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005562 pool_free(pool_head_quic_conn_rxbuf, qc->rx.buf.area);
5563 pool_free(pool_head_quic_conn, qc);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005564
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005565 TRACE_PROTO("QUIC conn. freed", QUIC_EV_CONN_FREED, qc);
5566
5567 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5568}
5569
5570/* Initialize the timer task of <qc> QUIC connection.
5571 * Returns 1 if succeeded, 0 if not.
5572 */
5573static int quic_conn_init_timer(struct quic_conn *qc)
5574{
5575 int ret = 0;
5576 /* Attach this task to the same thread ID used for the connection */
5577 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5578
5579 qc->timer_task = task_new_on(qc->tid);
5580 if (!qc->timer_task) {
5581 TRACE_ERROR("timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5582 goto leave;
5583 }
5584
5585 qc->timer = TICK_ETERNITY;
5586 qc->timer_task->process = qc_process_timer;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005587 qc->timer_task->context = qc;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005588
5589 ret = 1;
5590 leave:
5591 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5592 return ret;
5593}
5594
5595/* Rearm the idle timer for <qc> QUIC connection. */
5596static void qc_idle_timer_do_rearm(struct quic_conn *qc)
5597{
5598 unsigned int expire;
5599
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01005600 if (stopping && qc->flags & (QUIC_FL_CONN_CLOSING|QUIC_FL_CONN_DRAINING)) {
5601 TRACE_STATE("executing idle timer immediately on stopping", QUIC_EV_CONN_IDLE_TIMER, qc);
5602 task_wakeup(qc->idle_timer_task, TASK_WOKEN_MSG);
5603 }
5604 else {
5605 expire = QUIC_MAX(3 * quic_pto(qc), qc->max_idle_timeout);
5606 qc->idle_timer_task->expire = tick_add(now_ms, MS_TO_TICKS(expire));
5607 task_queue(qc->idle_timer_task);
5608 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005609}
5610
5611/* Rearm the idle timer for <qc> QUIC connection depending on <read> boolean
5612 * which is set to 1 when receiving a packet , and 0 when sending packet
5613 */
5614static void qc_idle_timer_rearm(struct quic_conn *qc, int read)
5615{
5616 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5617
5618 if (read) {
5619 qc->flags |= QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5620 }
5621 else {
5622 qc->flags &= ~QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5623 }
5624 qc_idle_timer_do_rearm(qc);
5625
5626 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5627}
5628
5629/* The task handling the idle timeout */
5630struct task *qc_idle_timer_task(struct task *t, void *ctx, unsigned int state)
5631{
5632 struct quic_conn *qc = ctx;
5633 struct quic_counters *prx_counters = qc->prx_counters;
5634 unsigned int qc_flags = qc->flags;
5635
5636 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5637
5638 /* Notify the MUX before settings QUIC_FL_CONN_EXP_TIMER or the MUX
5639 * might free the quic-conn too early via quic_close().
5640 */
5641 qc_notify_close(qc);
5642
5643 /* If the MUX is still alive, keep the quic-conn. The MUX is
5644 * responsible to call quic_close to release it.
5645 */
5646 qc->flags |= QUIC_FL_CONN_EXP_TIMER;
5647 if (qc->mux_state != QC_MUX_READY)
5648 quic_conn_release(qc);
5649
5650 /* TODO if the quic-conn cannot be freed because of the MUX, we may at
5651 * least clean some parts of it such as the tasklet.
5652 */
5653
5654 if (!(qc_flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
5655 qc_flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
5656 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
5657 HA_ATOMIC_DEC(&prx_counters->half_open_conn);
5658 }
5659
5660 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5661 return NULL;
5662}
5663
5664/* Initialize the idle timeout task for <qc>.
5665 * Returns 1 if succeeded, 0 if not.
5666 */
5667static int quic_conn_init_idle_timer_task(struct quic_conn *qc)
5668{
5669 int ret = 0;
5670
5671 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5672
5673 qc->idle_timer_task = task_new_here();
5674 if (!qc->idle_timer_task) {
5675 TRACE_ERROR("Idle timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5676 goto leave;
5677 }
5678
5679 qc->idle_timer_task->process = qc_idle_timer_task;
5680 qc->idle_timer_task->context = qc;
5681 qc_idle_timer_rearm(qc, 1);
5682 task_queue(qc->idle_timer_task);
5683
5684 ret = 1;
5685 leave:
5686 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5687 return ret;
5688}
5689
5690/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
5691 * past one byte of this buffer.
5692 */
5693static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
5694 struct quic_rx_packet *pkt)
5695{
5696 int ret = 0;
5697 unsigned char dcid_len, scid_len;
5698
5699 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5700
5701 if (end == *buf) {
5702 TRACE_ERROR("buffer data consumed", QUIC_EV_CONN_RXPKT);
5703 goto leave;
5704 }
5705
5706 /* Destination Connection ID Length */
5707 dcid_len = *(*buf)++;
5708 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
5709 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1) {
5710 TRACE_ERROR("too long DCID", QUIC_EV_CONN_RXPKT);
5711 goto leave;
5712 }
5713
5714 if (dcid_len) {
5715 /* Check that the length of this received DCID matches the CID lengths
5716 * of our implementation for non Initials packets only.
5717 */
5718 if (pkt->type != QUIC_PACKET_TYPE_INITIAL &&
5719 pkt->type != QUIC_PACKET_TYPE_0RTT &&
5720 dcid_len != QUIC_HAP_CID_LEN) {
5721 TRACE_ERROR("wrong DCID length", QUIC_EV_CONN_RXPKT);
5722 goto leave;
5723 }
5724
5725 memcpy(pkt->dcid.data, *buf, dcid_len);
5726 }
5727
5728 pkt->dcid.len = dcid_len;
5729 *buf += dcid_len;
5730
5731 /* Source Connection ID Length */
5732 scid_len = *(*buf)++;
5733 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len) {
5734 TRACE_ERROR("too long SCID", QUIC_EV_CONN_RXPKT);
5735 goto leave;
5736 }
5737
5738 if (scid_len)
5739 memcpy(pkt->scid.data, *buf, scid_len);
5740 pkt->scid.len = scid_len;
5741 *buf += scid_len;
5742
5743 ret = 1;
5744 leave:
5745 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5746 return ret;
5747}
5748
5749/* Insert <pkt> RX packet in its <qel> RX packets tree */
5750static void qc_pkt_insert(struct quic_conn *qc,
5751 struct quic_rx_packet *pkt, struct quic_enc_level *qel)
5752{
5753 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
5754
5755 pkt->pn_node.key = pkt->pn;
5756 quic_rx_packet_refinc(pkt);
5757 eb64_insert(&qel->rx.pkts, &pkt->pn_node);
5758
5759 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5760}
5761
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005762/* Try to remove the header protection of <pkt> QUIC packet with <beg> the
5763 * address of the packet first byte, using the keys from encryption level <el>.
5764 *
5765 * If header protection has been successfully removed, packet data are copied
5766 * into <qc> Rx buffer. If <el> secrets are not yet available, the copy is also
5767 * proceeded, and the packet is inserted into <qc> protected packets tree. In
5768 * both cases, packet can now be considered handled by the <qc> connection.
5769 *
5770 * If header protection cannot be removed due to <el> secrets already
5771 * discarded, no operation is conducted.
5772 *
5773 * Returns 1 on success : packet data is now handled by the connection. On
5774 * error 0 is returned : packet should be dropped by the caller.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005775 */
5776static inline int qc_try_rm_hp(struct quic_conn *qc,
5777 struct quic_rx_packet *pkt,
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005778 unsigned char *beg,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005779 struct quic_enc_level **el)
5780{
5781 int ret = 0;
5782 unsigned char *pn = NULL; /* Packet number field */
5783 enum quic_tls_enc_level tel;
5784 struct quic_enc_level *qel;
5785 /* Only for traces. */
5786 struct quic_rx_packet *qpkt_trace;
5787
5788 qpkt_trace = NULL;
5789 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005790 BUG_ON(!pkt->pn_offset);
5791
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005792 /* The packet number is here. This is also the start minus
5793 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
5794 * protection.
5795 */
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005796 pn = beg + pkt->pn_offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005797
5798 tel = quic_packet_type_enc_level(pkt->type);
5799 qel = &qc->els[tel];
5800
5801 if (qc_qel_may_rm_hp(qc, qel)) {
Frédéric Lécaille72027782023-02-22 16:20:09 +01005802 struct quic_tls_ctx *tls_ctx = qc_select_tls_ctx(qc, qel, pkt);
5803
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005804 /* Note that the following function enables us to unprotect the packet
5805 * number and its length subsequently used to decrypt the entire
5806 * packets.
5807 */
Frédéric Lécaille72027782023-02-22 16:20:09 +01005808 if (!qc_do_rm_hp(qc, pkt, tls_ctx,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005809 qel->pktns->rx.largest_pn, pn, beg)) {
5810 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, qc);
5811 goto out;
5812 }
5813
Frédéric Lécailleece86e62023-03-07 11:53:43 +01005814 qc_handle_spin_bit(qc, pkt, qel);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005815 /* The AAD includes the packet number field. */
5816 pkt->aad_len = pkt->pn_offset + pkt->pnl;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005817 if (pkt->len - pkt->aad_len < QUIC_TLS_TAG_LEN) {
5818 TRACE_PROTO("Too short packet", QUIC_EV_CONN_TRMHP, qc);
5819 goto out;
5820 }
5821
5822 qpkt_trace = pkt;
5823 }
5824 else {
5825 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
5826 /* If the packet number space has been discarded, this packet
5827 * will be not parsed.
5828 */
5829 TRACE_PROTO("Discarded pktns", QUIC_EV_CONN_TRMHP, qc, pkt);
5830 goto out;
5831 }
5832
5833 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005834 LIST_APPEND(&qel->rx.pqpkts, &pkt->list);
5835 quic_rx_packet_refinc(pkt);
5836 }
5837
5838 *el = qel;
5839 /* No reference counter incrementation here!!! */
5840 LIST_APPEND(&qc->rx.pkt_list, &pkt->qc_rx_pkt_list);
5841 memcpy(b_tail(&qc->rx.buf), beg, pkt->len);
5842 pkt->data = (unsigned char *)b_tail(&qc->rx.buf);
5843 b_add(&qc->rx.buf, pkt->len);
5844
5845 ret = 1;
5846 out:
5847 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc, qpkt_trace);
5848 return ret;
5849}
5850
5851/* Parse the header form from <byte0> first byte of <pkt> packet to set its type.
5852 * Also set <*long_header> to 1 if this form is long, 0 if not and the version
5853 * of this packet into <*version>.
5854 */
5855static inline int qc_parse_hd_form(struct quic_rx_packet *pkt,
5856 unsigned char **buf, const unsigned char *end,
5857 int *long_header, uint32_t *version)
5858{
5859 int ret = 0;
5860 const unsigned char byte0 = **buf;
5861
5862 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5863
5864 (*buf)++;
5865 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
5866 unsigned char type =
5867 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
5868
5869 *long_header = 1;
5870 /* Version */
5871 if (!quic_read_uint32(version, (const unsigned char **)buf, end)) {
5872 TRACE_ERROR("could not read the packet version", QUIC_EV_CONN_RXPKT);
5873 goto out;
5874 }
5875
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +01005876 if (*version != QUIC_PROTOCOL_VERSION_2) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005877 pkt->type = type;
5878 }
5879 else {
5880 switch (type) {
5881 case 0:
5882 pkt->type = QUIC_PACKET_TYPE_RETRY;
5883 break;
5884 case 1:
5885 pkt->type = QUIC_PACKET_TYPE_INITIAL;
5886 break;
5887 case 2:
5888 pkt->type = QUIC_PACKET_TYPE_0RTT;
5889 break;
5890 case 3:
5891 pkt->type = QUIC_PACKET_TYPE_HANDSHAKE;
5892 break;
5893 }
5894 }
5895 }
5896 else {
Frédéric Lécailleece86e62023-03-07 11:53:43 +01005897 if (byte0 & QUIC_PACKET_SPIN_BIT)
5898 pkt->flags |= QUIC_FL_RX_PACKET_SPIN_BIT;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005899 pkt->type = QUIC_PACKET_TYPE_SHORT;
5900 *long_header = 0;
5901 }
5902
5903 ret = 1;
5904 out:
5905 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5906 return ret;
5907}
5908
5909/* Return the QUIC version (quic_version struct) with <version> as version number
5910 * if supported or NULL if not.
5911 */
5912static inline const struct quic_version *qc_supported_version(uint32_t version)
5913{
5914 int i;
5915
5916 for (i = 0; i < quic_versions_nb; i++)
5917 if (quic_versions[i].num == version)
5918 return &quic_versions[i];
5919
5920 return NULL;
5921}
5922
5923/*
5924 * Send a Version Negotiation packet on response to <pkt> on socket <fd> to
5925 * address <addr>.
5926 * Implementation of RFC9000 6. Version Negotiation
5927 *
5928 * TODO implement a rate-limiting sending of Version Negotiation packets
5929 *
5930 * Returns 0 on success else non-zero
5931 */
5932static int send_version_negotiation(int fd, struct sockaddr_storage *addr,
5933 struct quic_rx_packet *pkt)
5934{
5935 char buf[256];
5936 int ret = 0, i = 0, j;
5937 uint32_t version;
5938 const socklen_t addrlen = get_addr_len(addr);
5939
5940 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5941 /*
5942 * header form
5943 * long header, fixed bit to 0 for Version Negotiation
5944 */
5945 /* TODO: RAND_bytes() should be replaced? */
5946 if (RAND_bytes((unsigned char *)buf, 1) != 1) {
5947 TRACE_ERROR("RAND_bytes() error", QUIC_EV_CONN_TXPKT);
5948 goto out;
5949 }
5950
5951 buf[i++] |= '\x80';
5952 /* null version for Version Negotiation */
5953 buf[i++] = '\x00';
5954 buf[i++] = '\x00';
5955 buf[i++] = '\x00';
5956 buf[i++] = '\x00';
5957
5958 /* source connection id */
5959 buf[i++] = pkt->scid.len;
5960 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5961 i += pkt->scid.len;
5962
5963 /* destination connection id */
5964 buf[i++] = pkt->dcid.len;
5965 memcpy(&buf[i], pkt->dcid.data, pkt->dcid.len);
5966 i += pkt->dcid.len;
5967
5968 /* supported version */
5969 for (j = 0; j < quic_versions_nb; j++) {
5970 version = htonl(quic_versions[j].num);
5971 memcpy(&buf[i], &version, sizeof(version));
5972 i += sizeof(version);
5973 }
5974
5975 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0)
5976 goto out;
5977
5978 ret = 1;
5979 out:
5980 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5981 return !ret;
5982}
5983
5984/* Send a stateless reset packet depending on <pkt> RX packet information
5985 * from <fd> UDP socket to <dst>
5986 * Return 1 if succeeded, 0 if not.
5987 */
5988static int send_stateless_reset(struct listener *l, struct sockaddr_storage *dstaddr,
5989 struct quic_rx_packet *rxpkt)
5990{
5991 int ret = 0, pktlen, rndlen;
5992 unsigned char pkt[64];
5993 const socklen_t addrlen = get_addr_len(dstaddr);
5994 struct proxy *prx;
5995 struct quic_counters *prx_counters;
5996
5997 TRACE_ENTER(QUIC_EV_STATELESS_RST);
5998
5999 prx = l->bind_conf->frontend;
6000 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6001 /* 10.3 Stateless Reset (https://www.rfc-editor.org/rfc/rfc9000.html#section-10.3)
6002 * The resulting minimum size of 21 bytes does not guarantee that a Stateless
6003 * Reset is difficult to distinguish from other packets if the recipient requires
6004 * the use of a connection ID. To achieve that end, the endpoint SHOULD ensure
6005 * that all packets it sends are at least 22 bytes longer than the minimum
6006 * connection ID length that it requests the peer to include in its packets,
6007 * adding PADDING frames as necessary. This ensures that any Stateless Reset
6008 * sent by the peer is indistinguishable from a valid packet sent to the endpoint.
6009 * An endpoint that sends a Stateless Reset in response to a packet that is
6010 * 43 bytes or shorter SHOULD send a Stateless Reset that is one byte shorter
6011 * than the packet it responds to.
6012 */
6013
6014 /* Note that we build at most a 42 bytes QUIC packet to mimic a short packet */
6015 pktlen = rxpkt->len <= 43 ? rxpkt->len - 1 : 0;
6016 pktlen = QUIC_MAX(QUIC_STATELESS_RESET_PACKET_MINLEN, pktlen);
6017 rndlen = pktlen - QUIC_STATELESS_RESET_TOKEN_LEN;
6018
6019 /* Put a header of random bytes */
6020 /* TODO: RAND_bytes() should be replaced */
6021 if (RAND_bytes(pkt, rndlen) != 1) {
6022 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_STATELESS_RST);
6023 goto leave;
6024 }
6025
6026 /* Clear the most significant bit, and set the second one */
6027 *pkt = (*pkt & ~0x80) | 0x40;
6028 if (!quic_stateless_reset_token_cpy(NULL, pkt + rndlen, QUIC_STATELESS_RESET_TOKEN_LEN,
6029 rxpkt->dcid.data, rxpkt->dcid.len))
6030 goto leave;
6031
6032 if (sendto(l->rx.fd, pkt, pktlen, 0, (struct sockaddr *)dstaddr, addrlen) < 0)
6033 goto leave;
6034
6035 ret = 1;
6036 HA_ATOMIC_INC(&prx_counters->stateless_reset_sent);
6037 TRACE_PROTO("stateless reset sent", QUIC_EV_STATELESS_RST, NULL, &rxpkt->dcid);
6038 leave:
6039 TRACE_LEAVE(QUIC_EV_STATELESS_RST);
6040 return ret;
6041}
6042
6043/* QUIC server only function.
6044 * Add AAD to <add> buffer from <cid> connection ID and <addr> socket address.
6045 * This is the responsibility of the caller to check <aad> size is big enough
6046 * to contain these data.
6047 * Return the number of bytes copied to <aad>.
6048 */
6049static int quic_generate_retry_token_aad(unsigned char *aad,
6050 uint32_t version,
6051 const struct quic_cid *cid,
6052 const struct sockaddr_storage *addr)
6053{
6054 unsigned char *p;
6055
6056 p = aad;
6057 memcpy(p, &version, sizeof version);
6058 p += sizeof version;
6059 p += quic_saddr_cpy(p, addr);
6060 memcpy(p, cid->data, cid->len);
6061 p += cid->len;
6062
6063 return p - aad;
6064}
6065
6066/* QUIC server only function.
6067 * Generate the token to be used in Retry packets. The token is written to
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006068 * <buf> with <len> as length. <odcid> is the original destination connection
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006069 * ID and <dcid> is our side destination connection ID (or client source
6070 * connection ID).
6071 * Returns the length of the encoded token or 0 on error.
6072 */
6073static int quic_generate_retry_token(unsigned char *buf, size_t len,
6074 const uint32_t version,
6075 const struct quic_cid *odcid,
6076 const struct quic_cid *dcid,
6077 struct sockaddr_storage *addr)
6078{
6079 int ret = 0;
6080 unsigned char *p;
6081 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02006082 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006083 size_t aadlen;
6084 unsigned char salt[QUIC_RETRY_TOKEN_SALTLEN];
6085 unsigned char key[QUIC_TLS_KEY_LEN];
6086 unsigned char iv[QUIC_TLS_IV_LEN];
6087 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
6088 size_t seclen = strlen(global.cluster_secret);
6089 EVP_CIPHER_CTX *ctx = NULL;
6090 const EVP_CIPHER *aead = EVP_aes_128_gcm();
6091 uint32_t timestamp = now_ms;
6092
6093 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
6094
6095 /* We copy the odcid into the token, prefixed by its one byte
6096 * length, the format token byte. It is followed by an AEAD TAG, and finally
6097 * the random bytes used to derive the secret to encrypt the token.
6098 */
6099 if (1 + dcid->len + 1 + QUIC_TLS_TAG_LEN + sizeof salt > len)
6100 goto err;
6101
6102 aadlen = quic_generate_retry_token_aad(aad, version, dcid, addr);
6103 /* TODO: RAND_bytes() should be replaced */
6104 if (RAND_bytes(salt, sizeof salt) != 1) {
6105 TRACE_ERROR("RAND_bytes()", QUIC_EV_CONN_TXPKT);
6106 goto err;
6107 }
6108
6109 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
6110 salt, sizeof salt, sec, seclen)) {
6111 TRACE_ERROR("quic_tls_derive_retry_token_secret() failed", QUIC_EV_CONN_TXPKT);
6112 goto err;
6113 }
6114
6115 if (!quic_tls_tx_ctx_init(&ctx, aead, key)) {
6116 TRACE_ERROR("quic_tls_tx_ctx_init() failed", QUIC_EV_CONN_TXPKT);
6117 goto err;
6118 }
6119
6120 /* Token build */
6121 p = buf;
6122 *p++ = QUIC_TOKEN_FMT_RETRY,
6123 *p++ = odcid->len;
6124 memcpy(p, odcid->data, odcid->len);
6125 p += odcid->len;
6126 write_u32(p, htonl(timestamp));
6127 p += sizeof timestamp;
6128
6129 /* Do not encrypt the QUIC_TOKEN_FMT_RETRY byte */
6130 if (!quic_tls_encrypt(buf + 1, p - buf - 1, aad, aadlen, ctx, aead, key, iv)) {
6131 TRACE_ERROR("quic_tls_encrypt() failed", QUIC_EV_CONN_TXPKT);
6132 goto err;
6133 }
6134
6135 p += QUIC_TLS_TAG_LEN;
6136 memcpy(p, salt, sizeof salt);
6137 p += sizeof salt;
6138 EVP_CIPHER_CTX_free(ctx);
6139
6140 ret = p - buf;
6141 leave:
6142 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
6143 return ret;
6144
6145 err:
6146 if (ctx)
6147 EVP_CIPHER_CTX_free(ctx);
6148 goto leave;
6149}
6150
6151/* QUIC server only function.
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006152 *
6153 * Check the validity of the Retry token from Initial packet <pkt>. <dgram> is
6154 * the UDP datagram containing <pkt> and <l> is the listener instance on which
6155 * it was received. If the token is valid, the ODCID of <qc> QUIC connection
6156 * will be put into <odcid>. <qc> is used to retrieve the QUIC version needed
6157 * to validate the token but it can be NULL : in this case the version will be
6158 * retrieved from the packet.
6159 *
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006160 * Return 1 if succeeded, 0 if not.
6161 */
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006162
6163static int quic_retry_token_check(struct quic_rx_packet *pkt,
6164 struct quic_dgram *dgram,
6165 struct listener *l,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006166 struct quic_conn *qc,
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006167 struct quic_cid *odcid)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006168{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006169 struct proxy *prx;
6170 struct quic_counters *prx_counters;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006171 int ret = 0;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006172 unsigned char *token = pkt->token;
6173 const uint64_t tokenlen = pkt->token_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006174 unsigned char buf[128];
6175 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02006176 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006177 size_t aadlen;
6178 const unsigned char *salt;
6179 unsigned char key[QUIC_TLS_KEY_LEN];
6180 unsigned char iv[QUIC_TLS_IV_LEN];
6181 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
6182 size_t seclen = strlen(global.cluster_secret);
6183 EVP_CIPHER_CTX *ctx = NULL;
6184 const EVP_CIPHER *aead = EVP_aes_128_gcm();
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006185 const struct quic_version *qv = qc ? qc->original_version :
6186 pkt->version;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006187
6188 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6189
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006190 /* The caller must ensure this. */
6191 BUG_ON(!global.cluster_secret || !pkt->token_len);
6192
6193 prx = l->bind_conf->frontend;
6194 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6195
6196 if (*pkt->token != QUIC_TOKEN_FMT_RETRY) {
6197 /* TODO: New token check */
6198 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6199 goto leave;
6200 }
6201
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006202 if (sizeof buf < tokenlen) {
6203 TRACE_ERROR("too short buffer", QUIC_EV_CONN_LPKT, qc);
6204 goto err;
6205 }
6206
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006207 aadlen = quic_generate_retry_token_aad(aad, qv->num, &pkt->scid, &dgram->saddr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006208 salt = token + tokenlen - QUIC_RETRY_TOKEN_SALTLEN;
6209 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
6210 salt, QUIC_RETRY_TOKEN_SALTLEN, sec, seclen)) {
6211 TRACE_ERROR("Could not derive retry secret", QUIC_EV_CONN_LPKT, qc);
6212 goto err;
6213 }
6214
6215 if (!quic_tls_rx_ctx_init(&ctx, aead, key)) {
6216 TRACE_ERROR("quic_tls_rx_ctx_init() failed", QUIC_EV_CONN_LPKT, qc);
6217 goto err;
6218 }
6219
6220 /* Do not decrypt the QUIC_TOKEN_FMT_RETRY byte */
6221 if (!quic_tls_decrypt2(buf, token + 1, tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, aad, aadlen,
6222 ctx, aead, key, iv)) {
6223 TRACE_ERROR("Could not decrypt retry token", QUIC_EV_CONN_LPKT, qc);
6224 goto err;
6225 }
6226
6227 if (parse_retry_token(qc, buf, buf + tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, odcid)) {
6228 TRACE_ERROR("Error during Initial token parsing", QUIC_EV_CONN_LPKT, qc);
6229 goto err;
6230 }
6231
6232 EVP_CIPHER_CTX_free(ctx);
6233
6234 ret = 1;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006235 HA_ATOMIC_INC(&prx_counters->retry_validated);
6236
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006237 leave:
6238 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6239 return ret;
6240
6241 err:
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006242 HA_ATOMIC_INC(&prx_counters->retry_error);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006243 if (ctx)
6244 EVP_CIPHER_CTX_free(ctx);
6245 goto leave;
6246}
6247
6248/* Generate a Retry packet and send it on <fd> socket to <addr> in response to
6249 * the Initial <pkt> packet.
6250 *
6251 * Returns 0 on success else non-zero.
6252 */
6253static int send_retry(int fd, struct sockaddr_storage *addr,
6254 struct quic_rx_packet *pkt, const struct quic_version *qv)
6255{
6256 int ret = 0;
6257 unsigned char buf[128];
6258 int i = 0, token_len;
6259 const socklen_t addrlen = get_addr_len(addr);
6260 struct quic_cid scid;
6261
6262 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
6263
6264 /* long header + fixed bit + packet type QUIC_PACKET_TYPE_RETRY */
6265 buf[i++] = (QUIC_PACKET_LONG_HEADER_BIT | QUIC_PACKET_FIXED_BIT) |
6266 (quic_pkt_type(QUIC_PACKET_TYPE_RETRY, qv->num) << QUIC_PACKET_TYPE_SHIFT);
6267 /* version */
6268 buf[i++] = *((unsigned char *)&qv->num + 3);
6269 buf[i++] = *((unsigned char *)&qv->num + 2);
6270 buf[i++] = *((unsigned char *)&qv->num + 1);
6271 buf[i++] = *(unsigned char *)&qv->num;
6272
6273 /* Use the SCID from <pkt> for Retry DCID. */
6274 buf[i++] = pkt->scid.len;
6275 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
6276 i += pkt->scid.len;
6277
6278 /* Generate a new CID to be used as SCID for the Retry packet. */
6279 scid.len = QUIC_HAP_CID_LEN;
6280 /* TODO: RAND_bytes() should be replaced */
6281 if (RAND_bytes(scid.data, scid.len) != 1) {
6282 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT);
6283 goto out;
6284 }
6285
6286 buf[i++] = scid.len;
6287 memcpy(&buf[i], scid.data, scid.len);
6288 i += scid.len;
6289
6290 /* token */
6291 if (!(token_len = quic_generate_retry_token(&buf[i], sizeof(buf) - i, qv->num,
6292 &pkt->dcid, &pkt->scid, addr))) {
6293 TRACE_ERROR("quic_generate_retry_token() failed", QUIC_EV_CONN_TXPKT);
6294 goto out;
6295 }
6296
6297 i += token_len;
6298
6299 /* token integrity tag */
6300 if ((&buf[i] - buf < QUIC_TLS_TAG_LEN) ||
6301 !quic_tls_generate_retry_integrity_tag(pkt->dcid.data,
6302 pkt->dcid.len, buf, i, qv)) {
6303 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
6304 goto out;
6305 }
6306
6307 i += QUIC_TLS_TAG_LEN;
6308
6309 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0) {
6310 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
6311 goto out;
6312 }
6313
6314 ret = 1;
6315 out:
6316 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
6317 return !ret;
6318}
6319
6320/* Retrieve a quic_conn instance from the <pkt> DCID field. If the packet is of
6321 * type INITIAL, the ODCID tree is first used. In this case, <saddr> is
6322 * concatenated to the <pkt> DCID field.
6323 *
6324 * Returns the instance or NULL if not found.
6325 */
6326static struct quic_conn *retrieve_qc_conn_from_cid(struct quic_rx_packet *pkt,
6327 struct listener *l,
6328 struct sockaddr_storage *saddr)
6329{
6330 struct quic_conn *qc = NULL;
6331 struct ebmb_node *node;
6332 struct quic_connection_id *id;
6333 /* set if the quic_conn is found in the second DCID tree */
6334
6335 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
6336
6337 /* Look first into ODCIDs tree for INITIAL/0-RTT packets. */
6338 if (pkt->type == QUIC_PACKET_TYPE_INITIAL ||
6339 pkt->type == QUIC_PACKET_TYPE_0RTT) {
6340 /* DCIDs of first packets coming from multiple clients may have
6341 * the same values. Let's distinguish them by concatenating the
6342 * socket addresses.
6343 */
6344 quic_cid_saddr_cat(&pkt->dcid, saddr);
6345 node = ebmb_lookup(&quic_dghdlrs[tid].odcids, pkt->dcid.data,
6346 pkt->dcid.len + pkt->dcid.addrlen);
6347 if (node) {
6348 qc = ebmb_entry(node, struct quic_conn, odcid_node);
6349 goto end;
6350 }
6351 }
6352
6353 /* Look into DCIDs tree for non-INITIAL/0-RTT packets. This may be used
6354 * also for INITIAL/0-RTT non-first packets with the final DCID in
6355 * used.
6356 */
6357 node = ebmb_lookup(&quic_dghdlrs[tid].cids, pkt->dcid.data, pkt->dcid.len);
6358 if (!node)
6359 goto end;
6360
6361 id = ebmb_entry(node, struct quic_connection_id, node);
6362 qc = id->qc;
6363
6364 /* If found in DCIDs tree, remove the quic_conn from the ODCIDs tree.
6365 * If already done, this is a noop.
6366 */
6367 if (qc)
6368 ebmb_delete(&qc->odcid_node);
6369
6370 end:
6371 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
6372 return qc;
6373}
6374
6375/* Try to allocate the <*ssl> SSL session object for <qc> QUIC connection
6376 * with <ssl_ctx> as SSL context inherited settings. Also set the transport
6377 * parameters of this session.
6378 * This is the responsibility of the caller to check the validity of all the
6379 * pointers passed as parameter to this function.
6380 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <qc->conn> to
6381 * CO_ER_SSL_NO_MEM.
6382 */
6383static int qc_ssl_sess_init(struct quic_conn *qc, SSL_CTX *ssl_ctx, SSL **ssl,
6384 unsigned char *params, size_t params_len)
6385{
6386 int retry, ret = -1;
6387
6388 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6389
6390 retry = 1;
6391 retry:
6392 *ssl = SSL_new(ssl_ctx);
6393 if (!*ssl) {
6394 if (!retry--)
6395 goto err;
6396
6397 pool_gc(NULL);
6398 goto retry;
6399 }
6400
6401 if (!SSL_set_quic_method(*ssl, &ha_quic_method) ||
6402 !SSL_set_ex_data(*ssl, ssl_qc_app_data_index, qc)) {
6403 SSL_free(*ssl);
6404 *ssl = NULL;
6405 if (!retry--)
6406 goto err;
6407
6408 pool_gc(NULL);
6409 goto retry;
6410 }
6411
6412 ret = 0;
6413 leave:
6414 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6415 return ret;
6416
6417 err:
6418 qc->conn->err_code = CO_ER_SSL_NO_MEM;
6419 goto leave;
6420}
6421
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006422/* Allocate the ssl_sock_ctx from connection <qc>. This creates the tasklet
6423 * used to process <qc> received packets. The allocated context is stored in
6424 * <qc.xprt_ctx>.
6425 *
6426 * Returns 0 on success else non-zero.
6427 */
6428static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc)
6429{
6430 int ret = 0;
6431 struct bind_conf *bc = qc->li->bind_conf;
6432 struct ssl_sock_ctx *ctx = NULL;
6433
6434 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6435
6436 ctx = pool_zalloc(pool_head_quic_conn_ctx);
6437 if (!ctx) {
6438 TRACE_ERROR("SSL context allocation failed", QUIC_EV_CONN_TXPKT);
6439 goto err;
6440 }
6441
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006442 ctx->subs = NULL;
6443 ctx->xprt_ctx = NULL;
6444 ctx->qc = qc;
6445
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006446 if (qc_is_listener(qc)) {
6447 if (qc_ssl_sess_init(qc, bc->initial_ctx, &ctx->ssl,
6448 qc->enc_params, qc->enc_params_len) == -1) {
6449 goto err;
6450 }
6451#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
6452 /* Enabling 0-RTT */
6453 if (bc->ssl_conf.early_data)
6454 SSL_set_quic_early_data_enabled(ctx->ssl, 1);
6455#endif
6456
6457 SSL_set_accept_state(ctx->ssl);
6458 }
6459
6460 ctx->xprt = xprt_get(XPRT_QUIC);
6461
6462 /* Store the allocated context in <qc>. */
6463 qc->xprt_ctx = ctx;
6464
6465 ret = 1;
6466 leave:
6467 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6468 return !ret;
6469
6470 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006471 pool_free(pool_head_quic_conn_ctx, ctx);
6472 goto leave;
6473}
6474
6475/* Check that all the bytes between <buf> included and <end> address
6476 * excluded are null. This is the responsibility of the caller to
6477 * check that there is at least one byte between <buf> end <end>.
6478 * Return 1 if this all the bytes are null, 0 if not.
6479 */
6480static inline int quic_padding_check(const unsigned char *buf,
6481 const unsigned char *end)
6482{
6483 while (buf < end && !*buf)
6484 buf++;
6485
6486 return buf == end;
6487}
6488
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006489/* Find the associated connection to the packet <pkt> or create a new one if
6490 * this is an Initial packet. <dgram> is the datagram containing the packet and
6491 * <l> is the listener instance on which it was received.
6492 *
6493 * Returns the quic-conn instance or NULL.
6494 */
6495static struct quic_conn *quic_rx_pkt_retrieve_conn(struct quic_rx_packet *pkt,
6496 struct quic_dgram *dgram,
6497 struct listener *l)
6498{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006499 struct quic_cid token_odcid = { .len = 0 };
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006500 struct quic_conn *qc = NULL;
6501 struct proxy *prx;
6502 struct quic_counters *prx_counters;
6503
6504 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6505
6506 prx = l->bind_conf->frontend;
6507 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6508
6509 qc = retrieve_qc_conn_from_cid(pkt, l, &dgram->saddr);
6510
6511 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6512 BUG_ON(!pkt->version); /* This must not happen. */
6513
6514 if (global.cluster_secret && pkt->token_len) {
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006515 if (!quic_retry_token_check(pkt, dgram, l, qc, &token_odcid))
6516 goto err;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006517 }
6518
6519 if (!qc) {
6520 int ipv4;
6521
6522 if (global.cluster_secret && !pkt->token_len && !(l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) &&
6523 HA_ATOMIC_LOAD(&prx_counters->half_open_conn) >= global.tune.quic_retry_threshold) {
6524 TRACE_PROTO("Initial without token, sending retry",
6525 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6526 if (send_retry(l->rx.fd, &dgram->saddr, pkt, pkt->version)) {
6527 TRACE_ERROR("Error during Retry generation",
6528 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6529 goto out;
6530 }
6531
6532 HA_ATOMIC_INC(&prx_counters->retry_sent);
6533 goto out;
6534 }
6535
6536 /* RFC 9000 7.2. Negotiating Connection IDs:
6537 * When an Initial packet is sent by a client that has not previously
6538 * received an Initial or Retry packet from the server, the client
6539 * populates the Destination Connection ID field with an unpredictable
6540 * value. This Destination Connection ID MUST be at least 8 bytes in length.
6541 */
6542 if (pkt->dcid.len < QUIC_ODCID_MINLEN) {
6543 TRACE_PROTO("dropped packet",
6544 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6545 goto err;
6546 }
6547
6548 pkt->saddr = dgram->saddr;
6549 ipv4 = dgram->saddr.ss_family == AF_INET;
6550
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006551 qc = qc_new_conn(pkt->version, ipv4, &pkt->dcid, &pkt->scid, &token_odcid,
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006552 &dgram->daddr, &pkt->saddr, 1,
6553 !!pkt->token_len, l);
6554 if (qc == NULL)
6555 goto err;
6556
6557 HA_ATOMIC_INC(&prx_counters->half_open_conn);
6558 /* Insert the DCID the QUIC client has chosen (only for listeners) */
6559 ebmb_insert(&quic_dghdlrs[tid].odcids, &qc->odcid_node,
6560 qc->odcid.len + qc->odcid.addrlen);
6561 }
6562 }
6563 else if (!qc) {
6564 TRACE_PROTO("No connection on a non Initial packet", QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6565 if (global.cluster_secret && !send_stateless_reset(l, &dgram->saddr, pkt))
6566 TRACE_ERROR("stateless reset not sent", QUIC_EV_CONN_LPKT, qc);
6567 goto err;
6568 }
6569
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006570 out:
6571 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6572 return qc;
6573
6574 err:
6575 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
6576 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
6577 return NULL;
6578}
6579
Amaury Denoyelle98289692022-10-19 15:37:44 +02006580/* Parse a QUIC packet starting at <buf>. Data won't be read after <end> even
6581 * if the packet is incomplete. This function will populate fields of <pkt>
6582 * instance, most notably its length. <dgram> is the UDP datagram which
6583 * contains the parsed packet. <l> is the listener instance on which it was
6584 * received.
6585 *
6586 * Returns 0 on success else non-zero. Packet length is guaranteed to be set to
6587 * the real packet value or to cover all data between <buf> and <end> : this is
6588 * useful to reject a whole datagram.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006589 */
Amaury Denoyelle98289692022-10-19 15:37:44 +02006590static int quic_rx_pkt_parse(struct quic_rx_packet *pkt,
6591 unsigned char *buf, const unsigned char *end,
6592 struct quic_dgram *dgram, struct listener *l)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006593{
Amaury Denoyelle98289692022-10-19 15:37:44 +02006594 const unsigned char *beg = buf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006595 struct proxy *prx;
6596 struct quic_counters *prx_counters;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006597 int long_header = 0;
Willy Tarreau33a68702022-11-24 09:16:41 +01006598 uint32_t version = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006599 const struct quic_version *qv = NULL;
6600
6601 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6602
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006603 prx = l->bind_conf->frontend;
6604 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6605 /* This ist only to please to traces and distinguish the
6606 * packet with parsed packet number from others.
6607 */
6608 pkt->pn_node.key = (uint64_t)-1;
6609 if (end <= buf) {
6610 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6611 goto drop;
6612 }
6613
6614 /* Fixed bit */
6615 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006616 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
6617 quic_padding_check(buf, end)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006618 /* Some browsers may pad the remaining datagram space with null bytes.
6619 * That is what we called add padding out of QUIC packets. Such
6620 * datagrams must be considered as valid. But we can only consume
6621 * the remaining space.
6622 */
6623 pkt->len = end - buf;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006624 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006625 }
6626
6627 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6628 goto drop;
6629 }
6630
6631 /* Header form */
6632 if (!qc_parse_hd_form(pkt, &buf, end, &long_header, &version)) {
6633 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6634 goto drop;
6635 }
6636
6637 if (long_header) {
6638 uint64_t len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006639
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006640 TRACE_PROTO("long header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006641 if (!quic_packet_read_long_header(&buf, end, pkt)) {
6642 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6643 goto drop;
6644 }
6645
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006646 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6647 * they must have the same DCID.
6648 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006649 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006650 (pkt->dcid.len != dgram->dcid_len ||
6651 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006652 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006653 goto drop;
6654 }
6655
6656 /* Retry of Version Negotiation packets are only sent by servers */
6657 if (pkt->type == QUIC_PACKET_TYPE_RETRY || !version) {
6658 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6659 goto drop;
6660 }
6661
6662 /* RFC9000 6. Version Negotiation */
6663 qv = qc_supported_version(version);
6664 if (!qv) {
6665 /* unsupported version, send Negotiation packet */
6666 if (send_version_negotiation(l->rx.fd, &dgram->saddr, pkt)) {
6667 TRACE_ERROR("VN packet not sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006668 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006669 }
6670
6671 TRACE_PROTO("VN packet sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006672 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006673 }
Amaury Denoyelle0eae5722022-10-17 18:05:18 +02006674 pkt->version = qv;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006675
6676 /* For Initial packets, and for servers (QUIC clients connections),
6677 * there is no Initial connection IDs storage.
6678 */
6679 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6680 uint64_t token_len;
6681
6682 if (!quic_dec_int(&token_len, (const unsigned char **)&buf, end) ||
6683 end - buf < token_len) {
6684 TRACE_PROTO("Packet dropped",
6685 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6686 goto drop;
6687 }
6688
6689 /* TODO Retry should be automatically activated if
6690 * suspect network usage is detected.
6691 */
6692 if (global.cluster_secret && !token_len) {
6693 if (l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) {
6694 TRACE_PROTO("Initial without token, sending retry",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006695 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006696 if (send_retry(l->rx.fd, &dgram->saddr, pkt, qv)) {
6697 TRACE_PROTO("Error during Retry generation",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006698 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006699 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006700 }
6701
6702 HA_ATOMIC_INC(&prx_counters->retry_sent);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006703 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006704 }
6705 }
6706 else if (!global.cluster_secret && token_len) {
6707 /* Impossible case: a token was received without configured
6708 * cluster secret.
6709 */
6710 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT,
6711 NULL, NULL, NULL, qv);
6712 goto drop;
6713 }
6714
6715 pkt->token = buf;
6716 pkt->token_len = token_len;
6717 buf += pkt->token_len;
6718 }
6719 else if (pkt->type != QUIC_PACKET_TYPE_0RTT) {
6720 if (pkt->dcid.len != QUIC_HAP_CID_LEN) {
6721 TRACE_PROTO("Packet dropped",
6722 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6723 goto drop;
6724 }
6725 }
6726
6727 if (!quic_dec_int(&len, (const unsigned char **)&buf, end) ||
6728 end - buf < len) {
6729 TRACE_PROTO("Packet dropped",
6730 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6731 goto drop;
6732 }
6733
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006734 /* Packet Number is stored here. Packet Length totalizes the
6735 * rest of the content.
6736 */
6737 pkt->pn_offset = buf - beg;
6738 pkt->len = pkt->pn_offset + len;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006739
Frédéric Lécaille35218c62023-02-16 11:40:11 +01006740 /* RFC 9000. Initial Datagram Size
6741 *
6742 * A server MUST discard an Initial packet that is carried in a UDP datagram
6743 * with a payload that is smaller than the smallest allowed maximum datagram
6744 * size of 1200 bytes.
6745 */
6746 if (pkt->type == QUIC_PACKET_TYPE_INITIAL &&
6747 dgram->len < QUIC_INITIAL_PACKET_MINLEN) {
6748 TRACE_PROTO("Too short datagram with an Initial packet", QUIC_EV_CONN_LPKT);
6749 HA_ATOMIC_INC(&prx_counters->too_short_initial_dgram);
6750 goto drop;
6751 }
6752
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006753 /* Interrupt parsing after packet length retrieval : this
6754 * ensures that only the packet is dropped but not the whole
6755 * datagram.
6756 */
6757 if (pkt->type == QUIC_PACKET_TYPE_0RTT && !l->bind_conf->ssl_conf.early_data) {
6758 TRACE_PROTO("0-RTT packet not supported", QUIC_EV_CONN_LPKT);
6759 goto drop;
6760 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006761 }
6762 else {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006763 TRACE_PROTO("short header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006764 if (end - buf < QUIC_HAP_CID_LEN) {
6765 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6766 goto drop;
6767 }
6768
6769 memcpy(pkt->dcid.data, buf, QUIC_HAP_CID_LEN);
6770 pkt->dcid.len = QUIC_HAP_CID_LEN;
6771
6772 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6773 * they must have the same DCID.
6774 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006775 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006776 (pkt->dcid.len != dgram->dcid_len ||
6777 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006778 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006779 goto drop;
6780 }
6781
6782 buf += QUIC_HAP_CID_LEN;
6783
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006784 pkt->pn_offset = buf - beg;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006785 /* A short packet is the last one of a UDP datagram. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006786 pkt->len = end - beg;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006787 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006788
Amaury Denoyelle98289692022-10-19 15:37:44 +02006789 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6790 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006791
Amaury Denoyelle98289692022-10-19 15:37:44 +02006792 drop:
6793 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006794 drop_silent:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006795 if (!pkt->len)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006796 pkt->len = end - beg;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006797 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6798 return -1;
6799}
6800
6801/* Check if received packet <pkt> should be drop due to <qc> already in closing
6802 * state. This can be true if a CONNECTION_CLOSE has already been emitted for
6803 * this connection.
6804 *
6805 * Returns false if connection is not in closing state else true. The caller
6806 * should drop the whole datagram in the last case to not mess up <qc>
6807 * CONNECTION_CLOSE rate limit counter.
6808 */
6809static int qc_rx_check_closing(struct quic_conn *qc,
6810 struct quic_rx_packet *pkt)
6811{
6812 if (!(qc->flags & QUIC_FL_CONN_CLOSING))
6813 return 0;
6814
6815 TRACE_STATE("Closing state connection", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6816
6817 /* Check if CONNECTION_CLOSE rate reemission is reached. */
6818 if (++qc->nb_pkt_since_cc >= qc->nb_pkt_for_cc) {
6819 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
6820 qc->nb_pkt_for_cc++;
6821 qc->nb_pkt_since_cc = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006822 }
6823
Amaury Denoyelle98289692022-10-19 15:37:44 +02006824 return 1;
6825}
6826
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006827/* React to a connection migration initiated on <qc> by a client with the new
6828 * path addresses <peer_addr>/<local_addr>.
6829 *
6830 * Returns 0 on success else non-zero.
6831 */
6832static int qc_handle_conn_migration(struct quic_conn *qc,
6833 const struct sockaddr_storage *peer_addr,
6834 const struct sockaddr_storage *local_addr)
6835{
6836 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6837
Frédéric Lécaille6fc86972023-01-12 08:29:23 +01006838 /* RFC 9000. Connection Migration
6839 *
6840 * If the peer sent the disable_active_migration transport parameter,
6841 * an endpoint also MUST NOT send packets (including probing packets;
6842 * see Section 9.1) from a different local address to the address the peer
6843 * used during the handshake, unless the endpoint has acted on a
6844 * preferred_address transport parameter from the peer.
6845 */
6846 if (qc->li->bind_conf->quic_params.disable_active_migration) {
6847 TRACE_ERROR("Active migration was disabled, datagram dropped", QUIC_EV_CONN_LPKT, qc);
6848 goto err;
6849 }
6850
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006851 /* RFC 9000 9. Connection Migration
6852 *
Amaury Denoyelleeb6be982022-11-21 11:14:45 +01006853 * The design of QUIC relies on endpoints retaining a stable address for
6854 * the duration of the handshake. An endpoint MUST NOT initiate
6855 * connection migration before the handshake is confirmed, as defined in
6856 * Section 4.1.2 of [QUIC-TLS].
6857 */
6858 if (qc->state < QUIC_HS_ST_COMPLETE) {
6859 TRACE_STATE("Connection migration during handshake rejected", QUIC_EV_CONN_LPKT, qc);
6860 goto err;
6861 }
6862
6863 /* RFC 9000 9. Connection Migration
6864 *
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006865 * TODO
6866 * An endpoint MUST
6867 * perform path validation (Section 8.2) if it detects any change to a
6868 * peer's address, unless it has previously validated that address.
6869 */
6870
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006871 /* Update quic-conn owned socket if in used.
6872 * TODO try to reuse it instead of closing and opening a new one.
6873 */
6874 if (qc_test_fd(qc)) {
6875 /* TODO try to reuse socket instead of closing it and opening a new one. */
6876 TRACE_STATE("Connection migration detected, allocate a new connection socket", QUIC_EV_CONN_LPKT, qc);
6877 qc_release_fd(qc, 1);
Amaury Denoyellefb375572023-02-01 09:28:32 +01006878 /* TODO need to adjust <jobs> on socket allocation failure. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006879 qc_alloc_fd(qc, local_addr, peer_addr);
6880 }
6881
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006882 qc->local_addr = *local_addr;
6883 qc->peer_addr = *peer_addr;
6884 HA_ATOMIC_INC(&qc->prx_counters->conn_migration_done);
6885
6886 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6887 return 0;
6888
6889 err:
6890 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6891 return 1;
6892}
6893
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006894/* Release the memory for the RX packets which are no more referenced
6895 * and consume their payloads which have been copied to the RX buffer
6896 * for the connection.
6897 * Always succeeds.
6898 */
6899static inline void quic_rx_pkts_del(struct quic_conn *qc)
6900{
6901 struct quic_rx_packet *pkt, *pktback;
6902
6903 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
6904 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006905 "pkt #%lld(type=%d,len=%llu,rawlen=%llu,refcnt=%u) (diff: %zd)",
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006906 (long long)pkt->pn_node.key,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006907 pkt->type, (ull)pkt->len, (ull)pkt->raw_len, pkt->refcnt,
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006908 (unsigned char *)b_head(&qc->rx.buf) - pkt->data);
6909 if (pkt->data != (unsigned char *)b_head(&qc->rx.buf)) {
6910 size_t cdata;
6911
6912 cdata = b_contig_data(&qc->rx.buf, 0);
6913 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006914 "cdata=%llu *b_head()=0x%x", (ull)cdata, *b_head(&qc->rx.buf));
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006915 if (cdata && !*b_head(&qc->rx.buf)) {
6916 /* Consume the remaining data */
6917 b_del(&qc->rx.buf, cdata);
6918 }
6919 break;
6920 }
6921
6922 if (pkt->refcnt)
6923 break;
6924
6925 b_del(&qc->rx.buf, pkt->raw_len);
6926 LIST_DELETE(&pkt->qc_rx_pkt_list);
6927 pool_free(pool_head_quic_rx_packet, pkt);
6928 }
6929
6930 /* In frequent cases the buffer will be emptied at this stage. */
6931 b_realign_if_empty(&qc->rx.buf);
6932}
6933
Amaury Denoyelle98289692022-10-19 15:37:44 +02006934/* Handle a parsed packet <pkt> by the connection <qc>. Data will be copied
6935 * into <qc> receive buffer after header protection removal procedure.
6936 *
6937 * <dgram> must be set to the datagram which contains the QUIC packet. <beg>
6938 * must point to packet buffer first byte.
6939 *
6940 * <tasklist_head> may be non-NULL when the caller treat several datagrams for
6941 * different quic-conn. In this case, each quic-conn tasklet will be appended
6942 * to it in order to be woken up after the current task.
6943 *
6944 * The caller can safely removed the packet data. If packet refcount was not
6945 * incremented by this function, it means that the connection did not handled
6946 * it and it should be freed by the caller.
6947 */
6948static void qc_rx_pkt_handle(struct quic_conn *qc, struct quic_rx_packet *pkt,
6949 struct quic_dgram *dgram, unsigned char *beg,
6950 struct list **tasklist_head)
6951{
6952 const struct quic_version *qv = pkt->version;
6953 struct quic_enc_level *qel = NULL;
6954 size_t b_cspace;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006955
Amaury Denoyelle3f474e62022-11-24 17:15:08 +01006956 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6957
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006958 if (pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006959 qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED) {
6960 TRACE_PROTO("PTO timer must be armed after anti-amplication was reached",
6961 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01006962 TRACE_DEVEL("needs to wakeup the timer task after the amplification limit was reached",
6963 QUIC_EV_CONN_LPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006964 /* Reset the anti-amplification bit. It will be set again
6965 * when sending the next packet if reached again.
6966 */
6967 qc->flags &= ~QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01006968 qc_set_timer(qc);
6969 if (qc->timer_task && tick_isset(qc->timer) && tick_is_lt(qc->timer, now_ms))
6970 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006971 }
6972
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006973 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
6974 TRACE_PROTO("Connection error",
6975 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6976 goto out;
6977 }
6978
6979 pkt->raw_len = pkt->len;
6980 quic_rx_pkts_del(qc);
6981 b_cspace = b_contig_space(&qc->rx.buf);
6982 if (b_cspace < pkt->len) {
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006983 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006984 "bspace=%llu pkt->len=%llu", (ull)b_cspace, (ull)pkt->len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006985 /* Do not consume buf if space not at the end. */
6986 if (b_tail(&qc->rx.buf) + b_cspace < b_wrap(&qc->rx.buf)) {
6987 TRACE_PROTO("Packet dropped",
6988 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006989 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006990 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006991 }
6992
6993 /* Let us consume the remaining contiguous space. */
6994 if (b_cspace) {
6995 b_putchr(&qc->rx.buf, 0x00);
6996 b_cspace--;
6997 }
6998 b_add(&qc->rx.buf, b_cspace);
6999 if (b_contig_space(&qc->rx.buf) < pkt->len) {
7000 TRACE_PROTO("Too big packet",
7001 QUIC_EV_CONN_LPKT, qc, pkt, &pkt->len, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02007002 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02007003 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007004 }
7005 }
7006
Amaury Denoyelle845169d2022-10-17 18:05:26 +02007007 if (!qc_try_rm_hp(qc, pkt, beg, &qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007008 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
7009 goto drop;
7010 }
7011
7012 TRACE_DATA("New packet", QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
7013 if (pkt->aad_len)
7014 qc_pkt_insert(qc, pkt, qel);
7015 out:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02007016 *tasklist_head = tasklet_wakeup_after(*tasklist_head,
7017 qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007018
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02007019 drop_silent:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007020 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007021 return;
7022
7023 drop:
Amaury Denoyelle98289692022-10-19 15:37:44 +02007024 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007025 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
7026}
7027
7028/* This function builds into <buf> buffer a QUIC long packet header.
7029 * Return 1 if enough room to build this header, 0 if not.
7030 */
7031static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
7032 int type, size_t pn_len,
7033 struct quic_conn *qc, const struct quic_version *ver)
7034{
7035 int ret = 0;
7036
7037 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
7038
7039 if (end - *buf < sizeof ver->num + qc->dcid.len + qc->scid.len + 3) {
7040 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
7041 goto leave;
7042 }
7043
7044 type = quic_pkt_type(type, ver->num);
7045 /* #0 byte flags */
7046 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
7047 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
7048 /* Version */
7049 quic_write_uint32(buf, end, ver->num);
7050 *(*buf)++ = qc->dcid.len;
7051 /* Destination connection ID */
7052 if (qc->dcid.len) {
7053 memcpy(*buf, qc->dcid.data, qc->dcid.len);
7054 *buf += qc->dcid.len;
7055 }
7056 /* Source connection ID */
7057 *(*buf)++ = qc->scid.len;
7058 if (qc->scid.len) {
7059 memcpy(*buf, qc->scid.data, qc->scid.len);
7060 *buf += qc->scid.len;
7061 }
7062
7063 ret = 1;
7064 leave:
7065 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
7066 return ret;
7067}
7068
7069/* This function builds into <buf> buffer a QUIC short packet header.
7070 * Return 1 if enough room to build this header, 0 if not.
7071 */
7072static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
7073 size_t pn_len, struct quic_conn *qc,
7074 unsigned char tls_flags)
7075{
7076 int ret = 0;
Frédéric Lécailleece86e62023-03-07 11:53:43 +01007077 unsigned char spin_bit =
7078 (qc->flags & QUIC_FL_CONN_SPIN_BIT) ? QUIC_PACKET_SPIN_BIT : 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007079
7080 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7081
7082 if (end - *buf < 1 + qc->dcid.len) {
7083 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
7084 goto leave;
7085 }
7086
7087 /* #0 byte flags */
Frédéric Lécailleece86e62023-03-07 11:53:43 +01007088 *(*buf)++ = QUIC_PACKET_FIXED_BIT | spin_bit |
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007089 ((tls_flags & QUIC_FL_TLS_KP_BIT_SET) ? QUIC_PACKET_KEY_PHASE_BIT : 0) | (pn_len - 1);
7090 /* Destination connection ID */
7091 if (qc->dcid.len) {
7092 memcpy(*buf, qc->dcid.data, qc->dcid.len);
7093 *buf += qc->dcid.len;
7094 }
7095
7096 ret = 1;
7097 leave:
7098 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7099 return ret;
7100}
7101
7102/* Apply QUIC header protection to the packet with <buf> as first byte address,
7103 * <pn> as address of the Packet number field, <pnlen> being this field length
7104 * with <aead> as AEAD cipher and <key> as secret key.
7105 * Returns 1 if succeeded or 0 if failed.
7106 */
7107static int quic_apply_header_protection(struct quic_conn *qc, unsigned char *buf,
7108 unsigned char *pn, size_t pnlen,
7109 struct quic_tls_ctx *tls_ctx)
7110
7111{
7112 int i, ret = 0;
7113 /* We need an IV of at least 5 bytes: one byte for bytes #0
7114 * and at most 4 bytes for the packet number
7115 */
7116 unsigned char mask[5] = {0};
7117 EVP_CIPHER_CTX *aes_ctx = tls_ctx->tx.hp_ctx;
7118
7119 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7120
7121 if (!quic_tls_aes_encrypt(mask, pn + QUIC_PACKET_PN_MAXLEN, sizeof mask, aes_ctx)) {
7122 TRACE_ERROR("could not apply header protection", QUIC_EV_CONN_TXPKT, qc);
7123 goto out;
7124 }
7125
7126 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
7127 for (i = 0; i < pnlen; i++)
7128 pn[i] ^= mask[i + 1];
7129
7130 ret = 1;
7131 out:
7132 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7133 return ret;
7134}
7135
7136/* Reduce the encoded size of <ack_frm> ACK frame removing the last
7137 * ACK ranges if needed to a value below <limit> in bytes.
7138 * Return 1 if succeeded, 0 if not.
7139 */
7140static int quic_ack_frm_reduce_sz(struct quic_conn *qc,
7141 struct quic_frame *ack_frm, size_t limit)
7142{
7143 size_t room, ack_delay_sz;
7144 int ret = 0;
7145
7146 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7147
7148 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
7149 /* A frame is made of 1 byte for the frame type. */
7150 room = limit - ack_delay_sz - 1;
7151 if (!quic_rm_last_ack_ranges(qc, ack_frm->tx_ack.arngs, room))
7152 goto leave;
7153
7154 ret = 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
7155 leave:
7156 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7157 return ret;
7158}
7159
7160/* Prepare into <outlist> as most as possible ack-eliciting frame from their
7161 * <inlist> prebuilt frames for <qel> encryption level to be encoded in a buffer
7162 * with <room> as available room, and <*len> the packet Length field initialized
7163 * with the number of bytes already present in this buffer which must be taken
7164 * into an account for the Length packet field value. <headlen> is the number of
7165 * bytes already present in this packet before building frames.
7166 *
7167 * Update consequently <*len> to reflect the size of these frames built
7168 * by this function. Also attach these frames to <l> frame list.
7169 * Return 1 if at least one ack-eleciting frame could be built, 0 if not.
7170 */
7171static inline int qc_build_frms(struct list *outlist, struct list *inlist,
7172 size_t room, size_t *len, size_t headlen,
7173 struct quic_enc_level *qel,
7174 struct quic_conn *qc)
7175{
7176 int ret;
7177 struct quic_frame *cf, *cfbak;
7178
7179 TRACE_ENTER(QUIC_EV_CONN_BCFRMS, qc);
7180
7181 ret = 0;
7182 if (*len > room)
7183 goto leave;
7184
7185 /* If we are not probing we must take into an account the congestion
7186 * control window.
7187 */
7188 if (!qel->pktns->tx.pto_probe) {
7189 size_t remain = quic_path_prep_data(qc->path);
7190
7191 if (headlen > remain)
7192 goto leave;
7193
7194 room = QUIC_MIN(room, remain - headlen);
7195 }
7196
7197 TRACE_PROTO("************** frames build (headlen)",
7198 QUIC_EV_CONN_BCFRMS, qc, &headlen);
7199
7200 /* NOTE: switch/case block inside a loop, a successful status must be
7201 * returned by this function only if at least one frame could be built
7202 * in the switch/case block.
7203 */
7204 list_for_each_entry_safe(cf, cfbak, inlist, list) {
7205 /* header length, data length, frame length. */
7206 size_t hlen, dlen, dlen_sz, avail_room, flen;
7207
7208 if (!room)
7209 break;
7210
7211 switch (cf->type) {
7212 case QUIC_FT_CRYPTO:
7213 TRACE_DEVEL(" New CRYPTO frame build (room, len)",
7214 QUIC_EV_CONN_BCFRMS, qc, &room, len);
7215 /* Compute the length of this CRYPTO frame header */
7216 hlen = 1 + quic_int_getsize(cf->crypto.offset);
7217 /* Compute the data length of this CRyPTO frame. */
7218 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
7219 TRACE_DEVEL(" CRYPTO data length (hlen, crypto.len, dlen)",
7220 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->crypto.len, &dlen);
7221 if (!dlen)
7222 continue;
7223
7224 /* CRYPTO frame length. */
7225 flen = hlen + quic_int_getsize(dlen) + dlen;
7226 TRACE_DEVEL(" CRYPTO frame length (flen)",
7227 QUIC_EV_CONN_BCFRMS, qc, &flen);
7228 /* Add the CRYPTO data length and its encoded length to the packet
7229 * length and the length of this length.
7230 */
7231 *len += flen;
7232 room -= flen;
7233 if (dlen == cf->crypto.len) {
7234 /* <cf> CRYPTO data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007235 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007236 LIST_APPEND(outlist, &cf->list);
7237 }
7238 else {
7239 struct quic_frame *new_cf;
7240
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01007241 new_cf = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007242 if (!new_cf) {
7243 TRACE_ERROR("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, qc);
7244 continue;
7245 }
7246
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007247 new_cf->crypto.len = dlen;
7248 new_cf->crypto.offset = cf->crypto.offset;
7249 new_cf->crypto.qel = qel;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05007250 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007251 if (cf->origin) {
7252 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
7253 /* This <cf> frame was duplicated */
7254 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
7255 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01007256 /* Detach the remaining CRYPTO frame from its original frame */
7257 LIST_DEL_INIT(&cf->ref);
7258 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007259 }
7260 LIST_APPEND(outlist, &new_cf->list);
7261 /* Consume <dlen> bytes of the current frame. */
7262 cf->crypto.len -= dlen;
7263 cf->crypto.offset += dlen;
7264 }
7265 break;
7266
7267 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01007268 if (cf->stream.dup) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007269 struct eb64_node *node = NULL;
7270 struct qc_stream_desc *stream_desc = NULL;
7271 struct quic_stream *strm = &cf->stream;
7272
7273 /* As this frame has been already lost, ensure the stream is always
7274 * available or the range of this frame is not consumed before
7275 * resending it.
7276 */
7277 node = eb64_lookup(&qc->streams_by_id, strm->id);
7278 if (!node) {
7279 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007280 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007281 continue;
7282 }
7283
7284 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
7285 if (strm->offset.key + strm->len <= stream_desc->ack_offset) {
7286 TRACE_DEVEL("ignored frame frame in already acked range",
7287 QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007288 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007289 continue;
7290 }
7291 else if (strm->offset.key < stream_desc->ack_offset) {
7292 strm->offset.key = stream_desc->ack_offset;
Frédéric Lécaillefc546ab2023-03-16 12:30:36 +01007293 strm->len -= stream_desc->ack_offset - strm->offset.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007294 TRACE_DEVEL("updated partially acked frame",
7295 QUIC_EV_CONN_PRSAFRM, qc, cf);
7296 }
7297 }
7298 /* Note that these frames are accepted in short packets only without
7299 * "Length" packet field. Here, <*len> is used only to compute the
7300 * sum of the lengths of the already built frames for this packet.
7301 *
7302 * Compute the length of this STREAM frame "header" made a all the field
7303 * excepting the variable ones. Note that +1 is for the type of this frame.
7304 */
7305 hlen = 1 + quic_int_getsize(cf->stream.id) +
7306 ((cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT) ? quic_int_getsize(cf->stream.offset.key) : 0);
7307 /* Compute the data length of this STREAM frame. */
7308 avail_room = room - hlen - *len;
7309 if ((ssize_t)avail_room <= 0)
7310 continue;
7311
7312 TRACE_DEVEL(" New STREAM frame build (room, len)",
7313 QUIC_EV_CONN_BCFRMS, qc, &room, len);
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007314
7315 /* hlen contains STREAM id and offset. Ensure there is
7316 * enough room for length field.
7317 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007318 if (cf->type & QUIC_STREAM_FRAME_TYPE_LEN_BIT) {
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007319 dlen = QUIC_MIN((uint64_t)max_available_room(avail_room, &dlen_sz),
7320 cf->stream.len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007321 dlen_sz = quic_int_getsize(dlen);
7322 flen = hlen + dlen_sz + dlen;
7323 }
7324 else {
7325 dlen = QUIC_MIN((uint64_t)avail_room, cf->stream.len);
7326 flen = hlen + dlen;
7327 }
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007328
7329 if (cf->stream.len && !dlen) {
7330 /* Only a small gap is left on buffer, not
7331 * enough to encode the STREAM data length.
7332 */
7333 continue;
7334 }
7335
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007336 TRACE_DEVEL(" STREAM data length (hlen, stream.len, dlen)",
7337 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->stream.len, &dlen);
7338 TRACE_DEVEL(" STREAM frame length (flen)",
7339 QUIC_EV_CONN_BCFRMS, qc, &flen);
7340 /* Add the STREAM data length and its encoded length to the packet
7341 * length and the length of this length.
7342 */
7343 *len += flen;
7344 room -= flen;
7345 if (dlen == cf->stream.len) {
7346 /* <cf> STREAM data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007347 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007348 LIST_APPEND(outlist, &cf->list);
7349
7350 /* Do not notify MUX on retransmission. */
7351 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7352 qcc_streams_sent_done(cf->stream.stream->ctx,
7353 cf->stream.len,
7354 cf->stream.offset.key);
7355 }
7356 }
7357 else {
7358 struct quic_frame *new_cf;
7359 struct buffer cf_buf;
7360
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01007361 new_cf = qc_frm_alloc(cf->type);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007362 if (!new_cf) {
7363 TRACE_ERROR("No memory for new STREAM frame", QUIC_EV_CONN_BCFRMS, qc);
7364 continue;
7365 }
7366
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007367 new_cf->stream.stream = cf->stream.stream;
7368 new_cf->stream.buf = cf->stream.buf;
7369 new_cf->stream.id = cf->stream.id;
Amaury Denoyelle1dac0182023-02-02 16:45:07 +01007370 new_cf->stream.offset = cf->stream.offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007371 new_cf->stream.len = dlen;
7372 new_cf->type |= QUIC_STREAM_FRAME_TYPE_LEN_BIT;
7373 /* FIN bit reset */
7374 new_cf->type &= ~QUIC_STREAM_FRAME_TYPE_FIN_BIT;
7375 new_cf->stream.data = cf->stream.data;
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01007376 new_cf->stream.dup = cf->stream.dup;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05007377 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007378 if (cf->origin) {
7379 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
7380 /* This <cf> frame was duplicated */
7381 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
7382 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01007383 /* Detach this STREAM frame from its origin */
7384 LIST_DEL_INIT(&cf->ref);
7385 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007386 }
7387 LIST_APPEND(outlist, &new_cf->list);
7388 cf->type |= QUIC_STREAM_FRAME_TYPE_OFF_BIT;
7389 /* Consume <dlen> bytes of the current frame. */
7390 cf_buf = b_make(b_orig(cf->stream.buf),
7391 b_size(cf->stream.buf),
7392 (char *)cf->stream.data - b_orig(cf->stream.buf), 0);
7393 cf->stream.len -= dlen;
7394 cf->stream.offset.key += dlen;
7395 cf->stream.data = (unsigned char *)b_peek(&cf_buf, dlen);
7396
7397 /* Do not notify MUX on retransmission. */
7398 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7399 qcc_streams_sent_done(new_cf->stream.stream->ctx,
7400 new_cf->stream.len,
7401 new_cf->stream.offset.key);
7402 }
7403 }
7404
7405 /* TODO the MUX is notified about the frame sending via
7406 * previous qcc_streams_sent_done call. However, the
7407 * sending can fail later, for example if the sendto
7408 * system call returns an error. As the MUX has been
7409 * notified, the transport layer is responsible to
7410 * bufferize and resent the announced data later.
7411 */
7412
7413 break;
7414
7415 default:
7416 flen = qc_frm_len(cf);
7417 BUG_ON(!flen);
7418 if (flen > room)
7419 continue;
7420
7421 *len += flen;
7422 room -= flen;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007423 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007424 LIST_APPEND(outlist, &cf->list);
7425 break;
7426 }
7427
7428 /* Successful status as soon as a frame could be built */
7429 ret = 1;
7430 }
7431
7432 leave:
7433 TRACE_LEAVE(QUIC_EV_CONN_BCFRMS, qc);
7434 return ret;
7435}
7436
7437/* Generate a CONNECTION_CLOSE frame for <qc> on <qel> encryption level. <out>
7438 * is used as return parameter and should be zero'ed by the caller.
7439 */
7440static void qc_build_cc_frm(struct quic_conn *qc, struct quic_enc_level *qel,
7441 struct quic_frame *out)
7442{
7443 /* TODO improve CONNECTION_CLOSE on Initial/Handshake encryption levels
7444 *
7445 * A CONNECTION_CLOSE frame should be sent in several packets with
7446 * different encryption levels depending on the client context. This is
7447 * to ensure that the client can decrypt it. See RFC 9000 10.2.3 for
7448 * more details on how to implement it.
7449 */
7450 TRACE_ENTER(QUIC_EV_CONN_BFRM, qc);
7451
7452
7453 if (qc->err.app) {
7454 if (unlikely(qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
7455 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
7456 /* RFC 9000 10.2.3. Immediate Close during the Handshake
7457 *
7458 * Sending a CONNECTION_CLOSE of type 0x1d in an Initial or Handshake
7459 * packet could expose application state or be used to alter application
7460 * state. A CONNECTION_CLOSE of type 0x1d MUST be replaced by a
7461 * CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or
7462 * Handshake packets. Otherwise, information about the application
7463 * state might be revealed. Endpoints MUST clear the value of the
7464 * Reason Phrase field and SHOULD use the APPLICATION_ERROR code when
7465 * converting to a CONNECTION_CLOSE of type 0x1c.
7466 */
7467 out->type = QUIC_FT_CONNECTION_CLOSE;
7468 out->connection_close.error_code = QC_ERR_APPLICATION_ERROR;
7469 out->connection_close.reason_phrase_len = 0;
7470 }
7471 else {
7472 out->type = QUIC_FT_CONNECTION_CLOSE_APP;
7473 out->connection_close.error_code = qc->err.code;
7474 }
7475 }
7476 else {
7477 out->type = QUIC_FT_CONNECTION_CLOSE;
7478 out->connection_close.error_code = qc->err.code;
7479 }
7480 TRACE_LEAVE(QUIC_EV_CONN_BFRM, qc);
7481
7482}
7483
7484/* This function builds a clear packet from <pkt> information (its type)
7485 * into a buffer with <pos> as position pointer and <qel> as QUIC TLS encryption
7486 * level for <conn> QUIC connection and <qel> as QUIC TLS encryption level,
7487 * filling the buffer with as much frames as possible from <frms> list of
7488 * prebuilt frames.
7489 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
7490 * reserved so that to ensure there is enough room to build this AEAD TAG after
7491 * having returned from this function.
7492 * This function also updates the value of <buf_pn> pointer to point to the packet
7493 * number field in this packet. <pn_len> will also have the packet number
7494 * length as value.
7495 *
7496 * Return 1 if succeeded (enough room to buile this packet), O if not.
7497 */
7498static int qc_do_build_pkt(unsigned char *pos, const unsigned char *end,
7499 size_t dglen, struct quic_tx_packet *pkt,
7500 int64_t pn, size_t *pn_len, unsigned char **buf_pn,
7501 int force_ack, int padding, int cc, int probe,
7502 struct quic_enc_level *qel, struct quic_conn *qc,
7503 const struct quic_version *ver, struct list *frms)
7504{
7505 unsigned char *beg, *payload;
7506 size_t len, len_sz, len_frms, padding_len;
7507 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
7508 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
7509 struct quic_frame cc_frm = { };
7510 size_t ack_frm_len, head_len;
7511 int64_t rx_largest_acked_pn;
7512 int add_ping_frm;
7513 struct list frm_list = LIST_HEAD_INIT(frm_list);
7514 struct quic_frame *cf;
7515 int must_ack, ret = 0;
7516 int nb_aepkts_since_last_ack;
7517
7518 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7519
7520 /* Length field value with CRYPTO frames if present. */
7521 len_frms = 0;
7522 beg = pos;
7523 /* When not probing, and no immediate close is required, reduce the size of this
7524 * buffer to respect the congestion controller window.
7525 * This size will be limited if we have ack-eliciting frames to send from <frms>.
7526 */
7527 if (!probe && !LIST_ISEMPTY(frms) && !cc) {
7528 size_t path_room;
7529
7530 path_room = quic_path_prep_data(qc->path);
7531 if (end - beg > path_room)
7532 end = beg + path_room;
7533 }
7534
7535 /* Ensure there is enough room for the TLS encryption tag and a zero token
7536 * length field if any.
7537 */
7538 if (end - pos < QUIC_TLS_TAG_LEN +
7539 (pkt->type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0))
7540 goto no_room;
7541
7542 end -= QUIC_TLS_TAG_LEN;
7543 rx_largest_acked_pn = qel->pktns->rx.largest_acked_pn;
7544 /* packet number length */
7545 *pn_len = quic_packet_number_length(pn, rx_largest_acked_pn);
7546 /* Build the header */
7547 if ((pkt->type == QUIC_PACKET_TYPE_SHORT &&
7548 !quic_build_packet_short_header(&pos, end, *pn_len, qc, qel->tls_ctx.flags)) ||
7549 (pkt->type != QUIC_PACKET_TYPE_SHORT &&
7550 !quic_build_packet_long_header(&pos, end, pkt->type, *pn_len, qc, ver)))
7551 goto no_room;
7552
7553 /* Encode the token length (0) for an Initial packet. */
7554 if (pkt->type == QUIC_PACKET_TYPE_INITIAL)
7555 *pos++ = 0;
7556 head_len = pos - beg;
7557 /* Build an ACK frame if required. */
7558 ack_frm_len = 0;
7559 nb_aepkts_since_last_ack = qel->pktns->rx.nb_aepkts_since_last_ack;
7560 must_ack = !qel->pktns->tx.pto_probe &&
7561 (force_ack || ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
7562 (LIST_ISEMPTY(frms) || nb_aepkts_since_last_ack >= QUIC_MAX_RX_AEPKTS_SINCE_LAST_ACK)));
7563 if (must_ack) {
7564 struct quic_arngs *arngs = &qel->pktns->rx.arngs;
7565 BUG_ON(eb_is_empty(&qel->pktns->rx.arngs.root));
7566 ack_frm.tx_ack.arngs = arngs;
7567 if (qel->pktns->flags & QUIC_FL_PKTNS_NEW_LARGEST_PN) {
7568 qel->pktns->tx.ack_delay =
7569 quic_compute_ack_delay_us(qel->pktns->rx.largest_time_received, qc);
7570 qel->pktns->flags &= ~QUIC_FL_PKTNS_NEW_LARGEST_PN;
7571 }
7572 ack_frm.tx_ack.ack_delay = qel->pktns->tx.ack_delay;
7573 /* XXX BE CAREFUL XXX : here we reserved at least one byte for the
7574 * smallest frame (PING) and <*pn_len> more for the packet number. Note
7575 * that from here, we do not know if we will have to send a PING frame.
7576 * This will be decided after having computed the ack-eliciting frames
7577 * to be added to this packet.
7578 */
7579 ack_frm_len = quic_ack_frm_reduce_sz(qc, &ack_frm, end - 1 - *pn_len - pos);
7580 if (!ack_frm_len)
7581 goto no_room;
7582 }
7583
7584 /* Length field value without the ack-eliciting frames. */
7585 len = ack_frm_len + *pn_len;
7586 len_frms = 0;
7587 if (!cc && !LIST_ISEMPTY(frms)) {
7588 ssize_t room = end - pos;
7589
7590 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7591 /* Initialize the length of the frames built below to <len>.
7592 * If any frame could be successfully built by qc_build_frms(),
7593 * we will have len_frms > len.
7594 */
7595 len_frms = len;
7596 if (!qc_build_frms(&frm_list, frms,
7597 end - pos, &len_frms, pos - beg, qel, qc)) {
7598 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7599 qc, NULL, NULL, &room);
7600 if (!ack_frm_len && !qel->pktns->tx.pto_probe)
7601 goto no_room;
7602 }
7603 }
7604
7605 /* Length (of the remaining data). Must not fail because, the buffer size
7606 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
7607 * for the encryption tag. It must be taken into an account for the length
7608 * of this packet.
7609 */
7610 if (len_frms)
7611 len = len_frms + QUIC_TLS_TAG_LEN;
7612 else
7613 len += QUIC_TLS_TAG_LEN;
7614 /* CONNECTION_CLOSE frame */
7615 if (cc) {
7616 qc_build_cc_frm(qc, qel, &cc_frm);
7617 len += qc_frm_len(&cc_frm);
7618 }
7619 add_ping_frm = 0;
7620 padding_len = 0;
7621 len_sz = quic_int_getsize(len);
7622 /* Add this packet size to <dglen> */
7623 dglen += head_len + len_sz + len;
Frédéric Lécailleec937212023-03-03 17:34:41 +01007624 /* Note that <padding> is true only when building an Handshake packet
7625 * coalesced to an Initial packet.
7626 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007627 if (padding && dglen < QUIC_INITIAL_PACKET_MINLEN) {
7628 /* This is a maximum padding size */
7629 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7630 /* The length field value is of this packet is <len> + <padding_len>
7631 * the size of which may be greater than the initial computed size
7632 * <len_sz>. So, let's deduce the difference between these to packet
7633 * sizes from <padding_len>.
7634 */
7635 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7636 len += padding_len;
7637 }
Frédéric Lécaille5faf5772023-02-16 17:30:53 +01007638 else if (len_frms && len_frms < QUIC_PACKET_PN_MAXLEN) {
7639 len += padding_len = QUIC_PACKET_PN_MAXLEN - len_frms;
7640 }
7641 else if (LIST_ISEMPTY(&frm_list)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007642 if (qel->pktns->tx.pto_probe) {
7643 /* If we cannot send a frame, we send a PING frame. */
7644 add_ping_frm = 1;
7645 len += 1;
Frédéric Lécailleec937212023-03-03 17:34:41 +01007646 dglen += 1;
7647 /* Note that only we are in the case where this Initial packet
7648 * is not coalesced to an Handshake packet. We must directly
7649 * pad the datragram.
7650 */
7651 if (pkt->type == QUIC_PACKET_TYPE_INITIAL && dglen < QUIC_INITIAL_PACKET_MINLEN) {
7652 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7653 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7654 len += padding_len;
7655 }
7656 }
7657 else {
7658 /* If there is no frame at all to follow, add at least a PADDING frame. */
7659 if (!ack_frm_len && !cc)
7660 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007661 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007662 }
7663
7664 if (pkt->type != QUIC_PACKET_TYPE_SHORT && !quic_enc_int(&pos, end, len))
7665 goto no_room;
7666
7667 /* Packet number field address. */
7668 *buf_pn = pos;
7669
7670 /* Packet number encoding. */
7671 if (!quic_packet_number_encode(&pos, end, pn, *pn_len))
7672 goto no_room;
7673
7674 /* payload building (ack-eliciting or not frames) */
7675 payload = pos;
7676 if (ack_frm_len) {
7677 if (!qc_build_frm(&pos, end, &ack_frm, pkt, qc))
7678 goto no_room;
7679
7680 pkt->largest_acked_pn = quic_pktns_get_largest_acked_pn(qel->pktns);
7681 pkt->flags |= QUIC_FL_TX_PACKET_ACK;
7682 }
7683
7684 /* Ack-eliciting frames */
7685 if (!LIST_ISEMPTY(&frm_list)) {
7686 struct quic_frame *tmp_cf;
7687 list_for_each_entry_safe(cf, tmp_cf, &frm_list, list) {
7688 if (!qc_build_frm(&pos, end, cf, pkt, qc)) {
7689 ssize_t room = end - pos;
7690 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7691 qc, NULL, NULL, &room);
7692 /* Note that <cf> was added from <frms> to <frm_list> list by
7693 * qc_build_frms().
7694 */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007695 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007696 LIST_INSERT(frms, &cf->list);
7697 continue;
7698 }
7699
7700 quic_tx_packet_refinc(pkt);
7701 cf->pkt = pkt;
7702 }
7703 }
7704
7705 /* Build a PING frame if needed. */
7706 if (add_ping_frm) {
7707 frm.type = QUIC_FT_PING;
7708 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7709 goto no_room;
7710 }
7711
7712 /* Build a CONNECTION_CLOSE frame if needed. */
7713 if (cc) {
7714 if (!qc_build_frm(&pos, end, &cc_frm, pkt, qc))
7715 goto no_room;
7716
7717 pkt->flags |= QUIC_FL_TX_PACKET_CC;
7718 }
7719
7720 /* Build a PADDING frame if needed. */
7721 if (padding_len) {
7722 frm.type = QUIC_FT_PADDING;
7723 frm.padding.len = padding_len;
7724 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7725 goto no_room;
7726 }
7727
7728 if (pos == payload) {
7729 /* No payload was built because of congestion control */
7730 TRACE_DEVEL("limited by congestion control", QUIC_EV_CONN_TXPKT, qc);
7731 goto no_room;
7732 }
7733
7734 /* If this packet is ack-eliciting and we are probing let's
7735 * decrement the PTO probe counter.
7736 */
7737 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING &&
7738 qel->pktns->tx.pto_probe)
7739 qel->pktns->tx.pto_probe--;
7740
7741 pkt->len = pos - beg;
7742 LIST_SPLICE(&pkt->frms, &frm_list);
7743
7744 ret = 1;
7745 TRACE_DEVEL("Packet ack-eliciting frames", QUIC_EV_CONN_TXPKT, qc, pkt);
7746 leave:
7747 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7748 return ret;
7749
7750 no_room:
7751 /* Replace the pre-built frames which could not be add to this packet */
7752 LIST_SPLICE(frms, &frm_list);
7753 TRACE_DEVEL("Remaining ack-eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7754 goto leave;
7755}
7756
7757static inline void quic_tx_packet_init(struct quic_tx_packet *pkt, int type)
7758{
7759 pkt->type = type;
7760 pkt->len = 0;
7761 pkt->in_flight_len = 0;
7762 pkt->pn_node.key = (uint64_t)-1;
7763 LIST_INIT(&pkt->frms);
7764 pkt->time_sent = TICK_ETERNITY;
7765 pkt->next = NULL;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01007766 pkt->prev = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007767 pkt->largest_acked_pn = -1;
7768 pkt->flags = 0;
7769 pkt->refcnt = 0;
7770}
7771
7772/* Build a packet into <buf> packet buffer with <pkt_type> as packet
7773 * type for <qc> QUIC connection from <qel> encryption level from <frms> list
7774 * of prebuilt frames.
7775 *
7776 * Return -2 if the packet could not be allocated or encrypted for any reason,
7777 * -1 if there was not enough room to build a packet.
7778 * XXX NOTE XXX
7779 * If you provide provide qc_build_pkt() with a big enough buffer to build a packet as big as
7780 * possible (to fill an MTU), the unique reason why this function may fail is the congestion
7781 * control window limitation.
7782 */
7783static struct quic_tx_packet *qc_build_pkt(unsigned char **pos,
7784 const unsigned char *buf_end,
7785 struct quic_enc_level *qel,
7786 struct quic_tls_ctx *tls_ctx, struct list *frms,
7787 struct quic_conn *qc, const struct quic_version *ver,
7788 size_t dglen, int pkt_type, int force_ack,
7789 int padding, int probe, int cc, int *err)
7790{
7791 struct quic_tx_packet *ret_pkt = NULL;
7792 /* The pointer to the packet number field. */
7793 unsigned char *buf_pn;
7794 unsigned char *beg, *end, *payload;
7795 int64_t pn;
7796 size_t pn_len, payload_len, aad_len;
7797 struct quic_tx_packet *pkt;
7798
7799 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc, NULL, qel);
7800 *err = 0;
7801 pkt = pool_alloc(pool_head_quic_tx_packet);
7802 if (!pkt) {
7803 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_TXPKT, qc);
7804 *err = -2;
7805 goto err;
7806 }
7807
7808 quic_tx_packet_init(pkt, pkt_type);
7809 beg = *pos;
7810 pn_len = 0;
7811 buf_pn = NULL;
7812
7813 pn = qel->pktns->tx.next_pn + 1;
7814 if (!qc_do_build_pkt(*pos, buf_end, dglen, pkt, pn, &pn_len, &buf_pn,
7815 force_ack, padding, cc, probe, qel, qc, ver, frms)) {
7816 // trace already emitted by function above
7817 *err = -1;
7818 goto err;
7819 }
7820
7821 end = beg + pkt->len;
7822 payload = buf_pn + pn_len;
7823 payload_len = end - payload;
7824 aad_len = payload - beg;
7825
7826 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc)) {
7827 // trace already emitted by function above
7828 *err = -2;
7829 goto err;
7830 }
7831
7832 end += QUIC_TLS_TAG_LEN;
7833 pkt->len += QUIC_TLS_TAG_LEN;
7834 if (!quic_apply_header_protection(qc, beg, buf_pn, pn_len, tls_ctx)) {
7835 // trace already emitted by function above
7836 *err = -2;
7837 goto err;
7838 }
7839
7840 /* Consume a packet number */
7841 qel->pktns->tx.next_pn++;
7842 qc->tx.prep_bytes += pkt->len;
7843 if (qc->tx.prep_bytes >= 3 * qc->rx.bytes && !quic_peer_validated_addr(qc)) {
7844 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
7845 TRACE_PROTO("anti-amplification limit reached", QUIC_EV_CONN_TXPKT, qc);
7846 }
7847 /* Now that a correct packet is built, let us consume <*pos> buffer. */
7848 *pos = end;
7849 /* Attach the built packet to its tree. */
7850 pkt->pn_node.key = pn;
7851 /* Set the packet in fligth length for in flight packet only. */
7852 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
7853 pkt->in_flight_len = pkt->len;
7854 qc->path->prep_in_flight += pkt->len;
7855 }
7856 /* Always reset this flags */
7857 qc->flags &= ~QUIC_FL_CONN_IMMEDIATE_CLOSE;
7858 if (pkt->flags & QUIC_FL_TX_PACKET_ACK) {
7859 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
7860 qel->pktns->rx.nb_aepkts_since_last_ack = 0;
7861 }
7862
7863 pkt->pktns = qel->pktns;
7864
7865 ret_pkt = pkt;
7866 leave:
7867 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc, ret_pkt);
7868 return ret_pkt;
7869
7870 err:
7871 /* TODO: what about the frames which have been built
7872 * for this packet.
7873 */
7874 free_quic_tx_packet(qc, pkt);
7875 goto leave;
7876}
7877
7878
7879static void __quic_conn_init(void)
7880{
7881 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
7882}
7883INITCALL0(STG_REGISTER, __quic_conn_init);
7884
7885static void __quic_conn_deinit(void)
7886{
7887 BIO_meth_free(ha_quic_meth);
7888}
7889REGISTER_POST_DEINIT(__quic_conn_deinit);
7890
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007891/* Handle a new <dgram> received. Parse each QUIC packets and copied their
7892 * content to a quic-conn instance. The datagram content can be released after
7893 * this function.
7894 *
7895 * If datagram has been received on a quic-conn owned FD, <from_qc> must be set
7896 * to the connection instance. <li> is the attached listener. The caller is
7897 * responsible to ensure that the first packet is destined to this connection
7898 * by comparing CIDs.
7899 *
7900 * If datagram has been received on a receiver FD, <from_qc> will be NULL. This
7901 * function will thus retrieve the connection from the CID tree or allocate a
7902 * new one if possible. <li> is the listener attached to the receiver.
7903 *
7904 * Returns 0 on success else non-zero. If an error happens, some packets from
7905 * the datagram may not have been parsed.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007906 */
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007907int quic_dgram_parse(struct quic_dgram *dgram, struct quic_conn *from_qc,
7908 struct listener *li)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007909{
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007910 struct quic_rx_packet *pkt;
7911 struct quic_conn *qc = NULL;
7912 unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007913 struct list *tasklist_head = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007914
7915 TRACE_ENTER(QUIC_EV_CONN_LPKT);
7916
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007917 pos = dgram->buf;
7918 end = pos + dgram->len;
7919 do {
7920 /* TODO replace zalloc -> alloc. */
7921 pkt = pool_zalloc(pool_head_quic_rx_packet);
7922 if (!pkt) {
7923 TRACE_ERROR("RX packet allocation failed", QUIC_EV_CONN_LPKT);
7924 goto err;
7925 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007926
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007927 pkt->version = NULL;
7928 pkt->pn_offset = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007929
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007930 /* Set flag if pkt is the first one in dgram. */
7931 if (pos == dgram->buf)
7932 pkt->flags |= QUIC_FL_RX_PACKET_DGRAM_FIRST;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007933
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007934 LIST_INIT(&pkt->qc_rx_pkt_list);
7935 pkt->time_received = now_ms;
7936 quic_rx_packet_refinc(pkt);
7937 if (quic_rx_pkt_parse(pkt, pos, end, dgram, li))
7938 goto next;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007939
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007940 /* Search quic-conn instance for first packet of the datagram.
7941 * quic_rx_packet_parse() is responsible to discard packets
7942 * with different DCID as the first one in the same datagram.
7943 */
7944 if (!qc) {
7945 qc = from_qc ? from_qc : quic_rx_pkt_retrieve_conn(pkt, dgram, li);
7946 /* qc is NULL if receiving a non Initial packet for an
7947 * unknown connection.
7948 */
7949 if (!qc) {
Amaury Denoyelle98289692022-10-19 15:37:44 +02007950 /* Skip the entire datagram. */
7951 pkt->len = end - pos;
7952 goto next;
7953 }
7954
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007955 dgram->qc = qc;
7956 }
Amaury Denoyelle98289692022-10-19 15:37:44 +02007957
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007958 if (qc_rx_check_closing(qc, pkt)) {
7959 /* Skip the entire datagram. */
7960 pkt->len = end - pos;
7961 goto next;
7962 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007963
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007964 /* Detect QUIC connection migration. */
Frédéric Lécaillef6769542023-01-12 10:36:26 +01007965 if (ipcmp(&qc->peer_addr, &dgram->saddr, 1)) {
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007966 if (qc_handle_conn_migration(qc, &dgram->saddr, &dgram->daddr)) {
7967 /* Skip the entire datagram. */
7968 TRACE_ERROR("error during connection migration, datagram dropped", QUIC_EV_CONN_LPKT, qc);
7969 pkt->len = end - pos;
7970 goto next;
7971 }
7972 }
7973
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007974 qc_rx_pkt_handle(qc, pkt, dgram, pos, &tasklist_head);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007975
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007976 next:
7977 pos += pkt->len;
7978 quic_rx_packet_refdec(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007979
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007980 /* Free rejected packets */
7981 if (!pkt->refcnt) {
7982 BUG_ON(LIST_INLIST(&pkt->qc_rx_pkt_list));
7983 pool_free(pool_head_quic_rx_packet, pkt);
7984 }
7985 } while (pos < end);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007986
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007987 /* Increasing the received bytes counter by the UDP datagram length
7988 * if this datagram could be associated to a connection.
7989 */
7990 if (dgram->qc)
7991 dgram->qc->rx.bytes += dgram->len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007992
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007993 /* This must never happen. */
7994 BUG_ON(pos > end);
7995 BUG_ON(pos < end || pos > dgram->buf + dgram->len);
7996 /* Mark this datagram as consumed */
7997 HA_ATOMIC_STORE(&dgram->buf, NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007998
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007999 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
8000 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008001
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008002 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008003 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008004 return -1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008005}
8006
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01008007/* Check if connection ID <dcid> of length <dcid_len> belongs to <qc> local
8008 * CIDs. This can be used to determine if a datagram is addressed to the right
8009 * connection instance.
8010 *
8011 * Returns a boolean value.
8012 */
8013int qc_check_dcid(struct quic_conn *qc, unsigned char *dcid, size_t dcid_len)
8014{
8015 struct ebmb_node *node;
8016 struct quic_connection_id *id;
8017
8018 /* For ODCID, address is concatenated to it after qc.odcid.len so this
8019 * comparison is safe.
8020 */
8021 if ((qc->scid.len == dcid_len &&
8022 memcmp(qc->scid.data, dcid, dcid_len) == 0) ||
8023 (qc->odcid.len == dcid_len &&
Frédéric Lécaille07846cb2023-02-13 16:14:24 +01008024 memcmp(qc->odcid.data, dcid, dcid_len) == 0)) {
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01008025 return 1;
8026 }
8027
8028 node = ebmb_lookup(&quic_dghdlrs[tid].cids, dcid, dcid_len);
8029 if (node) {
8030 id = ebmb_entry(node, struct quic_connection_id, node);
8031 if (qc == id->qc)
8032 return 1;
8033 }
8034
8035 return 0;
8036}
8037
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008038/* Retrieve the DCID from a QUIC datagram or packet with <buf> as first octet.
8039 * Returns 1 if succeeded, 0 if not.
8040 */
8041int quic_get_dgram_dcid(unsigned char *buf, const unsigned char *end,
8042 unsigned char **dcid, size_t *dcid_len)
8043{
8044 int ret = 0, long_header;
8045 size_t minlen, skip;
8046
8047 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
8048
8049 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
8050 TRACE_PROTO("fixed bit not set", QUIC_EV_CONN_RXPKT);
8051 goto err;
8052 }
8053
8054 long_header = *buf & QUIC_PACKET_LONG_HEADER_BIT;
8055 minlen = long_header ? QUIC_LONG_PACKET_MINLEN :
8056 QUIC_SHORT_PACKET_MINLEN + QUIC_HAP_CID_LEN + QUIC_TLS_TAG_LEN;
8057 skip = long_header ? QUIC_LONG_PACKET_DCID_OFF : QUIC_SHORT_PACKET_DCID_OFF;
8058 if (end - buf < minlen)
8059 goto err;
8060
8061 buf += skip;
8062 *dcid_len = long_header ? *buf++ : QUIC_HAP_CID_LEN;
8063 if (*dcid_len > QUIC_CID_MAXLEN || end - buf <= *dcid_len)
8064 goto err;
8065
8066 *dcid = buf;
8067
8068 ret = 1;
8069 leave:
8070 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
8071 return ret;
8072
8073 err:
8074 TRACE_PROTO("wrong datagram", QUIC_EV_CONN_RXPKT);
8075 goto leave;
8076}
8077
8078/* Notify the MUX layer if alive about an imminent close of <qc>. */
8079void qc_notify_close(struct quic_conn *qc)
8080{
8081 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
8082
8083 if (qc->flags & QUIC_FL_CONN_NOTIFY_CLOSE)
8084 goto leave;
8085
8086 qc->flags |= QUIC_FL_CONN_NOTIFY_CLOSE;
8087 /* wake up the MUX */
8088 if (qc->mux_state == QC_MUX_READY && qc->conn->mux->wake) {
8089 TRACE_STATE("connection closure notidfied to mux",
8090 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
8091 qc->conn->mux->wake(qc->conn);
8092 }
8093 else
8094 TRACE_STATE("connection closure not notidfied to mux",
8095 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
8096 leave:
8097 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
8098}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008099
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01008100/* Wake-up upper layer if waiting for send to be ready.
8101 *
8102 * Returns 1 if upper layer has been woken up else 0.
8103 */
8104int qc_notify_send(struct quic_conn *qc)
8105{
8106 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
Amaury Denoyellecaa16542023-02-28 15:11:26 +01008107 if (quic_path_prep_data(qc->path) &&
8108 (!qc_test_fd(qc) || !fd_send_active(qc->fd))) {
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01008109 tasklet_wakeup(qc->subs->tasklet);
8110 qc->subs->events &= ~SUB_RETRY_SEND;
8111 if (!qc->subs->events)
8112 qc->subs = NULL;
8113
8114 return 1;
8115 }
8116 }
8117
8118 return 0;
8119}
8120
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008121
8122/* appctx context used by "show quic" command */
8123struct show_quic_ctx {
8124 unsigned int epoch;
8125 struct bref bref; /* back-reference to the quic-conn being dumped */
8126 unsigned int thr;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01008127 int flags;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008128};
8129
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01008130#define QC_CLI_FL_SHOW_ALL 0x1 /* show closing/draining connections */
8131
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008132static int cli_parse_show_quic(char **args, char *payload, struct appctx *appctx, void *private)
8133{
8134 struct show_quic_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
8135
8136 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
8137 return 1;
8138
8139 ctx->epoch = _HA_ATOMIC_FETCH_ADD(&qc_epoch, 1);
8140 ctx->thr = 0;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01008141 ctx->flags = 0;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008142
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01008143 if (*args[2] && strcmp(args[2], "all") == 0)
8144 ctx->flags |= QC_CLI_FL_SHOW_ALL;
8145
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008146 LIST_INIT(&ctx->bref.users);
8147
8148 return 0;
8149}
8150
8151static int cli_io_handler_dump_quic(struct appctx *appctx)
8152{
8153 struct show_quic_ctx *ctx = appctx->svcctx;
8154 struct stconn *sc = appctx_sc(appctx);
8155 struct quic_conn *qc;
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01008156 struct quic_enc_level *qel;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008157 struct eb64_node *node;
8158 struct qc_stream_desc *stream;
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01008159 char bufaddr[INET6_ADDRSTRLEN], bufport[6];
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01008160 int expire;
8161 unsigned char cid_len;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008162
8163 thread_isolate();
8164
8165 if (ctx->thr >= global.nbthread)
8166 goto done;
8167
8168 if (unlikely(sc_ic(sc)->flags & CF_SHUTW)) {
8169 /* If we're forced to shut down, we might have to remove our
8170 * reference to the last stream being dumped.
8171 */
8172 if (!LIST_ISEMPTY(&ctx->bref.users))
8173 LIST_DEL_INIT(&ctx->bref.users);
8174 goto done;
8175 }
8176
8177 chunk_reset(&trash);
8178
8179 if (!LIST_ISEMPTY(&ctx->bref.users)) {
8180 /* Remove show_quic_ctx from previous quic_conn instance. */
8181 LIST_DEL_INIT(&ctx->bref.users);
8182 }
8183 else if (!ctx->bref.ref) {
8184 /* First invocation. */
8185 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
8186 }
8187
8188 while (1) {
8189 int done = 0;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008190 int i;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008191
8192 if (ctx->bref.ref == &ha_thread_ctx[ctx->thr].quic_conns) {
Amaury Denoyelle2d376292023-03-08 09:42:31 +01008193 /* If closing connections requested through "all", move
8194 * to quic_conns_clo list after browsing quic_conns.
8195 * Else move directly to the next quic_conns thread.
8196 */
8197 if (ctx->flags & QC_CLI_FL_SHOW_ALL) {
8198 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns_clo.n;
8199 continue;
8200 }
8201
8202 done = 1;
8203 }
8204 else if (ctx->bref.ref == &ha_thread_ctx[ctx->thr].quic_conns_clo) {
8205 /* Closing list entirely browsed, go to next quic_conns
8206 * thread.
8207 */
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008208 done = 1;
8209 }
8210 else {
Amaury Denoyelle2d376292023-03-08 09:42:31 +01008211 /* Retrieve next element of the current list. */
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008212 qc = LIST_ELEM(ctx->bref.ref, struct quic_conn *, el_th_ctx);
8213 if ((int)(qc->qc_epoch - ctx->epoch) > 0)
8214 done = 1;
8215 }
8216
8217 if (done) {
8218 ++ctx->thr;
8219 if (ctx->thr >= global.nbthread)
8220 break;
Amaury Denoyelle2d376292023-03-08 09:42:31 +01008221 /* Switch to next thread quic_conns list. */
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008222 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
8223 continue;
8224 }
8225
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01008226 /* CIDs */
8227 chunk_appendf(&trash, "* %p[%02u]: scid=", qc, qc->tid);
8228 for (cid_len = 0; cid_len < qc->scid.len; ++cid_len)
8229 chunk_appendf(&trash, "%02x", qc->scid.data[cid_len]);
8230 while (cid_len++ < 20)
8231 chunk_appendf(&trash, "..");
8232
8233 chunk_appendf(&trash, " dcid=");
8234 for (cid_len = 0; cid_len < qc->dcid.len; ++cid_len)
8235 chunk_appendf(&trash, "%02x", qc->dcid.data[cid_len]);
8236 while (cid_len++ < 20)
8237 chunk_appendf(&trash, "..");
8238
8239 chunk_appendf(&trash, "\n");
8240
Frédéric Lécaille5e3201e2023-03-07 15:18:02 +01008241 chunk_appendf(&trash, " loc. TPs:");
8242 quic_transport_params_dump(&trash, qc, &qc->rx.params);
8243 chunk_appendf(&trash, " rem. TPs:");
8244 quic_transport_params_dump(&trash, qc, &qc->tx.params);
8245
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01008246 /* Connection state */
8247 if (qc->flags & QUIC_FL_CONN_CLOSING)
8248 chunk_appendf(&trash, " st=closing ");
8249 else if (qc->flags & QUIC_FL_CONN_DRAINING)
8250 chunk_appendf(&trash, " st=draining ");
8251 else if (qc->state < QUIC_HS_ST_CONFIRMED)
8252 chunk_appendf(&trash, " st=handshake ");
8253 else
8254 chunk_appendf(&trash, " st=opened ");
8255
8256 if (qc->mux_state == QC_MUX_NULL)
8257 chunk_appendf(&trash, "mux=null ");
8258 else if (qc->mux_state == QC_MUX_READY)
8259 chunk_appendf(&trash, "mux=ready ");
8260 else
8261 chunk_appendf(&trash, "mux=released ");
8262
8263 expire = qc->idle_timer_task->expire;
8264 chunk_appendf(&trash, "expire=%02ds ",
8265 expire > now_ms ? (expire - now_ms) / 1000 : 0);
8266
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008267 chunk_appendf(&trash, "\n");
8268
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01008269 /* Socket */
8270 chunk_appendf(&trash, " fd=%d", qc->fd);
8271 if (qc->local_addr.ss_family == AF_INET ||
8272 qc->local_addr.ss_family == AF_INET6) {
8273 addr_to_str(&qc->local_addr, bufaddr, sizeof(bufaddr));
8274 port_to_str(&qc->local_addr, bufport, sizeof(bufport));
8275 chunk_appendf(&trash, " from=%s:%s", bufaddr, bufport);
8276
8277 addr_to_str(&qc->peer_addr, bufaddr, sizeof(bufaddr));
8278 port_to_str(&qc->peer_addr, bufport, sizeof(bufport));
8279 chunk_appendf(&trash, " to=%s:%s", bufaddr, bufport);
8280 }
8281
8282 chunk_appendf(&trash, "\n");
8283
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01008284 /* Encryption levels */
8285 qel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
8286 chunk_appendf(&trash, " [initl] rx.ackrng=%-6zu tx.inflight=%-6zu",
8287 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8288 qel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
8289 chunk_appendf(&trash, " [hndshk] rx.ackrng=%-6zu tx.inflight=%-6zu\n",
8290 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8291 qel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
8292 chunk_appendf(&trash, " [0-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
8293 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8294 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
8295 chunk_appendf(&trash, " [1-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
8296 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8297
8298 chunk_appendf(&trash, "\n");
8299
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008300 /* Streams */
8301 node = eb64_first(&qc->streams_by_id);
8302 i = 0;
8303 while (node) {
8304 stream = eb64_entry(node, struct qc_stream_desc, by_id);
8305 node = eb64_next(node);
8306
Amaury Denoyellea9de25a2023-02-10 09:25:22 +01008307 chunk_appendf(&trash, " | stream=%-8llu", (unsigned long long)stream->by_id.key);
8308 chunk_appendf(&trash, " off=%-8llu ack=%-8llu",
8309 (unsigned long long)stream->buf_offset,
8310 (unsigned long long)stream->ack_offset);
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008311
8312 if (!(++i % 3)) {
8313 chunk_appendf(&trash, "\n");
8314 i = 0;
8315 }
8316 }
8317
8318 chunk_appendf(&trash, "\n");
8319
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008320 if (applet_putchk(appctx, &trash) == -1) {
8321 /* Register show_quic_ctx to quic_conn instance. */
8322 LIST_APPEND(&qc->back_refs, &ctx->bref.users);
8323 goto full;
8324 }
8325
8326 ctx->bref.ref = qc->el_th_ctx.n;
8327 }
8328
8329 done:
8330 thread_release();
8331 return 1;
8332
8333 full:
8334 thread_release();
8335 return 0;
8336}
8337
8338static void cli_release_show_quic(struct appctx *appctx)
8339{
8340 struct show_quic_ctx *ctx = appctx->svcctx;
8341
8342 if (ctx->thr < global.nbthread) {
8343 thread_isolate();
8344 if (!LIST_ISEMPTY(&ctx->bref.users))
8345 LIST_DEL_INIT(&ctx->bref.users);
8346 thread_release();
8347 }
8348}
8349
8350static struct cli_kw_list cli_kws = {{ }, {
8351 { { "show", "quic", NULL }, "show quic : display quic connections status", cli_parse_show_quic, cli_io_handler_dump_quic, cli_release_show_quic },
Frédéric Lécaille91376d62023-02-11 20:24:42 +01008352 {{},}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008353}};
8354
8355INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
8356
8357static void init_quic()
8358{
8359 int thr;
8360
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01008361 for (thr = 0; thr < MAX_THREADS; ++thr) {
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008362 LIST_INIT(&ha_thread_ctx[thr].quic_conns);
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01008363 LIST_INIT(&ha_thread_ctx[thr].quic_conns_clo);
8364 }
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008365}
8366INITCALL0(STG_INIT, init_quic);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008367
8368/*
8369 * Local variables:
8370 * c-indent-level: 8
8371 * c-basic-offset: 8
8372 * End:
8373 */