blob: e512490cdcbb4e0e339b2f2d5c32c993749075ed [file] [log] [blame]
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001/*
2 * QUIC protocol implementation. Lower layer with internal features implemented
3 * here such as QUIC encryption, idle timeout, acknowledgement and
4 * retransmission.
5 *
6 * Copyright 2020 HAProxy Technologies, Frederic Lecaille <flecaille@haproxy.com>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version
11 * 2 of the License, or (at your option) any later version.
12 *
13 */
14
15#include <haproxy/quic_conn.h>
16
17#define _GNU_SOURCE
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020018#include <stdio.h>
19#include <stdlib.h>
20
21#include <sys/socket.h>
22#include <sys/stat.h>
23#include <sys/types.h>
24
25#include <netinet/tcp.h>
26
27#include <import/ebmbtree.h>
28
29#include <haproxy/buf-t.h>
30#include <haproxy/compat.h>
31#include <haproxy/api.h>
32#include <haproxy/debug.h>
33#include <haproxy/tools.h>
34#include <haproxy/ticks.h>
35
Amaury Denoyelle15c74702023-02-01 10:18:26 +010036#include <haproxy/applet-t.h>
37#include <haproxy/cli.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020038#include <haproxy/connection.h>
39#include <haproxy/fd.h>
40#include <haproxy/freq_ctr.h>
41#include <haproxy/global.h>
42#include <haproxy/h3.h>
43#include <haproxy/hq_interop.h>
44#include <haproxy/log.h>
45#include <haproxy/mux_quic.h>
46#include <haproxy/ncbuf.h>
47#include <haproxy/pipe.h>
48#include <haproxy/proxy.h>
49#include <haproxy/quic_cc.h>
50#include <haproxy/quic_frame.h>
51#include <haproxy/quic_enc.h>
52#include <haproxy/quic_loss.h>
53#include <haproxy/quic_sock.h>
54#include <haproxy/quic_stats.h>
55#include <haproxy/quic_stream.h>
56#include <haproxy/quic_tp.h>
57#include <haproxy/cbuf.h>
58#include <haproxy/proto_quic.h>
59#include <haproxy/quic_tls.h>
60#include <haproxy/ssl_sock.h>
61#include <haproxy/task.h>
Amaury Denoyelle15c74702023-02-01 10:18:26 +010062#include <haproxy/thread.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020063#include <haproxy/trace.h>
64
Amaury Denoyelle15c74702023-02-01 10:18:26 +010065/* incremented by each "show quic". */
66static unsigned int qc_epoch = 0;
67
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020068/* list of supported QUIC versions by this implementation */
69const struct quic_version quic_versions[] = {
70 {
71 .num = QUIC_PROTOCOL_VERSION_DRAFT_29,
72 .initial_salt = initial_salt_draft_29,
73 .initial_salt_len = sizeof initial_salt_draft_29,
74 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V1,
75 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V1) - 1,
76 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V1,
77 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V1) - 1,
78 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V1,
79 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V1) - 1,
80 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V1,
81 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V1) - 1,
82 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_DRAFT,
83 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_DRAFT,
84 },
85 {
86 .num = QUIC_PROTOCOL_VERSION_1,
87 .initial_salt = initial_salt_v1,
88 .initial_salt_len = sizeof initial_salt_v1,
89 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V1,
90 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V1) - 1,
91 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V1,
92 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V1) - 1,
93 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V1,
94 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V1) - 1,
95 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V1,
96 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V1) - 1,
97 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V1,
98 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V1,
99 },
100 {
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +0100101 .num = QUIC_PROTOCOL_VERSION_2,
102 .initial_salt = initial_salt_v2,
103 .initial_salt_len = sizeof initial_salt_v2,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200104 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V2,
105 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V2) - 1,
106 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V2,
107 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V2) - 1,
108 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V2,
109 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V2) - 1,
110 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V2,
111 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V2) - 1,
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +0100112 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V2,
113 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V2,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200114 },
115};
116
117/* The total number of supported versions */
118const size_t quic_versions_nb = sizeof quic_versions / sizeof *quic_versions;
119/* Listener only preferred version */
120const struct quic_version *preferred_version;
121
122/* trace source and events */
123static void quic_trace(enum trace_level level, uint64_t mask, \
124 const struct trace_source *src,
125 const struct ist where, const struct ist func,
126 const void *a1, const void *a2, const void *a3, const void *a4);
127
128static const struct trace_event quic_trace_events[] = {
129 { .mask = QUIC_EV_CONN_NEW, .name = "new_conn", .desc = "new QUIC connection" },
130 { .mask = QUIC_EV_CONN_INIT, .name = "new_conn_init", .desc = "new QUIC connection initialization" },
131 { .mask = QUIC_EV_CONN_ISEC, .name = "init_secs", .desc = "initial secrets derivation" },
132 { .mask = QUIC_EV_CONN_RSEC, .name = "read_secs", .desc = "read secrets derivation" },
133 { .mask = QUIC_EV_CONN_WSEC, .name = "write_secs", .desc = "write secrets derivation" },
134 { .mask = QUIC_EV_CONN_LPKT, .name = "lstnr_packet", .desc = "new listener received packet" },
135 { .mask = QUIC_EV_CONN_SPKT, .name = "srv_packet", .desc = "new server received packet" },
136 { .mask = QUIC_EV_CONN_ENCPKT, .name = "enc_hdshk_pkt", .desc = "handhshake packet encryption" },
137 { .mask = QUIC_EV_CONN_TXPKT, .name = "tx_pkt", .desc = "TX packet" },
138 { .mask = QUIC_EV_CONN_PAPKT, .name = "phdshk_apkt", .desc = "post handhshake application packet preparation" },
139 { .mask = QUIC_EV_CONN_PAPKTS, .name = "phdshk_apkts", .desc = "post handhshake application packets preparation" },
140 { .mask = QUIC_EV_CONN_IO_CB, .name = "qc_io_cb", .desc = "QUIC conn. I/O processing" },
141 { .mask = QUIC_EV_CONN_RMHP, .name = "rm_hp", .desc = "Remove header protection" },
142 { .mask = QUIC_EV_CONN_PRSHPKT, .name = "parse_hpkt", .desc = "parse handshake packet" },
143 { .mask = QUIC_EV_CONN_PRSAPKT, .name = "parse_apkt", .desc = "parse application packet" },
144 { .mask = QUIC_EV_CONN_PRSFRM, .name = "parse_frm", .desc = "parse frame" },
145 { .mask = QUIC_EV_CONN_PRSAFRM, .name = "parse_ack_frm", .desc = "parse ACK frame" },
146 { .mask = QUIC_EV_CONN_BFRM, .name = "build_frm", .desc = "build frame" },
147 { .mask = QUIC_EV_CONN_PHPKTS, .name = "phdshk_pkts", .desc = "handhshake packets preparation" },
148 { .mask = QUIC_EV_CONN_TRMHP, .name = "rm_hp_try", .desc = "header protection removing try" },
149 { .mask = QUIC_EV_CONN_ELRMHP, .name = "el_rm_hp", .desc = "handshake enc. level header protection removing" },
150 { .mask = QUIC_EV_CONN_RXPKT, .name = "rx_pkt", .desc = "RX packet" },
151 { .mask = QUIC_EV_CONN_SSLDATA, .name = "ssl_provide_data", .desc = "CRYPTO data provision to TLS stack" },
152 { .mask = QUIC_EV_CONN_RXCDATA, .name = "el_treat_rx_cfrms",.desc = "enc. level RX CRYPTO frames processing"},
153 { .mask = QUIC_EV_CONN_ADDDATA, .name = "add_hdshk_data", .desc = "TLS stack ->add_handshake_data() call"},
154 { .mask = QUIC_EV_CONN_FFLIGHT, .name = "flush_flight", .desc = "TLS stack ->flush_flight() call"},
155 { .mask = QUIC_EV_CONN_SSLALERT, .name = "send_alert", .desc = "TLS stack ->send_alert() call"},
156 { .mask = QUIC_EV_CONN_RTTUPDT, .name = "rtt_updt", .desc = "RTT sampling" },
157 { .mask = QUIC_EV_CONN_SPPKTS, .name = "sppkts", .desc = "send prepared packets" },
158 { .mask = QUIC_EV_CONN_PKTLOSS, .name = "pktloss", .desc = "detect packet loss" },
159 { .mask = QUIC_EV_CONN_STIMER, .name = "stimer", .desc = "set timer" },
160 { .mask = QUIC_EV_CONN_PTIMER, .name = "ptimer", .desc = "process timer" },
161 { .mask = QUIC_EV_CONN_SPTO, .name = "spto", .desc = "set PTO" },
162 { .mask = QUIC_EV_CONN_BCFRMS, .name = "bcfrms", .desc = "build CRYPTO data frames" },
163 { .mask = QUIC_EV_CONN_XPRTSEND, .name = "xprt_send", .desc = "sending XRPT subscription" },
164 { .mask = QUIC_EV_CONN_XPRTRECV, .name = "xprt_recv", .desc = "receiving XRPT subscription" },
165 { .mask = QUIC_EV_CONN_FREED, .name = "conn_freed", .desc = "releasing conn. memory" },
166 { .mask = QUIC_EV_CONN_CLOSE, .name = "conn_close", .desc = "closing conn." },
167 { .mask = QUIC_EV_CONN_ACKSTRM, .name = "ack_strm", .desc = "STREAM ack."},
168 { .mask = QUIC_EV_CONN_FRMLIST, .name = "frm_list", .desc = "frame list"},
169 { .mask = QUIC_EV_STATELESS_RST, .name = "stateless_reset", .desc = "stateless reset sent"},
170 { .mask = QUIC_EV_TRANSP_PARAMS, .name = "transport_params", .desc = "transport parameters"},
171 { .mask = QUIC_EV_CONN_IDLE_TIMER, .name = "idle_timer", .desc = "idle timer task"},
172 { .mask = QUIC_EV_CONN_SUB, .name = "xprt_sub", .desc = "RX/TX subcription or unsubscription to QUIC xprt"},
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200173 { .mask = QUIC_EV_CONN_RCV, .name = "conn_recv", .desc = "RX on connection" },
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200174 { /* end */ }
175};
176
177static const struct name_desc quic_trace_lockon_args[4] = {
178 /* arg1 */ { /* already used by the connection */ },
179 /* arg2 */ { .name="quic", .desc="QUIC transport" },
180 /* arg3 */ { },
181 /* arg4 */ { }
182};
183
184static const struct name_desc quic_trace_decoding[] = {
185#define QUIC_VERB_CLEAN 1
186 { .name="clean", .desc="only user-friendly stuff, generally suitable for level \"user\"" },
187 { /* end */ }
188};
189
190
191struct trace_source trace_quic = {
192 .name = IST("quic"),
193 .desc = "QUIC xprt",
194 .arg_def = TRC_ARG1_QCON, /* TRACE()'s first argument is always a quic_conn */
195 .default_cb = quic_trace,
196 .known_events = quic_trace_events,
197 .lockon_args = quic_trace_lockon_args,
198 .decoding = quic_trace_decoding,
199 .report_events = ~0, /* report everything by default */
200};
201
202#define TRACE_SOURCE &trace_quic
203INITCALL1(STG_REGISTER, trace_register_source, TRACE_SOURCE);
204
205static BIO_METHOD *ha_quic_meth;
206
207DECLARE_POOL(pool_head_quic_tx_ring, "quic_tx_ring", QUIC_TX_RING_BUFSZ);
208DECLARE_POOL(pool_head_quic_conn_rxbuf, "quic_conn_rxbuf", QUIC_CONN_RX_BUFSZ);
209DECLARE_STATIC_POOL(pool_head_quic_conn_ctx,
210 "quic_conn_ctx", sizeof(struct ssl_sock_ctx));
211DECLARE_STATIC_POOL(pool_head_quic_conn, "quic_conn", sizeof(struct quic_conn));
212DECLARE_POOL(pool_head_quic_connection_id,
213 "quic_connnection_id", sizeof(struct quic_connection_id));
214DECLARE_POOL(pool_head_quic_dgram, "quic_dgram", sizeof(struct quic_dgram));
215DECLARE_POOL(pool_head_quic_rx_packet, "quic_rx_packet", sizeof(struct quic_rx_packet));
216DECLARE_POOL(pool_head_quic_tx_packet, "quic_tx_packet", sizeof(struct quic_tx_packet));
217DECLARE_STATIC_POOL(pool_head_quic_rx_crypto_frm, "quic_rx_crypto_frm", sizeof(struct quic_rx_crypto_frm));
218DECLARE_STATIC_POOL(pool_head_quic_crypto_buf, "quic_crypto_buf", sizeof(struct quic_crypto_buf));
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +0200219DECLARE_STATIC_POOL(pool_head_quic_cstream, "quic_cstream", sizeof(struct quic_cstream));
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200220DECLARE_POOL(pool_head_quic_frame, "quic_frame", sizeof(struct quic_frame));
221DECLARE_STATIC_POOL(pool_head_quic_arng, "quic_arng", sizeof(struct quic_arng_node));
222
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +0100223static struct quic_connection_id *new_quic_cid(struct eb_root *root,
224 struct quic_conn *qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200225static struct quic_tx_packet *qc_build_pkt(unsigned char **pos, const unsigned char *buf_end,
226 struct quic_enc_level *qel, struct quic_tls_ctx *ctx,
227 struct list *frms, struct quic_conn *qc,
228 const struct quic_version *ver, size_t dglen, int pkt_type,
229 int force_ack, int padding, int probe, int cc, int *err);
230struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state);
231static void qc_idle_timer_do_rearm(struct quic_conn *qc);
232static void qc_idle_timer_rearm(struct quic_conn *qc, int read);
233static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc);
234static int quic_conn_init_timer(struct quic_conn *qc);
235static int quic_conn_init_idle_timer_task(struct quic_conn *qc);
236
237/* Only for debug purpose */
238struct enc_debug_info {
239 unsigned char *payload;
240 size_t payload_len;
241 unsigned char *aad;
242 size_t aad_len;
243 uint64_t pn;
244};
245
246/* Initializes a enc_debug_info struct (only for debug purpose) */
247static inline void enc_debug_info_init(struct enc_debug_info *edi,
248 unsigned char *payload, size_t payload_len,
249 unsigned char *aad, size_t aad_len, uint64_t pn)
250{
251 edi->payload = payload;
252 edi->payload_len = payload_len;
253 edi->aad = aad;
254 edi->aad_len = aad_len;
255 edi->pn = pn;
256}
257
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100258/* Used only for QUIC TLS key phase traces */
259struct quic_kp_trace {
260 const unsigned char *rx_sec;
261 size_t rx_seclen;
262 const struct quic_tls_kp *rx;
263 const unsigned char *tx_sec;
264 size_t tx_seclen;
265 const struct quic_tls_kp *tx;
266};
267
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200268/* Trace callback for QUIC.
269 * These traces always expect that arg1, if non-null, is of type connection.
270 */
271static void quic_trace(enum trace_level level, uint64_t mask, const struct trace_source *src,
272 const struct ist where, const struct ist func,
273 const void *a1, const void *a2, const void *a3, const void *a4)
274{
275 const struct quic_conn *qc = a1;
276
277 if (qc) {
278 const struct quic_tls_ctx *tls_ctx;
279
280 chunk_appendf(&trace_buf, " : qc@%p", qc);
281 if (mask & QUIC_EV_CONN_INIT) {
282 chunk_appendf(&trace_buf, "\n odcid");
283 quic_cid_dump(&trace_buf, &qc->odcid);
284 chunk_appendf(&trace_buf, "\n dcid");
285 quic_cid_dump(&trace_buf, &qc->dcid);
286 chunk_appendf(&trace_buf, "\n scid");
287 quic_cid_dump(&trace_buf, &qc->scid);
288 }
289
290 if (mask & QUIC_EV_TRANSP_PARAMS) {
291 const struct quic_transport_params *p = a2;
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100292
293 if (p)
294 quic_transport_params_dump(&trace_buf, qc, p);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200295 }
296
297 if (mask & QUIC_EV_CONN_ADDDATA) {
298 const enum ssl_encryption_level_t *level = a2;
299 const size_t *len = a3;
300
301 if (level) {
302 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
303
304 chunk_appendf(&trace_buf, " el=%c(%d)", quic_enc_level_char(lvl), lvl);
305 }
306 if (len)
307 chunk_appendf(&trace_buf, " len=%llu", (unsigned long long)*len);
308 }
309 if ((mask & QUIC_EV_CONN_ISEC) && qc) {
310 /* Initial read & write secrets. */
311 enum quic_tls_enc_level level = QUIC_TLS_ENC_LEVEL_INITIAL;
312 const unsigned char *rx_sec = a2;
313 const unsigned char *tx_sec = a3;
314
315 tls_ctx = &qc->els[level].tls_ctx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200316 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(level));
317 if (rx_sec)
318 quic_tls_secret_hexdump(&trace_buf, rx_sec, 32);
319 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
320 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(level));
321 if (tx_sec)
322 quic_tls_secret_hexdump(&trace_buf, tx_sec, 32);
323 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200324 }
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100325
326 if ((mask & QUIC_EV_CONN_KP) && qc) {
327 /* Initial read & write secrets. */
328 const struct quic_kp_trace *kp = a2;
329
330 if (kp) {
331 if (kp->rx) {
332 chunk_appendf(&trace_buf, "\n RX kp");
333 if (kp->rx_sec)
334 quic_tls_secret_hexdump(&trace_buf, kp->rx_sec, kp->rx_seclen);
335 quic_tls_kp_keys_hexdump(&trace_buf, kp->rx);
336 }
337 if (kp->tx) {
338 chunk_appendf(&trace_buf, "\n TX kp");
339 if (kp->tx_sec)
340 quic_tls_secret_hexdump(&trace_buf, kp->tx_sec, kp->tx_seclen);
341 quic_tls_kp_keys_hexdump(&trace_buf, kp->tx);
342 }
343 }
344 }
345
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200346 if (mask & (QUIC_EV_CONN_RSEC|QUIC_EV_CONN_RWSEC)) {
347 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200348
349 if (level) {
350 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
351
352 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200353 if (quic_tls_has_rx_sec(&qc->els[lvl])) {
354 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200355 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200356 }
357 else
358 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200359 }
360 }
361
362 if (mask & (QUIC_EV_CONN_WSEC|QUIC_EV_CONN_RWSEC)) {
363 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200364
365 if (level) {
366 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
367
368 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200369 if (quic_tls_has_tx_sec(&qc->els[lvl])) {
370 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200371 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200372 }
373 else
374 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200375 }
376
377 }
378
379 if (mask & QUIC_EV_CONN_FRMLIST) {
380 const struct list *l = a2;
381
382 if (l) {
383 const struct quic_frame *frm;
384 list_for_each_entry(frm, l, list) {
385 chunk_appendf(&trace_buf, " frm@%p", frm);
386 chunk_frm_appendf(&trace_buf, frm);
387 }
388 }
389 }
390
391 if (mask & (QUIC_EV_CONN_TXPKT|QUIC_EV_CONN_PAPKT)) {
392 const struct quic_tx_packet *pkt = a2;
393 const struct quic_enc_level *qel = a3;
394 const ssize_t *room = a4;
395
396 if (qel) {
397 const struct quic_pktns *pktns = qel->pktns;
Frédéric Lécaille45400532023-02-13 18:39:19 +0100398 chunk_appendf(&trace_buf, " qel=%c pto_count=%d cwnd=%llu ppif=%lld pif=%llu "
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200399 "if=%llu pp=%u",
400 quic_enc_level_char_from_qel(qel, qc),
Frédéric Lécaille45400532023-02-13 18:39:19 +0100401 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200402 (unsigned long long)qc->path->cwnd,
403 (unsigned long long)qc->path->prep_in_flight,
404 (unsigned long long)qc->path->in_flight,
405 (unsigned long long)pktns->tx.in_flight,
406 pktns->tx.pto_probe);
407 }
408 if (pkt) {
409 const struct quic_frame *frm;
410 if (pkt->pn_node.key != (uint64_t)-1)
411 chunk_appendf(&trace_buf, " pn=%llu",(ull)pkt->pn_node.key);
412 list_for_each_entry(frm, &pkt->frms, list) {
413 chunk_appendf(&trace_buf, " frm@%p", frm);
414 chunk_frm_appendf(&trace_buf, frm);
415 }
416 }
417
418 if (room) {
419 chunk_appendf(&trace_buf, " room=%lld", (long long)*room);
420 chunk_appendf(&trace_buf, " dcid.len=%llu scid.len=%llu",
421 (unsigned long long)qc->dcid.len, (unsigned long long)qc->scid.len);
422 }
423 }
424
425 if (mask & QUIC_EV_CONN_IO_CB) {
426 const enum quic_handshake_state *state = a2;
427 const int *err = a3;
428
429 if (state)
430 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(*state));
431 if (err)
432 chunk_appendf(&trace_buf, " err=%s", ssl_error_str(*err));
433 }
434
435 if (mask & (QUIC_EV_CONN_TRMHP|QUIC_EV_CONN_ELRMHP|QUIC_EV_CONN_SPKT)) {
436 const struct quic_rx_packet *pkt = a2;
437 const unsigned long *pktlen = a3;
438 const SSL *ssl = a4;
439
440 if (pkt) {
441 chunk_appendf(&trace_buf, " pkt@%p", pkt);
442 if (pkt->type == QUIC_PACKET_TYPE_SHORT && pkt->data)
443 chunk_appendf(&trace_buf, " kp=%d",
444 !!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT));
445 chunk_appendf(&trace_buf, " el=%c",
446 quic_packet_type_enc_level_char(pkt->type));
447 if (pkt->pnl)
448 chunk_appendf(&trace_buf, " pnl=%u pn=%llu", pkt->pnl,
449 (unsigned long long)pkt->pn);
450 if (pkt->token_len)
451 chunk_appendf(&trace_buf, " toklen=%llu",
452 (unsigned long long)pkt->token_len);
453 if (pkt->aad_len)
454 chunk_appendf(&trace_buf, " aadlen=%llu",
455 (unsigned long long)pkt->aad_len);
456 chunk_appendf(&trace_buf, " flags=0x%x len=%llu",
457 pkt->flags, (unsigned long long)pkt->len);
458 }
459 if (pktlen)
460 chunk_appendf(&trace_buf, " (%ld)", *pktlen);
461 if (ssl) {
462 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
463 chunk_appendf(&trace_buf, " el=%c",
464 quic_enc_level_char(ssl_to_quic_enc_level(level)));
465 }
466 }
467
468 if (mask & (QUIC_EV_CONN_RXPKT|QUIC_EV_CONN_PRSHPKT|QUIC_EV_CONN_SSLDATA)) {
469 const struct quic_rx_packet *pkt = a2;
470 const struct quic_rx_crypto_frm *cf = a3;
471 const SSL *ssl = a4;
472
473 if (pkt)
474 chunk_appendf(&trace_buf, " pkt@%p el=%c pn=%llu", pkt,
475 quic_packet_type_enc_level_char(pkt->type),
476 (unsigned long long)pkt->pn);
477 if (cf)
478 chunk_appendf(&trace_buf, " cfoff=%llu cflen=%llu",
479 (unsigned long long)cf->offset_node.key,
480 (unsigned long long)cf->len);
481 if (ssl) {
482 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
483 chunk_appendf(&trace_buf, " rel=%c",
484 quic_enc_level_char(ssl_to_quic_enc_level(level)));
485 }
486
487 if (qc->err.code)
488 chunk_appendf(&trace_buf, " err_code=0x%llx", (ull)qc->err.code);
489 }
490
491 if (mask & (QUIC_EV_CONN_PRSFRM|QUIC_EV_CONN_BFRM)) {
492 const struct quic_frame *frm = a2;
493
494 if (frm)
495 chunk_appendf(&trace_buf, " %s", quic_frame_type_string(frm->type));
496 }
497
498 if (mask & QUIC_EV_CONN_PHPKTS) {
499 const struct quic_enc_level *qel = a2;
500
501 if (qel) {
502 const struct quic_pktns *pktns = qel->pktns;
503 chunk_appendf(&trace_buf,
Frédéric Lécaille45400532023-02-13 18:39:19 +0100504 " qel=%c state=%s ack?%d pto_count=%d cwnd=%llu ppif=%lld pif=%llu if=%llu pp=%u off=%llu",
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200505 quic_enc_level_char_from_qel(qel, qc),
506 quic_hdshk_state_str(qc->state),
507 !!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED),
Frédéric Lécaille45400532023-02-13 18:39:19 +0100508 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200509 (unsigned long long)qc->path->cwnd,
510 (unsigned long long)qc->path->prep_in_flight,
511 (unsigned long long)qc->path->in_flight,
512 (unsigned long long)pktns->tx.in_flight,
Amaury Denoyelle2f668f02022-11-18 15:24:08 +0100513 pktns->tx.pto_probe,
514 qel->cstream ? (unsigned long long)qel->cstream->rx.offset : 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200515 }
516 }
517
518 if (mask & QUIC_EV_CONN_ENCPKT) {
519 const struct enc_debug_info *edi = a2;
520
521 if (edi)
522 chunk_appendf(&trace_buf,
523 " payload=@%p payload_len=%llu"
524 " aad=@%p aad_len=%llu pn=%llu",
525 edi->payload, (unsigned long long)edi->payload_len,
526 edi->aad, (unsigned long long)edi->aad_len,
527 (unsigned long long)edi->pn);
528 }
529
530 if (mask & QUIC_EV_CONN_RMHP) {
531 const struct quic_rx_packet *pkt = a2;
532
533 if (pkt) {
534 const int *ret = a3;
535
536 chunk_appendf(&trace_buf, " pkt@%p", pkt);
537 if (ret && *ret)
538 chunk_appendf(&trace_buf, " pnl=%u pn=%llu",
539 pkt->pnl, (unsigned long long)pkt->pn);
540 }
541 }
542
543 if (mask & QUIC_EV_CONN_PRSAFRM) {
544 const struct quic_frame *frm = a2;
545 const unsigned long *val1 = a3;
546 const unsigned long *val2 = a4;
547
548 if (frm) {
549 chunk_appendf(&trace_buf, " frm@%p", frm);
550 chunk_frm_appendf(&trace_buf, frm);
551 }
552 if (val1)
553 chunk_appendf(&trace_buf, " %lu", *val1);
554 if (val2)
555 chunk_appendf(&trace_buf, "..%lu", *val2);
556 }
557
558 if (mask & QUIC_EV_CONN_ACKSTRM) {
559 const struct quic_stream *s = a2;
560 const struct qc_stream_desc *stream = a3;
561
562 if (s)
563 chunk_appendf(&trace_buf, " off=%llu len=%llu", (ull)s->offset.key, (ull)s->len);
564 if (stream)
565 chunk_appendf(&trace_buf, " ack_offset=%llu", (ull)stream->ack_offset);
566 }
567
568 if (mask & QUIC_EV_CONN_RTTUPDT) {
569 const unsigned int *rtt_sample = a2;
570 const unsigned int *ack_delay = a3;
571 const struct quic_loss *ql = a4;
572
573 if (rtt_sample)
574 chunk_appendf(&trace_buf, " rtt_sample=%ums", *rtt_sample);
575 if (ack_delay)
576 chunk_appendf(&trace_buf, " ack_delay=%ums", *ack_delay);
577 if (ql)
578 chunk_appendf(&trace_buf,
579 " srtt=%ums rttvar=%ums min_rtt=%ums",
580 ql->srtt >> 3, ql->rtt_var >> 2, ql->rtt_min);
581 }
582 if (mask & QUIC_EV_CONN_CC) {
583 const struct quic_cc_event *ev = a2;
584 const struct quic_cc *cc = a3;
585
586 if (a2)
587 quic_cc_event_trace(&trace_buf, ev);
588 if (a3)
589 quic_cc_state_trace(&trace_buf, cc);
590 }
591
592 if (mask & QUIC_EV_CONN_PKTLOSS) {
593 const struct quic_pktns *pktns = a2;
594 const struct list *lost_pkts = a3;
595
596 if (pktns) {
597 chunk_appendf(&trace_buf, " pktns=%s",
598 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
599 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H");
600 if (pktns->tx.loss_time)
601 chunk_appendf(&trace_buf, " loss_time=%dms",
602 TICKS_TO_MS(tick_remain(now_ms, pktns->tx.loss_time)));
603 }
604 if (lost_pkts && !LIST_ISEMPTY(lost_pkts)) {
605 struct quic_tx_packet *pkt;
606
607 chunk_appendf(&trace_buf, " lost_pkts:");
608 list_for_each_entry(pkt, lost_pkts, list)
609 chunk_appendf(&trace_buf, " %lu", (unsigned long)pkt->pn_node.key);
610 }
611 }
612
613 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_PTIMER|QUIC_EV_CONN_SPTO)) {
614 const struct quic_pktns *pktns = a2;
615 const int *duration = a3;
616 const uint64_t *ifae_pkts = a4;
617
618 if (ifae_pkts)
619 chunk_appendf(&trace_buf, " ifae_pkts=%llu",
620 (unsigned long long)*ifae_pkts);
621 if (pktns) {
622 chunk_appendf(&trace_buf, " pktns=%s pp=%d",
623 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
624 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
625 pktns->tx.pto_probe);
626 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_SPTO)) {
627 if (pktns->tx.in_flight)
628 chunk_appendf(&trace_buf, " if=%llu", (ull)pktns->tx.in_flight);
629 if (pktns->tx.loss_time)
630 chunk_appendf(&trace_buf, " loss_time=%dms",
631 TICKS_TO_MS(pktns->tx.loss_time - now_ms));
632 }
633 if (mask & QUIC_EV_CONN_SPTO) {
634 if (pktns->tx.time_of_last_eliciting)
635 chunk_appendf(&trace_buf, " tole=%dms",
636 TICKS_TO_MS(pktns->tx.time_of_last_eliciting - now_ms));
637 if (duration)
638 chunk_appendf(&trace_buf, " dur=%dms", TICKS_TO_MS(*duration));
639 }
640 }
641
642 if (!(mask & (QUIC_EV_CONN_SPTO|QUIC_EV_CONN_PTIMER)) && qc->timer_task) {
643 chunk_appendf(&trace_buf,
644 " expire=%dms", TICKS_TO_MS(qc->timer - now_ms));
645 }
646 }
647
648 if (mask & QUIC_EV_CONN_SPPKTS) {
649 const struct quic_tx_packet *pkt = a2;
650
Frédéric Lécaille45400532023-02-13 18:39:19 +0100651 chunk_appendf(&trace_buf, " pto_count=%d cwnd=%llu ppif=%llu pif=%llu",
652 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200653 (unsigned long long)qc->path->cwnd,
654 (unsigned long long)qc->path->prep_in_flight,
655 (unsigned long long)qc->path->in_flight);
656 if (pkt) {
657 const struct quic_frame *frm;
658 chunk_appendf(&trace_buf, " pn=%lu(%s) iflen=%llu",
659 (unsigned long)pkt->pn_node.key,
660 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
661 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
662 (unsigned long long)pkt->in_flight_len);
663 chunk_appendf(&trace_buf, " rx.bytes=%llu tx.bytes=%llu",
664 (unsigned long long)qc->rx.bytes,
665 (unsigned long long)qc->tx.bytes);
666 list_for_each_entry(frm, &pkt->frms, list) {
667 chunk_appendf(&trace_buf, " frm@%p", frm);
668 chunk_frm_appendf(&trace_buf, frm);
669 }
Frédéric Lécaillebc09f742023-02-13 17:45:36 +0100670
671 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
672 chunk_appendf(&trace_buf, " with scid");
673 quic_cid_dump(&trace_buf, &qc->scid);
674 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200675 }
676 }
677
678 if (mask & QUIC_EV_CONN_SSLALERT) {
679 const uint8_t *alert = a2;
680 const enum ssl_encryption_level_t *level = a3;
681
682 if (alert)
683 chunk_appendf(&trace_buf, " alert=0x%02x", *alert);
684 if (level)
685 chunk_appendf(&trace_buf, " el=%c",
686 quic_enc_level_char(ssl_to_quic_enc_level(*level)));
687 }
688
689 if (mask & QUIC_EV_CONN_BCFRMS) {
690 const size_t *sz1 = a2;
691 const size_t *sz2 = a3;
692 const size_t *sz3 = a4;
693
694 if (sz1)
695 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz1);
696 if (sz2)
697 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz2);
698 if (sz3)
699 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz3);
700 }
701
702 if (mask & QUIC_EV_CONN_PSTRM) {
703 const struct quic_frame *frm = a2;
704
705 if (frm) {
706 chunk_appendf(&trace_buf, " frm@%p", frm);
707 chunk_frm_appendf(&trace_buf, frm);
708 }
709 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +0200710
711 if (mask & QUIC_EV_CONN_ELEVELSEL) {
712 const enum quic_handshake_state *state = a2;
713 const enum quic_tls_enc_level *level = a3;
714 const enum quic_tls_enc_level *next_level = a4;
715
716 if (state)
717 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(qc->state));
718 if (level)
719 chunk_appendf(&trace_buf, " level=%c", quic_enc_level_char(*level));
720 if (next_level)
721 chunk_appendf(&trace_buf, " next_level=%c", quic_enc_level_char(*next_level));
722
723 }
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200724
725 if (mask & QUIC_EV_CONN_RCV) {
726 const struct quic_dgram *dgram = a2;
727
728 if (dgram)
729 chunk_appendf(&trace_buf, " dgram.len=%zu", dgram->len);
730 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200731 }
732 if (mask & QUIC_EV_CONN_LPKT) {
733 const struct quic_rx_packet *pkt = a2;
734 const uint64_t *len = a3;
735 const struct quic_version *ver = a4;
736
737 if (pkt) {
738 chunk_appendf(&trace_buf, " pkt@%p type=0x%02x %s",
739 pkt, pkt->type, qc_pkt_long(pkt) ? "long" : "short");
740 if (pkt->pn_node.key != (uint64_t)-1)
741 chunk_appendf(&trace_buf, " pn=%llu", pkt->pn_node.key);
742 }
743
744 if (len)
745 chunk_appendf(&trace_buf, " len=%llu", (ull)*len);
746
747 if (ver)
748 chunk_appendf(&trace_buf, " ver=0x%08x", ver->num);
749 }
750
751 if (mask & QUIC_EV_STATELESS_RST) {
752 const struct quic_cid *cid = a2;
753
754 if (cid)
755 quic_cid_dump(&trace_buf, cid);
756 }
757
758}
759
760/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
761static inline int quic_peer_validated_addr(struct quic_conn *qc)
762{
763 struct quic_pktns *hdshk_pktns, *app_pktns;
764
765 if (!qc_is_listener(qc))
766 return 1;
767
768 hdshk_pktns = qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns;
769 app_pktns = qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns;
770 if ((hdshk_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
771 (app_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
772 qc->state >= QUIC_HS_ST_COMPLETE)
773 return 1;
774
775 return 0;
776}
777
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100778/* To be called to kill a connection as soon as possible (without sending any packet). */
779void qc_kill_conn(struct quic_conn *qc)
780{
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100781 TRACE_ENTER(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100782 qc->flags |= QUIC_FL_CONN_TO_KILL;
783 task_wakeup(qc->idle_timer_task, TASK_WOKEN_OTHER);
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100784 TRACE_LEAVE(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100785}
786
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200787/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
788 * both loss detection and PTO and schedule the task assiated to this timer if needed.
789 */
790static inline void qc_set_timer(struct quic_conn *qc)
791{
792 struct quic_pktns *pktns;
793 unsigned int pto;
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100794 int handshake_confirmed;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200795
796 TRACE_ENTER(QUIC_EV_CONN_STIMER, qc,
797 NULL, NULL, &qc->path->ifae_pkts);
798
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100799 pktns = NULL;
800 if (!qc->timer_task) {
801 TRACE_PROTO("already released timer task", QUIC_EV_CONN_STIMER, qc);
802 goto leave;
803 }
804
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200805 pktns = quic_loss_pktns(qc);
806 if (tick_isset(pktns->tx.loss_time)) {
807 qc->timer = pktns->tx.loss_time;
808 goto out;
809 }
810
811 /* anti-amplification: the timer must be
812 * cancelled for a server which reached the anti-amplification limit.
813 */
814 if (!quic_peer_validated_addr(qc) &&
815 (qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
816 TRACE_PROTO("anti-amplification reached", QUIC_EV_CONN_STIMER, qc);
817 qc->timer = TICK_ETERNITY;
818 goto out;
819 }
820
821 if (!qc->path->ifae_pkts && quic_peer_validated_addr(qc)) {
822 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, qc);
823 /* Timer cancellation. */
824 qc->timer = TICK_ETERNITY;
825 goto out;
826 }
827
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100828 handshake_confirmed = qc->state >= QUIC_HS_ST_CONFIRMED;
829 pktns = quic_pto_pktns(qc, handshake_confirmed, &pto);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200830 if (tick_isset(pto))
831 qc->timer = pto;
832 out:
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100833 if (qc->timer == TICK_ETERNITY) {
834 qc->timer_task->expire = TICK_ETERNITY;
835 }
836 else if (tick_is_expired(qc->timer, now_ms)) {
837 TRACE_DEVEL("wakeup asap timer task", QUIC_EV_CONN_STIMER, qc);
838 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
839 }
840 else {
841 TRACE_DEVEL("timer task scheduling", QUIC_EV_CONN_STIMER, qc);
842 task_schedule(qc->timer_task, qc->timer);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200843 }
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100844 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200845 TRACE_LEAVE(QUIC_EV_CONN_STIMER, qc, pktns);
846}
847
848/* Derive new keys and ivs required for Key Update feature for <qc> QUIC
849 * connection.
850 * Return 1 if succeeded, 0 if not.
851 */
852static int quic_tls_key_update(struct quic_conn *qc)
853{
854 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100855 struct quic_tls_secrets *rx = &tls_ctx->rx;
856 struct quic_tls_secrets *tx = &tls_ctx->tx;
857 /* Used only for the traces */
858 struct quic_kp_trace kp_trace = {
859 .rx_sec = rx->secret,
860 .rx_seclen = rx->secretlen,
861 .tx_sec = tx->secret,
862 .tx_seclen = tx->secretlen,
863 };
864 /* The next key phase secrets to be derived */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200865 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
866 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
867 const struct quic_version *ver =
868 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
869 int ret = 0;
870
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100871 TRACE_ENTER(QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200872
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200873 nxt_rx = &qc->ku.nxt_rx;
874 nxt_tx = &qc->ku.nxt_tx;
875
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100876 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
877 "nxt_rx->secretlen=%llu rx->secretlen=%llu",
878 (ull)nxt_rx->secretlen, (ull)rx->secretlen);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200879 /* Prepare new RX secrets */
880 if (!quic_tls_sec_update(rx->md, ver, nxt_rx->secret, nxt_rx->secretlen,
881 rx->secret, rx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100882 TRACE_ERROR("New RX secret update failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200883 goto leave;
884 }
885
886 if (!quic_tls_derive_keys(rx->aead, NULL, rx->md, ver,
887 nxt_rx->key, nxt_rx->keylen,
888 nxt_rx->iv, nxt_rx->ivlen, NULL, 0,
889 nxt_rx->secret, nxt_rx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100890 TRACE_ERROR("New RX key derivation failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200891 goto leave;
892 }
893
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100894 kp_trace.rx = nxt_rx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200895 /* Prepare new TX secrets */
896 if (!quic_tls_sec_update(tx->md, ver, nxt_tx->secret, nxt_tx->secretlen,
897 tx->secret, tx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100898 TRACE_ERROR("New TX secret update failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200899 goto leave;
900 }
901
902 if (!quic_tls_derive_keys(tx->aead, NULL, tx->md, ver,
903 nxt_tx->key, nxt_tx->keylen,
904 nxt_tx->iv, nxt_tx->ivlen, NULL, 0,
905 nxt_tx->secret, nxt_tx->secretlen)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100906 TRACE_ERROR("New TX key derivation failed", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200907 goto leave;
908 }
909
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100910 kp_trace.tx = nxt_tx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200911 if (nxt_rx->ctx) {
912 EVP_CIPHER_CTX_free(nxt_rx->ctx);
913 nxt_rx->ctx = NULL;
914 }
915
916 if (!quic_tls_rx_ctx_init(&nxt_rx->ctx, tls_ctx->rx.aead, nxt_rx->key)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100917 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200918 goto leave;
919 }
920
921 if (nxt_tx->ctx) {
922 EVP_CIPHER_CTX_free(nxt_tx->ctx);
923 nxt_tx->ctx = NULL;
924 }
925
926 if (!quic_tls_rx_ctx_init(&nxt_tx->ctx, tls_ctx->tx.aead, nxt_tx->key)) {
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100927 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_KP, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200928 goto leave;
929 }
930
931 ret = 1;
932 leave:
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +0100933 TRACE_LEAVE(QUIC_EV_CONN_KP, qc, &kp_trace);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200934 return ret;
935}
936
937/* Rotate the Key Update information for <qc> QUIC connection.
938 * Must be used after having updated them.
939 * Always succeeds.
940 */
941static void quic_tls_rotate_keys(struct quic_conn *qc)
942{
943 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
944 unsigned char *curr_secret, *curr_iv, *curr_key;
945 EVP_CIPHER_CTX *curr_ctx;
946
947 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
948
949 /* Rotate the RX secrets */
950 curr_ctx = tls_ctx->rx.ctx;
951 curr_secret = tls_ctx->rx.secret;
952 curr_iv = tls_ctx->rx.iv;
953 curr_key = tls_ctx->rx.key;
954
955 tls_ctx->rx.ctx = qc->ku.nxt_rx.ctx;
956 tls_ctx->rx.secret = qc->ku.nxt_rx.secret;
957 tls_ctx->rx.iv = qc->ku.nxt_rx.iv;
958 tls_ctx->rx.key = qc->ku.nxt_rx.key;
959
960 qc->ku.nxt_rx.ctx = qc->ku.prv_rx.ctx;
961 qc->ku.nxt_rx.secret = qc->ku.prv_rx.secret;
962 qc->ku.nxt_rx.iv = qc->ku.prv_rx.iv;
963 qc->ku.nxt_rx.key = qc->ku.prv_rx.key;
964
965 qc->ku.prv_rx.ctx = curr_ctx;
966 qc->ku.prv_rx.secret = curr_secret;
967 qc->ku.prv_rx.iv = curr_iv;
968 qc->ku.prv_rx.key = curr_key;
969 qc->ku.prv_rx.pn = tls_ctx->rx.pn;
970
971 /* Update the TX secrets */
972 curr_ctx = tls_ctx->tx.ctx;
973 curr_secret = tls_ctx->tx.secret;
974 curr_iv = tls_ctx->tx.iv;
975 curr_key = tls_ctx->tx.key;
976
977 tls_ctx->tx.ctx = qc->ku.nxt_tx.ctx;
978 tls_ctx->tx.secret = qc->ku.nxt_tx.secret;
979 tls_ctx->tx.iv = qc->ku.nxt_tx.iv;
980 tls_ctx->tx.key = qc->ku.nxt_tx.key;
981
982 qc->ku.nxt_tx.ctx = curr_ctx;
983 qc->ku.nxt_tx.secret = curr_secret;
984 qc->ku.nxt_tx.iv = curr_iv;
985 qc->ku.nxt_tx.key = curr_key;
986
987 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
988}
989
990/* returns 0 on error, 1 on success */
991int ha_quic_set_encryption_secrets(SSL *ssl, enum ssl_encryption_level_t level,
992 const uint8_t *read_secret,
993 const uint8_t *write_secret, size_t secret_len)
994{
995 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
996 struct quic_tls_ctx *tls_ctx = &qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
997 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200998 struct quic_tls_secrets *rx = NULL, *tx = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200999 const struct quic_version *ver =
1000 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
1001 int ret = 0;
1002
1003 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
1004 BUG_ON(secret_len > QUIC_TLS_SECRET_LEN);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01001005
1006 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
1007 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
1008 goto out;
1009 }
1010
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001011 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
1012 TRACE_PROTO("CC required", QUIC_EV_CONN_RWSEC, qc);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001013 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001014 }
1015
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001016 if (!read_secret)
1017 goto write;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001018
1019 rx = &tls_ctx->rx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001020 if (!quic_tls_secrets_keys_alloc(rx)) {
1021 TRACE_ERROR("RX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
1022 goto leave;
1023 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001024
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001025 rx->aead = tls_aead(cipher);
1026 rx->md = tls_md(cipher);
1027 rx->hp = tls_hp(cipher);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001028
1029 if (!quic_tls_derive_keys(rx->aead, rx->hp, rx->md, ver, rx->key, rx->keylen,
1030 rx->iv, rx->ivlen, rx->hp_key, sizeof rx->hp_key,
1031 read_secret, secret_len)) {
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001032 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001033 goto leave;
1034 }
1035
1036 if (!quic_tls_rx_ctx_init(&rx->ctx, rx->aead, rx->key)) {
1037 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
1038 goto leave;
1039 }
1040
1041 if (!quic_tls_dec_aes_ctx_init(&rx->hp_ctx, rx->hp, rx->hp_key)) {
1042 TRACE_ERROR("could not initial RX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
1043 goto leave;
1044 }
1045
1046 /* Enqueue this connection asap if we could derive O-RTT secrets as
1047 * listener. Note that a listener derives only RX secrets for this
1048 * level.
1049 */
1050 if (qc_is_listener(qc) && level == ssl_encryption_early_data) {
1051 TRACE_DEVEL("pushing connection into accept queue", QUIC_EV_CONN_RWSEC, qc);
1052 quic_accept_push_qc(qc);
1053 }
1054
1055write:
1056
1057 if (!write_secret)
1058 goto out;
1059
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001060 tx = &tls_ctx->tx;
1061 if (!quic_tls_secrets_keys_alloc(tx)) {
1062 TRACE_ERROR("TX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
1063 goto leave;
1064 }
1065
1066 tx->aead = tls_aead(cipher);
1067 tx->md = tls_md(cipher);
1068 tx->hp = tls_hp(cipher);
1069
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001070 if (!quic_tls_derive_keys(tx->aead, tx->hp, tx->md, ver, tx->key, tx->keylen,
1071 tx->iv, tx->ivlen, tx->hp_key, sizeof tx->hp_key,
1072 write_secret, secret_len)) {
1073 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
1074 goto leave;
1075 }
1076
1077 if (!quic_tls_tx_ctx_init(&tx->ctx, tx->aead, tx->key)) {
1078 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
1079 goto leave;
1080 }
1081
1082 if (!quic_tls_enc_aes_ctx_init(&tx->hp_ctx, tx->hp, tx->hp_key)) {
1083 TRACE_ERROR("could not initial TX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
1084 goto leave;
1085 }
1086
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01001087 if (level == ssl_encryption_handshake && qc_is_listener(qc)) {
1088 qc->enc_params_len =
1089 quic_transport_params_encode(qc->enc_params,
1090 qc->enc_params + sizeof qc->enc_params,
1091 &qc->rx.params, ver, 1);
1092 if (!qc->enc_params_len) {
1093 TRACE_ERROR("quic_transport_params_encode() failed", QUIC_EV_CONN_RWSEC);
1094 goto leave;
1095 }
1096
1097 if (!SSL_set_quic_transport_params(qc->xprt_ctx->ssl, qc->enc_params, qc->enc_params_len)) {
1098 TRACE_ERROR("SSL_set_quic_transport_params() failed", QUIC_EV_CONN_RWSEC);
1099 goto leave;
1100 }
1101 }
1102
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001103 if (level == ssl_encryption_application) {
1104 struct quic_tls_kp *prv_rx = &qc->ku.prv_rx;
1105 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
1106 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
1107
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001108 if (rx) {
1109 if (!(rx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1110 TRACE_ERROR("Could not allocate RX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1111 goto leave;
1112 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001113
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001114 memcpy(rx->secret, read_secret, secret_len);
1115 rx->secretlen = secret_len;
1116 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001117
1118 if (tx) {
1119 if (!(tx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1120 TRACE_ERROR("Could not allocate TX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1121 goto leave;
1122 }
1123
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001124 memcpy(tx->secret, write_secret, secret_len);
1125 tx->secretlen = secret_len;
1126 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001127
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001128 /* Initialize all the secret keys lengths */
1129 prv_rx->secretlen = nxt_rx->secretlen = nxt_tx->secretlen = secret_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001130 }
1131
1132 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001133 ret = 1;
1134 leave:
1135 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc, &level);
1136 return ret;
1137}
1138
1139/* This function copies the CRYPTO data provided by the TLS stack found at <data>
1140 * with <len> as size in CRYPTO buffers dedicated to store the information about
1141 * outgoing CRYPTO frames so that to be able to replay the CRYPTO data streams.
1142 * It fails (returns 0) only if it could not managed to allocate enough CRYPTO
1143 * buffers to store all the data.
1144 * Note that CRYPTO data may exist at any encryption level except at 0-RTT.
1145 */
1146static int quic_crypto_data_cpy(struct quic_conn *qc, struct quic_enc_level *qel,
1147 const unsigned char *data, size_t len)
1148{
1149 struct quic_crypto_buf **qcb;
1150 /* The remaining byte to store in CRYPTO buffers. */
1151 size_t cf_offset, cf_len, *nb_buf;
1152 unsigned char *pos;
1153 int ret = 0;
1154
1155 nb_buf = &qel->tx.crypto.nb_buf;
1156 qcb = &qel->tx.crypto.bufs[*nb_buf - 1];
1157 cf_offset = (*nb_buf - 1) * QUIC_CRYPTO_BUF_SZ + (*qcb)->sz;
1158 cf_len = len;
1159
1160 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1161
1162 while (len) {
1163 size_t to_copy, room;
1164
1165 pos = (*qcb)->data + (*qcb)->sz;
1166 room = QUIC_CRYPTO_BUF_SZ - (*qcb)->sz;
1167 to_copy = len > room ? room : len;
1168 if (to_copy) {
1169 memcpy(pos, data, to_copy);
1170 /* Increment the total size of this CRYPTO buffers by <to_copy>. */
1171 qel->tx.crypto.sz += to_copy;
1172 (*qcb)->sz += to_copy;
1173 len -= to_copy;
1174 data += to_copy;
1175 }
1176 else {
1177 struct quic_crypto_buf **tmp;
1178
1179 // FIXME: realloc!
1180 tmp = realloc(qel->tx.crypto.bufs,
1181 (*nb_buf + 1) * sizeof *qel->tx.crypto.bufs);
1182 if (tmp) {
1183 qel->tx.crypto.bufs = tmp;
1184 qcb = &qel->tx.crypto.bufs[*nb_buf];
1185 *qcb = pool_alloc(pool_head_quic_crypto_buf);
1186 if (!*qcb) {
1187 TRACE_ERROR("Could not allocate crypto buf", QUIC_EV_CONN_ADDDATA, qc);
1188 goto leave;
1189 }
1190
1191 (*qcb)->sz = 0;
1192 ++*nb_buf;
1193 }
1194 else {
1195 break;
1196 }
1197 }
1198 }
1199
1200 /* Allocate a TX CRYPTO frame only if all the CRYPTO data
1201 * have been buffered.
1202 */
1203 if (!len) {
1204 struct quic_frame *frm;
1205 struct quic_frame *found = NULL;
1206
1207 /* There is at most one CRYPTO frame in this packet number
1208 * space. Let's look for it.
1209 */
1210 list_for_each_entry(frm, &qel->pktns->tx.frms, list) {
1211 if (frm->type != QUIC_FT_CRYPTO)
1212 continue;
1213
1214 /* Found */
1215 found = frm;
1216 break;
1217 }
1218
1219 if (found) {
1220 found->crypto.len += cf_len;
1221 }
1222 else {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01001223 frm = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001224 if (!frm) {
1225 TRACE_ERROR("Could not allocate quic frame", QUIC_EV_CONN_ADDDATA, qc);
1226 goto leave;
1227 }
1228
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001229 frm->crypto.offset = cf_offset;
1230 frm->crypto.len = cf_len;
1231 frm->crypto.qel = qel;
1232 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
1233 }
1234 }
1235 ret = len == 0;
1236 leave:
1237 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1238 return ret;
1239}
1240
1241/* Prepare the emission of CONNECTION_CLOSE with error <err>. All send/receive
1242 * activity for <qc> will be interrupted.
1243 */
1244void quic_set_connection_close(struct quic_conn *qc, const struct quic_err err)
1245{
1246 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1247 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)
1248 goto leave;
1249
1250 TRACE_STATE("setting immediate close", QUIC_EV_CONN_CLOSE, qc);
1251 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
1252 qc->err.code = err.code;
1253 qc->err.app = err.app;
1254 leave:
1255 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1256}
1257
1258/* Set <alert> TLS alert as QUIC CRYPTO_ERROR error */
1259void quic_set_tls_alert(struct quic_conn *qc, int alert)
1260{
1261 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1262
1263 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
1264 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
1265 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
1266 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
1267 }
1268 quic_set_connection_close(qc, quic_err_tls(alert));
1269 qc->flags |= QUIC_FL_CONN_TLS_ALERT;
1270 TRACE_STATE("Alert set", QUIC_EV_CONN_SSLALERT, qc);
1271
1272 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1273}
1274
1275/* Set the application for <qc> QUIC connection.
1276 * Return 1 if succeeded, 0 if not.
1277 */
1278int quic_set_app_ops(struct quic_conn *qc, const unsigned char *alpn, size_t alpn_len)
1279{
1280 if (alpn_len >= 2 && memcmp(alpn, "h3", 2) == 0)
1281 qc->app_ops = &h3_ops;
1282 else if (alpn_len >= 10 && memcmp(alpn, "hq-interop", 10) == 0)
1283 qc->app_ops = &hq_interop_ops;
1284 else
1285 return 0;
1286
1287 return 1;
1288}
1289
1290/* ->add_handshake_data QUIC TLS callback used by the QUIC TLS stack when it
1291 * wants to provide the QUIC layer with CRYPTO data.
1292 * Returns 1 if succeeded, 0 if not.
1293 */
1294int ha_quic_add_handshake_data(SSL *ssl, enum ssl_encryption_level_t level,
1295 const uint8_t *data, size_t len)
1296{
1297 struct quic_conn *qc;
1298 enum quic_tls_enc_level tel;
1299 struct quic_enc_level *qel;
1300 int ret = 0;
1301
1302 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1303 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1304
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01001305 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
1306 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
1307 goto out;
1308 }
1309
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001310 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
1311 TRACE_PROTO("CC required", QUIC_EV_CONN_ADDDATA, qc);
1312 goto out;
1313 }
1314
1315 tel = ssl_to_quic_enc_level(level);
1316 if (tel == -1) {
1317 TRACE_ERROR("Wrong encryption level", QUIC_EV_CONN_ADDDATA, qc);
1318 goto leave;
1319 }
1320
1321 qel = &qc->els[tel];
1322 if (!quic_crypto_data_cpy(qc, qel, data, len)) {
1323 TRACE_ERROR("Could not bufferize", QUIC_EV_CONN_ADDDATA, qc);
1324 goto leave;
1325 }
1326
1327 TRACE_DEVEL("CRYPTO data buffered", QUIC_EV_CONN_ADDDATA,
1328 qc, &level, &len);
1329 out:
1330 ret = 1;
1331 leave:
1332 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1333 return ret;
1334}
1335
1336int ha_quic_flush_flight(SSL *ssl)
1337{
1338 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1339
1340 TRACE_ENTER(QUIC_EV_CONN_FFLIGHT, qc);
1341 TRACE_LEAVE(QUIC_EV_CONN_FFLIGHT, qc);
1342
1343 return 1;
1344}
1345
1346int ha_quic_send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
1347{
1348 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1349
1350 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1351
1352 TRACE_PROTO("Received TLS alert", QUIC_EV_CONN_SSLALERT, qc, &alert, &level);
1353
1354 quic_set_tls_alert(qc, alert);
1355 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1356 return 1;
1357}
1358
1359/* QUIC TLS methods */
1360static SSL_QUIC_METHOD ha_quic_method = {
1361 .set_encryption_secrets = ha_quic_set_encryption_secrets,
1362 .add_handshake_data = ha_quic_add_handshake_data,
1363 .flush_flight = ha_quic_flush_flight,
1364 .send_alert = ha_quic_send_alert,
1365};
1366
1367/* Initialize the TLS context of a listener with <bind_conf> as configuration.
1368 * Returns an error count.
1369 */
1370int ssl_quic_initial_ctx(struct bind_conf *bind_conf)
1371{
1372 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
1373 int cfgerr = 0;
1374
1375 long options =
1376 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1377 SSL_OP_SINGLE_ECDH_USE |
1378 SSL_OP_CIPHER_SERVER_PREFERENCE;
1379 SSL_CTX *ctx;
1380
1381 ctx = SSL_CTX_new(TLS_server_method());
1382 bind_conf->initial_ctx = ctx;
1383
1384 SSL_CTX_set_options(ctx, options);
1385 SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
1386 SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
1387 SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
1388
1389#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1390# if defined(HAVE_SSL_CLIENT_HELLO_CB)
1391# if defined(SSL_OP_NO_ANTI_REPLAY)
1392 if (bind_conf->ssl_conf.early_data) {
1393 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
1394 SSL_CTX_set_max_early_data(ctx, 0xffffffff);
1395 }
1396# endif /* !SSL_OP_NO_ANTI_REPLAY */
1397 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
1398 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
1399# else /* ! HAVE_SSL_CLIENT_HELLO_CB */
1400 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
1401# endif
1402 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
1403#endif
1404 SSL_CTX_set_quic_method(ctx, &ha_quic_method);
1405
1406 return cfgerr;
1407}
1408
1409/* Decode an expected packet number from <truncated_on> its truncated value,
1410 * depending on <largest_pn> the largest received packet number, and <pn_nbits>
1411 * the number of bits used to encode this packet number (its length in bytes * 8).
1412 * See https://quicwg.org/base-drafts/draft-ietf-quic-transport.html#packet-encoding
1413 */
1414static uint64_t decode_packet_number(uint64_t largest_pn,
1415 uint32_t truncated_pn, unsigned int pn_nbits)
1416{
1417 uint64_t expected_pn = largest_pn + 1;
1418 uint64_t pn_win = (uint64_t)1 << pn_nbits;
1419 uint64_t pn_hwin = pn_win / 2;
1420 uint64_t pn_mask = pn_win - 1;
1421 uint64_t candidate_pn;
1422
1423
1424 candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
1425 /* Note that <pn_win> > <pn_hwin>. */
1426 if (candidate_pn < QUIC_MAX_PACKET_NUM - pn_win &&
1427 candidate_pn + pn_hwin <= expected_pn)
1428 return candidate_pn + pn_win;
1429
1430 if (candidate_pn > expected_pn + pn_hwin && candidate_pn >= pn_win)
1431 return candidate_pn - pn_win;
1432
1433 return candidate_pn;
1434}
1435
1436/* Remove the header protection of <pkt> QUIC packet using <tls_ctx> as QUIC TLS
1437 * cryptographic context.
1438 * <largest_pn> is the largest received packet number and <pn> the address of
1439 * the packet number field for this packet with <byte0> address of its first byte.
1440 * <end> points to one byte past the end of this packet.
1441 * Returns 1 if succeeded, 0 if not.
1442 */
1443static int qc_do_rm_hp(struct quic_conn *qc,
1444 struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx,
1445 int64_t largest_pn, unsigned char *pn, unsigned char *byte0)
1446{
1447 int ret, i, pnlen;
1448 uint64_t packet_number;
1449 uint32_t truncated_pn = 0;
1450 unsigned char mask[5] = {0};
1451 unsigned char *sample;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001452
1453 TRACE_ENTER(QUIC_EV_CONN_RMHP, qc);
1454
1455 ret = 0;
1456
1457 /* Check there is enough data in this packet. */
1458 if (pkt->len - (pn - byte0) < QUIC_PACKET_PN_MAXLEN + sizeof mask) {
1459 TRACE_PROTO("too short packet", QUIC_EV_CONN_RMHP, qc, pkt);
1460 goto leave;
1461 }
1462
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001463 sample = pn + QUIC_PACKET_PN_MAXLEN;
1464
1465 if (!quic_tls_aes_decrypt(mask, sample, sizeof mask, tls_ctx->rx.hp_ctx)) {
1466 TRACE_ERROR("HP removing failed", QUIC_EV_CONN_RMHP, qc, pkt);
1467 goto leave;
1468 }
1469
1470 *byte0 ^= mask[0] & (*byte0 & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
1471 pnlen = (*byte0 & QUIC_PACKET_PNL_BITMASK) + 1;
1472 for (i = 0; i < pnlen; i++) {
1473 pn[i] ^= mask[i + 1];
1474 truncated_pn = (truncated_pn << 8) | pn[i];
1475 }
1476
1477 packet_number = decode_packet_number(largest_pn, truncated_pn, pnlen * 8);
1478 /* Store remaining information for this unprotected header */
1479 pkt->pn = packet_number;
1480 pkt->pnl = pnlen;
1481
1482 ret = 1;
1483 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001484 TRACE_LEAVE(QUIC_EV_CONN_RMHP, qc);
1485 return ret;
1486}
1487
1488/* Encrypt the payload of a QUIC packet with <pn> as number found at <payload>
1489 * address, with <payload_len> as payload length, <aad> as address of
1490 * the ADD and <aad_len> as AAD length depending on the <tls_ctx> QUIC TLS
1491 * context.
1492 * Returns 1 if succeeded, 0 if not.
1493 */
1494static int quic_packet_encrypt(unsigned char *payload, size_t payload_len,
1495 unsigned char *aad, size_t aad_len, uint64_t pn,
1496 struct quic_tls_ctx *tls_ctx, struct quic_conn *qc)
1497{
1498 int ret = 0;
1499 unsigned char iv[QUIC_TLS_IV_LEN];
1500 unsigned char *tx_iv = tls_ctx->tx.iv;
1501 size_t tx_iv_sz = tls_ctx->tx.ivlen;
1502 struct enc_debug_info edi;
1503
1504 TRACE_ENTER(QUIC_EV_CONN_ENCPKT, qc);
1505
1506 if (!quic_aead_iv_build(iv, sizeof iv, tx_iv, tx_iv_sz, pn)) {
1507 TRACE_ERROR("AEAD IV building for encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1508 goto err;
1509 }
1510
1511 if (!quic_tls_encrypt(payload, payload_len, aad, aad_len,
1512 tls_ctx->tx.ctx, tls_ctx->tx.aead, tls_ctx->tx.key, iv)) {
1513 TRACE_ERROR("QUIC packet encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1514 goto err;
1515 }
1516
1517 ret = 1;
1518 leave:
1519 TRACE_LEAVE(QUIC_EV_CONN_ENCPKT, qc);
1520 return ret;
1521
1522 err:
1523 enc_debug_info_init(&edi, payload, payload_len, aad, aad_len, pn);
1524 goto leave;
1525}
1526
Frédéric Lécaille72027782023-02-22 16:20:09 +01001527/* Select the correct TLS cipher context to used to decipher <pkt> packet
1528 * attached to <qc> connection from <qel> encryption level.
1529 */
1530static inline struct quic_tls_ctx *qc_select_tls_ctx(struct quic_conn *qc,
1531 struct quic_enc_level *qel,
1532 struct quic_rx_packet *pkt)
1533{
1534 return pkt->type != QUIC_PACKET_TYPE_INITIAL ? &qel->tls_ctx :
1535 pkt->version == qc->negotiated_version ? &qc->negotiated_ictx : &qel->tls_ctx;
1536}
1537
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001538/* Decrypt <pkt> packet using encryption level <qel> for <qc> connection.
1539 * Decryption is done in place in packet buffer.
1540 *
Ilya Shipitsin5fa29b82022-12-07 09:46:19 +05001541 * Returns 1 on success else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001542 */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001543static int qc_pkt_decrypt(struct quic_conn *qc, struct quic_enc_level *qel,
1544 struct quic_rx_packet *pkt)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001545{
1546 int ret, kp_changed;
1547 unsigned char iv[QUIC_TLS_IV_LEN];
Frédéric Lécaille72027782023-02-22 16:20:09 +01001548 struct quic_tls_ctx *tls_ctx = qc_select_tls_ctx(qc, qel, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001549 EVP_CIPHER_CTX *rx_ctx = tls_ctx->rx.ctx;
1550 unsigned char *rx_iv = tls_ctx->rx.iv;
1551 size_t rx_iv_sz = tls_ctx->rx.ivlen;
1552 unsigned char *rx_key = tls_ctx->rx.key;
1553
1554 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
1555
1556 ret = 0;
1557 kp_changed = 0;
1558
1559 if (pkt->type == QUIC_PACKET_TYPE_SHORT) {
1560 /* The two tested bits are not at the same position,
1561 * this is why they are first both inversed.
1562 */
1563 if (!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT) ^ !(tls_ctx->flags & QUIC_FL_TLS_KP_BIT_SET)) {
1564 if (pkt->pn < tls_ctx->rx.pn) {
1565 /* The lowest packet number of a previous key phase
1566 * cannot be null if it really stores previous key phase
1567 * secrets.
1568 */
1569 // TODO: check if BUG_ON() more suitable
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001570 if (!qc->ku.prv_rx.pn) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001571 TRACE_ERROR("null previous packet number", QUIC_EV_CONN_RXPKT, qc);
1572 goto leave;
1573 }
1574
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001575 rx_ctx = qc->ku.prv_rx.ctx;
1576 rx_iv = qc->ku.prv_rx.iv;
1577 rx_key = qc->ku.prv_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001578 }
1579 else if (pkt->pn > qel->pktns->rx.largest_pn) {
1580 /* Next key phase */
Frédéric Lécaille51a7caf2023-02-23 20:38:23 +01001581 TRACE_PROTO("Key phase changed", QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001582 kp_changed = 1;
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001583 rx_ctx = qc->ku.nxt_rx.ctx;
1584 rx_iv = qc->ku.nxt_rx.iv;
1585 rx_key = qc->ku.nxt_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001586 }
1587 }
1588 }
1589
1590 if (!quic_aead_iv_build(iv, sizeof iv, rx_iv, rx_iv_sz, pkt->pn)) {
1591 TRACE_ERROR("quic_aead_iv_build() failed", QUIC_EV_CONN_RXPKT, qc);
1592 goto leave;
1593 }
1594
1595 ret = quic_tls_decrypt(pkt->data + pkt->aad_len, pkt->len - pkt->aad_len,
1596 pkt->data, pkt->aad_len,
1597 rx_ctx, tls_ctx->rx.aead, rx_key, iv);
1598 if (!ret) {
1599 TRACE_ERROR("quic_tls_decrypt() failed", QUIC_EV_CONN_RXPKT, qc);
1600 goto leave;
1601 }
1602
1603 /* Update the keys only if the packet decryption succeeded. */
1604 if (kp_changed) {
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001605 quic_tls_rotate_keys(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001606 /* Toggle the Key Phase bit */
1607 tls_ctx->flags ^= QUIC_FL_TLS_KP_BIT_SET;
1608 /* Store the lowest packet number received for the current key phase */
1609 tls_ctx->rx.pn = pkt->pn;
1610 /* Prepare the next key update */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001611 if (!quic_tls_key_update(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001612 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_RXPKT, qc);
1613 goto leave;
1614 }
1615 }
1616
1617 /* Update the packet length (required to parse the frames). */
1618 pkt->len -= QUIC_TLS_TAG_LEN;
1619 ret = 1;
1620 leave:
1621 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
1622 return ret;
1623}
1624
1625
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001626/* Release <frm> frame and mark its copies as acknowledged */
1627void qc_release_frm(struct quic_conn *qc, struct quic_frame *frm)
1628{
1629 uint64_t pn;
1630 struct quic_frame *origin, *f, *tmp;
1631
1632 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1633
1634 /* Identify this frame: a frame copy or one of its copies */
1635 origin = frm->origin ? frm->origin : frm;
1636 /* Ensure the source of the copies is flagged as acked, <frm> being
1637 * possibly a copy of <origin>
1638 */
1639 origin->flags |= QUIC_FL_TX_FRAME_ACKED;
1640 /* Mark all the copy of <origin> as acknowledged. We must
1641 * not release the packets (releasing the frames) at this time as
1642 * they are possibly also to be acknowledged alongside the
1643 * the current one.
1644 */
1645 list_for_each_entry_safe(f, tmp, &origin->reflist, ref) {
1646 if (f->pkt) {
1647 f->flags |= QUIC_FL_TX_FRAME_ACKED;
1648 f->origin = NULL;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001649 LIST_DEL_INIT(&f->ref);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001650 pn = f->pkt->pn_node.key;
1651 TRACE_DEVEL("mark frame as acked from packet",
1652 QUIC_EV_CONN_PRSAFRM, qc, f, &pn);
1653 }
1654 else {
1655 TRACE_DEVEL("freeing unsent frame",
1656 QUIC_EV_CONN_PRSAFRM, qc, f);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001657 LIST_DEL_INIT(&f->ref);
1658 qc_frm_free(&f);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001659 }
1660 }
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001661 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001662 pn = frm->pkt->pn_node.key;
1663 quic_tx_packet_refdec(frm->pkt);
1664 TRACE_DEVEL("freeing frame from packet",
1665 QUIC_EV_CONN_PRSAFRM, qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001666 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001667
1668 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1669}
1670
1671/* Schedule a CONNECTION_CLOSE emission on <qc> if the MUX has been released
1672 * and all STREAM data are acknowledged. The MUX is responsible to have set
1673 * <qc.err> before as it is reused for the CONNECTION_CLOSE frame.
1674 *
1675 * TODO this should also be called on lost packet detection
1676 */
1677void qc_check_close_on_released_mux(struct quic_conn *qc)
1678{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001679 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1680
1681 if (qc->mux_state == QC_MUX_RELEASED && eb_is_empty(&qc->streams_by_id)) {
1682 /* Reuse errcode which should have been previously set by the MUX on release. */
1683 quic_set_connection_close(qc, qc->err);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02001684 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001685 }
1686
1687 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1688}
1689
1690/* Remove from <stream> the acknowledged frames.
1691 *
1692 * Returns 1 if at least one frame was removed else 0.
1693 */
1694static int quic_stream_try_to_consume(struct quic_conn *qc,
1695 struct qc_stream_desc *stream)
1696{
1697 int ret;
1698 struct eb64_node *frm_node;
1699
1700 TRACE_ENTER(QUIC_EV_CONN_ACKSTRM, qc);
1701
1702 ret = 0;
1703 frm_node = eb64_first(&stream->acked_frms);
1704 while (frm_node) {
1705 struct quic_stream *strm;
1706 struct quic_frame *frm;
1707 size_t offset, len;
1708
1709 strm = eb64_entry(frm_node, struct quic_stream, offset);
1710 offset = strm->offset.key;
1711 len = strm->len;
1712
1713 if (offset > stream->ack_offset)
1714 break;
1715
1716 if (qc_stream_desc_ack(&stream, offset, len)) {
1717 /* cf. next comment : frame may be freed at this stage. */
1718 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1719 qc, stream ? strm : NULL, stream);
1720 ret = 1;
1721 }
1722
1723 /* If stream is NULL after qc_stream_desc_ack(), it means frame
1724 * has been freed. with the stream frames tree. Nothing to do
1725 * anymore in here.
1726 */
1727 if (!stream) {
1728 qc_check_close_on_released_mux(qc);
1729 ret = 1;
1730 goto leave;
1731 }
1732
1733 frm_node = eb64_next(frm_node);
1734 eb64_delete(&strm->offset);
1735
1736 frm = container_of(strm, struct quic_frame, stream);
1737 qc_release_frm(qc, frm);
1738 }
1739
1740 leave:
1741 TRACE_LEAVE(QUIC_EV_CONN_ACKSTRM, qc);
1742 return ret;
1743}
1744
1745/* Treat <frm> frame whose packet it is attached to has just been acknowledged. */
1746static inline void qc_treat_acked_tx_frm(struct quic_conn *qc,
1747 struct quic_frame *frm)
1748{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001749 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc, frm);
1750
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001751 switch (frm->type) {
1752 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1753 {
1754 struct quic_stream *strm_frm = &frm->stream;
1755 struct eb64_node *node = NULL;
1756 struct qc_stream_desc *stream = NULL;
1757 const size_t offset = strm_frm->offset.key;
1758 const size_t len = strm_frm->len;
1759
1760 /* do not use strm_frm->stream as the qc_stream_desc instance
1761 * might be freed at this stage. Use the id to do a proper
1762 * lookup.
1763 *
1764 * TODO if lookup operation impact on the perf is noticeable,
1765 * implement a refcount on qc_stream_desc instances.
1766 */
1767 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1768 if (!node) {
1769 TRACE_DEVEL("acked stream for released stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm);
1770 qc_release_frm(qc, frm);
1771 /* early return */
1772 goto leave;
1773 }
1774 stream = eb64_entry(node, struct qc_stream_desc, by_id);
1775
1776 TRACE_DEVEL("acked stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm, stream);
1777 if (offset <= stream->ack_offset) {
1778 if (qc_stream_desc_ack(&stream, offset, len)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001779 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1780 qc, strm_frm, stream);
1781 }
1782
1783 if (!stream) {
1784 /* no need to continue if stream freed. */
1785 TRACE_DEVEL("stream released and freed", QUIC_EV_CONN_ACKSTRM, qc);
1786 qc_release_frm(qc, frm);
1787 qc_check_close_on_released_mux(qc);
1788 break;
1789 }
1790
1791 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1792 qc, strm_frm, stream);
1793 qc_release_frm(qc, frm);
1794 }
1795 else {
1796 eb64_insert(&stream->acked_frms, &strm_frm->offset);
1797 }
1798
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01001799 quic_stream_try_to_consume(qc, stream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001800 }
1801 break;
1802 default:
1803 qc_release_frm(qc, frm);
1804 }
1805
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001806 leave:
1807 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1808}
1809
1810/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1811 * deallocating them, and their TX frames.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001812 * May be NULL if <largest> node could not be found.
1813 */
Frédéric Lécaillec664e642023-03-15 17:21:13 +01001814static inline void qc_ackrng_pkts(struct quic_conn *qc,
1815 struct eb_root *pkts,
1816 unsigned int *pkt_flags,
1817 struct list *newly_acked_pkts,
1818 struct eb64_node *largest_node,
1819 uint64_t largest, uint64_t smallest)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001820{
1821 struct eb64_node *node;
1822 struct quic_tx_packet *pkt;
1823
1824 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1825
Frédéric Lécaillec664e642023-03-15 17:21:13 +01001826 node = eb64_lookup_ge(pkts, smallest);
1827 if (!node)
1828 goto leave;
1829
1830 largest_node = largest_node ? largest_node : eb64_lookup_le(pkts, largest);
1831 if (!largest_node)
1832 goto leave;
1833
1834 while (node && node->key <= largest_node->key) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001835 struct quic_frame *frm, *frmbak;
1836
1837 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
1838 *pkt_flags |= pkt->flags;
1839 LIST_INSERT(newly_acked_pkts, &pkt->list);
1840 TRACE_DEVEL("Removing packet #", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
1841 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1842 qc_treat_acked_tx_frm(qc, frm);
Frédéric Lécaille814645f2022-11-18 18:15:28 +01001843 /* If there are others packet in the same datagram <pkt> is attached to,
1844 * detach the previous one and the next one from <pkt>.
1845 */
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01001846 quic_tx_packet_dgram_detach(pkt);
Frédéric Lécaillec664e642023-03-15 17:21:13 +01001847 node = eb64_next(node);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001848 eb64_delete(&pkt->pn_node);
1849 }
1850
Frédéric Lécaillec664e642023-03-15 17:21:13 +01001851 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001852 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001853}
1854
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001855/* Remove all frames from <pkt_frm_list> and reinsert them in the same order
1856 * they have been sent into <pktns_frm_list>. The loss counter of each frame is
1857 * incremented and checked if it does not exceed retransmission limit.
1858 *
1859 * Returns 1 on success, 0 if a frame loss limit is exceeded. A
1860 * CONNECTION_CLOSE is scheduled in this case.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001861 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001862static inline int qc_requeue_nacked_pkt_tx_frms(struct quic_conn *qc,
1863 struct quic_tx_packet *pkt,
1864 struct list *pktns_frm_list)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001865{
1866 struct quic_frame *frm, *frmbak;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001867 struct list *pkt_frm_list = &pkt->frms;
1868 uint64_t pn = pkt->pn_node.key;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001869 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001870
1871 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1872
1873 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
1874 /* First remove this frame from the packet it was attached to */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001875 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001876 quic_tx_packet_refdec(pkt);
1877 /* At this time, this frame is not freed but removed from its packet */
1878 frm->pkt = NULL;
1879 /* Remove any reference to this frame */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001880 qc_frm_unref(frm, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001881 switch (frm->type) {
1882 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1883 {
1884 struct quic_stream *strm_frm = &frm->stream;
1885 struct eb64_node *node = NULL;
1886 struct qc_stream_desc *stream_desc;
1887
1888 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1889 if (!node) {
1890 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
1891 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1892 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001893 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001894 continue;
1895 }
1896
1897 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
1898 /* Do not resend this frame if in the "already acked range" */
1899 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
1900 TRACE_DEVEL("ignored frame in already acked range",
1901 QUIC_EV_CONN_PRSAFRM, qc, frm);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001902 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001903 continue;
1904 }
1905 else if (strm_frm->offset.key < stream_desc->ack_offset) {
Frédéric Lécailleca079792023-03-17 08:56:50 +01001906 uint64_t diff = stream_desc->ack_offset - strm_frm->offset.key;
1907
Frédéric Lécaillec425e032023-03-20 14:32:59 +01001908 qc_stream_frm_mv_fwd(frm, diff);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001909 TRACE_DEVEL("updated partially acked frame",
1910 QUIC_EV_CONN_PRSAFRM, qc, frm);
1911 }
1912 break;
1913 }
1914
1915 default:
1916 break;
1917 }
1918
1919 /* Do not resend probing packet with old data */
1920 if (pkt->flags & QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA) {
1921 TRACE_DEVEL("ignored frame with old data from packet", QUIC_EV_CONN_PRSAFRM,
1922 qc, frm, &pn);
1923 if (frm->origin)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001924 LIST_DEL_INIT(&frm->ref);
1925 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001926 continue;
1927 }
1928
1929 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
1930 TRACE_DEVEL("already acked frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
1931 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1932 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001933 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001934 }
1935 else {
Amaury Denoyelle24d5b722023-01-31 11:44:50 +01001936 if (++frm->loss_count >= global.tune.quic_max_frame_loss) {
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001937 TRACE_ERROR("retransmission limit reached, closing the connection", QUIC_EV_CONN_PRSAFRM, qc);
1938 quic_set_connection_close(qc, quic_err_transport(QC_ERR_INTERNAL_ERROR));
1939 close = 1;
1940 }
1941
Frédéric Lécaillebe795ce2023-03-08 18:23:13 +01001942 LIST_APPEND(pktns_frm_list, &frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001943 TRACE_DEVEL("frame requeued", QUIC_EV_CONN_PRSAFRM, qc, frm);
1944 }
1945 }
1946
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001947 end:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001948 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001949 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001950}
1951
1952/* Free <pkt> TX packet and its attached frames.
1953 * This is the responsibility of the caller to remove this packet of
1954 * any data structure it was possibly attached to.
1955 */
1956static inline void free_quic_tx_packet(struct quic_conn *qc,
1957 struct quic_tx_packet *pkt)
1958{
1959 struct quic_frame *frm, *frmbak;
1960
1961 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1962
1963 if (!pkt)
1964 goto leave;
1965
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001966 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1967 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001968 pool_free(pool_head_quic_tx_packet, pkt);
1969
1970 leave:
1971 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1972}
1973
1974/* Free the TX packets of <pkts> list */
1975static inline void free_quic_tx_pkts(struct quic_conn *qc, struct list *pkts)
1976{
1977 struct quic_tx_packet *pkt, *tmp;
1978
1979 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1980
1981 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1982 LIST_DELETE(&pkt->list);
1983 eb64_delete(&pkt->pn_node);
1984 free_quic_tx_packet(qc, pkt);
1985 }
1986
1987 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1988}
1989
1990/* Remove already sent ranges of acknowledged packet numbers from
1991 * <pktns> packet number space tree below <largest_acked_pn> possibly
1992 * updating the range which contains <largest_acked_pn>.
1993 * Never fails.
1994 */
1995static void qc_treat_ack_of_ack(struct quic_conn *qc,
1996 struct quic_pktns *pktns,
1997 int64_t largest_acked_pn)
1998{
1999 struct eb64_node *ar, *next_ar;
2000 struct quic_arngs *arngs = &pktns->rx.arngs;
2001
2002 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2003
2004 ar = eb64_first(&arngs->root);
2005 while (ar) {
2006 struct quic_arng_node *ar_node;
2007
2008 next_ar = eb64_next(ar);
2009 ar_node = eb64_entry(ar, struct quic_arng_node, first);
2010
2011 if ((int64_t)ar_node->first.key > largest_acked_pn) {
2012 TRACE_DEVEL("first.key > largest", QUIC_EV_CONN_PRSAFRM, qc);
2013 break;
2014 }
2015
2016 if (largest_acked_pn < ar_node->last) {
2017 eb64_delete(ar);
2018 ar_node->first.key = largest_acked_pn + 1;
2019 eb64_insert(&arngs->root, ar);
2020 break;
2021 }
2022
2023 eb64_delete(ar);
2024 pool_free(pool_head_quic_arng, ar_node);
2025 arngs->sz--;
2026 ar = next_ar;
2027 }
2028
2029 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2030}
2031
2032/* Send a packet ack event nofication for each newly acked packet of
2033 * <newly_acked_pkts> list and free them.
2034 * Always succeeds.
2035 */
2036static inline void qc_treat_newly_acked_pkts(struct quic_conn *qc,
2037 struct list *newly_acked_pkts)
2038{
2039 struct quic_tx_packet *pkt, *tmp;
2040 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
2041
2042 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2043
2044 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
2045 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2046 qc->path->prep_in_flight -= pkt->in_flight_len;
2047 qc->path->in_flight -= pkt->in_flight_len;
2048 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2049 qc->path->ifae_pkts--;
2050 /* If this packet contained an ACK frame, proceed to the
2051 * acknowledging of range of acks from the largest acknowledged
2052 * packet number which was sent in an ACK frame by this packet.
2053 */
2054 if (pkt->largest_acked_pn != -1)
2055 qc_treat_ack_of_ack(qc, pkt->pktns, pkt->largest_acked_pn);
2056 ev.ack.acked = pkt->in_flight_len;
2057 ev.ack.time_sent = pkt->time_sent;
2058 quic_cc_event(&qc->path->cc, &ev);
2059 LIST_DELETE(&pkt->list);
2060 eb64_delete(&pkt->pn_node);
2061 quic_tx_packet_refdec(pkt);
2062 }
2063
2064 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2065
2066}
2067
2068/* Release all the frames attached to <pktns> packet number space */
2069static inline void qc_release_pktns_frms(struct quic_conn *qc,
2070 struct quic_pktns *pktns)
2071{
2072 struct quic_frame *frm, *frmbak;
2073
2074 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
2075
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01002076 list_for_each_entry_safe(frm, frmbak, &pktns->tx.frms, list)
2077 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002078
2079 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
2080}
2081
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002082/* Handle <pkts> list of lost packets detected at <now_us> handling their TX
2083 * frames. Send a packet loss event to the congestion controller if in flight
2084 * packet have been lost. Also frees the packet in <pkts> list.
2085 *
2086 * Returns 1 on success else 0 if loss limit has been exceeded. A
2087 * CONNECTION_CLOSE was prepared to close the connection ASAP.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002088 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002089static inline int qc_release_lost_pkts(struct quic_conn *qc,
2090 struct quic_pktns *pktns,
2091 struct list *pkts,
2092 uint64_t now_us)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002093{
2094 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002095 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002096
2097 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2098
2099 if (LIST_ISEMPTY(pkts))
2100 goto leave;
2101
2102 oldest_lost = newest_lost = NULL;
2103 list_for_each_entry_safe(pkt, tmp, pkts, list) {
2104 struct list tmp = LIST_HEAD_INIT(tmp);
2105
2106 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2107 qc->path->prep_in_flight -= pkt->in_flight_len;
2108 qc->path->in_flight -= pkt->in_flight_len;
2109 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2110 qc->path->ifae_pkts--;
2111 /* Treat the frames of this lost packet. */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002112 if (!qc_requeue_nacked_pkt_tx_frms(qc, pkt, &pktns->tx.frms))
2113 close = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002114 LIST_DELETE(&pkt->list);
2115 if (!oldest_lost) {
2116 oldest_lost = newest_lost = pkt;
2117 }
2118 else {
2119 if (newest_lost != oldest_lost)
2120 quic_tx_packet_refdec(newest_lost);
2121 newest_lost = pkt;
2122 }
2123 }
2124
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002125 if (!close) {
2126 if (newest_lost) {
2127 /* Sent a congestion event to the controller */
2128 struct quic_cc_event ev = { };
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002129
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002130 ev.type = QUIC_CC_EVT_LOSS;
2131 ev.loss.time_sent = newest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002132
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002133 quic_cc_event(&qc->path->cc, &ev);
2134 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002135
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002136 /* If an RTT have been already sampled, <rtt_min> has been set.
2137 * We must check if we are experiencing a persistent congestion.
2138 * If this is the case, the congestion controller must re-enter
2139 * slow start state.
2140 */
2141 if (qc->path->loss.rtt_min && newest_lost != oldest_lost) {
2142 unsigned int period = newest_lost->time_sent - oldest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002143
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002144 if (quic_loss_persistent_congestion(&qc->path->loss, period,
2145 now_ms, qc->max_ack_delay))
2146 qc->path->cc.algo->slow_start(&qc->path->cc);
2147 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002148 }
2149
Amaury Denoyelle3a72ba22022-11-14 11:41:34 +01002150 /* <oldest_lost> cannot be NULL at this stage because we have ensured
2151 * that <pkts> list is not empty. Without this, GCC 12.2.0 reports a
2152 * possible overflow on a 0 byte region with O2 optimization.
2153 */
2154 ALREADY_CHECKED(oldest_lost);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002155 quic_tx_packet_refdec(oldest_lost);
2156 if (newest_lost != oldest_lost)
2157 quic_tx_packet_refdec(newest_lost);
2158
2159 leave:
2160 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002161 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002162}
2163
2164/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
2165 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
2166 * if the largest acked packet was newly acked and if there was at least one newly
2167 * acked ack-eliciting packet.
2168 * Return 1, if succeeded, 0 if not.
2169 */
2170static inline int qc_parse_ack_frm(struct quic_conn *qc,
2171 struct quic_frame *frm,
2172 struct quic_enc_level *qel,
2173 unsigned int *rtt_sample,
2174 const unsigned char **pos, const unsigned char *end)
2175{
2176 struct quic_ack *ack = &frm->ack;
2177 uint64_t smallest, largest;
2178 struct eb_root *pkts;
2179 struct eb64_node *largest_node;
2180 unsigned int time_sent, pkt_flags;
2181 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
2182 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2183 int ret = 0;
2184
2185 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2186
2187 if (ack->largest_ack > qel->pktns->tx.next_pn) {
2188 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
2189 qc, NULL, &ack->largest_ack);
2190 goto err;
2191 }
2192
2193 if (ack->first_ack_range > ack->largest_ack) {
2194 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
2195 qc, NULL, &ack->first_ack_range);
2196 goto err;
2197 }
2198
2199 largest = ack->largest_ack;
2200 smallest = largest - ack->first_ack_range;
2201 pkts = &qel->pktns->tx.pkts;
2202 pkt_flags = 0;
2203 largest_node = NULL;
2204 time_sent = 0;
2205
2206 if ((int64_t)ack->largest_ack > qel->pktns->rx.largest_acked_pn) {
2207 largest_node = eb64_lookup(pkts, largest);
2208 if (!largest_node) {
2209 TRACE_DEVEL("Largest acked packet not found",
2210 QUIC_EV_CONN_PRSAFRM, qc);
2211 }
2212 else {
2213 time_sent = eb64_entry(largest_node,
2214 struct quic_tx_packet, pn_node)->time_sent;
2215 }
2216 }
2217
2218 TRACE_PROTO("rcvd ack range", QUIC_EV_CONN_PRSAFRM,
2219 qc, NULL, &largest, &smallest);
2220 do {
2221 uint64_t gap, ack_range;
2222
2223 qc_ackrng_pkts(qc, pkts, &pkt_flags, &newly_acked_pkts,
2224 largest_node, largest, smallest);
2225 if (!ack->ack_range_num--)
2226 break;
2227
2228 if (!quic_dec_int(&gap, pos, end)) {
2229 TRACE_ERROR("quic_dec_int(gap) failed", QUIC_EV_CONN_PRSAFRM, qc);
2230 goto err;
2231 }
2232
2233 if (smallest < gap + 2) {
2234 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
2235 qc, NULL, &gap, &smallest);
2236 goto err;
2237 }
2238
2239 largest = smallest - gap - 2;
2240 if (!quic_dec_int(&ack_range, pos, end)) {
2241 TRACE_ERROR("quic_dec_int(ack_range) failed", QUIC_EV_CONN_PRSAFRM, qc);
2242 goto err;
2243 }
2244
2245 if (largest < ack_range) {
2246 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
2247 qc, NULL, &largest, &ack_range);
2248 goto err;
2249 }
2250
2251 /* Do not use this node anymore. */
2252 largest_node = NULL;
2253 /* Next range */
2254 smallest = largest - ack_range;
2255
2256 TRACE_PROTO("rcvd next ack range", QUIC_EV_CONN_PRSAFRM,
2257 qc, NULL, &largest, &smallest);
2258 } while (1);
2259
2260 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
2261 *rtt_sample = tick_remain(time_sent, now_ms);
2262 qel->pktns->rx.largest_acked_pn = ack->largest_ack;
2263 }
2264
2265 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
2266 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
2267 qc_packet_loss_lookup(qel->pktns, qc, &lost_pkts);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002268 if (!qc_release_lost_pkts(qc, qel->pktns, &lost_pkts, now_ms))
2269 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002270 }
2271 qc_treat_newly_acked_pkts(qc, &newly_acked_pkts);
2272 if (quic_peer_validated_addr(qc))
2273 qc->path->loss.pto_count = 0;
2274 qc_set_timer(qc);
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01002275 qc_notify_send(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002276 }
2277
2278 ret = 1;
2279 leave:
2280 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2281 return ret;
2282
2283 err:
2284 free_quic_tx_pkts(qc, &newly_acked_pkts);
2285 goto leave;
2286}
2287
2288/* This function gives the detail of the SSL error. It is used only
2289 * if the debug mode and the verbose mode are activated. It dump all
2290 * the SSL error until the stack was empty.
2291 */
2292static forceinline void qc_ssl_dump_errors(struct connection *conn)
2293{
2294 if (unlikely(global.mode & MODE_DEBUG)) {
2295 while (1) {
2296 const char *func = NULL;
2297 unsigned long ret;
2298
2299 ERR_peek_error_func(&func);
2300 ret = ERR_get_error();
2301 if (!ret)
2302 return;
2303
2304 fprintf(stderr, "conn. @%p OpenSSL error[0x%lx] %s: %s\n", conn, ret,
2305 func, ERR_reason_error_string(ret));
2306 }
2307 }
2308}
2309
2310int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx,
2311 const char **str, int *len);
2312
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002313/* Finalize <qc> QUIC connection:
2314 * - initialize the Initial QUIC TLS context for negotiated version,
2315 * - derive the secrets for this context,
2316 * - set them into the TLS stack,
2317 *
2318 * MUST be called after having received the remote transport parameters which
2319 * are parsed when the TLS callback for the ClientHello message is called upon
2320 * SSL_do_handshake() calls, not necessarily at the first time as this TLS
2321 * message may be splitted between packets
2322 * Return 1 if succeeded, 0 if not.
2323 */
2324static int qc_conn_finalize(struct quic_conn *qc, int server)
2325{
2326 int ret = 0;
2327
2328 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
2329
2330 if (qc->flags & QUIC_FL_CONN_FINALIZED)
2331 goto finalized;
2332
2333 if (qc->negotiated_version &&
2334 !qc_new_isecs(qc, &qc->negotiated_ictx, qc->negotiated_version,
2335 qc->odcid.data, qc->odcid.len, server))
2336 goto out;
2337
2338 /* This connection is functional (ready to send/receive) */
2339 qc->flags |= QUIC_FL_CONN_FINALIZED;
2340
2341 finalized:
2342 ret = 1;
2343 out:
2344 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
2345 return ret;
2346}
2347
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002348/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
2349 * from <qel> encryption level with <ctx> as QUIC connection context.
2350 * Remaining parameter are there for debugging purposes.
2351 * Return 1 if succeeded, 0 if not.
2352 */
2353static inline int qc_provide_cdata(struct quic_enc_level *el,
2354 struct ssl_sock_ctx *ctx,
2355 const unsigned char *data, size_t len,
2356 struct quic_rx_packet *pkt,
2357 struct quic_rx_crypto_frm *cf)
2358{
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002359#ifdef DEBUG_STRICT
2360 enum ncb_ret ncb_ret;
2361#endif
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002362 int ssl_err, state;
2363 struct quic_conn *qc;
2364 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002365 struct ncbuf *ncbuf = &el->cstream->rx.ncbuf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002366
2367 ssl_err = SSL_ERROR_NONE;
2368 qc = ctx->qc;
2369
2370 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, qc);
2371
2372 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
2373 TRACE_ERROR("SSL_provide_quic_data() error",
2374 QUIC_EV_CONN_SSLDATA, qc, pkt, cf, ctx->ssl);
2375 goto leave;
2376 }
2377
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002378 TRACE_PROTO("in order CRYPTO data",
2379 QUIC_EV_CONN_SSLDATA, qc, NULL, cf, ctx->ssl);
2380
2381 state = qc->state;
2382 if (state < QUIC_HS_ST_COMPLETE) {
2383 ssl_err = SSL_do_handshake(ctx->ssl);
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002384
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01002385 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
2386 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
2387 goto leave;
2388 }
2389
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002390 /* Finalize the connection as soon as possible if the peer transport parameters
2391 * have been received. This may be useful to send packets even if this
2392 * handshake fails.
2393 */
2394 if ((qc->flags & QUIC_FL_CONN_TX_TP_RECEIVED) && !qc_conn_finalize(qc, 1)) {
2395 TRACE_ERROR("connection finalization failed", QUIC_EV_CONN_IO_CB, qc, &state);
2396 goto leave;
2397 }
2398
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002399 if (ssl_err != 1) {
2400 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2401 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2402 TRACE_PROTO("SSL handshake in progress",
2403 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2404 goto out;
2405 }
2406
2407 /* TODO: Should close the connection asap */
2408 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2409 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2410 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2411 HA_ATOMIC_INC(&qc->prx_counters->hdshk_fail);
2412 }
2413 TRACE_ERROR("SSL handshake error", QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2414 qc_ssl_dump_errors(ctx->conn);
2415 ERR_clear_error();
2416 goto leave;
2417 }
2418
2419 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_IO_CB, qc, &state);
2420
2421 /* Check the alpn could be negotiated */
2422 if (!qc->app_ops) {
2423 TRACE_ERROR("No negotiated ALPN", QUIC_EV_CONN_IO_CB, qc, &state);
2424 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
2425 goto leave;
2426 }
2427
2428 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2429 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_IO_CB, qc, &state);
2430 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2431 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2432 }
2433 /* I/O callback switch */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002434 qc->wait_event.tasklet->process = quic_conn_app_io_cb;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002435 if (qc_is_listener(ctx->qc)) {
2436 qc->state = QUIC_HS_ST_CONFIRMED;
2437 /* The connection is ready to be accepted. */
2438 quic_accept_push_qc(qc);
2439 }
2440 else {
2441 qc->state = QUIC_HS_ST_COMPLETE;
2442 }
2443
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02002444 /* Prepare the next key update */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002445 if (!quic_tls_key_update(qc)) {
2446 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_IO_CB, qc);
2447 goto leave;
2448 }
2449 } else {
2450 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
2451 if (ssl_err != 1) {
2452 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2453 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2454 TRACE_PROTO("SSL post handshake in progress",
2455 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2456 goto out;
2457 }
2458
2459 TRACE_ERROR("SSL post handshake error",
2460 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2461 goto leave;
2462 }
2463
2464 TRACE_STATE("SSL post handshake succeeded", QUIC_EV_CONN_IO_CB, qc, &state);
2465 }
2466
2467 out:
2468 ret = 1;
2469 leave:
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002470 /* The CRYPTO data are consumed even in case of an error to release
2471 * the memory asap.
2472 */
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002473 if (!ncb_is_null(ncbuf)) {
2474#ifdef DEBUG_STRICT
2475 ncb_ret = ncb_advance(ncbuf, len);
2476 /* ncb_advance() must always succeed. This is guaranteed as
2477 * this is only done inside a data block. If false, this will
2478 * lead to handshake failure with quic_enc_level offset shifted
2479 * from buffer data.
2480 */
2481 BUG_ON(ncb_ret != NCB_RET_OK);
2482#else
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002483 ncb_advance(ncbuf, len);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002484#endif
2485 }
2486
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002487 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, qc);
2488 return ret;
2489}
2490
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002491/* Parse a STREAM frame <strm_frm> received in <pkt> packet for <qc>
2492 * connection. <fin> is true if FIN bit is set on frame type.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002493 *
2494 * Return 1 on success. On error, 0 is returned. In this case, the packet
2495 * containing the frame must not be acknowledged.
2496 */
2497static inline int qc_handle_strm_frm(struct quic_rx_packet *pkt,
2498 struct quic_stream *strm_frm,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002499 struct quic_conn *qc, char fin)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002500{
2501 int ret;
2502
2503 /* RFC9000 13.1. Packet Processing
2504 *
2505 * A packet MUST NOT be acknowledged until packet protection has been
2506 * successfully removed and all frames contained in the packet have
2507 * been processed. For STREAM frames, this means the data has been
2508 * enqueued in preparation to be received by the application protocol,
2509 * but it does not require that data be delivered and consumed.
2510 */
2511 TRACE_ENTER(QUIC_EV_CONN_PRSFRM, qc);
2512
2513 ret = qcc_recv(qc->qcc, strm_frm->id, strm_frm->len,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002514 strm_frm->offset.key, fin, (char *)strm_frm->data);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002515
2516 /* frame rejected - packet must not be acknowledeged */
2517 TRACE_LEAVE(QUIC_EV_CONN_PRSFRM, qc);
2518 return !ret;
2519}
2520
2521/* Duplicate all frames from <pkt_frm_list> list into <out_frm_list> list
2522 * for <qc> QUIC connection.
2523 * This is a best effort function which never fails even if no memory could be
2524 * allocated to duplicate these frames.
2525 */
2526static void qc_dup_pkt_frms(struct quic_conn *qc,
2527 struct list *pkt_frm_list, struct list *out_frm_list)
2528{
2529 struct quic_frame *frm, *frmbak;
2530 struct list tmp = LIST_HEAD_INIT(tmp);
2531
2532 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2533
2534 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
2535 struct quic_frame *dup_frm, *origin;
2536
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002537 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
2538 TRACE_DEVEL("already acknowledged frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2539 continue;
2540 }
2541
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002542 switch (frm->type) {
2543 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2544 {
2545 struct quic_stream *strm_frm = &frm->stream;
2546 struct eb64_node *node = NULL;
2547 struct qc_stream_desc *stream_desc;
2548
2549 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
2550 if (!node) {
2551 TRACE_DEVEL("ignored frame for a released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
2552 continue;
2553 }
2554
2555 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
2556 /* Do not resend this frame if in the "already acked range" */
2557 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
2558 TRACE_DEVEL("ignored frame in already acked range",
2559 QUIC_EV_CONN_PRSAFRM, qc, frm);
2560 continue;
2561 }
2562 else if (strm_frm->offset.key < stream_desc->ack_offset) {
Frédéric Lécailleca079792023-03-17 08:56:50 +01002563 uint64_t diff = stream_desc->ack_offset - strm_frm->offset.key;
2564
Frédéric Lécaillec425e032023-03-20 14:32:59 +01002565 qc_stream_frm_mv_fwd(frm, diff);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002566 TRACE_DEVEL("updated partially acked frame",
2567 QUIC_EV_CONN_PRSAFRM, qc, frm);
2568 }
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01002569
2570 strm_frm->dup = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002571 break;
2572 }
2573
2574 default:
2575 break;
2576 }
2577
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002578 /* If <frm> is already a copy of another frame, we must take
2579 * its original frame as source for the copy.
2580 */
2581 origin = frm->origin ? frm->origin : frm;
2582 dup_frm = qc_frm_dup(origin);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002583 if (!dup_frm) {
2584 TRACE_ERROR("could not duplicate frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2585 break;
2586 }
2587
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002588 TRACE_DEVEL("built probing frame", QUIC_EV_CONN_PRSAFRM, qc, origin);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002589 if (origin->pkt) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002590 TRACE_DEVEL("duplicated from packet", QUIC_EV_CONN_PRSAFRM,
2591 qc, NULL, &origin->pkt->pn_node.key);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002592 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002593 else {
2594 /* <origin> is a frame which was sent from a packet detected as lost. */
2595 TRACE_DEVEL("duplicated from lost packet", QUIC_EV_CONN_PRSAFRM, qc);
2596 }
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002597
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002598 LIST_APPEND(&tmp, &dup_frm->list);
2599 }
2600
2601 LIST_SPLICE(out_frm_list, &tmp);
2602
2603 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2604}
2605
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002606/* Boolean function which return 1 if <pkt> TX packet is only made of
2607 * already acknowledged frame.
2608 */
2609static inline int qc_pkt_with_only_acked_frms(struct quic_tx_packet *pkt)
2610{
2611 struct quic_frame *frm;
2612
2613 list_for_each_entry(frm, &pkt->frms, list)
2614 if (!(frm->flags & QUIC_FL_TX_FRAME_ACKED))
2615 return 0;
2616
2617 return 1;
2618}
2619
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002620/* Prepare a fast retransmission from <qel> encryption level */
2621static void qc_prep_fast_retrans(struct quic_conn *qc,
2622 struct quic_enc_level *qel,
2623 struct list *frms1, struct list *frms2)
2624{
2625 struct eb_root *pkts = &qel->pktns->tx.pkts;
2626 struct list *frms = frms1;
2627 struct eb64_node *node;
2628 struct quic_tx_packet *pkt;
2629
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002630 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002631
2632 BUG_ON(frms1 == frms2);
2633
2634 pkt = NULL;
2635 node = eb64_first(pkts);
2636 start:
2637 while (node) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002638 struct quic_tx_packet *p;
2639
2640 p = eb64_entry(node, struct quic_tx_packet, pn_node);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002641 node = eb64_next(node);
2642 /* Skip the empty and coalesced packets */
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002643 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002644 "--> pn=%llu (%d %d %d)", (ull)p->pn_node.key,
2645 LIST_ISEMPTY(&p->frms), !!(p->flags & QUIC_FL_TX_PACKET_COALESCED),
2646 qc_pkt_with_only_acked_frms(p));
2647 if (!LIST_ISEMPTY(&p->frms) && !qc_pkt_with_only_acked_frms(p)) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002648 pkt = p;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002649 break;
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002650 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002651 }
2652
2653 if (!pkt)
2654 goto leave;
2655
2656 /* When building a packet from another one, the field which may increase the
2657 * packet size is the packet number. And the maximum increase is 4 bytes.
2658 */
2659 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2660 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01002661 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002662 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2663 goto leave;
2664 }
2665
2666 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_SPPKTS, qc, pkt);
2667 qc_dup_pkt_frms(qc, &pkt->frms, frms);
2668 if (frms == frms1 && frms2) {
2669 frms = frms2;
2670 goto start;
2671 }
2672 leave:
2673 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
2674}
2675
2676/* Prepare a fast retransmission during a handshake after a client
2677 * has resent Initial packets. According to the RFC a server may retransmit
2678 * Initial packets send them coalescing with others (Handshake here).
2679 * (Listener only function).
2680 */
2681static void qc_prep_hdshk_fast_retrans(struct quic_conn *qc,
2682 struct list *ifrms, struct list *hfrms)
2683{
2684 struct list itmp = LIST_HEAD_INIT(itmp);
2685 struct list htmp = LIST_HEAD_INIT(htmp);
2686
2687 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2688 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2689 struct quic_enc_level *qel = iqel;
2690 struct eb_root *pkts;
2691 struct eb64_node *node;
2692 struct quic_tx_packet *pkt;
2693 struct list *tmp = &itmp;
2694
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002695 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002696 start:
2697 pkt = NULL;
2698 pkts = &qel->pktns->tx.pkts;
2699 node = eb64_first(pkts);
2700 /* Skip the empty packet (they have already been retransmitted) */
2701 while (node) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002702 struct quic_tx_packet *p;
2703
2704 p = eb64_entry(node, struct quic_tx_packet, pn_node);
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002705 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002706 "--> pn=%llu (%d %d)", (ull)p->pn_node.key,
2707 LIST_ISEMPTY(&p->frms), !!(p->flags & QUIC_FL_TX_PACKET_COALESCED));
Frédéric Lécaillee6359b62023-03-02 14:49:22 +01002708 if (!LIST_ISEMPTY(&p->frms) && !(p->flags & QUIC_FL_TX_PACKET_COALESCED) &&
2709 !qc_pkt_with_only_acked_frms(p)) {
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002710 pkt = p;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002711 break;
Frédéric Lécaille21564be2023-03-02 11:53:43 +01002712 }
2713
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002714 node = eb64_next(node);
2715 }
2716
2717 if (!pkt)
2718 goto end;
2719
2720 /* When building a packet from another one, the field which may increase the
2721 * packet size is the packet number. And the maximum increase is 4 bytes.
2722 */
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002723 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
2724 size_t dglen = pkt->len + 4;
2725
2726 dglen += pkt->next ? pkt->next->len + 4 : 0;
2727 if (dglen > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01002728 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002729 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2730 if (pkt->next)
2731 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt->next);
2732 goto end;
2733 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002734 }
2735
2736 qel->pktns->tx.pto_probe += 1;
2737
2738 /* No risk to loop here, #packet per datagram is bounded */
2739 requeue:
2740 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
2741 qc_dup_pkt_frms(qc, &pkt->frms, tmp);
2742 if (qel == iqel) {
2743 if (pkt->next && pkt->next->type == QUIC_PACKET_TYPE_HANDSHAKE) {
2744 pkt = pkt->next;
2745 tmp = &htmp;
2746 hqel->pktns->tx.pto_probe += 1;
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002747 TRACE_DEVEL("looping for next packet", QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002748 goto requeue;
2749 }
2750 }
2751
2752 end:
2753 LIST_SPLICE(ifrms, &itmp);
2754 LIST_SPLICE(hfrms, &htmp);
2755
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002756 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002757}
2758
2759static void qc_cc_err_count_inc(struct quic_conn *qc, struct quic_frame *frm)
2760{
2761 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
2762
2763 if (frm->type == QUIC_FT_CONNECTION_CLOSE)
2764 quic_stats_transp_err_count_inc(qc->prx_counters, frm->connection_close.error_code);
2765 else if (frm->type == QUIC_FT_CONNECTION_CLOSE_APP) {
2766 if (qc->mux_state != QC_MUX_READY || !qc->qcc->app_ops->inc_err_cnt)
2767 goto out;
2768
2769 qc->qcc->app_ops->inc_err_cnt(qc->qcc->ctx, frm->connection_close_app.error_code);
2770 }
2771
2772 out:
2773 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
2774}
2775
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002776/* Cancel a request on connection <qc> for stream id <id>. This is useful when
2777 * the client opens a new stream but the MUX has already been released. A
Amaury Denoyelle75463012023-02-20 10:31:27 +01002778 * STOP_SENDING + RESET_STREAM frames are prepared for emission.
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002779 *
2780 * TODO this function is closely related to H3. Its place should be in H3 layer
2781 * instead of quic-conn but this requires an architecture adjustment.
2782 *
2783 * Returns 1 on sucess else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002784 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002785static int qc_h3_request_reject(struct quic_conn *qc, uint64_t id)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002786{
2787 int ret = 0;
Amaury Denoyelle75463012023-02-20 10:31:27 +01002788 struct quic_frame *ss, *rs;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002789 struct quic_enc_level *qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002790 const uint64_t app_error_code = H3_REQUEST_REJECTED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002791
2792 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2793
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002794 /* Do not emit rejection for unknown unidirectional stream as it is
2795 * forbidden to close some of them (H3 control stream and QPACK
2796 * encoder/decoder streams).
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002797 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002798 if (quic_stream_is_uni(id)) {
2799 ret = 1;
2800 goto out;
2801 }
2802
Amaury Denoyelle75463012023-02-20 10:31:27 +01002803 ss = qc_frm_alloc(QUIC_FT_STOP_SENDING);
2804 if (!ss) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002805 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2806 goto out;
2807 }
2808
Amaury Denoyelle75463012023-02-20 10:31:27 +01002809 ss->stop_sending.id = id;
2810 ss->stop_sending.app_error_code = app_error_code;
2811
2812 rs = qc_frm_alloc(QUIC_FT_RESET_STREAM);
2813 if (!rs) {
2814 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2815 qc_frm_free(&ss);
2816 goto out;
2817 }
2818
2819 rs->reset_stream.id = id;
2820 rs->reset_stream.app_error_code = app_error_code;
2821 rs->reset_stream.final_size = 0;
2822
2823 LIST_APPEND(&qel->pktns->tx.frms, &ss->list);
2824 LIST_APPEND(&qel->pktns->tx.frms, &rs->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002825 ret = 1;
2826 out:
2827 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2828 return ret;
2829}
2830
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002831/* Release the underlying memory use by <ncbuf> non-contiguous buffer */
2832static void quic_free_ncbuf(struct ncbuf *ncbuf)
2833{
2834 struct buffer buf;
2835
2836 if (ncb_is_null(ncbuf))
2837 return;
2838
2839 buf = b_make(ncbuf->area, ncbuf->size, 0, 0);
2840 b_free(&buf);
2841 offer_buffers(NULL, 1);
2842
2843 *ncbuf = NCBUF_NULL;
2844}
2845
2846/* Allocate the underlying required memory for <ncbuf> non-contiguous buffer */
2847static struct ncbuf *quic_get_ncbuf(struct ncbuf *ncbuf)
2848{
2849 struct buffer buf = BUF_NULL;
2850
2851 if (!ncb_is_null(ncbuf))
2852 return ncbuf;
2853
2854 b_alloc(&buf);
2855 BUG_ON(b_is_null(&buf));
2856
2857 *ncbuf = ncb_make(buf.area, buf.size, 0);
2858 ncb_init(ncbuf, 0);
2859
2860 return ncbuf;
2861}
2862
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002863/* Parse <frm> CRYPTO frame coming with <pkt> packet at <qel> <qc> connectionn.
2864 * Returns 1 if succeeded, 0 if not. Also set <*fast_retrans> to 1 if the
2865 * speed up handshake completion may be run after having received duplicated
2866 * CRYPTO data.
2867 */
2868static int qc_handle_crypto_frm(struct quic_conn *qc,
2869 struct quic_crypto *frm, struct quic_rx_packet *pkt,
2870 struct quic_enc_level *qel, int *fast_retrans)
2871{
2872 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002873 enum ncb_ret ncb_ret;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002874 /* XXX TO DO: <cfdebug> is used only for the traces. */
2875 struct quic_rx_crypto_frm cfdebug = {
2876 .offset_node.key = frm->offset,
2877 .len = frm->len,
2878 };
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002879 struct quic_cstream *cstream = qel->cstream;
2880 struct ncbuf *ncbuf = &qel->cstream->rx.ncbuf;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002881
2882 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2883 if (unlikely(qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD)) {
2884 TRACE_PROTO("CRYPTO data discarded",
2885 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2886 goto done;
2887 }
2888
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002889 if (unlikely(frm->offset < cstream->rx.offset)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002890 size_t diff;
2891
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002892 if (frm->offset + frm->len <= cstream->rx.offset) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002893 /* Nothing to do */
2894 TRACE_PROTO("Already received CRYPTO data",
2895 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2896 if (qc_is_listener(qc) && qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] &&
2897 !(qc->flags & QUIC_FL_CONN_HANDSHAKE_SPEED_UP))
2898 *fast_retrans = 1;
2899 goto done;
2900 }
2901
2902 TRACE_PROTO("Partially already received CRYPTO data",
2903 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2904
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002905 diff = cstream->rx.offset - frm->offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002906 frm->len -= diff;
2907 frm->data += diff;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002908 frm->offset = cstream->rx.offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002909 }
2910
Amaury Denoyelleff95f2d2022-11-18 14:50:06 +01002911 if (frm->offset == cstream->rx.offset && ncb_is_empty(ncbuf)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002912 if (!qc_provide_cdata(qel, qc->xprt_ctx, frm->data, frm->len,
2913 pkt, &cfdebug)) {
2914 // trace already emitted by function above
2915 goto leave;
2916 }
2917
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002918 cstream->rx.offset += frm->len;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002919 TRACE_DEVEL("increment crypto level offset", QUIC_EV_CONN_PHPKTS, qc, qel);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002920 goto done;
2921 }
2922
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002923 if (!quic_get_ncbuf(ncbuf) ||
2924 ncb_is_null(ncbuf)) {
2925 TRACE_ERROR("CRYPTO ncbuf allocation failed", QUIC_EV_CONN_PRSHPKT, qc);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002926 goto leave;
2927 }
2928
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002929 /* frm->offset > cstream-trx.offset */
2930 ncb_ret = ncb_add(ncbuf, frm->offset - cstream->rx.offset,
2931 (const char *)frm->data, frm->len, NCB_ADD_COMPARE);
2932 if (ncb_ret != NCB_RET_OK) {
2933 if (ncb_ret == NCB_RET_DATA_REJ) {
2934 TRACE_ERROR("overlapping data rejected", QUIC_EV_CONN_PRSHPKT, qc);
2935 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
2936 }
2937 else if (ncb_ret == NCB_RET_GAP_SIZE) {
2938 TRACE_ERROR("cannot bufferize frame due to gap size limit",
2939 QUIC_EV_CONN_PRSHPKT, qc);
2940 }
2941 goto leave;
2942 }
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002943
2944 done:
2945 ret = 1;
2946 leave:
2947 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2948 return ret;
2949}
2950
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002951/* Allocate a new connection ID for <qc> connection and build a NEW_CONNECTION_ID
2952 * frame to be sent.
2953 * Return 1 if succeeded, 0 if not.
2954 */
2955static int qc_build_new_connection_id_frm(struct quic_conn *qc,
2956 struct quic_connection_id *cid)
2957{
2958 int ret = 0;
2959 struct quic_frame *frm;
2960 struct quic_enc_level *qel;
2961
2962 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2963
2964 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
2965 frm = qc_frm_alloc(QUIC_FT_NEW_CONNECTION_ID);
2966 if (!frm) {
2967 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
2968 goto leave;
2969 }
2970
2971 quic_connection_id_to_frm_cpy(frm, cid);
2972 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
2973 ret = 1;
2974 leave:
2975 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2976 return ret;
2977}
2978
2979
2980/* Handle RETIRE_CONNECTION_ID frame from <frm> frame.
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002981 * Return 1 if succeeded, 0 if not. If succeeded, also set <cid_to_retire>
2982 * to the CID to be retired if not already retired.
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002983 */
2984static int qc_handle_retire_connection_id_frm(struct quic_conn *qc,
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002985 struct quic_frame *frm,
2986 struct quic_cid *dcid,
2987 struct quic_connection_id **cid_to_retire)
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002988{
2989 int ret = 0;
2990 struct quic_retire_connection_id *rcid = &frm->retire_connection_id;
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002991 struct eb64_node *node;
2992 struct quic_connection_id *cid;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01002993
2994 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2995
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01002996 /* RFC 9000 19.16. RETIRE_CONNECTION_ID Frames:
2997 * Receipt of a RETIRE_CONNECTION_ID frame containing a sequence number greater
2998 * than any previously sent to the peer MUST be treated as a connection error
2999 * of type PROTOCOL_VIOLATION.
3000 */
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003001 if (rcid->seq_num >= qc->next_cid_seq_num) {
3002 TRACE_PROTO("CID seq. number too big", QUIC_EV_CONN_PSTRM, qc, frm);
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003003 goto protocol_violation;
3004 }
3005
3006 /* RFC 9000 19.16. RETIRE_CONNECTION_ID Frames:
3007 * The sequence number specified in a RETIRE_CONNECTION_ID frame MUST NOT refer to
3008 * the Destination Connection ID field of the packet in which the frame is contained.
3009 * The peer MAY treat this as a connection error of type PROTOCOL_VIOLATION.
3010 */
3011 node = eb64_lookup(&qc->cids, rcid->seq_num);
3012 if (!node) {
3013 TRACE_PROTO("CID already retired", QUIC_EV_CONN_PSTRM, qc, frm);
3014 goto out;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003015 }
3016
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003017 cid = eb64_entry(node, struct quic_connection_id, seq_num);
3018 /* Note that the length of <dcid> has already been checked. It must match the
3019 * length of the CIDs which have been provided to the peer.
3020 */
3021 if (!memcmp(dcid->data, cid->cid.data, QUIC_HAP_CID_LEN)) {
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003022 TRACE_PROTO("cannot retire the current CID", QUIC_EV_CONN_PSTRM, qc, frm);
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003023 goto protocol_violation;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003024 }
3025
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003026 *cid_to_retire = cid;
3027 out:
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003028 ret = 1;
3029 leave:
3030 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
3031 return ret;
Frédéric Lécaillecc101cd2023-03-08 11:01:58 +01003032 protocol_violation:
3033 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
3034 goto leave;
Frédéric Lécaille8ac8a872023-03-06 18:16:34 +01003035}
3036
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01003037/* Remove a <qc> quic-conn from its ha_thread_ctx list. If <closing> is true,
3038 * it will immediately be reinserted in the ha_thread_ctx quic_conns_clo list.
3039 */
3040static void qc_detach_th_ctx_list(struct quic_conn *qc, int closing)
3041{
3042 struct bref *bref, *back;
3043
3044 /* Detach CLI context watchers currently dumping this connection.
3045 * Reattach them to the next quic_conn instance.
3046 */
3047 list_for_each_entry_safe(bref, back, &qc->back_refs, users) {
3048 /* Remove watcher from this quic_conn instance. */
3049 LIST_DEL_INIT(&bref->users);
3050
3051 /* Attach it to next instance unless it was the last list element. */
3052 if (qc->el_th_ctx.n != &th_ctx->quic_conns &&
3053 qc->el_th_ctx.n != &th_ctx->quic_conns_clo) {
3054 struct quic_conn *next = LIST_NEXT(&qc->el_th_ctx,
3055 struct quic_conn *,
3056 el_th_ctx);
3057 LIST_APPEND(&next->back_refs, &bref->users);
3058 }
3059 bref->ref = qc->el_th_ctx.n;
3060 __ha_barrier_store();
3061 }
3062
3063 /* Remove quic_conn from global ha_thread_ctx list. */
3064 LIST_DEL_INIT(&qc->el_th_ctx);
3065
3066 if (closing)
3067 LIST_APPEND(&th_ctx->quic_conns_clo, &qc->el_th_ctx);
3068}
3069
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003070/* Parse all the frames of <pkt> QUIC packet for QUIC connection <qc> and <qel>
3071 * as encryption level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003072 * Returns 1 if succeeded, 0 if failed.
3073 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003074static int qc_parse_pkt_frms(struct quic_conn *qc, struct quic_rx_packet *pkt,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003075 struct quic_enc_level *qel)
3076{
3077 struct quic_frame frm;
3078 const unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003079 int fast_retrans = 0, ret = 0;
3080
3081 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
3082 /* Skip the AAD */
3083 pos = pkt->data + pkt->aad_len;
3084 end = pkt->data + pkt->len;
3085
3086 while (pos < end) {
3087 if (!qc_parse_frm(&frm, pkt, &pos, end, qc)) {
3088 // trace already emitted by function above
3089 goto leave;
3090 }
3091
3092 TRACE_PROTO("RX frame", QUIC_EV_CONN_PSTRM, qc, &frm);
3093 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);
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01003258 qc_idle_timer_do_rearm(qc);
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{
3373 unsigned int must_ack = force_ack ||
3374 (LIST_ISEMPTY(frms) && (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED));
3375
3376 /* Do not build any more packet if the TX secrets are not available or
3377 * if there is nothing to send, i.e. if no CONNECTION_CLOSE or ACK are required
3378 * and if there is no more packets to send upon PTO expiration
3379 * and if there is no more ack-eliciting frames to send or in flight
3380 * congestion control limit is reached for prepared data
3381 */
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02003382 if (!quic_tls_has_tx_sec(qel) ||
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003383 (!cc && !probe && !must_ack &&
3384 (LIST_ISEMPTY(frms) || qc->path->prep_in_flight >= qc->path->cwnd))) {
3385 return 0;
3386 }
3387
3388 return 1;
3389}
3390
3391/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3392 * <frms>. Each packet is stored in a distinct datagram written to <buf>.
3393 *
3394 * Each datagram is prepended by a two fields header : the datagram length and
3395 * the address of the packet contained in the datagram.
3396 *
3397 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3398 * -1 if something wrong happened.
3399 */
3400static int qc_prep_app_pkts(struct quic_conn *qc, struct buffer *buf,
3401 struct list *frms)
3402{
3403 int ret = -1;
3404 struct quic_enc_level *qel;
3405 unsigned char *end, *pos;
3406 struct quic_tx_packet *pkt;
3407 size_t total;
3408 /* Each datagram is prepended with its length followed by the address
3409 * of the first packet in the datagram.
3410 */
3411 const size_t dg_headlen = sizeof(uint16_t) + sizeof(pkt);
3412
3413 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3414
3415 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3416 total = 0;
3417 pos = (unsigned char *)b_tail(buf);
3418 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen) {
3419 int err, probe, cc;
3420
3421 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3422 probe = 0;
3423 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3424 /* We do not probe if an immediate close was asked */
3425 if (!cc)
3426 probe = qel->pktns->tx.pto_probe;
3427
3428 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, 0))
3429 break;
3430
3431 /* Leave room for the datagram header */
3432 pos += dg_headlen;
3433 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3434 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3435 }
3436 else {
3437 end = pos + qc->path->mtu;
3438 }
3439
3440 pkt = qc_build_pkt(&pos, end, qel, &qel->tls_ctx, frms, qc, NULL, 0,
3441 QUIC_PACKET_TYPE_SHORT, 0, 0, probe, cc, &err);
3442 switch (err) {
3443 case -2:
3444 // trace already emitted by function above
3445 goto leave;
3446 case -1:
3447 /* As we provide qc_build_pkt() with an enough big buffer to fulfill an
3448 * MTU, we are here because of the congestion control window. There is
3449 * no need to try to reuse this buffer.
3450 */
3451 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3452 goto out;
3453 default:
3454 break;
3455 }
3456
3457 /* This is to please to GCC. We cannot have (err >= 0 && !pkt) */
3458 BUG_ON(!pkt);
3459
3460 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3461 pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3462
3463 total += pkt->len;
3464
3465 /* Write datagram header. */
3466 qc_txb_store(buf, pkt->len, pkt);
3467 }
3468
3469 out:
3470 ret = total;
3471 leave:
3472 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3473 return ret;
3474}
3475
3476/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3477 * <frms>. Several packets can be regrouped in a single datagram. The result is
3478 * written into <buf>.
3479 *
3480 * Each datagram is prepended by a two fields header : the datagram length and
3481 * the address of first packet in the datagram.
3482 *
3483 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3484 * -1 if something wrong happened.
3485 */
3486static int qc_prep_pkts(struct quic_conn *qc, struct buffer *buf,
3487 enum quic_tls_enc_level tel, struct list *tel_frms,
3488 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
3489{
3490 struct quic_enc_level *qel;
3491 unsigned char *end, *pos;
3492 struct quic_tx_packet *first_pkt, *cur_pkt, *prv_pkt;
3493 /* length of datagrams */
3494 uint16_t dglen;
3495 size_t total;
3496 int ret = -1, padding;
3497 /* Each datagram is prepended with its length followed by the address
3498 * of the first packet in the datagram.
3499 */
3500 const size_t dg_headlen = sizeof(uint16_t) + sizeof(first_pkt);
3501 struct list *frms;
3502
3503 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3504
3505 /* Currently qc_prep_pkts() does not handle buffer wrapping so the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003506 * caller must ensure that buf is reset.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003507 */
3508 BUG_ON_HOT(buf->head || buf->data);
3509
3510 total = 0;
3511 qel = &qc->els[tel];
3512 frms = tel_frms;
3513 dglen = 0;
3514 padding = 0;
3515 pos = (unsigned char *)b_head(buf);
3516 first_pkt = prv_pkt = NULL;
3517 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen || prv_pkt) {
3518 int err, probe, cc;
3519 enum quic_pkt_type pkt_type;
3520 struct quic_tls_ctx *tls_ctx;
3521 const struct quic_version *ver;
3522 int force_ack = (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3523 (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
3524 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
3525
3526 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3527 probe = 0;
3528 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3529 /* We do not probe if an immediate close was asked */
3530 if (!cc)
3531 probe = qel->pktns->tx.pto_probe;
3532
3533 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, force_ack)) {
3534 if (prv_pkt)
3535 qc_txb_store(buf, dglen, first_pkt);
3536 /* Let's select the next encryption level */
3537 if (tel != next_tel && next_tel != QUIC_TLS_ENC_LEVEL_NONE) {
3538 tel = next_tel;
3539 frms = next_tel_frms;
3540 qel = &qc->els[tel];
3541 /* Build a new datagram */
3542 prv_pkt = NULL;
3543 TRACE_DEVEL("next encryption level selected", QUIC_EV_CONN_PHPKTS, qc);
3544 continue;
3545 }
3546 break;
3547 }
3548
3549 pkt_type = quic_tls_level_pkt_type(tel);
3550 if (!prv_pkt) {
3551 /* Leave room for the datagram header */
3552 pos += dg_headlen;
3553 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3554 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3555 }
3556 else {
3557 end = pos + qc->path->mtu;
3558 }
3559 }
3560
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003561 /* RFC 9000 14.1 Initial datagram size
3562 * a server MUST expand the payload of all UDP datagrams carrying ack-eliciting
3563 * Initial packets to at least the smallest allowed maximum datagram size of
3564 * 1200 bytes.
3565 *
3566 * Ensure that no ack-eliciting packets are sent into too small datagrams
3567 */
3568 if (pkt_type == QUIC_PACKET_TYPE_INITIAL && !LIST_ISEMPTY(tel_frms)) {
3569 if (end - pos < QUIC_INITIAL_PACKET_MINLEN) {
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01003570 TRACE_PROTO("No more enough room to build an Initial packet",
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003571 QUIC_EV_CONN_PHPKTS, qc);
3572 goto out;
3573 }
3574
3575 /* Pad this Initial packet if there is no ack-eliciting frames to send from
3576 * the next packet number space.
3577 */
Frédéric Lécailleec937212023-03-03 17:34:41 +01003578 if (!next_tel_frms || LIST_ISEMPTY(next_tel_frms))
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003579 padding = 1;
3580 }
3581
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003582 if (qc->negotiated_version) {
3583 ver = qc->negotiated_version;
3584 if (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL])
3585 tls_ctx = &qc->negotiated_ictx;
3586 else
3587 tls_ctx = &qel->tls_ctx;
3588 }
3589 else {
3590 ver = qc->original_version;
3591 tls_ctx = &qel->tls_ctx;
3592 }
3593
3594 cur_pkt = qc_build_pkt(&pos, end, qel, tls_ctx, frms,
3595 qc, ver, dglen, pkt_type,
3596 force_ack, padding, probe, cc, &err);
3597 switch (err) {
3598 case -2:
3599 // trace already emitted by function above
3600 goto leave;
3601 case -1:
3602 /* If there was already a correct packet present, set the
3603 * current datagram as prepared into <cbuf>.
3604 */
3605 if (prv_pkt)
3606 qc_txb_store(buf, dglen, first_pkt);
3607 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3608 goto out;
3609 default:
3610 break;
3611 }
3612
3613 /* This is to please to GCC. We cannot have (err >= 0 && !cur_pkt) */
3614 BUG_ON(!cur_pkt);
3615
3616 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3617 cur_pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3618
3619 total += cur_pkt->len;
3620 /* keep trace of the first packet in the datagram */
3621 if (!first_pkt)
3622 first_pkt = cur_pkt;
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01003623 /* Attach the current one to the previous one and vice versa */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003624 if (prv_pkt) {
3625 prv_pkt->next = cur_pkt;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01003626 cur_pkt->prev = prv_pkt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003627 cur_pkt->flags |= QUIC_FL_TX_PACKET_COALESCED;
3628 }
3629 /* Let's say we have to build a new dgram */
3630 prv_pkt = NULL;
3631 dglen += cur_pkt->len;
3632 /* Client: discard the Initial encryption keys as soon as
3633 * a handshake packet could be built.
3634 */
3635 if (qc->state == QUIC_HS_ST_CLIENT_INITIAL &&
3636 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
3637 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3638 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PHPKTS, qc);
3639 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
3640 qc_set_timer(qc);
3641 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3642 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3643 qc->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
3644 }
3645 /* If the data for the current encryption level have all been sent,
3646 * select the next level.
3647 */
3648 if ((tel == QUIC_TLS_ENC_LEVEL_INITIAL || tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE) &&
3649 next_tel != QUIC_TLS_ENC_LEVEL_NONE && (LIST_ISEMPTY(frms) && !qel->pktns->tx.pto_probe)) {
3650 /* If QUIC_TLS_ENC_LEVEL_HANDSHAKE was already reached let's try QUIC_TLS_ENC_LEVEL_APP */
3651 if (tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE && next_tel == tel)
3652 next_tel = QUIC_TLS_ENC_LEVEL_APP;
3653 tel = next_tel;
3654 if (tel == QUIC_TLS_ENC_LEVEL_APP)
3655 frms = &qc->els[tel].pktns->tx.frms;
3656 else
3657 frms = next_tel_frms;
3658 qel = &qc->els[tel];
3659 if (!LIST_ISEMPTY(frms)) {
3660 /* If there is data for the next level, do not
3661 * consume a datagram.
3662 */
3663 prv_pkt = cur_pkt;
3664 }
3665 }
3666
3667 /* If we have to build a new datagram, set the current datagram as
3668 * prepared into <cbuf>.
3669 */
3670 if (!prv_pkt) {
3671 qc_txb_store(buf, dglen, first_pkt);
3672 first_pkt = NULL;
3673 dglen = 0;
3674 padding = 0;
3675 }
3676 else if (prv_pkt->type == QUIC_TLS_ENC_LEVEL_INITIAL &&
3677 (!qc_is_listener(qc) ||
3678 prv_pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
3679 padding = 1;
3680 }
3681 }
3682
3683 out:
3684 ret = total;
3685 leave:
3686 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3687 return ret;
3688}
3689
3690/* Send datagrams stored in <buf>.
3691 *
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003692 * This function returns 1 for success. On error, there is several behavior
3693 * depending on underlying sendto() error :
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003694 * - for an unrecoverable error, 0 is returned and connection is killed.
3695 * - a transient error is handled differently if connection has its owned
3696 * socket. If this is the case, 0 is returned and socket is subscribed on the
3697 * poller. The other case is assimilated to a success case with 1 returned.
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003698 * Remaining data are purged from the buffer and will eventually be detected
3699 * as lost which gives the opportunity to retry sending.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003700 */
3701int qc_send_ppkts(struct buffer *buf, struct ssl_sock_ctx *ctx)
3702{
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003703 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003704 struct quic_conn *qc;
3705 char skip_sendto = 0;
3706
3707 qc = ctx->qc;
3708 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
3709 while (b_contig_data(buf, 0)) {
3710 unsigned char *pos;
3711 struct buffer tmpbuf = { };
3712 struct quic_tx_packet *first_pkt, *pkt, *next_pkt;
3713 uint16_t dglen;
3714 size_t headlen = sizeof dglen + sizeof first_pkt;
3715 unsigned int time_sent;
3716
3717 pos = (unsigned char *)b_head(buf);
3718 dglen = read_u16(pos);
3719 BUG_ON_HOT(!dglen); /* this should not happen */
3720
3721 pos += sizeof dglen;
3722 first_pkt = read_ptr(pos);
3723 pos += sizeof first_pkt;
3724 tmpbuf.area = (char *)pos;
3725 tmpbuf.size = tmpbuf.data = dglen;
3726
3727 TRACE_DATA("send dgram", QUIC_EV_CONN_SPPKTS, qc);
3728 /* If sendto is on error just skip the call to it for the rest
3729 * of the loop but continue to purge the buffer. Data will be
3730 * transmitted when QUIC packets are detected as lost on our
3731 * side.
3732 *
3733 * TODO use fd-monitoring to detect when send operation can be
3734 * retry. This should improve the bandwidth without relying on
3735 * retransmission timer. However, it requires a major rework on
3736 * quic-conn fd management.
3737 */
3738 if (!skip_sendto) {
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003739 int ret = qc_snd_buf(qc, &tmpbuf, tmpbuf.data, 0);
3740 if (ret < 0) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003741 TRACE_ERROR("sendto fatal error", QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003742 qc_kill_conn(qc);
3743 b_del(buf, buf->data);
3744 goto leave;
3745 }
3746 else if (!ret) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003747 /* Connection owned socket : poller will wake us up when transient error is cleared. */
3748 if (qc_test_fd(qc)) {
3749 TRACE_ERROR("sendto error, subscribe to poller", QUIC_EV_CONN_SPPKTS, qc);
3750 goto leave;
3751 }
3752
3753 /* No connection owned-socket : rely on retransmission to retry sending. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003754 skip_sendto = 1;
3755 TRACE_ERROR("sendto error, simulate sending for the rest of data", QUIC_EV_CONN_SPPKTS, qc);
3756 }
3757 }
3758
3759 b_del(buf, dglen + headlen);
3760 qc->tx.bytes += tmpbuf.data;
3761 time_sent = now_ms;
3762
3763 for (pkt = first_pkt; pkt; pkt = next_pkt) {
Frédéric Lécailleceb88b82023-02-20 14:43:55 +01003764 /* RFC 9000 14.1 Initial datagram size
3765 * a server MUST expand the payload of all UDP datagrams carrying ack-eliciting
3766 * Initial packets to at least the smallest allowed maximum datagram size of
3767 * 1200 bytes.
3768 */
3769 BUG_ON_HOT(pkt->type == QUIC_PACKET_TYPE_INITIAL &&
3770 (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) &&
3771 dglen < QUIC_INITIAL_PACKET_MINLEN);
3772
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003773 pkt->time_sent = time_sent;
3774 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
3775 pkt->pktns->tx.time_of_last_eliciting = time_sent;
3776 qc->path->ifae_pkts++;
3777 if (qc->flags & QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ)
3778 qc_idle_timer_rearm(qc, 0);
3779 }
3780 if (!(qc->flags & QUIC_FL_CONN_CLOSING) &&
3781 (pkt->flags & QUIC_FL_TX_PACKET_CC)) {
3782 qc->flags |= QUIC_FL_CONN_CLOSING;
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01003783 qc_detach_th_ctx_list(qc, 1);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003784 qc_notify_close(qc);
3785
3786 /* RFC 9000 10.2. Immediate Close:
3787 * The closing and draining connection states exist to ensure
3788 * that connections close cleanly and that delayed or reordered
3789 * packets are properly discarded. These states SHOULD persist
3790 * for at least three times the current PTO interval...
3791 *
3792 * Rearm the idle timeout only one time when entering closing
3793 * state.
3794 */
3795 qc_idle_timer_do_rearm(qc);
3796 if (qc->timer_task) {
3797 task_destroy(qc->timer_task);
3798 qc->timer_task = NULL;
3799 }
3800 }
3801 qc->path->in_flight += pkt->in_flight_len;
3802 pkt->pktns->tx.in_flight += pkt->in_flight_len;
3803 if (pkt->in_flight_len)
3804 qc_set_timer(qc);
3805 TRACE_DATA("sent pkt", QUIC_EV_CONN_SPPKTS, qc, pkt);
3806 next_pkt = pkt->next;
3807 quic_tx_packet_refinc(pkt);
3808 eb64_insert(&pkt->pktns->tx.pkts, &pkt->pn_node);
3809 }
3810 }
3811
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003812 ret = 1;
3813leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003814 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
3815
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003816 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003817}
3818
3819/* Copy into <buf> buffer a stateless reset token depending on the
3820 * <salt> salt input. This is the cluster secret which will be derived
3821 * as HKDF input secret to generate this token.
3822 * Return 1 if succeeded, 0 if not.
3823 */
3824static int quic_stateless_reset_token_cpy(struct quic_conn *qc,
3825 unsigned char *buf, size_t len,
3826 const unsigned char *salt, size_t saltlen)
3827{
3828 /* Input secret */
3829 const unsigned char *key = (const unsigned char *)global.cluster_secret;
3830 size_t keylen = strlen(global.cluster_secret);
3831 /* Info */
3832 const unsigned char label[] = "stateless token";
3833 size_t labellen = sizeof label - 1;
3834 int ret;
3835
3836 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3837
3838 ret = quic_hkdf_extract_and_expand(EVP_sha256(), buf, len,
3839 key, keylen, salt, saltlen, label, labellen);
3840 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3841 return ret;
3842}
3843
3844/* Initialize the stateless reset token attached to <cid> connection ID.
3845 * Returns 1 if succeeded, 0 if not.
3846 */
3847static int quic_stateless_reset_token_init(struct quic_conn *qc,
3848 struct quic_connection_id *quic_cid)
3849{
3850 int ret;
3851
3852 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3853
3854 if (global.cluster_secret) {
3855 /* Output secret */
3856 unsigned char *token = quic_cid->stateless_reset_token;
3857 size_t tokenlen = sizeof quic_cid->stateless_reset_token;
3858 /* Salt */
3859 const unsigned char *cid = quic_cid->cid.data;
3860 size_t cidlen = quic_cid->cid.len;
3861
3862 ret = quic_stateless_reset_token_cpy(qc, token, tokenlen, cid, cidlen);
3863 }
3864 else {
3865 /* TODO: RAND_bytes() should be replaced */
3866 ret = RAND_bytes(quic_cid->stateless_reset_token,
3867 sizeof quic_cid->stateless_reset_token) == 1;
3868 }
3869
3870 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3871 return ret;
3872}
3873
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003874/* Allocate a new CID and attach it to <root> ebtree.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003875 *
3876 * The CID is randomly generated in part with the result altered to be
3877 * associated with the current thread ID. This means this function must only
3878 * be called by the quic_conn thread.
3879 *
3880 * Returns the new CID if succeeded, NULL if not.
3881 */
3882static struct quic_connection_id *new_quic_cid(struct eb_root *root,
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003883 struct quic_conn *qc)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003884{
3885 struct quic_connection_id *cid;
3886
3887 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3888
3889 cid = pool_alloc(pool_head_quic_connection_id);
3890 if (!cid) {
3891 TRACE_ERROR("cid allocation failed", QUIC_EV_CONN_TXPKT, qc);
3892 goto err;
3893 }
3894
3895 cid->cid.len = QUIC_HAP_CID_LEN;
3896 /* TODO: RAND_bytes() should be replaced */
3897 if (RAND_bytes(cid->cid.data, cid->cid.len) != 1) {
3898 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT, qc);
3899 goto err;
3900 }
3901
3902 quic_pin_cid_to_tid(cid->cid.data, tid);
3903 if (quic_stateless_reset_token_init(qc, cid) != 1) {
3904 TRACE_ERROR("quic_stateless_reset_token_init() failed", QUIC_EV_CONN_TXPKT, qc);
3905 goto err;
3906 }
3907
3908 cid->qc = qc;
3909
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003910 cid->seq_num.key = qc->next_cid_seq_num++;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003911 cid->retire_prior_to = 0;
3912 /* insert the allocated CID in the quic_conn tree */
3913 eb64_insert(root, &cid->seq_num);
3914
3915 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3916 return cid;
3917
3918 err:
3919 pool_free(pool_head_quic_connection_id, cid);
3920 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3921 return NULL;
3922}
3923
3924/* Build all the frames which must be sent just after the handshake have succeeded.
3925 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
3926 * a HANDSHAKE_DONE frame.
3927 * Return 1 if succeeded, 0 if not.
3928 */
3929static int quic_build_post_handshake_frames(struct quic_conn *qc)
3930{
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003931 int ret = 0, max;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003932 struct quic_enc_level *qel;
3933 struct quic_frame *frm, *frmbak;
3934 struct list frm_list = LIST_HEAD_INIT(frm_list);
3935 struct eb64_node *node;
3936
3937 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
3938
3939 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3940 /* Only servers must send a HANDSHAKE_DONE frame. */
3941 if (qc_is_listener(qc)) {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003942 frm = qc_frm_alloc(QUIC_FT_HANDSHAKE_DONE);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003943 if (!frm) {
3944 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3945 goto leave;
3946 }
3947
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003948 LIST_APPEND(&frm_list, &frm->list);
3949 }
3950
3951 /* Initialize <max> connection IDs minus one: there is
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003952 * already one connection ID used for the current connection. Also limit
3953 * the number of connection IDs sent to the peer to 4 (3 from this function
3954 * plus 1 for the current connection.
3955 * Note that active_connection_id_limit >= 2: this has been already checked
3956 * when receiving this parameter.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003957 */
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003958 max = QUIC_MIN(qc->tx.params.active_connection_id_limit - 1, (uint64_t)3);
3959 while (max--) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003960 struct quic_connection_id *cid;
3961
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003962 frm = qc_frm_alloc(QUIC_FT_NEW_CONNECTION_ID);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003963 if (!frm) {
3964 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3965 goto err;
3966 }
3967
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003968 cid = new_quic_cid(&qc->cids, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003969 if (!cid) {
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003970 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003971 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3972 goto err;
3973 }
3974
3975 /* insert the allocated CID in the receiver datagram handler tree */
3976 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3977
3978 quic_connection_id_to_frm_cpy(frm, cid);
3979 LIST_APPEND(&frm_list, &frm->list);
3980 }
3981
3982 LIST_SPLICE(&qel->pktns->tx.frms, &frm_list);
3983 qc->flags |= QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT;
3984
3985 ret = 1;
3986 leave:
3987 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
3988 return ret;
3989
3990 err:
3991 /* free the frames */
3992 list_for_each_entry_safe(frm, frmbak, &frm_list, list)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003993 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003994
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01003995 /* The first CID sequence number value used to allocated CIDs by this function is 1,
3996 * 0 being the sequence number of the CID for this connection.
3997 */
3998 node = eb64_lookup_ge(&qc->cids, 1);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003999 while (node) {
4000 struct quic_connection_id *cid;
4001
4002 cid = eb64_entry(node, struct quic_connection_id, seq_num);
4003 if (cid->seq_num.key >= max)
4004 break;
4005
4006 node = eb64_next(node);
4007 ebmb_delete(&cid->node);
4008 eb64_delete(&cid->seq_num);
4009 pool_free(pool_head_quic_connection_id, cid);
4010 }
4011 goto leave;
4012}
4013
4014/* Deallocate <l> list of ACK ranges. */
4015void quic_free_arngs(struct quic_conn *qc, struct quic_arngs *arngs)
4016{
4017 struct eb64_node *n;
4018 struct quic_arng_node *ar;
4019
4020 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4021
4022 n = eb64_first(&arngs->root);
4023 while (n) {
4024 struct eb64_node *next;
4025
4026 ar = eb64_entry(n, struct quic_arng_node, first);
4027 next = eb64_next(n);
4028 eb64_delete(n);
4029 pool_free(pool_head_quic_arng, ar);
4030 n = next;
4031 }
4032
4033 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4034}
4035
4036/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
4037 * descending order.
4038 */
4039static inline size_t sack_gap(struct quic_arng_node *p,
4040 struct quic_arng_node *q)
4041{
4042 return p->first.key - q->last - 2;
4043}
4044
4045
4046/* Remove the last elements of <ack_ranges> list of ack range updating its
4047 * encoded size until it goes below <limit>.
4048 * Returns 1 if succeeded, 0 if not (no more element to remove).
4049 */
4050static int quic_rm_last_ack_ranges(struct quic_conn *qc,
4051 struct quic_arngs *arngs, size_t limit)
4052{
4053 int ret = 0;
4054 struct eb64_node *last, *prev;
4055
4056 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4057
4058 last = eb64_last(&arngs->root);
4059 while (last && arngs->enc_sz > limit) {
4060 struct quic_arng_node *last_node, *prev_node;
4061
4062 prev = eb64_prev(last);
4063 if (!prev) {
4064 TRACE_DEVEL("<last> not found", QUIC_EV_CONN_TXPKT, qc);
4065 goto out;
4066 }
4067
4068 last_node = eb64_entry(last, struct quic_arng_node, first);
4069 prev_node = eb64_entry(prev, struct quic_arng_node, first);
4070 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
4071 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
4072 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
4073 --arngs->sz;
4074 eb64_delete(last);
4075 pool_free(pool_head_quic_arng, last);
4076 last = prev;
4077 }
4078
4079 ret = 1;
4080 out:
4081 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4082 return ret;
4083}
4084
4085/* Set the encoded size of <arngs> QUIC ack ranges. */
4086static void quic_arngs_set_enc_sz(struct quic_conn *qc, struct quic_arngs *arngs)
4087{
4088 struct eb64_node *node, *next;
4089 struct quic_arng_node *ar, *ar_next;
4090
4091 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4092
4093 node = eb64_last(&arngs->root);
4094 if (!node)
4095 goto leave;
4096
4097 ar = eb64_entry(node, struct quic_arng_node, first);
4098 arngs->enc_sz = quic_int_getsize(ar->last) +
4099 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
4100
4101 while ((next = eb64_prev(node))) {
4102 ar_next = eb64_entry(next, struct quic_arng_node, first);
4103 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
4104 quic_int_getsize(ar_next->last - ar_next->first.key);
4105 node = next;
4106 ar = eb64_entry(node, struct quic_arng_node, first);
4107 }
4108
4109 leave:
4110 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4111}
4112
4113/* Insert <ar> ack range into <argns> tree of ack ranges.
4114 * Returns the ack range node which has been inserted if succeeded, NULL if not.
4115 */
4116static inline
4117struct quic_arng_node *quic_insert_new_range(struct quic_conn *qc,
4118 struct quic_arngs *arngs,
4119 struct quic_arng *ar)
4120{
4121 struct quic_arng_node *new_ar;
4122
4123 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
4124
4125 new_ar = pool_alloc(pool_head_quic_arng);
4126 if (!new_ar) {
4127 TRACE_ERROR("ack range allocation failed", QUIC_EV_CONN_RXPKT, qc);
4128 goto leave;
4129 }
4130
4131 new_ar->first.key = ar->first;
4132 new_ar->last = ar->last;
4133 eb64_insert(&arngs->root, &new_ar->first);
4134 arngs->sz++;
4135
4136 leave:
4137 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
4138 return new_ar;
4139}
4140
4141/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
4142 * Note that this function computes the number of bytes required to encode
4143 * this tree of ACK ranges in descending order.
4144 *
4145 * Descending order
4146 * ------------->
4147 * range1 range2
4148 * ..........|--------|..............|--------|
4149 * ^ ^ ^ ^
4150 * | | | |
4151 * last1 first1 last2 first2
4152 * ..........+--------+--------------+--------+......
4153 * diff1 gap12 diff2
4154 *
4155 * To encode the previous list of ranges we must encode integers as follows in
4156 * descending order:
4157 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
4158 * with diff1 = last1 - first1
4159 * diff2 = last2 - first2
4160 * gap12 = first1 - last2 - 2 (>= 0)
4161 *
4162
4163returns 0 on error
4164
4165 */
4166int quic_update_ack_ranges_list(struct quic_conn *qc,
4167 struct quic_arngs *arngs,
4168 struct quic_arng *ar)
4169{
4170 int ret = 0;
4171 struct eb64_node *le;
4172 struct quic_arng_node *new_node;
4173 struct eb64_node *new;
4174
4175 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
4176
4177 new = NULL;
4178 if (eb_is_empty(&arngs->root)) {
4179 new_node = quic_insert_new_range(qc, arngs, ar);
4180 if (new_node)
4181 ret = 1;
4182
4183 goto leave;
4184 }
4185
4186 le = eb64_lookup_le(&arngs->root, ar->first);
4187 if (!le) {
4188 new_node = quic_insert_new_range(qc, arngs, ar);
4189 if (!new_node)
4190 goto leave;
4191
4192 new = &new_node->first;
4193 }
4194 else {
4195 struct quic_arng_node *le_ar =
4196 eb64_entry(le, struct quic_arng_node, first);
4197
4198 /* Already existing range */
4199 if (le_ar->last >= ar->last) {
4200 ret = 1;
4201 }
4202 else if (le_ar->last + 1 >= ar->first) {
4203 le_ar->last = ar->last;
4204 new = le;
4205 new_node = le_ar;
4206 }
4207 else {
4208 new_node = quic_insert_new_range(qc, arngs, ar);
4209 if (!new_node)
4210 goto leave;
4211
4212 new = &new_node->first;
4213 }
4214 }
4215
4216 /* Verify that the new inserted node does not overlap the nodes
4217 * which follow it.
4218 */
4219 if (new) {
4220 struct eb64_node *next;
4221 struct quic_arng_node *next_node;
4222
4223 while ((next = eb64_next(new))) {
4224 next_node =
4225 eb64_entry(next, struct quic_arng_node, first);
4226 if (new_node->last + 1 < next_node->first.key)
4227 break;
4228
4229 if (next_node->last > new_node->last)
4230 new_node->last = next_node->last;
4231 eb64_delete(next);
4232 pool_free(pool_head_quic_arng, next_node);
4233 /* Decrement the size of these ranges. */
4234 arngs->sz--;
4235 }
4236 }
4237
4238 ret = 1;
4239 leave:
4240 quic_arngs_set_enc_sz(qc, arngs);
4241 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
4242 return ret;
4243}
Frédéric Lécailleece86e62023-03-07 11:53:43 +01004244
4245/* Detect the value of the spin bit to be used. */
4246static inline void qc_handle_spin_bit(struct quic_conn *qc, struct quic_rx_packet *pkt,
4247 struct quic_enc_level *qel)
4248{
4249 uint64_t largest_pn = qel->pktns->rx.largest_pn;
4250
4251 if (qel != &qc->els[QUIC_TLS_ENC_LEVEL_APP] || largest_pn == -1 ||
4252 pkt->pn <= largest_pn)
4253 return;
4254
4255 if (qc_is_listener(qc)) {
4256 if (pkt->flags & QUIC_FL_RX_PACKET_SPIN_BIT)
4257 qc->flags |= QUIC_FL_CONN_SPIN_BIT;
4258 else
4259 qc->flags &= ~QUIC_FL_CONN_SPIN_BIT;
4260 }
4261 else {
4262 if (pkt->flags & QUIC_FL_RX_PACKET_SPIN_BIT)
4263 qc->flags &= ~QUIC_FL_CONN_SPIN_BIT;
4264 else
4265 qc->flags |= QUIC_FL_CONN_SPIN_BIT;
4266 }
4267}
4268
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004269/* Remove the header protection of packets at <el> encryption level.
4270 * Always succeeds.
4271 */
4272static inline void qc_rm_hp_pkts(struct quic_conn *qc, struct quic_enc_level *el)
4273{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004274 struct quic_rx_packet *pqpkt, *pkttmp;
4275 struct quic_enc_level *app_qel;
4276
4277 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, qc);
4278 app_qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4279 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
4280 if (el == app_qel && qc_is_listener(qc) && qc->state < QUIC_HS_ST_COMPLETE) {
4281 TRACE_DEVEL("hp not removed (handshake not completed)",
4282 QUIC_EV_CONN_ELRMHP, qc);
4283 goto out;
4284 }
Frédéric Lécaille72027782023-02-22 16:20:09 +01004285
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004286 list_for_each_entry_safe(pqpkt, pkttmp, &el->rx.pqpkts, list) {
Frédéric Lécaille72027782023-02-22 16:20:09 +01004287 struct quic_tls_ctx *tls_ctx;
4288
4289 tls_ctx = qc_select_tls_ctx(qc, el, pqpkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004290 if (!qc_do_rm_hp(qc, pqpkt, tls_ctx, el->pktns->rx.largest_pn,
4291 pqpkt->data + pqpkt->pn_offset, pqpkt->data)) {
4292 TRACE_ERROR("hp removing error", QUIC_EV_CONN_ELRMHP, qc);
4293 }
4294 else {
Frédéric Lécailleece86e62023-03-07 11:53:43 +01004295 qc_handle_spin_bit(qc, pqpkt, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004296 /* The AAD includes the packet number field */
4297 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
4298 /* Store the packet into the tree of packets to decrypt. */
4299 pqpkt->pn_node.key = pqpkt->pn;
4300 eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
4301 quic_rx_packet_refinc(pqpkt);
4302 TRACE_DEVEL("hp removed", QUIC_EV_CONN_ELRMHP, qc, pqpkt);
4303 }
4304 LIST_DELETE(&pqpkt->list);
4305 quic_rx_packet_refdec(pqpkt);
4306 }
4307
4308 out:
4309 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, qc);
4310}
4311
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004312/* Process all the CRYPTO frame at <el> encryption level. This is the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004313 * responsibility of the called to ensure there exists a CRYPTO data
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004314 * stream for this level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004315 * Return 1 if succeeded, 0 if not.
4316 */
4317static inline int qc_treat_rx_crypto_frms(struct quic_conn *qc,
4318 struct quic_enc_level *el,
4319 struct ssl_sock_ctx *ctx)
4320{
4321 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004322 struct ncbuf *ncbuf;
4323 struct quic_cstream *cstream = el->cstream;
4324 ncb_sz_t data;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004325
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004326 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004327
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004328 BUG_ON(!cstream);
4329 ncbuf = &cstream->rx.ncbuf;
4330 if (ncb_is_null(ncbuf))
4331 goto done;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004332
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004333 /* TODO not working if buffer is wrapping */
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004334 while ((data = ncb_data(ncbuf, 0))) {
4335 const unsigned char *cdata = (const unsigned char *)ncb_head(ncbuf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004336
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004337 if (!qc_provide_cdata(el, ctx, cdata, data, NULL, NULL))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004338 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004339
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004340 cstream->rx.offset += data;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004341 TRACE_DEVEL("buffered crypto data were provided to TLS stack",
4342 QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004343 }
4344
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004345 done:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004346 ret = 1;
4347 leave:
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004348 if (!ncb_is_null(ncbuf) && ncb_is_empty(ncbuf)) {
4349 TRACE_DEVEL("freeing crypto buf", QUIC_EV_CONN_PHPKTS, qc, el);
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004350 quic_free_ncbuf(ncbuf);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004351 }
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004352 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004353 return ret;
4354}
4355
4356/* Process all the packets at <el> and <next_el> encryption level.
4357 * This is the caller responsibility to check that <cur_el> is different of <next_el>
4358 * as pointer value.
4359 * Return 1 if succeeded, 0 if not.
4360 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004361int qc_treat_rx_pkts(struct quic_conn *qc, struct quic_enc_level *cur_el,
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004362 struct quic_enc_level *next_el)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004363{
4364 int ret = 0;
4365 struct eb64_node *node;
4366 int64_t largest_pn = -1;
4367 unsigned int largest_pn_time_received = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004368 struct quic_enc_level *qel = cur_el;
4369
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004370 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004371 qel = cur_el;
4372 next_tel:
4373 if (!qel)
4374 goto out;
4375
4376 node = eb64_first(&qel->rx.pkts);
4377 while (node) {
4378 struct quic_rx_packet *pkt;
4379
4380 pkt = eb64_entry(node, struct quic_rx_packet, pn_node);
4381 TRACE_DATA("new packet", QUIC_EV_CONN_RXPKT,
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004382 qc, pkt, NULL, qc->xprt_ctx->ssl);
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01004383 if (!qc_pkt_decrypt(qc, qel, pkt)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004384 /* Drop the packet */
4385 TRACE_ERROR("packet decryption failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004386 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004387 }
4388 else {
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004389 if (!qc_parse_pkt_frms(qc, pkt, qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004390 /* Drop the packet */
4391 TRACE_ERROR("packet parsing failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004392 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004393 HA_ATOMIC_INC(&qc->prx_counters->dropped_parsing);
4394 }
4395 else {
4396 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
4397
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004398 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004399 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
4400 qel->pktns->rx.nb_aepkts_since_last_ack++;
4401 qc_idle_timer_rearm(qc, 1);
4402 }
4403 if (pkt->pn > largest_pn) {
4404 largest_pn = pkt->pn;
4405 largest_pn_time_received = pkt->time_received;
4406 }
4407 /* Update the list of ranges to acknowledge. */
4408 if (!quic_update_ack_ranges_list(qc, &qel->pktns->rx.arngs, &ar))
4409 TRACE_ERROR("Could not update ack range list",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004410 QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004411 }
4412 }
4413 node = eb64_next(node);
4414 eb64_delete(&pkt->pn_node);
4415 quic_rx_packet_refdec(pkt);
4416 }
4417
4418 if (largest_pn != -1 && largest_pn > qel->pktns->rx.largest_pn) {
4419 /* Update the largest packet number. */
4420 qel->pktns->rx.largest_pn = largest_pn;
4421 /* Update the largest acknowledged packet timestamps */
4422 qel->pktns->rx.largest_time_received = largest_pn_time_received;
4423 qel->pktns->flags |= QUIC_FL_PKTNS_NEW_LARGEST_PN;
4424 }
4425
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004426 if (qel->cstream && !qc_treat_rx_crypto_frms(qc, qel, qc->xprt_ctx)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004427 // trace already emitted by function above
4428 goto leave;
4429 }
4430
4431 if (qel == cur_el) {
4432 BUG_ON(qel == next_el);
4433 qel = next_el;
4434 largest_pn = -1;
4435 goto next_tel;
4436 }
4437
4438 out:
4439 ret = 1;
4440 leave:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004441 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004442 return ret;
4443}
4444
4445/* Check if it's possible to remove header protection for packets related to
4446 * encryption level <qel>. If <qel> is NULL, assume it's false.
4447 *
4448 * Return true if the operation is possible else false.
4449 */
4450static int qc_qel_may_rm_hp(struct quic_conn *qc, struct quic_enc_level *qel)
4451{
4452 int ret = 0;
4453 enum quic_tls_enc_level tel;
4454
4455 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
4456
4457 if (!qel)
4458 goto cant_rm_hp;
4459
4460 tel = ssl_to_quic_enc_level(qel->level);
4461
4462 /* check if tls secrets are available */
4463 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
4464 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, qc);
4465 goto cant_rm_hp;
4466 }
4467
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004468 if (!quic_tls_has_rx_sec(qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004469 TRACE_DEVEL("non available secrets", QUIC_EV_CONN_TRMHP, qc);
4470 goto cant_rm_hp;
4471 }
4472
Frédéric Lécaille8417beb2023-02-01 10:31:35 +01004473 if (tel == QUIC_TLS_ENC_LEVEL_APP && qc->state < QUIC_HS_ST_COMPLETE) {
4474 TRACE_DEVEL("handshake not complete", QUIC_EV_CONN_TRMHP, qc);
4475 goto cant_rm_hp;
4476 }
4477
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004478 /* check if the connection layer is ready before using app level */
4479 if ((tel == QUIC_TLS_ENC_LEVEL_APP || tel == QUIC_TLS_ENC_LEVEL_EARLY_DATA) &&
4480 qc->mux_state == QC_MUX_NULL) {
4481 TRACE_DEVEL("connection layer not ready", QUIC_EV_CONN_TRMHP, qc);
4482 goto cant_rm_hp;
4483 }
4484
4485 ret = 1;
4486 cant_rm_hp:
4487 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc);
4488 return ret;
4489}
4490
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004491/* Flush txbuf for <qc> connection. This must be called prior to a packet
4492 * preparation when txbuf contains older data. A send will be conducted for
4493 * these data.
4494 *
4495 * Returns 1 on success : buffer is empty and can be use for packet
4496 * preparation. On error 0 is returned.
4497 */
4498static int qc_purge_txbuf(struct quic_conn *qc, struct buffer *buf)
4499{
4500 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4501
4502 /* This operation can only be conducted if txbuf is not empty. This
4503 * case only happens for connection with their owned socket due to an
4504 * older transient sendto() error.
4505 */
4506 BUG_ON(!qc_test_fd(qc));
4507
4508 if (b_data(buf) && !qc_send_ppkts(buf, qc->xprt_ctx)) {
4509 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4510 qc_txb_release(qc);
4511 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TXPKT, qc);
4512 return 0;
4513 }
4514
4515 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4516 return 1;
4517}
4518
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004519/* Try to send application frames from list <frms> on connection <qc>.
4520 *
4521 * Use qc_send_app_probing wrapper when probing with old data.
4522 *
4523 * Returns 1 on success. Some data might not have been sent due to congestion,
4524 * in this case they are left in <frms> input list. The caller may subscribe on
4525 * quic-conn to retry later.
4526 *
4527 * Returns 0 on critical error.
4528 * TODO review and classify more distinctly transient from definitive errors to
4529 * allow callers to properly handle it.
4530 */
4531static int qc_send_app_pkts(struct quic_conn *qc, struct list *frms)
4532{
4533 int status = 0;
4534 struct buffer *buf;
4535
4536 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4537
4538 buf = qc_txb_alloc(qc);
4539 if (!buf) {
4540 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004541 goto err;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004542 }
4543
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004544 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4545 goto err;
4546
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004547 /* Prepare and send packets until we could not further prepare packets. */
4548 while (1) {
4549 int ret;
4550 /* Currently buf cannot be non-empty at this stage. Even if a
4551 * previous sendto() has failed it is emptied to simulate
4552 * packet emission and rely on QUIC lost detection to try to
4553 * emit it.
4554 */
4555 BUG_ON_HOT(b_data(buf));
4556 b_reset(buf);
4557
4558 ret = qc_prep_app_pkts(qc, buf, frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004559 if (ret == -1) {
4560 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004561 goto err;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004562 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004563
Amaury Denoyelle37333862023-02-28 11:53:48 +01004564 if (!ret)
4565 break;
4566
4567 if (!qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004568 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4569 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004570 goto err;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004571 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004572 }
4573
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004574 status = 1;
4575 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004576 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4577 return status;
4578
4579 err:
Amaury Denoyelle37333862023-02-28 11:53:48 +01004580 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TXPKT, qc);
4581 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004582}
4583
4584/* Try to send application frames from list <frms> on connection <qc>. Use this
4585 * function when probing is required.
4586 *
4587 * Returns the result from qc_send_app_pkts function.
4588 */
4589static forceinline int qc_send_app_probing(struct quic_conn *qc,
4590 struct list *frms)
4591{
4592 int ret;
4593
4594 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4595
4596 TRACE_STATE("preparing old data (probing)", QUIC_EV_CONN_TXPKT, qc);
4597 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4598 ret = qc_send_app_pkts(qc, frms);
4599 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4600
4601 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4602 return ret;
4603}
4604
4605/* Try to send application frames from list <frms> on connection <qc>. This
4606 * function is provided for MUX upper layer usage only.
4607 *
4608 * Returns the result from qc_send_app_pkts function.
4609 */
4610int qc_send_mux(struct quic_conn *qc, struct list *frms)
4611{
4612 int ret;
4613
4614 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4615 BUG_ON(qc->mux_state != QC_MUX_READY); /* Only MUX can uses this function so it must be ready. */
4616
4617 TRACE_STATE("preparing data (from MUX)", QUIC_EV_CONN_TXPKT, qc);
4618 qc->flags |= QUIC_FL_CONN_TX_MUX_CONTEXT;
4619 ret = qc_send_app_pkts(qc, frms);
4620 qc->flags &= ~QUIC_FL_CONN_TX_MUX_CONTEXT;
4621
4622 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4623 return ret;
4624}
4625
4626/* Sends handshake packets from up to two encryption levels <tel> and <next_te>
4627 * with <tel_frms> and <next_tel_frms> as frame list respectively for <qc>
4628 * QUIC connection. <old_data> is used as boolean to send data already sent but
4629 * not already acknowledged (in flight).
4630 * Returns 1 if succeeded, 0 if not.
4631 */
4632int qc_send_hdshk_pkts(struct quic_conn *qc, int old_data,
4633 enum quic_tls_enc_level tel, struct list *tel_frms,
4634 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
4635{
4636 int ret, status = 0;
4637 struct buffer *buf = qc_txb_alloc(qc);
4638
4639 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4640
4641 if (!buf) {
4642 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4643 goto leave;
4644 }
4645
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004646 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4647 goto out;
4648
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004649 /* Currently buf cannot be non-empty at this stage. Even if a previous
4650 * sendto() has failed it is emptied to simulate packet emission and
4651 * rely on QUIC lost detection to try to emit it.
4652 */
4653 BUG_ON_HOT(b_data(buf));
4654 b_reset(buf);
4655
4656 if (old_data) {
4657 TRACE_STATE("old data for probing asked", QUIC_EV_CONN_TXPKT, qc);
4658 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4659 }
4660
4661 ret = qc_prep_pkts(qc, buf, tel, tel_frms, next_tel, next_tel_frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004662 if (ret == -1) {
4663 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004664 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004665 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004666
Amaury Denoyelle37333862023-02-28 11:53:48 +01004667 if (ret && !qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004668 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4669 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004670 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004671 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004672
Amaury Denoyelle37333862023-02-28 11:53:48 +01004673 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004674 status = 1;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004675
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004676 out:
4677 TRACE_STATE("no more need old data for probing", QUIC_EV_CONN_TXPKT, qc);
4678 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004679 leave:
4680 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4681 return status;
4682}
4683
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004684/* Retransmit up to two datagrams depending on packet number space.
4685 * Return 0 when failed, 0 if not.
4686 */
4687static int qc_dgrams_retransmit(struct quic_conn *qc)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004688{
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004689 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004690 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4691 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4692 struct quic_enc_level *aqel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4693
4694 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4695
4696 if (iqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004697 int i;
4698
4699 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
4700 struct list ifrms = LIST_HEAD_INIT(ifrms);
4701 struct list hfrms = LIST_HEAD_INIT(hfrms);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004702
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004703 qc_prep_hdshk_fast_retrans(qc, &ifrms, &hfrms);
4704 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &ifrms);
4705 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4706 if (!LIST_ISEMPTY(&ifrms)) {
4707 iqel->pktns->tx.pto_probe = 1;
4708 if (!LIST_ISEMPTY(&hfrms))
4709 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004710 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4711 QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms))
4712 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004713 /* Put back unsent frames in their packet number spaces */
4714 LIST_SPLICE(&iqel->pktns->tx.frms, &ifrms);
4715 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4716 }
Frédéric Lécailleec937212023-03-03 17:34:41 +01004717 else {
4718 if (!(qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
4719 iqel->pktns->tx.pto_probe = 1;
4720 if (!qc_send_hdshk_pkts(qc, 0, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4721 QUIC_TLS_ENC_LEVEL_NONE, NULL))
4722 goto leave;
4723 }
4724 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004725 }
4726 TRACE_STATE("no more need to probe Initial packet number space",
4727 QUIC_EV_CONN_TXPKT, qc);
4728 iqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004729 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004730 }
4731 else {
4732 int i;
4733
4734 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004735 hqel->pktns->tx.pto_probe = 0;
4736 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
Frédéric Lécaille7b5d9b12022-11-28 17:21:45 +01004737 struct list frms1 = LIST_HEAD_INIT(frms1);
4738
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004739 qc_prep_fast_retrans(qc, hqel, &frms1, NULL);
4740 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4741 if (!LIST_ISEMPTY(&frms1)) {
4742 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004743 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &frms1,
4744 QUIC_TLS_ENC_LEVEL_NONE, NULL))
4745 goto leave;
4746
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004747 /* Put back unsent frames into their packet number spaces */
4748 LIST_SPLICE(&hqel->pktns->tx.frms, &frms1);
4749 }
4750 }
4751 TRACE_STATE("no more need to probe Handshake packet number space",
4752 QUIC_EV_CONN_TXPKT, qc);
4753 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4754 }
4755 else if (aqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4756 struct list frms2 = LIST_HEAD_INIT(frms2);
4757 struct list frms1 = LIST_HEAD_INIT(frms1);
4758
4759 aqel->pktns->tx.pto_probe = 0;
4760 qc_prep_fast_retrans(qc, aqel, &frms1, &frms2);
4761 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4762 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms2);
4763 if (!LIST_ISEMPTY(&frms1)) {
4764 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004765 if (!qc_send_app_probing(qc, &frms1))
4766 goto leave;
4767
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004768 /* Put back unsent frames into their packet number spaces */
4769 LIST_SPLICE(&aqel->pktns->tx.frms, &frms1);
4770 }
4771 if (!LIST_ISEMPTY(&frms2)) {
4772 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004773 if (!qc_send_app_probing(qc, &frms2))
4774 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004775 /* Put back unsent frames into their packet number spaces */
4776 LIST_SPLICE(&aqel->pktns->tx.frms, &frms2);
4777 }
4778 TRACE_STATE("no more need to probe 01RTT packet number space",
4779 QUIC_EV_CONN_TXPKT, qc);
4780 aqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4781 }
4782 }
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004783
4784 ret = 1;
4785 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004786 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004787 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004788}
4789
4790/* QUIC connection packet handler task (post handshake) */
4791struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state)
4792{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004793 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004794 struct quic_enc_level *qel;
4795
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004796 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4797
4798 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
4799 TRACE_STATE("connection handshake state", QUIC_EV_CONN_IO_CB, qc, &qc->state);
4800
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004801 if (qc_test_fd(qc))
4802 qc_rcv_buf(qc);
4803
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004804 /* Retranmissions */
4805 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4806 TRACE_STATE("retransmission needed", QUIC_EV_CONN_IO_CB, qc);
4807 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004808 if (!qc_dgrams_retransmit(qc))
4809 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004810 }
4811
4812 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4813 qc_rm_hp_pkts(qc, qel);
4814
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004815 if (!qc_treat_rx_pkts(qc, qel, NULL)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004816 TRACE_DEVEL("qc_treat_rx_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4817 goto out;
4818 }
4819
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004820 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4821 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
4822 goto out;
4823 }
4824
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004825 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4826 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)) {
4827 TRACE_STATE("draining connection (must not send packets)", QUIC_EV_CONN_IO_CB, qc);
4828 goto out;
4829 }
4830
4831 /* XXX TODO: how to limit the list frames to send */
4832 if (!qc_send_app_pkts(qc, &qel->pktns->tx.frms)) {
4833 TRACE_DEVEL("qc_send_app_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4834 goto out;
4835 }
4836
4837 out:
4838 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
4839 return t;
4840}
4841
4842/* Returns a boolean if <qc> needs to emit frames for <qel> encryption level. */
4843static int qc_need_sending(struct quic_conn *qc, struct quic_enc_level *qel)
4844{
4845 return (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) ||
4846 (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) ||
4847 qel->pktns->tx.pto_probe ||
4848 !LIST_ISEMPTY(&qel->pktns->tx.frms);
4849}
4850
4851/* QUIC connection packet handler task. */
4852struct task *quic_conn_io_cb(struct task *t, void *context, unsigned int state)
4853{
4854 int ret, ssl_err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004855 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004856 enum quic_tls_enc_level tel, next_tel;
4857 struct quic_enc_level *qel, *next_qel;
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004858 /* Early-data encryption level */
4859 struct quic_enc_level *eqel;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004860 struct buffer *buf = NULL;
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004861 int st, zero_rtt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004862
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004863 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004864 eqel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004865 st = qc->state;
4866 TRACE_PROTO("connection state", QUIC_EV_CONN_IO_CB, qc, &st);
4867
4868 /* Retranmissions */
4869 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4870 TRACE_DEVEL("retransmission needed", QUIC_EV_CONN_PHPKTS, qc);
4871 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004872 if (!qc_dgrams_retransmit(qc))
4873 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004874 }
4875
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004876 ssl_err = SSL_ERROR_NONE;
4877 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004878 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004879 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004880
4881 if (qc_test_fd(qc))
4882 qc_rcv_buf(qc);
4883
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004884 if (st >= QUIC_HS_ST_COMPLETE &&
4885 qc_el_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
4886 TRACE_DEVEL("remaining Handshake packets", QUIC_EV_CONN_PHPKTS, qc);
4887 /* There may be remaining Handshake packets to treat and acknowledge. */
4888 tel = QUIC_TLS_ENC_LEVEL_HANDSHAKE;
4889 next_tel = QUIC_TLS_ENC_LEVEL_APP;
4890 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004891 else if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, zero_rtt))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004892 goto out;
4893
4894 qel = &qc->els[tel];
4895 next_qel = next_tel == QUIC_TLS_ENC_LEVEL_NONE ? NULL : &qc->els[next_tel];
4896
4897 next_level:
4898 /* Treat packets waiting for header packet protection decryption */
4899 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4900 qc_rm_hp_pkts(qc, qel);
4901
Frédéric Lécailleb3562a32023-02-25 11:27:34 +01004902 if (!qc_treat_rx_pkts(qc, qel, next_qel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004903 goto out;
4904
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004905 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4906 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_PHPKTS, qc);
4907 goto out;
4908 }
4909
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004910 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4911 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE))
4912 goto out;
4913
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004914 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004915 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004916 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
4917 if (next_qel && next_qel == eqel && zero_rtt) {
4918 TRACE_DEVEL("select 0RTT as next encryption level",
4919 QUIC_EV_CONN_PHPKTS, qc);
4920 qel = next_qel;
4921 next_qel = NULL;
4922 goto next_level;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004923 }
4924
4925 st = qc->state;
4926 if (st >= QUIC_HS_ST_COMPLETE) {
4927 if (!(qc->flags & QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT) &&
4928 !quic_build_post_handshake_frames(qc))
4929 goto out;
4930
4931 if (!(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].tls_ctx.flags &
4932 QUIC_FL_TLS_SECRETS_DCD)) {
4933 /* Discard the Handshake keys. */
4934 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4935 TRACE_PROTO("discarding Handshake pktns", QUIC_EV_CONN_PHPKTS, qc);
4936 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, qc);
4937 qc_set_timer(qc);
4938 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4939 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns);
4940 }
4941
4942 if (qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) {
4943 /* There may be remaining handshake to build (acks) */
4944 st = QUIC_HS_ST_SERVER_HANDSHAKE;
4945 }
4946 }
4947
4948 /* A listener does not send any O-RTT packet. O-RTT packet number space must not
4949 * be considered.
4950 */
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004951 if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, 0))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004952 goto out;
4953
4954 if (!qc_need_sending(qc, qel) &&
4955 (!next_qel || !qc_need_sending(qc, next_qel))) {
4956 goto skip_send;
4957 }
4958
4959 buf = qc_txb_alloc(qc);
4960 if (!buf)
4961 goto out;
4962
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004963 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4964 goto skip_send;
4965
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004966 /* Currently buf cannot be non-empty at this stage. Even if a previous
4967 * sendto() has failed it is emptied to simulate packet emission and
4968 * rely on QUIC lost detection to try to emit it.
4969 */
4970 BUG_ON_HOT(b_data(buf));
4971 b_reset(buf);
4972
4973 ret = qc_prep_pkts(qc, buf, tel, &qc->els[tel].pktns->tx.frms,
4974 next_tel, &qc->els[next_tel].pktns->tx.frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004975 if (ret == -1) {
4976 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004977 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004978 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004979
Amaury Denoyelle37333862023-02-28 11:53:48 +01004980 if (ret && !qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004981 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4982 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004983 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004984 }
4985
4986 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004987
4988 skip_send:
4989 /* Check if there is something to do for the next level.
4990 */
4991 if (next_qel && next_qel != qel &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004992 quic_tls_has_rx_sec(next_qel) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004993 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || qc_el_rx_pkts(next_qel))) {
4994 qel = next_qel;
4995 next_qel = NULL;
4996 goto next_level;
4997 }
4998
4999 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005000 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc, &st, &ssl_err);
5001 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
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005144 TRACE_ENTER(QUIC_EV_CONN_PTIMER, qc,
5145 NULL, NULL, &qc->path->ifae_pkts);
5146 task->expire = TICK_ETERNITY;
5147 pktns = quic_loss_pktns(qc);
5148 if (tick_isset(pktns->tx.loss_time)) {
5149 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
5150
5151 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
5152 if (!LIST_ISEMPTY(&lost_pkts))
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005153 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01005154 if (qc_release_lost_pkts(qc, pktns, &lost_pkts, now_ms))
5155 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005156 goto out;
5157 }
5158
5159 if (qc->path->in_flight) {
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +01005160 pktns = quic_pto_pktns(qc, qc->state >= QUIC_HS_ST_CONFIRMED, NULL);
Amaury Denoyelle2a19b6e2023-03-20 18:29:36 +01005161 if (pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL]) {
5162 if (qc_may_probe_ipktns(qc)) {
5163 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5164 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
5165 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5166 }
5167 else {
5168 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5169 }
5170 if (qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].tx.in_flight) {
5171 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5172 qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
5173 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
5174 }
Frédéric Lécaillee25fce02023-03-20 17:23:19 +01005175 }
Amaury Denoyelle2a19b6e2023-03-20 18:29:36 +01005176 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE]) {
5177 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
5178 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5179 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
5180 if (qc->pktns[QUIC_TLS_PKTNS_INITIAL].tx.in_flight) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005181 if (qc_may_probe_ipktns(qc)) {
Amaury Denoyelle2a19b6e2023-03-20 18:29:36 +01005182 qc->pktns[QUIC_TLS_PKTNS_INITIAL].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005183 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5184 }
5185 else {
5186 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
5187 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005188 }
Amaury Denoyelle2a19b6e2023-03-20 18:29:36 +01005189 }
5190 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT]) {
Amaury Denoyelle8afe4b82023-03-21 11:39:24 +01005191 pktns->tx.pto_probe = QUIC_MAX_NB_PTO_DGRAMS;
Amaury Denoyelle2a19b6e2023-03-20 18:29:36 +01005192 /* Wake up upper layer if waiting to send new data. */
5193 if (!qc_notify_send(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005194 TRACE_STATE("needs to probe 01RTT packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01005195 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
5196 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005197 }
5198 }
5199 }
5200 else if (!qc_is_listener(qc) && qc->state <= QUIC_HS_ST_COMPLETE) {
5201 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
5202 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
5203
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02005204 if (quic_tls_has_tx_sec(hel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005205 hel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02005206 if (quic_tls_has_tx_sec(iel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005207 iel->pktns->tx.pto_probe = 1;
5208 }
5209
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005210 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005211 qc->path->loss.pto_count++;
5212
5213 out:
5214 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, qc, pktns);
5215
5216 return task;
5217}
5218
5219/* Parse the Retry token from buffer <token> with <end> a pointer to
5220 * one byte past the end of this buffer. This will extract the ODCID
5221 * which will be stored into <odcid>
5222 *
5223 * Returns 0 on success else non-zero.
5224 */
5225static int parse_retry_token(struct quic_conn *qc,
5226 const unsigned char *token, const unsigned char *end,
5227 struct quic_cid *odcid)
5228{
5229 int ret = 0;
5230 uint64_t odcid_len;
5231 uint32_t timestamp;
5232
5233 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5234
5235 if (!quic_dec_int(&odcid_len, &token, end)) {
5236 TRACE_ERROR("quic_dec_int() error", QUIC_EV_CONN_LPKT, qc);
5237 goto leave;
5238 }
5239
5240 /* RFC 9000 7.2. Negotiating Connection IDs:
5241 * When an Initial packet is sent by a client that has not previously
5242 * received an Initial or Retry packet from the server, the client
5243 * populates the Destination Connection ID field with an unpredictable
5244 * value. This Destination Connection ID MUST be at least 8 bytes in length.
5245 */
5246 if (odcid_len < QUIC_ODCID_MINLEN || odcid_len > QUIC_CID_MAXLEN) {
5247 TRACE_ERROR("wrong ODCID length", QUIC_EV_CONN_LPKT, qc);
5248 goto leave;
5249 }
5250
5251 if (end - token < odcid_len + sizeof timestamp) {
5252 TRACE_ERROR("too long ODCID length", QUIC_EV_CONN_LPKT, qc);
5253 goto leave;
5254 }
5255
5256 timestamp = ntohl(read_u32(token + odcid_len));
5257 if (timestamp + MS_TO_TICKS(QUIC_RETRY_DURATION_MS) <= now_ms) {
5258 TRACE_ERROR("token has expired", QUIC_EV_CONN_LPKT, qc);
5259 goto leave;
5260 }
5261
5262 ret = 1;
5263 memcpy(odcid->data, token, odcid_len);
5264 odcid->len = odcid_len;
5265 leave:
5266 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5267 return !ret;
5268}
5269
5270/* Allocate a new QUIC connection with <version> as QUIC version. <ipv4>
5271 * boolean is set to 1 for IPv4 connection, 0 for IPv6. <server> is set to 1
5272 * for QUIC servers (or haproxy listeners).
5273 * <dcid> is the destination connection ID, <scid> is the source connection ID,
5274 * <token> the token found to be used for this connection with <token_len> as
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005275 * length. Endpoints addresses are specified via <local_addr> and <peer_addr>.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005276 * Returns the connection if succeeded, NULL if not.
5277 */
5278static struct quic_conn *qc_new_conn(const struct quic_version *qv, int ipv4,
5279 struct quic_cid *dcid, struct quic_cid *scid,
5280 const struct quic_cid *token_odcid,
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005281 struct sockaddr_storage *local_addr,
5282 struct sockaddr_storage *peer_addr,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005283 int server, int token, void *owner)
5284{
5285 int i;
5286 struct quic_conn *qc;
5287 /* Initial CID. */
5288 struct quic_connection_id *icid;
5289 char *buf_area = NULL;
5290 struct listener *l = NULL;
5291 struct quic_cc_algo *cc_algo = NULL;
5292 struct quic_tls_ctx *ictx;
5293 TRACE_ENTER(QUIC_EV_CONN_INIT);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005294 /* TODO replace pool_zalloc by pool_alloc(). This requires special care
5295 * to properly initialized internal quic_conn members to safely use
5296 * quic_conn_release() on alloc failure.
5297 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005298 qc = pool_zalloc(pool_head_quic_conn);
5299 if (!qc) {
5300 TRACE_ERROR("Could not allocate a new connection", QUIC_EV_CONN_INIT);
5301 goto err;
5302 }
5303
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005304 /* Initialize in priority qc members required for a safe dealloc. */
5305
5306 /* required to use MTLIST_IN_LIST */
5307 MT_LIST_INIT(&qc->accept_list);
5308
5309 LIST_INIT(&qc->rx.pkt_list);
5310
Amaury Denoyelle42448332022-12-12 11:24:05 +01005311 qc_init_fd(qc);
5312
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005313 LIST_INIT(&qc->back_refs);
5314
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005315 /* Now proceeds to allocation of qc members. */
5316
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005317 buf_area = pool_alloc(pool_head_quic_conn_rxbuf);
5318 if (!buf_area) {
5319 TRACE_ERROR("Could not allocate a new RX buffer", QUIC_EV_CONN_INIT, qc);
5320 goto err;
5321 }
5322
5323 qc->cids = EB_ROOT;
5324 /* QUIC Server (or listener). */
5325 if (server) {
5326 struct proxy *prx;
5327
5328 l = owner;
5329 prx = l->bind_conf->frontend;
5330 cc_algo = l->bind_conf->quic_cc_algo;
5331
5332 qc->prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe,
5333 &quic_stats_module);
5334 qc->flags |= QUIC_FL_CONN_LISTENER;
5335 qc->state = QUIC_HS_ST_SERVER_INITIAL;
5336 /* Copy the initial DCID with the address. */
5337 qc->odcid.len = dcid->len;
5338 qc->odcid.addrlen = dcid->addrlen;
5339 memcpy(qc->odcid.data, dcid->data, dcid->len + dcid->addrlen);
5340
5341 /* copy the packet SCID to reuse it as DCID for sending */
5342 if (scid->len)
5343 memcpy(qc->dcid.data, scid->data, scid->len);
5344 qc->dcid.len = scid->len;
5345 qc->tx.buf = BUF_NULL;
5346 qc->li = l;
5347 }
5348 /* QUIC Client (outgoing connection to servers) */
5349 else {
5350 qc->state = QUIC_HS_ST_CLIENT_INITIAL;
5351 if (dcid->len)
5352 memcpy(qc->dcid.data, dcid->data, dcid->len);
5353 qc->dcid.len = dcid->len;
5354 }
5355 qc->mux_state = QC_MUX_NULL;
5356 qc->err = quic_err_transport(QC_ERR_NO_ERROR);
5357
Frédéric Lécailleb4c54712023-03-06 14:07:59 +01005358 /* Initialize the next CID sequence number to be used for this connection. */
5359 qc->next_cid_seq_num = 0;
5360 /* Insert the CID for this connection with 0 as sequence number. */
5361 icid = new_quic_cid(&qc->cids, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005362 if (!icid) {
5363 TRACE_ERROR("Could not allocate a new connection ID", QUIC_EV_CONN_INIT, qc);
5364 goto err;
5365 }
5366
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005367 if ((global.tune.options & GTUNE_QUIC_SOCK_PER_CONN) &&
5368 is_addr(local_addr)) {
5369 TRACE_USER("Allocate a socket for QUIC connection", QUIC_EV_CONN_INIT, qc);
5370 qc_alloc_fd(qc, local_addr, peer_addr);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005371
5372 /* haproxy soft-stop is supported only for QUIC connections
5373 * with their owned socket.
5374 */
5375 if (qc_test_fd(qc))
5376 _HA_ATOMIC_INC(&jobs);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005377 }
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005378
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005379 /* insert the allocated CID in the receiver datagram handler tree */
5380 if (server)
5381 ebmb_insert(&quic_dghdlrs[tid].cids, &icid->node, icid->cid.len);
5382
5383 /* Select our SCID which is the first CID with 0 as sequence number. */
5384 qc->scid = icid->cid;
5385
5386 /* Packet number spaces initialization. */
5387 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
5388 quic_pktns_init(&qc->pktns[i]);
5389 /* QUIC encryption level context initialization. */
5390 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5391 if (!quic_conn_enc_level_init(qc, i)) {
5392 TRACE_ERROR("Could not initialize an encryption level", QUIC_EV_CONN_INIT, qc);
5393 goto err;
5394 }
5395 /* Initialize the packet number space. */
5396 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
5397 }
5398
5399 qc->original_version = qv;
5400 qc->tps_tls_ext = (qc->original_version->num & 0xff000000) == 0xff000000 ?
5401 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS_DRAFT:
5402 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS;
5403 /* TX part. */
5404 LIST_INIT(&qc->tx.frms_to_send);
5405 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
5406 qc->tx.wbuf = qc->tx.rbuf = 0;
5407 qc->tx.bytes = 0;
5408 qc->tx.buf = BUF_NULL;
5409 /* RX part. */
5410 qc->rx.bytes = 0;
5411 qc->rx.buf = b_make(buf_area, QUIC_CONN_RX_BUFSZ, 0, 0);
5412 for (i = 0; i < QCS_MAX_TYPES; i++)
5413 qc->rx.strms[i].nb_streams = 0;
5414
5415 qc->nb_pkt_for_cc = 1;
5416 qc->nb_pkt_since_cc = 0;
5417
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005418 if (!quic_tls_ku_init(qc)) {
5419 TRACE_ERROR("Key update initialization failed", QUIC_EV_CONN_INIT, qc);
5420 goto err;
5421 }
5422
5423 /* XXX TO DO: Only one path at this time. */
5424 qc->path = &qc->paths[0];
5425 quic_path_init(qc->path, ipv4, cc_algo ? cc_algo : default_quic_cc_algo, qc);
5426
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005427 qc->streams_by_id = EB_ROOT_UNIQUE;
5428 qc->stream_buf_count = 0;
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005429 memcpy(&qc->local_addr, local_addr, sizeof(qc->local_addr));
5430 memcpy(&qc->peer_addr, peer_addr, sizeof qc->peer_addr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005431
5432 if (server && !qc_lstnr_params_init(qc, &l->bind_conf->quic_params,
5433 icid->stateless_reset_token,
5434 dcid->data, dcid->len,
5435 qc->scid.data, qc->scid.len, token_odcid))
5436 goto err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005437
5438 qc->wait_event.tasklet = tasklet_new();
5439 if (!qc->wait_event.tasklet) {
5440 TRACE_ERROR("tasklet_new() failed", QUIC_EV_CONN_TXPKT);
5441 goto err;
5442 }
5443 qc->wait_event.tasklet->process = quic_conn_io_cb;
5444 qc->wait_event.tasklet->context = qc;
5445 qc->wait_event.events = 0;
5446 /* Set tasklet tid based on the SCID selected by us for this
5447 * connection. The upper layer will also be binded on the same thread.
5448 */
Willy Tarreaueed78262022-12-21 09:09:19 +01005449 qc->tid = quic_get_cid_tid(qc->scid.data, &l->rx);
Willy Tarreauf5a0c8a2022-10-13 16:14:11 +02005450 qc->wait_event.tasklet->tid = qc->tid;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02005451 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005452
5453 if (qc_conn_alloc_ssl_ctx(qc) ||
5454 !quic_conn_init_timer(qc) ||
5455 !quic_conn_init_idle_timer_task(qc))
5456 goto err;
5457
5458 ictx = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
5459 if (!qc_new_isecs(qc, ictx,qc->original_version, dcid->data, dcid->len, 1))
5460 goto err;
5461
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005462 LIST_APPEND(&th_ctx->quic_conns, &qc->el_th_ctx);
5463 qc->qc_epoch = HA_ATOMIC_LOAD(&qc_epoch);
5464
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005465 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc);
5466
5467 return qc;
5468
5469 err:
5470 pool_free(pool_head_quic_conn_rxbuf, buf_area);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005471 if (qc) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005472 qc->rx.buf.area = NULL;
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005473 quic_conn_release(qc);
5474 }
5475 TRACE_LEAVE(QUIC_EV_CONN_INIT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005476 return NULL;
5477}
5478
5479/* Release the quic_conn <qc>. The connection is removed from the CIDs tree.
5480 * The connection tasklet is killed.
5481 *
5482 * This function must only be called by the thread responsible of the quic_conn
5483 * tasklet.
5484 */
5485void quic_conn_release(struct quic_conn *qc)
5486{
5487 int i;
5488 struct ssl_sock_ctx *conn_ctx;
5489 struct eb64_node *node;
5490 struct quic_tls_ctx *app_tls_ctx;
5491 struct quic_rx_packet *pkt, *pktback;
5492
5493 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5494
5495 /* We must not free the quic-conn if the MUX is still allocated. */
5496 BUG_ON(qc->mux_state == QC_MUX_READY);
5497
Amaury Denoyellefb375572023-02-01 09:28:32 +01005498 if (qc_test_fd(qc))
5499 _HA_ATOMIC_DEC(&jobs);
5500
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005501 /* Close quic-conn socket fd. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01005502 qc_release_fd(qc, 0);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005503
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005504 /* in the unlikely (but possible) case the connection was just added to
5505 * the accept_list we must delete it from there.
5506 */
5507 MT_LIST_DELETE(&qc->accept_list);
5508
5509 /* free remaining stream descriptors */
5510 node = eb64_first(&qc->streams_by_id);
5511 while (node) {
5512 struct qc_stream_desc *stream;
5513
5514 stream = eb64_entry(node, struct qc_stream_desc, by_id);
5515 node = eb64_next(node);
5516
5517 /* all streams attached to the quic-conn are released, so
5518 * qc_stream_desc_free will liberate the stream instance.
5519 */
5520 BUG_ON(!stream->release);
5521 qc_stream_desc_free(stream, 1);
5522 }
5523
5524 /* Purge Rx packet list. */
5525 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
5526 LIST_DELETE(&pkt->qc_rx_pkt_list);
5527 pool_free(pool_head_quic_rx_packet, pkt);
5528 }
5529
5530 if (qc->idle_timer_task) {
5531 task_destroy(qc->idle_timer_task);
5532 qc->idle_timer_task = NULL;
5533 }
5534
5535 if (qc->timer_task) {
5536 task_destroy(qc->timer_task);
5537 qc->timer_task = NULL;
5538 }
5539
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005540 if (qc->wait_event.tasklet)
5541 tasklet_free(qc->wait_event.tasklet);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005542
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005543 /* remove the connection from receiver cids trees */
5544 ebmb_delete(&qc->odcid_node);
5545 ebmb_delete(&qc->scid_node);
5546 free_quic_conn_cids(qc);
5547
5548 conn_ctx = qc->xprt_ctx;
5549 if (conn_ctx) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005550 SSL_free(conn_ctx->ssl);
5551 pool_free(pool_head_quic_conn_ctx, conn_ctx);
5552 }
5553
5554 quic_tls_ku_free(qc);
5555 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5556 quic_tls_ctx_secs_free(&qc->els[i].tls_ctx);
5557 quic_conn_enc_level_uninit(qc, &qc->els[i]);
5558 }
5559 quic_tls_ctx_secs_free(&qc->negotiated_ictx);
5560
5561 app_tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
5562 pool_free(pool_head_quic_tls_secret, app_tls_ctx->rx.secret);
5563 pool_free(pool_head_quic_tls_secret, app_tls_ctx->tx.secret);
5564
5565 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++) {
5566 quic_pktns_tx_pkts_release(&qc->pktns[i], qc);
5567 quic_free_arngs(qc, &qc->pktns[i].rx.arngs);
5568 }
5569
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01005570 qc_detach_th_ctx_list(qc, 0);
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005571
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005572 pool_free(pool_head_quic_conn_rxbuf, qc->rx.buf.area);
5573 pool_free(pool_head_quic_conn, qc);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005574
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005575 TRACE_PROTO("QUIC conn. freed", QUIC_EV_CONN_FREED, qc);
5576
5577 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5578}
5579
5580/* Initialize the timer task of <qc> QUIC connection.
5581 * Returns 1 if succeeded, 0 if not.
5582 */
5583static int quic_conn_init_timer(struct quic_conn *qc)
5584{
5585 int ret = 0;
5586 /* Attach this task to the same thread ID used for the connection */
5587 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5588
5589 qc->timer_task = task_new_on(qc->tid);
5590 if (!qc->timer_task) {
5591 TRACE_ERROR("timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5592 goto leave;
5593 }
5594
5595 qc->timer = TICK_ETERNITY;
5596 qc->timer_task->process = qc_process_timer;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005597 qc->timer_task->context = qc;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005598
5599 ret = 1;
5600 leave:
5601 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5602 return ret;
5603}
5604
5605/* Rearm the idle timer for <qc> QUIC connection. */
5606static void qc_idle_timer_do_rearm(struct quic_conn *qc)
5607{
5608 unsigned int expire;
5609
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01005610 if (stopping && qc->flags & (QUIC_FL_CONN_CLOSING|QUIC_FL_CONN_DRAINING)) {
5611 TRACE_STATE("executing idle timer immediately on stopping", QUIC_EV_CONN_IDLE_TIMER, qc);
5612 task_wakeup(qc->idle_timer_task, TASK_WOKEN_MSG);
5613 }
5614 else {
5615 expire = QUIC_MAX(3 * quic_pto(qc), qc->max_idle_timeout);
5616 qc->idle_timer_task->expire = tick_add(now_ms, MS_TO_TICKS(expire));
5617 task_queue(qc->idle_timer_task);
5618 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005619}
5620
5621/* Rearm the idle timer for <qc> QUIC connection depending on <read> boolean
5622 * which is set to 1 when receiving a packet , and 0 when sending packet
5623 */
5624static void qc_idle_timer_rearm(struct quic_conn *qc, int read)
5625{
5626 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5627
5628 if (read) {
5629 qc->flags |= QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5630 }
5631 else {
5632 qc->flags &= ~QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5633 }
5634 qc_idle_timer_do_rearm(qc);
5635
5636 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5637}
5638
5639/* The task handling the idle timeout */
5640struct task *qc_idle_timer_task(struct task *t, void *ctx, unsigned int state)
5641{
5642 struct quic_conn *qc = ctx;
5643 struct quic_counters *prx_counters = qc->prx_counters;
5644 unsigned int qc_flags = qc->flags;
5645
5646 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5647
5648 /* Notify the MUX before settings QUIC_FL_CONN_EXP_TIMER or the MUX
5649 * might free the quic-conn too early via quic_close().
5650 */
5651 qc_notify_close(qc);
5652
5653 /* If the MUX is still alive, keep the quic-conn. The MUX is
5654 * responsible to call quic_close to release it.
5655 */
5656 qc->flags |= QUIC_FL_CONN_EXP_TIMER;
5657 if (qc->mux_state != QC_MUX_READY)
5658 quic_conn_release(qc);
5659
5660 /* TODO if the quic-conn cannot be freed because of the MUX, we may at
5661 * least clean some parts of it such as the tasklet.
5662 */
5663
5664 if (!(qc_flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
5665 qc_flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
5666 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
5667 HA_ATOMIC_DEC(&prx_counters->half_open_conn);
5668 }
5669
5670 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5671 return NULL;
5672}
5673
5674/* Initialize the idle timeout task for <qc>.
5675 * Returns 1 if succeeded, 0 if not.
5676 */
5677static int quic_conn_init_idle_timer_task(struct quic_conn *qc)
5678{
5679 int ret = 0;
5680
5681 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5682
5683 qc->idle_timer_task = task_new_here();
5684 if (!qc->idle_timer_task) {
5685 TRACE_ERROR("Idle timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5686 goto leave;
5687 }
5688
5689 qc->idle_timer_task->process = qc_idle_timer_task;
5690 qc->idle_timer_task->context = qc;
5691 qc_idle_timer_rearm(qc, 1);
5692 task_queue(qc->idle_timer_task);
5693
5694 ret = 1;
5695 leave:
5696 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5697 return ret;
5698}
5699
5700/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
5701 * past one byte of this buffer.
5702 */
5703static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
5704 struct quic_rx_packet *pkt)
5705{
5706 int ret = 0;
5707 unsigned char dcid_len, scid_len;
5708
5709 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5710
5711 if (end == *buf) {
5712 TRACE_ERROR("buffer data consumed", QUIC_EV_CONN_RXPKT);
5713 goto leave;
5714 }
5715
5716 /* Destination Connection ID Length */
5717 dcid_len = *(*buf)++;
5718 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
5719 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1) {
5720 TRACE_ERROR("too long DCID", QUIC_EV_CONN_RXPKT);
5721 goto leave;
5722 }
5723
5724 if (dcid_len) {
5725 /* Check that the length of this received DCID matches the CID lengths
5726 * of our implementation for non Initials packets only.
5727 */
5728 if (pkt->type != QUIC_PACKET_TYPE_INITIAL &&
5729 pkt->type != QUIC_PACKET_TYPE_0RTT &&
5730 dcid_len != QUIC_HAP_CID_LEN) {
5731 TRACE_ERROR("wrong DCID length", QUIC_EV_CONN_RXPKT);
5732 goto leave;
5733 }
5734
5735 memcpy(pkt->dcid.data, *buf, dcid_len);
5736 }
5737
5738 pkt->dcid.len = dcid_len;
5739 *buf += dcid_len;
5740
5741 /* Source Connection ID Length */
5742 scid_len = *(*buf)++;
5743 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len) {
5744 TRACE_ERROR("too long SCID", QUIC_EV_CONN_RXPKT);
5745 goto leave;
5746 }
5747
5748 if (scid_len)
5749 memcpy(pkt->scid.data, *buf, scid_len);
5750 pkt->scid.len = scid_len;
5751 *buf += scid_len;
5752
5753 ret = 1;
5754 leave:
5755 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5756 return ret;
5757}
5758
5759/* Insert <pkt> RX packet in its <qel> RX packets tree */
5760static void qc_pkt_insert(struct quic_conn *qc,
5761 struct quic_rx_packet *pkt, struct quic_enc_level *qel)
5762{
5763 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
5764
5765 pkt->pn_node.key = pkt->pn;
5766 quic_rx_packet_refinc(pkt);
5767 eb64_insert(&qel->rx.pkts, &pkt->pn_node);
5768
5769 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5770}
5771
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005772/* Try to remove the header protection of <pkt> QUIC packet with <beg> the
5773 * address of the packet first byte, using the keys from encryption level <el>.
5774 *
5775 * If header protection has been successfully removed, packet data are copied
5776 * into <qc> Rx buffer. If <el> secrets are not yet available, the copy is also
5777 * proceeded, and the packet is inserted into <qc> protected packets tree. In
5778 * both cases, packet can now be considered handled by the <qc> connection.
5779 *
5780 * If header protection cannot be removed due to <el> secrets already
5781 * discarded, no operation is conducted.
5782 *
5783 * Returns 1 on success : packet data is now handled by the connection. On
5784 * error 0 is returned : packet should be dropped by the caller.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005785 */
5786static inline int qc_try_rm_hp(struct quic_conn *qc,
5787 struct quic_rx_packet *pkt,
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005788 unsigned char *beg,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005789 struct quic_enc_level **el)
5790{
5791 int ret = 0;
5792 unsigned char *pn = NULL; /* Packet number field */
5793 enum quic_tls_enc_level tel;
5794 struct quic_enc_level *qel;
5795 /* Only for traces. */
5796 struct quic_rx_packet *qpkt_trace;
5797
5798 qpkt_trace = NULL;
5799 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005800 BUG_ON(!pkt->pn_offset);
5801
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005802 /* The packet number is here. This is also the start minus
5803 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
5804 * protection.
5805 */
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005806 pn = beg + pkt->pn_offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005807
5808 tel = quic_packet_type_enc_level(pkt->type);
5809 qel = &qc->els[tel];
5810
5811 if (qc_qel_may_rm_hp(qc, qel)) {
Frédéric Lécaille72027782023-02-22 16:20:09 +01005812 struct quic_tls_ctx *tls_ctx = qc_select_tls_ctx(qc, qel, pkt);
5813
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005814 /* Note that the following function enables us to unprotect the packet
5815 * number and its length subsequently used to decrypt the entire
5816 * packets.
5817 */
Frédéric Lécaille72027782023-02-22 16:20:09 +01005818 if (!qc_do_rm_hp(qc, pkt, tls_ctx,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005819 qel->pktns->rx.largest_pn, pn, beg)) {
5820 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, qc);
5821 goto out;
5822 }
5823
Frédéric Lécailleece86e62023-03-07 11:53:43 +01005824 qc_handle_spin_bit(qc, pkt, qel);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005825 /* The AAD includes the packet number field. */
5826 pkt->aad_len = pkt->pn_offset + pkt->pnl;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005827 if (pkt->len - pkt->aad_len < QUIC_TLS_TAG_LEN) {
5828 TRACE_PROTO("Too short packet", QUIC_EV_CONN_TRMHP, qc);
5829 goto out;
5830 }
5831
5832 qpkt_trace = pkt;
5833 }
5834 else {
5835 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
5836 /* If the packet number space has been discarded, this packet
5837 * will be not parsed.
5838 */
5839 TRACE_PROTO("Discarded pktns", QUIC_EV_CONN_TRMHP, qc, pkt);
5840 goto out;
5841 }
5842
5843 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005844 LIST_APPEND(&qel->rx.pqpkts, &pkt->list);
5845 quic_rx_packet_refinc(pkt);
5846 }
5847
5848 *el = qel;
5849 /* No reference counter incrementation here!!! */
5850 LIST_APPEND(&qc->rx.pkt_list, &pkt->qc_rx_pkt_list);
5851 memcpy(b_tail(&qc->rx.buf), beg, pkt->len);
5852 pkt->data = (unsigned char *)b_tail(&qc->rx.buf);
5853 b_add(&qc->rx.buf, pkt->len);
5854
5855 ret = 1;
5856 out:
5857 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc, qpkt_trace);
5858 return ret;
5859}
5860
5861/* Parse the header form from <byte0> first byte of <pkt> packet to set its type.
5862 * Also set <*long_header> to 1 if this form is long, 0 if not and the version
5863 * of this packet into <*version>.
5864 */
5865static inline int qc_parse_hd_form(struct quic_rx_packet *pkt,
5866 unsigned char **buf, const unsigned char *end,
5867 int *long_header, uint32_t *version)
5868{
5869 int ret = 0;
5870 const unsigned char byte0 = **buf;
5871
5872 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5873
5874 (*buf)++;
5875 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
5876 unsigned char type =
5877 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
5878
5879 *long_header = 1;
5880 /* Version */
5881 if (!quic_read_uint32(version, (const unsigned char **)buf, end)) {
5882 TRACE_ERROR("could not read the packet version", QUIC_EV_CONN_RXPKT);
5883 goto out;
5884 }
5885
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +01005886 if (*version != QUIC_PROTOCOL_VERSION_2) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005887 pkt->type = type;
5888 }
5889 else {
5890 switch (type) {
5891 case 0:
5892 pkt->type = QUIC_PACKET_TYPE_RETRY;
5893 break;
5894 case 1:
5895 pkt->type = QUIC_PACKET_TYPE_INITIAL;
5896 break;
5897 case 2:
5898 pkt->type = QUIC_PACKET_TYPE_0RTT;
5899 break;
5900 case 3:
5901 pkt->type = QUIC_PACKET_TYPE_HANDSHAKE;
5902 break;
5903 }
5904 }
5905 }
5906 else {
Frédéric Lécailleece86e62023-03-07 11:53:43 +01005907 if (byte0 & QUIC_PACKET_SPIN_BIT)
5908 pkt->flags |= QUIC_FL_RX_PACKET_SPIN_BIT;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005909 pkt->type = QUIC_PACKET_TYPE_SHORT;
5910 *long_header = 0;
5911 }
5912
5913 ret = 1;
5914 out:
5915 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5916 return ret;
5917}
5918
5919/* Return the QUIC version (quic_version struct) with <version> as version number
5920 * if supported or NULL if not.
5921 */
5922static inline const struct quic_version *qc_supported_version(uint32_t version)
5923{
5924 int i;
5925
5926 for (i = 0; i < quic_versions_nb; i++)
5927 if (quic_versions[i].num == version)
5928 return &quic_versions[i];
5929
5930 return NULL;
5931}
5932
5933/*
5934 * Send a Version Negotiation packet on response to <pkt> on socket <fd> to
5935 * address <addr>.
5936 * Implementation of RFC9000 6. Version Negotiation
5937 *
5938 * TODO implement a rate-limiting sending of Version Negotiation packets
5939 *
5940 * Returns 0 on success else non-zero
5941 */
5942static int send_version_negotiation(int fd, struct sockaddr_storage *addr,
5943 struct quic_rx_packet *pkt)
5944{
5945 char buf[256];
5946 int ret = 0, i = 0, j;
5947 uint32_t version;
5948 const socklen_t addrlen = get_addr_len(addr);
5949
5950 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5951 /*
5952 * header form
5953 * long header, fixed bit to 0 for Version Negotiation
5954 */
5955 /* TODO: RAND_bytes() should be replaced? */
5956 if (RAND_bytes((unsigned char *)buf, 1) != 1) {
5957 TRACE_ERROR("RAND_bytes() error", QUIC_EV_CONN_TXPKT);
5958 goto out;
5959 }
5960
5961 buf[i++] |= '\x80';
5962 /* null version for Version Negotiation */
5963 buf[i++] = '\x00';
5964 buf[i++] = '\x00';
5965 buf[i++] = '\x00';
5966 buf[i++] = '\x00';
5967
5968 /* source connection id */
5969 buf[i++] = pkt->scid.len;
5970 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5971 i += pkt->scid.len;
5972
5973 /* destination connection id */
5974 buf[i++] = pkt->dcid.len;
5975 memcpy(&buf[i], pkt->dcid.data, pkt->dcid.len);
5976 i += pkt->dcid.len;
5977
5978 /* supported version */
5979 for (j = 0; j < quic_versions_nb; j++) {
5980 version = htonl(quic_versions[j].num);
5981 memcpy(&buf[i], &version, sizeof(version));
5982 i += sizeof(version);
5983 }
5984
5985 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0)
5986 goto out;
5987
5988 ret = 1;
5989 out:
5990 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5991 return !ret;
5992}
5993
5994/* Send a stateless reset packet depending on <pkt> RX packet information
5995 * from <fd> UDP socket to <dst>
5996 * Return 1 if succeeded, 0 if not.
5997 */
5998static int send_stateless_reset(struct listener *l, struct sockaddr_storage *dstaddr,
5999 struct quic_rx_packet *rxpkt)
6000{
6001 int ret = 0, pktlen, rndlen;
6002 unsigned char pkt[64];
6003 const socklen_t addrlen = get_addr_len(dstaddr);
6004 struct proxy *prx;
6005 struct quic_counters *prx_counters;
6006
6007 TRACE_ENTER(QUIC_EV_STATELESS_RST);
6008
6009 prx = l->bind_conf->frontend;
6010 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6011 /* 10.3 Stateless Reset (https://www.rfc-editor.org/rfc/rfc9000.html#section-10.3)
6012 * The resulting minimum size of 21 bytes does not guarantee that a Stateless
6013 * Reset is difficult to distinguish from other packets if the recipient requires
6014 * the use of a connection ID. To achieve that end, the endpoint SHOULD ensure
6015 * that all packets it sends are at least 22 bytes longer than the minimum
6016 * connection ID length that it requests the peer to include in its packets,
6017 * adding PADDING frames as necessary. This ensures that any Stateless Reset
6018 * sent by the peer is indistinguishable from a valid packet sent to the endpoint.
6019 * An endpoint that sends a Stateless Reset in response to a packet that is
6020 * 43 bytes or shorter SHOULD send a Stateless Reset that is one byte shorter
6021 * than the packet it responds to.
6022 */
6023
6024 /* Note that we build at most a 42 bytes QUIC packet to mimic a short packet */
6025 pktlen = rxpkt->len <= 43 ? rxpkt->len - 1 : 0;
6026 pktlen = QUIC_MAX(QUIC_STATELESS_RESET_PACKET_MINLEN, pktlen);
6027 rndlen = pktlen - QUIC_STATELESS_RESET_TOKEN_LEN;
6028
6029 /* Put a header of random bytes */
6030 /* TODO: RAND_bytes() should be replaced */
6031 if (RAND_bytes(pkt, rndlen) != 1) {
6032 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_STATELESS_RST);
6033 goto leave;
6034 }
6035
6036 /* Clear the most significant bit, and set the second one */
6037 *pkt = (*pkt & ~0x80) | 0x40;
6038 if (!quic_stateless_reset_token_cpy(NULL, pkt + rndlen, QUIC_STATELESS_RESET_TOKEN_LEN,
6039 rxpkt->dcid.data, rxpkt->dcid.len))
6040 goto leave;
6041
6042 if (sendto(l->rx.fd, pkt, pktlen, 0, (struct sockaddr *)dstaddr, addrlen) < 0)
6043 goto leave;
6044
6045 ret = 1;
6046 HA_ATOMIC_INC(&prx_counters->stateless_reset_sent);
6047 TRACE_PROTO("stateless reset sent", QUIC_EV_STATELESS_RST, NULL, &rxpkt->dcid);
6048 leave:
6049 TRACE_LEAVE(QUIC_EV_STATELESS_RST);
6050 return ret;
6051}
6052
6053/* QUIC server only function.
6054 * Add AAD to <add> buffer from <cid> connection ID and <addr> socket address.
6055 * This is the responsibility of the caller to check <aad> size is big enough
6056 * to contain these data.
6057 * Return the number of bytes copied to <aad>.
6058 */
6059static int quic_generate_retry_token_aad(unsigned char *aad,
6060 uint32_t version,
6061 const struct quic_cid *cid,
6062 const struct sockaddr_storage *addr)
6063{
6064 unsigned char *p;
6065
6066 p = aad;
6067 memcpy(p, &version, sizeof version);
6068 p += sizeof version;
6069 p += quic_saddr_cpy(p, addr);
6070 memcpy(p, cid->data, cid->len);
6071 p += cid->len;
6072
6073 return p - aad;
6074}
6075
6076/* QUIC server only function.
6077 * Generate the token to be used in Retry packets. The token is written to
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006078 * <buf> with <len> as length. <odcid> is the original destination connection
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006079 * ID and <dcid> is our side destination connection ID (or client source
6080 * connection ID).
6081 * Returns the length of the encoded token or 0 on error.
6082 */
6083static int quic_generate_retry_token(unsigned char *buf, size_t len,
6084 const uint32_t version,
6085 const struct quic_cid *odcid,
6086 const struct quic_cid *dcid,
6087 struct sockaddr_storage *addr)
6088{
6089 int ret = 0;
6090 unsigned char *p;
6091 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02006092 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006093 size_t aadlen;
6094 unsigned char salt[QUIC_RETRY_TOKEN_SALTLEN];
6095 unsigned char key[QUIC_TLS_KEY_LEN];
6096 unsigned char iv[QUIC_TLS_IV_LEN];
6097 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
6098 size_t seclen = strlen(global.cluster_secret);
6099 EVP_CIPHER_CTX *ctx = NULL;
6100 const EVP_CIPHER *aead = EVP_aes_128_gcm();
6101 uint32_t timestamp = now_ms;
6102
6103 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
6104
6105 /* We copy the odcid into the token, prefixed by its one byte
6106 * length, the format token byte. It is followed by an AEAD TAG, and finally
6107 * the random bytes used to derive the secret to encrypt the token.
6108 */
6109 if (1 + dcid->len + 1 + QUIC_TLS_TAG_LEN + sizeof salt > len)
6110 goto err;
6111
6112 aadlen = quic_generate_retry_token_aad(aad, version, dcid, addr);
6113 /* TODO: RAND_bytes() should be replaced */
6114 if (RAND_bytes(salt, sizeof salt) != 1) {
6115 TRACE_ERROR("RAND_bytes()", QUIC_EV_CONN_TXPKT);
6116 goto err;
6117 }
6118
6119 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
6120 salt, sizeof salt, sec, seclen)) {
6121 TRACE_ERROR("quic_tls_derive_retry_token_secret() failed", QUIC_EV_CONN_TXPKT);
6122 goto err;
6123 }
6124
6125 if (!quic_tls_tx_ctx_init(&ctx, aead, key)) {
6126 TRACE_ERROR("quic_tls_tx_ctx_init() failed", QUIC_EV_CONN_TXPKT);
6127 goto err;
6128 }
6129
6130 /* Token build */
6131 p = buf;
6132 *p++ = QUIC_TOKEN_FMT_RETRY,
6133 *p++ = odcid->len;
6134 memcpy(p, odcid->data, odcid->len);
6135 p += odcid->len;
6136 write_u32(p, htonl(timestamp));
6137 p += sizeof timestamp;
6138
6139 /* Do not encrypt the QUIC_TOKEN_FMT_RETRY byte */
6140 if (!quic_tls_encrypt(buf + 1, p - buf - 1, aad, aadlen, ctx, aead, key, iv)) {
6141 TRACE_ERROR("quic_tls_encrypt() failed", QUIC_EV_CONN_TXPKT);
6142 goto err;
6143 }
6144
6145 p += QUIC_TLS_TAG_LEN;
6146 memcpy(p, salt, sizeof salt);
6147 p += sizeof salt;
6148 EVP_CIPHER_CTX_free(ctx);
6149
6150 ret = p - buf;
6151 leave:
6152 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
6153 return ret;
6154
6155 err:
6156 if (ctx)
6157 EVP_CIPHER_CTX_free(ctx);
6158 goto leave;
6159}
6160
6161/* QUIC server only function.
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006162 *
6163 * Check the validity of the Retry token from Initial packet <pkt>. <dgram> is
6164 * the UDP datagram containing <pkt> and <l> is the listener instance on which
6165 * it was received. If the token is valid, the ODCID of <qc> QUIC connection
6166 * will be put into <odcid>. <qc> is used to retrieve the QUIC version needed
6167 * to validate the token but it can be NULL : in this case the version will be
6168 * retrieved from the packet.
6169 *
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006170 * Return 1 if succeeded, 0 if not.
6171 */
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006172
6173static int quic_retry_token_check(struct quic_rx_packet *pkt,
6174 struct quic_dgram *dgram,
6175 struct listener *l,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006176 struct quic_conn *qc,
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006177 struct quic_cid *odcid)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006178{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006179 struct proxy *prx;
6180 struct quic_counters *prx_counters;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006181 int ret = 0;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006182 unsigned char *token = pkt->token;
6183 const uint64_t tokenlen = pkt->token_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006184 unsigned char buf[128];
6185 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02006186 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006187 size_t aadlen;
6188 const unsigned char *salt;
6189 unsigned char key[QUIC_TLS_KEY_LEN];
6190 unsigned char iv[QUIC_TLS_IV_LEN];
6191 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
6192 size_t seclen = strlen(global.cluster_secret);
6193 EVP_CIPHER_CTX *ctx = NULL;
6194 const EVP_CIPHER *aead = EVP_aes_128_gcm();
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006195 const struct quic_version *qv = qc ? qc->original_version :
6196 pkt->version;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006197
6198 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6199
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006200 /* The caller must ensure this. */
6201 BUG_ON(!global.cluster_secret || !pkt->token_len);
6202
6203 prx = l->bind_conf->frontend;
6204 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6205
6206 if (*pkt->token != QUIC_TOKEN_FMT_RETRY) {
6207 /* TODO: New token check */
6208 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6209 goto leave;
6210 }
6211
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006212 if (sizeof buf < tokenlen) {
6213 TRACE_ERROR("too short buffer", QUIC_EV_CONN_LPKT, qc);
6214 goto err;
6215 }
6216
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006217 aadlen = quic_generate_retry_token_aad(aad, qv->num, &pkt->scid, &dgram->saddr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006218 salt = token + tokenlen - QUIC_RETRY_TOKEN_SALTLEN;
6219 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
6220 salt, QUIC_RETRY_TOKEN_SALTLEN, sec, seclen)) {
6221 TRACE_ERROR("Could not derive retry secret", QUIC_EV_CONN_LPKT, qc);
6222 goto err;
6223 }
6224
6225 if (!quic_tls_rx_ctx_init(&ctx, aead, key)) {
6226 TRACE_ERROR("quic_tls_rx_ctx_init() failed", QUIC_EV_CONN_LPKT, qc);
6227 goto err;
6228 }
6229
6230 /* Do not decrypt the QUIC_TOKEN_FMT_RETRY byte */
6231 if (!quic_tls_decrypt2(buf, token + 1, tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, aad, aadlen,
6232 ctx, aead, key, iv)) {
6233 TRACE_ERROR("Could not decrypt retry token", QUIC_EV_CONN_LPKT, qc);
6234 goto err;
6235 }
6236
6237 if (parse_retry_token(qc, buf, buf + tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, odcid)) {
6238 TRACE_ERROR("Error during Initial token parsing", QUIC_EV_CONN_LPKT, qc);
6239 goto err;
6240 }
6241
6242 EVP_CIPHER_CTX_free(ctx);
6243
6244 ret = 1;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006245 HA_ATOMIC_INC(&prx_counters->retry_validated);
6246
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006247 leave:
6248 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6249 return ret;
6250
6251 err:
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006252 HA_ATOMIC_INC(&prx_counters->retry_error);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006253 if (ctx)
6254 EVP_CIPHER_CTX_free(ctx);
6255 goto leave;
6256}
6257
6258/* Generate a Retry packet and send it on <fd> socket to <addr> in response to
6259 * the Initial <pkt> packet.
6260 *
6261 * Returns 0 on success else non-zero.
6262 */
6263static int send_retry(int fd, struct sockaddr_storage *addr,
6264 struct quic_rx_packet *pkt, const struct quic_version *qv)
6265{
6266 int ret = 0;
6267 unsigned char buf[128];
6268 int i = 0, token_len;
6269 const socklen_t addrlen = get_addr_len(addr);
6270 struct quic_cid scid;
6271
6272 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
6273
6274 /* long header + fixed bit + packet type QUIC_PACKET_TYPE_RETRY */
6275 buf[i++] = (QUIC_PACKET_LONG_HEADER_BIT | QUIC_PACKET_FIXED_BIT) |
6276 (quic_pkt_type(QUIC_PACKET_TYPE_RETRY, qv->num) << QUIC_PACKET_TYPE_SHIFT);
6277 /* version */
6278 buf[i++] = *((unsigned char *)&qv->num + 3);
6279 buf[i++] = *((unsigned char *)&qv->num + 2);
6280 buf[i++] = *((unsigned char *)&qv->num + 1);
6281 buf[i++] = *(unsigned char *)&qv->num;
6282
6283 /* Use the SCID from <pkt> for Retry DCID. */
6284 buf[i++] = pkt->scid.len;
6285 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
6286 i += pkt->scid.len;
6287
6288 /* Generate a new CID to be used as SCID for the Retry packet. */
6289 scid.len = QUIC_HAP_CID_LEN;
6290 /* TODO: RAND_bytes() should be replaced */
6291 if (RAND_bytes(scid.data, scid.len) != 1) {
6292 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT);
6293 goto out;
6294 }
6295
6296 buf[i++] = scid.len;
6297 memcpy(&buf[i], scid.data, scid.len);
6298 i += scid.len;
6299
6300 /* token */
6301 if (!(token_len = quic_generate_retry_token(&buf[i], sizeof(buf) - i, qv->num,
6302 &pkt->dcid, &pkt->scid, addr))) {
6303 TRACE_ERROR("quic_generate_retry_token() failed", QUIC_EV_CONN_TXPKT);
6304 goto out;
6305 }
6306
6307 i += token_len;
6308
6309 /* token integrity tag */
6310 if ((&buf[i] - buf < QUIC_TLS_TAG_LEN) ||
6311 !quic_tls_generate_retry_integrity_tag(pkt->dcid.data,
6312 pkt->dcid.len, buf, i, qv)) {
6313 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
6314 goto out;
6315 }
6316
6317 i += QUIC_TLS_TAG_LEN;
6318
6319 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0) {
6320 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
6321 goto out;
6322 }
6323
6324 ret = 1;
6325 out:
6326 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
6327 return !ret;
6328}
6329
6330/* Retrieve a quic_conn instance from the <pkt> DCID field. If the packet is of
6331 * type INITIAL, the ODCID tree is first used. In this case, <saddr> is
6332 * concatenated to the <pkt> DCID field.
6333 *
6334 * Returns the instance or NULL if not found.
6335 */
6336static struct quic_conn *retrieve_qc_conn_from_cid(struct quic_rx_packet *pkt,
6337 struct listener *l,
6338 struct sockaddr_storage *saddr)
6339{
6340 struct quic_conn *qc = NULL;
6341 struct ebmb_node *node;
6342 struct quic_connection_id *id;
6343 /* set if the quic_conn is found in the second DCID tree */
6344
6345 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
6346
6347 /* Look first into ODCIDs tree for INITIAL/0-RTT packets. */
6348 if (pkt->type == QUIC_PACKET_TYPE_INITIAL ||
6349 pkt->type == QUIC_PACKET_TYPE_0RTT) {
6350 /* DCIDs of first packets coming from multiple clients may have
6351 * the same values. Let's distinguish them by concatenating the
6352 * socket addresses.
6353 */
6354 quic_cid_saddr_cat(&pkt->dcid, saddr);
6355 node = ebmb_lookup(&quic_dghdlrs[tid].odcids, pkt->dcid.data,
6356 pkt->dcid.len + pkt->dcid.addrlen);
6357 if (node) {
6358 qc = ebmb_entry(node, struct quic_conn, odcid_node);
6359 goto end;
6360 }
6361 }
6362
6363 /* Look into DCIDs tree for non-INITIAL/0-RTT packets. This may be used
6364 * also for INITIAL/0-RTT non-first packets with the final DCID in
6365 * used.
6366 */
6367 node = ebmb_lookup(&quic_dghdlrs[tid].cids, pkt->dcid.data, pkt->dcid.len);
6368 if (!node)
6369 goto end;
6370
6371 id = ebmb_entry(node, struct quic_connection_id, node);
6372 qc = id->qc;
6373
6374 /* If found in DCIDs tree, remove the quic_conn from the ODCIDs tree.
6375 * If already done, this is a noop.
6376 */
6377 if (qc)
6378 ebmb_delete(&qc->odcid_node);
6379
6380 end:
6381 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
6382 return qc;
6383}
6384
6385/* Try to allocate the <*ssl> SSL session object for <qc> QUIC connection
6386 * with <ssl_ctx> as SSL context inherited settings. Also set the transport
6387 * parameters of this session.
6388 * This is the responsibility of the caller to check the validity of all the
6389 * pointers passed as parameter to this function.
6390 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <qc->conn> to
6391 * CO_ER_SSL_NO_MEM.
6392 */
6393static int qc_ssl_sess_init(struct quic_conn *qc, SSL_CTX *ssl_ctx, SSL **ssl,
6394 unsigned char *params, size_t params_len)
6395{
6396 int retry, ret = -1;
6397
6398 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6399
6400 retry = 1;
6401 retry:
6402 *ssl = SSL_new(ssl_ctx);
6403 if (!*ssl) {
6404 if (!retry--)
6405 goto err;
6406
6407 pool_gc(NULL);
6408 goto retry;
6409 }
6410
6411 if (!SSL_set_quic_method(*ssl, &ha_quic_method) ||
6412 !SSL_set_ex_data(*ssl, ssl_qc_app_data_index, qc)) {
6413 SSL_free(*ssl);
6414 *ssl = NULL;
6415 if (!retry--)
6416 goto err;
6417
6418 pool_gc(NULL);
6419 goto retry;
6420 }
6421
6422 ret = 0;
6423 leave:
6424 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6425 return ret;
6426
6427 err:
6428 qc->conn->err_code = CO_ER_SSL_NO_MEM;
6429 goto leave;
6430}
6431
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006432/* Allocate the ssl_sock_ctx from connection <qc>. This creates the tasklet
6433 * used to process <qc> received packets. The allocated context is stored in
6434 * <qc.xprt_ctx>.
6435 *
6436 * Returns 0 on success else non-zero.
6437 */
6438static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc)
6439{
6440 int ret = 0;
6441 struct bind_conf *bc = qc->li->bind_conf;
6442 struct ssl_sock_ctx *ctx = NULL;
6443
6444 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6445
6446 ctx = pool_zalloc(pool_head_quic_conn_ctx);
6447 if (!ctx) {
6448 TRACE_ERROR("SSL context allocation failed", QUIC_EV_CONN_TXPKT);
6449 goto err;
6450 }
6451
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006452 ctx->subs = NULL;
6453 ctx->xprt_ctx = NULL;
6454 ctx->qc = qc;
6455
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006456 if (qc_is_listener(qc)) {
6457 if (qc_ssl_sess_init(qc, bc->initial_ctx, &ctx->ssl,
6458 qc->enc_params, qc->enc_params_len) == -1) {
6459 goto err;
6460 }
6461#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
6462 /* Enabling 0-RTT */
6463 if (bc->ssl_conf.early_data)
6464 SSL_set_quic_early_data_enabled(ctx->ssl, 1);
6465#endif
6466
6467 SSL_set_accept_state(ctx->ssl);
6468 }
6469
6470 ctx->xprt = xprt_get(XPRT_QUIC);
6471
6472 /* Store the allocated context in <qc>. */
6473 qc->xprt_ctx = ctx;
6474
6475 ret = 1;
6476 leave:
6477 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6478 return !ret;
6479
6480 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006481 pool_free(pool_head_quic_conn_ctx, ctx);
6482 goto leave;
6483}
6484
6485/* Check that all the bytes between <buf> included and <end> address
6486 * excluded are null. This is the responsibility of the caller to
6487 * check that there is at least one byte between <buf> end <end>.
6488 * Return 1 if this all the bytes are null, 0 if not.
6489 */
6490static inline int quic_padding_check(const unsigned char *buf,
6491 const unsigned char *end)
6492{
6493 while (buf < end && !*buf)
6494 buf++;
6495
6496 return buf == end;
6497}
6498
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006499/* Find the associated connection to the packet <pkt> or create a new one if
6500 * this is an Initial packet. <dgram> is the datagram containing the packet and
6501 * <l> is the listener instance on which it was received.
6502 *
6503 * Returns the quic-conn instance or NULL.
6504 */
6505static struct quic_conn *quic_rx_pkt_retrieve_conn(struct quic_rx_packet *pkt,
6506 struct quic_dgram *dgram,
6507 struct listener *l)
6508{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006509 struct quic_cid token_odcid = { .len = 0 };
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006510 struct quic_conn *qc = NULL;
6511 struct proxy *prx;
6512 struct quic_counters *prx_counters;
6513
6514 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6515
6516 prx = l->bind_conf->frontend;
6517 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6518
6519 qc = retrieve_qc_conn_from_cid(pkt, l, &dgram->saddr);
6520
6521 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6522 BUG_ON(!pkt->version); /* This must not happen. */
6523
6524 if (global.cluster_secret && pkt->token_len) {
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006525 if (!quic_retry_token_check(pkt, dgram, l, qc, &token_odcid))
6526 goto err;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006527 }
6528
6529 if (!qc) {
6530 int ipv4;
6531
6532 if (global.cluster_secret && !pkt->token_len && !(l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) &&
6533 HA_ATOMIC_LOAD(&prx_counters->half_open_conn) >= global.tune.quic_retry_threshold) {
6534 TRACE_PROTO("Initial without token, sending retry",
6535 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6536 if (send_retry(l->rx.fd, &dgram->saddr, pkt, pkt->version)) {
6537 TRACE_ERROR("Error during Retry generation",
6538 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6539 goto out;
6540 }
6541
6542 HA_ATOMIC_INC(&prx_counters->retry_sent);
6543 goto out;
6544 }
6545
6546 /* RFC 9000 7.2. Negotiating Connection IDs:
6547 * When an Initial packet is sent by a client that has not previously
6548 * received an Initial or Retry packet from the server, the client
6549 * populates the Destination Connection ID field with an unpredictable
6550 * value. This Destination Connection ID MUST be at least 8 bytes in length.
6551 */
6552 if (pkt->dcid.len < QUIC_ODCID_MINLEN) {
6553 TRACE_PROTO("dropped packet",
6554 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6555 goto err;
6556 }
6557
6558 pkt->saddr = dgram->saddr;
6559 ipv4 = dgram->saddr.ss_family == AF_INET;
6560
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006561 qc = qc_new_conn(pkt->version, ipv4, &pkt->dcid, &pkt->scid, &token_odcid,
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006562 &dgram->daddr, &pkt->saddr, 1,
6563 !!pkt->token_len, l);
6564 if (qc == NULL)
6565 goto err;
6566
6567 HA_ATOMIC_INC(&prx_counters->half_open_conn);
6568 /* Insert the DCID the QUIC client has chosen (only for listeners) */
6569 ebmb_insert(&quic_dghdlrs[tid].odcids, &qc->odcid_node,
6570 qc->odcid.len + qc->odcid.addrlen);
6571 }
6572 }
6573 else if (!qc) {
6574 TRACE_PROTO("No connection on a non Initial packet", QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6575 if (global.cluster_secret && !send_stateless_reset(l, &dgram->saddr, pkt))
6576 TRACE_ERROR("stateless reset not sent", QUIC_EV_CONN_LPKT, qc);
6577 goto err;
6578 }
6579
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006580 out:
6581 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6582 return qc;
6583
6584 err:
6585 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
6586 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
6587 return NULL;
6588}
6589
Amaury Denoyelle98289692022-10-19 15:37:44 +02006590/* Parse a QUIC packet starting at <buf>. Data won't be read after <end> even
6591 * if the packet is incomplete. This function will populate fields of <pkt>
6592 * instance, most notably its length. <dgram> is the UDP datagram which
6593 * contains the parsed packet. <l> is the listener instance on which it was
6594 * received.
6595 *
6596 * Returns 0 on success else non-zero. Packet length is guaranteed to be set to
6597 * the real packet value or to cover all data between <buf> and <end> : this is
6598 * useful to reject a whole datagram.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006599 */
Amaury Denoyelle98289692022-10-19 15:37:44 +02006600static int quic_rx_pkt_parse(struct quic_rx_packet *pkt,
6601 unsigned char *buf, const unsigned char *end,
6602 struct quic_dgram *dgram, struct listener *l)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006603{
Amaury Denoyelle98289692022-10-19 15:37:44 +02006604 const unsigned char *beg = buf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006605 struct proxy *prx;
6606 struct quic_counters *prx_counters;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006607 int long_header = 0;
Willy Tarreau33a68702022-11-24 09:16:41 +01006608 uint32_t version = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006609 const struct quic_version *qv = NULL;
6610
6611 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6612
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006613 prx = l->bind_conf->frontend;
6614 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6615 /* This ist only to please to traces and distinguish the
6616 * packet with parsed packet number from others.
6617 */
6618 pkt->pn_node.key = (uint64_t)-1;
6619 if (end <= buf) {
6620 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6621 goto drop;
6622 }
6623
6624 /* Fixed bit */
6625 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006626 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
6627 quic_padding_check(buf, end)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006628 /* Some browsers may pad the remaining datagram space with null bytes.
6629 * That is what we called add padding out of QUIC packets. Such
6630 * datagrams must be considered as valid. But we can only consume
6631 * the remaining space.
6632 */
6633 pkt->len = end - buf;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006634 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006635 }
6636
6637 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6638 goto drop;
6639 }
6640
6641 /* Header form */
6642 if (!qc_parse_hd_form(pkt, &buf, end, &long_header, &version)) {
6643 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6644 goto drop;
6645 }
6646
6647 if (long_header) {
6648 uint64_t len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006649
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006650 TRACE_PROTO("long header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006651 if (!quic_packet_read_long_header(&buf, end, pkt)) {
6652 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6653 goto drop;
6654 }
6655
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006656 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6657 * they must have the same DCID.
6658 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006659 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006660 (pkt->dcid.len != dgram->dcid_len ||
6661 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006662 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006663 goto drop;
6664 }
6665
6666 /* Retry of Version Negotiation packets are only sent by servers */
6667 if (pkt->type == QUIC_PACKET_TYPE_RETRY || !version) {
6668 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6669 goto drop;
6670 }
6671
6672 /* RFC9000 6. Version Negotiation */
6673 qv = qc_supported_version(version);
6674 if (!qv) {
6675 /* unsupported version, send Negotiation packet */
6676 if (send_version_negotiation(l->rx.fd, &dgram->saddr, pkt)) {
6677 TRACE_ERROR("VN packet not sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006678 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006679 }
6680
6681 TRACE_PROTO("VN packet sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006682 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006683 }
Amaury Denoyelle0eae5722022-10-17 18:05:18 +02006684 pkt->version = qv;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006685
6686 /* For Initial packets, and for servers (QUIC clients connections),
6687 * there is no Initial connection IDs storage.
6688 */
6689 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6690 uint64_t token_len;
6691
6692 if (!quic_dec_int(&token_len, (const unsigned char **)&buf, end) ||
6693 end - buf < token_len) {
6694 TRACE_PROTO("Packet dropped",
6695 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6696 goto drop;
6697 }
6698
6699 /* TODO Retry should be automatically activated if
6700 * suspect network usage is detected.
6701 */
6702 if (global.cluster_secret && !token_len) {
6703 if (l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) {
6704 TRACE_PROTO("Initial without token, sending retry",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006705 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006706 if (send_retry(l->rx.fd, &dgram->saddr, pkt, qv)) {
6707 TRACE_PROTO("Error during Retry generation",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006708 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006709 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006710 }
6711
6712 HA_ATOMIC_INC(&prx_counters->retry_sent);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006713 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006714 }
6715 }
6716 else if (!global.cluster_secret && token_len) {
6717 /* Impossible case: a token was received without configured
6718 * cluster secret.
6719 */
6720 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT,
6721 NULL, NULL, NULL, qv);
6722 goto drop;
6723 }
6724
6725 pkt->token = buf;
6726 pkt->token_len = token_len;
6727 buf += pkt->token_len;
6728 }
6729 else if (pkt->type != QUIC_PACKET_TYPE_0RTT) {
6730 if (pkt->dcid.len != QUIC_HAP_CID_LEN) {
6731 TRACE_PROTO("Packet dropped",
6732 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6733 goto drop;
6734 }
6735 }
6736
6737 if (!quic_dec_int(&len, (const unsigned char **)&buf, end) ||
6738 end - buf < len) {
6739 TRACE_PROTO("Packet dropped",
6740 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6741 goto drop;
6742 }
6743
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006744 /* Packet Number is stored here. Packet Length totalizes the
6745 * rest of the content.
6746 */
6747 pkt->pn_offset = buf - beg;
6748 pkt->len = pkt->pn_offset + len;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006749
Frédéric Lécaille35218c62023-02-16 11:40:11 +01006750 /* RFC 9000. Initial Datagram Size
6751 *
6752 * A server MUST discard an Initial packet that is carried in a UDP datagram
6753 * with a payload that is smaller than the smallest allowed maximum datagram
6754 * size of 1200 bytes.
6755 */
6756 if (pkt->type == QUIC_PACKET_TYPE_INITIAL &&
6757 dgram->len < QUIC_INITIAL_PACKET_MINLEN) {
6758 TRACE_PROTO("Too short datagram with an Initial packet", QUIC_EV_CONN_LPKT);
6759 HA_ATOMIC_INC(&prx_counters->too_short_initial_dgram);
6760 goto drop;
6761 }
6762
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006763 /* Interrupt parsing after packet length retrieval : this
6764 * ensures that only the packet is dropped but not the whole
6765 * datagram.
6766 */
6767 if (pkt->type == QUIC_PACKET_TYPE_0RTT && !l->bind_conf->ssl_conf.early_data) {
6768 TRACE_PROTO("0-RTT packet not supported", QUIC_EV_CONN_LPKT);
6769 goto drop;
6770 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006771 }
6772 else {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006773 TRACE_PROTO("short header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006774 if (end - buf < QUIC_HAP_CID_LEN) {
6775 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6776 goto drop;
6777 }
6778
6779 memcpy(pkt->dcid.data, buf, QUIC_HAP_CID_LEN);
6780 pkt->dcid.len = QUIC_HAP_CID_LEN;
6781
6782 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6783 * they must have the same DCID.
6784 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006785 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006786 (pkt->dcid.len != dgram->dcid_len ||
6787 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006788 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006789 goto drop;
6790 }
6791
6792 buf += QUIC_HAP_CID_LEN;
6793
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006794 pkt->pn_offset = buf - beg;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006795 /* A short packet is the last one of a UDP datagram. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006796 pkt->len = end - beg;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006797 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006798
Amaury Denoyelle98289692022-10-19 15:37:44 +02006799 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6800 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006801
Amaury Denoyelle98289692022-10-19 15:37:44 +02006802 drop:
6803 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006804 drop_silent:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006805 if (!pkt->len)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006806 pkt->len = end - beg;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006807 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6808 return -1;
6809}
6810
6811/* Check if received packet <pkt> should be drop due to <qc> already in closing
6812 * state. This can be true if a CONNECTION_CLOSE has already been emitted for
6813 * this connection.
6814 *
6815 * Returns false if connection is not in closing state else true. The caller
6816 * should drop the whole datagram in the last case to not mess up <qc>
6817 * CONNECTION_CLOSE rate limit counter.
6818 */
6819static int qc_rx_check_closing(struct quic_conn *qc,
6820 struct quic_rx_packet *pkt)
6821{
6822 if (!(qc->flags & QUIC_FL_CONN_CLOSING))
6823 return 0;
6824
6825 TRACE_STATE("Closing state connection", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6826
6827 /* Check if CONNECTION_CLOSE rate reemission is reached. */
6828 if (++qc->nb_pkt_since_cc >= qc->nb_pkt_for_cc) {
6829 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
6830 qc->nb_pkt_for_cc++;
6831 qc->nb_pkt_since_cc = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006832 }
6833
Amaury Denoyelle98289692022-10-19 15:37:44 +02006834 return 1;
6835}
6836
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006837/* React to a connection migration initiated on <qc> by a client with the new
6838 * path addresses <peer_addr>/<local_addr>.
6839 *
6840 * Returns 0 on success else non-zero.
6841 */
6842static int qc_handle_conn_migration(struct quic_conn *qc,
6843 const struct sockaddr_storage *peer_addr,
6844 const struct sockaddr_storage *local_addr)
6845{
6846 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6847
Frédéric Lécaille6fc86972023-01-12 08:29:23 +01006848 /* RFC 9000. Connection Migration
6849 *
6850 * If the peer sent the disable_active_migration transport parameter,
6851 * an endpoint also MUST NOT send packets (including probing packets;
6852 * see Section 9.1) from a different local address to the address the peer
6853 * used during the handshake, unless the endpoint has acted on a
6854 * preferred_address transport parameter from the peer.
6855 */
6856 if (qc->li->bind_conf->quic_params.disable_active_migration) {
6857 TRACE_ERROR("Active migration was disabled, datagram dropped", QUIC_EV_CONN_LPKT, qc);
6858 goto err;
6859 }
6860
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006861 /* RFC 9000 9. Connection Migration
6862 *
Amaury Denoyelleeb6be982022-11-21 11:14:45 +01006863 * The design of QUIC relies on endpoints retaining a stable address for
6864 * the duration of the handshake. An endpoint MUST NOT initiate
6865 * connection migration before the handshake is confirmed, as defined in
6866 * Section 4.1.2 of [QUIC-TLS].
6867 */
6868 if (qc->state < QUIC_HS_ST_COMPLETE) {
6869 TRACE_STATE("Connection migration during handshake rejected", QUIC_EV_CONN_LPKT, qc);
6870 goto err;
6871 }
6872
6873 /* RFC 9000 9. Connection Migration
6874 *
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006875 * TODO
6876 * An endpoint MUST
6877 * perform path validation (Section 8.2) if it detects any change to a
6878 * peer's address, unless it has previously validated that address.
6879 */
6880
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006881 /* Update quic-conn owned socket if in used.
6882 * TODO try to reuse it instead of closing and opening a new one.
6883 */
6884 if (qc_test_fd(qc)) {
6885 /* TODO try to reuse socket instead of closing it and opening a new one. */
6886 TRACE_STATE("Connection migration detected, allocate a new connection socket", QUIC_EV_CONN_LPKT, qc);
6887 qc_release_fd(qc, 1);
Amaury Denoyellefb375572023-02-01 09:28:32 +01006888 /* TODO need to adjust <jobs> on socket allocation failure. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006889 qc_alloc_fd(qc, local_addr, peer_addr);
6890 }
6891
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006892 qc->local_addr = *local_addr;
6893 qc->peer_addr = *peer_addr;
6894 HA_ATOMIC_INC(&qc->prx_counters->conn_migration_done);
6895
6896 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6897 return 0;
6898
6899 err:
6900 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6901 return 1;
6902}
6903
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006904/* Release the memory for the RX packets which are no more referenced
6905 * and consume their payloads which have been copied to the RX buffer
6906 * for the connection.
6907 * Always succeeds.
6908 */
6909static inline void quic_rx_pkts_del(struct quic_conn *qc)
6910{
6911 struct quic_rx_packet *pkt, *pktback;
6912
6913 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
6914 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006915 "pkt #%lld(type=%d,len=%llu,rawlen=%llu,refcnt=%u) (diff: %zd)",
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006916 (long long)pkt->pn_node.key,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006917 pkt->type, (ull)pkt->len, (ull)pkt->raw_len, pkt->refcnt,
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006918 (unsigned char *)b_head(&qc->rx.buf) - pkt->data);
6919 if (pkt->data != (unsigned char *)b_head(&qc->rx.buf)) {
6920 size_t cdata;
6921
6922 cdata = b_contig_data(&qc->rx.buf, 0);
6923 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006924 "cdata=%llu *b_head()=0x%x", (ull)cdata, *b_head(&qc->rx.buf));
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006925 if (cdata && !*b_head(&qc->rx.buf)) {
6926 /* Consume the remaining data */
6927 b_del(&qc->rx.buf, cdata);
6928 }
6929 break;
6930 }
6931
6932 if (pkt->refcnt)
6933 break;
6934
6935 b_del(&qc->rx.buf, pkt->raw_len);
6936 LIST_DELETE(&pkt->qc_rx_pkt_list);
6937 pool_free(pool_head_quic_rx_packet, pkt);
6938 }
6939
6940 /* In frequent cases the buffer will be emptied at this stage. */
6941 b_realign_if_empty(&qc->rx.buf);
6942}
6943
Amaury Denoyelle98289692022-10-19 15:37:44 +02006944/* Handle a parsed packet <pkt> by the connection <qc>. Data will be copied
6945 * into <qc> receive buffer after header protection removal procedure.
6946 *
6947 * <dgram> must be set to the datagram which contains the QUIC packet. <beg>
6948 * must point to packet buffer first byte.
6949 *
6950 * <tasklist_head> may be non-NULL when the caller treat several datagrams for
6951 * different quic-conn. In this case, each quic-conn tasklet will be appended
6952 * to it in order to be woken up after the current task.
6953 *
6954 * The caller can safely removed the packet data. If packet refcount was not
6955 * incremented by this function, it means that the connection did not handled
6956 * it and it should be freed by the caller.
6957 */
6958static void qc_rx_pkt_handle(struct quic_conn *qc, struct quic_rx_packet *pkt,
6959 struct quic_dgram *dgram, unsigned char *beg,
6960 struct list **tasklist_head)
6961{
6962 const struct quic_version *qv = pkt->version;
6963 struct quic_enc_level *qel = NULL;
6964 size_t b_cspace;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006965
Amaury Denoyelle3f474e62022-11-24 17:15:08 +01006966 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6967
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006968 if (pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006969 qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED) {
6970 TRACE_PROTO("PTO timer must be armed after anti-amplication was reached",
6971 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01006972 TRACE_DEVEL("needs to wakeup the timer task after the amplification limit was reached",
6973 QUIC_EV_CONN_LPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006974 /* Reset the anti-amplification bit. It will be set again
6975 * when sending the next packet if reached again.
6976 */
6977 qc->flags &= ~QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Frédéric Lécaillea65b71f2023-03-03 10:16:32 +01006978 qc_set_timer(qc);
6979 if (qc->timer_task && tick_isset(qc->timer) && tick_is_lt(qc->timer, now_ms))
6980 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006981 }
6982
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006983 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
6984 TRACE_PROTO("Connection error",
6985 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6986 goto out;
6987 }
6988
6989 pkt->raw_len = pkt->len;
6990 quic_rx_pkts_del(qc);
6991 b_cspace = b_contig_space(&qc->rx.buf);
6992 if (b_cspace < pkt->len) {
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006993 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006994 "bspace=%llu pkt->len=%llu", (ull)b_cspace, (ull)pkt->len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006995 /* Do not consume buf if space not at the end. */
6996 if (b_tail(&qc->rx.buf) + b_cspace < b_wrap(&qc->rx.buf)) {
6997 TRACE_PROTO("Packet dropped",
6998 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006999 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02007000 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007001 }
7002
7003 /* Let us consume the remaining contiguous space. */
7004 if (b_cspace) {
7005 b_putchr(&qc->rx.buf, 0x00);
7006 b_cspace--;
7007 }
7008 b_add(&qc->rx.buf, b_cspace);
7009 if (b_contig_space(&qc->rx.buf) < pkt->len) {
7010 TRACE_PROTO("Too big packet",
7011 QUIC_EV_CONN_LPKT, qc, pkt, &pkt->len, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02007012 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02007013 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007014 }
7015 }
7016
Amaury Denoyelle845169d2022-10-17 18:05:26 +02007017 if (!qc_try_rm_hp(qc, pkt, beg, &qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007018 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
7019 goto drop;
7020 }
7021
7022 TRACE_DATA("New packet", QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
7023 if (pkt->aad_len)
7024 qc_pkt_insert(qc, pkt, qel);
7025 out:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02007026 *tasklist_head = tasklet_wakeup_after(*tasklist_head,
7027 qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007028
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02007029 drop_silent:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007030 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007031 return;
7032
7033 drop:
Amaury Denoyelle98289692022-10-19 15:37:44 +02007034 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007035 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
7036}
7037
7038/* This function builds into <buf> buffer a QUIC long packet header.
7039 * Return 1 if enough room to build this header, 0 if not.
7040 */
7041static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
7042 int type, size_t pn_len,
7043 struct quic_conn *qc, const struct quic_version *ver)
7044{
7045 int ret = 0;
7046
7047 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
7048
7049 if (end - *buf < sizeof ver->num + qc->dcid.len + qc->scid.len + 3) {
7050 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
7051 goto leave;
7052 }
7053
7054 type = quic_pkt_type(type, ver->num);
7055 /* #0 byte flags */
7056 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
7057 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
7058 /* Version */
7059 quic_write_uint32(buf, end, ver->num);
7060 *(*buf)++ = qc->dcid.len;
7061 /* Destination connection ID */
7062 if (qc->dcid.len) {
7063 memcpy(*buf, qc->dcid.data, qc->dcid.len);
7064 *buf += qc->dcid.len;
7065 }
7066 /* Source connection ID */
7067 *(*buf)++ = qc->scid.len;
7068 if (qc->scid.len) {
7069 memcpy(*buf, qc->scid.data, qc->scid.len);
7070 *buf += qc->scid.len;
7071 }
7072
7073 ret = 1;
7074 leave:
7075 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
7076 return ret;
7077}
7078
7079/* This function builds into <buf> buffer a QUIC short packet header.
7080 * Return 1 if enough room to build this header, 0 if not.
7081 */
7082static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
7083 size_t pn_len, struct quic_conn *qc,
7084 unsigned char tls_flags)
7085{
7086 int ret = 0;
Frédéric Lécailleece86e62023-03-07 11:53:43 +01007087 unsigned char spin_bit =
7088 (qc->flags & QUIC_FL_CONN_SPIN_BIT) ? QUIC_PACKET_SPIN_BIT : 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007089
7090 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7091
7092 if (end - *buf < 1 + qc->dcid.len) {
7093 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
7094 goto leave;
7095 }
7096
7097 /* #0 byte flags */
Frédéric Lécailleece86e62023-03-07 11:53:43 +01007098 *(*buf)++ = QUIC_PACKET_FIXED_BIT | spin_bit |
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007099 ((tls_flags & QUIC_FL_TLS_KP_BIT_SET) ? QUIC_PACKET_KEY_PHASE_BIT : 0) | (pn_len - 1);
7100 /* Destination connection ID */
7101 if (qc->dcid.len) {
7102 memcpy(*buf, qc->dcid.data, qc->dcid.len);
7103 *buf += qc->dcid.len;
7104 }
7105
7106 ret = 1;
7107 leave:
7108 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7109 return ret;
7110}
7111
7112/* Apply QUIC header protection to the packet with <buf> as first byte address,
7113 * <pn> as address of the Packet number field, <pnlen> being this field length
7114 * with <aead> as AEAD cipher and <key> as secret key.
7115 * Returns 1 if succeeded or 0 if failed.
7116 */
7117static int quic_apply_header_protection(struct quic_conn *qc, unsigned char *buf,
7118 unsigned char *pn, size_t pnlen,
7119 struct quic_tls_ctx *tls_ctx)
7120
7121{
7122 int i, ret = 0;
7123 /* We need an IV of at least 5 bytes: one byte for bytes #0
7124 * and at most 4 bytes for the packet number
7125 */
7126 unsigned char mask[5] = {0};
7127 EVP_CIPHER_CTX *aes_ctx = tls_ctx->tx.hp_ctx;
7128
7129 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7130
7131 if (!quic_tls_aes_encrypt(mask, pn + QUIC_PACKET_PN_MAXLEN, sizeof mask, aes_ctx)) {
7132 TRACE_ERROR("could not apply header protection", QUIC_EV_CONN_TXPKT, qc);
7133 goto out;
7134 }
7135
7136 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
7137 for (i = 0; i < pnlen; i++)
7138 pn[i] ^= mask[i + 1];
7139
7140 ret = 1;
7141 out:
7142 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7143 return ret;
7144}
7145
7146/* Reduce the encoded size of <ack_frm> ACK frame removing the last
7147 * ACK ranges if needed to a value below <limit> in bytes.
7148 * Return 1 if succeeded, 0 if not.
7149 */
7150static int quic_ack_frm_reduce_sz(struct quic_conn *qc,
7151 struct quic_frame *ack_frm, size_t limit)
7152{
7153 size_t room, ack_delay_sz;
7154 int ret = 0;
7155
7156 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7157
7158 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
7159 /* A frame is made of 1 byte for the frame type. */
7160 room = limit - ack_delay_sz - 1;
7161 if (!quic_rm_last_ack_ranges(qc, ack_frm->tx_ack.arngs, room))
7162 goto leave;
7163
7164 ret = 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
7165 leave:
7166 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7167 return ret;
7168}
7169
7170/* Prepare into <outlist> as most as possible ack-eliciting frame from their
7171 * <inlist> prebuilt frames for <qel> encryption level to be encoded in a buffer
7172 * with <room> as available room, and <*len> the packet Length field initialized
7173 * with the number of bytes already present in this buffer which must be taken
7174 * into an account for the Length packet field value. <headlen> is the number of
7175 * bytes already present in this packet before building frames.
7176 *
7177 * Update consequently <*len> to reflect the size of these frames built
7178 * by this function. Also attach these frames to <l> frame list.
7179 * Return 1 if at least one ack-eleciting frame could be built, 0 if not.
7180 */
7181static inline int qc_build_frms(struct list *outlist, struct list *inlist,
7182 size_t room, size_t *len, size_t headlen,
7183 struct quic_enc_level *qel,
7184 struct quic_conn *qc)
7185{
7186 int ret;
7187 struct quic_frame *cf, *cfbak;
7188
7189 TRACE_ENTER(QUIC_EV_CONN_BCFRMS, qc);
7190
7191 ret = 0;
7192 if (*len > room)
7193 goto leave;
7194
7195 /* If we are not probing we must take into an account the congestion
7196 * control window.
7197 */
7198 if (!qel->pktns->tx.pto_probe) {
7199 size_t remain = quic_path_prep_data(qc->path);
7200
7201 if (headlen > remain)
7202 goto leave;
7203
7204 room = QUIC_MIN(room, remain - headlen);
7205 }
7206
7207 TRACE_PROTO("************** frames build (headlen)",
7208 QUIC_EV_CONN_BCFRMS, qc, &headlen);
7209
7210 /* NOTE: switch/case block inside a loop, a successful status must be
7211 * returned by this function only if at least one frame could be built
7212 * in the switch/case block.
7213 */
7214 list_for_each_entry_safe(cf, cfbak, inlist, list) {
7215 /* header length, data length, frame length. */
7216 size_t hlen, dlen, dlen_sz, avail_room, flen;
7217
7218 if (!room)
7219 break;
7220
7221 switch (cf->type) {
7222 case QUIC_FT_CRYPTO:
7223 TRACE_DEVEL(" New CRYPTO frame build (room, len)",
7224 QUIC_EV_CONN_BCFRMS, qc, &room, len);
7225 /* Compute the length of this CRYPTO frame header */
7226 hlen = 1 + quic_int_getsize(cf->crypto.offset);
7227 /* Compute the data length of this CRyPTO frame. */
7228 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
7229 TRACE_DEVEL(" CRYPTO data length (hlen, crypto.len, dlen)",
7230 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->crypto.len, &dlen);
7231 if (!dlen)
7232 continue;
7233
7234 /* CRYPTO frame length. */
7235 flen = hlen + quic_int_getsize(dlen) + dlen;
7236 TRACE_DEVEL(" CRYPTO frame length (flen)",
7237 QUIC_EV_CONN_BCFRMS, qc, &flen);
7238 /* Add the CRYPTO data length and its encoded length to the packet
7239 * length and the length of this length.
7240 */
7241 *len += flen;
7242 room -= flen;
7243 if (dlen == cf->crypto.len) {
7244 /* <cf> CRYPTO data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007245 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007246 LIST_APPEND(outlist, &cf->list);
7247 }
7248 else {
7249 struct quic_frame *new_cf;
7250
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01007251 new_cf = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007252 if (!new_cf) {
7253 TRACE_ERROR("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, qc);
7254 continue;
7255 }
7256
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007257 new_cf->crypto.len = dlen;
7258 new_cf->crypto.offset = cf->crypto.offset;
7259 new_cf->crypto.qel = qel;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05007260 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007261 if (cf->origin) {
7262 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
7263 /* This <cf> frame was duplicated */
7264 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
7265 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01007266 /* Detach the remaining CRYPTO frame from its original frame */
7267 LIST_DEL_INIT(&cf->ref);
7268 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007269 }
7270 LIST_APPEND(outlist, &new_cf->list);
7271 /* Consume <dlen> bytes of the current frame. */
7272 cf->crypto.len -= dlen;
7273 cf->crypto.offset += dlen;
7274 }
7275 break;
7276
7277 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01007278 if (cf->stream.dup) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007279 struct eb64_node *node = NULL;
7280 struct qc_stream_desc *stream_desc = NULL;
7281 struct quic_stream *strm = &cf->stream;
7282
7283 /* As this frame has been already lost, ensure the stream is always
7284 * available or the range of this frame is not consumed before
7285 * resending it.
7286 */
7287 node = eb64_lookup(&qc->streams_by_id, strm->id);
7288 if (!node) {
7289 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007290 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007291 continue;
7292 }
7293
7294 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
7295 if (strm->offset.key + strm->len <= stream_desc->ack_offset) {
7296 TRACE_DEVEL("ignored frame frame in already acked range",
7297 QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007298 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007299 continue;
7300 }
7301 else if (strm->offset.key < stream_desc->ack_offset) {
Frédéric Lécailleca079792023-03-17 08:56:50 +01007302 uint64_t diff = stream_desc->ack_offset - strm->offset.key;
7303
Frédéric Lécaillec425e032023-03-20 14:32:59 +01007304 qc_stream_frm_mv_fwd(cf, diff);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007305 TRACE_DEVEL("updated partially acked frame",
7306 QUIC_EV_CONN_PRSAFRM, qc, cf);
7307 }
7308 }
7309 /* Note that these frames are accepted in short packets only without
7310 * "Length" packet field. Here, <*len> is used only to compute the
7311 * sum of the lengths of the already built frames for this packet.
7312 *
7313 * Compute the length of this STREAM frame "header" made a all the field
7314 * excepting the variable ones. Note that +1 is for the type of this frame.
7315 */
7316 hlen = 1 + quic_int_getsize(cf->stream.id) +
7317 ((cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT) ? quic_int_getsize(cf->stream.offset.key) : 0);
7318 /* Compute the data length of this STREAM frame. */
7319 avail_room = room - hlen - *len;
7320 if ((ssize_t)avail_room <= 0)
7321 continue;
7322
7323 TRACE_DEVEL(" New STREAM frame build (room, len)",
7324 QUIC_EV_CONN_BCFRMS, qc, &room, len);
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007325
7326 /* hlen contains STREAM id and offset. Ensure there is
7327 * enough room for length field.
7328 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007329 if (cf->type & QUIC_STREAM_FRAME_TYPE_LEN_BIT) {
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007330 dlen = QUIC_MIN((uint64_t)max_available_room(avail_room, &dlen_sz),
7331 cf->stream.len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007332 dlen_sz = quic_int_getsize(dlen);
7333 flen = hlen + dlen_sz + dlen;
7334 }
7335 else {
7336 dlen = QUIC_MIN((uint64_t)avail_room, cf->stream.len);
7337 flen = hlen + dlen;
7338 }
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007339
7340 if (cf->stream.len && !dlen) {
7341 /* Only a small gap is left on buffer, not
7342 * enough to encode the STREAM data length.
7343 */
7344 continue;
7345 }
7346
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007347 TRACE_DEVEL(" STREAM data length (hlen, stream.len, dlen)",
7348 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->stream.len, &dlen);
7349 TRACE_DEVEL(" STREAM frame length (flen)",
7350 QUIC_EV_CONN_BCFRMS, qc, &flen);
7351 /* Add the STREAM data length and its encoded length to the packet
7352 * length and the length of this length.
7353 */
7354 *len += flen;
7355 room -= flen;
7356 if (dlen == cf->stream.len) {
7357 /* <cf> STREAM data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007358 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007359 LIST_APPEND(outlist, &cf->list);
7360
7361 /* Do not notify MUX on retransmission. */
7362 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7363 qcc_streams_sent_done(cf->stream.stream->ctx,
7364 cf->stream.len,
7365 cf->stream.offset.key);
7366 }
7367 }
7368 else {
7369 struct quic_frame *new_cf;
7370 struct buffer cf_buf;
7371
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01007372 new_cf = qc_frm_alloc(cf->type);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007373 if (!new_cf) {
7374 TRACE_ERROR("No memory for new STREAM frame", QUIC_EV_CONN_BCFRMS, qc);
7375 continue;
7376 }
7377
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007378 new_cf->stream.stream = cf->stream.stream;
7379 new_cf->stream.buf = cf->stream.buf;
7380 new_cf->stream.id = cf->stream.id;
Amaury Denoyelle1dac0182023-02-02 16:45:07 +01007381 new_cf->stream.offset = cf->stream.offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007382 new_cf->stream.len = dlen;
7383 new_cf->type |= QUIC_STREAM_FRAME_TYPE_LEN_BIT;
7384 /* FIN bit reset */
7385 new_cf->type &= ~QUIC_STREAM_FRAME_TYPE_FIN_BIT;
7386 new_cf->stream.data = cf->stream.data;
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01007387 new_cf->stream.dup = cf->stream.dup;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05007388 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007389 if (cf->origin) {
7390 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
7391 /* This <cf> frame was duplicated */
7392 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
7393 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01007394 /* Detach this STREAM frame from its origin */
7395 LIST_DEL_INIT(&cf->ref);
7396 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007397 }
7398 LIST_APPEND(outlist, &new_cf->list);
7399 cf->type |= QUIC_STREAM_FRAME_TYPE_OFF_BIT;
7400 /* Consume <dlen> bytes of the current frame. */
7401 cf_buf = b_make(b_orig(cf->stream.buf),
7402 b_size(cf->stream.buf),
7403 (char *)cf->stream.data - b_orig(cf->stream.buf), 0);
7404 cf->stream.len -= dlen;
7405 cf->stream.offset.key += dlen;
7406 cf->stream.data = (unsigned char *)b_peek(&cf_buf, dlen);
7407
7408 /* Do not notify MUX on retransmission. */
7409 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7410 qcc_streams_sent_done(new_cf->stream.stream->ctx,
7411 new_cf->stream.len,
7412 new_cf->stream.offset.key);
7413 }
7414 }
7415
7416 /* TODO the MUX is notified about the frame sending via
7417 * previous qcc_streams_sent_done call. However, the
7418 * sending can fail later, for example if the sendto
7419 * system call returns an error. As the MUX has been
7420 * notified, the transport layer is responsible to
7421 * bufferize and resent the announced data later.
7422 */
7423
7424 break;
7425
7426 default:
7427 flen = qc_frm_len(cf);
7428 BUG_ON(!flen);
7429 if (flen > room)
7430 continue;
7431
7432 *len += flen;
7433 room -= flen;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007434 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007435 LIST_APPEND(outlist, &cf->list);
7436 break;
7437 }
7438
7439 /* Successful status as soon as a frame could be built */
7440 ret = 1;
7441 }
7442
7443 leave:
7444 TRACE_LEAVE(QUIC_EV_CONN_BCFRMS, qc);
7445 return ret;
7446}
7447
7448/* Generate a CONNECTION_CLOSE frame for <qc> on <qel> encryption level. <out>
7449 * is used as return parameter and should be zero'ed by the caller.
7450 */
7451static void qc_build_cc_frm(struct quic_conn *qc, struct quic_enc_level *qel,
7452 struct quic_frame *out)
7453{
7454 /* TODO improve CONNECTION_CLOSE on Initial/Handshake encryption levels
7455 *
7456 * A CONNECTION_CLOSE frame should be sent in several packets with
7457 * different encryption levels depending on the client context. This is
7458 * to ensure that the client can decrypt it. See RFC 9000 10.2.3 for
7459 * more details on how to implement it.
7460 */
7461 TRACE_ENTER(QUIC_EV_CONN_BFRM, qc);
7462
7463
7464 if (qc->err.app) {
7465 if (unlikely(qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
7466 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
7467 /* RFC 9000 10.2.3. Immediate Close during the Handshake
7468 *
7469 * Sending a CONNECTION_CLOSE of type 0x1d in an Initial or Handshake
7470 * packet could expose application state or be used to alter application
7471 * state. A CONNECTION_CLOSE of type 0x1d MUST be replaced by a
7472 * CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or
7473 * Handshake packets. Otherwise, information about the application
7474 * state might be revealed. Endpoints MUST clear the value of the
7475 * Reason Phrase field and SHOULD use the APPLICATION_ERROR code when
7476 * converting to a CONNECTION_CLOSE of type 0x1c.
7477 */
7478 out->type = QUIC_FT_CONNECTION_CLOSE;
7479 out->connection_close.error_code = QC_ERR_APPLICATION_ERROR;
7480 out->connection_close.reason_phrase_len = 0;
7481 }
7482 else {
7483 out->type = QUIC_FT_CONNECTION_CLOSE_APP;
7484 out->connection_close.error_code = qc->err.code;
7485 }
7486 }
7487 else {
7488 out->type = QUIC_FT_CONNECTION_CLOSE;
7489 out->connection_close.error_code = qc->err.code;
7490 }
7491 TRACE_LEAVE(QUIC_EV_CONN_BFRM, qc);
7492
7493}
7494
7495/* This function builds a clear packet from <pkt> information (its type)
7496 * into a buffer with <pos> as position pointer and <qel> as QUIC TLS encryption
7497 * level for <conn> QUIC connection and <qel> as QUIC TLS encryption level,
7498 * filling the buffer with as much frames as possible from <frms> list of
7499 * prebuilt frames.
7500 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
7501 * reserved so that to ensure there is enough room to build this AEAD TAG after
7502 * having returned from this function.
7503 * This function also updates the value of <buf_pn> pointer to point to the packet
7504 * number field in this packet. <pn_len> will also have the packet number
7505 * length as value.
7506 *
7507 * Return 1 if succeeded (enough room to buile this packet), O if not.
7508 */
7509static int qc_do_build_pkt(unsigned char *pos, const unsigned char *end,
7510 size_t dglen, struct quic_tx_packet *pkt,
7511 int64_t pn, size_t *pn_len, unsigned char **buf_pn,
7512 int force_ack, int padding, int cc, int probe,
7513 struct quic_enc_level *qel, struct quic_conn *qc,
7514 const struct quic_version *ver, struct list *frms)
7515{
7516 unsigned char *beg, *payload;
7517 size_t len, len_sz, len_frms, padding_len;
7518 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
7519 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
7520 struct quic_frame cc_frm = { };
7521 size_t ack_frm_len, head_len;
7522 int64_t rx_largest_acked_pn;
7523 int add_ping_frm;
7524 struct list frm_list = LIST_HEAD_INIT(frm_list);
7525 struct quic_frame *cf;
7526 int must_ack, ret = 0;
7527 int nb_aepkts_since_last_ack;
7528
7529 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7530
7531 /* Length field value with CRYPTO frames if present. */
7532 len_frms = 0;
7533 beg = pos;
7534 /* When not probing, and no immediate close is required, reduce the size of this
7535 * buffer to respect the congestion controller window.
7536 * This size will be limited if we have ack-eliciting frames to send from <frms>.
7537 */
7538 if (!probe && !LIST_ISEMPTY(frms) && !cc) {
7539 size_t path_room;
7540
7541 path_room = quic_path_prep_data(qc->path);
7542 if (end - beg > path_room)
7543 end = beg + path_room;
7544 }
7545
7546 /* Ensure there is enough room for the TLS encryption tag and a zero token
7547 * length field if any.
7548 */
7549 if (end - pos < QUIC_TLS_TAG_LEN +
7550 (pkt->type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0))
7551 goto no_room;
7552
7553 end -= QUIC_TLS_TAG_LEN;
7554 rx_largest_acked_pn = qel->pktns->rx.largest_acked_pn;
7555 /* packet number length */
7556 *pn_len = quic_packet_number_length(pn, rx_largest_acked_pn);
7557 /* Build the header */
7558 if ((pkt->type == QUIC_PACKET_TYPE_SHORT &&
7559 !quic_build_packet_short_header(&pos, end, *pn_len, qc, qel->tls_ctx.flags)) ||
7560 (pkt->type != QUIC_PACKET_TYPE_SHORT &&
7561 !quic_build_packet_long_header(&pos, end, pkt->type, *pn_len, qc, ver)))
7562 goto no_room;
7563
7564 /* Encode the token length (0) for an Initial packet. */
7565 if (pkt->type == QUIC_PACKET_TYPE_INITIAL)
7566 *pos++ = 0;
7567 head_len = pos - beg;
7568 /* Build an ACK frame if required. */
7569 ack_frm_len = 0;
7570 nb_aepkts_since_last_ack = qel->pktns->rx.nb_aepkts_since_last_ack;
7571 must_ack = !qel->pktns->tx.pto_probe &&
7572 (force_ack || ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
7573 (LIST_ISEMPTY(frms) || nb_aepkts_since_last_ack >= QUIC_MAX_RX_AEPKTS_SINCE_LAST_ACK)));
7574 if (must_ack) {
7575 struct quic_arngs *arngs = &qel->pktns->rx.arngs;
7576 BUG_ON(eb_is_empty(&qel->pktns->rx.arngs.root));
7577 ack_frm.tx_ack.arngs = arngs;
7578 if (qel->pktns->flags & QUIC_FL_PKTNS_NEW_LARGEST_PN) {
7579 qel->pktns->tx.ack_delay =
7580 quic_compute_ack_delay_us(qel->pktns->rx.largest_time_received, qc);
7581 qel->pktns->flags &= ~QUIC_FL_PKTNS_NEW_LARGEST_PN;
7582 }
7583 ack_frm.tx_ack.ack_delay = qel->pktns->tx.ack_delay;
7584 /* XXX BE CAREFUL XXX : here we reserved at least one byte for the
7585 * smallest frame (PING) and <*pn_len> more for the packet number. Note
7586 * that from here, we do not know if we will have to send a PING frame.
7587 * This will be decided after having computed the ack-eliciting frames
7588 * to be added to this packet.
7589 */
7590 ack_frm_len = quic_ack_frm_reduce_sz(qc, &ack_frm, end - 1 - *pn_len - pos);
7591 if (!ack_frm_len)
7592 goto no_room;
7593 }
7594
7595 /* Length field value without the ack-eliciting frames. */
7596 len = ack_frm_len + *pn_len;
7597 len_frms = 0;
7598 if (!cc && !LIST_ISEMPTY(frms)) {
7599 ssize_t room = end - pos;
7600
7601 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7602 /* Initialize the length of the frames built below to <len>.
7603 * If any frame could be successfully built by qc_build_frms(),
7604 * we will have len_frms > len.
7605 */
7606 len_frms = len;
7607 if (!qc_build_frms(&frm_list, frms,
7608 end - pos, &len_frms, pos - beg, qel, qc)) {
7609 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7610 qc, NULL, NULL, &room);
7611 if (!ack_frm_len && !qel->pktns->tx.pto_probe)
7612 goto no_room;
7613 }
7614 }
7615
7616 /* Length (of the remaining data). Must not fail because, the buffer size
7617 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
7618 * for the encryption tag. It must be taken into an account for the length
7619 * of this packet.
7620 */
7621 if (len_frms)
7622 len = len_frms + QUIC_TLS_TAG_LEN;
7623 else
7624 len += QUIC_TLS_TAG_LEN;
7625 /* CONNECTION_CLOSE frame */
7626 if (cc) {
7627 qc_build_cc_frm(qc, qel, &cc_frm);
7628 len += qc_frm_len(&cc_frm);
7629 }
7630 add_ping_frm = 0;
7631 padding_len = 0;
7632 len_sz = quic_int_getsize(len);
7633 /* Add this packet size to <dglen> */
7634 dglen += head_len + len_sz + len;
Frédéric Lécailleec937212023-03-03 17:34:41 +01007635 /* Note that <padding> is true only when building an Handshake packet
7636 * coalesced to an Initial packet.
7637 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007638 if (padding && dglen < QUIC_INITIAL_PACKET_MINLEN) {
7639 /* This is a maximum padding size */
7640 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7641 /* The length field value is of this packet is <len> + <padding_len>
7642 * the size of which may be greater than the initial computed size
7643 * <len_sz>. So, let's deduce the difference between these to packet
7644 * sizes from <padding_len>.
7645 */
7646 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7647 len += padding_len;
7648 }
Frédéric Lécaille5faf5772023-02-16 17:30:53 +01007649 else if (len_frms && len_frms < QUIC_PACKET_PN_MAXLEN) {
7650 len += padding_len = QUIC_PACKET_PN_MAXLEN - len_frms;
7651 }
7652 else if (LIST_ISEMPTY(&frm_list)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007653 if (qel->pktns->tx.pto_probe) {
7654 /* If we cannot send a frame, we send a PING frame. */
7655 add_ping_frm = 1;
7656 len += 1;
Frédéric Lécailleec937212023-03-03 17:34:41 +01007657 dglen += 1;
7658 /* Note that only we are in the case where this Initial packet
7659 * is not coalesced to an Handshake packet. We must directly
7660 * pad the datragram.
7661 */
Frédéric Lécaille9c317b12023-03-28 15:39:11 +02007662 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
7663 if (dglen < QUIC_INITIAL_PACKET_MINLEN) {
7664 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7665 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7666 len += padding_len;
7667 }
7668 }
7669 else {
7670 /* Note that +1 is for the PING frame */
7671 if (*pn_len + 1 < QUIC_PACKET_PN_MAXLEN)
7672 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len - 1;
Frédéric Lécailleec937212023-03-03 17:34:41 +01007673 }
7674 }
7675 else {
7676 /* If there is no frame at all to follow, add at least a PADDING frame. */
7677 if (!ack_frm_len && !cc)
7678 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007679 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007680 }
7681
7682 if (pkt->type != QUIC_PACKET_TYPE_SHORT && !quic_enc_int(&pos, end, len))
7683 goto no_room;
7684
7685 /* Packet number field address. */
7686 *buf_pn = pos;
7687
7688 /* Packet number encoding. */
7689 if (!quic_packet_number_encode(&pos, end, pn, *pn_len))
7690 goto no_room;
7691
7692 /* payload building (ack-eliciting or not frames) */
7693 payload = pos;
7694 if (ack_frm_len) {
7695 if (!qc_build_frm(&pos, end, &ack_frm, pkt, qc))
7696 goto no_room;
7697
7698 pkt->largest_acked_pn = quic_pktns_get_largest_acked_pn(qel->pktns);
7699 pkt->flags |= QUIC_FL_TX_PACKET_ACK;
7700 }
7701
7702 /* Ack-eliciting frames */
7703 if (!LIST_ISEMPTY(&frm_list)) {
7704 struct quic_frame *tmp_cf;
7705 list_for_each_entry_safe(cf, tmp_cf, &frm_list, list) {
7706 if (!qc_build_frm(&pos, end, cf, pkt, qc)) {
7707 ssize_t room = end - pos;
7708 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7709 qc, NULL, NULL, &room);
7710 /* Note that <cf> was added from <frms> to <frm_list> list by
7711 * qc_build_frms().
7712 */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007713 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007714 LIST_INSERT(frms, &cf->list);
7715 continue;
7716 }
7717
7718 quic_tx_packet_refinc(pkt);
7719 cf->pkt = pkt;
7720 }
7721 }
7722
7723 /* Build a PING frame if needed. */
7724 if (add_ping_frm) {
7725 frm.type = QUIC_FT_PING;
7726 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7727 goto no_room;
7728 }
7729
7730 /* Build a CONNECTION_CLOSE frame if needed. */
7731 if (cc) {
7732 if (!qc_build_frm(&pos, end, &cc_frm, pkt, qc))
7733 goto no_room;
7734
7735 pkt->flags |= QUIC_FL_TX_PACKET_CC;
7736 }
7737
7738 /* Build a PADDING frame if needed. */
7739 if (padding_len) {
7740 frm.type = QUIC_FT_PADDING;
7741 frm.padding.len = padding_len;
7742 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7743 goto no_room;
7744 }
7745
7746 if (pos == payload) {
7747 /* No payload was built because of congestion control */
7748 TRACE_DEVEL("limited by congestion control", QUIC_EV_CONN_TXPKT, qc);
7749 goto no_room;
7750 }
7751
7752 /* If this packet is ack-eliciting and we are probing let's
7753 * decrement the PTO probe counter.
7754 */
7755 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING &&
7756 qel->pktns->tx.pto_probe)
7757 qel->pktns->tx.pto_probe--;
7758
7759 pkt->len = pos - beg;
7760 LIST_SPLICE(&pkt->frms, &frm_list);
7761
7762 ret = 1;
7763 TRACE_DEVEL("Packet ack-eliciting frames", QUIC_EV_CONN_TXPKT, qc, pkt);
7764 leave:
7765 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7766 return ret;
7767
7768 no_room:
7769 /* Replace the pre-built frames which could not be add to this packet */
7770 LIST_SPLICE(frms, &frm_list);
7771 TRACE_DEVEL("Remaining ack-eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7772 goto leave;
7773}
7774
7775static inline void quic_tx_packet_init(struct quic_tx_packet *pkt, int type)
7776{
7777 pkt->type = type;
7778 pkt->len = 0;
7779 pkt->in_flight_len = 0;
7780 pkt->pn_node.key = (uint64_t)-1;
7781 LIST_INIT(&pkt->frms);
7782 pkt->time_sent = TICK_ETERNITY;
7783 pkt->next = NULL;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01007784 pkt->prev = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007785 pkt->largest_acked_pn = -1;
7786 pkt->flags = 0;
7787 pkt->refcnt = 0;
7788}
7789
7790/* Build a packet into <buf> packet buffer with <pkt_type> as packet
7791 * type for <qc> QUIC connection from <qel> encryption level from <frms> list
7792 * of prebuilt frames.
7793 *
7794 * Return -2 if the packet could not be allocated or encrypted for any reason,
7795 * -1 if there was not enough room to build a packet.
7796 * XXX NOTE XXX
7797 * If you provide provide qc_build_pkt() with a big enough buffer to build a packet as big as
7798 * possible (to fill an MTU), the unique reason why this function may fail is the congestion
7799 * control window limitation.
7800 */
7801static struct quic_tx_packet *qc_build_pkt(unsigned char **pos,
7802 const unsigned char *buf_end,
7803 struct quic_enc_level *qel,
7804 struct quic_tls_ctx *tls_ctx, struct list *frms,
7805 struct quic_conn *qc, const struct quic_version *ver,
7806 size_t dglen, int pkt_type, int force_ack,
7807 int padding, int probe, int cc, int *err)
7808{
7809 struct quic_tx_packet *ret_pkt = NULL;
7810 /* The pointer to the packet number field. */
7811 unsigned char *buf_pn;
7812 unsigned char *beg, *end, *payload;
7813 int64_t pn;
7814 size_t pn_len, payload_len, aad_len;
7815 struct quic_tx_packet *pkt;
7816
7817 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc, NULL, qel);
7818 *err = 0;
7819 pkt = pool_alloc(pool_head_quic_tx_packet);
7820 if (!pkt) {
7821 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_TXPKT, qc);
7822 *err = -2;
7823 goto err;
7824 }
7825
7826 quic_tx_packet_init(pkt, pkt_type);
7827 beg = *pos;
7828 pn_len = 0;
7829 buf_pn = NULL;
7830
7831 pn = qel->pktns->tx.next_pn + 1;
7832 if (!qc_do_build_pkt(*pos, buf_end, dglen, pkt, pn, &pn_len, &buf_pn,
7833 force_ack, padding, cc, probe, qel, qc, ver, frms)) {
7834 // trace already emitted by function above
7835 *err = -1;
7836 goto err;
7837 }
7838
7839 end = beg + pkt->len;
7840 payload = buf_pn + pn_len;
7841 payload_len = end - payload;
7842 aad_len = payload - beg;
7843
7844 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc)) {
7845 // trace already emitted by function above
7846 *err = -2;
7847 goto err;
7848 }
7849
7850 end += QUIC_TLS_TAG_LEN;
7851 pkt->len += QUIC_TLS_TAG_LEN;
7852 if (!quic_apply_header_protection(qc, beg, buf_pn, pn_len, tls_ctx)) {
7853 // trace already emitted by function above
7854 *err = -2;
7855 goto err;
7856 }
7857
7858 /* Consume a packet number */
7859 qel->pktns->tx.next_pn++;
7860 qc->tx.prep_bytes += pkt->len;
7861 if (qc->tx.prep_bytes >= 3 * qc->rx.bytes && !quic_peer_validated_addr(qc)) {
7862 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
7863 TRACE_PROTO("anti-amplification limit reached", QUIC_EV_CONN_TXPKT, qc);
7864 }
7865 /* Now that a correct packet is built, let us consume <*pos> buffer. */
7866 *pos = end;
7867 /* Attach the built packet to its tree. */
7868 pkt->pn_node.key = pn;
7869 /* Set the packet in fligth length for in flight packet only. */
7870 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
7871 pkt->in_flight_len = pkt->len;
7872 qc->path->prep_in_flight += pkt->len;
7873 }
7874 /* Always reset this flags */
7875 qc->flags &= ~QUIC_FL_CONN_IMMEDIATE_CLOSE;
7876 if (pkt->flags & QUIC_FL_TX_PACKET_ACK) {
7877 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
7878 qel->pktns->rx.nb_aepkts_since_last_ack = 0;
7879 }
7880
7881 pkt->pktns = qel->pktns;
7882
7883 ret_pkt = pkt;
7884 leave:
7885 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc, ret_pkt);
7886 return ret_pkt;
7887
7888 err:
7889 /* TODO: what about the frames which have been built
7890 * for this packet.
7891 */
7892 free_quic_tx_packet(qc, pkt);
7893 goto leave;
7894}
7895
7896
7897static void __quic_conn_init(void)
7898{
7899 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
7900}
7901INITCALL0(STG_REGISTER, __quic_conn_init);
7902
7903static void __quic_conn_deinit(void)
7904{
7905 BIO_meth_free(ha_quic_meth);
7906}
7907REGISTER_POST_DEINIT(__quic_conn_deinit);
7908
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007909/* Handle a new <dgram> received. Parse each QUIC packets and copied their
7910 * content to a quic-conn instance. The datagram content can be released after
7911 * this function.
7912 *
7913 * If datagram has been received on a quic-conn owned FD, <from_qc> must be set
7914 * to the connection instance. <li> is the attached listener. The caller is
7915 * responsible to ensure that the first packet is destined to this connection
7916 * by comparing CIDs.
7917 *
7918 * If datagram has been received on a receiver FD, <from_qc> will be NULL. This
7919 * function will thus retrieve the connection from the CID tree or allocate a
7920 * new one if possible. <li> is the listener attached to the receiver.
7921 *
7922 * Returns 0 on success else non-zero. If an error happens, some packets from
7923 * the datagram may not have been parsed.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007924 */
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007925int quic_dgram_parse(struct quic_dgram *dgram, struct quic_conn *from_qc,
7926 struct listener *li)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007927{
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007928 struct quic_rx_packet *pkt;
7929 struct quic_conn *qc = NULL;
7930 unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007931 struct list *tasklist_head = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007932
7933 TRACE_ENTER(QUIC_EV_CONN_LPKT);
7934
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007935 pos = dgram->buf;
7936 end = pos + dgram->len;
7937 do {
7938 /* TODO replace zalloc -> alloc. */
7939 pkt = pool_zalloc(pool_head_quic_rx_packet);
7940 if (!pkt) {
7941 TRACE_ERROR("RX packet allocation failed", QUIC_EV_CONN_LPKT);
7942 goto err;
7943 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007944
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007945 pkt->version = NULL;
7946 pkt->pn_offset = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007947
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007948 /* Set flag if pkt is the first one in dgram. */
7949 if (pos == dgram->buf)
7950 pkt->flags |= QUIC_FL_RX_PACKET_DGRAM_FIRST;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007951
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007952 LIST_INIT(&pkt->qc_rx_pkt_list);
7953 pkt->time_received = now_ms;
7954 quic_rx_packet_refinc(pkt);
7955 if (quic_rx_pkt_parse(pkt, pos, end, dgram, li))
7956 goto next;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007957
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007958 /* Search quic-conn instance for first packet of the datagram.
7959 * quic_rx_packet_parse() is responsible to discard packets
7960 * with different DCID as the first one in the same datagram.
7961 */
7962 if (!qc) {
7963 qc = from_qc ? from_qc : quic_rx_pkt_retrieve_conn(pkt, dgram, li);
7964 /* qc is NULL if receiving a non Initial packet for an
7965 * unknown connection.
7966 */
7967 if (!qc) {
Amaury Denoyelle98289692022-10-19 15:37:44 +02007968 /* Skip the entire datagram. */
7969 pkt->len = end - pos;
7970 goto next;
7971 }
7972
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007973 dgram->qc = qc;
7974 }
Amaury Denoyelle98289692022-10-19 15:37:44 +02007975
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007976 if (qc_rx_check_closing(qc, pkt)) {
7977 /* Skip the entire datagram. */
7978 pkt->len = end - pos;
7979 goto next;
7980 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007981
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007982 /* Detect QUIC connection migration. */
Frédéric Lécaillef6769542023-01-12 10:36:26 +01007983 if (ipcmp(&qc->peer_addr, &dgram->saddr, 1)) {
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007984 if (qc_handle_conn_migration(qc, &dgram->saddr, &dgram->daddr)) {
7985 /* Skip the entire datagram. */
7986 TRACE_ERROR("error during connection migration, datagram dropped", QUIC_EV_CONN_LPKT, qc);
7987 pkt->len = end - pos;
7988 goto next;
7989 }
7990 }
7991
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007992 qc_rx_pkt_handle(qc, pkt, dgram, pos, &tasklist_head);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007993
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007994 next:
7995 pos += pkt->len;
7996 quic_rx_packet_refdec(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007997
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007998 /* Free rejected packets */
7999 if (!pkt->refcnt) {
8000 BUG_ON(LIST_INLIST(&pkt->qc_rx_pkt_list));
8001 pool_free(pool_head_quic_rx_packet, pkt);
8002 }
8003 } while (pos < end);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008004
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008005 /* Increasing the received bytes counter by the UDP datagram length
8006 * if this datagram could be associated to a connection.
8007 */
8008 if (dgram->qc)
8009 dgram->qc->rx.bytes += dgram->len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008010
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008011 /* This must never happen. */
8012 BUG_ON(pos > end);
8013 BUG_ON(pos < end || pos > dgram->buf + dgram->len);
8014 /* Mark this datagram as consumed */
8015 HA_ATOMIC_STORE(&dgram->buf, NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008016
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008017 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
8018 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008019
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008020 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008021 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle8687b632022-09-27 14:22:09 +02008022 return -1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008023}
8024
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01008025/* Check if connection ID <dcid> of length <dcid_len> belongs to <qc> local
8026 * CIDs. This can be used to determine if a datagram is addressed to the right
8027 * connection instance.
8028 *
8029 * Returns a boolean value.
8030 */
8031int qc_check_dcid(struct quic_conn *qc, unsigned char *dcid, size_t dcid_len)
8032{
8033 struct ebmb_node *node;
8034 struct quic_connection_id *id;
8035
8036 /* For ODCID, address is concatenated to it after qc.odcid.len so this
8037 * comparison is safe.
8038 */
8039 if ((qc->scid.len == dcid_len &&
8040 memcmp(qc->scid.data, dcid, dcid_len) == 0) ||
8041 (qc->odcid.len == dcid_len &&
Frédéric Lécaille07846cb2023-02-13 16:14:24 +01008042 memcmp(qc->odcid.data, dcid, dcid_len) == 0)) {
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01008043 return 1;
8044 }
8045
8046 node = ebmb_lookup(&quic_dghdlrs[tid].cids, dcid, dcid_len);
8047 if (node) {
8048 id = ebmb_entry(node, struct quic_connection_id, node);
8049 if (qc == id->qc)
8050 return 1;
8051 }
8052
8053 return 0;
8054}
8055
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008056/* Retrieve the DCID from a QUIC datagram or packet with <buf> as first octet.
8057 * Returns 1 if succeeded, 0 if not.
8058 */
8059int quic_get_dgram_dcid(unsigned char *buf, const unsigned char *end,
8060 unsigned char **dcid, size_t *dcid_len)
8061{
8062 int ret = 0, long_header;
8063 size_t minlen, skip;
8064
8065 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
8066
8067 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
8068 TRACE_PROTO("fixed bit not set", QUIC_EV_CONN_RXPKT);
8069 goto err;
8070 }
8071
8072 long_header = *buf & QUIC_PACKET_LONG_HEADER_BIT;
8073 minlen = long_header ? QUIC_LONG_PACKET_MINLEN :
8074 QUIC_SHORT_PACKET_MINLEN + QUIC_HAP_CID_LEN + QUIC_TLS_TAG_LEN;
8075 skip = long_header ? QUIC_LONG_PACKET_DCID_OFF : QUIC_SHORT_PACKET_DCID_OFF;
8076 if (end - buf < minlen)
8077 goto err;
8078
8079 buf += skip;
8080 *dcid_len = long_header ? *buf++ : QUIC_HAP_CID_LEN;
8081 if (*dcid_len > QUIC_CID_MAXLEN || end - buf <= *dcid_len)
8082 goto err;
8083
8084 *dcid = buf;
8085
8086 ret = 1;
8087 leave:
8088 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
8089 return ret;
8090
8091 err:
8092 TRACE_PROTO("wrong datagram", QUIC_EV_CONN_RXPKT);
8093 goto leave;
8094}
8095
8096/* Notify the MUX layer if alive about an imminent close of <qc>. */
8097void qc_notify_close(struct quic_conn *qc)
8098{
8099 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
8100
8101 if (qc->flags & QUIC_FL_CONN_NOTIFY_CLOSE)
8102 goto leave;
8103
8104 qc->flags |= QUIC_FL_CONN_NOTIFY_CLOSE;
8105 /* wake up the MUX */
8106 if (qc->mux_state == QC_MUX_READY && qc->conn->mux->wake) {
8107 TRACE_STATE("connection closure notidfied to mux",
8108 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
8109 qc->conn->mux->wake(qc->conn);
8110 }
8111 else
8112 TRACE_STATE("connection closure not notidfied to mux",
8113 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
8114 leave:
8115 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
8116}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008117
Amaury Denoyelle8afe4b82023-03-21 11:39:24 +01008118/* Wake-up upper layer for sending if all conditions are met :
8119 * - room in congestion window or probe packet to sent
8120 * - socket FD ready to sent or listener socket used
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01008121 *
8122 * Returns 1 if upper layer has been woken up else 0.
8123 */
8124int qc_notify_send(struct quic_conn *qc)
8125{
Amaury Denoyelle8afe4b82023-03-21 11:39:24 +01008126 const struct quic_pktns *pktns = &qc->pktns[QUIC_TLS_PKTNS_01RTT];
8127
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01008128 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
Amaury Denoyelle8afe4b82023-03-21 11:39:24 +01008129 /* RFC 9002 7.5. Probe Timeout
8130 *
8131 * Probe packets MUST NOT be blocked by the congestion controller.
8132 */
8133 if ((quic_path_prep_data(qc->path) || pktns->tx.pto_probe) &&
Amaury Denoyellecaa16542023-02-28 15:11:26 +01008134 (!qc_test_fd(qc) || !fd_send_active(qc->fd))) {
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01008135 tasklet_wakeup(qc->subs->tasklet);
8136 qc->subs->events &= ~SUB_RETRY_SEND;
8137 if (!qc->subs->events)
8138 qc->subs = NULL;
8139
8140 return 1;
8141 }
8142 }
8143
8144 return 0;
8145}
8146
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008147
8148/* appctx context used by "show quic" command */
8149struct show_quic_ctx {
8150 unsigned int epoch;
8151 struct bref bref; /* back-reference to the quic-conn being dumped */
8152 unsigned int thr;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01008153 int flags;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008154};
8155
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01008156#define QC_CLI_FL_SHOW_ALL 0x1 /* show closing/draining connections */
8157
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008158static int cli_parse_show_quic(char **args, char *payload, struct appctx *appctx, void *private)
8159{
8160 struct show_quic_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
8161
8162 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
8163 return 1;
8164
8165 ctx->epoch = _HA_ATOMIC_FETCH_ADD(&qc_epoch, 1);
8166 ctx->thr = 0;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01008167 ctx->flags = 0;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008168
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01008169 if (*args[2] && strcmp(args[2], "all") == 0)
8170 ctx->flags |= QC_CLI_FL_SHOW_ALL;
8171
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008172 LIST_INIT(&ctx->bref.users);
8173
8174 return 0;
8175}
8176
8177static int cli_io_handler_dump_quic(struct appctx *appctx)
8178{
8179 struct show_quic_ctx *ctx = appctx->svcctx;
8180 struct stconn *sc = appctx_sc(appctx);
8181 struct quic_conn *qc;
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01008182 struct quic_enc_level *qel;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008183 struct eb64_node *node;
8184 struct qc_stream_desc *stream;
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01008185 char bufaddr[INET6_ADDRSTRLEN], bufport[6];
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01008186 int expire;
8187 unsigned char cid_len;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008188
8189 thread_isolate();
8190
8191 if (ctx->thr >= global.nbthread)
8192 goto done;
8193
8194 if (unlikely(sc_ic(sc)->flags & CF_SHUTW)) {
8195 /* If we're forced to shut down, we might have to remove our
8196 * reference to the last stream being dumped.
8197 */
8198 if (!LIST_ISEMPTY(&ctx->bref.users))
8199 LIST_DEL_INIT(&ctx->bref.users);
8200 goto done;
8201 }
8202
8203 chunk_reset(&trash);
8204
8205 if (!LIST_ISEMPTY(&ctx->bref.users)) {
8206 /* Remove show_quic_ctx from previous quic_conn instance. */
8207 LIST_DEL_INIT(&ctx->bref.users);
8208 }
8209 else if (!ctx->bref.ref) {
8210 /* First invocation. */
8211 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
8212 }
8213
8214 while (1) {
8215 int done = 0;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008216 int i;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008217
8218 if (ctx->bref.ref == &ha_thread_ctx[ctx->thr].quic_conns) {
Amaury Denoyelle2d376292023-03-08 09:42:31 +01008219 /* If closing connections requested through "all", move
8220 * to quic_conns_clo list after browsing quic_conns.
8221 * Else move directly to the next quic_conns thread.
8222 */
8223 if (ctx->flags & QC_CLI_FL_SHOW_ALL) {
8224 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns_clo.n;
8225 continue;
8226 }
8227
8228 done = 1;
8229 }
8230 else if (ctx->bref.ref == &ha_thread_ctx[ctx->thr].quic_conns_clo) {
8231 /* Closing list entirely browsed, go to next quic_conns
8232 * thread.
8233 */
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008234 done = 1;
8235 }
8236 else {
Amaury Denoyelle2d376292023-03-08 09:42:31 +01008237 /* Retrieve next element of the current list. */
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008238 qc = LIST_ELEM(ctx->bref.ref, struct quic_conn *, el_th_ctx);
8239 if ((int)(qc->qc_epoch - ctx->epoch) > 0)
8240 done = 1;
8241 }
8242
8243 if (done) {
8244 ++ctx->thr;
8245 if (ctx->thr >= global.nbthread)
8246 break;
Amaury Denoyelle2d376292023-03-08 09:42:31 +01008247 /* Switch to next thread quic_conns list. */
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008248 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
8249 continue;
8250 }
8251
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01008252 /* CIDs */
8253 chunk_appendf(&trash, "* %p[%02u]: scid=", qc, qc->tid);
8254 for (cid_len = 0; cid_len < qc->scid.len; ++cid_len)
8255 chunk_appendf(&trash, "%02x", qc->scid.data[cid_len]);
8256 while (cid_len++ < 20)
8257 chunk_appendf(&trash, "..");
8258
8259 chunk_appendf(&trash, " dcid=");
8260 for (cid_len = 0; cid_len < qc->dcid.len; ++cid_len)
8261 chunk_appendf(&trash, "%02x", qc->dcid.data[cid_len]);
8262 while (cid_len++ < 20)
8263 chunk_appendf(&trash, "..");
8264
8265 chunk_appendf(&trash, "\n");
8266
Frédéric Lécaille5e3201e2023-03-07 15:18:02 +01008267 chunk_appendf(&trash, " loc. TPs:");
8268 quic_transport_params_dump(&trash, qc, &qc->rx.params);
8269 chunk_appendf(&trash, " rem. TPs:");
8270 quic_transport_params_dump(&trash, qc, &qc->tx.params);
8271
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01008272 /* Connection state */
8273 if (qc->flags & QUIC_FL_CONN_CLOSING)
8274 chunk_appendf(&trash, " st=closing ");
8275 else if (qc->flags & QUIC_FL_CONN_DRAINING)
8276 chunk_appendf(&trash, " st=draining ");
8277 else if (qc->state < QUIC_HS_ST_CONFIRMED)
8278 chunk_appendf(&trash, " st=handshake ");
8279 else
8280 chunk_appendf(&trash, " st=opened ");
8281
8282 if (qc->mux_state == QC_MUX_NULL)
8283 chunk_appendf(&trash, "mux=null ");
8284 else if (qc->mux_state == QC_MUX_READY)
8285 chunk_appendf(&trash, "mux=ready ");
8286 else
8287 chunk_appendf(&trash, "mux=released ");
8288
8289 expire = qc->idle_timer_task->expire;
8290 chunk_appendf(&trash, "expire=%02ds ",
8291 expire > now_ms ? (expire - now_ms) / 1000 : 0);
8292
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008293 chunk_appendf(&trash, "\n");
8294
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01008295 /* Socket */
8296 chunk_appendf(&trash, " fd=%d", qc->fd);
8297 if (qc->local_addr.ss_family == AF_INET ||
8298 qc->local_addr.ss_family == AF_INET6) {
8299 addr_to_str(&qc->local_addr, bufaddr, sizeof(bufaddr));
8300 port_to_str(&qc->local_addr, bufport, sizeof(bufport));
8301 chunk_appendf(&trash, " from=%s:%s", bufaddr, bufport);
8302
8303 addr_to_str(&qc->peer_addr, bufaddr, sizeof(bufaddr));
8304 port_to_str(&qc->peer_addr, bufport, sizeof(bufport));
8305 chunk_appendf(&trash, " to=%s:%s", bufaddr, bufport);
8306 }
8307
8308 chunk_appendf(&trash, "\n");
8309
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01008310 /* Encryption levels */
8311 qel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
8312 chunk_appendf(&trash, " [initl] rx.ackrng=%-6zu tx.inflight=%-6zu",
8313 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8314 qel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
8315 chunk_appendf(&trash, " [hndshk] rx.ackrng=%-6zu tx.inflight=%-6zu\n",
8316 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8317 qel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
8318 chunk_appendf(&trash, " [0-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
8319 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8320 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
8321 chunk_appendf(&trash, " [1-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
8322 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8323
8324 chunk_appendf(&trash, "\n");
8325
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008326 /* Streams */
8327 node = eb64_first(&qc->streams_by_id);
8328 i = 0;
8329 while (node) {
8330 stream = eb64_entry(node, struct qc_stream_desc, by_id);
8331 node = eb64_next(node);
8332
Amaury Denoyellea9de25a2023-02-10 09:25:22 +01008333 chunk_appendf(&trash, " | stream=%-8llu", (unsigned long long)stream->by_id.key);
8334 chunk_appendf(&trash, " off=%-8llu ack=%-8llu",
8335 (unsigned long long)stream->buf_offset,
8336 (unsigned long long)stream->ack_offset);
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008337
8338 if (!(++i % 3)) {
8339 chunk_appendf(&trash, "\n");
8340 i = 0;
8341 }
8342 }
8343
8344 chunk_appendf(&trash, "\n");
8345
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008346 if (applet_putchk(appctx, &trash) == -1) {
8347 /* Register show_quic_ctx to quic_conn instance. */
8348 LIST_APPEND(&qc->back_refs, &ctx->bref.users);
8349 goto full;
8350 }
8351
8352 ctx->bref.ref = qc->el_th_ctx.n;
8353 }
8354
8355 done:
8356 thread_release();
8357 return 1;
8358
8359 full:
8360 thread_release();
8361 return 0;
8362}
8363
8364static void cli_release_show_quic(struct appctx *appctx)
8365{
8366 struct show_quic_ctx *ctx = appctx->svcctx;
8367
8368 if (ctx->thr < global.nbthread) {
8369 thread_isolate();
8370 if (!LIST_ISEMPTY(&ctx->bref.users))
8371 LIST_DEL_INIT(&ctx->bref.users);
8372 thread_release();
8373 }
8374}
8375
8376static struct cli_kw_list cli_kws = {{ }, {
8377 { { "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 +01008378 {{},}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008379}};
8380
8381INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
8382
8383static void init_quic()
8384{
8385 int thr;
8386
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01008387 for (thr = 0; thr < MAX_THREADS; ++thr) {
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008388 LIST_INIT(&ha_thread_ctx[thr].quic_conns);
Amaury Denoyelleefed86c2023-03-08 09:42:04 +01008389 LIST_INIT(&ha_thread_ctx[thr].quic_conns_clo);
8390 }
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008391}
8392INITCALL0(STG_INIT, init_quic);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008393
8394/*
8395 * Local variables:
8396 * c-indent-level: 8
8397 * c-basic-offset: 8
8398 * End:
8399 */