blob: 3de0d90054dfde2c0437cec77f1c6a9317510d7e [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
18#include <errno.h>
19#include <stdio.h>
20#include <stdlib.h>
21
22#include <sys/socket.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25
26#include <netinet/tcp.h>
27
28#include <import/ebmbtree.h>
29
30#include <haproxy/buf-t.h>
31#include <haproxy/compat.h>
32#include <haproxy/api.h>
33#include <haproxy/debug.h>
34#include <haproxy/tools.h>
35#include <haproxy/ticks.h>
36
Amaury Denoyelle15c74702023-02-01 10:18:26 +010037#include <haproxy/applet-t.h>
38#include <haproxy/cli.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020039#include <haproxy/connection.h>
40#include <haproxy/fd.h>
41#include <haproxy/freq_ctr.h>
42#include <haproxy/global.h>
43#include <haproxy/h3.h>
44#include <haproxy/hq_interop.h>
45#include <haproxy/log.h>
46#include <haproxy/mux_quic.h>
47#include <haproxy/ncbuf.h>
48#include <haproxy/pipe.h>
49#include <haproxy/proxy.h>
50#include <haproxy/quic_cc.h>
51#include <haproxy/quic_frame.h>
52#include <haproxy/quic_enc.h>
53#include <haproxy/quic_loss.h>
54#include <haproxy/quic_sock.h>
55#include <haproxy/quic_stats.h>
56#include <haproxy/quic_stream.h>
57#include <haproxy/quic_tp.h>
58#include <haproxy/cbuf.h>
59#include <haproxy/proto_quic.h>
60#include <haproxy/quic_tls.h>
61#include <haproxy/ssl_sock.h>
62#include <haproxy/task.h>
Amaury Denoyelle15c74702023-02-01 10:18:26 +010063#include <haproxy/thread.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020064#include <haproxy/trace.h>
65
Amaury Denoyelle15c74702023-02-01 10:18:26 +010066/* incremented by each "show quic". */
67static unsigned int qc_epoch = 0;
68
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020069/* list of supported QUIC versions by this implementation */
70const struct quic_version quic_versions[] = {
71 {
72 .num = QUIC_PROTOCOL_VERSION_DRAFT_29,
73 .initial_salt = initial_salt_draft_29,
74 .initial_salt_len = sizeof initial_salt_draft_29,
75 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V1,
76 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V1) - 1,
77 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V1,
78 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V1) - 1,
79 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V1,
80 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V1) - 1,
81 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V1,
82 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V1) - 1,
83 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_DRAFT,
84 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_DRAFT,
85 },
86 {
87 .num = QUIC_PROTOCOL_VERSION_1,
88 .initial_salt = initial_salt_v1,
89 .initial_salt_len = sizeof initial_salt_v1,
90 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V1,
91 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V1) - 1,
92 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V1,
93 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V1) - 1,
94 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V1,
95 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V1) - 1,
96 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V1,
97 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V1) - 1,
98 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V1,
99 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V1,
100 },
101 {
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +0100102 .num = QUIC_PROTOCOL_VERSION_2,
103 .initial_salt = initial_salt_v2,
104 .initial_salt_len = sizeof initial_salt_v2,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200105 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V2,
106 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V2) - 1,
107 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V2,
108 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V2) - 1,
109 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V2,
110 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V2) - 1,
111 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V2,
112 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V2) - 1,
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +0100113 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V2,
114 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V2,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200115 },
116};
117
118/* The total number of supported versions */
119const size_t quic_versions_nb = sizeof quic_versions / sizeof *quic_versions;
120/* Listener only preferred version */
121const struct quic_version *preferred_version;
122
123/* trace source and events */
124static void quic_trace(enum trace_level level, uint64_t mask, \
125 const struct trace_source *src,
126 const struct ist where, const struct ist func,
127 const void *a1, const void *a2, const void *a3, const void *a4);
128
129static const struct trace_event quic_trace_events[] = {
130 { .mask = QUIC_EV_CONN_NEW, .name = "new_conn", .desc = "new QUIC connection" },
131 { .mask = QUIC_EV_CONN_INIT, .name = "new_conn_init", .desc = "new QUIC connection initialization" },
132 { .mask = QUIC_EV_CONN_ISEC, .name = "init_secs", .desc = "initial secrets derivation" },
133 { .mask = QUIC_EV_CONN_RSEC, .name = "read_secs", .desc = "read secrets derivation" },
134 { .mask = QUIC_EV_CONN_WSEC, .name = "write_secs", .desc = "write secrets derivation" },
135 { .mask = QUIC_EV_CONN_LPKT, .name = "lstnr_packet", .desc = "new listener received packet" },
136 { .mask = QUIC_EV_CONN_SPKT, .name = "srv_packet", .desc = "new server received packet" },
137 { .mask = QUIC_EV_CONN_ENCPKT, .name = "enc_hdshk_pkt", .desc = "handhshake packet encryption" },
138 { .mask = QUIC_EV_CONN_TXPKT, .name = "tx_pkt", .desc = "TX packet" },
139 { .mask = QUIC_EV_CONN_PAPKT, .name = "phdshk_apkt", .desc = "post handhshake application packet preparation" },
140 { .mask = QUIC_EV_CONN_PAPKTS, .name = "phdshk_apkts", .desc = "post handhshake application packets preparation" },
141 { .mask = QUIC_EV_CONN_IO_CB, .name = "qc_io_cb", .desc = "QUIC conn. I/O processing" },
142 { .mask = QUIC_EV_CONN_RMHP, .name = "rm_hp", .desc = "Remove header protection" },
143 { .mask = QUIC_EV_CONN_PRSHPKT, .name = "parse_hpkt", .desc = "parse handshake packet" },
144 { .mask = QUIC_EV_CONN_PRSAPKT, .name = "parse_apkt", .desc = "parse application packet" },
145 { .mask = QUIC_EV_CONN_PRSFRM, .name = "parse_frm", .desc = "parse frame" },
146 { .mask = QUIC_EV_CONN_PRSAFRM, .name = "parse_ack_frm", .desc = "parse ACK frame" },
147 { .mask = QUIC_EV_CONN_BFRM, .name = "build_frm", .desc = "build frame" },
148 { .mask = QUIC_EV_CONN_PHPKTS, .name = "phdshk_pkts", .desc = "handhshake packets preparation" },
149 { .mask = QUIC_EV_CONN_TRMHP, .name = "rm_hp_try", .desc = "header protection removing try" },
150 { .mask = QUIC_EV_CONN_ELRMHP, .name = "el_rm_hp", .desc = "handshake enc. level header protection removing" },
151 { .mask = QUIC_EV_CONN_RXPKT, .name = "rx_pkt", .desc = "RX packet" },
152 { .mask = QUIC_EV_CONN_SSLDATA, .name = "ssl_provide_data", .desc = "CRYPTO data provision to TLS stack" },
153 { .mask = QUIC_EV_CONN_RXCDATA, .name = "el_treat_rx_cfrms",.desc = "enc. level RX CRYPTO frames processing"},
154 { .mask = QUIC_EV_CONN_ADDDATA, .name = "add_hdshk_data", .desc = "TLS stack ->add_handshake_data() call"},
155 { .mask = QUIC_EV_CONN_FFLIGHT, .name = "flush_flight", .desc = "TLS stack ->flush_flight() call"},
156 { .mask = QUIC_EV_CONN_SSLALERT, .name = "send_alert", .desc = "TLS stack ->send_alert() call"},
157 { .mask = QUIC_EV_CONN_RTTUPDT, .name = "rtt_updt", .desc = "RTT sampling" },
158 { .mask = QUIC_EV_CONN_SPPKTS, .name = "sppkts", .desc = "send prepared packets" },
159 { .mask = QUIC_EV_CONN_PKTLOSS, .name = "pktloss", .desc = "detect packet loss" },
160 { .mask = QUIC_EV_CONN_STIMER, .name = "stimer", .desc = "set timer" },
161 { .mask = QUIC_EV_CONN_PTIMER, .name = "ptimer", .desc = "process timer" },
162 { .mask = QUIC_EV_CONN_SPTO, .name = "spto", .desc = "set PTO" },
163 { .mask = QUIC_EV_CONN_BCFRMS, .name = "bcfrms", .desc = "build CRYPTO data frames" },
164 { .mask = QUIC_EV_CONN_XPRTSEND, .name = "xprt_send", .desc = "sending XRPT subscription" },
165 { .mask = QUIC_EV_CONN_XPRTRECV, .name = "xprt_recv", .desc = "receiving XRPT subscription" },
166 { .mask = QUIC_EV_CONN_FREED, .name = "conn_freed", .desc = "releasing conn. memory" },
167 { .mask = QUIC_EV_CONN_CLOSE, .name = "conn_close", .desc = "closing conn." },
168 { .mask = QUIC_EV_CONN_ACKSTRM, .name = "ack_strm", .desc = "STREAM ack."},
169 { .mask = QUIC_EV_CONN_FRMLIST, .name = "frm_list", .desc = "frame list"},
170 { .mask = QUIC_EV_STATELESS_RST, .name = "stateless_reset", .desc = "stateless reset sent"},
171 { .mask = QUIC_EV_TRANSP_PARAMS, .name = "transport_params", .desc = "transport parameters"},
172 { .mask = QUIC_EV_CONN_IDLE_TIMER, .name = "idle_timer", .desc = "idle timer task"},
173 { .mask = QUIC_EV_CONN_SUB, .name = "xprt_sub", .desc = "RX/TX subcription or unsubscription to QUIC xprt"},
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200174 { .mask = QUIC_EV_CONN_RCV, .name = "conn_recv", .desc = "RX on connection" },
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200175 { /* end */ }
176};
177
178static const struct name_desc quic_trace_lockon_args[4] = {
179 /* arg1 */ { /* already used by the connection */ },
180 /* arg2 */ { .name="quic", .desc="QUIC transport" },
181 /* arg3 */ { },
182 /* arg4 */ { }
183};
184
185static const struct name_desc quic_trace_decoding[] = {
186#define QUIC_VERB_CLEAN 1
187 { .name="clean", .desc="only user-friendly stuff, generally suitable for level \"user\"" },
188 { /* end */ }
189};
190
191
192struct trace_source trace_quic = {
193 .name = IST("quic"),
194 .desc = "QUIC xprt",
195 .arg_def = TRC_ARG1_QCON, /* TRACE()'s first argument is always a quic_conn */
196 .default_cb = quic_trace,
197 .known_events = quic_trace_events,
198 .lockon_args = quic_trace_lockon_args,
199 .decoding = quic_trace_decoding,
200 .report_events = ~0, /* report everything by default */
201};
202
203#define TRACE_SOURCE &trace_quic
204INITCALL1(STG_REGISTER, trace_register_source, TRACE_SOURCE);
205
206static BIO_METHOD *ha_quic_meth;
207
208DECLARE_POOL(pool_head_quic_tx_ring, "quic_tx_ring", QUIC_TX_RING_BUFSZ);
209DECLARE_POOL(pool_head_quic_conn_rxbuf, "quic_conn_rxbuf", QUIC_CONN_RX_BUFSZ);
210DECLARE_STATIC_POOL(pool_head_quic_conn_ctx,
211 "quic_conn_ctx", sizeof(struct ssl_sock_ctx));
212DECLARE_STATIC_POOL(pool_head_quic_conn, "quic_conn", sizeof(struct quic_conn));
213DECLARE_POOL(pool_head_quic_connection_id,
214 "quic_connnection_id", sizeof(struct quic_connection_id));
215DECLARE_POOL(pool_head_quic_dgram, "quic_dgram", sizeof(struct quic_dgram));
216DECLARE_POOL(pool_head_quic_rx_packet, "quic_rx_packet", sizeof(struct quic_rx_packet));
217DECLARE_POOL(pool_head_quic_tx_packet, "quic_tx_packet", sizeof(struct quic_tx_packet));
218DECLARE_STATIC_POOL(pool_head_quic_rx_crypto_frm, "quic_rx_crypto_frm", sizeof(struct quic_rx_crypto_frm));
219DECLARE_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 +0200220DECLARE_STATIC_POOL(pool_head_quic_cstream, "quic_cstream", sizeof(struct quic_cstream));
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200221DECLARE_POOL(pool_head_quic_frame, "quic_frame", sizeof(struct quic_frame));
222DECLARE_STATIC_POOL(pool_head_quic_arng, "quic_arng", sizeof(struct quic_arng_node));
223
224static struct quic_tx_packet *qc_build_pkt(unsigned char **pos, const unsigned char *buf_end,
225 struct quic_enc_level *qel, struct quic_tls_ctx *ctx,
226 struct list *frms, struct quic_conn *qc,
227 const struct quic_version *ver, size_t dglen, int pkt_type,
228 int force_ack, int padding, int probe, int cc, int *err);
229struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state);
230static void qc_idle_timer_do_rearm(struct quic_conn *qc);
231static void qc_idle_timer_rearm(struct quic_conn *qc, int read);
232static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc);
233static int quic_conn_init_timer(struct quic_conn *qc);
234static int quic_conn_init_idle_timer_task(struct quic_conn *qc);
235
236/* Only for debug purpose */
237struct enc_debug_info {
238 unsigned char *payload;
239 size_t payload_len;
240 unsigned char *aad;
241 size_t aad_len;
242 uint64_t pn;
243};
244
245/* Initializes a enc_debug_info struct (only for debug purpose) */
246static inline void enc_debug_info_init(struct enc_debug_info *edi,
247 unsigned char *payload, size_t payload_len,
248 unsigned char *aad, size_t aad_len, uint64_t pn)
249{
250 edi->payload = payload;
251 edi->payload_len = payload_len;
252 edi->aad = aad;
253 edi->aad_len = aad_len;
254 edi->pn = pn;
255}
256
257/* Trace callback for QUIC.
258 * These traces always expect that arg1, if non-null, is of type connection.
259 */
260static void quic_trace(enum trace_level level, uint64_t mask, const struct trace_source *src,
261 const struct ist where, const struct ist func,
262 const void *a1, const void *a2, const void *a3, const void *a4)
263{
264 const struct quic_conn *qc = a1;
265
266 if (qc) {
267 const struct quic_tls_ctx *tls_ctx;
268
269 chunk_appendf(&trace_buf, " : qc@%p", qc);
270 if (mask & QUIC_EV_CONN_INIT) {
271 chunk_appendf(&trace_buf, "\n odcid");
272 quic_cid_dump(&trace_buf, &qc->odcid);
273 chunk_appendf(&trace_buf, "\n dcid");
274 quic_cid_dump(&trace_buf, &qc->dcid);
275 chunk_appendf(&trace_buf, "\n scid");
276 quic_cid_dump(&trace_buf, &qc->scid);
277 }
278
279 if (mask & QUIC_EV_TRANSP_PARAMS) {
280 const struct quic_transport_params *p = a2;
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100281
282 if (p)
283 quic_transport_params_dump(&trace_buf, qc, p);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200284 }
285
286 if (mask & QUIC_EV_CONN_ADDDATA) {
287 const enum ssl_encryption_level_t *level = a2;
288 const size_t *len = a3;
289
290 if (level) {
291 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
292
293 chunk_appendf(&trace_buf, " el=%c(%d)", quic_enc_level_char(lvl), lvl);
294 }
295 if (len)
296 chunk_appendf(&trace_buf, " len=%llu", (unsigned long long)*len);
297 }
298 if ((mask & QUIC_EV_CONN_ISEC) && qc) {
299 /* Initial read & write secrets. */
300 enum quic_tls_enc_level level = QUIC_TLS_ENC_LEVEL_INITIAL;
301 const unsigned char *rx_sec = a2;
302 const unsigned char *tx_sec = a3;
303
304 tls_ctx = &qc->els[level].tls_ctx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200305 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(level));
306 if (rx_sec)
307 quic_tls_secret_hexdump(&trace_buf, rx_sec, 32);
308 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
309 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(level));
310 if (tx_sec)
311 quic_tls_secret_hexdump(&trace_buf, tx_sec, 32);
312 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200313 }
314 if (mask & (QUIC_EV_CONN_RSEC|QUIC_EV_CONN_RWSEC)) {
315 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200316
317 if (level) {
318 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
319
320 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200321 if (quic_tls_has_rx_sec(&qc->els[lvl])) {
322 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200323 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200324 }
325 else
326 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200327 }
328 }
329
330 if (mask & (QUIC_EV_CONN_WSEC|QUIC_EV_CONN_RWSEC)) {
331 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200332
333 if (level) {
334 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
335
336 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200337 if (quic_tls_has_tx_sec(&qc->els[lvl])) {
338 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200339 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200340 }
341 else
342 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200343 }
344
345 }
346
347 if (mask & QUIC_EV_CONN_FRMLIST) {
348 const struct list *l = a2;
349
350 if (l) {
351 const struct quic_frame *frm;
352 list_for_each_entry(frm, l, list) {
353 chunk_appendf(&trace_buf, " frm@%p", frm);
354 chunk_frm_appendf(&trace_buf, frm);
355 }
356 }
357 }
358
359 if (mask & (QUIC_EV_CONN_TXPKT|QUIC_EV_CONN_PAPKT)) {
360 const struct quic_tx_packet *pkt = a2;
361 const struct quic_enc_level *qel = a3;
362 const ssize_t *room = a4;
363
364 if (qel) {
365 const struct quic_pktns *pktns = qel->pktns;
Frédéric Lécaille45400532023-02-13 18:39:19 +0100366 chunk_appendf(&trace_buf, " qel=%c pto_count=%d cwnd=%llu ppif=%lld pif=%llu "
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200367 "if=%llu pp=%u",
368 quic_enc_level_char_from_qel(qel, qc),
Frédéric Lécaille45400532023-02-13 18:39:19 +0100369 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200370 (unsigned long long)qc->path->cwnd,
371 (unsigned long long)qc->path->prep_in_flight,
372 (unsigned long long)qc->path->in_flight,
373 (unsigned long long)pktns->tx.in_flight,
374 pktns->tx.pto_probe);
375 }
376 if (pkt) {
377 const struct quic_frame *frm;
378 if (pkt->pn_node.key != (uint64_t)-1)
379 chunk_appendf(&trace_buf, " pn=%llu",(ull)pkt->pn_node.key);
380 list_for_each_entry(frm, &pkt->frms, list) {
381 chunk_appendf(&trace_buf, " frm@%p", frm);
382 chunk_frm_appendf(&trace_buf, frm);
383 }
384 }
385
386 if (room) {
387 chunk_appendf(&trace_buf, " room=%lld", (long long)*room);
388 chunk_appendf(&trace_buf, " dcid.len=%llu scid.len=%llu",
389 (unsigned long long)qc->dcid.len, (unsigned long long)qc->scid.len);
390 }
391 }
392
393 if (mask & QUIC_EV_CONN_IO_CB) {
394 const enum quic_handshake_state *state = a2;
395 const int *err = a3;
396
397 if (state)
398 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(*state));
399 if (err)
400 chunk_appendf(&trace_buf, " err=%s", ssl_error_str(*err));
401 }
402
403 if (mask & (QUIC_EV_CONN_TRMHP|QUIC_EV_CONN_ELRMHP|QUIC_EV_CONN_SPKT)) {
404 const struct quic_rx_packet *pkt = a2;
405 const unsigned long *pktlen = a3;
406 const SSL *ssl = a4;
407
408 if (pkt) {
409 chunk_appendf(&trace_buf, " pkt@%p", pkt);
410 if (pkt->type == QUIC_PACKET_TYPE_SHORT && pkt->data)
411 chunk_appendf(&trace_buf, " kp=%d",
412 !!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT));
413 chunk_appendf(&trace_buf, " el=%c",
414 quic_packet_type_enc_level_char(pkt->type));
415 if (pkt->pnl)
416 chunk_appendf(&trace_buf, " pnl=%u pn=%llu", pkt->pnl,
417 (unsigned long long)pkt->pn);
418 if (pkt->token_len)
419 chunk_appendf(&trace_buf, " toklen=%llu",
420 (unsigned long long)pkt->token_len);
421 if (pkt->aad_len)
422 chunk_appendf(&trace_buf, " aadlen=%llu",
423 (unsigned long long)pkt->aad_len);
424 chunk_appendf(&trace_buf, " flags=0x%x len=%llu",
425 pkt->flags, (unsigned long long)pkt->len);
426 }
427 if (pktlen)
428 chunk_appendf(&trace_buf, " (%ld)", *pktlen);
429 if (ssl) {
430 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
431 chunk_appendf(&trace_buf, " el=%c",
432 quic_enc_level_char(ssl_to_quic_enc_level(level)));
433 }
434 }
435
436 if (mask & (QUIC_EV_CONN_RXPKT|QUIC_EV_CONN_PRSHPKT|QUIC_EV_CONN_SSLDATA)) {
437 const struct quic_rx_packet *pkt = a2;
438 const struct quic_rx_crypto_frm *cf = a3;
439 const SSL *ssl = a4;
440
441 if (pkt)
442 chunk_appendf(&trace_buf, " pkt@%p el=%c pn=%llu", pkt,
443 quic_packet_type_enc_level_char(pkt->type),
444 (unsigned long long)pkt->pn);
445 if (cf)
446 chunk_appendf(&trace_buf, " cfoff=%llu cflen=%llu",
447 (unsigned long long)cf->offset_node.key,
448 (unsigned long long)cf->len);
449 if (ssl) {
450 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
451 chunk_appendf(&trace_buf, " rel=%c",
452 quic_enc_level_char(ssl_to_quic_enc_level(level)));
453 }
454
455 if (qc->err.code)
456 chunk_appendf(&trace_buf, " err_code=0x%llx", (ull)qc->err.code);
457 }
458
459 if (mask & (QUIC_EV_CONN_PRSFRM|QUIC_EV_CONN_BFRM)) {
460 const struct quic_frame *frm = a2;
461
462 if (frm)
463 chunk_appendf(&trace_buf, " %s", quic_frame_type_string(frm->type));
464 }
465
466 if (mask & QUIC_EV_CONN_PHPKTS) {
467 const struct quic_enc_level *qel = a2;
468
469 if (qel) {
470 const struct quic_pktns *pktns = qel->pktns;
471 chunk_appendf(&trace_buf,
Frédéric Lécaille45400532023-02-13 18:39:19 +0100472 " 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 +0200473 quic_enc_level_char_from_qel(qel, qc),
474 quic_hdshk_state_str(qc->state),
475 !!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED),
Frédéric Lécaille45400532023-02-13 18:39:19 +0100476 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200477 (unsigned long long)qc->path->cwnd,
478 (unsigned long long)qc->path->prep_in_flight,
479 (unsigned long long)qc->path->in_flight,
480 (unsigned long long)pktns->tx.in_flight,
Amaury Denoyelle2f668f02022-11-18 15:24:08 +0100481 pktns->tx.pto_probe,
482 qel->cstream ? (unsigned long long)qel->cstream->rx.offset : 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200483 }
484 }
485
486 if (mask & QUIC_EV_CONN_ENCPKT) {
487 const struct enc_debug_info *edi = a2;
488
489 if (edi)
490 chunk_appendf(&trace_buf,
491 " payload=@%p payload_len=%llu"
492 " aad=@%p aad_len=%llu pn=%llu",
493 edi->payload, (unsigned long long)edi->payload_len,
494 edi->aad, (unsigned long long)edi->aad_len,
495 (unsigned long long)edi->pn);
496 }
497
498 if (mask & QUIC_EV_CONN_RMHP) {
499 const struct quic_rx_packet *pkt = a2;
500
501 if (pkt) {
502 const int *ret = a3;
503
504 chunk_appendf(&trace_buf, " pkt@%p", pkt);
505 if (ret && *ret)
506 chunk_appendf(&trace_buf, " pnl=%u pn=%llu",
507 pkt->pnl, (unsigned long long)pkt->pn);
508 }
509 }
510
511 if (mask & QUIC_EV_CONN_PRSAFRM) {
512 const struct quic_frame *frm = a2;
513 const unsigned long *val1 = a3;
514 const unsigned long *val2 = a4;
515
516 if (frm) {
517 chunk_appendf(&trace_buf, " frm@%p", frm);
518 chunk_frm_appendf(&trace_buf, frm);
519 }
520 if (val1)
521 chunk_appendf(&trace_buf, " %lu", *val1);
522 if (val2)
523 chunk_appendf(&trace_buf, "..%lu", *val2);
524 }
525
526 if (mask & QUIC_EV_CONN_ACKSTRM) {
527 const struct quic_stream *s = a2;
528 const struct qc_stream_desc *stream = a3;
529
530 if (s)
531 chunk_appendf(&trace_buf, " off=%llu len=%llu", (ull)s->offset.key, (ull)s->len);
532 if (stream)
533 chunk_appendf(&trace_buf, " ack_offset=%llu", (ull)stream->ack_offset);
534 }
535
536 if (mask & QUIC_EV_CONN_RTTUPDT) {
537 const unsigned int *rtt_sample = a2;
538 const unsigned int *ack_delay = a3;
539 const struct quic_loss *ql = a4;
540
541 if (rtt_sample)
542 chunk_appendf(&trace_buf, " rtt_sample=%ums", *rtt_sample);
543 if (ack_delay)
544 chunk_appendf(&trace_buf, " ack_delay=%ums", *ack_delay);
545 if (ql)
546 chunk_appendf(&trace_buf,
547 " srtt=%ums rttvar=%ums min_rtt=%ums",
548 ql->srtt >> 3, ql->rtt_var >> 2, ql->rtt_min);
549 }
550 if (mask & QUIC_EV_CONN_CC) {
551 const struct quic_cc_event *ev = a2;
552 const struct quic_cc *cc = a3;
553
554 if (a2)
555 quic_cc_event_trace(&trace_buf, ev);
556 if (a3)
557 quic_cc_state_trace(&trace_buf, cc);
558 }
559
560 if (mask & QUIC_EV_CONN_PKTLOSS) {
561 const struct quic_pktns *pktns = a2;
562 const struct list *lost_pkts = a3;
563
564 if (pktns) {
565 chunk_appendf(&trace_buf, " pktns=%s",
566 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
567 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H");
568 if (pktns->tx.loss_time)
569 chunk_appendf(&trace_buf, " loss_time=%dms",
570 TICKS_TO_MS(tick_remain(now_ms, pktns->tx.loss_time)));
571 }
572 if (lost_pkts && !LIST_ISEMPTY(lost_pkts)) {
573 struct quic_tx_packet *pkt;
574
575 chunk_appendf(&trace_buf, " lost_pkts:");
576 list_for_each_entry(pkt, lost_pkts, list)
577 chunk_appendf(&trace_buf, " %lu", (unsigned long)pkt->pn_node.key);
578 }
579 }
580
581 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_PTIMER|QUIC_EV_CONN_SPTO)) {
582 const struct quic_pktns *pktns = a2;
583 const int *duration = a3;
584 const uint64_t *ifae_pkts = a4;
585
586 if (ifae_pkts)
587 chunk_appendf(&trace_buf, " ifae_pkts=%llu",
588 (unsigned long long)*ifae_pkts);
589 if (pktns) {
590 chunk_appendf(&trace_buf, " pktns=%s pp=%d",
591 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
592 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
593 pktns->tx.pto_probe);
594 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_SPTO)) {
595 if (pktns->tx.in_flight)
596 chunk_appendf(&trace_buf, " if=%llu", (ull)pktns->tx.in_flight);
597 if (pktns->tx.loss_time)
598 chunk_appendf(&trace_buf, " loss_time=%dms",
599 TICKS_TO_MS(pktns->tx.loss_time - now_ms));
600 }
601 if (mask & QUIC_EV_CONN_SPTO) {
602 if (pktns->tx.time_of_last_eliciting)
603 chunk_appendf(&trace_buf, " tole=%dms",
604 TICKS_TO_MS(pktns->tx.time_of_last_eliciting - now_ms));
605 if (duration)
606 chunk_appendf(&trace_buf, " dur=%dms", TICKS_TO_MS(*duration));
607 }
608 }
609
610 if (!(mask & (QUIC_EV_CONN_SPTO|QUIC_EV_CONN_PTIMER)) && qc->timer_task) {
611 chunk_appendf(&trace_buf,
612 " expire=%dms", TICKS_TO_MS(qc->timer - now_ms));
613 }
614 }
615
616 if (mask & QUIC_EV_CONN_SPPKTS) {
617 const struct quic_tx_packet *pkt = a2;
618
Frédéric Lécaille45400532023-02-13 18:39:19 +0100619 chunk_appendf(&trace_buf, " pto_count=%d cwnd=%llu ppif=%llu pif=%llu",
620 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200621 (unsigned long long)qc->path->cwnd,
622 (unsigned long long)qc->path->prep_in_flight,
623 (unsigned long long)qc->path->in_flight);
624 if (pkt) {
625 const struct quic_frame *frm;
626 chunk_appendf(&trace_buf, " pn=%lu(%s) iflen=%llu",
627 (unsigned long)pkt->pn_node.key,
628 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
629 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
630 (unsigned long long)pkt->in_flight_len);
631 chunk_appendf(&trace_buf, " rx.bytes=%llu tx.bytes=%llu",
632 (unsigned long long)qc->rx.bytes,
633 (unsigned long long)qc->tx.bytes);
634 list_for_each_entry(frm, &pkt->frms, list) {
635 chunk_appendf(&trace_buf, " frm@%p", frm);
636 chunk_frm_appendf(&trace_buf, frm);
637 }
Frédéric Lécaillebc09f742023-02-13 17:45:36 +0100638
639 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
640 chunk_appendf(&trace_buf, " with scid");
641 quic_cid_dump(&trace_buf, &qc->scid);
642 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200643 }
644 }
645
646 if (mask & QUIC_EV_CONN_SSLALERT) {
647 const uint8_t *alert = a2;
648 const enum ssl_encryption_level_t *level = a3;
649
650 if (alert)
651 chunk_appendf(&trace_buf, " alert=0x%02x", *alert);
652 if (level)
653 chunk_appendf(&trace_buf, " el=%c",
654 quic_enc_level_char(ssl_to_quic_enc_level(*level)));
655 }
656
657 if (mask & QUIC_EV_CONN_BCFRMS) {
658 const size_t *sz1 = a2;
659 const size_t *sz2 = a3;
660 const size_t *sz3 = a4;
661
662 if (sz1)
663 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz1);
664 if (sz2)
665 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz2);
666 if (sz3)
667 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz3);
668 }
669
670 if (mask & QUIC_EV_CONN_PSTRM) {
671 const struct quic_frame *frm = a2;
672
673 if (frm) {
674 chunk_appendf(&trace_buf, " frm@%p", frm);
675 chunk_frm_appendf(&trace_buf, frm);
676 }
677 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +0200678
679 if (mask & QUIC_EV_CONN_ELEVELSEL) {
680 const enum quic_handshake_state *state = a2;
681 const enum quic_tls_enc_level *level = a3;
682 const enum quic_tls_enc_level *next_level = a4;
683
684 if (state)
685 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(qc->state));
686 if (level)
687 chunk_appendf(&trace_buf, " level=%c", quic_enc_level_char(*level));
688 if (next_level)
689 chunk_appendf(&trace_buf, " next_level=%c", quic_enc_level_char(*next_level));
690
691 }
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200692
693 if (mask & QUIC_EV_CONN_RCV) {
694 const struct quic_dgram *dgram = a2;
695
696 if (dgram)
697 chunk_appendf(&trace_buf, " dgram.len=%zu", dgram->len);
698 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200699 }
700 if (mask & QUIC_EV_CONN_LPKT) {
701 const struct quic_rx_packet *pkt = a2;
702 const uint64_t *len = a3;
703 const struct quic_version *ver = a4;
704
705 if (pkt) {
706 chunk_appendf(&trace_buf, " pkt@%p type=0x%02x %s",
707 pkt, pkt->type, qc_pkt_long(pkt) ? "long" : "short");
708 if (pkt->pn_node.key != (uint64_t)-1)
709 chunk_appendf(&trace_buf, " pn=%llu", pkt->pn_node.key);
710 }
711
712 if (len)
713 chunk_appendf(&trace_buf, " len=%llu", (ull)*len);
714
715 if (ver)
716 chunk_appendf(&trace_buf, " ver=0x%08x", ver->num);
717 }
718
719 if (mask & QUIC_EV_STATELESS_RST) {
720 const struct quic_cid *cid = a2;
721
722 if (cid)
723 quic_cid_dump(&trace_buf, cid);
724 }
725
726}
727
728/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
729static inline int quic_peer_validated_addr(struct quic_conn *qc)
730{
731 struct quic_pktns *hdshk_pktns, *app_pktns;
732
733 if (!qc_is_listener(qc))
734 return 1;
735
736 hdshk_pktns = qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns;
737 app_pktns = qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns;
738 if ((hdshk_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
739 (app_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
740 qc->state >= QUIC_HS_ST_COMPLETE)
741 return 1;
742
743 return 0;
744}
745
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100746/* To be called to kill a connection as soon as possible (without sending any packet). */
747void qc_kill_conn(struct quic_conn *qc)
748{
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100749 TRACE_ENTER(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100750 qc->flags |= QUIC_FL_CONN_TO_KILL;
751 task_wakeup(qc->idle_timer_task, TASK_WOKEN_OTHER);
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100752 TRACE_LEAVE(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100753}
754
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200755/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
756 * both loss detection and PTO and schedule the task assiated to this timer if needed.
757 */
758static inline void qc_set_timer(struct quic_conn *qc)
759{
760 struct quic_pktns *pktns;
761 unsigned int pto;
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100762 int handshake_confirmed;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200763
764 TRACE_ENTER(QUIC_EV_CONN_STIMER, qc,
765 NULL, NULL, &qc->path->ifae_pkts);
766
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100767 pktns = NULL;
768 if (!qc->timer_task) {
769 TRACE_PROTO("already released timer task", QUIC_EV_CONN_STIMER, qc);
770 goto leave;
771 }
772
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200773 pktns = quic_loss_pktns(qc);
774 if (tick_isset(pktns->tx.loss_time)) {
775 qc->timer = pktns->tx.loss_time;
776 goto out;
777 }
778
779 /* anti-amplification: the timer must be
780 * cancelled for a server which reached the anti-amplification limit.
781 */
782 if (!quic_peer_validated_addr(qc) &&
783 (qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
784 TRACE_PROTO("anti-amplification reached", QUIC_EV_CONN_STIMER, qc);
785 qc->timer = TICK_ETERNITY;
786 goto out;
787 }
788
789 if (!qc->path->ifae_pkts && quic_peer_validated_addr(qc)) {
790 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, qc);
791 /* Timer cancellation. */
792 qc->timer = TICK_ETERNITY;
793 goto out;
794 }
795
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100796 handshake_confirmed = qc->state >= QUIC_HS_ST_CONFIRMED;
797 pktns = quic_pto_pktns(qc, handshake_confirmed, &pto);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200798 if (tick_isset(pto))
799 qc->timer = pto;
800 out:
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100801 if (qc->timer == TICK_ETERNITY) {
802 qc->timer_task->expire = TICK_ETERNITY;
803 }
804 else if (tick_is_expired(qc->timer, now_ms)) {
805 TRACE_DEVEL("wakeup asap timer task", QUIC_EV_CONN_STIMER, qc);
806 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
807 }
808 else {
809 TRACE_DEVEL("timer task scheduling", QUIC_EV_CONN_STIMER, qc);
810 task_schedule(qc->timer_task, qc->timer);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200811 }
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100812 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200813 TRACE_LEAVE(QUIC_EV_CONN_STIMER, qc, pktns);
814}
815
816/* Derive new keys and ivs required for Key Update feature for <qc> QUIC
817 * connection.
818 * Return 1 if succeeded, 0 if not.
819 */
820static int quic_tls_key_update(struct quic_conn *qc)
821{
822 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
823 struct quic_tls_secrets *rx, *tx;
824 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
825 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
826 const struct quic_version *ver =
827 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
828 int ret = 0;
829
830 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
831
832 tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
833 rx = &tls_ctx->rx;
834 tx = &tls_ctx->tx;
835 nxt_rx = &qc->ku.nxt_rx;
836 nxt_tx = &qc->ku.nxt_tx;
837
838 /* Prepare new RX secrets */
839 if (!quic_tls_sec_update(rx->md, ver, nxt_rx->secret, nxt_rx->secretlen,
840 rx->secret, rx->secretlen)) {
841 TRACE_ERROR("New RX secret update failed", QUIC_EV_CONN_RWSEC, qc);
842 goto leave;
843 }
844
845 if (!quic_tls_derive_keys(rx->aead, NULL, rx->md, ver,
846 nxt_rx->key, nxt_rx->keylen,
847 nxt_rx->iv, nxt_rx->ivlen, NULL, 0,
848 nxt_rx->secret, nxt_rx->secretlen)) {
849 TRACE_ERROR("New RX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
850 goto leave;
851 }
852
853 /* Prepare new TX secrets */
854 if (!quic_tls_sec_update(tx->md, ver, nxt_tx->secret, nxt_tx->secretlen,
855 tx->secret, tx->secretlen)) {
856 TRACE_ERROR("New TX secret update failed", QUIC_EV_CONN_RWSEC, qc);
857 goto leave;
858 }
859
860 if (!quic_tls_derive_keys(tx->aead, NULL, tx->md, ver,
861 nxt_tx->key, nxt_tx->keylen,
862 nxt_tx->iv, nxt_tx->ivlen, NULL, 0,
863 nxt_tx->secret, nxt_tx->secretlen)) {
864 TRACE_ERROR("New TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
865 goto leave;
866 }
867
868 if (nxt_rx->ctx) {
869 EVP_CIPHER_CTX_free(nxt_rx->ctx);
870 nxt_rx->ctx = NULL;
871 }
872
873 if (!quic_tls_rx_ctx_init(&nxt_rx->ctx, tls_ctx->rx.aead, nxt_rx->key)) {
874 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
875 goto leave;
876 }
877
878 if (nxt_tx->ctx) {
879 EVP_CIPHER_CTX_free(nxt_tx->ctx);
880 nxt_tx->ctx = NULL;
881 }
882
883 if (!quic_tls_rx_ctx_init(&nxt_tx->ctx, tls_ctx->tx.aead, nxt_tx->key)) {
884 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
885 goto leave;
886 }
887
888 ret = 1;
889 leave:
890 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc);
891 return ret;
892}
893
894/* Rotate the Key Update information for <qc> QUIC connection.
895 * Must be used after having updated them.
896 * Always succeeds.
897 */
898static void quic_tls_rotate_keys(struct quic_conn *qc)
899{
900 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
901 unsigned char *curr_secret, *curr_iv, *curr_key;
902 EVP_CIPHER_CTX *curr_ctx;
903
904 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
905
906 /* Rotate the RX secrets */
907 curr_ctx = tls_ctx->rx.ctx;
908 curr_secret = tls_ctx->rx.secret;
909 curr_iv = tls_ctx->rx.iv;
910 curr_key = tls_ctx->rx.key;
911
912 tls_ctx->rx.ctx = qc->ku.nxt_rx.ctx;
913 tls_ctx->rx.secret = qc->ku.nxt_rx.secret;
914 tls_ctx->rx.iv = qc->ku.nxt_rx.iv;
915 tls_ctx->rx.key = qc->ku.nxt_rx.key;
916
917 qc->ku.nxt_rx.ctx = qc->ku.prv_rx.ctx;
918 qc->ku.nxt_rx.secret = qc->ku.prv_rx.secret;
919 qc->ku.nxt_rx.iv = qc->ku.prv_rx.iv;
920 qc->ku.nxt_rx.key = qc->ku.prv_rx.key;
921
922 qc->ku.prv_rx.ctx = curr_ctx;
923 qc->ku.prv_rx.secret = curr_secret;
924 qc->ku.prv_rx.iv = curr_iv;
925 qc->ku.prv_rx.key = curr_key;
926 qc->ku.prv_rx.pn = tls_ctx->rx.pn;
927
928 /* Update the TX secrets */
929 curr_ctx = tls_ctx->tx.ctx;
930 curr_secret = tls_ctx->tx.secret;
931 curr_iv = tls_ctx->tx.iv;
932 curr_key = tls_ctx->tx.key;
933
934 tls_ctx->tx.ctx = qc->ku.nxt_tx.ctx;
935 tls_ctx->tx.secret = qc->ku.nxt_tx.secret;
936 tls_ctx->tx.iv = qc->ku.nxt_tx.iv;
937 tls_ctx->tx.key = qc->ku.nxt_tx.key;
938
939 qc->ku.nxt_tx.ctx = curr_ctx;
940 qc->ku.nxt_tx.secret = curr_secret;
941 qc->ku.nxt_tx.iv = curr_iv;
942 qc->ku.nxt_tx.key = curr_key;
943
944 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
945}
946
947/* returns 0 on error, 1 on success */
948int ha_quic_set_encryption_secrets(SSL *ssl, enum ssl_encryption_level_t level,
949 const uint8_t *read_secret,
950 const uint8_t *write_secret, size_t secret_len)
951{
952 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
953 struct quic_tls_ctx *tls_ctx = &qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
954 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200955 struct quic_tls_secrets *rx = NULL, *tx = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200956 const struct quic_version *ver =
957 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
958 int ret = 0;
959
960 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
961 BUG_ON(secret_len > QUIC_TLS_SECRET_LEN);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100962
963 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
964 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
965 goto out;
966 }
967
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200968 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
969 TRACE_PROTO("CC required", QUIC_EV_CONN_RWSEC, qc);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200970 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200971 }
972
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200973 if (!read_secret)
974 goto write;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200975
976 rx = &tls_ctx->rx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200977 if (!quic_tls_secrets_keys_alloc(rx)) {
978 TRACE_ERROR("RX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
979 goto leave;
980 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200981
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200982 rx->aead = tls_aead(cipher);
983 rx->md = tls_md(cipher);
984 rx->hp = tls_hp(cipher);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200985
986 if (!quic_tls_derive_keys(rx->aead, rx->hp, rx->md, ver, rx->key, rx->keylen,
987 rx->iv, rx->ivlen, rx->hp_key, sizeof rx->hp_key,
988 read_secret, secret_len)) {
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200989 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200990 goto leave;
991 }
992
993 if (!quic_tls_rx_ctx_init(&rx->ctx, rx->aead, rx->key)) {
994 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
995 goto leave;
996 }
997
998 if (!quic_tls_dec_aes_ctx_init(&rx->hp_ctx, rx->hp, rx->hp_key)) {
999 TRACE_ERROR("could not initial RX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
1000 goto leave;
1001 }
1002
1003 /* Enqueue this connection asap if we could derive O-RTT secrets as
1004 * listener. Note that a listener derives only RX secrets for this
1005 * level.
1006 */
1007 if (qc_is_listener(qc) && level == ssl_encryption_early_data) {
1008 TRACE_DEVEL("pushing connection into accept queue", QUIC_EV_CONN_RWSEC, qc);
1009 quic_accept_push_qc(qc);
1010 }
1011
1012write:
1013
1014 if (!write_secret)
1015 goto out;
1016
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001017 tx = &tls_ctx->tx;
1018 if (!quic_tls_secrets_keys_alloc(tx)) {
1019 TRACE_ERROR("TX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
1020 goto leave;
1021 }
1022
1023 tx->aead = tls_aead(cipher);
1024 tx->md = tls_md(cipher);
1025 tx->hp = tls_hp(cipher);
1026
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001027 if (!quic_tls_derive_keys(tx->aead, tx->hp, tx->md, ver, tx->key, tx->keylen,
1028 tx->iv, tx->ivlen, tx->hp_key, sizeof tx->hp_key,
1029 write_secret, secret_len)) {
1030 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
1031 goto leave;
1032 }
1033
1034 if (!quic_tls_tx_ctx_init(&tx->ctx, tx->aead, tx->key)) {
1035 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
1036 goto leave;
1037 }
1038
1039 if (!quic_tls_enc_aes_ctx_init(&tx->hp_ctx, tx->hp, tx->hp_key)) {
1040 TRACE_ERROR("could not initial TX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
1041 goto leave;
1042 }
1043
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01001044 if (level == ssl_encryption_handshake && qc_is_listener(qc)) {
1045 qc->enc_params_len =
1046 quic_transport_params_encode(qc->enc_params,
1047 qc->enc_params + sizeof qc->enc_params,
1048 &qc->rx.params, ver, 1);
1049 if (!qc->enc_params_len) {
1050 TRACE_ERROR("quic_transport_params_encode() failed", QUIC_EV_CONN_RWSEC);
1051 goto leave;
1052 }
1053
1054 if (!SSL_set_quic_transport_params(qc->xprt_ctx->ssl, qc->enc_params, qc->enc_params_len)) {
1055 TRACE_ERROR("SSL_set_quic_transport_params() failed", QUIC_EV_CONN_RWSEC);
1056 goto leave;
1057 }
1058 }
1059
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001060 if (level == ssl_encryption_application) {
1061 struct quic_tls_kp *prv_rx = &qc->ku.prv_rx;
1062 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
1063 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
1064
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001065 if (rx) {
1066 if (!(rx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1067 TRACE_ERROR("Could not allocate RX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1068 goto leave;
1069 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001070
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001071 memcpy(rx->secret, read_secret, secret_len);
1072 rx->secretlen = secret_len;
1073 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001074
1075 if (tx) {
1076 if (!(tx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1077 TRACE_ERROR("Could not allocate TX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1078 goto leave;
1079 }
1080
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001081 memcpy(tx->secret, write_secret, secret_len);
1082 tx->secretlen = secret_len;
1083 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001084
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001085 /* Initialize all the secret keys lengths */
1086 prv_rx->secretlen = nxt_rx->secretlen = nxt_tx->secretlen = secret_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001087 }
1088
1089 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001090 ret = 1;
1091 leave:
1092 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc, &level);
1093 return ret;
1094}
1095
1096/* This function copies the CRYPTO data provided by the TLS stack found at <data>
1097 * with <len> as size in CRYPTO buffers dedicated to store the information about
1098 * outgoing CRYPTO frames so that to be able to replay the CRYPTO data streams.
1099 * It fails (returns 0) only if it could not managed to allocate enough CRYPTO
1100 * buffers to store all the data.
1101 * Note that CRYPTO data may exist at any encryption level except at 0-RTT.
1102 */
1103static int quic_crypto_data_cpy(struct quic_conn *qc, struct quic_enc_level *qel,
1104 const unsigned char *data, size_t len)
1105{
1106 struct quic_crypto_buf **qcb;
1107 /* The remaining byte to store in CRYPTO buffers. */
1108 size_t cf_offset, cf_len, *nb_buf;
1109 unsigned char *pos;
1110 int ret = 0;
1111
1112 nb_buf = &qel->tx.crypto.nb_buf;
1113 qcb = &qel->tx.crypto.bufs[*nb_buf - 1];
1114 cf_offset = (*nb_buf - 1) * QUIC_CRYPTO_BUF_SZ + (*qcb)->sz;
1115 cf_len = len;
1116
1117 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1118
1119 while (len) {
1120 size_t to_copy, room;
1121
1122 pos = (*qcb)->data + (*qcb)->sz;
1123 room = QUIC_CRYPTO_BUF_SZ - (*qcb)->sz;
1124 to_copy = len > room ? room : len;
1125 if (to_copy) {
1126 memcpy(pos, data, to_copy);
1127 /* Increment the total size of this CRYPTO buffers by <to_copy>. */
1128 qel->tx.crypto.sz += to_copy;
1129 (*qcb)->sz += to_copy;
1130 len -= to_copy;
1131 data += to_copy;
1132 }
1133 else {
1134 struct quic_crypto_buf **tmp;
1135
1136 // FIXME: realloc!
1137 tmp = realloc(qel->tx.crypto.bufs,
1138 (*nb_buf + 1) * sizeof *qel->tx.crypto.bufs);
1139 if (tmp) {
1140 qel->tx.crypto.bufs = tmp;
1141 qcb = &qel->tx.crypto.bufs[*nb_buf];
1142 *qcb = pool_alloc(pool_head_quic_crypto_buf);
1143 if (!*qcb) {
1144 TRACE_ERROR("Could not allocate crypto buf", QUIC_EV_CONN_ADDDATA, qc);
1145 goto leave;
1146 }
1147
1148 (*qcb)->sz = 0;
1149 ++*nb_buf;
1150 }
1151 else {
1152 break;
1153 }
1154 }
1155 }
1156
1157 /* Allocate a TX CRYPTO frame only if all the CRYPTO data
1158 * have been buffered.
1159 */
1160 if (!len) {
1161 struct quic_frame *frm;
1162 struct quic_frame *found = NULL;
1163
1164 /* There is at most one CRYPTO frame in this packet number
1165 * space. Let's look for it.
1166 */
1167 list_for_each_entry(frm, &qel->pktns->tx.frms, list) {
1168 if (frm->type != QUIC_FT_CRYPTO)
1169 continue;
1170
1171 /* Found */
1172 found = frm;
1173 break;
1174 }
1175
1176 if (found) {
1177 found->crypto.len += cf_len;
1178 }
1179 else {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01001180 frm = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001181 if (!frm) {
1182 TRACE_ERROR("Could not allocate quic frame", QUIC_EV_CONN_ADDDATA, qc);
1183 goto leave;
1184 }
1185
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001186 frm->crypto.offset = cf_offset;
1187 frm->crypto.len = cf_len;
1188 frm->crypto.qel = qel;
1189 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
1190 }
1191 }
1192 ret = len == 0;
1193 leave:
1194 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1195 return ret;
1196}
1197
1198/* Prepare the emission of CONNECTION_CLOSE with error <err>. All send/receive
1199 * activity for <qc> will be interrupted.
1200 */
1201void quic_set_connection_close(struct quic_conn *qc, const struct quic_err err)
1202{
1203 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1204 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)
1205 goto leave;
1206
1207 TRACE_STATE("setting immediate close", QUIC_EV_CONN_CLOSE, qc);
1208 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
1209 qc->err.code = err.code;
1210 qc->err.app = err.app;
1211 leave:
1212 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1213}
1214
1215/* Set <alert> TLS alert as QUIC CRYPTO_ERROR error */
1216void quic_set_tls_alert(struct quic_conn *qc, int alert)
1217{
1218 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1219
1220 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
1221 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
1222 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
1223 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
1224 }
1225 quic_set_connection_close(qc, quic_err_tls(alert));
1226 qc->flags |= QUIC_FL_CONN_TLS_ALERT;
1227 TRACE_STATE("Alert set", QUIC_EV_CONN_SSLALERT, qc);
1228
1229 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1230}
1231
1232/* Set the application for <qc> QUIC connection.
1233 * Return 1 if succeeded, 0 if not.
1234 */
1235int quic_set_app_ops(struct quic_conn *qc, const unsigned char *alpn, size_t alpn_len)
1236{
1237 if (alpn_len >= 2 && memcmp(alpn, "h3", 2) == 0)
1238 qc->app_ops = &h3_ops;
1239 else if (alpn_len >= 10 && memcmp(alpn, "hq-interop", 10) == 0)
1240 qc->app_ops = &hq_interop_ops;
1241 else
1242 return 0;
1243
1244 return 1;
1245}
1246
1247/* ->add_handshake_data QUIC TLS callback used by the QUIC TLS stack when it
1248 * wants to provide the QUIC layer with CRYPTO data.
1249 * Returns 1 if succeeded, 0 if not.
1250 */
1251int ha_quic_add_handshake_data(SSL *ssl, enum ssl_encryption_level_t level,
1252 const uint8_t *data, size_t len)
1253{
1254 struct quic_conn *qc;
1255 enum quic_tls_enc_level tel;
1256 struct quic_enc_level *qel;
1257 int ret = 0;
1258
1259 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1260 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1261
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01001262 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
1263 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
1264 goto out;
1265 }
1266
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001267 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
1268 TRACE_PROTO("CC required", QUIC_EV_CONN_ADDDATA, qc);
1269 goto out;
1270 }
1271
1272 tel = ssl_to_quic_enc_level(level);
1273 if (tel == -1) {
1274 TRACE_ERROR("Wrong encryption level", QUIC_EV_CONN_ADDDATA, qc);
1275 goto leave;
1276 }
1277
1278 qel = &qc->els[tel];
1279 if (!quic_crypto_data_cpy(qc, qel, data, len)) {
1280 TRACE_ERROR("Could not bufferize", QUIC_EV_CONN_ADDDATA, qc);
1281 goto leave;
1282 }
1283
1284 TRACE_DEVEL("CRYPTO data buffered", QUIC_EV_CONN_ADDDATA,
1285 qc, &level, &len);
1286 out:
1287 ret = 1;
1288 leave:
1289 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1290 return ret;
1291}
1292
1293int ha_quic_flush_flight(SSL *ssl)
1294{
1295 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1296
1297 TRACE_ENTER(QUIC_EV_CONN_FFLIGHT, qc);
1298 TRACE_LEAVE(QUIC_EV_CONN_FFLIGHT, qc);
1299
1300 return 1;
1301}
1302
1303int ha_quic_send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
1304{
1305 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1306
1307 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1308
1309 TRACE_PROTO("Received TLS alert", QUIC_EV_CONN_SSLALERT, qc, &alert, &level);
1310
1311 quic_set_tls_alert(qc, alert);
1312 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1313 return 1;
1314}
1315
1316/* QUIC TLS methods */
1317static SSL_QUIC_METHOD ha_quic_method = {
1318 .set_encryption_secrets = ha_quic_set_encryption_secrets,
1319 .add_handshake_data = ha_quic_add_handshake_data,
1320 .flush_flight = ha_quic_flush_flight,
1321 .send_alert = ha_quic_send_alert,
1322};
1323
1324/* Initialize the TLS context of a listener with <bind_conf> as configuration.
1325 * Returns an error count.
1326 */
1327int ssl_quic_initial_ctx(struct bind_conf *bind_conf)
1328{
1329 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
1330 int cfgerr = 0;
1331
1332 long options =
1333 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1334 SSL_OP_SINGLE_ECDH_USE |
1335 SSL_OP_CIPHER_SERVER_PREFERENCE;
1336 SSL_CTX *ctx;
1337
1338 ctx = SSL_CTX_new(TLS_server_method());
1339 bind_conf->initial_ctx = ctx;
1340
1341 SSL_CTX_set_options(ctx, options);
1342 SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
1343 SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
1344 SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
1345
1346#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1347# if defined(HAVE_SSL_CLIENT_HELLO_CB)
1348# if defined(SSL_OP_NO_ANTI_REPLAY)
1349 if (bind_conf->ssl_conf.early_data) {
1350 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
1351 SSL_CTX_set_max_early_data(ctx, 0xffffffff);
1352 }
1353# endif /* !SSL_OP_NO_ANTI_REPLAY */
1354 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
1355 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
1356# else /* ! HAVE_SSL_CLIENT_HELLO_CB */
1357 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
1358# endif
1359 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
1360#endif
1361 SSL_CTX_set_quic_method(ctx, &ha_quic_method);
1362
1363 return cfgerr;
1364}
1365
1366/* Decode an expected packet number from <truncated_on> its truncated value,
1367 * depending on <largest_pn> the largest received packet number, and <pn_nbits>
1368 * the number of bits used to encode this packet number (its length in bytes * 8).
1369 * See https://quicwg.org/base-drafts/draft-ietf-quic-transport.html#packet-encoding
1370 */
1371static uint64_t decode_packet_number(uint64_t largest_pn,
1372 uint32_t truncated_pn, unsigned int pn_nbits)
1373{
1374 uint64_t expected_pn = largest_pn + 1;
1375 uint64_t pn_win = (uint64_t)1 << pn_nbits;
1376 uint64_t pn_hwin = pn_win / 2;
1377 uint64_t pn_mask = pn_win - 1;
1378 uint64_t candidate_pn;
1379
1380
1381 candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
1382 /* Note that <pn_win> > <pn_hwin>. */
1383 if (candidate_pn < QUIC_MAX_PACKET_NUM - pn_win &&
1384 candidate_pn + pn_hwin <= expected_pn)
1385 return candidate_pn + pn_win;
1386
1387 if (candidate_pn > expected_pn + pn_hwin && candidate_pn >= pn_win)
1388 return candidate_pn - pn_win;
1389
1390 return candidate_pn;
1391}
1392
1393/* Remove the header protection of <pkt> QUIC packet using <tls_ctx> as QUIC TLS
1394 * cryptographic context.
1395 * <largest_pn> is the largest received packet number and <pn> the address of
1396 * the packet number field for this packet with <byte0> address of its first byte.
1397 * <end> points to one byte past the end of this packet.
1398 * Returns 1 if succeeded, 0 if not.
1399 */
1400static int qc_do_rm_hp(struct quic_conn *qc,
1401 struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx,
1402 int64_t largest_pn, unsigned char *pn, unsigned char *byte0)
1403{
1404 int ret, i, pnlen;
1405 uint64_t packet_number;
1406 uint32_t truncated_pn = 0;
1407 unsigned char mask[5] = {0};
1408 unsigned char *sample;
1409 EVP_CIPHER_CTX *cctx = NULL;
1410
1411 TRACE_ENTER(QUIC_EV_CONN_RMHP, qc);
1412
1413 ret = 0;
1414
1415 /* Check there is enough data in this packet. */
1416 if (pkt->len - (pn - byte0) < QUIC_PACKET_PN_MAXLEN + sizeof mask) {
1417 TRACE_PROTO("too short packet", QUIC_EV_CONN_RMHP, qc, pkt);
1418 goto leave;
1419 }
1420
1421 cctx = EVP_CIPHER_CTX_new();
1422 if (!cctx) {
1423 TRACE_ERROR("memory allocation failed", QUIC_EV_CONN_RMHP, qc, pkt);
1424 goto leave;
1425 }
1426
1427 sample = pn + QUIC_PACKET_PN_MAXLEN;
1428
1429 if (!quic_tls_aes_decrypt(mask, sample, sizeof mask, tls_ctx->rx.hp_ctx)) {
1430 TRACE_ERROR("HP removing failed", QUIC_EV_CONN_RMHP, qc, pkt);
1431 goto leave;
1432 }
1433
1434 *byte0 ^= mask[0] & (*byte0 & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
1435 pnlen = (*byte0 & QUIC_PACKET_PNL_BITMASK) + 1;
1436 for (i = 0; i < pnlen; i++) {
1437 pn[i] ^= mask[i + 1];
1438 truncated_pn = (truncated_pn << 8) | pn[i];
1439 }
1440
1441 packet_number = decode_packet_number(largest_pn, truncated_pn, pnlen * 8);
1442 /* Store remaining information for this unprotected header */
1443 pkt->pn = packet_number;
1444 pkt->pnl = pnlen;
1445
1446 ret = 1;
1447 leave:
1448 if (cctx)
1449 EVP_CIPHER_CTX_free(cctx);
1450 TRACE_LEAVE(QUIC_EV_CONN_RMHP, qc);
1451 return ret;
1452}
1453
1454/* Encrypt the payload of a QUIC packet with <pn> as number found at <payload>
1455 * address, with <payload_len> as payload length, <aad> as address of
1456 * the ADD and <aad_len> as AAD length depending on the <tls_ctx> QUIC TLS
1457 * context.
1458 * Returns 1 if succeeded, 0 if not.
1459 */
1460static int quic_packet_encrypt(unsigned char *payload, size_t payload_len,
1461 unsigned char *aad, size_t aad_len, uint64_t pn,
1462 struct quic_tls_ctx *tls_ctx, struct quic_conn *qc)
1463{
1464 int ret = 0;
1465 unsigned char iv[QUIC_TLS_IV_LEN];
1466 unsigned char *tx_iv = tls_ctx->tx.iv;
1467 size_t tx_iv_sz = tls_ctx->tx.ivlen;
1468 struct enc_debug_info edi;
1469
1470 TRACE_ENTER(QUIC_EV_CONN_ENCPKT, qc);
1471
1472 if (!quic_aead_iv_build(iv, sizeof iv, tx_iv, tx_iv_sz, pn)) {
1473 TRACE_ERROR("AEAD IV building for encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1474 goto err;
1475 }
1476
1477 if (!quic_tls_encrypt(payload, payload_len, aad, aad_len,
1478 tls_ctx->tx.ctx, tls_ctx->tx.aead, tls_ctx->tx.key, iv)) {
1479 TRACE_ERROR("QUIC packet encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1480 goto err;
1481 }
1482
1483 ret = 1;
1484 leave:
1485 TRACE_LEAVE(QUIC_EV_CONN_ENCPKT, qc);
1486 return ret;
1487
1488 err:
1489 enc_debug_info_init(&edi, payload, payload_len, aad, aad_len, pn);
1490 goto leave;
1491}
1492
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001493/* Decrypt <pkt> packet using encryption level <qel> for <qc> connection.
1494 * Decryption is done in place in packet buffer.
1495 *
Ilya Shipitsin5fa29b82022-12-07 09:46:19 +05001496 * Returns 1 on success else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001497 */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001498static int qc_pkt_decrypt(struct quic_conn *qc, struct quic_enc_level *qel,
1499 struct quic_rx_packet *pkt)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001500{
1501 int ret, kp_changed;
1502 unsigned char iv[QUIC_TLS_IV_LEN];
1503 struct quic_tls_ctx *tls_ctx = &qel->tls_ctx;
1504 EVP_CIPHER_CTX *rx_ctx = tls_ctx->rx.ctx;
1505 unsigned char *rx_iv = tls_ctx->rx.iv;
1506 size_t rx_iv_sz = tls_ctx->rx.ivlen;
1507 unsigned char *rx_key = tls_ctx->rx.key;
1508
1509 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
1510
1511 ret = 0;
1512 kp_changed = 0;
1513
1514 if (pkt->type == QUIC_PACKET_TYPE_SHORT) {
1515 /* The two tested bits are not at the same position,
1516 * this is why they are first both inversed.
1517 */
1518 if (!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT) ^ !(tls_ctx->flags & QUIC_FL_TLS_KP_BIT_SET)) {
1519 if (pkt->pn < tls_ctx->rx.pn) {
1520 /* The lowest packet number of a previous key phase
1521 * cannot be null if it really stores previous key phase
1522 * secrets.
1523 */
1524 // TODO: check if BUG_ON() more suitable
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001525 if (!qc->ku.prv_rx.pn) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001526 TRACE_ERROR("null previous packet number", QUIC_EV_CONN_RXPKT, qc);
1527 goto leave;
1528 }
1529
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001530 rx_ctx = qc->ku.prv_rx.ctx;
1531 rx_iv = qc->ku.prv_rx.iv;
1532 rx_key = qc->ku.prv_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001533 }
1534 else if (pkt->pn > qel->pktns->rx.largest_pn) {
1535 /* Next key phase */
1536 kp_changed = 1;
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001537 rx_ctx = qc->ku.nxt_rx.ctx;
1538 rx_iv = qc->ku.nxt_rx.iv;
1539 rx_key = qc->ku.nxt_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001540 }
1541 }
1542 }
1543
1544 if (!quic_aead_iv_build(iv, sizeof iv, rx_iv, rx_iv_sz, pkt->pn)) {
1545 TRACE_ERROR("quic_aead_iv_build() failed", QUIC_EV_CONN_RXPKT, qc);
1546 goto leave;
1547 }
1548
1549 ret = quic_tls_decrypt(pkt->data + pkt->aad_len, pkt->len - pkt->aad_len,
1550 pkt->data, pkt->aad_len,
1551 rx_ctx, tls_ctx->rx.aead, rx_key, iv);
1552 if (!ret) {
1553 TRACE_ERROR("quic_tls_decrypt() failed", QUIC_EV_CONN_RXPKT, qc);
1554 goto leave;
1555 }
1556
1557 /* Update the keys only if the packet decryption succeeded. */
1558 if (kp_changed) {
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001559 quic_tls_rotate_keys(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001560 /* Toggle the Key Phase bit */
1561 tls_ctx->flags ^= QUIC_FL_TLS_KP_BIT_SET;
1562 /* Store the lowest packet number received for the current key phase */
1563 tls_ctx->rx.pn = pkt->pn;
1564 /* Prepare the next key update */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001565 if (!quic_tls_key_update(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001566 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_RXPKT, qc);
1567 goto leave;
1568 }
1569 }
1570
1571 /* Update the packet length (required to parse the frames). */
1572 pkt->len -= QUIC_TLS_TAG_LEN;
1573 ret = 1;
1574 leave:
1575 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
1576 return ret;
1577}
1578
1579
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001580/* Release <frm> frame and mark its copies as acknowledged */
1581void qc_release_frm(struct quic_conn *qc, struct quic_frame *frm)
1582{
1583 uint64_t pn;
1584 struct quic_frame *origin, *f, *tmp;
1585
1586 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1587
1588 /* Identify this frame: a frame copy or one of its copies */
1589 origin = frm->origin ? frm->origin : frm;
1590 /* Ensure the source of the copies is flagged as acked, <frm> being
1591 * possibly a copy of <origin>
1592 */
1593 origin->flags |= QUIC_FL_TX_FRAME_ACKED;
1594 /* Mark all the copy of <origin> as acknowledged. We must
1595 * not release the packets (releasing the frames) at this time as
1596 * they are possibly also to be acknowledged alongside the
1597 * the current one.
1598 */
1599 list_for_each_entry_safe(f, tmp, &origin->reflist, ref) {
1600 if (f->pkt) {
1601 f->flags |= QUIC_FL_TX_FRAME_ACKED;
1602 f->origin = NULL;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001603 LIST_DEL_INIT(&f->ref);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001604 pn = f->pkt->pn_node.key;
1605 TRACE_DEVEL("mark frame as acked from packet",
1606 QUIC_EV_CONN_PRSAFRM, qc, f, &pn);
1607 }
1608 else {
1609 TRACE_DEVEL("freeing unsent frame",
1610 QUIC_EV_CONN_PRSAFRM, qc, f);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001611 LIST_DEL_INIT(&f->ref);
1612 qc_frm_free(&f);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001613 }
1614 }
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001615 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001616 pn = frm->pkt->pn_node.key;
1617 quic_tx_packet_refdec(frm->pkt);
1618 TRACE_DEVEL("freeing frame from packet",
1619 QUIC_EV_CONN_PRSAFRM, qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001620 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001621
1622 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1623}
1624
1625/* Schedule a CONNECTION_CLOSE emission on <qc> if the MUX has been released
1626 * and all STREAM data are acknowledged. The MUX is responsible to have set
1627 * <qc.err> before as it is reused for the CONNECTION_CLOSE frame.
1628 *
1629 * TODO this should also be called on lost packet detection
1630 */
1631void qc_check_close_on_released_mux(struct quic_conn *qc)
1632{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001633 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1634
1635 if (qc->mux_state == QC_MUX_RELEASED && eb_is_empty(&qc->streams_by_id)) {
1636 /* Reuse errcode which should have been previously set by the MUX on release. */
1637 quic_set_connection_close(qc, qc->err);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02001638 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001639 }
1640
1641 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1642}
1643
1644/* Remove from <stream> the acknowledged frames.
1645 *
1646 * Returns 1 if at least one frame was removed else 0.
1647 */
1648static int quic_stream_try_to_consume(struct quic_conn *qc,
1649 struct qc_stream_desc *stream)
1650{
1651 int ret;
1652 struct eb64_node *frm_node;
1653
1654 TRACE_ENTER(QUIC_EV_CONN_ACKSTRM, qc);
1655
1656 ret = 0;
1657 frm_node = eb64_first(&stream->acked_frms);
1658 while (frm_node) {
1659 struct quic_stream *strm;
1660 struct quic_frame *frm;
1661 size_t offset, len;
1662
1663 strm = eb64_entry(frm_node, struct quic_stream, offset);
1664 offset = strm->offset.key;
1665 len = strm->len;
1666
1667 if (offset > stream->ack_offset)
1668 break;
1669
1670 if (qc_stream_desc_ack(&stream, offset, len)) {
1671 /* cf. next comment : frame may be freed at this stage. */
1672 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1673 qc, stream ? strm : NULL, stream);
1674 ret = 1;
1675 }
1676
1677 /* If stream is NULL after qc_stream_desc_ack(), it means frame
1678 * has been freed. with the stream frames tree. Nothing to do
1679 * anymore in here.
1680 */
1681 if (!stream) {
1682 qc_check_close_on_released_mux(qc);
1683 ret = 1;
1684 goto leave;
1685 }
1686
1687 frm_node = eb64_next(frm_node);
1688 eb64_delete(&strm->offset);
1689
1690 frm = container_of(strm, struct quic_frame, stream);
1691 qc_release_frm(qc, frm);
1692 }
1693
1694 leave:
1695 TRACE_LEAVE(QUIC_EV_CONN_ACKSTRM, qc);
1696 return ret;
1697}
1698
1699/* Treat <frm> frame whose packet it is attached to has just been acknowledged. */
1700static inline void qc_treat_acked_tx_frm(struct quic_conn *qc,
1701 struct quic_frame *frm)
1702{
1703 int stream_acked;
1704
1705 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc, frm);
1706
1707 stream_acked = 0;
1708 switch (frm->type) {
1709 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1710 {
1711 struct quic_stream *strm_frm = &frm->stream;
1712 struct eb64_node *node = NULL;
1713 struct qc_stream_desc *stream = NULL;
1714 const size_t offset = strm_frm->offset.key;
1715 const size_t len = strm_frm->len;
1716
1717 /* do not use strm_frm->stream as the qc_stream_desc instance
1718 * might be freed at this stage. Use the id to do a proper
1719 * lookup.
1720 *
1721 * TODO if lookup operation impact on the perf is noticeable,
1722 * implement a refcount on qc_stream_desc instances.
1723 */
1724 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1725 if (!node) {
1726 TRACE_DEVEL("acked stream for released stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm);
1727 qc_release_frm(qc, frm);
1728 /* early return */
1729 goto leave;
1730 }
1731 stream = eb64_entry(node, struct qc_stream_desc, by_id);
1732
1733 TRACE_DEVEL("acked stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm, stream);
1734 if (offset <= stream->ack_offset) {
1735 if (qc_stream_desc_ack(&stream, offset, len)) {
1736 stream_acked = 1;
1737 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1738 qc, strm_frm, stream);
1739 }
1740
1741 if (!stream) {
1742 /* no need to continue if stream freed. */
1743 TRACE_DEVEL("stream released and freed", QUIC_EV_CONN_ACKSTRM, qc);
1744 qc_release_frm(qc, frm);
1745 qc_check_close_on_released_mux(qc);
1746 break;
1747 }
1748
1749 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1750 qc, strm_frm, stream);
1751 qc_release_frm(qc, frm);
1752 }
1753 else {
1754 eb64_insert(&stream->acked_frms, &strm_frm->offset);
1755 }
1756
1757 stream_acked |= quic_stream_try_to_consume(qc, stream);
1758 }
1759 break;
1760 default:
1761 qc_release_frm(qc, frm);
1762 }
1763
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02001764 if (stream_acked) {
1765 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
1766 tasklet_wakeup(qc->subs->tasklet);
1767 qc->subs->events &= ~SUB_RETRY_SEND;
1768 if (!qc->subs->events)
1769 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001770 }
1771 }
1772 leave:
1773 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1774}
1775
1776/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1777 * deallocating them, and their TX frames.
1778 * Returns the last node reached to be used for the next range.
1779 * May be NULL if <largest> node could not be found.
1780 */
1781static inline struct eb64_node *qc_ackrng_pkts(struct quic_conn *qc,
1782 struct eb_root *pkts,
1783 unsigned int *pkt_flags,
1784 struct list *newly_acked_pkts,
1785 struct eb64_node *largest_node,
1786 uint64_t largest, uint64_t smallest)
1787{
1788 struct eb64_node *node;
1789 struct quic_tx_packet *pkt;
1790
1791 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1792
1793 node = largest_node ? largest_node : eb64_lookup_le(pkts, largest);
1794 while (node && node->key >= smallest) {
1795 struct quic_frame *frm, *frmbak;
1796
1797 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
1798 *pkt_flags |= pkt->flags;
1799 LIST_INSERT(newly_acked_pkts, &pkt->list);
1800 TRACE_DEVEL("Removing packet #", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
1801 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1802 qc_treat_acked_tx_frm(qc, frm);
Frédéric Lécaille814645f2022-11-18 18:15:28 +01001803 /* If there are others packet in the same datagram <pkt> is attached to,
1804 * detach the previous one and the next one from <pkt>.
1805 */
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01001806 quic_tx_packet_dgram_detach(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001807 node = eb64_prev(node);
1808 eb64_delete(&pkt->pn_node);
1809 }
1810
1811 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1812 return node;
1813}
1814
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001815/* Remove all frames from <pkt_frm_list> and reinsert them in the same order
1816 * they have been sent into <pktns_frm_list>. The loss counter of each frame is
1817 * incremented and checked if it does not exceed retransmission limit.
1818 *
1819 * Returns 1 on success, 0 if a frame loss limit is exceeded. A
1820 * CONNECTION_CLOSE is scheduled in this case.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001821 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001822static inline int qc_requeue_nacked_pkt_tx_frms(struct quic_conn *qc,
1823 struct quic_tx_packet *pkt,
1824 struct list *pktns_frm_list)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001825{
1826 struct quic_frame *frm, *frmbak;
1827 struct list tmp = LIST_HEAD_INIT(tmp);
1828 struct list *pkt_frm_list = &pkt->frms;
1829 uint64_t pn = pkt->pn_node.key;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001830 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001831
1832 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1833
1834 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
1835 /* First remove this frame from the packet it was attached to */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001836 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001837 quic_tx_packet_refdec(pkt);
1838 /* At this time, this frame is not freed but removed from its packet */
1839 frm->pkt = NULL;
1840 /* Remove any reference to this frame */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001841 qc_frm_unref(frm, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001842 switch (frm->type) {
1843 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1844 {
1845 struct quic_stream *strm_frm = &frm->stream;
1846 struct eb64_node *node = NULL;
1847 struct qc_stream_desc *stream_desc;
1848
1849 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1850 if (!node) {
1851 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
1852 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1853 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001854 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001855 continue;
1856 }
1857
1858 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
1859 /* Do not resend this frame if in the "already acked range" */
1860 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
1861 TRACE_DEVEL("ignored frame in already acked range",
1862 QUIC_EV_CONN_PRSAFRM, qc, frm);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001863 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001864 continue;
1865 }
1866 else if (strm_frm->offset.key < stream_desc->ack_offset) {
1867 strm_frm->offset.key = stream_desc->ack_offset;
1868 TRACE_DEVEL("updated partially acked frame",
1869 QUIC_EV_CONN_PRSAFRM, qc, frm);
1870 }
1871 break;
1872 }
1873
1874 default:
1875 break;
1876 }
1877
1878 /* Do not resend probing packet with old data */
1879 if (pkt->flags & QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA) {
1880 TRACE_DEVEL("ignored frame with old data from packet", QUIC_EV_CONN_PRSAFRM,
1881 qc, frm, &pn);
1882 if (frm->origin)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001883 LIST_DEL_INIT(&frm->ref);
1884 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001885 continue;
1886 }
1887
1888 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
1889 TRACE_DEVEL("already acked frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
1890 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1891 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001892 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001893 }
1894 else {
Amaury Denoyelle24d5b722023-01-31 11:44:50 +01001895 if (++frm->loss_count >= global.tune.quic_max_frame_loss) {
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001896 TRACE_ERROR("retransmission limit reached, closing the connection", QUIC_EV_CONN_PRSAFRM, qc);
1897 quic_set_connection_close(qc, quic_err_transport(QC_ERR_INTERNAL_ERROR));
1898 close = 1;
1899 }
1900
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001901 if (QUIC_FT_STREAM_8 <= frm->type && frm->type <= QUIC_FT_STREAM_F) {
1902 /* Mark this STREAM frame as lost. A look up their stream descriptor
1903 * will be performed to check the stream is not consumed or released.
1904 */
1905 frm->flags |= QUIC_FL_TX_FRAME_LOST;
1906 }
1907 LIST_APPEND(&tmp, &frm->list);
1908 TRACE_DEVEL("frame requeued", QUIC_EV_CONN_PRSAFRM, qc, frm);
1909 }
1910 }
1911
1912 LIST_SPLICE(pktns_frm_list, &tmp);
1913
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001914 end:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001915 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001916 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001917}
1918
1919/* Free <pkt> TX packet and its attached frames.
1920 * This is the responsibility of the caller to remove this packet of
1921 * any data structure it was possibly attached to.
1922 */
1923static inline void free_quic_tx_packet(struct quic_conn *qc,
1924 struct quic_tx_packet *pkt)
1925{
1926 struct quic_frame *frm, *frmbak;
1927
1928 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1929
1930 if (!pkt)
1931 goto leave;
1932
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001933 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1934 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001935 pool_free(pool_head_quic_tx_packet, pkt);
1936
1937 leave:
1938 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1939}
1940
1941/* Free the TX packets of <pkts> list */
1942static inline void free_quic_tx_pkts(struct quic_conn *qc, struct list *pkts)
1943{
1944 struct quic_tx_packet *pkt, *tmp;
1945
1946 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1947
1948 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1949 LIST_DELETE(&pkt->list);
1950 eb64_delete(&pkt->pn_node);
1951 free_quic_tx_packet(qc, pkt);
1952 }
1953
1954 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1955}
1956
1957/* Remove already sent ranges of acknowledged packet numbers from
1958 * <pktns> packet number space tree below <largest_acked_pn> possibly
1959 * updating the range which contains <largest_acked_pn>.
1960 * Never fails.
1961 */
1962static void qc_treat_ack_of_ack(struct quic_conn *qc,
1963 struct quic_pktns *pktns,
1964 int64_t largest_acked_pn)
1965{
1966 struct eb64_node *ar, *next_ar;
1967 struct quic_arngs *arngs = &pktns->rx.arngs;
1968
1969 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1970
1971 ar = eb64_first(&arngs->root);
1972 while (ar) {
1973 struct quic_arng_node *ar_node;
1974
1975 next_ar = eb64_next(ar);
1976 ar_node = eb64_entry(ar, struct quic_arng_node, first);
1977
1978 if ((int64_t)ar_node->first.key > largest_acked_pn) {
1979 TRACE_DEVEL("first.key > largest", QUIC_EV_CONN_PRSAFRM, qc);
1980 break;
1981 }
1982
1983 if (largest_acked_pn < ar_node->last) {
1984 eb64_delete(ar);
1985 ar_node->first.key = largest_acked_pn + 1;
1986 eb64_insert(&arngs->root, ar);
1987 break;
1988 }
1989
1990 eb64_delete(ar);
1991 pool_free(pool_head_quic_arng, ar_node);
1992 arngs->sz--;
1993 ar = next_ar;
1994 }
1995
1996 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1997}
1998
1999/* Send a packet ack event nofication for each newly acked packet of
2000 * <newly_acked_pkts> list and free them.
2001 * Always succeeds.
2002 */
2003static inline void qc_treat_newly_acked_pkts(struct quic_conn *qc,
2004 struct list *newly_acked_pkts)
2005{
2006 struct quic_tx_packet *pkt, *tmp;
2007 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
2008
2009 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2010
2011 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
2012 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2013 qc->path->prep_in_flight -= pkt->in_flight_len;
2014 qc->path->in_flight -= pkt->in_flight_len;
2015 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2016 qc->path->ifae_pkts--;
2017 /* If this packet contained an ACK frame, proceed to the
2018 * acknowledging of range of acks from the largest acknowledged
2019 * packet number which was sent in an ACK frame by this packet.
2020 */
2021 if (pkt->largest_acked_pn != -1)
2022 qc_treat_ack_of_ack(qc, pkt->pktns, pkt->largest_acked_pn);
2023 ev.ack.acked = pkt->in_flight_len;
2024 ev.ack.time_sent = pkt->time_sent;
2025 quic_cc_event(&qc->path->cc, &ev);
2026 LIST_DELETE(&pkt->list);
2027 eb64_delete(&pkt->pn_node);
2028 quic_tx_packet_refdec(pkt);
2029 }
2030
2031 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2032
2033}
2034
2035/* Release all the frames attached to <pktns> packet number space */
2036static inline void qc_release_pktns_frms(struct quic_conn *qc,
2037 struct quic_pktns *pktns)
2038{
2039 struct quic_frame *frm, *frmbak;
2040
2041 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
2042
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01002043 list_for_each_entry_safe(frm, frmbak, &pktns->tx.frms, list)
2044 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002045
2046 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
2047}
2048
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002049/* Handle <pkts> list of lost packets detected at <now_us> handling their TX
2050 * frames. Send a packet loss event to the congestion controller if in flight
2051 * packet have been lost. Also frees the packet in <pkts> list.
2052 *
2053 * Returns 1 on success else 0 if loss limit has been exceeded. A
2054 * CONNECTION_CLOSE was prepared to close the connection ASAP.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002055 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002056static inline int qc_release_lost_pkts(struct quic_conn *qc,
2057 struct quic_pktns *pktns,
2058 struct list *pkts,
2059 uint64_t now_us)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002060{
2061 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002062 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002063
2064 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2065
2066 if (LIST_ISEMPTY(pkts))
2067 goto leave;
2068
2069 oldest_lost = newest_lost = NULL;
2070 list_for_each_entry_safe(pkt, tmp, pkts, list) {
2071 struct list tmp = LIST_HEAD_INIT(tmp);
2072
2073 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2074 qc->path->prep_in_flight -= pkt->in_flight_len;
2075 qc->path->in_flight -= pkt->in_flight_len;
2076 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2077 qc->path->ifae_pkts--;
2078 /* Treat the frames of this lost packet. */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002079 if (!qc_requeue_nacked_pkt_tx_frms(qc, pkt, &pktns->tx.frms))
2080 close = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002081 LIST_DELETE(&pkt->list);
2082 if (!oldest_lost) {
2083 oldest_lost = newest_lost = pkt;
2084 }
2085 else {
2086 if (newest_lost != oldest_lost)
2087 quic_tx_packet_refdec(newest_lost);
2088 newest_lost = pkt;
2089 }
2090 }
2091
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002092 if (!close) {
2093 if (newest_lost) {
2094 /* Sent a congestion event to the controller */
2095 struct quic_cc_event ev = { };
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002096
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002097 ev.type = QUIC_CC_EVT_LOSS;
2098 ev.loss.time_sent = newest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002099
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002100 quic_cc_event(&qc->path->cc, &ev);
2101 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002102
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002103 /* If an RTT have been already sampled, <rtt_min> has been set.
2104 * We must check if we are experiencing a persistent congestion.
2105 * If this is the case, the congestion controller must re-enter
2106 * slow start state.
2107 */
2108 if (qc->path->loss.rtt_min && newest_lost != oldest_lost) {
2109 unsigned int period = newest_lost->time_sent - oldest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002110
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002111 if (quic_loss_persistent_congestion(&qc->path->loss, period,
2112 now_ms, qc->max_ack_delay))
2113 qc->path->cc.algo->slow_start(&qc->path->cc);
2114 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002115 }
2116
Amaury Denoyelle3a72ba22022-11-14 11:41:34 +01002117 /* <oldest_lost> cannot be NULL at this stage because we have ensured
2118 * that <pkts> list is not empty. Without this, GCC 12.2.0 reports a
2119 * possible overflow on a 0 byte region with O2 optimization.
2120 */
2121 ALREADY_CHECKED(oldest_lost);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002122 quic_tx_packet_refdec(oldest_lost);
2123 if (newest_lost != oldest_lost)
2124 quic_tx_packet_refdec(newest_lost);
2125
2126 leave:
2127 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002128 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002129}
2130
2131/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
2132 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
2133 * if the largest acked packet was newly acked and if there was at least one newly
2134 * acked ack-eliciting packet.
2135 * Return 1, if succeeded, 0 if not.
2136 */
2137static inline int qc_parse_ack_frm(struct quic_conn *qc,
2138 struct quic_frame *frm,
2139 struct quic_enc_level *qel,
2140 unsigned int *rtt_sample,
2141 const unsigned char **pos, const unsigned char *end)
2142{
2143 struct quic_ack *ack = &frm->ack;
2144 uint64_t smallest, largest;
2145 struct eb_root *pkts;
2146 struct eb64_node *largest_node;
2147 unsigned int time_sent, pkt_flags;
2148 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
2149 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2150 int ret = 0;
2151
2152 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2153
2154 if (ack->largest_ack > qel->pktns->tx.next_pn) {
2155 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
2156 qc, NULL, &ack->largest_ack);
2157 goto err;
2158 }
2159
2160 if (ack->first_ack_range > ack->largest_ack) {
2161 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
2162 qc, NULL, &ack->first_ack_range);
2163 goto err;
2164 }
2165
2166 largest = ack->largest_ack;
2167 smallest = largest - ack->first_ack_range;
2168 pkts = &qel->pktns->tx.pkts;
2169 pkt_flags = 0;
2170 largest_node = NULL;
2171 time_sent = 0;
2172
2173 if ((int64_t)ack->largest_ack > qel->pktns->rx.largest_acked_pn) {
2174 largest_node = eb64_lookup(pkts, largest);
2175 if (!largest_node) {
2176 TRACE_DEVEL("Largest acked packet not found",
2177 QUIC_EV_CONN_PRSAFRM, qc);
2178 }
2179 else {
2180 time_sent = eb64_entry(largest_node,
2181 struct quic_tx_packet, pn_node)->time_sent;
2182 }
2183 }
2184
2185 TRACE_PROTO("rcvd ack range", QUIC_EV_CONN_PRSAFRM,
2186 qc, NULL, &largest, &smallest);
2187 do {
2188 uint64_t gap, ack_range;
2189
2190 qc_ackrng_pkts(qc, pkts, &pkt_flags, &newly_acked_pkts,
2191 largest_node, largest, smallest);
2192 if (!ack->ack_range_num--)
2193 break;
2194
2195 if (!quic_dec_int(&gap, pos, end)) {
2196 TRACE_ERROR("quic_dec_int(gap) failed", QUIC_EV_CONN_PRSAFRM, qc);
2197 goto err;
2198 }
2199
2200 if (smallest < gap + 2) {
2201 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
2202 qc, NULL, &gap, &smallest);
2203 goto err;
2204 }
2205
2206 largest = smallest - gap - 2;
2207 if (!quic_dec_int(&ack_range, pos, end)) {
2208 TRACE_ERROR("quic_dec_int(ack_range) failed", QUIC_EV_CONN_PRSAFRM, qc);
2209 goto err;
2210 }
2211
2212 if (largest < ack_range) {
2213 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
2214 qc, NULL, &largest, &ack_range);
2215 goto err;
2216 }
2217
2218 /* Do not use this node anymore. */
2219 largest_node = NULL;
2220 /* Next range */
2221 smallest = largest - ack_range;
2222
2223 TRACE_PROTO("rcvd next ack range", QUIC_EV_CONN_PRSAFRM,
2224 qc, NULL, &largest, &smallest);
2225 } while (1);
2226
2227 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
2228 *rtt_sample = tick_remain(time_sent, now_ms);
2229 qel->pktns->rx.largest_acked_pn = ack->largest_ack;
2230 }
2231
2232 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
2233 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
2234 qc_packet_loss_lookup(qel->pktns, qc, &lost_pkts);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002235 if (!qc_release_lost_pkts(qc, qel->pktns, &lost_pkts, now_ms))
2236 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002237 }
2238 qc_treat_newly_acked_pkts(qc, &newly_acked_pkts);
2239 if (quic_peer_validated_addr(qc))
2240 qc->path->loss.pto_count = 0;
2241 qc_set_timer(qc);
2242 }
2243
2244 ret = 1;
2245 leave:
2246 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2247 return ret;
2248
2249 err:
2250 free_quic_tx_pkts(qc, &newly_acked_pkts);
2251 goto leave;
2252}
2253
2254/* This function gives the detail of the SSL error. It is used only
2255 * if the debug mode and the verbose mode are activated. It dump all
2256 * the SSL error until the stack was empty.
2257 */
2258static forceinline void qc_ssl_dump_errors(struct connection *conn)
2259{
2260 if (unlikely(global.mode & MODE_DEBUG)) {
2261 while (1) {
2262 const char *func = NULL;
2263 unsigned long ret;
2264
2265 ERR_peek_error_func(&func);
2266 ret = ERR_get_error();
2267 if (!ret)
2268 return;
2269
2270 fprintf(stderr, "conn. @%p OpenSSL error[0x%lx] %s: %s\n", conn, ret,
2271 func, ERR_reason_error_string(ret));
2272 }
2273 }
2274}
2275
2276int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx,
2277 const char **str, int *len);
2278
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002279/* Finalize <qc> QUIC connection:
2280 * - initialize the Initial QUIC TLS context for negotiated version,
2281 * - derive the secrets for this context,
2282 * - set them into the TLS stack,
2283 *
2284 * MUST be called after having received the remote transport parameters which
2285 * are parsed when the TLS callback for the ClientHello message is called upon
2286 * SSL_do_handshake() calls, not necessarily at the first time as this TLS
2287 * message may be splitted between packets
2288 * Return 1 if succeeded, 0 if not.
2289 */
2290static int qc_conn_finalize(struct quic_conn *qc, int server)
2291{
2292 int ret = 0;
2293
2294 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
2295
2296 if (qc->flags & QUIC_FL_CONN_FINALIZED)
2297 goto finalized;
2298
2299 if (qc->negotiated_version &&
2300 !qc_new_isecs(qc, &qc->negotiated_ictx, qc->negotiated_version,
2301 qc->odcid.data, qc->odcid.len, server))
2302 goto out;
2303
2304 /* This connection is functional (ready to send/receive) */
2305 qc->flags |= QUIC_FL_CONN_FINALIZED;
2306
2307 finalized:
2308 ret = 1;
2309 out:
2310 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
2311 return ret;
2312}
2313
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002314/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
2315 * from <qel> encryption level with <ctx> as QUIC connection context.
2316 * Remaining parameter are there for debugging purposes.
2317 * Return 1 if succeeded, 0 if not.
2318 */
2319static inline int qc_provide_cdata(struct quic_enc_level *el,
2320 struct ssl_sock_ctx *ctx,
2321 const unsigned char *data, size_t len,
2322 struct quic_rx_packet *pkt,
2323 struct quic_rx_crypto_frm *cf)
2324{
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002325#ifdef DEBUG_STRICT
2326 enum ncb_ret ncb_ret;
2327#endif
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002328 int ssl_err, state;
2329 struct quic_conn *qc;
2330 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002331 struct ncbuf *ncbuf = &el->cstream->rx.ncbuf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002332
2333 ssl_err = SSL_ERROR_NONE;
2334 qc = ctx->qc;
2335
2336 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, qc);
2337
2338 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
2339 TRACE_ERROR("SSL_provide_quic_data() error",
2340 QUIC_EV_CONN_SSLDATA, qc, pkt, cf, ctx->ssl);
2341 goto leave;
2342 }
2343
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002344 TRACE_PROTO("in order CRYPTO data",
2345 QUIC_EV_CONN_SSLDATA, qc, NULL, cf, ctx->ssl);
2346
2347 state = qc->state;
2348 if (state < QUIC_HS_ST_COMPLETE) {
2349 ssl_err = SSL_do_handshake(ctx->ssl);
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002350
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01002351 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
2352 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
2353 goto leave;
2354 }
2355
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002356 /* Finalize the connection as soon as possible if the peer transport parameters
2357 * have been received. This may be useful to send packets even if this
2358 * handshake fails.
2359 */
2360 if ((qc->flags & QUIC_FL_CONN_TX_TP_RECEIVED) && !qc_conn_finalize(qc, 1)) {
2361 TRACE_ERROR("connection finalization failed", QUIC_EV_CONN_IO_CB, qc, &state);
2362 goto leave;
2363 }
2364
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002365 if (ssl_err != 1) {
2366 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2367 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2368 TRACE_PROTO("SSL handshake in progress",
2369 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2370 goto out;
2371 }
2372
2373 /* TODO: Should close the connection asap */
2374 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2375 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2376 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2377 HA_ATOMIC_INC(&qc->prx_counters->hdshk_fail);
2378 }
2379 TRACE_ERROR("SSL handshake error", QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2380 qc_ssl_dump_errors(ctx->conn);
2381 ERR_clear_error();
2382 goto leave;
2383 }
2384
2385 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_IO_CB, qc, &state);
2386
2387 /* Check the alpn could be negotiated */
2388 if (!qc->app_ops) {
2389 TRACE_ERROR("No negotiated ALPN", QUIC_EV_CONN_IO_CB, qc, &state);
2390 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
2391 goto leave;
2392 }
2393
2394 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2395 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_IO_CB, qc, &state);
2396 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2397 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2398 }
2399 /* I/O callback switch */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002400 qc->wait_event.tasklet->process = quic_conn_app_io_cb;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002401 if (qc_is_listener(ctx->qc)) {
2402 qc->state = QUIC_HS_ST_CONFIRMED;
2403 /* The connection is ready to be accepted. */
2404 quic_accept_push_qc(qc);
2405 }
2406 else {
2407 qc->state = QUIC_HS_ST_COMPLETE;
2408 }
2409
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02002410 /* Prepare the next key update */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002411 if (!quic_tls_key_update(qc)) {
2412 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_IO_CB, qc);
2413 goto leave;
2414 }
2415 } else {
2416 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
2417 if (ssl_err != 1) {
2418 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2419 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2420 TRACE_PROTO("SSL post handshake in progress",
2421 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2422 goto out;
2423 }
2424
2425 TRACE_ERROR("SSL post handshake error",
2426 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2427 goto leave;
2428 }
2429
2430 TRACE_STATE("SSL post handshake succeeded", QUIC_EV_CONN_IO_CB, qc, &state);
2431 }
2432
2433 out:
2434 ret = 1;
2435 leave:
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002436 /* The CRYPTO data are consumed even in case of an error to release
2437 * the memory asap.
2438 */
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002439 if (!ncb_is_null(ncbuf)) {
2440#ifdef DEBUG_STRICT
2441 ncb_ret = ncb_advance(ncbuf, len);
2442 /* ncb_advance() must always succeed. This is guaranteed as
2443 * this is only done inside a data block. If false, this will
2444 * lead to handshake failure with quic_enc_level offset shifted
2445 * from buffer data.
2446 */
2447 BUG_ON(ncb_ret != NCB_RET_OK);
2448#else
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002449 ncb_advance(ncbuf, len);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002450#endif
2451 }
2452
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002453 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, qc);
2454 return ret;
2455}
2456
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002457/* Parse a STREAM frame <strm_frm> received in <pkt> packet for <qc>
2458 * connection. <fin> is true if FIN bit is set on frame type.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002459 *
2460 * Return 1 on success. On error, 0 is returned. In this case, the packet
2461 * containing the frame must not be acknowledged.
2462 */
2463static inline int qc_handle_strm_frm(struct quic_rx_packet *pkt,
2464 struct quic_stream *strm_frm,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002465 struct quic_conn *qc, char fin)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002466{
2467 int ret;
2468
2469 /* RFC9000 13.1. Packet Processing
2470 *
2471 * A packet MUST NOT be acknowledged until packet protection has been
2472 * successfully removed and all frames contained in the packet have
2473 * been processed. For STREAM frames, this means the data has been
2474 * enqueued in preparation to be received by the application protocol,
2475 * but it does not require that data be delivered and consumed.
2476 */
2477 TRACE_ENTER(QUIC_EV_CONN_PRSFRM, qc);
2478
2479 ret = qcc_recv(qc->qcc, strm_frm->id, strm_frm->len,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002480 strm_frm->offset.key, fin, (char *)strm_frm->data);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002481
2482 /* frame rejected - packet must not be acknowledeged */
2483 TRACE_LEAVE(QUIC_EV_CONN_PRSFRM, qc);
2484 return !ret;
2485}
2486
2487/* Duplicate all frames from <pkt_frm_list> list into <out_frm_list> list
2488 * for <qc> QUIC connection.
2489 * This is a best effort function which never fails even if no memory could be
2490 * allocated to duplicate these frames.
2491 */
2492static void qc_dup_pkt_frms(struct quic_conn *qc,
2493 struct list *pkt_frm_list, struct list *out_frm_list)
2494{
2495 struct quic_frame *frm, *frmbak;
2496 struct list tmp = LIST_HEAD_INIT(tmp);
2497
2498 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2499
2500 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
2501 struct quic_frame *dup_frm, *origin;
2502
2503 switch (frm->type) {
2504 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2505 {
2506 struct quic_stream *strm_frm = &frm->stream;
2507 struct eb64_node *node = NULL;
2508 struct qc_stream_desc *stream_desc;
2509
2510 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
2511 if (!node) {
2512 TRACE_DEVEL("ignored frame for a released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
2513 continue;
2514 }
2515
2516 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
2517 /* Do not resend this frame if in the "already acked range" */
2518 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
2519 TRACE_DEVEL("ignored frame in already acked range",
2520 QUIC_EV_CONN_PRSAFRM, qc, frm);
2521 continue;
2522 }
2523 else if (strm_frm->offset.key < stream_desc->ack_offset) {
2524 strm_frm->offset.key = stream_desc->ack_offset;
2525 TRACE_DEVEL("updated partially acked frame",
2526 QUIC_EV_CONN_PRSAFRM, qc, frm);
2527 }
2528 break;
2529 }
2530
2531 default:
2532 break;
2533 }
2534
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002535 /* If <frm> is already a copy of another frame, we must take
2536 * its original frame as source for the copy.
2537 */
2538 origin = frm->origin ? frm->origin : frm;
2539 dup_frm = qc_frm_dup(origin);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002540 if (!dup_frm) {
2541 TRACE_ERROR("could not duplicate frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2542 break;
2543 }
2544
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002545 TRACE_DEVEL("built probing frame", QUIC_EV_CONN_PRSAFRM, qc, origin);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002546 if (origin->pkt) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002547 TRACE_DEVEL("duplicated from packet", QUIC_EV_CONN_PRSAFRM,
2548 qc, NULL, &origin->pkt->pn_node.key);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002549 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002550 else {
2551 /* <origin> is a frame which was sent from a packet detected as lost. */
2552 TRACE_DEVEL("duplicated from lost packet", QUIC_EV_CONN_PRSAFRM, qc);
2553 }
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002554
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002555 LIST_APPEND(&tmp, &dup_frm->list);
2556 }
2557
2558 LIST_SPLICE(out_frm_list, &tmp);
2559
2560 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2561}
2562
2563/* Prepare a fast retransmission from <qel> encryption level */
2564static void qc_prep_fast_retrans(struct quic_conn *qc,
2565 struct quic_enc_level *qel,
2566 struct list *frms1, struct list *frms2)
2567{
2568 struct eb_root *pkts = &qel->pktns->tx.pkts;
2569 struct list *frms = frms1;
2570 struct eb64_node *node;
2571 struct quic_tx_packet *pkt;
2572
2573 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2574
2575 BUG_ON(frms1 == frms2);
2576
2577 pkt = NULL;
2578 node = eb64_first(pkts);
2579 start:
2580 while (node) {
2581 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
2582 node = eb64_next(node);
2583 /* Skip the empty and coalesced packets */
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002584 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
2585 "--> pn=%llu (%d %d)", (ull)pkt->pn_node.key,
2586 LIST_ISEMPTY(&pkt->frms), !!(pkt->flags & QUIC_FL_TX_PACKET_COALESCED));
Frédéric Lécaille055e8262023-01-31 10:10:06 +01002587 if (!LIST_ISEMPTY(&pkt->frms))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002588 break;
2589 }
2590
2591 if (!pkt)
2592 goto leave;
2593
2594 /* When building a packet from another one, the field which may increase the
2595 * packet size is the packet number. And the maximum increase is 4 bytes.
2596 */
2597 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2598 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
2599 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2600 goto leave;
2601 }
2602
2603 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_SPPKTS, qc, pkt);
2604 qc_dup_pkt_frms(qc, &pkt->frms, frms);
2605 if (frms == frms1 && frms2) {
2606 frms = frms2;
2607 goto start;
2608 }
2609 leave:
2610 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
2611}
2612
2613/* Prepare a fast retransmission during a handshake after a client
2614 * has resent Initial packets. According to the RFC a server may retransmit
2615 * Initial packets send them coalescing with others (Handshake here).
2616 * (Listener only function).
2617 */
2618static void qc_prep_hdshk_fast_retrans(struct quic_conn *qc,
2619 struct list *ifrms, struct list *hfrms)
2620{
2621 struct list itmp = LIST_HEAD_INIT(itmp);
2622 struct list htmp = LIST_HEAD_INIT(htmp);
2623
2624 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2625 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2626 struct quic_enc_level *qel = iqel;
2627 struct eb_root *pkts;
2628 struct eb64_node *node;
2629 struct quic_tx_packet *pkt;
2630 struct list *tmp = &itmp;
2631
2632 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2633 start:
2634 pkt = NULL;
2635 pkts = &qel->pktns->tx.pkts;
2636 node = eb64_first(pkts);
2637 /* Skip the empty packet (they have already been retransmitted) */
2638 while (node) {
2639 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002640 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
2641 "--> pn=%llu (%d %d)", (ull)pkt->pn_node.key,
2642 LIST_ISEMPTY(&pkt->frms), !!(pkt->flags & QUIC_FL_TX_PACKET_COALESCED));
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002643 if (!LIST_ISEMPTY(&pkt->frms) && !(pkt->flags & QUIC_FL_TX_PACKET_COALESCED))
2644 break;
2645 node = eb64_next(node);
2646 }
2647
2648 if (!pkt)
2649 goto end;
2650
2651 /* When building a packet from another one, the field which may increase the
2652 * packet size is the packet number. And the maximum increase is 4 bytes.
2653 */
2654 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2655 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
2656 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_PRSAFRM, qc);
2657 goto end;
2658 }
2659
2660 qel->pktns->tx.pto_probe += 1;
2661
2662 /* No risk to loop here, #packet per datagram is bounded */
2663 requeue:
2664 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
2665 qc_dup_pkt_frms(qc, &pkt->frms, tmp);
2666 if (qel == iqel) {
2667 if (pkt->next && pkt->next->type == QUIC_PACKET_TYPE_HANDSHAKE) {
2668 pkt = pkt->next;
2669 tmp = &htmp;
2670 hqel->pktns->tx.pto_probe += 1;
2671 TRACE_DEVEL("looping for next packet", QUIC_EV_CONN_PRSAFRM, qc);
2672 goto requeue;
2673 }
2674 }
2675
2676 end:
2677 LIST_SPLICE(ifrms, &itmp);
2678 LIST_SPLICE(hfrms, &htmp);
2679
2680 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2681}
2682
2683static void qc_cc_err_count_inc(struct quic_conn *qc, struct quic_frame *frm)
2684{
2685 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
2686
2687 if (frm->type == QUIC_FT_CONNECTION_CLOSE)
2688 quic_stats_transp_err_count_inc(qc->prx_counters, frm->connection_close.error_code);
2689 else if (frm->type == QUIC_FT_CONNECTION_CLOSE_APP) {
2690 if (qc->mux_state != QC_MUX_READY || !qc->qcc->app_ops->inc_err_cnt)
2691 goto out;
2692
2693 qc->qcc->app_ops->inc_err_cnt(qc->qcc->ctx, frm->connection_close_app.error_code);
2694 }
2695
2696 out:
2697 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
2698}
2699
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002700/* Cancel a request on connection <qc> for stream id <id>. This is useful when
2701 * the client opens a new stream but the MUX has already been released. A
Amaury Denoyelle75463012023-02-20 10:31:27 +01002702 * STOP_SENDING + RESET_STREAM frames are prepared for emission.
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002703 *
2704 * TODO this function is closely related to H3. Its place should be in H3 layer
2705 * instead of quic-conn but this requires an architecture adjustment.
2706 *
2707 * Returns 1 on sucess else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002708 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002709static int qc_h3_request_reject(struct quic_conn *qc, uint64_t id)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002710{
2711 int ret = 0;
Amaury Denoyelle75463012023-02-20 10:31:27 +01002712 struct quic_frame *ss, *rs;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002713 struct quic_enc_level *qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002714 const uint64_t app_error_code = H3_REQUEST_REJECTED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002715
2716 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2717
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002718 /* Do not emit rejection for unknown unidirectional stream as it is
2719 * forbidden to close some of them (H3 control stream and QPACK
2720 * encoder/decoder streams).
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002721 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002722 if (quic_stream_is_uni(id)) {
2723 ret = 1;
2724 goto out;
2725 }
2726
Amaury Denoyelle75463012023-02-20 10:31:27 +01002727 ss = qc_frm_alloc(QUIC_FT_STOP_SENDING);
2728 if (!ss) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002729 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2730 goto out;
2731 }
2732
Amaury Denoyelle75463012023-02-20 10:31:27 +01002733 ss->stop_sending.id = id;
2734 ss->stop_sending.app_error_code = app_error_code;
2735
2736 rs = qc_frm_alloc(QUIC_FT_RESET_STREAM);
2737 if (!rs) {
2738 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2739 qc_frm_free(&ss);
2740 goto out;
2741 }
2742
2743 rs->reset_stream.id = id;
2744 rs->reset_stream.app_error_code = app_error_code;
2745 rs->reset_stream.final_size = 0;
2746
2747 LIST_APPEND(&qel->pktns->tx.frms, &ss->list);
2748 LIST_APPEND(&qel->pktns->tx.frms, &rs->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002749 ret = 1;
2750 out:
2751 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2752 return ret;
2753}
2754
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002755/* Release the underlying memory use by <ncbuf> non-contiguous buffer */
2756static void quic_free_ncbuf(struct ncbuf *ncbuf)
2757{
2758 struct buffer buf;
2759
2760 if (ncb_is_null(ncbuf))
2761 return;
2762
2763 buf = b_make(ncbuf->area, ncbuf->size, 0, 0);
2764 b_free(&buf);
2765 offer_buffers(NULL, 1);
2766
2767 *ncbuf = NCBUF_NULL;
2768}
2769
2770/* Allocate the underlying required memory for <ncbuf> non-contiguous buffer */
2771static struct ncbuf *quic_get_ncbuf(struct ncbuf *ncbuf)
2772{
2773 struct buffer buf = BUF_NULL;
2774
2775 if (!ncb_is_null(ncbuf))
2776 return ncbuf;
2777
2778 b_alloc(&buf);
2779 BUG_ON(b_is_null(&buf));
2780
2781 *ncbuf = ncb_make(buf.area, buf.size, 0);
2782 ncb_init(ncbuf, 0);
2783
2784 return ncbuf;
2785}
2786
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002787/* Parse <frm> CRYPTO frame coming with <pkt> packet at <qel> <qc> connectionn.
2788 * Returns 1 if succeeded, 0 if not. Also set <*fast_retrans> to 1 if the
2789 * speed up handshake completion may be run after having received duplicated
2790 * CRYPTO data.
2791 */
2792static int qc_handle_crypto_frm(struct quic_conn *qc,
2793 struct quic_crypto *frm, struct quic_rx_packet *pkt,
2794 struct quic_enc_level *qel, int *fast_retrans)
2795{
2796 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002797 enum ncb_ret ncb_ret;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002798 /* XXX TO DO: <cfdebug> is used only for the traces. */
2799 struct quic_rx_crypto_frm cfdebug = {
2800 .offset_node.key = frm->offset,
2801 .len = frm->len,
2802 };
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002803 struct quic_cstream *cstream = qel->cstream;
2804 struct ncbuf *ncbuf = &qel->cstream->rx.ncbuf;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002805
2806 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2807 if (unlikely(qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD)) {
2808 TRACE_PROTO("CRYPTO data discarded",
2809 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2810 goto done;
2811 }
2812
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002813 if (unlikely(frm->offset < cstream->rx.offset)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002814 size_t diff;
2815
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002816 if (frm->offset + frm->len <= cstream->rx.offset) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002817 /* Nothing to do */
2818 TRACE_PROTO("Already received CRYPTO data",
2819 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2820 if (qc_is_listener(qc) && qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] &&
2821 !(qc->flags & QUIC_FL_CONN_HANDSHAKE_SPEED_UP))
2822 *fast_retrans = 1;
2823 goto done;
2824 }
2825
2826 TRACE_PROTO("Partially already received CRYPTO data",
2827 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2828
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002829 diff = cstream->rx.offset - frm->offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002830 frm->len -= diff;
2831 frm->data += diff;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002832 frm->offset = cstream->rx.offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002833 }
2834
Amaury Denoyelleff95f2d2022-11-18 14:50:06 +01002835 if (frm->offset == cstream->rx.offset && ncb_is_empty(ncbuf)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002836 if (!qc_provide_cdata(qel, qc->xprt_ctx, frm->data, frm->len,
2837 pkt, &cfdebug)) {
2838 // trace already emitted by function above
2839 goto leave;
2840 }
2841
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002842 cstream->rx.offset += frm->len;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002843 TRACE_DEVEL("increment crypto level offset", QUIC_EV_CONN_PHPKTS, qc, qel);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002844 goto done;
2845 }
2846
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002847 if (!quic_get_ncbuf(ncbuf) ||
2848 ncb_is_null(ncbuf)) {
2849 TRACE_ERROR("CRYPTO ncbuf allocation failed", QUIC_EV_CONN_PRSHPKT, qc);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002850 goto leave;
2851 }
2852
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002853 /* frm->offset > cstream-trx.offset */
2854 ncb_ret = ncb_add(ncbuf, frm->offset - cstream->rx.offset,
2855 (const char *)frm->data, frm->len, NCB_ADD_COMPARE);
2856 if (ncb_ret != NCB_RET_OK) {
2857 if (ncb_ret == NCB_RET_DATA_REJ) {
2858 TRACE_ERROR("overlapping data rejected", QUIC_EV_CONN_PRSHPKT, qc);
2859 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
2860 }
2861 else if (ncb_ret == NCB_RET_GAP_SIZE) {
2862 TRACE_ERROR("cannot bufferize frame due to gap size limit",
2863 QUIC_EV_CONN_PRSHPKT, qc);
2864 }
2865 goto leave;
2866 }
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002867
2868 done:
2869 ret = 1;
2870 leave:
2871 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2872 return ret;
2873}
2874
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002875/* Parse all the frames of <pkt> QUIC packet for QUIC connection <qc> and <qel>
2876 * as encryption level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002877 * Returns 1 if succeeded, 0 if failed.
2878 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002879static int qc_parse_pkt_frms(struct quic_conn *qc, struct quic_rx_packet *pkt,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002880 struct quic_enc_level *qel)
2881{
2882 struct quic_frame frm;
2883 const unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002884 int fast_retrans = 0, ret = 0;
2885
2886 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2887 /* Skip the AAD */
2888 pos = pkt->data + pkt->aad_len;
2889 end = pkt->data + pkt->len;
2890
2891 while (pos < end) {
2892 if (!qc_parse_frm(&frm, pkt, &pos, end, qc)) {
2893 // trace already emitted by function above
2894 goto leave;
2895 }
2896
2897 TRACE_PROTO("RX frame", QUIC_EV_CONN_PSTRM, qc, &frm);
2898 switch (frm.type) {
2899 case QUIC_FT_PADDING:
2900 break;
2901 case QUIC_FT_PING:
2902 break;
2903 case QUIC_FT_ACK:
2904 {
2905 unsigned int rtt_sample;
2906
2907 rtt_sample = 0;
2908 if (!qc_parse_ack_frm(qc, &frm, qel, &rtt_sample, &pos, end)) {
2909 // trace already emitted by function above
2910 goto leave;
2911 }
2912
2913 if (rtt_sample) {
2914 unsigned int ack_delay;
2915
2916 ack_delay = !quic_application_pktns(qel->pktns, qc) ? 0 :
2917 qc->state >= QUIC_HS_ST_CONFIRMED ?
2918 MS_TO_TICKS(QUIC_MIN(quic_ack_delay_ms(&frm.ack, qc), qc->max_ack_delay)) :
2919 MS_TO_TICKS(quic_ack_delay_ms(&frm.ack, qc));
2920 quic_loss_srtt_update(&qc->path->loss, rtt_sample, ack_delay, qc);
2921 }
2922 break;
2923 }
2924 case QUIC_FT_RESET_STREAM:
Amaury Denoyelle5854fc02022-12-09 16:25:48 +01002925 if (qc->mux_state == QC_MUX_READY) {
2926 struct quic_reset_stream *rs = &frm.reset_stream;
2927 qcc_recv_reset_stream(qc->qcc, rs->id, rs->app_error_code, rs->final_size);
2928 }
2929 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002930 case QUIC_FT_STOP_SENDING:
2931 {
2932 struct quic_stop_sending *stop_sending = &frm.stop_sending;
2933 if (qc->mux_state == QC_MUX_READY) {
2934 if (qcc_recv_stop_sending(qc->qcc, stop_sending->id,
2935 stop_sending->app_error_code)) {
2936 TRACE_ERROR("qcc_recv_stop_sending() failed", QUIC_EV_CONN_PRSHPKT, qc);
2937 goto leave;
2938 }
2939 }
2940 break;
2941 }
2942 case QUIC_FT_CRYPTO:
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002943 if (!qc_handle_crypto_frm(qc, &frm.crypto, pkt, qel, &fast_retrans))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002944 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002945 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002946 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2947 {
2948 struct quic_stream *stream = &frm.stream;
2949 unsigned nb_streams = qc->rx.strms[qcs_id_type(stream->id)].nb_streams;
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002950 const char fin = frm.type & QUIC_STREAM_FRAME_TYPE_FIN_BIT;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002951
2952 /* The upper layer may not be allocated. */
2953 if (qc->mux_state != QC_MUX_READY) {
2954 if ((stream->id >> QCS_ID_TYPE_SHIFT) < nb_streams) {
2955 TRACE_DATA("Already closed stream", QUIC_EV_CONN_PRSHPKT, qc);
2956 break;
2957 }
2958 else {
2959 TRACE_DEVEL("No mux for new stream", QUIC_EV_CONN_PRSHPKT, qc);
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002960 if (qc->app_ops == &h3_ops) {
Amaury Denoyelle156a89a2023-02-20 10:32:16 +01002961 if (!qc_h3_request_reject(qc, stream->id)) {
2962 TRACE_ERROR("error on request rejection", QUIC_EV_CONN_PRSHPKT, qc);
2963 /* This packet will not be acknowledged */
2964 goto leave;
2965 }
2966 }
2967 else {
2968 /* This packet will not be acknowledged */
2969 goto leave;
Frédéric Lécailled18025e2023-01-20 15:33:50 +01002970 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002971 }
2972 }
2973
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002974 if (!qc_handle_strm_frm(pkt, stream, qc, fin)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002975 TRACE_ERROR("qc_handle_strm_frm() failed", QUIC_EV_CONN_PRSHPKT, qc);
2976 goto leave;
2977 }
2978
2979 break;
2980 }
2981 case QUIC_FT_MAX_DATA:
2982 if (qc->mux_state == QC_MUX_READY) {
2983 struct quic_max_data *data = &frm.max_data;
2984 qcc_recv_max_data(qc->qcc, data->max_data);
2985 }
2986 break;
2987 case QUIC_FT_MAX_STREAM_DATA:
2988 if (qc->mux_state == QC_MUX_READY) {
2989 struct quic_max_stream_data *data = &frm.max_stream_data;
2990 if (qcc_recv_max_stream_data(qc->qcc, data->id,
2991 data->max_stream_data)) {
2992 TRACE_ERROR("qcc_recv_max_stream_data() failed", QUIC_EV_CONN_PRSHPKT, qc);
2993 goto leave;
2994 }
2995 }
2996 break;
2997 case QUIC_FT_MAX_STREAMS_BIDI:
2998 case QUIC_FT_MAX_STREAMS_UNI:
2999 break;
3000 case QUIC_FT_DATA_BLOCKED:
3001 HA_ATOMIC_INC(&qc->prx_counters->data_blocked);
3002 break;
3003 case QUIC_FT_STREAM_DATA_BLOCKED:
3004 HA_ATOMIC_INC(&qc->prx_counters->stream_data_blocked);
3005 break;
3006 case QUIC_FT_STREAMS_BLOCKED_BIDI:
3007 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_bidi);
3008 break;
3009 case QUIC_FT_STREAMS_BLOCKED_UNI:
3010 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_uni);
3011 break;
3012 case QUIC_FT_NEW_CONNECTION_ID:
3013 case QUIC_FT_RETIRE_CONNECTION_ID:
3014 /* XXX TO DO XXX */
3015 break;
3016 case QUIC_FT_CONNECTION_CLOSE:
3017 case QUIC_FT_CONNECTION_CLOSE_APP:
3018 /* Increment the error counters */
3019 qc_cc_err_count_inc(qc, &frm);
3020 if (!(qc->flags & QUIC_FL_CONN_DRAINING)) {
3021 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
3022 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
3023 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
3024 }
3025 TRACE_STATE("Entering draining state", QUIC_EV_CONN_PRSHPKT, qc);
3026 /* RFC 9000 10.2. Immediate Close:
3027 * The closing and draining connection states exist to ensure
3028 * that connections close cleanly and that delayed or reordered
3029 * packets are properly discarded. These states SHOULD persist
3030 * for at least three times the current PTO interval...
3031 *
3032 * Rearm the idle timeout only one time when entering draining
3033 * state.
3034 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003035 qc->flags |= QUIC_FL_CONN_DRAINING|QUIC_FL_CONN_IMMEDIATE_CLOSE;
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01003036 qc_idle_timer_do_rearm(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003037 qc_notify_close(qc);
3038 }
3039 break;
3040 case QUIC_FT_HANDSHAKE_DONE:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003041 if (qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003042 TRACE_ERROR("non accepted QUIC_FT_HANDSHAKE_DONE frame",
3043 QUIC_EV_CONN_PRSHPKT, qc);
3044 goto leave;
3045 }
3046
3047 qc->state = QUIC_HS_ST_CONFIRMED;
3048 break;
3049 default:
3050 TRACE_ERROR("unknosw frame type", QUIC_EV_CONN_PRSHPKT, qc);
3051 goto leave;
3052 }
3053 }
3054
3055 /* Flag this packet number space as having received a packet. */
3056 qel->pktns->flags |= QUIC_FL_PKTNS_PKT_RECEIVED;
3057
3058 if (fast_retrans) {
3059 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
3060 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
3061
3062 TRACE_PROTO("speeding up handshake completion", QUIC_EV_CONN_PRSHPKT, qc);
3063 qc_prep_hdshk_fast_retrans(qc, &iqel->pktns->tx.frms, &hqel->pktns->tx.frms);
3064 qc->flags |= QUIC_FL_CONN_HANDSHAKE_SPEED_UP;
3065 }
3066
3067 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
3068 * has successfully parse a Handshake packet. The Initial encryption must also
3069 * be discarded.
3070 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003071 if (pkt->type == QUIC_PACKET_TYPE_HANDSHAKE && qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003072 if (qc->state >= QUIC_HS_ST_SERVER_INITIAL) {
3073 if (!(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx.flags &
3074 QUIC_FL_TLS_SECRETS_DCD)) {
3075 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3076 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PRSHPKT, qc);
3077 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003078 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003079 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3080 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3081 }
3082 if (qc->state < QUIC_HS_ST_SERVER_HANDSHAKE)
3083 qc->state = QUIC_HS_ST_SERVER_HANDSHAKE;
3084 }
3085 }
3086
3087 ret = 1;
3088 leave:
3089 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
3090 return ret;
3091}
3092
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003093
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003094/* Allocate Tx buffer from <qc> quic-conn if needed.
3095 *
3096 * Returns allocated buffer or NULL on error.
3097 */
3098static struct buffer *qc_txb_alloc(struct quic_conn *qc)
3099{
3100 struct buffer *buf = &qc->tx.buf;
3101 if (!b_alloc(buf))
3102 return NULL;
3103
3104 return buf;
3105}
3106
3107/* Free Tx buffer from <qc> if it is empty. */
3108static void qc_txb_release(struct quic_conn *qc)
3109{
3110 struct buffer *buf = &qc->tx.buf;
3111
3112 /* For the moment sending function is responsible to purge the buffer
3113 * entirely. It may change in the future but this requires to be able
3114 * to reuse old data.
Frédéric Lécaillebbf86be2023-02-20 09:28:58 +01003115 * For the momemt we do not care to leave data in the buffer for
3116 * a connection which is supposed to be killed asap.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003117 */
3118 BUG_ON_HOT(buf && b_data(buf));
3119
3120 if (!b_data(buf)) {
3121 b_free(buf);
3122 offer_buffers(NULL, 1);
3123 }
3124}
3125
3126/* Commit a datagram payload written into <buf> of length <length>. <first_pkt>
3127 * must contains the address of the first packet stored in the payload.
3128 *
3129 * Caller is responsible that there is enough space in the buffer.
3130 */
3131static void qc_txb_store(struct buffer *buf, uint16_t length,
3132 struct quic_tx_packet *first_pkt)
3133{
3134 const size_t hdlen = sizeof(uint16_t) + sizeof(void *);
3135 BUG_ON_HOT(b_contig_space(buf) < hdlen); /* this must not happen */
3136
3137 write_u16(b_tail(buf), length);
3138 write_ptr(b_tail(buf) + sizeof(length), first_pkt);
3139 b_add(buf, hdlen + length);
3140}
3141
3142/* Returns 1 if a packet may be built for <qc> from <qel> encryption level
3143 * with <frms> as ack-eliciting frame list to send, 0 if not.
3144 * <cc> must equal to 1 if an immediate close was asked, 0 if not.
3145 * <probe> must equalt to 1 if a probing packet is required, 0 if not.
3146 * <force_ack> may be set to 1 if you want to force an ack.
3147 */
3148static int qc_may_build_pkt(struct quic_conn *qc, struct list *frms,
3149 struct quic_enc_level *qel, int cc, int probe, int force_ack)
3150{
3151 unsigned int must_ack = force_ack ||
3152 (LIST_ISEMPTY(frms) && (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED));
3153
3154 /* Do not build any more packet if the TX secrets are not available or
3155 * if there is nothing to send, i.e. if no CONNECTION_CLOSE or ACK are required
3156 * and if there is no more packets to send upon PTO expiration
3157 * and if there is no more ack-eliciting frames to send or in flight
3158 * congestion control limit is reached for prepared data
3159 */
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02003160 if (!quic_tls_has_tx_sec(qel) ||
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003161 (!cc && !probe && !must_ack &&
3162 (LIST_ISEMPTY(frms) || qc->path->prep_in_flight >= qc->path->cwnd))) {
3163 return 0;
3164 }
3165
3166 return 1;
3167}
3168
3169/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3170 * <frms>. Each packet is stored in a distinct datagram written to <buf>.
3171 *
3172 * Each datagram is prepended by a two fields header : the datagram length and
3173 * the address of the packet contained in the datagram.
3174 *
3175 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3176 * -1 if something wrong happened.
3177 */
3178static int qc_prep_app_pkts(struct quic_conn *qc, struct buffer *buf,
3179 struct list *frms)
3180{
3181 int ret = -1;
3182 struct quic_enc_level *qel;
3183 unsigned char *end, *pos;
3184 struct quic_tx_packet *pkt;
3185 size_t total;
3186 /* Each datagram is prepended with its length followed by the address
3187 * of the first packet in the datagram.
3188 */
3189 const size_t dg_headlen = sizeof(uint16_t) + sizeof(pkt);
3190
3191 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3192
3193 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3194 total = 0;
3195 pos = (unsigned char *)b_tail(buf);
3196 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen) {
3197 int err, probe, cc;
3198
3199 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3200 probe = 0;
3201 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3202 /* We do not probe if an immediate close was asked */
3203 if (!cc)
3204 probe = qel->pktns->tx.pto_probe;
3205
3206 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, 0))
3207 break;
3208
3209 /* Leave room for the datagram header */
3210 pos += dg_headlen;
3211 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3212 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3213 }
3214 else {
3215 end = pos + qc->path->mtu;
3216 }
3217
3218 pkt = qc_build_pkt(&pos, end, qel, &qel->tls_ctx, frms, qc, NULL, 0,
3219 QUIC_PACKET_TYPE_SHORT, 0, 0, probe, cc, &err);
3220 switch (err) {
3221 case -2:
3222 // trace already emitted by function above
3223 goto leave;
3224 case -1:
3225 /* As we provide qc_build_pkt() with an enough big buffer to fulfill an
3226 * MTU, we are here because of the congestion control window. There is
3227 * no need to try to reuse this buffer.
3228 */
3229 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3230 goto out;
3231 default:
3232 break;
3233 }
3234
3235 /* This is to please to GCC. We cannot have (err >= 0 && !pkt) */
3236 BUG_ON(!pkt);
3237
3238 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3239 pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3240
3241 total += pkt->len;
3242
3243 /* Write datagram header. */
3244 qc_txb_store(buf, pkt->len, pkt);
3245 }
3246
3247 out:
3248 ret = total;
3249 leave:
3250 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3251 return ret;
3252}
3253
3254/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3255 * <frms>. Several packets can be regrouped in a single datagram. The result is
3256 * written into <buf>.
3257 *
3258 * Each datagram is prepended by a two fields header : the datagram length and
3259 * the address of first packet in the datagram.
3260 *
3261 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3262 * -1 if something wrong happened.
3263 */
3264static int qc_prep_pkts(struct quic_conn *qc, struct buffer *buf,
3265 enum quic_tls_enc_level tel, struct list *tel_frms,
3266 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
3267{
3268 struct quic_enc_level *qel;
3269 unsigned char *end, *pos;
3270 struct quic_tx_packet *first_pkt, *cur_pkt, *prv_pkt;
3271 /* length of datagrams */
3272 uint16_t dglen;
3273 size_t total;
3274 int ret = -1, padding;
3275 /* Each datagram is prepended with its length followed by the address
3276 * of the first packet in the datagram.
3277 */
3278 const size_t dg_headlen = sizeof(uint16_t) + sizeof(first_pkt);
3279 struct list *frms;
3280
3281 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3282
3283 /* Currently qc_prep_pkts() does not handle buffer wrapping so the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003284 * caller must ensure that buf is reset.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003285 */
3286 BUG_ON_HOT(buf->head || buf->data);
3287
3288 total = 0;
3289 qel = &qc->els[tel];
3290 frms = tel_frms;
3291 dglen = 0;
3292 padding = 0;
3293 pos = (unsigned char *)b_head(buf);
3294 first_pkt = prv_pkt = NULL;
3295 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen || prv_pkt) {
3296 int err, probe, cc;
3297 enum quic_pkt_type pkt_type;
3298 struct quic_tls_ctx *tls_ctx;
3299 const struct quic_version *ver;
3300 int force_ack = (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3301 (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
3302 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
3303
3304 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3305 probe = 0;
3306 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3307 /* We do not probe if an immediate close was asked */
3308 if (!cc)
3309 probe = qel->pktns->tx.pto_probe;
3310
3311 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, force_ack)) {
3312 if (prv_pkt)
3313 qc_txb_store(buf, dglen, first_pkt);
3314 /* Let's select the next encryption level */
3315 if (tel != next_tel && next_tel != QUIC_TLS_ENC_LEVEL_NONE) {
3316 tel = next_tel;
3317 frms = next_tel_frms;
3318 qel = &qc->els[tel];
3319 /* Build a new datagram */
3320 prv_pkt = NULL;
3321 TRACE_DEVEL("next encryption level selected", QUIC_EV_CONN_PHPKTS, qc);
3322 continue;
3323 }
3324 break;
3325 }
3326
3327 pkt_type = quic_tls_level_pkt_type(tel);
3328 if (!prv_pkt) {
3329 /* Leave room for the datagram header */
3330 pos += dg_headlen;
3331 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3332 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3333 }
3334 else {
3335 end = pos + qc->path->mtu;
3336 }
3337 }
3338
3339 if (qc->negotiated_version) {
3340 ver = qc->negotiated_version;
3341 if (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL])
3342 tls_ctx = &qc->negotiated_ictx;
3343 else
3344 tls_ctx = &qel->tls_ctx;
3345 }
3346 else {
3347 ver = qc->original_version;
3348 tls_ctx = &qel->tls_ctx;
3349 }
3350
3351 cur_pkt = qc_build_pkt(&pos, end, qel, tls_ctx, frms,
3352 qc, ver, dglen, pkt_type,
3353 force_ack, padding, probe, cc, &err);
3354 switch (err) {
3355 case -2:
3356 // trace already emitted by function above
3357 goto leave;
3358 case -1:
3359 /* If there was already a correct packet present, set the
3360 * current datagram as prepared into <cbuf>.
3361 */
3362 if (prv_pkt)
3363 qc_txb_store(buf, dglen, first_pkt);
3364 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3365 goto out;
3366 default:
3367 break;
3368 }
3369
3370 /* This is to please to GCC. We cannot have (err >= 0 && !cur_pkt) */
3371 BUG_ON(!cur_pkt);
3372
3373 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3374 cur_pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3375
3376 total += cur_pkt->len;
3377 /* keep trace of the first packet in the datagram */
3378 if (!first_pkt)
3379 first_pkt = cur_pkt;
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01003380 /* Attach the current one to the previous one and vice versa */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003381 if (prv_pkt) {
3382 prv_pkt->next = cur_pkt;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01003383 cur_pkt->prev = prv_pkt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003384 cur_pkt->flags |= QUIC_FL_TX_PACKET_COALESCED;
3385 }
3386 /* Let's say we have to build a new dgram */
3387 prv_pkt = NULL;
3388 dglen += cur_pkt->len;
3389 /* Client: discard the Initial encryption keys as soon as
3390 * a handshake packet could be built.
3391 */
3392 if (qc->state == QUIC_HS_ST_CLIENT_INITIAL &&
3393 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
3394 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3395 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PHPKTS, qc);
3396 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
3397 qc_set_timer(qc);
3398 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3399 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3400 qc->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
3401 }
3402 /* If the data for the current encryption level have all been sent,
3403 * select the next level.
3404 */
3405 if ((tel == QUIC_TLS_ENC_LEVEL_INITIAL || tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE) &&
3406 next_tel != QUIC_TLS_ENC_LEVEL_NONE && (LIST_ISEMPTY(frms) && !qel->pktns->tx.pto_probe)) {
3407 /* If QUIC_TLS_ENC_LEVEL_HANDSHAKE was already reached let's try QUIC_TLS_ENC_LEVEL_APP */
3408 if (tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE && next_tel == tel)
3409 next_tel = QUIC_TLS_ENC_LEVEL_APP;
3410 tel = next_tel;
3411 if (tel == QUIC_TLS_ENC_LEVEL_APP)
3412 frms = &qc->els[tel].pktns->tx.frms;
3413 else
3414 frms = next_tel_frms;
3415 qel = &qc->els[tel];
3416 if (!LIST_ISEMPTY(frms)) {
3417 /* If there is data for the next level, do not
3418 * consume a datagram.
3419 */
3420 prv_pkt = cur_pkt;
3421 }
3422 }
3423
3424 /* If we have to build a new datagram, set the current datagram as
3425 * prepared into <cbuf>.
3426 */
3427 if (!prv_pkt) {
3428 qc_txb_store(buf, dglen, first_pkt);
3429 first_pkt = NULL;
3430 dglen = 0;
3431 padding = 0;
3432 }
3433 else if (prv_pkt->type == QUIC_TLS_ENC_LEVEL_INITIAL &&
3434 (!qc_is_listener(qc) ||
3435 prv_pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
3436 padding = 1;
3437 }
3438 }
3439
3440 out:
3441 ret = total;
3442 leave:
3443 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3444 return ret;
3445}
3446
3447/* Send datagrams stored in <buf>.
3448 *
Frédéric Lécaillebbf86be2023-02-20 09:28:58 +01003449 * This function returns 1 for success. Even if sendto() syscall failed,
3450 * buffer is drained and packets are considered as emitted and this function returns 1
3451 * There is a unique exception when sendto() fails with ECONNREFUSED as errno,
3452 * this function returns 0.
3453 * QUIC loss detection mechanism is used as a back door way to retry sending.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003454 */
3455int qc_send_ppkts(struct buffer *buf, struct ssl_sock_ctx *ctx)
3456{
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003457 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003458 struct quic_conn *qc;
3459 char skip_sendto = 0;
3460
3461 qc = ctx->qc;
3462 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
3463 while (b_contig_data(buf, 0)) {
3464 unsigned char *pos;
3465 struct buffer tmpbuf = { };
3466 struct quic_tx_packet *first_pkt, *pkt, *next_pkt;
3467 uint16_t dglen;
3468 size_t headlen = sizeof dglen + sizeof first_pkt;
3469 unsigned int time_sent;
3470
3471 pos = (unsigned char *)b_head(buf);
3472 dglen = read_u16(pos);
3473 BUG_ON_HOT(!dglen); /* this should not happen */
3474
3475 pos += sizeof dglen;
3476 first_pkt = read_ptr(pos);
3477 pos += sizeof first_pkt;
3478 tmpbuf.area = (char *)pos;
3479 tmpbuf.size = tmpbuf.data = dglen;
3480
3481 TRACE_DATA("send dgram", QUIC_EV_CONN_SPPKTS, qc);
3482 /* If sendto is on error just skip the call to it for the rest
3483 * of the loop but continue to purge the buffer. Data will be
3484 * transmitted when QUIC packets are detected as lost on our
3485 * side.
3486 *
3487 * TODO use fd-monitoring to detect when send operation can be
3488 * retry. This should improve the bandwidth without relying on
3489 * retransmission timer. However, it requires a major rework on
3490 * quic-conn fd management.
3491 */
3492 if (!skip_sendto) {
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003493 int syscall_errno;
3494
3495 syscall_errno = 0;
3496 if (qc_snd_buf(qc, &tmpbuf, tmpbuf.data, 0, &syscall_errno)) {
3497 if (syscall_errno == ECONNREFUSED) {
3498 /* Let's kill this connection asap. */
3499 TRACE_PROTO("UDP port unreachable", QUIC_EV_CONN_SPPKTS, qc);
3500 qc_kill_conn(qc);
Frédéric Lécaillebbf86be2023-02-20 09:28:58 +01003501 b_del(buf, buf->data);
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003502 goto leave;
3503 }
3504
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003505 skip_sendto = 1;
3506 TRACE_ERROR("sendto error, simulate sending for the rest of data", QUIC_EV_CONN_SPPKTS, qc);
3507 }
3508 }
3509
3510 b_del(buf, dglen + headlen);
3511 qc->tx.bytes += tmpbuf.data;
3512 time_sent = now_ms;
3513
3514 for (pkt = first_pkt; pkt; pkt = next_pkt) {
3515 pkt->time_sent = time_sent;
3516 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
3517 pkt->pktns->tx.time_of_last_eliciting = time_sent;
3518 qc->path->ifae_pkts++;
3519 if (qc->flags & QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ)
3520 qc_idle_timer_rearm(qc, 0);
3521 }
3522 if (!(qc->flags & QUIC_FL_CONN_CLOSING) &&
3523 (pkt->flags & QUIC_FL_TX_PACKET_CC)) {
3524 qc->flags |= QUIC_FL_CONN_CLOSING;
3525 qc_notify_close(qc);
3526
3527 /* RFC 9000 10.2. Immediate Close:
3528 * The closing and draining connection states exist to ensure
3529 * that connections close cleanly and that delayed or reordered
3530 * packets are properly discarded. These states SHOULD persist
3531 * for at least three times the current PTO interval...
3532 *
3533 * Rearm the idle timeout only one time when entering closing
3534 * state.
3535 */
3536 qc_idle_timer_do_rearm(qc);
3537 if (qc->timer_task) {
3538 task_destroy(qc->timer_task);
3539 qc->timer_task = NULL;
3540 }
3541 }
3542 qc->path->in_flight += pkt->in_flight_len;
3543 pkt->pktns->tx.in_flight += pkt->in_flight_len;
3544 if (pkt->in_flight_len)
3545 qc_set_timer(qc);
3546 TRACE_DATA("sent pkt", QUIC_EV_CONN_SPPKTS, qc, pkt);
3547 next_pkt = pkt->next;
3548 quic_tx_packet_refinc(pkt);
3549 eb64_insert(&pkt->pktns->tx.pkts, &pkt->pn_node);
3550 }
3551 }
3552
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003553 ret = 1;
3554leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003555 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
3556
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003557 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003558}
3559
3560/* Copy into <buf> buffer a stateless reset token depending on the
3561 * <salt> salt input. This is the cluster secret which will be derived
3562 * as HKDF input secret to generate this token.
3563 * Return 1 if succeeded, 0 if not.
3564 */
3565static int quic_stateless_reset_token_cpy(struct quic_conn *qc,
3566 unsigned char *buf, size_t len,
3567 const unsigned char *salt, size_t saltlen)
3568{
3569 /* Input secret */
3570 const unsigned char *key = (const unsigned char *)global.cluster_secret;
3571 size_t keylen = strlen(global.cluster_secret);
3572 /* Info */
3573 const unsigned char label[] = "stateless token";
3574 size_t labellen = sizeof label - 1;
3575 int ret;
3576
3577 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3578
3579 ret = quic_hkdf_extract_and_expand(EVP_sha256(), buf, len,
3580 key, keylen, salt, saltlen, label, labellen);
3581 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3582 return ret;
3583}
3584
3585/* Initialize the stateless reset token attached to <cid> connection ID.
3586 * Returns 1 if succeeded, 0 if not.
3587 */
3588static int quic_stateless_reset_token_init(struct quic_conn *qc,
3589 struct quic_connection_id *quic_cid)
3590{
3591 int ret;
3592
3593 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3594
3595 if (global.cluster_secret) {
3596 /* Output secret */
3597 unsigned char *token = quic_cid->stateless_reset_token;
3598 size_t tokenlen = sizeof quic_cid->stateless_reset_token;
3599 /* Salt */
3600 const unsigned char *cid = quic_cid->cid.data;
3601 size_t cidlen = quic_cid->cid.len;
3602
3603 ret = quic_stateless_reset_token_cpy(qc, token, tokenlen, cid, cidlen);
3604 }
3605 else {
3606 /* TODO: RAND_bytes() should be replaced */
3607 ret = RAND_bytes(quic_cid->stateless_reset_token,
3608 sizeof quic_cid->stateless_reset_token) == 1;
3609 }
3610
3611 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3612 return ret;
3613}
3614
3615/* Allocate a new CID with <seq_num> as sequence number and attach it to <root>
3616 * ebtree.
3617 *
3618 * The CID is randomly generated in part with the result altered to be
3619 * associated with the current thread ID. This means this function must only
3620 * be called by the quic_conn thread.
3621 *
3622 * Returns the new CID if succeeded, NULL if not.
3623 */
3624static struct quic_connection_id *new_quic_cid(struct eb_root *root,
3625 struct quic_conn *qc,
3626 int seq_num)
3627{
3628 struct quic_connection_id *cid;
3629
3630 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3631
3632 cid = pool_alloc(pool_head_quic_connection_id);
3633 if (!cid) {
3634 TRACE_ERROR("cid allocation failed", QUIC_EV_CONN_TXPKT, qc);
3635 goto err;
3636 }
3637
3638 cid->cid.len = QUIC_HAP_CID_LEN;
3639 /* TODO: RAND_bytes() should be replaced */
3640 if (RAND_bytes(cid->cid.data, cid->cid.len) != 1) {
3641 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT, qc);
3642 goto err;
3643 }
3644
3645 quic_pin_cid_to_tid(cid->cid.data, tid);
3646 if (quic_stateless_reset_token_init(qc, cid) != 1) {
3647 TRACE_ERROR("quic_stateless_reset_token_init() failed", QUIC_EV_CONN_TXPKT, qc);
3648 goto err;
3649 }
3650
3651 cid->qc = qc;
3652
3653 cid->seq_num.key = seq_num;
3654 cid->retire_prior_to = 0;
3655 /* insert the allocated CID in the quic_conn tree */
3656 eb64_insert(root, &cid->seq_num);
3657
3658 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3659 return cid;
3660
3661 err:
3662 pool_free(pool_head_quic_connection_id, cid);
3663 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3664 return NULL;
3665}
3666
3667/* Build all the frames which must be sent just after the handshake have succeeded.
3668 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
3669 * a HANDSHAKE_DONE frame.
3670 * Return 1 if succeeded, 0 if not.
3671 */
3672static int quic_build_post_handshake_frames(struct quic_conn *qc)
3673{
3674 int ret = 0, i, first, max;
3675 struct quic_enc_level *qel;
3676 struct quic_frame *frm, *frmbak;
3677 struct list frm_list = LIST_HEAD_INIT(frm_list);
3678 struct eb64_node *node;
3679
3680 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
3681
3682 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3683 /* Only servers must send a HANDSHAKE_DONE frame. */
3684 if (qc_is_listener(qc)) {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003685 frm = qc_frm_alloc(QUIC_FT_HANDSHAKE_DONE);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003686 if (!frm) {
3687 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3688 goto leave;
3689 }
3690
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003691 LIST_APPEND(&frm_list, &frm->list);
3692 }
3693
3694 /* Initialize <max> connection IDs minus one: there is
3695 * already one connection ID used for the current connection.
3696 */
3697 first = 1;
3698 max = qc->tx.params.active_connection_id_limit;
3699
3700 /* TODO: check limit */
3701 for (i = first; i < max; i++) {
3702 struct quic_connection_id *cid;
3703
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003704 frm = qc_frm_alloc(QUIC_FT_NEW_CONNECTION_ID);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003705 if (!frm) {
3706 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3707 goto err;
3708 }
3709
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003710 cid = new_quic_cid(&qc->cids, qc, i);
3711 if (!cid) {
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003712 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003713 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3714 goto err;
3715 }
3716
3717 /* insert the allocated CID in the receiver datagram handler tree */
3718 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3719
3720 quic_connection_id_to_frm_cpy(frm, cid);
3721 LIST_APPEND(&frm_list, &frm->list);
3722 }
3723
3724 LIST_SPLICE(&qel->pktns->tx.frms, &frm_list);
3725 qc->flags |= QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT;
3726
3727 ret = 1;
3728 leave:
3729 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
3730 return ret;
3731
3732 err:
3733 /* free the frames */
3734 list_for_each_entry_safe(frm, frmbak, &frm_list, list)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003735 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003736
3737 node = eb64_lookup_ge(&qc->cids, first);
3738 while (node) {
3739 struct quic_connection_id *cid;
3740
3741 cid = eb64_entry(node, struct quic_connection_id, seq_num);
3742 if (cid->seq_num.key >= max)
3743 break;
3744
3745 node = eb64_next(node);
3746 ebmb_delete(&cid->node);
3747 eb64_delete(&cid->seq_num);
3748 pool_free(pool_head_quic_connection_id, cid);
3749 }
3750 goto leave;
3751}
3752
3753/* Deallocate <l> list of ACK ranges. */
3754void quic_free_arngs(struct quic_conn *qc, struct quic_arngs *arngs)
3755{
3756 struct eb64_node *n;
3757 struct quic_arng_node *ar;
3758
3759 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
3760
3761 n = eb64_first(&arngs->root);
3762 while (n) {
3763 struct eb64_node *next;
3764
3765 ar = eb64_entry(n, struct quic_arng_node, first);
3766 next = eb64_next(n);
3767 eb64_delete(n);
3768 pool_free(pool_head_quic_arng, ar);
3769 n = next;
3770 }
3771
3772 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
3773}
3774
3775/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
3776 * descending order.
3777 */
3778static inline size_t sack_gap(struct quic_arng_node *p,
3779 struct quic_arng_node *q)
3780{
3781 return p->first.key - q->last - 2;
3782}
3783
3784
3785/* Remove the last elements of <ack_ranges> list of ack range updating its
3786 * encoded size until it goes below <limit>.
3787 * Returns 1 if succeeded, 0 if not (no more element to remove).
3788 */
3789static int quic_rm_last_ack_ranges(struct quic_conn *qc,
3790 struct quic_arngs *arngs, size_t limit)
3791{
3792 int ret = 0;
3793 struct eb64_node *last, *prev;
3794
3795 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3796
3797 last = eb64_last(&arngs->root);
3798 while (last && arngs->enc_sz > limit) {
3799 struct quic_arng_node *last_node, *prev_node;
3800
3801 prev = eb64_prev(last);
3802 if (!prev) {
3803 TRACE_DEVEL("<last> not found", QUIC_EV_CONN_TXPKT, qc);
3804 goto out;
3805 }
3806
3807 last_node = eb64_entry(last, struct quic_arng_node, first);
3808 prev_node = eb64_entry(prev, struct quic_arng_node, first);
3809 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
3810 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
3811 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
3812 --arngs->sz;
3813 eb64_delete(last);
3814 pool_free(pool_head_quic_arng, last);
3815 last = prev;
3816 }
3817
3818 ret = 1;
3819 out:
3820 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3821 return ret;
3822}
3823
3824/* Set the encoded size of <arngs> QUIC ack ranges. */
3825static void quic_arngs_set_enc_sz(struct quic_conn *qc, struct quic_arngs *arngs)
3826{
3827 struct eb64_node *node, *next;
3828 struct quic_arng_node *ar, *ar_next;
3829
3830 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3831
3832 node = eb64_last(&arngs->root);
3833 if (!node)
3834 goto leave;
3835
3836 ar = eb64_entry(node, struct quic_arng_node, first);
3837 arngs->enc_sz = quic_int_getsize(ar->last) +
3838 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
3839
3840 while ((next = eb64_prev(node))) {
3841 ar_next = eb64_entry(next, struct quic_arng_node, first);
3842 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
3843 quic_int_getsize(ar_next->last - ar_next->first.key);
3844 node = next;
3845 ar = eb64_entry(node, struct quic_arng_node, first);
3846 }
3847
3848 leave:
3849 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3850}
3851
3852/* Insert <ar> ack range into <argns> tree of ack ranges.
3853 * Returns the ack range node which has been inserted if succeeded, NULL if not.
3854 */
3855static inline
3856struct quic_arng_node *quic_insert_new_range(struct quic_conn *qc,
3857 struct quic_arngs *arngs,
3858 struct quic_arng *ar)
3859{
3860 struct quic_arng_node *new_ar;
3861
3862 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3863
3864 new_ar = pool_alloc(pool_head_quic_arng);
3865 if (!new_ar) {
3866 TRACE_ERROR("ack range allocation failed", QUIC_EV_CONN_RXPKT, qc);
3867 goto leave;
3868 }
3869
3870 new_ar->first.key = ar->first;
3871 new_ar->last = ar->last;
3872 eb64_insert(&arngs->root, &new_ar->first);
3873 arngs->sz++;
3874
3875 leave:
3876 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3877 return new_ar;
3878}
3879
3880/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
3881 * Note that this function computes the number of bytes required to encode
3882 * this tree of ACK ranges in descending order.
3883 *
3884 * Descending order
3885 * ------------->
3886 * range1 range2
3887 * ..........|--------|..............|--------|
3888 * ^ ^ ^ ^
3889 * | | | |
3890 * last1 first1 last2 first2
3891 * ..........+--------+--------------+--------+......
3892 * diff1 gap12 diff2
3893 *
3894 * To encode the previous list of ranges we must encode integers as follows in
3895 * descending order:
3896 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
3897 * with diff1 = last1 - first1
3898 * diff2 = last2 - first2
3899 * gap12 = first1 - last2 - 2 (>= 0)
3900 *
3901
3902returns 0 on error
3903
3904 */
3905int quic_update_ack_ranges_list(struct quic_conn *qc,
3906 struct quic_arngs *arngs,
3907 struct quic_arng *ar)
3908{
3909 int ret = 0;
3910 struct eb64_node *le;
3911 struct quic_arng_node *new_node;
3912 struct eb64_node *new;
3913
3914 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3915
3916 new = NULL;
3917 if (eb_is_empty(&arngs->root)) {
3918 new_node = quic_insert_new_range(qc, arngs, ar);
3919 if (new_node)
3920 ret = 1;
3921
3922 goto leave;
3923 }
3924
3925 le = eb64_lookup_le(&arngs->root, ar->first);
3926 if (!le) {
3927 new_node = quic_insert_new_range(qc, arngs, ar);
3928 if (!new_node)
3929 goto leave;
3930
3931 new = &new_node->first;
3932 }
3933 else {
3934 struct quic_arng_node *le_ar =
3935 eb64_entry(le, struct quic_arng_node, first);
3936
3937 /* Already existing range */
3938 if (le_ar->last >= ar->last) {
3939 ret = 1;
3940 }
3941 else if (le_ar->last + 1 >= ar->first) {
3942 le_ar->last = ar->last;
3943 new = le;
3944 new_node = le_ar;
3945 }
3946 else {
3947 new_node = quic_insert_new_range(qc, arngs, ar);
3948 if (!new_node)
3949 goto leave;
3950
3951 new = &new_node->first;
3952 }
3953 }
3954
3955 /* Verify that the new inserted node does not overlap the nodes
3956 * which follow it.
3957 */
3958 if (new) {
3959 struct eb64_node *next;
3960 struct quic_arng_node *next_node;
3961
3962 while ((next = eb64_next(new))) {
3963 next_node =
3964 eb64_entry(next, struct quic_arng_node, first);
3965 if (new_node->last + 1 < next_node->first.key)
3966 break;
3967
3968 if (next_node->last > new_node->last)
3969 new_node->last = next_node->last;
3970 eb64_delete(next);
3971 pool_free(pool_head_quic_arng, next_node);
3972 /* Decrement the size of these ranges. */
3973 arngs->sz--;
3974 }
3975 }
3976
3977 ret = 1;
3978 leave:
3979 quic_arngs_set_enc_sz(qc, arngs);
3980 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3981 return ret;
3982}
3983/* Remove the header protection of packets at <el> encryption level.
3984 * Always succeeds.
3985 */
3986static inline void qc_rm_hp_pkts(struct quic_conn *qc, struct quic_enc_level *el)
3987{
3988 struct quic_tls_ctx *tls_ctx;
3989 struct quic_rx_packet *pqpkt, *pkttmp;
3990 struct quic_enc_level *app_qel;
3991
3992 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, qc);
3993 app_qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3994 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
3995 if (el == app_qel && qc_is_listener(qc) && qc->state < QUIC_HS_ST_COMPLETE) {
3996 TRACE_DEVEL("hp not removed (handshake not completed)",
3997 QUIC_EV_CONN_ELRMHP, qc);
3998 goto out;
3999 }
4000 tls_ctx = &el->tls_ctx;
4001 list_for_each_entry_safe(pqpkt, pkttmp, &el->rx.pqpkts, list) {
4002 if (!qc_do_rm_hp(qc, pqpkt, tls_ctx, el->pktns->rx.largest_pn,
4003 pqpkt->data + pqpkt->pn_offset, pqpkt->data)) {
4004 TRACE_ERROR("hp removing error", QUIC_EV_CONN_ELRMHP, qc);
4005 }
4006 else {
4007 /* The AAD includes the packet number field */
4008 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
4009 /* Store the packet into the tree of packets to decrypt. */
4010 pqpkt->pn_node.key = pqpkt->pn;
4011 eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
4012 quic_rx_packet_refinc(pqpkt);
4013 TRACE_DEVEL("hp removed", QUIC_EV_CONN_ELRMHP, qc, pqpkt);
4014 }
4015 LIST_DELETE(&pqpkt->list);
4016 quic_rx_packet_refdec(pqpkt);
4017 }
4018
4019 out:
4020 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, qc);
4021}
4022
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004023/* Process all the CRYPTO frame at <el> encryption level. This is the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004024 * responsibility of the called to ensure there exists a CRYPTO data
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004025 * stream for this level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004026 * Return 1 if succeeded, 0 if not.
4027 */
4028static inline int qc_treat_rx_crypto_frms(struct quic_conn *qc,
4029 struct quic_enc_level *el,
4030 struct ssl_sock_ctx *ctx)
4031{
4032 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004033 struct ncbuf *ncbuf;
4034 struct quic_cstream *cstream = el->cstream;
4035 ncb_sz_t data;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004036
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004037 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004038
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004039 BUG_ON(!cstream);
4040 ncbuf = &cstream->rx.ncbuf;
4041 if (ncb_is_null(ncbuf))
4042 goto done;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004043
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004044 /* TODO not working if buffer is wrapping */
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004045 while ((data = ncb_data(ncbuf, 0))) {
4046 const unsigned char *cdata = (const unsigned char *)ncb_head(ncbuf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004047
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004048 if (!qc_provide_cdata(el, ctx, cdata, data, NULL, NULL))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004049 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004050
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004051 cstream->rx.offset += data;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004052 TRACE_DEVEL("buffered crypto data were provided to TLS stack",
4053 QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004054 }
4055
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004056 done:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004057 ret = 1;
4058 leave:
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004059 if (!ncb_is_null(ncbuf) && ncb_is_empty(ncbuf)) {
4060 TRACE_DEVEL("freeing crypto buf", QUIC_EV_CONN_PHPKTS, qc, el);
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004061 quic_free_ncbuf(ncbuf);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004062 }
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004063 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004064 return ret;
4065}
4066
4067/* Process all the packets at <el> and <next_el> encryption level.
4068 * This is the caller responsibility to check that <cur_el> is different of <next_el>
4069 * as pointer value.
4070 * Return 1 if succeeded, 0 if not.
4071 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004072int qc_treat_rx_pkts(struct quic_conn *qc, struct quic_enc_level *cur_el,
4073 struct quic_enc_level *next_el, int force_ack)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004074{
4075 int ret = 0;
4076 struct eb64_node *node;
4077 int64_t largest_pn = -1;
4078 unsigned int largest_pn_time_received = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004079 struct quic_enc_level *qel = cur_el;
4080
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004081 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004082 qel = cur_el;
4083 next_tel:
4084 if (!qel)
4085 goto out;
4086
4087 node = eb64_first(&qel->rx.pkts);
4088 while (node) {
4089 struct quic_rx_packet *pkt;
4090
4091 pkt = eb64_entry(node, struct quic_rx_packet, pn_node);
4092 TRACE_DATA("new packet", QUIC_EV_CONN_RXPKT,
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004093 qc, pkt, NULL, qc->xprt_ctx->ssl);
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01004094 if (!qc_pkt_decrypt(qc, qel, pkt)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004095 /* Drop the packet */
4096 TRACE_ERROR("packet decryption failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004097 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004098 }
4099 else {
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004100 if (!qc_parse_pkt_frms(qc, pkt, qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004101 /* Drop the packet */
4102 TRACE_ERROR("packet parsing failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004103 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004104 HA_ATOMIC_INC(&qc->prx_counters->dropped_parsing);
4105 }
4106 else {
4107 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
4108
4109 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING || force_ack) {
4110 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
4111 qel->pktns->rx.nb_aepkts_since_last_ack++;
4112 qc_idle_timer_rearm(qc, 1);
4113 }
4114 if (pkt->pn > largest_pn) {
4115 largest_pn = pkt->pn;
4116 largest_pn_time_received = pkt->time_received;
4117 }
4118 /* Update the list of ranges to acknowledge. */
4119 if (!quic_update_ack_ranges_list(qc, &qel->pktns->rx.arngs, &ar))
4120 TRACE_ERROR("Could not update ack range list",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004121 QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004122 }
4123 }
4124 node = eb64_next(node);
4125 eb64_delete(&pkt->pn_node);
4126 quic_rx_packet_refdec(pkt);
4127 }
4128
4129 if (largest_pn != -1 && largest_pn > qel->pktns->rx.largest_pn) {
4130 /* Update the largest packet number. */
4131 qel->pktns->rx.largest_pn = largest_pn;
4132 /* Update the largest acknowledged packet timestamps */
4133 qel->pktns->rx.largest_time_received = largest_pn_time_received;
4134 qel->pktns->flags |= QUIC_FL_PKTNS_NEW_LARGEST_PN;
4135 }
4136
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004137 if (qel->cstream && !qc_treat_rx_crypto_frms(qc, qel, qc->xprt_ctx)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004138 // trace already emitted by function above
4139 goto leave;
4140 }
4141
4142 if (qel == cur_el) {
4143 BUG_ON(qel == next_el);
4144 qel = next_el;
4145 largest_pn = -1;
4146 goto next_tel;
4147 }
4148
4149 out:
4150 ret = 1;
4151 leave:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004152 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004153 return ret;
4154}
4155
4156/* Check if it's possible to remove header protection for packets related to
4157 * encryption level <qel>. If <qel> is NULL, assume it's false.
4158 *
4159 * Return true if the operation is possible else false.
4160 */
4161static int qc_qel_may_rm_hp(struct quic_conn *qc, struct quic_enc_level *qel)
4162{
4163 int ret = 0;
4164 enum quic_tls_enc_level tel;
4165
4166 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
4167
4168 if (!qel)
4169 goto cant_rm_hp;
4170
4171 tel = ssl_to_quic_enc_level(qel->level);
4172
4173 /* check if tls secrets are available */
4174 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
4175 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, qc);
4176 goto cant_rm_hp;
4177 }
4178
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004179 if (!quic_tls_has_rx_sec(qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004180 TRACE_DEVEL("non available secrets", QUIC_EV_CONN_TRMHP, qc);
4181 goto cant_rm_hp;
4182 }
4183
Frédéric Lécaille8417beb2023-02-01 10:31:35 +01004184 if (tel == QUIC_TLS_ENC_LEVEL_APP && qc->state < QUIC_HS_ST_COMPLETE) {
4185 TRACE_DEVEL("handshake not complete", QUIC_EV_CONN_TRMHP, qc);
4186 goto cant_rm_hp;
4187 }
4188
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004189 /* check if the connection layer is ready before using app level */
4190 if ((tel == QUIC_TLS_ENC_LEVEL_APP || tel == QUIC_TLS_ENC_LEVEL_EARLY_DATA) &&
4191 qc->mux_state == QC_MUX_NULL) {
4192 TRACE_DEVEL("connection layer not ready", QUIC_EV_CONN_TRMHP, qc);
4193 goto cant_rm_hp;
4194 }
4195
4196 ret = 1;
4197 cant_rm_hp:
4198 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc);
4199 return ret;
4200}
4201
4202/* Try to send application frames from list <frms> on connection <qc>.
4203 *
4204 * Use qc_send_app_probing wrapper when probing with old data.
4205 *
4206 * Returns 1 on success. Some data might not have been sent due to congestion,
4207 * in this case they are left in <frms> input list. The caller may subscribe on
4208 * quic-conn to retry later.
4209 *
4210 * Returns 0 on critical error.
4211 * TODO review and classify more distinctly transient from definitive errors to
4212 * allow callers to properly handle it.
4213 */
4214static int qc_send_app_pkts(struct quic_conn *qc, struct list *frms)
4215{
4216 int status = 0;
4217 struct buffer *buf;
4218
4219 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4220
4221 buf = qc_txb_alloc(qc);
4222 if (!buf) {
4223 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4224 goto leave;
4225 }
4226
4227 /* Prepare and send packets until we could not further prepare packets. */
4228 while (1) {
4229 int ret;
4230 /* Currently buf cannot be non-empty at this stage. Even if a
4231 * previous sendto() has failed it is emptied to simulate
4232 * packet emission and rely on QUIC lost detection to try to
4233 * emit it.
4234 */
4235 BUG_ON_HOT(b_data(buf));
4236 b_reset(buf);
4237
4238 ret = qc_prep_app_pkts(qc, buf, frms);
4239 if (ret == -1)
4240 goto err;
4241 else if (ret == 0)
4242 goto out;
4243
4244 if (!qc_send_ppkts(buf, qc->xprt_ctx))
4245 goto err;
4246 }
4247
4248 out:
4249 status = 1;
4250 qc_txb_release(qc);
4251 leave:
4252 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4253 return status;
4254
4255 err:
4256 qc_txb_release(qc);
4257 goto leave;
4258}
4259
4260/* Try to send application frames from list <frms> on connection <qc>. Use this
4261 * function when probing is required.
4262 *
4263 * Returns the result from qc_send_app_pkts function.
4264 */
4265static forceinline int qc_send_app_probing(struct quic_conn *qc,
4266 struct list *frms)
4267{
4268 int ret;
4269
4270 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4271
4272 TRACE_STATE("preparing old data (probing)", QUIC_EV_CONN_TXPKT, qc);
4273 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4274 ret = qc_send_app_pkts(qc, frms);
4275 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4276
4277 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4278 return ret;
4279}
4280
4281/* Try to send application frames from list <frms> on connection <qc>. This
4282 * function is provided for MUX upper layer usage only.
4283 *
4284 * Returns the result from qc_send_app_pkts function.
4285 */
4286int qc_send_mux(struct quic_conn *qc, struct list *frms)
4287{
4288 int ret;
4289
4290 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4291 BUG_ON(qc->mux_state != QC_MUX_READY); /* Only MUX can uses this function so it must be ready. */
4292
4293 TRACE_STATE("preparing data (from MUX)", QUIC_EV_CONN_TXPKT, qc);
4294 qc->flags |= QUIC_FL_CONN_TX_MUX_CONTEXT;
4295 ret = qc_send_app_pkts(qc, frms);
4296 qc->flags &= ~QUIC_FL_CONN_TX_MUX_CONTEXT;
4297
4298 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4299 return ret;
4300}
4301
4302/* Sends handshake packets from up to two encryption levels <tel> and <next_te>
4303 * with <tel_frms> and <next_tel_frms> as frame list respectively for <qc>
4304 * QUIC connection. <old_data> is used as boolean to send data already sent but
4305 * not already acknowledged (in flight).
4306 * Returns 1 if succeeded, 0 if not.
4307 */
4308int qc_send_hdshk_pkts(struct quic_conn *qc, int old_data,
4309 enum quic_tls_enc_level tel, struct list *tel_frms,
4310 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
4311{
4312 int ret, status = 0;
4313 struct buffer *buf = qc_txb_alloc(qc);
4314
4315 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4316
4317 if (!buf) {
4318 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4319 goto leave;
4320 }
4321
4322 /* Currently buf cannot be non-empty at this stage. Even if a previous
4323 * sendto() has failed it is emptied to simulate packet emission and
4324 * rely on QUIC lost detection to try to emit it.
4325 */
4326 BUG_ON_HOT(b_data(buf));
4327 b_reset(buf);
4328
4329 if (old_data) {
4330 TRACE_STATE("old data for probing asked", QUIC_EV_CONN_TXPKT, qc);
4331 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4332 }
4333
4334 ret = qc_prep_pkts(qc, buf, tel, tel_frms, next_tel, next_tel_frms);
4335 if (ret == -1)
4336 goto out;
4337 else if (ret == 0)
4338 goto skip_send;
4339
4340 if (!qc_send_ppkts(buf, qc->xprt_ctx))
4341 goto out;
4342
4343 skip_send:
4344 status = 1;
4345 out:
4346 TRACE_STATE("no more need old data for probing", QUIC_EV_CONN_TXPKT, qc);
4347 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4348 qc_txb_release(qc);
4349 leave:
4350 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4351 return status;
4352}
4353
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004354/* Retransmit up to two datagrams depending on packet number space.
4355 * Return 0 when failed, 0 if not.
4356 */
4357static int qc_dgrams_retransmit(struct quic_conn *qc)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004358{
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004359 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004360 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4361 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4362 struct quic_enc_level *aqel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4363
4364 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4365
4366 if (iqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004367 int i;
4368
4369 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
4370 struct list ifrms = LIST_HEAD_INIT(ifrms);
4371 struct list hfrms = LIST_HEAD_INIT(hfrms);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004372
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004373 qc_prep_hdshk_fast_retrans(qc, &ifrms, &hfrms);
4374 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &ifrms);
4375 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4376 if (!LIST_ISEMPTY(&ifrms)) {
4377 iqel->pktns->tx.pto_probe = 1;
4378 if (!LIST_ISEMPTY(&hfrms))
4379 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004380 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4381 QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms))
4382 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004383 /* Put back unsent frames in their packet number spaces */
4384 LIST_SPLICE(&iqel->pktns->tx.frms, &ifrms);
4385 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4386 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004387 }
4388 TRACE_STATE("no more need to probe Initial packet number space",
4389 QUIC_EV_CONN_TXPKT, qc);
4390 iqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004391 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004392 }
4393 else {
4394 int i;
4395
4396 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004397 hqel->pktns->tx.pto_probe = 0;
4398 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
Frédéric Lécaille7b5d9b12022-11-28 17:21:45 +01004399 struct list frms1 = LIST_HEAD_INIT(frms1);
4400
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004401 qc_prep_fast_retrans(qc, hqel, &frms1, NULL);
4402 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4403 if (!LIST_ISEMPTY(&frms1)) {
4404 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004405 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &frms1,
4406 QUIC_TLS_ENC_LEVEL_NONE, NULL))
4407 goto leave;
4408
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004409 /* Put back unsent frames into their packet number spaces */
4410 LIST_SPLICE(&hqel->pktns->tx.frms, &frms1);
4411 }
4412 }
4413 TRACE_STATE("no more need to probe Handshake packet number space",
4414 QUIC_EV_CONN_TXPKT, qc);
4415 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4416 }
4417 else if (aqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4418 struct list frms2 = LIST_HEAD_INIT(frms2);
4419 struct list frms1 = LIST_HEAD_INIT(frms1);
4420
4421 aqel->pktns->tx.pto_probe = 0;
4422 qc_prep_fast_retrans(qc, aqel, &frms1, &frms2);
4423 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4424 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms2);
4425 if (!LIST_ISEMPTY(&frms1)) {
4426 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004427 if (!qc_send_app_probing(qc, &frms1))
4428 goto leave;
4429
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004430 /* Put back unsent frames into their packet number spaces */
4431 LIST_SPLICE(&aqel->pktns->tx.frms, &frms1);
4432 }
4433 if (!LIST_ISEMPTY(&frms2)) {
4434 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004435 if (!qc_send_app_probing(qc, &frms2))
4436 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004437 /* Put back unsent frames into their packet number spaces */
4438 LIST_SPLICE(&aqel->pktns->tx.frms, &frms2);
4439 }
4440 TRACE_STATE("no more need to probe 01RTT packet number space",
4441 QUIC_EV_CONN_TXPKT, qc);
4442 aqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4443 }
4444 }
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004445
4446 ret = 1;
4447 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004448 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004449 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004450}
4451
4452/* QUIC connection packet handler task (post handshake) */
4453struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state)
4454{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004455 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004456 struct quic_enc_level *qel;
4457
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004458 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4459
4460 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
4461 TRACE_STATE("connection handshake state", QUIC_EV_CONN_IO_CB, qc, &qc->state);
4462
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004463 if (qc_test_fd(qc))
4464 qc_rcv_buf(qc);
4465
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004466 /* Retranmissions */
4467 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4468 TRACE_STATE("retransmission needed", QUIC_EV_CONN_IO_CB, qc);
4469 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004470 if (!qc_dgrams_retransmit(qc))
4471 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004472 }
4473
4474 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4475 qc_rm_hp_pkts(qc, qel);
4476
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004477 if (!qc_treat_rx_pkts(qc, qel, NULL, 0)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004478 TRACE_DEVEL("qc_treat_rx_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4479 goto out;
4480 }
4481
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004482 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4483 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
4484 goto out;
4485 }
4486
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004487 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4488 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)) {
4489 TRACE_STATE("draining connection (must not send packets)", QUIC_EV_CONN_IO_CB, qc);
4490 goto out;
4491 }
4492
4493 /* XXX TODO: how to limit the list frames to send */
4494 if (!qc_send_app_pkts(qc, &qel->pktns->tx.frms)) {
4495 TRACE_DEVEL("qc_send_app_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4496 goto out;
4497 }
4498
4499 out:
4500 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
4501 return t;
4502}
4503
4504/* Returns a boolean if <qc> needs to emit frames for <qel> encryption level. */
4505static int qc_need_sending(struct quic_conn *qc, struct quic_enc_level *qel)
4506{
4507 return (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) ||
4508 (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) ||
4509 qel->pktns->tx.pto_probe ||
4510 !LIST_ISEMPTY(&qel->pktns->tx.frms);
4511}
4512
4513/* QUIC connection packet handler task. */
4514struct task *quic_conn_io_cb(struct task *t, void *context, unsigned int state)
4515{
4516 int ret, ssl_err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004517 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004518 enum quic_tls_enc_level tel, next_tel;
4519 struct quic_enc_level *qel, *next_qel;
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004520 /* Early-data encryption level */
4521 struct quic_enc_level *eqel;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004522 struct buffer *buf = NULL;
4523 int st, force_ack, zero_rtt;
4524
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004525 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004526 eqel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004527 st = qc->state;
4528 TRACE_PROTO("connection state", QUIC_EV_CONN_IO_CB, qc, &st);
4529
4530 /* Retranmissions */
4531 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4532 TRACE_DEVEL("retransmission needed", QUIC_EV_CONN_PHPKTS, qc);
4533 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004534 if (!qc_dgrams_retransmit(qc))
4535 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004536 }
4537
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004538 ssl_err = SSL_ERROR_NONE;
4539 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004540 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004541 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004542
4543 if (qc_test_fd(qc))
4544 qc_rcv_buf(qc);
4545
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004546 if (st >= QUIC_HS_ST_COMPLETE &&
4547 qc_el_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
4548 TRACE_DEVEL("remaining Handshake packets", QUIC_EV_CONN_PHPKTS, qc);
4549 /* There may be remaining Handshake packets to treat and acknowledge. */
4550 tel = QUIC_TLS_ENC_LEVEL_HANDSHAKE;
4551 next_tel = QUIC_TLS_ENC_LEVEL_APP;
4552 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004553 else if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, zero_rtt))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004554 goto out;
4555
4556 qel = &qc->els[tel];
4557 next_qel = next_tel == QUIC_TLS_ENC_LEVEL_NONE ? NULL : &qc->els[next_tel];
4558
4559 next_level:
4560 /* Treat packets waiting for header packet protection decryption */
4561 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4562 qc_rm_hp_pkts(qc, qel);
4563
4564 force_ack = qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
4565 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004566 if (!qc_treat_rx_pkts(qc, qel, next_qel, force_ack))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004567 goto out;
4568
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004569 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4570 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_PHPKTS, qc);
4571 goto out;
4572 }
4573
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004574 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4575 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE))
4576 goto out;
4577
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004578 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004579 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004580 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
4581 if (next_qel && next_qel == eqel && zero_rtt) {
4582 TRACE_DEVEL("select 0RTT as next encryption level",
4583 QUIC_EV_CONN_PHPKTS, qc);
4584 qel = next_qel;
4585 next_qel = NULL;
4586 goto next_level;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004587 }
4588
4589 st = qc->state;
4590 if (st >= QUIC_HS_ST_COMPLETE) {
4591 if (!(qc->flags & QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT) &&
4592 !quic_build_post_handshake_frames(qc))
4593 goto out;
4594
4595 if (!(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].tls_ctx.flags &
4596 QUIC_FL_TLS_SECRETS_DCD)) {
4597 /* Discard the Handshake keys. */
4598 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4599 TRACE_PROTO("discarding Handshake pktns", QUIC_EV_CONN_PHPKTS, qc);
4600 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, qc);
4601 qc_set_timer(qc);
4602 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4603 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns);
4604 }
4605
4606 if (qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) {
4607 /* There may be remaining handshake to build (acks) */
4608 st = QUIC_HS_ST_SERVER_HANDSHAKE;
4609 }
4610 }
4611
4612 /* A listener does not send any O-RTT packet. O-RTT packet number space must not
4613 * be considered.
4614 */
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004615 if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, 0))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004616 goto out;
4617
4618 if (!qc_need_sending(qc, qel) &&
4619 (!next_qel || !qc_need_sending(qc, next_qel))) {
4620 goto skip_send;
4621 }
4622
4623 buf = qc_txb_alloc(qc);
4624 if (!buf)
4625 goto out;
4626
4627 /* Currently buf cannot be non-empty at this stage. Even if a previous
4628 * sendto() has failed it is emptied to simulate packet emission and
4629 * rely on QUIC lost detection to try to emit it.
4630 */
4631 BUG_ON_HOT(b_data(buf));
4632 b_reset(buf);
4633
4634 ret = qc_prep_pkts(qc, buf, tel, &qc->els[tel].pktns->tx.frms,
4635 next_tel, &qc->els[next_tel].pktns->tx.frms);
4636 if (ret == -1)
4637 goto out;
4638 else if (ret == 0)
4639 goto skip_send;
4640
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004641 if (!qc_send_ppkts(buf, qc->xprt_ctx))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004642 goto out;
4643
4644 skip_send:
4645 /* Check if there is something to do for the next level.
4646 */
4647 if (next_qel && next_qel != qel &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004648 quic_tls_has_rx_sec(next_qel) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004649 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || qc_el_rx_pkts(next_qel))) {
4650 qel = next_qel;
4651 next_qel = NULL;
4652 goto next_level;
4653 }
4654
4655 out:
4656 qc_txb_release(qc);
4657 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc, &st, &ssl_err);
4658 return t;
4659}
4660
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004661/* Release the memory allocated for <cs> CRYPTO stream */
4662void quic_cstream_free(struct quic_cstream *cs)
4663{
4664 if (!cs) {
4665 /* This is the case for ORTT encryption level */
4666 return;
4667 }
4668
Amaury Denoyellebc174b22022-11-17 10:12:52 +01004669 quic_free_ncbuf(&cs->rx.ncbuf);
4670
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004671 qc_stream_desc_release(cs->desc);
4672 pool_free(pool_head_quic_cstream, cs);
4673}
4674
4675/* Allocate a new QUIC stream for <qc>.
4676 * Return it if succeeded, NULL if not.
4677 */
4678struct quic_cstream *quic_cstream_new(struct quic_conn *qc)
4679{
4680 struct quic_cstream *cs, *ret_cs = NULL;
4681
4682 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4683 cs = pool_alloc(pool_head_quic_cstream);
4684 if (!cs) {
4685 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4686 goto leave;
4687 }
4688
4689 cs->rx.offset = 0;
4690 cs->rx.ncbuf = NCBUF_NULL;
4691 cs->rx.offset = 0;
4692
4693 cs->tx.offset = 0;
4694 cs->tx.sent_offset = 0;
4695 cs->tx.buf = BUF_NULL;
4696 cs->desc = qc_stream_desc_new((uint64_t)-1, -1, cs, qc);
4697 if (!cs->desc) {
4698 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4699 goto err;
4700 }
4701
4702 ret_cs = cs;
4703 leave:
4704 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4705 return ret_cs;
4706
4707 err:
4708 pool_free(pool_head_quic_cstream, cs);
4709 goto leave;
4710}
4711
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004712/* Uninitialize <qel> QUIC encryption level. Never fails. */
4713static void quic_conn_enc_level_uninit(struct quic_conn *qc, struct quic_enc_level *qel)
4714{
4715 int i;
4716
4717 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4718
4719 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
4720 if (qel->tx.crypto.bufs[i]) {
4721 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
4722 qel->tx.crypto.bufs[i] = NULL;
4723 }
4724 }
4725 ha_free(&qel->tx.crypto.bufs);
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004726 quic_cstream_free(qel->cstream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004727
4728 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4729}
4730
4731/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
4732 * connection allocating everything needed.
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004733 *
4734 * Returns 1 if succeeded, 0 if not. On error the caller is responsible to use
4735 * quic_conn_enc_level_uninit() to cleanup partially allocated content.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004736 */
4737static int quic_conn_enc_level_init(struct quic_conn *qc,
4738 enum quic_tls_enc_level level)
4739{
4740 int ret = 0;
4741 struct quic_enc_level *qel;
4742
4743 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4744
4745 qel = &qc->els[level];
4746 qel->level = quic_to_ssl_enc_level(level);
4747 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
4748 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
4749 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
4750 qel->tls_ctx.flags = 0;
4751
4752 qel->rx.pkts = EB_ROOT;
4753 LIST_INIT(&qel->rx.pqpkts);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004754
4755 /* Allocate only one buffer. */
4756 /* TODO: use a pool */
4757 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
4758 if (!qel->tx.crypto.bufs)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004759 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004760
4761 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
4762 if (!qel->tx.crypto.bufs[0])
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004763 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004764
4765 qel->tx.crypto.bufs[0]->sz = 0;
4766 qel->tx.crypto.nb_buf = 1;
4767
4768 qel->tx.crypto.sz = 0;
4769 qel->tx.crypto.offset = 0;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004770 /* No CRYPTO data for early data TLS encryption level */
4771 if (level == QUIC_TLS_ENC_LEVEL_EARLY_DATA)
4772 qel->cstream = NULL;
4773 else {
4774 qel->cstream = quic_cstream_new(qc);
4775 if (!qel->cstream)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004776 goto leave;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004777 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004778
4779 ret = 1;
4780 leave:
4781 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4782 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004783}
4784
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004785/* Return 1 if <qc> connection may probe the Initial packet number space, 0 if not.
4786 * This is not the case if the remote peer address is not validated and if
4787 * it cannot send at least QUIC_INITIAL_PACKET_MINLEN bytes.
4788 */
4789static int qc_may_probe_ipktns(struct quic_conn *qc)
4790{
4791 return quic_peer_validated_addr(qc) ||
4792 (int)(3 * qc->rx.bytes - qc->tx.prep_bytes) >= QUIC_INITIAL_PACKET_MINLEN;
4793}
4794
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004795/* Callback called upon loss detection and PTO timer expirations. */
4796struct task *qc_process_timer(struct task *task, void *ctx, unsigned int state)
4797{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004798 struct quic_conn *qc = ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004799 struct quic_pktns *pktns;
4800
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004801 TRACE_ENTER(QUIC_EV_CONN_PTIMER, qc,
4802 NULL, NULL, &qc->path->ifae_pkts);
4803 task->expire = TICK_ETERNITY;
4804 pktns = quic_loss_pktns(qc);
4805 if (tick_isset(pktns->tx.loss_time)) {
4806 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
4807
4808 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
4809 if (!LIST_ISEMPTY(&lost_pkts))
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004810 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01004811 if (qc_release_lost_pkts(qc, pktns, &lost_pkts, now_ms))
4812 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004813 goto out;
4814 }
4815
4816 if (qc->path->in_flight) {
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +01004817 pktns = quic_pto_pktns(qc, qc->state >= QUIC_HS_ST_CONFIRMED, NULL);
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02004818 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004819 pktns->tx.pto_probe = QUIC_MAX_NB_PTO_DGRAMS;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02004820 tasklet_wakeup(qc->subs->tasklet);
4821 qc->subs->events &= ~SUB_RETRY_SEND;
4822 if (!qc->subs->events)
4823 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004824 }
4825 else {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004826 if (pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL]) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004827 if (qc_may_probe_ipktns(qc)) {
4828 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4829 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4830 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4831 }
4832 else {
4833 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4834 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004835 if (qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].tx.in_flight) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004836 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004837 qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4838 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
4839 }
4840 }
4841 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE]) {
4842 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004843 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4844 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004845 if (qc->pktns[QUIC_TLS_PKTNS_INITIAL].tx.in_flight) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004846 if (qc_may_probe_ipktns(qc)) {
4847 qc->pktns[QUIC_TLS_PKTNS_INITIAL].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4848 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4849 }
4850 else {
4851 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4852 }
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004853 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004854 }
4855 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT]) {
4856 TRACE_STATE("needs to probe 01RTT packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004857 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4858 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004859 }
4860 }
4861 }
4862 else if (!qc_is_listener(qc) && qc->state <= QUIC_HS_ST_COMPLETE) {
4863 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4864 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4865
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004866 if (quic_tls_has_tx_sec(hel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004867 hel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004868 if (quic_tls_has_tx_sec(iel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004869 iel->pktns->tx.pto_probe = 1;
4870 }
4871
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004872 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004873 qc->path->loss.pto_count++;
4874
4875 out:
4876 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, qc, pktns);
4877
4878 return task;
4879}
4880
4881/* Parse the Retry token from buffer <token> with <end> a pointer to
4882 * one byte past the end of this buffer. This will extract the ODCID
4883 * which will be stored into <odcid>
4884 *
4885 * Returns 0 on success else non-zero.
4886 */
4887static int parse_retry_token(struct quic_conn *qc,
4888 const unsigned char *token, const unsigned char *end,
4889 struct quic_cid *odcid)
4890{
4891 int ret = 0;
4892 uint64_t odcid_len;
4893 uint32_t timestamp;
4894
4895 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4896
4897 if (!quic_dec_int(&odcid_len, &token, end)) {
4898 TRACE_ERROR("quic_dec_int() error", QUIC_EV_CONN_LPKT, qc);
4899 goto leave;
4900 }
4901
4902 /* RFC 9000 7.2. Negotiating Connection IDs:
4903 * When an Initial packet is sent by a client that has not previously
4904 * received an Initial or Retry packet from the server, the client
4905 * populates the Destination Connection ID field with an unpredictable
4906 * value. This Destination Connection ID MUST be at least 8 bytes in length.
4907 */
4908 if (odcid_len < QUIC_ODCID_MINLEN || odcid_len > QUIC_CID_MAXLEN) {
4909 TRACE_ERROR("wrong ODCID length", QUIC_EV_CONN_LPKT, qc);
4910 goto leave;
4911 }
4912
4913 if (end - token < odcid_len + sizeof timestamp) {
4914 TRACE_ERROR("too long ODCID length", QUIC_EV_CONN_LPKT, qc);
4915 goto leave;
4916 }
4917
4918 timestamp = ntohl(read_u32(token + odcid_len));
4919 if (timestamp + MS_TO_TICKS(QUIC_RETRY_DURATION_MS) <= now_ms) {
4920 TRACE_ERROR("token has expired", QUIC_EV_CONN_LPKT, qc);
4921 goto leave;
4922 }
4923
4924 ret = 1;
4925 memcpy(odcid->data, token, odcid_len);
4926 odcid->len = odcid_len;
4927 leave:
4928 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4929 return !ret;
4930}
4931
4932/* Allocate a new QUIC connection with <version> as QUIC version. <ipv4>
4933 * boolean is set to 1 for IPv4 connection, 0 for IPv6. <server> is set to 1
4934 * for QUIC servers (or haproxy listeners).
4935 * <dcid> is the destination connection ID, <scid> is the source connection ID,
4936 * <token> the token found to be used for this connection with <token_len> as
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004937 * length. Endpoints addresses are specified via <local_addr> and <peer_addr>.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004938 * Returns the connection if succeeded, NULL if not.
4939 */
4940static struct quic_conn *qc_new_conn(const struct quic_version *qv, int ipv4,
4941 struct quic_cid *dcid, struct quic_cid *scid,
4942 const struct quic_cid *token_odcid,
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004943 struct sockaddr_storage *local_addr,
4944 struct sockaddr_storage *peer_addr,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004945 int server, int token, void *owner)
4946{
4947 int i;
4948 struct quic_conn *qc;
4949 /* Initial CID. */
4950 struct quic_connection_id *icid;
4951 char *buf_area = NULL;
4952 struct listener *l = NULL;
4953 struct quic_cc_algo *cc_algo = NULL;
4954 struct quic_tls_ctx *ictx;
4955 TRACE_ENTER(QUIC_EV_CONN_INIT);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004956 /* TODO replace pool_zalloc by pool_alloc(). This requires special care
4957 * to properly initialized internal quic_conn members to safely use
4958 * quic_conn_release() on alloc failure.
4959 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004960 qc = pool_zalloc(pool_head_quic_conn);
4961 if (!qc) {
4962 TRACE_ERROR("Could not allocate a new connection", QUIC_EV_CONN_INIT);
4963 goto err;
4964 }
4965
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004966 /* Initialize in priority qc members required for a safe dealloc. */
4967
4968 /* required to use MTLIST_IN_LIST */
4969 MT_LIST_INIT(&qc->accept_list);
4970
4971 LIST_INIT(&qc->rx.pkt_list);
4972
Amaury Denoyelle42448332022-12-12 11:24:05 +01004973 qc_init_fd(qc);
4974
Amaury Denoyelle15c74702023-02-01 10:18:26 +01004975 LIST_INIT(&qc->back_refs);
4976
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004977 /* Now proceeds to allocation of qc members. */
4978
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004979 buf_area = pool_alloc(pool_head_quic_conn_rxbuf);
4980 if (!buf_area) {
4981 TRACE_ERROR("Could not allocate a new RX buffer", QUIC_EV_CONN_INIT, qc);
4982 goto err;
4983 }
4984
4985 qc->cids = EB_ROOT;
4986 /* QUIC Server (or listener). */
4987 if (server) {
4988 struct proxy *prx;
4989
4990 l = owner;
4991 prx = l->bind_conf->frontend;
4992 cc_algo = l->bind_conf->quic_cc_algo;
4993
4994 qc->prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe,
4995 &quic_stats_module);
4996 qc->flags |= QUIC_FL_CONN_LISTENER;
4997 qc->state = QUIC_HS_ST_SERVER_INITIAL;
4998 /* Copy the initial DCID with the address. */
4999 qc->odcid.len = dcid->len;
5000 qc->odcid.addrlen = dcid->addrlen;
5001 memcpy(qc->odcid.data, dcid->data, dcid->len + dcid->addrlen);
5002
5003 /* copy the packet SCID to reuse it as DCID for sending */
5004 if (scid->len)
5005 memcpy(qc->dcid.data, scid->data, scid->len);
5006 qc->dcid.len = scid->len;
5007 qc->tx.buf = BUF_NULL;
5008 qc->li = l;
5009 }
5010 /* QUIC Client (outgoing connection to servers) */
5011 else {
5012 qc->state = QUIC_HS_ST_CLIENT_INITIAL;
5013 if (dcid->len)
5014 memcpy(qc->dcid.data, dcid->data, dcid->len);
5015 qc->dcid.len = dcid->len;
5016 }
5017 qc->mux_state = QC_MUX_NULL;
5018 qc->err = quic_err_transport(QC_ERR_NO_ERROR);
5019
5020 icid = new_quic_cid(&qc->cids, qc, 0);
5021 if (!icid) {
5022 TRACE_ERROR("Could not allocate a new connection ID", QUIC_EV_CONN_INIT, qc);
5023 goto err;
5024 }
5025
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005026 if ((global.tune.options & GTUNE_QUIC_SOCK_PER_CONN) &&
5027 is_addr(local_addr)) {
5028 TRACE_USER("Allocate a socket for QUIC connection", QUIC_EV_CONN_INIT, qc);
5029 qc_alloc_fd(qc, local_addr, peer_addr);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005030
5031 /* haproxy soft-stop is supported only for QUIC connections
5032 * with their owned socket.
5033 */
5034 if (qc_test_fd(qc))
5035 _HA_ATOMIC_INC(&jobs);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005036 }
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005037
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005038 /* insert the allocated CID in the receiver datagram handler tree */
5039 if (server)
5040 ebmb_insert(&quic_dghdlrs[tid].cids, &icid->node, icid->cid.len);
5041
5042 /* Select our SCID which is the first CID with 0 as sequence number. */
5043 qc->scid = icid->cid;
5044
5045 /* Packet number spaces initialization. */
5046 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
5047 quic_pktns_init(&qc->pktns[i]);
5048 /* QUIC encryption level context initialization. */
5049 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5050 if (!quic_conn_enc_level_init(qc, i)) {
5051 TRACE_ERROR("Could not initialize an encryption level", QUIC_EV_CONN_INIT, qc);
5052 goto err;
5053 }
5054 /* Initialize the packet number space. */
5055 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
5056 }
5057
5058 qc->original_version = qv;
5059 qc->tps_tls_ext = (qc->original_version->num & 0xff000000) == 0xff000000 ?
5060 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS_DRAFT:
5061 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS;
5062 /* TX part. */
5063 LIST_INIT(&qc->tx.frms_to_send);
5064 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
5065 qc->tx.wbuf = qc->tx.rbuf = 0;
5066 qc->tx.bytes = 0;
5067 qc->tx.buf = BUF_NULL;
5068 /* RX part. */
5069 qc->rx.bytes = 0;
5070 qc->rx.buf = b_make(buf_area, QUIC_CONN_RX_BUFSZ, 0, 0);
5071 for (i = 0; i < QCS_MAX_TYPES; i++)
5072 qc->rx.strms[i].nb_streams = 0;
5073
5074 qc->nb_pkt_for_cc = 1;
5075 qc->nb_pkt_since_cc = 0;
5076
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005077 if (!quic_tls_ku_init(qc)) {
5078 TRACE_ERROR("Key update initialization failed", QUIC_EV_CONN_INIT, qc);
5079 goto err;
5080 }
5081
5082 /* XXX TO DO: Only one path at this time. */
5083 qc->path = &qc->paths[0];
5084 quic_path_init(qc->path, ipv4, cc_algo ? cc_algo : default_quic_cc_algo, qc);
5085
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005086 qc->streams_by_id = EB_ROOT_UNIQUE;
5087 qc->stream_buf_count = 0;
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005088 memcpy(&qc->local_addr, local_addr, sizeof(qc->local_addr));
5089 memcpy(&qc->peer_addr, peer_addr, sizeof qc->peer_addr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005090
5091 if (server && !qc_lstnr_params_init(qc, &l->bind_conf->quic_params,
5092 icid->stateless_reset_token,
5093 dcid->data, dcid->len,
5094 qc->scid.data, qc->scid.len, token_odcid))
5095 goto err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005096
5097 qc->wait_event.tasklet = tasklet_new();
5098 if (!qc->wait_event.tasklet) {
5099 TRACE_ERROR("tasklet_new() failed", QUIC_EV_CONN_TXPKT);
5100 goto err;
5101 }
5102 qc->wait_event.tasklet->process = quic_conn_io_cb;
5103 qc->wait_event.tasklet->context = qc;
5104 qc->wait_event.events = 0;
5105 /* Set tasklet tid based on the SCID selected by us for this
5106 * connection. The upper layer will also be binded on the same thread.
5107 */
Willy Tarreaueed78262022-12-21 09:09:19 +01005108 qc->tid = quic_get_cid_tid(qc->scid.data, &l->rx);
Willy Tarreauf5a0c8a2022-10-13 16:14:11 +02005109 qc->wait_event.tasklet->tid = qc->tid;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02005110 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005111
5112 if (qc_conn_alloc_ssl_ctx(qc) ||
5113 !quic_conn_init_timer(qc) ||
5114 !quic_conn_init_idle_timer_task(qc))
5115 goto err;
5116
5117 ictx = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
5118 if (!qc_new_isecs(qc, ictx,qc->original_version, dcid->data, dcid->len, 1))
5119 goto err;
5120
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005121 LIST_APPEND(&th_ctx->quic_conns, &qc->el_th_ctx);
5122 qc->qc_epoch = HA_ATOMIC_LOAD(&qc_epoch);
5123
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005124 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc);
5125
5126 return qc;
5127
5128 err:
5129 pool_free(pool_head_quic_conn_rxbuf, buf_area);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005130 if (qc) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005131 qc->rx.buf.area = NULL;
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005132 quic_conn_release(qc);
5133 }
5134 TRACE_LEAVE(QUIC_EV_CONN_INIT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005135 return NULL;
5136}
5137
5138/* Release the quic_conn <qc>. The connection is removed from the CIDs tree.
5139 * The connection tasklet is killed.
5140 *
5141 * This function must only be called by the thread responsible of the quic_conn
5142 * tasklet.
5143 */
5144void quic_conn_release(struct quic_conn *qc)
5145{
5146 int i;
5147 struct ssl_sock_ctx *conn_ctx;
5148 struct eb64_node *node;
5149 struct quic_tls_ctx *app_tls_ctx;
5150 struct quic_rx_packet *pkt, *pktback;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005151 struct bref *bref, *back;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005152
5153 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5154
5155 /* We must not free the quic-conn if the MUX is still allocated. */
5156 BUG_ON(qc->mux_state == QC_MUX_READY);
5157
Amaury Denoyellefb375572023-02-01 09:28:32 +01005158 if (qc_test_fd(qc))
5159 _HA_ATOMIC_DEC(&jobs);
5160
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005161 /* Close quic-conn socket fd. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01005162 qc_release_fd(qc, 0);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005163
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005164 /* in the unlikely (but possible) case the connection was just added to
5165 * the accept_list we must delete it from there.
5166 */
5167 MT_LIST_DELETE(&qc->accept_list);
5168
5169 /* free remaining stream descriptors */
5170 node = eb64_first(&qc->streams_by_id);
5171 while (node) {
5172 struct qc_stream_desc *stream;
5173
5174 stream = eb64_entry(node, struct qc_stream_desc, by_id);
5175 node = eb64_next(node);
5176
5177 /* all streams attached to the quic-conn are released, so
5178 * qc_stream_desc_free will liberate the stream instance.
5179 */
5180 BUG_ON(!stream->release);
5181 qc_stream_desc_free(stream, 1);
5182 }
5183
5184 /* Purge Rx packet list. */
5185 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
5186 LIST_DELETE(&pkt->qc_rx_pkt_list);
5187 pool_free(pool_head_quic_rx_packet, pkt);
5188 }
5189
5190 if (qc->idle_timer_task) {
5191 task_destroy(qc->idle_timer_task);
5192 qc->idle_timer_task = NULL;
5193 }
5194
5195 if (qc->timer_task) {
5196 task_destroy(qc->timer_task);
5197 qc->timer_task = NULL;
5198 }
5199
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005200 if (qc->wait_event.tasklet)
5201 tasklet_free(qc->wait_event.tasklet);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005202
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005203 /* remove the connection from receiver cids trees */
5204 ebmb_delete(&qc->odcid_node);
5205 ebmb_delete(&qc->scid_node);
5206 free_quic_conn_cids(qc);
5207
5208 conn_ctx = qc->xprt_ctx;
5209 if (conn_ctx) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005210 SSL_free(conn_ctx->ssl);
5211 pool_free(pool_head_quic_conn_ctx, conn_ctx);
5212 }
5213
5214 quic_tls_ku_free(qc);
5215 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5216 quic_tls_ctx_secs_free(&qc->els[i].tls_ctx);
5217 quic_conn_enc_level_uninit(qc, &qc->els[i]);
5218 }
5219 quic_tls_ctx_secs_free(&qc->negotiated_ictx);
5220
5221 app_tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
5222 pool_free(pool_head_quic_tls_secret, app_tls_ctx->rx.secret);
5223 pool_free(pool_head_quic_tls_secret, app_tls_ctx->tx.secret);
5224
5225 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++) {
5226 quic_pktns_tx_pkts_release(&qc->pktns[i], qc);
5227 quic_free_arngs(qc, &qc->pktns[i].rx.arngs);
5228 }
5229
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005230 /* Detach CLI context watchers currently dumping this connection.
5231 * Reattach them to the next quic_conn instance.
5232 */
5233 list_for_each_entry_safe(bref, back, &qc->back_refs, users) {
5234 /* Remove watcher from this quic_conn instance. */
5235 LIST_DEL_INIT(&bref->users);
5236
5237 /* Attach it to next instance unless it was the last list element. */
5238 if (qc->el_th_ctx.n != &th_ctx->quic_conns) {
5239 struct quic_conn *next = LIST_NEXT(&qc->el_th_ctx,
5240 struct quic_conn *,
5241 el_th_ctx);
5242 LIST_APPEND(&next->back_refs, &bref->users);
5243 }
5244 bref->ref = qc->el_th_ctx.n;
5245 __ha_barrier_store();
5246 }
5247 /* Remove quic_conn from global ha_thread_ctx list. */
5248 LIST_DELETE(&qc->el_th_ctx);
5249
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005250 pool_free(pool_head_quic_conn_rxbuf, qc->rx.buf.area);
5251 pool_free(pool_head_quic_conn, qc);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005252
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005253 TRACE_PROTO("QUIC conn. freed", QUIC_EV_CONN_FREED, qc);
5254
5255 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5256}
5257
5258/* Initialize the timer task of <qc> QUIC connection.
5259 * Returns 1 if succeeded, 0 if not.
5260 */
5261static int quic_conn_init_timer(struct quic_conn *qc)
5262{
5263 int ret = 0;
5264 /* Attach this task to the same thread ID used for the connection */
5265 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5266
5267 qc->timer_task = task_new_on(qc->tid);
5268 if (!qc->timer_task) {
5269 TRACE_ERROR("timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5270 goto leave;
5271 }
5272
5273 qc->timer = TICK_ETERNITY;
5274 qc->timer_task->process = qc_process_timer;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005275 qc->timer_task->context = qc;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005276
5277 ret = 1;
5278 leave:
5279 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5280 return ret;
5281}
5282
5283/* Rearm the idle timer for <qc> QUIC connection. */
5284static void qc_idle_timer_do_rearm(struct quic_conn *qc)
5285{
5286 unsigned int expire;
5287
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01005288 if (stopping && qc->flags & (QUIC_FL_CONN_CLOSING|QUIC_FL_CONN_DRAINING)) {
5289 TRACE_STATE("executing idle timer immediately on stopping", QUIC_EV_CONN_IDLE_TIMER, qc);
5290 task_wakeup(qc->idle_timer_task, TASK_WOKEN_MSG);
5291 }
5292 else {
5293 expire = QUIC_MAX(3 * quic_pto(qc), qc->max_idle_timeout);
5294 qc->idle_timer_task->expire = tick_add(now_ms, MS_TO_TICKS(expire));
5295 task_queue(qc->idle_timer_task);
5296 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005297}
5298
5299/* Rearm the idle timer for <qc> QUIC connection depending on <read> boolean
5300 * which is set to 1 when receiving a packet , and 0 when sending packet
5301 */
5302static void qc_idle_timer_rearm(struct quic_conn *qc, int read)
5303{
5304 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5305
5306 if (read) {
5307 qc->flags |= QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5308 }
5309 else {
5310 qc->flags &= ~QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5311 }
5312 qc_idle_timer_do_rearm(qc);
5313
5314 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5315}
5316
5317/* The task handling the idle timeout */
5318struct task *qc_idle_timer_task(struct task *t, void *ctx, unsigned int state)
5319{
5320 struct quic_conn *qc = ctx;
5321 struct quic_counters *prx_counters = qc->prx_counters;
5322 unsigned int qc_flags = qc->flags;
5323
5324 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5325
5326 /* Notify the MUX before settings QUIC_FL_CONN_EXP_TIMER or the MUX
5327 * might free the quic-conn too early via quic_close().
5328 */
5329 qc_notify_close(qc);
5330
5331 /* If the MUX is still alive, keep the quic-conn. The MUX is
5332 * responsible to call quic_close to release it.
5333 */
5334 qc->flags |= QUIC_FL_CONN_EXP_TIMER;
5335 if (qc->mux_state != QC_MUX_READY)
5336 quic_conn_release(qc);
5337
5338 /* TODO if the quic-conn cannot be freed because of the MUX, we may at
5339 * least clean some parts of it such as the tasklet.
5340 */
5341
5342 if (!(qc_flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
5343 qc_flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
5344 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
5345 HA_ATOMIC_DEC(&prx_counters->half_open_conn);
5346 }
5347
5348 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5349 return NULL;
5350}
5351
5352/* Initialize the idle timeout task for <qc>.
5353 * Returns 1 if succeeded, 0 if not.
5354 */
5355static int quic_conn_init_idle_timer_task(struct quic_conn *qc)
5356{
5357 int ret = 0;
5358
5359 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5360
5361 qc->idle_timer_task = task_new_here();
5362 if (!qc->idle_timer_task) {
5363 TRACE_ERROR("Idle timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5364 goto leave;
5365 }
5366
5367 qc->idle_timer_task->process = qc_idle_timer_task;
5368 qc->idle_timer_task->context = qc;
5369 qc_idle_timer_rearm(qc, 1);
5370 task_queue(qc->idle_timer_task);
5371
5372 ret = 1;
5373 leave:
5374 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5375 return ret;
5376}
5377
5378/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
5379 * past one byte of this buffer.
5380 */
5381static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
5382 struct quic_rx_packet *pkt)
5383{
5384 int ret = 0;
5385 unsigned char dcid_len, scid_len;
5386
5387 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5388
5389 if (end == *buf) {
5390 TRACE_ERROR("buffer data consumed", QUIC_EV_CONN_RXPKT);
5391 goto leave;
5392 }
5393
5394 /* Destination Connection ID Length */
5395 dcid_len = *(*buf)++;
5396 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
5397 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1) {
5398 TRACE_ERROR("too long DCID", QUIC_EV_CONN_RXPKT);
5399 goto leave;
5400 }
5401
5402 if (dcid_len) {
5403 /* Check that the length of this received DCID matches the CID lengths
5404 * of our implementation for non Initials packets only.
5405 */
5406 if (pkt->type != QUIC_PACKET_TYPE_INITIAL &&
5407 pkt->type != QUIC_PACKET_TYPE_0RTT &&
5408 dcid_len != QUIC_HAP_CID_LEN) {
5409 TRACE_ERROR("wrong DCID length", QUIC_EV_CONN_RXPKT);
5410 goto leave;
5411 }
5412
5413 memcpy(pkt->dcid.data, *buf, dcid_len);
5414 }
5415
5416 pkt->dcid.len = dcid_len;
5417 *buf += dcid_len;
5418
5419 /* Source Connection ID Length */
5420 scid_len = *(*buf)++;
5421 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len) {
5422 TRACE_ERROR("too long SCID", QUIC_EV_CONN_RXPKT);
5423 goto leave;
5424 }
5425
5426 if (scid_len)
5427 memcpy(pkt->scid.data, *buf, scid_len);
5428 pkt->scid.len = scid_len;
5429 *buf += scid_len;
5430
5431 ret = 1;
5432 leave:
5433 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5434 return ret;
5435}
5436
5437/* Insert <pkt> RX packet in its <qel> RX packets tree */
5438static void qc_pkt_insert(struct quic_conn *qc,
5439 struct quic_rx_packet *pkt, struct quic_enc_level *qel)
5440{
5441 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
5442
5443 pkt->pn_node.key = pkt->pn;
5444 quic_rx_packet_refinc(pkt);
5445 eb64_insert(&qel->rx.pkts, &pkt->pn_node);
5446
5447 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5448}
5449
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005450/* Try to remove the header protection of <pkt> QUIC packet with <beg> the
5451 * address of the packet first byte, using the keys from encryption level <el>.
5452 *
5453 * If header protection has been successfully removed, packet data are copied
5454 * into <qc> Rx buffer. If <el> secrets are not yet available, the copy is also
5455 * proceeded, and the packet is inserted into <qc> protected packets tree. In
5456 * both cases, packet can now be considered handled by the <qc> connection.
5457 *
5458 * If header protection cannot be removed due to <el> secrets already
5459 * discarded, no operation is conducted.
5460 *
5461 * Returns 1 on success : packet data is now handled by the connection. On
5462 * error 0 is returned : packet should be dropped by the caller.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005463 */
5464static inline int qc_try_rm_hp(struct quic_conn *qc,
5465 struct quic_rx_packet *pkt,
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005466 unsigned char *beg,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005467 struct quic_enc_level **el)
5468{
5469 int ret = 0;
5470 unsigned char *pn = NULL; /* Packet number field */
5471 enum quic_tls_enc_level tel;
5472 struct quic_enc_level *qel;
5473 /* Only for traces. */
5474 struct quic_rx_packet *qpkt_trace;
5475
5476 qpkt_trace = NULL;
5477 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005478 BUG_ON(!pkt->pn_offset);
5479
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005480 /* The packet number is here. This is also the start minus
5481 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
5482 * protection.
5483 */
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005484 pn = beg + pkt->pn_offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005485
5486 tel = quic_packet_type_enc_level(pkt->type);
5487 qel = &qc->els[tel];
5488
5489 if (qc_qel_may_rm_hp(qc, qel)) {
5490 /* Note that the following function enables us to unprotect the packet
5491 * number and its length subsequently used to decrypt the entire
5492 * packets.
5493 */
5494 if (!qc_do_rm_hp(qc, pkt, &qel->tls_ctx,
5495 qel->pktns->rx.largest_pn, pn, beg)) {
5496 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, qc);
5497 goto out;
5498 }
5499
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005500 /* The AAD includes the packet number field. */
5501 pkt->aad_len = pkt->pn_offset + pkt->pnl;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005502 if (pkt->len - pkt->aad_len < QUIC_TLS_TAG_LEN) {
5503 TRACE_PROTO("Too short packet", QUIC_EV_CONN_TRMHP, qc);
5504 goto out;
5505 }
5506
5507 qpkt_trace = pkt;
5508 }
5509 else {
5510 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
5511 /* If the packet number space has been discarded, this packet
5512 * will be not parsed.
5513 */
5514 TRACE_PROTO("Discarded pktns", QUIC_EV_CONN_TRMHP, qc, pkt);
5515 goto out;
5516 }
5517
5518 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005519 LIST_APPEND(&qel->rx.pqpkts, &pkt->list);
5520 quic_rx_packet_refinc(pkt);
5521 }
5522
5523 *el = qel;
5524 /* No reference counter incrementation here!!! */
5525 LIST_APPEND(&qc->rx.pkt_list, &pkt->qc_rx_pkt_list);
5526 memcpy(b_tail(&qc->rx.buf), beg, pkt->len);
5527 pkt->data = (unsigned char *)b_tail(&qc->rx.buf);
5528 b_add(&qc->rx.buf, pkt->len);
5529
5530 ret = 1;
5531 out:
5532 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc, qpkt_trace);
5533 return ret;
5534}
5535
5536/* Parse the header form from <byte0> first byte of <pkt> packet to set its type.
5537 * Also set <*long_header> to 1 if this form is long, 0 if not and the version
5538 * of this packet into <*version>.
5539 */
5540static inline int qc_parse_hd_form(struct quic_rx_packet *pkt,
5541 unsigned char **buf, const unsigned char *end,
5542 int *long_header, uint32_t *version)
5543{
5544 int ret = 0;
5545 const unsigned char byte0 = **buf;
5546
5547 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5548
5549 (*buf)++;
5550 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
5551 unsigned char type =
5552 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
5553
5554 *long_header = 1;
5555 /* Version */
5556 if (!quic_read_uint32(version, (const unsigned char **)buf, end)) {
5557 TRACE_ERROR("could not read the packet version", QUIC_EV_CONN_RXPKT);
5558 goto out;
5559 }
5560
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +01005561 if (*version != QUIC_PROTOCOL_VERSION_2) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005562 pkt->type = type;
5563 }
5564 else {
5565 switch (type) {
5566 case 0:
5567 pkt->type = QUIC_PACKET_TYPE_RETRY;
5568 break;
5569 case 1:
5570 pkt->type = QUIC_PACKET_TYPE_INITIAL;
5571 break;
5572 case 2:
5573 pkt->type = QUIC_PACKET_TYPE_0RTT;
5574 break;
5575 case 3:
5576 pkt->type = QUIC_PACKET_TYPE_HANDSHAKE;
5577 break;
5578 }
5579 }
5580 }
5581 else {
5582 pkt->type = QUIC_PACKET_TYPE_SHORT;
5583 *long_header = 0;
5584 }
5585
5586 ret = 1;
5587 out:
5588 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5589 return ret;
5590}
5591
5592/* Return the QUIC version (quic_version struct) with <version> as version number
5593 * if supported or NULL if not.
5594 */
5595static inline const struct quic_version *qc_supported_version(uint32_t version)
5596{
5597 int i;
5598
5599 for (i = 0; i < quic_versions_nb; i++)
5600 if (quic_versions[i].num == version)
5601 return &quic_versions[i];
5602
5603 return NULL;
5604}
5605
5606/*
5607 * Send a Version Negotiation packet on response to <pkt> on socket <fd> to
5608 * address <addr>.
5609 * Implementation of RFC9000 6. Version Negotiation
5610 *
5611 * TODO implement a rate-limiting sending of Version Negotiation packets
5612 *
5613 * Returns 0 on success else non-zero
5614 */
5615static int send_version_negotiation(int fd, struct sockaddr_storage *addr,
5616 struct quic_rx_packet *pkt)
5617{
5618 char buf[256];
5619 int ret = 0, i = 0, j;
5620 uint32_t version;
5621 const socklen_t addrlen = get_addr_len(addr);
5622
5623 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5624 /*
5625 * header form
5626 * long header, fixed bit to 0 for Version Negotiation
5627 */
5628 /* TODO: RAND_bytes() should be replaced? */
5629 if (RAND_bytes((unsigned char *)buf, 1) != 1) {
5630 TRACE_ERROR("RAND_bytes() error", QUIC_EV_CONN_TXPKT);
5631 goto out;
5632 }
5633
5634 buf[i++] |= '\x80';
5635 /* null version for Version Negotiation */
5636 buf[i++] = '\x00';
5637 buf[i++] = '\x00';
5638 buf[i++] = '\x00';
5639 buf[i++] = '\x00';
5640
5641 /* source connection id */
5642 buf[i++] = pkt->scid.len;
5643 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5644 i += pkt->scid.len;
5645
5646 /* destination connection id */
5647 buf[i++] = pkt->dcid.len;
5648 memcpy(&buf[i], pkt->dcid.data, pkt->dcid.len);
5649 i += pkt->dcid.len;
5650
5651 /* supported version */
5652 for (j = 0; j < quic_versions_nb; j++) {
5653 version = htonl(quic_versions[j].num);
5654 memcpy(&buf[i], &version, sizeof(version));
5655 i += sizeof(version);
5656 }
5657
5658 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0)
5659 goto out;
5660
5661 ret = 1;
5662 out:
5663 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5664 return !ret;
5665}
5666
5667/* Send a stateless reset packet depending on <pkt> RX packet information
5668 * from <fd> UDP socket to <dst>
5669 * Return 1 if succeeded, 0 if not.
5670 */
5671static int send_stateless_reset(struct listener *l, struct sockaddr_storage *dstaddr,
5672 struct quic_rx_packet *rxpkt)
5673{
5674 int ret = 0, pktlen, rndlen;
5675 unsigned char pkt[64];
5676 const socklen_t addrlen = get_addr_len(dstaddr);
5677 struct proxy *prx;
5678 struct quic_counters *prx_counters;
5679
5680 TRACE_ENTER(QUIC_EV_STATELESS_RST);
5681
5682 prx = l->bind_conf->frontend;
5683 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5684 /* 10.3 Stateless Reset (https://www.rfc-editor.org/rfc/rfc9000.html#section-10.3)
5685 * The resulting minimum size of 21 bytes does not guarantee that a Stateless
5686 * Reset is difficult to distinguish from other packets if the recipient requires
5687 * the use of a connection ID. To achieve that end, the endpoint SHOULD ensure
5688 * that all packets it sends are at least 22 bytes longer than the minimum
5689 * connection ID length that it requests the peer to include in its packets,
5690 * adding PADDING frames as necessary. This ensures that any Stateless Reset
5691 * sent by the peer is indistinguishable from a valid packet sent to the endpoint.
5692 * An endpoint that sends a Stateless Reset in response to a packet that is
5693 * 43 bytes or shorter SHOULD send a Stateless Reset that is one byte shorter
5694 * than the packet it responds to.
5695 */
5696
5697 /* Note that we build at most a 42 bytes QUIC packet to mimic a short packet */
5698 pktlen = rxpkt->len <= 43 ? rxpkt->len - 1 : 0;
5699 pktlen = QUIC_MAX(QUIC_STATELESS_RESET_PACKET_MINLEN, pktlen);
5700 rndlen = pktlen - QUIC_STATELESS_RESET_TOKEN_LEN;
5701
5702 /* Put a header of random bytes */
5703 /* TODO: RAND_bytes() should be replaced */
5704 if (RAND_bytes(pkt, rndlen) != 1) {
5705 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_STATELESS_RST);
5706 goto leave;
5707 }
5708
5709 /* Clear the most significant bit, and set the second one */
5710 *pkt = (*pkt & ~0x80) | 0x40;
5711 if (!quic_stateless_reset_token_cpy(NULL, pkt + rndlen, QUIC_STATELESS_RESET_TOKEN_LEN,
5712 rxpkt->dcid.data, rxpkt->dcid.len))
5713 goto leave;
5714
5715 if (sendto(l->rx.fd, pkt, pktlen, 0, (struct sockaddr *)dstaddr, addrlen) < 0)
5716 goto leave;
5717
5718 ret = 1;
5719 HA_ATOMIC_INC(&prx_counters->stateless_reset_sent);
5720 TRACE_PROTO("stateless reset sent", QUIC_EV_STATELESS_RST, NULL, &rxpkt->dcid);
5721 leave:
5722 TRACE_LEAVE(QUIC_EV_STATELESS_RST);
5723 return ret;
5724}
5725
5726/* QUIC server only function.
5727 * Add AAD to <add> buffer from <cid> connection ID and <addr> socket address.
5728 * This is the responsibility of the caller to check <aad> size is big enough
5729 * to contain these data.
5730 * Return the number of bytes copied to <aad>.
5731 */
5732static int quic_generate_retry_token_aad(unsigned char *aad,
5733 uint32_t version,
5734 const struct quic_cid *cid,
5735 const struct sockaddr_storage *addr)
5736{
5737 unsigned char *p;
5738
5739 p = aad;
5740 memcpy(p, &version, sizeof version);
5741 p += sizeof version;
5742 p += quic_saddr_cpy(p, addr);
5743 memcpy(p, cid->data, cid->len);
5744 p += cid->len;
5745
5746 return p - aad;
5747}
5748
5749/* QUIC server only function.
5750 * Generate the token to be used in Retry packets. The token is written to
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05005751 * <buf> with <len> as length. <odcid> is the original destination connection
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005752 * ID and <dcid> is our side destination connection ID (or client source
5753 * connection ID).
5754 * Returns the length of the encoded token or 0 on error.
5755 */
5756static int quic_generate_retry_token(unsigned char *buf, size_t len,
5757 const uint32_t version,
5758 const struct quic_cid *odcid,
5759 const struct quic_cid *dcid,
5760 struct sockaddr_storage *addr)
5761{
5762 int ret = 0;
5763 unsigned char *p;
5764 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005765 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005766 size_t aadlen;
5767 unsigned char salt[QUIC_RETRY_TOKEN_SALTLEN];
5768 unsigned char key[QUIC_TLS_KEY_LEN];
5769 unsigned char iv[QUIC_TLS_IV_LEN];
5770 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5771 size_t seclen = strlen(global.cluster_secret);
5772 EVP_CIPHER_CTX *ctx = NULL;
5773 const EVP_CIPHER *aead = EVP_aes_128_gcm();
5774 uint32_t timestamp = now_ms;
5775
5776 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5777
5778 /* We copy the odcid into the token, prefixed by its one byte
5779 * length, the format token byte. It is followed by an AEAD TAG, and finally
5780 * the random bytes used to derive the secret to encrypt the token.
5781 */
5782 if (1 + dcid->len + 1 + QUIC_TLS_TAG_LEN + sizeof salt > len)
5783 goto err;
5784
5785 aadlen = quic_generate_retry_token_aad(aad, version, dcid, addr);
5786 /* TODO: RAND_bytes() should be replaced */
5787 if (RAND_bytes(salt, sizeof salt) != 1) {
5788 TRACE_ERROR("RAND_bytes()", QUIC_EV_CONN_TXPKT);
5789 goto err;
5790 }
5791
5792 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5793 salt, sizeof salt, sec, seclen)) {
5794 TRACE_ERROR("quic_tls_derive_retry_token_secret() failed", QUIC_EV_CONN_TXPKT);
5795 goto err;
5796 }
5797
5798 if (!quic_tls_tx_ctx_init(&ctx, aead, key)) {
5799 TRACE_ERROR("quic_tls_tx_ctx_init() failed", QUIC_EV_CONN_TXPKT);
5800 goto err;
5801 }
5802
5803 /* Token build */
5804 p = buf;
5805 *p++ = QUIC_TOKEN_FMT_RETRY,
5806 *p++ = odcid->len;
5807 memcpy(p, odcid->data, odcid->len);
5808 p += odcid->len;
5809 write_u32(p, htonl(timestamp));
5810 p += sizeof timestamp;
5811
5812 /* Do not encrypt the QUIC_TOKEN_FMT_RETRY byte */
5813 if (!quic_tls_encrypt(buf + 1, p - buf - 1, aad, aadlen, ctx, aead, key, iv)) {
5814 TRACE_ERROR("quic_tls_encrypt() failed", QUIC_EV_CONN_TXPKT);
5815 goto err;
5816 }
5817
5818 p += QUIC_TLS_TAG_LEN;
5819 memcpy(p, salt, sizeof salt);
5820 p += sizeof salt;
5821 EVP_CIPHER_CTX_free(ctx);
5822
5823 ret = p - buf;
5824 leave:
5825 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5826 return ret;
5827
5828 err:
5829 if (ctx)
5830 EVP_CIPHER_CTX_free(ctx);
5831 goto leave;
5832}
5833
5834/* QUIC server only function.
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005835 *
5836 * Check the validity of the Retry token from Initial packet <pkt>. <dgram> is
5837 * the UDP datagram containing <pkt> and <l> is the listener instance on which
5838 * it was received. If the token is valid, the ODCID of <qc> QUIC connection
5839 * will be put into <odcid>. <qc> is used to retrieve the QUIC version needed
5840 * to validate the token but it can be NULL : in this case the version will be
5841 * retrieved from the packet.
5842 *
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005843 * Return 1 if succeeded, 0 if not.
5844 */
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005845
5846static int quic_retry_token_check(struct quic_rx_packet *pkt,
5847 struct quic_dgram *dgram,
5848 struct listener *l,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005849 struct quic_conn *qc,
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005850 struct quic_cid *odcid)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005851{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005852 struct proxy *prx;
5853 struct quic_counters *prx_counters;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005854 int ret = 0;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005855 unsigned char *token = pkt->token;
5856 const uint64_t tokenlen = pkt->token_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005857 unsigned char buf[128];
5858 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005859 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005860 size_t aadlen;
5861 const unsigned char *salt;
5862 unsigned char key[QUIC_TLS_KEY_LEN];
5863 unsigned char iv[QUIC_TLS_IV_LEN];
5864 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5865 size_t seclen = strlen(global.cluster_secret);
5866 EVP_CIPHER_CTX *ctx = NULL;
5867 const EVP_CIPHER *aead = EVP_aes_128_gcm();
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005868 const struct quic_version *qv = qc ? qc->original_version :
5869 pkt->version;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005870
5871 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5872
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005873 /* The caller must ensure this. */
5874 BUG_ON(!global.cluster_secret || !pkt->token_len);
5875
5876 prx = l->bind_conf->frontend;
5877 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5878
5879 if (*pkt->token != QUIC_TOKEN_FMT_RETRY) {
5880 /* TODO: New token check */
5881 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
5882 goto leave;
5883 }
5884
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005885 if (sizeof buf < tokenlen) {
5886 TRACE_ERROR("too short buffer", QUIC_EV_CONN_LPKT, qc);
5887 goto err;
5888 }
5889
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005890 aadlen = quic_generate_retry_token_aad(aad, qv->num, &pkt->scid, &dgram->saddr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005891 salt = token + tokenlen - QUIC_RETRY_TOKEN_SALTLEN;
5892 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5893 salt, QUIC_RETRY_TOKEN_SALTLEN, sec, seclen)) {
5894 TRACE_ERROR("Could not derive retry secret", QUIC_EV_CONN_LPKT, qc);
5895 goto err;
5896 }
5897
5898 if (!quic_tls_rx_ctx_init(&ctx, aead, key)) {
5899 TRACE_ERROR("quic_tls_rx_ctx_init() failed", QUIC_EV_CONN_LPKT, qc);
5900 goto err;
5901 }
5902
5903 /* Do not decrypt the QUIC_TOKEN_FMT_RETRY byte */
5904 if (!quic_tls_decrypt2(buf, token + 1, tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, aad, aadlen,
5905 ctx, aead, key, iv)) {
5906 TRACE_ERROR("Could not decrypt retry token", QUIC_EV_CONN_LPKT, qc);
5907 goto err;
5908 }
5909
5910 if (parse_retry_token(qc, buf, buf + tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, odcid)) {
5911 TRACE_ERROR("Error during Initial token parsing", QUIC_EV_CONN_LPKT, qc);
5912 goto err;
5913 }
5914
5915 EVP_CIPHER_CTX_free(ctx);
5916
5917 ret = 1;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005918 HA_ATOMIC_INC(&prx_counters->retry_validated);
5919
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005920 leave:
5921 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5922 return ret;
5923
5924 err:
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005925 HA_ATOMIC_INC(&prx_counters->retry_error);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005926 if (ctx)
5927 EVP_CIPHER_CTX_free(ctx);
5928 goto leave;
5929}
5930
5931/* Generate a Retry packet and send it on <fd> socket to <addr> in response to
5932 * the Initial <pkt> packet.
5933 *
5934 * Returns 0 on success else non-zero.
5935 */
5936static int send_retry(int fd, struct sockaddr_storage *addr,
5937 struct quic_rx_packet *pkt, const struct quic_version *qv)
5938{
5939 int ret = 0;
5940 unsigned char buf[128];
5941 int i = 0, token_len;
5942 const socklen_t addrlen = get_addr_len(addr);
5943 struct quic_cid scid;
5944
5945 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5946
5947 /* long header + fixed bit + packet type QUIC_PACKET_TYPE_RETRY */
5948 buf[i++] = (QUIC_PACKET_LONG_HEADER_BIT | QUIC_PACKET_FIXED_BIT) |
5949 (quic_pkt_type(QUIC_PACKET_TYPE_RETRY, qv->num) << QUIC_PACKET_TYPE_SHIFT);
5950 /* version */
5951 buf[i++] = *((unsigned char *)&qv->num + 3);
5952 buf[i++] = *((unsigned char *)&qv->num + 2);
5953 buf[i++] = *((unsigned char *)&qv->num + 1);
5954 buf[i++] = *(unsigned char *)&qv->num;
5955
5956 /* Use the SCID from <pkt> for Retry DCID. */
5957 buf[i++] = pkt->scid.len;
5958 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5959 i += pkt->scid.len;
5960
5961 /* Generate a new CID to be used as SCID for the Retry packet. */
5962 scid.len = QUIC_HAP_CID_LEN;
5963 /* TODO: RAND_bytes() should be replaced */
5964 if (RAND_bytes(scid.data, scid.len) != 1) {
5965 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT);
5966 goto out;
5967 }
5968
5969 buf[i++] = scid.len;
5970 memcpy(&buf[i], scid.data, scid.len);
5971 i += scid.len;
5972
5973 /* token */
5974 if (!(token_len = quic_generate_retry_token(&buf[i], sizeof(buf) - i, qv->num,
5975 &pkt->dcid, &pkt->scid, addr))) {
5976 TRACE_ERROR("quic_generate_retry_token() failed", QUIC_EV_CONN_TXPKT);
5977 goto out;
5978 }
5979
5980 i += token_len;
5981
5982 /* token integrity tag */
5983 if ((&buf[i] - buf < QUIC_TLS_TAG_LEN) ||
5984 !quic_tls_generate_retry_integrity_tag(pkt->dcid.data,
5985 pkt->dcid.len, buf, i, qv)) {
5986 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
5987 goto out;
5988 }
5989
5990 i += QUIC_TLS_TAG_LEN;
5991
5992 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0) {
5993 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
5994 goto out;
5995 }
5996
5997 ret = 1;
5998 out:
5999 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
6000 return !ret;
6001}
6002
6003/* Retrieve a quic_conn instance from the <pkt> DCID field. If the packet is of
6004 * type INITIAL, the ODCID tree is first used. In this case, <saddr> is
6005 * concatenated to the <pkt> DCID field.
6006 *
6007 * Returns the instance or NULL if not found.
6008 */
6009static struct quic_conn *retrieve_qc_conn_from_cid(struct quic_rx_packet *pkt,
6010 struct listener *l,
6011 struct sockaddr_storage *saddr)
6012{
6013 struct quic_conn *qc = NULL;
6014 struct ebmb_node *node;
6015 struct quic_connection_id *id;
6016 /* set if the quic_conn is found in the second DCID tree */
6017
6018 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
6019
6020 /* Look first into ODCIDs tree for INITIAL/0-RTT packets. */
6021 if (pkt->type == QUIC_PACKET_TYPE_INITIAL ||
6022 pkt->type == QUIC_PACKET_TYPE_0RTT) {
6023 /* DCIDs of first packets coming from multiple clients may have
6024 * the same values. Let's distinguish them by concatenating the
6025 * socket addresses.
6026 */
6027 quic_cid_saddr_cat(&pkt->dcid, saddr);
6028 node = ebmb_lookup(&quic_dghdlrs[tid].odcids, pkt->dcid.data,
6029 pkt->dcid.len + pkt->dcid.addrlen);
6030 if (node) {
6031 qc = ebmb_entry(node, struct quic_conn, odcid_node);
6032 goto end;
6033 }
6034 }
6035
6036 /* Look into DCIDs tree for non-INITIAL/0-RTT packets. This may be used
6037 * also for INITIAL/0-RTT non-first packets with the final DCID in
6038 * used.
6039 */
6040 node = ebmb_lookup(&quic_dghdlrs[tid].cids, pkt->dcid.data, pkt->dcid.len);
6041 if (!node)
6042 goto end;
6043
6044 id = ebmb_entry(node, struct quic_connection_id, node);
6045 qc = id->qc;
6046
6047 /* If found in DCIDs tree, remove the quic_conn from the ODCIDs tree.
6048 * If already done, this is a noop.
6049 */
6050 if (qc)
6051 ebmb_delete(&qc->odcid_node);
6052
6053 end:
6054 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
6055 return qc;
6056}
6057
6058/* Try to allocate the <*ssl> SSL session object for <qc> QUIC connection
6059 * with <ssl_ctx> as SSL context inherited settings. Also set the transport
6060 * parameters of this session.
6061 * This is the responsibility of the caller to check the validity of all the
6062 * pointers passed as parameter to this function.
6063 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <qc->conn> to
6064 * CO_ER_SSL_NO_MEM.
6065 */
6066static int qc_ssl_sess_init(struct quic_conn *qc, SSL_CTX *ssl_ctx, SSL **ssl,
6067 unsigned char *params, size_t params_len)
6068{
6069 int retry, ret = -1;
6070
6071 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6072
6073 retry = 1;
6074 retry:
6075 *ssl = SSL_new(ssl_ctx);
6076 if (!*ssl) {
6077 if (!retry--)
6078 goto err;
6079
6080 pool_gc(NULL);
6081 goto retry;
6082 }
6083
6084 if (!SSL_set_quic_method(*ssl, &ha_quic_method) ||
6085 !SSL_set_ex_data(*ssl, ssl_qc_app_data_index, qc)) {
6086 SSL_free(*ssl);
6087 *ssl = NULL;
6088 if (!retry--)
6089 goto err;
6090
6091 pool_gc(NULL);
6092 goto retry;
6093 }
6094
6095 ret = 0;
6096 leave:
6097 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6098 return ret;
6099
6100 err:
6101 qc->conn->err_code = CO_ER_SSL_NO_MEM;
6102 goto leave;
6103}
6104
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006105/* Allocate the ssl_sock_ctx from connection <qc>. This creates the tasklet
6106 * used to process <qc> received packets. The allocated context is stored in
6107 * <qc.xprt_ctx>.
6108 *
6109 * Returns 0 on success else non-zero.
6110 */
6111static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc)
6112{
6113 int ret = 0;
6114 struct bind_conf *bc = qc->li->bind_conf;
6115 struct ssl_sock_ctx *ctx = NULL;
6116
6117 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6118
6119 ctx = pool_zalloc(pool_head_quic_conn_ctx);
6120 if (!ctx) {
6121 TRACE_ERROR("SSL context allocation failed", QUIC_EV_CONN_TXPKT);
6122 goto err;
6123 }
6124
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006125 ctx->subs = NULL;
6126 ctx->xprt_ctx = NULL;
6127 ctx->qc = qc;
6128
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006129 if (qc_is_listener(qc)) {
6130 if (qc_ssl_sess_init(qc, bc->initial_ctx, &ctx->ssl,
6131 qc->enc_params, qc->enc_params_len) == -1) {
6132 goto err;
6133 }
6134#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
6135 /* Enabling 0-RTT */
6136 if (bc->ssl_conf.early_data)
6137 SSL_set_quic_early_data_enabled(ctx->ssl, 1);
6138#endif
6139
6140 SSL_set_accept_state(ctx->ssl);
6141 }
6142
6143 ctx->xprt = xprt_get(XPRT_QUIC);
6144
6145 /* Store the allocated context in <qc>. */
6146 qc->xprt_ctx = ctx;
6147
6148 ret = 1;
6149 leave:
6150 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6151 return !ret;
6152
6153 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006154 pool_free(pool_head_quic_conn_ctx, ctx);
6155 goto leave;
6156}
6157
6158/* Check that all the bytes between <buf> included and <end> address
6159 * excluded are null. This is the responsibility of the caller to
6160 * check that there is at least one byte between <buf> end <end>.
6161 * Return 1 if this all the bytes are null, 0 if not.
6162 */
6163static inline int quic_padding_check(const unsigned char *buf,
6164 const unsigned char *end)
6165{
6166 while (buf < end && !*buf)
6167 buf++;
6168
6169 return buf == end;
6170}
6171
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006172/* Find the associated connection to the packet <pkt> or create a new one if
6173 * this is an Initial packet. <dgram> is the datagram containing the packet and
6174 * <l> is the listener instance on which it was received.
6175 *
6176 * Returns the quic-conn instance or NULL.
6177 */
6178static struct quic_conn *quic_rx_pkt_retrieve_conn(struct quic_rx_packet *pkt,
6179 struct quic_dgram *dgram,
6180 struct listener *l)
6181{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006182 struct quic_cid token_odcid = { .len = 0 };
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006183 struct quic_conn *qc = NULL;
6184 struct proxy *prx;
6185 struct quic_counters *prx_counters;
6186
6187 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6188
6189 prx = l->bind_conf->frontend;
6190 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6191
6192 qc = retrieve_qc_conn_from_cid(pkt, l, &dgram->saddr);
6193
6194 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6195 BUG_ON(!pkt->version); /* This must not happen. */
6196
6197 if (global.cluster_secret && pkt->token_len) {
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006198 if (!quic_retry_token_check(pkt, dgram, l, qc, &token_odcid))
6199 goto err;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006200 }
6201
6202 if (!qc) {
6203 int ipv4;
6204
6205 if (global.cluster_secret && !pkt->token_len && !(l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) &&
6206 HA_ATOMIC_LOAD(&prx_counters->half_open_conn) >= global.tune.quic_retry_threshold) {
6207 TRACE_PROTO("Initial without token, sending retry",
6208 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6209 if (send_retry(l->rx.fd, &dgram->saddr, pkt, pkt->version)) {
6210 TRACE_ERROR("Error during Retry generation",
6211 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6212 goto out;
6213 }
6214
6215 HA_ATOMIC_INC(&prx_counters->retry_sent);
6216 goto out;
6217 }
6218
6219 /* RFC 9000 7.2. Negotiating Connection IDs:
6220 * When an Initial packet is sent by a client that has not previously
6221 * received an Initial or Retry packet from the server, the client
6222 * populates the Destination Connection ID field with an unpredictable
6223 * value. This Destination Connection ID MUST be at least 8 bytes in length.
6224 */
6225 if (pkt->dcid.len < QUIC_ODCID_MINLEN) {
6226 TRACE_PROTO("dropped packet",
6227 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6228 goto err;
6229 }
6230
6231 pkt->saddr = dgram->saddr;
6232 ipv4 = dgram->saddr.ss_family == AF_INET;
6233
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006234 qc = qc_new_conn(pkt->version, ipv4, &pkt->dcid, &pkt->scid, &token_odcid,
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006235 &dgram->daddr, &pkt->saddr, 1,
6236 !!pkt->token_len, l);
6237 if (qc == NULL)
6238 goto err;
6239
6240 HA_ATOMIC_INC(&prx_counters->half_open_conn);
6241 /* Insert the DCID the QUIC client has chosen (only for listeners) */
6242 ebmb_insert(&quic_dghdlrs[tid].odcids, &qc->odcid_node,
6243 qc->odcid.len + qc->odcid.addrlen);
6244 }
6245 }
6246 else if (!qc) {
6247 TRACE_PROTO("No connection on a non Initial packet", QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6248 if (global.cluster_secret && !send_stateless_reset(l, &dgram->saddr, pkt))
6249 TRACE_ERROR("stateless reset not sent", QUIC_EV_CONN_LPKT, qc);
6250 goto err;
6251 }
6252
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006253 out:
6254 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6255 return qc;
6256
6257 err:
6258 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
6259 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
6260 return NULL;
6261}
6262
Amaury Denoyelle98289692022-10-19 15:37:44 +02006263/* Parse a QUIC packet starting at <buf>. Data won't be read after <end> even
6264 * if the packet is incomplete. This function will populate fields of <pkt>
6265 * instance, most notably its length. <dgram> is the UDP datagram which
6266 * contains the parsed packet. <l> is the listener instance on which it was
6267 * received.
6268 *
6269 * Returns 0 on success else non-zero. Packet length is guaranteed to be set to
6270 * the real packet value or to cover all data between <buf> and <end> : this is
6271 * useful to reject a whole datagram.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006272 */
Amaury Denoyelle98289692022-10-19 15:37:44 +02006273static int quic_rx_pkt_parse(struct quic_rx_packet *pkt,
6274 unsigned char *buf, const unsigned char *end,
6275 struct quic_dgram *dgram, struct listener *l)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006276{
Amaury Denoyelle98289692022-10-19 15:37:44 +02006277 const unsigned char *beg = buf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006278 struct proxy *prx;
6279 struct quic_counters *prx_counters;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006280 int long_header = 0;
Willy Tarreau33a68702022-11-24 09:16:41 +01006281 uint32_t version = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006282 const struct quic_version *qv = NULL;
6283
6284 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6285
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006286 prx = l->bind_conf->frontend;
6287 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6288 /* This ist only to please to traces and distinguish the
6289 * packet with parsed packet number from others.
6290 */
6291 pkt->pn_node.key = (uint64_t)-1;
6292 if (end <= buf) {
6293 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6294 goto drop;
6295 }
6296
6297 /* Fixed bit */
6298 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006299 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
6300 quic_padding_check(buf, end)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006301 /* Some browsers may pad the remaining datagram space with null bytes.
6302 * That is what we called add padding out of QUIC packets. Such
6303 * datagrams must be considered as valid. But we can only consume
6304 * the remaining space.
6305 */
6306 pkt->len = end - buf;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006307 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006308 }
6309
6310 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6311 goto drop;
6312 }
6313
6314 /* Header form */
6315 if (!qc_parse_hd_form(pkt, &buf, end, &long_header, &version)) {
6316 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6317 goto drop;
6318 }
6319
6320 if (long_header) {
6321 uint64_t len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006322
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006323 TRACE_PROTO("long header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006324 if (!quic_packet_read_long_header(&buf, end, pkt)) {
6325 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6326 goto drop;
6327 }
6328
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006329 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6330 * they must have the same DCID.
6331 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006332 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006333 (pkt->dcid.len != dgram->dcid_len ||
6334 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006335 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006336 goto drop;
6337 }
6338
6339 /* Retry of Version Negotiation packets are only sent by servers */
6340 if (pkt->type == QUIC_PACKET_TYPE_RETRY || !version) {
6341 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6342 goto drop;
6343 }
6344
6345 /* RFC9000 6. Version Negotiation */
6346 qv = qc_supported_version(version);
6347 if (!qv) {
6348 /* unsupported version, send Negotiation packet */
6349 if (send_version_negotiation(l->rx.fd, &dgram->saddr, pkt)) {
6350 TRACE_ERROR("VN packet not sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006351 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006352 }
6353
6354 TRACE_PROTO("VN packet sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006355 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006356 }
Amaury Denoyelle0eae5722022-10-17 18:05:18 +02006357 pkt->version = qv;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006358
6359 /* For Initial packets, and for servers (QUIC clients connections),
6360 * there is no Initial connection IDs storage.
6361 */
6362 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6363 uint64_t token_len;
6364
6365 if (!quic_dec_int(&token_len, (const unsigned char **)&buf, end) ||
6366 end - buf < token_len) {
6367 TRACE_PROTO("Packet dropped",
6368 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6369 goto drop;
6370 }
6371
6372 /* TODO Retry should be automatically activated if
6373 * suspect network usage is detected.
6374 */
6375 if (global.cluster_secret && !token_len) {
6376 if (l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) {
6377 TRACE_PROTO("Initial without token, sending retry",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006378 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006379 if (send_retry(l->rx.fd, &dgram->saddr, pkt, qv)) {
6380 TRACE_PROTO("Error during Retry generation",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006381 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006382 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006383 }
6384
6385 HA_ATOMIC_INC(&prx_counters->retry_sent);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006386 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006387 }
6388 }
6389 else if (!global.cluster_secret && token_len) {
6390 /* Impossible case: a token was received without configured
6391 * cluster secret.
6392 */
6393 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT,
6394 NULL, NULL, NULL, qv);
6395 goto drop;
6396 }
6397
6398 pkt->token = buf;
6399 pkt->token_len = token_len;
6400 buf += pkt->token_len;
6401 }
6402 else if (pkt->type != QUIC_PACKET_TYPE_0RTT) {
6403 if (pkt->dcid.len != QUIC_HAP_CID_LEN) {
6404 TRACE_PROTO("Packet dropped",
6405 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6406 goto drop;
6407 }
6408 }
6409
6410 if (!quic_dec_int(&len, (const unsigned char **)&buf, end) ||
6411 end - buf < len) {
6412 TRACE_PROTO("Packet dropped",
6413 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6414 goto drop;
6415 }
6416
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006417 /* Packet Number is stored here. Packet Length totalizes the
6418 * rest of the content.
6419 */
6420 pkt->pn_offset = buf - beg;
6421 pkt->len = pkt->pn_offset + len;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006422
Frédéric Lécaille35218c62023-02-16 11:40:11 +01006423 /* RFC 9000. Initial Datagram Size
6424 *
6425 * A server MUST discard an Initial packet that is carried in a UDP datagram
6426 * with a payload that is smaller than the smallest allowed maximum datagram
6427 * size of 1200 bytes.
6428 */
6429 if (pkt->type == QUIC_PACKET_TYPE_INITIAL &&
6430 dgram->len < QUIC_INITIAL_PACKET_MINLEN) {
6431 TRACE_PROTO("Too short datagram with an Initial packet", QUIC_EV_CONN_LPKT);
6432 HA_ATOMIC_INC(&prx_counters->too_short_initial_dgram);
6433 goto drop;
6434 }
6435
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006436 /* Interrupt parsing after packet length retrieval : this
6437 * ensures that only the packet is dropped but not the whole
6438 * datagram.
6439 */
6440 if (pkt->type == QUIC_PACKET_TYPE_0RTT && !l->bind_conf->ssl_conf.early_data) {
6441 TRACE_PROTO("0-RTT packet not supported", QUIC_EV_CONN_LPKT);
6442 goto drop;
6443 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006444 }
6445 else {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006446 TRACE_PROTO("short header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006447 if (end - buf < QUIC_HAP_CID_LEN) {
6448 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6449 goto drop;
6450 }
6451
6452 memcpy(pkt->dcid.data, buf, QUIC_HAP_CID_LEN);
6453 pkt->dcid.len = QUIC_HAP_CID_LEN;
6454
6455 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6456 * they must have the same DCID.
6457 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006458 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006459 (pkt->dcid.len != dgram->dcid_len ||
6460 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006461 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006462 goto drop;
6463 }
6464
6465 buf += QUIC_HAP_CID_LEN;
6466
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006467 pkt->pn_offset = buf - beg;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006468 /* A short packet is the last one of a UDP datagram. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006469 pkt->len = end - beg;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006470 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006471
Amaury Denoyelle98289692022-10-19 15:37:44 +02006472 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6473 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006474
Amaury Denoyelle98289692022-10-19 15:37:44 +02006475 drop:
6476 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006477 drop_silent:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006478 if (!pkt->len)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006479 pkt->len = end - beg;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006480 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6481 return -1;
6482}
6483
6484/* Check if received packet <pkt> should be drop due to <qc> already in closing
6485 * state. This can be true if a CONNECTION_CLOSE has already been emitted for
6486 * this connection.
6487 *
6488 * Returns false if connection is not in closing state else true. The caller
6489 * should drop the whole datagram in the last case to not mess up <qc>
6490 * CONNECTION_CLOSE rate limit counter.
6491 */
6492static int qc_rx_check_closing(struct quic_conn *qc,
6493 struct quic_rx_packet *pkt)
6494{
6495 if (!(qc->flags & QUIC_FL_CONN_CLOSING))
6496 return 0;
6497
6498 TRACE_STATE("Closing state connection", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6499
6500 /* Check if CONNECTION_CLOSE rate reemission is reached. */
6501 if (++qc->nb_pkt_since_cc >= qc->nb_pkt_for_cc) {
6502 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
6503 qc->nb_pkt_for_cc++;
6504 qc->nb_pkt_since_cc = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006505 }
6506
Amaury Denoyelle98289692022-10-19 15:37:44 +02006507 return 1;
6508}
6509
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006510/* React to a connection migration initiated on <qc> by a client with the new
6511 * path addresses <peer_addr>/<local_addr>.
6512 *
6513 * Returns 0 on success else non-zero.
6514 */
6515static int qc_handle_conn_migration(struct quic_conn *qc,
6516 const struct sockaddr_storage *peer_addr,
6517 const struct sockaddr_storage *local_addr)
6518{
6519 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6520
Frédéric Lécaille6fc86972023-01-12 08:29:23 +01006521 /* RFC 9000. Connection Migration
6522 *
6523 * If the peer sent the disable_active_migration transport parameter,
6524 * an endpoint also MUST NOT send packets (including probing packets;
6525 * see Section 9.1) from a different local address to the address the peer
6526 * used during the handshake, unless the endpoint has acted on a
6527 * preferred_address transport parameter from the peer.
6528 */
6529 if (qc->li->bind_conf->quic_params.disable_active_migration) {
6530 TRACE_ERROR("Active migration was disabled, datagram dropped", QUIC_EV_CONN_LPKT, qc);
6531 goto err;
6532 }
6533
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006534 /* RFC 9000 9. Connection Migration
6535 *
Amaury Denoyelleeb6be982022-11-21 11:14:45 +01006536 * The design of QUIC relies on endpoints retaining a stable address for
6537 * the duration of the handshake. An endpoint MUST NOT initiate
6538 * connection migration before the handshake is confirmed, as defined in
6539 * Section 4.1.2 of [QUIC-TLS].
6540 */
6541 if (qc->state < QUIC_HS_ST_COMPLETE) {
6542 TRACE_STATE("Connection migration during handshake rejected", QUIC_EV_CONN_LPKT, qc);
6543 goto err;
6544 }
6545
6546 /* RFC 9000 9. Connection Migration
6547 *
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006548 * TODO
6549 * An endpoint MUST
6550 * perform path validation (Section 8.2) if it detects any change to a
6551 * peer's address, unless it has previously validated that address.
6552 */
6553
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006554 /* Update quic-conn owned socket if in used.
6555 * TODO try to reuse it instead of closing and opening a new one.
6556 */
6557 if (qc_test_fd(qc)) {
6558 /* TODO try to reuse socket instead of closing it and opening a new one. */
6559 TRACE_STATE("Connection migration detected, allocate a new connection socket", QUIC_EV_CONN_LPKT, qc);
6560 qc_release_fd(qc, 1);
Amaury Denoyellefb375572023-02-01 09:28:32 +01006561 /* TODO need to adjust <jobs> on socket allocation failure. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006562 qc_alloc_fd(qc, local_addr, peer_addr);
6563 }
6564
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006565 qc->local_addr = *local_addr;
6566 qc->peer_addr = *peer_addr;
6567 HA_ATOMIC_INC(&qc->prx_counters->conn_migration_done);
6568
6569 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6570 return 0;
6571
6572 err:
6573 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6574 return 1;
6575}
6576
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006577/* Release the memory for the RX packets which are no more referenced
6578 * and consume their payloads which have been copied to the RX buffer
6579 * for the connection.
6580 * Always succeeds.
6581 */
6582static inline void quic_rx_pkts_del(struct quic_conn *qc)
6583{
6584 struct quic_rx_packet *pkt, *pktback;
6585
6586 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
6587 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
6588 "pkt #%lld(type=%d,len=%zu,rawlen=%zu,refcnt=%u) (diff: %zd)",
6589 (long long)pkt->pn_node.key,
6590 pkt->type, pkt->len, pkt->raw_len, pkt->refcnt,
6591 (unsigned char *)b_head(&qc->rx.buf) - pkt->data);
6592 if (pkt->data != (unsigned char *)b_head(&qc->rx.buf)) {
6593 size_t cdata;
6594
6595 cdata = b_contig_data(&qc->rx.buf, 0);
6596 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
6597 "cdata=%zu *b_head()=0x%x", cdata, *b_head(&qc->rx.buf));
6598 if (cdata && !*b_head(&qc->rx.buf)) {
6599 /* Consume the remaining data */
6600 b_del(&qc->rx.buf, cdata);
6601 }
6602 break;
6603 }
6604
6605 if (pkt->refcnt)
6606 break;
6607
6608 b_del(&qc->rx.buf, pkt->raw_len);
6609 LIST_DELETE(&pkt->qc_rx_pkt_list);
6610 pool_free(pool_head_quic_rx_packet, pkt);
6611 }
6612
6613 /* In frequent cases the buffer will be emptied at this stage. */
6614 b_realign_if_empty(&qc->rx.buf);
6615}
6616
Amaury Denoyelle98289692022-10-19 15:37:44 +02006617/* Handle a parsed packet <pkt> by the connection <qc>. Data will be copied
6618 * into <qc> receive buffer after header protection removal procedure.
6619 *
6620 * <dgram> must be set to the datagram which contains the QUIC packet. <beg>
6621 * must point to packet buffer first byte.
6622 *
6623 * <tasklist_head> may be non-NULL when the caller treat several datagrams for
6624 * different quic-conn. In this case, each quic-conn tasklet will be appended
6625 * to it in order to be woken up after the current task.
6626 *
6627 * The caller can safely removed the packet data. If packet refcount was not
6628 * incremented by this function, it means that the connection did not handled
6629 * it and it should be freed by the caller.
6630 */
6631static void qc_rx_pkt_handle(struct quic_conn *qc, struct quic_rx_packet *pkt,
6632 struct quic_dgram *dgram, unsigned char *beg,
6633 struct list **tasklist_head)
6634{
6635 const struct quic_version *qv = pkt->version;
6636 struct quic_enc_level *qel = NULL;
6637 size_t b_cspace;
Frédéric Lécaille8f7d2242023-02-15 11:55:21 +01006638 int io_cb_wakeup = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006639
Amaury Denoyelle3f474e62022-11-24 17:15:08 +01006640 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6641
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006642 if (pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST &&
6643 !quic_peer_validated_addr(qc) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006644 qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED) {
6645 TRACE_PROTO("PTO timer must be armed after anti-amplication was reached",
6646 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6647 /* Reset the anti-amplification bit. It will be set again
6648 * when sending the next packet if reached again.
6649 */
6650 qc->flags &= ~QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006651 io_cb_wakeup = 1;
6652 }
6653
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006654 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
6655 TRACE_PROTO("Connection error",
6656 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6657 goto out;
6658 }
6659
6660 pkt->raw_len = pkt->len;
6661 quic_rx_pkts_del(qc);
6662 b_cspace = b_contig_space(&qc->rx.buf);
6663 if (b_cspace < pkt->len) {
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006664 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
6665 "bspace=%zu pkt->len=%zu", b_cspace, pkt->len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006666 /* Do not consume buf if space not at the end. */
6667 if (b_tail(&qc->rx.buf) + b_cspace < b_wrap(&qc->rx.buf)) {
6668 TRACE_PROTO("Packet dropped",
6669 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006670 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006671 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006672 }
6673
6674 /* Let us consume the remaining contiguous space. */
6675 if (b_cspace) {
6676 b_putchr(&qc->rx.buf, 0x00);
6677 b_cspace--;
6678 }
6679 b_add(&qc->rx.buf, b_cspace);
6680 if (b_contig_space(&qc->rx.buf) < pkt->len) {
6681 TRACE_PROTO("Too big packet",
6682 QUIC_EV_CONN_LPKT, qc, pkt, &pkt->len, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006683 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006684 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006685 }
6686 }
6687
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006688 if (!qc_try_rm_hp(qc, pkt, beg, &qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006689 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6690 goto drop;
6691 }
6692
6693 TRACE_DATA("New packet", QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6694 if (pkt->aad_len)
6695 qc_pkt_insert(qc, pkt, qel);
6696 out:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006697 *tasklist_head = tasklet_wakeup_after(*tasklist_head,
6698 qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006699
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006700 drop_silent:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006701 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006702 return;
6703
6704 drop:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006705 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt);
Frédéric Lécaille75c8ad52023-02-08 16:08:28 +01006706 if (io_cb_wakeup) {
6707 TRACE_DEVEL("needs to wakeup the timer task after the amplification limit was reached",
6708 QUIC_EV_CONN_LPKT, qc);
6709 qc_set_timer(qc);
6710 if (qc->timer_task && tick_isset(qc->timer) && tick_is_lt(qc->timer, now_ms))
6711 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
6712 }
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006713
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006714 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
6715}
6716
6717/* This function builds into <buf> buffer a QUIC long packet header.
6718 * Return 1 if enough room to build this header, 0 if not.
6719 */
6720static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
6721 int type, size_t pn_len,
6722 struct quic_conn *qc, const struct quic_version *ver)
6723{
6724 int ret = 0;
6725
6726 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6727
6728 if (end - *buf < sizeof ver->num + qc->dcid.len + qc->scid.len + 3) {
6729 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6730 goto leave;
6731 }
6732
6733 type = quic_pkt_type(type, ver->num);
6734 /* #0 byte flags */
6735 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
6736 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
6737 /* Version */
6738 quic_write_uint32(buf, end, ver->num);
6739 *(*buf)++ = qc->dcid.len;
6740 /* Destination connection ID */
6741 if (qc->dcid.len) {
6742 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6743 *buf += qc->dcid.len;
6744 }
6745 /* Source connection ID */
6746 *(*buf)++ = qc->scid.len;
6747 if (qc->scid.len) {
6748 memcpy(*buf, qc->scid.data, qc->scid.len);
6749 *buf += qc->scid.len;
6750 }
6751
6752 ret = 1;
6753 leave:
6754 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6755 return ret;
6756}
6757
6758/* This function builds into <buf> buffer a QUIC short packet header.
6759 * Return 1 if enough room to build this header, 0 if not.
6760 */
6761static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
6762 size_t pn_len, struct quic_conn *qc,
6763 unsigned char tls_flags)
6764{
6765 int ret = 0;
6766
6767 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6768
6769 if (end - *buf < 1 + qc->dcid.len) {
6770 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6771 goto leave;
6772 }
6773
6774 /* #0 byte flags */
6775 *(*buf)++ = QUIC_PACKET_FIXED_BIT |
6776 ((tls_flags & QUIC_FL_TLS_KP_BIT_SET) ? QUIC_PACKET_KEY_PHASE_BIT : 0) | (pn_len - 1);
6777 /* Destination connection ID */
6778 if (qc->dcid.len) {
6779 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6780 *buf += qc->dcid.len;
6781 }
6782
6783 ret = 1;
6784 leave:
6785 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6786 return ret;
6787}
6788
6789/* Apply QUIC header protection to the packet with <buf> as first byte address,
6790 * <pn> as address of the Packet number field, <pnlen> being this field length
6791 * with <aead> as AEAD cipher and <key> as secret key.
6792 * Returns 1 if succeeded or 0 if failed.
6793 */
6794static int quic_apply_header_protection(struct quic_conn *qc, unsigned char *buf,
6795 unsigned char *pn, size_t pnlen,
6796 struct quic_tls_ctx *tls_ctx)
6797
6798{
6799 int i, ret = 0;
6800 /* We need an IV of at least 5 bytes: one byte for bytes #0
6801 * and at most 4 bytes for the packet number
6802 */
6803 unsigned char mask[5] = {0};
6804 EVP_CIPHER_CTX *aes_ctx = tls_ctx->tx.hp_ctx;
6805
6806 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6807
6808 if (!quic_tls_aes_encrypt(mask, pn + QUIC_PACKET_PN_MAXLEN, sizeof mask, aes_ctx)) {
6809 TRACE_ERROR("could not apply header protection", QUIC_EV_CONN_TXPKT, qc);
6810 goto out;
6811 }
6812
6813 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
6814 for (i = 0; i < pnlen; i++)
6815 pn[i] ^= mask[i + 1];
6816
6817 ret = 1;
6818 out:
6819 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6820 return ret;
6821}
6822
6823/* Reduce the encoded size of <ack_frm> ACK frame removing the last
6824 * ACK ranges if needed to a value below <limit> in bytes.
6825 * Return 1 if succeeded, 0 if not.
6826 */
6827static int quic_ack_frm_reduce_sz(struct quic_conn *qc,
6828 struct quic_frame *ack_frm, size_t limit)
6829{
6830 size_t room, ack_delay_sz;
6831 int ret = 0;
6832
6833 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6834
6835 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
6836 /* A frame is made of 1 byte for the frame type. */
6837 room = limit - ack_delay_sz - 1;
6838 if (!quic_rm_last_ack_ranges(qc, ack_frm->tx_ack.arngs, room))
6839 goto leave;
6840
6841 ret = 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
6842 leave:
6843 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6844 return ret;
6845}
6846
6847/* Prepare into <outlist> as most as possible ack-eliciting frame from their
6848 * <inlist> prebuilt frames for <qel> encryption level to be encoded in a buffer
6849 * with <room> as available room, and <*len> the packet Length field initialized
6850 * with the number of bytes already present in this buffer which must be taken
6851 * into an account for the Length packet field value. <headlen> is the number of
6852 * bytes already present in this packet before building frames.
6853 *
6854 * Update consequently <*len> to reflect the size of these frames built
6855 * by this function. Also attach these frames to <l> frame list.
6856 * Return 1 if at least one ack-eleciting frame could be built, 0 if not.
6857 */
6858static inline int qc_build_frms(struct list *outlist, struct list *inlist,
6859 size_t room, size_t *len, size_t headlen,
6860 struct quic_enc_level *qel,
6861 struct quic_conn *qc)
6862{
6863 int ret;
6864 struct quic_frame *cf, *cfbak;
6865
6866 TRACE_ENTER(QUIC_EV_CONN_BCFRMS, qc);
6867
6868 ret = 0;
6869 if (*len > room)
6870 goto leave;
6871
6872 /* If we are not probing we must take into an account the congestion
6873 * control window.
6874 */
6875 if (!qel->pktns->tx.pto_probe) {
6876 size_t remain = quic_path_prep_data(qc->path);
6877
6878 if (headlen > remain)
6879 goto leave;
6880
6881 room = QUIC_MIN(room, remain - headlen);
6882 }
6883
6884 TRACE_PROTO("************** frames build (headlen)",
6885 QUIC_EV_CONN_BCFRMS, qc, &headlen);
6886
6887 /* NOTE: switch/case block inside a loop, a successful status must be
6888 * returned by this function only if at least one frame could be built
6889 * in the switch/case block.
6890 */
6891 list_for_each_entry_safe(cf, cfbak, inlist, list) {
6892 /* header length, data length, frame length. */
6893 size_t hlen, dlen, dlen_sz, avail_room, flen;
6894
6895 if (!room)
6896 break;
6897
6898 switch (cf->type) {
6899 case QUIC_FT_CRYPTO:
6900 TRACE_DEVEL(" New CRYPTO frame build (room, len)",
6901 QUIC_EV_CONN_BCFRMS, qc, &room, len);
6902 /* Compute the length of this CRYPTO frame header */
6903 hlen = 1 + quic_int_getsize(cf->crypto.offset);
6904 /* Compute the data length of this CRyPTO frame. */
6905 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
6906 TRACE_DEVEL(" CRYPTO data length (hlen, crypto.len, dlen)",
6907 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->crypto.len, &dlen);
6908 if (!dlen)
6909 continue;
6910
6911 /* CRYPTO frame length. */
6912 flen = hlen + quic_int_getsize(dlen) + dlen;
6913 TRACE_DEVEL(" CRYPTO frame length (flen)",
6914 QUIC_EV_CONN_BCFRMS, qc, &flen);
6915 /* Add the CRYPTO data length and its encoded length to the packet
6916 * length and the length of this length.
6917 */
6918 *len += flen;
6919 room -= flen;
6920 if (dlen == cf->crypto.len) {
6921 /* <cf> CRYPTO data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01006922 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006923 LIST_APPEND(outlist, &cf->list);
6924 }
6925 else {
6926 struct quic_frame *new_cf;
6927
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01006928 new_cf = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006929 if (!new_cf) {
6930 TRACE_ERROR("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, qc);
6931 continue;
6932 }
6933
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006934 new_cf->crypto.len = dlen;
6935 new_cf->crypto.offset = cf->crypto.offset;
6936 new_cf->crypto.qel = qel;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006937 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006938 if (cf->origin) {
6939 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
6940 /* This <cf> frame was duplicated */
6941 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
6942 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01006943 /* Detach the remaining CRYPTO frame from its original frame */
6944 LIST_DEL_INIT(&cf->ref);
6945 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006946 }
6947 LIST_APPEND(outlist, &new_cf->list);
6948 /* Consume <dlen> bytes of the current frame. */
6949 cf->crypto.len -= dlen;
6950 cf->crypto.offset += dlen;
6951 }
6952 break;
6953
6954 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
6955 if (cf->flags & QUIC_FL_TX_FRAME_LOST) {
6956 struct eb64_node *node = NULL;
6957 struct qc_stream_desc *stream_desc = NULL;
6958 struct quic_stream *strm = &cf->stream;
6959
6960 /* As this frame has been already lost, ensure the stream is always
6961 * available or the range of this frame is not consumed before
6962 * resending it.
6963 */
6964 node = eb64_lookup(&qc->streams_by_id, strm->id);
6965 if (!node) {
6966 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01006967 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006968 continue;
6969 }
6970
6971 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
6972 if (strm->offset.key + strm->len <= stream_desc->ack_offset) {
6973 TRACE_DEVEL("ignored frame frame in already acked range",
6974 QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01006975 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006976 continue;
6977 }
6978 else if (strm->offset.key < stream_desc->ack_offset) {
6979 strm->offset.key = stream_desc->ack_offset;
6980 TRACE_DEVEL("updated partially acked frame",
6981 QUIC_EV_CONN_PRSAFRM, qc, cf);
6982 }
6983 }
6984 /* Note that these frames are accepted in short packets only without
6985 * "Length" packet field. Here, <*len> is used only to compute the
6986 * sum of the lengths of the already built frames for this packet.
6987 *
6988 * Compute the length of this STREAM frame "header" made a all the field
6989 * excepting the variable ones. Note that +1 is for the type of this frame.
6990 */
6991 hlen = 1 + quic_int_getsize(cf->stream.id) +
6992 ((cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT) ? quic_int_getsize(cf->stream.offset.key) : 0);
6993 /* Compute the data length of this STREAM frame. */
6994 avail_room = room - hlen - *len;
6995 if ((ssize_t)avail_room <= 0)
6996 continue;
6997
6998 TRACE_DEVEL(" New STREAM frame build (room, len)",
6999 QUIC_EV_CONN_BCFRMS, qc, &room, len);
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007000
7001 /* hlen contains STREAM id and offset. Ensure there is
7002 * enough room for length field.
7003 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007004 if (cf->type & QUIC_STREAM_FRAME_TYPE_LEN_BIT) {
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007005 dlen = QUIC_MIN((uint64_t)max_available_room(avail_room, &dlen_sz),
7006 cf->stream.len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007007 dlen_sz = quic_int_getsize(dlen);
7008 flen = hlen + dlen_sz + dlen;
7009 }
7010 else {
7011 dlen = QUIC_MIN((uint64_t)avail_room, cf->stream.len);
7012 flen = hlen + dlen;
7013 }
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007014
7015 if (cf->stream.len && !dlen) {
7016 /* Only a small gap is left on buffer, not
7017 * enough to encode the STREAM data length.
7018 */
7019 continue;
7020 }
7021
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007022 TRACE_DEVEL(" STREAM data length (hlen, stream.len, dlen)",
7023 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->stream.len, &dlen);
7024 TRACE_DEVEL(" STREAM frame length (flen)",
7025 QUIC_EV_CONN_BCFRMS, qc, &flen);
7026 /* Add the STREAM data length and its encoded length to the packet
7027 * length and the length of this length.
7028 */
7029 *len += flen;
7030 room -= flen;
7031 if (dlen == cf->stream.len) {
7032 /* <cf> STREAM data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007033 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007034 LIST_APPEND(outlist, &cf->list);
7035
7036 /* Do not notify MUX on retransmission. */
7037 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7038 qcc_streams_sent_done(cf->stream.stream->ctx,
7039 cf->stream.len,
7040 cf->stream.offset.key);
7041 }
7042 }
7043 else {
7044 struct quic_frame *new_cf;
7045 struct buffer cf_buf;
7046
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01007047 new_cf = qc_frm_alloc(cf->type);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007048 if (!new_cf) {
7049 TRACE_ERROR("No memory for new STREAM frame", QUIC_EV_CONN_BCFRMS, qc);
7050 continue;
7051 }
7052
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007053 new_cf->stream.stream = cf->stream.stream;
7054 new_cf->stream.buf = cf->stream.buf;
7055 new_cf->stream.id = cf->stream.id;
Amaury Denoyelle1dac0182023-02-02 16:45:07 +01007056 new_cf->stream.offset = cf->stream.offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007057 new_cf->stream.len = dlen;
7058 new_cf->type |= QUIC_STREAM_FRAME_TYPE_LEN_BIT;
7059 /* FIN bit reset */
7060 new_cf->type &= ~QUIC_STREAM_FRAME_TYPE_FIN_BIT;
7061 new_cf->stream.data = cf->stream.data;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05007062 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007063 if (cf->origin) {
7064 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
7065 /* This <cf> frame was duplicated */
7066 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
7067 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01007068 /* Detach this STREAM frame from its origin */
7069 LIST_DEL_INIT(&cf->ref);
7070 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007071 }
7072 LIST_APPEND(outlist, &new_cf->list);
7073 cf->type |= QUIC_STREAM_FRAME_TYPE_OFF_BIT;
7074 /* Consume <dlen> bytes of the current frame. */
7075 cf_buf = b_make(b_orig(cf->stream.buf),
7076 b_size(cf->stream.buf),
7077 (char *)cf->stream.data - b_orig(cf->stream.buf), 0);
7078 cf->stream.len -= dlen;
7079 cf->stream.offset.key += dlen;
7080 cf->stream.data = (unsigned char *)b_peek(&cf_buf, dlen);
7081
7082 /* Do not notify MUX on retransmission. */
7083 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7084 qcc_streams_sent_done(new_cf->stream.stream->ctx,
7085 new_cf->stream.len,
7086 new_cf->stream.offset.key);
7087 }
7088 }
7089
7090 /* TODO the MUX is notified about the frame sending via
7091 * previous qcc_streams_sent_done call. However, the
7092 * sending can fail later, for example if the sendto
7093 * system call returns an error. As the MUX has been
7094 * notified, the transport layer is responsible to
7095 * bufferize and resent the announced data later.
7096 */
7097
7098 break;
7099
7100 default:
7101 flen = qc_frm_len(cf);
7102 BUG_ON(!flen);
7103 if (flen > room)
7104 continue;
7105
7106 *len += flen;
7107 room -= flen;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007108 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007109 LIST_APPEND(outlist, &cf->list);
7110 break;
7111 }
7112
7113 /* Successful status as soon as a frame could be built */
7114 ret = 1;
7115 }
7116
7117 leave:
7118 TRACE_LEAVE(QUIC_EV_CONN_BCFRMS, qc);
7119 return ret;
7120}
7121
7122/* Generate a CONNECTION_CLOSE frame for <qc> on <qel> encryption level. <out>
7123 * is used as return parameter and should be zero'ed by the caller.
7124 */
7125static void qc_build_cc_frm(struct quic_conn *qc, struct quic_enc_level *qel,
7126 struct quic_frame *out)
7127{
7128 /* TODO improve CONNECTION_CLOSE on Initial/Handshake encryption levels
7129 *
7130 * A CONNECTION_CLOSE frame should be sent in several packets with
7131 * different encryption levels depending on the client context. This is
7132 * to ensure that the client can decrypt it. See RFC 9000 10.2.3 for
7133 * more details on how to implement it.
7134 */
7135 TRACE_ENTER(QUIC_EV_CONN_BFRM, qc);
7136
7137
7138 if (qc->err.app) {
7139 if (unlikely(qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
7140 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
7141 /* RFC 9000 10.2.3. Immediate Close during the Handshake
7142 *
7143 * Sending a CONNECTION_CLOSE of type 0x1d in an Initial or Handshake
7144 * packet could expose application state or be used to alter application
7145 * state. A CONNECTION_CLOSE of type 0x1d MUST be replaced by a
7146 * CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or
7147 * Handshake packets. Otherwise, information about the application
7148 * state might be revealed. Endpoints MUST clear the value of the
7149 * Reason Phrase field and SHOULD use the APPLICATION_ERROR code when
7150 * converting to a CONNECTION_CLOSE of type 0x1c.
7151 */
7152 out->type = QUIC_FT_CONNECTION_CLOSE;
7153 out->connection_close.error_code = QC_ERR_APPLICATION_ERROR;
7154 out->connection_close.reason_phrase_len = 0;
7155 }
7156 else {
7157 out->type = QUIC_FT_CONNECTION_CLOSE_APP;
7158 out->connection_close.error_code = qc->err.code;
7159 }
7160 }
7161 else {
7162 out->type = QUIC_FT_CONNECTION_CLOSE;
7163 out->connection_close.error_code = qc->err.code;
7164 }
7165 TRACE_LEAVE(QUIC_EV_CONN_BFRM, qc);
7166
7167}
7168
7169/* This function builds a clear packet from <pkt> information (its type)
7170 * into a buffer with <pos> as position pointer and <qel> as QUIC TLS encryption
7171 * level for <conn> QUIC connection and <qel> as QUIC TLS encryption level,
7172 * filling the buffer with as much frames as possible from <frms> list of
7173 * prebuilt frames.
7174 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
7175 * reserved so that to ensure there is enough room to build this AEAD TAG after
7176 * having returned from this function.
7177 * This function also updates the value of <buf_pn> pointer to point to the packet
7178 * number field in this packet. <pn_len> will also have the packet number
7179 * length as value.
7180 *
7181 * Return 1 if succeeded (enough room to buile this packet), O if not.
7182 */
7183static int qc_do_build_pkt(unsigned char *pos, const unsigned char *end,
7184 size_t dglen, struct quic_tx_packet *pkt,
7185 int64_t pn, size_t *pn_len, unsigned char **buf_pn,
7186 int force_ack, int padding, int cc, int probe,
7187 struct quic_enc_level *qel, struct quic_conn *qc,
7188 const struct quic_version *ver, struct list *frms)
7189{
7190 unsigned char *beg, *payload;
7191 size_t len, len_sz, len_frms, padding_len;
7192 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
7193 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
7194 struct quic_frame cc_frm = { };
7195 size_t ack_frm_len, head_len;
7196 int64_t rx_largest_acked_pn;
7197 int add_ping_frm;
7198 struct list frm_list = LIST_HEAD_INIT(frm_list);
7199 struct quic_frame *cf;
7200 int must_ack, ret = 0;
7201 int nb_aepkts_since_last_ack;
7202
7203 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7204
7205 /* Length field value with CRYPTO frames if present. */
7206 len_frms = 0;
7207 beg = pos;
7208 /* When not probing, and no immediate close is required, reduce the size of this
7209 * buffer to respect the congestion controller window.
7210 * This size will be limited if we have ack-eliciting frames to send from <frms>.
7211 */
7212 if (!probe && !LIST_ISEMPTY(frms) && !cc) {
7213 size_t path_room;
7214
7215 path_room = quic_path_prep_data(qc->path);
7216 if (end - beg > path_room)
7217 end = beg + path_room;
7218 }
7219
7220 /* Ensure there is enough room for the TLS encryption tag and a zero token
7221 * length field if any.
7222 */
7223 if (end - pos < QUIC_TLS_TAG_LEN +
7224 (pkt->type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0))
7225 goto no_room;
7226
7227 end -= QUIC_TLS_TAG_LEN;
7228 rx_largest_acked_pn = qel->pktns->rx.largest_acked_pn;
7229 /* packet number length */
7230 *pn_len = quic_packet_number_length(pn, rx_largest_acked_pn);
7231 /* Build the header */
7232 if ((pkt->type == QUIC_PACKET_TYPE_SHORT &&
7233 !quic_build_packet_short_header(&pos, end, *pn_len, qc, qel->tls_ctx.flags)) ||
7234 (pkt->type != QUIC_PACKET_TYPE_SHORT &&
7235 !quic_build_packet_long_header(&pos, end, pkt->type, *pn_len, qc, ver)))
7236 goto no_room;
7237
7238 /* Encode the token length (0) for an Initial packet. */
7239 if (pkt->type == QUIC_PACKET_TYPE_INITIAL)
7240 *pos++ = 0;
7241 head_len = pos - beg;
7242 /* Build an ACK frame if required. */
7243 ack_frm_len = 0;
7244 nb_aepkts_since_last_ack = qel->pktns->rx.nb_aepkts_since_last_ack;
7245 must_ack = !qel->pktns->tx.pto_probe &&
7246 (force_ack || ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
7247 (LIST_ISEMPTY(frms) || nb_aepkts_since_last_ack >= QUIC_MAX_RX_AEPKTS_SINCE_LAST_ACK)));
7248 if (must_ack) {
7249 struct quic_arngs *arngs = &qel->pktns->rx.arngs;
7250 BUG_ON(eb_is_empty(&qel->pktns->rx.arngs.root));
7251 ack_frm.tx_ack.arngs = arngs;
7252 if (qel->pktns->flags & QUIC_FL_PKTNS_NEW_LARGEST_PN) {
7253 qel->pktns->tx.ack_delay =
7254 quic_compute_ack_delay_us(qel->pktns->rx.largest_time_received, qc);
7255 qel->pktns->flags &= ~QUIC_FL_PKTNS_NEW_LARGEST_PN;
7256 }
7257 ack_frm.tx_ack.ack_delay = qel->pktns->tx.ack_delay;
7258 /* XXX BE CAREFUL XXX : here we reserved at least one byte for the
7259 * smallest frame (PING) and <*pn_len> more for the packet number. Note
7260 * that from here, we do not know if we will have to send a PING frame.
7261 * This will be decided after having computed the ack-eliciting frames
7262 * to be added to this packet.
7263 */
7264 ack_frm_len = quic_ack_frm_reduce_sz(qc, &ack_frm, end - 1 - *pn_len - pos);
7265 if (!ack_frm_len)
7266 goto no_room;
7267 }
7268
7269 /* Length field value without the ack-eliciting frames. */
7270 len = ack_frm_len + *pn_len;
7271 len_frms = 0;
7272 if (!cc && !LIST_ISEMPTY(frms)) {
7273 ssize_t room = end - pos;
7274
7275 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7276 /* Initialize the length of the frames built below to <len>.
7277 * If any frame could be successfully built by qc_build_frms(),
7278 * we will have len_frms > len.
7279 */
7280 len_frms = len;
7281 if (!qc_build_frms(&frm_list, frms,
7282 end - pos, &len_frms, pos - beg, qel, qc)) {
7283 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7284 qc, NULL, NULL, &room);
7285 if (!ack_frm_len && !qel->pktns->tx.pto_probe)
7286 goto no_room;
7287 }
7288 }
7289
7290 /* Length (of the remaining data). Must not fail because, the buffer size
7291 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
7292 * for the encryption tag. It must be taken into an account for the length
7293 * of this packet.
7294 */
7295 if (len_frms)
7296 len = len_frms + QUIC_TLS_TAG_LEN;
7297 else
7298 len += QUIC_TLS_TAG_LEN;
7299 /* CONNECTION_CLOSE frame */
7300 if (cc) {
7301 qc_build_cc_frm(qc, qel, &cc_frm);
7302 len += qc_frm_len(&cc_frm);
7303 }
7304 add_ping_frm = 0;
7305 padding_len = 0;
7306 len_sz = quic_int_getsize(len);
7307 /* Add this packet size to <dglen> */
7308 dglen += head_len + len_sz + len;
7309 if (padding && dglen < QUIC_INITIAL_PACKET_MINLEN) {
7310 /* This is a maximum padding size */
7311 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7312 /* The length field value is of this packet is <len> + <padding_len>
7313 * the size of which may be greater than the initial computed size
7314 * <len_sz>. So, let's deduce the difference between these to packet
7315 * sizes from <padding_len>.
7316 */
7317 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7318 len += padding_len;
7319 }
Frédéric Lécaille5faf5772023-02-16 17:30:53 +01007320 else if (len_frms && len_frms < QUIC_PACKET_PN_MAXLEN) {
7321 len += padding_len = QUIC_PACKET_PN_MAXLEN - len_frms;
7322 }
7323 else if (LIST_ISEMPTY(&frm_list)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007324 if (qel->pktns->tx.pto_probe) {
7325 /* If we cannot send a frame, we send a PING frame. */
7326 add_ping_frm = 1;
7327 len += 1;
7328 }
7329 /* If there is no frame at all to follow, add at least a PADDING frame. */
7330 if (!ack_frm_len && !cc)
7331 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
7332 }
7333
7334 if (pkt->type != QUIC_PACKET_TYPE_SHORT && !quic_enc_int(&pos, end, len))
7335 goto no_room;
7336
7337 /* Packet number field address. */
7338 *buf_pn = pos;
7339
7340 /* Packet number encoding. */
7341 if (!quic_packet_number_encode(&pos, end, pn, *pn_len))
7342 goto no_room;
7343
7344 /* payload building (ack-eliciting or not frames) */
7345 payload = pos;
7346 if (ack_frm_len) {
7347 if (!qc_build_frm(&pos, end, &ack_frm, pkt, qc))
7348 goto no_room;
7349
7350 pkt->largest_acked_pn = quic_pktns_get_largest_acked_pn(qel->pktns);
7351 pkt->flags |= QUIC_FL_TX_PACKET_ACK;
7352 }
7353
7354 /* Ack-eliciting frames */
7355 if (!LIST_ISEMPTY(&frm_list)) {
7356 struct quic_frame *tmp_cf;
7357 list_for_each_entry_safe(cf, tmp_cf, &frm_list, list) {
7358 if (!qc_build_frm(&pos, end, cf, pkt, qc)) {
7359 ssize_t room = end - pos;
7360 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7361 qc, NULL, NULL, &room);
7362 /* Note that <cf> was added from <frms> to <frm_list> list by
7363 * qc_build_frms().
7364 */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007365 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007366 LIST_INSERT(frms, &cf->list);
7367 continue;
7368 }
7369
7370 quic_tx_packet_refinc(pkt);
7371 cf->pkt = pkt;
7372 }
7373 }
7374
7375 /* Build a PING frame if needed. */
7376 if (add_ping_frm) {
7377 frm.type = QUIC_FT_PING;
7378 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7379 goto no_room;
7380 }
7381
7382 /* Build a CONNECTION_CLOSE frame if needed. */
7383 if (cc) {
7384 if (!qc_build_frm(&pos, end, &cc_frm, pkt, qc))
7385 goto no_room;
7386
7387 pkt->flags |= QUIC_FL_TX_PACKET_CC;
7388 }
7389
7390 /* Build a PADDING frame if needed. */
7391 if (padding_len) {
7392 frm.type = QUIC_FT_PADDING;
7393 frm.padding.len = padding_len;
7394 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7395 goto no_room;
7396 }
7397
7398 if (pos == payload) {
7399 /* No payload was built because of congestion control */
7400 TRACE_DEVEL("limited by congestion control", QUIC_EV_CONN_TXPKT, qc);
7401 goto no_room;
7402 }
7403
7404 /* If this packet is ack-eliciting and we are probing let's
7405 * decrement the PTO probe counter.
7406 */
7407 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING &&
7408 qel->pktns->tx.pto_probe)
7409 qel->pktns->tx.pto_probe--;
7410
7411 pkt->len = pos - beg;
7412 LIST_SPLICE(&pkt->frms, &frm_list);
7413
7414 ret = 1;
7415 TRACE_DEVEL("Packet ack-eliciting frames", QUIC_EV_CONN_TXPKT, qc, pkt);
7416 leave:
7417 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7418 return ret;
7419
7420 no_room:
7421 /* Replace the pre-built frames which could not be add to this packet */
7422 LIST_SPLICE(frms, &frm_list);
7423 TRACE_DEVEL("Remaining ack-eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7424 goto leave;
7425}
7426
7427static inline void quic_tx_packet_init(struct quic_tx_packet *pkt, int type)
7428{
7429 pkt->type = type;
7430 pkt->len = 0;
7431 pkt->in_flight_len = 0;
7432 pkt->pn_node.key = (uint64_t)-1;
7433 LIST_INIT(&pkt->frms);
7434 pkt->time_sent = TICK_ETERNITY;
7435 pkt->next = NULL;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01007436 pkt->prev = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007437 pkt->largest_acked_pn = -1;
7438 pkt->flags = 0;
7439 pkt->refcnt = 0;
7440}
7441
7442/* Build a packet into <buf> packet buffer with <pkt_type> as packet
7443 * type for <qc> QUIC connection from <qel> encryption level from <frms> list
7444 * of prebuilt frames.
7445 *
7446 * Return -2 if the packet could not be allocated or encrypted for any reason,
7447 * -1 if there was not enough room to build a packet.
7448 * XXX NOTE XXX
7449 * If you provide provide qc_build_pkt() with a big enough buffer to build a packet as big as
7450 * possible (to fill an MTU), the unique reason why this function may fail is the congestion
7451 * control window limitation.
7452 */
7453static struct quic_tx_packet *qc_build_pkt(unsigned char **pos,
7454 const unsigned char *buf_end,
7455 struct quic_enc_level *qel,
7456 struct quic_tls_ctx *tls_ctx, struct list *frms,
7457 struct quic_conn *qc, const struct quic_version *ver,
7458 size_t dglen, int pkt_type, int force_ack,
7459 int padding, int probe, int cc, int *err)
7460{
7461 struct quic_tx_packet *ret_pkt = NULL;
7462 /* The pointer to the packet number field. */
7463 unsigned char *buf_pn;
7464 unsigned char *beg, *end, *payload;
7465 int64_t pn;
7466 size_t pn_len, payload_len, aad_len;
7467 struct quic_tx_packet *pkt;
7468
7469 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc, NULL, qel);
7470 *err = 0;
7471 pkt = pool_alloc(pool_head_quic_tx_packet);
7472 if (!pkt) {
7473 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_TXPKT, qc);
7474 *err = -2;
7475 goto err;
7476 }
7477
7478 quic_tx_packet_init(pkt, pkt_type);
7479 beg = *pos;
7480 pn_len = 0;
7481 buf_pn = NULL;
7482
7483 pn = qel->pktns->tx.next_pn + 1;
7484 if (!qc_do_build_pkt(*pos, buf_end, dglen, pkt, pn, &pn_len, &buf_pn,
7485 force_ack, padding, cc, probe, qel, qc, ver, frms)) {
7486 // trace already emitted by function above
7487 *err = -1;
7488 goto err;
7489 }
7490
7491 end = beg + pkt->len;
7492 payload = buf_pn + pn_len;
7493 payload_len = end - payload;
7494 aad_len = payload - beg;
7495
7496 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc)) {
7497 // trace already emitted by function above
7498 *err = -2;
7499 goto err;
7500 }
7501
7502 end += QUIC_TLS_TAG_LEN;
7503 pkt->len += QUIC_TLS_TAG_LEN;
7504 if (!quic_apply_header_protection(qc, beg, buf_pn, pn_len, tls_ctx)) {
7505 // trace already emitted by function above
7506 *err = -2;
7507 goto err;
7508 }
7509
7510 /* Consume a packet number */
7511 qel->pktns->tx.next_pn++;
7512 qc->tx.prep_bytes += pkt->len;
7513 if (qc->tx.prep_bytes >= 3 * qc->rx.bytes && !quic_peer_validated_addr(qc)) {
7514 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
7515 TRACE_PROTO("anti-amplification limit reached", QUIC_EV_CONN_TXPKT, qc);
7516 }
7517 /* Now that a correct packet is built, let us consume <*pos> buffer. */
7518 *pos = end;
7519 /* Attach the built packet to its tree. */
7520 pkt->pn_node.key = pn;
7521 /* Set the packet in fligth length for in flight packet only. */
7522 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
7523 pkt->in_flight_len = pkt->len;
7524 qc->path->prep_in_flight += pkt->len;
7525 }
7526 /* Always reset this flags */
7527 qc->flags &= ~QUIC_FL_CONN_IMMEDIATE_CLOSE;
7528 if (pkt->flags & QUIC_FL_TX_PACKET_ACK) {
7529 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
7530 qel->pktns->rx.nb_aepkts_since_last_ack = 0;
7531 }
7532
7533 pkt->pktns = qel->pktns;
7534
7535 ret_pkt = pkt;
7536 leave:
7537 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc, ret_pkt);
7538 return ret_pkt;
7539
7540 err:
7541 /* TODO: what about the frames which have been built
7542 * for this packet.
7543 */
7544 free_quic_tx_packet(qc, pkt);
7545 goto leave;
7546}
7547
7548
7549static void __quic_conn_init(void)
7550{
7551 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
7552}
7553INITCALL0(STG_REGISTER, __quic_conn_init);
7554
7555static void __quic_conn_deinit(void)
7556{
7557 BIO_meth_free(ha_quic_meth);
7558}
7559REGISTER_POST_DEINIT(__quic_conn_deinit);
7560
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007561/* Handle a new <dgram> received. Parse each QUIC packets and copied their
7562 * content to a quic-conn instance. The datagram content can be released after
7563 * this function.
7564 *
7565 * If datagram has been received on a quic-conn owned FD, <from_qc> must be set
7566 * to the connection instance. <li> is the attached listener. The caller is
7567 * responsible to ensure that the first packet is destined to this connection
7568 * by comparing CIDs.
7569 *
7570 * If datagram has been received on a receiver FD, <from_qc> will be NULL. This
7571 * function will thus retrieve the connection from the CID tree or allocate a
7572 * new one if possible. <li> is the listener attached to the receiver.
7573 *
7574 * Returns 0 on success else non-zero. If an error happens, some packets from
7575 * the datagram may not have been parsed.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007576 */
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007577int quic_dgram_parse(struct quic_dgram *dgram, struct quic_conn *from_qc,
7578 struct listener *li)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007579{
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007580 struct quic_rx_packet *pkt;
7581 struct quic_conn *qc = NULL;
7582 unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007583 struct list *tasklist_head = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007584
7585 TRACE_ENTER(QUIC_EV_CONN_LPKT);
7586
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007587 pos = dgram->buf;
7588 end = pos + dgram->len;
7589 do {
7590 /* TODO replace zalloc -> alloc. */
7591 pkt = pool_zalloc(pool_head_quic_rx_packet);
7592 if (!pkt) {
7593 TRACE_ERROR("RX packet allocation failed", QUIC_EV_CONN_LPKT);
7594 goto err;
7595 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007596
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007597 pkt->version = NULL;
7598 pkt->pn_offset = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007599
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007600 /* Set flag if pkt is the first one in dgram. */
7601 if (pos == dgram->buf)
7602 pkt->flags |= QUIC_FL_RX_PACKET_DGRAM_FIRST;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007603
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007604 LIST_INIT(&pkt->qc_rx_pkt_list);
7605 pkt->time_received = now_ms;
7606 quic_rx_packet_refinc(pkt);
7607 if (quic_rx_pkt_parse(pkt, pos, end, dgram, li))
7608 goto next;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007609
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007610 /* Search quic-conn instance for first packet of the datagram.
7611 * quic_rx_packet_parse() is responsible to discard packets
7612 * with different DCID as the first one in the same datagram.
7613 */
7614 if (!qc) {
7615 qc = from_qc ? from_qc : quic_rx_pkt_retrieve_conn(pkt, dgram, li);
7616 /* qc is NULL if receiving a non Initial packet for an
7617 * unknown connection.
7618 */
7619 if (!qc) {
Amaury Denoyelle98289692022-10-19 15:37:44 +02007620 /* Skip the entire datagram. */
7621 pkt->len = end - pos;
7622 goto next;
7623 }
7624
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007625 dgram->qc = qc;
7626 }
Amaury Denoyelle98289692022-10-19 15:37:44 +02007627
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007628 if (qc_rx_check_closing(qc, pkt)) {
7629 /* Skip the entire datagram. */
7630 pkt->len = end - pos;
7631 goto next;
7632 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007633
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007634 /* Detect QUIC connection migration. */
Frédéric Lécaillef6769542023-01-12 10:36:26 +01007635 if (ipcmp(&qc->peer_addr, &dgram->saddr, 1)) {
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007636 if (qc_handle_conn_migration(qc, &dgram->saddr, &dgram->daddr)) {
7637 /* Skip the entire datagram. */
7638 TRACE_ERROR("error during connection migration, datagram dropped", QUIC_EV_CONN_LPKT, qc);
7639 pkt->len = end - pos;
7640 goto next;
7641 }
7642 }
7643
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007644 qc_rx_pkt_handle(qc, pkt, dgram, pos, &tasklist_head);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007645
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007646 next:
7647 pos += pkt->len;
7648 quic_rx_packet_refdec(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007649
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007650 /* Free rejected packets */
7651 if (!pkt->refcnt) {
7652 BUG_ON(LIST_INLIST(&pkt->qc_rx_pkt_list));
7653 pool_free(pool_head_quic_rx_packet, pkt);
7654 }
7655 } while (pos < end);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007656
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007657 /* Increasing the received bytes counter by the UDP datagram length
7658 * if this datagram could be associated to a connection.
7659 */
7660 if (dgram->qc)
7661 dgram->qc->rx.bytes += dgram->len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007662
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007663 /* This must never happen. */
7664 BUG_ON(pos > end);
7665 BUG_ON(pos < end || pos > dgram->buf + dgram->len);
7666 /* Mark this datagram as consumed */
7667 HA_ATOMIC_STORE(&dgram->buf, NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007668
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007669 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
7670 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007671
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007672 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007673 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007674 return -1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007675}
7676
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01007677/* Check if connection ID <dcid> of length <dcid_len> belongs to <qc> local
7678 * CIDs. This can be used to determine if a datagram is addressed to the right
7679 * connection instance.
7680 *
7681 * Returns a boolean value.
7682 */
7683int qc_check_dcid(struct quic_conn *qc, unsigned char *dcid, size_t dcid_len)
7684{
7685 struct ebmb_node *node;
7686 struct quic_connection_id *id;
7687
7688 /* For ODCID, address is concatenated to it after qc.odcid.len so this
7689 * comparison is safe.
7690 */
7691 if ((qc->scid.len == dcid_len &&
7692 memcmp(qc->scid.data, dcid, dcid_len) == 0) ||
7693 (qc->odcid.len == dcid_len &&
Frédéric Lécaille07846cb2023-02-13 16:14:24 +01007694 memcmp(qc->odcid.data, dcid, dcid_len) == 0)) {
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01007695 return 1;
7696 }
7697
7698 node = ebmb_lookup(&quic_dghdlrs[tid].cids, dcid, dcid_len);
7699 if (node) {
7700 id = ebmb_entry(node, struct quic_connection_id, node);
7701 if (qc == id->qc)
7702 return 1;
7703 }
7704
7705 return 0;
7706}
7707
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007708/* Retrieve the DCID from a QUIC datagram or packet with <buf> as first octet.
7709 * Returns 1 if succeeded, 0 if not.
7710 */
7711int quic_get_dgram_dcid(unsigned char *buf, const unsigned char *end,
7712 unsigned char **dcid, size_t *dcid_len)
7713{
7714 int ret = 0, long_header;
7715 size_t minlen, skip;
7716
7717 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
7718
7719 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
7720 TRACE_PROTO("fixed bit not set", QUIC_EV_CONN_RXPKT);
7721 goto err;
7722 }
7723
7724 long_header = *buf & QUIC_PACKET_LONG_HEADER_BIT;
7725 minlen = long_header ? QUIC_LONG_PACKET_MINLEN :
7726 QUIC_SHORT_PACKET_MINLEN + QUIC_HAP_CID_LEN + QUIC_TLS_TAG_LEN;
7727 skip = long_header ? QUIC_LONG_PACKET_DCID_OFF : QUIC_SHORT_PACKET_DCID_OFF;
7728 if (end - buf < minlen)
7729 goto err;
7730
7731 buf += skip;
7732 *dcid_len = long_header ? *buf++ : QUIC_HAP_CID_LEN;
7733 if (*dcid_len > QUIC_CID_MAXLEN || end - buf <= *dcid_len)
7734 goto err;
7735
7736 *dcid = buf;
7737
7738 ret = 1;
7739 leave:
7740 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
7741 return ret;
7742
7743 err:
7744 TRACE_PROTO("wrong datagram", QUIC_EV_CONN_RXPKT);
7745 goto leave;
7746}
7747
7748/* Notify the MUX layer if alive about an imminent close of <qc>. */
7749void qc_notify_close(struct quic_conn *qc)
7750{
7751 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
7752
7753 if (qc->flags & QUIC_FL_CONN_NOTIFY_CLOSE)
7754 goto leave;
7755
7756 qc->flags |= QUIC_FL_CONN_NOTIFY_CLOSE;
7757 /* wake up the MUX */
7758 if (qc->mux_state == QC_MUX_READY && qc->conn->mux->wake) {
7759 TRACE_STATE("connection closure notidfied to mux",
7760 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7761 qc->conn->mux->wake(qc->conn);
7762 }
7763 else
7764 TRACE_STATE("connection closure not notidfied to mux",
7765 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7766 leave:
7767 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
7768}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007769
7770
7771/* appctx context used by "show quic" command */
7772struct show_quic_ctx {
7773 unsigned int epoch;
7774 struct bref bref; /* back-reference to the quic-conn being dumped */
7775 unsigned int thr;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007776 int flags;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007777};
7778
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007779#define QC_CLI_FL_SHOW_ALL 0x1 /* show closing/draining connections */
7780
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007781static int cli_parse_show_quic(char **args, char *payload, struct appctx *appctx, void *private)
7782{
7783 struct show_quic_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7784
7785 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
7786 return 1;
7787
7788 ctx->epoch = _HA_ATOMIC_FETCH_ADD(&qc_epoch, 1);
7789 ctx->thr = 0;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007790 ctx->flags = 0;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007791
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01007792 if (*args[2] && strcmp(args[2], "all") == 0)
7793 ctx->flags |= QC_CLI_FL_SHOW_ALL;
7794
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007795 LIST_INIT(&ctx->bref.users);
7796
7797 return 0;
7798}
7799
7800static int cli_io_handler_dump_quic(struct appctx *appctx)
7801{
7802 struct show_quic_ctx *ctx = appctx->svcctx;
7803 struct stconn *sc = appctx_sc(appctx);
7804 struct quic_conn *qc;
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01007805 struct quic_enc_level *qel;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007806 struct eb64_node *node;
7807 struct qc_stream_desc *stream;
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01007808 char bufaddr[INET6_ADDRSTRLEN], bufport[6];
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01007809 int expire;
7810 unsigned char cid_len;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007811
7812 thread_isolate();
7813
7814 if (ctx->thr >= global.nbthread)
7815 goto done;
7816
7817 if (unlikely(sc_ic(sc)->flags & CF_SHUTW)) {
7818 /* If we're forced to shut down, we might have to remove our
7819 * reference to the last stream being dumped.
7820 */
7821 if (!LIST_ISEMPTY(&ctx->bref.users))
7822 LIST_DEL_INIT(&ctx->bref.users);
7823 goto done;
7824 }
7825
7826 chunk_reset(&trash);
7827
7828 if (!LIST_ISEMPTY(&ctx->bref.users)) {
7829 /* Remove show_quic_ctx from previous quic_conn instance. */
7830 LIST_DEL_INIT(&ctx->bref.users);
7831 }
7832 else if (!ctx->bref.ref) {
7833 /* First invocation. */
7834 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
7835 }
7836
7837 while (1) {
7838 int done = 0;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007839 int i;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007840
7841 if (ctx->bref.ref == &ha_thread_ctx[ctx->thr].quic_conns) {
7842 done = 1;
7843 }
7844 else {
7845 qc = LIST_ELEM(ctx->bref.ref, struct quic_conn *, el_th_ctx);
7846 if ((int)(qc->qc_epoch - ctx->epoch) > 0)
7847 done = 1;
7848 }
7849
7850 if (done) {
7851 ++ctx->thr;
7852 if (ctx->thr >= global.nbthread)
7853 break;
7854 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
7855 continue;
7856 }
7857
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01007858 if (!(ctx->flags & QC_CLI_FL_SHOW_ALL) &&
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007859 qc->flags & (QUIC_FL_CONN_CLOSING|QUIC_FL_CONN_DRAINING)) {
7860 ctx->bref.ref = qc->el_th_ctx.n;
7861 continue;
7862 }
7863
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01007864 /* CIDs */
7865 chunk_appendf(&trash, "* %p[%02u]: scid=", qc, qc->tid);
7866 for (cid_len = 0; cid_len < qc->scid.len; ++cid_len)
7867 chunk_appendf(&trash, "%02x", qc->scid.data[cid_len]);
7868 while (cid_len++ < 20)
7869 chunk_appendf(&trash, "..");
7870
7871 chunk_appendf(&trash, " dcid=");
7872 for (cid_len = 0; cid_len < qc->dcid.len; ++cid_len)
7873 chunk_appendf(&trash, "%02x", qc->dcid.data[cid_len]);
7874 while (cid_len++ < 20)
7875 chunk_appendf(&trash, "..");
7876
7877 chunk_appendf(&trash, "\n");
7878
7879 /* Connection state */
7880 if (qc->flags & QUIC_FL_CONN_CLOSING)
7881 chunk_appendf(&trash, " st=closing ");
7882 else if (qc->flags & QUIC_FL_CONN_DRAINING)
7883 chunk_appendf(&trash, " st=draining ");
7884 else if (qc->state < QUIC_HS_ST_CONFIRMED)
7885 chunk_appendf(&trash, " st=handshake ");
7886 else
7887 chunk_appendf(&trash, " st=opened ");
7888
7889 if (qc->mux_state == QC_MUX_NULL)
7890 chunk_appendf(&trash, "mux=null ");
7891 else if (qc->mux_state == QC_MUX_READY)
7892 chunk_appendf(&trash, "mux=ready ");
7893 else
7894 chunk_appendf(&trash, "mux=released ");
7895
7896 expire = qc->idle_timer_task->expire;
7897 chunk_appendf(&trash, "expire=%02ds ",
7898 expire > now_ms ? (expire - now_ms) / 1000 : 0);
7899
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007900 chunk_appendf(&trash, "\n");
7901
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01007902 /* Socket */
7903 chunk_appendf(&trash, " fd=%d", qc->fd);
7904 if (qc->local_addr.ss_family == AF_INET ||
7905 qc->local_addr.ss_family == AF_INET6) {
7906 addr_to_str(&qc->local_addr, bufaddr, sizeof(bufaddr));
7907 port_to_str(&qc->local_addr, bufport, sizeof(bufport));
7908 chunk_appendf(&trash, " from=%s:%s", bufaddr, bufport);
7909
7910 addr_to_str(&qc->peer_addr, bufaddr, sizeof(bufaddr));
7911 port_to_str(&qc->peer_addr, bufport, sizeof(bufport));
7912 chunk_appendf(&trash, " to=%s:%s", bufaddr, bufport);
7913 }
7914
7915 chunk_appendf(&trash, "\n");
7916
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01007917 /* Encryption levels */
7918 qel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
7919 chunk_appendf(&trash, " [initl] rx.ackrng=%-6zu tx.inflight=%-6zu",
7920 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7921 qel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
7922 chunk_appendf(&trash, " [hndshk] rx.ackrng=%-6zu tx.inflight=%-6zu\n",
7923 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7924 qel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
7925 chunk_appendf(&trash, " [0-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
7926 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7927 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
7928 chunk_appendf(&trash, " [1-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
7929 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7930
7931 chunk_appendf(&trash, "\n");
7932
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007933 /* Streams */
7934 node = eb64_first(&qc->streams_by_id);
7935 i = 0;
7936 while (node) {
7937 stream = eb64_entry(node, struct qc_stream_desc, by_id);
7938 node = eb64_next(node);
7939
Amaury Denoyellea9de25a2023-02-10 09:25:22 +01007940 chunk_appendf(&trash, " | stream=%-8llu", (unsigned long long)stream->by_id.key);
7941 chunk_appendf(&trash, " off=%-8llu ack=%-8llu",
7942 (unsigned long long)stream->buf_offset,
7943 (unsigned long long)stream->ack_offset);
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007944
7945 if (!(++i % 3)) {
7946 chunk_appendf(&trash, "\n");
7947 i = 0;
7948 }
7949 }
7950
7951 chunk_appendf(&trash, "\n");
7952
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007953 if (applet_putchk(appctx, &trash) == -1) {
7954 /* Register show_quic_ctx to quic_conn instance. */
7955 LIST_APPEND(&qc->back_refs, &ctx->bref.users);
7956 goto full;
7957 }
7958
7959 ctx->bref.ref = qc->el_th_ctx.n;
7960 }
7961
7962 done:
7963 thread_release();
7964 return 1;
7965
7966 full:
7967 thread_release();
7968 return 0;
7969}
7970
7971static void cli_release_show_quic(struct appctx *appctx)
7972{
7973 struct show_quic_ctx *ctx = appctx->svcctx;
7974
7975 if (ctx->thr < global.nbthread) {
7976 thread_isolate();
7977 if (!LIST_ISEMPTY(&ctx->bref.users))
7978 LIST_DEL_INIT(&ctx->bref.users);
7979 thread_release();
7980 }
7981}
7982
7983static struct cli_kw_list cli_kws = {{ }, {
7984 { { "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 +01007985 {{},}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007986}};
7987
7988INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
7989
7990static void init_quic()
7991{
7992 int thr;
7993
7994 for (thr = 0; thr < MAX_THREADS; ++thr)
7995 LIST_INIT(&ha_thread_ctx[thr].quic_conns);
7996}
7997INITCALL0(STG_INIT, init_quic);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007998
7999/*
8000 * Local variables:
8001 * c-indent-level: 8
8002 * c-basic-offset: 8
8003 * End:
8004 */