blob: f6d9a684acaaa41adba960c9e9ccfd00f4186911 [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);
Frédéric Lécailled7215712023-03-24 18:13:37 +0100231static void qc_idle_timer_do_rearm(struct quic_conn *qc, int arm_ack);
232static void qc_idle_timer_rearm(struct quic_conn *qc, int read, int arm_ack);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200233static 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
Frédéric Lécaille8f991942023-03-24 15:14:45 +0100705 if (frm)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200706 chunk_frm_appendf(&trace_buf, frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200707 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +0200708
709 if (mask & QUIC_EV_CONN_ELEVELSEL) {
710 const enum quic_handshake_state *state = a2;
711 const enum quic_tls_enc_level *level = a3;
712 const enum quic_tls_enc_level *next_level = a4;
713
714 if (state)
715 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(qc->state));
716 if (level)
717 chunk_appendf(&trace_buf, " level=%c", quic_enc_level_char(*level));
718 if (next_level)
719 chunk_appendf(&trace_buf, " next_level=%c", quic_enc_level_char(*next_level));
720
721 }
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200722
723 if (mask & QUIC_EV_CONN_RCV) {
724 const struct quic_dgram *dgram = a2;
725
726 if (dgram)
727 chunk_appendf(&trace_buf, " dgram.len=%zu", dgram->len);
728 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200729 }
730 if (mask & QUIC_EV_CONN_LPKT) {
731 const struct quic_rx_packet *pkt = a2;
732 const uint64_t *len = a3;
733 const struct quic_version *ver = a4;
734
735 if (pkt) {
736 chunk_appendf(&trace_buf, " pkt@%p type=0x%02x %s",
737 pkt, pkt->type, qc_pkt_long(pkt) ? "long" : "short");
738 if (pkt->pn_node.key != (uint64_t)-1)
739 chunk_appendf(&trace_buf, " pn=%llu", pkt->pn_node.key);
740 }
741
742 if (len)
743 chunk_appendf(&trace_buf, " len=%llu", (ull)*len);
744
745 if (ver)
746 chunk_appendf(&trace_buf, " ver=0x%08x", ver->num);
747 }
748
749 if (mask & QUIC_EV_STATELESS_RST) {
750 const struct quic_cid *cid = a2;
751
752 if (cid)
753 quic_cid_dump(&trace_buf, cid);
754 }
755
756}
757
758/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
759static inline int quic_peer_validated_addr(struct quic_conn *qc)
760{
761 struct quic_pktns *hdshk_pktns, *app_pktns;
762
763 if (!qc_is_listener(qc))
764 return 1;
765
766 hdshk_pktns = qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns;
767 app_pktns = qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns;
768 if ((hdshk_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
769 (app_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
770 qc->state >= QUIC_HS_ST_COMPLETE)
771 return 1;
772
773 return 0;
774}
775
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100776/* To be called to kill a connection as soon as possible (without sending any packet). */
777void qc_kill_conn(struct quic_conn *qc)
778{
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100779 TRACE_ENTER(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100780 qc->flags |= QUIC_FL_CONN_TO_KILL;
781 task_wakeup(qc->idle_timer_task, TASK_WOKEN_OTHER);
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100782 TRACE_LEAVE(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100783}
784
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200785/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
786 * both loss detection and PTO and schedule the task assiated to this timer if needed.
787 */
788static inline void qc_set_timer(struct quic_conn *qc)
789{
790 struct quic_pktns *pktns;
791 unsigned int pto;
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100792 int handshake_confirmed;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200793
Frédéric Lécaille8f991942023-03-24 15:14:45 +0100794 TRACE_ENTER(QUIC_EV_CONN_STIMER, qc);
795 TRACE_PROTO("set timer", QUIC_EV_CONN_STIMER, qc, NULL, NULL, &qc->path->ifae_pkts);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200796
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100797 pktns = NULL;
798 if (!qc->timer_task) {
799 TRACE_PROTO("already released timer task", QUIC_EV_CONN_STIMER, qc);
800 goto leave;
801 }
802
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200803 pktns = quic_loss_pktns(qc);
804 if (tick_isset(pktns->tx.loss_time)) {
805 qc->timer = pktns->tx.loss_time;
806 goto out;
807 }
808
809 /* anti-amplification: the timer must be
810 * cancelled for a server which reached the anti-amplification limit.
811 */
812 if (!quic_peer_validated_addr(qc) &&
813 (qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
814 TRACE_PROTO("anti-amplification reached", QUIC_EV_CONN_STIMER, qc);
815 qc->timer = TICK_ETERNITY;
816 goto out;
817 }
818
819 if (!qc->path->ifae_pkts && quic_peer_validated_addr(qc)) {
820 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, qc);
821 /* Timer cancellation. */
822 qc->timer = TICK_ETERNITY;
823 goto out;
824 }
825
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100826 handshake_confirmed = qc->state >= QUIC_HS_ST_CONFIRMED;
827 pktns = quic_pto_pktns(qc, handshake_confirmed, &pto);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200828 if (tick_isset(pto))
829 qc->timer = pto;
830 out:
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100831 if (qc->timer == TICK_ETERNITY) {
832 qc->timer_task->expire = TICK_ETERNITY;
833 }
834 else if (tick_is_expired(qc->timer, now_ms)) {
835 TRACE_DEVEL("wakeup asap timer task", QUIC_EV_CONN_STIMER, qc);
836 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
837 }
838 else {
839 TRACE_DEVEL("timer task scheduling", QUIC_EV_CONN_STIMER, qc);
840 task_schedule(qc->timer_task, qc->timer);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200841 }
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100842 leave:
Frédéric Lécaille8f991942023-03-24 15:14:45 +0100843 TRACE_PROTO("set timer", QUIC_EV_CONN_STIMER, qc, pktns);
844 TRACE_LEAVE(QUIC_EV_CONN_STIMER, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200845}
846
847/* Derive new keys and ivs required for Key Update feature for <qc> QUIC
848 * connection.
849 * Return 1 if succeeded, 0 if not.
850 */
851static int quic_tls_key_update(struct quic_conn *qc)
852{
853 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 +0100854 struct quic_tls_secrets *rx = &tls_ctx->rx;
855 struct quic_tls_secrets *tx = &tls_ctx->tx;
856 /* Used only for the traces */
857 struct quic_kp_trace kp_trace = {
858 .rx_sec = rx->secret,
859 .rx_seclen = rx->secretlen,
860 .tx_sec = tx->secret,
861 .tx_seclen = tx->secretlen,
862 };
863 /* The next key phase secrets to be derived */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200864 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
865 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
866 const struct quic_version *ver =
867 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
868 int ret = 0;
869
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100870 TRACE_ENTER(QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200871
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200872 nxt_rx = &qc->ku.nxt_rx;
873 nxt_tx = &qc->ku.nxt_tx;
874
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100875 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
876 "nxt_rx->secretlen=%llu rx->secretlen=%llu",
877 (ull)nxt_rx->secretlen, (ull)rx->secretlen);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200878 /* Prepare new RX secrets */
879 if (!quic_tls_sec_update(rx->md, ver, nxt_rx->secret, nxt_rx->secretlen,
880 rx->secret, rx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100881 TRACE_ERROR("New RX secret update failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200882 goto leave;
883 }
884
885 if (!quic_tls_derive_keys(rx->aead, NULL, rx->md, ver,
886 nxt_rx->key, nxt_rx->keylen,
887 nxt_rx->iv, nxt_rx->ivlen, NULL, 0,
888 nxt_rx->secret, nxt_rx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100889 TRACE_ERROR("New RX key derivation failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200890 goto leave;
891 }
892
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100893 kp_trace.rx = nxt_rx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200894 /* Prepare new TX secrets */
895 if (!quic_tls_sec_update(tx->md, ver, nxt_tx->secret, nxt_tx->secretlen,
896 tx->secret, tx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100897 TRACE_ERROR("New TX secret update failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200898 goto leave;
899 }
900
901 if (!quic_tls_derive_keys(tx->aead, NULL, tx->md, ver,
902 nxt_tx->key, nxt_tx->keylen,
903 nxt_tx->iv, nxt_tx->ivlen, NULL, 0,
904 nxt_tx->secret, nxt_tx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100905 TRACE_ERROR("New TX key derivation failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200906 goto leave;
907 }
908
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100909 kp_trace.tx = nxt_tx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200910 if (nxt_rx->ctx) {
911 EVP_CIPHER_CTX_free(nxt_rx->ctx);
912 nxt_rx->ctx = NULL;
913 }
914
915 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 +0100916 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200917 goto leave;
918 }
919
920 if (nxt_tx->ctx) {
921 EVP_CIPHER_CTX_free(nxt_tx->ctx);
922 nxt_tx->ctx = NULL;
923 }
924
925 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 +0100926 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200927 goto leave;
928 }
929
930 ret = 1;
931 leave:
Frédéric Lécaille8f991942023-03-24 15:14:45 +0100932 TRACE_PROTO("key update", QUIC_EV_CONN_KP, qc, &kp_trace);
933 TRACE_LEAVE(QUIC_EV_CONN_KP, qc);
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{
Frédéric Lécaille8f991942023-03-24 15:14:45 +01001749 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1750 TRACE_PROTO("RX ack TX frm", QUIC_EV_CONN_PRSAFRM, qc, frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001751
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001752 switch (frm->type) {
1753 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1754 {
1755 struct quic_stream *strm_frm = &frm->stream;
1756 struct eb64_node *node = NULL;
1757 struct qc_stream_desc *stream = NULL;
1758 const size_t offset = strm_frm->offset.key;
1759 const size_t len = strm_frm->len;
1760
1761 /* do not use strm_frm->stream as the qc_stream_desc instance
1762 * might be freed at this stage. Use the id to do a proper
1763 * lookup.
1764 *
1765 * TODO if lookup operation impact on the perf is noticeable,
1766 * implement a refcount on qc_stream_desc instances.
1767 */
1768 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1769 if (!node) {
1770 TRACE_DEVEL("acked stream for released stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm);
1771 qc_release_frm(qc, frm);
1772 /* early return */
1773 goto leave;
1774 }
1775 stream = eb64_entry(node, struct qc_stream_desc, by_id);
1776
1777 TRACE_DEVEL("acked stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm, stream);
1778 if (offset <= stream->ack_offset) {
1779 if (qc_stream_desc_ack(&stream, offset, len)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001780 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1781 qc, strm_frm, stream);
1782 }
1783
1784 if (!stream) {
1785 /* no need to continue if stream freed. */
1786 TRACE_DEVEL("stream released and freed", QUIC_EV_CONN_ACKSTRM, qc);
1787 qc_release_frm(qc, frm);
1788 qc_check_close_on_released_mux(qc);
1789 break;
1790 }
1791
1792 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1793 qc, strm_frm, stream);
1794 qc_release_frm(qc, frm);
1795 }
1796 else {
1797 eb64_insert(&stream->acked_frms, &strm_frm->offset);
1798 }
1799
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01001800 quic_stream_try_to_consume(qc, stream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001801 }
1802 break;
1803 default:
1804 qc_release_frm(qc, frm);
1805 }
1806
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001807 leave:
1808 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1809}
1810
1811/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1812 * deallocating them, and their TX frames.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001813 * May be NULL if <largest> node could not be found.
1814 */
Frédéric Lécaillec664e642023-03-15 17:21:13 +01001815static inline void 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)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001821{
1822 struct eb64_node *node;
1823 struct quic_tx_packet *pkt;
1824
1825 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1826
Frédéric Lécaillec664e642023-03-15 17:21:13 +01001827 node = eb64_lookup_ge(pkts, smallest);
1828 if (!node)
1829 goto leave;
1830
1831 largest_node = largest_node ? largest_node : eb64_lookup_le(pkts, largest);
1832 if (!largest_node)
1833 goto leave;
1834
1835 while (node && node->key <= largest_node->key) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001836 struct quic_frame *frm, *frmbak;
1837
1838 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
1839 *pkt_flags |= pkt->flags;
1840 LIST_INSERT(newly_acked_pkts, &pkt->list);
1841 TRACE_DEVEL("Removing packet #", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
1842 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1843 qc_treat_acked_tx_frm(qc, frm);
Frédéric Lécaille814645f2022-11-18 18:15:28 +01001844 /* If there are others packet in the same datagram <pkt> is attached to,
1845 * detach the previous one and the next one from <pkt>.
1846 */
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01001847 quic_tx_packet_dgram_detach(pkt);
Frédéric Lécaillec664e642023-03-15 17:21:13 +01001848 node = eb64_next(node);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001849 eb64_delete(&pkt->pn_node);
1850 }
1851
Frédéric Lécaillec664e642023-03-15 17:21:13 +01001852 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001853 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001854}
1855
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001856/* Remove all frames from <pkt_frm_list> and reinsert them in the same order
1857 * they have been sent into <pktns_frm_list>. The loss counter of each frame is
1858 * incremented and checked if it does not exceed retransmission limit.
1859 *
1860 * Returns 1 on success, 0 if a frame loss limit is exceeded. A
1861 * CONNECTION_CLOSE is scheduled in this case.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001862 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001863static inline int qc_requeue_nacked_pkt_tx_frms(struct quic_conn *qc,
1864 struct quic_tx_packet *pkt,
1865 struct list *pktns_frm_list)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001866{
1867 struct quic_frame *frm, *frmbak;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001868 struct list *pkt_frm_list = &pkt->frms;
1869 uint64_t pn = pkt->pn_node.key;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001870 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001871
1872 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1873
1874 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
1875 /* First remove this frame from the packet it was attached to */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001876 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001877 quic_tx_packet_refdec(pkt);
1878 /* At this time, this frame is not freed but removed from its packet */
1879 frm->pkt = NULL;
1880 /* Remove any reference to this frame */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001881 qc_frm_unref(frm, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001882 switch (frm->type) {
1883 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1884 {
1885 struct quic_stream *strm_frm = &frm->stream;
1886 struct eb64_node *node = NULL;
1887 struct qc_stream_desc *stream_desc;
1888
1889 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1890 if (!node) {
1891 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
1892 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1893 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001894 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001895 continue;
1896 }
1897
1898 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
1899 /* Do not resend this frame if in the "already acked range" */
1900 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
1901 TRACE_DEVEL("ignored frame in already acked range",
1902 QUIC_EV_CONN_PRSAFRM, qc, frm);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001903 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001904 continue;
1905 }
1906 else if (strm_frm->offset.key < stream_desc->ack_offset) {
Frédéric Lécailleca079792023-03-17 08:56:50 +01001907 uint64_t diff = stream_desc->ack_offset - strm_frm->offset.key;
1908
Frédéric Lécaillec425e032023-03-20 14:32:59 +01001909 qc_stream_frm_mv_fwd(frm, diff);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001910 TRACE_DEVEL("updated partially acked frame",
1911 QUIC_EV_CONN_PRSAFRM, qc, frm);
1912 }
1913 break;
1914 }
1915
1916 default:
1917 break;
1918 }
1919
1920 /* Do not resend probing packet with old data */
1921 if (pkt->flags & QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA) {
1922 TRACE_DEVEL("ignored frame with old data from packet", QUIC_EV_CONN_PRSAFRM,
1923 qc, frm, &pn);
1924 if (frm->origin)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001925 LIST_DEL_INIT(&frm->ref);
1926 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001927 continue;
1928 }
1929
1930 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
1931 TRACE_DEVEL("already acked frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
1932 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1933 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001934 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001935 }
1936 else {
Amaury Denoyelle24d5b722023-01-31 11:44:50 +01001937 if (++frm->loss_count >= global.tune.quic_max_frame_loss) {
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001938 TRACE_ERROR("retransmission limit reached, closing the connection", QUIC_EV_CONN_PRSAFRM, qc);
1939 quic_set_connection_close(qc, quic_err_transport(QC_ERR_INTERNAL_ERROR));
1940 close = 1;
1941 }
1942
Frédéric Lécaillebe795ce2023-03-08 18:23:13 +01001943 LIST_APPEND(pktns_frm_list, &frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001944 TRACE_DEVEL("frame requeued", QUIC_EV_CONN_PRSAFRM, qc, frm);
1945 }
1946 }
1947
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001948 end:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001949 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001950 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001951}
1952
1953/* Free <pkt> TX packet and its attached frames.
1954 * This is the responsibility of the caller to remove this packet of
1955 * any data structure it was possibly attached to.
1956 */
1957static inline void free_quic_tx_packet(struct quic_conn *qc,
1958 struct quic_tx_packet *pkt)
1959{
1960 struct quic_frame *frm, *frmbak;
1961
1962 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1963
1964 if (!pkt)
1965 goto leave;
1966
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001967 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1968 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001969 pool_free(pool_head_quic_tx_packet, pkt);
1970
1971 leave:
1972 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1973}
1974
1975/* Free the TX packets of <pkts> list */
1976static inline void free_quic_tx_pkts(struct quic_conn *qc, struct list *pkts)
1977{
1978 struct quic_tx_packet *pkt, *tmp;
1979
1980 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1981
1982 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1983 LIST_DELETE(&pkt->list);
1984 eb64_delete(&pkt->pn_node);
1985 free_quic_tx_packet(qc, pkt);
1986 }
1987
1988 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1989}
1990
1991/* Remove already sent ranges of acknowledged packet numbers from
1992 * <pktns> packet number space tree below <largest_acked_pn> possibly
1993 * updating the range which contains <largest_acked_pn>.
1994 * Never fails.
1995 */
1996static void qc_treat_ack_of_ack(struct quic_conn *qc,
1997 struct quic_pktns *pktns,
1998 int64_t largest_acked_pn)
1999{
2000 struct eb64_node *ar, *next_ar;
2001 struct quic_arngs *arngs = &pktns->rx.arngs;
2002
2003 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2004
2005 ar = eb64_first(&arngs->root);
2006 while (ar) {
2007 struct quic_arng_node *ar_node;
2008
2009 next_ar = eb64_next(ar);
2010 ar_node = eb64_entry(ar, struct quic_arng_node, first);
2011
2012 if ((int64_t)ar_node->first.key > largest_acked_pn) {
2013 TRACE_DEVEL("first.key > largest", QUIC_EV_CONN_PRSAFRM, qc);
2014 break;
2015 }
2016
2017 if (largest_acked_pn < ar_node->last) {
2018 eb64_delete(ar);
2019 ar_node->first.key = largest_acked_pn + 1;
2020 eb64_insert(&arngs->root, ar);
2021 break;
2022 }
2023
2024 eb64_delete(ar);
2025 pool_free(pool_head_quic_arng, ar_node);
2026 arngs->sz--;
2027 ar = next_ar;
2028 }
2029
2030 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2031}
2032
2033/* Send a packet ack event nofication for each newly acked packet of
2034 * <newly_acked_pkts> list and free them.
2035 * Always succeeds.
2036 */
2037static inline void qc_treat_newly_acked_pkts(struct quic_conn *qc,
2038 struct list *newly_acked_pkts)
2039{
2040 struct quic_tx_packet *pkt, *tmp;
2041 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
2042
2043 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2044
2045 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
2046 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2047 qc->path->prep_in_flight -= pkt->in_flight_len;
2048 qc->path->in_flight -= pkt->in_flight_len;
2049 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2050 qc->path->ifae_pkts--;
2051 /* If this packet contained an ACK frame, proceed to the
2052 * acknowledging of range of acks from the largest acknowledged
2053 * packet number which was sent in an ACK frame by this packet.
2054 */
2055 if (pkt->largest_acked_pn != -1)
2056 qc_treat_ack_of_ack(qc, pkt->pktns, pkt->largest_acked_pn);
2057 ev.ack.acked = pkt->in_flight_len;
2058 ev.ack.time_sent = pkt->time_sent;
2059 quic_cc_event(&qc->path->cc, &ev);
2060 LIST_DELETE(&pkt->list);
2061 eb64_delete(&pkt->pn_node);
2062 quic_tx_packet_refdec(pkt);
2063 }
2064
2065 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2066
2067}
2068
2069/* Release all the frames attached to <pktns> packet number space */
2070static inline void qc_release_pktns_frms(struct quic_conn *qc,
2071 struct quic_pktns *pktns)
2072{
2073 struct quic_frame *frm, *frmbak;
2074
2075 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
2076
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01002077 list_for_each_entry_safe(frm, frmbak, &pktns->tx.frms, list)
2078 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002079
2080 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
2081}
2082
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002083/* Handle <pkts> list of lost packets detected at <now_us> handling their TX
2084 * frames. Send a packet loss event to the congestion controller if in flight
2085 * packet have been lost. Also frees the packet in <pkts> list.
2086 *
2087 * Returns 1 on success else 0 if loss limit has been exceeded. A
2088 * CONNECTION_CLOSE was prepared to close the connection ASAP.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002089 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002090static inline int qc_release_lost_pkts(struct quic_conn *qc,
2091 struct quic_pktns *pktns,
2092 struct list *pkts,
2093 uint64_t now_us)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002094{
2095 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002096 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002097
2098 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2099
2100 if (LIST_ISEMPTY(pkts))
2101 goto leave;
2102
2103 oldest_lost = newest_lost = NULL;
2104 list_for_each_entry_safe(pkt, tmp, pkts, list) {
2105 struct list tmp = LIST_HEAD_INIT(tmp);
2106
2107 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2108 qc->path->prep_in_flight -= pkt->in_flight_len;
2109 qc->path->in_flight -= pkt->in_flight_len;
2110 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2111 qc->path->ifae_pkts--;
2112 /* Treat the frames of this lost packet. */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002113 if (!qc_requeue_nacked_pkt_tx_frms(qc, pkt, &pktns->tx.frms))
2114 close = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002115 LIST_DELETE(&pkt->list);
2116 if (!oldest_lost) {
2117 oldest_lost = newest_lost = pkt;
2118 }
2119 else {
2120 if (newest_lost != oldest_lost)
2121 quic_tx_packet_refdec(newest_lost);
2122 newest_lost = pkt;
2123 }
2124 }
2125
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002126 if (!close) {
2127 if (newest_lost) {
2128 /* Sent a congestion event to the controller */
2129 struct quic_cc_event ev = { };
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002130
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002131 ev.type = QUIC_CC_EVT_LOSS;
2132 ev.loss.time_sent = newest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002133
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002134 quic_cc_event(&qc->path->cc, &ev);
2135 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002136
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002137 /* If an RTT have been already sampled, <rtt_min> has been set.
2138 * We must check if we are experiencing a persistent congestion.
2139 * If this is the case, the congestion controller must re-enter
2140 * slow start state.
2141 */
2142 if (qc->path->loss.rtt_min && newest_lost != oldest_lost) {
2143 unsigned int period = newest_lost->time_sent - oldest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002144
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002145 if (quic_loss_persistent_congestion(&qc->path->loss, period,
2146 now_ms, qc->max_ack_delay))
2147 qc->path->cc.algo->slow_start(&qc->path->cc);
2148 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002149 }
2150
Amaury Denoyelle3a72ba22022-11-14 11:41:34 +01002151 /* <oldest_lost> cannot be NULL at this stage because we have ensured
2152 * that <pkts> list is not empty. Without this, GCC 12.2.0 reports a
2153 * possible overflow on a 0 byte region with O2 optimization.
2154 */
2155 ALREADY_CHECKED(oldest_lost);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002156 quic_tx_packet_refdec(oldest_lost);
2157 if (newest_lost != oldest_lost)
2158 quic_tx_packet_refdec(newest_lost);
2159
2160 leave:
2161 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002162 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002163}
2164
2165/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
2166 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
2167 * if the largest acked packet was newly acked and if there was at least one newly
2168 * acked ack-eliciting packet.
2169 * Return 1, if succeeded, 0 if not.
2170 */
2171static inline int qc_parse_ack_frm(struct quic_conn *qc,
2172 struct quic_frame *frm,
2173 struct quic_enc_level *qel,
2174 unsigned int *rtt_sample,
2175 const unsigned char **pos, const unsigned char *end)
2176{
2177 struct quic_ack *ack = &frm->ack;
2178 uint64_t smallest, largest;
2179 struct eb_root *pkts;
2180 struct eb64_node *largest_node;
2181 unsigned int time_sent, pkt_flags;
2182 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
2183 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2184 int ret = 0;
2185
2186 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2187
2188 if (ack->largest_ack > qel->pktns->tx.next_pn) {
2189 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
2190 qc, NULL, &ack->largest_ack);
2191 goto err;
2192 }
2193
2194 if (ack->first_ack_range > ack->largest_ack) {
2195 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
2196 qc, NULL, &ack->first_ack_range);
2197 goto err;
2198 }
2199
2200 largest = ack->largest_ack;
2201 smallest = largest - ack->first_ack_range;
2202 pkts = &qel->pktns->tx.pkts;
2203 pkt_flags = 0;
2204 largest_node = NULL;
2205 time_sent = 0;
2206
2207 if ((int64_t)ack->largest_ack > qel->pktns->rx.largest_acked_pn) {
2208 largest_node = eb64_lookup(pkts, largest);
2209 if (!largest_node) {
2210 TRACE_DEVEL("Largest acked packet not found",
2211 QUIC_EV_CONN_PRSAFRM, qc);
2212 }
2213 else {
2214 time_sent = eb64_entry(largest_node,
2215 struct quic_tx_packet, pn_node)->time_sent;
2216 }
2217 }
2218
Frédéric Lécaille8f991942023-03-24 15:14:45 +01002219 TRACE_PROTO("RX ack range", QUIC_EV_CONN_PRSAFRM,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002220 qc, NULL, &largest, &smallest);
2221 do {
2222 uint64_t gap, ack_range;
2223
2224 qc_ackrng_pkts(qc, pkts, &pkt_flags, &newly_acked_pkts,
2225 largest_node, largest, smallest);
2226 if (!ack->ack_range_num--)
2227 break;
2228
2229 if (!quic_dec_int(&gap, pos, end)) {
2230 TRACE_ERROR("quic_dec_int(gap) failed", QUIC_EV_CONN_PRSAFRM, qc);
2231 goto err;
2232 }
2233
2234 if (smallest < gap + 2) {
2235 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
2236 qc, NULL, &gap, &smallest);
2237 goto err;
2238 }
2239
2240 largest = smallest - gap - 2;
2241 if (!quic_dec_int(&ack_range, pos, end)) {
2242 TRACE_ERROR("quic_dec_int(ack_range) failed", QUIC_EV_CONN_PRSAFRM, qc);
2243 goto err;
2244 }
2245
2246 if (largest < ack_range) {
2247 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
2248 qc, NULL, &largest, &ack_range);
2249 goto err;
2250 }
2251
2252 /* Do not use this node anymore. */
2253 largest_node = NULL;
2254 /* Next range */
2255 smallest = largest - ack_range;
2256
Frédéric Lécaille8f991942023-03-24 15:14:45 +01002257 TRACE_PROTO("RX next ack range", QUIC_EV_CONN_PRSAFRM,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002258 qc, NULL, &largest, &smallest);
2259 } while (1);
2260
2261 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
2262 *rtt_sample = tick_remain(time_sent, now_ms);
2263 qel->pktns->rx.largest_acked_pn = ack->largest_ack;
2264 }
2265
2266 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
2267 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
2268 qc_packet_loss_lookup(qel->pktns, qc, &lost_pkts);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002269 if (!qc_release_lost_pkts(qc, qel->pktns, &lost_pkts, now_ms))
2270 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002271 }
2272 qc_treat_newly_acked_pkts(qc, &newly_acked_pkts);
2273 if (quic_peer_validated_addr(qc))
2274 qc->path->loss.pto_count = 0;
2275 qc_set_timer(qc);
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01002276 qc_notify_send(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002277 }
2278
2279 ret = 1;
2280 leave:
2281 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2282 return ret;
2283
2284 err:
2285 free_quic_tx_pkts(qc, &newly_acked_pkts);
2286 goto leave;
2287}
2288
2289/* This function gives the detail of the SSL error. It is used only
2290 * if the debug mode and the verbose mode are activated. It dump all
2291 * the SSL error until the stack was empty.
2292 */
2293static forceinline void qc_ssl_dump_errors(struct connection *conn)
2294{
2295 if (unlikely(global.mode & MODE_DEBUG)) {
2296 while (1) {
2297 const char *func = NULL;
2298 unsigned long ret;
2299
2300 ERR_peek_error_func(&func);
2301 ret = ERR_get_error();
2302 if (!ret)
2303 return;
2304
2305 fprintf(stderr, "conn. @%p OpenSSL error[0x%lx] %s: %s\n", conn, ret,
2306 func, ERR_reason_error_string(ret));
2307 }
2308 }
2309}
2310
2311int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx,
2312 const char **str, int *len);
2313
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002314/* Finalize <qc> QUIC connection:
2315 * - initialize the Initial QUIC TLS context for negotiated version,
2316 * - derive the secrets for this context,
2317 * - set them into the TLS stack,
2318 *
2319 * MUST be called after having received the remote transport parameters which
2320 * are parsed when the TLS callback for the ClientHello message is called upon
2321 * SSL_do_handshake() calls, not necessarily at the first time as this TLS
2322 * message may be splitted between packets
2323 * Return 1 if succeeded, 0 if not.
2324 */
2325static int qc_conn_finalize(struct quic_conn *qc, int server)
2326{
2327 int ret = 0;
2328
2329 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
2330
2331 if (qc->flags & QUIC_FL_CONN_FINALIZED)
2332 goto finalized;
2333
2334 if (qc->negotiated_version &&
2335 !qc_new_isecs(qc, &qc->negotiated_ictx, qc->negotiated_version,
2336 qc->odcid.data, qc->odcid.len, server))
2337 goto out;
2338
2339 /* This connection is functional (ready to send/receive) */
2340 qc->flags |= QUIC_FL_CONN_FINALIZED;
2341
2342 finalized:
2343 ret = 1;
2344 out:
2345 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
2346 return ret;
2347}
2348
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002349/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
2350 * from <qel> encryption level with <ctx> as QUIC connection context.
2351 * Remaining parameter are there for debugging purposes.
2352 * Return 1 if succeeded, 0 if not.
2353 */
2354static inline int qc_provide_cdata(struct quic_enc_level *el,
2355 struct ssl_sock_ctx *ctx,
2356 const unsigned char *data, size_t len,
2357 struct quic_rx_packet *pkt,
2358 struct quic_rx_crypto_frm *cf)
2359{
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002360#ifdef DEBUG_STRICT
2361 enum ncb_ret ncb_ret;
2362#endif
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002363 int ssl_err, state;
2364 struct quic_conn *qc;
2365 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002366 struct ncbuf *ncbuf = &el->cstream->rx.ncbuf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002367
2368 ssl_err = SSL_ERROR_NONE;
2369 qc = ctx->qc;
2370
2371 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, qc);
2372
2373 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
2374 TRACE_ERROR("SSL_provide_quic_data() error",
2375 QUIC_EV_CONN_SSLDATA, qc, pkt, cf, ctx->ssl);
2376 goto leave;
2377 }
2378
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002379 TRACE_PROTO("in order CRYPTO data",
2380 QUIC_EV_CONN_SSLDATA, qc, NULL, cf, ctx->ssl);
2381
2382 state = qc->state;
2383 if (state < QUIC_HS_ST_COMPLETE) {
2384 ssl_err = SSL_do_handshake(ctx->ssl);
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002385
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01002386 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
2387 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
2388 goto leave;
2389 }
2390
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002391 /* Finalize the connection as soon as possible if the peer transport parameters
2392 * have been received. This may be useful to send packets even if this
2393 * handshake fails.
2394 */
2395 if ((qc->flags & QUIC_FL_CONN_TX_TP_RECEIVED) && !qc_conn_finalize(qc, 1)) {
2396 TRACE_ERROR("connection finalization failed", QUIC_EV_CONN_IO_CB, qc, &state);
2397 goto leave;
2398 }
2399
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002400 if (ssl_err != 1) {
2401 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2402 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2403 TRACE_PROTO("SSL handshake in progress",
2404 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2405 goto out;
2406 }
2407
2408 /* TODO: Should close the connection asap */
2409 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2410 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2411 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2412 HA_ATOMIC_INC(&qc->prx_counters->hdshk_fail);
2413 }
2414 TRACE_ERROR("SSL handshake error", QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2415 qc_ssl_dump_errors(ctx->conn);
2416 ERR_clear_error();
2417 goto leave;
2418 }
2419
2420 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_IO_CB, qc, &state);
2421
2422 /* Check the alpn could be negotiated */
2423 if (!qc->app_ops) {
2424 TRACE_ERROR("No negotiated ALPN", QUIC_EV_CONN_IO_CB, qc, &state);
2425 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
2426 goto leave;
2427 }
2428
2429 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2430 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_IO_CB, qc, &state);
2431 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2432 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2433 }
2434 /* I/O callback switch */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002435 qc->wait_event.tasklet->process = quic_conn_app_io_cb;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002436 if (qc_is_listener(ctx->qc)) {
2437 qc->state = QUIC_HS_ST_CONFIRMED;
2438 /* The connection is ready to be accepted. */
2439 quic_accept_push_qc(qc);
2440 }
2441 else {
2442 qc->state = QUIC_HS_ST_COMPLETE;
2443 }
2444
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02002445 /* Prepare the next key update */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002446 if (!quic_tls_key_update(qc)) {
2447 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_IO_CB, qc);
2448 goto leave;
2449 }
2450 } else {
2451 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
2452 if (ssl_err != 1) {
2453 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2454 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2455 TRACE_PROTO("SSL post handshake in progress",
2456 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2457 goto out;
2458 }
2459
2460 TRACE_ERROR("SSL post handshake error",
2461 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2462 goto leave;
2463 }
2464
2465 TRACE_STATE("SSL post handshake succeeded", QUIC_EV_CONN_IO_CB, qc, &state);
2466 }
2467
2468 out:
2469 ret = 1;
2470 leave:
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002471 /* The CRYPTO data are consumed even in case of an error to release
2472 * the memory asap.
2473 */
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002474 if (!ncb_is_null(ncbuf)) {
2475#ifdef DEBUG_STRICT
2476 ncb_ret = ncb_advance(ncbuf, len);
2477 /* ncb_advance() must always succeed. This is guaranteed as
2478 * this is only done inside a data block. If false, this will
2479 * lead to handshake failure with quic_enc_level offset shifted
2480 * from buffer data.
2481 */
2482 BUG_ON(ncb_ret != NCB_RET_OK);
2483#else
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002484 ncb_advance(ncbuf, len);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002485#endif
2486 }
2487
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002488 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, qc);
2489 return ret;
2490}
2491
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002492/* Parse a STREAM frame <strm_frm> received in <pkt> packet for <qc>
2493 * connection. <fin> is true if FIN bit is set on frame type.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002494 *
2495 * Return 1 on success. On error, 0 is returned. In this case, the packet
2496 * containing the frame must not be acknowledged.
2497 */
2498static inline int qc_handle_strm_frm(struct quic_rx_packet *pkt,
2499 struct quic_stream *strm_frm,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002500 struct quic_conn *qc, char fin)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002501{
2502 int ret;
2503
2504 /* RFC9000 13.1. Packet Processing
2505 *
2506 * A packet MUST NOT be acknowledged until packet protection has been
2507 * successfully removed and all frames contained in the packet have
2508 * been processed. For STREAM frames, this means the data has been
2509 * enqueued in preparation to be received by the application protocol,
2510 * but it does not require that data be delivered and consumed.
2511 */
2512 TRACE_ENTER(QUIC_EV_CONN_PRSFRM, qc);
2513
2514 ret = qcc_recv(qc->qcc, strm_frm->id, strm_frm->len,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002515 strm_frm->offset.key, fin, (char *)strm_frm->data);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002516
2517 /* frame rejected - packet must not be acknowledeged */
2518 TRACE_LEAVE(QUIC_EV_CONN_PRSFRM, qc);
2519 return !ret;
2520}
2521
2522/* Duplicate all frames from <pkt_frm_list> list into <out_frm_list> list
2523 * for <qc> QUIC connection.
2524 * This is a best effort function which never fails even if no memory could be
2525 * allocated to duplicate these frames.
2526 */
2527static void qc_dup_pkt_frms(struct quic_conn *qc,
2528 struct list *pkt_frm_list, struct list *out_frm_list)
2529{
2530 struct quic_frame *frm, *frmbak;
2531 struct list tmp = LIST_HEAD_INIT(tmp);
2532
2533 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2534
2535 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
2536 struct quic_frame *dup_frm, *origin;
2537
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002538 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
2539 TRACE_DEVEL("already acknowledged frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2540 continue;
2541 }
2542
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002543 switch (frm->type) {
2544 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2545 {
2546 struct quic_stream *strm_frm = &frm->stream;
2547 struct eb64_node *node = NULL;
2548 struct qc_stream_desc *stream_desc;
2549
2550 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
2551 if (!node) {
2552 TRACE_DEVEL("ignored frame for a released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
2553 continue;
2554 }
2555
2556 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
2557 /* Do not resend this frame if in the "already acked range" */
2558 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
2559 TRACE_DEVEL("ignored frame in already acked range",
2560 QUIC_EV_CONN_PRSAFRM, qc, frm);
2561 continue;
2562 }
2563 else if (strm_frm->offset.key < stream_desc->ack_offset) {
Frédéric Lécailleca079792023-03-17 08:56:50 +01002564 uint64_t diff = stream_desc->ack_offset - strm_frm->offset.key;
2565
Frédéric Lécaillec425e032023-03-20 14:32:59 +01002566 qc_stream_frm_mv_fwd(frm, diff);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002567 TRACE_DEVEL("updated partially acked frame",
2568 QUIC_EV_CONN_PRSAFRM, qc, frm);
2569 }
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01002570
2571 strm_frm->dup = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002572 break;
2573 }
2574
2575 default:
2576 break;
2577 }
2578
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002579 /* If <frm> is already a copy of another frame, we must take
2580 * its original frame as source for the copy.
2581 */
2582 origin = frm->origin ? frm->origin : frm;
2583 dup_frm = qc_frm_dup(origin);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002584 if (!dup_frm) {
2585 TRACE_ERROR("could not duplicate frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2586 break;
2587 }
2588
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002589 TRACE_DEVEL("built probing frame", QUIC_EV_CONN_PRSAFRM, qc, origin);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002590 if (origin->pkt) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002591 TRACE_DEVEL("duplicated from packet", QUIC_EV_CONN_PRSAFRM,
2592 qc, NULL, &origin->pkt->pn_node.key);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002593 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002594 else {
2595 /* <origin> is a frame which was sent from a packet detected as lost. */
2596 TRACE_DEVEL("duplicated from lost packet", QUIC_EV_CONN_PRSAFRM, qc);
2597 }
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002598
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002599 LIST_APPEND(&tmp, &dup_frm->list);
2600 }
2601
2602 LIST_SPLICE(out_frm_list, &tmp);
2603
2604 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2605}
2606
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002607/* Boolean function which return 1 if <pkt> TX packet is only made of
2608 * already acknowledged frame.
2609 */
2610static inline int qc_pkt_with_only_acked_frms(struct quic_tx_packet *pkt)
2611{
2612 struct quic_frame *frm;
2613
2614 list_for_each_entry(frm, &pkt->frms, list)
2615 if (!(frm->flags & QUIC_FL_TX_FRAME_ACKED))
2616 return 0;
2617
2618 return 1;
2619}
2620
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002621/* Prepare a fast retransmission from <qel> encryption level */
2622static void qc_prep_fast_retrans(struct quic_conn *qc,
2623 struct quic_enc_level *qel,
2624 struct list *frms1, struct list *frms2)
2625{
2626 struct eb_root *pkts = &qel->pktns->tx.pkts;
2627 struct list *frms = frms1;
2628 struct eb64_node *node;
2629 struct quic_tx_packet *pkt;
2630
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002631 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002632
2633 BUG_ON(frms1 == frms2);
2634
2635 pkt = NULL;
2636 node = eb64_first(pkts);
2637 start:
2638 while (node) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002639 struct quic_tx_packet *p;
2640
2641 p = eb64_entry(node, struct quic_tx_packet, pn_node);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002642 node = eb64_next(node);
2643 /* Skip the empty and coalesced packets */
Frédéric Lécaille8f991942023-03-24 15:14:45 +01002644 TRACE_PRINTF(TRACE_LEVEL_PROTO, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002645 "--> pn=%llu (%d %d %d)", (ull)p->pn_node.key,
2646 LIST_ISEMPTY(&p->frms), !!(p->flags & QUIC_FL_TX_PACKET_COALESCED),
2647 qc_pkt_with_only_acked_frms(p));
2648 if (!LIST_ISEMPTY(&p->frms) && !qc_pkt_with_only_acked_frms(p)) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002649 pkt = p;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002650 break;
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002651 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002652 }
2653
2654 if (!pkt)
2655 goto leave;
2656
2657 /* When building a packet from another one, the field which may increase the
2658 * packet size is the packet number. And the maximum increase is 4 bytes.
2659 */
2660 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2661 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01002662 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002663 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2664 goto leave;
2665 }
2666
Frédéric Lécaille8f991942023-03-24 15:14:45 +01002667 TRACE_PROTO("duplicating packet", QUIC_EV_CONN_SPPKTS, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002668 qc_dup_pkt_frms(qc, &pkt->frms, frms);
2669 if (frms == frms1 && frms2) {
2670 frms = frms2;
2671 goto start;
2672 }
2673 leave:
2674 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
2675}
2676
2677/* Prepare a fast retransmission during a handshake after a client
2678 * has resent Initial packets. According to the RFC a server may retransmit
2679 * Initial packets send them coalescing with others (Handshake here).
2680 * (Listener only function).
2681 */
2682static void qc_prep_hdshk_fast_retrans(struct quic_conn *qc,
2683 struct list *ifrms, struct list *hfrms)
2684{
2685 struct list itmp = LIST_HEAD_INIT(itmp);
2686 struct list htmp = LIST_HEAD_INIT(htmp);
2687
2688 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2689 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2690 struct quic_enc_level *qel = iqel;
2691 struct eb_root *pkts;
2692 struct eb64_node *node;
2693 struct quic_tx_packet *pkt;
2694 struct list *tmp = &itmp;
2695
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002696 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002697 start:
2698 pkt = NULL;
2699 pkts = &qel->pktns->tx.pkts;
2700 node = eb64_first(pkts);
2701 /* Skip the empty packet (they have already been retransmitted) */
2702 while (node) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002703 struct quic_tx_packet *p;
2704
2705 p = eb64_entry(node, struct quic_tx_packet, pn_node);
Frédéric Lécaille8f991942023-03-24 15:14:45 +01002706 TRACE_PRINTF(TRACE_LEVEL_PROTO, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002707 "--> pn=%llu (%d %d)", (ull)p->pn_node.key,
2708 LIST_ISEMPTY(&p->frms), !!(p->flags & QUIC_FL_TX_PACKET_COALESCED));
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002709 if (!LIST_ISEMPTY(&p->frms) && !(p->flags & QUIC_FL_TX_PACKET_COALESCED) &&
2710 !qc_pkt_with_only_acked_frms(p)) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002711 pkt = p;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002712 break;
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002713 }
2714
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002715 node = eb64_next(node);
2716 }
2717
2718 if (!pkt)
2719 goto end;
2720
2721 /* When building a packet from another one, the field which may increase the
2722 * packet size is the packet number. And the maximum increase is 4 bytes.
2723 */
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002724 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
2725 size_t dglen = pkt->len + 4;
2726
2727 dglen += pkt->next ? pkt->next->len + 4 : 0;
2728 if (dglen > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01002729 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002730 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2731 if (pkt->next)
2732 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt->next);
2733 goto end;
2734 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002735 }
2736
2737 qel->pktns->tx.pto_probe += 1;
2738
2739 /* No risk to loop here, #packet per datagram is bounded */
2740 requeue:
Frédéric Lécaille8f991942023-03-24 15:14:45 +01002741 TRACE_PROTO("duplicating packet", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002742 qc_dup_pkt_frms(qc, &pkt->frms, tmp);
2743 if (qel == iqel) {
2744 if (pkt->next && pkt->next->type == QUIC_PACKET_TYPE_HANDSHAKE) {
2745 pkt = pkt->next;
2746 tmp = &htmp;
2747 hqel->pktns->tx.pto_probe += 1;
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002748 TRACE_DEVEL("looping for next packet", QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002749 goto requeue;
2750 }
2751 }
2752
2753 end:
2754 LIST_SPLICE(ifrms, &itmp);
2755 LIST_SPLICE(hfrms, &htmp);
2756
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002757 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002758}
2759
2760static void qc_cc_err_count_inc(struct quic_conn *qc, struct quic_frame *frm)
2761{
2762 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
2763
2764 if (frm->type == QUIC_FT_CONNECTION_CLOSE)
2765 quic_stats_transp_err_count_inc(qc->prx_counters, frm->connection_close.error_code);
2766 else if (frm->type == QUIC_FT_CONNECTION_CLOSE_APP) {
2767 if (qc->mux_state != QC_MUX_READY || !qc->qcc->app_ops->inc_err_cnt)
2768 goto out;
2769
2770 qc->qcc->app_ops->inc_err_cnt(qc->qcc->ctx, frm->connection_close_app.error_code);
2771 }
2772
2773 out:
2774 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
2775}
2776
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002777/* Cancel a request on connection <qc> for stream id <id>. This is useful when
2778 * the client opens a new stream but the MUX has already been released. A
Amaury Denoyelle75463012023-02-20 10:31:27 +01002779 * STOP_SENDING + RESET_STREAM frames are prepared for emission.
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002780 *
2781 * TODO this function is closely related to H3. Its place should be in H3 layer
2782 * instead of quic-conn but this requires an architecture adjustment.
2783 *
2784 * Returns 1 on sucess else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002785 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002786static int qc_h3_request_reject(struct quic_conn *qc, uint64_t id)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002787{
2788 int ret = 0;
Amaury Denoyelle75463012023-02-20 10:31:27 +01002789 struct quic_frame *ss, *rs;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002790 struct quic_enc_level *qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002791 const uint64_t app_error_code = H3_REQUEST_REJECTED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002792
2793 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2794
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002795 /* Do not emit rejection for unknown unidirectional stream as it is
2796 * forbidden to close some of them (H3 control stream and QPACK
2797 * encoder/decoder streams).
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002798 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002799 if (quic_stream_is_uni(id)) {
2800 ret = 1;
2801 goto out;
2802 }
2803
Amaury Denoyelle75463012023-02-20 10:31:27 +01002804 ss = qc_frm_alloc(QUIC_FT_STOP_SENDING);
2805 if (!ss) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002806 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2807 goto out;
2808 }
2809
Amaury Denoyelle75463012023-02-20 10:31:27 +01002810 ss->stop_sending.id = id;
2811 ss->stop_sending.app_error_code = app_error_code;
2812
2813 rs = qc_frm_alloc(QUIC_FT_RESET_STREAM);
2814 if (!rs) {
2815 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2816 qc_frm_free(&ss);
2817 goto out;
2818 }
2819
2820 rs->reset_stream.id = id;
2821 rs->reset_stream.app_error_code = app_error_code;
2822 rs->reset_stream.final_size = 0;
2823
2824 LIST_APPEND(&qel->pktns->tx.frms, &ss->list);
2825 LIST_APPEND(&qel->pktns->tx.frms, &rs->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002826 ret = 1;
2827 out:
2828 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2829 return ret;
2830}
2831
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002832/* Release the underlying memory use by <ncbuf> non-contiguous buffer */
2833static void quic_free_ncbuf(struct ncbuf *ncbuf)
2834{
2835 struct buffer buf;
2836
2837 if (ncb_is_null(ncbuf))
2838 return;
2839
2840 buf = b_make(ncbuf->area, ncbuf->size, 0, 0);
2841 b_free(&buf);
2842 offer_buffers(NULL, 1);
2843
2844 *ncbuf = NCBUF_NULL;
2845}
2846
2847/* Allocate the underlying required memory for <ncbuf> non-contiguous buffer */
2848static struct ncbuf *quic_get_ncbuf(struct ncbuf *ncbuf)
2849{
2850 struct buffer buf = BUF_NULL;
2851
2852 if (!ncb_is_null(ncbuf))
2853 return ncbuf;
2854
2855 b_alloc(&buf);
2856 BUG_ON(b_is_null(&buf));
2857
2858 *ncbuf = ncb_make(buf.area, buf.size, 0);
2859 ncb_init(ncbuf, 0);
2860
2861 return ncbuf;
2862}
2863
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002864/* Parse <frm> CRYPTO frame coming with <pkt> packet at <qel> <qc> connectionn.
2865 * Returns 1 if succeeded, 0 if not. Also set <*fast_retrans> to 1 if the
2866 * speed up handshake completion may be run after having received duplicated
2867 * CRYPTO data.
2868 */
2869static int qc_handle_crypto_frm(struct quic_conn *qc,
2870 struct quic_crypto *frm, struct quic_rx_packet *pkt,
2871 struct quic_enc_level *qel, int *fast_retrans)
2872{
2873 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002874 enum ncb_ret ncb_ret;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002875 /* XXX TO DO: <cfdebug> is used only for the traces. */
2876 struct quic_rx_crypto_frm cfdebug = {
2877 .offset_node.key = frm->offset,
2878 .len = frm->len,
2879 };
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002880 struct quic_cstream *cstream = qel->cstream;
2881 struct ncbuf *ncbuf = &qel->cstream->rx.ncbuf;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002882
2883 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2884 if (unlikely(qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD)) {
2885 TRACE_PROTO("CRYPTO data discarded",
2886 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2887 goto done;
2888 }
2889
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002890 if (unlikely(frm->offset < cstream->rx.offset)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002891 size_t diff;
2892
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002893 if (frm->offset + frm->len <= cstream->rx.offset) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002894 /* Nothing to do */
2895 TRACE_PROTO("Already received CRYPTO data",
2896 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2897 if (qc_is_listener(qc) && qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] &&
2898 !(qc->flags & QUIC_FL_CONN_HANDSHAKE_SPEED_UP))
2899 *fast_retrans = 1;
2900 goto done;
2901 }
2902
2903 TRACE_PROTO("Partially already received CRYPTO data",
2904 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2905
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002906 diff = cstream->rx.offset - frm->offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002907 frm->len -= diff;
2908 frm->data += diff;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002909 frm->offset = cstream->rx.offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002910 }
2911
Amaury Denoyelleff95f2d2022-11-18 14:50:06 +01002912 if (frm->offset == cstream->rx.offset && ncb_is_empty(ncbuf)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002913 if (!qc_provide_cdata(qel, qc->xprt_ctx, frm->data, frm->len,
2914 pkt, &cfdebug)) {
2915 // trace already emitted by function above
2916 goto leave;
2917 }
2918
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002919 cstream->rx.offset += frm->len;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002920 TRACE_DEVEL("increment crypto level offset", QUIC_EV_CONN_PHPKTS, qc, qel);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002921 goto done;
2922 }
2923
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002924 if (!quic_get_ncbuf(ncbuf) ||
2925 ncb_is_null(ncbuf)) {
2926 TRACE_ERROR("CRYPTO ncbuf allocation failed", QUIC_EV_CONN_PRSHPKT, qc);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002927 goto leave;
2928 }
2929
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002930 /* frm->offset > cstream-trx.offset */
2931 ncb_ret = ncb_add(ncbuf, frm->offset - cstream->rx.offset,
2932 (const char *)frm->data, frm->len, NCB_ADD_COMPARE);
2933 if (ncb_ret != NCB_RET_OK) {
2934 if (ncb_ret == NCB_RET_DATA_REJ) {
2935 TRACE_ERROR("overlapping data rejected", QUIC_EV_CONN_PRSHPKT, qc);
2936 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
2937 }
2938 else if (ncb_ret == NCB_RET_GAP_SIZE) {
2939 TRACE_ERROR("cannot bufferize frame due to gap size limit",
2940 QUIC_EV_CONN_PRSHPKT, qc);
2941 }
2942 goto leave;
2943 }
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002944
2945 done:
2946 ret = 1;
2947 leave:
2948 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2949 return ret;
2950}
2951
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002952/* Allocate a new connection ID for <qc> connection and build a NEW_CONNECTION_ID
2953 * frame to be sent.
2954 * Return 1 if succeeded, 0 if not.
2955 */
2956static int qc_build_new_connection_id_frm(struct quic_conn *qc,
2957 struct quic_connection_id *cid)
2958{
2959 int ret = 0;
2960 struct quic_frame *frm;
2961 struct quic_enc_level *qel;
2962
2963 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2964
2965 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
2966 frm = qc_frm_alloc(QUIC_FT_NEW_CONNECTION_ID);
2967 if (!frm) {
2968 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
2969 goto leave;
2970 }
2971
2972 quic_connection_id_to_frm_cpy(frm, cid);
2973 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
2974 ret = 1;
2975 leave:
2976 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2977 return ret;
2978}
2979
2980
2981/* Handle RETIRE_CONNECTION_ID frame from <frm> frame.
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002982 * Return 1 if succeeded, 0 if not. If succeeded, also set <cid_to_retire>
2983 * to the CID to be retired if not already retired.
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002984 */
2985static int qc_handle_retire_connection_id_frm(struct quic_conn *qc,
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002986 struct quic_frame *frm,
2987 struct quic_cid *dcid,
2988 struct quic_connection_id **cid_to_retire)
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002989{
2990 int ret = 0;
2991 struct quic_retire_connection_id *rcid = &frm->retire_connection_id;
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002992 struct eb64_node *node;
2993 struct quic_connection_id *cid;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002994
2995 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2996
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002997 /* RFC 9000 19.16. RETIRE_CONNECTION_ID Frames:
2998 * Receipt of a RETIRE_CONNECTION_ID frame containing a sequence number greater
2999 * than any previously sent to the peer MUST be treated as a connection error
3000 * of type PROTOCOL_VIOLATION.
3001 */
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003002 if (rcid->seq_num >= qc->next_cid_seq_num) {
3003 TRACE_PROTO("CID seq. number too big", QUIC_EV_CONN_PSTRM, qc, frm);
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003004 goto protocol_violation;
3005 }
3006
3007 /* RFC 9000 19.16. RETIRE_CONNECTION_ID Frames:
3008 * The sequence number specified in a RETIRE_CONNECTION_ID frame MUST NOT refer to
3009 * the Destination Connection ID field of the packet in which the frame is contained.
3010 * The peer MAY treat this as a connection error of type PROTOCOL_VIOLATION.
3011 */
3012 node = eb64_lookup(&qc->cids, rcid->seq_num);
3013 if (!node) {
3014 TRACE_PROTO("CID already retired", QUIC_EV_CONN_PSTRM, qc, frm);
3015 goto out;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003016 }
3017
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003018 cid = eb64_entry(node, struct quic_connection_id, seq_num);
3019 /* Note that the length of <dcid> has already been checked. It must match the
3020 * length of the CIDs which have been provided to the peer.
3021 */
3022 if (!memcmp(dcid->data, cid->cid.data, QUIC_HAP_CID_LEN)) {
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003023 TRACE_PROTO("cannot retire the current CID", QUIC_EV_CONN_PSTRM, qc, frm);
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003024 goto protocol_violation;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003025 }
3026
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003027 *cid_to_retire = cid;
3028 out:
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003029 ret = 1;
3030 leave:
3031 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
3032 return ret;
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003033 protocol_violation:
3034 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
3035 goto leave;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003036}
3037
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01003038/* Remove a <qc> quic-conn from its ha_thread_ctx list. If <closing> is true,
3039 * it will immediately be reinserted in the ha_thread_ctx quic_conns_clo list.
3040 */
3041static void qc_detach_th_ctx_list(struct quic_conn *qc, int closing)
3042{
3043 struct bref *bref, *back;
3044
3045 /* Detach CLI context watchers currently dumping this connection.
3046 * Reattach them to the next quic_conn instance.
3047 */
3048 list_for_each_entry_safe(bref, back, &qc->back_refs, users) {
3049 /* Remove watcher from this quic_conn instance. */
3050 LIST_DEL_INIT(&bref->users);
3051
3052 /* Attach it to next instance unless it was the last list element. */
3053 if (qc->el_th_ctx.n != &th_ctx->quic_conns &&
3054 qc->el_th_ctx.n != &th_ctx->quic_conns_clo) {
3055 struct quic_conn *next = LIST_NEXT(&qc->el_th_ctx,
3056 struct quic_conn *,
3057 el_th_ctx);
3058 LIST_APPEND(&next->back_refs, &bref->users);
3059 }
3060 bref->ref = qc->el_th_ctx.n;
3061 __ha_barrier_store();
3062 }
3063
3064 /* Remove quic_conn from global ha_thread_ctx list. */
3065 LIST_DEL_INIT(&qc->el_th_ctx);
3066
3067 if (closing)
3068 LIST_APPEND(&th_ctx->quic_conns_clo, &qc->el_th_ctx);
3069}
3070
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003071/* Parse all the frames of <pkt> QUIC packet for QUIC connection <qc> and <qel>
3072 * as encryption level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003073 * Returns 1 if succeeded, 0 if failed.
3074 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003075static int qc_parse_pkt_frms(struct quic_conn *qc, struct quic_rx_packet *pkt,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003076 struct quic_enc_level *qel)
3077{
3078 struct quic_frame frm;
3079 const unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003080 int fast_retrans = 0, ret = 0;
3081
3082 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
3083 /* Skip the AAD */
3084 pos = pkt->data + pkt->aad_len;
3085 end = pkt->data + pkt->len;
3086
3087 while (pos < end) {
3088 if (!qc_parse_frm(&frm, pkt, &pos, end, qc)) {
3089 // trace already emitted by function above
3090 goto leave;
3091 }
3092
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003093 switch (frm.type) {
3094 case QUIC_FT_PADDING:
3095 break;
3096 case QUIC_FT_PING:
3097 break;
3098 case QUIC_FT_ACK:
3099 {
3100 unsigned int rtt_sample;
3101
3102 rtt_sample = 0;
3103 if (!qc_parse_ack_frm(qc, &frm, qel, &rtt_sample, &pos, end)) {
3104 // trace already emitted by function above
3105 goto leave;
3106 }
3107
3108 if (rtt_sample) {
3109 unsigned int ack_delay;
3110
3111 ack_delay = !quic_application_pktns(qel->pktns, qc) ? 0 :
3112 qc->state >= QUIC_HS_ST_CONFIRMED ?
3113 MS_TO_TICKS(QUIC_MIN(quic_ack_delay_ms(&frm.ack, qc), qc->max_ack_delay)) :
3114 MS_TO_TICKS(quic_ack_delay_ms(&frm.ack, qc));
3115 quic_loss_srtt_update(&qc->path->loss, rtt_sample, ack_delay, qc);
3116 }
3117 break;
3118 }
3119 case QUIC_FT_RESET_STREAM:
Amaury Denoyelle5854fc02022-12-09 16:25:48 +01003120 if (qc->mux_state == QC_MUX_READY) {
3121 struct quic_reset_stream *rs = &frm.reset_stream;
3122 qcc_recv_reset_stream(qc->qcc, rs->id, rs->app_error_code, rs->final_size);
3123 }
3124 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003125 case QUIC_FT_STOP_SENDING:
3126 {
3127 struct quic_stop_sending *stop_sending = &frm.stop_sending;
3128 if (qc->mux_state == QC_MUX_READY) {
3129 if (qcc_recv_stop_sending(qc->qcc, stop_sending->id,
3130 stop_sending->app_error_code)) {
3131 TRACE_ERROR("qcc_recv_stop_sending() failed", QUIC_EV_CONN_PRSHPKT, qc);
3132 goto leave;
3133 }
3134 }
3135 break;
3136 }
3137 case QUIC_FT_CRYPTO:
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02003138 if (!qc_handle_crypto_frm(qc, &frm.crypto, pkt, qel, &fast_retrans))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003139 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003140 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003141 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
3142 {
3143 struct quic_stream *stream = &frm.stream;
3144 unsigned nb_streams = qc->rx.strms[qcs_id_type(stream->id)].nb_streams;
Amaury Denoyelle2216b082023-02-02 14:59:36 +01003145 const char fin = frm.type & QUIC_STREAM_FRAME_TYPE_FIN_BIT;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003146
3147 /* The upper layer may not be allocated. */
3148 if (qc->mux_state != QC_MUX_READY) {
3149 if ((stream->id >> QCS_ID_TYPE_SHIFT) < nb_streams) {
3150 TRACE_DATA("Already closed stream", QUIC_EV_CONN_PRSHPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003151 }
3152 else {
3153 TRACE_DEVEL("No mux for new stream", QUIC_EV_CONN_PRSHPKT, qc);
Amaury Denoyelle38836b62023-02-07 14:24:54 +01003154 if (qc->app_ops == &h3_ops) {
Amaury Denoyelle156a89a2023-02-20 10:32:16 +01003155 if (!qc_h3_request_reject(qc, stream->id)) {
3156 TRACE_ERROR("error on request rejection", QUIC_EV_CONN_PRSHPKT, qc);
3157 /* This packet will not be acknowledged */
3158 goto leave;
3159 }
3160 }
3161 else {
3162 /* This packet will not be acknowledged */
3163 goto leave;
Frédéric Lécailled18025e2023-01-20 15:33:50 +01003164 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003165 }
Amaury Denoyelle315a4f62023-03-06 09:10:53 +01003166
3167 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003168 }
3169
Amaury Denoyelle2216b082023-02-02 14:59:36 +01003170 if (!qc_handle_strm_frm(pkt, stream, qc, fin)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003171 TRACE_ERROR("qc_handle_strm_frm() failed", QUIC_EV_CONN_PRSHPKT, qc);
3172 goto leave;
3173 }
3174
3175 break;
3176 }
3177 case QUIC_FT_MAX_DATA:
3178 if (qc->mux_state == QC_MUX_READY) {
3179 struct quic_max_data *data = &frm.max_data;
3180 qcc_recv_max_data(qc->qcc, data->max_data);
3181 }
3182 break;
3183 case QUIC_FT_MAX_STREAM_DATA:
3184 if (qc->mux_state == QC_MUX_READY) {
3185 struct quic_max_stream_data *data = &frm.max_stream_data;
3186 if (qcc_recv_max_stream_data(qc->qcc, data->id,
3187 data->max_stream_data)) {
3188 TRACE_ERROR("qcc_recv_max_stream_data() failed", QUIC_EV_CONN_PRSHPKT, qc);
3189 goto leave;
3190 }
3191 }
3192 break;
3193 case QUIC_FT_MAX_STREAMS_BIDI:
3194 case QUIC_FT_MAX_STREAMS_UNI:
3195 break;
3196 case QUIC_FT_DATA_BLOCKED:
3197 HA_ATOMIC_INC(&qc->prx_counters->data_blocked);
3198 break;
3199 case QUIC_FT_STREAM_DATA_BLOCKED:
3200 HA_ATOMIC_INC(&qc->prx_counters->stream_data_blocked);
3201 break;
3202 case QUIC_FT_STREAMS_BLOCKED_BIDI:
3203 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_bidi);
3204 break;
3205 case QUIC_FT_STREAMS_BLOCKED_UNI:
3206 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_uni);
3207 break;
3208 case QUIC_FT_NEW_CONNECTION_ID:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003209 /* XXX TO DO XXX */
3210 break;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003211 case QUIC_FT_RETIRE_CONNECTION_ID:
3212 {
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003213 struct quic_connection_id *cid = NULL;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003214
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003215 if (!qc_handle_retire_connection_id_frm(qc, &frm, &pkt->dcid, &cid))
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003216 goto leave;
3217
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003218 if (!cid)
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003219 break;
3220
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003221 ebmb_delete(&cid->node);
3222 eb64_delete(&cid->seq_num);
3223 pool_free(pool_head_quic_connection_id, cid);
3224 TRACE_PROTO("CID retired", QUIC_EV_CONN_PSTRM, qc);
3225
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003226 cid = new_quic_cid(&qc->cids, qc);
3227 if (!cid) {
3228 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3229 }
3230 else {
3231 /* insert the allocated CID in the receiver datagram handler tree */
3232 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3233 qc_build_new_connection_id_frm(qc, cid);
3234 }
3235 break;
3236 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003237 case QUIC_FT_CONNECTION_CLOSE:
3238 case QUIC_FT_CONNECTION_CLOSE_APP:
3239 /* Increment the error counters */
3240 qc_cc_err_count_inc(qc, &frm);
3241 if (!(qc->flags & QUIC_FL_CONN_DRAINING)) {
3242 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
3243 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
3244 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
3245 }
3246 TRACE_STATE("Entering draining state", QUIC_EV_CONN_PRSHPKT, qc);
3247 /* RFC 9000 10.2. Immediate Close:
3248 * The closing and draining connection states exist to ensure
3249 * that connections close cleanly and that delayed or reordered
3250 * packets are properly discarded. These states SHOULD persist
3251 * for at least three times the current PTO interval...
3252 *
3253 * Rearm the idle timeout only one time when entering draining
3254 * state.
3255 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003256 qc->flags |= QUIC_FL_CONN_DRAINING|QUIC_FL_CONN_IMMEDIATE_CLOSE;
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01003257 qc_detach_th_ctx_list(qc, 1);
Frédéric Lécailled7215712023-03-24 18:13:37 +01003258 qc_idle_timer_do_rearm(qc, 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003259 qc_notify_close(qc);
3260 }
3261 break;
3262 case QUIC_FT_HANDSHAKE_DONE:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003263 if (qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003264 TRACE_ERROR("non accepted QUIC_FT_HANDSHAKE_DONE frame",
3265 QUIC_EV_CONN_PRSHPKT, qc);
3266 goto leave;
3267 }
3268
3269 qc->state = QUIC_HS_ST_CONFIRMED;
3270 break;
3271 default:
3272 TRACE_ERROR("unknosw frame type", QUIC_EV_CONN_PRSHPKT, qc);
3273 goto leave;
3274 }
3275 }
3276
3277 /* Flag this packet number space as having received a packet. */
3278 qel->pktns->flags |= QUIC_FL_PKTNS_PKT_RECEIVED;
3279
3280 if (fast_retrans) {
3281 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
3282 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
3283
3284 TRACE_PROTO("speeding up handshake completion", QUIC_EV_CONN_PRSHPKT, qc);
3285 qc_prep_hdshk_fast_retrans(qc, &iqel->pktns->tx.frms, &hqel->pktns->tx.frms);
3286 qc->flags |= QUIC_FL_CONN_HANDSHAKE_SPEED_UP;
3287 }
3288
3289 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
3290 * has successfully parse a Handshake packet. The Initial encryption must also
3291 * be discarded.
3292 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003293 if (pkt->type == QUIC_PACKET_TYPE_HANDSHAKE && qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003294 if (qc->state >= QUIC_HS_ST_SERVER_INITIAL) {
3295 if (!(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx.flags &
3296 QUIC_FL_TLS_SECRETS_DCD)) {
3297 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3298 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PRSHPKT, qc);
3299 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003300 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003301 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3302 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3303 }
3304 if (qc->state < QUIC_HS_ST_SERVER_HANDSHAKE)
3305 qc->state = QUIC_HS_ST_SERVER_HANDSHAKE;
3306 }
3307 }
3308
3309 ret = 1;
3310 leave:
3311 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
3312 return ret;
3313}
3314
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003315
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003316/* Allocate Tx buffer from <qc> quic-conn if needed.
3317 *
3318 * Returns allocated buffer or NULL on error.
3319 */
3320static struct buffer *qc_txb_alloc(struct quic_conn *qc)
3321{
3322 struct buffer *buf = &qc->tx.buf;
3323 if (!b_alloc(buf))
3324 return NULL;
3325
3326 return buf;
3327}
3328
3329/* Free Tx buffer from <qc> if it is empty. */
3330static void qc_txb_release(struct quic_conn *qc)
3331{
3332 struct buffer *buf = &qc->tx.buf;
3333
3334 /* For the moment sending function is responsible to purge the buffer
3335 * entirely. It may change in the future but this requires to be able
3336 * to reuse old data.
Frédéric Lécaillebbf86be2023-02-20 09:28:58 +01003337 * For the momemt we do not care to leave data in the buffer for
3338 * a connection which is supposed to be killed asap.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003339 */
3340 BUG_ON_HOT(buf && b_data(buf));
3341
3342 if (!b_data(buf)) {
3343 b_free(buf);
3344 offer_buffers(NULL, 1);
3345 }
3346}
3347
3348/* Commit a datagram payload written into <buf> of length <length>. <first_pkt>
3349 * must contains the address of the first packet stored in the payload.
3350 *
3351 * Caller is responsible that there is enough space in the buffer.
3352 */
3353static void qc_txb_store(struct buffer *buf, uint16_t length,
3354 struct quic_tx_packet *first_pkt)
3355{
3356 const size_t hdlen = sizeof(uint16_t) + sizeof(void *);
3357 BUG_ON_HOT(b_contig_space(buf) < hdlen); /* this must not happen */
3358
3359 write_u16(b_tail(buf), length);
3360 write_ptr(b_tail(buf) + sizeof(length), first_pkt);
3361 b_add(buf, hdlen + length);
3362}
3363
3364/* Returns 1 if a packet may be built for <qc> from <qel> encryption level
3365 * with <frms> as ack-eliciting frame list to send, 0 if not.
3366 * <cc> must equal to 1 if an immediate close was asked, 0 if not.
3367 * <probe> must equalt to 1 if a probing packet is required, 0 if not.
3368 * <force_ack> may be set to 1 if you want to force an ack.
3369 */
3370static int qc_may_build_pkt(struct quic_conn *qc, struct list *frms,
3371 struct quic_enc_level *qel, int cc, int probe, int force_ack)
3372{
Frédéric Lécailled7215712023-03-24 18:13:37 +01003373 unsigned int must_ack = force_ack || (qc->flags & QUIC_FL_CONN_ACK_TIMER_FIRED);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003374
3375 /* Do not build any more packet if the TX secrets are not available or
3376 * if there is nothing to send, i.e. if no CONNECTION_CLOSE or ACK are required
3377 * and if there is no more packets to send upon PTO expiration
3378 * and if there is no more ack-eliciting frames to send or in flight
3379 * congestion control limit is reached for prepared data
3380 */
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02003381 if (!quic_tls_has_tx_sec(qel) ||
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003382 (!cc && !probe && !must_ack &&
3383 (LIST_ISEMPTY(frms) || qc->path->prep_in_flight >= qc->path->cwnd))) {
3384 return 0;
3385 }
3386
3387 return 1;
3388}
3389
3390/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3391 * <frms>. Each packet is stored in a distinct datagram written to <buf>.
3392 *
3393 * Each datagram is prepended by a two fields header : the datagram length and
3394 * the address of the packet contained in the datagram.
3395 *
3396 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3397 * -1 if something wrong happened.
3398 */
3399static int qc_prep_app_pkts(struct quic_conn *qc, struct buffer *buf,
3400 struct list *frms)
3401{
3402 int ret = -1;
3403 struct quic_enc_level *qel;
3404 unsigned char *end, *pos;
3405 struct quic_tx_packet *pkt;
3406 size_t total;
3407 /* Each datagram is prepended with its length followed by the address
3408 * of the first packet in the datagram.
3409 */
3410 const size_t dg_headlen = sizeof(uint16_t) + sizeof(pkt);
3411
3412 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3413
3414 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3415 total = 0;
3416 pos = (unsigned char *)b_tail(buf);
3417 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen) {
3418 int err, probe, cc;
3419
3420 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3421 probe = 0;
3422 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3423 /* We do not probe if an immediate close was asked */
3424 if (!cc)
3425 probe = qel->pktns->tx.pto_probe;
3426
3427 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, 0))
3428 break;
3429
3430 /* Leave room for the datagram header */
3431 pos += dg_headlen;
3432 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3433 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3434 }
3435 else {
3436 end = pos + qc->path->mtu;
3437 }
3438
3439 pkt = qc_build_pkt(&pos, end, qel, &qel->tls_ctx, frms, qc, NULL, 0,
3440 QUIC_PACKET_TYPE_SHORT, 0, 0, probe, cc, &err);
3441 switch (err) {
3442 case -2:
3443 // trace already emitted by function above
3444 goto leave;
3445 case -1:
3446 /* As we provide qc_build_pkt() with an enough big buffer to fulfill an
3447 * MTU, we are here because of the congestion control window. There is
3448 * no need to try to reuse this buffer.
3449 */
3450 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3451 goto out;
3452 default:
3453 break;
3454 }
3455
3456 /* This is to please to GCC. We cannot have (err >= 0 && !pkt) */
3457 BUG_ON(!pkt);
3458
3459 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3460 pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3461
3462 total += pkt->len;
3463
3464 /* Write datagram header. */
3465 qc_txb_store(buf, pkt->len, pkt);
3466 }
3467
3468 out:
3469 ret = total;
3470 leave:
3471 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3472 return ret;
3473}
3474
3475/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3476 * <frms>. Several packets can be regrouped in a single datagram. The result is
3477 * written into <buf>.
3478 *
3479 * Each datagram is prepended by a two fields header : the datagram length and
3480 * the address of first packet in the datagram.
3481 *
3482 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3483 * -1 if something wrong happened.
3484 */
3485static int qc_prep_pkts(struct quic_conn *qc, struct buffer *buf,
3486 enum quic_tls_enc_level tel, struct list *tel_frms,
3487 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
3488{
3489 struct quic_enc_level *qel;
3490 unsigned char *end, *pos;
3491 struct quic_tx_packet *first_pkt, *cur_pkt, *prv_pkt;
3492 /* length of datagrams */
3493 uint16_t dglen;
3494 size_t total;
3495 int ret = -1, padding;
3496 /* Each datagram is prepended with its length followed by the address
3497 * of the first packet in the datagram.
3498 */
3499 const size_t dg_headlen = sizeof(uint16_t) + sizeof(first_pkt);
3500 struct list *frms;
3501
3502 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3503
3504 /* Currently qc_prep_pkts() does not handle buffer wrapping so the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003505 * caller must ensure that buf is reset.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003506 */
3507 BUG_ON_HOT(buf->head || buf->data);
3508
3509 total = 0;
3510 qel = &qc->els[tel];
3511 frms = tel_frms;
3512 dglen = 0;
3513 padding = 0;
3514 pos = (unsigned char *)b_head(buf);
3515 first_pkt = prv_pkt = NULL;
3516 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen || prv_pkt) {
3517 int err, probe, cc;
3518 enum quic_pkt_type pkt_type;
3519 struct quic_tls_ctx *tls_ctx;
3520 const struct quic_version *ver;
3521 int force_ack = (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3522 (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
3523 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
3524
Frédéric Lécaille8f991942023-03-24 15:14:45 +01003525 TRACE_PROTO("TX prep pks", QUIC_EV_CONN_PHPKTS, qc, qel);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003526 probe = 0;
3527 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3528 /* We do not probe if an immediate close was asked */
3529 if (!cc)
3530 probe = qel->pktns->tx.pto_probe;
3531
3532 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, force_ack)) {
3533 if (prv_pkt)
3534 qc_txb_store(buf, dglen, first_pkt);
3535 /* Let's select the next encryption level */
3536 if (tel != next_tel && next_tel != QUIC_TLS_ENC_LEVEL_NONE) {
3537 tel = next_tel;
3538 frms = next_tel_frms;
3539 qel = &qc->els[tel];
3540 /* Build a new datagram */
3541 prv_pkt = NULL;
3542 TRACE_DEVEL("next encryption level selected", QUIC_EV_CONN_PHPKTS, qc);
3543 continue;
3544 }
3545 break;
3546 }
3547
3548 pkt_type = quic_tls_level_pkt_type(tel);
3549 if (!prv_pkt) {
3550 /* Leave room for the datagram header */
3551 pos += dg_headlen;
3552 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3553 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3554 }
3555 else {
3556 end = pos + qc->path->mtu;
3557 }
3558 }
3559
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003560 /* RFC 9000 14.1 Initial datagram size
3561 * a server MUST expand the payload of all UDP datagrams carrying ack-eliciting
3562 * Initial packets to at least the smallest allowed maximum datagram size of
3563 * 1200 bytes.
3564 *
3565 * Ensure that no ack-eliciting packets are sent into too small datagrams
3566 */
3567 if (pkt_type == QUIC_PACKET_TYPE_INITIAL && !LIST_ISEMPTY(tel_frms)) {
3568 if (end - pos < QUIC_INITIAL_PACKET_MINLEN) {
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01003569 TRACE_PROTO("No more enough room to build an Initial packet",
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003570 QUIC_EV_CONN_PHPKTS, qc);
3571 goto out;
3572 }
3573
3574 /* Pad this Initial packet if there is no ack-eliciting frames to send from
3575 * the next packet number space.
3576 */
Frédéric Lécailleec937212023-03-03 17:34:41 +01003577 if (!next_tel_frms || LIST_ISEMPTY(next_tel_frms))
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003578 padding = 1;
3579 }
3580
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003581 if (qc->negotiated_version) {
3582 ver = qc->negotiated_version;
3583 if (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL])
3584 tls_ctx = &qc->negotiated_ictx;
3585 else
3586 tls_ctx = &qel->tls_ctx;
3587 }
3588 else {
3589 ver = qc->original_version;
3590 tls_ctx = &qel->tls_ctx;
3591 }
3592
3593 cur_pkt = qc_build_pkt(&pos, end, qel, tls_ctx, frms,
3594 qc, ver, dglen, pkt_type,
3595 force_ack, padding, probe, cc, &err);
3596 switch (err) {
3597 case -2:
3598 // trace already emitted by function above
3599 goto leave;
3600 case -1:
3601 /* If there was already a correct packet present, set the
3602 * current datagram as prepared into <cbuf>.
3603 */
3604 if (prv_pkt)
3605 qc_txb_store(buf, dglen, first_pkt);
3606 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3607 goto out;
3608 default:
3609 break;
3610 }
3611
3612 /* This is to please to GCC. We cannot have (err >= 0 && !cur_pkt) */
3613 BUG_ON(!cur_pkt);
3614
3615 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3616 cur_pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3617
3618 total += cur_pkt->len;
3619 /* keep trace of the first packet in the datagram */
3620 if (!first_pkt)
3621 first_pkt = cur_pkt;
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01003622 /* Attach the current one to the previous one and vice versa */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003623 if (prv_pkt) {
3624 prv_pkt->next = cur_pkt;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01003625 cur_pkt->prev = prv_pkt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003626 cur_pkt->flags |= QUIC_FL_TX_PACKET_COALESCED;
3627 }
3628 /* Let's say we have to build a new dgram */
3629 prv_pkt = NULL;
3630 dglen += cur_pkt->len;
3631 /* Client: discard the Initial encryption keys as soon as
3632 * a handshake packet could be built.
3633 */
3634 if (qc->state == QUIC_HS_ST_CLIENT_INITIAL &&
3635 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
3636 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3637 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PHPKTS, qc);
3638 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
3639 qc_set_timer(qc);
3640 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3641 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3642 qc->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
3643 }
3644 /* If the data for the current encryption level have all been sent,
3645 * select the next level.
3646 */
3647 if ((tel == QUIC_TLS_ENC_LEVEL_INITIAL || tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE) &&
3648 next_tel != QUIC_TLS_ENC_LEVEL_NONE && (LIST_ISEMPTY(frms) && !qel->pktns->tx.pto_probe)) {
3649 /* If QUIC_TLS_ENC_LEVEL_HANDSHAKE was already reached let's try QUIC_TLS_ENC_LEVEL_APP */
3650 if (tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE && next_tel == tel)
3651 next_tel = QUIC_TLS_ENC_LEVEL_APP;
3652 tel = next_tel;
3653 if (tel == QUIC_TLS_ENC_LEVEL_APP)
3654 frms = &qc->els[tel].pktns->tx.frms;
3655 else
3656 frms = next_tel_frms;
3657 qel = &qc->els[tel];
3658 if (!LIST_ISEMPTY(frms)) {
3659 /* If there is data for the next level, do not
3660 * consume a datagram.
3661 */
3662 prv_pkt = cur_pkt;
3663 }
3664 }
3665
3666 /* If we have to build a new datagram, set the current datagram as
3667 * prepared into <cbuf>.
3668 */
3669 if (!prv_pkt) {
3670 qc_txb_store(buf, dglen, first_pkt);
3671 first_pkt = NULL;
3672 dglen = 0;
3673 padding = 0;
3674 }
3675 else if (prv_pkt->type == QUIC_TLS_ENC_LEVEL_INITIAL &&
3676 (!qc_is_listener(qc) ||
3677 prv_pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
3678 padding = 1;
3679 }
3680 }
3681
3682 out:
3683 ret = total;
3684 leave:
3685 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3686 return ret;
3687}
3688
3689/* Send datagrams stored in <buf>.
3690 *
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003691 * This function returns 1 for success. On error, there is several behavior
3692 * depending on underlying sendto() error :
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003693 * - for an unrecoverable error, 0 is returned and connection is killed.
3694 * - a transient error is handled differently if connection has its owned
3695 * socket. If this is the case, 0 is returned and socket is subscribed on the
3696 * poller. The other case is assimilated to a success case with 1 returned.
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003697 * Remaining data are purged from the buffer and will eventually be detected
3698 * as lost which gives the opportunity to retry sending.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003699 */
3700int qc_send_ppkts(struct buffer *buf, struct ssl_sock_ctx *ctx)
3701{
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003702 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003703 struct quic_conn *qc;
3704 char skip_sendto = 0;
3705
3706 qc = ctx->qc;
3707 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
3708 while (b_contig_data(buf, 0)) {
3709 unsigned char *pos;
3710 struct buffer tmpbuf = { };
3711 struct quic_tx_packet *first_pkt, *pkt, *next_pkt;
3712 uint16_t dglen;
3713 size_t headlen = sizeof dglen + sizeof first_pkt;
3714 unsigned int time_sent;
3715
3716 pos = (unsigned char *)b_head(buf);
3717 dglen = read_u16(pos);
3718 BUG_ON_HOT(!dglen); /* this should not happen */
3719
3720 pos += sizeof dglen;
3721 first_pkt = read_ptr(pos);
3722 pos += sizeof first_pkt;
3723 tmpbuf.area = (char *)pos;
3724 tmpbuf.size = tmpbuf.data = dglen;
3725
Frédéric Lécaille8f991942023-03-24 15:14:45 +01003726 TRACE_PROTO("TX dgram", QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003727 /* If sendto is on error just skip the call to it for the rest
3728 * of the loop but continue to purge the buffer. Data will be
3729 * transmitted when QUIC packets are detected as lost on our
3730 * side.
3731 *
3732 * TODO use fd-monitoring to detect when send operation can be
3733 * retry. This should improve the bandwidth without relying on
3734 * retransmission timer. However, it requires a major rework on
3735 * quic-conn fd management.
3736 */
3737 if (!skip_sendto) {
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003738 int ret = qc_snd_buf(qc, &tmpbuf, tmpbuf.data, 0);
3739 if (ret < 0) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003740 TRACE_ERROR("sendto fatal error", QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003741 qc_kill_conn(qc);
3742 b_del(buf, buf->data);
3743 goto leave;
3744 }
3745 else if (!ret) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003746 /* Connection owned socket : poller will wake us up when transient error is cleared. */
3747 if (qc_test_fd(qc)) {
3748 TRACE_ERROR("sendto error, subscribe to poller", QUIC_EV_CONN_SPPKTS, qc);
3749 goto leave;
3750 }
3751
3752 /* No connection owned-socket : rely on retransmission to retry sending. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003753 skip_sendto = 1;
3754 TRACE_ERROR("sendto error, simulate sending for the rest of data", QUIC_EV_CONN_SPPKTS, qc);
3755 }
3756 }
3757
3758 b_del(buf, dglen + headlen);
3759 qc->tx.bytes += tmpbuf.data;
3760 time_sent = now_ms;
3761
3762 for (pkt = first_pkt; pkt; pkt = next_pkt) {
Frédéric Lécailleceb88b82023-02-20 14:43:55 +01003763 /* RFC 9000 14.1 Initial datagram size
3764 * a server MUST expand the payload of all UDP datagrams carrying ack-eliciting
3765 * Initial packets to at least the smallest allowed maximum datagram size of
3766 * 1200 bytes.
3767 */
3768 BUG_ON_HOT(pkt->type == QUIC_PACKET_TYPE_INITIAL &&
3769 (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) &&
3770 dglen < QUIC_INITIAL_PACKET_MINLEN);
3771
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003772 pkt->time_sent = time_sent;
3773 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
3774 pkt->pktns->tx.time_of_last_eliciting = time_sent;
3775 qc->path->ifae_pkts++;
3776 if (qc->flags & QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ)
Frédéric Lécailled7215712023-03-24 18:13:37 +01003777 qc_idle_timer_rearm(qc, 0, 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003778 }
3779 if (!(qc->flags & QUIC_FL_CONN_CLOSING) &&
3780 (pkt->flags & QUIC_FL_TX_PACKET_CC)) {
3781 qc->flags |= QUIC_FL_CONN_CLOSING;
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01003782 qc_detach_th_ctx_list(qc, 1);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003783 qc_notify_close(qc);
3784
3785 /* RFC 9000 10.2. Immediate Close:
3786 * The closing and draining connection states exist to ensure
3787 * that connections close cleanly and that delayed or reordered
3788 * packets are properly discarded. These states SHOULD persist
3789 * for at least three times the current PTO interval...
3790 *
3791 * Rearm the idle timeout only one time when entering closing
3792 * state.
3793 */
Frédéric Lécailled7215712023-03-24 18:13:37 +01003794 qc_idle_timer_do_rearm(qc, 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003795 if (qc->timer_task) {
3796 task_destroy(qc->timer_task);
3797 qc->timer_task = NULL;
3798 }
3799 }
3800 qc->path->in_flight += pkt->in_flight_len;
3801 pkt->pktns->tx.in_flight += pkt->in_flight_len;
3802 if (pkt->in_flight_len)
3803 qc_set_timer(qc);
Frédéric Lécaille8f991942023-03-24 15:14:45 +01003804 TRACE_PROTO("TX pkt", QUIC_EV_CONN_SPPKTS, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003805 next_pkt = pkt->next;
3806 quic_tx_packet_refinc(pkt);
3807 eb64_insert(&pkt->pktns->tx.pkts, &pkt->pn_node);
3808 }
3809 }
3810
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003811 ret = 1;
3812leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003813 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
3814
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003815 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003816}
3817
3818/* Copy into <buf> buffer a stateless reset token depending on the
3819 * <salt> salt input. This is the cluster secret which will be derived
3820 * as HKDF input secret to generate this token.
3821 * Return 1 if succeeded, 0 if not.
3822 */
3823static int quic_stateless_reset_token_cpy(struct quic_conn *qc,
3824 unsigned char *buf, size_t len,
3825 const unsigned char *salt, size_t saltlen)
3826{
3827 /* Input secret */
3828 const unsigned char *key = (const unsigned char *)global.cluster_secret;
3829 size_t keylen = strlen(global.cluster_secret);
3830 /* Info */
3831 const unsigned char label[] = "stateless token";
3832 size_t labellen = sizeof label - 1;
3833 int ret;
3834
3835 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3836
3837 ret = quic_hkdf_extract_and_expand(EVP_sha256(), buf, len,
3838 key, keylen, salt, saltlen, label, labellen);
3839 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3840 return ret;
3841}
3842
3843/* Initialize the stateless reset token attached to <cid> connection ID.
3844 * Returns 1 if succeeded, 0 if not.
3845 */
3846static int quic_stateless_reset_token_init(struct quic_conn *qc,
3847 struct quic_connection_id *quic_cid)
3848{
3849 int ret;
3850
3851 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3852
3853 if (global.cluster_secret) {
3854 /* Output secret */
3855 unsigned char *token = quic_cid->stateless_reset_token;
3856 size_t tokenlen = sizeof quic_cid->stateless_reset_token;
3857 /* Salt */
3858 const unsigned char *cid = quic_cid->cid.data;
3859 size_t cidlen = quic_cid->cid.len;
3860
3861 ret = quic_stateless_reset_token_cpy(qc, token, tokenlen, cid, cidlen);
3862 }
3863 else {
3864 /* TODO: RAND_bytes() should be replaced */
3865 ret = RAND_bytes(quic_cid->stateless_reset_token,
3866 sizeof quic_cid->stateless_reset_token) == 1;
3867 }
3868
3869 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3870 return ret;
3871}
3872
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003873/* Allocate a new CID and attach it to <root> ebtree.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003874 *
3875 * The CID is randomly generated in part with the result altered to be
3876 * associated with the current thread ID. This means this function must only
3877 * be called by the quic_conn thread.
3878 *
3879 * Returns the new CID if succeeded, NULL if not.
3880 */
3881static struct quic_connection_id *new_quic_cid(struct eb_root *root,
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003882 struct quic_conn *qc)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003883{
3884 struct quic_connection_id *cid;
3885
3886 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3887
3888 cid = pool_alloc(pool_head_quic_connection_id);
3889 if (!cid) {
3890 TRACE_ERROR("cid allocation failed", QUIC_EV_CONN_TXPKT, qc);
3891 goto err;
3892 }
3893
3894 cid->cid.len = QUIC_HAP_CID_LEN;
3895 /* TODO: RAND_bytes() should be replaced */
3896 if (RAND_bytes(cid->cid.data, cid->cid.len) != 1) {
3897 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT, qc);
3898 goto err;
3899 }
3900
3901 quic_pin_cid_to_tid(cid->cid.data, tid);
3902 if (quic_stateless_reset_token_init(qc, cid) != 1) {
3903 TRACE_ERROR("quic_stateless_reset_token_init() failed", QUIC_EV_CONN_TXPKT, qc);
3904 goto err;
3905 }
3906
3907 cid->qc = qc;
3908
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003909 cid->seq_num.key = qc->next_cid_seq_num++;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003910 cid->retire_prior_to = 0;
3911 /* insert the allocated CID in the quic_conn tree */
3912 eb64_insert(root, &cid->seq_num);
3913
3914 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3915 return cid;
3916
3917 err:
3918 pool_free(pool_head_quic_connection_id, cid);
3919 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3920 return NULL;
3921}
3922
3923/* Build all the frames which must be sent just after the handshake have succeeded.
3924 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
3925 * a HANDSHAKE_DONE frame.
3926 * Return 1 if succeeded, 0 if not.
3927 */
3928static int quic_build_post_handshake_frames(struct quic_conn *qc)
3929{
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003930 int ret = 0, max;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003931 struct quic_enc_level *qel;
3932 struct quic_frame *frm, *frmbak;
3933 struct list frm_list = LIST_HEAD_INIT(frm_list);
3934 struct eb64_node *node;
3935
3936 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
3937
3938 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3939 /* Only servers must send a HANDSHAKE_DONE frame. */
3940 if (qc_is_listener(qc)) {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003941 frm = qc_frm_alloc(QUIC_FT_HANDSHAKE_DONE);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003942 if (!frm) {
3943 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3944 goto leave;
3945 }
3946
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003947 LIST_APPEND(&frm_list, &frm->list);
3948 }
3949
3950 /* Initialize <max> connection IDs minus one: there is
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003951 * already one connection ID used for the current connection. Also limit
3952 * the number of connection IDs sent to the peer to 4 (3 from this function
3953 * plus 1 for the current connection.
3954 * Note that active_connection_id_limit >= 2: this has been already checked
3955 * when receiving this parameter.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003956 */
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003957 max = QUIC_MIN(qc->tx.params.active_connection_id_limit - 1, (uint64_t)3);
3958 while (max--) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003959 struct quic_connection_id *cid;
3960
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003961 frm = qc_frm_alloc(QUIC_FT_NEW_CONNECTION_ID);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003962 if (!frm) {
3963 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3964 goto err;
3965 }
3966
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003967 cid = new_quic_cid(&qc->cids, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003968 if (!cid) {
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003969 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003970 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3971 goto err;
3972 }
3973
3974 /* insert the allocated CID in the receiver datagram handler tree */
3975 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3976
3977 quic_connection_id_to_frm_cpy(frm, cid);
3978 LIST_APPEND(&frm_list, &frm->list);
3979 }
3980
3981 LIST_SPLICE(&qel->pktns->tx.frms, &frm_list);
3982 qc->flags |= QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT;
3983
3984 ret = 1;
3985 leave:
3986 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
3987 return ret;
3988
3989 err:
3990 /* free the frames */
3991 list_for_each_entry_safe(frm, frmbak, &frm_list, list)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003992 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003993
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003994 /* The first CID sequence number value used to allocated CIDs by this function is 1,
3995 * 0 being the sequence number of the CID for this connection.
3996 */
3997 node = eb64_lookup_ge(&qc->cids, 1);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003998 while (node) {
3999 struct quic_connection_id *cid;
4000
4001 cid = eb64_entry(node, struct quic_connection_id, seq_num);
4002 if (cid->seq_num.key >= max)
4003 break;
4004
4005 node = eb64_next(node);
4006 ebmb_delete(&cid->node);
4007 eb64_delete(&cid->seq_num);
4008 pool_free(pool_head_quic_connection_id, cid);
4009 }
4010 goto leave;
4011}
4012
4013/* Deallocate <l> list of ACK ranges. */
4014void quic_free_arngs(struct quic_conn *qc, struct quic_arngs *arngs)
4015{
4016 struct eb64_node *n;
4017 struct quic_arng_node *ar;
4018
4019 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4020
4021 n = eb64_first(&arngs->root);
4022 while (n) {
4023 struct eb64_node *next;
4024
4025 ar = eb64_entry(n, struct quic_arng_node, first);
4026 next = eb64_next(n);
4027 eb64_delete(n);
4028 pool_free(pool_head_quic_arng, ar);
4029 n = next;
4030 }
4031
4032 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4033}
4034
4035/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
4036 * descending order.
4037 */
4038static inline size_t sack_gap(struct quic_arng_node *p,
4039 struct quic_arng_node *q)
4040{
4041 return p->first.key - q->last - 2;
4042}
4043
4044
4045/* Remove the last elements of <ack_ranges> list of ack range updating its
4046 * encoded size until it goes below <limit>.
4047 * Returns 1 if succeeded, 0 if not (no more element to remove).
4048 */
4049static int quic_rm_last_ack_ranges(struct quic_conn *qc,
4050 struct quic_arngs *arngs, size_t limit)
4051{
4052 int ret = 0;
4053 struct eb64_node *last, *prev;
4054
4055 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4056
4057 last = eb64_last(&arngs->root);
4058 while (last && arngs->enc_sz > limit) {
4059 struct quic_arng_node *last_node, *prev_node;
4060
4061 prev = eb64_prev(last);
4062 if (!prev) {
4063 TRACE_DEVEL("<last> not found", QUIC_EV_CONN_TXPKT, qc);
4064 goto out;
4065 }
4066
4067 last_node = eb64_entry(last, struct quic_arng_node, first);
4068 prev_node = eb64_entry(prev, struct quic_arng_node, first);
4069 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
4070 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
4071 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
4072 --arngs->sz;
4073 eb64_delete(last);
4074 pool_free(pool_head_quic_arng, last);
4075 last = prev;
4076 }
4077
4078 ret = 1;
4079 out:
4080 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4081 return ret;
4082}
4083
4084/* Set the encoded size of <arngs> QUIC ack ranges. */
4085static void quic_arngs_set_enc_sz(struct quic_conn *qc, struct quic_arngs *arngs)
4086{
4087 struct eb64_node *node, *next;
4088 struct quic_arng_node *ar, *ar_next;
4089
4090 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4091
4092 node = eb64_last(&arngs->root);
4093 if (!node)
4094 goto leave;
4095
4096 ar = eb64_entry(node, struct quic_arng_node, first);
4097 arngs->enc_sz = quic_int_getsize(ar->last) +
4098 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
4099
4100 while ((next = eb64_prev(node))) {
4101 ar_next = eb64_entry(next, struct quic_arng_node, first);
4102 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
4103 quic_int_getsize(ar_next->last - ar_next->first.key);
4104 node = next;
4105 ar = eb64_entry(node, struct quic_arng_node, first);
4106 }
4107
4108 leave:
4109 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4110}
4111
4112/* Insert <ar> ack range into <argns> tree of ack ranges.
4113 * Returns the ack range node which has been inserted if succeeded, NULL if not.
4114 */
4115static inline
4116struct quic_arng_node *quic_insert_new_range(struct quic_conn *qc,
4117 struct quic_arngs *arngs,
4118 struct quic_arng *ar)
4119{
4120 struct quic_arng_node *new_ar;
4121
4122 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
4123
4124 new_ar = pool_alloc(pool_head_quic_arng);
4125 if (!new_ar) {
4126 TRACE_ERROR("ack range allocation failed", QUIC_EV_CONN_RXPKT, qc);
4127 goto leave;
4128 }
4129
4130 new_ar->first.key = ar->first;
4131 new_ar->last = ar->last;
4132 eb64_insert(&arngs->root, &new_ar->first);
4133 arngs->sz++;
4134
4135 leave:
4136 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
4137 return new_ar;
4138}
4139
4140/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
4141 * Note that this function computes the number of bytes required to encode
4142 * this tree of ACK ranges in descending order.
4143 *
4144 * Descending order
4145 * ------------->
4146 * range1 range2
4147 * ..........|--------|..............|--------|
4148 * ^ ^ ^ ^
4149 * | | | |
4150 * last1 first1 last2 first2
4151 * ..........+--------+--------------+--------+......
4152 * diff1 gap12 diff2
4153 *
4154 * To encode the previous list of ranges we must encode integers as follows in
4155 * descending order:
4156 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
4157 * with diff1 = last1 - first1
4158 * diff2 = last2 - first2
4159 * gap12 = first1 - last2 - 2 (>= 0)
4160 *
4161
4162returns 0 on error
4163
4164 */
4165int quic_update_ack_ranges_list(struct quic_conn *qc,
4166 struct quic_arngs *arngs,
4167 struct quic_arng *ar)
4168{
4169 int ret = 0;
4170 struct eb64_node *le;
4171 struct quic_arng_node *new_node;
4172 struct eb64_node *new;
4173
4174 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
4175
4176 new = NULL;
4177 if (eb_is_empty(&arngs->root)) {
4178 new_node = quic_insert_new_range(qc, arngs, ar);
4179 if (new_node)
4180 ret = 1;
4181
4182 goto leave;
4183 }
4184
4185 le = eb64_lookup_le(&arngs->root, ar->first);
4186 if (!le) {
4187 new_node = quic_insert_new_range(qc, arngs, ar);
4188 if (!new_node)
4189 goto leave;
4190
4191 new = &new_node->first;
4192 }
4193 else {
4194 struct quic_arng_node *le_ar =
4195 eb64_entry(le, struct quic_arng_node, first);
4196
4197 /* Already existing range */
4198 if (le_ar->last >= ar->last) {
4199 ret = 1;
4200 }
4201 else if (le_ar->last + 1 >= ar->first) {
4202 le_ar->last = ar->last;
4203 new = le;
4204 new_node = le_ar;
4205 }
4206 else {
4207 new_node = quic_insert_new_range(qc, arngs, ar);
4208 if (!new_node)
4209 goto leave;
4210
4211 new = &new_node->first;
4212 }
4213 }
4214
4215 /* Verify that the new inserted node does not overlap the nodes
4216 * which follow it.
4217 */
4218 if (new) {
4219 struct eb64_node *next;
4220 struct quic_arng_node *next_node;
4221
4222 while ((next = eb64_next(new))) {
4223 next_node =
4224 eb64_entry(next, struct quic_arng_node, first);
4225 if (new_node->last + 1 < next_node->first.key)
4226 break;
4227
4228 if (next_node->last > new_node->last)
4229 new_node->last = next_node->last;
4230 eb64_delete(next);
4231 pool_free(pool_head_quic_arng, next_node);
4232 /* Decrement the size of these ranges. */
4233 arngs->sz--;
4234 }
4235 }
4236
4237 ret = 1;
4238 leave:
4239 quic_arngs_set_enc_sz(qc, arngs);
4240 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
4241 return ret;
4242}
Frédéric Lécailleece86e62023-03-07 11:53:43 +01004243
4244/* Detect the value of the spin bit to be used. */
4245static inline void qc_handle_spin_bit(struct quic_conn *qc, struct quic_rx_packet *pkt,
4246 struct quic_enc_level *qel)
4247{
4248 uint64_t largest_pn = qel->pktns->rx.largest_pn;
4249
4250 if (qel != &qc->els[QUIC_TLS_ENC_LEVEL_APP] || largest_pn == -1 ||
4251 pkt->pn <= largest_pn)
4252 return;
4253
4254 if (qc_is_listener(qc)) {
4255 if (pkt->flags & QUIC_FL_RX_PACKET_SPIN_BIT)
4256 qc->flags |= QUIC_FL_CONN_SPIN_BIT;
4257 else
4258 qc->flags &= ~QUIC_FL_CONN_SPIN_BIT;
4259 }
4260 else {
4261 if (pkt->flags & QUIC_FL_RX_PACKET_SPIN_BIT)
4262 qc->flags &= ~QUIC_FL_CONN_SPIN_BIT;
4263 else
4264 qc->flags |= QUIC_FL_CONN_SPIN_BIT;
4265 }
4266}
4267
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004268/* Remove the header protection of packets at <el> encryption level.
4269 * Always succeeds.
4270 */
4271static inline void qc_rm_hp_pkts(struct quic_conn *qc, struct quic_enc_level *el)
4272{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004273 struct quic_rx_packet *pqpkt, *pkttmp;
4274 struct quic_enc_level *app_qel;
4275
4276 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, qc);
4277 app_qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4278 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
4279 if (el == app_qel && qc_is_listener(qc) && qc->state < QUIC_HS_ST_COMPLETE) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01004280 TRACE_PROTO("RX hp not removed (handshake not completed)",
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004281 QUIC_EV_CONN_ELRMHP, qc);
4282 goto out;
4283 }
Frédéric Lécaille72027782023-02-22 16:20:09 +01004284
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004285 list_for_each_entry_safe(pqpkt, pkttmp, &el->rx.pqpkts, list) {
Frédéric Lécaille72027782023-02-22 16:20:09 +01004286 struct quic_tls_ctx *tls_ctx;
4287
4288 tls_ctx = qc_select_tls_ctx(qc, el, pqpkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004289 if (!qc_do_rm_hp(qc, pqpkt, tls_ctx, el->pktns->rx.largest_pn,
4290 pqpkt->data + pqpkt->pn_offset, pqpkt->data)) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01004291 TRACE_ERROR("RX hp removing error", QUIC_EV_CONN_ELRMHP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004292 }
4293 else {
Frédéric Lécailleece86e62023-03-07 11:53:43 +01004294 qc_handle_spin_bit(qc, pqpkt, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004295 /* The AAD includes the packet number field */
4296 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
4297 /* Store the packet into the tree of packets to decrypt. */
4298 pqpkt->pn_node.key = pqpkt->pn;
4299 eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
4300 quic_rx_packet_refinc(pqpkt);
Frédéric Lécaille8f991942023-03-24 15:14:45 +01004301 TRACE_PROTO("RX hp removed", QUIC_EV_CONN_ELRMHP, qc, pqpkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004302 }
4303 LIST_DELETE(&pqpkt->list);
4304 quic_rx_packet_refdec(pqpkt);
4305 }
4306
4307 out:
4308 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, qc);
4309}
4310
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004311/* Process all the CRYPTO frame at <el> encryption level. This is the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004312 * responsibility of the called to ensure there exists a CRYPTO data
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004313 * stream for this level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004314 * Return 1 if succeeded, 0 if not.
4315 */
4316static inline int qc_treat_rx_crypto_frms(struct quic_conn *qc,
4317 struct quic_enc_level *el,
4318 struct ssl_sock_ctx *ctx)
4319{
4320 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004321 struct ncbuf *ncbuf;
4322 struct quic_cstream *cstream = el->cstream;
4323 ncb_sz_t data;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004324
Frédéric Lécaille8f991942023-03-24 15:14:45 +01004325 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004326
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004327 BUG_ON(!cstream);
4328 ncbuf = &cstream->rx.ncbuf;
4329 if (ncb_is_null(ncbuf))
4330 goto done;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004331
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004332 /* TODO not working if buffer is wrapping */
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004333 while ((data = ncb_data(ncbuf, 0))) {
4334 const unsigned char *cdata = (const unsigned char *)ncb_head(ncbuf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004335
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004336 if (!qc_provide_cdata(el, ctx, cdata, data, NULL, NULL))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004337 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004338
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004339 cstream->rx.offset += data;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004340 TRACE_DEVEL("buffered crypto data were provided to TLS stack",
4341 QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004342 }
4343
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004344 done:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004345 ret = 1;
4346 leave:
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004347 if (!ncb_is_null(ncbuf) && ncb_is_empty(ncbuf)) {
4348 TRACE_DEVEL("freeing crypto buf", QUIC_EV_CONN_PHPKTS, qc, el);
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004349 quic_free_ncbuf(ncbuf);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004350 }
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004351 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004352 return ret;
4353}
4354
4355/* Process all the packets at <el> and <next_el> encryption level.
4356 * This is the caller responsibility to check that <cur_el> is different of <next_el>
4357 * as pointer value.
4358 * Return 1 if succeeded, 0 if not.
4359 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004360int qc_treat_rx_pkts(struct quic_conn *qc, struct quic_enc_level *cur_el,
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004361 struct quic_enc_level *next_el)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004362{
4363 int ret = 0;
4364 struct eb64_node *node;
4365 int64_t largest_pn = -1;
4366 unsigned int largest_pn_time_received = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004367 struct quic_enc_level *qel = cur_el;
4368
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004369 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004370 qel = cur_el;
4371 next_tel:
4372 if (!qel)
4373 goto out;
4374
4375 node = eb64_first(&qel->rx.pkts);
4376 while (node) {
4377 struct quic_rx_packet *pkt;
4378
4379 pkt = eb64_entry(node, struct quic_rx_packet, pn_node);
4380 TRACE_DATA("new packet", QUIC_EV_CONN_RXPKT,
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004381 qc, pkt, NULL, qc->xprt_ctx->ssl);
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01004382 if (!qc_pkt_decrypt(qc, qel, pkt)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004383 /* Drop the packet */
4384 TRACE_ERROR("packet decryption failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004385 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004386 }
4387 else {
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004388 if (!qc_parse_pkt_frms(qc, pkt, qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004389 /* Drop the packet */
4390 TRACE_ERROR("packet parsing failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004391 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004392 HA_ATOMIC_INC(&qc->prx_counters->dropped_parsing);
4393 }
4394 else {
4395 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
4396
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004397 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004398 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
4399 qel->pktns->rx.nb_aepkts_since_last_ack++;
Frédéric Lécailled7215712023-03-24 18:13:37 +01004400 qc_idle_timer_rearm(qc, 1, 1);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004401 }
4402 if (pkt->pn > largest_pn) {
4403 largest_pn = pkt->pn;
4404 largest_pn_time_received = pkt->time_received;
4405 }
4406 /* Update the list of ranges to acknowledge. */
4407 if (!quic_update_ack_ranges_list(qc, &qel->pktns->rx.arngs, &ar))
4408 TRACE_ERROR("Could not update ack range list",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004409 QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004410 }
4411 }
4412 node = eb64_next(node);
4413 eb64_delete(&pkt->pn_node);
4414 quic_rx_packet_refdec(pkt);
4415 }
4416
4417 if (largest_pn != -1 && largest_pn > qel->pktns->rx.largest_pn) {
4418 /* Update the largest packet number. */
4419 qel->pktns->rx.largest_pn = largest_pn;
4420 /* Update the largest acknowledged packet timestamps */
4421 qel->pktns->rx.largest_time_received = largest_pn_time_received;
4422 qel->pktns->flags |= QUIC_FL_PKTNS_NEW_LARGEST_PN;
4423 }
4424
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004425 if (qel->cstream && !qc_treat_rx_crypto_frms(qc, qel, qc->xprt_ctx)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004426 // trace already emitted by function above
4427 goto leave;
4428 }
4429
4430 if (qel == cur_el) {
4431 BUG_ON(qel == next_el);
4432 qel = next_el;
4433 largest_pn = -1;
4434 goto next_tel;
4435 }
4436
4437 out:
4438 ret = 1;
4439 leave:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004440 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004441 return ret;
4442}
4443
4444/* Check if it's possible to remove header protection for packets related to
4445 * encryption level <qel>. If <qel> is NULL, assume it's false.
4446 *
4447 * Return true if the operation is possible else false.
4448 */
4449static int qc_qel_may_rm_hp(struct quic_conn *qc, struct quic_enc_level *qel)
4450{
4451 int ret = 0;
4452 enum quic_tls_enc_level tel;
4453
4454 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
4455
4456 if (!qel)
4457 goto cant_rm_hp;
4458
4459 tel = ssl_to_quic_enc_level(qel->level);
4460
4461 /* check if tls secrets are available */
4462 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01004463 TRACE_PROTO("Discarded keys", QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004464 goto cant_rm_hp;
4465 }
4466
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004467 if (!quic_tls_has_rx_sec(qel)) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01004468 TRACE_PROTO("non available secrets", QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004469 goto cant_rm_hp;
4470 }
4471
Frédéric Lécaille8417beb2023-02-01 10:31:35 +01004472 if (tel == QUIC_TLS_ENC_LEVEL_APP && qc->state < QUIC_HS_ST_COMPLETE) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01004473 TRACE_PROTO("handshake not complete", QUIC_EV_CONN_TRMHP, qc);
Frédéric Lécaille8417beb2023-02-01 10:31:35 +01004474 goto cant_rm_hp;
4475 }
4476
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004477 /* check if the connection layer is ready before using app level */
4478 if ((tel == QUIC_TLS_ENC_LEVEL_APP || tel == QUIC_TLS_ENC_LEVEL_EARLY_DATA) &&
4479 qc->mux_state == QC_MUX_NULL) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01004480 TRACE_PROTO("connection layer not ready", QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004481 goto cant_rm_hp;
4482 }
4483
4484 ret = 1;
4485 cant_rm_hp:
4486 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc);
4487 return ret;
4488}
4489
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004490/* Flush txbuf for <qc> connection. This must be called prior to a packet
4491 * preparation when txbuf contains older data. A send will be conducted for
4492 * these data.
4493 *
4494 * Returns 1 on success : buffer is empty and can be use for packet
4495 * preparation. On error 0 is returned.
4496 */
4497static int qc_purge_txbuf(struct quic_conn *qc, struct buffer *buf)
4498{
4499 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4500
4501 /* This operation can only be conducted if txbuf is not empty. This
4502 * case only happens for connection with their owned socket due to an
4503 * older transient sendto() error.
4504 */
4505 BUG_ON(!qc_test_fd(qc));
4506
4507 if (b_data(buf) && !qc_send_ppkts(buf, qc->xprt_ctx)) {
4508 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4509 qc_txb_release(qc);
4510 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TXPKT, qc);
4511 return 0;
4512 }
4513
4514 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4515 return 1;
4516}
4517
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004518/* Try to send application frames from list <frms> on connection <qc>.
4519 *
4520 * Use qc_send_app_probing wrapper when probing with old data.
4521 *
4522 * Returns 1 on success. Some data might not have been sent due to congestion,
4523 * in this case they are left in <frms> input list. The caller may subscribe on
4524 * quic-conn to retry later.
4525 *
4526 * Returns 0 on critical error.
4527 * TODO review and classify more distinctly transient from definitive errors to
4528 * allow callers to properly handle it.
4529 */
4530static int qc_send_app_pkts(struct quic_conn *qc, struct list *frms)
4531{
4532 int status = 0;
4533 struct buffer *buf;
4534
4535 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4536
4537 buf = qc_txb_alloc(qc);
4538 if (!buf) {
4539 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004540 goto err;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004541 }
4542
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004543 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4544 goto err;
4545
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004546 /* Prepare and send packets until we could not further prepare packets. */
4547 while (1) {
4548 int ret;
4549 /* Currently buf cannot be non-empty at this stage. Even if a
4550 * previous sendto() has failed it is emptied to simulate
4551 * packet emission and rely on QUIC lost detection to try to
4552 * emit it.
4553 */
4554 BUG_ON_HOT(b_data(buf));
4555 b_reset(buf);
4556
4557 ret = qc_prep_app_pkts(qc, buf, frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004558 if (ret == -1) {
4559 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004560 goto err;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004561 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004562
Amaury Denoyelle37333862023-02-28 11:53:48 +01004563 if (!ret)
4564 break;
4565
4566 if (!qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004567 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4568 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004569 goto err;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004570 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004571 }
4572
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004573 status = 1;
4574 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004575 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4576 return status;
4577
4578 err:
Amaury Denoyelle37333862023-02-28 11:53:48 +01004579 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TXPKT, qc);
4580 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004581}
4582
4583/* Try to send application frames from list <frms> on connection <qc>. Use this
4584 * function when probing is required.
4585 *
4586 * Returns the result from qc_send_app_pkts function.
4587 */
4588static forceinline int qc_send_app_probing(struct quic_conn *qc,
4589 struct list *frms)
4590{
4591 int ret;
4592
4593 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4594
4595 TRACE_STATE("preparing old data (probing)", QUIC_EV_CONN_TXPKT, qc);
4596 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4597 ret = qc_send_app_pkts(qc, frms);
4598 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4599
4600 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4601 return ret;
4602}
4603
4604/* Try to send application frames from list <frms> on connection <qc>. This
4605 * function is provided for MUX upper layer usage only.
4606 *
4607 * Returns the result from qc_send_app_pkts function.
4608 */
4609int qc_send_mux(struct quic_conn *qc, struct list *frms)
4610{
4611 int ret;
4612
4613 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4614 BUG_ON(qc->mux_state != QC_MUX_READY); /* Only MUX can uses this function so it must be ready. */
4615
4616 TRACE_STATE("preparing data (from MUX)", QUIC_EV_CONN_TXPKT, qc);
4617 qc->flags |= QUIC_FL_CONN_TX_MUX_CONTEXT;
4618 ret = qc_send_app_pkts(qc, frms);
4619 qc->flags &= ~QUIC_FL_CONN_TX_MUX_CONTEXT;
4620
4621 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4622 return ret;
4623}
4624
4625/* Sends handshake packets from up to two encryption levels <tel> and <next_te>
4626 * with <tel_frms> and <next_tel_frms> as frame list respectively for <qc>
4627 * QUIC connection. <old_data> is used as boolean to send data already sent but
4628 * not already acknowledged (in flight).
4629 * Returns 1 if succeeded, 0 if not.
4630 */
4631int qc_send_hdshk_pkts(struct quic_conn *qc, int old_data,
4632 enum quic_tls_enc_level tel, struct list *tel_frms,
4633 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
4634{
4635 int ret, status = 0;
4636 struct buffer *buf = qc_txb_alloc(qc);
4637
4638 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4639
4640 if (!buf) {
4641 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4642 goto leave;
4643 }
4644
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004645 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4646 goto out;
4647
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004648 /* Currently buf cannot be non-empty at this stage. Even if a previous
4649 * sendto() has failed it is emptied to simulate packet emission and
4650 * rely on QUIC lost detection to try to emit it.
4651 */
4652 BUG_ON_HOT(b_data(buf));
4653 b_reset(buf);
4654
4655 if (old_data) {
4656 TRACE_STATE("old data for probing asked", QUIC_EV_CONN_TXPKT, qc);
4657 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4658 }
4659
4660 ret = qc_prep_pkts(qc, buf, tel, tel_frms, next_tel, next_tel_frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004661 if (ret == -1) {
4662 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004663 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004664 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004665
Amaury Denoyelle37333862023-02-28 11:53:48 +01004666 if (ret && !qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004667 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4668 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004669 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004670 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004671
Amaury Denoyelle37333862023-02-28 11:53:48 +01004672 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004673 status = 1;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004674
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004675 out:
4676 TRACE_STATE("no more need old data for probing", QUIC_EV_CONN_TXPKT, qc);
4677 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004678 leave:
4679 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4680 return status;
4681}
4682
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004683/* Retransmit up to two datagrams depending on packet number space.
4684 * Return 0 when failed, 0 if not.
4685 */
4686static int qc_dgrams_retransmit(struct quic_conn *qc)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004687{
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004688 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004689 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4690 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4691 struct quic_enc_level *aqel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4692
4693 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4694
4695 if (iqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004696 int i;
4697
4698 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
4699 struct list ifrms = LIST_HEAD_INIT(ifrms);
4700 struct list hfrms = LIST_HEAD_INIT(hfrms);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004701
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004702 qc_prep_hdshk_fast_retrans(qc, &ifrms, &hfrms);
4703 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &ifrms);
4704 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4705 if (!LIST_ISEMPTY(&ifrms)) {
4706 iqel->pktns->tx.pto_probe = 1;
4707 if (!LIST_ISEMPTY(&hfrms))
4708 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004709 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4710 QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms))
4711 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004712 /* Put back unsent frames in their packet number spaces */
4713 LIST_SPLICE(&iqel->pktns->tx.frms, &ifrms);
4714 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4715 }
Frédéric Lécailleec937212023-03-03 17:34:41 +01004716 else {
4717 if (!(qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
4718 iqel->pktns->tx.pto_probe = 1;
4719 if (!qc_send_hdshk_pkts(qc, 0, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4720 QUIC_TLS_ENC_LEVEL_NONE, NULL))
4721 goto leave;
4722 }
4723 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004724 }
4725 TRACE_STATE("no more need to probe Initial packet number space",
4726 QUIC_EV_CONN_TXPKT, qc);
4727 iqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004728 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004729 }
4730 else {
4731 int i;
4732
4733 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004734 hqel->pktns->tx.pto_probe = 0;
4735 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
Frédéric Lécaille7b5d9b12022-11-28 17:21:45 +01004736 struct list frms1 = LIST_HEAD_INIT(frms1);
4737
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004738 qc_prep_fast_retrans(qc, hqel, &frms1, NULL);
4739 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4740 if (!LIST_ISEMPTY(&frms1)) {
4741 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004742 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &frms1,
4743 QUIC_TLS_ENC_LEVEL_NONE, NULL))
4744 goto leave;
4745
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004746 /* Put back unsent frames into their packet number spaces */
4747 LIST_SPLICE(&hqel->pktns->tx.frms, &frms1);
4748 }
4749 }
4750 TRACE_STATE("no more need to probe Handshake packet number space",
4751 QUIC_EV_CONN_TXPKT, qc);
4752 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4753 }
4754 else if (aqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4755 struct list frms2 = LIST_HEAD_INIT(frms2);
4756 struct list frms1 = LIST_HEAD_INIT(frms1);
4757
4758 aqel->pktns->tx.pto_probe = 0;
4759 qc_prep_fast_retrans(qc, aqel, &frms1, &frms2);
4760 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4761 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms2);
4762 if (!LIST_ISEMPTY(&frms1)) {
4763 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004764 if (!qc_send_app_probing(qc, &frms1))
4765 goto leave;
4766
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004767 /* Put back unsent frames into their packet number spaces */
4768 LIST_SPLICE(&aqel->pktns->tx.frms, &frms1);
4769 }
4770 if (!LIST_ISEMPTY(&frms2)) {
4771 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004772 if (!qc_send_app_probing(qc, &frms2))
4773 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004774 /* Put back unsent frames into their packet number spaces */
4775 LIST_SPLICE(&aqel->pktns->tx.frms, &frms2);
4776 }
4777 TRACE_STATE("no more need to probe 01RTT packet number space",
4778 QUIC_EV_CONN_TXPKT, qc);
4779 aqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4780 }
4781 }
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004782
4783 ret = 1;
4784 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004785 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004786 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004787}
4788
4789/* QUIC connection packet handler task (post handshake) */
4790struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state)
4791{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004792 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004793 struct quic_enc_level *qel;
4794
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004795 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4796
4797 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
4798 TRACE_STATE("connection handshake state", QUIC_EV_CONN_IO_CB, qc, &qc->state);
4799
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004800 if (qc_test_fd(qc))
4801 qc_rcv_buf(qc);
4802
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004803 /* Retranmissions */
4804 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4805 TRACE_STATE("retransmission needed", QUIC_EV_CONN_IO_CB, qc);
4806 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004807 if (!qc_dgrams_retransmit(qc))
4808 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004809 }
4810
4811 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4812 qc_rm_hp_pkts(qc, qel);
4813
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004814 if (!qc_treat_rx_pkts(qc, qel, NULL)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004815 TRACE_DEVEL("qc_treat_rx_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4816 goto out;
4817 }
4818
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004819 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4820 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
4821 goto out;
4822 }
4823
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004824 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4825 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)) {
4826 TRACE_STATE("draining connection (must not send packets)", QUIC_EV_CONN_IO_CB, qc);
4827 goto out;
4828 }
4829
4830 /* XXX TODO: how to limit the list frames to send */
4831 if (!qc_send_app_pkts(qc, &qel->pktns->tx.frms)) {
4832 TRACE_DEVEL("qc_send_app_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4833 goto out;
4834 }
4835
4836 out:
4837 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
4838 return t;
4839}
4840
4841/* Returns a boolean if <qc> needs to emit frames for <qel> encryption level. */
4842static int qc_need_sending(struct quic_conn *qc, struct quic_enc_level *qel)
4843{
4844 return (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) ||
4845 (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) ||
4846 qel->pktns->tx.pto_probe ||
4847 !LIST_ISEMPTY(&qel->pktns->tx.frms);
4848}
4849
4850/* QUIC connection packet handler task. */
4851struct task *quic_conn_io_cb(struct task *t, void *context, unsigned int state)
4852{
4853 int ret, ssl_err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004854 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004855 enum quic_tls_enc_level tel, next_tel;
4856 struct quic_enc_level *qel, *next_qel;
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004857 /* Early-data encryption level */
4858 struct quic_enc_level *eqel;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004859 struct buffer *buf = NULL;
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004860 int st, zero_rtt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004861
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004862 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004863 eqel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004864 st = qc->state;
4865 TRACE_PROTO("connection state", QUIC_EV_CONN_IO_CB, qc, &st);
4866
4867 /* Retranmissions */
4868 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4869 TRACE_DEVEL("retransmission needed", QUIC_EV_CONN_PHPKTS, qc);
4870 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004871 if (!qc_dgrams_retransmit(qc))
4872 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004873 }
4874
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004875 ssl_err = SSL_ERROR_NONE;
4876 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004877 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004878 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004879
4880 if (qc_test_fd(qc))
4881 qc_rcv_buf(qc);
4882
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004883 if (st >= QUIC_HS_ST_COMPLETE &&
4884 qc_el_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
4885 TRACE_DEVEL("remaining Handshake packets", QUIC_EV_CONN_PHPKTS, qc);
4886 /* There may be remaining Handshake packets to treat and acknowledge. */
4887 tel = QUIC_TLS_ENC_LEVEL_HANDSHAKE;
4888 next_tel = QUIC_TLS_ENC_LEVEL_APP;
4889 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004890 else if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, zero_rtt))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004891 goto out;
4892
4893 qel = &qc->els[tel];
4894 next_qel = next_tel == QUIC_TLS_ENC_LEVEL_NONE ? NULL : &qc->els[next_tel];
4895
4896 next_level:
4897 /* Treat packets waiting for header packet protection decryption */
4898 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4899 qc_rm_hp_pkts(qc, qel);
4900
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004901 if (!qc_treat_rx_pkts(qc, qel, next_qel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004902 goto out;
4903
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004904 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4905 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_PHPKTS, qc);
4906 goto out;
4907 }
4908
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004909 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4910 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE))
4911 goto out;
4912
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004913 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004914 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004915 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
4916 if (next_qel && next_qel == eqel && zero_rtt) {
4917 TRACE_DEVEL("select 0RTT as next encryption level",
4918 QUIC_EV_CONN_PHPKTS, qc);
4919 qel = next_qel;
4920 next_qel = NULL;
4921 goto next_level;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004922 }
4923
4924 st = qc->state;
4925 if (st >= QUIC_HS_ST_COMPLETE) {
4926 if (!(qc->flags & QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT) &&
4927 !quic_build_post_handshake_frames(qc))
4928 goto out;
4929
4930 if (!(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].tls_ctx.flags &
4931 QUIC_FL_TLS_SECRETS_DCD)) {
4932 /* Discard the Handshake keys. */
4933 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4934 TRACE_PROTO("discarding Handshake pktns", QUIC_EV_CONN_PHPKTS, qc);
4935 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, qc);
4936 qc_set_timer(qc);
4937 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4938 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns);
4939 }
4940
4941 if (qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) {
4942 /* There may be remaining handshake to build (acks) */
4943 st = QUIC_HS_ST_SERVER_HANDSHAKE;
4944 }
4945 }
4946
4947 /* A listener does not send any O-RTT packet. O-RTT packet number space must not
4948 * be considered.
4949 */
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004950 if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, 0))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004951 goto out;
4952
4953 if (!qc_need_sending(qc, qel) &&
4954 (!next_qel || !qc_need_sending(qc, next_qel))) {
4955 goto skip_send;
4956 }
4957
4958 buf = qc_txb_alloc(qc);
4959 if (!buf)
4960 goto out;
4961
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004962 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4963 goto skip_send;
4964
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004965 /* Currently buf cannot be non-empty at this stage. Even if a previous
4966 * sendto() has failed it is emptied to simulate packet emission and
4967 * rely on QUIC lost detection to try to emit it.
4968 */
4969 BUG_ON_HOT(b_data(buf));
4970 b_reset(buf);
4971
4972 ret = qc_prep_pkts(qc, buf, tel, &qc->els[tel].pktns->tx.frms,
4973 next_tel, &qc->els[next_tel].pktns->tx.frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004974 if (ret == -1) {
4975 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004976 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004977 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004978
Amaury Denoyelle37333862023-02-28 11:53:48 +01004979 if (ret && !qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004980 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4981 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004982 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004983 }
4984
4985 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004986
4987 skip_send:
4988 /* Check if there is something to do for the next level.
4989 */
4990 if (next_qel && next_qel != qel &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004991 quic_tls_has_rx_sec(next_qel) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004992 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || qc_el_rx_pkts(next_qel))) {
4993 qel = next_qel;
4994 next_qel = NULL;
4995 goto next_level;
4996 }
4997
4998 out:
Frédéric Lécaille8f991942023-03-24 15:14:45 +01004999 TRACE_PROTO("ssl error", QUIC_EV_CONN_IO_CB, qc, &st, &ssl_err);
5000 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005001 return t;
5002}
5003
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02005004/* Release the memory allocated for <cs> CRYPTO stream */
5005void quic_cstream_free(struct quic_cstream *cs)
5006{
5007 if (!cs) {
5008 /* This is the case for ORTT encryption level */
5009 return;
5010 }
5011
Amaury Denoyellebc174b22022-11-17 10:12:52 +01005012 quic_free_ncbuf(&cs->rx.ncbuf);
5013
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02005014 qc_stream_desc_release(cs->desc);
5015 pool_free(pool_head_quic_cstream, cs);
5016}
5017
5018/* Allocate a new QUIC stream for <qc>.
5019 * Return it if succeeded, NULL if not.
5020 */
5021struct quic_cstream *quic_cstream_new(struct quic_conn *qc)
5022{
5023 struct quic_cstream *cs, *ret_cs = NULL;
5024
5025 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5026 cs = pool_alloc(pool_head_quic_cstream);
5027 if (!cs) {
5028 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
5029 goto leave;
5030 }
5031
5032 cs->rx.offset = 0;
5033 cs->rx.ncbuf = NCBUF_NULL;
5034 cs->rx.offset = 0;
5035
5036 cs->tx.offset = 0;
5037 cs->tx.sent_offset = 0;
5038 cs->tx.buf = BUF_NULL;
5039 cs->desc = qc_stream_desc_new((uint64_t)-1, -1, cs, qc);
5040 if (!cs->desc) {
5041 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
5042 goto err;
5043 }
5044
5045 ret_cs = cs;
5046 leave:
5047 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5048 return ret_cs;
5049
5050 err:
5051 pool_free(pool_head_quic_cstream, cs);
5052 goto leave;
5053}
5054
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005055/* Uninitialize <qel> QUIC encryption level. Never fails. */
5056static void quic_conn_enc_level_uninit(struct quic_conn *qc, struct quic_enc_level *qel)
5057{
5058 int i;
5059
5060 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5061
5062 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
5063 if (qel->tx.crypto.bufs[i]) {
5064 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
5065 qel->tx.crypto.bufs[i] = NULL;
5066 }
5067 }
5068 ha_free(&qel->tx.crypto.bufs);
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02005069 quic_cstream_free(qel->cstream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005070
5071 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5072}
5073
5074/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
5075 * connection allocating everything needed.
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005076 *
5077 * Returns 1 if succeeded, 0 if not. On error the caller is responsible to use
5078 * quic_conn_enc_level_uninit() to cleanup partially allocated content.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005079 */
5080static int quic_conn_enc_level_init(struct quic_conn *qc,
5081 enum quic_tls_enc_level level)
5082{
5083 int ret = 0;
5084 struct quic_enc_level *qel;
5085
5086 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5087
5088 qel = &qc->els[level];
5089 qel->level = quic_to_ssl_enc_level(level);
5090 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
5091 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
5092 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
5093 qel->tls_ctx.flags = 0;
5094
5095 qel->rx.pkts = EB_ROOT;
5096 LIST_INIT(&qel->rx.pqpkts);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005097
5098 /* Allocate only one buffer. */
5099 /* TODO: use a pool */
5100 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
5101 if (!qel->tx.crypto.bufs)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005102 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005103
5104 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
5105 if (!qel->tx.crypto.bufs[0])
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005106 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005107
5108 qel->tx.crypto.bufs[0]->sz = 0;
5109 qel->tx.crypto.nb_buf = 1;
5110
5111 qel->tx.crypto.sz = 0;
5112 qel->tx.crypto.offset = 0;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02005113 /* No CRYPTO data for early data TLS encryption level */
5114 if (level == QUIC_TLS_ENC_LEVEL_EARLY_DATA)
5115 qel->cstream = NULL;
5116 else {
5117 qel->cstream = quic_cstream_new(qc);
5118 if (!qel->cstream)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005119 goto leave;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02005120 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005121
5122 ret = 1;
5123 leave:
5124 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5125 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005126}
5127
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005128/* Return 1 if <qc> connection may probe the Initial packet number space, 0 if not.
5129 * This is not the case if the remote peer address is not validated and if
5130 * it cannot send at least QUIC_INITIAL_PACKET_MINLEN bytes.
5131 */
5132static int qc_may_probe_ipktns(struct quic_conn *qc)
5133{
5134 return quic_peer_validated_addr(qc) ||
5135 (int)(3 * qc->rx.bytes - qc->tx.prep_bytes) >= QUIC_INITIAL_PACKET_MINLEN;
5136}
5137
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005138/* Callback called upon loss detection and PTO timer expirations. */
5139struct task *qc_process_timer(struct task *task, void *ctx, unsigned int state)
5140{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005141 struct quic_conn *qc = ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005142 struct quic_pktns *pktns;
5143
Frédéric Lécaille8f991942023-03-24 15:14:45 +01005144 TRACE_ENTER(QUIC_EV_CONN_PTIMER, qc);
5145 TRACE_PROTO("process timer", QUIC_EV_CONN_PTIMER, qc,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005146 NULL, NULL, &qc->path->ifae_pkts);
5147 task->expire = TICK_ETERNITY;
5148 pktns = quic_loss_pktns(qc);
5149 if (tick_isset(pktns->tx.loss_time)) {
5150 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
5151
5152 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
5153 if (!LIST_ISEMPTY(&lost_pkts))
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005154 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01005155 if (qc_release_lost_pkts(qc, pktns, &lost_pkts, now_ms))
5156 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005157 goto out;
5158 }
5159
5160 if (qc->path->in_flight) {
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +01005161 pktns = quic_pto_pktns(qc, qc->state >= QUIC_HS_ST_CONFIRMED, NULL);
Amaury Denoyelle2a19b6e2023-03-20 18:29:36 +01005162 if (pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL]) {
5163 if (qc_may_probe_ipktns(qc)) {
5164 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5165 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
5166 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5167 }
5168 else {
5169 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5170 }
5171 if (qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].tx.in_flight) {
5172 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5173 qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
5174 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
5175 }
Frédéric Lécaillee25fce02023-03-20 17:23:19 +01005176 }
Amaury Denoyelle2a19b6e2023-03-20 18:29:36 +01005177 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE]) {
5178 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
5179 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5180 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
5181 if (qc->pktns[QUIC_TLS_PKTNS_INITIAL].tx.in_flight) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005182 if (qc_may_probe_ipktns(qc)) {
Amaury Denoyelle2a19b6e2023-03-20 18:29:36 +01005183 qc->pktns[QUIC_TLS_PKTNS_INITIAL].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005184 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5185 }
5186 else {
5187 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5188 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005189 }
Amaury Denoyelle2a19b6e2023-03-20 18:29:36 +01005190 }
5191 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT]) {
Amaury Denoyelle8afe4b82023-03-21 11:39:24 +01005192 pktns->tx.pto_probe = QUIC_MAX_NB_PTO_DGRAMS;
Amaury Denoyelle2a19b6e2023-03-20 18:29:36 +01005193 /* Wake up upper layer if waiting to send new data. */
5194 if (!qc_notify_send(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005195 TRACE_STATE("needs to probe 01RTT packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005196 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5197 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005198 }
5199 }
5200 }
5201 else if (!qc_is_listener(qc) && qc->state <= QUIC_HS_ST_COMPLETE) {
5202 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
5203 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
5204
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02005205 if (quic_tls_has_tx_sec(hel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005206 hel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02005207 if (quic_tls_has_tx_sec(iel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005208 iel->pktns->tx.pto_probe = 1;
5209 }
5210
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005211 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005212 qc->path->loss.pto_count++;
5213
5214 out:
Frédéric Lécaille8f991942023-03-24 15:14:45 +01005215 TRACE_PROTO("process timer", QUIC_EV_CONN_PTIMER, qc, pktns);
5216 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005217
5218 return task;
5219}
5220
5221/* Parse the Retry token from buffer <token> with <end> a pointer to
5222 * one byte past the end of this buffer. This will extract the ODCID
5223 * which will be stored into <odcid>
5224 *
5225 * Returns 0 on success else non-zero.
5226 */
5227static int parse_retry_token(struct quic_conn *qc,
5228 const unsigned char *token, const unsigned char *end,
5229 struct quic_cid *odcid)
5230{
5231 int ret = 0;
5232 uint64_t odcid_len;
5233 uint32_t timestamp;
5234
5235 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5236
5237 if (!quic_dec_int(&odcid_len, &token, end)) {
5238 TRACE_ERROR("quic_dec_int() error", QUIC_EV_CONN_LPKT, qc);
5239 goto leave;
5240 }
5241
5242 /* RFC 9000 7.2. Negotiating Connection IDs:
5243 * When an Initial packet is sent by a client that has not previously
5244 * received an Initial or Retry packet from the server, the client
5245 * populates the Destination Connection ID field with an unpredictable
5246 * value. This Destination Connection ID MUST be at least 8 bytes in length.
5247 */
5248 if (odcid_len < QUIC_ODCID_MINLEN || odcid_len > QUIC_CID_MAXLEN) {
5249 TRACE_ERROR("wrong ODCID length", QUIC_EV_CONN_LPKT, qc);
5250 goto leave;
5251 }
5252
5253 if (end - token < odcid_len + sizeof timestamp) {
5254 TRACE_ERROR("too long ODCID length", QUIC_EV_CONN_LPKT, qc);
5255 goto leave;
5256 }
5257
5258 timestamp = ntohl(read_u32(token + odcid_len));
5259 if (timestamp + MS_TO_TICKS(QUIC_RETRY_DURATION_MS) <= now_ms) {
5260 TRACE_ERROR("token has expired", QUIC_EV_CONN_LPKT, qc);
5261 goto leave;
5262 }
5263
5264 ret = 1;
5265 memcpy(odcid->data, token, odcid_len);
5266 odcid->len = odcid_len;
5267 leave:
5268 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5269 return !ret;
5270}
5271
5272/* Allocate a new QUIC connection with <version> as QUIC version. <ipv4>
5273 * boolean is set to 1 for IPv4 connection, 0 for IPv6. <server> is set to 1
5274 * for QUIC servers (or haproxy listeners).
5275 * <dcid> is the destination connection ID, <scid> is the source connection ID,
5276 * <token> the token found to be used for this connection with <token_len> as
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005277 * length. Endpoints addresses are specified via <local_addr> and <peer_addr>.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005278 * Returns the connection if succeeded, NULL if not.
5279 */
5280static struct quic_conn *qc_new_conn(const struct quic_version *qv, int ipv4,
5281 struct quic_cid *dcid, struct quic_cid *scid,
5282 const struct quic_cid *token_odcid,
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005283 struct sockaddr_storage *local_addr,
5284 struct sockaddr_storage *peer_addr,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005285 int server, int token, void *owner)
5286{
5287 int i;
5288 struct quic_conn *qc;
5289 /* Initial CID. */
5290 struct quic_connection_id *icid;
5291 char *buf_area = NULL;
5292 struct listener *l = NULL;
5293 struct quic_cc_algo *cc_algo = NULL;
5294 struct quic_tls_ctx *ictx;
5295 TRACE_ENTER(QUIC_EV_CONN_INIT);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005296 /* TODO replace pool_zalloc by pool_alloc(). This requires special care
5297 * to properly initialized internal quic_conn members to safely use
5298 * quic_conn_release() on alloc failure.
5299 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005300 qc = pool_zalloc(pool_head_quic_conn);
5301 if (!qc) {
5302 TRACE_ERROR("Could not allocate a new connection", QUIC_EV_CONN_INIT);
5303 goto err;
5304 }
5305
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005306 /* Initialize in priority qc members required for a safe dealloc. */
5307
5308 /* required to use MTLIST_IN_LIST */
5309 MT_LIST_INIT(&qc->accept_list);
5310
5311 LIST_INIT(&qc->rx.pkt_list);
5312
Amaury Denoyelle42448332022-12-12 11:24:05 +01005313 qc_init_fd(qc);
5314
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005315 LIST_INIT(&qc->back_refs);
5316
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005317 /* Now proceeds to allocation of qc members. */
5318
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005319 buf_area = pool_alloc(pool_head_quic_conn_rxbuf);
5320 if (!buf_area) {
5321 TRACE_ERROR("Could not allocate a new RX buffer", QUIC_EV_CONN_INIT, qc);
5322 goto err;
5323 }
5324
5325 qc->cids = EB_ROOT;
5326 /* QUIC Server (or listener). */
5327 if (server) {
5328 struct proxy *prx;
5329
5330 l = owner;
5331 prx = l->bind_conf->frontend;
5332 cc_algo = l->bind_conf->quic_cc_algo;
5333
5334 qc->prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe,
5335 &quic_stats_module);
5336 qc->flags |= QUIC_FL_CONN_LISTENER;
5337 qc->state = QUIC_HS_ST_SERVER_INITIAL;
5338 /* Copy the initial DCID with the address. */
5339 qc->odcid.len = dcid->len;
5340 qc->odcid.addrlen = dcid->addrlen;
5341 memcpy(qc->odcid.data, dcid->data, dcid->len + dcid->addrlen);
5342
5343 /* copy the packet SCID to reuse it as DCID for sending */
5344 if (scid->len)
5345 memcpy(qc->dcid.data, scid->data, scid->len);
5346 qc->dcid.len = scid->len;
5347 qc->tx.buf = BUF_NULL;
5348 qc->li = l;
5349 }
5350 /* QUIC Client (outgoing connection to servers) */
5351 else {
5352 qc->state = QUIC_HS_ST_CLIENT_INITIAL;
5353 if (dcid->len)
5354 memcpy(qc->dcid.data, dcid->data, dcid->len);
5355 qc->dcid.len = dcid->len;
5356 }
5357 qc->mux_state = QC_MUX_NULL;
5358 qc->err = quic_err_transport(QC_ERR_NO_ERROR);
5359
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01005360 /* Initialize the next CID sequence number to be used for this connection. */
5361 qc->next_cid_seq_num = 0;
5362 /* Insert the CID for this connection with 0 as sequence number. */
5363 icid = new_quic_cid(&qc->cids, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005364 if (!icid) {
5365 TRACE_ERROR("Could not allocate a new connection ID", QUIC_EV_CONN_INIT, qc);
5366 goto err;
5367 }
5368
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005369 if ((global.tune.options & GTUNE_QUIC_SOCK_PER_CONN) &&
5370 is_addr(local_addr)) {
5371 TRACE_USER("Allocate a socket for QUIC connection", QUIC_EV_CONN_INIT, qc);
5372 qc_alloc_fd(qc, local_addr, peer_addr);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005373
5374 /* haproxy soft-stop is supported only for QUIC connections
5375 * with their owned socket.
5376 */
5377 if (qc_test_fd(qc))
5378 _HA_ATOMIC_INC(&jobs);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005379 }
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005380
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005381 /* insert the allocated CID in the receiver datagram handler tree */
5382 if (server)
5383 ebmb_insert(&quic_dghdlrs[tid].cids, &icid->node, icid->cid.len);
5384
5385 /* Select our SCID which is the first CID with 0 as sequence number. */
5386 qc->scid = icid->cid;
5387
5388 /* Packet number spaces initialization. */
5389 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
5390 quic_pktns_init(&qc->pktns[i]);
5391 /* QUIC encryption level context initialization. */
5392 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5393 if (!quic_conn_enc_level_init(qc, i)) {
5394 TRACE_ERROR("Could not initialize an encryption level", QUIC_EV_CONN_INIT, qc);
5395 goto err;
5396 }
5397 /* Initialize the packet number space. */
5398 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
5399 }
5400
5401 qc->original_version = qv;
5402 qc->tps_tls_ext = (qc->original_version->num & 0xff000000) == 0xff000000 ?
5403 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS_DRAFT:
5404 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS;
5405 /* TX part. */
5406 LIST_INIT(&qc->tx.frms_to_send);
5407 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
5408 qc->tx.wbuf = qc->tx.rbuf = 0;
5409 qc->tx.bytes = 0;
5410 qc->tx.buf = BUF_NULL;
5411 /* RX part. */
5412 qc->rx.bytes = 0;
5413 qc->rx.buf = b_make(buf_area, QUIC_CONN_RX_BUFSZ, 0, 0);
5414 for (i = 0; i < QCS_MAX_TYPES; i++)
5415 qc->rx.strms[i].nb_streams = 0;
5416
5417 qc->nb_pkt_for_cc = 1;
5418 qc->nb_pkt_since_cc = 0;
5419
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005420 if (!quic_tls_ku_init(qc)) {
5421 TRACE_ERROR("Key update initialization failed", QUIC_EV_CONN_INIT, qc);
5422 goto err;
5423 }
5424
5425 /* XXX TO DO: Only one path at this time. */
5426 qc->path = &qc->paths[0];
5427 quic_path_init(qc->path, ipv4, cc_algo ? cc_algo : default_quic_cc_algo, qc);
5428
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005429 qc->streams_by_id = EB_ROOT_UNIQUE;
5430 qc->stream_buf_count = 0;
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005431 memcpy(&qc->local_addr, local_addr, sizeof(qc->local_addr));
5432 memcpy(&qc->peer_addr, peer_addr, sizeof qc->peer_addr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005433
5434 if (server && !qc_lstnr_params_init(qc, &l->bind_conf->quic_params,
5435 icid->stateless_reset_token,
5436 dcid->data, dcid->len,
5437 qc->scid.data, qc->scid.len, token_odcid))
5438 goto err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005439
Frédéric Lécailledeb97812023-03-22 11:29:45 +01005440 /* Initialize the idle timeout of the connection at the "max_idle_timeout"
5441 * value from local transport parameters.
5442 */
5443 qc->max_idle_timeout = qc->rx.params.max_idle_timeout;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005444 qc->wait_event.tasklet = tasklet_new();
5445 if (!qc->wait_event.tasklet) {
5446 TRACE_ERROR("tasklet_new() failed", QUIC_EV_CONN_TXPKT);
5447 goto err;
5448 }
5449 qc->wait_event.tasklet->process = quic_conn_io_cb;
5450 qc->wait_event.tasklet->context = qc;
5451 qc->wait_event.events = 0;
5452 /* Set tasklet tid based on the SCID selected by us for this
5453 * connection. The upper layer will also be binded on the same thread.
5454 */
Willy Tarreaueed78262022-12-21 09:09:19 +01005455 qc->tid = quic_get_cid_tid(qc->scid.data, &l->rx);
Willy Tarreauf5a0c8a2022-10-13 16:14:11 +02005456 qc->wait_event.tasklet->tid = qc->tid;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02005457 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005458
5459 if (qc_conn_alloc_ssl_ctx(qc) ||
5460 !quic_conn_init_timer(qc) ||
5461 !quic_conn_init_idle_timer_task(qc))
5462 goto err;
5463
5464 ictx = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
5465 if (!qc_new_isecs(qc, ictx,qc->original_version, dcid->data, dcid->len, 1))
5466 goto err;
5467
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005468 LIST_APPEND(&th_ctx->quic_conns, &qc->el_th_ctx);
5469 qc->qc_epoch = HA_ATOMIC_LOAD(&qc_epoch);
5470
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005471 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc);
5472
5473 return qc;
5474
5475 err:
5476 pool_free(pool_head_quic_conn_rxbuf, buf_area);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005477 if (qc) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005478 qc->rx.buf.area = NULL;
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005479 quic_conn_release(qc);
5480 }
5481 TRACE_LEAVE(QUIC_EV_CONN_INIT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005482 return NULL;
5483}
5484
5485/* Release the quic_conn <qc>. The connection is removed from the CIDs tree.
5486 * The connection tasklet is killed.
5487 *
5488 * This function must only be called by the thread responsible of the quic_conn
5489 * tasklet.
5490 */
5491void quic_conn_release(struct quic_conn *qc)
5492{
5493 int i;
5494 struct ssl_sock_ctx *conn_ctx;
5495 struct eb64_node *node;
5496 struct quic_tls_ctx *app_tls_ctx;
5497 struct quic_rx_packet *pkt, *pktback;
5498
5499 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5500
5501 /* We must not free the quic-conn if the MUX is still allocated. */
5502 BUG_ON(qc->mux_state == QC_MUX_READY);
5503
Amaury Denoyellefb375572023-02-01 09:28:32 +01005504 if (qc_test_fd(qc))
5505 _HA_ATOMIC_DEC(&jobs);
5506
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005507 /* Close quic-conn socket fd. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01005508 qc_release_fd(qc, 0);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005509
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005510 /* in the unlikely (but possible) case the connection was just added to
5511 * the accept_list we must delete it from there.
5512 */
5513 MT_LIST_DELETE(&qc->accept_list);
5514
5515 /* free remaining stream descriptors */
5516 node = eb64_first(&qc->streams_by_id);
5517 while (node) {
5518 struct qc_stream_desc *stream;
5519
5520 stream = eb64_entry(node, struct qc_stream_desc, by_id);
5521 node = eb64_next(node);
5522
5523 /* all streams attached to the quic-conn are released, so
5524 * qc_stream_desc_free will liberate the stream instance.
5525 */
5526 BUG_ON(!stream->release);
5527 qc_stream_desc_free(stream, 1);
5528 }
5529
5530 /* Purge Rx packet list. */
5531 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
5532 LIST_DELETE(&pkt->qc_rx_pkt_list);
5533 pool_free(pool_head_quic_rx_packet, pkt);
5534 }
5535
5536 if (qc->idle_timer_task) {
5537 task_destroy(qc->idle_timer_task);
5538 qc->idle_timer_task = NULL;
5539 }
5540
5541 if (qc->timer_task) {
5542 task_destroy(qc->timer_task);
5543 qc->timer_task = NULL;
5544 }
5545
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005546 if (qc->wait_event.tasklet)
5547 tasklet_free(qc->wait_event.tasklet);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005548
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005549 /* remove the connection from receiver cids trees */
5550 ebmb_delete(&qc->odcid_node);
5551 ebmb_delete(&qc->scid_node);
5552 free_quic_conn_cids(qc);
5553
5554 conn_ctx = qc->xprt_ctx;
5555 if (conn_ctx) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005556 SSL_free(conn_ctx->ssl);
5557 pool_free(pool_head_quic_conn_ctx, conn_ctx);
5558 }
5559
5560 quic_tls_ku_free(qc);
5561 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5562 quic_tls_ctx_secs_free(&qc->els[i].tls_ctx);
5563 quic_conn_enc_level_uninit(qc, &qc->els[i]);
5564 }
5565 quic_tls_ctx_secs_free(&qc->negotiated_ictx);
5566
5567 app_tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
5568 pool_free(pool_head_quic_tls_secret, app_tls_ctx->rx.secret);
5569 pool_free(pool_head_quic_tls_secret, app_tls_ctx->tx.secret);
5570
5571 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++) {
5572 quic_pktns_tx_pkts_release(&qc->pktns[i], qc);
5573 quic_free_arngs(qc, &qc->pktns[i].rx.arngs);
5574 }
5575
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01005576 qc_detach_th_ctx_list(qc, 0);
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005577
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005578 pool_free(pool_head_quic_conn_rxbuf, qc->rx.buf.area);
5579 pool_free(pool_head_quic_conn, qc);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005580
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005581 TRACE_PROTO("QUIC conn. freed", QUIC_EV_CONN_FREED, qc);
5582
5583 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5584}
5585
5586/* Initialize the timer task of <qc> QUIC connection.
5587 * Returns 1 if succeeded, 0 if not.
5588 */
5589static int quic_conn_init_timer(struct quic_conn *qc)
5590{
5591 int ret = 0;
5592 /* Attach this task to the same thread ID used for the connection */
5593 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5594
5595 qc->timer_task = task_new_on(qc->tid);
5596 if (!qc->timer_task) {
5597 TRACE_ERROR("timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5598 goto leave;
5599 }
5600
5601 qc->timer = TICK_ETERNITY;
5602 qc->timer_task->process = qc_process_timer;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005603 qc->timer_task->context = qc;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005604
5605 ret = 1;
5606 leave:
5607 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5608 return ret;
5609}
5610
Frédéric Lécailled7215712023-03-24 18:13:37 +01005611/* Rearm the idle timer or the ack timer (if not already armde) for <qc> QUIC
5612 * connection. */
5613static void qc_idle_timer_do_rearm(struct quic_conn *qc, int arm_ack)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005614{
5615 unsigned int expire;
5616
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01005617 if (stopping && qc->flags & (QUIC_FL_CONN_CLOSING|QUIC_FL_CONN_DRAINING)) {
5618 TRACE_STATE("executing idle timer immediately on stopping", QUIC_EV_CONN_IDLE_TIMER, qc);
Frédéric Lécailled7215712023-03-24 18:13:37 +01005619 qc->ack_expire = TICK_ETERNITY;
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01005620 task_wakeup(qc->idle_timer_task, TASK_WOKEN_MSG);
5621 }
5622 else {
5623 expire = QUIC_MAX(3 * quic_pto(qc), qc->max_idle_timeout);
Frédéric Lécailled7215712023-03-24 18:13:37 +01005624 qc->idle_expire = tick_add(now_ms, MS_TO_TICKS(expire));
5625 if (arm_ack) {
5626 /* Arm the ack timer only if not already armed. */
5627 if (!tick_isset(qc->ack_expire)) {
5628 qc->ack_expire = tick_add(now_ms, MS_TO_TICKS(QUIC_ACK_DELAY));
5629 qc->idle_timer_task->expire = qc->ack_expire;
5630 task_queue(qc->idle_timer_task);
5631 TRACE_PROTO("ack timer armed", QUIC_EV_CONN_SSLALERT, qc);
5632 }
5633 }
5634 else {
5635 qc->idle_timer_task->expire = tick_first(qc->ack_expire, qc->idle_expire);
5636 task_queue(qc->idle_timer_task);
5637 }
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01005638 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005639}
5640
Frédéric Lécailled7215712023-03-24 18:13:37 +01005641/* Rearm the idle timer or ack timer for <qc> QUIC connection depending on <read>
5642 * and <arm_ack> booleans. The former is set to 1 when receiving a packet ,
5643 * and 0 when sending packet. <arm_ack> is set to 1 if this is the ack timer
5644 * which must be rearmed.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005645 */
Frédéric Lécailled7215712023-03-24 18:13:37 +01005646static void qc_idle_timer_rearm(struct quic_conn *qc, int read, int arm_ack)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005647{
5648 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5649
5650 if (read) {
5651 qc->flags |= QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5652 }
5653 else {
5654 qc->flags &= ~QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5655 }
Frédéric Lécailled7215712023-03-24 18:13:37 +01005656 qc_idle_timer_do_rearm(qc, arm_ack);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005657
5658 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5659}
5660
5661/* The task handling the idle timeout */
5662struct task *qc_idle_timer_task(struct task *t, void *ctx, unsigned int state)
5663{
5664 struct quic_conn *qc = ctx;
5665 struct quic_counters *prx_counters = qc->prx_counters;
5666 unsigned int qc_flags = qc->flags;
5667
5668 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5669
Frédéric Lécailled7215712023-03-24 18:13:37 +01005670 if (tick_is_expired(qc->ack_expire, now_ms)) {
5671 TRACE_PROTO("ack timer expired", QUIC_EV_CONN_SSLALERT, qc);
5672 qc->ack_expire = TICK_ETERNITY;
5673 /* Note that ->idle_expire is always set. */
5674 t->expire = qc->idle_expire;
5675 qc->flags |= QUIC_FL_CONN_ACK_TIMER_FIRED;
5676 tasklet_wakeup(qc->wait_event.tasklet);
5677 goto requeue;
5678 }
5679
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005680 /* Notify the MUX before settings QUIC_FL_CONN_EXP_TIMER or the MUX
5681 * might free the quic-conn too early via quic_close().
5682 */
5683 qc_notify_close(qc);
5684
5685 /* If the MUX is still alive, keep the quic-conn. The MUX is
5686 * responsible to call quic_close to release it.
5687 */
5688 qc->flags |= QUIC_FL_CONN_EXP_TIMER;
5689 if (qc->mux_state != QC_MUX_READY)
5690 quic_conn_release(qc);
5691
5692 /* TODO if the quic-conn cannot be freed because of the MUX, we may at
5693 * least clean some parts of it such as the tasklet.
5694 */
5695
5696 if (!(qc_flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
5697 qc_flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
5698 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
5699 HA_ATOMIC_DEC(&prx_counters->half_open_conn);
5700 }
5701
Frédéric Lécailled7215712023-03-24 18:13:37 +01005702 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005703 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5704 return NULL;
Frédéric Lécailled7215712023-03-24 18:13:37 +01005705
5706 requeue:
5707 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5708 return t;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005709}
5710
5711/* Initialize the idle timeout task for <qc>.
5712 * Returns 1 if succeeded, 0 if not.
5713 */
5714static int quic_conn_init_idle_timer_task(struct quic_conn *qc)
5715{
5716 int ret = 0;
5717
5718 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5719
5720 qc->idle_timer_task = task_new_here();
5721 if (!qc->idle_timer_task) {
5722 TRACE_ERROR("Idle timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5723 goto leave;
5724 }
5725
5726 qc->idle_timer_task->process = qc_idle_timer_task;
5727 qc->idle_timer_task->context = qc;
Frédéric Lécailled7215712023-03-24 18:13:37 +01005728 qc->ack_expire = TICK_ETERNITY;
5729 qc_idle_timer_rearm(qc, 1, 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005730 task_queue(qc->idle_timer_task);
5731
5732 ret = 1;
5733 leave:
5734 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5735 return ret;
5736}
5737
5738/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
5739 * past one byte of this buffer.
5740 */
5741static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
5742 struct quic_rx_packet *pkt)
5743{
5744 int ret = 0;
5745 unsigned char dcid_len, scid_len;
5746
5747 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5748
5749 if (end == *buf) {
5750 TRACE_ERROR("buffer data consumed", QUIC_EV_CONN_RXPKT);
5751 goto leave;
5752 }
5753
5754 /* Destination Connection ID Length */
5755 dcid_len = *(*buf)++;
5756 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
5757 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1) {
5758 TRACE_ERROR("too long DCID", QUIC_EV_CONN_RXPKT);
5759 goto leave;
5760 }
5761
5762 if (dcid_len) {
5763 /* Check that the length of this received DCID matches the CID lengths
5764 * of our implementation for non Initials packets only.
5765 */
5766 if (pkt->type != QUIC_PACKET_TYPE_INITIAL &&
5767 pkt->type != QUIC_PACKET_TYPE_0RTT &&
5768 dcid_len != QUIC_HAP_CID_LEN) {
5769 TRACE_ERROR("wrong DCID length", QUIC_EV_CONN_RXPKT);
5770 goto leave;
5771 }
5772
5773 memcpy(pkt->dcid.data, *buf, dcid_len);
5774 }
5775
5776 pkt->dcid.len = dcid_len;
5777 *buf += dcid_len;
5778
5779 /* Source Connection ID Length */
5780 scid_len = *(*buf)++;
5781 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len) {
5782 TRACE_ERROR("too long SCID", QUIC_EV_CONN_RXPKT);
5783 goto leave;
5784 }
5785
5786 if (scid_len)
5787 memcpy(pkt->scid.data, *buf, scid_len);
5788 pkt->scid.len = scid_len;
5789 *buf += scid_len;
5790
5791 ret = 1;
5792 leave:
5793 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5794 return ret;
5795}
5796
5797/* Insert <pkt> RX packet in its <qel> RX packets tree */
5798static void qc_pkt_insert(struct quic_conn *qc,
5799 struct quic_rx_packet *pkt, struct quic_enc_level *qel)
5800{
5801 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
5802
5803 pkt->pn_node.key = pkt->pn;
5804 quic_rx_packet_refinc(pkt);
5805 eb64_insert(&qel->rx.pkts, &pkt->pn_node);
5806
5807 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5808}
5809
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005810/* Try to remove the header protection of <pkt> QUIC packet with <beg> the
5811 * address of the packet first byte, using the keys from encryption level <el>.
5812 *
5813 * If header protection has been successfully removed, packet data are copied
5814 * into <qc> Rx buffer. If <el> secrets are not yet available, the copy is also
5815 * proceeded, and the packet is inserted into <qc> protected packets tree. In
5816 * both cases, packet can now be considered handled by the <qc> connection.
5817 *
5818 * If header protection cannot be removed due to <el> secrets already
5819 * discarded, no operation is conducted.
5820 *
5821 * Returns 1 on success : packet data is now handled by the connection. On
5822 * error 0 is returned : packet should be dropped by the caller.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005823 */
5824static inline int qc_try_rm_hp(struct quic_conn *qc,
5825 struct quic_rx_packet *pkt,
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005826 unsigned char *beg,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005827 struct quic_enc_level **el)
5828{
5829 int ret = 0;
5830 unsigned char *pn = NULL; /* Packet number field */
5831 enum quic_tls_enc_level tel;
5832 struct quic_enc_level *qel;
5833 /* Only for traces. */
5834 struct quic_rx_packet *qpkt_trace;
5835
5836 qpkt_trace = NULL;
5837 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005838 BUG_ON(!pkt->pn_offset);
5839
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005840 /* The packet number is here. This is also the start minus
5841 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
5842 * protection.
5843 */
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005844 pn = beg + pkt->pn_offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005845
5846 tel = quic_packet_type_enc_level(pkt->type);
5847 qel = &qc->els[tel];
5848
5849 if (qc_qel_may_rm_hp(qc, qel)) {
Frédéric Lécaille72027782023-02-22 16:20:09 +01005850 struct quic_tls_ctx *tls_ctx = qc_select_tls_ctx(qc, qel, pkt);
5851
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005852 /* Note that the following function enables us to unprotect the packet
5853 * number and its length subsequently used to decrypt the entire
5854 * packets.
5855 */
Frédéric Lécaille72027782023-02-22 16:20:09 +01005856 if (!qc_do_rm_hp(qc, pkt, tls_ctx,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005857 qel->pktns->rx.largest_pn, pn, beg)) {
5858 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, qc);
5859 goto out;
5860 }
5861
Frédéric Lécailleece86e62023-03-07 11:53:43 +01005862 qc_handle_spin_bit(qc, pkt, qel);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005863 /* The AAD includes the packet number field. */
5864 pkt->aad_len = pkt->pn_offset + pkt->pnl;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005865 if (pkt->len - pkt->aad_len < QUIC_TLS_TAG_LEN) {
5866 TRACE_PROTO("Too short packet", QUIC_EV_CONN_TRMHP, qc);
5867 goto out;
5868 }
5869
5870 qpkt_trace = pkt;
5871 }
5872 else {
5873 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
5874 /* If the packet number space has been discarded, this packet
5875 * will be not parsed.
5876 */
5877 TRACE_PROTO("Discarded pktns", QUIC_EV_CONN_TRMHP, qc, pkt);
5878 goto out;
5879 }
5880
Frédéric Lécaille8f991942023-03-24 15:14:45 +01005881 TRACE_PROTO("RX hp not removed", QUIC_EV_CONN_TRMHP, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005882 LIST_APPEND(&qel->rx.pqpkts, &pkt->list);
5883 quic_rx_packet_refinc(pkt);
5884 }
5885
5886 *el = qel;
5887 /* No reference counter incrementation here!!! */
5888 LIST_APPEND(&qc->rx.pkt_list, &pkt->qc_rx_pkt_list);
5889 memcpy(b_tail(&qc->rx.buf), beg, pkt->len);
5890 pkt->data = (unsigned char *)b_tail(&qc->rx.buf);
5891 b_add(&qc->rx.buf, pkt->len);
5892
5893 ret = 1;
5894 out:
5895 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc, qpkt_trace);
5896 return ret;
5897}
5898
5899/* Parse the header form from <byte0> first byte of <pkt> packet to set its type.
5900 * Also set <*long_header> to 1 if this form is long, 0 if not and the version
5901 * of this packet into <*version>.
5902 */
5903static inline int qc_parse_hd_form(struct quic_rx_packet *pkt,
5904 unsigned char **buf, const unsigned char *end,
5905 int *long_header, uint32_t *version)
5906{
5907 int ret = 0;
5908 const unsigned char byte0 = **buf;
5909
5910 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5911
5912 (*buf)++;
5913 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
5914 unsigned char type =
5915 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
5916
5917 *long_header = 1;
5918 /* Version */
5919 if (!quic_read_uint32(version, (const unsigned char **)buf, end)) {
5920 TRACE_ERROR("could not read the packet version", QUIC_EV_CONN_RXPKT);
5921 goto out;
5922 }
5923
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +01005924 if (*version != QUIC_PROTOCOL_VERSION_2) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005925 pkt->type = type;
5926 }
5927 else {
5928 switch (type) {
5929 case 0:
5930 pkt->type = QUIC_PACKET_TYPE_RETRY;
5931 break;
5932 case 1:
5933 pkt->type = QUIC_PACKET_TYPE_INITIAL;
5934 break;
5935 case 2:
5936 pkt->type = QUIC_PACKET_TYPE_0RTT;
5937 break;
5938 case 3:
5939 pkt->type = QUIC_PACKET_TYPE_HANDSHAKE;
5940 break;
5941 }
5942 }
5943 }
5944 else {
Frédéric Lécailleece86e62023-03-07 11:53:43 +01005945 if (byte0 & QUIC_PACKET_SPIN_BIT)
5946 pkt->flags |= QUIC_FL_RX_PACKET_SPIN_BIT;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005947 pkt->type = QUIC_PACKET_TYPE_SHORT;
5948 *long_header = 0;
5949 }
5950
5951 ret = 1;
5952 out:
5953 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5954 return ret;
5955}
5956
5957/* Return the QUIC version (quic_version struct) with <version> as version number
5958 * if supported or NULL if not.
5959 */
5960static inline const struct quic_version *qc_supported_version(uint32_t version)
5961{
5962 int i;
5963
5964 for (i = 0; i < quic_versions_nb; i++)
5965 if (quic_versions[i].num == version)
5966 return &quic_versions[i];
5967
5968 return NULL;
5969}
5970
5971/*
5972 * Send a Version Negotiation packet on response to <pkt> on socket <fd> to
5973 * address <addr>.
5974 * Implementation of RFC9000 6. Version Negotiation
5975 *
5976 * TODO implement a rate-limiting sending of Version Negotiation packets
5977 *
5978 * Returns 0 on success else non-zero
5979 */
5980static int send_version_negotiation(int fd, struct sockaddr_storage *addr,
5981 struct quic_rx_packet *pkt)
5982{
5983 char buf[256];
5984 int ret = 0, i = 0, j;
5985 uint32_t version;
5986 const socklen_t addrlen = get_addr_len(addr);
5987
5988 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5989 /*
5990 * header form
5991 * long header, fixed bit to 0 for Version Negotiation
5992 */
5993 /* TODO: RAND_bytes() should be replaced? */
5994 if (RAND_bytes((unsigned char *)buf, 1) != 1) {
5995 TRACE_ERROR("RAND_bytes() error", QUIC_EV_CONN_TXPKT);
5996 goto out;
5997 }
5998
5999 buf[i++] |= '\x80';
6000 /* null version for Version Negotiation */
6001 buf[i++] = '\x00';
6002 buf[i++] = '\x00';
6003 buf[i++] = '\x00';
6004 buf[i++] = '\x00';
6005
6006 /* source connection id */
6007 buf[i++] = pkt->scid.len;
6008 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
6009 i += pkt->scid.len;
6010
6011 /* destination connection id */
6012 buf[i++] = pkt->dcid.len;
6013 memcpy(&buf[i], pkt->dcid.data, pkt->dcid.len);
6014 i += pkt->dcid.len;
6015
6016 /* supported version */
6017 for (j = 0; j < quic_versions_nb; j++) {
6018 version = htonl(quic_versions[j].num);
6019 memcpy(&buf[i], &version, sizeof(version));
6020 i += sizeof(version);
6021 }
6022
6023 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0)
6024 goto out;
6025
6026 ret = 1;
6027 out:
6028 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
6029 return !ret;
6030}
6031
6032/* Send a stateless reset packet depending on <pkt> RX packet information
6033 * from <fd> UDP socket to <dst>
6034 * Return 1 if succeeded, 0 if not.
6035 */
6036static int send_stateless_reset(struct listener *l, struct sockaddr_storage *dstaddr,
6037 struct quic_rx_packet *rxpkt)
6038{
6039 int ret = 0, pktlen, rndlen;
6040 unsigned char pkt[64];
6041 const socklen_t addrlen = get_addr_len(dstaddr);
6042 struct proxy *prx;
6043 struct quic_counters *prx_counters;
6044
6045 TRACE_ENTER(QUIC_EV_STATELESS_RST);
6046
6047 prx = l->bind_conf->frontend;
6048 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6049 /* 10.3 Stateless Reset (https://www.rfc-editor.org/rfc/rfc9000.html#section-10.3)
6050 * The resulting minimum size of 21 bytes does not guarantee that a Stateless
6051 * Reset is difficult to distinguish from other packets if the recipient requires
6052 * the use of a connection ID. To achieve that end, the endpoint SHOULD ensure
6053 * that all packets it sends are at least 22 bytes longer than the minimum
6054 * connection ID length that it requests the peer to include in its packets,
6055 * adding PADDING frames as necessary. This ensures that any Stateless Reset
6056 * sent by the peer is indistinguishable from a valid packet sent to the endpoint.
6057 * An endpoint that sends a Stateless Reset in response to a packet that is
6058 * 43 bytes or shorter SHOULD send a Stateless Reset that is one byte shorter
6059 * than the packet it responds to.
6060 */
6061
6062 /* Note that we build at most a 42 bytes QUIC packet to mimic a short packet */
6063 pktlen = rxpkt->len <= 43 ? rxpkt->len - 1 : 0;
6064 pktlen = QUIC_MAX(QUIC_STATELESS_RESET_PACKET_MINLEN, pktlen);
6065 rndlen = pktlen - QUIC_STATELESS_RESET_TOKEN_LEN;
6066
6067 /* Put a header of random bytes */
6068 /* TODO: RAND_bytes() should be replaced */
6069 if (RAND_bytes(pkt, rndlen) != 1) {
6070 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_STATELESS_RST);
6071 goto leave;
6072 }
6073
6074 /* Clear the most significant bit, and set the second one */
6075 *pkt = (*pkt & ~0x80) | 0x40;
6076 if (!quic_stateless_reset_token_cpy(NULL, pkt + rndlen, QUIC_STATELESS_RESET_TOKEN_LEN,
6077 rxpkt->dcid.data, rxpkt->dcid.len))
6078 goto leave;
6079
6080 if (sendto(l->rx.fd, pkt, pktlen, 0, (struct sockaddr *)dstaddr, addrlen) < 0)
6081 goto leave;
6082
6083 ret = 1;
6084 HA_ATOMIC_INC(&prx_counters->stateless_reset_sent);
6085 TRACE_PROTO("stateless reset sent", QUIC_EV_STATELESS_RST, NULL, &rxpkt->dcid);
6086 leave:
6087 TRACE_LEAVE(QUIC_EV_STATELESS_RST);
6088 return ret;
6089}
6090
6091/* QUIC server only function.
6092 * Add AAD to <add> buffer from <cid> connection ID and <addr> socket address.
6093 * This is the responsibility of the caller to check <aad> size is big enough
6094 * to contain these data.
6095 * Return the number of bytes copied to <aad>.
6096 */
6097static int quic_generate_retry_token_aad(unsigned char *aad,
6098 uint32_t version,
6099 const struct quic_cid *cid,
6100 const struct sockaddr_storage *addr)
6101{
6102 unsigned char *p;
6103
6104 p = aad;
6105 memcpy(p, &version, sizeof version);
6106 p += sizeof version;
6107 p += quic_saddr_cpy(p, addr);
6108 memcpy(p, cid->data, cid->len);
6109 p += cid->len;
6110
6111 return p - aad;
6112}
6113
6114/* QUIC server only function.
6115 * Generate the token to be used in Retry packets. The token is written to
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006116 * <buf> with <len> as length. <odcid> is the original destination connection
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006117 * ID and <dcid> is our side destination connection ID (or client source
6118 * connection ID).
6119 * Returns the length of the encoded token or 0 on error.
6120 */
6121static int quic_generate_retry_token(unsigned char *buf, size_t len,
6122 const uint32_t version,
6123 const struct quic_cid *odcid,
6124 const struct quic_cid *dcid,
6125 struct sockaddr_storage *addr)
6126{
6127 int ret = 0;
6128 unsigned char *p;
6129 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02006130 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006131 size_t aadlen;
6132 unsigned char salt[QUIC_RETRY_TOKEN_SALTLEN];
6133 unsigned char key[QUIC_TLS_KEY_LEN];
6134 unsigned char iv[QUIC_TLS_IV_LEN];
6135 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
6136 size_t seclen = strlen(global.cluster_secret);
6137 EVP_CIPHER_CTX *ctx = NULL;
6138 const EVP_CIPHER *aead = EVP_aes_128_gcm();
6139 uint32_t timestamp = now_ms;
6140
6141 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
6142
6143 /* We copy the odcid into the token, prefixed by its one byte
6144 * length, the format token byte. It is followed by an AEAD TAG, and finally
6145 * the random bytes used to derive the secret to encrypt the token.
6146 */
6147 if (1 + dcid->len + 1 + QUIC_TLS_TAG_LEN + sizeof salt > len)
6148 goto err;
6149
6150 aadlen = quic_generate_retry_token_aad(aad, version, dcid, addr);
6151 /* TODO: RAND_bytes() should be replaced */
6152 if (RAND_bytes(salt, sizeof salt) != 1) {
6153 TRACE_ERROR("RAND_bytes()", QUIC_EV_CONN_TXPKT);
6154 goto err;
6155 }
6156
6157 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
6158 salt, sizeof salt, sec, seclen)) {
6159 TRACE_ERROR("quic_tls_derive_retry_token_secret() failed", QUIC_EV_CONN_TXPKT);
6160 goto err;
6161 }
6162
6163 if (!quic_tls_tx_ctx_init(&ctx, aead, key)) {
6164 TRACE_ERROR("quic_tls_tx_ctx_init() failed", QUIC_EV_CONN_TXPKT);
6165 goto err;
6166 }
6167
6168 /* Token build */
6169 p = buf;
6170 *p++ = QUIC_TOKEN_FMT_RETRY,
6171 *p++ = odcid->len;
6172 memcpy(p, odcid->data, odcid->len);
6173 p += odcid->len;
6174 write_u32(p, htonl(timestamp));
6175 p += sizeof timestamp;
6176
6177 /* Do not encrypt the QUIC_TOKEN_FMT_RETRY byte */
6178 if (!quic_tls_encrypt(buf + 1, p - buf - 1, aad, aadlen, ctx, aead, key, iv)) {
6179 TRACE_ERROR("quic_tls_encrypt() failed", QUIC_EV_CONN_TXPKT);
6180 goto err;
6181 }
6182
6183 p += QUIC_TLS_TAG_LEN;
6184 memcpy(p, salt, sizeof salt);
6185 p += sizeof salt;
6186 EVP_CIPHER_CTX_free(ctx);
6187
6188 ret = p - buf;
6189 leave:
6190 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
6191 return ret;
6192
6193 err:
6194 if (ctx)
6195 EVP_CIPHER_CTX_free(ctx);
6196 goto leave;
6197}
6198
6199/* QUIC server only function.
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006200 *
6201 * Check the validity of the Retry token from Initial packet <pkt>. <dgram> is
6202 * the UDP datagram containing <pkt> and <l> is the listener instance on which
6203 * it was received. If the token is valid, the ODCID of <qc> QUIC connection
6204 * will be put into <odcid>. <qc> is used to retrieve the QUIC version needed
6205 * to validate the token but it can be NULL : in this case the version will be
6206 * retrieved from the packet.
6207 *
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006208 * Return 1 if succeeded, 0 if not.
6209 */
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006210
6211static int quic_retry_token_check(struct quic_rx_packet *pkt,
6212 struct quic_dgram *dgram,
6213 struct listener *l,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006214 struct quic_conn *qc,
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006215 struct quic_cid *odcid)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006216{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006217 struct proxy *prx;
6218 struct quic_counters *prx_counters;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006219 int ret = 0;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006220 unsigned char *token = pkt->token;
6221 const uint64_t tokenlen = pkt->token_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006222 unsigned char buf[128];
6223 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02006224 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006225 size_t aadlen;
6226 const unsigned char *salt;
6227 unsigned char key[QUIC_TLS_KEY_LEN];
6228 unsigned char iv[QUIC_TLS_IV_LEN];
6229 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
6230 size_t seclen = strlen(global.cluster_secret);
6231 EVP_CIPHER_CTX *ctx = NULL;
6232 const EVP_CIPHER *aead = EVP_aes_128_gcm();
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006233 const struct quic_version *qv = qc ? qc->original_version :
6234 pkt->version;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006235
6236 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6237
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006238 /* The caller must ensure this. */
6239 BUG_ON(!global.cluster_secret || !pkt->token_len);
6240
6241 prx = l->bind_conf->frontend;
6242 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6243
6244 if (*pkt->token != QUIC_TOKEN_FMT_RETRY) {
6245 /* TODO: New token check */
6246 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6247 goto leave;
6248 }
6249
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006250 if (sizeof buf < tokenlen) {
6251 TRACE_ERROR("too short buffer", QUIC_EV_CONN_LPKT, qc);
6252 goto err;
6253 }
6254
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006255 aadlen = quic_generate_retry_token_aad(aad, qv->num, &pkt->scid, &dgram->saddr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006256 salt = token + tokenlen - QUIC_RETRY_TOKEN_SALTLEN;
6257 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
6258 salt, QUIC_RETRY_TOKEN_SALTLEN, sec, seclen)) {
6259 TRACE_ERROR("Could not derive retry secret", QUIC_EV_CONN_LPKT, qc);
6260 goto err;
6261 }
6262
6263 if (!quic_tls_rx_ctx_init(&ctx, aead, key)) {
6264 TRACE_ERROR("quic_tls_rx_ctx_init() failed", QUIC_EV_CONN_LPKT, qc);
6265 goto err;
6266 }
6267
6268 /* Do not decrypt the QUIC_TOKEN_FMT_RETRY byte */
6269 if (!quic_tls_decrypt2(buf, token + 1, tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, aad, aadlen,
6270 ctx, aead, key, iv)) {
6271 TRACE_ERROR("Could not decrypt retry token", QUIC_EV_CONN_LPKT, qc);
6272 goto err;
6273 }
6274
6275 if (parse_retry_token(qc, buf, buf + tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, odcid)) {
6276 TRACE_ERROR("Error during Initial token parsing", QUIC_EV_CONN_LPKT, qc);
6277 goto err;
6278 }
6279
6280 EVP_CIPHER_CTX_free(ctx);
6281
6282 ret = 1;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006283 HA_ATOMIC_INC(&prx_counters->retry_validated);
6284
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006285 leave:
6286 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6287 return ret;
6288
6289 err:
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006290 HA_ATOMIC_INC(&prx_counters->retry_error);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006291 if (ctx)
6292 EVP_CIPHER_CTX_free(ctx);
6293 goto leave;
6294}
6295
6296/* Generate a Retry packet and send it on <fd> socket to <addr> in response to
6297 * the Initial <pkt> packet.
6298 *
6299 * Returns 0 on success else non-zero.
6300 */
6301static int send_retry(int fd, struct sockaddr_storage *addr,
6302 struct quic_rx_packet *pkt, const struct quic_version *qv)
6303{
6304 int ret = 0;
6305 unsigned char buf[128];
6306 int i = 0, token_len;
6307 const socklen_t addrlen = get_addr_len(addr);
6308 struct quic_cid scid;
6309
6310 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
6311
6312 /* long header + fixed bit + packet type QUIC_PACKET_TYPE_RETRY */
6313 buf[i++] = (QUIC_PACKET_LONG_HEADER_BIT | QUIC_PACKET_FIXED_BIT) |
6314 (quic_pkt_type(QUIC_PACKET_TYPE_RETRY, qv->num) << QUIC_PACKET_TYPE_SHIFT);
6315 /* version */
6316 buf[i++] = *((unsigned char *)&qv->num + 3);
6317 buf[i++] = *((unsigned char *)&qv->num + 2);
6318 buf[i++] = *((unsigned char *)&qv->num + 1);
6319 buf[i++] = *(unsigned char *)&qv->num;
6320
6321 /* Use the SCID from <pkt> for Retry DCID. */
6322 buf[i++] = pkt->scid.len;
6323 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
6324 i += pkt->scid.len;
6325
6326 /* Generate a new CID to be used as SCID for the Retry packet. */
6327 scid.len = QUIC_HAP_CID_LEN;
6328 /* TODO: RAND_bytes() should be replaced */
6329 if (RAND_bytes(scid.data, scid.len) != 1) {
6330 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT);
6331 goto out;
6332 }
6333
6334 buf[i++] = scid.len;
6335 memcpy(&buf[i], scid.data, scid.len);
6336 i += scid.len;
6337
6338 /* token */
6339 if (!(token_len = quic_generate_retry_token(&buf[i], sizeof(buf) - i, qv->num,
6340 &pkt->dcid, &pkt->scid, addr))) {
6341 TRACE_ERROR("quic_generate_retry_token() failed", QUIC_EV_CONN_TXPKT);
6342 goto out;
6343 }
6344
6345 i += token_len;
6346
6347 /* token integrity tag */
6348 if ((&buf[i] - buf < QUIC_TLS_TAG_LEN) ||
6349 !quic_tls_generate_retry_integrity_tag(pkt->dcid.data,
6350 pkt->dcid.len, buf, i, qv)) {
6351 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
6352 goto out;
6353 }
6354
6355 i += QUIC_TLS_TAG_LEN;
6356
6357 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0) {
6358 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
6359 goto out;
6360 }
6361
6362 ret = 1;
6363 out:
6364 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
6365 return !ret;
6366}
6367
6368/* Retrieve a quic_conn instance from the <pkt> DCID field. If the packet is of
6369 * type INITIAL, the ODCID tree is first used. In this case, <saddr> is
6370 * concatenated to the <pkt> DCID field.
6371 *
6372 * Returns the instance or NULL if not found.
6373 */
6374static struct quic_conn *retrieve_qc_conn_from_cid(struct quic_rx_packet *pkt,
6375 struct listener *l,
6376 struct sockaddr_storage *saddr)
6377{
6378 struct quic_conn *qc = NULL;
6379 struct ebmb_node *node;
6380 struct quic_connection_id *id;
6381 /* set if the quic_conn is found in the second DCID tree */
6382
6383 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
6384
6385 /* Look first into ODCIDs tree for INITIAL/0-RTT packets. */
6386 if (pkt->type == QUIC_PACKET_TYPE_INITIAL ||
6387 pkt->type == QUIC_PACKET_TYPE_0RTT) {
6388 /* DCIDs of first packets coming from multiple clients may have
6389 * the same values. Let's distinguish them by concatenating the
6390 * socket addresses.
6391 */
6392 quic_cid_saddr_cat(&pkt->dcid, saddr);
6393 node = ebmb_lookup(&quic_dghdlrs[tid].odcids, pkt->dcid.data,
6394 pkt->dcid.len + pkt->dcid.addrlen);
6395 if (node) {
6396 qc = ebmb_entry(node, struct quic_conn, odcid_node);
6397 goto end;
6398 }
6399 }
6400
6401 /* Look into DCIDs tree for non-INITIAL/0-RTT packets. This may be used
6402 * also for INITIAL/0-RTT non-first packets with the final DCID in
6403 * used.
6404 */
6405 node = ebmb_lookup(&quic_dghdlrs[tid].cids, pkt->dcid.data, pkt->dcid.len);
6406 if (!node)
6407 goto end;
6408
6409 id = ebmb_entry(node, struct quic_connection_id, node);
6410 qc = id->qc;
6411
6412 /* If found in DCIDs tree, remove the quic_conn from the ODCIDs tree.
6413 * If already done, this is a noop.
6414 */
6415 if (qc)
6416 ebmb_delete(&qc->odcid_node);
6417
6418 end:
6419 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
6420 return qc;
6421}
6422
6423/* Try to allocate the <*ssl> SSL session object for <qc> QUIC connection
6424 * with <ssl_ctx> as SSL context inherited settings. Also set the transport
6425 * parameters of this session.
6426 * This is the responsibility of the caller to check the validity of all the
6427 * pointers passed as parameter to this function.
6428 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <qc->conn> to
6429 * CO_ER_SSL_NO_MEM.
6430 */
6431static int qc_ssl_sess_init(struct quic_conn *qc, SSL_CTX *ssl_ctx, SSL **ssl,
6432 unsigned char *params, size_t params_len)
6433{
6434 int retry, ret = -1;
6435
6436 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6437
6438 retry = 1;
6439 retry:
6440 *ssl = SSL_new(ssl_ctx);
6441 if (!*ssl) {
6442 if (!retry--)
6443 goto err;
6444
6445 pool_gc(NULL);
6446 goto retry;
6447 }
6448
6449 if (!SSL_set_quic_method(*ssl, &ha_quic_method) ||
6450 !SSL_set_ex_data(*ssl, ssl_qc_app_data_index, qc)) {
6451 SSL_free(*ssl);
6452 *ssl = NULL;
6453 if (!retry--)
6454 goto err;
6455
6456 pool_gc(NULL);
6457 goto retry;
6458 }
6459
6460 ret = 0;
6461 leave:
6462 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6463 return ret;
6464
6465 err:
6466 qc->conn->err_code = CO_ER_SSL_NO_MEM;
6467 goto leave;
6468}
6469
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006470/* Allocate the ssl_sock_ctx from connection <qc>. This creates the tasklet
6471 * used to process <qc> received packets. The allocated context is stored in
6472 * <qc.xprt_ctx>.
6473 *
6474 * Returns 0 on success else non-zero.
6475 */
6476static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc)
6477{
6478 int ret = 0;
6479 struct bind_conf *bc = qc->li->bind_conf;
6480 struct ssl_sock_ctx *ctx = NULL;
6481
6482 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6483
6484 ctx = pool_zalloc(pool_head_quic_conn_ctx);
6485 if (!ctx) {
6486 TRACE_ERROR("SSL context allocation failed", QUIC_EV_CONN_TXPKT);
6487 goto err;
6488 }
6489
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006490 ctx->subs = NULL;
6491 ctx->xprt_ctx = NULL;
6492 ctx->qc = qc;
6493
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006494 if (qc_is_listener(qc)) {
6495 if (qc_ssl_sess_init(qc, bc->initial_ctx, &ctx->ssl,
6496 qc->enc_params, qc->enc_params_len) == -1) {
6497 goto err;
6498 }
6499#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
6500 /* Enabling 0-RTT */
6501 if (bc->ssl_conf.early_data)
6502 SSL_set_quic_early_data_enabled(ctx->ssl, 1);
6503#endif
6504
6505 SSL_set_accept_state(ctx->ssl);
6506 }
6507
6508 ctx->xprt = xprt_get(XPRT_QUIC);
6509
6510 /* Store the allocated context in <qc>. */
6511 qc->xprt_ctx = ctx;
6512
6513 ret = 1;
6514 leave:
6515 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6516 return !ret;
6517
6518 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006519 pool_free(pool_head_quic_conn_ctx, ctx);
6520 goto leave;
6521}
6522
6523/* Check that all the bytes between <buf> included and <end> address
6524 * excluded are null. This is the responsibility of the caller to
6525 * check that there is at least one byte between <buf> end <end>.
6526 * Return 1 if this all the bytes are null, 0 if not.
6527 */
6528static inline int quic_padding_check(const unsigned char *buf,
6529 const unsigned char *end)
6530{
6531 while (buf < end && !*buf)
6532 buf++;
6533
6534 return buf == end;
6535}
6536
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006537/* Find the associated connection to the packet <pkt> or create a new one if
6538 * this is an Initial packet. <dgram> is the datagram containing the packet and
6539 * <l> is the listener instance on which it was received.
6540 *
6541 * Returns the quic-conn instance or NULL.
6542 */
6543static struct quic_conn *quic_rx_pkt_retrieve_conn(struct quic_rx_packet *pkt,
6544 struct quic_dgram *dgram,
6545 struct listener *l)
6546{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006547 struct quic_cid token_odcid = { .len = 0 };
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006548 struct quic_conn *qc = NULL;
6549 struct proxy *prx;
6550 struct quic_counters *prx_counters;
6551
6552 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6553
6554 prx = l->bind_conf->frontend;
6555 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6556
6557 qc = retrieve_qc_conn_from_cid(pkt, l, &dgram->saddr);
6558
6559 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6560 BUG_ON(!pkt->version); /* This must not happen. */
6561
6562 if (global.cluster_secret && pkt->token_len) {
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006563 if (!quic_retry_token_check(pkt, dgram, l, qc, &token_odcid))
6564 goto err;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006565 }
6566
6567 if (!qc) {
6568 int ipv4;
6569
6570 if (global.cluster_secret && !pkt->token_len && !(l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) &&
6571 HA_ATOMIC_LOAD(&prx_counters->half_open_conn) >= global.tune.quic_retry_threshold) {
6572 TRACE_PROTO("Initial without token, sending retry",
6573 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6574 if (send_retry(l->rx.fd, &dgram->saddr, pkt, pkt->version)) {
6575 TRACE_ERROR("Error during Retry generation",
6576 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6577 goto out;
6578 }
6579
6580 HA_ATOMIC_INC(&prx_counters->retry_sent);
6581 goto out;
6582 }
6583
6584 /* RFC 9000 7.2. Negotiating Connection IDs:
6585 * When an Initial packet is sent by a client that has not previously
6586 * received an Initial or Retry packet from the server, the client
6587 * populates the Destination Connection ID field with an unpredictable
6588 * value. This Destination Connection ID MUST be at least 8 bytes in length.
6589 */
6590 if (pkt->dcid.len < QUIC_ODCID_MINLEN) {
6591 TRACE_PROTO("dropped packet",
6592 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6593 goto err;
6594 }
6595
6596 pkt->saddr = dgram->saddr;
6597 ipv4 = dgram->saddr.ss_family == AF_INET;
6598
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006599 qc = qc_new_conn(pkt->version, ipv4, &pkt->dcid, &pkt->scid, &token_odcid,
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006600 &dgram->daddr, &pkt->saddr, 1,
6601 !!pkt->token_len, l);
6602 if (qc == NULL)
6603 goto err;
6604
6605 HA_ATOMIC_INC(&prx_counters->half_open_conn);
6606 /* Insert the DCID the QUIC client has chosen (only for listeners) */
6607 ebmb_insert(&quic_dghdlrs[tid].odcids, &qc->odcid_node,
6608 qc->odcid.len + qc->odcid.addrlen);
6609 }
6610 }
6611 else if (!qc) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01006612 TRACE_PROTO("RX non Initial pkt without connection", QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006613 if (global.cluster_secret && !send_stateless_reset(l, &dgram->saddr, pkt))
6614 TRACE_ERROR("stateless reset not sent", QUIC_EV_CONN_LPKT, qc);
6615 goto err;
6616 }
6617
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006618 out:
6619 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6620 return qc;
6621
6622 err:
6623 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
6624 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
6625 return NULL;
6626}
6627
Amaury Denoyelle98289692022-10-19 15:37:44 +02006628/* Parse a QUIC packet starting at <buf>. Data won't be read after <end> even
6629 * if the packet is incomplete. This function will populate fields of <pkt>
6630 * instance, most notably its length. <dgram> is the UDP datagram which
6631 * contains the parsed packet. <l> is the listener instance on which it was
6632 * received.
6633 *
6634 * Returns 0 on success else non-zero. Packet length is guaranteed to be set to
6635 * the real packet value or to cover all data between <buf> and <end> : this is
6636 * useful to reject a whole datagram.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006637 */
Amaury Denoyelle98289692022-10-19 15:37:44 +02006638static int quic_rx_pkt_parse(struct quic_rx_packet *pkt,
6639 unsigned char *buf, const unsigned char *end,
6640 struct quic_dgram *dgram, struct listener *l)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006641{
Amaury Denoyelle98289692022-10-19 15:37:44 +02006642 const unsigned char *beg = buf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006643 struct proxy *prx;
6644 struct quic_counters *prx_counters;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006645 int long_header = 0;
Willy Tarreau33a68702022-11-24 09:16:41 +01006646 uint32_t version = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006647 const struct quic_version *qv = NULL;
6648
6649 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6650
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006651 prx = l->bind_conf->frontend;
6652 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6653 /* This ist only to please to traces and distinguish the
6654 * packet with parsed packet number from others.
6655 */
6656 pkt->pn_node.key = (uint64_t)-1;
6657 if (end <= buf) {
6658 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6659 goto drop;
6660 }
6661
6662 /* Fixed bit */
6663 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006664 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
6665 quic_padding_check(buf, end)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006666 /* Some browsers may pad the remaining datagram space with null bytes.
6667 * That is what we called add padding out of QUIC packets. Such
6668 * datagrams must be considered as valid. But we can only consume
6669 * the remaining space.
6670 */
6671 pkt->len = end - buf;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006672 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006673 }
6674
6675 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6676 goto drop;
6677 }
6678
6679 /* Header form */
6680 if (!qc_parse_hd_form(pkt, &buf, end, &long_header, &version)) {
6681 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6682 goto drop;
6683 }
6684
6685 if (long_header) {
6686 uint64_t len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006687
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006688 TRACE_PROTO("long header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006689 if (!quic_packet_read_long_header(&buf, end, pkt)) {
6690 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6691 goto drop;
6692 }
6693
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006694 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6695 * they must have the same DCID.
6696 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006697 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006698 (pkt->dcid.len != dgram->dcid_len ||
6699 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006700 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006701 goto drop;
6702 }
6703
6704 /* Retry of Version Negotiation packets are only sent by servers */
6705 if (pkt->type == QUIC_PACKET_TYPE_RETRY || !version) {
6706 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6707 goto drop;
6708 }
6709
6710 /* RFC9000 6. Version Negotiation */
6711 qv = qc_supported_version(version);
6712 if (!qv) {
6713 /* unsupported version, send Negotiation packet */
6714 if (send_version_negotiation(l->rx.fd, &dgram->saddr, pkt)) {
6715 TRACE_ERROR("VN packet not sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006716 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006717 }
6718
6719 TRACE_PROTO("VN packet sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006720 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006721 }
Amaury Denoyelle0eae5722022-10-17 18:05:18 +02006722 pkt->version = qv;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006723
6724 /* For Initial packets, and for servers (QUIC clients connections),
6725 * there is no Initial connection IDs storage.
6726 */
6727 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6728 uint64_t token_len;
6729
6730 if (!quic_dec_int(&token_len, (const unsigned char **)&buf, end) ||
6731 end - buf < token_len) {
6732 TRACE_PROTO("Packet dropped",
6733 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6734 goto drop;
6735 }
6736
6737 /* TODO Retry should be automatically activated if
6738 * suspect network usage is detected.
6739 */
6740 if (global.cluster_secret && !token_len) {
6741 if (l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) {
6742 TRACE_PROTO("Initial without token, sending retry",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006743 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006744 if (send_retry(l->rx.fd, &dgram->saddr, pkt, qv)) {
6745 TRACE_PROTO("Error during Retry generation",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006746 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006747 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006748 }
6749
6750 HA_ATOMIC_INC(&prx_counters->retry_sent);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006751 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006752 }
6753 }
6754 else if (!global.cluster_secret && token_len) {
6755 /* Impossible case: a token was received without configured
6756 * cluster secret.
6757 */
6758 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT,
6759 NULL, NULL, NULL, qv);
6760 goto drop;
6761 }
6762
6763 pkt->token = buf;
6764 pkt->token_len = token_len;
6765 buf += pkt->token_len;
6766 }
6767 else if (pkt->type != QUIC_PACKET_TYPE_0RTT) {
6768 if (pkt->dcid.len != QUIC_HAP_CID_LEN) {
6769 TRACE_PROTO("Packet dropped",
6770 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6771 goto drop;
6772 }
6773 }
6774
6775 if (!quic_dec_int(&len, (const unsigned char **)&buf, end) ||
6776 end - buf < len) {
6777 TRACE_PROTO("Packet dropped",
6778 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6779 goto drop;
6780 }
6781
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006782 /* Packet Number is stored here. Packet Length totalizes the
6783 * rest of the content.
6784 */
6785 pkt->pn_offset = buf - beg;
6786 pkt->len = pkt->pn_offset + len;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006787
Frédéric Lécaille35218c62023-02-16 11:40:11 +01006788 /* RFC 9000. Initial Datagram Size
6789 *
6790 * A server MUST discard an Initial packet that is carried in a UDP datagram
6791 * with a payload that is smaller than the smallest allowed maximum datagram
6792 * size of 1200 bytes.
6793 */
6794 if (pkt->type == QUIC_PACKET_TYPE_INITIAL &&
6795 dgram->len < QUIC_INITIAL_PACKET_MINLEN) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01006796 TRACE_PROTO("RX too short datagram with an Initial packet", QUIC_EV_CONN_LPKT);
Frédéric Lécaille35218c62023-02-16 11:40:11 +01006797 HA_ATOMIC_INC(&prx_counters->too_short_initial_dgram);
6798 goto drop;
6799 }
6800
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006801 /* Interrupt parsing after packet length retrieval : this
6802 * ensures that only the packet is dropped but not the whole
6803 * datagram.
6804 */
6805 if (pkt->type == QUIC_PACKET_TYPE_0RTT && !l->bind_conf->ssl_conf.early_data) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01006806 TRACE_PROTO("RX 0-RTT packet not supported", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006807 goto drop;
6808 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006809 }
6810 else {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01006811 TRACE_PROTO("RX short header packet", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006812 if (end - buf < QUIC_HAP_CID_LEN) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01006813 TRACE_PROTO("RX pkt dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006814 goto drop;
6815 }
6816
6817 memcpy(pkt->dcid.data, buf, QUIC_HAP_CID_LEN);
6818 pkt->dcid.len = QUIC_HAP_CID_LEN;
6819
6820 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6821 * they must have the same DCID.
6822 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006823 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006824 (pkt->dcid.len != dgram->dcid_len ||
6825 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Frédéric Lécaille8f991942023-03-24 15:14:45 +01006826 TRACE_PROTO("RX pkt dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006827 goto drop;
6828 }
6829
6830 buf += QUIC_HAP_CID_LEN;
6831
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006832 pkt->pn_offset = buf - beg;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006833 /* A short packet is the last one of a UDP datagram. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006834 pkt->len = end - beg;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006835 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006836
Frédéric Lécaille8f991942023-03-24 15:14:45 +01006837 TRACE_PROTO("RX pkt parsed", QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6838 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006839 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006840
Amaury Denoyelle98289692022-10-19 15:37:44 +02006841 drop:
6842 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006843 drop_silent:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006844 if (!pkt->len)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006845 pkt->len = end - beg;
Frédéric Lécaille8f991942023-03-24 15:14:45 +01006846 TRACE_PROTO("RX pkt parsing failed", QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6847 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006848 return -1;
6849}
6850
6851/* Check if received packet <pkt> should be drop due to <qc> already in closing
6852 * state. This can be true if a CONNECTION_CLOSE has already been emitted for
6853 * this connection.
6854 *
6855 * Returns false if connection is not in closing state else true. The caller
6856 * should drop the whole datagram in the last case to not mess up <qc>
6857 * CONNECTION_CLOSE rate limit counter.
6858 */
6859static int qc_rx_check_closing(struct quic_conn *qc,
6860 struct quic_rx_packet *pkt)
6861{
6862 if (!(qc->flags & QUIC_FL_CONN_CLOSING))
6863 return 0;
6864
6865 TRACE_STATE("Closing state connection", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6866
6867 /* Check if CONNECTION_CLOSE rate reemission is reached. */
6868 if (++qc->nb_pkt_since_cc >= qc->nb_pkt_for_cc) {
6869 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
6870 qc->nb_pkt_for_cc++;
6871 qc->nb_pkt_since_cc = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006872 }
6873
Amaury Denoyelle98289692022-10-19 15:37:44 +02006874 return 1;
6875}
6876
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006877/* React to a connection migration initiated on <qc> by a client with the new
6878 * path addresses <peer_addr>/<local_addr>.
6879 *
6880 * Returns 0 on success else non-zero.
6881 */
6882static int qc_handle_conn_migration(struct quic_conn *qc,
6883 const struct sockaddr_storage *peer_addr,
6884 const struct sockaddr_storage *local_addr)
6885{
6886 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6887
Frédéric Lécaille6fc86972023-01-12 08:29:23 +01006888 /* RFC 9000. Connection Migration
6889 *
6890 * If the peer sent the disable_active_migration transport parameter,
6891 * an endpoint also MUST NOT send packets (including probing packets;
6892 * see Section 9.1) from a different local address to the address the peer
6893 * used during the handshake, unless the endpoint has acted on a
6894 * preferred_address transport parameter from the peer.
6895 */
6896 if (qc->li->bind_conf->quic_params.disable_active_migration) {
6897 TRACE_ERROR("Active migration was disabled, datagram dropped", QUIC_EV_CONN_LPKT, qc);
6898 goto err;
6899 }
6900
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006901 /* RFC 9000 9. Connection Migration
6902 *
Amaury Denoyelleeb6be982022-11-21 11:14:45 +01006903 * The design of QUIC relies on endpoints retaining a stable address for
6904 * the duration of the handshake. An endpoint MUST NOT initiate
6905 * connection migration before the handshake is confirmed, as defined in
6906 * Section 4.1.2 of [QUIC-TLS].
6907 */
6908 if (qc->state < QUIC_HS_ST_COMPLETE) {
6909 TRACE_STATE("Connection migration during handshake rejected", QUIC_EV_CONN_LPKT, qc);
6910 goto err;
6911 }
6912
6913 /* RFC 9000 9. Connection Migration
6914 *
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006915 * TODO
6916 * An endpoint MUST
6917 * perform path validation (Section 8.2) if it detects any change to a
6918 * peer's address, unless it has previously validated that address.
6919 */
6920
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006921 /* Update quic-conn owned socket if in used.
6922 * TODO try to reuse it instead of closing and opening a new one.
6923 */
6924 if (qc_test_fd(qc)) {
6925 /* TODO try to reuse socket instead of closing it and opening a new one. */
6926 TRACE_STATE("Connection migration detected, allocate a new connection socket", QUIC_EV_CONN_LPKT, qc);
6927 qc_release_fd(qc, 1);
Amaury Denoyellefb375572023-02-01 09:28:32 +01006928 /* TODO need to adjust <jobs> on socket allocation failure. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006929 qc_alloc_fd(qc, local_addr, peer_addr);
6930 }
6931
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006932 qc->local_addr = *local_addr;
6933 qc->peer_addr = *peer_addr;
6934 HA_ATOMIC_INC(&qc->prx_counters->conn_migration_done);
6935
6936 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6937 return 0;
6938
6939 err:
6940 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6941 return 1;
6942}
6943
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006944/* Release the memory for the RX packets which are no more referenced
6945 * and consume their payloads which have been copied to the RX buffer
6946 * for the connection.
6947 * Always succeeds.
6948 */
6949static inline void quic_rx_pkts_del(struct quic_conn *qc)
6950{
6951 struct quic_rx_packet *pkt, *pktback;
6952
6953 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
6954 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006955 "pkt #%lld(type=%d,len=%llu,rawlen=%llu,refcnt=%u) (diff: %zd)",
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006956 (long long)pkt->pn_node.key,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006957 pkt->type, (ull)pkt->len, (ull)pkt->raw_len, pkt->refcnt,
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006958 (unsigned char *)b_head(&qc->rx.buf) - pkt->data);
6959 if (pkt->data != (unsigned char *)b_head(&qc->rx.buf)) {
6960 size_t cdata;
6961
6962 cdata = b_contig_data(&qc->rx.buf, 0);
6963 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006964 "cdata=%llu *b_head()=0x%x", (ull)cdata, *b_head(&qc->rx.buf));
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006965 if (cdata && !*b_head(&qc->rx.buf)) {
6966 /* Consume the remaining data */
6967 b_del(&qc->rx.buf, cdata);
6968 }
6969 break;
6970 }
6971
6972 if (pkt->refcnt)
6973 break;
6974
6975 b_del(&qc->rx.buf, pkt->raw_len);
6976 LIST_DELETE(&pkt->qc_rx_pkt_list);
6977 pool_free(pool_head_quic_rx_packet, pkt);
6978 }
6979
6980 /* In frequent cases the buffer will be emptied at this stage. */
6981 b_realign_if_empty(&qc->rx.buf);
6982}
6983
Amaury Denoyelle98289692022-10-19 15:37:44 +02006984/* Handle a parsed packet <pkt> by the connection <qc>. Data will be copied
6985 * into <qc> receive buffer after header protection removal procedure.
6986 *
6987 * <dgram> must be set to the datagram which contains the QUIC packet. <beg>
6988 * must point to packet buffer first byte.
6989 *
6990 * <tasklist_head> may be non-NULL when the caller treat several datagrams for
6991 * different quic-conn. In this case, each quic-conn tasklet will be appended
6992 * to it in order to be woken up after the current task.
6993 *
6994 * The caller can safely removed the packet data. If packet refcount was not
6995 * incremented by this function, it means that the connection did not handled
6996 * it and it should be freed by the caller.
6997 */
6998static void qc_rx_pkt_handle(struct quic_conn *qc, struct quic_rx_packet *pkt,
6999 struct quic_dgram *dgram, unsigned char *beg,
7000 struct list **tasklist_head)
7001{
7002 const struct quic_version *qv = pkt->version;
7003 struct quic_enc_level *qel = NULL;
7004 size_t b_cspace;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007005
Frédéric Lécaille8f991942023-03-24 15:14:45 +01007006 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
7007 TRACE_PROTO("RX pkt", QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
Amaury Denoyelle3f474e62022-11-24 17:15:08 +01007008
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02007009 if (pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007010 qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED) {
7011 TRACE_PROTO("PTO timer must be armed after anti-amplication was reached",
7012 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01007013 TRACE_DEVEL("needs to wakeup the timer task after the amplification limit was reached",
7014 QUIC_EV_CONN_LPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007015 /* Reset the anti-amplification bit. It will be set again
7016 * when sending the next packet if reached again.
7017 */
7018 qc->flags &= ~QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01007019 qc_set_timer(qc);
7020 if (qc->timer_task && tick_isset(qc->timer) && tick_is_lt(qc->timer, now_ms))
7021 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007022 }
7023
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007024 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
7025 TRACE_PROTO("Connection error",
7026 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
7027 goto out;
7028 }
7029
7030 pkt->raw_len = pkt->len;
7031 quic_rx_pkts_del(qc);
7032 b_cspace = b_contig_space(&qc->rx.buf);
7033 if (b_cspace < pkt->len) {
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01007034 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01007035 "bspace=%llu pkt->len=%llu", (ull)b_cspace, (ull)pkt->len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007036 /* Do not consume buf if space not at the end. */
7037 if (b_tail(&qc->rx.buf) + b_cspace < b_wrap(&qc->rx.buf)) {
7038 TRACE_PROTO("Packet dropped",
7039 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02007040 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02007041 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007042 }
7043
7044 /* Let us consume the remaining contiguous space. */
7045 if (b_cspace) {
7046 b_putchr(&qc->rx.buf, 0x00);
7047 b_cspace--;
7048 }
7049 b_add(&qc->rx.buf, b_cspace);
7050 if (b_contig_space(&qc->rx.buf) < pkt->len) {
7051 TRACE_PROTO("Too big packet",
7052 QUIC_EV_CONN_LPKT, qc, pkt, &pkt->len, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02007053 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02007054 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007055 }
7056 }
7057
Amaury Denoyelle845169d2022-10-17 18:05:26 +02007058 if (!qc_try_rm_hp(qc, pkt, beg, &qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007059 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
7060 goto drop;
7061 }
7062
7063 TRACE_DATA("New packet", QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
7064 if (pkt->aad_len)
7065 qc_pkt_insert(qc, pkt, qel);
7066 out:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02007067 *tasklist_head = tasklet_wakeup_after(*tasklist_head,
7068 qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007069
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02007070 drop_silent:
Frédéric Lécaille8f991942023-03-24 15:14:45 +01007071 TRACE_PROTO("RX pkt", QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
7072 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007073 return;
7074
7075 drop:
Amaury Denoyelle98289692022-10-19 15:37:44 +02007076 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt);
Frédéric Lécaille8f991942023-03-24 15:14:45 +01007077 TRACE_PROTO("packet drop", QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
7078 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007079}
7080
7081/* This function builds into <buf> buffer a QUIC long packet header.
7082 * Return 1 if enough room to build this header, 0 if not.
7083 */
7084static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
7085 int type, size_t pn_len,
7086 struct quic_conn *qc, const struct quic_version *ver)
7087{
7088 int ret = 0;
7089
7090 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
7091
7092 if (end - *buf < sizeof ver->num + qc->dcid.len + qc->scid.len + 3) {
7093 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
7094 goto leave;
7095 }
7096
7097 type = quic_pkt_type(type, ver->num);
7098 /* #0 byte flags */
7099 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
7100 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
7101 /* Version */
7102 quic_write_uint32(buf, end, ver->num);
7103 *(*buf)++ = qc->dcid.len;
7104 /* Destination connection ID */
7105 if (qc->dcid.len) {
7106 memcpy(*buf, qc->dcid.data, qc->dcid.len);
7107 *buf += qc->dcid.len;
7108 }
7109 /* Source connection ID */
7110 *(*buf)++ = qc->scid.len;
7111 if (qc->scid.len) {
7112 memcpy(*buf, qc->scid.data, qc->scid.len);
7113 *buf += qc->scid.len;
7114 }
7115
7116 ret = 1;
7117 leave:
7118 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
7119 return ret;
7120}
7121
7122/* This function builds into <buf> buffer a QUIC short packet header.
7123 * Return 1 if enough room to build this header, 0 if not.
7124 */
7125static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
7126 size_t pn_len, struct quic_conn *qc,
7127 unsigned char tls_flags)
7128{
7129 int ret = 0;
Frédéric Lécailleece86e62023-03-07 11:53:43 +01007130 unsigned char spin_bit =
7131 (qc->flags & QUIC_FL_CONN_SPIN_BIT) ? QUIC_PACKET_SPIN_BIT : 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007132
7133 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7134
7135 if (end - *buf < 1 + qc->dcid.len) {
7136 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
7137 goto leave;
7138 }
7139
7140 /* #0 byte flags */
Frédéric Lécailleece86e62023-03-07 11:53:43 +01007141 *(*buf)++ = QUIC_PACKET_FIXED_BIT | spin_bit |
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007142 ((tls_flags & QUIC_FL_TLS_KP_BIT_SET) ? QUIC_PACKET_KEY_PHASE_BIT : 0) | (pn_len - 1);
7143 /* Destination connection ID */
7144 if (qc->dcid.len) {
7145 memcpy(*buf, qc->dcid.data, qc->dcid.len);
7146 *buf += qc->dcid.len;
7147 }
7148
7149 ret = 1;
7150 leave:
7151 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7152 return ret;
7153}
7154
7155/* Apply QUIC header protection to the packet with <buf> as first byte address,
7156 * <pn> as address of the Packet number field, <pnlen> being this field length
7157 * with <aead> as AEAD cipher and <key> as secret key.
7158 * Returns 1 if succeeded or 0 if failed.
7159 */
7160static int quic_apply_header_protection(struct quic_conn *qc, unsigned char *buf,
7161 unsigned char *pn, size_t pnlen,
7162 struct quic_tls_ctx *tls_ctx)
7163
7164{
7165 int i, ret = 0;
7166 /* We need an IV of at least 5 bytes: one byte for bytes #0
7167 * and at most 4 bytes for the packet number
7168 */
7169 unsigned char mask[5] = {0};
7170 EVP_CIPHER_CTX *aes_ctx = tls_ctx->tx.hp_ctx;
7171
7172 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7173
7174 if (!quic_tls_aes_encrypt(mask, pn + QUIC_PACKET_PN_MAXLEN, sizeof mask, aes_ctx)) {
7175 TRACE_ERROR("could not apply header protection", QUIC_EV_CONN_TXPKT, qc);
7176 goto out;
7177 }
7178
7179 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
7180 for (i = 0; i < pnlen; i++)
7181 pn[i] ^= mask[i + 1];
7182
7183 ret = 1;
7184 out:
7185 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7186 return ret;
7187}
7188
7189/* Reduce the encoded size of <ack_frm> ACK frame removing the last
7190 * ACK ranges if needed to a value below <limit> in bytes.
7191 * Return 1 if succeeded, 0 if not.
7192 */
7193static int quic_ack_frm_reduce_sz(struct quic_conn *qc,
7194 struct quic_frame *ack_frm, size_t limit)
7195{
7196 size_t room, ack_delay_sz;
7197 int ret = 0;
7198
7199 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7200
7201 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
7202 /* A frame is made of 1 byte for the frame type. */
7203 room = limit - ack_delay_sz - 1;
7204 if (!quic_rm_last_ack_ranges(qc, ack_frm->tx_ack.arngs, room))
7205 goto leave;
7206
7207 ret = 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
7208 leave:
7209 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7210 return ret;
7211}
7212
7213/* Prepare into <outlist> as most as possible ack-eliciting frame from their
7214 * <inlist> prebuilt frames for <qel> encryption level to be encoded in a buffer
7215 * with <room> as available room, and <*len> the packet Length field initialized
7216 * with the number of bytes already present in this buffer which must be taken
7217 * into an account for the Length packet field value. <headlen> is the number of
7218 * bytes already present in this packet before building frames.
7219 *
7220 * Update consequently <*len> to reflect the size of these frames built
7221 * by this function. Also attach these frames to <l> frame list.
7222 * Return 1 if at least one ack-eleciting frame could be built, 0 if not.
7223 */
7224static inline int qc_build_frms(struct list *outlist, struct list *inlist,
7225 size_t room, size_t *len, size_t headlen,
7226 struct quic_enc_level *qel,
7227 struct quic_conn *qc)
7228{
7229 int ret;
7230 struct quic_frame *cf, *cfbak;
7231
7232 TRACE_ENTER(QUIC_EV_CONN_BCFRMS, qc);
7233
7234 ret = 0;
7235 if (*len > room)
7236 goto leave;
7237
7238 /* If we are not probing we must take into an account the congestion
7239 * control window.
7240 */
7241 if (!qel->pktns->tx.pto_probe) {
7242 size_t remain = quic_path_prep_data(qc->path);
7243
7244 if (headlen > remain)
7245 goto leave;
7246
7247 room = QUIC_MIN(room, remain - headlen);
7248 }
7249
Frédéric Lécaille8f991942023-03-24 15:14:45 +01007250 TRACE_PROTO("TX frms build (headlen)",
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007251 QUIC_EV_CONN_BCFRMS, qc, &headlen);
7252
7253 /* NOTE: switch/case block inside a loop, a successful status must be
7254 * returned by this function only if at least one frame could be built
7255 * in the switch/case block.
7256 */
7257 list_for_each_entry_safe(cf, cfbak, inlist, list) {
7258 /* header length, data length, frame length. */
7259 size_t hlen, dlen, dlen_sz, avail_room, flen;
7260
7261 if (!room)
7262 break;
7263
7264 switch (cf->type) {
7265 case QUIC_FT_CRYPTO:
7266 TRACE_DEVEL(" New CRYPTO frame build (room, len)",
7267 QUIC_EV_CONN_BCFRMS, qc, &room, len);
7268 /* Compute the length of this CRYPTO frame header */
7269 hlen = 1 + quic_int_getsize(cf->crypto.offset);
7270 /* Compute the data length of this CRyPTO frame. */
7271 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
7272 TRACE_DEVEL(" CRYPTO data length (hlen, crypto.len, dlen)",
7273 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->crypto.len, &dlen);
7274 if (!dlen)
7275 continue;
7276
7277 /* CRYPTO frame length. */
7278 flen = hlen + quic_int_getsize(dlen) + dlen;
7279 TRACE_DEVEL(" CRYPTO frame length (flen)",
7280 QUIC_EV_CONN_BCFRMS, qc, &flen);
7281 /* Add the CRYPTO data length and its encoded length to the packet
7282 * length and the length of this length.
7283 */
7284 *len += flen;
7285 room -= flen;
7286 if (dlen == cf->crypto.len) {
7287 /* <cf> CRYPTO data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007288 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007289 LIST_APPEND(outlist, &cf->list);
7290 }
7291 else {
7292 struct quic_frame *new_cf;
7293
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01007294 new_cf = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007295 if (!new_cf) {
7296 TRACE_ERROR("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, qc);
7297 continue;
7298 }
7299
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007300 new_cf->crypto.len = dlen;
7301 new_cf->crypto.offset = cf->crypto.offset;
7302 new_cf->crypto.qel = qel;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05007303 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007304 if (cf->origin) {
7305 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
7306 /* This <cf> frame was duplicated */
7307 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
7308 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01007309 /* Detach the remaining CRYPTO frame from its original frame */
7310 LIST_DEL_INIT(&cf->ref);
7311 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007312 }
7313 LIST_APPEND(outlist, &new_cf->list);
7314 /* Consume <dlen> bytes of the current frame. */
7315 cf->crypto.len -= dlen;
7316 cf->crypto.offset += dlen;
7317 }
7318 break;
7319
7320 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01007321 if (cf->stream.dup) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007322 struct eb64_node *node = NULL;
7323 struct qc_stream_desc *stream_desc = NULL;
7324 struct quic_stream *strm = &cf->stream;
7325
7326 /* As this frame has been already lost, ensure the stream is always
7327 * available or the range of this frame is not consumed before
7328 * resending it.
7329 */
7330 node = eb64_lookup(&qc->streams_by_id, strm->id);
7331 if (!node) {
7332 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007333 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007334 continue;
7335 }
7336
7337 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
7338 if (strm->offset.key + strm->len <= stream_desc->ack_offset) {
7339 TRACE_DEVEL("ignored frame frame in already acked range",
7340 QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007341 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007342 continue;
7343 }
7344 else if (strm->offset.key < stream_desc->ack_offset) {
Frédéric Lécailleca079792023-03-17 08:56:50 +01007345 uint64_t diff = stream_desc->ack_offset - strm->offset.key;
7346
Frédéric Lécaillec425e032023-03-20 14:32:59 +01007347 qc_stream_frm_mv_fwd(cf, diff);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007348 TRACE_DEVEL("updated partially acked frame",
7349 QUIC_EV_CONN_PRSAFRM, qc, cf);
7350 }
7351 }
7352 /* Note that these frames are accepted in short packets only without
7353 * "Length" packet field. Here, <*len> is used only to compute the
7354 * sum of the lengths of the already built frames for this packet.
7355 *
7356 * Compute the length of this STREAM frame "header" made a all the field
7357 * excepting the variable ones. Note that +1 is for the type of this frame.
7358 */
7359 hlen = 1 + quic_int_getsize(cf->stream.id) +
7360 ((cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT) ? quic_int_getsize(cf->stream.offset.key) : 0);
7361 /* Compute the data length of this STREAM frame. */
7362 avail_room = room - hlen - *len;
7363 if ((ssize_t)avail_room <= 0)
7364 continue;
7365
7366 TRACE_DEVEL(" New STREAM frame build (room, len)",
7367 QUIC_EV_CONN_BCFRMS, qc, &room, len);
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007368
7369 /* hlen contains STREAM id and offset. Ensure there is
7370 * enough room for length field.
7371 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007372 if (cf->type & QUIC_STREAM_FRAME_TYPE_LEN_BIT) {
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007373 dlen = QUIC_MIN((uint64_t)max_available_room(avail_room, &dlen_sz),
7374 cf->stream.len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007375 dlen_sz = quic_int_getsize(dlen);
7376 flen = hlen + dlen_sz + dlen;
7377 }
7378 else {
7379 dlen = QUIC_MIN((uint64_t)avail_room, cf->stream.len);
7380 flen = hlen + dlen;
7381 }
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007382
7383 if (cf->stream.len && !dlen) {
7384 /* Only a small gap is left on buffer, not
7385 * enough to encode the STREAM data length.
7386 */
7387 continue;
7388 }
7389
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007390 TRACE_DEVEL(" STREAM data length (hlen, stream.len, dlen)",
7391 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->stream.len, &dlen);
7392 TRACE_DEVEL(" STREAM frame length (flen)",
7393 QUIC_EV_CONN_BCFRMS, qc, &flen);
7394 /* Add the STREAM data length and its encoded length to the packet
7395 * length and the length of this length.
7396 */
7397 *len += flen;
7398 room -= flen;
7399 if (dlen == cf->stream.len) {
7400 /* <cf> STREAM data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007401 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007402 LIST_APPEND(outlist, &cf->list);
7403
7404 /* Do not notify MUX on retransmission. */
7405 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7406 qcc_streams_sent_done(cf->stream.stream->ctx,
7407 cf->stream.len,
7408 cf->stream.offset.key);
7409 }
7410 }
7411 else {
7412 struct quic_frame *new_cf;
7413 struct buffer cf_buf;
7414
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01007415 new_cf = qc_frm_alloc(cf->type);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007416 if (!new_cf) {
7417 TRACE_ERROR("No memory for new STREAM frame", QUIC_EV_CONN_BCFRMS, qc);
7418 continue;
7419 }
7420
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007421 new_cf->stream.stream = cf->stream.stream;
7422 new_cf->stream.buf = cf->stream.buf;
7423 new_cf->stream.id = cf->stream.id;
Amaury Denoyelle1dac0182023-02-02 16:45:07 +01007424 new_cf->stream.offset = cf->stream.offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007425 new_cf->stream.len = dlen;
7426 new_cf->type |= QUIC_STREAM_FRAME_TYPE_LEN_BIT;
7427 /* FIN bit reset */
7428 new_cf->type &= ~QUIC_STREAM_FRAME_TYPE_FIN_BIT;
7429 new_cf->stream.data = cf->stream.data;
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01007430 new_cf->stream.dup = cf->stream.dup;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05007431 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007432 if (cf->origin) {
7433 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
7434 /* This <cf> frame was duplicated */
7435 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
7436 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01007437 /* Detach this STREAM frame from its origin */
7438 LIST_DEL_INIT(&cf->ref);
7439 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007440 }
7441 LIST_APPEND(outlist, &new_cf->list);
7442 cf->type |= QUIC_STREAM_FRAME_TYPE_OFF_BIT;
7443 /* Consume <dlen> bytes of the current frame. */
7444 cf_buf = b_make(b_orig(cf->stream.buf),
7445 b_size(cf->stream.buf),
7446 (char *)cf->stream.data - b_orig(cf->stream.buf), 0);
7447 cf->stream.len -= dlen;
7448 cf->stream.offset.key += dlen;
7449 cf->stream.data = (unsigned char *)b_peek(&cf_buf, dlen);
7450
7451 /* Do not notify MUX on retransmission. */
7452 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7453 qcc_streams_sent_done(new_cf->stream.stream->ctx,
7454 new_cf->stream.len,
7455 new_cf->stream.offset.key);
7456 }
7457 }
7458
7459 /* TODO the MUX is notified about the frame sending via
7460 * previous qcc_streams_sent_done call. However, the
7461 * sending can fail later, for example if the sendto
7462 * system call returns an error. As the MUX has been
7463 * notified, the transport layer is responsible to
7464 * bufferize and resent the announced data later.
7465 */
7466
7467 break;
7468
7469 default:
7470 flen = qc_frm_len(cf);
7471 BUG_ON(!flen);
7472 if (flen > room)
7473 continue;
7474
7475 *len += flen;
7476 room -= flen;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007477 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007478 LIST_APPEND(outlist, &cf->list);
7479 break;
7480 }
7481
7482 /* Successful status as soon as a frame could be built */
7483 ret = 1;
7484 }
7485
7486 leave:
7487 TRACE_LEAVE(QUIC_EV_CONN_BCFRMS, qc);
7488 return ret;
7489}
7490
7491/* Generate a CONNECTION_CLOSE frame for <qc> on <qel> encryption level. <out>
7492 * is used as return parameter and should be zero'ed by the caller.
7493 */
7494static void qc_build_cc_frm(struct quic_conn *qc, struct quic_enc_level *qel,
7495 struct quic_frame *out)
7496{
7497 /* TODO improve CONNECTION_CLOSE on Initial/Handshake encryption levels
7498 *
7499 * A CONNECTION_CLOSE frame should be sent in several packets with
7500 * different encryption levels depending on the client context. This is
7501 * to ensure that the client can decrypt it. See RFC 9000 10.2.3 for
7502 * more details on how to implement it.
7503 */
7504 TRACE_ENTER(QUIC_EV_CONN_BFRM, qc);
7505
7506
7507 if (qc->err.app) {
7508 if (unlikely(qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
7509 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
7510 /* RFC 9000 10.2.3. Immediate Close during the Handshake
7511 *
7512 * Sending a CONNECTION_CLOSE of type 0x1d in an Initial or Handshake
7513 * packet could expose application state or be used to alter application
7514 * state. A CONNECTION_CLOSE of type 0x1d MUST be replaced by a
7515 * CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or
7516 * Handshake packets. Otherwise, information about the application
7517 * state might be revealed. Endpoints MUST clear the value of the
7518 * Reason Phrase field and SHOULD use the APPLICATION_ERROR code when
7519 * converting to a CONNECTION_CLOSE of type 0x1c.
7520 */
7521 out->type = QUIC_FT_CONNECTION_CLOSE;
7522 out->connection_close.error_code = QC_ERR_APPLICATION_ERROR;
7523 out->connection_close.reason_phrase_len = 0;
7524 }
7525 else {
7526 out->type = QUIC_FT_CONNECTION_CLOSE_APP;
7527 out->connection_close.error_code = qc->err.code;
7528 }
7529 }
7530 else {
7531 out->type = QUIC_FT_CONNECTION_CLOSE;
7532 out->connection_close.error_code = qc->err.code;
7533 }
7534 TRACE_LEAVE(QUIC_EV_CONN_BFRM, qc);
7535
7536}
7537
7538/* This function builds a clear packet from <pkt> information (its type)
7539 * into a buffer with <pos> as position pointer and <qel> as QUIC TLS encryption
7540 * level for <conn> QUIC connection and <qel> as QUIC TLS encryption level,
7541 * filling the buffer with as much frames as possible from <frms> list of
7542 * prebuilt frames.
7543 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
7544 * reserved so that to ensure there is enough room to build this AEAD TAG after
7545 * having returned from this function.
7546 * This function also updates the value of <buf_pn> pointer to point to the packet
7547 * number field in this packet. <pn_len> will also have the packet number
7548 * length as value.
7549 *
7550 * Return 1 if succeeded (enough room to buile this packet), O if not.
7551 */
7552static int qc_do_build_pkt(unsigned char *pos, const unsigned char *end,
7553 size_t dglen, struct quic_tx_packet *pkt,
7554 int64_t pn, size_t *pn_len, unsigned char **buf_pn,
7555 int force_ack, int padding, int cc, int probe,
7556 struct quic_enc_level *qel, struct quic_conn *qc,
7557 const struct quic_version *ver, struct list *frms)
7558{
7559 unsigned char *beg, *payload;
7560 size_t len, len_sz, len_frms, padding_len;
7561 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
7562 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
7563 struct quic_frame cc_frm = { };
7564 size_t ack_frm_len, head_len;
7565 int64_t rx_largest_acked_pn;
7566 int add_ping_frm;
7567 struct list frm_list = LIST_HEAD_INIT(frm_list);
7568 struct quic_frame *cf;
7569 int must_ack, ret = 0;
7570 int nb_aepkts_since_last_ack;
7571
7572 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7573
7574 /* Length field value with CRYPTO frames if present. */
7575 len_frms = 0;
7576 beg = pos;
7577 /* When not probing, and no immediate close is required, reduce the size of this
7578 * buffer to respect the congestion controller window.
7579 * This size will be limited if we have ack-eliciting frames to send from <frms>.
7580 */
7581 if (!probe && !LIST_ISEMPTY(frms) && !cc) {
7582 size_t path_room;
7583
7584 path_room = quic_path_prep_data(qc->path);
7585 if (end - beg > path_room)
7586 end = beg + path_room;
7587 }
7588
7589 /* Ensure there is enough room for the TLS encryption tag and a zero token
7590 * length field if any.
7591 */
7592 if (end - pos < QUIC_TLS_TAG_LEN +
7593 (pkt->type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0))
7594 goto no_room;
7595
7596 end -= QUIC_TLS_TAG_LEN;
7597 rx_largest_acked_pn = qel->pktns->rx.largest_acked_pn;
7598 /* packet number length */
7599 *pn_len = quic_packet_number_length(pn, rx_largest_acked_pn);
7600 /* Build the header */
7601 if ((pkt->type == QUIC_PACKET_TYPE_SHORT &&
7602 !quic_build_packet_short_header(&pos, end, *pn_len, qc, qel->tls_ctx.flags)) ||
7603 (pkt->type != QUIC_PACKET_TYPE_SHORT &&
7604 !quic_build_packet_long_header(&pos, end, pkt->type, *pn_len, qc, ver)))
7605 goto no_room;
7606
7607 /* Encode the token length (0) for an Initial packet. */
7608 if (pkt->type == QUIC_PACKET_TYPE_INITIAL)
7609 *pos++ = 0;
7610 head_len = pos - beg;
7611 /* Build an ACK frame if required. */
7612 ack_frm_len = 0;
7613 nb_aepkts_since_last_ack = qel->pktns->rx.nb_aepkts_since_last_ack;
7614 must_ack = !qel->pktns->tx.pto_probe &&
7615 (force_ack || ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
7616 (LIST_ISEMPTY(frms) || nb_aepkts_since_last_ack >= QUIC_MAX_RX_AEPKTS_SINCE_LAST_ACK)));
7617 if (must_ack) {
7618 struct quic_arngs *arngs = &qel->pktns->rx.arngs;
7619 BUG_ON(eb_is_empty(&qel->pktns->rx.arngs.root));
7620 ack_frm.tx_ack.arngs = arngs;
7621 if (qel->pktns->flags & QUIC_FL_PKTNS_NEW_LARGEST_PN) {
7622 qel->pktns->tx.ack_delay =
7623 quic_compute_ack_delay_us(qel->pktns->rx.largest_time_received, qc);
7624 qel->pktns->flags &= ~QUIC_FL_PKTNS_NEW_LARGEST_PN;
7625 }
7626 ack_frm.tx_ack.ack_delay = qel->pktns->tx.ack_delay;
7627 /* XXX BE CAREFUL XXX : here we reserved at least one byte for the
7628 * smallest frame (PING) and <*pn_len> more for the packet number. Note
7629 * that from here, we do not know if we will have to send a PING frame.
7630 * This will be decided after having computed the ack-eliciting frames
7631 * to be added to this packet.
7632 */
7633 ack_frm_len = quic_ack_frm_reduce_sz(qc, &ack_frm, end - 1 - *pn_len - pos);
7634 if (!ack_frm_len)
7635 goto no_room;
7636 }
7637
7638 /* Length field value without the ack-eliciting frames. */
7639 len = ack_frm_len + *pn_len;
7640 len_frms = 0;
7641 if (!cc && !LIST_ISEMPTY(frms)) {
7642 ssize_t room = end - pos;
7643
7644 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7645 /* Initialize the length of the frames built below to <len>.
7646 * If any frame could be successfully built by qc_build_frms(),
7647 * we will have len_frms > len.
7648 */
7649 len_frms = len;
7650 if (!qc_build_frms(&frm_list, frms,
7651 end - pos, &len_frms, pos - beg, qel, qc)) {
7652 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7653 qc, NULL, NULL, &room);
7654 if (!ack_frm_len && !qel->pktns->tx.pto_probe)
7655 goto no_room;
7656 }
7657 }
7658
7659 /* Length (of the remaining data). Must not fail because, the buffer size
7660 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
7661 * for the encryption tag. It must be taken into an account for the length
7662 * of this packet.
7663 */
7664 if (len_frms)
7665 len = len_frms + QUIC_TLS_TAG_LEN;
7666 else
7667 len += QUIC_TLS_TAG_LEN;
7668 /* CONNECTION_CLOSE frame */
7669 if (cc) {
7670 qc_build_cc_frm(qc, qel, &cc_frm);
7671 len += qc_frm_len(&cc_frm);
7672 }
7673 add_ping_frm = 0;
7674 padding_len = 0;
7675 len_sz = quic_int_getsize(len);
7676 /* Add this packet size to <dglen> */
7677 dglen += head_len + len_sz + len;
Frédéric Lécailleec937212023-03-03 17:34:41 +01007678 /* Note that <padding> is true only when building an Handshake packet
7679 * coalesced to an Initial packet.
7680 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007681 if (padding && dglen < QUIC_INITIAL_PACKET_MINLEN) {
7682 /* This is a maximum padding size */
7683 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7684 /* The length field value is of this packet is <len> + <padding_len>
7685 * the size of which may be greater than the initial computed size
7686 * <len_sz>. So, let's deduce the difference between these to packet
7687 * sizes from <padding_len>.
7688 */
7689 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7690 len += padding_len;
7691 }
Frédéric Lécaille5faf5772023-02-16 17:30:53 +01007692 else if (len_frms && len_frms < QUIC_PACKET_PN_MAXLEN) {
7693 len += padding_len = QUIC_PACKET_PN_MAXLEN - len_frms;
7694 }
7695 else if (LIST_ISEMPTY(&frm_list)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007696 if (qel->pktns->tx.pto_probe) {
7697 /* If we cannot send a frame, we send a PING frame. */
7698 add_ping_frm = 1;
7699 len += 1;
Frédéric Lécailleec937212023-03-03 17:34:41 +01007700 dglen += 1;
7701 /* Note that only we are in the case where this Initial packet
7702 * is not coalesced to an Handshake packet. We must directly
7703 * pad the datragram.
7704 */
Frédéric Lécaille9c317b12023-03-28 15:39:11 +02007705 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
7706 if (dglen < QUIC_INITIAL_PACKET_MINLEN) {
7707 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7708 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7709 len += padding_len;
7710 }
7711 }
7712 else {
7713 /* Note that +1 is for the PING frame */
7714 if (*pn_len + 1 < QUIC_PACKET_PN_MAXLEN)
7715 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len - 1;
Frédéric Lécailleec937212023-03-03 17:34:41 +01007716 }
7717 }
7718 else {
7719 /* If there is no frame at all to follow, add at least a PADDING frame. */
7720 if (!ack_frm_len && !cc)
7721 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007722 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007723 }
7724
7725 if (pkt->type != QUIC_PACKET_TYPE_SHORT && !quic_enc_int(&pos, end, len))
7726 goto no_room;
7727
7728 /* Packet number field address. */
7729 *buf_pn = pos;
7730
7731 /* Packet number encoding. */
7732 if (!quic_packet_number_encode(&pos, end, pn, *pn_len))
7733 goto no_room;
7734
7735 /* payload building (ack-eliciting or not frames) */
7736 payload = pos;
7737 if (ack_frm_len) {
7738 if (!qc_build_frm(&pos, end, &ack_frm, pkt, qc))
7739 goto no_room;
7740
7741 pkt->largest_acked_pn = quic_pktns_get_largest_acked_pn(qel->pktns);
7742 pkt->flags |= QUIC_FL_TX_PACKET_ACK;
7743 }
7744
7745 /* Ack-eliciting frames */
7746 if (!LIST_ISEMPTY(&frm_list)) {
7747 struct quic_frame *tmp_cf;
7748 list_for_each_entry_safe(cf, tmp_cf, &frm_list, list) {
7749 if (!qc_build_frm(&pos, end, cf, pkt, qc)) {
7750 ssize_t room = end - pos;
7751 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7752 qc, NULL, NULL, &room);
7753 /* Note that <cf> was added from <frms> to <frm_list> list by
7754 * qc_build_frms().
7755 */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007756 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007757 LIST_INSERT(frms, &cf->list);
7758 continue;
7759 }
7760
7761 quic_tx_packet_refinc(pkt);
7762 cf->pkt = pkt;
7763 }
7764 }
7765
7766 /* Build a PING frame if needed. */
7767 if (add_ping_frm) {
7768 frm.type = QUIC_FT_PING;
7769 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7770 goto no_room;
7771 }
7772
7773 /* Build a CONNECTION_CLOSE frame if needed. */
7774 if (cc) {
7775 if (!qc_build_frm(&pos, end, &cc_frm, pkt, qc))
7776 goto no_room;
7777
7778 pkt->flags |= QUIC_FL_TX_PACKET_CC;
7779 }
7780
7781 /* Build a PADDING frame if needed. */
7782 if (padding_len) {
7783 frm.type = QUIC_FT_PADDING;
7784 frm.padding.len = padding_len;
7785 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7786 goto no_room;
7787 }
7788
7789 if (pos == payload) {
7790 /* No payload was built because of congestion control */
7791 TRACE_DEVEL("limited by congestion control", QUIC_EV_CONN_TXPKT, qc);
7792 goto no_room;
7793 }
7794
7795 /* If this packet is ack-eliciting and we are probing let's
7796 * decrement the PTO probe counter.
7797 */
7798 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING &&
7799 qel->pktns->tx.pto_probe)
7800 qel->pktns->tx.pto_probe--;
7801
7802 pkt->len = pos - beg;
7803 LIST_SPLICE(&pkt->frms, &frm_list);
7804
7805 ret = 1;
7806 TRACE_DEVEL("Packet ack-eliciting frames", QUIC_EV_CONN_TXPKT, qc, pkt);
7807 leave:
7808 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7809 return ret;
7810
7811 no_room:
7812 /* Replace the pre-built frames which could not be add to this packet */
7813 LIST_SPLICE(frms, &frm_list);
7814 TRACE_DEVEL("Remaining ack-eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7815 goto leave;
7816}
7817
7818static inline void quic_tx_packet_init(struct quic_tx_packet *pkt, int type)
7819{
7820 pkt->type = type;
7821 pkt->len = 0;
7822 pkt->in_flight_len = 0;
7823 pkt->pn_node.key = (uint64_t)-1;
7824 LIST_INIT(&pkt->frms);
7825 pkt->time_sent = TICK_ETERNITY;
7826 pkt->next = NULL;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01007827 pkt->prev = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007828 pkt->largest_acked_pn = -1;
7829 pkt->flags = 0;
7830 pkt->refcnt = 0;
7831}
7832
7833/* Build a packet into <buf> packet buffer with <pkt_type> as packet
7834 * type for <qc> QUIC connection from <qel> encryption level from <frms> list
7835 * of prebuilt frames.
7836 *
7837 * Return -2 if the packet could not be allocated or encrypted for any reason,
7838 * -1 if there was not enough room to build a packet.
7839 * XXX NOTE XXX
7840 * If you provide provide qc_build_pkt() with a big enough buffer to build a packet as big as
7841 * possible (to fill an MTU), the unique reason why this function may fail is the congestion
7842 * control window limitation.
7843 */
7844static struct quic_tx_packet *qc_build_pkt(unsigned char **pos,
7845 const unsigned char *buf_end,
7846 struct quic_enc_level *qel,
7847 struct quic_tls_ctx *tls_ctx, struct list *frms,
7848 struct quic_conn *qc, const struct quic_version *ver,
7849 size_t dglen, int pkt_type, int force_ack,
7850 int padding, int probe, int cc, int *err)
7851{
7852 struct quic_tx_packet *ret_pkt = NULL;
7853 /* The pointer to the packet number field. */
7854 unsigned char *buf_pn;
7855 unsigned char *beg, *end, *payload;
7856 int64_t pn;
7857 size_t pn_len, payload_len, aad_len;
7858 struct quic_tx_packet *pkt;
7859
Frédéric Lécaille8f991942023-03-24 15:14:45 +01007860 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7861 TRACE_PROTO("TX pkt build", QUIC_EV_CONN_TXPKT, qc, NULL, qel);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007862 *err = 0;
7863 pkt = pool_alloc(pool_head_quic_tx_packet);
7864 if (!pkt) {
7865 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_TXPKT, qc);
7866 *err = -2;
7867 goto err;
7868 }
7869
7870 quic_tx_packet_init(pkt, pkt_type);
7871 beg = *pos;
7872 pn_len = 0;
7873 buf_pn = NULL;
7874
7875 pn = qel->pktns->tx.next_pn + 1;
7876 if (!qc_do_build_pkt(*pos, buf_end, dglen, pkt, pn, &pn_len, &buf_pn,
7877 force_ack, padding, cc, probe, qel, qc, ver, frms)) {
7878 // trace already emitted by function above
7879 *err = -1;
7880 goto err;
7881 }
7882
7883 end = beg + pkt->len;
7884 payload = buf_pn + pn_len;
7885 payload_len = end - payload;
7886 aad_len = payload - beg;
7887
7888 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc)) {
7889 // trace already emitted by function above
7890 *err = -2;
7891 goto err;
7892 }
7893
7894 end += QUIC_TLS_TAG_LEN;
7895 pkt->len += QUIC_TLS_TAG_LEN;
7896 if (!quic_apply_header_protection(qc, beg, buf_pn, pn_len, tls_ctx)) {
7897 // trace already emitted by function above
7898 *err = -2;
7899 goto err;
7900 }
7901
7902 /* Consume a packet number */
7903 qel->pktns->tx.next_pn++;
7904 qc->tx.prep_bytes += pkt->len;
7905 if (qc->tx.prep_bytes >= 3 * qc->rx.bytes && !quic_peer_validated_addr(qc)) {
7906 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
7907 TRACE_PROTO("anti-amplification limit reached", QUIC_EV_CONN_TXPKT, qc);
7908 }
7909 /* Now that a correct packet is built, let us consume <*pos> buffer. */
7910 *pos = end;
7911 /* Attach the built packet to its tree. */
7912 pkt->pn_node.key = pn;
7913 /* Set the packet in fligth length for in flight packet only. */
7914 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
7915 pkt->in_flight_len = pkt->len;
7916 qc->path->prep_in_flight += pkt->len;
7917 }
Frédéric Lécailled7215712023-03-24 18:13:37 +01007918 /* Always reset this flag */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007919 qc->flags &= ~QUIC_FL_CONN_IMMEDIATE_CLOSE;
7920 if (pkt->flags & QUIC_FL_TX_PACKET_ACK) {
7921 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
7922 qel->pktns->rx.nb_aepkts_since_last_ack = 0;
Frédéric Lécailled7215712023-03-24 18:13:37 +01007923 qc->flags &= ~QUIC_FL_CONN_ACK_TIMER_FIRED;
7924 if (tick_isset(qc->ack_expire)) {
7925 qc->ack_expire = TICK_ETERNITY;
7926 qc->idle_timer_task->expire = qc->idle_expire;
7927 task_queue(qc->idle_timer_task);
7928 TRACE_PROTO("ack timer cancelled", QUIC_EV_CONN_TXPKT, qc);
7929 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007930 }
7931
7932 pkt->pktns = qel->pktns;
7933
7934 ret_pkt = pkt;
7935 leave:
Frédéric Lécaille8f991942023-03-24 15:14:45 +01007936 TRACE_PROTO("TX pkt built", QUIC_EV_CONN_TXPKT, qc, ret_pkt);
7937 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007938 return ret_pkt;
7939
7940 err:
7941 /* TODO: what about the frames which have been built
7942 * for this packet.
7943 */
7944 free_quic_tx_packet(qc, pkt);
7945 goto leave;
7946}
7947
7948
7949static void __quic_conn_init(void)
7950{
7951 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
7952}
7953INITCALL0(STG_REGISTER, __quic_conn_init);
7954
7955static void __quic_conn_deinit(void)
7956{
7957 BIO_meth_free(ha_quic_meth);
7958}
7959REGISTER_POST_DEINIT(__quic_conn_deinit);
7960
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007961/* Handle a new <dgram> received. Parse each QUIC packets and copied their
7962 * content to a quic-conn instance. The datagram content can be released after
7963 * this function.
7964 *
7965 * If datagram has been received on a quic-conn owned FD, <from_qc> must be set
7966 * to the connection instance. <li> is the attached listener. The caller is
7967 * responsible to ensure that the first packet is destined to this connection
7968 * by comparing CIDs.
7969 *
7970 * If datagram has been received on a receiver FD, <from_qc> will be NULL. This
7971 * function will thus retrieve the connection from the CID tree or allocate a
7972 * new one if possible. <li> is the listener attached to the receiver.
7973 *
7974 * Returns 0 on success else non-zero. If an error happens, some packets from
7975 * the datagram may not have been parsed.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007976 */
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007977int quic_dgram_parse(struct quic_dgram *dgram, struct quic_conn *from_qc,
7978 struct listener *li)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007979{
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007980 struct quic_rx_packet *pkt;
7981 struct quic_conn *qc = NULL;
7982 unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007983 struct list *tasklist_head = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007984
7985 TRACE_ENTER(QUIC_EV_CONN_LPKT);
7986
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007987 pos = dgram->buf;
7988 end = pos + dgram->len;
7989 do {
7990 /* TODO replace zalloc -> alloc. */
7991 pkt = pool_zalloc(pool_head_quic_rx_packet);
7992 if (!pkt) {
7993 TRACE_ERROR("RX packet allocation failed", QUIC_EV_CONN_LPKT);
7994 goto err;
7995 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007996
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007997 pkt->version = NULL;
7998 pkt->pn_offset = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007999
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008000 /* Set flag if pkt is the first one in dgram. */
8001 if (pos == dgram->buf)
8002 pkt->flags |= QUIC_FL_RX_PACKET_DGRAM_FIRST;
Amaury Denoyelle98289692022-10-19 15:37:44 +02008003
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008004 LIST_INIT(&pkt->qc_rx_pkt_list);
8005 pkt->time_received = now_ms;
8006 quic_rx_packet_refinc(pkt);
8007 if (quic_rx_pkt_parse(pkt, pos, end, dgram, li))
8008 goto next;
Amaury Denoyelle98289692022-10-19 15:37:44 +02008009
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008010 /* Search quic-conn instance for first packet of the datagram.
8011 * quic_rx_packet_parse() is responsible to discard packets
8012 * with different DCID as the first one in the same datagram.
8013 */
8014 if (!qc) {
8015 qc = from_qc ? from_qc : quic_rx_pkt_retrieve_conn(pkt, dgram, li);
8016 /* qc is NULL if receiving a non Initial packet for an
8017 * unknown connection.
8018 */
8019 if (!qc) {
Amaury Denoyelle98289692022-10-19 15:37:44 +02008020 /* Skip the entire datagram. */
8021 pkt->len = end - pos;
8022 goto next;
8023 }
8024
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008025 dgram->qc = qc;
8026 }
Amaury Denoyelle98289692022-10-19 15:37:44 +02008027
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008028 if (qc_rx_check_closing(qc, pkt)) {
8029 /* Skip the entire datagram. */
8030 pkt->len = end - pos;
8031 goto next;
8032 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008033
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01008034 /* Detect QUIC connection migration. */
Frédéric Lécaillef6769542023-01-12 10:36:26 +01008035 if (ipcmp(&qc->peer_addr, &dgram->saddr, 1)) {
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01008036 if (qc_handle_conn_migration(qc, &dgram->saddr, &dgram->daddr)) {
8037 /* Skip the entire datagram. */
8038 TRACE_ERROR("error during connection migration, datagram dropped", QUIC_EV_CONN_LPKT, qc);
8039 pkt->len = end - pos;
8040 goto next;
8041 }
8042 }
8043
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008044 qc_rx_pkt_handle(qc, pkt, dgram, pos, &tasklist_head);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008045
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008046 next:
8047 pos += pkt->len;
8048 quic_rx_packet_refdec(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008049
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008050 /* Free rejected packets */
8051 if (!pkt->refcnt) {
8052 BUG_ON(LIST_INLIST(&pkt->qc_rx_pkt_list));
8053 pool_free(pool_head_quic_rx_packet, pkt);
8054 }
8055 } while (pos < end);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008056
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008057 /* Increasing the received bytes counter by the UDP datagram length
8058 * if this datagram could be associated to a connection.
8059 */
8060 if (dgram->qc)
8061 dgram->qc->rx.bytes += dgram->len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008062
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008063 /* This must never happen. */
8064 BUG_ON(pos > end);
8065 BUG_ON(pos < end || pos > dgram->buf + dgram->len);
8066 /* Mark this datagram as consumed */
8067 HA_ATOMIC_STORE(&dgram->buf, NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008068
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008069 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
8070 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008071
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008072 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008073 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008074 return -1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008075}
8076
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01008077/* Check if connection ID <dcid> of length <dcid_len> belongs to <qc> local
8078 * CIDs. This can be used to determine if a datagram is addressed to the right
8079 * connection instance.
8080 *
8081 * Returns a boolean value.
8082 */
8083int qc_check_dcid(struct quic_conn *qc, unsigned char *dcid, size_t dcid_len)
8084{
8085 struct ebmb_node *node;
8086 struct quic_connection_id *id;
8087
8088 /* For ODCID, address is concatenated to it after qc.odcid.len so this
8089 * comparison is safe.
8090 */
8091 if ((qc->scid.len == dcid_len &&
8092 memcmp(qc->scid.data, dcid, dcid_len) == 0) ||
8093 (qc->odcid.len == dcid_len &&
Frédéric Lécaille07846cb2023-02-13 16:14:24 +01008094 memcmp(qc->odcid.data, dcid, dcid_len) == 0)) {
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01008095 return 1;
8096 }
8097
8098 node = ebmb_lookup(&quic_dghdlrs[tid].cids, dcid, dcid_len);
8099 if (node) {
8100 id = ebmb_entry(node, struct quic_connection_id, node);
8101 if (qc == id->qc)
8102 return 1;
8103 }
8104
8105 return 0;
8106}
8107
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008108/* Retrieve the DCID from a QUIC datagram or packet with <buf> as first octet.
8109 * Returns 1 if succeeded, 0 if not.
8110 */
8111int quic_get_dgram_dcid(unsigned char *buf, const unsigned char *end,
8112 unsigned char **dcid, size_t *dcid_len)
8113{
8114 int ret = 0, long_header;
8115 size_t minlen, skip;
8116
8117 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
8118
8119 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
8120 TRACE_PROTO("fixed bit not set", QUIC_EV_CONN_RXPKT);
8121 goto err;
8122 }
8123
8124 long_header = *buf & QUIC_PACKET_LONG_HEADER_BIT;
8125 minlen = long_header ? QUIC_LONG_PACKET_MINLEN :
8126 QUIC_SHORT_PACKET_MINLEN + QUIC_HAP_CID_LEN + QUIC_TLS_TAG_LEN;
8127 skip = long_header ? QUIC_LONG_PACKET_DCID_OFF : QUIC_SHORT_PACKET_DCID_OFF;
8128 if (end - buf < minlen)
8129 goto err;
8130
8131 buf += skip;
8132 *dcid_len = long_header ? *buf++ : QUIC_HAP_CID_LEN;
8133 if (*dcid_len > QUIC_CID_MAXLEN || end - buf <= *dcid_len)
8134 goto err;
8135
8136 *dcid = buf;
8137
8138 ret = 1;
8139 leave:
8140 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
8141 return ret;
8142
8143 err:
8144 TRACE_PROTO("wrong datagram", QUIC_EV_CONN_RXPKT);
8145 goto leave;
8146}
8147
8148/* Notify the MUX layer if alive about an imminent close of <qc>. */
8149void qc_notify_close(struct quic_conn *qc)
8150{
8151 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
8152
8153 if (qc->flags & QUIC_FL_CONN_NOTIFY_CLOSE)
8154 goto leave;
8155
8156 qc->flags |= QUIC_FL_CONN_NOTIFY_CLOSE;
8157 /* wake up the MUX */
8158 if (qc->mux_state == QC_MUX_READY && qc->conn->mux->wake) {
8159 TRACE_STATE("connection closure notidfied to mux",
8160 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
8161 qc->conn->mux->wake(qc->conn);
8162 }
8163 else
8164 TRACE_STATE("connection closure not notidfied to mux",
8165 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
8166 leave:
8167 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
8168}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008169
Amaury Denoyelle8afe4b82023-03-21 11:39:24 +01008170/* Wake-up upper layer for sending if all conditions are met :
8171 * - room in congestion window or probe packet to sent
8172 * - socket FD ready to sent or listener socket used
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01008173 *
8174 * Returns 1 if upper layer has been woken up else 0.
8175 */
8176int qc_notify_send(struct quic_conn *qc)
8177{
Amaury Denoyelle8afe4b82023-03-21 11:39:24 +01008178 const struct quic_pktns *pktns = &qc->pktns[QUIC_TLS_PKTNS_01RTT];
8179
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01008180 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
Amaury Denoyelle8afe4b82023-03-21 11:39:24 +01008181 /* RFC 9002 7.5. Probe Timeout
8182 *
8183 * Probe packets MUST NOT be blocked by the congestion controller.
8184 */
8185 if ((quic_path_prep_data(qc->path) || pktns->tx.pto_probe) &&
Amaury Denoyellecaa16542023-02-28 15:11:26 +01008186 (!qc_test_fd(qc) || !fd_send_active(qc->fd))) {
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01008187 tasklet_wakeup(qc->subs->tasklet);
8188 qc->subs->events &= ~SUB_RETRY_SEND;
8189 if (!qc->subs->events)
8190 qc->subs = NULL;
8191
8192 return 1;
8193 }
8194 }
8195
8196 return 0;
8197}
8198
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008199
8200/* appctx context used by "show quic" command */
8201struct show_quic_ctx {
8202 unsigned int epoch;
8203 struct bref bref; /* back-reference to the quic-conn being dumped */
8204 unsigned int thr;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01008205 int flags;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008206};
8207
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01008208#define QC_CLI_FL_SHOW_ALL 0x1 /* show closing/draining connections */
8209
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008210static int cli_parse_show_quic(char **args, char *payload, struct appctx *appctx, void *private)
8211{
8212 struct show_quic_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
8213
8214 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
8215 return 1;
8216
8217 ctx->epoch = _HA_ATOMIC_FETCH_ADD(&qc_epoch, 1);
8218 ctx->thr = 0;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01008219 ctx->flags = 0;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008220
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01008221 if (*args[2] && strcmp(args[2], "all") == 0)
8222 ctx->flags |= QC_CLI_FL_SHOW_ALL;
8223
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008224 LIST_INIT(&ctx->bref.users);
8225
8226 return 0;
8227}
8228
8229static int cli_io_handler_dump_quic(struct appctx *appctx)
8230{
8231 struct show_quic_ctx *ctx = appctx->svcctx;
8232 struct stconn *sc = appctx_sc(appctx);
8233 struct quic_conn *qc;
Frédéric Lécaillea3772e12023-03-21 13:42:43 +01008234 struct quic_pktns *pktns;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008235 struct eb64_node *node;
8236 struct qc_stream_desc *stream;
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01008237 char bufaddr[INET6_ADDRSTRLEN], bufport[6];
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01008238 int expire;
8239 unsigned char cid_len;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008240
8241 thread_isolate();
8242
8243 if (ctx->thr >= global.nbthread)
8244 goto done;
8245
8246 if (unlikely(sc_ic(sc)->flags & CF_SHUTW)) {
8247 /* If we're forced to shut down, we might have to remove our
8248 * reference to the last stream being dumped.
8249 */
8250 if (!LIST_ISEMPTY(&ctx->bref.users))
8251 LIST_DEL_INIT(&ctx->bref.users);
8252 goto done;
8253 }
8254
8255 chunk_reset(&trash);
8256
8257 if (!LIST_ISEMPTY(&ctx->bref.users)) {
8258 /* Remove show_quic_ctx from previous quic_conn instance. */
8259 LIST_DEL_INIT(&ctx->bref.users);
8260 }
8261 else if (!ctx->bref.ref) {
8262 /* First invocation. */
8263 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
8264 }
8265
8266 while (1) {
8267 int done = 0;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008268 int i;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008269
8270 if (ctx->bref.ref == &ha_thread_ctx[ctx->thr].quic_conns) {
Amaury Denoyelle2d376292023-03-08 09:42:31 +01008271 /* If closing connections requested through "all", move
8272 * to quic_conns_clo list after browsing quic_conns.
8273 * Else move directly to the next quic_conns thread.
8274 */
8275 if (ctx->flags & QC_CLI_FL_SHOW_ALL) {
8276 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns_clo.n;
8277 continue;
8278 }
8279
8280 done = 1;
8281 }
8282 else if (ctx->bref.ref == &ha_thread_ctx[ctx->thr].quic_conns_clo) {
8283 /* Closing list entirely browsed, go to next quic_conns
8284 * thread.
8285 */
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008286 done = 1;
8287 }
8288 else {
Amaury Denoyelle2d376292023-03-08 09:42:31 +01008289 /* Retrieve next element of the current list. */
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008290 qc = LIST_ELEM(ctx->bref.ref, struct quic_conn *, el_th_ctx);
8291 if ((int)(qc->qc_epoch - ctx->epoch) > 0)
8292 done = 1;
8293 }
8294
8295 if (done) {
8296 ++ctx->thr;
8297 if (ctx->thr >= global.nbthread)
8298 break;
Amaury Denoyelle2d376292023-03-08 09:42:31 +01008299 /* Switch to next thread quic_conns list. */
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008300 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
8301 continue;
8302 }
8303
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01008304 /* CIDs */
8305 chunk_appendf(&trash, "* %p[%02u]: scid=", qc, qc->tid);
8306 for (cid_len = 0; cid_len < qc->scid.len; ++cid_len)
8307 chunk_appendf(&trash, "%02x", qc->scid.data[cid_len]);
8308 while (cid_len++ < 20)
8309 chunk_appendf(&trash, "..");
8310
8311 chunk_appendf(&trash, " dcid=");
8312 for (cid_len = 0; cid_len < qc->dcid.len; ++cid_len)
8313 chunk_appendf(&trash, "%02x", qc->dcid.data[cid_len]);
8314 while (cid_len++ < 20)
8315 chunk_appendf(&trash, "..");
8316
8317 chunk_appendf(&trash, "\n");
8318
Frédéric Lécaille5e3201e2023-03-07 15:18:02 +01008319 chunk_appendf(&trash, " loc. TPs:");
8320 quic_transport_params_dump(&trash, qc, &qc->rx.params);
Frédéric Lécaille8f991942023-03-24 15:14:45 +01008321 chunk_appendf(&trash, "\n");
Frédéric Lécaille5e3201e2023-03-07 15:18:02 +01008322 chunk_appendf(&trash, " rem. TPs:");
8323 quic_transport_params_dump(&trash, qc, &qc->tx.params);
Frédéric Lécaille8f991942023-03-24 15:14:45 +01008324 chunk_appendf(&trash, "\n");
Frédéric Lécaille5e3201e2023-03-07 15:18:02 +01008325
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01008326 /* Connection state */
8327 if (qc->flags & QUIC_FL_CONN_CLOSING)
8328 chunk_appendf(&trash, " st=closing ");
8329 else if (qc->flags & QUIC_FL_CONN_DRAINING)
8330 chunk_appendf(&trash, " st=draining ");
8331 else if (qc->state < QUIC_HS_ST_CONFIRMED)
8332 chunk_appendf(&trash, " st=handshake ");
8333 else
8334 chunk_appendf(&trash, " st=opened ");
8335
8336 if (qc->mux_state == QC_MUX_NULL)
8337 chunk_appendf(&trash, "mux=null ");
8338 else if (qc->mux_state == QC_MUX_READY)
8339 chunk_appendf(&trash, "mux=ready ");
8340 else
8341 chunk_appendf(&trash, "mux=released ");
8342
8343 expire = qc->idle_timer_task->expire;
8344 chunk_appendf(&trash, "expire=%02ds ",
8345 expire > now_ms ? (expire - now_ms) / 1000 : 0);
8346
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008347 chunk_appendf(&trash, "\n");
8348
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01008349 /* Socket */
8350 chunk_appendf(&trash, " fd=%d", qc->fd);
8351 if (qc->local_addr.ss_family == AF_INET ||
8352 qc->local_addr.ss_family == AF_INET6) {
8353 addr_to_str(&qc->local_addr, bufaddr, sizeof(bufaddr));
8354 port_to_str(&qc->local_addr, bufport, sizeof(bufport));
8355 chunk_appendf(&trash, " from=%s:%s", bufaddr, bufport);
8356
8357 addr_to_str(&qc->peer_addr, bufaddr, sizeof(bufaddr));
8358 port_to_str(&qc->peer_addr, bufport, sizeof(bufport));
8359 chunk_appendf(&trash, " to=%s:%s", bufaddr, bufport);
8360 }
8361
8362 chunk_appendf(&trash, "\n");
8363
Frédéric Lécaillea3772e12023-03-21 13:42:43 +01008364 /* Packet number spaces information */
8365 pktns = &qc->pktns[QUIC_TLS_PKTNS_INITIAL];
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01008366 chunk_appendf(&trash, " [initl] rx.ackrng=%-6zu tx.inflight=%-6zu",
Frédéric Lécaillea3772e12023-03-21 13:42:43 +01008367 pktns->rx.arngs.sz, pktns->tx.in_flight);
8368 pktns = &qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE];
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01008369 chunk_appendf(&trash, " [hndshk] rx.ackrng=%-6zu tx.inflight=%-6zu\n",
Frédéric Lécaillea3772e12023-03-21 13:42:43 +01008370 pktns->rx.arngs.sz, pktns->tx.in_flight);
8371 pktns = &qc->pktns[QUIC_TLS_PKTNS_01RTT];
8372 chunk_appendf(&trash, " [01rtt] rx.ackrng=%-6zu tx.inflight=%-6zu\n",
8373 pktns->rx.arngs.sz, pktns->tx.in_flight);
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01008374
Frédéric Lécaillea3772e12023-03-21 13:42:43 +01008375 chunk_appendf(&trash, " srtt=%-4u rttvar=%-4u rttmin=%-4u ptoc=%-4u cwnd=%-6zu\n",
8376 qc->path->loss.srtt >> 3, qc->path->loss.rtt_var >> 2,
8377 qc->path->loss.rtt_min, qc->path->loss.pto_count, qc->path->cwnd);
8378
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01008379
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008380 /* Streams */
8381 node = eb64_first(&qc->streams_by_id);
8382 i = 0;
8383 while (node) {
8384 stream = eb64_entry(node, struct qc_stream_desc, by_id);
8385 node = eb64_next(node);
8386
Amaury Denoyellea9de25a2023-02-10 09:25:22 +01008387 chunk_appendf(&trash, " | stream=%-8llu", (unsigned long long)stream->by_id.key);
8388 chunk_appendf(&trash, " off=%-8llu ack=%-8llu",
8389 (unsigned long long)stream->buf_offset,
8390 (unsigned long long)stream->ack_offset);
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008391
8392 if (!(++i % 3)) {
8393 chunk_appendf(&trash, "\n");
8394 i = 0;
8395 }
8396 }
8397
8398 chunk_appendf(&trash, "\n");
8399
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008400 if (applet_putchk(appctx, &trash) == -1) {
8401 /* Register show_quic_ctx to quic_conn instance. */
8402 LIST_APPEND(&qc->back_refs, &ctx->bref.users);
8403 goto full;
8404 }
8405
8406 ctx->bref.ref = qc->el_th_ctx.n;
8407 }
8408
8409 done:
8410 thread_release();
8411 return 1;
8412
8413 full:
8414 thread_release();
8415 return 0;
8416}
8417
8418static void cli_release_show_quic(struct appctx *appctx)
8419{
8420 struct show_quic_ctx *ctx = appctx->svcctx;
8421
8422 if (ctx->thr < global.nbthread) {
8423 thread_isolate();
8424 if (!LIST_ISEMPTY(&ctx->bref.users))
8425 LIST_DEL_INIT(&ctx->bref.users);
8426 thread_release();
8427 }
8428}
8429
8430static struct cli_kw_list cli_kws = {{ }, {
8431 { { "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 +01008432 {{},}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008433}};
8434
8435INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
8436
8437static void init_quic()
8438{
8439 int thr;
8440
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01008441 for (thr = 0; thr < MAX_THREADS; ++thr) {
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008442 LIST_INIT(&ha_thread_ctx[thr].quic_conns);
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01008443 LIST_INIT(&ha_thread_ctx[thr].quic_conns_clo);
8444 }
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008445}
8446INITCALL0(STG_INIT, init_quic);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008447
8448/*
8449 * Local variables:
8450 * c-indent-level: 8
8451 * c-basic-offset: 8
8452 * End:
8453 */