blob: 1021bb130b26591761c2d84a1da18f710aa41f64 [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
223static struct quic_tx_packet *qc_build_pkt(unsigned char **pos, const unsigned char *buf_end,
224 struct quic_enc_level *qel, struct quic_tls_ctx *ctx,
225 struct list *frms, struct quic_conn *qc,
226 const struct quic_version *ver, size_t dglen, int pkt_type,
227 int force_ack, int padding, int probe, int cc, int *err);
228struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state);
229static void qc_idle_timer_do_rearm(struct quic_conn *qc);
230static void qc_idle_timer_rearm(struct quic_conn *qc, int read);
231static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc);
232static int quic_conn_init_timer(struct quic_conn *qc);
233static int quic_conn_init_idle_timer_task(struct quic_conn *qc);
234
235/* Only for debug purpose */
236struct enc_debug_info {
237 unsigned char *payload;
238 size_t payload_len;
239 unsigned char *aad;
240 size_t aad_len;
241 uint64_t pn;
242};
243
244/* Initializes a enc_debug_info struct (only for debug purpose) */
245static inline void enc_debug_info_init(struct enc_debug_info *edi,
246 unsigned char *payload, size_t payload_len,
247 unsigned char *aad, size_t aad_len, uint64_t pn)
248{
249 edi->payload = payload;
250 edi->payload_len = payload_len;
251 edi->aad = aad;
252 edi->aad_len = aad_len;
253 edi->pn = pn;
254}
255
256/* Trace callback for QUIC.
257 * These traces always expect that arg1, if non-null, is of type connection.
258 */
259static void quic_trace(enum trace_level level, uint64_t mask, const struct trace_source *src,
260 const struct ist where, const struct ist func,
261 const void *a1, const void *a2, const void *a3, const void *a4)
262{
263 const struct quic_conn *qc = a1;
264
265 if (qc) {
266 const struct quic_tls_ctx *tls_ctx;
267
268 chunk_appendf(&trace_buf, " : qc@%p", qc);
269 if (mask & QUIC_EV_CONN_INIT) {
270 chunk_appendf(&trace_buf, "\n odcid");
271 quic_cid_dump(&trace_buf, &qc->odcid);
272 chunk_appendf(&trace_buf, "\n dcid");
273 quic_cid_dump(&trace_buf, &qc->dcid);
274 chunk_appendf(&trace_buf, "\n scid");
275 quic_cid_dump(&trace_buf, &qc->scid);
276 }
277
278 if (mask & QUIC_EV_TRANSP_PARAMS) {
279 const struct quic_transport_params *p = a2;
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100280
281 if (p)
282 quic_transport_params_dump(&trace_buf, qc, p);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200283 }
284
285 if (mask & QUIC_EV_CONN_ADDDATA) {
286 const enum ssl_encryption_level_t *level = a2;
287 const size_t *len = a3;
288
289 if (level) {
290 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
291
292 chunk_appendf(&trace_buf, " el=%c(%d)", quic_enc_level_char(lvl), lvl);
293 }
294 if (len)
295 chunk_appendf(&trace_buf, " len=%llu", (unsigned long long)*len);
296 }
297 if ((mask & QUIC_EV_CONN_ISEC) && qc) {
298 /* Initial read & write secrets. */
299 enum quic_tls_enc_level level = QUIC_TLS_ENC_LEVEL_INITIAL;
300 const unsigned char *rx_sec = a2;
301 const unsigned char *tx_sec = a3;
302
303 tls_ctx = &qc->els[level].tls_ctx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200304 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(level));
305 if (rx_sec)
306 quic_tls_secret_hexdump(&trace_buf, rx_sec, 32);
307 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
308 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(level));
309 if (tx_sec)
310 quic_tls_secret_hexdump(&trace_buf, tx_sec, 32);
311 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200312 }
313 if (mask & (QUIC_EV_CONN_RSEC|QUIC_EV_CONN_RWSEC)) {
314 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200315
316 if (level) {
317 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
318
319 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200320 if (quic_tls_has_rx_sec(&qc->els[lvl])) {
321 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200322 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200323 }
324 else
325 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200326 }
327 }
328
329 if (mask & (QUIC_EV_CONN_WSEC|QUIC_EV_CONN_RWSEC)) {
330 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200331
332 if (level) {
333 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
334
335 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200336 if (quic_tls_has_tx_sec(&qc->els[lvl])) {
337 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200338 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200339 }
340 else
341 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200342 }
343
344 }
345
346 if (mask & QUIC_EV_CONN_FRMLIST) {
347 const struct list *l = a2;
348
349 if (l) {
350 const struct quic_frame *frm;
351 list_for_each_entry(frm, l, list) {
352 chunk_appendf(&trace_buf, " frm@%p", frm);
353 chunk_frm_appendf(&trace_buf, frm);
354 }
355 }
356 }
357
358 if (mask & (QUIC_EV_CONN_TXPKT|QUIC_EV_CONN_PAPKT)) {
359 const struct quic_tx_packet *pkt = a2;
360 const struct quic_enc_level *qel = a3;
361 const ssize_t *room = a4;
362
363 if (qel) {
364 const struct quic_pktns *pktns = qel->pktns;
Frédéric Lécaille45400532023-02-13 18:39:19 +0100365 chunk_appendf(&trace_buf, " qel=%c pto_count=%d cwnd=%llu ppif=%lld pif=%llu "
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200366 "if=%llu pp=%u",
367 quic_enc_level_char_from_qel(qel, qc),
Frédéric Lécaille45400532023-02-13 18:39:19 +0100368 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200369 (unsigned long long)qc->path->cwnd,
370 (unsigned long long)qc->path->prep_in_flight,
371 (unsigned long long)qc->path->in_flight,
372 (unsigned long long)pktns->tx.in_flight,
373 pktns->tx.pto_probe);
374 }
375 if (pkt) {
376 const struct quic_frame *frm;
377 if (pkt->pn_node.key != (uint64_t)-1)
378 chunk_appendf(&trace_buf, " pn=%llu",(ull)pkt->pn_node.key);
379 list_for_each_entry(frm, &pkt->frms, list) {
380 chunk_appendf(&trace_buf, " frm@%p", frm);
381 chunk_frm_appendf(&trace_buf, frm);
382 }
383 }
384
385 if (room) {
386 chunk_appendf(&trace_buf, " room=%lld", (long long)*room);
387 chunk_appendf(&trace_buf, " dcid.len=%llu scid.len=%llu",
388 (unsigned long long)qc->dcid.len, (unsigned long long)qc->scid.len);
389 }
390 }
391
392 if (mask & QUIC_EV_CONN_IO_CB) {
393 const enum quic_handshake_state *state = a2;
394 const int *err = a3;
395
396 if (state)
397 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(*state));
398 if (err)
399 chunk_appendf(&trace_buf, " err=%s", ssl_error_str(*err));
400 }
401
402 if (mask & (QUIC_EV_CONN_TRMHP|QUIC_EV_CONN_ELRMHP|QUIC_EV_CONN_SPKT)) {
403 const struct quic_rx_packet *pkt = a2;
404 const unsigned long *pktlen = a3;
405 const SSL *ssl = a4;
406
407 if (pkt) {
408 chunk_appendf(&trace_buf, " pkt@%p", pkt);
409 if (pkt->type == QUIC_PACKET_TYPE_SHORT && pkt->data)
410 chunk_appendf(&trace_buf, " kp=%d",
411 !!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT));
412 chunk_appendf(&trace_buf, " el=%c",
413 quic_packet_type_enc_level_char(pkt->type));
414 if (pkt->pnl)
415 chunk_appendf(&trace_buf, " pnl=%u pn=%llu", pkt->pnl,
416 (unsigned long long)pkt->pn);
417 if (pkt->token_len)
418 chunk_appendf(&trace_buf, " toklen=%llu",
419 (unsigned long long)pkt->token_len);
420 if (pkt->aad_len)
421 chunk_appendf(&trace_buf, " aadlen=%llu",
422 (unsigned long long)pkt->aad_len);
423 chunk_appendf(&trace_buf, " flags=0x%x len=%llu",
424 pkt->flags, (unsigned long long)pkt->len);
425 }
426 if (pktlen)
427 chunk_appendf(&trace_buf, " (%ld)", *pktlen);
428 if (ssl) {
429 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
430 chunk_appendf(&trace_buf, " el=%c",
431 quic_enc_level_char(ssl_to_quic_enc_level(level)));
432 }
433 }
434
435 if (mask & (QUIC_EV_CONN_RXPKT|QUIC_EV_CONN_PRSHPKT|QUIC_EV_CONN_SSLDATA)) {
436 const struct quic_rx_packet *pkt = a2;
437 const struct quic_rx_crypto_frm *cf = a3;
438 const SSL *ssl = a4;
439
440 if (pkt)
441 chunk_appendf(&trace_buf, " pkt@%p el=%c pn=%llu", pkt,
442 quic_packet_type_enc_level_char(pkt->type),
443 (unsigned long long)pkt->pn);
444 if (cf)
445 chunk_appendf(&trace_buf, " cfoff=%llu cflen=%llu",
446 (unsigned long long)cf->offset_node.key,
447 (unsigned long long)cf->len);
448 if (ssl) {
449 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
450 chunk_appendf(&trace_buf, " rel=%c",
451 quic_enc_level_char(ssl_to_quic_enc_level(level)));
452 }
453
454 if (qc->err.code)
455 chunk_appendf(&trace_buf, " err_code=0x%llx", (ull)qc->err.code);
456 }
457
458 if (mask & (QUIC_EV_CONN_PRSFRM|QUIC_EV_CONN_BFRM)) {
459 const struct quic_frame *frm = a2;
460
461 if (frm)
462 chunk_appendf(&trace_buf, " %s", quic_frame_type_string(frm->type));
463 }
464
465 if (mask & QUIC_EV_CONN_PHPKTS) {
466 const struct quic_enc_level *qel = a2;
467
468 if (qel) {
469 const struct quic_pktns *pktns = qel->pktns;
470 chunk_appendf(&trace_buf,
Frédéric Lécaille45400532023-02-13 18:39:19 +0100471 " 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 +0200472 quic_enc_level_char_from_qel(qel, qc),
473 quic_hdshk_state_str(qc->state),
474 !!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED),
Frédéric Lécaille45400532023-02-13 18:39:19 +0100475 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200476 (unsigned long long)qc->path->cwnd,
477 (unsigned long long)qc->path->prep_in_flight,
478 (unsigned long long)qc->path->in_flight,
479 (unsigned long long)pktns->tx.in_flight,
Amaury Denoyelle2f668f02022-11-18 15:24:08 +0100480 pktns->tx.pto_probe,
481 qel->cstream ? (unsigned long long)qel->cstream->rx.offset : 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200482 }
483 }
484
485 if (mask & QUIC_EV_CONN_ENCPKT) {
486 const struct enc_debug_info *edi = a2;
487
488 if (edi)
489 chunk_appendf(&trace_buf,
490 " payload=@%p payload_len=%llu"
491 " aad=@%p aad_len=%llu pn=%llu",
492 edi->payload, (unsigned long long)edi->payload_len,
493 edi->aad, (unsigned long long)edi->aad_len,
494 (unsigned long long)edi->pn);
495 }
496
497 if (mask & QUIC_EV_CONN_RMHP) {
498 const struct quic_rx_packet *pkt = a2;
499
500 if (pkt) {
501 const int *ret = a3;
502
503 chunk_appendf(&trace_buf, " pkt@%p", pkt);
504 if (ret && *ret)
505 chunk_appendf(&trace_buf, " pnl=%u pn=%llu",
506 pkt->pnl, (unsigned long long)pkt->pn);
507 }
508 }
509
510 if (mask & QUIC_EV_CONN_PRSAFRM) {
511 const struct quic_frame *frm = a2;
512 const unsigned long *val1 = a3;
513 const unsigned long *val2 = a4;
514
515 if (frm) {
516 chunk_appendf(&trace_buf, " frm@%p", frm);
517 chunk_frm_appendf(&trace_buf, frm);
518 }
519 if (val1)
520 chunk_appendf(&trace_buf, " %lu", *val1);
521 if (val2)
522 chunk_appendf(&trace_buf, "..%lu", *val2);
523 }
524
525 if (mask & QUIC_EV_CONN_ACKSTRM) {
526 const struct quic_stream *s = a2;
527 const struct qc_stream_desc *stream = a3;
528
529 if (s)
530 chunk_appendf(&trace_buf, " off=%llu len=%llu", (ull)s->offset.key, (ull)s->len);
531 if (stream)
532 chunk_appendf(&trace_buf, " ack_offset=%llu", (ull)stream->ack_offset);
533 }
534
535 if (mask & QUIC_EV_CONN_RTTUPDT) {
536 const unsigned int *rtt_sample = a2;
537 const unsigned int *ack_delay = a3;
538 const struct quic_loss *ql = a4;
539
540 if (rtt_sample)
541 chunk_appendf(&trace_buf, " rtt_sample=%ums", *rtt_sample);
542 if (ack_delay)
543 chunk_appendf(&trace_buf, " ack_delay=%ums", *ack_delay);
544 if (ql)
545 chunk_appendf(&trace_buf,
546 " srtt=%ums rttvar=%ums min_rtt=%ums",
547 ql->srtt >> 3, ql->rtt_var >> 2, ql->rtt_min);
548 }
549 if (mask & QUIC_EV_CONN_CC) {
550 const struct quic_cc_event *ev = a2;
551 const struct quic_cc *cc = a3;
552
553 if (a2)
554 quic_cc_event_trace(&trace_buf, ev);
555 if (a3)
556 quic_cc_state_trace(&trace_buf, cc);
557 }
558
559 if (mask & QUIC_EV_CONN_PKTLOSS) {
560 const struct quic_pktns *pktns = a2;
561 const struct list *lost_pkts = a3;
562
563 if (pktns) {
564 chunk_appendf(&trace_buf, " pktns=%s",
565 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
566 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H");
567 if (pktns->tx.loss_time)
568 chunk_appendf(&trace_buf, " loss_time=%dms",
569 TICKS_TO_MS(tick_remain(now_ms, pktns->tx.loss_time)));
570 }
571 if (lost_pkts && !LIST_ISEMPTY(lost_pkts)) {
572 struct quic_tx_packet *pkt;
573
574 chunk_appendf(&trace_buf, " lost_pkts:");
575 list_for_each_entry(pkt, lost_pkts, list)
576 chunk_appendf(&trace_buf, " %lu", (unsigned long)pkt->pn_node.key);
577 }
578 }
579
580 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_PTIMER|QUIC_EV_CONN_SPTO)) {
581 const struct quic_pktns *pktns = a2;
582 const int *duration = a3;
583 const uint64_t *ifae_pkts = a4;
584
585 if (ifae_pkts)
586 chunk_appendf(&trace_buf, " ifae_pkts=%llu",
587 (unsigned long long)*ifae_pkts);
588 if (pktns) {
589 chunk_appendf(&trace_buf, " pktns=%s pp=%d",
590 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
591 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
592 pktns->tx.pto_probe);
593 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_SPTO)) {
594 if (pktns->tx.in_flight)
595 chunk_appendf(&trace_buf, " if=%llu", (ull)pktns->tx.in_flight);
596 if (pktns->tx.loss_time)
597 chunk_appendf(&trace_buf, " loss_time=%dms",
598 TICKS_TO_MS(pktns->tx.loss_time - now_ms));
599 }
600 if (mask & QUIC_EV_CONN_SPTO) {
601 if (pktns->tx.time_of_last_eliciting)
602 chunk_appendf(&trace_buf, " tole=%dms",
603 TICKS_TO_MS(pktns->tx.time_of_last_eliciting - now_ms));
604 if (duration)
605 chunk_appendf(&trace_buf, " dur=%dms", TICKS_TO_MS(*duration));
606 }
607 }
608
609 if (!(mask & (QUIC_EV_CONN_SPTO|QUIC_EV_CONN_PTIMER)) && qc->timer_task) {
610 chunk_appendf(&trace_buf,
611 " expire=%dms", TICKS_TO_MS(qc->timer - now_ms));
612 }
613 }
614
615 if (mask & QUIC_EV_CONN_SPPKTS) {
616 const struct quic_tx_packet *pkt = a2;
617
Frédéric Lécaille45400532023-02-13 18:39:19 +0100618 chunk_appendf(&trace_buf, " pto_count=%d cwnd=%llu ppif=%llu pif=%llu",
619 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200620 (unsigned long long)qc->path->cwnd,
621 (unsigned long long)qc->path->prep_in_flight,
622 (unsigned long long)qc->path->in_flight);
623 if (pkt) {
624 const struct quic_frame *frm;
625 chunk_appendf(&trace_buf, " pn=%lu(%s) iflen=%llu",
626 (unsigned long)pkt->pn_node.key,
627 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
628 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
629 (unsigned long long)pkt->in_flight_len);
630 chunk_appendf(&trace_buf, " rx.bytes=%llu tx.bytes=%llu",
631 (unsigned long long)qc->rx.bytes,
632 (unsigned long long)qc->tx.bytes);
633 list_for_each_entry(frm, &pkt->frms, list) {
634 chunk_appendf(&trace_buf, " frm@%p", frm);
635 chunk_frm_appendf(&trace_buf, frm);
636 }
Frédéric Lécaillebc09f742023-02-13 17:45:36 +0100637
638 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
639 chunk_appendf(&trace_buf, " with scid");
640 quic_cid_dump(&trace_buf, &qc->scid);
641 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200642 }
643 }
644
645 if (mask & QUIC_EV_CONN_SSLALERT) {
646 const uint8_t *alert = a2;
647 const enum ssl_encryption_level_t *level = a3;
648
649 if (alert)
650 chunk_appendf(&trace_buf, " alert=0x%02x", *alert);
651 if (level)
652 chunk_appendf(&trace_buf, " el=%c",
653 quic_enc_level_char(ssl_to_quic_enc_level(*level)));
654 }
655
656 if (mask & QUIC_EV_CONN_BCFRMS) {
657 const size_t *sz1 = a2;
658 const size_t *sz2 = a3;
659 const size_t *sz3 = a4;
660
661 if (sz1)
662 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz1);
663 if (sz2)
664 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz2);
665 if (sz3)
666 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz3);
667 }
668
669 if (mask & QUIC_EV_CONN_PSTRM) {
670 const struct quic_frame *frm = a2;
671
672 if (frm) {
673 chunk_appendf(&trace_buf, " frm@%p", frm);
674 chunk_frm_appendf(&trace_buf, frm);
675 }
676 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +0200677
678 if (mask & QUIC_EV_CONN_ELEVELSEL) {
679 const enum quic_handshake_state *state = a2;
680 const enum quic_tls_enc_level *level = a3;
681 const enum quic_tls_enc_level *next_level = a4;
682
683 if (state)
684 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(qc->state));
685 if (level)
686 chunk_appendf(&trace_buf, " level=%c", quic_enc_level_char(*level));
687 if (next_level)
688 chunk_appendf(&trace_buf, " next_level=%c", quic_enc_level_char(*next_level));
689
690 }
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200691
692 if (mask & QUIC_EV_CONN_RCV) {
693 const struct quic_dgram *dgram = a2;
694
695 if (dgram)
696 chunk_appendf(&trace_buf, " dgram.len=%zu", dgram->len);
697 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200698 }
699 if (mask & QUIC_EV_CONN_LPKT) {
700 const struct quic_rx_packet *pkt = a2;
701 const uint64_t *len = a3;
702 const struct quic_version *ver = a4;
703
704 if (pkt) {
705 chunk_appendf(&trace_buf, " pkt@%p type=0x%02x %s",
706 pkt, pkt->type, qc_pkt_long(pkt) ? "long" : "short");
707 if (pkt->pn_node.key != (uint64_t)-1)
708 chunk_appendf(&trace_buf, " pn=%llu", pkt->pn_node.key);
709 }
710
711 if (len)
712 chunk_appendf(&trace_buf, " len=%llu", (ull)*len);
713
714 if (ver)
715 chunk_appendf(&trace_buf, " ver=0x%08x", ver->num);
716 }
717
718 if (mask & QUIC_EV_STATELESS_RST) {
719 const struct quic_cid *cid = a2;
720
721 if (cid)
722 quic_cid_dump(&trace_buf, cid);
723 }
724
725}
726
727/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
728static inline int quic_peer_validated_addr(struct quic_conn *qc)
729{
730 struct quic_pktns *hdshk_pktns, *app_pktns;
731
732 if (!qc_is_listener(qc))
733 return 1;
734
735 hdshk_pktns = qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns;
736 app_pktns = qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns;
737 if ((hdshk_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
738 (app_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
739 qc->state >= QUIC_HS_ST_COMPLETE)
740 return 1;
741
742 return 0;
743}
744
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100745/* To be called to kill a connection as soon as possible (without sending any packet). */
746void qc_kill_conn(struct quic_conn *qc)
747{
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100748 TRACE_ENTER(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100749 qc->flags |= QUIC_FL_CONN_TO_KILL;
750 task_wakeup(qc->idle_timer_task, TASK_WOKEN_OTHER);
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100751 TRACE_LEAVE(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100752}
753
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200754/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
755 * both loss detection and PTO and schedule the task assiated to this timer if needed.
756 */
757static inline void qc_set_timer(struct quic_conn *qc)
758{
759 struct quic_pktns *pktns;
760 unsigned int pto;
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100761 int handshake_confirmed;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200762
763 TRACE_ENTER(QUIC_EV_CONN_STIMER, qc,
764 NULL, NULL, &qc->path->ifae_pkts);
765
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100766 pktns = NULL;
767 if (!qc->timer_task) {
768 TRACE_PROTO("already released timer task", QUIC_EV_CONN_STIMER, qc);
769 goto leave;
770 }
771
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200772 pktns = quic_loss_pktns(qc);
773 if (tick_isset(pktns->tx.loss_time)) {
774 qc->timer = pktns->tx.loss_time;
775 goto out;
776 }
777
778 /* anti-amplification: the timer must be
779 * cancelled for a server which reached the anti-amplification limit.
780 */
781 if (!quic_peer_validated_addr(qc) &&
782 (qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
783 TRACE_PROTO("anti-amplification reached", QUIC_EV_CONN_STIMER, qc);
784 qc->timer = TICK_ETERNITY;
785 goto out;
786 }
787
788 if (!qc->path->ifae_pkts && quic_peer_validated_addr(qc)) {
789 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, qc);
790 /* Timer cancellation. */
791 qc->timer = TICK_ETERNITY;
792 goto out;
793 }
794
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100795 handshake_confirmed = qc->state >= QUIC_HS_ST_CONFIRMED;
796 pktns = quic_pto_pktns(qc, handshake_confirmed, &pto);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200797 if (tick_isset(pto))
798 qc->timer = pto;
799 out:
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100800 if (qc->timer == TICK_ETERNITY) {
801 qc->timer_task->expire = TICK_ETERNITY;
802 }
803 else if (tick_is_expired(qc->timer, now_ms)) {
804 TRACE_DEVEL("wakeup asap timer task", QUIC_EV_CONN_STIMER, qc);
805 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
806 }
807 else {
808 TRACE_DEVEL("timer task scheduling", QUIC_EV_CONN_STIMER, qc);
809 task_schedule(qc->timer_task, qc->timer);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200810 }
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100811 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200812 TRACE_LEAVE(QUIC_EV_CONN_STIMER, qc, pktns);
813}
814
815/* Derive new keys and ivs required for Key Update feature for <qc> QUIC
816 * connection.
817 * Return 1 if succeeded, 0 if not.
818 */
819static int quic_tls_key_update(struct quic_conn *qc)
820{
821 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
822 struct quic_tls_secrets *rx, *tx;
823 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
824 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
825 const struct quic_version *ver =
826 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
827 int ret = 0;
828
829 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
830
831 tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
832 rx = &tls_ctx->rx;
833 tx = &tls_ctx->tx;
834 nxt_rx = &qc->ku.nxt_rx;
835 nxt_tx = &qc->ku.nxt_tx;
836
837 /* Prepare new RX secrets */
838 if (!quic_tls_sec_update(rx->md, ver, nxt_rx->secret, nxt_rx->secretlen,
839 rx->secret, rx->secretlen)) {
840 TRACE_ERROR("New RX secret update failed", QUIC_EV_CONN_RWSEC, qc);
841 goto leave;
842 }
843
844 if (!quic_tls_derive_keys(rx->aead, NULL, rx->md, ver,
845 nxt_rx->key, nxt_rx->keylen,
846 nxt_rx->iv, nxt_rx->ivlen, NULL, 0,
847 nxt_rx->secret, nxt_rx->secretlen)) {
848 TRACE_ERROR("New RX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
849 goto leave;
850 }
851
852 /* Prepare new TX secrets */
853 if (!quic_tls_sec_update(tx->md, ver, nxt_tx->secret, nxt_tx->secretlen,
854 tx->secret, tx->secretlen)) {
855 TRACE_ERROR("New TX secret update failed", QUIC_EV_CONN_RWSEC, qc);
856 goto leave;
857 }
858
859 if (!quic_tls_derive_keys(tx->aead, NULL, tx->md, ver,
860 nxt_tx->key, nxt_tx->keylen,
861 nxt_tx->iv, nxt_tx->ivlen, NULL, 0,
862 nxt_tx->secret, nxt_tx->secretlen)) {
863 TRACE_ERROR("New TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
864 goto leave;
865 }
866
867 if (nxt_rx->ctx) {
868 EVP_CIPHER_CTX_free(nxt_rx->ctx);
869 nxt_rx->ctx = NULL;
870 }
871
872 if (!quic_tls_rx_ctx_init(&nxt_rx->ctx, tls_ctx->rx.aead, nxt_rx->key)) {
873 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
874 goto leave;
875 }
876
877 if (nxt_tx->ctx) {
878 EVP_CIPHER_CTX_free(nxt_tx->ctx);
879 nxt_tx->ctx = NULL;
880 }
881
882 if (!quic_tls_rx_ctx_init(&nxt_tx->ctx, tls_ctx->tx.aead, nxt_tx->key)) {
883 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
884 goto leave;
885 }
886
887 ret = 1;
888 leave:
889 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc);
890 return ret;
891}
892
893/* Rotate the Key Update information for <qc> QUIC connection.
894 * Must be used after having updated them.
895 * Always succeeds.
896 */
897static void quic_tls_rotate_keys(struct quic_conn *qc)
898{
899 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
900 unsigned char *curr_secret, *curr_iv, *curr_key;
901 EVP_CIPHER_CTX *curr_ctx;
902
903 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
904
905 /* Rotate the RX secrets */
906 curr_ctx = tls_ctx->rx.ctx;
907 curr_secret = tls_ctx->rx.secret;
908 curr_iv = tls_ctx->rx.iv;
909 curr_key = tls_ctx->rx.key;
910
911 tls_ctx->rx.ctx = qc->ku.nxt_rx.ctx;
912 tls_ctx->rx.secret = qc->ku.nxt_rx.secret;
913 tls_ctx->rx.iv = qc->ku.nxt_rx.iv;
914 tls_ctx->rx.key = qc->ku.nxt_rx.key;
915
916 qc->ku.nxt_rx.ctx = qc->ku.prv_rx.ctx;
917 qc->ku.nxt_rx.secret = qc->ku.prv_rx.secret;
918 qc->ku.nxt_rx.iv = qc->ku.prv_rx.iv;
919 qc->ku.nxt_rx.key = qc->ku.prv_rx.key;
920
921 qc->ku.prv_rx.ctx = curr_ctx;
922 qc->ku.prv_rx.secret = curr_secret;
923 qc->ku.prv_rx.iv = curr_iv;
924 qc->ku.prv_rx.key = curr_key;
925 qc->ku.prv_rx.pn = tls_ctx->rx.pn;
926
927 /* Update the TX secrets */
928 curr_ctx = tls_ctx->tx.ctx;
929 curr_secret = tls_ctx->tx.secret;
930 curr_iv = tls_ctx->tx.iv;
931 curr_key = tls_ctx->tx.key;
932
933 tls_ctx->tx.ctx = qc->ku.nxt_tx.ctx;
934 tls_ctx->tx.secret = qc->ku.nxt_tx.secret;
935 tls_ctx->tx.iv = qc->ku.nxt_tx.iv;
936 tls_ctx->tx.key = qc->ku.nxt_tx.key;
937
938 qc->ku.nxt_tx.ctx = curr_ctx;
939 qc->ku.nxt_tx.secret = curr_secret;
940 qc->ku.nxt_tx.iv = curr_iv;
941 qc->ku.nxt_tx.key = curr_key;
942
943 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
944}
945
946/* returns 0 on error, 1 on success */
947int ha_quic_set_encryption_secrets(SSL *ssl, enum ssl_encryption_level_t level,
948 const uint8_t *read_secret,
949 const uint8_t *write_secret, size_t secret_len)
950{
951 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
952 struct quic_tls_ctx *tls_ctx = &qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
953 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200954 struct quic_tls_secrets *rx = NULL, *tx = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200955 const struct quic_version *ver =
956 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
957 int ret = 0;
958
959 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
960 BUG_ON(secret_len > QUIC_TLS_SECRET_LEN);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100961
962 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
963 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
964 goto out;
965 }
966
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200967 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
968 TRACE_PROTO("CC required", QUIC_EV_CONN_RWSEC, qc);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200969 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200970 }
971
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200972 if (!read_secret)
973 goto write;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200974
975 rx = &tls_ctx->rx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200976 if (!quic_tls_secrets_keys_alloc(rx)) {
977 TRACE_ERROR("RX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
978 goto leave;
979 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200980
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200981 rx->aead = tls_aead(cipher);
982 rx->md = tls_md(cipher);
983 rx->hp = tls_hp(cipher);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200984
985 if (!quic_tls_derive_keys(rx->aead, rx->hp, rx->md, ver, rx->key, rx->keylen,
986 rx->iv, rx->ivlen, rx->hp_key, sizeof rx->hp_key,
987 read_secret, secret_len)) {
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200988 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200989 goto leave;
990 }
991
992 if (!quic_tls_rx_ctx_init(&rx->ctx, rx->aead, rx->key)) {
993 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
994 goto leave;
995 }
996
997 if (!quic_tls_dec_aes_ctx_init(&rx->hp_ctx, rx->hp, rx->hp_key)) {
998 TRACE_ERROR("could not initial RX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
999 goto leave;
1000 }
1001
1002 /* Enqueue this connection asap if we could derive O-RTT secrets as
1003 * listener. Note that a listener derives only RX secrets for this
1004 * level.
1005 */
1006 if (qc_is_listener(qc) && level == ssl_encryption_early_data) {
1007 TRACE_DEVEL("pushing connection into accept queue", QUIC_EV_CONN_RWSEC, qc);
1008 quic_accept_push_qc(qc);
1009 }
1010
1011write:
1012
1013 if (!write_secret)
1014 goto out;
1015
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001016 tx = &tls_ctx->tx;
1017 if (!quic_tls_secrets_keys_alloc(tx)) {
1018 TRACE_ERROR("TX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
1019 goto leave;
1020 }
1021
1022 tx->aead = tls_aead(cipher);
1023 tx->md = tls_md(cipher);
1024 tx->hp = tls_hp(cipher);
1025
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001026 if (!quic_tls_derive_keys(tx->aead, tx->hp, tx->md, ver, tx->key, tx->keylen,
1027 tx->iv, tx->ivlen, tx->hp_key, sizeof tx->hp_key,
1028 write_secret, secret_len)) {
1029 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
1030 goto leave;
1031 }
1032
1033 if (!quic_tls_tx_ctx_init(&tx->ctx, tx->aead, tx->key)) {
1034 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
1035 goto leave;
1036 }
1037
1038 if (!quic_tls_enc_aes_ctx_init(&tx->hp_ctx, tx->hp, tx->hp_key)) {
1039 TRACE_ERROR("could not initial TX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
1040 goto leave;
1041 }
1042
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01001043 if (level == ssl_encryption_handshake && qc_is_listener(qc)) {
1044 qc->enc_params_len =
1045 quic_transport_params_encode(qc->enc_params,
1046 qc->enc_params + sizeof qc->enc_params,
1047 &qc->rx.params, ver, 1);
1048 if (!qc->enc_params_len) {
1049 TRACE_ERROR("quic_transport_params_encode() failed", QUIC_EV_CONN_RWSEC);
1050 goto leave;
1051 }
1052
1053 if (!SSL_set_quic_transport_params(qc->xprt_ctx->ssl, qc->enc_params, qc->enc_params_len)) {
1054 TRACE_ERROR("SSL_set_quic_transport_params() failed", QUIC_EV_CONN_RWSEC);
1055 goto leave;
1056 }
1057 }
1058
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001059 if (level == ssl_encryption_application) {
1060 struct quic_tls_kp *prv_rx = &qc->ku.prv_rx;
1061 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
1062 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
1063
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001064 if (rx) {
1065 if (!(rx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1066 TRACE_ERROR("Could not allocate RX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1067 goto leave;
1068 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001069
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001070 memcpy(rx->secret, read_secret, secret_len);
1071 rx->secretlen = secret_len;
1072 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001073
1074 if (tx) {
1075 if (!(tx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1076 TRACE_ERROR("Could not allocate TX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1077 goto leave;
1078 }
1079
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001080 memcpy(tx->secret, write_secret, secret_len);
1081 tx->secretlen = secret_len;
1082 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001083
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001084 /* Initialize all the secret keys lengths */
1085 prv_rx->secretlen = nxt_rx->secretlen = nxt_tx->secretlen = secret_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001086 }
1087
1088 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001089 ret = 1;
1090 leave:
1091 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc, &level);
1092 return ret;
1093}
1094
1095/* This function copies the CRYPTO data provided by the TLS stack found at <data>
1096 * with <len> as size in CRYPTO buffers dedicated to store the information about
1097 * outgoing CRYPTO frames so that to be able to replay the CRYPTO data streams.
1098 * It fails (returns 0) only if it could not managed to allocate enough CRYPTO
1099 * buffers to store all the data.
1100 * Note that CRYPTO data may exist at any encryption level except at 0-RTT.
1101 */
1102static int quic_crypto_data_cpy(struct quic_conn *qc, struct quic_enc_level *qel,
1103 const unsigned char *data, size_t len)
1104{
1105 struct quic_crypto_buf **qcb;
1106 /* The remaining byte to store in CRYPTO buffers. */
1107 size_t cf_offset, cf_len, *nb_buf;
1108 unsigned char *pos;
1109 int ret = 0;
1110
1111 nb_buf = &qel->tx.crypto.nb_buf;
1112 qcb = &qel->tx.crypto.bufs[*nb_buf - 1];
1113 cf_offset = (*nb_buf - 1) * QUIC_CRYPTO_BUF_SZ + (*qcb)->sz;
1114 cf_len = len;
1115
1116 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1117
1118 while (len) {
1119 size_t to_copy, room;
1120
1121 pos = (*qcb)->data + (*qcb)->sz;
1122 room = QUIC_CRYPTO_BUF_SZ - (*qcb)->sz;
1123 to_copy = len > room ? room : len;
1124 if (to_copy) {
1125 memcpy(pos, data, to_copy);
1126 /* Increment the total size of this CRYPTO buffers by <to_copy>. */
1127 qel->tx.crypto.sz += to_copy;
1128 (*qcb)->sz += to_copy;
1129 len -= to_copy;
1130 data += to_copy;
1131 }
1132 else {
1133 struct quic_crypto_buf **tmp;
1134
1135 // FIXME: realloc!
1136 tmp = realloc(qel->tx.crypto.bufs,
1137 (*nb_buf + 1) * sizeof *qel->tx.crypto.bufs);
1138 if (tmp) {
1139 qel->tx.crypto.bufs = tmp;
1140 qcb = &qel->tx.crypto.bufs[*nb_buf];
1141 *qcb = pool_alloc(pool_head_quic_crypto_buf);
1142 if (!*qcb) {
1143 TRACE_ERROR("Could not allocate crypto buf", QUIC_EV_CONN_ADDDATA, qc);
1144 goto leave;
1145 }
1146
1147 (*qcb)->sz = 0;
1148 ++*nb_buf;
1149 }
1150 else {
1151 break;
1152 }
1153 }
1154 }
1155
1156 /* Allocate a TX CRYPTO frame only if all the CRYPTO data
1157 * have been buffered.
1158 */
1159 if (!len) {
1160 struct quic_frame *frm;
1161 struct quic_frame *found = NULL;
1162
1163 /* There is at most one CRYPTO frame in this packet number
1164 * space. Let's look for it.
1165 */
1166 list_for_each_entry(frm, &qel->pktns->tx.frms, list) {
1167 if (frm->type != QUIC_FT_CRYPTO)
1168 continue;
1169
1170 /* Found */
1171 found = frm;
1172 break;
1173 }
1174
1175 if (found) {
1176 found->crypto.len += cf_len;
1177 }
1178 else {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01001179 frm = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001180 if (!frm) {
1181 TRACE_ERROR("Could not allocate quic frame", QUIC_EV_CONN_ADDDATA, qc);
1182 goto leave;
1183 }
1184
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001185 frm->crypto.offset = cf_offset;
1186 frm->crypto.len = cf_len;
1187 frm->crypto.qel = qel;
1188 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
1189 }
1190 }
1191 ret = len == 0;
1192 leave:
1193 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1194 return ret;
1195}
1196
1197/* Prepare the emission of CONNECTION_CLOSE with error <err>. All send/receive
1198 * activity for <qc> will be interrupted.
1199 */
1200void quic_set_connection_close(struct quic_conn *qc, const struct quic_err err)
1201{
1202 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1203 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)
1204 goto leave;
1205
1206 TRACE_STATE("setting immediate close", QUIC_EV_CONN_CLOSE, qc);
1207 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
1208 qc->err.code = err.code;
1209 qc->err.app = err.app;
1210 leave:
1211 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1212}
1213
1214/* Set <alert> TLS alert as QUIC CRYPTO_ERROR error */
1215void quic_set_tls_alert(struct quic_conn *qc, int alert)
1216{
1217 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1218
1219 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
1220 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
1221 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
1222 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
1223 }
1224 quic_set_connection_close(qc, quic_err_tls(alert));
1225 qc->flags |= QUIC_FL_CONN_TLS_ALERT;
1226 TRACE_STATE("Alert set", QUIC_EV_CONN_SSLALERT, qc);
1227
1228 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1229}
1230
1231/* Set the application for <qc> QUIC connection.
1232 * Return 1 if succeeded, 0 if not.
1233 */
1234int quic_set_app_ops(struct quic_conn *qc, const unsigned char *alpn, size_t alpn_len)
1235{
1236 if (alpn_len >= 2 && memcmp(alpn, "h3", 2) == 0)
1237 qc->app_ops = &h3_ops;
1238 else if (alpn_len >= 10 && memcmp(alpn, "hq-interop", 10) == 0)
1239 qc->app_ops = &hq_interop_ops;
1240 else
1241 return 0;
1242
1243 return 1;
1244}
1245
1246/* ->add_handshake_data QUIC TLS callback used by the QUIC TLS stack when it
1247 * wants to provide the QUIC layer with CRYPTO data.
1248 * Returns 1 if succeeded, 0 if not.
1249 */
1250int ha_quic_add_handshake_data(SSL *ssl, enum ssl_encryption_level_t level,
1251 const uint8_t *data, size_t len)
1252{
1253 struct quic_conn *qc;
1254 enum quic_tls_enc_level tel;
1255 struct quic_enc_level *qel;
1256 int ret = 0;
1257
1258 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1259 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1260
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01001261 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
1262 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
1263 goto out;
1264 }
1265
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001266 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
1267 TRACE_PROTO("CC required", QUIC_EV_CONN_ADDDATA, qc);
1268 goto out;
1269 }
1270
1271 tel = ssl_to_quic_enc_level(level);
1272 if (tel == -1) {
1273 TRACE_ERROR("Wrong encryption level", QUIC_EV_CONN_ADDDATA, qc);
1274 goto leave;
1275 }
1276
1277 qel = &qc->els[tel];
1278 if (!quic_crypto_data_cpy(qc, qel, data, len)) {
1279 TRACE_ERROR("Could not bufferize", QUIC_EV_CONN_ADDDATA, qc);
1280 goto leave;
1281 }
1282
1283 TRACE_DEVEL("CRYPTO data buffered", QUIC_EV_CONN_ADDDATA,
1284 qc, &level, &len);
1285 out:
1286 ret = 1;
1287 leave:
1288 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1289 return ret;
1290}
1291
1292int ha_quic_flush_flight(SSL *ssl)
1293{
1294 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1295
1296 TRACE_ENTER(QUIC_EV_CONN_FFLIGHT, qc);
1297 TRACE_LEAVE(QUIC_EV_CONN_FFLIGHT, qc);
1298
1299 return 1;
1300}
1301
1302int ha_quic_send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
1303{
1304 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1305
1306 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1307
1308 TRACE_PROTO("Received TLS alert", QUIC_EV_CONN_SSLALERT, qc, &alert, &level);
1309
1310 quic_set_tls_alert(qc, alert);
1311 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1312 return 1;
1313}
1314
1315/* QUIC TLS methods */
1316static SSL_QUIC_METHOD ha_quic_method = {
1317 .set_encryption_secrets = ha_quic_set_encryption_secrets,
1318 .add_handshake_data = ha_quic_add_handshake_data,
1319 .flush_flight = ha_quic_flush_flight,
1320 .send_alert = ha_quic_send_alert,
1321};
1322
1323/* Initialize the TLS context of a listener with <bind_conf> as configuration.
1324 * Returns an error count.
1325 */
1326int ssl_quic_initial_ctx(struct bind_conf *bind_conf)
1327{
1328 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
1329 int cfgerr = 0;
1330
1331 long options =
1332 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1333 SSL_OP_SINGLE_ECDH_USE |
1334 SSL_OP_CIPHER_SERVER_PREFERENCE;
1335 SSL_CTX *ctx;
1336
1337 ctx = SSL_CTX_new(TLS_server_method());
1338 bind_conf->initial_ctx = ctx;
1339
1340 SSL_CTX_set_options(ctx, options);
1341 SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
1342 SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
1343 SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
1344
1345#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1346# if defined(HAVE_SSL_CLIENT_HELLO_CB)
1347# if defined(SSL_OP_NO_ANTI_REPLAY)
1348 if (bind_conf->ssl_conf.early_data) {
1349 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
1350 SSL_CTX_set_max_early_data(ctx, 0xffffffff);
1351 }
1352# endif /* !SSL_OP_NO_ANTI_REPLAY */
1353 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
1354 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
1355# else /* ! HAVE_SSL_CLIENT_HELLO_CB */
1356 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
1357# endif
1358 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
1359#endif
1360 SSL_CTX_set_quic_method(ctx, &ha_quic_method);
1361
1362 return cfgerr;
1363}
1364
1365/* Decode an expected packet number from <truncated_on> its truncated value,
1366 * depending on <largest_pn> the largest received packet number, and <pn_nbits>
1367 * the number of bits used to encode this packet number (its length in bytes * 8).
1368 * See https://quicwg.org/base-drafts/draft-ietf-quic-transport.html#packet-encoding
1369 */
1370static uint64_t decode_packet_number(uint64_t largest_pn,
1371 uint32_t truncated_pn, unsigned int pn_nbits)
1372{
1373 uint64_t expected_pn = largest_pn + 1;
1374 uint64_t pn_win = (uint64_t)1 << pn_nbits;
1375 uint64_t pn_hwin = pn_win / 2;
1376 uint64_t pn_mask = pn_win - 1;
1377 uint64_t candidate_pn;
1378
1379
1380 candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
1381 /* Note that <pn_win> > <pn_hwin>. */
1382 if (candidate_pn < QUIC_MAX_PACKET_NUM - pn_win &&
1383 candidate_pn + pn_hwin <= expected_pn)
1384 return candidate_pn + pn_win;
1385
1386 if (candidate_pn > expected_pn + pn_hwin && candidate_pn >= pn_win)
1387 return candidate_pn - pn_win;
1388
1389 return candidate_pn;
1390}
1391
1392/* Remove the header protection of <pkt> QUIC packet using <tls_ctx> as QUIC TLS
1393 * cryptographic context.
1394 * <largest_pn> is the largest received packet number and <pn> the address of
1395 * the packet number field for this packet with <byte0> address of its first byte.
1396 * <end> points to one byte past the end of this packet.
1397 * Returns 1 if succeeded, 0 if not.
1398 */
1399static int qc_do_rm_hp(struct quic_conn *qc,
1400 struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx,
1401 int64_t largest_pn, unsigned char *pn, unsigned char *byte0)
1402{
1403 int ret, i, pnlen;
1404 uint64_t packet_number;
1405 uint32_t truncated_pn = 0;
1406 unsigned char mask[5] = {0};
1407 unsigned char *sample;
1408 EVP_CIPHER_CTX *cctx = NULL;
1409
1410 TRACE_ENTER(QUIC_EV_CONN_RMHP, qc);
1411
1412 ret = 0;
1413
1414 /* Check there is enough data in this packet. */
1415 if (pkt->len - (pn - byte0) < QUIC_PACKET_PN_MAXLEN + sizeof mask) {
1416 TRACE_PROTO("too short packet", QUIC_EV_CONN_RMHP, qc, pkt);
1417 goto leave;
1418 }
1419
1420 cctx = EVP_CIPHER_CTX_new();
1421 if (!cctx) {
1422 TRACE_ERROR("memory allocation failed", QUIC_EV_CONN_RMHP, qc, pkt);
1423 goto leave;
1424 }
1425
1426 sample = pn + QUIC_PACKET_PN_MAXLEN;
1427
1428 if (!quic_tls_aes_decrypt(mask, sample, sizeof mask, tls_ctx->rx.hp_ctx)) {
1429 TRACE_ERROR("HP removing failed", QUIC_EV_CONN_RMHP, qc, pkt);
1430 goto leave;
1431 }
1432
1433 *byte0 ^= mask[0] & (*byte0 & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
1434 pnlen = (*byte0 & QUIC_PACKET_PNL_BITMASK) + 1;
1435 for (i = 0; i < pnlen; i++) {
1436 pn[i] ^= mask[i + 1];
1437 truncated_pn = (truncated_pn << 8) | pn[i];
1438 }
1439
1440 packet_number = decode_packet_number(largest_pn, truncated_pn, pnlen * 8);
1441 /* Store remaining information for this unprotected header */
1442 pkt->pn = packet_number;
1443 pkt->pnl = pnlen;
1444
1445 ret = 1;
1446 leave:
1447 if (cctx)
1448 EVP_CIPHER_CTX_free(cctx);
1449 TRACE_LEAVE(QUIC_EV_CONN_RMHP, qc);
1450 return ret;
1451}
1452
1453/* Encrypt the payload of a QUIC packet with <pn> as number found at <payload>
1454 * address, with <payload_len> as payload length, <aad> as address of
1455 * the ADD and <aad_len> as AAD length depending on the <tls_ctx> QUIC TLS
1456 * context.
1457 * Returns 1 if succeeded, 0 if not.
1458 */
1459static int quic_packet_encrypt(unsigned char *payload, size_t payload_len,
1460 unsigned char *aad, size_t aad_len, uint64_t pn,
1461 struct quic_tls_ctx *tls_ctx, struct quic_conn *qc)
1462{
1463 int ret = 0;
1464 unsigned char iv[QUIC_TLS_IV_LEN];
1465 unsigned char *tx_iv = tls_ctx->tx.iv;
1466 size_t tx_iv_sz = tls_ctx->tx.ivlen;
1467 struct enc_debug_info edi;
1468
1469 TRACE_ENTER(QUIC_EV_CONN_ENCPKT, qc);
1470
1471 if (!quic_aead_iv_build(iv, sizeof iv, tx_iv, tx_iv_sz, pn)) {
1472 TRACE_ERROR("AEAD IV building for encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1473 goto err;
1474 }
1475
1476 if (!quic_tls_encrypt(payload, payload_len, aad, aad_len,
1477 tls_ctx->tx.ctx, tls_ctx->tx.aead, tls_ctx->tx.key, iv)) {
1478 TRACE_ERROR("QUIC packet encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1479 goto err;
1480 }
1481
1482 ret = 1;
1483 leave:
1484 TRACE_LEAVE(QUIC_EV_CONN_ENCPKT, qc);
1485 return ret;
1486
1487 err:
1488 enc_debug_info_init(&edi, payload, payload_len, aad, aad_len, pn);
1489 goto leave;
1490}
1491
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001492/* Decrypt <pkt> packet using encryption level <qel> for <qc> connection.
1493 * Decryption is done in place in packet buffer.
1494 *
Ilya Shipitsin5fa29b82022-12-07 09:46:19 +05001495 * Returns 1 on success else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001496 */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001497static int qc_pkt_decrypt(struct quic_conn *qc, struct quic_enc_level *qel,
1498 struct quic_rx_packet *pkt)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001499{
1500 int ret, kp_changed;
1501 unsigned char iv[QUIC_TLS_IV_LEN];
1502 struct quic_tls_ctx *tls_ctx = &qel->tls_ctx;
1503 EVP_CIPHER_CTX *rx_ctx = tls_ctx->rx.ctx;
1504 unsigned char *rx_iv = tls_ctx->rx.iv;
1505 size_t rx_iv_sz = tls_ctx->rx.ivlen;
1506 unsigned char *rx_key = tls_ctx->rx.key;
1507
1508 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
1509
1510 ret = 0;
1511 kp_changed = 0;
1512
1513 if (pkt->type == QUIC_PACKET_TYPE_SHORT) {
1514 /* The two tested bits are not at the same position,
1515 * this is why they are first both inversed.
1516 */
1517 if (!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT) ^ !(tls_ctx->flags & QUIC_FL_TLS_KP_BIT_SET)) {
1518 if (pkt->pn < tls_ctx->rx.pn) {
1519 /* The lowest packet number of a previous key phase
1520 * cannot be null if it really stores previous key phase
1521 * secrets.
1522 */
1523 // TODO: check if BUG_ON() more suitable
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001524 if (!qc->ku.prv_rx.pn) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001525 TRACE_ERROR("null previous packet number", QUIC_EV_CONN_RXPKT, qc);
1526 goto leave;
1527 }
1528
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001529 rx_ctx = qc->ku.prv_rx.ctx;
1530 rx_iv = qc->ku.prv_rx.iv;
1531 rx_key = qc->ku.prv_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001532 }
1533 else if (pkt->pn > qel->pktns->rx.largest_pn) {
1534 /* Next key phase */
1535 kp_changed = 1;
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001536 rx_ctx = qc->ku.nxt_rx.ctx;
1537 rx_iv = qc->ku.nxt_rx.iv;
1538 rx_key = qc->ku.nxt_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001539 }
1540 }
1541 }
1542
1543 if (!quic_aead_iv_build(iv, sizeof iv, rx_iv, rx_iv_sz, pkt->pn)) {
1544 TRACE_ERROR("quic_aead_iv_build() failed", QUIC_EV_CONN_RXPKT, qc);
1545 goto leave;
1546 }
1547
1548 ret = quic_tls_decrypt(pkt->data + pkt->aad_len, pkt->len - pkt->aad_len,
1549 pkt->data, pkt->aad_len,
1550 rx_ctx, tls_ctx->rx.aead, rx_key, iv);
1551 if (!ret) {
1552 TRACE_ERROR("quic_tls_decrypt() failed", QUIC_EV_CONN_RXPKT, qc);
1553 goto leave;
1554 }
1555
1556 /* Update the keys only if the packet decryption succeeded. */
1557 if (kp_changed) {
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001558 quic_tls_rotate_keys(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001559 /* Toggle the Key Phase bit */
1560 tls_ctx->flags ^= QUIC_FL_TLS_KP_BIT_SET;
1561 /* Store the lowest packet number received for the current key phase */
1562 tls_ctx->rx.pn = pkt->pn;
1563 /* Prepare the next key update */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001564 if (!quic_tls_key_update(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001565 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_RXPKT, qc);
1566 goto leave;
1567 }
1568 }
1569
1570 /* Update the packet length (required to parse the frames). */
1571 pkt->len -= QUIC_TLS_TAG_LEN;
1572 ret = 1;
1573 leave:
1574 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
1575 return ret;
1576}
1577
1578
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001579/* Release <frm> frame and mark its copies as acknowledged */
1580void qc_release_frm(struct quic_conn *qc, struct quic_frame *frm)
1581{
1582 uint64_t pn;
1583 struct quic_frame *origin, *f, *tmp;
1584
1585 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1586
1587 /* Identify this frame: a frame copy or one of its copies */
1588 origin = frm->origin ? frm->origin : frm;
1589 /* Ensure the source of the copies is flagged as acked, <frm> being
1590 * possibly a copy of <origin>
1591 */
1592 origin->flags |= QUIC_FL_TX_FRAME_ACKED;
1593 /* Mark all the copy of <origin> as acknowledged. We must
1594 * not release the packets (releasing the frames) at this time as
1595 * they are possibly also to be acknowledged alongside the
1596 * the current one.
1597 */
1598 list_for_each_entry_safe(f, tmp, &origin->reflist, ref) {
1599 if (f->pkt) {
1600 f->flags |= QUIC_FL_TX_FRAME_ACKED;
1601 f->origin = NULL;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001602 LIST_DEL_INIT(&f->ref);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001603 pn = f->pkt->pn_node.key;
1604 TRACE_DEVEL("mark frame as acked from packet",
1605 QUIC_EV_CONN_PRSAFRM, qc, f, &pn);
1606 }
1607 else {
1608 TRACE_DEVEL("freeing unsent frame",
1609 QUIC_EV_CONN_PRSAFRM, qc, f);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001610 LIST_DEL_INIT(&f->ref);
1611 qc_frm_free(&f);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001612 }
1613 }
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001614 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001615 pn = frm->pkt->pn_node.key;
1616 quic_tx_packet_refdec(frm->pkt);
1617 TRACE_DEVEL("freeing frame from packet",
1618 QUIC_EV_CONN_PRSAFRM, qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001619 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001620
1621 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1622}
1623
1624/* Schedule a CONNECTION_CLOSE emission on <qc> if the MUX has been released
1625 * and all STREAM data are acknowledged. The MUX is responsible to have set
1626 * <qc.err> before as it is reused for the CONNECTION_CLOSE frame.
1627 *
1628 * TODO this should also be called on lost packet detection
1629 */
1630void qc_check_close_on_released_mux(struct quic_conn *qc)
1631{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001632 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1633
1634 if (qc->mux_state == QC_MUX_RELEASED && eb_is_empty(&qc->streams_by_id)) {
1635 /* Reuse errcode which should have been previously set by the MUX on release. */
1636 quic_set_connection_close(qc, qc->err);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02001637 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001638 }
1639
1640 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1641}
1642
1643/* Remove from <stream> the acknowledged frames.
1644 *
1645 * Returns 1 if at least one frame was removed else 0.
1646 */
1647static int quic_stream_try_to_consume(struct quic_conn *qc,
1648 struct qc_stream_desc *stream)
1649{
1650 int ret;
1651 struct eb64_node *frm_node;
1652
1653 TRACE_ENTER(QUIC_EV_CONN_ACKSTRM, qc);
1654
1655 ret = 0;
1656 frm_node = eb64_first(&stream->acked_frms);
1657 while (frm_node) {
1658 struct quic_stream *strm;
1659 struct quic_frame *frm;
1660 size_t offset, len;
1661
1662 strm = eb64_entry(frm_node, struct quic_stream, offset);
1663 offset = strm->offset.key;
1664 len = strm->len;
1665
1666 if (offset > stream->ack_offset)
1667 break;
1668
1669 if (qc_stream_desc_ack(&stream, offset, len)) {
1670 /* cf. next comment : frame may be freed at this stage. */
1671 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1672 qc, stream ? strm : NULL, stream);
1673 ret = 1;
1674 }
1675
1676 /* If stream is NULL after qc_stream_desc_ack(), it means frame
1677 * has been freed. with the stream frames tree. Nothing to do
1678 * anymore in here.
1679 */
1680 if (!stream) {
1681 qc_check_close_on_released_mux(qc);
1682 ret = 1;
1683 goto leave;
1684 }
1685
1686 frm_node = eb64_next(frm_node);
1687 eb64_delete(&strm->offset);
1688
1689 frm = container_of(strm, struct quic_frame, stream);
1690 qc_release_frm(qc, frm);
1691 }
1692
1693 leave:
1694 TRACE_LEAVE(QUIC_EV_CONN_ACKSTRM, qc);
1695 return ret;
1696}
1697
1698/* Treat <frm> frame whose packet it is attached to has just been acknowledged. */
1699static inline void qc_treat_acked_tx_frm(struct quic_conn *qc,
1700 struct quic_frame *frm)
1701{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001702 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc, frm);
1703
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001704 switch (frm->type) {
1705 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1706 {
1707 struct quic_stream *strm_frm = &frm->stream;
1708 struct eb64_node *node = NULL;
1709 struct qc_stream_desc *stream = NULL;
1710 const size_t offset = strm_frm->offset.key;
1711 const size_t len = strm_frm->len;
1712
1713 /* do not use strm_frm->stream as the qc_stream_desc instance
1714 * might be freed at this stage. Use the id to do a proper
1715 * lookup.
1716 *
1717 * TODO if lookup operation impact on the perf is noticeable,
1718 * implement a refcount on qc_stream_desc instances.
1719 */
1720 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1721 if (!node) {
1722 TRACE_DEVEL("acked stream for released stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm);
1723 qc_release_frm(qc, frm);
1724 /* early return */
1725 goto leave;
1726 }
1727 stream = eb64_entry(node, struct qc_stream_desc, by_id);
1728
1729 TRACE_DEVEL("acked stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm, stream);
1730 if (offset <= stream->ack_offset) {
1731 if (qc_stream_desc_ack(&stream, offset, len)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001732 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1733 qc, strm_frm, stream);
1734 }
1735
1736 if (!stream) {
1737 /* no need to continue if stream freed. */
1738 TRACE_DEVEL("stream released and freed", QUIC_EV_CONN_ACKSTRM, qc);
1739 qc_release_frm(qc, frm);
1740 qc_check_close_on_released_mux(qc);
1741 break;
1742 }
1743
1744 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1745 qc, strm_frm, stream);
1746 qc_release_frm(qc, frm);
1747 }
1748 else {
1749 eb64_insert(&stream->acked_frms, &strm_frm->offset);
1750 }
1751
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01001752 quic_stream_try_to_consume(qc, stream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001753 }
1754 break;
1755 default:
1756 qc_release_frm(qc, frm);
1757 }
1758
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001759 leave:
1760 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1761}
1762
1763/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1764 * deallocating them, and their TX frames.
1765 * Returns the last node reached to be used for the next range.
1766 * May be NULL if <largest> node could not be found.
1767 */
1768static inline struct eb64_node *qc_ackrng_pkts(struct quic_conn *qc,
1769 struct eb_root *pkts,
1770 unsigned int *pkt_flags,
1771 struct list *newly_acked_pkts,
1772 struct eb64_node *largest_node,
1773 uint64_t largest, uint64_t smallest)
1774{
1775 struct eb64_node *node;
1776 struct quic_tx_packet *pkt;
1777
1778 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1779
1780 node = largest_node ? largest_node : eb64_lookup_le(pkts, largest);
1781 while (node && node->key >= smallest) {
1782 struct quic_frame *frm, *frmbak;
1783
1784 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
1785 *pkt_flags |= pkt->flags;
1786 LIST_INSERT(newly_acked_pkts, &pkt->list);
1787 TRACE_DEVEL("Removing packet #", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
1788 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1789 qc_treat_acked_tx_frm(qc, frm);
Frédéric Lécaille814645f2022-11-18 18:15:28 +01001790 /* If there are others packet in the same datagram <pkt> is attached to,
1791 * detach the previous one and the next one from <pkt>.
1792 */
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01001793 quic_tx_packet_dgram_detach(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001794 node = eb64_prev(node);
1795 eb64_delete(&pkt->pn_node);
1796 }
1797
1798 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1799 return node;
1800}
1801
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001802/* Remove all frames from <pkt_frm_list> and reinsert them in the same order
1803 * they have been sent into <pktns_frm_list>. The loss counter of each frame is
1804 * incremented and checked if it does not exceed retransmission limit.
1805 *
1806 * Returns 1 on success, 0 if a frame loss limit is exceeded. A
1807 * CONNECTION_CLOSE is scheduled in this case.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001808 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001809static inline int qc_requeue_nacked_pkt_tx_frms(struct quic_conn *qc,
1810 struct quic_tx_packet *pkt,
1811 struct list *pktns_frm_list)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001812{
1813 struct quic_frame *frm, *frmbak;
1814 struct list tmp = LIST_HEAD_INIT(tmp);
1815 struct list *pkt_frm_list = &pkt->frms;
1816 uint64_t pn = pkt->pn_node.key;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001817 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001818
1819 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1820
1821 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
1822 /* First remove this frame from the packet it was attached to */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001823 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001824 quic_tx_packet_refdec(pkt);
1825 /* At this time, this frame is not freed but removed from its packet */
1826 frm->pkt = NULL;
1827 /* Remove any reference to this frame */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001828 qc_frm_unref(frm, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001829 switch (frm->type) {
1830 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1831 {
1832 struct quic_stream *strm_frm = &frm->stream;
1833 struct eb64_node *node = NULL;
1834 struct qc_stream_desc *stream_desc;
1835
1836 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1837 if (!node) {
1838 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
1839 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1840 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001841 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001842 continue;
1843 }
1844
1845 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
1846 /* Do not resend this frame if in the "already acked range" */
1847 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
1848 TRACE_DEVEL("ignored frame in already acked range",
1849 QUIC_EV_CONN_PRSAFRM, qc, frm);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001850 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001851 continue;
1852 }
1853 else if (strm_frm->offset.key < stream_desc->ack_offset) {
1854 strm_frm->offset.key = stream_desc->ack_offset;
1855 TRACE_DEVEL("updated partially acked frame",
1856 QUIC_EV_CONN_PRSAFRM, qc, frm);
1857 }
1858 break;
1859 }
1860
1861 default:
1862 break;
1863 }
1864
1865 /* Do not resend probing packet with old data */
1866 if (pkt->flags & QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA) {
1867 TRACE_DEVEL("ignored frame with old data from packet", QUIC_EV_CONN_PRSAFRM,
1868 qc, frm, &pn);
1869 if (frm->origin)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001870 LIST_DEL_INIT(&frm->ref);
1871 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001872 continue;
1873 }
1874
1875 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
1876 TRACE_DEVEL("already acked frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
1877 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1878 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001879 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001880 }
1881 else {
Amaury Denoyelle24d5b722023-01-31 11:44:50 +01001882 if (++frm->loss_count >= global.tune.quic_max_frame_loss) {
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001883 TRACE_ERROR("retransmission limit reached, closing the connection", QUIC_EV_CONN_PRSAFRM, qc);
1884 quic_set_connection_close(qc, quic_err_transport(QC_ERR_INTERNAL_ERROR));
1885 close = 1;
1886 }
1887
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001888 if (QUIC_FT_STREAM_8 <= frm->type && frm->type <= QUIC_FT_STREAM_F) {
1889 /* Mark this STREAM frame as lost. A look up their stream descriptor
1890 * will be performed to check the stream is not consumed or released.
1891 */
1892 frm->flags |= QUIC_FL_TX_FRAME_LOST;
1893 }
1894 LIST_APPEND(&tmp, &frm->list);
1895 TRACE_DEVEL("frame requeued", QUIC_EV_CONN_PRSAFRM, qc, frm);
1896 }
1897 }
1898
1899 LIST_SPLICE(pktns_frm_list, &tmp);
1900
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001901 end:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001902 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001903 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001904}
1905
1906/* Free <pkt> TX packet and its attached frames.
1907 * This is the responsibility of the caller to remove this packet of
1908 * any data structure it was possibly attached to.
1909 */
1910static inline void free_quic_tx_packet(struct quic_conn *qc,
1911 struct quic_tx_packet *pkt)
1912{
1913 struct quic_frame *frm, *frmbak;
1914
1915 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1916
1917 if (!pkt)
1918 goto leave;
1919
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001920 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1921 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001922 pool_free(pool_head_quic_tx_packet, pkt);
1923
1924 leave:
1925 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1926}
1927
1928/* Free the TX packets of <pkts> list */
1929static inline void free_quic_tx_pkts(struct quic_conn *qc, struct list *pkts)
1930{
1931 struct quic_tx_packet *pkt, *tmp;
1932
1933 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1934
1935 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1936 LIST_DELETE(&pkt->list);
1937 eb64_delete(&pkt->pn_node);
1938 free_quic_tx_packet(qc, pkt);
1939 }
1940
1941 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1942}
1943
1944/* Remove already sent ranges of acknowledged packet numbers from
1945 * <pktns> packet number space tree below <largest_acked_pn> possibly
1946 * updating the range which contains <largest_acked_pn>.
1947 * Never fails.
1948 */
1949static void qc_treat_ack_of_ack(struct quic_conn *qc,
1950 struct quic_pktns *pktns,
1951 int64_t largest_acked_pn)
1952{
1953 struct eb64_node *ar, *next_ar;
1954 struct quic_arngs *arngs = &pktns->rx.arngs;
1955
1956 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1957
1958 ar = eb64_first(&arngs->root);
1959 while (ar) {
1960 struct quic_arng_node *ar_node;
1961
1962 next_ar = eb64_next(ar);
1963 ar_node = eb64_entry(ar, struct quic_arng_node, first);
1964
1965 if ((int64_t)ar_node->first.key > largest_acked_pn) {
1966 TRACE_DEVEL("first.key > largest", QUIC_EV_CONN_PRSAFRM, qc);
1967 break;
1968 }
1969
1970 if (largest_acked_pn < ar_node->last) {
1971 eb64_delete(ar);
1972 ar_node->first.key = largest_acked_pn + 1;
1973 eb64_insert(&arngs->root, ar);
1974 break;
1975 }
1976
1977 eb64_delete(ar);
1978 pool_free(pool_head_quic_arng, ar_node);
1979 arngs->sz--;
1980 ar = next_ar;
1981 }
1982
1983 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1984}
1985
1986/* Send a packet ack event nofication for each newly acked packet of
1987 * <newly_acked_pkts> list and free them.
1988 * Always succeeds.
1989 */
1990static inline void qc_treat_newly_acked_pkts(struct quic_conn *qc,
1991 struct list *newly_acked_pkts)
1992{
1993 struct quic_tx_packet *pkt, *tmp;
1994 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
1995
1996 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1997
1998 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
1999 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2000 qc->path->prep_in_flight -= pkt->in_flight_len;
2001 qc->path->in_flight -= pkt->in_flight_len;
2002 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2003 qc->path->ifae_pkts--;
2004 /* If this packet contained an ACK frame, proceed to the
2005 * acknowledging of range of acks from the largest acknowledged
2006 * packet number which was sent in an ACK frame by this packet.
2007 */
2008 if (pkt->largest_acked_pn != -1)
2009 qc_treat_ack_of_ack(qc, pkt->pktns, pkt->largest_acked_pn);
2010 ev.ack.acked = pkt->in_flight_len;
2011 ev.ack.time_sent = pkt->time_sent;
2012 quic_cc_event(&qc->path->cc, &ev);
2013 LIST_DELETE(&pkt->list);
2014 eb64_delete(&pkt->pn_node);
2015 quic_tx_packet_refdec(pkt);
2016 }
2017
2018 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2019
2020}
2021
2022/* Release all the frames attached to <pktns> packet number space */
2023static inline void qc_release_pktns_frms(struct quic_conn *qc,
2024 struct quic_pktns *pktns)
2025{
2026 struct quic_frame *frm, *frmbak;
2027
2028 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
2029
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01002030 list_for_each_entry_safe(frm, frmbak, &pktns->tx.frms, list)
2031 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002032
2033 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
2034}
2035
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002036/* Handle <pkts> list of lost packets detected at <now_us> handling their TX
2037 * frames. Send a packet loss event to the congestion controller if in flight
2038 * packet have been lost. Also frees the packet in <pkts> list.
2039 *
2040 * Returns 1 on success else 0 if loss limit has been exceeded. A
2041 * CONNECTION_CLOSE was prepared to close the connection ASAP.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002042 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002043static inline int qc_release_lost_pkts(struct quic_conn *qc,
2044 struct quic_pktns *pktns,
2045 struct list *pkts,
2046 uint64_t now_us)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002047{
2048 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002049 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002050
2051 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2052
2053 if (LIST_ISEMPTY(pkts))
2054 goto leave;
2055
2056 oldest_lost = newest_lost = NULL;
2057 list_for_each_entry_safe(pkt, tmp, pkts, list) {
2058 struct list tmp = LIST_HEAD_INIT(tmp);
2059
2060 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2061 qc->path->prep_in_flight -= pkt->in_flight_len;
2062 qc->path->in_flight -= pkt->in_flight_len;
2063 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2064 qc->path->ifae_pkts--;
2065 /* Treat the frames of this lost packet. */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002066 if (!qc_requeue_nacked_pkt_tx_frms(qc, pkt, &pktns->tx.frms))
2067 close = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002068 LIST_DELETE(&pkt->list);
2069 if (!oldest_lost) {
2070 oldest_lost = newest_lost = pkt;
2071 }
2072 else {
2073 if (newest_lost != oldest_lost)
2074 quic_tx_packet_refdec(newest_lost);
2075 newest_lost = pkt;
2076 }
2077 }
2078
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002079 if (!close) {
2080 if (newest_lost) {
2081 /* Sent a congestion event to the controller */
2082 struct quic_cc_event ev = { };
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002083
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002084 ev.type = QUIC_CC_EVT_LOSS;
2085 ev.loss.time_sent = newest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002086
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002087 quic_cc_event(&qc->path->cc, &ev);
2088 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002089
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002090 /* If an RTT have been already sampled, <rtt_min> has been set.
2091 * We must check if we are experiencing a persistent congestion.
2092 * If this is the case, the congestion controller must re-enter
2093 * slow start state.
2094 */
2095 if (qc->path->loss.rtt_min && newest_lost != oldest_lost) {
2096 unsigned int period = newest_lost->time_sent - oldest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002097
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002098 if (quic_loss_persistent_congestion(&qc->path->loss, period,
2099 now_ms, qc->max_ack_delay))
2100 qc->path->cc.algo->slow_start(&qc->path->cc);
2101 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002102 }
2103
Amaury Denoyelle3a72ba22022-11-14 11:41:34 +01002104 /* <oldest_lost> cannot be NULL at this stage because we have ensured
2105 * that <pkts> list is not empty. Without this, GCC 12.2.0 reports a
2106 * possible overflow on a 0 byte region with O2 optimization.
2107 */
2108 ALREADY_CHECKED(oldest_lost);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002109 quic_tx_packet_refdec(oldest_lost);
2110 if (newest_lost != oldest_lost)
2111 quic_tx_packet_refdec(newest_lost);
2112
2113 leave:
2114 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002115 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002116}
2117
2118/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
2119 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
2120 * if the largest acked packet was newly acked and if there was at least one newly
2121 * acked ack-eliciting packet.
2122 * Return 1, if succeeded, 0 if not.
2123 */
2124static inline int qc_parse_ack_frm(struct quic_conn *qc,
2125 struct quic_frame *frm,
2126 struct quic_enc_level *qel,
2127 unsigned int *rtt_sample,
2128 const unsigned char **pos, const unsigned char *end)
2129{
2130 struct quic_ack *ack = &frm->ack;
2131 uint64_t smallest, largest;
2132 struct eb_root *pkts;
2133 struct eb64_node *largest_node;
2134 unsigned int time_sent, pkt_flags;
2135 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
2136 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2137 int ret = 0;
2138
2139 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2140
2141 if (ack->largest_ack > qel->pktns->tx.next_pn) {
2142 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
2143 qc, NULL, &ack->largest_ack);
2144 goto err;
2145 }
2146
2147 if (ack->first_ack_range > ack->largest_ack) {
2148 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
2149 qc, NULL, &ack->first_ack_range);
2150 goto err;
2151 }
2152
2153 largest = ack->largest_ack;
2154 smallest = largest - ack->first_ack_range;
2155 pkts = &qel->pktns->tx.pkts;
2156 pkt_flags = 0;
2157 largest_node = NULL;
2158 time_sent = 0;
2159
2160 if ((int64_t)ack->largest_ack > qel->pktns->rx.largest_acked_pn) {
2161 largest_node = eb64_lookup(pkts, largest);
2162 if (!largest_node) {
2163 TRACE_DEVEL("Largest acked packet not found",
2164 QUIC_EV_CONN_PRSAFRM, qc);
2165 }
2166 else {
2167 time_sent = eb64_entry(largest_node,
2168 struct quic_tx_packet, pn_node)->time_sent;
2169 }
2170 }
2171
2172 TRACE_PROTO("rcvd ack range", QUIC_EV_CONN_PRSAFRM,
2173 qc, NULL, &largest, &smallest);
2174 do {
2175 uint64_t gap, ack_range;
2176
2177 qc_ackrng_pkts(qc, pkts, &pkt_flags, &newly_acked_pkts,
2178 largest_node, largest, smallest);
2179 if (!ack->ack_range_num--)
2180 break;
2181
2182 if (!quic_dec_int(&gap, pos, end)) {
2183 TRACE_ERROR("quic_dec_int(gap) failed", QUIC_EV_CONN_PRSAFRM, qc);
2184 goto err;
2185 }
2186
2187 if (smallest < gap + 2) {
2188 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
2189 qc, NULL, &gap, &smallest);
2190 goto err;
2191 }
2192
2193 largest = smallest - gap - 2;
2194 if (!quic_dec_int(&ack_range, pos, end)) {
2195 TRACE_ERROR("quic_dec_int(ack_range) failed", QUIC_EV_CONN_PRSAFRM, qc);
2196 goto err;
2197 }
2198
2199 if (largest < ack_range) {
2200 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
2201 qc, NULL, &largest, &ack_range);
2202 goto err;
2203 }
2204
2205 /* Do not use this node anymore. */
2206 largest_node = NULL;
2207 /* Next range */
2208 smallest = largest - ack_range;
2209
2210 TRACE_PROTO("rcvd next ack range", QUIC_EV_CONN_PRSAFRM,
2211 qc, NULL, &largest, &smallest);
2212 } while (1);
2213
2214 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
2215 *rtt_sample = tick_remain(time_sent, now_ms);
2216 qel->pktns->rx.largest_acked_pn = ack->largest_ack;
2217 }
2218
2219 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
2220 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
2221 qc_packet_loss_lookup(qel->pktns, qc, &lost_pkts);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002222 if (!qc_release_lost_pkts(qc, qel->pktns, &lost_pkts, now_ms))
2223 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002224 }
2225 qc_treat_newly_acked_pkts(qc, &newly_acked_pkts);
2226 if (quic_peer_validated_addr(qc))
2227 qc->path->loss.pto_count = 0;
2228 qc_set_timer(qc);
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01002229 qc_notify_send(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002230 }
2231
2232 ret = 1;
2233 leave:
2234 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2235 return ret;
2236
2237 err:
2238 free_quic_tx_pkts(qc, &newly_acked_pkts);
2239 goto leave;
2240}
2241
2242/* This function gives the detail of the SSL error. It is used only
2243 * if the debug mode and the verbose mode are activated. It dump all
2244 * the SSL error until the stack was empty.
2245 */
2246static forceinline void qc_ssl_dump_errors(struct connection *conn)
2247{
2248 if (unlikely(global.mode & MODE_DEBUG)) {
2249 while (1) {
2250 const char *func = NULL;
2251 unsigned long ret;
2252
2253 ERR_peek_error_func(&func);
2254 ret = ERR_get_error();
2255 if (!ret)
2256 return;
2257
2258 fprintf(stderr, "conn. @%p OpenSSL error[0x%lx] %s: %s\n", conn, ret,
2259 func, ERR_reason_error_string(ret));
2260 }
2261 }
2262}
2263
2264int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx,
2265 const char **str, int *len);
2266
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002267/* Finalize <qc> QUIC connection:
2268 * - initialize the Initial QUIC TLS context for negotiated version,
2269 * - derive the secrets for this context,
2270 * - set them into the TLS stack,
2271 *
2272 * MUST be called after having received the remote transport parameters which
2273 * are parsed when the TLS callback for the ClientHello message is called upon
2274 * SSL_do_handshake() calls, not necessarily at the first time as this TLS
2275 * message may be splitted between packets
2276 * Return 1 if succeeded, 0 if not.
2277 */
2278static int qc_conn_finalize(struct quic_conn *qc, int server)
2279{
2280 int ret = 0;
2281
2282 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
2283
2284 if (qc->flags & QUIC_FL_CONN_FINALIZED)
2285 goto finalized;
2286
2287 if (qc->negotiated_version &&
2288 !qc_new_isecs(qc, &qc->negotiated_ictx, qc->negotiated_version,
2289 qc->odcid.data, qc->odcid.len, server))
2290 goto out;
2291
2292 /* This connection is functional (ready to send/receive) */
2293 qc->flags |= QUIC_FL_CONN_FINALIZED;
2294
2295 finalized:
2296 ret = 1;
2297 out:
2298 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
2299 return ret;
2300}
2301
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002302/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
2303 * from <qel> encryption level with <ctx> as QUIC connection context.
2304 * Remaining parameter are there for debugging purposes.
2305 * Return 1 if succeeded, 0 if not.
2306 */
2307static inline int qc_provide_cdata(struct quic_enc_level *el,
2308 struct ssl_sock_ctx *ctx,
2309 const unsigned char *data, size_t len,
2310 struct quic_rx_packet *pkt,
2311 struct quic_rx_crypto_frm *cf)
2312{
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002313#ifdef DEBUG_STRICT
2314 enum ncb_ret ncb_ret;
2315#endif
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002316 int ssl_err, state;
2317 struct quic_conn *qc;
2318 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002319 struct ncbuf *ncbuf = &el->cstream->rx.ncbuf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002320
2321 ssl_err = SSL_ERROR_NONE;
2322 qc = ctx->qc;
2323
2324 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, qc);
2325
2326 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
2327 TRACE_ERROR("SSL_provide_quic_data() error",
2328 QUIC_EV_CONN_SSLDATA, qc, pkt, cf, ctx->ssl);
2329 goto leave;
2330 }
2331
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002332 TRACE_PROTO("in order CRYPTO data",
2333 QUIC_EV_CONN_SSLDATA, qc, NULL, cf, ctx->ssl);
2334
2335 state = qc->state;
2336 if (state < QUIC_HS_ST_COMPLETE) {
2337 ssl_err = SSL_do_handshake(ctx->ssl);
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002338
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01002339 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
2340 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
2341 goto leave;
2342 }
2343
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002344 /* Finalize the connection as soon as possible if the peer transport parameters
2345 * have been received. This may be useful to send packets even if this
2346 * handshake fails.
2347 */
2348 if ((qc->flags & QUIC_FL_CONN_TX_TP_RECEIVED) && !qc_conn_finalize(qc, 1)) {
2349 TRACE_ERROR("connection finalization failed", QUIC_EV_CONN_IO_CB, qc, &state);
2350 goto leave;
2351 }
2352
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002353 if (ssl_err != 1) {
2354 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2355 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2356 TRACE_PROTO("SSL handshake in progress",
2357 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2358 goto out;
2359 }
2360
2361 /* TODO: Should close the connection asap */
2362 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2363 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2364 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2365 HA_ATOMIC_INC(&qc->prx_counters->hdshk_fail);
2366 }
2367 TRACE_ERROR("SSL handshake error", QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2368 qc_ssl_dump_errors(ctx->conn);
2369 ERR_clear_error();
2370 goto leave;
2371 }
2372
2373 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_IO_CB, qc, &state);
2374
2375 /* Check the alpn could be negotiated */
2376 if (!qc->app_ops) {
2377 TRACE_ERROR("No negotiated ALPN", QUIC_EV_CONN_IO_CB, qc, &state);
2378 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
2379 goto leave;
2380 }
2381
2382 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2383 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_IO_CB, qc, &state);
2384 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2385 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2386 }
2387 /* I/O callback switch */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002388 qc->wait_event.tasklet->process = quic_conn_app_io_cb;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002389 if (qc_is_listener(ctx->qc)) {
2390 qc->state = QUIC_HS_ST_CONFIRMED;
2391 /* The connection is ready to be accepted. */
2392 quic_accept_push_qc(qc);
2393 }
2394 else {
2395 qc->state = QUIC_HS_ST_COMPLETE;
2396 }
2397
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02002398 /* Prepare the next key update */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002399 if (!quic_tls_key_update(qc)) {
2400 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_IO_CB, qc);
2401 goto leave;
2402 }
2403 } else {
2404 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
2405 if (ssl_err != 1) {
2406 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2407 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2408 TRACE_PROTO("SSL post handshake in progress",
2409 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2410 goto out;
2411 }
2412
2413 TRACE_ERROR("SSL post handshake error",
2414 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2415 goto leave;
2416 }
2417
2418 TRACE_STATE("SSL post handshake succeeded", QUIC_EV_CONN_IO_CB, qc, &state);
2419 }
2420
2421 out:
2422 ret = 1;
2423 leave:
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002424 /* The CRYPTO data are consumed even in case of an error to release
2425 * the memory asap.
2426 */
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002427 if (!ncb_is_null(ncbuf)) {
2428#ifdef DEBUG_STRICT
2429 ncb_ret = ncb_advance(ncbuf, len);
2430 /* ncb_advance() must always succeed. This is guaranteed as
2431 * this is only done inside a data block. If false, this will
2432 * lead to handshake failure with quic_enc_level offset shifted
2433 * from buffer data.
2434 */
2435 BUG_ON(ncb_ret != NCB_RET_OK);
2436#else
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002437 ncb_advance(ncbuf, len);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002438#endif
2439 }
2440
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002441 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, qc);
2442 return ret;
2443}
2444
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002445/* Parse a STREAM frame <strm_frm> received in <pkt> packet for <qc>
2446 * connection. <fin> is true if FIN bit is set on frame type.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002447 *
2448 * Return 1 on success. On error, 0 is returned. In this case, the packet
2449 * containing the frame must not be acknowledged.
2450 */
2451static inline int qc_handle_strm_frm(struct quic_rx_packet *pkt,
2452 struct quic_stream *strm_frm,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002453 struct quic_conn *qc, char fin)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002454{
2455 int ret;
2456
2457 /* RFC9000 13.1. Packet Processing
2458 *
2459 * A packet MUST NOT be acknowledged until packet protection has been
2460 * successfully removed and all frames contained in the packet have
2461 * been processed. For STREAM frames, this means the data has been
2462 * enqueued in preparation to be received by the application protocol,
2463 * but it does not require that data be delivered and consumed.
2464 */
2465 TRACE_ENTER(QUIC_EV_CONN_PRSFRM, qc);
2466
2467 ret = qcc_recv(qc->qcc, strm_frm->id, strm_frm->len,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002468 strm_frm->offset.key, fin, (char *)strm_frm->data);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002469
2470 /* frame rejected - packet must not be acknowledeged */
2471 TRACE_LEAVE(QUIC_EV_CONN_PRSFRM, qc);
2472 return !ret;
2473}
2474
2475/* Duplicate all frames from <pkt_frm_list> list into <out_frm_list> list
2476 * for <qc> QUIC connection.
2477 * This is a best effort function which never fails even if no memory could be
2478 * allocated to duplicate these frames.
2479 */
2480static void qc_dup_pkt_frms(struct quic_conn *qc,
2481 struct list *pkt_frm_list, struct list *out_frm_list)
2482{
2483 struct quic_frame *frm, *frmbak;
2484 struct list tmp = LIST_HEAD_INIT(tmp);
2485
2486 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2487
2488 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
2489 struct quic_frame *dup_frm, *origin;
2490
2491 switch (frm->type) {
2492 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2493 {
2494 struct quic_stream *strm_frm = &frm->stream;
2495 struct eb64_node *node = NULL;
2496 struct qc_stream_desc *stream_desc;
2497
2498 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
2499 if (!node) {
2500 TRACE_DEVEL("ignored frame for a released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
2501 continue;
2502 }
2503
2504 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
2505 /* Do not resend this frame if in the "already acked range" */
2506 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
2507 TRACE_DEVEL("ignored frame in already acked range",
2508 QUIC_EV_CONN_PRSAFRM, qc, frm);
2509 continue;
2510 }
2511 else if (strm_frm->offset.key < stream_desc->ack_offset) {
2512 strm_frm->offset.key = stream_desc->ack_offset;
2513 TRACE_DEVEL("updated partially acked frame",
2514 QUIC_EV_CONN_PRSAFRM, qc, frm);
2515 }
2516 break;
2517 }
2518
2519 default:
2520 break;
2521 }
2522
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002523 /* If <frm> is already a copy of another frame, we must take
2524 * its original frame as source for the copy.
2525 */
2526 origin = frm->origin ? frm->origin : frm;
2527 dup_frm = qc_frm_dup(origin);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002528 if (!dup_frm) {
2529 TRACE_ERROR("could not duplicate frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2530 break;
2531 }
2532
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002533 TRACE_DEVEL("built probing frame", QUIC_EV_CONN_PRSAFRM, qc, origin);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002534 if (origin->pkt) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002535 TRACE_DEVEL("duplicated from packet", QUIC_EV_CONN_PRSAFRM,
2536 qc, NULL, &origin->pkt->pn_node.key);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002537 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002538 else {
2539 /* <origin> is a frame which was sent from a packet detected as lost. */
2540 TRACE_DEVEL("duplicated from lost packet", QUIC_EV_CONN_PRSAFRM, qc);
2541 }
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002542
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002543 LIST_APPEND(&tmp, &dup_frm->list);
2544 }
2545
2546 LIST_SPLICE(out_frm_list, &tmp);
2547
2548 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2549}
2550
2551/* Prepare a fast retransmission from <qel> encryption level */
2552static void qc_prep_fast_retrans(struct quic_conn *qc,
2553 struct quic_enc_level *qel,
2554 struct list *frms1, struct list *frms2)
2555{
2556 struct eb_root *pkts = &qel->pktns->tx.pkts;
2557 struct list *frms = frms1;
2558 struct eb64_node *node;
2559 struct quic_tx_packet *pkt;
2560
2561 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2562
2563 BUG_ON(frms1 == frms2);
2564
2565 pkt = NULL;
2566 node = eb64_first(pkts);
2567 start:
2568 while (node) {
2569 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
2570 node = eb64_next(node);
2571 /* Skip the empty and coalesced packets */
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002572 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
2573 "--> pn=%llu (%d %d)", (ull)pkt->pn_node.key,
2574 LIST_ISEMPTY(&pkt->frms), !!(pkt->flags & QUIC_FL_TX_PACKET_COALESCED));
Frédéric Lécaille055e8262023-01-31 10:10:06 +01002575 if (!LIST_ISEMPTY(&pkt->frms))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002576 break;
2577 }
2578
2579 if (!pkt)
2580 goto leave;
2581
2582 /* When building a packet from another one, the field which may increase the
2583 * packet size is the packet number. And the maximum increase is 4 bytes.
2584 */
2585 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2586 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
2587 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2588 goto leave;
2589 }
2590
2591 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_SPPKTS, qc, pkt);
2592 qc_dup_pkt_frms(qc, &pkt->frms, frms);
2593 if (frms == frms1 && frms2) {
2594 frms = frms2;
2595 goto start;
2596 }
2597 leave:
2598 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
2599}
2600
2601/* Prepare a fast retransmission during a handshake after a client
2602 * has resent Initial packets. According to the RFC a server may retransmit
2603 * Initial packets send them coalescing with others (Handshake here).
2604 * (Listener only function).
2605 */
2606static void qc_prep_hdshk_fast_retrans(struct quic_conn *qc,
2607 struct list *ifrms, struct list *hfrms)
2608{
2609 struct list itmp = LIST_HEAD_INIT(itmp);
2610 struct list htmp = LIST_HEAD_INIT(htmp);
2611
2612 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2613 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2614 struct quic_enc_level *qel = iqel;
2615 struct eb_root *pkts;
2616 struct eb64_node *node;
2617 struct quic_tx_packet *pkt;
2618 struct list *tmp = &itmp;
2619
2620 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2621 start:
2622 pkt = NULL;
2623 pkts = &qel->pktns->tx.pkts;
2624 node = eb64_first(pkts);
2625 /* Skip the empty packet (they have already been retransmitted) */
2626 while (node) {
2627 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002628 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
2629 "--> pn=%llu (%d %d)", (ull)pkt->pn_node.key,
2630 LIST_ISEMPTY(&pkt->frms), !!(pkt->flags & QUIC_FL_TX_PACKET_COALESCED));
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002631 if (!LIST_ISEMPTY(&pkt->frms) && !(pkt->flags & QUIC_FL_TX_PACKET_COALESCED))
2632 break;
2633 node = eb64_next(node);
2634 }
2635
2636 if (!pkt)
2637 goto end;
2638
2639 /* When building a packet from another one, the field which may increase the
2640 * packet size is the packet number. And the maximum increase is 4 bytes.
2641 */
2642 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2643 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
2644 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_PRSAFRM, qc);
2645 goto end;
2646 }
2647
2648 qel->pktns->tx.pto_probe += 1;
2649
2650 /* No risk to loop here, #packet per datagram is bounded */
2651 requeue:
2652 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
2653 qc_dup_pkt_frms(qc, &pkt->frms, tmp);
2654 if (qel == iqel) {
2655 if (pkt->next && pkt->next->type == QUIC_PACKET_TYPE_HANDSHAKE) {
2656 pkt = pkt->next;
2657 tmp = &htmp;
2658 hqel->pktns->tx.pto_probe += 1;
2659 TRACE_DEVEL("looping for next packet", QUIC_EV_CONN_PRSAFRM, qc);
2660 goto requeue;
2661 }
2662 }
2663
2664 end:
2665 LIST_SPLICE(ifrms, &itmp);
2666 LIST_SPLICE(hfrms, &htmp);
2667
2668 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2669}
2670
2671static void qc_cc_err_count_inc(struct quic_conn *qc, struct quic_frame *frm)
2672{
2673 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
2674
2675 if (frm->type == QUIC_FT_CONNECTION_CLOSE)
2676 quic_stats_transp_err_count_inc(qc->prx_counters, frm->connection_close.error_code);
2677 else if (frm->type == QUIC_FT_CONNECTION_CLOSE_APP) {
2678 if (qc->mux_state != QC_MUX_READY || !qc->qcc->app_ops->inc_err_cnt)
2679 goto out;
2680
2681 qc->qcc->app_ops->inc_err_cnt(qc->qcc->ctx, frm->connection_close_app.error_code);
2682 }
2683
2684 out:
2685 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
2686}
2687
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002688/* Cancel a request on connection <qc> for stream id <id>. This is useful when
2689 * the client opens a new stream but the MUX has already been released. A
Amaury Denoyelle75463012023-02-20 10:31:27 +01002690 * STOP_SENDING + RESET_STREAM frames are prepared for emission.
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002691 *
2692 * TODO this function is closely related to H3. Its place should be in H3 layer
2693 * instead of quic-conn but this requires an architecture adjustment.
2694 *
2695 * Returns 1 on sucess else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002696 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002697static int qc_h3_request_reject(struct quic_conn *qc, uint64_t id)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002698{
2699 int ret = 0;
Amaury Denoyelle75463012023-02-20 10:31:27 +01002700 struct quic_frame *ss, *rs;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002701 struct quic_enc_level *qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002702 const uint64_t app_error_code = H3_REQUEST_REJECTED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002703
2704 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2705
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002706 /* Do not emit rejection for unknown unidirectional stream as it is
2707 * forbidden to close some of them (H3 control stream and QPACK
2708 * encoder/decoder streams).
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002709 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002710 if (quic_stream_is_uni(id)) {
2711 ret = 1;
2712 goto out;
2713 }
2714
Amaury Denoyelle75463012023-02-20 10:31:27 +01002715 ss = qc_frm_alloc(QUIC_FT_STOP_SENDING);
2716 if (!ss) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002717 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2718 goto out;
2719 }
2720
Amaury Denoyelle75463012023-02-20 10:31:27 +01002721 ss->stop_sending.id = id;
2722 ss->stop_sending.app_error_code = app_error_code;
2723
2724 rs = qc_frm_alloc(QUIC_FT_RESET_STREAM);
2725 if (!rs) {
2726 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2727 qc_frm_free(&ss);
2728 goto out;
2729 }
2730
2731 rs->reset_stream.id = id;
2732 rs->reset_stream.app_error_code = app_error_code;
2733 rs->reset_stream.final_size = 0;
2734
2735 LIST_APPEND(&qel->pktns->tx.frms, &ss->list);
2736 LIST_APPEND(&qel->pktns->tx.frms, &rs->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002737 ret = 1;
2738 out:
2739 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2740 return ret;
2741}
2742
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002743/* Release the underlying memory use by <ncbuf> non-contiguous buffer */
2744static void quic_free_ncbuf(struct ncbuf *ncbuf)
2745{
2746 struct buffer buf;
2747
2748 if (ncb_is_null(ncbuf))
2749 return;
2750
2751 buf = b_make(ncbuf->area, ncbuf->size, 0, 0);
2752 b_free(&buf);
2753 offer_buffers(NULL, 1);
2754
2755 *ncbuf = NCBUF_NULL;
2756}
2757
2758/* Allocate the underlying required memory for <ncbuf> non-contiguous buffer */
2759static struct ncbuf *quic_get_ncbuf(struct ncbuf *ncbuf)
2760{
2761 struct buffer buf = BUF_NULL;
2762
2763 if (!ncb_is_null(ncbuf))
2764 return ncbuf;
2765
2766 b_alloc(&buf);
2767 BUG_ON(b_is_null(&buf));
2768
2769 *ncbuf = ncb_make(buf.area, buf.size, 0);
2770 ncb_init(ncbuf, 0);
2771
2772 return ncbuf;
2773}
2774
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002775/* Parse <frm> CRYPTO frame coming with <pkt> packet at <qel> <qc> connectionn.
2776 * Returns 1 if succeeded, 0 if not. Also set <*fast_retrans> to 1 if the
2777 * speed up handshake completion may be run after having received duplicated
2778 * CRYPTO data.
2779 */
2780static int qc_handle_crypto_frm(struct quic_conn *qc,
2781 struct quic_crypto *frm, struct quic_rx_packet *pkt,
2782 struct quic_enc_level *qel, int *fast_retrans)
2783{
2784 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002785 enum ncb_ret ncb_ret;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002786 /* XXX TO DO: <cfdebug> is used only for the traces. */
2787 struct quic_rx_crypto_frm cfdebug = {
2788 .offset_node.key = frm->offset,
2789 .len = frm->len,
2790 };
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002791 struct quic_cstream *cstream = qel->cstream;
2792 struct ncbuf *ncbuf = &qel->cstream->rx.ncbuf;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002793
2794 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2795 if (unlikely(qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD)) {
2796 TRACE_PROTO("CRYPTO data discarded",
2797 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2798 goto done;
2799 }
2800
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002801 if (unlikely(frm->offset < cstream->rx.offset)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002802 size_t diff;
2803
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002804 if (frm->offset + frm->len <= cstream->rx.offset) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002805 /* Nothing to do */
2806 TRACE_PROTO("Already received CRYPTO data",
2807 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2808 if (qc_is_listener(qc) && qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] &&
2809 !(qc->flags & QUIC_FL_CONN_HANDSHAKE_SPEED_UP))
2810 *fast_retrans = 1;
2811 goto done;
2812 }
2813
2814 TRACE_PROTO("Partially already received CRYPTO data",
2815 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2816
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002817 diff = cstream->rx.offset - frm->offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002818 frm->len -= diff;
2819 frm->data += diff;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002820 frm->offset = cstream->rx.offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002821 }
2822
Amaury Denoyelleff95f2d2022-11-18 14:50:06 +01002823 if (frm->offset == cstream->rx.offset && ncb_is_empty(ncbuf)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002824 if (!qc_provide_cdata(qel, qc->xprt_ctx, frm->data, frm->len,
2825 pkt, &cfdebug)) {
2826 // trace already emitted by function above
2827 goto leave;
2828 }
2829
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002830 cstream->rx.offset += frm->len;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002831 TRACE_DEVEL("increment crypto level offset", QUIC_EV_CONN_PHPKTS, qc, qel);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002832 goto done;
2833 }
2834
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002835 if (!quic_get_ncbuf(ncbuf) ||
2836 ncb_is_null(ncbuf)) {
2837 TRACE_ERROR("CRYPTO ncbuf allocation failed", QUIC_EV_CONN_PRSHPKT, qc);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002838 goto leave;
2839 }
2840
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002841 /* frm->offset > cstream-trx.offset */
2842 ncb_ret = ncb_add(ncbuf, frm->offset - cstream->rx.offset,
2843 (const char *)frm->data, frm->len, NCB_ADD_COMPARE);
2844 if (ncb_ret != NCB_RET_OK) {
2845 if (ncb_ret == NCB_RET_DATA_REJ) {
2846 TRACE_ERROR("overlapping data rejected", QUIC_EV_CONN_PRSHPKT, qc);
2847 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
2848 }
2849 else if (ncb_ret == NCB_RET_GAP_SIZE) {
2850 TRACE_ERROR("cannot bufferize frame due to gap size limit",
2851 QUIC_EV_CONN_PRSHPKT, qc);
2852 }
2853 goto leave;
2854 }
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002855
2856 done:
2857 ret = 1;
2858 leave:
2859 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2860 return ret;
2861}
2862
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002863/* Parse all the frames of <pkt> QUIC packet for QUIC connection <qc> and <qel>
2864 * as encryption level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002865 * Returns 1 if succeeded, 0 if failed.
2866 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002867static int qc_parse_pkt_frms(struct quic_conn *qc, struct quic_rx_packet *pkt,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002868 struct quic_enc_level *qel)
2869{
2870 struct quic_frame frm;
2871 const unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002872 int fast_retrans = 0, ret = 0;
2873
2874 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2875 /* Skip the AAD */
2876 pos = pkt->data + pkt->aad_len;
2877 end = pkt->data + pkt->len;
2878
2879 while (pos < end) {
2880 if (!qc_parse_frm(&frm, pkt, &pos, end, qc)) {
2881 // trace already emitted by function above
2882 goto leave;
2883 }
2884
2885 TRACE_PROTO("RX frame", QUIC_EV_CONN_PSTRM, qc, &frm);
2886 switch (frm.type) {
2887 case QUIC_FT_PADDING:
2888 break;
2889 case QUIC_FT_PING:
2890 break;
2891 case QUIC_FT_ACK:
2892 {
2893 unsigned int rtt_sample;
2894
2895 rtt_sample = 0;
2896 if (!qc_parse_ack_frm(qc, &frm, qel, &rtt_sample, &pos, end)) {
2897 // trace already emitted by function above
2898 goto leave;
2899 }
2900
2901 if (rtt_sample) {
2902 unsigned int ack_delay;
2903
2904 ack_delay = !quic_application_pktns(qel->pktns, qc) ? 0 :
2905 qc->state >= QUIC_HS_ST_CONFIRMED ?
2906 MS_TO_TICKS(QUIC_MIN(quic_ack_delay_ms(&frm.ack, qc), qc->max_ack_delay)) :
2907 MS_TO_TICKS(quic_ack_delay_ms(&frm.ack, qc));
2908 quic_loss_srtt_update(&qc->path->loss, rtt_sample, ack_delay, qc);
2909 }
2910 break;
2911 }
2912 case QUIC_FT_RESET_STREAM:
Amaury Denoyelle5854fc02022-12-09 16:25:48 +01002913 if (qc->mux_state == QC_MUX_READY) {
2914 struct quic_reset_stream *rs = &frm.reset_stream;
2915 qcc_recv_reset_stream(qc->qcc, rs->id, rs->app_error_code, rs->final_size);
2916 }
2917 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002918 case QUIC_FT_STOP_SENDING:
2919 {
2920 struct quic_stop_sending *stop_sending = &frm.stop_sending;
2921 if (qc->mux_state == QC_MUX_READY) {
2922 if (qcc_recv_stop_sending(qc->qcc, stop_sending->id,
2923 stop_sending->app_error_code)) {
2924 TRACE_ERROR("qcc_recv_stop_sending() failed", QUIC_EV_CONN_PRSHPKT, qc);
2925 goto leave;
2926 }
2927 }
2928 break;
2929 }
2930 case QUIC_FT_CRYPTO:
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002931 if (!qc_handle_crypto_frm(qc, &frm.crypto, pkt, qel, &fast_retrans))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002932 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002933 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002934 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2935 {
2936 struct quic_stream *stream = &frm.stream;
2937 unsigned nb_streams = qc->rx.strms[qcs_id_type(stream->id)].nb_streams;
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002938 const char fin = frm.type & QUIC_STREAM_FRAME_TYPE_FIN_BIT;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002939
2940 /* The upper layer may not be allocated. */
2941 if (qc->mux_state != QC_MUX_READY) {
2942 if ((stream->id >> QCS_ID_TYPE_SHIFT) < nb_streams) {
2943 TRACE_DATA("Already closed stream", QUIC_EV_CONN_PRSHPKT, qc);
2944 break;
2945 }
2946 else {
2947 TRACE_DEVEL("No mux for new stream", QUIC_EV_CONN_PRSHPKT, qc);
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002948 if (qc->app_ops == &h3_ops) {
Amaury Denoyelle156a89a2023-02-20 10:32:16 +01002949 if (!qc_h3_request_reject(qc, stream->id)) {
2950 TRACE_ERROR("error on request rejection", QUIC_EV_CONN_PRSHPKT, qc);
2951 /* This packet will not be acknowledged */
2952 goto leave;
2953 }
2954 }
2955 else {
2956 /* This packet will not be acknowledged */
2957 goto leave;
Frédéric Lécailled18025e2023-01-20 15:33:50 +01002958 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002959 }
2960 }
2961
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002962 if (!qc_handle_strm_frm(pkt, stream, qc, fin)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002963 TRACE_ERROR("qc_handle_strm_frm() failed", QUIC_EV_CONN_PRSHPKT, qc);
2964 goto leave;
2965 }
2966
2967 break;
2968 }
2969 case QUIC_FT_MAX_DATA:
2970 if (qc->mux_state == QC_MUX_READY) {
2971 struct quic_max_data *data = &frm.max_data;
2972 qcc_recv_max_data(qc->qcc, data->max_data);
2973 }
2974 break;
2975 case QUIC_FT_MAX_STREAM_DATA:
2976 if (qc->mux_state == QC_MUX_READY) {
2977 struct quic_max_stream_data *data = &frm.max_stream_data;
2978 if (qcc_recv_max_stream_data(qc->qcc, data->id,
2979 data->max_stream_data)) {
2980 TRACE_ERROR("qcc_recv_max_stream_data() failed", QUIC_EV_CONN_PRSHPKT, qc);
2981 goto leave;
2982 }
2983 }
2984 break;
2985 case QUIC_FT_MAX_STREAMS_BIDI:
2986 case QUIC_FT_MAX_STREAMS_UNI:
2987 break;
2988 case QUIC_FT_DATA_BLOCKED:
2989 HA_ATOMIC_INC(&qc->prx_counters->data_blocked);
2990 break;
2991 case QUIC_FT_STREAM_DATA_BLOCKED:
2992 HA_ATOMIC_INC(&qc->prx_counters->stream_data_blocked);
2993 break;
2994 case QUIC_FT_STREAMS_BLOCKED_BIDI:
2995 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_bidi);
2996 break;
2997 case QUIC_FT_STREAMS_BLOCKED_UNI:
2998 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_uni);
2999 break;
3000 case QUIC_FT_NEW_CONNECTION_ID:
3001 case QUIC_FT_RETIRE_CONNECTION_ID:
3002 /* XXX TO DO XXX */
3003 break;
3004 case QUIC_FT_CONNECTION_CLOSE:
3005 case QUIC_FT_CONNECTION_CLOSE_APP:
3006 /* Increment the error counters */
3007 qc_cc_err_count_inc(qc, &frm);
3008 if (!(qc->flags & QUIC_FL_CONN_DRAINING)) {
3009 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
3010 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
3011 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
3012 }
3013 TRACE_STATE("Entering draining state", QUIC_EV_CONN_PRSHPKT, qc);
3014 /* RFC 9000 10.2. Immediate Close:
3015 * The closing and draining connection states exist to ensure
3016 * that connections close cleanly and that delayed or reordered
3017 * packets are properly discarded. These states SHOULD persist
3018 * for at least three times the current PTO interval...
3019 *
3020 * Rearm the idle timeout only one time when entering draining
3021 * state.
3022 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003023 qc->flags |= QUIC_FL_CONN_DRAINING|QUIC_FL_CONN_IMMEDIATE_CLOSE;
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01003024 qc_idle_timer_do_rearm(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003025 qc_notify_close(qc);
3026 }
3027 break;
3028 case QUIC_FT_HANDSHAKE_DONE:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003029 if (qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003030 TRACE_ERROR("non accepted QUIC_FT_HANDSHAKE_DONE frame",
3031 QUIC_EV_CONN_PRSHPKT, qc);
3032 goto leave;
3033 }
3034
3035 qc->state = QUIC_HS_ST_CONFIRMED;
3036 break;
3037 default:
3038 TRACE_ERROR("unknosw frame type", QUIC_EV_CONN_PRSHPKT, qc);
3039 goto leave;
3040 }
3041 }
3042
3043 /* Flag this packet number space as having received a packet. */
3044 qel->pktns->flags |= QUIC_FL_PKTNS_PKT_RECEIVED;
3045
3046 if (fast_retrans) {
3047 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
3048 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
3049
3050 TRACE_PROTO("speeding up handshake completion", QUIC_EV_CONN_PRSHPKT, qc);
3051 qc_prep_hdshk_fast_retrans(qc, &iqel->pktns->tx.frms, &hqel->pktns->tx.frms);
3052 qc->flags |= QUIC_FL_CONN_HANDSHAKE_SPEED_UP;
3053 }
3054
3055 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
3056 * has successfully parse a Handshake packet. The Initial encryption must also
3057 * be discarded.
3058 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003059 if (pkt->type == QUIC_PACKET_TYPE_HANDSHAKE && qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003060 if (qc->state >= QUIC_HS_ST_SERVER_INITIAL) {
3061 if (!(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx.flags &
3062 QUIC_FL_TLS_SECRETS_DCD)) {
3063 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3064 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PRSHPKT, qc);
3065 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003066 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003067 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3068 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3069 }
3070 if (qc->state < QUIC_HS_ST_SERVER_HANDSHAKE)
3071 qc->state = QUIC_HS_ST_SERVER_HANDSHAKE;
3072 }
3073 }
3074
3075 ret = 1;
3076 leave:
3077 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
3078 return ret;
3079}
3080
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003081
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003082/* Allocate Tx buffer from <qc> quic-conn if needed.
3083 *
3084 * Returns allocated buffer or NULL on error.
3085 */
3086static struct buffer *qc_txb_alloc(struct quic_conn *qc)
3087{
3088 struct buffer *buf = &qc->tx.buf;
3089 if (!b_alloc(buf))
3090 return NULL;
3091
3092 return buf;
3093}
3094
3095/* Free Tx buffer from <qc> if it is empty. */
3096static void qc_txb_release(struct quic_conn *qc)
3097{
3098 struct buffer *buf = &qc->tx.buf;
3099
3100 /* For the moment sending function is responsible to purge the buffer
3101 * entirely. It may change in the future but this requires to be able
3102 * to reuse old data.
Frédéric Lécaillebbf86be2023-02-20 09:28:58 +01003103 * For the momemt we do not care to leave data in the buffer for
3104 * a connection which is supposed to be killed asap.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003105 */
3106 BUG_ON_HOT(buf && b_data(buf));
3107
3108 if (!b_data(buf)) {
3109 b_free(buf);
3110 offer_buffers(NULL, 1);
3111 }
3112}
3113
3114/* Commit a datagram payload written into <buf> of length <length>. <first_pkt>
3115 * must contains the address of the first packet stored in the payload.
3116 *
3117 * Caller is responsible that there is enough space in the buffer.
3118 */
3119static void qc_txb_store(struct buffer *buf, uint16_t length,
3120 struct quic_tx_packet *first_pkt)
3121{
3122 const size_t hdlen = sizeof(uint16_t) + sizeof(void *);
3123 BUG_ON_HOT(b_contig_space(buf) < hdlen); /* this must not happen */
3124
3125 write_u16(b_tail(buf), length);
3126 write_ptr(b_tail(buf) + sizeof(length), first_pkt);
3127 b_add(buf, hdlen + length);
3128}
3129
3130/* Returns 1 if a packet may be built for <qc> from <qel> encryption level
3131 * with <frms> as ack-eliciting frame list to send, 0 if not.
3132 * <cc> must equal to 1 if an immediate close was asked, 0 if not.
3133 * <probe> must equalt to 1 if a probing packet is required, 0 if not.
3134 * <force_ack> may be set to 1 if you want to force an ack.
3135 */
3136static int qc_may_build_pkt(struct quic_conn *qc, struct list *frms,
3137 struct quic_enc_level *qel, int cc, int probe, int force_ack)
3138{
3139 unsigned int must_ack = force_ack ||
3140 (LIST_ISEMPTY(frms) && (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED));
3141
3142 /* Do not build any more packet if the TX secrets are not available or
3143 * if there is nothing to send, i.e. if no CONNECTION_CLOSE or ACK are required
3144 * and if there is no more packets to send upon PTO expiration
3145 * and if there is no more ack-eliciting frames to send or in flight
3146 * congestion control limit is reached for prepared data
3147 */
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02003148 if (!quic_tls_has_tx_sec(qel) ||
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003149 (!cc && !probe && !must_ack &&
3150 (LIST_ISEMPTY(frms) || qc->path->prep_in_flight >= qc->path->cwnd))) {
3151 return 0;
3152 }
3153
3154 return 1;
3155}
3156
3157/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3158 * <frms>. Each packet is stored in a distinct datagram written to <buf>.
3159 *
3160 * Each datagram is prepended by a two fields header : the datagram length and
3161 * the address of the packet contained in the datagram.
3162 *
3163 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3164 * -1 if something wrong happened.
3165 */
3166static int qc_prep_app_pkts(struct quic_conn *qc, struct buffer *buf,
3167 struct list *frms)
3168{
3169 int ret = -1;
3170 struct quic_enc_level *qel;
3171 unsigned char *end, *pos;
3172 struct quic_tx_packet *pkt;
3173 size_t total;
3174 /* Each datagram is prepended with its length followed by the address
3175 * of the first packet in the datagram.
3176 */
3177 const size_t dg_headlen = sizeof(uint16_t) + sizeof(pkt);
3178
3179 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3180
3181 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3182 total = 0;
3183 pos = (unsigned char *)b_tail(buf);
3184 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen) {
3185 int err, probe, cc;
3186
3187 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3188 probe = 0;
3189 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3190 /* We do not probe if an immediate close was asked */
3191 if (!cc)
3192 probe = qel->pktns->tx.pto_probe;
3193
3194 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, 0))
3195 break;
3196
3197 /* Leave room for the datagram header */
3198 pos += dg_headlen;
3199 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3200 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3201 }
3202 else {
3203 end = pos + qc->path->mtu;
3204 }
3205
3206 pkt = qc_build_pkt(&pos, end, qel, &qel->tls_ctx, frms, qc, NULL, 0,
3207 QUIC_PACKET_TYPE_SHORT, 0, 0, probe, cc, &err);
3208 switch (err) {
3209 case -2:
3210 // trace already emitted by function above
3211 goto leave;
3212 case -1:
3213 /* As we provide qc_build_pkt() with an enough big buffer to fulfill an
3214 * MTU, we are here because of the congestion control window. There is
3215 * no need to try to reuse this buffer.
3216 */
3217 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3218 goto out;
3219 default:
3220 break;
3221 }
3222
3223 /* This is to please to GCC. We cannot have (err >= 0 && !pkt) */
3224 BUG_ON(!pkt);
3225
3226 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3227 pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3228
3229 total += pkt->len;
3230
3231 /* Write datagram header. */
3232 qc_txb_store(buf, pkt->len, pkt);
3233 }
3234
3235 out:
3236 ret = total;
3237 leave:
3238 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3239 return ret;
3240}
3241
3242/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3243 * <frms>. Several packets can be regrouped in a single datagram. The result is
3244 * written into <buf>.
3245 *
3246 * Each datagram is prepended by a two fields header : the datagram length and
3247 * the address of first packet in the datagram.
3248 *
3249 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3250 * -1 if something wrong happened.
3251 */
3252static int qc_prep_pkts(struct quic_conn *qc, struct buffer *buf,
3253 enum quic_tls_enc_level tel, struct list *tel_frms,
3254 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
3255{
3256 struct quic_enc_level *qel;
3257 unsigned char *end, *pos;
3258 struct quic_tx_packet *first_pkt, *cur_pkt, *prv_pkt;
3259 /* length of datagrams */
3260 uint16_t dglen;
3261 size_t total;
3262 int ret = -1, padding;
3263 /* Each datagram is prepended with its length followed by the address
3264 * of the first packet in the datagram.
3265 */
3266 const size_t dg_headlen = sizeof(uint16_t) + sizeof(first_pkt);
3267 struct list *frms;
3268
3269 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3270
3271 /* Currently qc_prep_pkts() does not handle buffer wrapping so the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003272 * caller must ensure that buf is reset.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003273 */
3274 BUG_ON_HOT(buf->head || buf->data);
3275
3276 total = 0;
3277 qel = &qc->els[tel];
3278 frms = tel_frms;
3279 dglen = 0;
3280 padding = 0;
3281 pos = (unsigned char *)b_head(buf);
3282 first_pkt = prv_pkt = NULL;
3283 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen || prv_pkt) {
3284 int err, probe, cc;
3285 enum quic_pkt_type pkt_type;
3286 struct quic_tls_ctx *tls_ctx;
3287 const struct quic_version *ver;
3288 int force_ack = (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3289 (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
3290 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
3291
3292 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3293 probe = 0;
3294 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3295 /* We do not probe if an immediate close was asked */
3296 if (!cc)
3297 probe = qel->pktns->tx.pto_probe;
3298
3299 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, force_ack)) {
3300 if (prv_pkt)
3301 qc_txb_store(buf, dglen, first_pkt);
3302 /* Let's select the next encryption level */
3303 if (tel != next_tel && next_tel != QUIC_TLS_ENC_LEVEL_NONE) {
3304 tel = next_tel;
3305 frms = next_tel_frms;
3306 qel = &qc->els[tel];
3307 /* Build a new datagram */
3308 prv_pkt = NULL;
3309 TRACE_DEVEL("next encryption level selected", QUIC_EV_CONN_PHPKTS, qc);
3310 continue;
3311 }
3312 break;
3313 }
3314
3315 pkt_type = quic_tls_level_pkt_type(tel);
3316 if (!prv_pkt) {
3317 /* Leave room for the datagram header */
3318 pos += dg_headlen;
3319 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3320 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3321 }
3322 else {
3323 end = pos + qc->path->mtu;
3324 }
3325 }
3326
3327 if (qc->negotiated_version) {
3328 ver = qc->negotiated_version;
3329 if (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL])
3330 tls_ctx = &qc->negotiated_ictx;
3331 else
3332 tls_ctx = &qel->tls_ctx;
3333 }
3334 else {
3335 ver = qc->original_version;
3336 tls_ctx = &qel->tls_ctx;
3337 }
3338
3339 cur_pkt = qc_build_pkt(&pos, end, qel, tls_ctx, frms,
3340 qc, ver, dglen, pkt_type,
3341 force_ack, padding, probe, cc, &err);
3342 switch (err) {
3343 case -2:
3344 // trace already emitted by function above
3345 goto leave;
3346 case -1:
3347 /* If there was already a correct packet present, set the
3348 * current datagram as prepared into <cbuf>.
3349 */
3350 if (prv_pkt)
3351 qc_txb_store(buf, dglen, first_pkt);
3352 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3353 goto out;
3354 default:
3355 break;
3356 }
3357
3358 /* This is to please to GCC. We cannot have (err >= 0 && !cur_pkt) */
3359 BUG_ON(!cur_pkt);
3360
3361 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3362 cur_pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3363
3364 total += cur_pkt->len;
3365 /* keep trace of the first packet in the datagram */
3366 if (!first_pkt)
3367 first_pkt = cur_pkt;
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01003368 /* Attach the current one to the previous one and vice versa */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003369 if (prv_pkt) {
3370 prv_pkt->next = cur_pkt;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01003371 cur_pkt->prev = prv_pkt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003372 cur_pkt->flags |= QUIC_FL_TX_PACKET_COALESCED;
3373 }
3374 /* Let's say we have to build a new dgram */
3375 prv_pkt = NULL;
3376 dglen += cur_pkt->len;
3377 /* Client: discard the Initial encryption keys as soon as
3378 * a handshake packet could be built.
3379 */
3380 if (qc->state == QUIC_HS_ST_CLIENT_INITIAL &&
3381 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
3382 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3383 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PHPKTS, qc);
3384 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
3385 qc_set_timer(qc);
3386 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3387 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3388 qc->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
3389 }
3390 /* If the data for the current encryption level have all been sent,
3391 * select the next level.
3392 */
3393 if ((tel == QUIC_TLS_ENC_LEVEL_INITIAL || tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE) &&
3394 next_tel != QUIC_TLS_ENC_LEVEL_NONE && (LIST_ISEMPTY(frms) && !qel->pktns->tx.pto_probe)) {
3395 /* If QUIC_TLS_ENC_LEVEL_HANDSHAKE was already reached let's try QUIC_TLS_ENC_LEVEL_APP */
3396 if (tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE && next_tel == tel)
3397 next_tel = QUIC_TLS_ENC_LEVEL_APP;
3398 tel = next_tel;
3399 if (tel == QUIC_TLS_ENC_LEVEL_APP)
3400 frms = &qc->els[tel].pktns->tx.frms;
3401 else
3402 frms = next_tel_frms;
3403 qel = &qc->els[tel];
3404 if (!LIST_ISEMPTY(frms)) {
3405 /* If there is data for the next level, do not
3406 * consume a datagram.
3407 */
3408 prv_pkt = cur_pkt;
3409 }
3410 }
3411
3412 /* If we have to build a new datagram, set the current datagram as
3413 * prepared into <cbuf>.
3414 */
3415 if (!prv_pkt) {
3416 qc_txb_store(buf, dglen, first_pkt);
3417 first_pkt = NULL;
3418 dglen = 0;
3419 padding = 0;
3420 }
3421 else if (prv_pkt->type == QUIC_TLS_ENC_LEVEL_INITIAL &&
3422 (!qc_is_listener(qc) ||
3423 prv_pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
3424 padding = 1;
3425 }
3426 }
3427
3428 out:
3429 ret = total;
3430 leave:
3431 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3432 return ret;
3433}
3434
3435/* Send datagrams stored in <buf>.
3436 *
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003437 * This function returns 1 for success. On error, there is several behavior
3438 * depending on underlying sendto() error :
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003439 * - for an unrecoverable error, 0 is returned and connection is killed.
3440 * - a transient error is handled differently if connection has its owned
3441 * socket. If this is the case, 0 is returned and socket is subscribed on the
3442 * poller. The other case is assimilated to a success case with 1 returned.
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003443 * Remaining data are purged from the buffer and will eventually be detected
3444 * as lost which gives the opportunity to retry sending.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003445 */
3446int qc_send_ppkts(struct buffer *buf, struct ssl_sock_ctx *ctx)
3447{
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003448 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003449 struct quic_conn *qc;
3450 char skip_sendto = 0;
3451
3452 qc = ctx->qc;
3453 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
3454 while (b_contig_data(buf, 0)) {
3455 unsigned char *pos;
3456 struct buffer tmpbuf = { };
3457 struct quic_tx_packet *first_pkt, *pkt, *next_pkt;
3458 uint16_t dglen;
3459 size_t headlen = sizeof dglen + sizeof first_pkt;
3460 unsigned int time_sent;
3461
3462 pos = (unsigned char *)b_head(buf);
3463 dglen = read_u16(pos);
3464 BUG_ON_HOT(!dglen); /* this should not happen */
3465
3466 pos += sizeof dglen;
3467 first_pkt = read_ptr(pos);
3468 pos += sizeof first_pkt;
3469 tmpbuf.area = (char *)pos;
3470 tmpbuf.size = tmpbuf.data = dglen;
3471
3472 TRACE_DATA("send dgram", QUIC_EV_CONN_SPPKTS, qc);
3473 /* If sendto is on error just skip the call to it for the rest
3474 * of the loop but continue to purge the buffer. Data will be
3475 * transmitted when QUIC packets are detected as lost on our
3476 * side.
3477 *
3478 * TODO use fd-monitoring to detect when send operation can be
3479 * retry. This should improve the bandwidth without relying on
3480 * retransmission timer. However, it requires a major rework on
3481 * quic-conn fd management.
3482 */
3483 if (!skip_sendto) {
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003484 int ret = qc_snd_buf(qc, &tmpbuf, tmpbuf.data, 0);
3485 if (ret < 0) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003486 TRACE_ERROR("sendto fatal error", QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003487 qc_kill_conn(qc);
3488 b_del(buf, buf->data);
3489 goto leave;
3490 }
3491 else if (!ret) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003492 /* Connection owned socket : poller will wake us up when transient error is cleared. */
3493 if (qc_test_fd(qc)) {
3494 TRACE_ERROR("sendto error, subscribe to poller", QUIC_EV_CONN_SPPKTS, qc);
3495 goto leave;
3496 }
3497
3498 /* No connection owned-socket : rely on retransmission to retry sending. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003499 skip_sendto = 1;
3500 TRACE_ERROR("sendto error, simulate sending for the rest of data", QUIC_EV_CONN_SPPKTS, qc);
3501 }
3502 }
3503
3504 b_del(buf, dglen + headlen);
3505 qc->tx.bytes += tmpbuf.data;
3506 time_sent = now_ms;
3507
3508 for (pkt = first_pkt; pkt; pkt = next_pkt) {
3509 pkt->time_sent = time_sent;
3510 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
3511 pkt->pktns->tx.time_of_last_eliciting = time_sent;
3512 qc->path->ifae_pkts++;
3513 if (qc->flags & QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ)
3514 qc_idle_timer_rearm(qc, 0);
3515 }
3516 if (!(qc->flags & QUIC_FL_CONN_CLOSING) &&
3517 (pkt->flags & QUIC_FL_TX_PACKET_CC)) {
3518 qc->flags |= QUIC_FL_CONN_CLOSING;
3519 qc_notify_close(qc);
3520
3521 /* RFC 9000 10.2. Immediate Close:
3522 * The closing and draining connection states exist to ensure
3523 * that connections close cleanly and that delayed or reordered
3524 * packets are properly discarded. These states SHOULD persist
3525 * for at least three times the current PTO interval...
3526 *
3527 * Rearm the idle timeout only one time when entering closing
3528 * state.
3529 */
3530 qc_idle_timer_do_rearm(qc);
3531 if (qc->timer_task) {
3532 task_destroy(qc->timer_task);
3533 qc->timer_task = NULL;
3534 }
3535 }
3536 qc->path->in_flight += pkt->in_flight_len;
3537 pkt->pktns->tx.in_flight += pkt->in_flight_len;
3538 if (pkt->in_flight_len)
3539 qc_set_timer(qc);
3540 TRACE_DATA("sent pkt", QUIC_EV_CONN_SPPKTS, qc, pkt);
3541 next_pkt = pkt->next;
3542 quic_tx_packet_refinc(pkt);
3543 eb64_insert(&pkt->pktns->tx.pkts, &pkt->pn_node);
3544 }
3545 }
3546
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003547 ret = 1;
3548leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003549 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
3550
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003551 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003552}
3553
3554/* Copy into <buf> buffer a stateless reset token depending on the
3555 * <salt> salt input. This is the cluster secret which will be derived
3556 * as HKDF input secret to generate this token.
3557 * Return 1 if succeeded, 0 if not.
3558 */
3559static int quic_stateless_reset_token_cpy(struct quic_conn *qc,
3560 unsigned char *buf, size_t len,
3561 const unsigned char *salt, size_t saltlen)
3562{
3563 /* Input secret */
3564 const unsigned char *key = (const unsigned char *)global.cluster_secret;
3565 size_t keylen = strlen(global.cluster_secret);
3566 /* Info */
3567 const unsigned char label[] = "stateless token";
3568 size_t labellen = sizeof label - 1;
3569 int ret;
3570
3571 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3572
3573 ret = quic_hkdf_extract_and_expand(EVP_sha256(), buf, len,
3574 key, keylen, salt, saltlen, label, labellen);
3575 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3576 return ret;
3577}
3578
3579/* Initialize the stateless reset token attached to <cid> connection ID.
3580 * Returns 1 if succeeded, 0 if not.
3581 */
3582static int quic_stateless_reset_token_init(struct quic_conn *qc,
3583 struct quic_connection_id *quic_cid)
3584{
3585 int ret;
3586
3587 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3588
3589 if (global.cluster_secret) {
3590 /* Output secret */
3591 unsigned char *token = quic_cid->stateless_reset_token;
3592 size_t tokenlen = sizeof quic_cid->stateless_reset_token;
3593 /* Salt */
3594 const unsigned char *cid = quic_cid->cid.data;
3595 size_t cidlen = quic_cid->cid.len;
3596
3597 ret = quic_stateless_reset_token_cpy(qc, token, tokenlen, cid, cidlen);
3598 }
3599 else {
3600 /* TODO: RAND_bytes() should be replaced */
3601 ret = RAND_bytes(quic_cid->stateless_reset_token,
3602 sizeof quic_cid->stateless_reset_token) == 1;
3603 }
3604
3605 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3606 return ret;
3607}
3608
3609/* Allocate a new CID with <seq_num> as sequence number and attach it to <root>
3610 * ebtree.
3611 *
3612 * The CID is randomly generated in part with the result altered to be
3613 * associated with the current thread ID. This means this function must only
3614 * be called by the quic_conn thread.
3615 *
3616 * Returns the new CID if succeeded, NULL if not.
3617 */
3618static struct quic_connection_id *new_quic_cid(struct eb_root *root,
3619 struct quic_conn *qc,
3620 int seq_num)
3621{
3622 struct quic_connection_id *cid;
3623
3624 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3625
3626 cid = pool_alloc(pool_head_quic_connection_id);
3627 if (!cid) {
3628 TRACE_ERROR("cid allocation failed", QUIC_EV_CONN_TXPKT, qc);
3629 goto err;
3630 }
3631
3632 cid->cid.len = QUIC_HAP_CID_LEN;
3633 /* TODO: RAND_bytes() should be replaced */
3634 if (RAND_bytes(cid->cid.data, cid->cid.len) != 1) {
3635 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT, qc);
3636 goto err;
3637 }
3638
3639 quic_pin_cid_to_tid(cid->cid.data, tid);
3640 if (quic_stateless_reset_token_init(qc, cid) != 1) {
3641 TRACE_ERROR("quic_stateless_reset_token_init() failed", QUIC_EV_CONN_TXPKT, qc);
3642 goto err;
3643 }
3644
3645 cid->qc = qc;
3646
3647 cid->seq_num.key = seq_num;
3648 cid->retire_prior_to = 0;
3649 /* insert the allocated CID in the quic_conn tree */
3650 eb64_insert(root, &cid->seq_num);
3651
3652 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3653 return cid;
3654
3655 err:
3656 pool_free(pool_head_quic_connection_id, cid);
3657 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3658 return NULL;
3659}
3660
3661/* Build all the frames which must be sent just after the handshake have succeeded.
3662 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
3663 * a HANDSHAKE_DONE frame.
3664 * Return 1 if succeeded, 0 if not.
3665 */
3666static int quic_build_post_handshake_frames(struct quic_conn *qc)
3667{
3668 int ret = 0, i, first, max;
3669 struct quic_enc_level *qel;
3670 struct quic_frame *frm, *frmbak;
3671 struct list frm_list = LIST_HEAD_INIT(frm_list);
3672 struct eb64_node *node;
3673
3674 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
3675
3676 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3677 /* Only servers must send a HANDSHAKE_DONE frame. */
3678 if (qc_is_listener(qc)) {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003679 frm = qc_frm_alloc(QUIC_FT_HANDSHAKE_DONE);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003680 if (!frm) {
3681 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3682 goto leave;
3683 }
3684
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003685 LIST_APPEND(&frm_list, &frm->list);
3686 }
3687
3688 /* Initialize <max> connection IDs minus one: there is
3689 * already one connection ID used for the current connection.
3690 */
3691 first = 1;
3692 max = qc->tx.params.active_connection_id_limit;
3693
3694 /* TODO: check limit */
3695 for (i = first; i < max; i++) {
3696 struct quic_connection_id *cid;
3697
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003698 frm = qc_frm_alloc(QUIC_FT_NEW_CONNECTION_ID);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003699 if (!frm) {
3700 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3701 goto err;
3702 }
3703
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003704 cid = new_quic_cid(&qc->cids, qc, i);
3705 if (!cid) {
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003706 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003707 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3708 goto err;
3709 }
3710
3711 /* insert the allocated CID in the receiver datagram handler tree */
3712 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3713
3714 quic_connection_id_to_frm_cpy(frm, cid);
3715 LIST_APPEND(&frm_list, &frm->list);
3716 }
3717
3718 LIST_SPLICE(&qel->pktns->tx.frms, &frm_list);
3719 qc->flags |= QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT;
3720
3721 ret = 1;
3722 leave:
3723 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
3724 return ret;
3725
3726 err:
3727 /* free the frames */
3728 list_for_each_entry_safe(frm, frmbak, &frm_list, list)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003729 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003730
3731 node = eb64_lookup_ge(&qc->cids, first);
3732 while (node) {
3733 struct quic_connection_id *cid;
3734
3735 cid = eb64_entry(node, struct quic_connection_id, seq_num);
3736 if (cid->seq_num.key >= max)
3737 break;
3738
3739 node = eb64_next(node);
3740 ebmb_delete(&cid->node);
3741 eb64_delete(&cid->seq_num);
3742 pool_free(pool_head_quic_connection_id, cid);
3743 }
3744 goto leave;
3745}
3746
3747/* Deallocate <l> list of ACK ranges. */
3748void quic_free_arngs(struct quic_conn *qc, struct quic_arngs *arngs)
3749{
3750 struct eb64_node *n;
3751 struct quic_arng_node *ar;
3752
3753 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
3754
3755 n = eb64_first(&arngs->root);
3756 while (n) {
3757 struct eb64_node *next;
3758
3759 ar = eb64_entry(n, struct quic_arng_node, first);
3760 next = eb64_next(n);
3761 eb64_delete(n);
3762 pool_free(pool_head_quic_arng, ar);
3763 n = next;
3764 }
3765
3766 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
3767}
3768
3769/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
3770 * descending order.
3771 */
3772static inline size_t sack_gap(struct quic_arng_node *p,
3773 struct quic_arng_node *q)
3774{
3775 return p->first.key - q->last - 2;
3776}
3777
3778
3779/* Remove the last elements of <ack_ranges> list of ack range updating its
3780 * encoded size until it goes below <limit>.
3781 * Returns 1 if succeeded, 0 if not (no more element to remove).
3782 */
3783static int quic_rm_last_ack_ranges(struct quic_conn *qc,
3784 struct quic_arngs *arngs, size_t limit)
3785{
3786 int ret = 0;
3787 struct eb64_node *last, *prev;
3788
3789 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3790
3791 last = eb64_last(&arngs->root);
3792 while (last && arngs->enc_sz > limit) {
3793 struct quic_arng_node *last_node, *prev_node;
3794
3795 prev = eb64_prev(last);
3796 if (!prev) {
3797 TRACE_DEVEL("<last> not found", QUIC_EV_CONN_TXPKT, qc);
3798 goto out;
3799 }
3800
3801 last_node = eb64_entry(last, struct quic_arng_node, first);
3802 prev_node = eb64_entry(prev, struct quic_arng_node, first);
3803 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
3804 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
3805 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
3806 --arngs->sz;
3807 eb64_delete(last);
3808 pool_free(pool_head_quic_arng, last);
3809 last = prev;
3810 }
3811
3812 ret = 1;
3813 out:
3814 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3815 return ret;
3816}
3817
3818/* Set the encoded size of <arngs> QUIC ack ranges. */
3819static void quic_arngs_set_enc_sz(struct quic_conn *qc, struct quic_arngs *arngs)
3820{
3821 struct eb64_node *node, *next;
3822 struct quic_arng_node *ar, *ar_next;
3823
3824 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3825
3826 node = eb64_last(&arngs->root);
3827 if (!node)
3828 goto leave;
3829
3830 ar = eb64_entry(node, struct quic_arng_node, first);
3831 arngs->enc_sz = quic_int_getsize(ar->last) +
3832 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
3833
3834 while ((next = eb64_prev(node))) {
3835 ar_next = eb64_entry(next, struct quic_arng_node, first);
3836 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
3837 quic_int_getsize(ar_next->last - ar_next->first.key);
3838 node = next;
3839 ar = eb64_entry(node, struct quic_arng_node, first);
3840 }
3841
3842 leave:
3843 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3844}
3845
3846/* Insert <ar> ack range into <argns> tree of ack ranges.
3847 * Returns the ack range node which has been inserted if succeeded, NULL if not.
3848 */
3849static inline
3850struct quic_arng_node *quic_insert_new_range(struct quic_conn *qc,
3851 struct quic_arngs *arngs,
3852 struct quic_arng *ar)
3853{
3854 struct quic_arng_node *new_ar;
3855
3856 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3857
3858 new_ar = pool_alloc(pool_head_quic_arng);
3859 if (!new_ar) {
3860 TRACE_ERROR("ack range allocation failed", QUIC_EV_CONN_RXPKT, qc);
3861 goto leave;
3862 }
3863
3864 new_ar->first.key = ar->first;
3865 new_ar->last = ar->last;
3866 eb64_insert(&arngs->root, &new_ar->first);
3867 arngs->sz++;
3868
3869 leave:
3870 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3871 return new_ar;
3872}
3873
3874/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
3875 * Note that this function computes the number of bytes required to encode
3876 * this tree of ACK ranges in descending order.
3877 *
3878 * Descending order
3879 * ------------->
3880 * range1 range2
3881 * ..........|--------|..............|--------|
3882 * ^ ^ ^ ^
3883 * | | | |
3884 * last1 first1 last2 first2
3885 * ..........+--------+--------------+--------+......
3886 * diff1 gap12 diff2
3887 *
3888 * To encode the previous list of ranges we must encode integers as follows in
3889 * descending order:
3890 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
3891 * with diff1 = last1 - first1
3892 * diff2 = last2 - first2
3893 * gap12 = first1 - last2 - 2 (>= 0)
3894 *
3895
3896returns 0 on error
3897
3898 */
3899int quic_update_ack_ranges_list(struct quic_conn *qc,
3900 struct quic_arngs *arngs,
3901 struct quic_arng *ar)
3902{
3903 int ret = 0;
3904 struct eb64_node *le;
3905 struct quic_arng_node *new_node;
3906 struct eb64_node *new;
3907
3908 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3909
3910 new = NULL;
3911 if (eb_is_empty(&arngs->root)) {
3912 new_node = quic_insert_new_range(qc, arngs, ar);
3913 if (new_node)
3914 ret = 1;
3915
3916 goto leave;
3917 }
3918
3919 le = eb64_lookup_le(&arngs->root, ar->first);
3920 if (!le) {
3921 new_node = quic_insert_new_range(qc, arngs, ar);
3922 if (!new_node)
3923 goto leave;
3924
3925 new = &new_node->first;
3926 }
3927 else {
3928 struct quic_arng_node *le_ar =
3929 eb64_entry(le, struct quic_arng_node, first);
3930
3931 /* Already existing range */
3932 if (le_ar->last >= ar->last) {
3933 ret = 1;
3934 }
3935 else if (le_ar->last + 1 >= ar->first) {
3936 le_ar->last = ar->last;
3937 new = le;
3938 new_node = le_ar;
3939 }
3940 else {
3941 new_node = quic_insert_new_range(qc, arngs, ar);
3942 if (!new_node)
3943 goto leave;
3944
3945 new = &new_node->first;
3946 }
3947 }
3948
3949 /* Verify that the new inserted node does not overlap the nodes
3950 * which follow it.
3951 */
3952 if (new) {
3953 struct eb64_node *next;
3954 struct quic_arng_node *next_node;
3955
3956 while ((next = eb64_next(new))) {
3957 next_node =
3958 eb64_entry(next, struct quic_arng_node, first);
3959 if (new_node->last + 1 < next_node->first.key)
3960 break;
3961
3962 if (next_node->last > new_node->last)
3963 new_node->last = next_node->last;
3964 eb64_delete(next);
3965 pool_free(pool_head_quic_arng, next_node);
3966 /* Decrement the size of these ranges. */
3967 arngs->sz--;
3968 }
3969 }
3970
3971 ret = 1;
3972 leave:
3973 quic_arngs_set_enc_sz(qc, arngs);
3974 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3975 return ret;
3976}
3977/* Remove the header protection of packets at <el> encryption level.
3978 * Always succeeds.
3979 */
3980static inline void qc_rm_hp_pkts(struct quic_conn *qc, struct quic_enc_level *el)
3981{
3982 struct quic_tls_ctx *tls_ctx;
3983 struct quic_rx_packet *pqpkt, *pkttmp;
3984 struct quic_enc_level *app_qel;
3985
3986 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, qc);
3987 app_qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3988 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
3989 if (el == app_qel && qc_is_listener(qc) && qc->state < QUIC_HS_ST_COMPLETE) {
3990 TRACE_DEVEL("hp not removed (handshake not completed)",
3991 QUIC_EV_CONN_ELRMHP, qc);
3992 goto out;
3993 }
3994 tls_ctx = &el->tls_ctx;
3995 list_for_each_entry_safe(pqpkt, pkttmp, &el->rx.pqpkts, list) {
3996 if (!qc_do_rm_hp(qc, pqpkt, tls_ctx, el->pktns->rx.largest_pn,
3997 pqpkt->data + pqpkt->pn_offset, pqpkt->data)) {
3998 TRACE_ERROR("hp removing error", QUIC_EV_CONN_ELRMHP, qc);
3999 }
4000 else {
4001 /* The AAD includes the packet number field */
4002 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
4003 /* Store the packet into the tree of packets to decrypt. */
4004 pqpkt->pn_node.key = pqpkt->pn;
4005 eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
4006 quic_rx_packet_refinc(pqpkt);
4007 TRACE_DEVEL("hp removed", QUIC_EV_CONN_ELRMHP, qc, pqpkt);
4008 }
4009 LIST_DELETE(&pqpkt->list);
4010 quic_rx_packet_refdec(pqpkt);
4011 }
4012
4013 out:
4014 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, qc);
4015}
4016
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004017/* Process all the CRYPTO frame at <el> encryption level. This is the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004018 * responsibility of the called to ensure there exists a CRYPTO data
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004019 * stream for this level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004020 * Return 1 if succeeded, 0 if not.
4021 */
4022static inline int qc_treat_rx_crypto_frms(struct quic_conn *qc,
4023 struct quic_enc_level *el,
4024 struct ssl_sock_ctx *ctx)
4025{
4026 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004027 struct ncbuf *ncbuf;
4028 struct quic_cstream *cstream = el->cstream;
4029 ncb_sz_t data;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004030
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004031 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004032
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004033 BUG_ON(!cstream);
4034 ncbuf = &cstream->rx.ncbuf;
4035 if (ncb_is_null(ncbuf))
4036 goto done;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004037
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004038 /* TODO not working if buffer is wrapping */
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004039 while ((data = ncb_data(ncbuf, 0))) {
4040 const unsigned char *cdata = (const unsigned char *)ncb_head(ncbuf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004041
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004042 if (!qc_provide_cdata(el, ctx, cdata, data, NULL, NULL))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004043 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004044
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004045 cstream->rx.offset += data;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004046 TRACE_DEVEL("buffered crypto data were provided to TLS stack",
4047 QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004048 }
4049
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004050 done:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004051 ret = 1;
4052 leave:
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004053 if (!ncb_is_null(ncbuf) && ncb_is_empty(ncbuf)) {
4054 TRACE_DEVEL("freeing crypto buf", QUIC_EV_CONN_PHPKTS, qc, el);
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004055 quic_free_ncbuf(ncbuf);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004056 }
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004057 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004058 return ret;
4059}
4060
4061/* Process all the packets at <el> and <next_el> encryption level.
4062 * This is the caller responsibility to check that <cur_el> is different of <next_el>
4063 * as pointer value.
4064 * Return 1 if succeeded, 0 if not.
4065 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004066int qc_treat_rx_pkts(struct quic_conn *qc, struct quic_enc_level *cur_el,
4067 struct quic_enc_level *next_el, int force_ack)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004068{
4069 int ret = 0;
4070 struct eb64_node *node;
4071 int64_t largest_pn = -1;
4072 unsigned int largest_pn_time_received = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004073 struct quic_enc_level *qel = cur_el;
4074
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004075 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004076 qel = cur_el;
4077 next_tel:
4078 if (!qel)
4079 goto out;
4080
4081 node = eb64_first(&qel->rx.pkts);
4082 while (node) {
4083 struct quic_rx_packet *pkt;
4084
4085 pkt = eb64_entry(node, struct quic_rx_packet, pn_node);
4086 TRACE_DATA("new packet", QUIC_EV_CONN_RXPKT,
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004087 qc, pkt, NULL, qc->xprt_ctx->ssl);
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01004088 if (!qc_pkt_decrypt(qc, qel, pkt)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004089 /* Drop the packet */
4090 TRACE_ERROR("packet decryption failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004091 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004092 }
4093 else {
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004094 if (!qc_parse_pkt_frms(qc, pkt, qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004095 /* Drop the packet */
4096 TRACE_ERROR("packet parsing failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004097 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004098 HA_ATOMIC_INC(&qc->prx_counters->dropped_parsing);
4099 }
4100 else {
4101 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
4102
4103 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING || force_ack) {
4104 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
4105 qel->pktns->rx.nb_aepkts_since_last_ack++;
4106 qc_idle_timer_rearm(qc, 1);
4107 }
4108 if (pkt->pn > largest_pn) {
4109 largest_pn = pkt->pn;
4110 largest_pn_time_received = pkt->time_received;
4111 }
4112 /* Update the list of ranges to acknowledge. */
4113 if (!quic_update_ack_ranges_list(qc, &qel->pktns->rx.arngs, &ar))
4114 TRACE_ERROR("Could not update ack range list",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004115 QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004116 }
4117 }
4118 node = eb64_next(node);
4119 eb64_delete(&pkt->pn_node);
4120 quic_rx_packet_refdec(pkt);
4121 }
4122
4123 if (largest_pn != -1 && largest_pn > qel->pktns->rx.largest_pn) {
4124 /* Update the largest packet number. */
4125 qel->pktns->rx.largest_pn = largest_pn;
4126 /* Update the largest acknowledged packet timestamps */
4127 qel->pktns->rx.largest_time_received = largest_pn_time_received;
4128 qel->pktns->flags |= QUIC_FL_PKTNS_NEW_LARGEST_PN;
4129 }
4130
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004131 if (qel->cstream && !qc_treat_rx_crypto_frms(qc, qel, qc->xprt_ctx)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004132 // trace already emitted by function above
4133 goto leave;
4134 }
4135
4136 if (qel == cur_el) {
4137 BUG_ON(qel == next_el);
4138 qel = next_el;
4139 largest_pn = -1;
4140 goto next_tel;
4141 }
4142
4143 out:
4144 ret = 1;
4145 leave:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004146 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004147 return ret;
4148}
4149
4150/* Check if it's possible to remove header protection for packets related to
4151 * encryption level <qel>. If <qel> is NULL, assume it's false.
4152 *
4153 * Return true if the operation is possible else false.
4154 */
4155static int qc_qel_may_rm_hp(struct quic_conn *qc, struct quic_enc_level *qel)
4156{
4157 int ret = 0;
4158 enum quic_tls_enc_level tel;
4159
4160 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
4161
4162 if (!qel)
4163 goto cant_rm_hp;
4164
4165 tel = ssl_to_quic_enc_level(qel->level);
4166
4167 /* check if tls secrets are available */
4168 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
4169 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, qc);
4170 goto cant_rm_hp;
4171 }
4172
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004173 if (!quic_tls_has_rx_sec(qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004174 TRACE_DEVEL("non available secrets", QUIC_EV_CONN_TRMHP, qc);
4175 goto cant_rm_hp;
4176 }
4177
Frédéric Lécaille8417beb2023-02-01 10:31:35 +01004178 if (tel == QUIC_TLS_ENC_LEVEL_APP && qc->state < QUIC_HS_ST_COMPLETE) {
4179 TRACE_DEVEL("handshake not complete", QUIC_EV_CONN_TRMHP, qc);
4180 goto cant_rm_hp;
4181 }
4182
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004183 /* check if the connection layer is ready before using app level */
4184 if ((tel == QUIC_TLS_ENC_LEVEL_APP || tel == QUIC_TLS_ENC_LEVEL_EARLY_DATA) &&
4185 qc->mux_state == QC_MUX_NULL) {
4186 TRACE_DEVEL("connection layer not ready", QUIC_EV_CONN_TRMHP, qc);
4187 goto cant_rm_hp;
4188 }
4189
4190 ret = 1;
4191 cant_rm_hp:
4192 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc);
4193 return ret;
4194}
4195
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004196/* Flush txbuf for <qc> connection. This must be called prior to a packet
4197 * preparation when txbuf contains older data. A send will be conducted for
4198 * these data.
4199 *
4200 * Returns 1 on success : buffer is empty and can be use for packet
4201 * preparation. On error 0 is returned.
4202 */
4203static int qc_purge_txbuf(struct quic_conn *qc, struct buffer *buf)
4204{
4205 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4206
4207 /* This operation can only be conducted if txbuf is not empty. This
4208 * case only happens for connection with their owned socket due to an
4209 * older transient sendto() error.
4210 */
4211 BUG_ON(!qc_test_fd(qc));
4212
4213 if (b_data(buf) && !qc_send_ppkts(buf, qc->xprt_ctx)) {
4214 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4215 qc_txb_release(qc);
4216 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TXPKT, qc);
4217 return 0;
4218 }
4219
4220 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4221 return 1;
4222}
4223
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004224/* Try to send application frames from list <frms> on connection <qc>.
4225 *
4226 * Use qc_send_app_probing wrapper when probing with old data.
4227 *
4228 * Returns 1 on success. Some data might not have been sent due to congestion,
4229 * in this case they are left in <frms> input list. The caller may subscribe on
4230 * quic-conn to retry later.
4231 *
4232 * Returns 0 on critical error.
4233 * TODO review and classify more distinctly transient from definitive errors to
4234 * allow callers to properly handle it.
4235 */
4236static int qc_send_app_pkts(struct quic_conn *qc, struct list *frms)
4237{
4238 int status = 0;
4239 struct buffer *buf;
4240
4241 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4242
4243 buf = qc_txb_alloc(qc);
4244 if (!buf) {
4245 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004246 goto err;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004247 }
4248
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004249 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4250 goto err;
4251
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004252 /* Prepare and send packets until we could not further prepare packets. */
4253 while (1) {
4254 int ret;
4255 /* Currently buf cannot be non-empty at this stage. Even if a
4256 * previous sendto() has failed it is emptied to simulate
4257 * packet emission and rely on QUIC lost detection to try to
4258 * emit it.
4259 */
4260 BUG_ON_HOT(b_data(buf));
4261 b_reset(buf);
4262
4263 ret = qc_prep_app_pkts(qc, buf, frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004264 if (ret == -1) {
4265 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004266 goto err;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004267 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004268
Amaury Denoyelle37333862023-02-28 11:53:48 +01004269 if (!ret)
4270 break;
4271
4272 if (!qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004273 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4274 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004275 goto err;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004276 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004277 }
4278
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004279 status = 1;
4280 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004281 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4282 return status;
4283
4284 err:
Amaury Denoyelle37333862023-02-28 11:53:48 +01004285 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TXPKT, qc);
4286 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004287}
4288
4289/* Try to send application frames from list <frms> on connection <qc>. Use this
4290 * function when probing is required.
4291 *
4292 * Returns the result from qc_send_app_pkts function.
4293 */
4294static forceinline int qc_send_app_probing(struct quic_conn *qc,
4295 struct list *frms)
4296{
4297 int ret;
4298
4299 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4300
4301 TRACE_STATE("preparing old data (probing)", QUIC_EV_CONN_TXPKT, qc);
4302 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4303 ret = qc_send_app_pkts(qc, frms);
4304 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4305
4306 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4307 return ret;
4308}
4309
4310/* Try to send application frames from list <frms> on connection <qc>. This
4311 * function is provided for MUX upper layer usage only.
4312 *
4313 * Returns the result from qc_send_app_pkts function.
4314 */
4315int qc_send_mux(struct quic_conn *qc, struct list *frms)
4316{
4317 int ret;
4318
4319 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4320 BUG_ON(qc->mux_state != QC_MUX_READY); /* Only MUX can uses this function so it must be ready. */
4321
4322 TRACE_STATE("preparing data (from MUX)", QUIC_EV_CONN_TXPKT, qc);
4323 qc->flags |= QUIC_FL_CONN_TX_MUX_CONTEXT;
4324 ret = qc_send_app_pkts(qc, frms);
4325 qc->flags &= ~QUIC_FL_CONN_TX_MUX_CONTEXT;
4326
4327 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4328 return ret;
4329}
4330
4331/* Sends handshake packets from up to two encryption levels <tel> and <next_te>
4332 * with <tel_frms> and <next_tel_frms> as frame list respectively for <qc>
4333 * QUIC connection. <old_data> is used as boolean to send data already sent but
4334 * not already acknowledged (in flight).
4335 * Returns 1 if succeeded, 0 if not.
4336 */
4337int qc_send_hdshk_pkts(struct quic_conn *qc, int old_data,
4338 enum quic_tls_enc_level tel, struct list *tel_frms,
4339 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
4340{
4341 int ret, status = 0;
4342 struct buffer *buf = qc_txb_alloc(qc);
4343
4344 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4345
4346 if (!buf) {
4347 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4348 goto leave;
4349 }
4350
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004351 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4352 goto out;
4353
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004354 /* Currently buf cannot be non-empty at this stage. Even if a previous
4355 * sendto() has failed it is emptied to simulate packet emission and
4356 * rely on QUIC lost detection to try to emit it.
4357 */
4358 BUG_ON_HOT(b_data(buf));
4359 b_reset(buf);
4360
4361 if (old_data) {
4362 TRACE_STATE("old data for probing asked", QUIC_EV_CONN_TXPKT, qc);
4363 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4364 }
4365
4366 ret = qc_prep_pkts(qc, buf, tel, tel_frms, next_tel, next_tel_frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004367 if (ret == -1) {
4368 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004369 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004370 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004371
Amaury Denoyelle37333862023-02-28 11:53:48 +01004372 if (ret && !qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004373 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4374 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004375 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004376 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004377
Amaury Denoyelle37333862023-02-28 11:53:48 +01004378 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004379 status = 1;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004380
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004381 out:
4382 TRACE_STATE("no more need old data for probing", QUIC_EV_CONN_TXPKT, qc);
4383 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004384 leave:
4385 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4386 return status;
4387}
4388
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004389/* Retransmit up to two datagrams depending on packet number space.
4390 * Return 0 when failed, 0 if not.
4391 */
4392static int qc_dgrams_retransmit(struct quic_conn *qc)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004393{
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004394 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004395 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4396 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4397 struct quic_enc_level *aqel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4398
4399 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4400
4401 if (iqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004402 int i;
4403
4404 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
4405 struct list ifrms = LIST_HEAD_INIT(ifrms);
4406 struct list hfrms = LIST_HEAD_INIT(hfrms);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004407
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004408 qc_prep_hdshk_fast_retrans(qc, &ifrms, &hfrms);
4409 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &ifrms);
4410 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4411 if (!LIST_ISEMPTY(&ifrms)) {
4412 iqel->pktns->tx.pto_probe = 1;
4413 if (!LIST_ISEMPTY(&hfrms))
4414 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004415 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4416 QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms))
4417 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004418 /* Put back unsent frames in their packet number spaces */
4419 LIST_SPLICE(&iqel->pktns->tx.frms, &ifrms);
4420 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4421 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004422 }
4423 TRACE_STATE("no more need to probe Initial packet number space",
4424 QUIC_EV_CONN_TXPKT, qc);
4425 iqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004426 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004427 }
4428 else {
4429 int i;
4430
4431 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004432 hqel->pktns->tx.pto_probe = 0;
4433 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
Frédéric Lécaille7b5d9b12022-11-28 17:21:45 +01004434 struct list frms1 = LIST_HEAD_INIT(frms1);
4435
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004436 qc_prep_fast_retrans(qc, hqel, &frms1, NULL);
4437 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4438 if (!LIST_ISEMPTY(&frms1)) {
4439 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004440 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &frms1,
4441 QUIC_TLS_ENC_LEVEL_NONE, NULL))
4442 goto leave;
4443
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004444 /* Put back unsent frames into their packet number spaces */
4445 LIST_SPLICE(&hqel->pktns->tx.frms, &frms1);
4446 }
4447 }
4448 TRACE_STATE("no more need to probe Handshake packet number space",
4449 QUIC_EV_CONN_TXPKT, qc);
4450 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4451 }
4452 else if (aqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4453 struct list frms2 = LIST_HEAD_INIT(frms2);
4454 struct list frms1 = LIST_HEAD_INIT(frms1);
4455
4456 aqel->pktns->tx.pto_probe = 0;
4457 qc_prep_fast_retrans(qc, aqel, &frms1, &frms2);
4458 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4459 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms2);
4460 if (!LIST_ISEMPTY(&frms1)) {
4461 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004462 if (!qc_send_app_probing(qc, &frms1))
4463 goto leave;
4464
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004465 /* Put back unsent frames into their packet number spaces */
4466 LIST_SPLICE(&aqel->pktns->tx.frms, &frms1);
4467 }
4468 if (!LIST_ISEMPTY(&frms2)) {
4469 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004470 if (!qc_send_app_probing(qc, &frms2))
4471 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004472 /* Put back unsent frames into their packet number spaces */
4473 LIST_SPLICE(&aqel->pktns->tx.frms, &frms2);
4474 }
4475 TRACE_STATE("no more need to probe 01RTT packet number space",
4476 QUIC_EV_CONN_TXPKT, qc);
4477 aqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4478 }
4479 }
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004480
4481 ret = 1;
4482 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004483 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004484 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004485}
4486
4487/* QUIC connection packet handler task (post handshake) */
4488struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state)
4489{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004490 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004491 struct quic_enc_level *qel;
4492
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004493 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4494
4495 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
4496 TRACE_STATE("connection handshake state", QUIC_EV_CONN_IO_CB, qc, &qc->state);
4497
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004498 if (qc_test_fd(qc))
4499 qc_rcv_buf(qc);
4500
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004501 /* Retranmissions */
4502 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4503 TRACE_STATE("retransmission needed", QUIC_EV_CONN_IO_CB, qc);
4504 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004505 if (!qc_dgrams_retransmit(qc))
4506 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004507 }
4508
4509 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4510 qc_rm_hp_pkts(qc, qel);
4511
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004512 if (!qc_treat_rx_pkts(qc, qel, NULL, 0)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004513 TRACE_DEVEL("qc_treat_rx_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4514 goto out;
4515 }
4516
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004517 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4518 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
4519 goto out;
4520 }
4521
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004522 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4523 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)) {
4524 TRACE_STATE("draining connection (must not send packets)", QUIC_EV_CONN_IO_CB, qc);
4525 goto out;
4526 }
4527
4528 /* XXX TODO: how to limit the list frames to send */
4529 if (!qc_send_app_pkts(qc, &qel->pktns->tx.frms)) {
4530 TRACE_DEVEL("qc_send_app_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4531 goto out;
4532 }
4533
4534 out:
4535 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
4536 return t;
4537}
4538
4539/* Returns a boolean if <qc> needs to emit frames for <qel> encryption level. */
4540static int qc_need_sending(struct quic_conn *qc, struct quic_enc_level *qel)
4541{
4542 return (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) ||
4543 (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) ||
4544 qel->pktns->tx.pto_probe ||
4545 !LIST_ISEMPTY(&qel->pktns->tx.frms);
4546}
4547
4548/* QUIC connection packet handler task. */
4549struct task *quic_conn_io_cb(struct task *t, void *context, unsigned int state)
4550{
4551 int ret, ssl_err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004552 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004553 enum quic_tls_enc_level tel, next_tel;
4554 struct quic_enc_level *qel, *next_qel;
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004555 /* Early-data encryption level */
4556 struct quic_enc_level *eqel;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004557 struct buffer *buf = NULL;
4558 int st, force_ack, zero_rtt;
4559
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004560 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004561 eqel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004562 st = qc->state;
4563 TRACE_PROTO("connection state", QUIC_EV_CONN_IO_CB, qc, &st);
4564
4565 /* Retranmissions */
4566 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4567 TRACE_DEVEL("retransmission needed", QUIC_EV_CONN_PHPKTS, qc);
4568 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004569 if (!qc_dgrams_retransmit(qc))
4570 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004571 }
4572
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004573 ssl_err = SSL_ERROR_NONE;
4574 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004575 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004576 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004577
4578 if (qc_test_fd(qc))
4579 qc_rcv_buf(qc);
4580
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004581 if (st >= QUIC_HS_ST_COMPLETE &&
4582 qc_el_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
4583 TRACE_DEVEL("remaining Handshake packets", QUIC_EV_CONN_PHPKTS, qc);
4584 /* There may be remaining Handshake packets to treat and acknowledge. */
4585 tel = QUIC_TLS_ENC_LEVEL_HANDSHAKE;
4586 next_tel = QUIC_TLS_ENC_LEVEL_APP;
4587 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004588 else if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, zero_rtt))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004589 goto out;
4590
4591 qel = &qc->els[tel];
4592 next_qel = next_tel == QUIC_TLS_ENC_LEVEL_NONE ? NULL : &qc->els[next_tel];
4593
4594 next_level:
4595 /* Treat packets waiting for header packet protection decryption */
4596 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4597 qc_rm_hp_pkts(qc, qel);
4598
4599 force_ack = qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
4600 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004601 if (!qc_treat_rx_pkts(qc, qel, next_qel, force_ack))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004602 goto out;
4603
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004604 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4605 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_PHPKTS, qc);
4606 goto out;
4607 }
4608
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004609 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4610 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE))
4611 goto out;
4612
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004613 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004614 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004615 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
4616 if (next_qel && next_qel == eqel && zero_rtt) {
4617 TRACE_DEVEL("select 0RTT as next encryption level",
4618 QUIC_EV_CONN_PHPKTS, qc);
4619 qel = next_qel;
4620 next_qel = NULL;
4621 goto next_level;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004622 }
4623
4624 st = qc->state;
4625 if (st >= QUIC_HS_ST_COMPLETE) {
4626 if (!(qc->flags & QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT) &&
4627 !quic_build_post_handshake_frames(qc))
4628 goto out;
4629
4630 if (!(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].tls_ctx.flags &
4631 QUIC_FL_TLS_SECRETS_DCD)) {
4632 /* Discard the Handshake keys. */
4633 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4634 TRACE_PROTO("discarding Handshake pktns", QUIC_EV_CONN_PHPKTS, qc);
4635 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, qc);
4636 qc_set_timer(qc);
4637 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4638 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns);
4639 }
4640
4641 if (qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) {
4642 /* There may be remaining handshake to build (acks) */
4643 st = QUIC_HS_ST_SERVER_HANDSHAKE;
4644 }
4645 }
4646
4647 /* A listener does not send any O-RTT packet. O-RTT packet number space must not
4648 * be considered.
4649 */
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004650 if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, 0))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004651 goto out;
4652
4653 if (!qc_need_sending(qc, qel) &&
4654 (!next_qel || !qc_need_sending(qc, next_qel))) {
4655 goto skip_send;
4656 }
4657
4658 buf = qc_txb_alloc(qc);
4659 if (!buf)
4660 goto out;
4661
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004662 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4663 goto skip_send;
4664
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004665 /* Currently buf cannot be non-empty at this stage. Even if a previous
4666 * sendto() has failed it is emptied to simulate packet emission and
4667 * rely on QUIC lost detection to try to emit it.
4668 */
4669 BUG_ON_HOT(b_data(buf));
4670 b_reset(buf);
4671
4672 ret = qc_prep_pkts(qc, buf, tel, &qc->els[tel].pktns->tx.frms,
4673 next_tel, &qc->els[next_tel].pktns->tx.frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004674 if (ret == -1) {
4675 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004676 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004677 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004678
Amaury Denoyelle37333862023-02-28 11:53:48 +01004679 if (ret && !qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004680 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4681 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004682 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004683 }
4684
4685 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004686
4687 skip_send:
4688 /* Check if there is something to do for the next level.
4689 */
4690 if (next_qel && next_qel != qel &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004691 quic_tls_has_rx_sec(next_qel) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004692 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || qc_el_rx_pkts(next_qel))) {
4693 qel = next_qel;
4694 next_qel = NULL;
4695 goto next_level;
4696 }
4697
4698 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004699 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc, &st, &ssl_err);
4700 return t;
4701}
4702
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004703/* Release the memory allocated for <cs> CRYPTO stream */
4704void quic_cstream_free(struct quic_cstream *cs)
4705{
4706 if (!cs) {
4707 /* This is the case for ORTT encryption level */
4708 return;
4709 }
4710
Amaury Denoyellebc174b22022-11-17 10:12:52 +01004711 quic_free_ncbuf(&cs->rx.ncbuf);
4712
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004713 qc_stream_desc_release(cs->desc);
4714 pool_free(pool_head_quic_cstream, cs);
4715}
4716
4717/* Allocate a new QUIC stream for <qc>.
4718 * Return it if succeeded, NULL if not.
4719 */
4720struct quic_cstream *quic_cstream_new(struct quic_conn *qc)
4721{
4722 struct quic_cstream *cs, *ret_cs = NULL;
4723
4724 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4725 cs = pool_alloc(pool_head_quic_cstream);
4726 if (!cs) {
4727 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4728 goto leave;
4729 }
4730
4731 cs->rx.offset = 0;
4732 cs->rx.ncbuf = NCBUF_NULL;
4733 cs->rx.offset = 0;
4734
4735 cs->tx.offset = 0;
4736 cs->tx.sent_offset = 0;
4737 cs->tx.buf = BUF_NULL;
4738 cs->desc = qc_stream_desc_new((uint64_t)-1, -1, cs, qc);
4739 if (!cs->desc) {
4740 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4741 goto err;
4742 }
4743
4744 ret_cs = cs;
4745 leave:
4746 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4747 return ret_cs;
4748
4749 err:
4750 pool_free(pool_head_quic_cstream, cs);
4751 goto leave;
4752}
4753
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004754/* Uninitialize <qel> QUIC encryption level. Never fails. */
4755static void quic_conn_enc_level_uninit(struct quic_conn *qc, struct quic_enc_level *qel)
4756{
4757 int i;
4758
4759 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4760
4761 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
4762 if (qel->tx.crypto.bufs[i]) {
4763 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
4764 qel->tx.crypto.bufs[i] = NULL;
4765 }
4766 }
4767 ha_free(&qel->tx.crypto.bufs);
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004768 quic_cstream_free(qel->cstream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004769
4770 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4771}
4772
4773/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
4774 * connection allocating everything needed.
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004775 *
4776 * Returns 1 if succeeded, 0 if not. On error the caller is responsible to use
4777 * quic_conn_enc_level_uninit() to cleanup partially allocated content.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004778 */
4779static int quic_conn_enc_level_init(struct quic_conn *qc,
4780 enum quic_tls_enc_level level)
4781{
4782 int ret = 0;
4783 struct quic_enc_level *qel;
4784
4785 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4786
4787 qel = &qc->els[level];
4788 qel->level = quic_to_ssl_enc_level(level);
4789 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
4790 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
4791 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
4792 qel->tls_ctx.flags = 0;
4793
4794 qel->rx.pkts = EB_ROOT;
4795 LIST_INIT(&qel->rx.pqpkts);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004796
4797 /* Allocate only one buffer. */
4798 /* TODO: use a pool */
4799 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
4800 if (!qel->tx.crypto.bufs)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004801 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004802
4803 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
4804 if (!qel->tx.crypto.bufs[0])
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004805 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004806
4807 qel->tx.crypto.bufs[0]->sz = 0;
4808 qel->tx.crypto.nb_buf = 1;
4809
4810 qel->tx.crypto.sz = 0;
4811 qel->tx.crypto.offset = 0;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004812 /* No CRYPTO data for early data TLS encryption level */
4813 if (level == QUIC_TLS_ENC_LEVEL_EARLY_DATA)
4814 qel->cstream = NULL;
4815 else {
4816 qel->cstream = quic_cstream_new(qc);
4817 if (!qel->cstream)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004818 goto leave;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004819 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004820
4821 ret = 1;
4822 leave:
4823 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4824 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004825}
4826
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004827/* Return 1 if <qc> connection may probe the Initial packet number space, 0 if not.
4828 * This is not the case if the remote peer address is not validated and if
4829 * it cannot send at least QUIC_INITIAL_PACKET_MINLEN bytes.
4830 */
4831static int qc_may_probe_ipktns(struct quic_conn *qc)
4832{
4833 return quic_peer_validated_addr(qc) ||
4834 (int)(3 * qc->rx.bytes - qc->tx.prep_bytes) >= QUIC_INITIAL_PACKET_MINLEN;
4835}
4836
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004837/* Callback called upon loss detection and PTO timer expirations. */
4838struct task *qc_process_timer(struct task *task, void *ctx, unsigned int state)
4839{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004840 struct quic_conn *qc = ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004841 struct quic_pktns *pktns;
4842
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004843 TRACE_ENTER(QUIC_EV_CONN_PTIMER, qc,
4844 NULL, NULL, &qc->path->ifae_pkts);
4845 task->expire = TICK_ETERNITY;
4846 pktns = quic_loss_pktns(qc);
4847 if (tick_isset(pktns->tx.loss_time)) {
4848 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
4849
4850 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
4851 if (!LIST_ISEMPTY(&lost_pkts))
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004852 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01004853 if (qc_release_lost_pkts(qc, pktns, &lost_pkts, now_ms))
4854 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004855 goto out;
4856 }
4857
4858 if (qc->path->in_flight) {
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +01004859 pktns = quic_pto_pktns(qc, qc->state >= QUIC_HS_ST_CONFIRMED, NULL);
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01004860 if (!qc_notify_send(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004861 if (pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL]) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004862 if (qc_may_probe_ipktns(qc)) {
4863 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4864 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4865 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4866 }
4867 else {
4868 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4869 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004870 if (qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].tx.in_flight) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004871 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004872 qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4873 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
4874 }
4875 }
4876 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE]) {
4877 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004878 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4879 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004880 if (qc->pktns[QUIC_TLS_PKTNS_INITIAL].tx.in_flight) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004881 if (qc_may_probe_ipktns(qc)) {
4882 qc->pktns[QUIC_TLS_PKTNS_INITIAL].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4883 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4884 }
4885 else {
4886 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4887 }
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004888 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004889 }
4890 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT]) {
4891 TRACE_STATE("needs to probe 01RTT packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004892 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4893 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004894 }
4895 }
4896 }
4897 else if (!qc_is_listener(qc) && qc->state <= QUIC_HS_ST_COMPLETE) {
4898 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4899 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4900
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004901 if (quic_tls_has_tx_sec(hel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004902 hel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004903 if (quic_tls_has_tx_sec(iel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004904 iel->pktns->tx.pto_probe = 1;
4905 }
4906
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004907 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004908 qc->path->loss.pto_count++;
4909
4910 out:
4911 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, qc, pktns);
4912
4913 return task;
4914}
4915
4916/* Parse the Retry token from buffer <token> with <end> a pointer to
4917 * one byte past the end of this buffer. This will extract the ODCID
4918 * which will be stored into <odcid>
4919 *
4920 * Returns 0 on success else non-zero.
4921 */
4922static int parse_retry_token(struct quic_conn *qc,
4923 const unsigned char *token, const unsigned char *end,
4924 struct quic_cid *odcid)
4925{
4926 int ret = 0;
4927 uint64_t odcid_len;
4928 uint32_t timestamp;
4929
4930 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4931
4932 if (!quic_dec_int(&odcid_len, &token, end)) {
4933 TRACE_ERROR("quic_dec_int() error", QUIC_EV_CONN_LPKT, qc);
4934 goto leave;
4935 }
4936
4937 /* RFC 9000 7.2. Negotiating Connection IDs:
4938 * When an Initial packet is sent by a client that has not previously
4939 * received an Initial or Retry packet from the server, the client
4940 * populates the Destination Connection ID field with an unpredictable
4941 * value. This Destination Connection ID MUST be at least 8 bytes in length.
4942 */
4943 if (odcid_len < QUIC_ODCID_MINLEN || odcid_len > QUIC_CID_MAXLEN) {
4944 TRACE_ERROR("wrong ODCID length", QUIC_EV_CONN_LPKT, qc);
4945 goto leave;
4946 }
4947
4948 if (end - token < odcid_len + sizeof timestamp) {
4949 TRACE_ERROR("too long ODCID length", QUIC_EV_CONN_LPKT, qc);
4950 goto leave;
4951 }
4952
4953 timestamp = ntohl(read_u32(token + odcid_len));
4954 if (timestamp + MS_TO_TICKS(QUIC_RETRY_DURATION_MS) <= now_ms) {
4955 TRACE_ERROR("token has expired", QUIC_EV_CONN_LPKT, qc);
4956 goto leave;
4957 }
4958
4959 ret = 1;
4960 memcpy(odcid->data, token, odcid_len);
4961 odcid->len = odcid_len;
4962 leave:
4963 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4964 return !ret;
4965}
4966
4967/* Allocate a new QUIC connection with <version> as QUIC version. <ipv4>
4968 * boolean is set to 1 for IPv4 connection, 0 for IPv6. <server> is set to 1
4969 * for QUIC servers (or haproxy listeners).
4970 * <dcid> is the destination connection ID, <scid> is the source connection ID,
4971 * <token> the token found to be used for this connection with <token_len> as
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004972 * length. Endpoints addresses are specified via <local_addr> and <peer_addr>.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004973 * Returns the connection if succeeded, NULL if not.
4974 */
4975static struct quic_conn *qc_new_conn(const struct quic_version *qv, int ipv4,
4976 struct quic_cid *dcid, struct quic_cid *scid,
4977 const struct quic_cid *token_odcid,
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004978 struct sockaddr_storage *local_addr,
4979 struct sockaddr_storage *peer_addr,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004980 int server, int token, void *owner)
4981{
4982 int i;
4983 struct quic_conn *qc;
4984 /* Initial CID. */
4985 struct quic_connection_id *icid;
4986 char *buf_area = NULL;
4987 struct listener *l = NULL;
4988 struct quic_cc_algo *cc_algo = NULL;
4989 struct quic_tls_ctx *ictx;
4990 TRACE_ENTER(QUIC_EV_CONN_INIT);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004991 /* TODO replace pool_zalloc by pool_alloc(). This requires special care
4992 * to properly initialized internal quic_conn members to safely use
4993 * quic_conn_release() on alloc failure.
4994 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004995 qc = pool_zalloc(pool_head_quic_conn);
4996 if (!qc) {
4997 TRACE_ERROR("Could not allocate a new connection", QUIC_EV_CONN_INIT);
4998 goto err;
4999 }
5000
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005001 /* Initialize in priority qc members required for a safe dealloc. */
5002
5003 /* required to use MTLIST_IN_LIST */
5004 MT_LIST_INIT(&qc->accept_list);
5005
5006 LIST_INIT(&qc->rx.pkt_list);
5007
Amaury Denoyelle42448332022-12-12 11:24:05 +01005008 qc_init_fd(qc);
5009
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005010 LIST_INIT(&qc->back_refs);
5011
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005012 /* Now proceeds to allocation of qc members. */
5013
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005014 buf_area = pool_alloc(pool_head_quic_conn_rxbuf);
5015 if (!buf_area) {
5016 TRACE_ERROR("Could not allocate a new RX buffer", QUIC_EV_CONN_INIT, qc);
5017 goto err;
5018 }
5019
5020 qc->cids = EB_ROOT;
5021 /* QUIC Server (or listener). */
5022 if (server) {
5023 struct proxy *prx;
5024
5025 l = owner;
5026 prx = l->bind_conf->frontend;
5027 cc_algo = l->bind_conf->quic_cc_algo;
5028
5029 qc->prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe,
5030 &quic_stats_module);
5031 qc->flags |= QUIC_FL_CONN_LISTENER;
5032 qc->state = QUIC_HS_ST_SERVER_INITIAL;
5033 /* Copy the initial DCID with the address. */
5034 qc->odcid.len = dcid->len;
5035 qc->odcid.addrlen = dcid->addrlen;
5036 memcpy(qc->odcid.data, dcid->data, dcid->len + dcid->addrlen);
5037
5038 /* copy the packet SCID to reuse it as DCID for sending */
5039 if (scid->len)
5040 memcpy(qc->dcid.data, scid->data, scid->len);
5041 qc->dcid.len = scid->len;
5042 qc->tx.buf = BUF_NULL;
5043 qc->li = l;
5044 }
5045 /* QUIC Client (outgoing connection to servers) */
5046 else {
5047 qc->state = QUIC_HS_ST_CLIENT_INITIAL;
5048 if (dcid->len)
5049 memcpy(qc->dcid.data, dcid->data, dcid->len);
5050 qc->dcid.len = dcid->len;
5051 }
5052 qc->mux_state = QC_MUX_NULL;
5053 qc->err = quic_err_transport(QC_ERR_NO_ERROR);
5054
5055 icid = new_quic_cid(&qc->cids, qc, 0);
5056 if (!icid) {
5057 TRACE_ERROR("Could not allocate a new connection ID", QUIC_EV_CONN_INIT, qc);
5058 goto err;
5059 }
5060
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005061 if ((global.tune.options & GTUNE_QUIC_SOCK_PER_CONN) &&
5062 is_addr(local_addr)) {
5063 TRACE_USER("Allocate a socket for QUIC connection", QUIC_EV_CONN_INIT, qc);
5064 qc_alloc_fd(qc, local_addr, peer_addr);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005065
5066 /* haproxy soft-stop is supported only for QUIC connections
5067 * with their owned socket.
5068 */
5069 if (qc_test_fd(qc))
5070 _HA_ATOMIC_INC(&jobs);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005071 }
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005072
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005073 /* insert the allocated CID in the receiver datagram handler tree */
5074 if (server)
5075 ebmb_insert(&quic_dghdlrs[tid].cids, &icid->node, icid->cid.len);
5076
5077 /* Select our SCID which is the first CID with 0 as sequence number. */
5078 qc->scid = icid->cid;
5079
5080 /* Packet number spaces initialization. */
5081 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
5082 quic_pktns_init(&qc->pktns[i]);
5083 /* QUIC encryption level context initialization. */
5084 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5085 if (!quic_conn_enc_level_init(qc, i)) {
5086 TRACE_ERROR("Could not initialize an encryption level", QUIC_EV_CONN_INIT, qc);
5087 goto err;
5088 }
5089 /* Initialize the packet number space. */
5090 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
5091 }
5092
5093 qc->original_version = qv;
5094 qc->tps_tls_ext = (qc->original_version->num & 0xff000000) == 0xff000000 ?
5095 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS_DRAFT:
5096 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS;
5097 /* TX part. */
5098 LIST_INIT(&qc->tx.frms_to_send);
5099 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
5100 qc->tx.wbuf = qc->tx.rbuf = 0;
5101 qc->tx.bytes = 0;
5102 qc->tx.buf = BUF_NULL;
5103 /* RX part. */
5104 qc->rx.bytes = 0;
5105 qc->rx.buf = b_make(buf_area, QUIC_CONN_RX_BUFSZ, 0, 0);
5106 for (i = 0; i < QCS_MAX_TYPES; i++)
5107 qc->rx.strms[i].nb_streams = 0;
5108
5109 qc->nb_pkt_for_cc = 1;
5110 qc->nb_pkt_since_cc = 0;
5111
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005112 if (!quic_tls_ku_init(qc)) {
5113 TRACE_ERROR("Key update initialization failed", QUIC_EV_CONN_INIT, qc);
5114 goto err;
5115 }
5116
5117 /* XXX TO DO: Only one path at this time. */
5118 qc->path = &qc->paths[0];
5119 quic_path_init(qc->path, ipv4, cc_algo ? cc_algo : default_quic_cc_algo, qc);
5120
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005121 qc->streams_by_id = EB_ROOT_UNIQUE;
5122 qc->stream_buf_count = 0;
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005123 memcpy(&qc->local_addr, local_addr, sizeof(qc->local_addr));
5124 memcpy(&qc->peer_addr, peer_addr, sizeof qc->peer_addr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005125
5126 if (server && !qc_lstnr_params_init(qc, &l->bind_conf->quic_params,
5127 icid->stateless_reset_token,
5128 dcid->data, dcid->len,
5129 qc->scid.data, qc->scid.len, token_odcid))
5130 goto err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005131
5132 qc->wait_event.tasklet = tasklet_new();
5133 if (!qc->wait_event.tasklet) {
5134 TRACE_ERROR("tasklet_new() failed", QUIC_EV_CONN_TXPKT);
5135 goto err;
5136 }
5137 qc->wait_event.tasklet->process = quic_conn_io_cb;
5138 qc->wait_event.tasklet->context = qc;
5139 qc->wait_event.events = 0;
5140 /* Set tasklet tid based on the SCID selected by us for this
5141 * connection. The upper layer will also be binded on the same thread.
5142 */
Willy Tarreaueed78262022-12-21 09:09:19 +01005143 qc->tid = quic_get_cid_tid(qc->scid.data, &l->rx);
Willy Tarreauf5a0c8a2022-10-13 16:14:11 +02005144 qc->wait_event.tasklet->tid = qc->tid;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02005145 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005146
5147 if (qc_conn_alloc_ssl_ctx(qc) ||
5148 !quic_conn_init_timer(qc) ||
5149 !quic_conn_init_idle_timer_task(qc))
5150 goto err;
5151
5152 ictx = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
5153 if (!qc_new_isecs(qc, ictx,qc->original_version, dcid->data, dcid->len, 1))
5154 goto err;
5155
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005156 LIST_APPEND(&th_ctx->quic_conns, &qc->el_th_ctx);
5157 qc->qc_epoch = HA_ATOMIC_LOAD(&qc_epoch);
5158
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005159 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc);
5160
5161 return qc;
5162
5163 err:
5164 pool_free(pool_head_quic_conn_rxbuf, buf_area);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005165 if (qc) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005166 qc->rx.buf.area = NULL;
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005167 quic_conn_release(qc);
5168 }
5169 TRACE_LEAVE(QUIC_EV_CONN_INIT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005170 return NULL;
5171}
5172
5173/* Release the quic_conn <qc>. The connection is removed from the CIDs tree.
5174 * The connection tasklet is killed.
5175 *
5176 * This function must only be called by the thread responsible of the quic_conn
5177 * tasklet.
5178 */
5179void quic_conn_release(struct quic_conn *qc)
5180{
5181 int i;
5182 struct ssl_sock_ctx *conn_ctx;
5183 struct eb64_node *node;
5184 struct quic_tls_ctx *app_tls_ctx;
5185 struct quic_rx_packet *pkt, *pktback;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005186 struct bref *bref, *back;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005187
5188 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5189
5190 /* We must not free the quic-conn if the MUX is still allocated. */
5191 BUG_ON(qc->mux_state == QC_MUX_READY);
5192
Amaury Denoyellefb375572023-02-01 09:28:32 +01005193 if (qc_test_fd(qc))
5194 _HA_ATOMIC_DEC(&jobs);
5195
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005196 /* Close quic-conn socket fd. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01005197 qc_release_fd(qc, 0);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005198
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005199 /* in the unlikely (but possible) case the connection was just added to
5200 * the accept_list we must delete it from there.
5201 */
5202 MT_LIST_DELETE(&qc->accept_list);
5203
5204 /* free remaining stream descriptors */
5205 node = eb64_first(&qc->streams_by_id);
5206 while (node) {
5207 struct qc_stream_desc *stream;
5208
5209 stream = eb64_entry(node, struct qc_stream_desc, by_id);
5210 node = eb64_next(node);
5211
5212 /* all streams attached to the quic-conn are released, so
5213 * qc_stream_desc_free will liberate the stream instance.
5214 */
5215 BUG_ON(!stream->release);
5216 qc_stream_desc_free(stream, 1);
5217 }
5218
5219 /* Purge Rx packet list. */
5220 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
5221 LIST_DELETE(&pkt->qc_rx_pkt_list);
5222 pool_free(pool_head_quic_rx_packet, pkt);
5223 }
5224
5225 if (qc->idle_timer_task) {
5226 task_destroy(qc->idle_timer_task);
5227 qc->idle_timer_task = NULL;
5228 }
5229
5230 if (qc->timer_task) {
5231 task_destroy(qc->timer_task);
5232 qc->timer_task = NULL;
5233 }
5234
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005235 if (qc->wait_event.tasklet)
5236 tasklet_free(qc->wait_event.tasklet);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005237
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005238 /* remove the connection from receiver cids trees */
5239 ebmb_delete(&qc->odcid_node);
5240 ebmb_delete(&qc->scid_node);
5241 free_quic_conn_cids(qc);
5242
5243 conn_ctx = qc->xprt_ctx;
5244 if (conn_ctx) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005245 SSL_free(conn_ctx->ssl);
5246 pool_free(pool_head_quic_conn_ctx, conn_ctx);
5247 }
5248
5249 quic_tls_ku_free(qc);
5250 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5251 quic_tls_ctx_secs_free(&qc->els[i].tls_ctx);
5252 quic_conn_enc_level_uninit(qc, &qc->els[i]);
5253 }
5254 quic_tls_ctx_secs_free(&qc->negotiated_ictx);
5255
5256 app_tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
5257 pool_free(pool_head_quic_tls_secret, app_tls_ctx->rx.secret);
5258 pool_free(pool_head_quic_tls_secret, app_tls_ctx->tx.secret);
5259
5260 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++) {
5261 quic_pktns_tx_pkts_release(&qc->pktns[i], qc);
5262 quic_free_arngs(qc, &qc->pktns[i].rx.arngs);
5263 }
5264
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005265 /* Detach CLI context watchers currently dumping this connection.
5266 * Reattach them to the next quic_conn instance.
5267 */
5268 list_for_each_entry_safe(bref, back, &qc->back_refs, users) {
5269 /* Remove watcher from this quic_conn instance. */
5270 LIST_DEL_INIT(&bref->users);
5271
5272 /* Attach it to next instance unless it was the last list element. */
5273 if (qc->el_th_ctx.n != &th_ctx->quic_conns) {
5274 struct quic_conn *next = LIST_NEXT(&qc->el_th_ctx,
5275 struct quic_conn *,
5276 el_th_ctx);
5277 LIST_APPEND(&next->back_refs, &bref->users);
5278 }
5279 bref->ref = qc->el_th_ctx.n;
5280 __ha_barrier_store();
5281 }
5282 /* Remove quic_conn from global ha_thread_ctx list. */
5283 LIST_DELETE(&qc->el_th_ctx);
5284
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005285 pool_free(pool_head_quic_conn_rxbuf, qc->rx.buf.area);
5286 pool_free(pool_head_quic_conn, qc);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005287
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005288 TRACE_PROTO("QUIC conn. freed", QUIC_EV_CONN_FREED, qc);
5289
5290 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5291}
5292
5293/* Initialize the timer task of <qc> QUIC connection.
5294 * Returns 1 if succeeded, 0 if not.
5295 */
5296static int quic_conn_init_timer(struct quic_conn *qc)
5297{
5298 int ret = 0;
5299 /* Attach this task to the same thread ID used for the connection */
5300 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5301
5302 qc->timer_task = task_new_on(qc->tid);
5303 if (!qc->timer_task) {
5304 TRACE_ERROR("timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5305 goto leave;
5306 }
5307
5308 qc->timer = TICK_ETERNITY;
5309 qc->timer_task->process = qc_process_timer;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005310 qc->timer_task->context = qc;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005311
5312 ret = 1;
5313 leave:
5314 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5315 return ret;
5316}
5317
5318/* Rearm the idle timer for <qc> QUIC connection. */
5319static void qc_idle_timer_do_rearm(struct quic_conn *qc)
5320{
5321 unsigned int expire;
5322
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01005323 if (stopping && qc->flags & (QUIC_FL_CONN_CLOSING|QUIC_FL_CONN_DRAINING)) {
5324 TRACE_STATE("executing idle timer immediately on stopping", QUIC_EV_CONN_IDLE_TIMER, qc);
5325 task_wakeup(qc->idle_timer_task, TASK_WOKEN_MSG);
5326 }
5327 else {
5328 expire = QUIC_MAX(3 * quic_pto(qc), qc->max_idle_timeout);
5329 qc->idle_timer_task->expire = tick_add(now_ms, MS_TO_TICKS(expire));
5330 task_queue(qc->idle_timer_task);
5331 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005332}
5333
5334/* Rearm the idle timer for <qc> QUIC connection depending on <read> boolean
5335 * which is set to 1 when receiving a packet , and 0 when sending packet
5336 */
5337static void qc_idle_timer_rearm(struct quic_conn *qc, int read)
5338{
5339 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5340
5341 if (read) {
5342 qc->flags |= QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5343 }
5344 else {
5345 qc->flags &= ~QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5346 }
5347 qc_idle_timer_do_rearm(qc);
5348
5349 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5350}
5351
5352/* The task handling the idle timeout */
5353struct task *qc_idle_timer_task(struct task *t, void *ctx, unsigned int state)
5354{
5355 struct quic_conn *qc = ctx;
5356 struct quic_counters *prx_counters = qc->prx_counters;
5357 unsigned int qc_flags = qc->flags;
5358
5359 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5360
5361 /* Notify the MUX before settings QUIC_FL_CONN_EXP_TIMER or the MUX
5362 * might free the quic-conn too early via quic_close().
5363 */
5364 qc_notify_close(qc);
5365
5366 /* If the MUX is still alive, keep the quic-conn. The MUX is
5367 * responsible to call quic_close to release it.
5368 */
5369 qc->flags |= QUIC_FL_CONN_EXP_TIMER;
5370 if (qc->mux_state != QC_MUX_READY)
5371 quic_conn_release(qc);
5372
5373 /* TODO if the quic-conn cannot be freed because of the MUX, we may at
5374 * least clean some parts of it such as the tasklet.
5375 */
5376
5377 if (!(qc_flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
5378 qc_flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
5379 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
5380 HA_ATOMIC_DEC(&prx_counters->half_open_conn);
5381 }
5382
5383 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5384 return NULL;
5385}
5386
5387/* Initialize the idle timeout task for <qc>.
5388 * Returns 1 if succeeded, 0 if not.
5389 */
5390static int quic_conn_init_idle_timer_task(struct quic_conn *qc)
5391{
5392 int ret = 0;
5393
5394 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5395
5396 qc->idle_timer_task = task_new_here();
5397 if (!qc->idle_timer_task) {
5398 TRACE_ERROR("Idle timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5399 goto leave;
5400 }
5401
5402 qc->idle_timer_task->process = qc_idle_timer_task;
5403 qc->idle_timer_task->context = qc;
5404 qc_idle_timer_rearm(qc, 1);
5405 task_queue(qc->idle_timer_task);
5406
5407 ret = 1;
5408 leave:
5409 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5410 return ret;
5411}
5412
5413/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
5414 * past one byte of this buffer.
5415 */
5416static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
5417 struct quic_rx_packet *pkt)
5418{
5419 int ret = 0;
5420 unsigned char dcid_len, scid_len;
5421
5422 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5423
5424 if (end == *buf) {
5425 TRACE_ERROR("buffer data consumed", QUIC_EV_CONN_RXPKT);
5426 goto leave;
5427 }
5428
5429 /* Destination Connection ID Length */
5430 dcid_len = *(*buf)++;
5431 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
5432 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1) {
5433 TRACE_ERROR("too long DCID", QUIC_EV_CONN_RXPKT);
5434 goto leave;
5435 }
5436
5437 if (dcid_len) {
5438 /* Check that the length of this received DCID matches the CID lengths
5439 * of our implementation for non Initials packets only.
5440 */
5441 if (pkt->type != QUIC_PACKET_TYPE_INITIAL &&
5442 pkt->type != QUIC_PACKET_TYPE_0RTT &&
5443 dcid_len != QUIC_HAP_CID_LEN) {
5444 TRACE_ERROR("wrong DCID length", QUIC_EV_CONN_RXPKT);
5445 goto leave;
5446 }
5447
5448 memcpy(pkt->dcid.data, *buf, dcid_len);
5449 }
5450
5451 pkt->dcid.len = dcid_len;
5452 *buf += dcid_len;
5453
5454 /* Source Connection ID Length */
5455 scid_len = *(*buf)++;
5456 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len) {
5457 TRACE_ERROR("too long SCID", QUIC_EV_CONN_RXPKT);
5458 goto leave;
5459 }
5460
5461 if (scid_len)
5462 memcpy(pkt->scid.data, *buf, scid_len);
5463 pkt->scid.len = scid_len;
5464 *buf += scid_len;
5465
5466 ret = 1;
5467 leave:
5468 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5469 return ret;
5470}
5471
5472/* Insert <pkt> RX packet in its <qel> RX packets tree */
5473static void qc_pkt_insert(struct quic_conn *qc,
5474 struct quic_rx_packet *pkt, struct quic_enc_level *qel)
5475{
5476 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
5477
5478 pkt->pn_node.key = pkt->pn;
5479 quic_rx_packet_refinc(pkt);
5480 eb64_insert(&qel->rx.pkts, &pkt->pn_node);
5481
5482 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5483}
5484
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005485/* Try to remove the header protection of <pkt> QUIC packet with <beg> the
5486 * address of the packet first byte, using the keys from encryption level <el>.
5487 *
5488 * If header protection has been successfully removed, packet data are copied
5489 * into <qc> Rx buffer. If <el> secrets are not yet available, the copy is also
5490 * proceeded, and the packet is inserted into <qc> protected packets tree. In
5491 * both cases, packet can now be considered handled by the <qc> connection.
5492 *
5493 * If header protection cannot be removed due to <el> secrets already
5494 * discarded, no operation is conducted.
5495 *
5496 * Returns 1 on success : packet data is now handled by the connection. On
5497 * error 0 is returned : packet should be dropped by the caller.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005498 */
5499static inline int qc_try_rm_hp(struct quic_conn *qc,
5500 struct quic_rx_packet *pkt,
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005501 unsigned char *beg,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005502 struct quic_enc_level **el)
5503{
5504 int ret = 0;
5505 unsigned char *pn = NULL; /* Packet number field */
5506 enum quic_tls_enc_level tel;
5507 struct quic_enc_level *qel;
5508 /* Only for traces. */
5509 struct quic_rx_packet *qpkt_trace;
5510
5511 qpkt_trace = NULL;
5512 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005513 BUG_ON(!pkt->pn_offset);
5514
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005515 /* The packet number is here. This is also the start minus
5516 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
5517 * protection.
5518 */
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005519 pn = beg + pkt->pn_offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005520
5521 tel = quic_packet_type_enc_level(pkt->type);
5522 qel = &qc->els[tel];
5523
5524 if (qc_qel_may_rm_hp(qc, qel)) {
5525 /* Note that the following function enables us to unprotect the packet
5526 * number and its length subsequently used to decrypt the entire
5527 * packets.
5528 */
5529 if (!qc_do_rm_hp(qc, pkt, &qel->tls_ctx,
5530 qel->pktns->rx.largest_pn, pn, beg)) {
5531 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, qc);
5532 goto out;
5533 }
5534
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005535 /* The AAD includes the packet number field. */
5536 pkt->aad_len = pkt->pn_offset + pkt->pnl;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005537 if (pkt->len - pkt->aad_len < QUIC_TLS_TAG_LEN) {
5538 TRACE_PROTO("Too short packet", QUIC_EV_CONN_TRMHP, qc);
5539 goto out;
5540 }
5541
5542 qpkt_trace = pkt;
5543 }
5544 else {
5545 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
5546 /* If the packet number space has been discarded, this packet
5547 * will be not parsed.
5548 */
5549 TRACE_PROTO("Discarded pktns", QUIC_EV_CONN_TRMHP, qc, pkt);
5550 goto out;
5551 }
5552
5553 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005554 LIST_APPEND(&qel->rx.pqpkts, &pkt->list);
5555 quic_rx_packet_refinc(pkt);
5556 }
5557
5558 *el = qel;
5559 /* No reference counter incrementation here!!! */
5560 LIST_APPEND(&qc->rx.pkt_list, &pkt->qc_rx_pkt_list);
5561 memcpy(b_tail(&qc->rx.buf), beg, pkt->len);
5562 pkt->data = (unsigned char *)b_tail(&qc->rx.buf);
5563 b_add(&qc->rx.buf, pkt->len);
5564
5565 ret = 1;
5566 out:
5567 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc, qpkt_trace);
5568 return ret;
5569}
5570
5571/* Parse the header form from <byte0> first byte of <pkt> packet to set its type.
5572 * Also set <*long_header> to 1 if this form is long, 0 if not and the version
5573 * of this packet into <*version>.
5574 */
5575static inline int qc_parse_hd_form(struct quic_rx_packet *pkt,
5576 unsigned char **buf, const unsigned char *end,
5577 int *long_header, uint32_t *version)
5578{
5579 int ret = 0;
5580 const unsigned char byte0 = **buf;
5581
5582 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5583
5584 (*buf)++;
5585 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
5586 unsigned char type =
5587 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
5588
5589 *long_header = 1;
5590 /* Version */
5591 if (!quic_read_uint32(version, (const unsigned char **)buf, end)) {
5592 TRACE_ERROR("could not read the packet version", QUIC_EV_CONN_RXPKT);
5593 goto out;
5594 }
5595
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +01005596 if (*version != QUIC_PROTOCOL_VERSION_2) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005597 pkt->type = type;
5598 }
5599 else {
5600 switch (type) {
5601 case 0:
5602 pkt->type = QUIC_PACKET_TYPE_RETRY;
5603 break;
5604 case 1:
5605 pkt->type = QUIC_PACKET_TYPE_INITIAL;
5606 break;
5607 case 2:
5608 pkt->type = QUIC_PACKET_TYPE_0RTT;
5609 break;
5610 case 3:
5611 pkt->type = QUIC_PACKET_TYPE_HANDSHAKE;
5612 break;
5613 }
5614 }
5615 }
5616 else {
5617 pkt->type = QUIC_PACKET_TYPE_SHORT;
5618 *long_header = 0;
5619 }
5620
5621 ret = 1;
5622 out:
5623 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5624 return ret;
5625}
5626
5627/* Return the QUIC version (quic_version struct) with <version> as version number
5628 * if supported or NULL if not.
5629 */
5630static inline const struct quic_version *qc_supported_version(uint32_t version)
5631{
5632 int i;
5633
5634 for (i = 0; i < quic_versions_nb; i++)
5635 if (quic_versions[i].num == version)
5636 return &quic_versions[i];
5637
5638 return NULL;
5639}
5640
5641/*
5642 * Send a Version Negotiation packet on response to <pkt> on socket <fd> to
5643 * address <addr>.
5644 * Implementation of RFC9000 6. Version Negotiation
5645 *
5646 * TODO implement a rate-limiting sending of Version Negotiation packets
5647 *
5648 * Returns 0 on success else non-zero
5649 */
5650static int send_version_negotiation(int fd, struct sockaddr_storage *addr,
5651 struct quic_rx_packet *pkt)
5652{
5653 char buf[256];
5654 int ret = 0, i = 0, j;
5655 uint32_t version;
5656 const socklen_t addrlen = get_addr_len(addr);
5657
5658 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5659 /*
5660 * header form
5661 * long header, fixed bit to 0 for Version Negotiation
5662 */
5663 /* TODO: RAND_bytes() should be replaced? */
5664 if (RAND_bytes((unsigned char *)buf, 1) != 1) {
5665 TRACE_ERROR("RAND_bytes() error", QUIC_EV_CONN_TXPKT);
5666 goto out;
5667 }
5668
5669 buf[i++] |= '\x80';
5670 /* null version for Version Negotiation */
5671 buf[i++] = '\x00';
5672 buf[i++] = '\x00';
5673 buf[i++] = '\x00';
5674 buf[i++] = '\x00';
5675
5676 /* source connection id */
5677 buf[i++] = pkt->scid.len;
5678 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5679 i += pkt->scid.len;
5680
5681 /* destination connection id */
5682 buf[i++] = pkt->dcid.len;
5683 memcpy(&buf[i], pkt->dcid.data, pkt->dcid.len);
5684 i += pkt->dcid.len;
5685
5686 /* supported version */
5687 for (j = 0; j < quic_versions_nb; j++) {
5688 version = htonl(quic_versions[j].num);
5689 memcpy(&buf[i], &version, sizeof(version));
5690 i += sizeof(version);
5691 }
5692
5693 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0)
5694 goto out;
5695
5696 ret = 1;
5697 out:
5698 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5699 return !ret;
5700}
5701
5702/* Send a stateless reset packet depending on <pkt> RX packet information
5703 * from <fd> UDP socket to <dst>
5704 * Return 1 if succeeded, 0 if not.
5705 */
5706static int send_stateless_reset(struct listener *l, struct sockaddr_storage *dstaddr,
5707 struct quic_rx_packet *rxpkt)
5708{
5709 int ret = 0, pktlen, rndlen;
5710 unsigned char pkt[64];
5711 const socklen_t addrlen = get_addr_len(dstaddr);
5712 struct proxy *prx;
5713 struct quic_counters *prx_counters;
5714
5715 TRACE_ENTER(QUIC_EV_STATELESS_RST);
5716
5717 prx = l->bind_conf->frontend;
5718 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5719 /* 10.3 Stateless Reset (https://www.rfc-editor.org/rfc/rfc9000.html#section-10.3)
5720 * The resulting minimum size of 21 bytes does not guarantee that a Stateless
5721 * Reset is difficult to distinguish from other packets if the recipient requires
5722 * the use of a connection ID. To achieve that end, the endpoint SHOULD ensure
5723 * that all packets it sends are at least 22 bytes longer than the minimum
5724 * connection ID length that it requests the peer to include in its packets,
5725 * adding PADDING frames as necessary. This ensures that any Stateless Reset
5726 * sent by the peer is indistinguishable from a valid packet sent to the endpoint.
5727 * An endpoint that sends a Stateless Reset in response to a packet that is
5728 * 43 bytes or shorter SHOULD send a Stateless Reset that is one byte shorter
5729 * than the packet it responds to.
5730 */
5731
5732 /* Note that we build at most a 42 bytes QUIC packet to mimic a short packet */
5733 pktlen = rxpkt->len <= 43 ? rxpkt->len - 1 : 0;
5734 pktlen = QUIC_MAX(QUIC_STATELESS_RESET_PACKET_MINLEN, pktlen);
5735 rndlen = pktlen - QUIC_STATELESS_RESET_TOKEN_LEN;
5736
5737 /* Put a header of random bytes */
5738 /* TODO: RAND_bytes() should be replaced */
5739 if (RAND_bytes(pkt, rndlen) != 1) {
5740 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_STATELESS_RST);
5741 goto leave;
5742 }
5743
5744 /* Clear the most significant bit, and set the second one */
5745 *pkt = (*pkt & ~0x80) | 0x40;
5746 if (!quic_stateless_reset_token_cpy(NULL, pkt + rndlen, QUIC_STATELESS_RESET_TOKEN_LEN,
5747 rxpkt->dcid.data, rxpkt->dcid.len))
5748 goto leave;
5749
5750 if (sendto(l->rx.fd, pkt, pktlen, 0, (struct sockaddr *)dstaddr, addrlen) < 0)
5751 goto leave;
5752
5753 ret = 1;
5754 HA_ATOMIC_INC(&prx_counters->stateless_reset_sent);
5755 TRACE_PROTO("stateless reset sent", QUIC_EV_STATELESS_RST, NULL, &rxpkt->dcid);
5756 leave:
5757 TRACE_LEAVE(QUIC_EV_STATELESS_RST);
5758 return ret;
5759}
5760
5761/* QUIC server only function.
5762 * Add AAD to <add> buffer from <cid> connection ID and <addr> socket address.
5763 * This is the responsibility of the caller to check <aad> size is big enough
5764 * to contain these data.
5765 * Return the number of bytes copied to <aad>.
5766 */
5767static int quic_generate_retry_token_aad(unsigned char *aad,
5768 uint32_t version,
5769 const struct quic_cid *cid,
5770 const struct sockaddr_storage *addr)
5771{
5772 unsigned char *p;
5773
5774 p = aad;
5775 memcpy(p, &version, sizeof version);
5776 p += sizeof version;
5777 p += quic_saddr_cpy(p, addr);
5778 memcpy(p, cid->data, cid->len);
5779 p += cid->len;
5780
5781 return p - aad;
5782}
5783
5784/* QUIC server only function.
5785 * Generate the token to be used in Retry packets. The token is written to
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05005786 * <buf> with <len> as length. <odcid> is the original destination connection
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005787 * ID and <dcid> is our side destination connection ID (or client source
5788 * connection ID).
5789 * Returns the length of the encoded token or 0 on error.
5790 */
5791static int quic_generate_retry_token(unsigned char *buf, size_t len,
5792 const uint32_t version,
5793 const struct quic_cid *odcid,
5794 const struct quic_cid *dcid,
5795 struct sockaddr_storage *addr)
5796{
5797 int ret = 0;
5798 unsigned char *p;
5799 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005800 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005801 size_t aadlen;
5802 unsigned char salt[QUIC_RETRY_TOKEN_SALTLEN];
5803 unsigned char key[QUIC_TLS_KEY_LEN];
5804 unsigned char iv[QUIC_TLS_IV_LEN];
5805 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5806 size_t seclen = strlen(global.cluster_secret);
5807 EVP_CIPHER_CTX *ctx = NULL;
5808 const EVP_CIPHER *aead = EVP_aes_128_gcm();
5809 uint32_t timestamp = now_ms;
5810
5811 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5812
5813 /* We copy the odcid into the token, prefixed by its one byte
5814 * length, the format token byte. It is followed by an AEAD TAG, and finally
5815 * the random bytes used to derive the secret to encrypt the token.
5816 */
5817 if (1 + dcid->len + 1 + QUIC_TLS_TAG_LEN + sizeof salt > len)
5818 goto err;
5819
5820 aadlen = quic_generate_retry_token_aad(aad, version, dcid, addr);
5821 /* TODO: RAND_bytes() should be replaced */
5822 if (RAND_bytes(salt, sizeof salt) != 1) {
5823 TRACE_ERROR("RAND_bytes()", QUIC_EV_CONN_TXPKT);
5824 goto err;
5825 }
5826
5827 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5828 salt, sizeof salt, sec, seclen)) {
5829 TRACE_ERROR("quic_tls_derive_retry_token_secret() failed", QUIC_EV_CONN_TXPKT);
5830 goto err;
5831 }
5832
5833 if (!quic_tls_tx_ctx_init(&ctx, aead, key)) {
5834 TRACE_ERROR("quic_tls_tx_ctx_init() failed", QUIC_EV_CONN_TXPKT);
5835 goto err;
5836 }
5837
5838 /* Token build */
5839 p = buf;
5840 *p++ = QUIC_TOKEN_FMT_RETRY,
5841 *p++ = odcid->len;
5842 memcpy(p, odcid->data, odcid->len);
5843 p += odcid->len;
5844 write_u32(p, htonl(timestamp));
5845 p += sizeof timestamp;
5846
5847 /* Do not encrypt the QUIC_TOKEN_FMT_RETRY byte */
5848 if (!quic_tls_encrypt(buf + 1, p - buf - 1, aad, aadlen, ctx, aead, key, iv)) {
5849 TRACE_ERROR("quic_tls_encrypt() failed", QUIC_EV_CONN_TXPKT);
5850 goto err;
5851 }
5852
5853 p += QUIC_TLS_TAG_LEN;
5854 memcpy(p, salt, sizeof salt);
5855 p += sizeof salt;
5856 EVP_CIPHER_CTX_free(ctx);
5857
5858 ret = p - buf;
5859 leave:
5860 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5861 return ret;
5862
5863 err:
5864 if (ctx)
5865 EVP_CIPHER_CTX_free(ctx);
5866 goto leave;
5867}
5868
5869/* QUIC server only function.
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005870 *
5871 * Check the validity of the Retry token from Initial packet <pkt>. <dgram> is
5872 * the UDP datagram containing <pkt> and <l> is the listener instance on which
5873 * it was received. If the token is valid, the ODCID of <qc> QUIC connection
5874 * will be put into <odcid>. <qc> is used to retrieve the QUIC version needed
5875 * to validate the token but it can be NULL : in this case the version will be
5876 * retrieved from the packet.
5877 *
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005878 * Return 1 if succeeded, 0 if not.
5879 */
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005880
5881static int quic_retry_token_check(struct quic_rx_packet *pkt,
5882 struct quic_dgram *dgram,
5883 struct listener *l,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005884 struct quic_conn *qc,
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005885 struct quic_cid *odcid)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005886{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005887 struct proxy *prx;
5888 struct quic_counters *prx_counters;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005889 int ret = 0;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005890 unsigned char *token = pkt->token;
5891 const uint64_t tokenlen = pkt->token_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005892 unsigned char buf[128];
5893 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005894 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005895 size_t aadlen;
5896 const unsigned char *salt;
5897 unsigned char key[QUIC_TLS_KEY_LEN];
5898 unsigned char iv[QUIC_TLS_IV_LEN];
5899 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5900 size_t seclen = strlen(global.cluster_secret);
5901 EVP_CIPHER_CTX *ctx = NULL;
5902 const EVP_CIPHER *aead = EVP_aes_128_gcm();
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005903 const struct quic_version *qv = qc ? qc->original_version :
5904 pkt->version;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005905
5906 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5907
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005908 /* The caller must ensure this. */
5909 BUG_ON(!global.cluster_secret || !pkt->token_len);
5910
5911 prx = l->bind_conf->frontend;
5912 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5913
5914 if (*pkt->token != QUIC_TOKEN_FMT_RETRY) {
5915 /* TODO: New token check */
5916 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
5917 goto leave;
5918 }
5919
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005920 if (sizeof buf < tokenlen) {
5921 TRACE_ERROR("too short buffer", QUIC_EV_CONN_LPKT, qc);
5922 goto err;
5923 }
5924
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005925 aadlen = quic_generate_retry_token_aad(aad, qv->num, &pkt->scid, &dgram->saddr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005926 salt = token + tokenlen - QUIC_RETRY_TOKEN_SALTLEN;
5927 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5928 salt, QUIC_RETRY_TOKEN_SALTLEN, sec, seclen)) {
5929 TRACE_ERROR("Could not derive retry secret", QUIC_EV_CONN_LPKT, qc);
5930 goto err;
5931 }
5932
5933 if (!quic_tls_rx_ctx_init(&ctx, aead, key)) {
5934 TRACE_ERROR("quic_tls_rx_ctx_init() failed", QUIC_EV_CONN_LPKT, qc);
5935 goto err;
5936 }
5937
5938 /* Do not decrypt the QUIC_TOKEN_FMT_RETRY byte */
5939 if (!quic_tls_decrypt2(buf, token + 1, tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, aad, aadlen,
5940 ctx, aead, key, iv)) {
5941 TRACE_ERROR("Could not decrypt retry token", QUIC_EV_CONN_LPKT, qc);
5942 goto err;
5943 }
5944
5945 if (parse_retry_token(qc, buf, buf + tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, odcid)) {
5946 TRACE_ERROR("Error during Initial token parsing", QUIC_EV_CONN_LPKT, qc);
5947 goto err;
5948 }
5949
5950 EVP_CIPHER_CTX_free(ctx);
5951
5952 ret = 1;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005953 HA_ATOMIC_INC(&prx_counters->retry_validated);
5954
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005955 leave:
5956 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5957 return ret;
5958
5959 err:
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005960 HA_ATOMIC_INC(&prx_counters->retry_error);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005961 if (ctx)
5962 EVP_CIPHER_CTX_free(ctx);
5963 goto leave;
5964}
5965
5966/* Generate a Retry packet and send it on <fd> socket to <addr> in response to
5967 * the Initial <pkt> packet.
5968 *
5969 * Returns 0 on success else non-zero.
5970 */
5971static int send_retry(int fd, struct sockaddr_storage *addr,
5972 struct quic_rx_packet *pkt, const struct quic_version *qv)
5973{
5974 int ret = 0;
5975 unsigned char buf[128];
5976 int i = 0, token_len;
5977 const socklen_t addrlen = get_addr_len(addr);
5978 struct quic_cid scid;
5979
5980 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5981
5982 /* long header + fixed bit + packet type QUIC_PACKET_TYPE_RETRY */
5983 buf[i++] = (QUIC_PACKET_LONG_HEADER_BIT | QUIC_PACKET_FIXED_BIT) |
5984 (quic_pkt_type(QUIC_PACKET_TYPE_RETRY, qv->num) << QUIC_PACKET_TYPE_SHIFT);
5985 /* version */
5986 buf[i++] = *((unsigned char *)&qv->num + 3);
5987 buf[i++] = *((unsigned char *)&qv->num + 2);
5988 buf[i++] = *((unsigned char *)&qv->num + 1);
5989 buf[i++] = *(unsigned char *)&qv->num;
5990
5991 /* Use the SCID from <pkt> for Retry DCID. */
5992 buf[i++] = pkt->scid.len;
5993 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5994 i += pkt->scid.len;
5995
5996 /* Generate a new CID to be used as SCID for the Retry packet. */
5997 scid.len = QUIC_HAP_CID_LEN;
5998 /* TODO: RAND_bytes() should be replaced */
5999 if (RAND_bytes(scid.data, scid.len) != 1) {
6000 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT);
6001 goto out;
6002 }
6003
6004 buf[i++] = scid.len;
6005 memcpy(&buf[i], scid.data, scid.len);
6006 i += scid.len;
6007
6008 /* token */
6009 if (!(token_len = quic_generate_retry_token(&buf[i], sizeof(buf) - i, qv->num,
6010 &pkt->dcid, &pkt->scid, addr))) {
6011 TRACE_ERROR("quic_generate_retry_token() failed", QUIC_EV_CONN_TXPKT);
6012 goto out;
6013 }
6014
6015 i += token_len;
6016
6017 /* token integrity tag */
6018 if ((&buf[i] - buf < QUIC_TLS_TAG_LEN) ||
6019 !quic_tls_generate_retry_integrity_tag(pkt->dcid.data,
6020 pkt->dcid.len, buf, i, qv)) {
6021 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
6022 goto out;
6023 }
6024
6025 i += QUIC_TLS_TAG_LEN;
6026
6027 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0) {
6028 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
6029 goto out;
6030 }
6031
6032 ret = 1;
6033 out:
6034 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
6035 return !ret;
6036}
6037
6038/* Retrieve a quic_conn instance from the <pkt> DCID field. If the packet is of
6039 * type INITIAL, the ODCID tree is first used. In this case, <saddr> is
6040 * concatenated to the <pkt> DCID field.
6041 *
6042 * Returns the instance or NULL if not found.
6043 */
6044static struct quic_conn *retrieve_qc_conn_from_cid(struct quic_rx_packet *pkt,
6045 struct listener *l,
6046 struct sockaddr_storage *saddr)
6047{
6048 struct quic_conn *qc = NULL;
6049 struct ebmb_node *node;
6050 struct quic_connection_id *id;
6051 /* set if the quic_conn is found in the second DCID tree */
6052
6053 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
6054
6055 /* Look first into ODCIDs tree for INITIAL/0-RTT packets. */
6056 if (pkt->type == QUIC_PACKET_TYPE_INITIAL ||
6057 pkt->type == QUIC_PACKET_TYPE_0RTT) {
6058 /* DCIDs of first packets coming from multiple clients may have
6059 * the same values. Let's distinguish them by concatenating the
6060 * socket addresses.
6061 */
6062 quic_cid_saddr_cat(&pkt->dcid, saddr);
6063 node = ebmb_lookup(&quic_dghdlrs[tid].odcids, pkt->dcid.data,
6064 pkt->dcid.len + pkt->dcid.addrlen);
6065 if (node) {
6066 qc = ebmb_entry(node, struct quic_conn, odcid_node);
6067 goto end;
6068 }
6069 }
6070
6071 /* Look into DCIDs tree for non-INITIAL/0-RTT packets. This may be used
6072 * also for INITIAL/0-RTT non-first packets with the final DCID in
6073 * used.
6074 */
6075 node = ebmb_lookup(&quic_dghdlrs[tid].cids, pkt->dcid.data, pkt->dcid.len);
6076 if (!node)
6077 goto end;
6078
6079 id = ebmb_entry(node, struct quic_connection_id, node);
6080 qc = id->qc;
6081
6082 /* If found in DCIDs tree, remove the quic_conn from the ODCIDs tree.
6083 * If already done, this is a noop.
6084 */
6085 if (qc)
6086 ebmb_delete(&qc->odcid_node);
6087
6088 end:
6089 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
6090 return qc;
6091}
6092
6093/* Try to allocate the <*ssl> SSL session object for <qc> QUIC connection
6094 * with <ssl_ctx> as SSL context inherited settings. Also set the transport
6095 * parameters of this session.
6096 * This is the responsibility of the caller to check the validity of all the
6097 * pointers passed as parameter to this function.
6098 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <qc->conn> to
6099 * CO_ER_SSL_NO_MEM.
6100 */
6101static int qc_ssl_sess_init(struct quic_conn *qc, SSL_CTX *ssl_ctx, SSL **ssl,
6102 unsigned char *params, size_t params_len)
6103{
6104 int retry, ret = -1;
6105
6106 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6107
6108 retry = 1;
6109 retry:
6110 *ssl = SSL_new(ssl_ctx);
6111 if (!*ssl) {
6112 if (!retry--)
6113 goto err;
6114
6115 pool_gc(NULL);
6116 goto retry;
6117 }
6118
6119 if (!SSL_set_quic_method(*ssl, &ha_quic_method) ||
6120 !SSL_set_ex_data(*ssl, ssl_qc_app_data_index, qc)) {
6121 SSL_free(*ssl);
6122 *ssl = NULL;
6123 if (!retry--)
6124 goto err;
6125
6126 pool_gc(NULL);
6127 goto retry;
6128 }
6129
6130 ret = 0;
6131 leave:
6132 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6133 return ret;
6134
6135 err:
6136 qc->conn->err_code = CO_ER_SSL_NO_MEM;
6137 goto leave;
6138}
6139
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006140/* Allocate the ssl_sock_ctx from connection <qc>. This creates the tasklet
6141 * used to process <qc> received packets. The allocated context is stored in
6142 * <qc.xprt_ctx>.
6143 *
6144 * Returns 0 on success else non-zero.
6145 */
6146static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc)
6147{
6148 int ret = 0;
6149 struct bind_conf *bc = qc->li->bind_conf;
6150 struct ssl_sock_ctx *ctx = NULL;
6151
6152 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6153
6154 ctx = pool_zalloc(pool_head_quic_conn_ctx);
6155 if (!ctx) {
6156 TRACE_ERROR("SSL context allocation failed", QUIC_EV_CONN_TXPKT);
6157 goto err;
6158 }
6159
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006160 ctx->subs = NULL;
6161 ctx->xprt_ctx = NULL;
6162 ctx->qc = qc;
6163
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006164 if (qc_is_listener(qc)) {
6165 if (qc_ssl_sess_init(qc, bc->initial_ctx, &ctx->ssl,
6166 qc->enc_params, qc->enc_params_len) == -1) {
6167 goto err;
6168 }
6169#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
6170 /* Enabling 0-RTT */
6171 if (bc->ssl_conf.early_data)
6172 SSL_set_quic_early_data_enabled(ctx->ssl, 1);
6173#endif
6174
6175 SSL_set_accept_state(ctx->ssl);
6176 }
6177
6178 ctx->xprt = xprt_get(XPRT_QUIC);
6179
6180 /* Store the allocated context in <qc>. */
6181 qc->xprt_ctx = ctx;
6182
6183 ret = 1;
6184 leave:
6185 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6186 return !ret;
6187
6188 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006189 pool_free(pool_head_quic_conn_ctx, ctx);
6190 goto leave;
6191}
6192
6193/* Check that all the bytes between <buf> included and <end> address
6194 * excluded are null. This is the responsibility of the caller to
6195 * check that there is at least one byte between <buf> end <end>.
6196 * Return 1 if this all the bytes are null, 0 if not.
6197 */
6198static inline int quic_padding_check(const unsigned char *buf,
6199 const unsigned char *end)
6200{
6201 while (buf < end && !*buf)
6202 buf++;
6203
6204 return buf == end;
6205}
6206
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006207/* Find the associated connection to the packet <pkt> or create a new one if
6208 * this is an Initial packet. <dgram> is the datagram containing the packet and
6209 * <l> is the listener instance on which it was received.
6210 *
6211 * Returns the quic-conn instance or NULL.
6212 */
6213static struct quic_conn *quic_rx_pkt_retrieve_conn(struct quic_rx_packet *pkt,
6214 struct quic_dgram *dgram,
6215 struct listener *l)
6216{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006217 struct quic_cid token_odcid = { .len = 0 };
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006218 struct quic_conn *qc = NULL;
6219 struct proxy *prx;
6220 struct quic_counters *prx_counters;
6221
6222 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6223
6224 prx = l->bind_conf->frontend;
6225 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6226
6227 qc = retrieve_qc_conn_from_cid(pkt, l, &dgram->saddr);
6228
6229 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6230 BUG_ON(!pkt->version); /* This must not happen. */
6231
6232 if (global.cluster_secret && pkt->token_len) {
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006233 if (!quic_retry_token_check(pkt, dgram, l, qc, &token_odcid))
6234 goto err;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006235 }
6236
6237 if (!qc) {
6238 int ipv4;
6239
6240 if (global.cluster_secret && !pkt->token_len && !(l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) &&
6241 HA_ATOMIC_LOAD(&prx_counters->half_open_conn) >= global.tune.quic_retry_threshold) {
6242 TRACE_PROTO("Initial without token, sending retry",
6243 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6244 if (send_retry(l->rx.fd, &dgram->saddr, pkt, pkt->version)) {
6245 TRACE_ERROR("Error during Retry generation",
6246 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6247 goto out;
6248 }
6249
6250 HA_ATOMIC_INC(&prx_counters->retry_sent);
6251 goto out;
6252 }
6253
6254 /* RFC 9000 7.2. Negotiating Connection IDs:
6255 * When an Initial packet is sent by a client that has not previously
6256 * received an Initial or Retry packet from the server, the client
6257 * populates the Destination Connection ID field with an unpredictable
6258 * value. This Destination Connection ID MUST be at least 8 bytes in length.
6259 */
6260 if (pkt->dcid.len < QUIC_ODCID_MINLEN) {
6261 TRACE_PROTO("dropped packet",
6262 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6263 goto err;
6264 }
6265
6266 pkt->saddr = dgram->saddr;
6267 ipv4 = dgram->saddr.ss_family == AF_INET;
6268
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006269 qc = qc_new_conn(pkt->version, ipv4, &pkt->dcid, &pkt->scid, &token_odcid,
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006270 &dgram->daddr, &pkt->saddr, 1,
6271 !!pkt->token_len, l);
6272 if (qc == NULL)
6273 goto err;
6274
6275 HA_ATOMIC_INC(&prx_counters->half_open_conn);
6276 /* Insert the DCID the QUIC client has chosen (only for listeners) */
6277 ebmb_insert(&quic_dghdlrs[tid].odcids, &qc->odcid_node,
6278 qc->odcid.len + qc->odcid.addrlen);
6279 }
6280 }
6281 else if (!qc) {
6282 TRACE_PROTO("No connection on a non Initial packet", QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6283 if (global.cluster_secret && !send_stateless_reset(l, &dgram->saddr, pkt))
6284 TRACE_ERROR("stateless reset not sent", QUIC_EV_CONN_LPKT, qc);
6285 goto err;
6286 }
6287
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006288 out:
6289 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6290 return qc;
6291
6292 err:
6293 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
6294 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
6295 return NULL;
6296}
6297
Amaury Denoyelle98289692022-10-19 15:37:44 +02006298/* Parse a QUIC packet starting at <buf>. Data won't be read after <end> even
6299 * if the packet is incomplete. This function will populate fields of <pkt>
6300 * instance, most notably its length. <dgram> is the UDP datagram which
6301 * contains the parsed packet. <l> is the listener instance on which it was
6302 * received.
6303 *
6304 * Returns 0 on success else non-zero. Packet length is guaranteed to be set to
6305 * the real packet value or to cover all data between <buf> and <end> : this is
6306 * useful to reject a whole datagram.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006307 */
Amaury Denoyelle98289692022-10-19 15:37:44 +02006308static int quic_rx_pkt_parse(struct quic_rx_packet *pkt,
6309 unsigned char *buf, const unsigned char *end,
6310 struct quic_dgram *dgram, struct listener *l)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006311{
Amaury Denoyelle98289692022-10-19 15:37:44 +02006312 const unsigned char *beg = buf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006313 struct proxy *prx;
6314 struct quic_counters *prx_counters;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006315 int long_header = 0;
Willy Tarreau33a68702022-11-24 09:16:41 +01006316 uint32_t version = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006317 const struct quic_version *qv = NULL;
6318
6319 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6320
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006321 prx = l->bind_conf->frontend;
6322 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6323 /* This ist only to please to traces and distinguish the
6324 * packet with parsed packet number from others.
6325 */
6326 pkt->pn_node.key = (uint64_t)-1;
6327 if (end <= buf) {
6328 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6329 goto drop;
6330 }
6331
6332 /* Fixed bit */
6333 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006334 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
6335 quic_padding_check(buf, end)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006336 /* Some browsers may pad the remaining datagram space with null bytes.
6337 * That is what we called add padding out of QUIC packets. Such
6338 * datagrams must be considered as valid. But we can only consume
6339 * the remaining space.
6340 */
6341 pkt->len = end - buf;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006342 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006343 }
6344
6345 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6346 goto drop;
6347 }
6348
6349 /* Header form */
6350 if (!qc_parse_hd_form(pkt, &buf, end, &long_header, &version)) {
6351 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6352 goto drop;
6353 }
6354
6355 if (long_header) {
6356 uint64_t len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006357
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006358 TRACE_PROTO("long header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006359 if (!quic_packet_read_long_header(&buf, end, pkt)) {
6360 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6361 goto drop;
6362 }
6363
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006364 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6365 * they must have the same DCID.
6366 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006367 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006368 (pkt->dcid.len != dgram->dcid_len ||
6369 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006370 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006371 goto drop;
6372 }
6373
6374 /* Retry of Version Negotiation packets are only sent by servers */
6375 if (pkt->type == QUIC_PACKET_TYPE_RETRY || !version) {
6376 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6377 goto drop;
6378 }
6379
6380 /* RFC9000 6. Version Negotiation */
6381 qv = qc_supported_version(version);
6382 if (!qv) {
6383 /* unsupported version, send Negotiation packet */
6384 if (send_version_negotiation(l->rx.fd, &dgram->saddr, pkt)) {
6385 TRACE_ERROR("VN packet not sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006386 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006387 }
6388
6389 TRACE_PROTO("VN packet sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006390 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006391 }
Amaury Denoyelle0eae5722022-10-17 18:05:18 +02006392 pkt->version = qv;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006393
6394 /* For Initial packets, and for servers (QUIC clients connections),
6395 * there is no Initial connection IDs storage.
6396 */
6397 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6398 uint64_t token_len;
6399
6400 if (!quic_dec_int(&token_len, (const unsigned char **)&buf, end) ||
6401 end - buf < token_len) {
6402 TRACE_PROTO("Packet dropped",
6403 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6404 goto drop;
6405 }
6406
6407 /* TODO Retry should be automatically activated if
6408 * suspect network usage is detected.
6409 */
6410 if (global.cluster_secret && !token_len) {
6411 if (l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) {
6412 TRACE_PROTO("Initial without token, sending retry",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006413 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006414 if (send_retry(l->rx.fd, &dgram->saddr, pkt, qv)) {
6415 TRACE_PROTO("Error during Retry generation",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006416 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006417 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006418 }
6419
6420 HA_ATOMIC_INC(&prx_counters->retry_sent);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006421 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006422 }
6423 }
6424 else if (!global.cluster_secret && token_len) {
6425 /* Impossible case: a token was received without configured
6426 * cluster secret.
6427 */
6428 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT,
6429 NULL, NULL, NULL, qv);
6430 goto drop;
6431 }
6432
6433 pkt->token = buf;
6434 pkt->token_len = token_len;
6435 buf += pkt->token_len;
6436 }
6437 else if (pkt->type != QUIC_PACKET_TYPE_0RTT) {
6438 if (pkt->dcid.len != QUIC_HAP_CID_LEN) {
6439 TRACE_PROTO("Packet dropped",
6440 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6441 goto drop;
6442 }
6443 }
6444
6445 if (!quic_dec_int(&len, (const unsigned char **)&buf, end) ||
6446 end - buf < len) {
6447 TRACE_PROTO("Packet dropped",
6448 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6449 goto drop;
6450 }
6451
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006452 /* Packet Number is stored here. Packet Length totalizes the
6453 * rest of the content.
6454 */
6455 pkt->pn_offset = buf - beg;
6456 pkt->len = pkt->pn_offset + len;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006457
Frédéric Lécaille35218c62023-02-16 11:40:11 +01006458 /* RFC 9000. Initial Datagram Size
6459 *
6460 * A server MUST discard an Initial packet that is carried in a UDP datagram
6461 * with a payload that is smaller than the smallest allowed maximum datagram
6462 * size of 1200 bytes.
6463 */
6464 if (pkt->type == QUIC_PACKET_TYPE_INITIAL &&
6465 dgram->len < QUIC_INITIAL_PACKET_MINLEN) {
6466 TRACE_PROTO("Too short datagram with an Initial packet", QUIC_EV_CONN_LPKT);
6467 HA_ATOMIC_INC(&prx_counters->too_short_initial_dgram);
6468 goto drop;
6469 }
6470
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006471 /* Interrupt parsing after packet length retrieval : this
6472 * ensures that only the packet is dropped but not the whole
6473 * datagram.
6474 */
6475 if (pkt->type == QUIC_PACKET_TYPE_0RTT && !l->bind_conf->ssl_conf.early_data) {
6476 TRACE_PROTO("0-RTT packet not supported", QUIC_EV_CONN_LPKT);
6477 goto drop;
6478 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006479 }
6480 else {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006481 TRACE_PROTO("short header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006482 if (end - buf < QUIC_HAP_CID_LEN) {
6483 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6484 goto drop;
6485 }
6486
6487 memcpy(pkt->dcid.data, buf, QUIC_HAP_CID_LEN);
6488 pkt->dcid.len = QUIC_HAP_CID_LEN;
6489
6490 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6491 * they must have the same DCID.
6492 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006493 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006494 (pkt->dcid.len != dgram->dcid_len ||
6495 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006496 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006497 goto drop;
6498 }
6499
6500 buf += QUIC_HAP_CID_LEN;
6501
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006502 pkt->pn_offset = buf - beg;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006503 /* A short packet is the last one of a UDP datagram. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006504 pkt->len = end - beg;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006505 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006506
Amaury Denoyelle98289692022-10-19 15:37:44 +02006507 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6508 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006509
Amaury Denoyelle98289692022-10-19 15:37:44 +02006510 drop:
6511 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006512 drop_silent:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006513 if (!pkt->len)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006514 pkt->len = end - beg;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006515 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6516 return -1;
6517}
6518
6519/* Check if received packet <pkt> should be drop due to <qc> already in closing
6520 * state. This can be true if a CONNECTION_CLOSE has already been emitted for
6521 * this connection.
6522 *
6523 * Returns false if connection is not in closing state else true. The caller
6524 * should drop the whole datagram in the last case to not mess up <qc>
6525 * CONNECTION_CLOSE rate limit counter.
6526 */
6527static int qc_rx_check_closing(struct quic_conn *qc,
6528 struct quic_rx_packet *pkt)
6529{
6530 if (!(qc->flags & QUIC_FL_CONN_CLOSING))
6531 return 0;
6532
6533 TRACE_STATE("Closing state connection", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6534
6535 /* Check if CONNECTION_CLOSE rate reemission is reached. */
6536 if (++qc->nb_pkt_since_cc >= qc->nb_pkt_for_cc) {
6537 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
6538 qc->nb_pkt_for_cc++;
6539 qc->nb_pkt_since_cc = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006540 }
6541
Amaury Denoyelle98289692022-10-19 15:37:44 +02006542 return 1;
6543}
6544
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006545/* React to a connection migration initiated on <qc> by a client with the new
6546 * path addresses <peer_addr>/<local_addr>.
6547 *
6548 * Returns 0 on success else non-zero.
6549 */
6550static int qc_handle_conn_migration(struct quic_conn *qc,
6551 const struct sockaddr_storage *peer_addr,
6552 const struct sockaddr_storage *local_addr)
6553{
6554 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6555
Frédéric Lécaille6fc86972023-01-12 08:29:23 +01006556 /* RFC 9000. Connection Migration
6557 *
6558 * If the peer sent the disable_active_migration transport parameter,
6559 * an endpoint also MUST NOT send packets (including probing packets;
6560 * see Section 9.1) from a different local address to the address the peer
6561 * used during the handshake, unless the endpoint has acted on a
6562 * preferred_address transport parameter from the peer.
6563 */
6564 if (qc->li->bind_conf->quic_params.disable_active_migration) {
6565 TRACE_ERROR("Active migration was disabled, datagram dropped", QUIC_EV_CONN_LPKT, qc);
6566 goto err;
6567 }
6568
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006569 /* RFC 9000 9. Connection Migration
6570 *
Amaury Denoyelleeb6be982022-11-21 11:14:45 +01006571 * The design of QUIC relies on endpoints retaining a stable address for
6572 * the duration of the handshake. An endpoint MUST NOT initiate
6573 * connection migration before the handshake is confirmed, as defined in
6574 * Section 4.1.2 of [QUIC-TLS].
6575 */
6576 if (qc->state < QUIC_HS_ST_COMPLETE) {
6577 TRACE_STATE("Connection migration during handshake rejected", QUIC_EV_CONN_LPKT, qc);
6578 goto err;
6579 }
6580
6581 /* RFC 9000 9. Connection Migration
6582 *
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006583 * TODO
6584 * An endpoint MUST
6585 * perform path validation (Section 8.2) if it detects any change to a
6586 * peer's address, unless it has previously validated that address.
6587 */
6588
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006589 /* Update quic-conn owned socket if in used.
6590 * TODO try to reuse it instead of closing and opening a new one.
6591 */
6592 if (qc_test_fd(qc)) {
6593 /* TODO try to reuse socket instead of closing it and opening a new one. */
6594 TRACE_STATE("Connection migration detected, allocate a new connection socket", QUIC_EV_CONN_LPKT, qc);
6595 qc_release_fd(qc, 1);
Amaury Denoyellefb375572023-02-01 09:28:32 +01006596 /* TODO need to adjust <jobs> on socket allocation failure. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006597 qc_alloc_fd(qc, local_addr, peer_addr);
6598 }
6599
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006600 qc->local_addr = *local_addr;
6601 qc->peer_addr = *peer_addr;
6602 HA_ATOMIC_INC(&qc->prx_counters->conn_migration_done);
6603
6604 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6605 return 0;
6606
6607 err:
6608 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6609 return 1;
6610}
6611
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006612/* Release the memory for the RX packets which are no more referenced
6613 * and consume their payloads which have been copied to the RX buffer
6614 * for the connection.
6615 * Always succeeds.
6616 */
6617static inline void quic_rx_pkts_del(struct quic_conn *qc)
6618{
6619 struct quic_rx_packet *pkt, *pktback;
6620
6621 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
6622 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006623 "pkt #%lld(type=%d,len=%llu,rawlen=%llu,refcnt=%u) (diff: %zd)",
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006624 (long long)pkt->pn_node.key,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006625 pkt->type, (ull)pkt->len, (ull)pkt->raw_len, pkt->refcnt,
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006626 (unsigned char *)b_head(&qc->rx.buf) - pkt->data);
6627 if (pkt->data != (unsigned char *)b_head(&qc->rx.buf)) {
6628 size_t cdata;
6629
6630 cdata = b_contig_data(&qc->rx.buf, 0);
6631 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006632 "cdata=%llu *b_head()=0x%x", (ull)cdata, *b_head(&qc->rx.buf));
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006633 if (cdata && !*b_head(&qc->rx.buf)) {
6634 /* Consume the remaining data */
6635 b_del(&qc->rx.buf, cdata);
6636 }
6637 break;
6638 }
6639
6640 if (pkt->refcnt)
6641 break;
6642
6643 b_del(&qc->rx.buf, pkt->raw_len);
6644 LIST_DELETE(&pkt->qc_rx_pkt_list);
6645 pool_free(pool_head_quic_rx_packet, pkt);
6646 }
6647
6648 /* In frequent cases the buffer will be emptied at this stage. */
6649 b_realign_if_empty(&qc->rx.buf);
6650}
6651
Amaury Denoyelle98289692022-10-19 15:37:44 +02006652/* Handle a parsed packet <pkt> by the connection <qc>. Data will be copied
6653 * into <qc> receive buffer after header protection removal procedure.
6654 *
6655 * <dgram> must be set to the datagram which contains the QUIC packet. <beg>
6656 * must point to packet buffer first byte.
6657 *
6658 * <tasklist_head> may be non-NULL when the caller treat several datagrams for
6659 * different quic-conn. In this case, each quic-conn tasklet will be appended
6660 * to it in order to be woken up after the current task.
6661 *
6662 * The caller can safely removed the packet data. If packet refcount was not
6663 * incremented by this function, it means that the connection did not handled
6664 * it and it should be freed by the caller.
6665 */
6666static void qc_rx_pkt_handle(struct quic_conn *qc, struct quic_rx_packet *pkt,
6667 struct quic_dgram *dgram, unsigned char *beg,
6668 struct list **tasklist_head)
6669{
6670 const struct quic_version *qv = pkt->version;
6671 struct quic_enc_level *qel = NULL;
6672 size_t b_cspace;
Frédéric Lécaille8f7d2242023-02-15 11:55:21 +01006673 int io_cb_wakeup = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006674
Amaury Denoyelle3f474e62022-11-24 17:15:08 +01006675 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6676
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006677 if (pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST &&
6678 !quic_peer_validated_addr(qc) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006679 qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED) {
6680 TRACE_PROTO("PTO timer must be armed after anti-amplication was reached",
6681 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6682 /* Reset the anti-amplification bit. It will be set again
6683 * when sending the next packet if reached again.
6684 */
6685 qc->flags &= ~QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006686 io_cb_wakeup = 1;
6687 }
6688
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006689 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
6690 TRACE_PROTO("Connection error",
6691 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6692 goto out;
6693 }
6694
6695 pkt->raw_len = pkt->len;
6696 quic_rx_pkts_del(qc);
6697 b_cspace = b_contig_space(&qc->rx.buf);
6698 if (b_cspace < pkt->len) {
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006699 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006700 "bspace=%llu pkt->len=%llu", (ull)b_cspace, (ull)pkt->len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006701 /* Do not consume buf if space not at the end. */
6702 if (b_tail(&qc->rx.buf) + b_cspace < b_wrap(&qc->rx.buf)) {
6703 TRACE_PROTO("Packet dropped",
6704 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006705 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006706 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006707 }
6708
6709 /* Let us consume the remaining contiguous space. */
6710 if (b_cspace) {
6711 b_putchr(&qc->rx.buf, 0x00);
6712 b_cspace--;
6713 }
6714 b_add(&qc->rx.buf, b_cspace);
6715 if (b_contig_space(&qc->rx.buf) < pkt->len) {
6716 TRACE_PROTO("Too big packet",
6717 QUIC_EV_CONN_LPKT, qc, pkt, &pkt->len, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006718 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006719 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006720 }
6721 }
6722
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006723 if (!qc_try_rm_hp(qc, pkt, beg, &qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006724 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6725 goto drop;
6726 }
6727
6728 TRACE_DATA("New packet", QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6729 if (pkt->aad_len)
6730 qc_pkt_insert(qc, pkt, qel);
6731 out:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006732 *tasklist_head = tasklet_wakeup_after(*tasklist_head,
6733 qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006734
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006735 drop_silent:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006736 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006737 return;
6738
6739 drop:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006740 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt);
Frédéric Lécaille75c8ad52023-02-08 16:08:28 +01006741 if (io_cb_wakeup) {
6742 TRACE_DEVEL("needs to wakeup the timer task after the amplification limit was reached",
6743 QUIC_EV_CONN_LPKT, qc);
6744 qc_set_timer(qc);
6745 if (qc->timer_task && tick_isset(qc->timer) && tick_is_lt(qc->timer, now_ms))
6746 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
6747 }
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006748
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006749 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
6750}
6751
6752/* This function builds into <buf> buffer a QUIC long packet header.
6753 * Return 1 if enough room to build this header, 0 if not.
6754 */
6755static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
6756 int type, size_t pn_len,
6757 struct quic_conn *qc, const struct quic_version *ver)
6758{
6759 int ret = 0;
6760
6761 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6762
6763 if (end - *buf < sizeof ver->num + qc->dcid.len + qc->scid.len + 3) {
6764 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6765 goto leave;
6766 }
6767
6768 type = quic_pkt_type(type, ver->num);
6769 /* #0 byte flags */
6770 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
6771 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
6772 /* Version */
6773 quic_write_uint32(buf, end, ver->num);
6774 *(*buf)++ = qc->dcid.len;
6775 /* Destination connection ID */
6776 if (qc->dcid.len) {
6777 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6778 *buf += qc->dcid.len;
6779 }
6780 /* Source connection ID */
6781 *(*buf)++ = qc->scid.len;
6782 if (qc->scid.len) {
6783 memcpy(*buf, qc->scid.data, qc->scid.len);
6784 *buf += qc->scid.len;
6785 }
6786
6787 ret = 1;
6788 leave:
6789 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6790 return ret;
6791}
6792
6793/* This function builds into <buf> buffer a QUIC short packet header.
6794 * Return 1 if enough room to build this header, 0 if not.
6795 */
6796static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
6797 size_t pn_len, struct quic_conn *qc,
6798 unsigned char tls_flags)
6799{
6800 int ret = 0;
6801
6802 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6803
6804 if (end - *buf < 1 + qc->dcid.len) {
6805 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6806 goto leave;
6807 }
6808
6809 /* #0 byte flags */
6810 *(*buf)++ = QUIC_PACKET_FIXED_BIT |
6811 ((tls_flags & QUIC_FL_TLS_KP_BIT_SET) ? QUIC_PACKET_KEY_PHASE_BIT : 0) | (pn_len - 1);
6812 /* Destination connection ID */
6813 if (qc->dcid.len) {
6814 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6815 *buf += qc->dcid.len;
6816 }
6817
6818 ret = 1;
6819 leave:
6820 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6821 return ret;
6822}
6823
6824/* Apply QUIC header protection to the packet with <buf> as first byte address,
6825 * <pn> as address of the Packet number field, <pnlen> being this field length
6826 * with <aead> as AEAD cipher and <key> as secret key.
6827 * Returns 1 if succeeded or 0 if failed.
6828 */
6829static int quic_apply_header_protection(struct quic_conn *qc, unsigned char *buf,
6830 unsigned char *pn, size_t pnlen,
6831 struct quic_tls_ctx *tls_ctx)
6832
6833{
6834 int i, ret = 0;
6835 /* We need an IV of at least 5 bytes: one byte for bytes #0
6836 * and at most 4 bytes for the packet number
6837 */
6838 unsigned char mask[5] = {0};
6839 EVP_CIPHER_CTX *aes_ctx = tls_ctx->tx.hp_ctx;
6840
6841 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6842
6843 if (!quic_tls_aes_encrypt(mask, pn + QUIC_PACKET_PN_MAXLEN, sizeof mask, aes_ctx)) {
6844 TRACE_ERROR("could not apply header protection", QUIC_EV_CONN_TXPKT, qc);
6845 goto out;
6846 }
6847
6848 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
6849 for (i = 0; i < pnlen; i++)
6850 pn[i] ^= mask[i + 1];
6851
6852 ret = 1;
6853 out:
6854 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6855 return ret;
6856}
6857
6858/* Reduce the encoded size of <ack_frm> ACK frame removing the last
6859 * ACK ranges if needed to a value below <limit> in bytes.
6860 * Return 1 if succeeded, 0 if not.
6861 */
6862static int quic_ack_frm_reduce_sz(struct quic_conn *qc,
6863 struct quic_frame *ack_frm, size_t limit)
6864{
6865 size_t room, ack_delay_sz;
6866 int ret = 0;
6867
6868 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6869
6870 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
6871 /* A frame is made of 1 byte for the frame type. */
6872 room = limit - ack_delay_sz - 1;
6873 if (!quic_rm_last_ack_ranges(qc, ack_frm->tx_ack.arngs, room))
6874 goto leave;
6875
6876 ret = 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
6877 leave:
6878 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6879 return ret;
6880}
6881
6882/* Prepare into <outlist> as most as possible ack-eliciting frame from their
6883 * <inlist> prebuilt frames for <qel> encryption level to be encoded in a buffer
6884 * with <room> as available room, and <*len> the packet Length field initialized
6885 * with the number of bytes already present in this buffer which must be taken
6886 * into an account for the Length packet field value. <headlen> is the number of
6887 * bytes already present in this packet before building frames.
6888 *
6889 * Update consequently <*len> to reflect the size of these frames built
6890 * by this function. Also attach these frames to <l> frame list.
6891 * Return 1 if at least one ack-eleciting frame could be built, 0 if not.
6892 */
6893static inline int qc_build_frms(struct list *outlist, struct list *inlist,
6894 size_t room, size_t *len, size_t headlen,
6895 struct quic_enc_level *qel,
6896 struct quic_conn *qc)
6897{
6898 int ret;
6899 struct quic_frame *cf, *cfbak;
6900
6901 TRACE_ENTER(QUIC_EV_CONN_BCFRMS, qc);
6902
6903 ret = 0;
6904 if (*len > room)
6905 goto leave;
6906
6907 /* If we are not probing we must take into an account the congestion
6908 * control window.
6909 */
6910 if (!qel->pktns->tx.pto_probe) {
6911 size_t remain = quic_path_prep_data(qc->path);
6912
6913 if (headlen > remain)
6914 goto leave;
6915
6916 room = QUIC_MIN(room, remain - headlen);
6917 }
6918
6919 TRACE_PROTO("************** frames build (headlen)",
6920 QUIC_EV_CONN_BCFRMS, qc, &headlen);
6921
6922 /* NOTE: switch/case block inside a loop, a successful status must be
6923 * returned by this function only if at least one frame could be built
6924 * in the switch/case block.
6925 */
6926 list_for_each_entry_safe(cf, cfbak, inlist, list) {
6927 /* header length, data length, frame length. */
6928 size_t hlen, dlen, dlen_sz, avail_room, flen;
6929
6930 if (!room)
6931 break;
6932
6933 switch (cf->type) {
6934 case QUIC_FT_CRYPTO:
6935 TRACE_DEVEL(" New CRYPTO frame build (room, len)",
6936 QUIC_EV_CONN_BCFRMS, qc, &room, len);
6937 /* Compute the length of this CRYPTO frame header */
6938 hlen = 1 + quic_int_getsize(cf->crypto.offset);
6939 /* Compute the data length of this CRyPTO frame. */
6940 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
6941 TRACE_DEVEL(" CRYPTO data length (hlen, crypto.len, dlen)",
6942 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->crypto.len, &dlen);
6943 if (!dlen)
6944 continue;
6945
6946 /* CRYPTO frame length. */
6947 flen = hlen + quic_int_getsize(dlen) + dlen;
6948 TRACE_DEVEL(" CRYPTO frame length (flen)",
6949 QUIC_EV_CONN_BCFRMS, qc, &flen);
6950 /* Add the CRYPTO data length and its encoded length to the packet
6951 * length and the length of this length.
6952 */
6953 *len += flen;
6954 room -= flen;
6955 if (dlen == cf->crypto.len) {
6956 /* <cf> CRYPTO data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01006957 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006958 LIST_APPEND(outlist, &cf->list);
6959 }
6960 else {
6961 struct quic_frame *new_cf;
6962
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01006963 new_cf = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006964 if (!new_cf) {
6965 TRACE_ERROR("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, qc);
6966 continue;
6967 }
6968
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006969 new_cf->crypto.len = dlen;
6970 new_cf->crypto.offset = cf->crypto.offset;
6971 new_cf->crypto.qel = qel;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006972 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006973 if (cf->origin) {
6974 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
6975 /* This <cf> frame was duplicated */
6976 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
6977 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01006978 /* Detach the remaining CRYPTO frame from its original frame */
6979 LIST_DEL_INIT(&cf->ref);
6980 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006981 }
6982 LIST_APPEND(outlist, &new_cf->list);
6983 /* Consume <dlen> bytes of the current frame. */
6984 cf->crypto.len -= dlen;
6985 cf->crypto.offset += dlen;
6986 }
6987 break;
6988
6989 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
6990 if (cf->flags & QUIC_FL_TX_FRAME_LOST) {
6991 struct eb64_node *node = NULL;
6992 struct qc_stream_desc *stream_desc = NULL;
6993 struct quic_stream *strm = &cf->stream;
6994
6995 /* As this frame has been already lost, ensure the stream is always
6996 * available or the range of this frame is not consumed before
6997 * resending it.
6998 */
6999 node = eb64_lookup(&qc->streams_by_id, strm->id);
7000 if (!node) {
7001 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007002 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007003 continue;
7004 }
7005
7006 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
7007 if (strm->offset.key + strm->len <= stream_desc->ack_offset) {
7008 TRACE_DEVEL("ignored frame frame in already acked range",
7009 QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007010 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007011 continue;
7012 }
7013 else if (strm->offset.key < stream_desc->ack_offset) {
7014 strm->offset.key = stream_desc->ack_offset;
7015 TRACE_DEVEL("updated partially acked frame",
7016 QUIC_EV_CONN_PRSAFRM, qc, cf);
7017 }
7018 }
7019 /* Note that these frames are accepted in short packets only without
7020 * "Length" packet field. Here, <*len> is used only to compute the
7021 * sum of the lengths of the already built frames for this packet.
7022 *
7023 * Compute the length of this STREAM frame "header" made a all the field
7024 * excepting the variable ones. Note that +1 is for the type of this frame.
7025 */
7026 hlen = 1 + quic_int_getsize(cf->stream.id) +
7027 ((cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT) ? quic_int_getsize(cf->stream.offset.key) : 0);
7028 /* Compute the data length of this STREAM frame. */
7029 avail_room = room - hlen - *len;
7030 if ((ssize_t)avail_room <= 0)
7031 continue;
7032
7033 TRACE_DEVEL(" New STREAM frame build (room, len)",
7034 QUIC_EV_CONN_BCFRMS, qc, &room, len);
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007035
7036 /* hlen contains STREAM id and offset. Ensure there is
7037 * enough room for length field.
7038 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007039 if (cf->type & QUIC_STREAM_FRAME_TYPE_LEN_BIT) {
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007040 dlen = QUIC_MIN((uint64_t)max_available_room(avail_room, &dlen_sz),
7041 cf->stream.len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007042 dlen_sz = quic_int_getsize(dlen);
7043 flen = hlen + dlen_sz + dlen;
7044 }
7045 else {
7046 dlen = QUIC_MIN((uint64_t)avail_room, cf->stream.len);
7047 flen = hlen + dlen;
7048 }
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007049
7050 if (cf->stream.len && !dlen) {
7051 /* Only a small gap is left on buffer, not
7052 * enough to encode the STREAM data length.
7053 */
7054 continue;
7055 }
7056
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007057 TRACE_DEVEL(" STREAM data length (hlen, stream.len, dlen)",
7058 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->stream.len, &dlen);
7059 TRACE_DEVEL(" STREAM frame length (flen)",
7060 QUIC_EV_CONN_BCFRMS, qc, &flen);
7061 /* Add the STREAM data length and its encoded length to the packet
7062 * length and the length of this length.
7063 */
7064 *len += flen;
7065 room -= flen;
7066 if (dlen == cf->stream.len) {
7067 /* <cf> STREAM data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007068 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007069 LIST_APPEND(outlist, &cf->list);
7070
7071 /* Do not notify MUX on retransmission. */
7072 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7073 qcc_streams_sent_done(cf->stream.stream->ctx,
7074 cf->stream.len,
7075 cf->stream.offset.key);
7076 }
7077 }
7078 else {
7079 struct quic_frame *new_cf;
7080 struct buffer cf_buf;
7081
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01007082 new_cf = qc_frm_alloc(cf->type);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007083 if (!new_cf) {
7084 TRACE_ERROR("No memory for new STREAM frame", QUIC_EV_CONN_BCFRMS, qc);
7085 continue;
7086 }
7087
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007088 new_cf->stream.stream = cf->stream.stream;
7089 new_cf->stream.buf = cf->stream.buf;
7090 new_cf->stream.id = cf->stream.id;
Amaury Denoyelle1dac0182023-02-02 16:45:07 +01007091 new_cf->stream.offset = cf->stream.offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007092 new_cf->stream.len = dlen;
7093 new_cf->type |= QUIC_STREAM_FRAME_TYPE_LEN_BIT;
7094 /* FIN bit reset */
7095 new_cf->type &= ~QUIC_STREAM_FRAME_TYPE_FIN_BIT;
7096 new_cf->stream.data = cf->stream.data;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05007097 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007098 if (cf->origin) {
7099 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
7100 /* This <cf> frame was duplicated */
7101 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
7102 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01007103 /* Detach this STREAM frame from its origin */
7104 LIST_DEL_INIT(&cf->ref);
7105 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007106 }
7107 LIST_APPEND(outlist, &new_cf->list);
7108 cf->type |= QUIC_STREAM_FRAME_TYPE_OFF_BIT;
7109 /* Consume <dlen> bytes of the current frame. */
7110 cf_buf = b_make(b_orig(cf->stream.buf),
7111 b_size(cf->stream.buf),
7112 (char *)cf->stream.data - b_orig(cf->stream.buf), 0);
7113 cf->stream.len -= dlen;
7114 cf->stream.offset.key += dlen;
7115 cf->stream.data = (unsigned char *)b_peek(&cf_buf, dlen);
7116
7117 /* Do not notify MUX on retransmission. */
7118 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7119 qcc_streams_sent_done(new_cf->stream.stream->ctx,
7120 new_cf->stream.len,
7121 new_cf->stream.offset.key);
7122 }
7123 }
7124
7125 /* TODO the MUX is notified about the frame sending via
7126 * previous qcc_streams_sent_done call. However, the
7127 * sending can fail later, for example if the sendto
7128 * system call returns an error. As the MUX has been
7129 * notified, the transport layer is responsible to
7130 * bufferize and resent the announced data later.
7131 */
7132
7133 break;
7134
7135 default:
7136 flen = qc_frm_len(cf);
7137 BUG_ON(!flen);
7138 if (flen > room)
7139 continue;
7140
7141 *len += flen;
7142 room -= flen;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007143 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007144 LIST_APPEND(outlist, &cf->list);
7145 break;
7146 }
7147
7148 /* Successful status as soon as a frame could be built */
7149 ret = 1;
7150 }
7151
7152 leave:
7153 TRACE_LEAVE(QUIC_EV_CONN_BCFRMS, qc);
7154 return ret;
7155}
7156
7157/* Generate a CONNECTION_CLOSE frame for <qc> on <qel> encryption level. <out>
7158 * is used as return parameter and should be zero'ed by the caller.
7159 */
7160static void qc_build_cc_frm(struct quic_conn *qc, struct quic_enc_level *qel,
7161 struct quic_frame *out)
7162{
7163 /* TODO improve CONNECTION_CLOSE on Initial/Handshake encryption levels
7164 *
7165 * A CONNECTION_CLOSE frame should be sent in several packets with
7166 * different encryption levels depending on the client context. This is
7167 * to ensure that the client can decrypt it. See RFC 9000 10.2.3 for
7168 * more details on how to implement it.
7169 */
7170 TRACE_ENTER(QUIC_EV_CONN_BFRM, qc);
7171
7172
7173 if (qc->err.app) {
7174 if (unlikely(qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
7175 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
7176 /* RFC 9000 10.2.3. Immediate Close during the Handshake
7177 *
7178 * Sending a CONNECTION_CLOSE of type 0x1d in an Initial or Handshake
7179 * packet could expose application state or be used to alter application
7180 * state. A CONNECTION_CLOSE of type 0x1d MUST be replaced by a
7181 * CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or
7182 * Handshake packets. Otherwise, information about the application
7183 * state might be revealed. Endpoints MUST clear the value of the
7184 * Reason Phrase field and SHOULD use the APPLICATION_ERROR code when
7185 * converting to a CONNECTION_CLOSE of type 0x1c.
7186 */
7187 out->type = QUIC_FT_CONNECTION_CLOSE;
7188 out->connection_close.error_code = QC_ERR_APPLICATION_ERROR;
7189 out->connection_close.reason_phrase_len = 0;
7190 }
7191 else {
7192 out->type = QUIC_FT_CONNECTION_CLOSE_APP;
7193 out->connection_close.error_code = qc->err.code;
7194 }
7195 }
7196 else {
7197 out->type = QUIC_FT_CONNECTION_CLOSE;
7198 out->connection_close.error_code = qc->err.code;
7199 }
7200 TRACE_LEAVE(QUIC_EV_CONN_BFRM, qc);
7201
7202}
7203
7204/* This function builds a clear packet from <pkt> information (its type)
7205 * into a buffer with <pos> as position pointer and <qel> as QUIC TLS encryption
7206 * level for <conn> QUIC connection and <qel> as QUIC TLS encryption level,
7207 * filling the buffer with as much frames as possible from <frms> list of
7208 * prebuilt frames.
7209 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
7210 * reserved so that to ensure there is enough room to build this AEAD TAG after
7211 * having returned from this function.
7212 * This function also updates the value of <buf_pn> pointer to point to the packet
7213 * number field in this packet. <pn_len> will also have the packet number
7214 * length as value.
7215 *
7216 * Return 1 if succeeded (enough room to buile this packet), O if not.
7217 */
7218static int qc_do_build_pkt(unsigned char *pos, const unsigned char *end,
7219 size_t dglen, struct quic_tx_packet *pkt,
7220 int64_t pn, size_t *pn_len, unsigned char **buf_pn,
7221 int force_ack, int padding, int cc, int probe,
7222 struct quic_enc_level *qel, struct quic_conn *qc,
7223 const struct quic_version *ver, struct list *frms)
7224{
7225 unsigned char *beg, *payload;
7226 size_t len, len_sz, len_frms, padding_len;
7227 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
7228 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
7229 struct quic_frame cc_frm = { };
7230 size_t ack_frm_len, head_len;
7231 int64_t rx_largest_acked_pn;
7232 int add_ping_frm;
7233 struct list frm_list = LIST_HEAD_INIT(frm_list);
7234 struct quic_frame *cf;
7235 int must_ack, ret = 0;
7236 int nb_aepkts_since_last_ack;
7237
7238 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7239
7240 /* Length field value with CRYPTO frames if present. */
7241 len_frms = 0;
7242 beg = pos;
7243 /* When not probing, and no immediate close is required, reduce the size of this
7244 * buffer to respect the congestion controller window.
7245 * This size will be limited if we have ack-eliciting frames to send from <frms>.
7246 */
7247 if (!probe && !LIST_ISEMPTY(frms) && !cc) {
7248 size_t path_room;
7249
7250 path_room = quic_path_prep_data(qc->path);
7251 if (end - beg > path_room)
7252 end = beg + path_room;
7253 }
7254
7255 /* Ensure there is enough room for the TLS encryption tag and a zero token
7256 * length field if any.
7257 */
7258 if (end - pos < QUIC_TLS_TAG_LEN +
7259 (pkt->type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0))
7260 goto no_room;
7261
7262 end -= QUIC_TLS_TAG_LEN;
7263 rx_largest_acked_pn = qel->pktns->rx.largest_acked_pn;
7264 /* packet number length */
7265 *pn_len = quic_packet_number_length(pn, rx_largest_acked_pn);
7266 /* Build the header */
7267 if ((pkt->type == QUIC_PACKET_TYPE_SHORT &&
7268 !quic_build_packet_short_header(&pos, end, *pn_len, qc, qel->tls_ctx.flags)) ||
7269 (pkt->type != QUIC_PACKET_TYPE_SHORT &&
7270 !quic_build_packet_long_header(&pos, end, pkt->type, *pn_len, qc, ver)))
7271 goto no_room;
7272
7273 /* Encode the token length (0) for an Initial packet. */
7274 if (pkt->type == QUIC_PACKET_TYPE_INITIAL)
7275 *pos++ = 0;
7276 head_len = pos - beg;
7277 /* Build an ACK frame if required. */
7278 ack_frm_len = 0;
7279 nb_aepkts_since_last_ack = qel->pktns->rx.nb_aepkts_since_last_ack;
7280 must_ack = !qel->pktns->tx.pto_probe &&
7281 (force_ack || ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
7282 (LIST_ISEMPTY(frms) || nb_aepkts_since_last_ack >= QUIC_MAX_RX_AEPKTS_SINCE_LAST_ACK)));
7283 if (must_ack) {
7284 struct quic_arngs *arngs = &qel->pktns->rx.arngs;
7285 BUG_ON(eb_is_empty(&qel->pktns->rx.arngs.root));
7286 ack_frm.tx_ack.arngs = arngs;
7287 if (qel->pktns->flags & QUIC_FL_PKTNS_NEW_LARGEST_PN) {
7288 qel->pktns->tx.ack_delay =
7289 quic_compute_ack_delay_us(qel->pktns->rx.largest_time_received, qc);
7290 qel->pktns->flags &= ~QUIC_FL_PKTNS_NEW_LARGEST_PN;
7291 }
7292 ack_frm.tx_ack.ack_delay = qel->pktns->tx.ack_delay;
7293 /* XXX BE CAREFUL XXX : here we reserved at least one byte for the
7294 * smallest frame (PING) and <*pn_len> more for the packet number. Note
7295 * that from here, we do not know if we will have to send a PING frame.
7296 * This will be decided after having computed the ack-eliciting frames
7297 * to be added to this packet.
7298 */
7299 ack_frm_len = quic_ack_frm_reduce_sz(qc, &ack_frm, end - 1 - *pn_len - pos);
7300 if (!ack_frm_len)
7301 goto no_room;
7302 }
7303
7304 /* Length field value without the ack-eliciting frames. */
7305 len = ack_frm_len + *pn_len;
7306 len_frms = 0;
7307 if (!cc && !LIST_ISEMPTY(frms)) {
7308 ssize_t room = end - pos;
7309
7310 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7311 /* Initialize the length of the frames built below to <len>.
7312 * If any frame could be successfully built by qc_build_frms(),
7313 * we will have len_frms > len.
7314 */
7315 len_frms = len;
7316 if (!qc_build_frms(&frm_list, frms,
7317 end - pos, &len_frms, pos - beg, qel, qc)) {
7318 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7319 qc, NULL, NULL, &room);
7320 if (!ack_frm_len && !qel->pktns->tx.pto_probe)
7321 goto no_room;
7322 }
7323 }
7324
7325 /* Length (of the remaining data). Must not fail because, the buffer size
7326 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
7327 * for the encryption tag. It must be taken into an account for the length
7328 * of this packet.
7329 */
7330 if (len_frms)
7331 len = len_frms + QUIC_TLS_TAG_LEN;
7332 else
7333 len += QUIC_TLS_TAG_LEN;
7334 /* CONNECTION_CLOSE frame */
7335 if (cc) {
7336 qc_build_cc_frm(qc, qel, &cc_frm);
7337 len += qc_frm_len(&cc_frm);
7338 }
7339 add_ping_frm = 0;
7340 padding_len = 0;
7341 len_sz = quic_int_getsize(len);
7342 /* Add this packet size to <dglen> */
7343 dglen += head_len + len_sz + len;
7344 if (padding && dglen < QUIC_INITIAL_PACKET_MINLEN) {
7345 /* This is a maximum padding size */
7346 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7347 /* The length field value is of this packet is <len> + <padding_len>
7348 * the size of which may be greater than the initial computed size
7349 * <len_sz>. So, let's deduce the difference between these to packet
7350 * sizes from <padding_len>.
7351 */
7352 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7353 len += padding_len;
7354 }
Frédéric Lécaille5faf5772023-02-16 17:30:53 +01007355 else if (len_frms && len_frms < QUIC_PACKET_PN_MAXLEN) {
7356 len += padding_len = QUIC_PACKET_PN_MAXLEN - len_frms;
7357 }
7358 else if (LIST_ISEMPTY(&frm_list)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007359 if (qel->pktns->tx.pto_probe) {
7360 /* If we cannot send a frame, we send a PING frame. */
7361 add_ping_frm = 1;
7362 len += 1;
7363 }
7364 /* If there is no frame at all to follow, add at least a PADDING frame. */
7365 if (!ack_frm_len && !cc)
7366 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
7367 }
7368
7369 if (pkt->type != QUIC_PACKET_TYPE_SHORT && !quic_enc_int(&pos, end, len))
7370 goto no_room;
7371
7372 /* Packet number field address. */
7373 *buf_pn = pos;
7374
7375 /* Packet number encoding. */
7376 if (!quic_packet_number_encode(&pos, end, pn, *pn_len))
7377 goto no_room;
7378
7379 /* payload building (ack-eliciting or not frames) */
7380 payload = pos;
7381 if (ack_frm_len) {
7382 if (!qc_build_frm(&pos, end, &ack_frm, pkt, qc))
7383 goto no_room;
7384
7385 pkt->largest_acked_pn = quic_pktns_get_largest_acked_pn(qel->pktns);
7386 pkt->flags |= QUIC_FL_TX_PACKET_ACK;
7387 }
7388
7389 /* Ack-eliciting frames */
7390 if (!LIST_ISEMPTY(&frm_list)) {
7391 struct quic_frame *tmp_cf;
7392 list_for_each_entry_safe(cf, tmp_cf, &frm_list, list) {
7393 if (!qc_build_frm(&pos, end, cf, pkt, qc)) {
7394 ssize_t room = end - pos;
7395 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7396 qc, NULL, NULL, &room);
7397 /* Note that <cf> was added from <frms> to <frm_list> list by
7398 * qc_build_frms().
7399 */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007400 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007401 LIST_INSERT(frms, &cf->list);
7402 continue;
7403 }
7404
7405 quic_tx_packet_refinc(pkt);
7406 cf->pkt = pkt;
7407 }
7408 }
7409
7410 /* Build a PING frame if needed. */
7411 if (add_ping_frm) {
7412 frm.type = QUIC_FT_PING;
7413 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7414 goto no_room;
7415 }
7416
7417 /* Build a CONNECTION_CLOSE frame if needed. */
7418 if (cc) {
7419 if (!qc_build_frm(&pos, end, &cc_frm, pkt, qc))
7420 goto no_room;
7421
7422 pkt->flags |= QUIC_FL_TX_PACKET_CC;
7423 }
7424
7425 /* Build a PADDING frame if needed. */
7426 if (padding_len) {
7427 frm.type = QUIC_FT_PADDING;
7428 frm.padding.len = padding_len;
7429 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7430 goto no_room;
7431 }
7432
7433 if (pos == payload) {
7434 /* No payload was built because of congestion control */
7435 TRACE_DEVEL("limited by congestion control", QUIC_EV_CONN_TXPKT, qc);
7436 goto no_room;
7437 }
7438
7439 /* If this packet is ack-eliciting and we are probing let's
7440 * decrement the PTO probe counter.
7441 */
7442 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING &&
7443 qel->pktns->tx.pto_probe)
7444 qel->pktns->tx.pto_probe--;
7445
7446 pkt->len = pos - beg;
7447 LIST_SPLICE(&pkt->frms, &frm_list);
7448
7449 ret = 1;
7450 TRACE_DEVEL("Packet ack-eliciting frames", QUIC_EV_CONN_TXPKT, qc, pkt);
7451 leave:
7452 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7453 return ret;
7454
7455 no_room:
7456 /* Replace the pre-built frames which could not be add to this packet */
7457 LIST_SPLICE(frms, &frm_list);
7458 TRACE_DEVEL("Remaining ack-eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7459 goto leave;
7460}
7461
7462static inline void quic_tx_packet_init(struct quic_tx_packet *pkt, int type)
7463{
7464 pkt->type = type;
7465 pkt->len = 0;
7466 pkt->in_flight_len = 0;
7467 pkt->pn_node.key = (uint64_t)-1;
7468 LIST_INIT(&pkt->frms);
7469 pkt->time_sent = TICK_ETERNITY;
7470 pkt->next = NULL;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01007471 pkt->prev = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007472 pkt->largest_acked_pn = -1;
7473 pkt->flags = 0;
7474 pkt->refcnt = 0;
7475}
7476
7477/* Build a packet into <buf> packet buffer with <pkt_type> as packet
7478 * type for <qc> QUIC connection from <qel> encryption level from <frms> list
7479 * of prebuilt frames.
7480 *
7481 * Return -2 if the packet could not be allocated or encrypted for any reason,
7482 * -1 if there was not enough room to build a packet.
7483 * XXX NOTE XXX
7484 * If you provide provide qc_build_pkt() with a big enough buffer to build a packet as big as
7485 * possible (to fill an MTU), the unique reason why this function may fail is the congestion
7486 * control window limitation.
7487 */
7488static struct quic_tx_packet *qc_build_pkt(unsigned char **pos,
7489 const unsigned char *buf_end,
7490 struct quic_enc_level *qel,
7491 struct quic_tls_ctx *tls_ctx, struct list *frms,
7492 struct quic_conn *qc, const struct quic_version *ver,
7493 size_t dglen, int pkt_type, int force_ack,
7494 int padding, int probe, int cc, int *err)
7495{
7496 struct quic_tx_packet *ret_pkt = NULL;
7497 /* The pointer to the packet number field. */
7498 unsigned char *buf_pn;
7499 unsigned char *beg, *end, *payload;
7500 int64_t pn;
7501 size_t pn_len, payload_len, aad_len;
7502 struct quic_tx_packet *pkt;
7503
7504 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc, NULL, qel);
7505 *err = 0;
7506 pkt = pool_alloc(pool_head_quic_tx_packet);
7507 if (!pkt) {
7508 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_TXPKT, qc);
7509 *err = -2;
7510 goto err;
7511 }
7512
7513 quic_tx_packet_init(pkt, pkt_type);
7514 beg = *pos;
7515 pn_len = 0;
7516 buf_pn = NULL;
7517
7518 pn = qel->pktns->tx.next_pn + 1;
7519 if (!qc_do_build_pkt(*pos, buf_end, dglen, pkt, pn, &pn_len, &buf_pn,
7520 force_ack, padding, cc, probe, qel, qc, ver, frms)) {
7521 // trace already emitted by function above
7522 *err = -1;
7523 goto err;
7524 }
7525
7526 end = beg + pkt->len;
7527 payload = buf_pn + pn_len;
7528 payload_len = end - payload;
7529 aad_len = payload - beg;
7530
7531 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc)) {
7532 // trace already emitted by function above
7533 *err = -2;
7534 goto err;
7535 }
7536
7537 end += QUIC_TLS_TAG_LEN;
7538 pkt->len += QUIC_TLS_TAG_LEN;
7539 if (!quic_apply_header_protection(qc, beg, buf_pn, pn_len, tls_ctx)) {
7540 // trace already emitted by function above
7541 *err = -2;
7542 goto err;
7543 }
7544
7545 /* Consume a packet number */
7546 qel->pktns->tx.next_pn++;
7547 qc->tx.prep_bytes += pkt->len;
7548 if (qc->tx.prep_bytes >= 3 * qc->rx.bytes && !quic_peer_validated_addr(qc)) {
7549 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
7550 TRACE_PROTO("anti-amplification limit reached", QUIC_EV_CONN_TXPKT, qc);
7551 }
7552 /* Now that a correct packet is built, let us consume <*pos> buffer. */
7553 *pos = end;
7554 /* Attach the built packet to its tree. */
7555 pkt->pn_node.key = pn;
7556 /* Set the packet in fligth length for in flight packet only. */
7557 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
7558 pkt->in_flight_len = pkt->len;
7559 qc->path->prep_in_flight += pkt->len;
7560 }
7561 /* Always reset this flags */
7562 qc->flags &= ~QUIC_FL_CONN_IMMEDIATE_CLOSE;
7563 if (pkt->flags & QUIC_FL_TX_PACKET_ACK) {
7564 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
7565 qel->pktns->rx.nb_aepkts_since_last_ack = 0;
7566 }
7567
7568 pkt->pktns = qel->pktns;
7569
7570 ret_pkt = pkt;
7571 leave:
7572 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc, ret_pkt);
7573 return ret_pkt;
7574
7575 err:
7576 /* TODO: what about the frames which have been built
7577 * for this packet.
7578 */
7579 free_quic_tx_packet(qc, pkt);
7580 goto leave;
7581}
7582
7583
7584static void __quic_conn_init(void)
7585{
7586 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
7587}
7588INITCALL0(STG_REGISTER, __quic_conn_init);
7589
7590static void __quic_conn_deinit(void)
7591{
7592 BIO_meth_free(ha_quic_meth);
7593}
7594REGISTER_POST_DEINIT(__quic_conn_deinit);
7595
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007596/* Handle a new <dgram> received. Parse each QUIC packets and copied their
7597 * content to a quic-conn instance. The datagram content can be released after
7598 * this function.
7599 *
7600 * If datagram has been received on a quic-conn owned FD, <from_qc> must be set
7601 * to the connection instance. <li> is the attached listener. The caller is
7602 * responsible to ensure that the first packet is destined to this connection
7603 * by comparing CIDs.
7604 *
7605 * If datagram has been received on a receiver FD, <from_qc> will be NULL. This
7606 * function will thus retrieve the connection from the CID tree or allocate a
7607 * new one if possible. <li> is the listener attached to the receiver.
7608 *
7609 * Returns 0 on success else non-zero. If an error happens, some packets from
7610 * the datagram may not have been parsed.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007611 */
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007612int quic_dgram_parse(struct quic_dgram *dgram, struct quic_conn *from_qc,
7613 struct listener *li)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007614{
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007615 struct quic_rx_packet *pkt;
7616 struct quic_conn *qc = NULL;
7617 unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007618 struct list *tasklist_head = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007619
7620 TRACE_ENTER(QUIC_EV_CONN_LPKT);
7621
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007622 pos = dgram->buf;
7623 end = pos + dgram->len;
7624 do {
7625 /* TODO replace zalloc -> alloc. */
7626 pkt = pool_zalloc(pool_head_quic_rx_packet);
7627 if (!pkt) {
7628 TRACE_ERROR("RX packet allocation failed", QUIC_EV_CONN_LPKT);
7629 goto err;
7630 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007631
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007632 pkt->version = NULL;
7633 pkt->pn_offset = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007634
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007635 /* Set flag if pkt is the first one in dgram. */
7636 if (pos == dgram->buf)
7637 pkt->flags |= QUIC_FL_RX_PACKET_DGRAM_FIRST;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007638
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007639 LIST_INIT(&pkt->qc_rx_pkt_list);
7640 pkt->time_received = now_ms;
7641 quic_rx_packet_refinc(pkt);
7642 if (quic_rx_pkt_parse(pkt, pos, end, dgram, li))
7643 goto next;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007644
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007645 /* Search quic-conn instance for first packet of the datagram.
7646 * quic_rx_packet_parse() is responsible to discard packets
7647 * with different DCID as the first one in the same datagram.
7648 */
7649 if (!qc) {
7650 qc = from_qc ? from_qc : quic_rx_pkt_retrieve_conn(pkt, dgram, li);
7651 /* qc is NULL if receiving a non Initial packet for an
7652 * unknown connection.
7653 */
7654 if (!qc) {
Amaury Denoyelle98289692022-10-19 15:37:44 +02007655 /* Skip the entire datagram. */
7656 pkt->len = end - pos;
7657 goto next;
7658 }
7659
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007660 dgram->qc = qc;
7661 }
Amaury Denoyelle98289692022-10-19 15:37:44 +02007662
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007663 if (qc_rx_check_closing(qc, pkt)) {
7664 /* Skip the entire datagram. */
7665 pkt->len = end - pos;
7666 goto next;
7667 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007668
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007669 /* Detect QUIC connection migration. */
Frédéric Lécaillef6769542023-01-12 10:36:26 +01007670 if (ipcmp(&qc->peer_addr, &dgram->saddr, 1)) {
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007671 if (qc_handle_conn_migration(qc, &dgram->saddr, &dgram->daddr)) {
7672 /* Skip the entire datagram. */
7673 TRACE_ERROR("error during connection migration, datagram dropped", QUIC_EV_CONN_LPKT, qc);
7674 pkt->len = end - pos;
7675 goto next;
7676 }
7677 }
7678
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007679 qc_rx_pkt_handle(qc, pkt, dgram, pos, &tasklist_head);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007680
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007681 next:
7682 pos += pkt->len;
7683 quic_rx_packet_refdec(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007684
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007685 /* Free rejected packets */
7686 if (!pkt->refcnt) {
7687 BUG_ON(LIST_INLIST(&pkt->qc_rx_pkt_list));
7688 pool_free(pool_head_quic_rx_packet, pkt);
7689 }
7690 } while (pos < end);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007691
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007692 /* Increasing the received bytes counter by the UDP datagram length
7693 * if this datagram could be associated to a connection.
7694 */
7695 if (dgram->qc)
7696 dgram->qc->rx.bytes += dgram->len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007697
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007698 /* This must never happen. */
7699 BUG_ON(pos > end);
7700 BUG_ON(pos < end || pos > dgram->buf + dgram->len);
7701 /* Mark this datagram as consumed */
7702 HA_ATOMIC_STORE(&dgram->buf, NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007703
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007704 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
7705 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007706
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007707 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007708 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007709 return -1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007710}
7711
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01007712/* Check if connection ID <dcid> of length <dcid_len> belongs to <qc> local
7713 * CIDs. This can be used to determine if a datagram is addressed to the right
7714 * connection instance.
7715 *
7716 * Returns a boolean value.
7717 */
7718int qc_check_dcid(struct quic_conn *qc, unsigned char *dcid, size_t dcid_len)
7719{
7720 struct ebmb_node *node;
7721 struct quic_connection_id *id;
7722
7723 /* For ODCID, address is concatenated to it after qc.odcid.len so this
7724 * comparison is safe.
7725 */
7726 if ((qc->scid.len == dcid_len &&
7727 memcmp(qc->scid.data, dcid, dcid_len) == 0) ||
7728 (qc->odcid.len == dcid_len &&
Frédéric Lécaille07846cb2023-02-13 16:14:24 +01007729 memcmp(qc->odcid.data, dcid, dcid_len) == 0)) {
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01007730 return 1;
7731 }
7732
7733 node = ebmb_lookup(&quic_dghdlrs[tid].cids, dcid, dcid_len);
7734 if (node) {
7735 id = ebmb_entry(node, struct quic_connection_id, node);
7736 if (qc == id->qc)
7737 return 1;
7738 }
7739
7740 return 0;
7741}
7742
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007743/* Retrieve the DCID from a QUIC datagram or packet with <buf> as first octet.
7744 * Returns 1 if succeeded, 0 if not.
7745 */
7746int quic_get_dgram_dcid(unsigned char *buf, const unsigned char *end,
7747 unsigned char **dcid, size_t *dcid_len)
7748{
7749 int ret = 0, long_header;
7750 size_t minlen, skip;
7751
7752 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
7753
7754 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
7755 TRACE_PROTO("fixed bit not set", QUIC_EV_CONN_RXPKT);
7756 goto err;
7757 }
7758
7759 long_header = *buf & QUIC_PACKET_LONG_HEADER_BIT;
7760 minlen = long_header ? QUIC_LONG_PACKET_MINLEN :
7761 QUIC_SHORT_PACKET_MINLEN + QUIC_HAP_CID_LEN + QUIC_TLS_TAG_LEN;
7762 skip = long_header ? QUIC_LONG_PACKET_DCID_OFF : QUIC_SHORT_PACKET_DCID_OFF;
7763 if (end - buf < minlen)
7764 goto err;
7765
7766 buf += skip;
7767 *dcid_len = long_header ? *buf++ : QUIC_HAP_CID_LEN;
7768 if (*dcid_len > QUIC_CID_MAXLEN || end - buf <= *dcid_len)
7769 goto err;
7770
7771 *dcid = buf;
7772
7773 ret = 1;
7774 leave:
7775 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
7776 return ret;
7777
7778 err:
7779 TRACE_PROTO("wrong datagram", QUIC_EV_CONN_RXPKT);
7780 goto leave;
7781}
7782
7783/* Notify the MUX layer if alive about an imminent close of <qc>. */
7784void qc_notify_close(struct quic_conn *qc)
7785{
7786 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
7787
7788 if (qc->flags & QUIC_FL_CONN_NOTIFY_CLOSE)
7789 goto leave;
7790
7791 qc->flags |= QUIC_FL_CONN_NOTIFY_CLOSE;
7792 /* wake up the MUX */
7793 if (qc->mux_state == QC_MUX_READY && qc->conn->mux->wake) {
7794 TRACE_STATE("connection closure notidfied to mux",
7795 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7796 qc->conn->mux->wake(qc->conn);
7797 }
7798 else
7799 TRACE_STATE("connection closure not notidfied to mux",
7800 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7801 leave:
7802 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
7803}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007804
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01007805/* Wake-up upper layer if waiting for send to be ready.
7806 *
7807 * Returns 1 if upper layer has been woken up else 0.
7808 */
7809int qc_notify_send(struct quic_conn *qc)
7810{
7811 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
7812 if (quic_path_prep_data(qc->path)) {
7813 tasklet_wakeup(qc->subs->tasklet);
7814 qc->subs->events &= ~SUB_RETRY_SEND;
7815 if (!qc->subs->events)
7816 qc->subs = NULL;
7817
7818 return 1;
7819 }
7820 }
7821
7822 return 0;
7823}
7824
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007825
7826/* appctx context used by "show quic" command */
7827struct show_quic_ctx {
7828 unsigned int epoch;
7829 struct bref bref; /* back-reference to the quic-conn being dumped */
7830 unsigned int thr;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007831 int flags;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007832};
7833
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007834#define QC_CLI_FL_SHOW_ALL 0x1 /* show closing/draining connections */
7835
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007836static int cli_parse_show_quic(char **args, char *payload, struct appctx *appctx, void *private)
7837{
7838 struct show_quic_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7839
7840 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
7841 return 1;
7842
7843 ctx->epoch = _HA_ATOMIC_FETCH_ADD(&qc_epoch, 1);
7844 ctx->thr = 0;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007845 ctx->flags = 0;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007846
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01007847 if (*args[2] && strcmp(args[2], "all") == 0)
7848 ctx->flags |= QC_CLI_FL_SHOW_ALL;
7849
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007850 LIST_INIT(&ctx->bref.users);
7851
7852 return 0;
7853}
7854
7855static int cli_io_handler_dump_quic(struct appctx *appctx)
7856{
7857 struct show_quic_ctx *ctx = appctx->svcctx;
7858 struct stconn *sc = appctx_sc(appctx);
7859 struct quic_conn *qc;
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01007860 struct quic_enc_level *qel;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007861 struct eb64_node *node;
7862 struct qc_stream_desc *stream;
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01007863 char bufaddr[INET6_ADDRSTRLEN], bufport[6];
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01007864 int expire;
7865 unsigned char cid_len;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007866
7867 thread_isolate();
7868
7869 if (ctx->thr >= global.nbthread)
7870 goto done;
7871
7872 if (unlikely(sc_ic(sc)->flags & CF_SHUTW)) {
7873 /* If we're forced to shut down, we might have to remove our
7874 * reference to the last stream being dumped.
7875 */
7876 if (!LIST_ISEMPTY(&ctx->bref.users))
7877 LIST_DEL_INIT(&ctx->bref.users);
7878 goto done;
7879 }
7880
7881 chunk_reset(&trash);
7882
7883 if (!LIST_ISEMPTY(&ctx->bref.users)) {
7884 /* Remove show_quic_ctx from previous quic_conn instance. */
7885 LIST_DEL_INIT(&ctx->bref.users);
7886 }
7887 else if (!ctx->bref.ref) {
7888 /* First invocation. */
7889 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
7890 }
7891
7892 while (1) {
7893 int done = 0;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007894 int i;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007895
7896 if (ctx->bref.ref == &ha_thread_ctx[ctx->thr].quic_conns) {
7897 done = 1;
7898 }
7899 else {
7900 qc = LIST_ELEM(ctx->bref.ref, struct quic_conn *, el_th_ctx);
7901 if ((int)(qc->qc_epoch - ctx->epoch) > 0)
7902 done = 1;
7903 }
7904
7905 if (done) {
7906 ++ctx->thr;
7907 if (ctx->thr >= global.nbthread)
7908 break;
7909 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
7910 continue;
7911 }
7912
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01007913 if (!(ctx->flags & QC_CLI_FL_SHOW_ALL) &&
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007914 qc->flags & (QUIC_FL_CONN_CLOSING|QUIC_FL_CONN_DRAINING)) {
7915 ctx->bref.ref = qc->el_th_ctx.n;
7916 continue;
7917 }
7918
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01007919 /* CIDs */
7920 chunk_appendf(&trash, "* %p[%02u]: scid=", qc, qc->tid);
7921 for (cid_len = 0; cid_len < qc->scid.len; ++cid_len)
7922 chunk_appendf(&trash, "%02x", qc->scid.data[cid_len]);
7923 while (cid_len++ < 20)
7924 chunk_appendf(&trash, "..");
7925
7926 chunk_appendf(&trash, " dcid=");
7927 for (cid_len = 0; cid_len < qc->dcid.len; ++cid_len)
7928 chunk_appendf(&trash, "%02x", qc->dcid.data[cid_len]);
7929 while (cid_len++ < 20)
7930 chunk_appendf(&trash, "..");
7931
7932 chunk_appendf(&trash, "\n");
7933
7934 /* Connection state */
7935 if (qc->flags & QUIC_FL_CONN_CLOSING)
7936 chunk_appendf(&trash, " st=closing ");
7937 else if (qc->flags & QUIC_FL_CONN_DRAINING)
7938 chunk_appendf(&trash, " st=draining ");
7939 else if (qc->state < QUIC_HS_ST_CONFIRMED)
7940 chunk_appendf(&trash, " st=handshake ");
7941 else
7942 chunk_appendf(&trash, " st=opened ");
7943
7944 if (qc->mux_state == QC_MUX_NULL)
7945 chunk_appendf(&trash, "mux=null ");
7946 else if (qc->mux_state == QC_MUX_READY)
7947 chunk_appendf(&trash, "mux=ready ");
7948 else
7949 chunk_appendf(&trash, "mux=released ");
7950
7951 expire = qc->idle_timer_task->expire;
7952 chunk_appendf(&trash, "expire=%02ds ",
7953 expire > now_ms ? (expire - now_ms) / 1000 : 0);
7954
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007955 chunk_appendf(&trash, "\n");
7956
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01007957 /* Socket */
7958 chunk_appendf(&trash, " fd=%d", qc->fd);
7959 if (qc->local_addr.ss_family == AF_INET ||
7960 qc->local_addr.ss_family == AF_INET6) {
7961 addr_to_str(&qc->local_addr, bufaddr, sizeof(bufaddr));
7962 port_to_str(&qc->local_addr, bufport, sizeof(bufport));
7963 chunk_appendf(&trash, " from=%s:%s", bufaddr, bufport);
7964
7965 addr_to_str(&qc->peer_addr, bufaddr, sizeof(bufaddr));
7966 port_to_str(&qc->peer_addr, bufport, sizeof(bufport));
7967 chunk_appendf(&trash, " to=%s:%s", bufaddr, bufport);
7968 }
7969
7970 chunk_appendf(&trash, "\n");
7971
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01007972 /* Encryption levels */
7973 qel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
7974 chunk_appendf(&trash, " [initl] rx.ackrng=%-6zu tx.inflight=%-6zu",
7975 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7976 qel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
7977 chunk_appendf(&trash, " [hndshk] rx.ackrng=%-6zu tx.inflight=%-6zu\n",
7978 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7979 qel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
7980 chunk_appendf(&trash, " [0-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
7981 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7982 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
7983 chunk_appendf(&trash, " [1-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
7984 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7985
7986 chunk_appendf(&trash, "\n");
7987
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007988 /* Streams */
7989 node = eb64_first(&qc->streams_by_id);
7990 i = 0;
7991 while (node) {
7992 stream = eb64_entry(node, struct qc_stream_desc, by_id);
7993 node = eb64_next(node);
7994
Amaury Denoyellea9de25a2023-02-10 09:25:22 +01007995 chunk_appendf(&trash, " | stream=%-8llu", (unsigned long long)stream->by_id.key);
7996 chunk_appendf(&trash, " off=%-8llu ack=%-8llu",
7997 (unsigned long long)stream->buf_offset,
7998 (unsigned long long)stream->ack_offset);
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007999
8000 if (!(++i % 3)) {
8001 chunk_appendf(&trash, "\n");
8002 i = 0;
8003 }
8004 }
8005
8006 chunk_appendf(&trash, "\n");
8007
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008008 if (applet_putchk(appctx, &trash) == -1) {
8009 /* Register show_quic_ctx to quic_conn instance. */
8010 LIST_APPEND(&qc->back_refs, &ctx->bref.users);
8011 goto full;
8012 }
8013
8014 ctx->bref.ref = qc->el_th_ctx.n;
8015 }
8016
8017 done:
8018 thread_release();
8019 return 1;
8020
8021 full:
8022 thread_release();
8023 return 0;
8024}
8025
8026static void cli_release_show_quic(struct appctx *appctx)
8027{
8028 struct show_quic_ctx *ctx = appctx->svcctx;
8029
8030 if (ctx->thr < global.nbthread) {
8031 thread_isolate();
8032 if (!LIST_ISEMPTY(&ctx->bref.users))
8033 LIST_DEL_INIT(&ctx->bref.users);
8034 thread_release();
8035 }
8036}
8037
8038static struct cli_kw_list cli_kws = {{ }, {
8039 { { "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 +01008040 {{},}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008041}};
8042
8043INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
8044
8045static void init_quic()
8046{
8047 int thr;
8048
8049 for (thr = 0; thr < MAX_THREADS; ++thr)
8050 LIST_INIT(&ha_thread_ctx[thr].quic_conns);
8051}
8052INITCALL0(STG_INIT, init_quic);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008053
8054/*
8055 * Local variables:
8056 * c-indent-level: 8
8057 * c-basic-offset: 8
8058 * End:
8059 */