blob: 5b9d5a327561a6f21142435e7de12f854144fe01 [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;
366 chunk_appendf(&trace_buf, " qel=%c cwnd=%llu ppif=%lld pif=%llu "
367 "if=%llu pp=%u",
368 quic_enc_level_char_from_qel(qel, qc),
369 (unsigned long long)qc->path->cwnd,
370 (unsigned long long)qc->path->prep_in_flight,
371 (unsigned long long)qc->path->in_flight,
372 (unsigned long long)pktns->tx.in_flight,
373 pktns->tx.pto_probe);
374 }
375 if (pkt) {
376 const struct quic_frame *frm;
377 if (pkt->pn_node.key != (uint64_t)-1)
378 chunk_appendf(&trace_buf, " pn=%llu",(ull)pkt->pn_node.key);
379 list_for_each_entry(frm, &pkt->frms, list) {
380 chunk_appendf(&trace_buf, " frm@%p", frm);
381 chunk_frm_appendf(&trace_buf, frm);
382 }
383 }
384
385 if (room) {
386 chunk_appendf(&trace_buf, " room=%lld", (long long)*room);
387 chunk_appendf(&trace_buf, " dcid.len=%llu scid.len=%llu",
388 (unsigned long long)qc->dcid.len, (unsigned long long)qc->scid.len);
389 }
390 }
391
392 if (mask & QUIC_EV_CONN_IO_CB) {
393 const enum quic_handshake_state *state = a2;
394 const int *err = a3;
395
396 if (state)
397 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(*state));
398 if (err)
399 chunk_appendf(&trace_buf, " err=%s", ssl_error_str(*err));
400 }
401
402 if (mask & (QUIC_EV_CONN_TRMHP|QUIC_EV_CONN_ELRMHP|QUIC_EV_CONN_SPKT)) {
403 const struct quic_rx_packet *pkt = a2;
404 const unsigned long *pktlen = a3;
405 const SSL *ssl = a4;
406
407 if (pkt) {
408 chunk_appendf(&trace_buf, " pkt@%p", pkt);
409 if (pkt->type == QUIC_PACKET_TYPE_SHORT && pkt->data)
410 chunk_appendf(&trace_buf, " kp=%d",
411 !!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT));
412 chunk_appendf(&trace_buf, " el=%c",
413 quic_packet_type_enc_level_char(pkt->type));
414 if (pkt->pnl)
415 chunk_appendf(&trace_buf, " pnl=%u pn=%llu", pkt->pnl,
416 (unsigned long long)pkt->pn);
417 if (pkt->token_len)
418 chunk_appendf(&trace_buf, " toklen=%llu",
419 (unsigned long long)pkt->token_len);
420 if (pkt->aad_len)
421 chunk_appendf(&trace_buf, " aadlen=%llu",
422 (unsigned long long)pkt->aad_len);
423 chunk_appendf(&trace_buf, " flags=0x%x len=%llu",
424 pkt->flags, (unsigned long long)pkt->len);
425 }
426 if (pktlen)
427 chunk_appendf(&trace_buf, " (%ld)", *pktlen);
428 if (ssl) {
429 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
430 chunk_appendf(&trace_buf, " el=%c",
431 quic_enc_level_char(ssl_to_quic_enc_level(level)));
432 }
433 }
434
435 if (mask & (QUIC_EV_CONN_RXPKT|QUIC_EV_CONN_PRSHPKT|QUIC_EV_CONN_SSLDATA)) {
436 const struct quic_rx_packet *pkt = a2;
437 const struct quic_rx_crypto_frm *cf = a3;
438 const SSL *ssl = a4;
439
440 if (pkt)
441 chunk_appendf(&trace_buf, " pkt@%p el=%c pn=%llu", pkt,
442 quic_packet_type_enc_level_char(pkt->type),
443 (unsigned long long)pkt->pn);
444 if (cf)
445 chunk_appendf(&trace_buf, " cfoff=%llu cflen=%llu",
446 (unsigned long long)cf->offset_node.key,
447 (unsigned long long)cf->len);
448 if (ssl) {
449 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
450 chunk_appendf(&trace_buf, " rel=%c",
451 quic_enc_level_char(ssl_to_quic_enc_level(level)));
452 }
453
454 if (qc->err.code)
455 chunk_appendf(&trace_buf, " err_code=0x%llx", (ull)qc->err.code);
456 }
457
458 if (mask & (QUIC_EV_CONN_PRSFRM|QUIC_EV_CONN_BFRM)) {
459 const struct quic_frame *frm = a2;
460
461 if (frm)
462 chunk_appendf(&trace_buf, " %s", quic_frame_type_string(frm->type));
463 }
464
465 if (mask & QUIC_EV_CONN_PHPKTS) {
466 const struct quic_enc_level *qel = a2;
467
468 if (qel) {
469 const struct quic_pktns *pktns = qel->pktns;
470 chunk_appendf(&trace_buf,
Amaury Denoyelle2f668f02022-11-18 15:24:08 +0100471 " qel=%c state=%s ack?%d cwnd=%llu ppif=%lld pif=%llu if=%llu pp=%u off=%llu",
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200472 quic_enc_level_char_from_qel(qel, qc),
473 quic_hdshk_state_str(qc->state),
474 !!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED),
475 (unsigned long long)qc->path->cwnd,
476 (unsigned long long)qc->path->prep_in_flight,
477 (unsigned long long)qc->path->in_flight,
478 (unsigned long long)pktns->tx.in_flight,
Amaury Denoyelle2f668f02022-11-18 15:24:08 +0100479 pktns->tx.pto_probe,
480 qel->cstream ? (unsigned long long)qel->cstream->rx.offset : 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200481 }
482 }
483
484 if (mask & QUIC_EV_CONN_ENCPKT) {
485 const struct enc_debug_info *edi = a2;
486
487 if (edi)
488 chunk_appendf(&trace_buf,
489 " payload=@%p payload_len=%llu"
490 " aad=@%p aad_len=%llu pn=%llu",
491 edi->payload, (unsigned long long)edi->payload_len,
492 edi->aad, (unsigned long long)edi->aad_len,
493 (unsigned long long)edi->pn);
494 }
495
496 if (mask & QUIC_EV_CONN_RMHP) {
497 const struct quic_rx_packet *pkt = a2;
498
499 if (pkt) {
500 const int *ret = a3;
501
502 chunk_appendf(&trace_buf, " pkt@%p", pkt);
503 if (ret && *ret)
504 chunk_appendf(&trace_buf, " pnl=%u pn=%llu",
505 pkt->pnl, (unsigned long long)pkt->pn);
506 }
507 }
508
509 if (mask & QUIC_EV_CONN_PRSAFRM) {
510 const struct quic_frame *frm = a2;
511 const unsigned long *val1 = a3;
512 const unsigned long *val2 = a4;
513
514 if (frm) {
515 chunk_appendf(&trace_buf, " frm@%p", frm);
516 chunk_frm_appendf(&trace_buf, frm);
517 }
518 if (val1)
519 chunk_appendf(&trace_buf, " %lu", *val1);
520 if (val2)
521 chunk_appendf(&trace_buf, "..%lu", *val2);
522 }
523
524 if (mask & QUIC_EV_CONN_ACKSTRM) {
525 const struct quic_stream *s = a2;
526 const struct qc_stream_desc *stream = a3;
527
528 if (s)
529 chunk_appendf(&trace_buf, " off=%llu len=%llu", (ull)s->offset.key, (ull)s->len);
530 if (stream)
531 chunk_appendf(&trace_buf, " ack_offset=%llu", (ull)stream->ack_offset);
532 }
533
534 if (mask & QUIC_EV_CONN_RTTUPDT) {
535 const unsigned int *rtt_sample = a2;
536 const unsigned int *ack_delay = a3;
537 const struct quic_loss *ql = a4;
538
539 if (rtt_sample)
540 chunk_appendf(&trace_buf, " rtt_sample=%ums", *rtt_sample);
541 if (ack_delay)
542 chunk_appendf(&trace_buf, " ack_delay=%ums", *ack_delay);
543 if (ql)
544 chunk_appendf(&trace_buf,
545 " srtt=%ums rttvar=%ums min_rtt=%ums",
546 ql->srtt >> 3, ql->rtt_var >> 2, ql->rtt_min);
547 }
548 if (mask & QUIC_EV_CONN_CC) {
549 const struct quic_cc_event *ev = a2;
550 const struct quic_cc *cc = a3;
551
552 if (a2)
553 quic_cc_event_trace(&trace_buf, ev);
554 if (a3)
555 quic_cc_state_trace(&trace_buf, cc);
556 }
557
558 if (mask & QUIC_EV_CONN_PKTLOSS) {
559 const struct quic_pktns *pktns = a2;
560 const struct list *lost_pkts = a3;
561
562 if (pktns) {
563 chunk_appendf(&trace_buf, " pktns=%s",
564 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
565 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H");
566 if (pktns->tx.loss_time)
567 chunk_appendf(&trace_buf, " loss_time=%dms",
568 TICKS_TO_MS(tick_remain(now_ms, pktns->tx.loss_time)));
569 }
570 if (lost_pkts && !LIST_ISEMPTY(lost_pkts)) {
571 struct quic_tx_packet *pkt;
572
573 chunk_appendf(&trace_buf, " lost_pkts:");
574 list_for_each_entry(pkt, lost_pkts, list)
575 chunk_appendf(&trace_buf, " %lu", (unsigned long)pkt->pn_node.key);
576 }
577 }
578
579 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_PTIMER|QUIC_EV_CONN_SPTO)) {
580 const struct quic_pktns *pktns = a2;
581 const int *duration = a3;
582 const uint64_t *ifae_pkts = a4;
583
584 if (ifae_pkts)
585 chunk_appendf(&trace_buf, " ifae_pkts=%llu",
586 (unsigned long long)*ifae_pkts);
587 if (pktns) {
588 chunk_appendf(&trace_buf, " pktns=%s pp=%d",
589 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
590 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
591 pktns->tx.pto_probe);
592 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_SPTO)) {
593 if (pktns->tx.in_flight)
594 chunk_appendf(&trace_buf, " if=%llu", (ull)pktns->tx.in_flight);
595 if (pktns->tx.loss_time)
596 chunk_appendf(&trace_buf, " loss_time=%dms",
597 TICKS_TO_MS(pktns->tx.loss_time - now_ms));
598 }
599 if (mask & QUIC_EV_CONN_SPTO) {
600 if (pktns->tx.time_of_last_eliciting)
601 chunk_appendf(&trace_buf, " tole=%dms",
602 TICKS_TO_MS(pktns->tx.time_of_last_eliciting - now_ms));
603 if (duration)
604 chunk_appendf(&trace_buf, " dur=%dms", TICKS_TO_MS(*duration));
605 }
606 }
607
608 if (!(mask & (QUIC_EV_CONN_SPTO|QUIC_EV_CONN_PTIMER)) && qc->timer_task) {
609 chunk_appendf(&trace_buf,
610 " expire=%dms", TICKS_TO_MS(qc->timer - now_ms));
611 }
612 }
613
614 if (mask & QUIC_EV_CONN_SPPKTS) {
615 const struct quic_tx_packet *pkt = a2;
616
617 chunk_appendf(&trace_buf, " cwnd=%llu ppif=%llu pif=%llu",
618 (unsigned long long)qc->path->cwnd,
619 (unsigned long long)qc->path->prep_in_flight,
620 (unsigned long long)qc->path->in_flight);
621 if (pkt) {
622 const struct quic_frame *frm;
623 chunk_appendf(&trace_buf, " pn=%lu(%s) iflen=%llu",
624 (unsigned long)pkt->pn_node.key,
625 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
626 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
627 (unsigned long long)pkt->in_flight_len);
628 chunk_appendf(&trace_buf, " rx.bytes=%llu tx.bytes=%llu",
629 (unsigned long long)qc->rx.bytes,
630 (unsigned long long)qc->tx.bytes);
631 list_for_each_entry(frm, &pkt->frms, list) {
632 chunk_appendf(&trace_buf, " frm@%p", frm);
633 chunk_frm_appendf(&trace_buf, frm);
634 }
635 }
636 }
637
638 if (mask & QUIC_EV_CONN_SSLALERT) {
639 const uint8_t *alert = a2;
640 const enum ssl_encryption_level_t *level = a3;
641
642 if (alert)
643 chunk_appendf(&trace_buf, " alert=0x%02x", *alert);
644 if (level)
645 chunk_appendf(&trace_buf, " el=%c",
646 quic_enc_level_char(ssl_to_quic_enc_level(*level)));
647 }
648
649 if (mask & QUIC_EV_CONN_BCFRMS) {
650 const size_t *sz1 = a2;
651 const size_t *sz2 = a3;
652 const size_t *sz3 = a4;
653
654 if (sz1)
655 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz1);
656 if (sz2)
657 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz2);
658 if (sz3)
659 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz3);
660 }
661
662 if (mask & QUIC_EV_CONN_PSTRM) {
663 const struct quic_frame *frm = a2;
664
665 if (frm) {
666 chunk_appendf(&trace_buf, " frm@%p", frm);
667 chunk_frm_appendf(&trace_buf, frm);
668 }
669 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +0200670
671 if (mask & QUIC_EV_CONN_ELEVELSEL) {
672 const enum quic_handshake_state *state = a2;
673 const enum quic_tls_enc_level *level = a3;
674 const enum quic_tls_enc_level *next_level = a4;
675
676 if (state)
677 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(qc->state));
678 if (level)
679 chunk_appendf(&trace_buf, " level=%c", quic_enc_level_char(*level));
680 if (next_level)
681 chunk_appendf(&trace_buf, " next_level=%c", quic_enc_level_char(*next_level));
682
683 }
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200684
685 if (mask & QUIC_EV_CONN_RCV) {
686 const struct quic_dgram *dgram = a2;
687
688 if (dgram)
689 chunk_appendf(&trace_buf, " dgram.len=%zu", dgram->len);
690 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200691 }
692 if (mask & QUIC_EV_CONN_LPKT) {
693 const struct quic_rx_packet *pkt = a2;
694 const uint64_t *len = a3;
695 const struct quic_version *ver = a4;
696
697 if (pkt) {
698 chunk_appendf(&trace_buf, " pkt@%p type=0x%02x %s",
699 pkt, pkt->type, qc_pkt_long(pkt) ? "long" : "short");
700 if (pkt->pn_node.key != (uint64_t)-1)
701 chunk_appendf(&trace_buf, " pn=%llu", pkt->pn_node.key);
702 }
703
704 if (len)
705 chunk_appendf(&trace_buf, " len=%llu", (ull)*len);
706
707 if (ver)
708 chunk_appendf(&trace_buf, " ver=0x%08x", ver->num);
709 }
710
711 if (mask & QUIC_EV_STATELESS_RST) {
712 const struct quic_cid *cid = a2;
713
714 if (cid)
715 quic_cid_dump(&trace_buf, cid);
716 }
717
718}
719
720/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
721static inline int quic_peer_validated_addr(struct quic_conn *qc)
722{
723 struct quic_pktns *hdshk_pktns, *app_pktns;
724
725 if (!qc_is_listener(qc))
726 return 1;
727
728 hdshk_pktns = qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns;
729 app_pktns = qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns;
730 if ((hdshk_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
731 (app_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
732 qc->state >= QUIC_HS_ST_COMPLETE)
733 return 1;
734
735 return 0;
736}
737
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100738/* To be called to kill a connection as soon as possible (without sending any packet). */
739void qc_kill_conn(struct quic_conn *qc)
740{
741 qc->flags |= QUIC_FL_CONN_TO_KILL;
742 task_wakeup(qc->idle_timer_task, TASK_WOKEN_OTHER);
743}
744
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200745/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
746 * both loss detection and PTO and schedule the task assiated to this timer if needed.
747 */
748static inline void qc_set_timer(struct quic_conn *qc)
749{
750 struct quic_pktns *pktns;
751 unsigned int pto;
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100752 int handshake_confirmed;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200753
754 TRACE_ENTER(QUIC_EV_CONN_STIMER, qc,
755 NULL, NULL, &qc->path->ifae_pkts);
756
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100757 pktns = NULL;
758 if (!qc->timer_task) {
759 TRACE_PROTO("already released timer task", QUIC_EV_CONN_STIMER, qc);
760 goto leave;
761 }
762
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200763 pktns = quic_loss_pktns(qc);
764 if (tick_isset(pktns->tx.loss_time)) {
765 qc->timer = pktns->tx.loss_time;
766 goto out;
767 }
768
769 /* anti-amplification: the timer must be
770 * cancelled for a server which reached the anti-amplification limit.
771 */
772 if (!quic_peer_validated_addr(qc) &&
773 (qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
774 TRACE_PROTO("anti-amplification reached", QUIC_EV_CONN_STIMER, qc);
775 qc->timer = TICK_ETERNITY;
776 goto out;
777 }
778
779 if (!qc->path->ifae_pkts && quic_peer_validated_addr(qc)) {
780 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, qc);
781 /* Timer cancellation. */
782 qc->timer = TICK_ETERNITY;
783 goto out;
784 }
785
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100786 handshake_confirmed = qc->state >= QUIC_HS_ST_CONFIRMED;
787 pktns = quic_pto_pktns(qc, handshake_confirmed, &pto);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200788 if (tick_isset(pto))
789 qc->timer = pto;
790 out:
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100791 if (qc->timer == TICK_ETERNITY) {
792 qc->timer_task->expire = TICK_ETERNITY;
793 }
794 else if (tick_is_expired(qc->timer, now_ms)) {
795 TRACE_DEVEL("wakeup asap timer task", QUIC_EV_CONN_STIMER, qc);
796 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
797 }
798 else {
799 TRACE_DEVEL("timer task scheduling", QUIC_EV_CONN_STIMER, qc);
800 task_schedule(qc->timer_task, qc->timer);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200801 }
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100802 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200803 TRACE_LEAVE(QUIC_EV_CONN_STIMER, qc, pktns);
804}
805
806/* Derive new keys and ivs required for Key Update feature for <qc> QUIC
807 * connection.
808 * Return 1 if succeeded, 0 if not.
809 */
810static int quic_tls_key_update(struct quic_conn *qc)
811{
812 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
813 struct quic_tls_secrets *rx, *tx;
814 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
815 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
816 const struct quic_version *ver =
817 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
818 int ret = 0;
819
820 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
821
822 tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
823 rx = &tls_ctx->rx;
824 tx = &tls_ctx->tx;
825 nxt_rx = &qc->ku.nxt_rx;
826 nxt_tx = &qc->ku.nxt_tx;
827
828 /* Prepare new RX secrets */
829 if (!quic_tls_sec_update(rx->md, ver, nxt_rx->secret, nxt_rx->secretlen,
830 rx->secret, rx->secretlen)) {
831 TRACE_ERROR("New RX secret update failed", QUIC_EV_CONN_RWSEC, qc);
832 goto leave;
833 }
834
835 if (!quic_tls_derive_keys(rx->aead, NULL, rx->md, ver,
836 nxt_rx->key, nxt_rx->keylen,
837 nxt_rx->iv, nxt_rx->ivlen, NULL, 0,
838 nxt_rx->secret, nxt_rx->secretlen)) {
839 TRACE_ERROR("New RX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
840 goto leave;
841 }
842
843 /* Prepare new TX secrets */
844 if (!quic_tls_sec_update(tx->md, ver, nxt_tx->secret, nxt_tx->secretlen,
845 tx->secret, tx->secretlen)) {
846 TRACE_ERROR("New TX secret update failed", QUIC_EV_CONN_RWSEC, qc);
847 goto leave;
848 }
849
850 if (!quic_tls_derive_keys(tx->aead, NULL, tx->md, ver,
851 nxt_tx->key, nxt_tx->keylen,
852 nxt_tx->iv, nxt_tx->ivlen, NULL, 0,
853 nxt_tx->secret, nxt_tx->secretlen)) {
854 TRACE_ERROR("New TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
855 goto leave;
856 }
857
858 if (nxt_rx->ctx) {
859 EVP_CIPHER_CTX_free(nxt_rx->ctx);
860 nxt_rx->ctx = NULL;
861 }
862
863 if (!quic_tls_rx_ctx_init(&nxt_rx->ctx, tls_ctx->rx.aead, nxt_rx->key)) {
864 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
865 goto leave;
866 }
867
868 if (nxt_tx->ctx) {
869 EVP_CIPHER_CTX_free(nxt_tx->ctx);
870 nxt_tx->ctx = NULL;
871 }
872
873 if (!quic_tls_rx_ctx_init(&nxt_tx->ctx, tls_ctx->tx.aead, nxt_tx->key)) {
874 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
875 goto leave;
876 }
877
878 ret = 1;
879 leave:
880 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc);
881 return ret;
882}
883
884/* Rotate the Key Update information for <qc> QUIC connection.
885 * Must be used after having updated them.
886 * Always succeeds.
887 */
888static void quic_tls_rotate_keys(struct quic_conn *qc)
889{
890 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
891 unsigned char *curr_secret, *curr_iv, *curr_key;
892 EVP_CIPHER_CTX *curr_ctx;
893
894 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
895
896 /* Rotate the RX secrets */
897 curr_ctx = tls_ctx->rx.ctx;
898 curr_secret = tls_ctx->rx.secret;
899 curr_iv = tls_ctx->rx.iv;
900 curr_key = tls_ctx->rx.key;
901
902 tls_ctx->rx.ctx = qc->ku.nxt_rx.ctx;
903 tls_ctx->rx.secret = qc->ku.nxt_rx.secret;
904 tls_ctx->rx.iv = qc->ku.nxt_rx.iv;
905 tls_ctx->rx.key = qc->ku.nxt_rx.key;
906
907 qc->ku.nxt_rx.ctx = qc->ku.prv_rx.ctx;
908 qc->ku.nxt_rx.secret = qc->ku.prv_rx.secret;
909 qc->ku.nxt_rx.iv = qc->ku.prv_rx.iv;
910 qc->ku.nxt_rx.key = qc->ku.prv_rx.key;
911
912 qc->ku.prv_rx.ctx = curr_ctx;
913 qc->ku.prv_rx.secret = curr_secret;
914 qc->ku.prv_rx.iv = curr_iv;
915 qc->ku.prv_rx.key = curr_key;
916 qc->ku.prv_rx.pn = tls_ctx->rx.pn;
917
918 /* Update the TX secrets */
919 curr_ctx = tls_ctx->tx.ctx;
920 curr_secret = tls_ctx->tx.secret;
921 curr_iv = tls_ctx->tx.iv;
922 curr_key = tls_ctx->tx.key;
923
924 tls_ctx->tx.ctx = qc->ku.nxt_tx.ctx;
925 tls_ctx->tx.secret = qc->ku.nxt_tx.secret;
926 tls_ctx->tx.iv = qc->ku.nxt_tx.iv;
927 tls_ctx->tx.key = qc->ku.nxt_tx.key;
928
929 qc->ku.nxt_tx.ctx = curr_ctx;
930 qc->ku.nxt_tx.secret = curr_secret;
931 qc->ku.nxt_tx.iv = curr_iv;
932 qc->ku.nxt_tx.key = curr_key;
933
934 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
935}
936
937/* returns 0 on error, 1 on success */
938int ha_quic_set_encryption_secrets(SSL *ssl, enum ssl_encryption_level_t level,
939 const uint8_t *read_secret,
940 const uint8_t *write_secret, size_t secret_len)
941{
942 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
943 struct quic_tls_ctx *tls_ctx = &qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
944 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200945 struct quic_tls_secrets *rx = NULL, *tx = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200946 const struct quic_version *ver =
947 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
948 int ret = 0;
949
950 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
951 BUG_ON(secret_len > QUIC_TLS_SECRET_LEN);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100952
953 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
954 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
955 goto out;
956 }
957
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200958 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
959 TRACE_PROTO("CC required", QUIC_EV_CONN_RWSEC, qc);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200960 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200961 }
962
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200963 if (!read_secret)
964 goto write;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200965
966 rx = &tls_ctx->rx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200967 if (!quic_tls_secrets_keys_alloc(rx)) {
968 TRACE_ERROR("RX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
969 goto leave;
970 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200971
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200972 rx->aead = tls_aead(cipher);
973 rx->md = tls_md(cipher);
974 rx->hp = tls_hp(cipher);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200975
976 if (!quic_tls_derive_keys(rx->aead, rx->hp, rx->md, ver, rx->key, rx->keylen,
977 rx->iv, rx->ivlen, rx->hp_key, sizeof rx->hp_key,
978 read_secret, secret_len)) {
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200979 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200980 goto leave;
981 }
982
983 if (!quic_tls_rx_ctx_init(&rx->ctx, rx->aead, rx->key)) {
984 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
985 goto leave;
986 }
987
988 if (!quic_tls_dec_aes_ctx_init(&rx->hp_ctx, rx->hp, rx->hp_key)) {
989 TRACE_ERROR("could not initial RX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
990 goto leave;
991 }
992
993 /* Enqueue this connection asap if we could derive O-RTT secrets as
994 * listener. Note that a listener derives only RX secrets for this
995 * level.
996 */
997 if (qc_is_listener(qc) && level == ssl_encryption_early_data) {
998 TRACE_DEVEL("pushing connection into accept queue", QUIC_EV_CONN_RWSEC, qc);
999 quic_accept_push_qc(qc);
1000 }
1001
1002write:
1003
1004 if (!write_secret)
1005 goto out;
1006
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001007 tx = &tls_ctx->tx;
1008 if (!quic_tls_secrets_keys_alloc(tx)) {
1009 TRACE_ERROR("TX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
1010 goto leave;
1011 }
1012
1013 tx->aead = tls_aead(cipher);
1014 tx->md = tls_md(cipher);
1015 tx->hp = tls_hp(cipher);
1016
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001017 if (!quic_tls_derive_keys(tx->aead, tx->hp, tx->md, ver, tx->key, tx->keylen,
1018 tx->iv, tx->ivlen, tx->hp_key, sizeof tx->hp_key,
1019 write_secret, secret_len)) {
1020 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
1021 goto leave;
1022 }
1023
1024 if (!quic_tls_tx_ctx_init(&tx->ctx, tx->aead, tx->key)) {
1025 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
1026 goto leave;
1027 }
1028
1029 if (!quic_tls_enc_aes_ctx_init(&tx->hp_ctx, tx->hp, tx->hp_key)) {
1030 TRACE_ERROR("could not initial TX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
1031 goto leave;
1032 }
1033
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01001034 if (level == ssl_encryption_handshake && qc_is_listener(qc)) {
1035 qc->enc_params_len =
1036 quic_transport_params_encode(qc->enc_params,
1037 qc->enc_params + sizeof qc->enc_params,
1038 &qc->rx.params, ver, 1);
1039 if (!qc->enc_params_len) {
1040 TRACE_ERROR("quic_transport_params_encode() failed", QUIC_EV_CONN_RWSEC);
1041 goto leave;
1042 }
1043
1044 if (!SSL_set_quic_transport_params(qc->xprt_ctx->ssl, qc->enc_params, qc->enc_params_len)) {
1045 TRACE_ERROR("SSL_set_quic_transport_params() failed", QUIC_EV_CONN_RWSEC);
1046 goto leave;
1047 }
1048 }
1049
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001050 if (level == ssl_encryption_application) {
1051 struct quic_tls_kp *prv_rx = &qc->ku.prv_rx;
1052 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
1053 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
1054
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001055 if (rx) {
1056 if (!(rx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1057 TRACE_ERROR("Could not allocate RX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1058 goto leave;
1059 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001060
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001061 memcpy(rx->secret, read_secret, secret_len);
1062 rx->secretlen = secret_len;
1063 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001064
1065 if (tx) {
1066 if (!(tx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1067 TRACE_ERROR("Could not allocate TX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1068 goto leave;
1069 }
1070
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001071 memcpy(tx->secret, write_secret, secret_len);
1072 tx->secretlen = secret_len;
1073 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001074
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001075 /* Initialize all the secret keys lengths */
1076 prv_rx->secretlen = nxt_rx->secretlen = nxt_tx->secretlen = secret_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001077 }
1078
1079 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001080 ret = 1;
1081 leave:
1082 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc, &level);
1083 return ret;
1084}
1085
1086/* This function copies the CRYPTO data provided by the TLS stack found at <data>
1087 * with <len> as size in CRYPTO buffers dedicated to store the information about
1088 * outgoing CRYPTO frames so that to be able to replay the CRYPTO data streams.
1089 * It fails (returns 0) only if it could not managed to allocate enough CRYPTO
1090 * buffers to store all the data.
1091 * Note that CRYPTO data may exist at any encryption level except at 0-RTT.
1092 */
1093static int quic_crypto_data_cpy(struct quic_conn *qc, struct quic_enc_level *qel,
1094 const unsigned char *data, size_t len)
1095{
1096 struct quic_crypto_buf **qcb;
1097 /* The remaining byte to store in CRYPTO buffers. */
1098 size_t cf_offset, cf_len, *nb_buf;
1099 unsigned char *pos;
1100 int ret = 0;
1101
1102 nb_buf = &qel->tx.crypto.nb_buf;
1103 qcb = &qel->tx.crypto.bufs[*nb_buf - 1];
1104 cf_offset = (*nb_buf - 1) * QUIC_CRYPTO_BUF_SZ + (*qcb)->sz;
1105 cf_len = len;
1106
1107 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1108
1109 while (len) {
1110 size_t to_copy, room;
1111
1112 pos = (*qcb)->data + (*qcb)->sz;
1113 room = QUIC_CRYPTO_BUF_SZ - (*qcb)->sz;
1114 to_copy = len > room ? room : len;
1115 if (to_copy) {
1116 memcpy(pos, data, to_copy);
1117 /* Increment the total size of this CRYPTO buffers by <to_copy>. */
1118 qel->tx.crypto.sz += to_copy;
1119 (*qcb)->sz += to_copy;
1120 len -= to_copy;
1121 data += to_copy;
1122 }
1123 else {
1124 struct quic_crypto_buf **tmp;
1125
1126 // FIXME: realloc!
1127 tmp = realloc(qel->tx.crypto.bufs,
1128 (*nb_buf + 1) * sizeof *qel->tx.crypto.bufs);
1129 if (tmp) {
1130 qel->tx.crypto.bufs = tmp;
1131 qcb = &qel->tx.crypto.bufs[*nb_buf];
1132 *qcb = pool_alloc(pool_head_quic_crypto_buf);
1133 if (!*qcb) {
1134 TRACE_ERROR("Could not allocate crypto buf", QUIC_EV_CONN_ADDDATA, qc);
1135 goto leave;
1136 }
1137
1138 (*qcb)->sz = 0;
1139 ++*nb_buf;
1140 }
1141 else {
1142 break;
1143 }
1144 }
1145 }
1146
1147 /* Allocate a TX CRYPTO frame only if all the CRYPTO data
1148 * have been buffered.
1149 */
1150 if (!len) {
1151 struct quic_frame *frm;
1152 struct quic_frame *found = NULL;
1153
1154 /* There is at most one CRYPTO frame in this packet number
1155 * space. Let's look for it.
1156 */
1157 list_for_each_entry(frm, &qel->pktns->tx.frms, list) {
1158 if (frm->type != QUIC_FT_CRYPTO)
1159 continue;
1160
1161 /* Found */
1162 found = frm;
1163 break;
1164 }
1165
1166 if (found) {
1167 found->crypto.len += cf_len;
1168 }
1169 else {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01001170 frm = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001171 if (!frm) {
1172 TRACE_ERROR("Could not allocate quic frame", QUIC_EV_CONN_ADDDATA, qc);
1173 goto leave;
1174 }
1175
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001176 frm->crypto.offset = cf_offset;
1177 frm->crypto.len = cf_len;
1178 frm->crypto.qel = qel;
1179 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
1180 }
1181 }
1182 ret = len == 0;
1183 leave:
1184 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1185 return ret;
1186}
1187
1188/* Prepare the emission of CONNECTION_CLOSE with error <err>. All send/receive
1189 * activity for <qc> will be interrupted.
1190 */
1191void quic_set_connection_close(struct quic_conn *qc, const struct quic_err err)
1192{
1193 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1194 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)
1195 goto leave;
1196
1197 TRACE_STATE("setting immediate close", QUIC_EV_CONN_CLOSE, qc);
1198 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
1199 qc->err.code = err.code;
1200 qc->err.app = err.app;
1201 leave:
1202 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1203}
1204
1205/* Set <alert> TLS alert as QUIC CRYPTO_ERROR error */
1206void quic_set_tls_alert(struct quic_conn *qc, int alert)
1207{
1208 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1209
1210 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
1211 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
1212 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
1213 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
1214 }
1215 quic_set_connection_close(qc, quic_err_tls(alert));
1216 qc->flags |= QUIC_FL_CONN_TLS_ALERT;
1217 TRACE_STATE("Alert set", QUIC_EV_CONN_SSLALERT, qc);
1218
1219 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1220}
1221
1222/* Set the application for <qc> QUIC connection.
1223 * Return 1 if succeeded, 0 if not.
1224 */
1225int quic_set_app_ops(struct quic_conn *qc, const unsigned char *alpn, size_t alpn_len)
1226{
1227 if (alpn_len >= 2 && memcmp(alpn, "h3", 2) == 0)
1228 qc->app_ops = &h3_ops;
1229 else if (alpn_len >= 10 && memcmp(alpn, "hq-interop", 10) == 0)
1230 qc->app_ops = &hq_interop_ops;
1231 else
1232 return 0;
1233
1234 return 1;
1235}
1236
1237/* ->add_handshake_data QUIC TLS callback used by the QUIC TLS stack when it
1238 * wants to provide the QUIC layer with CRYPTO data.
1239 * Returns 1 if succeeded, 0 if not.
1240 */
1241int ha_quic_add_handshake_data(SSL *ssl, enum ssl_encryption_level_t level,
1242 const uint8_t *data, size_t len)
1243{
1244 struct quic_conn *qc;
1245 enum quic_tls_enc_level tel;
1246 struct quic_enc_level *qel;
1247 int ret = 0;
1248
1249 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1250 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1251
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01001252 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
1253 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
1254 goto out;
1255 }
1256
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001257 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
1258 TRACE_PROTO("CC required", QUIC_EV_CONN_ADDDATA, qc);
1259 goto out;
1260 }
1261
1262 tel = ssl_to_quic_enc_level(level);
1263 if (tel == -1) {
1264 TRACE_ERROR("Wrong encryption level", QUIC_EV_CONN_ADDDATA, qc);
1265 goto leave;
1266 }
1267
1268 qel = &qc->els[tel];
1269 if (!quic_crypto_data_cpy(qc, qel, data, len)) {
1270 TRACE_ERROR("Could not bufferize", QUIC_EV_CONN_ADDDATA, qc);
1271 goto leave;
1272 }
1273
1274 TRACE_DEVEL("CRYPTO data buffered", QUIC_EV_CONN_ADDDATA,
1275 qc, &level, &len);
1276 out:
1277 ret = 1;
1278 leave:
1279 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1280 return ret;
1281}
1282
1283int ha_quic_flush_flight(SSL *ssl)
1284{
1285 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1286
1287 TRACE_ENTER(QUIC_EV_CONN_FFLIGHT, qc);
1288 TRACE_LEAVE(QUIC_EV_CONN_FFLIGHT, qc);
1289
1290 return 1;
1291}
1292
1293int ha_quic_send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
1294{
1295 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1296
1297 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1298
1299 TRACE_PROTO("Received TLS alert", QUIC_EV_CONN_SSLALERT, qc, &alert, &level);
1300
1301 quic_set_tls_alert(qc, alert);
1302 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1303 return 1;
1304}
1305
1306/* QUIC TLS methods */
1307static SSL_QUIC_METHOD ha_quic_method = {
1308 .set_encryption_secrets = ha_quic_set_encryption_secrets,
1309 .add_handshake_data = ha_quic_add_handshake_data,
1310 .flush_flight = ha_quic_flush_flight,
1311 .send_alert = ha_quic_send_alert,
1312};
1313
1314/* Initialize the TLS context of a listener with <bind_conf> as configuration.
1315 * Returns an error count.
1316 */
1317int ssl_quic_initial_ctx(struct bind_conf *bind_conf)
1318{
1319 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
1320 int cfgerr = 0;
1321
1322 long options =
1323 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1324 SSL_OP_SINGLE_ECDH_USE |
1325 SSL_OP_CIPHER_SERVER_PREFERENCE;
1326 SSL_CTX *ctx;
1327
1328 ctx = SSL_CTX_new(TLS_server_method());
1329 bind_conf->initial_ctx = ctx;
1330
1331 SSL_CTX_set_options(ctx, options);
1332 SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
1333 SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
1334 SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
1335
1336#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1337# if defined(HAVE_SSL_CLIENT_HELLO_CB)
1338# if defined(SSL_OP_NO_ANTI_REPLAY)
1339 if (bind_conf->ssl_conf.early_data) {
1340 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
1341 SSL_CTX_set_max_early_data(ctx, 0xffffffff);
1342 }
1343# endif /* !SSL_OP_NO_ANTI_REPLAY */
1344 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
1345 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
1346# else /* ! HAVE_SSL_CLIENT_HELLO_CB */
1347 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
1348# endif
1349 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
1350#endif
1351 SSL_CTX_set_quic_method(ctx, &ha_quic_method);
1352
1353 return cfgerr;
1354}
1355
1356/* Decode an expected packet number from <truncated_on> its truncated value,
1357 * depending on <largest_pn> the largest received packet number, and <pn_nbits>
1358 * the number of bits used to encode this packet number (its length in bytes * 8).
1359 * See https://quicwg.org/base-drafts/draft-ietf-quic-transport.html#packet-encoding
1360 */
1361static uint64_t decode_packet_number(uint64_t largest_pn,
1362 uint32_t truncated_pn, unsigned int pn_nbits)
1363{
1364 uint64_t expected_pn = largest_pn + 1;
1365 uint64_t pn_win = (uint64_t)1 << pn_nbits;
1366 uint64_t pn_hwin = pn_win / 2;
1367 uint64_t pn_mask = pn_win - 1;
1368 uint64_t candidate_pn;
1369
1370
1371 candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
1372 /* Note that <pn_win> > <pn_hwin>. */
1373 if (candidate_pn < QUIC_MAX_PACKET_NUM - pn_win &&
1374 candidate_pn + pn_hwin <= expected_pn)
1375 return candidate_pn + pn_win;
1376
1377 if (candidate_pn > expected_pn + pn_hwin && candidate_pn >= pn_win)
1378 return candidate_pn - pn_win;
1379
1380 return candidate_pn;
1381}
1382
1383/* Remove the header protection of <pkt> QUIC packet using <tls_ctx> as QUIC TLS
1384 * cryptographic context.
1385 * <largest_pn> is the largest received packet number and <pn> the address of
1386 * the packet number field for this packet with <byte0> address of its first byte.
1387 * <end> points to one byte past the end of this packet.
1388 * Returns 1 if succeeded, 0 if not.
1389 */
1390static int qc_do_rm_hp(struct quic_conn *qc,
1391 struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx,
1392 int64_t largest_pn, unsigned char *pn, unsigned char *byte0)
1393{
1394 int ret, i, pnlen;
1395 uint64_t packet_number;
1396 uint32_t truncated_pn = 0;
1397 unsigned char mask[5] = {0};
1398 unsigned char *sample;
1399 EVP_CIPHER_CTX *cctx = NULL;
1400
1401 TRACE_ENTER(QUIC_EV_CONN_RMHP, qc);
1402
1403 ret = 0;
1404
1405 /* Check there is enough data in this packet. */
1406 if (pkt->len - (pn - byte0) < QUIC_PACKET_PN_MAXLEN + sizeof mask) {
1407 TRACE_PROTO("too short packet", QUIC_EV_CONN_RMHP, qc, pkt);
1408 goto leave;
1409 }
1410
1411 cctx = EVP_CIPHER_CTX_new();
1412 if (!cctx) {
1413 TRACE_ERROR("memory allocation failed", QUIC_EV_CONN_RMHP, qc, pkt);
1414 goto leave;
1415 }
1416
1417 sample = pn + QUIC_PACKET_PN_MAXLEN;
1418
1419 if (!quic_tls_aes_decrypt(mask, sample, sizeof mask, tls_ctx->rx.hp_ctx)) {
1420 TRACE_ERROR("HP removing failed", QUIC_EV_CONN_RMHP, qc, pkt);
1421 goto leave;
1422 }
1423
1424 *byte0 ^= mask[0] & (*byte0 & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
1425 pnlen = (*byte0 & QUIC_PACKET_PNL_BITMASK) + 1;
1426 for (i = 0; i < pnlen; i++) {
1427 pn[i] ^= mask[i + 1];
1428 truncated_pn = (truncated_pn << 8) | pn[i];
1429 }
1430
1431 packet_number = decode_packet_number(largest_pn, truncated_pn, pnlen * 8);
1432 /* Store remaining information for this unprotected header */
1433 pkt->pn = packet_number;
1434 pkt->pnl = pnlen;
1435
1436 ret = 1;
1437 leave:
1438 if (cctx)
1439 EVP_CIPHER_CTX_free(cctx);
1440 TRACE_LEAVE(QUIC_EV_CONN_RMHP, qc);
1441 return ret;
1442}
1443
1444/* Encrypt the payload of a QUIC packet with <pn> as number found at <payload>
1445 * address, with <payload_len> as payload length, <aad> as address of
1446 * the ADD and <aad_len> as AAD length depending on the <tls_ctx> QUIC TLS
1447 * context.
1448 * Returns 1 if succeeded, 0 if not.
1449 */
1450static int quic_packet_encrypt(unsigned char *payload, size_t payload_len,
1451 unsigned char *aad, size_t aad_len, uint64_t pn,
1452 struct quic_tls_ctx *tls_ctx, struct quic_conn *qc)
1453{
1454 int ret = 0;
1455 unsigned char iv[QUIC_TLS_IV_LEN];
1456 unsigned char *tx_iv = tls_ctx->tx.iv;
1457 size_t tx_iv_sz = tls_ctx->tx.ivlen;
1458 struct enc_debug_info edi;
1459
1460 TRACE_ENTER(QUIC_EV_CONN_ENCPKT, qc);
1461
1462 if (!quic_aead_iv_build(iv, sizeof iv, tx_iv, tx_iv_sz, pn)) {
1463 TRACE_ERROR("AEAD IV building for encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1464 goto err;
1465 }
1466
1467 if (!quic_tls_encrypt(payload, payload_len, aad, aad_len,
1468 tls_ctx->tx.ctx, tls_ctx->tx.aead, tls_ctx->tx.key, iv)) {
1469 TRACE_ERROR("QUIC packet encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1470 goto err;
1471 }
1472
1473 ret = 1;
1474 leave:
1475 TRACE_LEAVE(QUIC_EV_CONN_ENCPKT, qc);
1476 return ret;
1477
1478 err:
1479 enc_debug_info_init(&edi, payload, payload_len, aad, aad_len, pn);
1480 goto leave;
1481}
1482
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001483/* Decrypt <pkt> packet using encryption level <qel> for <qc> connection.
1484 * Decryption is done in place in packet buffer.
1485 *
Ilya Shipitsin5fa29b82022-12-07 09:46:19 +05001486 * Returns 1 on success else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001487 */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001488static int qc_pkt_decrypt(struct quic_conn *qc, struct quic_enc_level *qel,
1489 struct quic_rx_packet *pkt)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001490{
1491 int ret, kp_changed;
1492 unsigned char iv[QUIC_TLS_IV_LEN];
1493 struct quic_tls_ctx *tls_ctx = &qel->tls_ctx;
1494 EVP_CIPHER_CTX *rx_ctx = tls_ctx->rx.ctx;
1495 unsigned char *rx_iv = tls_ctx->rx.iv;
1496 size_t rx_iv_sz = tls_ctx->rx.ivlen;
1497 unsigned char *rx_key = tls_ctx->rx.key;
1498
1499 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
1500
1501 ret = 0;
1502 kp_changed = 0;
1503
1504 if (pkt->type == QUIC_PACKET_TYPE_SHORT) {
1505 /* The two tested bits are not at the same position,
1506 * this is why they are first both inversed.
1507 */
1508 if (!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT) ^ !(tls_ctx->flags & QUIC_FL_TLS_KP_BIT_SET)) {
1509 if (pkt->pn < tls_ctx->rx.pn) {
1510 /* The lowest packet number of a previous key phase
1511 * cannot be null if it really stores previous key phase
1512 * secrets.
1513 */
1514 // TODO: check if BUG_ON() more suitable
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001515 if (!qc->ku.prv_rx.pn) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001516 TRACE_ERROR("null previous packet number", QUIC_EV_CONN_RXPKT, qc);
1517 goto leave;
1518 }
1519
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001520 rx_ctx = qc->ku.prv_rx.ctx;
1521 rx_iv = qc->ku.prv_rx.iv;
1522 rx_key = qc->ku.prv_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001523 }
1524 else if (pkt->pn > qel->pktns->rx.largest_pn) {
1525 /* Next key phase */
1526 kp_changed = 1;
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001527 rx_ctx = qc->ku.nxt_rx.ctx;
1528 rx_iv = qc->ku.nxt_rx.iv;
1529 rx_key = qc->ku.nxt_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001530 }
1531 }
1532 }
1533
1534 if (!quic_aead_iv_build(iv, sizeof iv, rx_iv, rx_iv_sz, pkt->pn)) {
1535 TRACE_ERROR("quic_aead_iv_build() failed", QUIC_EV_CONN_RXPKT, qc);
1536 goto leave;
1537 }
1538
1539 ret = quic_tls_decrypt(pkt->data + pkt->aad_len, pkt->len - pkt->aad_len,
1540 pkt->data, pkt->aad_len,
1541 rx_ctx, tls_ctx->rx.aead, rx_key, iv);
1542 if (!ret) {
1543 TRACE_ERROR("quic_tls_decrypt() failed", QUIC_EV_CONN_RXPKT, qc);
1544 goto leave;
1545 }
1546
1547 /* Update the keys only if the packet decryption succeeded. */
1548 if (kp_changed) {
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001549 quic_tls_rotate_keys(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001550 /* Toggle the Key Phase bit */
1551 tls_ctx->flags ^= QUIC_FL_TLS_KP_BIT_SET;
1552 /* Store the lowest packet number received for the current key phase */
1553 tls_ctx->rx.pn = pkt->pn;
1554 /* Prepare the next key update */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001555 if (!quic_tls_key_update(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001556 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_RXPKT, qc);
1557 goto leave;
1558 }
1559 }
1560
1561 /* Update the packet length (required to parse the frames). */
1562 pkt->len -= QUIC_TLS_TAG_LEN;
1563 ret = 1;
1564 leave:
1565 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
1566 return ret;
1567}
1568
1569
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001570/* Release <frm> frame and mark its copies as acknowledged */
1571void qc_release_frm(struct quic_conn *qc, struct quic_frame *frm)
1572{
1573 uint64_t pn;
1574 struct quic_frame *origin, *f, *tmp;
1575
1576 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1577
1578 /* Identify this frame: a frame copy or one of its copies */
1579 origin = frm->origin ? frm->origin : frm;
1580 /* Ensure the source of the copies is flagged as acked, <frm> being
1581 * possibly a copy of <origin>
1582 */
1583 origin->flags |= QUIC_FL_TX_FRAME_ACKED;
1584 /* Mark all the copy of <origin> as acknowledged. We must
1585 * not release the packets (releasing the frames) at this time as
1586 * they are possibly also to be acknowledged alongside the
1587 * the current one.
1588 */
1589 list_for_each_entry_safe(f, tmp, &origin->reflist, ref) {
1590 if (f->pkt) {
1591 f->flags |= QUIC_FL_TX_FRAME_ACKED;
1592 f->origin = NULL;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001593 LIST_DEL_INIT(&f->ref);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001594 pn = f->pkt->pn_node.key;
1595 TRACE_DEVEL("mark frame as acked from packet",
1596 QUIC_EV_CONN_PRSAFRM, qc, f, &pn);
1597 }
1598 else {
1599 TRACE_DEVEL("freeing unsent frame",
1600 QUIC_EV_CONN_PRSAFRM, qc, f);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001601 LIST_DEL_INIT(&f->ref);
1602 qc_frm_free(&f);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001603 }
1604 }
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001605 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001606 pn = frm->pkt->pn_node.key;
1607 quic_tx_packet_refdec(frm->pkt);
1608 TRACE_DEVEL("freeing frame from packet",
1609 QUIC_EV_CONN_PRSAFRM, qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001610 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001611
1612 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1613}
1614
1615/* Schedule a CONNECTION_CLOSE emission on <qc> if the MUX has been released
1616 * and all STREAM data are acknowledged. The MUX is responsible to have set
1617 * <qc.err> before as it is reused for the CONNECTION_CLOSE frame.
1618 *
1619 * TODO this should also be called on lost packet detection
1620 */
1621void qc_check_close_on_released_mux(struct quic_conn *qc)
1622{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001623 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1624
1625 if (qc->mux_state == QC_MUX_RELEASED && eb_is_empty(&qc->streams_by_id)) {
1626 /* Reuse errcode which should have been previously set by the MUX on release. */
1627 quic_set_connection_close(qc, qc->err);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02001628 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001629 }
1630
1631 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1632}
1633
1634/* Remove from <stream> the acknowledged frames.
1635 *
1636 * Returns 1 if at least one frame was removed else 0.
1637 */
1638static int quic_stream_try_to_consume(struct quic_conn *qc,
1639 struct qc_stream_desc *stream)
1640{
1641 int ret;
1642 struct eb64_node *frm_node;
1643
1644 TRACE_ENTER(QUIC_EV_CONN_ACKSTRM, qc);
1645
1646 ret = 0;
1647 frm_node = eb64_first(&stream->acked_frms);
1648 while (frm_node) {
1649 struct quic_stream *strm;
1650 struct quic_frame *frm;
1651 size_t offset, len;
1652
1653 strm = eb64_entry(frm_node, struct quic_stream, offset);
1654 offset = strm->offset.key;
1655 len = strm->len;
1656
1657 if (offset > stream->ack_offset)
1658 break;
1659
1660 if (qc_stream_desc_ack(&stream, offset, len)) {
1661 /* cf. next comment : frame may be freed at this stage. */
1662 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1663 qc, stream ? strm : NULL, stream);
1664 ret = 1;
1665 }
1666
1667 /* If stream is NULL after qc_stream_desc_ack(), it means frame
1668 * has been freed. with the stream frames tree. Nothing to do
1669 * anymore in here.
1670 */
1671 if (!stream) {
1672 qc_check_close_on_released_mux(qc);
1673 ret = 1;
1674 goto leave;
1675 }
1676
1677 frm_node = eb64_next(frm_node);
1678 eb64_delete(&strm->offset);
1679
1680 frm = container_of(strm, struct quic_frame, stream);
1681 qc_release_frm(qc, frm);
1682 }
1683
1684 leave:
1685 TRACE_LEAVE(QUIC_EV_CONN_ACKSTRM, qc);
1686 return ret;
1687}
1688
1689/* Treat <frm> frame whose packet it is attached to has just been acknowledged. */
1690static inline void qc_treat_acked_tx_frm(struct quic_conn *qc,
1691 struct quic_frame *frm)
1692{
1693 int stream_acked;
1694
1695 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc, frm);
1696
1697 stream_acked = 0;
1698 switch (frm->type) {
1699 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1700 {
1701 struct quic_stream *strm_frm = &frm->stream;
1702 struct eb64_node *node = NULL;
1703 struct qc_stream_desc *stream = NULL;
1704 const size_t offset = strm_frm->offset.key;
1705 const size_t len = strm_frm->len;
1706
1707 /* do not use strm_frm->stream as the qc_stream_desc instance
1708 * might be freed at this stage. Use the id to do a proper
1709 * lookup.
1710 *
1711 * TODO if lookup operation impact on the perf is noticeable,
1712 * implement a refcount on qc_stream_desc instances.
1713 */
1714 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1715 if (!node) {
1716 TRACE_DEVEL("acked stream for released stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm);
1717 qc_release_frm(qc, frm);
1718 /* early return */
1719 goto leave;
1720 }
1721 stream = eb64_entry(node, struct qc_stream_desc, by_id);
1722
1723 TRACE_DEVEL("acked stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm, stream);
1724 if (offset <= stream->ack_offset) {
1725 if (qc_stream_desc_ack(&stream, offset, len)) {
1726 stream_acked = 1;
1727 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1728 qc, strm_frm, stream);
1729 }
1730
1731 if (!stream) {
1732 /* no need to continue if stream freed. */
1733 TRACE_DEVEL("stream released and freed", QUIC_EV_CONN_ACKSTRM, qc);
1734 qc_release_frm(qc, frm);
1735 qc_check_close_on_released_mux(qc);
1736 break;
1737 }
1738
1739 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1740 qc, strm_frm, stream);
1741 qc_release_frm(qc, frm);
1742 }
1743 else {
1744 eb64_insert(&stream->acked_frms, &strm_frm->offset);
1745 }
1746
1747 stream_acked |= quic_stream_try_to_consume(qc, stream);
1748 }
1749 break;
1750 default:
1751 qc_release_frm(qc, frm);
1752 }
1753
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02001754 if (stream_acked) {
1755 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
1756 tasklet_wakeup(qc->subs->tasklet);
1757 qc->subs->events &= ~SUB_RETRY_SEND;
1758 if (!qc->subs->events)
1759 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001760 }
1761 }
1762 leave:
1763 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1764}
1765
1766/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1767 * deallocating them, and their TX frames.
1768 * Returns the last node reached to be used for the next range.
1769 * May be NULL if <largest> node could not be found.
1770 */
1771static inline struct eb64_node *qc_ackrng_pkts(struct quic_conn *qc,
1772 struct eb_root *pkts,
1773 unsigned int *pkt_flags,
1774 struct list *newly_acked_pkts,
1775 struct eb64_node *largest_node,
1776 uint64_t largest, uint64_t smallest)
1777{
1778 struct eb64_node *node;
1779 struct quic_tx_packet *pkt;
1780
1781 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1782
1783 node = largest_node ? largest_node : eb64_lookup_le(pkts, largest);
1784 while (node && node->key >= smallest) {
1785 struct quic_frame *frm, *frmbak;
1786
1787 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
1788 *pkt_flags |= pkt->flags;
1789 LIST_INSERT(newly_acked_pkts, &pkt->list);
1790 TRACE_DEVEL("Removing packet #", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
1791 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1792 qc_treat_acked_tx_frm(qc, frm);
Frédéric Lécaille814645f2022-11-18 18:15:28 +01001793 /* If there are others packet in the same datagram <pkt> is attached to,
1794 * detach the previous one and the next one from <pkt>.
1795 */
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01001796 quic_tx_packet_dgram_detach(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001797 node = eb64_prev(node);
1798 eb64_delete(&pkt->pn_node);
1799 }
1800
1801 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1802 return node;
1803}
1804
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001805/* Remove all frames from <pkt_frm_list> and reinsert them in the same order
1806 * they have been sent into <pktns_frm_list>. The loss counter of each frame is
1807 * incremented and checked if it does not exceed retransmission limit.
1808 *
1809 * Returns 1 on success, 0 if a frame loss limit is exceeded. A
1810 * CONNECTION_CLOSE is scheduled in this case.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001811 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001812static inline int qc_requeue_nacked_pkt_tx_frms(struct quic_conn *qc,
1813 struct quic_tx_packet *pkt,
1814 struct list *pktns_frm_list)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001815{
1816 struct quic_frame *frm, *frmbak;
1817 struct list tmp = LIST_HEAD_INIT(tmp);
1818 struct list *pkt_frm_list = &pkt->frms;
1819 uint64_t pn = pkt->pn_node.key;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001820 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001821
1822 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1823
1824 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
1825 /* First remove this frame from the packet it was attached to */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001826 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001827 quic_tx_packet_refdec(pkt);
1828 /* At this time, this frame is not freed but removed from its packet */
1829 frm->pkt = NULL;
1830 /* Remove any reference to this frame */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001831 qc_frm_unref(frm, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001832 switch (frm->type) {
1833 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1834 {
1835 struct quic_stream *strm_frm = &frm->stream;
1836 struct eb64_node *node = NULL;
1837 struct qc_stream_desc *stream_desc;
1838
1839 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1840 if (!node) {
1841 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
1842 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1843 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001844 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001845 continue;
1846 }
1847
1848 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
1849 /* Do not resend this frame if in the "already acked range" */
1850 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
1851 TRACE_DEVEL("ignored frame in already acked range",
1852 QUIC_EV_CONN_PRSAFRM, qc, frm);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001853 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001854 continue;
1855 }
1856 else if (strm_frm->offset.key < stream_desc->ack_offset) {
1857 strm_frm->offset.key = stream_desc->ack_offset;
1858 TRACE_DEVEL("updated partially acked frame",
1859 QUIC_EV_CONN_PRSAFRM, qc, frm);
1860 }
1861 break;
1862 }
1863
1864 default:
1865 break;
1866 }
1867
1868 /* Do not resend probing packet with old data */
1869 if (pkt->flags & QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA) {
1870 TRACE_DEVEL("ignored frame with old data from packet", QUIC_EV_CONN_PRSAFRM,
1871 qc, frm, &pn);
1872 if (frm->origin)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001873 LIST_DEL_INIT(&frm->ref);
1874 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001875 continue;
1876 }
1877
1878 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
1879 TRACE_DEVEL("already acked frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
1880 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1881 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001882 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001883 }
1884 else {
Amaury Denoyelle24d5b722023-01-31 11:44:50 +01001885 if (++frm->loss_count >= global.tune.quic_max_frame_loss) {
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001886 TRACE_ERROR("retransmission limit reached, closing the connection", QUIC_EV_CONN_PRSAFRM, qc);
1887 quic_set_connection_close(qc, quic_err_transport(QC_ERR_INTERNAL_ERROR));
1888 close = 1;
1889 }
1890
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001891 if (QUIC_FT_STREAM_8 <= frm->type && frm->type <= QUIC_FT_STREAM_F) {
1892 /* Mark this STREAM frame as lost. A look up their stream descriptor
1893 * will be performed to check the stream is not consumed or released.
1894 */
1895 frm->flags |= QUIC_FL_TX_FRAME_LOST;
1896 }
1897 LIST_APPEND(&tmp, &frm->list);
1898 TRACE_DEVEL("frame requeued", QUIC_EV_CONN_PRSAFRM, qc, frm);
1899 }
1900 }
1901
1902 LIST_SPLICE(pktns_frm_list, &tmp);
1903
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001904 end:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001905 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001906 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001907}
1908
1909/* Free <pkt> TX packet and its attached frames.
1910 * This is the responsibility of the caller to remove this packet of
1911 * any data structure it was possibly attached to.
1912 */
1913static inline void free_quic_tx_packet(struct quic_conn *qc,
1914 struct quic_tx_packet *pkt)
1915{
1916 struct quic_frame *frm, *frmbak;
1917
1918 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1919
1920 if (!pkt)
1921 goto leave;
1922
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001923 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1924 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001925 pool_free(pool_head_quic_tx_packet, pkt);
1926
1927 leave:
1928 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1929}
1930
1931/* Free the TX packets of <pkts> list */
1932static inline void free_quic_tx_pkts(struct quic_conn *qc, struct list *pkts)
1933{
1934 struct quic_tx_packet *pkt, *tmp;
1935
1936 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1937
1938 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1939 LIST_DELETE(&pkt->list);
1940 eb64_delete(&pkt->pn_node);
1941 free_quic_tx_packet(qc, pkt);
1942 }
1943
1944 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1945}
1946
1947/* Remove already sent ranges of acknowledged packet numbers from
1948 * <pktns> packet number space tree below <largest_acked_pn> possibly
1949 * updating the range which contains <largest_acked_pn>.
1950 * Never fails.
1951 */
1952static void qc_treat_ack_of_ack(struct quic_conn *qc,
1953 struct quic_pktns *pktns,
1954 int64_t largest_acked_pn)
1955{
1956 struct eb64_node *ar, *next_ar;
1957 struct quic_arngs *arngs = &pktns->rx.arngs;
1958
1959 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1960
1961 ar = eb64_first(&arngs->root);
1962 while (ar) {
1963 struct quic_arng_node *ar_node;
1964
1965 next_ar = eb64_next(ar);
1966 ar_node = eb64_entry(ar, struct quic_arng_node, first);
1967
1968 if ((int64_t)ar_node->first.key > largest_acked_pn) {
1969 TRACE_DEVEL("first.key > largest", QUIC_EV_CONN_PRSAFRM, qc);
1970 break;
1971 }
1972
1973 if (largest_acked_pn < ar_node->last) {
1974 eb64_delete(ar);
1975 ar_node->first.key = largest_acked_pn + 1;
1976 eb64_insert(&arngs->root, ar);
1977 break;
1978 }
1979
1980 eb64_delete(ar);
1981 pool_free(pool_head_quic_arng, ar_node);
1982 arngs->sz--;
1983 ar = next_ar;
1984 }
1985
1986 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1987}
1988
1989/* Send a packet ack event nofication for each newly acked packet of
1990 * <newly_acked_pkts> list and free them.
1991 * Always succeeds.
1992 */
1993static inline void qc_treat_newly_acked_pkts(struct quic_conn *qc,
1994 struct list *newly_acked_pkts)
1995{
1996 struct quic_tx_packet *pkt, *tmp;
1997 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
1998
1999 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2000
2001 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
2002 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2003 qc->path->prep_in_flight -= pkt->in_flight_len;
2004 qc->path->in_flight -= pkt->in_flight_len;
2005 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2006 qc->path->ifae_pkts--;
2007 /* If this packet contained an ACK frame, proceed to the
2008 * acknowledging of range of acks from the largest acknowledged
2009 * packet number which was sent in an ACK frame by this packet.
2010 */
2011 if (pkt->largest_acked_pn != -1)
2012 qc_treat_ack_of_ack(qc, pkt->pktns, pkt->largest_acked_pn);
2013 ev.ack.acked = pkt->in_flight_len;
2014 ev.ack.time_sent = pkt->time_sent;
2015 quic_cc_event(&qc->path->cc, &ev);
2016 LIST_DELETE(&pkt->list);
2017 eb64_delete(&pkt->pn_node);
2018 quic_tx_packet_refdec(pkt);
2019 }
2020
2021 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2022
2023}
2024
2025/* Release all the frames attached to <pktns> packet number space */
2026static inline void qc_release_pktns_frms(struct quic_conn *qc,
2027 struct quic_pktns *pktns)
2028{
2029 struct quic_frame *frm, *frmbak;
2030
2031 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
2032
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01002033 list_for_each_entry_safe(frm, frmbak, &pktns->tx.frms, list)
2034 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002035
2036 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
2037}
2038
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002039/* Handle <pkts> list of lost packets detected at <now_us> handling their TX
2040 * frames. Send a packet loss event to the congestion controller if in flight
2041 * packet have been lost. Also frees the packet in <pkts> list.
2042 *
2043 * Returns 1 on success else 0 if loss limit has been exceeded. A
2044 * CONNECTION_CLOSE was prepared to close the connection ASAP.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002045 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002046static inline int qc_release_lost_pkts(struct quic_conn *qc,
2047 struct quic_pktns *pktns,
2048 struct list *pkts,
2049 uint64_t now_us)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002050{
2051 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002052 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002053
2054 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2055
2056 if (LIST_ISEMPTY(pkts))
2057 goto leave;
2058
2059 oldest_lost = newest_lost = NULL;
2060 list_for_each_entry_safe(pkt, tmp, pkts, list) {
2061 struct list tmp = LIST_HEAD_INIT(tmp);
2062
2063 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2064 qc->path->prep_in_flight -= pkt->in_flight_len;
2065 qc->path->in_flight -= pkt->in_flight_len;
2066 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2067 qc->path->ifae_pkts--;
2068 /* Treat the frames of this lost packet. */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002069 if (!qc_requeue_nacked_pkt_tx_frms(qc, pkt, &pktns->tx.frms))
2070 close = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002071 LIST_DELETE(&pkt->list);
2072 if (!oldest_lost) {
2073 oldest_lost = newest_lost = pkt;
2074 }
2075 else {
2076 if (newest_lost != oldest_lost)
2077 quic_tx_packet_refdec(newest_lost);
2078 newest_lost = pkt;
2079 }
2080 }
2081
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002082 if (!close) {
2083 if (newest_lost) {
2084 /* Sent a congestion event to the controller */
2085 struct quic_cc_event ev = { };
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002086
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002087 ev.type = QUIC_CC_EVT_LOSS;
2088 ev.loss.time_sent = newest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002089
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002090 quic_cc_event(&qc->path->cc, &ev);
2091 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002092
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002093 /* If an RTT have been already sampled, <rtt_min> has been set.
2094 * We must check if we are experiencing a persistent congestion.
2095 * If this is the case, the congestion controller must re-enter
2096 * slow start state.
2097 */
2098 if (qc->path->loss.rtt_min && newest_lost != oldest_lost) {
2099 unsigned int period = newest_lost->time_sent - oldest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002100
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002101 if (quic_loss_persistent_congestion(&qc->path->loss, period,
2102 now_ms, qc->max_ack_delay))
2103 qc->path->cc.algo->slow_start(&qc->path->cc);
2104 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002105 }
2106
Amaury Denoyelle3a72ba22022-11-14 11:41:34 +01002107 /* <oldest_lost> cannot be NULL at this stage because we have ensured
2108 * that <pkts> list is not empty. Without this, GCC 12.2.0 reports a
2109 * possible overflow on a 0 byte region with O2 optimization.
2110 */
2111 ALREADY_CHECKED(oldest_lost);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002112 quic_tx_packet_refdec(oldest_lost);
2113 if (newest_lost != oldest_lost)
2114 quic_tx_packet_refdec(newest_lost);
2115
2116 leave:
2117 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002118 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002119}
2120
2121/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
2122 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
2123 * if the largest acked packet was newly acked and if there was at least one newly
2124 * acked ack-eliciting packet.
2125 * Return 1, if succeeded, 0 if not.
2126 */
2127static inline int qc_parse_ack_frm(struct quic_conn *qc,
2128 struct quic_frame *frm,
2129 struct quic_enc_level *qel,
2130 unsigned int *rtt_sample,
2131 const unsigned char **pos, const unsigned char *end)
2132{
2133 struct quic_ack *ack = &frm->ack;
2134 uint64_t smallest, largest;
2135 struct eb_root *pkts;
2136 struct eb64_node *largest_node;
2137 unsigned int time_sent, pkt_flags;
2138 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
2139 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2140 int ret = 0;
2141
2142 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2143
2144 if (ack->largest_ack > qel->pktns->tx.next_pn) {
2145 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
2146 qc, NULL, &ack->largest_ack);
2147 goto err;
2148 }
2149
2150 if (ack->first_ack_range > ack->largest_ack) {
2151 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
2152 qc, NULL, &ack->first_ack_range);
2153 goto err;
2154 }
2155
2156 largest = ack->largest_ack;
2157 smallest = largest - ack->first_ack_range;
2158 pkts = &qel->pktns->tx.pkts;
2159 pkt_flags = 0;
2160 largest_node = NULL;
2161 time_sent = 0;
2162
2163 if ((int64_t)ack->largest_ack > qel->pktns->rx.largest_acked_pn) {
2164 largest_node = eb64_lookup(pkts, largest);
2165 if (!largest_node) {
2166 TRACE_DEVEL("Largest acked packet not found",
2167 QUIC_EV_CONN_PRSAFRM, qc);
2168 }
2169 else {
2170 time_sent = eb64_entry(largest_node,
2171 struct quic_tx_packet, pn_node)->time_sent;
2172 }
2173 }
2174
2175 TRACE_PROTO("rcvd ack range", QUIC_EV_CONN_PRSAFRM,
2176 qc, NULL, &largest, &smallest);
2177 do {
2178 uint64_t gap, ack_range;
2179
2180 qc_ackrng_pkts(qc, pkts, &pkt_flags, &newly_acked_pkts,
2181 largest_node, largest, smallest);
2182 if (!ack->ack_range_num--)
2183 break;
2184
2185 if (!quic_dec_int(&gap, pos, end)) {
2186 TRACE_ERROR("quic_dec_int(gap) failed", QUIC_EV_CONN_PRSAFRM, qc);
2187 goto err;
2188 }
2189
2190 if (smallest < gap + 2) {
2191 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
2192 qc, NULL, &gap, &smallest);
2193 goto err;
2194 }
2195
2196 largest = smallest - gap - 2;
2197 if (!quic_dec_int(&ack_range, pos, end)) {
2198 TRACE_ERROR("quic_dec_int(ack_range) failed", QUIC_EV_CONN_PRSAFRM, qc);
2199 goto err;
2200 }
2201
2202 if (largest < ack_range) {
2203 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
2204 qc, NULL, &largest, &ack_range);
2205 goto err;
2206 }
2207
2208 /* Do not use this node anymore. */
2209 largest_node = NULL;
2210 /* Next range */
2211 smallest = largest - ack_range;
2212
2213 TRACE_PROTO("rcvd next ack range", QUIC_EV_CONN_PRSAFRM,
2214 qc, NULL, &largest, &smallest);
2215 } while (1);
2216
2217 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
2218 *rtt_sample = tick_remain(time_sent, now_ms);
2219 qel->pktns->rx.largest_acked_pn = ack->largest_ack;
2220 }
2221
2222 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
2223 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
2224 qc_packet_loss_lookup(qel->pktns, qc, &lost_pkts);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002225 if (!qc_release_lost_pkts(qc, qel->pktns, &lost_pkts, now_ms))
2226 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002227 }
2228 qc_treat_newly_acked_pkts(qc, &newly_acked_pkts);
2229 if (quic_peer_validated_addr(qc))
2230 qc->path->loss.pto_count = 0;
2231 qc_set_timer(qc);
2232 }
2233
2234 ret = 1;
2235 leave:
2236 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2237 return ret;
2238
2239 err:
2240 free_quic_tx_pkts(qc, &newly_acked_pkts);
2241 goto leave;
2242}
2243
2244/* This function gives the detail of the SSL error. It is used only
2245 * if the debug mode and the verbose mode are activated. It dump all
2246 * the SSL error until the stack was empty.
2247 */
2248static forceinline void qc_ssl_dump_errors(struct connection *conn)
2249{
2250 if (unlikely(global.mode & MODE_DEBUG)) {
2251 while (1) {
2252 const char *func = NULL;
2253 unsigned long ret;
2254
2255 ERR_peek_error_func(&func);
2256 ret = ERR_get_error();
2257 if (!ret)
2258 return;
2259
2260 fprintf(stderr, "conn. @%p OpenSSL error[0x%lx] %s: %s\n", conn, ret,
2261 func, ERR_reason_error_string(ret));
2262 }
2263 }
2264}
2265
2266int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx,
2267 const char **str, int *len);
2268
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002269/* Finalize <qc> QUIC connection:
2270 * - initialize the Initial QUIC TLS context for negotiated version,
2271 * - derive the secrets for this context,
2272 * - set them into the TLS stack,
2273 *
2274 * MUST be called after having received the remote transport parameters which
2275 * are parsed when the TLS callback for the ClientHello message is called upon
2276 * SSL_do_handshake() calls, not necessarily at the first time as this TLS
2277 * message may be splitted between packets
2278 * Return 1 if succeeded, 0 if not.
2279 */
2280static int qc_conn_finalize(struct quic_conn *qc, int server)
2281{
2282 int ret = 0;
2283
2284 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
2285
2286 if (qc->flags & QUIC_FL_CONN_FINALIZED)
2287 goto finalized;
2288
2289 if (qc->negotiated_version &&
2290 !qc_new_isecs(qc, &qc->negotiated_ictx, qc->negotiated_version,
2291 qc->odcid.data, qc->odcid.len, server))
2292 goto out;
2293
2294 /* This connection is functional (ready to send/receive) */
2295 qc->flags |= QUIC_FL_CONN_FINALIZED;
2296
2297 finalized:
2298 ret = 1;
2299 out:
2300 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
2301 return ret;
2302}
2303
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002304/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
2305 * from <qel> encryption level with <ctx> as QUIC connection context.
2306 * Remaining parameter are there for debugging purposes.
2307 * Return 1 if succeeded, 0 if not.
2308 */
2309static inline int qc_provide_cdata(struct quic_enc_level *el,
2310 struct ssl_sock_ctx *ctx,
2311 const unsigned char *data, size_t len,
2312 struct quic_rx_packet *pkt,
2313 struct quic_rx_crypto_frm *cf)
2314{
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002315#ifdef DEBUG_STRICT
2316 enum ncb_ret ncb_ret;
2317#endif
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002318 int ssl_err, state;
2319 struct quic_conn *qc;
2320 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002321 struct ncbuf *ncbuf = &el->cstream->rx.ncbuf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002322
2323 ssl_err = SSL_ERROR_NONE;
2324 qc = ctx->qc;
2325
2326 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, qc);
2327
2328 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
2329 TRACE_ERROR("SSL_provide_quic_data() error",
2330 QUIC_EV_CONN_SSLDATA, qc, pkt, cf, ctx->ssl);
2331 goto leave;
2332 }
2333
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002334 TRACE_PROTO("in order CRYPTO data",
2335 QUIC_EV_CONN_SSLDATA, qc, NULL, cf, ctx->ssl);
2336
2337 state = qc->state;
2338 if (state < QUIC_HS_ST_COMPLETE) {
2339 ssl_err = SSL_do_handshake(ctx->ssl);
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002340
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01002341 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
2342 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
2343 goto leave;
2344 }
2345
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002346 /* Finalize the connection as soon as possible if the peer transport parameters
2347 * have been received. This may be useful to send packets even if this
2348 * handshake fails.
2349 */
2350 if ((qc->flags & QUIC_FL_CONN_TX_TP_RECEIVED) && !qc_conn_finalize(qc, 1)) {
2351 TRACE_ERROR("connection finalization failed", QUIC_EV_CONN_IO_CB, qc, &state);
2352 goto leave;
2353 }
2354
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002355 if (ssl_err != 1) {
2356 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2357 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2358 TRACE_PROTO("SSL handshake in progress",
2359 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2360 goto out;
2361 }
2362
2363 /* TODO: Should close the connection asap */
2364 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2365 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2366 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2367 HA_ATOMIC_INC(&qc->prx_counters->hdshk_fail);
2368 }
2369 TRACE_ERROR("SSL handshake error", QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2370 qc_ssl_dump_errors(ctx->conn);
2371 ERR_clear_error();
2372 goto leave;
2373 }
2374
2375 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_IO_CB, qc, &state);
2376
2377 /* Check the alpn could be negotiated */
2378 if (!qc->app_ops) {
2379 TRACE_ERROR("No negotiated ALPN", QUIC_EV_CONN_IO_CB, qc, &state);
2380 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
2381 goto leave;
2382 }
2383
2384 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2385 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_IO_CB, qc, &state);
2386 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2387 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2388 }
2389 /* I/O callback switch */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002390 qc->wait_event.tasklet->process = quic_conn_app_io_cb;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002391 if (qc_is_listener(ctx->qc)) {
2392 qc->state = QUIC_HS_ST_CONFIRMED;
2393 /* The connection is ready to be accepted. */
2394 quic_accept_push_qc(qc);
2395 }
2396 else {
2397 qc->state = QUIC_HS_ST_COMPLETE;
2398 }
2399
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02002400 /* Prepare the next key update */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002401 if (!quic_tls_key_update(qc)) {
2402 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_IO_CB, qc);
2403 goto leave;
2404 }
2405 } else {
2406 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
2407 if (ssl_err != 1) {
2408 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2409 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2410 TRACE_PROTO("SSL post handshake in progress",
2411 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2412 goto out;
2413 }
2414
2415 TRACE_ERROR("SSL post handshake error",
2416 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2417 goto leave;
2418 }
2419
2420 TRACE_STATE("SSL post handshake succeeded", QUIC_EV_CONN_IO_CB, qc, &state);
2421 }
2422
2423 out:
2424 ret = 1;
2425 leave:
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002426 /* The CRYPTO data are consumed even in case of an error to release
2427 * the memory asap.
2428 */
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002429 if (!ncb_is_null(ncbuf)) {
2430#ifdef DEBUG_STRICT
2431 ncb_ret = ncb_advance(ncbuf, len);
2432 /* ncb_advance() must always succeed. This is guaranteed as
2433 * this is only done inside a data block. If false, this will
2434 * lead to handshake failure with quic_enc_level offset shifted
2435 * from buffer data.
2436 */
2437 BUG_ON(ncb_ret != NCB_RET_OK);
2438#else
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002439 ncb_advance(ncbuf, len);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002440#endif
2441 }
2442
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002443 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, qc);
2444 return ret;
2445}
2446
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002447/* Parse a STREAM frame <strm_frm> received in <pkt> packet for <qc>
2448 * connection. <fin> is true if FIN bit is set on frame type.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002449 *
2450 * Return 1 on success. On error, 0 is returned. In this case, the packet
2451 * containing the frame must not be acknowledged.
2452 */
2453static inline int qc_handle_strm_frm(struct quic_rx_packet *pkt,
2454 struct quic_stream *strm_frm,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002455 struct quic_conn *qc, char fin)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002456{
2457 int ret;
2458
2459 /* RFC9000 13.1. Packet Processing
2460 *
2461 * A packet MUST NOT be acknowledged until packet protection has been
2462 * successfully removed and all frames contained in the packet have
2463 * been processed. For STREAM frames, this means the data has been
2464 * enqueued in preparation to be received by the application protocol,
2465 * but it does not require that data be delivered and consumed.
2466 */
2467 TRACE_ENTER(QUIC_EV_CONN_PRSFRM, qc);
2468
2469 ret = qcc_recv(qc->qcc, strm_frm->id, strm_frm->len,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002470 strm_frm->offset.key, fin, (char *)strm_frm->data);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002471
2472 /* frame rejected - packet must not be acknowledeged */
2473 TRACE_LEAVE(QUIC_EV_CONN_PRSFRM, qc);
2474 return !ret;
2475}
2476
2477/* Duplicate all frames from <pkt_frm_list> list into <out_frm_list> list
2478 * for <qc> QUIC connection.
2479 * This is a best effort function which never fails even if no memory could be
2480 * allocated to duplicate these frames.
2481 */
2482static void qc_dup_pkt_frms(struct quic_conn *qc,
2483 struct list *pkt_frm_list, struct list *out_frm_list)
2484{
2485 struct quic_frame *frm, *frmbak;
2486 struct list tmp = LIST_HEAD_INIT(tmp);
2487
2488 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2489
2490 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
2491 struct quic_frame *dup_frm, *origin;
2492
2493 switch (frm->type) {
2494 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2495 {
2496 struct quic_stream *strm_frm = &frm->stream;
2497 struct eb64_node *node = NULL;
2498 struct qc_stream_desc *stream_desc;
2499
2500 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
2501 if (!node) {
2502 TRACE_DEVEL("ignored frame for a released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
2503 continue;
2504 }
2505
2506 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
2507 /* Do not resend this frame if in the "already acked range" */
2508 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
2509 TRACE_DEVEL("ignored frame in already acked range",
2510 QUIC_EV_CONN_PRSAFRM, qc, frm);
2511 continue;
2512 }
2513 else if (strm_frm->offset.key < stream_desc->ack_offset) {
2514 strm_frm->offset.key = stream_desc->ack_offset;
2515 TRACE_DEVEL("updated partially acked frame",
2516 QUIC_EV_CONN_PRSAFRM, qc, frm);
2517 }
2518 break;
2519 }
2520
2521 default:
2522 break;
2523 }
2524
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002525 /* If <frm> is already a copy of another frame, we must take
2526 * its original frame as source for the copy.
2527 */
2528 origin = frm->origin ? frm->origin : frm;
2529 dup_frm = qc_frm_dup(origin);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002530 if (!dup_frm) {
2531 TRACE_ERROR("could not duplicate frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2532 break;
2533 }
2534
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002535 TRACE_DEVEL("built probing frame", QUIC_EV_CONN_PRSAFRM, qc, origin);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002536 if (origin->pkt) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002537 TRACE_DEVEL("duplicated from packet", QUIC_EV_CONN_PRSAFRM,
2538 qc, NULL, &origin->pkt->pn_node.key);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002539 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002540 else {
2541 /* <origin> is a frame which was sent from a packet detected as lost. */
2542 TRACE_DEVEL("duplicated from lost packet", QUIC_EV_CONN_PRSAFRM, qc);
2543 }
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002544
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002545 LIST_APPEND(&tmp, &dup_frm->list);
2546 }
2547
2548 LIST_SPLICE(out_frm_list, &tmp);
2549
2550 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2551}
2552
2553/* Prepare a fast retransmission from <qel> encryption level */
2554static void qc_prep_fast_retrans(struct quic_conn *qc,
2555 struct quic_enc_level *qel,
2556 struct list *frms1, struct list *frms2)
2557{
2558 struct eb_root *pkts = &qel->pktns->tx.pkts;
2559 struct list *frms = frms1;
2560 struct eb64_node *node;
2561 struct quic_tx_packet *pkt;
2562
2563 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2564
2565 BUG_ON(frms1 == frms2);
2566
2567 pkt = NULL;
2568 node = eb64_first(pkts);
2569 start:
2570 while (node) {
2571 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
2572 node = eb64_next(node);
2573 /* Skip the empty and coalesced packets */
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002574 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
2575 "--> pn=%llu (%d %d)", (ull)pkt->pn_node.key,
2576 LIST_ISEMPTY(&pkt->frms), !!(pkt->flags & QUIC_FL_TX_PACKET_COALESCED));
Frédéric Lécaille055e8262023-01-31 10:10:06 +01002577 if (!LIST_ISEMPTY(&pkt->frms))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002578 break;
2579 }
2580
2581 if (!pkt)
2582 goto leave;
2583
2584 /* When building a packet from another one, the field which may increase the
2585 * packet size is the packet number. And the maximum increase is 4 bytes.
2586 */
2587 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2588 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
2589 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2590 goto leave;
2591 }
2592
2593 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_SPPKTS, qc, pkt);
2594 qc_dup_pkt_frms(qc, &pkt->frms, frms);
2595 if (frms == frms1 && frms2) {
2596 frms = frms2;
2597 goto start;
2598 }
2599 leave:
2600 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
2601}
2602
2603/* Prepare a fast retransmission during a handshake after a client
2604 * has resent Initial packets. According to the RFC a server may retransmit
2605 * Initial packets send them coalescing with others (Handshake here).
2606 * (Listener only function).
2607 */
2608static void qc_prep_hdshk_fast_retrans(struct quic_conn *qc,
2609 struct list *ifrms, struct list *hfrms)
2610{
2611 struct list itmp = LIST_HEAD_INIT(itmp);
2612 struct list htmp = LIST_HEAD_INIT(htmp);
2613
2614 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2615 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2616 struct quic_enc_level *qel = iqel;
2617 struct eb_root *pkts;
2618 struct eb64_node *node;
2619 struct quic_tx_packet *pkt;
2620 struct list *tmp = &itmp;
2621
2622 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2623 start:
2624 pkt = NULL;
2625 pkts = &qel->pktns->tx.pkts;
2626 node = eb64_first(pkts);
2627 /* Skip the empty packet (they have already been retransmitted) */
2628 while (node) {
2629 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002630 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
2631 "--> pn=%llu (%d %d)", (ull)pkt->pn_node.key,
2632 LIST_ISEMPTY(&pkt->frms), !!(pkt->flags & QUIC_FL_TX_PACKET_COALESCED));
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002633 if (!LIST_ISEMPTY(&pkt->frms) && !(pkt->flags & QUIC_FL_TX_PACKET_COALESCED))
2634 break;
2635 node = eb64_next(node);
2636 }
2637
2638 if (!pkt)
2639 goto end;
2640
2641 /* When building a packet from another one, the field which may increase the
2642 * packet size is the packet number. And the maximum increase is 4 bytes.
2643 */
2644 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2645 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
2646 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_PRSAFRM, qc);
2647 goto end;
2648 }
2649
2650 qel->pktns->tx.pto_probe += 1;
2651
2652 /* No risk to loop here, #packet per datagram is bounded */
2653 requeue:
2654 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
2655 qc_dup_pkt_frms(qc, &pkt->frms, tmp);
2656 if (qel == iqel) {
2657 if (pkt->next && pkt->next->type == QUIC_PACKET_TYPE_HANDSHAKE) {
2658 pkt = pkt->next;
2659 tmp = &htmp;
2660 hqel->pktns->tx.pto_probe += 1;
2661 TRACE_DEVEL("looping for next packet", QUIC_EV_CONN_PRSAFRM, qc);
2662 goto requeue;
2663 }
2664 }
2665
2666 end:
2667 LIST_SPLICE(ifrms, &itmp);
2668 LIST_SPLICE(hfrms, &htmp);
2669
2670 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2671}
2672
2673static void qc_cc_err_count_inc(struct quic_conn *qc, struct quic_frame *frm)
2674{
2675 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
2676
2677 if (frm->type == QUIC_FT_CONNECTION_CLOSE)
2678 quic_stats_transp_err_count_inc(qc->prx_counters, frm->connection_close.error_code);
2679 else if (frm->type == QUIC_FT_CONNECTION_CLOSE_APP) {
2680 if (qc->mux_state != QC_MUX_READY || !qc->qcc->app_ops->inc_err_cnt)
2681 goto out;
2682
2683 qc->qcc->app_ops->inc_err_cnt(qc->qcc->ctx, frm->connection_close_app.error_code);
2684 }
2685
2686 out:
2687 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
2688}
2689
2690/* Enqueue a STOP_SENDING frame to send into 1RTT packet number space
2691 * frame list to send.
2692 * Return 1 if succeeded, 0 if not.
2693 */
2694static int qc_stop_sending_frm_enqueue(struct quic_conn *qc, uint64_t id)
2695{
2696 int ret = 0;
2697 struct quic_frame *frm;
2698 struct quic_enc_level *qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
2699 uint64_t app_error_code;
2700
2701 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2702
2703 /* TODO: the mux may be released, we cannot have more
2704 * information about the application error code to send
2705 * at this time.
2706 */
2707 app_error_code = H3_REQUEST_REJECTED;
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002708 frm = qc_frm_alloc(QUIC_FT_STOP_SENDING);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002709 if (!frm) {
2710 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2711 goto out;
2712 }
2713
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002714 frm->stop_sending.id = id;
2715 frm->stop_sending.app_error_code = app_error_code;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002716 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
2717 ret = 1;
2718 out:
2719 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2720 return ret;
2721}
2722
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002723/* Release the underlying memory use by <ncbuf> non-contiguous buffer */
2724static void quic_free_ncbuf(struct ncbuf *ncbuf)
2725{
2726 struct buffer buf;
2727
2728 if (ncb_is_null(ncbuf))
2729 return;
2730
2731 buf = b_make(ncbuf->area, ncbuf->size, 0, 0);
2732 b_free(&buf);
2733 offer_buffers(NULL, 1);
2734
2735 *ncbuf = NCBUF_NULL;
2736}
2737
2738/* Allocate the underlying required memory for <ncbuf> non-contiguous buffer */
2739static struct ncbuf *quic_get_ncbuf(struct ncbuf *ncbuf)
2740{
2741 struct buffer buf = BUF_NULL;
2742
2743 if (!ncb_is_null(ncbuf))
2744 return ncbuf;
2745
2746 b_alloc(&buf);
2747 BUG_ON(b_is_null(&buf));
2748
2749 *ncbuf = ncb_make(buf.area, buf.size, 0);
2750 ncb_init(ncbuf, 0);
2751
2752 return ncbuf;
2753}
2754
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002755/* Parse <frm> CRYPTO frame coming with <pkt> packet at <qel> <qc> connectionn.
2756 * Returns 1 if succeeded, 0 if not. Also set <*fast_retrans> to 1 if the
2757 * speed up handshake completion may be run after having received duplicated
2758 * CRYPTO data.
2759 */
2760static int qc_handle_crypto_frm(struct quic_conn *qc,
2761 struct quic_crypto *frm, struct quic_rx_packet *pkt,
2762 struct quic_enc_level *qel, int *fast_retrans)
2763{
2764 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002765 enum ncb_ret ncb_ret;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002766 /* XXX TO DO: <cfdebug> is used only for the traces. */
2767 struct quic_rx_crypto_frm cfdebug = {
2768 .offset_node.key = frm->offset,
2769 .len = frm->len,
2770 };
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002771 struct quic_cstream *cstream = qel->cstream;
2772 struct ncbuf *ncbuf = &qel->cstream->rx.ncbuf;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002773
2774 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2775 if (unlikely(qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD)) {
2776 TRACE_PROTO("CRYPTO data discarded",
2777 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2778 goto done;
2779 }
2780
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002781 if (unlikely(frm->offset < cstream->rx.offset)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002782 size_t diff;
2783
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002784 if (frm->offset + frm->len <= cstream->rx.offset) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002785 /* Nothing to do */
2786 TRACE_PROTO("Already received CRYPTO data",
2787 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2788 if (qc_is_listener(qc) && qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] &&
2789 !(qc->flags & QUIC_FL_CONN_HANDSHAKE_SPEED_UP))
2790 *fast_retrans = 1;
2791 goto done;
2792 }
2793
2794 TRACE_PROTO("Partially already received CRYPTO data",
2795 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2796
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002797 diff = cstream->rx.offset - frm->offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002798 frm->len -= diff;
2799 frm->data += diff;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002800 frm->offset = cstream->rx.offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002801 }
2802
Amaury Denoyelleff95f2d2022-11-18 14:50:06 +01002803 if (frm->offset == cstream->rx.offset && ncb_is_empty(ncbuf)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002804 if (!qc_provide_cdata(qel, qc->xprt_ctx, frm->data, frm->len,
2805 pkt, &cfdebug)) {
2806 // trace already emitted by function above
2807 goto leave;
2808 }
2809
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002810 cstream->rx.offset += frm->len;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002811 TRACE_DEVEL("increment crypto level offset", QUIC_EV_CONN_PHPKTS, qc, qel);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002812 goto done;
2813 }
2814
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002815 if (!quic_get_ncbuf(ncbuf) ||
2816 ncb_is_null(ncbuf)) {
2817 TRACE_ERROR("CRYPTO ncbuf allocation failed", QUIC_EV_CONN_PRSHPKT, qc);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002818 goto leave;
2819 }
2820
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002821 /* frm->offset > cstream-trx.offset */
2822 ncb_ret = ncb_add(ncbuf, frm->offset - cstream->rx.offset,
2823 (const char *)frm->data, frm->len, NCB_ADD_COMPARE);
2824 if (ncb_ret != NCB_RET_OK) {
2825 if (ncb_ret == NCB_RET_DATA_REJ) {
2826 TRACE_ERROR("overlapping data rejected", QUIC_EV_CONN_PRSHPKT, qc);
2827 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
2828 }
2829 else if (ncb_ret == NCB_RET_GAP_SIZE) {
2830 TRACE_ERROR("cannot bufferize frame due to gap size limit",
2831 QUIC_EV_CONN_PRSHPKT, qc);
2832 }
2833 goto leave;
2834 }
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002835
2836 done:
2837 ret = 1;
2838 leave:
2839 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2840 return ret;
2841}
2842
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002843/* Parse all the frames of <pkt> QUIC packet for QUIC connection <qc> and <qel>
2844 * as encryption level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002845 * Returns 1 if succeeded, 0 if failed.
2846 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002847static int qc_parse_pkt_frms(struct quic_conn *qc, struct quic_rx_packet *pkt,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002848 struct quic_enc_level *qel)
2849{
2850 struct quic_frame frm;
2851 const unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002852 int fast_retrans = 0, ret = 0;
2853
2854 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2855 /* Skip the AAD */
2856 pos = pkt->data + pkt->aad_len;
2857 end = pkt->data + pkt->len;
2858
2859 while (pos < end) {
2860 if (!qc_parse_frm(&frm, pkt, &pos, end, qc)) {
2861 // trace already emitted by function above
2862 goto leave;
2863 }
2864
2865 TRACE_PROTO("RX frame", QUIC_EV_CONN_PSTRM, qc, &frm);
2866 switch (frm.type) {
2867 case QUIC_FT_PADDING:
2868 break;
2869 case QUIC_FT_PING:
2870 break;
2871 case QUIC_FT_ACK:
2872 {
2873 unsigned int rtt_sample;
2874
2875 rtt_sample = 0;
2876 if (!qc_parse_ack_frm(qc, &frm, qel, &rtt_sample, &pos, end)) {
2877 // trace already emitted by function above
2878 goto leave;
2879 }
2880
2881 if (rtt_sample) {
2882 unsigned int ack_delay;
2883
2884 ack_delay = !quic_application_pktns(qel->pktns, qc) ? 0 :
2885 qc->state >= QUIC_HS_ST_CONFIRMED ?
2886 MS_TO_TICKS(QUIC_MIN(quic_ack_delay_ms(&frm.ack, qc), qc->max_ack_delay)) :
2887 MS_TO_TICKS(quic_ack_delay_ms(&frm.ack, qc));
2888 quic_loss_srtt_update(&qc->path->loss, rtt_sample, ack_delay, qc);
2889 }
2890 break;
2891 }
2892 case QUIC_FT_RESET_STREAM:
Amaury Denoyelle5854fc02022-12-09 16:25:48 +01002893 if (qc->mux_state == QC_MUX_READY) {
2894 struct quic_reset_stream *rs = &frm.reset_stream;
2895 qcc_recv_reset_stream(qc->qcc, rs->id, rs->app_error_code, rs->final_size);
2896 }
2897 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002898 case QUIC_FT_STOP_SENDING:
2899 {
2900 struct quic_stop_sending *stop_sending = &frm.stop_sending;
2901 if (qc->mux_state == QC_MUX_READY) {
2902 if (qcc_recv_stop_sending(qc->qcc, stop_sending->id,
2903 stop_sending->app_error_code)) {
2904 TRACE_ERROR("qcc_recv_stop_sending() failed", QUIC_EV_CONN_PRSHPKT, qc);
2905 goto leave;
2906 }
2907 }
2908 break;
2909 }
2910 case QUIC_FT_CRYPTO:
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002911 if (!qc_handle_crypto_frm(qc, &frm.crypto, pkt, qel, &fast_retrans))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002912 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002913 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002914 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2915 {
2916 struct quic_stream *stream = &frm.stream;
2917 unsigned nb_streams = qc->rx.strms[qcs_id_type(stream->id)].nb_streams;
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002918 const char fin = frm.type & QUIC_STREAM_FRAME_TYPE_FIN_BIT;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002919
2920 /* The upper layer may not be allocated. */
2921 if (qc->mux_state != QC_MUX_READY) {
2922 if ((stream->id >> QCS_ID_TYPE_SHIFT) < nb_streams) {
2923 TRACE_DATA("Already closed stream", QUIC_EV_CONN_PRSHPKT, qc);
2924 break;
2925 }
2926 else {
2927 TRACE_DEVEL("No mux for new stream", QUIC_EV_CONN_PRSHPKT, qc);
Frédéric Lécailled18025e2023-01-20 15:33:50 +01002928 if (qc->app_ops == &h3_ops && quic_stream_is_uni(stream->id)) {
2929 /* Do not send STOP_SENDING frames for h3 unidirectional streams.
2930 * TODO: this test should be removed when the connection closure
2931 * will be more clean.
2932 * At quic_conn level there is no mean to know that an application
2933 * want to forbid stream closure requests to receivers. This is the
2934 * case for the Control and QPACK h3 unidirectional streams.
2935 */
2936 goto leave;
2937 }
2938
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002939 if (!qc_stop_sending_frm_enqueue(qc, stream->id))
2940 TRACE_ERROR("could not enqueue STOP_SENDING frame", QUIC_EV_CONN_PRSHPKT, qc);
2941 /* This packet will not be acknowledged */
2942 goto leave;
2943 }
2944 }
2945
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002946 if (!qc_handle_strm_frm(pkt, stream, qc, fin)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002947 TRACE_ERROR("qc_handle_strm_frm() failed", QUIC_EV_CONN_PRSHPKT, qc);
2948 goto leave;
2949 }
2950
2951 break;
2952 }
2953 case QUIC_FT_MAX_DATA:
2954 if (qc->mux_state == QC_MUX_READY) {
2955 struct quic_max_data *data = &frm.max_data;
2956 qcc_recv_max_data(qc->qcc, data->max_data);
2957 }
2958 break;
2959 case QUIC_FT_MAX_STREAM_DATA:
2960 if (qc->mux_state == QC_MUX_READY) {
2961 struct quic_max_stream_data *data = &frm.max_stream_data;
2962 if (qcc_recv_max_stream_data(qc->qcc, data->id,
2963 data->max_stream_data)) {
2964 TRACE_ERROR("qcc_recv_max_stream_data() failed", QUIC_EV_CONN_PRSHPKT, qc);
2965 goto leave;
2966 }
2967 }
2968 break;
2969 case QUIC_FT_MAX_STREAMS_BIDI:
2970 case QUIC_FT_MAX_STREAMS_UNI:
2971 break;
2972 case QUIC_FT_DATA_BLOCKED:
2973 HA_ATOMIC_INC(&qc->prx_counters->data_blocked);
2974 break;
2975 case QUIC_FT_STREAM_DATA_BLOCKED:
2976 HA_ATOMIC_INC(&qc->prx_counters->stream_data_blocked);
2977 break;
2978 case QUIC_FT_STREAMS_BLOCKED_BIDI:
2979 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_bidi);
2980 break;
2981 case QUIC_FT_STREAMS_BLOCKED_UNI:
2982 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_uni);
2983 break;
2984 case QUIC_FT_NEW_CONNECTION_ID:
2985 case QUIC_FT_RETIRE_CONNECTION_ID:
2986 /* XXX TO DO XXX */
2987 break;
2988 case QUIC_FT_CONNECTION_CLOSE:
2989 case QUIC_FT_CONNECTION_CLOSE_APP:
2990 /* Increment the error counters */
2991 qc_cc_err_count_inc(qc, &frm);
2992 if (!(qc->flags & QUIC_FL_CONN_DRAINING)) {
2993 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2994 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2995 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2996 }
2997 TRACE_STATE("Entering draining state", QUIC_EV_CONN_PRSHPKT, qc);
2998 /* RFC 9000 10.2. Immediate Close:
2999 * The closing and draining connection states exist to ensure
3000 * that connections close cleanly and that delayed or reordered
3001 * packets are properly discarded. These states SHOULD persist
3002 * for at least three times the current PTO interval...
3003 *
3004 * Rearm the idle timeout only one time when entering draining
3005 * state.
3006 */
3007 qc_idle_timer_do_rearm(qc);
3008 qc->flags |= QUIC_FL_CONN_DRAINING|QUIC_FL_CONN_IMMEDIATE_CLOSE;
3009 qc_notify_close(qc);
3010 }
3011 break;
3012 case QUIC_FT_HANDSHAKE_DONE:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003013 if (qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003014 TRACE_ERROR("non accepted QUIC_FT_HANDSHAKE_DONE frame",
3015 QUIC_EV_CONN_PRSHPKT, qc);
3016 goto leave;
3017 }
3018
3019 qc->state = QUIC_HS_ST_CONFIRMED;
3020 break;
3021 default:
3022 TRACE_ERROR("unknosw frame type", QUIC_EV_CONN_PRSHPKT, qc);
3023 goto leave;
3024 }
3025 }
3026
3027 /* Flag this packet number space as having received a packet. */
3028 qel->pktns->flags |= QUIC_FL_PKTNS_PKT_RECEIVED;
3029
3030 if (fast_retrans) {
3031 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
3032 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
3033
3034 TRACE_PROTO("speeding up handshake completion", QUIC_EV_CONN_PRSHPKT, qc);
3035 qc_prep_hdshk_fast_retrans(qc, &iqel->pktns->tx.frms, &hqel->pktns->tx.frms);
3036 qc->flags |= QUIC_FL_CONN_HANDSHAKE_SPEED_UP;
3037 }
3038
3039 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
3040 * has successfully parse a Handshake packet. The Initial encryption must also
3041 * be discarded.
3042 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003043 if (pkt->type == QUIC_PACKET_TYPE_HANDSHAKE && qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003044 if (qc->state >= QUIC_HS_ST_SERVER_INITIAL) {
3045 if (!(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx.flags &
3046 QUIC_FL_TLS_SECRETS_DCD)) {
3047 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3048 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PRSHPKT, qc);
3049 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003050 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003051 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3052 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3053 }
3054 if (qc->state < QUIC_HS_ST_SERVER_HANDSHAKE)
3055 qc->state = QUIC_HS_ST_SERVER_HANDSHAKE;
3056 }
3057 }
3058
3059 ret = 1;
3060 leave:
3061 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
3062 return ret;
3063}
3064
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003065
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003066/* Allocate Tx buffer from <qc> quic-conn if needed.
3067 *
3068 * Returns allocated buffer or NULL on error.
3069 */
3070static struct buffer *qc_txb_alloc(struct quic_conn *qc)
3071{
3072 struct buffer *buf = &qc->tx.buf;
3073 if (!b_alloc(buf))
3074 return NULL;
3075
3076 return buf;
3077}
3078
3079/* Free Tx buffer from <qc> if it is empty. */
3080static void qc_txb_release(struct quic_conn *qc)
3081{
3082 struct buffer *buf = &qc->tx.buf;
3083
3084 /* For the moment sending function is responsible to purge the buffer
3085 * entirely. It may change in the future but this requires to be able
3086 * to reuse old data.
3087 */
3088 BUG_ON_HOT(buf && b_data(buf));
3089
3090 if (!b_data(buf)) {
3091 b_free(buf);
3092 offer_buffers(NULL, 1);
3093 }
3094}
3095
3096/* Commit a datagram payload written into <buf> of length <length>. <first_pkt>
3097 * must contains the address of the first packet stored in the payload.
3098 *
3099 * Caller is responsible that there is enough space in the buffer.
3100 */
3101static void qc_txb_store(struct buffer *buf, uint16_t length,
3102 struct quic_tx_packet *first_pkt)
3103{
3104 const size_t hdlen = sizeof(uint16_t) + sizeof(void *);
3105 BUG_ON_HOT(b_contig_space(buf) < hdlen); /* this must not happen */
3106
3107 write_u16(b_tail(buf), length);
3108 write_ptr(b_tail(buf) + sizeof(length), first_pkt);
3109 b_add(buf, hdlen + length);
3110}
3111
3112/* Returns 1 if a packet may be built for <qc> from <qel> encryption level
3113 * with <frms> as ack-eliciting frame list to send, 0 if not.
3114 * <cc> must equal to 1 if an immediate close was asked, 0 if not.
3115 * <probe> must equalt to 1 if a probing packet is required, 0 if not.
3116 * <force_ack> may be set to 1 if you want to force an ack.
3117 */
3118static int qc_may_build_pkt(struct quic_conn *qc, struct list *frms,
3119 struct quic_enc_level *qel, int cc, int probe, int force_ack)
3120{
3121 unsigned int must_ack = force_ack ||
3122 (LIST_ISEMPTY(frms) && (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED));
3123
3124 /* Do not build any more packet if the TX secrets are not available or
3125 * if there is nothing to send, i.e. if no CONNECTION_CLOSE or ACK are required
3126 * and if there is no more packets to send upon PTO expiration
3127 * and if there is no more ack-eliciting frames to send or in flight
3128 * congestion control limit is reached for prepared data
3129 */
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02003130 if (!quic_tls_has_tx_sec(qel) ||
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003131 (!cc && !probe && !must_ack &&
3132 (LIST_ISEMPTY(frms) || qc->path->prep_in_flight >= qc->path->cwnd))) {
3133 return 0;
3134 }
3135
3136 return 1;
3137}
3138
3139/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3140 * <frms>. Each packet is stored in a distinct datagram written to <buf>.
3141 *
3142 * Each datagram is prepended by a two fields header : the datagram length and
3143 * the address of the packet contained in the datagram.
3144 *
3145 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3146 * -1 if something wrong happened.
3147 */
3148static int qc_prep_app_pkts(struct quic_conn *qc, struct buffer *buf,
3149 struct list *frms)
3150{
3151 int ret = -1;
3152 struct quic_enc_level *qel;
3153 unsigned char *end, *pos;
3154 struct quic_tx_packet *pkt;
3155 size_t total;
3156 /* Each datagram is prepended with its length followed by the address
3157 * of the first packet in the datagram.
3158 */
3159 const size_t dg_headlen = sizeof(uint16_t) + sizeof(pkt);
3160
3161 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3162
3163 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3164 total = 0;
3165 pos = (unsigned char *)b_tail(buf);
3166 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen) {
3167 int err, probe, cc;
3168
3169 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3170 probe = 0;
3171 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3172 /* We do not probe if an immediate close was asked */
3173 if (!cc)
3174 probe = qel->pktns->tx.pto_probe;
3175
3176 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, 0))
3177 break;
3178
3179 /* Leave room for the datagram header */
3180 pos += dg_headlen;
3181 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3182 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3183 }
3184 else {
3185 end = pos + qc->path->mtu;
3186 }
3187
3188 pkt = qc_build_pkt(&pos, end, qel, &qel->tls_ctx, frms, qc, NULL, 0,
3189 QUIC_PACKET_TYPE_SHORT, 0, 0, probe, cc, &err);
3190 switch (err) {
3191 case -2:
3192 // trace already emitted by function above
3193 goto leave;
3194 case -1:
3195 /* As we provide qc_build_pkt() with an enough big buffer to fulfill an
3196 * MTU, we are here because of the congestion control window. There is
3197 * no need to try to reuse this buffer.
3198 */
3199 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3200 goto out;
3201 default:
3202 break;
3203 }
3204
3205 /* This is to please to GCC. We cannot have (err >= 0 && !pkt) */
3206 BUG_ON(!pkt);
3207
3208 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3209 pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3210
3211 total += pkt->len;
3212
3213 /* Write datagram header. */
3214 qc_txb_store(buf, pkt->len, pkt);
3215 }
3216
3217 out:
3218 ret = total;
3219 leave:
3220 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3221 return ret;
3222}
3223
3224/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3225 * <frms>. Several packets can be regrouped in a single datagram. The result is
3226 * written into <buf>.
3227 *
3228 * Each datagram is prepended by a two fields header : the datagram length and
3229 * the address of first packet in the datagram.
3230 *
3231 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3232 * -1 if something wrong happened.
3233 */
3234static int qc_prep_pkts(struct quic_conn *qc, struct buffer *buf,
3235 enum quic_tls_enc_level tel, struct list *tel_frms,
3236 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
3237{
3238 struct quic_enc_level *qel;
3239 unsigned char *end, *pos;
3240 struct quic_tx_packet *first_pkt, *cur_pkt, *prv_pkt;
3241 /* length of datagrams */
3242 uint16_t dglen;
3243 size_t total;
3244 int ret = -1, padding;
3245 /* Each datagram is prepended with its length followed by the address
3246 * of the first packet in the datagram.
3247 */
3248 const size_t dg_headlen = sizeof(uint16_t) + sizeof(first_pkt);
3249 struct list *frms;
3250
3251 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3252
3253 /* Currently qc_prep_pkts() does not handle buffer wrapping so the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003254 * caller must ensure that buf is reset.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003255 */
3256 BUG_ON_HOT(buf->head || buf->data);
3257
3258 total = 0;
3259 qel = &qc->els[tel];
3260 frms = tel_frms;
3261 dglen = 0;
3262 padding = 0;
3263 pos = (unsigned char *)b_head(buf);
3264 first_pkt = prv_pkt = NULL;
3265 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen || prv_pkt) {
3266 int err, probe, cc;
3267 enum quic_pkt_type pkt_type;
3268 struct quic_tls_ctx *tls_ctx;
3269 const struct quic_version *ver;
3270 int force_ack = (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3271 (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
3272 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
3273
3274 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3275 probe = 0;
3276 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3277 /* We do not probe if an immediate close was asked */
3278 if (!cc)
3279 probe = qel->pktns->tx.pto_probe;
3280
3281 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, force_ack)) {
3282 if (prv_pkt)
3283 qc_txb_store(buf, dglen, first_pkt);
3284 /* Let's select the next encryption level */
3285 if (tel != next_tel && next_tel != QUIC_TLS_ENC_LEVEL_NONE) {
3286 tel = next_tel;
3287 frms = next_tel_frms;
3288 qel = &qc->els[tel];
3289 /* Build a new datagram */
3290 prv_pkt = NULL;
3291 TRACE_DEVEL("next encryption level selected", QUIC_EV_CONN_PHPKTS, qc);
3292 continue;
3293 }
3294 break;
3295 }
3296
3297 pkt_type = quic_tls_level_pkt_type(tel);
3298 if (!prv_pkt) {
3299 /* Leave room for the datagram header */
3300 pos += dg_headlen;
3301 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3302 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3303 }
3304 else {
3305 end = pos + qc->path->mtu;
3306 }
3307 }
3308
3309 if (qc->negotiated_version) {
3310 ver = qc->negotiated_version;
3311 if (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL])
3312 tls_ctx = &qc->negotiated_ictx;
3313 else
3314 tls_ctx = &qel->tls_ctx;
3315 }
3316 else {
3317 ver = qc->original_version;
3318 tls_ctx = &qel->tls_ctx;
3319 }
3320
3321 cur_pkt = qc_build_pkt(&pos, end, qel, tls_ctx, frms,
3322 qc, ver, dglen, pkt_type,
3323 force_ack, padding, probe, cc, &err);
3324 switch (err) {
3325 case -2:
3326 // trace already emitted by function above
3327 goto leave;
3328 case -1:
3329 /* If there was already a correct packet present, set the
3330 * current datagram as prepared into <cbuf>.
3331 */
3332 if (prv_pkt)
3333 qc_txb_store(buf, dglen, first_pkt);
3334 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3335 goto out;
3336 default:
3337 break;
3338 }
3339
3340 /* This is to please to GCC. We cannot have (err >= 0 && !cur_pkt) */
3341 BUG_ON(!cur_pkt);
3342
3343 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3344 cur_pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3345
3346 total += cur_pkt->len;
3347 /* keep trace of the first packet in the datagram */
3348 if (!first_pkt)
3349 first_pkt = cur_pkt;
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01003350 /* Attach the current one to the previous one and vice versa */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003351 if (prv_pkt) {
3352 prv_pkt->next = cur_pkt;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01003353 cur_pkt->prev = prv_pkt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003354 cur_pkt->flags |= QUIC_FL_TX_PACKET_COALESCED;
3355 }
3356 /* Let's say we have to build a new dgram */
3357 prv_pkt = NULL;
3358 dglen += cur_pkt->len;
3359 /* Client: discard the Initial encryption keys as soon as
3360 * a handshake packet could be built.
3361 */
3362 if (qc->state == QUIC_HS_ST_CLIENT_INITIAL &&
3363 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
3364 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3365 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PHPKTS, qc);
3366 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
3367 qc_set_timer(qc);
3368 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3369 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3370 qc->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
3371 }
3372 /* If the data for the current encryption level have all been sent,
3373 * select the next level.
3374 */
3375 if ((tel == QUIC_TLS_ENC_LEVEL_INITIAL || tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE) &&
3376 next_tel != QUIC_TLS_ENC_LEVEL_NONE && (LIST_ISEMPTY(frms) && !qel->pktns->tx.pto_probe)) {
3377 /* If QUIC_TLS_ENC_LEVEL_HANDSHAKE was already reached let's try QUIC_TLS_ENC_LEVEL_APP */
3378 if (tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE && next_tel == tel)
3379 next_tel = QUIC_TLS_ENC_LEVEL_APP;
3380 tel = next_tel;
3381 if (tel == QUIC_TLS_ENC_LEVEL_APP)
3382 frms = &qc->els[tel].pktns->tx.frms;
3383 else
3384 frms = next_tel_frms;
3385 qel = &qc->els[tel];
3386 if (!LIST_ISEMPTY(frms)) {
3387 /* If there is data for the next level, do not
3388 * consume a datagram.
3389 */
3390 prv_pkt = cur_pkt;
3391 }
3392 }
3393
3394 /* If we have to build a new datagram, set the current datagram as
3395 * prepared into <cbuf>.
3396 */
3397 if (!prv_pkt) {
3398 qc_txb_store(buf, dglen, first_pkt);
3399 first_pkt = NULL;
3400 dglen = 0;
3401 padding = 0;
3402 }
3403 else if (prv_pkt->type == QUIC_TLS_ENC_LEVEL_INITIAL &&
3404 (!qc_is_listener(qc) ||
3405 prv_pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
3406 padding = 1;
3407 }
3408 }
3409
3410 out:
3411 ret = total;
3412 leave:
3413 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3414 return ret;
3415}
3416
3417/* Send datagrams stored in <buf>.
3418 *
3419 * This function always returns 1 for success. Even if sendto() syscall failed,
3420 * buffer is drained and packets are considered as emitted. QUIC loss detection
3421 * mechanism is used as a back door way to retry sending.
3422 */
3423int qc_send_ppkts(struct buffer *buf, struct ssl_sock_ctx *ctx)
3424{
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003425 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003426 struct quic_conn *qc;
3427 char skip_sendto = 0;
3428
3429 qc = ctx->qc;
3430 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
3431 while (b_contig_data(buf, 0)) {
3432 unsigned char *pos;
3433 struct buffer tmpbuf = { };
3434 struct quic_tx_packet *first_pkt, *pkt, *next_pkt;
3435 uint16_t dglen;
3436 size_t headlen = sizeof dglen + sizeof first_pkt;
3437 unsigned int time_sent;
3438
3439 pos = (unsigned char *)b_head(buf);
3440 dglen = read_u16(pos);
3441 BUG_ON_HOT(!dglen); /* this should not happen */
3442
3443 pos += sizeof dglen;
3444 first_pkt = read_ptr(pos);
3445 pos += sizeof first_pkt;
3446 tmpbuf.area = (char *)pos;
3447 tmpbuf.size = tmpbuf.data = dglen;
3448
3449 TRACE_DATA("send dgram", QUIC_EV_CONN_SPPKTS, qc);
3450 /* If sendto is on error just skip the call to it for the rest
3451 * of the loop but continue to purge the buffer. Data will be
3452 * transmitted when QUIC packets are detected as lost on our
3453 * side.
3454 *
3455 * TODO use fd-monitoring to detect when send operation can be
3456 * retry. This should improve the bandwidth without relying on
3457 * retransmission timer. However, it requires a major rework on
3458 * quic-conn fd management.
3459 */
3460 if (!skip_sendto) {
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003461 int syscall_errno;
3462
3463 syscall_errno = 0;
3464 if (qc_snd_buf(qc, &tmpbuf, tmpbuf.data, 0, &syscall_errno)) {
3465 if (syscall_errno == ECONNREFUSED) {
3466 /* Let's kill this connection asap. */
3467 TRACE_PROTO("UDP port unreachable", QUIC_EV_CONN_SPPKTS, qc);
3468 qc_kill_conn(qc);
3469 goto leave;
3470 }
3471
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003472 skip_sendto = 1;
3473 TRACE_ERROR("sendto error, simulate sending for the rest of data", QUIC_EV_CONN_SPPKTS, qc);
3474 }
3475 }
3476
3477 b_del(buf, dglen + headlen);
3478 qc->tx.bytes += tmpbuf.data;
3479 time_sent = now_ms;
3480
3481 for (pkt = first_pkt; pkt; pkt = next_pkt) {
3482 pkt->time_sent = time_sent;
3483 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
3484 pkt->pktns->tx.time_of_last_eliciting = time_sent;
3485 qc->path->ifae_pkts++;
3486 if (qc->flags & QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ)
3487 qc_idle_timer_rearm(qc, 0);
3488 }
3489 if (!(qc->flags & QUIC_FL_CONN_CLOSING) &&
3490 (pkt->flags & QUIC_FL_TX_PACKET_CC)) {
3491 qc->flags |= QUIC_FL_CONN_CLOSING;
3492 qc_notify_close(qc);
3493
3494 /* RFC 9000 10.2. Immediate Close:
3495 * The closing and draining connection states exist to ensure
3496 * that connections close cleanly and that delayed or reordered
3497 * packets are properly discarded. These states SHOULD persist
3498 * for at least three times the current PTO interval...
3499 *
3500 * Rearm the idle timeout only one time when entering closing
3501 * state.
3502 */
3503 qc_idle_timer_do_rearm(qc);
3504 if (qc->timer_task) {
3505 task_destroy(qc->timer_task);
3506 qc->timer_task = NULL;
3507 }
3508 }
3509 qc->path->in_flight += pkt->in_flight_len;
3510 pkt->pktns->tx.in_flight += pkt->in_flight_len;
3511 if (pkt->in_flight_len)
3512 qc_set_timer(qc);
3513 TRACE_DATA("sent pkt", QUIC_EV_CONN_SPPKTS, qc, pkt);
3514 next_pkt = pkt->next;
3515 quic_tx_packet_refinc(pkt);
3516 eb64_insert(&pkt->pktns->tx.pkts, &pkt->pn_node);
3517 }
3518 }
3519
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003520 ret = 1;
3521leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003522 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
3523
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003524 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003525}
3526
3527/* Copy into <buf> buffer a stateless reset token depending on the
3528 * <salt> salt input. This is the cluster secret which will be derived
3529 * as HKDF input secret to generate this token.
3530 * Return 1 if succeeded, 0 if not.
3531 */
3532static int quic_stateless_reset_token_cpy(struct quic_conn *qc,
3533 unsigned char *buf, size_t len,
3534 const unsigned char *salt, size_t saltlen)
3535{
3536 /* Input secret */
3537 const unsigned char *key = (const unsigned char *)global.cluster_secret;
3538 size_t keylen = strlen(global.cluster_secret);
3539 /* Info */
3540 const unsigned char label[] = "stateless token";
3541 size_t labellen = sizeof label - 1;
3542 int ret;
3543
3544 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3545
3546 ret = quic_hkdf_extract_and_expand(EVP_sha256(), buf, len,
3547 key, keylen, salt, saltlen, label, labellen);
3548 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3549 return ret;
3550}
3551
3552/* Initialize the stateless reset token attached to <cid> connection ID.
3553 * Returns 1 if succeeded, 0 if not.
3554 */
3555static int quic_stateless_reset_token_init(struct quic_conn *qc,
3556 struct quic_connection_id *quic_cid)
3557{
3558 int ret;
3559
3560 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3561
3562 if (global.cluster_secret) {
3563 /* Output secret */
3564 unsigned char *token = quic_cid->stateless_reset_token;
3565 size_t tokenlen = sizeof quic_cid->stateless_reset_token;
3566 /* Salt */
3567 const unsigned char *cid = quic_cid->cid.data;
3568 size_t cidlen = quic_cid->cid.len;
3569
3570 ret = quic_stateless_reset_token_cpy(qc, token, tokenlen, cid, cidlen);
3571 }
3572 else {
3573 /* TODO: RAND_bytes() should be replaced */
3574 ret = RAND_bytes(quic_cid->stateless_reset_token,
3575 sizeof quic_cid->stateless_reset_token) == 1;
3576 }
3577
3578 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3579 return ret;
3580}
3581
3582/* Allocate a new CID with <seq_num> as sequence number and attach it to <root>
3583 * ebtree.
3584 *
3585 * The CID is randomly generated in part with the result altered to be
3586 * associated with the current thread ID. This means this function must only
3587 * be called by the quic_conn thread.
3588 *
3589 * Returns the new CID if succeeded, NULL if not.
3590 */
3591static struct quic_connection_id *new_quic_cid(struct eb_root *root,
3592 struct quic_conn *qc,
3593 int seq_num)
3594{
3595 struct quic_connection_id *cid;
3596
3597 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3598
3599 cid = pool_alloc(pool_head_quic_connection_id);
3600 if (!cid) {
3601 TRACE_ERROR("cid allocation failed", QUIC_EV_CONN_TXPKT, qc);
3602 goto err;
3603 }
3604
3605 cid->cid.len = QUIC_HAP_CID_LEN;
3606 /* TODO: RAND_bytes() should be replaced */
3607 if (RAND_bytes(cid->cid.data, cid->cid.len) != 1) {
3608 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT, qc);
3609 goto err;
3610 }
3611
3612 quic_pin_cid_to_tid(cid->cid.data, tid);
3613 if (quic_stateless_reset_token_init(qc, cid) != 1) {
3614 TRACE_ERROR("quic_stateless_reset_token_init() failed", QUIC_EV_CONN_TXPKT, qc);
3615 goto err;
3616 }
3617
3618 cid->qc = qc;
3619
3620 cid->seq_num.key = seq_num;
3621 cid->retire_prior_to = 0;
3622 /* insert the allocated CID in the quic_conn tree */
3623 eb64_insert(root, &cid->seq_num);
3624
3625 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3626 return cid;
3627
3628 err:
3629 pool_free(pool_head_quic_connection_id, cid);
3630 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3631 return NULL;
3632}
3633
3634/* Build all the frames which must be sent just after the handshake have succeeded.
3635 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
3636 * a HANDSHAKE_DONE frame.
3637 * Return 1 if succeeded, 0 if not.
3638 */
3639static int quic_build_post_handshake_frames(struct quic_conn *qc)
3640{
3641 int ret = 0, i, first, max;
3642 struct quic_enc_level *qel;
3643 struct quic_frame *frm, *frmbak;
3644 struct list frm_list = LIST_HEAD_INIT(frm_list);
3645 struct eb64_node *node;
3646
3647 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
3648
3649 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3650 /* Only servers must send a HANDSHAKE_DONE frame. */
3651 if (qc_is_listener(qc)) {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003652 frm = qc_frm_alloc(QUIC_FT_HANDSHAKE_DONE);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003653 if (!frm) {
3654 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3655 goto leave;
3656 }
3657
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003658 LIST_APPEND(&frm_list, &frm->list);
3659 }
3660
3661 /* Initialize <max> connection IDs minus one: there is
3662 * already one connection ID used for the current connection.
3663 */
3664 first = 1;
3665 max = qc->tx.params.active_connection_id_limit;
3666
3667 /* TODO: check limit */
3668 for (i = first; i < max; i++) {
3669 struct quic_connection_id *cid;
3670
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003671 frm = qc_frm_alloc(QUIC_FT_NEW_CONNECTION_ID);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003672 if (!frm) {
3673 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3674 goto err;
3675 }
3676
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003677 cid = new_quic_cid(&qc->cids, qc, i);
3678 if (!cid) {
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003679 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003680 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3681 goto err;
3682 }
3683
3684 /* insert the allocated CID in the receiver datagram handler tree */
3685 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3686
3687 quic_connection_id_to_frm_cpy(frm, cid);
3688 LIST_APPEND(&frm_list, &frm->list);
3689 }
3690
3691 LIST_SPLICE(&qel->pktns->tx.frms, &frm_list);
3692 qc->flags |= QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT;
3693
3694 ret = 1;
3695 leave:
3696 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
3697 return ret;
3698
3699 err:
3700 /* free the frames */
3701 list_for_each_entry_safe(frm, frmbak, &frm_list, list)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003702 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003703
3704 node = eb64_lookup_ge(&qc->cids, first);
3705 while (node) {
3706 struct quic_connection_id *cid;
3707
3708 cid = eb64_entry(node, struct quic_connection_id, seq_num);
3709 if (cid->seq_num.key >= max)
3710 break;
3711
3712 node = eb64_next(node);
3713 ebmb_delete(&cid->node);
3714 eb64_delete(&cid->seq_num);
3715 pool_free(pool_head_quic_connection_id, cid);
3716 }
3717 goto leave;
3718}
3719
3720/* Deallocate <l> list of ACK ranges. */
3721void quic_free_arngs(struct quic_conn *qc, struct quic_arngs *arngs)
3722{
3723 struct eb64_node *n;
3724 struct quic_arng_node *ar;
3725
3726 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
3727
3728 n = eb64_first(&arngs->root);
3729 while (n) {
3730 struct eb64_node *next;
3731
3732 ar = eb64_entry(n, struct quic_arng_node, first);
3733 next = eb64_next(n);
3734 eb64_delete(n);
3735 pool_free(pool_head_quic_arng, ar);
3736 n = next;
3737 }
3738
3739 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
3740}
3741
3742/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
3743 * descending order.
3744 */
3745static inline size_t sack_gap(struct quic_arng_node *p,
3746 struct quic_arng_node *q)
3747{
3748 return p->first.key - q->last - 2;
3749}
3750
3751
3752/* Remove the last elements of <ack_ranges> list of ack range updating its
3753 * encoded size until it goes below <limit>.
3754 * Returns 1 if succeeded, 0 if not (no more element to remove).
3755 */
3756static int quic_rm_last_ack_ranges(struct quic_conn *qc,
3757 struct quic_arngs *arngs, size_t limit)
3758{
3759 int ret = 0;
3760 struct eb64_node *last, *prev;
3761
3762 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3763
3764 last = eb64_last(&arngs->root);
3765 while (last && arngs->enc_sz > limit) {
3766 struct quic_arng_node *last_node, *prev_node;
3767
3768 prev = eb64_prev(last);
3769 if (!prev) {
3770 TRACE_DEVEL("<last> not found", QUIC_EV_CONN_TXPKT, qc);
3771 goto out;
3772 }
3773
3774 last_node = eb64_entry(last, struct quic_arng_node, first);
3775 prev_node = eb64_entry(prev, struct quic_arng_node, first);
3776 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
3777 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
3778 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
3779 --arngs->sz;
3780 eb64_delete(last);
3781 pool_free(pool_head_quic_arng, last);
3782 last = prev;
3783 }
3784
3785 ret = 1;
3786 out:
3787 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3788 return ret;
3789}
3790
3791/* Set the encoded size of <arngs> QUIC ack ranges. */
3792static void quic_arngs_set_enc_sz(struct quic_conn *qc, struct quic_arngs *arngs)
3793{
3794 struct eb64_node *node, *next;
3795 struct quic_arng_node *ar, *ar_next;
3796
3797 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3798
3799 node = eb64_last(&arngs->root);
3800 if (!node)
3801 goto leave;
3802
3803 ar = eb64_entry(node, struct quic_arng_node, first);
3804 arngs->enc_sz = quic_int_getsize(ar->last) +
3805 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
3806
3807 while ((next = eb64_prev(node))) {
3808 ar_next = eb64_entry(next, struct quic_arng_node, first);
3809 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
3810 quic_int_getsize(ar_next->last - ar_next->first.key);
3811 node = next;
3812 ar = eb64_entry(node, struct quic_arng_node, first);
3813 }
3814
3815 leave:
3816 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3817}
3818
3819/* Insert <ar> ack range into <argns> tree of ack ranges.
3820 * Returns the ack range node which has been inserted if succeeded, NULL if not.
3821 */
3822static inline
3823struct quic_arng_node *quic_insert_new_range(struct quic_conn *qc,
3824 struct quic_arngs *arngs,
3825 struct quic_arng *ar)
3826{
3827 struct quic_arng_node *new_ar;
3828
3829 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3830
3831 new_ar = pool_alloc(pool_head_quic_arng);
3832 if (!new_ar) {
3833 TRACE_ERROR("ack range allocation failed", QUIC_EV_CONN_RXPKT, qc);
3834 goto leave;
3835 }
3836
3837 new_ar->first.key = ar->first;
3838 new_ar->last = ar->last;
3839 eb64_insert(&arngs->root, &new_ar->first);
3840 arngs->sz++;
3841
3842 leave:
3843 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3844 return new_ar;
3845}
3846
3847/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
3848 * Note that this function computes the number of bytes required to encode
3849 * this tree of ACK ranges in descending order.
3850 *
3851 * Descending order
3852 * ------------->
3853 * range1 range2
3854 * ..........|--------|..............|--------|
3855 * ^ ^ ^ ^
3856 * | | | |
3857 * last1 first1 last2 first2
3858 * ..........+--------+--------------+--------+......
3859 * diff1 gap12 diff2
3860 *
3861 * To encode the previous list of ranges we must encode integers as follows in
3862 * descending order:
3863 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
3864 * with diff1 = last1 - first1
3865 * diff2 = last2 - first2
3866 * gap12 = first1 - last2 - 2 (>= 0)
3867 *
3868
3869returns 0 on error
3870
3871 */
3872int quic_update_ack_ranges_list(struct quic_conn *qc,
3873 struct quic_arngs *arngs,
3874 struct quic_arng *ar)
3875{
3876 int ret = 0;
3877 struct eb64_node *le;
3878 struct quic_arng_node *new_node;
3879 struct eb64_node *new;
3880
3881 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3882
3883 new = NULL;
3884 if (eb_is_empty(&arngs->root)) {
3885 new_node = quic_insert_new_range(qc, arngs, ar);
3886 if (new_node)
3887 ret = 1;
3888
3889 goto leave;
3890 }
3891
3892 le = eb64_lookup_le(&arngs->root, ar->first);
3893 if (!le) {
3894 new_node = quic_insert_new_range(qc, arngs, ar);
3895 if (!new_node)
3896 goto leave;
3897
3898 new = &new_node->first;
3899 }
3900 else {
3901 struct quic_arng_node *le_ar =
3902 eb64_entry(le, struct quic_arng_node, first);
3903
3904 /* Already existing range */
3905 if (le_ar->last >= ar->last) {
3906 ret = 1;
3907 }
3908 else if (le_ar->last + 1 >= ar->first) {
3909 le_ar->last = ar->last;
3910 new = le;
3911 new_node = le_ar;
3912 }
3913 else {
3914 new_node = quic_insert_new_range(qc, arngs, ar);
3915 if (!new_node)
3916 goto leave;
3917
3918 new = &new_node->first;
3919 }
3920 }
3921
3922 /* Verify that the new inserted node does not overlap the nodes
3923 * which follow it.
3924 */
3925 if (new) {
3926 struct eb64_node *next;
3927 struct quic_arng_node *next_node;
3928
3929 while ((next = eb64_next(new))) {
3930 next_node =
3931 eb64_entry(next, struct quic_arng_node, first);
3932 if (new_node->last + 1 < next_node->first.key)
3933 break;
3934
3935 if (next_node->last > new_node->last)
3936 new_node->last = next_node->last;
3937 eb64_delete(next);
3938 pool_free(pool_head_quic_arng, next_node);
3939 /* Decrement the size of these ranges. */
3940 arngs->sz--;
3941 }
3942 }
3943
3944 ret = 1;
3945 leave:
3946 quic_arngs_set_enc_sz(qc, arngs);
3947 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3948 return ret;
3949}
3950/* Remove the header protection of packets at <el> encryption level.
3951 * Always succeeds.
3952 */
3953static inline void qc_rm_hp_pkts(struct quic_conn *qc, struct quic_enc_level *el)
3954{
3955 struct quic_tls_ctx *tls_ctx;
3956 struct quic_rx_packet *pqpkt, *pkttmp;
3957 struct quic_enc_level *app_qel;
3958
3959 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, qc);
3960 app_qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3961 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
3962 if (el == app_qel && qc_is_listener(qc) && qc->state < QUIC_HS_ST_COMPLETE) {
3963 TRACE_DEVEL("hp not removed (handshake not completed)",
3964 QUIC_EV_CONN_ELRMHP, qc);
3965 goto out;
3966 }
3967 tls_ctx = &el->tls_ctx;
3968 list_for_each_entry_safe(pqpkt, pkttmp, &el->rx.pqpkts, list) {
3969 if (!qc_do_rm_hp(qc, pqpkt, tls_ctx, el->pktns->rx.largest_pn,
3970 pqpkt->data + pqpkt->pn_offset, pqpkt->data)) {
3971 TRACE_ERROR("hp removing error", QUIC_EV_CONN_ELRMHP, qc);
3972 }
3973 else {
3974 /* The AAD includes the packet number field */
3975 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
3976 /* Store the packet into the tree of packets to decrypt. */
3977 pqpkt->pn_node.key = pqpkt->pn;
3978 eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
3979 quic_rx_packet_refinc(pqpkt);
3980 TRACE_DEVEL("hp removed", QUIC_EV_CONN_ELRMHP, qc, pqpkt);
3981 }
3982 LIST_DELETE(&pqpkt->list);
3983 quic_rx_packet_refdec(pqpkt);
3984 }
3985
3986 out:
3987 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, qc);
3988}
3989
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003990/* Process all the CRYPTO frame at <el> encryption level. This is the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003991 * responsibility of the called to ensure there exists a CRYPTO data
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003992 * stream for this level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003993 * Return 1 if succeeded, 0 if not.
3994 */
3995static inline int qc_treat_rx_crypto_frms(struct quic_conn *qc,
3996 struct quic_enc_level *el,
3997 struct ssl_sock_ctx *ctx)
3998{
3999 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004000 struct ncbuf *ncbuf;
4001 struct quic_cstream *cstream = el->cstream;
4002 ncb_sz_t data;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004003
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004004 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004005
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004006 BUG_ON(!cstream);
4007 ncbuf = &cstream->rx.ncbuf;
4008 if (ncb_is_null(ncbuf))
4009 goto done;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004010
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004011 /* TODO not working if buffer is wrapping */
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004012 while ((data = ncb_data(ncbuf, 0))) {
4013 const unsigned char *cdata = (const unsigned char *)ncb_head(ncbuf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004014
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004015 if (!qc_provide_cdata(el, ctx, cdata, data, NULL, NULL))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004016 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004017
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004018 cstream->rx.offset += data;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004019 TRACE_DEVEL("buffered crypto data were provided to TLS stack",
4020 QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004021 }
4022
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004023 done:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004024 ret = 1;
4025 leave:
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004026 if (!ncb_is_null(ncbuf) && ncb_is_empty(ncbuf)) {
4027 TRACE_DEVEL("freeing crypto buf", QUIC_EV_CONN_PHPKTS, qc, el);
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004028 quic_free_ncbuf(ncbuf);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004029 }
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004030 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004031 return ret;
4032}
4033
4034/* Process all the packets at <el> and <next_el> encryption level.
4035 * This is the caller responsibility to check that <cur_el> is different of <next_el>
4036 * as pointer value.
4037 * Return 1 if succeeded, 0 if not.
4038 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004039int qc_treat_rx_pkts(struct quic_conn *qc, struct quic_enc_level *cur_el,
4040 struct quic_enc_level *next_el, int force_ack)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004041{
4042 int ret = 0;
4043 struct eb64_node *node;
4044 int64_t largest_pn = -1;
4045 unsigned int largest_pn_time_received = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004046 struct quic_enc_level *qel = cur_el;
4047
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004048 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004049 qel = cur_el;
4050 next_tel:
4051 if (!qel)
4052 goto out;
4053
4054 node = eb64_first(&qel->rx.pkts);
4055 while (node) {
4056 struct quic_rx_packet *pkt;
4057
4058 pkt = eb64_entry(node, struct quic_rx_packet, pn_node);
4059 TRACE_DATA("new packet", QUIC_EV_CONN_RXPKT,
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004060 qc, pkt, NULL, qc->xprt_ctx->ssl);
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01004061 if (!qc_pkt_decrypt(qc, qel, pkt)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004062 /* Drop the packet */
4063 TRACE_ERROR("packet decryption failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004064 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004065 }
4066 else {
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004067 if (!qc_parse_pkt_frms(qc, pkt, qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004068 /* Drop the packet */
4069 TRACE_ERROR("packet parsing failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004070 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004071 HA_ATOMIC_INC(&qc->prx_counters->dropped_parsing);
4072 }
4073 else {
4074 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
4075
4076 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING || force_ack) {
4077 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
4078 qel->pktns->rx.nb_aepkts_since_last_ack++;
4079 qc_idle_timer_rearm(qc, 1);
4080 }
4081 if (pkt->pn > largest_pn) {
4082 largest_pn = pkt->pn;
4083 largest_pn_time_received = pkt->time_received;
4084 }
4085 /* Update the list of ranges to acknowledge. */
4086 if (!quic_update_ack_ranges_list(qc, &qel->pktns->rx.arngs, &ar))
4087 TRACE_ERROR("Could not update ack range list",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004088 QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004089 }
4090 }
4091 node = eb64_next(node);
4092 eb64_delete(&pkt->pn_node);
4093 quic_rx_packet_refdec(pkt);
4094 }
4095
4096 if (largest_pn != -1 && largest_pn > qel->pktns->rx.largest_pn) {
4097 /* Update the largest packet number. */
4098 qel->pktns->rx.largest_pn = largest_pn;
4099 /* Update the largest acknowledged packet timestamps */
4100 qel->pktns->rx.largest_time_received = largest_pn_time_received;
4101 qel->pktns->flags |= QUIC_FL_PKTNS_NEW_LARGEST_PN;
4102 }
4103
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004104 if (qel->cstream && !qc_treat_rx_crypto_frms(qc, qel, qc->xprt_ctx)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004105 // trace already emitted by function above
4106 goto leave;
4107 }
4108
4109 if (qel == cur_el) {
4110 BUG_ON(qel == next_el);
4111 qel = next_el;
4112 largest_pn = -1;
4113 goto next_tel;
4114 }
4115
4116 out:
4117 ret = 1;
4118 leave:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004119 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004120 return ret;
4121}
4122
4123/* Check if it's possible to remove header protection for packets related to
4124 * encryption level <qel>. If <qel> is NULL, assume it's false.
4125 *
4126 * Return true if the operation is possible else false.
4127 */
4128static int qc_qel_may_rm_hp(struct quic_conn *qc, struct quic_enc_level *qel)
4129{
4130 int ret = 0;
4131 enum quic_tls_enc_level tel;
4132
4133 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
4134
4135 if (!qel)
4136 goto cant_rm_hp;
4137
4138 tel = ssl_to_quic_enc_level(qel->level);
4139
4140 /* check if tls secrets are available */
4141 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
4142 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, qc);
4143 goto cant_rm_hp;
4144 }
4145
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004146 if (!quic_tls_has_rx_sec(qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004147 TRACE_DEVEL("non available secrets", QUIC_EV_CONN_TRMHP, qc);
4148 goto cant_rm_hp;
4149 }
4150
Frédéric Lécaille8417beb2023-02-01 10:31:35 +01004151 if (tel == QUIC_TLS_ENC_LEVEL_APP && qc->state < QUIC_HS_ST_COMPLETE) {
4152 TRACE_DEVEL("handshake not complete", QUIC_EV_CONN_TRMHP, qc);
4153 goto cant_rm_hp;
4154 }
4155
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004156 /* check if the connection layer is ready before using app level */
4157 if ((tel == QUIC_TLS_ENC_LEVEL_APP || tel == QUIC_TLS_ENC_LEVEL_EARLY_DATA) &&
4158 qc->mux_state == QC_MUX_NULL) {
4159 TRACE_DEVEL("connection layer not ready", QUIC_EV_CONN_TRMHP, qc);
4160 goto cant_rm_hp;
4161 }
4162
4163 ret = 1;
4164 cant_rm_hp:
4165 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc);
4166 return ret;
4167}
4168
4169/* Try to send application frames from list <frms> on connection <qc>.
4170 *
4171 * Use qc_send_app_probing wrapper when probing with old data.
4172 *
4173 * Returns 1 on success. Some data might not have been sent due to congestion,
4174 * in this case they are left in <frms> input list. The caller may subscribe on
4175 * quic-conn to retry later.
4176 *
4177 * Returns 0 on critical error.
4178 * TODO review and classify more distinctly transient from definitive errors to
4179 * allow callers to properly handle it.
4180 */
4181static int qc_send_app_pkts(struct quic_conn *qc, struct list *frms)
4182{
4183 int status = 0;
4184 struct buffer *buf;
4185
4186 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4187
4188 buf = qc_txb_alloc(qc);
4189 if (!buf) {
4190 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4191 goto leave;
4192 }
4193
4194 /* Prepare and send packets until we could not further prepare packets. */
4195 while (1) {
4196 int ret;
4197 /* Currently buf cannot be non-empty at this stage. Even if a
4198 * previous sendto() has failed it is emptied to simulate
4199 * packet emission and rely on QUIC lost detection to try to
4200 * emit it.
4201 */
4202 BUG_ON_HOT(b_data(buf));
4203 b_reset(buf);
4204
4205 ret = qc_prep_app_pkts(qc, buf, frms);
4206 if (ret == -1)
4207 goto err;
4208 else if (ret == 0)
4209 goto out;
4210
4211 if (!qc_send_ppkts(buf, qc->xprt_ctx))
4212 goto err;
4213 }
4214
4215 out:
4216 status = 1;
4217 qc_txb_release(qc);
4218 leave:
4219 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4220 return status;
4221
4222 err:
4223 qc_txb_release(qc);
4224 goto leave;
4225}
4226
4227/* Try to send application frames from list <frms> on connection <qc>. Use this
4228 * function when probing is required.
4229 *
4230 * Returns the result from qc_send_app_pkts function.
4231 */
4232static forceinline int qc_send_app_probing(struct quic_conn *qc,
4233 struct list *frms)
4234{
4235 int ret;
4236
4237 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4238
4239 TRACE_STATE("preparing old data (probing)", QUIC_EV_CONN_TXPKT, qc);
4240 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4241 ret = qc_send_app_pkts(qc, frms);
4242 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4243
4244 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4245 return ret;
4246}
4247
4248/* Try to send application frames from list <frms> on connection <qc>. This
4249 * function is provided for MUX upper layer usage only.
4250 *
4251 * Returns the result from qc_send_app_pkts function.
4252 */
4253int qc_send_mux(struct quic_conn *qc, struct list *frms)
4254{
4255 int ret;
4256
4257 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4258 BUG_ON(qc->mux_state != QC_MUX_READY); /* Only MUX can uses this function so it must be ready. */
4259
4260 TRACE_STATE("preparing data (from MUX)", QUIC_EV_CONN_TXPKT, qc);
4261 qc->flags |= QUIC_FL_CONN_TX_MUX_CONTEXT;
4262 ret = qc_send_app_pkts(qc, frms);
4263 qc->flags &= ~QUIC_FL_CONN_TX_MUX_CONTEXT;
4264
4265 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4266 return ret;
4267}
4268
4269/* Sends handshake packets from up to two encryption levels <tel> and <next_te>
4270 * with <tel_frms> and <next_tel_frms> as frame list respectively for <qc>
4271 * QUIC connection. <old_data> is used as boolean to send data already sent but
4272 * not already acknowledged (in flight).
4273 * Returns 1 if succeeded, 0 if not.
4274 */
4275int qc_send_hdshk_pkts(struct quic_conn *qc, int old_data,
4276 enum quic_tls_enc_level tel, struct list *tel_frms,
4277 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
4278{
4279 int ret, status = 0;
4280 struct buffer *buf = qc_txb_alloc(qc);
4281
4282 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4283
4284 if (!buf) {
4285 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4286 goto leave;
4287 }
4288
4289 /* Currently buf cannot be non-empty at this stage. Even if a previous
4290 * sendto() has failed it is emptied to simulate packet emission and
4291 * rely on QUIC lost detection to try to emit it.
4292 */
4293 BUG_ON_HOT(b_data(buf));
4294 b_reset(buf);
4295
4296 if (old_data) {
4297 TRACE_STATE("old data for probing asked", QUIC_EV_CONN_TXPKT, qc);
4298 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4299 }
4300
4301 ret = qc_prep_pkts(qc, buf, tel, tel_frms, next_tel, next_tel_frms);
4302 if (ret == -1)
4303 goto out;
4304 else if (ret == 0)
4305 goto skip_send;
4306
4307 if (!qc_send_ppkts(buf, qc->xprt_ctx))
4308 goto out;
4309
4310 skip_send:
4311 status = 1;
4312 out:
4313 TRACE_STATE("no more need old data for probing", QUIC_EV_CONN_TXPKT, qc);
4314 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4315 qc_txb_release(qc);
4316 leave:
4317 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4318 return status;
4319}
4320
4321/* Retransmit up to two datagrams depending on packet number space */
4322static void qc_dgrams_retransmit(struct quic_conn *qc)
4323{
4324 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4325 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4326 struct quic_enc_level *aqel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4327
4328 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4329
4330 if (iqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004331 int i;
4332
4333 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
4334 struct list ifrms = LIST_HEAD_INIT(ifrms);
4335 struct list hfrms = LIST_HEAD_INIT(hfrms);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004336
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004337 qc_prep_hdshk_fast_retrans(qc, &ifrms, &hfrms);
4338 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &ifrms);
4339 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4340 if (!LIST_ISEMPTY(&ifrms)) {
4341 iqel->pktns->tx.pto_probe = 1;
4342 if (!LIST_ISEMPTY(&hfrms))
4343 hqel->pktns->tx.pto_probe = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004344 qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4345 QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms);
4346 /* Put back unsent frames in their packet number spaces */
4347 LIST_SPLICE(&iqel->pktns->tx.frms, &ifrms);
4348 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4349 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004350 }
4351 TRACE_STATE("no more need to probe Initial packet number space",
4352 QUIC_EV_CONN_TXPKT, qc);
4353 iqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004354 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004355 }
4356 else {
4357 int i;
4358
4359 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004360 hqel->pktns->tx.pto_probe = 0;
4361 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
Frédéric Lécaille7b5d9b12022-11-28 17:21:45 +01004362 struct list frms1 = LIST_HEAD_INIT(frms1);
4363
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004364 qc_prep_fast_retrans(qc, hqel, &frms1, NULL);
4365 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4366 if (!LIST_ISEMPTY(&frms1)) {
4367 hqel->pktns->tx.pto_probe = 1;
4368 qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &frms1,
4369 QUIC_TLS_ENC_LEVEL_NONE, NULL);
4370 /* Put back unsent frames into their packet number spaces */
4371 LIST_SPLICE(&hqel->pktns->tx.frms, &frms1);
4372 }
4373 }
4374 TRACE_STATE("no more need to probe Handshake packet number space",
4375 QUIC_EV_CONN_TXPKT, qc);
4376 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4377 }
4378 else if (aqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4379 struct list frms2 = LIST_HEAD_INIT(frms2);
4380 struct list frms1 = LIST_HEAD_INIT(frms1);
4381
4382 aqel->pktns->tx.pto_probe = 0;
4383 qc_prep_fast_retrans(qc, aqel, &frms1, &frms2);
4384 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4385 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms2);
4386 if (!LIST_ISEMPTY(&frms1)) {
4387 aqel->pktns->tx.pto_probe = 1;
4388 qc_send_app_probing(qc, &frms1);
4389 /* Put back unsent frames into their packet number spaces */
4390 LIST_SPLICE(&aqel->pktns->tx.frms, &frms1);
4391 }
4392 if (!LIST_ISEMPTY(&frms2)) {
4393 aqel->pktns->tx.pto_probe = 1;
4394 qc_send_app_probing(qc, &frms2);
4395 /* Put back unsent frames into their packet number spaces */
4396 LIST_SPLICE(&aqel->pktns->tx.frms, &frms2);
4397 }
4398 TRACE_STATE("no more need to probe 01RTT packet number space",
4399 QUIC_EV_CONN_TXPKT, qc);
4400 aqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4401 }
4402 }
4403 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4404}
4405
4406/* QUIC connection packet handler task (post handshake) */
4407struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state)
4408{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004409 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004410 struct quic_enc_level *qel;
4411
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004412 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4413
4414 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
4415 TRACE_STATE("connection handshake state", QUIC_EV_CONN_IO_CB, qc, &qc->state);
4416
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004417 if (qc_test_fd(qc))
4418 qc_rcv_buf(qc);
4419
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004420 /* Retranmissions */
4421 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4422 TRACE_STATE("retransmission needed", QUIC_EV_CONN_IO_CB, qc);
4423 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
4424 qc_dgrams_retransmit(qc);
4425 }
4426
4427 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4428 qc_rm_hp_pkts(qc, qel);
4429
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004430 if (!qc_treat_rx_pkts(qc, qel, NULL, 0)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004431 TRACE_DEVEL("qc_treat_rx_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4432 goto out;
4433 }
4434
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004435 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4436 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
4437 goto out;
4438 }
4439
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004440 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4441 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)) {
4442 TRACE_STATE("draining connection (must not send packets)", QUIC_EV_CONN_IO_CB, qc);
4443 goto out;
4444 }
4445
4446 /* XXX TODO: how to limit the list frames to send */
4447 if (!qc_send_app_pkts(qc, &qel->pktns->tx.frms)) {
4448 TRACE_DEVEL("qc_send_app_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4449 goto out;
4450 }
4451
4452 out:
4453 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
4454 return t;
4455}
4456
4457/* Returns a boolean if <qc> needs to emit frames for <qel> encryption level. */
4458static int qc_need_sending(struct quic_conn *qc, struct quic_enc_level *qel)
4459{
4460 return (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) ||
4461 (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) ||
4462 qel->pktns->tx.pto_probe ||
4463 !LIST_ISEMPTY(&qel->pktns->tx.frms);
4464}
4465
4466/* QUIC connection packet handler task. */
4467struct task *quic_conn_io_cb(struct task *t, void *context, unsigned int state)
4468{
4469 int ret, ssl_err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004470 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004471 enum quic_tls_enc_level tel, next_tel;
4472 struct quic_enc_level *qel, *next_qel;
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004473 /* Early-data encryption level */
4474 struct quic_enc_level *eqel;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004475 struct buffer *buf = NULL;
4476 int st, force_ack, zero_rtt;
4477
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004478 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004479 eqel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004480 st = qc->state;
4481 TRACE_PROTO("connection state", QUIC_EV_CONN_IO_CB, qc, &st);
4482
4483 /* Retranmissions */
4484 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4485 TRACE_DEVEL("retransmission needed", QUIC_EV_CONN_PHPKTS, qc);
4486 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
4487 qc_dgrams_retransmit(qc);
4488 }
4489
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004490 ssl_err = SSL_ERROR_NONE;
4491 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004492 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004493 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004494
4495 if (qc_test_fd(qc))
4496 qc_rcv_buf(qc);
4497
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004498 if (st >= QUIC_HS_ST_COMPLETE &&
4499 qc_el_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
4500 TRACE_DEVEL("remaining Handshake packets", QUIC_EV_CONN_PHPKTS, qc);
4501 /* There may be remaining Handshake packets to treat and acknowledge. */
4502 tel = QUIC_TLS_ENC_LEVEL_HANDSHAKE;
4503 next_tel = QUIC_TLS_ENC_LEVEL_APP;
4504 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004505 else if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, zero_rtt))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004506 goto out;
4507
4508 qel = &qc->els[tel];
4509 next_qel = next_tel == QUIC_TLS_ENC_LEVEL_NONE ? NULL : &qc->els[next_tel];
4510
4511 next_level:
4512 /* Treat packets waiting for header packet protection decryption */
4513 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4514 qc_rm_hp_pkts(qc, qel);
4515
4516 force_ack = qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
4517 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004518 if (!qc_treat_rx_pkts(qc, qel, next_qel, force_ack))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004519 goto out;
4520
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004521 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4522 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_PHPKTS, qc);
4523 goto out;
4524 }
4525
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004526 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4527 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE))
4528 goto out;
4529
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004530 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004531 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004532 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
4533 if (next_qel && next_qel == eqel && zero_rtt) {
4534 TRACE_DEVEL("select 0RTT as next encryption level",
4535 QUIC_EV_CONN_PHPKTS, qc);
4536 qel = next_qel;
4537 next_qel = NULL;
4538 goto next_level;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004539 }
4540
4541 st = qc->state;
4542 if (st >= QUIC_HS_ST_COMPLETE) {
4543 if (!(qc->flags & QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT) &&
4544 !quic_build_post_handshake_frames(qc))
4545 goto out;
4546
4547 if (!(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].tls_ctx.flags &
4548 QUIC_FL_TLS_SECRETS_DCD)) {
4549 /* Discard the Handshake keys. */
4550 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4551 TRACE_PROTO("discarding Handshake pktns", QUIC_EV_CONN_PHPKTS, qc);
4552 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, qc);
4553 qc_set_timer(qc);
4554 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4555 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns);
4556 }
4557
4558 if (qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) {
4559 /* There may be remaining handshake to build (acks) */
4560 st = QUIC_HS_ST_SERVER_HANDSHAKE;
4561 }
4562 }
4563
4564 /* A listener does not send any O-RTT packet. O-RTT packet number space must not
4565 * be considered.
4566 */
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004567 if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, 0))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004568 goto out;
4569
4570 if (!qc_need_sending(qc, qel) &&
4571 (!next_qel || !qc_need_sending(qc, next_qel))) {
4572 goto skip_send;
4573 }
4574
4575 buf = qc_txb_alloc(qc);
4576 if (!buf)
4577 goto out;
4578
4579 /* Currently buf cannot be non-empty at this stage. Even if a previous
4580 * sendto() has failed it is emptied to simulate packet emission and
4581 * rely on QUIC lost detection to try to emit it.
4582 */
4583 BUG_ON_HOT(b_data(buf));
4584 b_reset(buf);
4585
4586 ret = qc_prep_pkts(qc, buf, tel, &qc->els[tel].pktns->tx.frms,
4587 next_tel, &qc->els[next_tel].pktns->tx.frms);
4588 if (ret == -1)
4589 goto out;
4590 else if (ret == 0)
4591 goto skip_send;
4592
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004593 if (!qc_send_ppkts(buf, qc->xprt_ctx))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004594 goto out;
4595
4596 skip_send:
4597 /* Check if there is something to do for the next level.
4598 */
4599 if (next_qel && next_qel != qel &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004600 quic_tls_has_rx_sec(next_qel) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004601 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || qc_el_rx_pkts(next_qel))) {
4602 qel = next_qel;
4603 next_qel = NULL;
4604 goto next_level;
4605 }
4606
4607 out:
4608 qc_txb_release(qc);
4609 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc, &st, &ssl_err);
4610 return t;
4611}
4612
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004613/* Release the memory allocated for <cs> CRYPTO stream */
4614void quic_cstream_free(struct quic_cstream *cs)
4615{
4616 if (!cs) {
4617 /* This is the case for ORTT encryption level */
4618 return;
4619 }
4620
Amaury Denoyellebc174b22022-11-17 10:12:52 +01004621 quic_free_ncbuf(&cs->rx.ncbuf);
4622
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004623 qc_stream_desc_release(cs->desc);
4624 pool_free(pool_head_quic_cstream, cs);
4625}
4626
4627/* Allocate a new QUIC stream for <qc>.
4628 * Return it if succeeded, NULL if not.
4629 */
4630struct quic_cstream *quic_cstream_new(struct quic_conn *qc)
4631{
4632 struct quic_cstream *cs, *ret_cs = NULL;
4633
4634 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4635 cs = pool_alloc(pool_head_quic_cstream);
4636 if (!cs) {
4637 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4638 goto leave;
4639 }
4640
4641 cs->rx.offset = 0;
4642 cs->rx.ncbuf = NCBUF_NULL;
4643 cs->rx.offset = 0;
4644
4645 cs->tx.offset = 0;
4646 cs->tx.sent_offset = 0;
4647 cs->tx.buf = BUF_NULL;
4648 cs->desc = qc_stream_desc_new((uint64_t)-1, -1, cs, qc);
4649 if (!cs->desc) {
4650 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4651 goto err;
4652 }
4653
4654 ret_cs = cs;
4655 leave:
4656 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4657 return ret_cs;
4658
4659 err:
4660 pool_free(pool_head_quic_cstream, cs);
4661 goto leave;
4662}
4663
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004664/* Uninitialize <qel> QUIC encryption level. Never fails. */
4665static void quic_conn_enc_level_uninit(struct quic_conn *qc, struct quic_enc_level *qel)
4666{
4667 int i;
4668
4669 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4670
4671 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
4672 if (qel->tx.crypto.bufs[i]) {
4673 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
4674 qel->tx.crypto.bufs[i] = NULL;
4675 }
4676 }
4677 ha_free(&qel->tx.crypto.bufs);
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004678 quic_cstream_free(qel->cstream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004679
4680 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4681}
4682
4683/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
4684 * connection allocating everything needed.
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004685 *
4686 * Returns 1 if succeeded, 0 if not. On error the caller is responsible to use
4687 * quic_conn_enc_level_uninit() to cleanup partially allocated content.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004688 */
4689static int quic_conn_enc_level_init(struct quic_conn *qc,
4690 enum quic_tls_enc_level level)
4691{
4692 int ret = 0;
4693 struct quic_enc_level *qel;
4694
4695 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4696
4697 qel = &qc->els[level];
4698 qel->level = quic_to_ssl_enc_level(level);
4699 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
4700 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
4701 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
4702 qel->tls_ctx.flags = 0;
4703
4704 qel->rx.pkts = EB_ROOT;
4705 LIST_INIT(&qel->rx.pqpkts);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004706
4707 /* Allocate only one buffer. */
4708 /* TODO: use a pool */
4709 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
4710 if (!qel->tx.crypto.bufs)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004711 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004712
4713 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
4714 if (!qel->tx.crypto.bufs[0])
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004715 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004716
4717 qel->tx.crypto.bufs[0]->sz = 0;
4718 qel->tx.crypto.nb_buf = 1;
4719
4720 qel->tx.crypto.sz = 0;
4721 qel->tx.crypto.offset = 0;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004722 /* No CRYPTO data for early data TLS encryption level */
4723 if (level == QUIC_TLS_ENC_LEVEL_EARLY_DATA)
4724 qel->cstream = NULL;
4725 else {
4726 qel->cstream = quic_cstream_new(qc);
4727 if (!qel->cstream)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004728 goto leave;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004729 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004730
4731 ret = 1;
4732 leave:
4733 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4734 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004735}
4736
4737/* Callback called upon loss detection and PTO timer expirations. */
4738struct task *qc_process_timer(struct task *task, void *ctx, unsigned int state)
4739{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004740 struct quic_conn *qc = ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004741 struct quic_pktns *pktns;
4742
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004743 TRACE_ENTER(QUIC_EV_CONN_PTIMER, qc,
4744 NULL, NULL, &qc->path->ifae_pkts);
4745 task->expire = TICK_ETERNITY;
4746 pktns = quic_loss_pktns(qc);
4747 if (tick_isset(pktns->tx.loss_time)) {
4748 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
4749
4750 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
4751 if (!LIST_ISEMPTY(&lost_pkts))
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004752 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01004753 if (qc_release_lost_pkts(qc, pktns, &lost_pkts, now_ms))
4754 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004755 goto out;
4756 }
4757
4758 if (qc->path->in_flight) {
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +01004759 pktns = quic_pto_pktns(qc, qc->state >= QUIC_HS_ST_CONFIRMED, NULL);
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02004760 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004761 pktns->tx.pto_probe = QUIC_MAX_NB_PTO_DGRAMS;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02004762 tasklet_wakeup(qc->subs->tasklet);
4763 qc->subs->events &= ~SUB_RETRY_SEND;
4764 if (!qc->subs->events)
4765 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004766 }
4767 else {
4768 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4769 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4770 if (pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL]) {
4771 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4772 if (qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].tx.in_flight) {
4773 qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4774 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
4775 }
4776 }
4777 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE]) {
4778 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004779 if (qc->pktns[QUIC_TLS_PKTNS_INITIAL].tx.in_flight) {
4780 qc->pktns[QUIC_TLS_PKTNS_INITIAL].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4781 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4782 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004783 }
4784 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT]) {
4785 TRACE_STATE("needs to probe 01RTT packet number space", QUIC_EV_CONN_TXPKT, qc);
4786 }
4787 }
4788 }
4789 else if (!qc_is_listener(qc) && qc->state <= QUIC_HS_ST_COMPLETE) {
4790 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4791 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4792
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004793 if (quic_tls_has_tx_sec(hel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004794 hel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004795 if (quic_tls_has_tx_sec(iel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004796 iel->pktns->tx.pto_probe = 1;
4797 }
4798
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004799 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004800 qc->path->loss.pto_count++;
4801
4802 out:
4803 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, qc, pktns);
4804
4805 return task;
4806}
4807
4808/* Parse the Retry token from buffer <token> with <end> a pointer to
4809 * one byte past the end of this buffer. This will extract the ODCID
4810 * which will be stored into <odcid>
4811 *
4812 * Returns 0 on success else non-zero.
4813 */
4814static int parse_retry_token(struct quic_conn *qc,
4815 const unsigned char *token, const unsigned char *end,
4816 struct quic_cid *odcid)
4817{
4818 int ret = 0;
4819 uint64_t odcid_len;
4820 uint32_t timestamp;
4821
4822 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4823
4824 if (!quic_dec_int(&odcid_len, &token, end)) {
4825 TRACE_ERROR("quic_dec_int() error", QUIC_EV_CONN_LPKT, qc);
4826 goto leave;
4827 }
4828
4829 /* RFC 9000 7.2. Negotiating Connection IDs:
4830 * When an Initial packet is sent by a client that has not previously
4831 * received an Initial or Retry packet from the server, the client
4832 * populates the Destination Connection ID field with an unpredictable
4833 * value. This Destination Connection ID MUST be at least 8 bytes in length.
4834 */
4835 if (odcid_len < QUIC_ODCID_MINLEN || odcid_len > QUIC_CID_MAXLEN) {
4836 TRACE_ERROR("wrong ODCID length", QUIC_EV_CONN_LPKT, qc);
4837 goto leave;
4838 }
4839
4840 if (end - token < odcid_len + sizeof timestamp) {
4841 TRACE_ERROR("too long ODCID length", QUIC_EV_CONN_LPKT, qc);
4842 goto leave;
4843 }
4844
4845 timestamp = ntohl(read_u32(token + odcid_len));
4846 if (timestamp + MS_TO_TICKS(QUIC_RETRY_DURATION_MS) <= now_ms) {
4847 TRACE_ERROR("token has expired", QUIC_EV_CONN_LPKT, qc);
4848 goto leave;
4849 }
4850
4851 ret = 1;
4852 memcpy(odcid->data, token, odcid_len);
4853 odcid->len = odcid_len;
4854 leave:
4855 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4856 return !ret;
4857}
4858
4859/* Allocate a new QUIC connection with <version> as QUIC version. <ipv4>
4860 * boolean is set to 1 for IPv4 connection, 0 for IPv6. <server> is set to 1
4861 * for QUIC servers (or haproxy listeners).
4862 * <dcid> is the destination connection ID, <scid> is the source connection ID,
4863 * <token> the token found to be used for this connection with <token_len> as
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004864 * length. Endpoints addresses are specified via <local_addr> and <peer_addr>.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004865 * Returns the connection if succeeded, NULL if not.
4866 */
4867static struct quic_conn *qc_new_conn(const struct quic_version *qv, int ipv4,
4868 struct quic_cid *dcid, struct quic_cid *scid,
4869 const struct quic_cid *token_odcid,
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004870 struct sockaddr_storage *local_addr,
4871 struct sockaddr_storage *peer_addr,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004872 int server, int token, void *owner)
4873{
4874 int i;
4875 struct quic_conn *qc;
4876 /* Initial CID. */
4877 struct quic_connection_id *icid;
4878 char *buf_area = NULL;
4879 struct listener *l = NULL;
4880 struct quic_cc_algo *cc_algo = NULL;
4881 struct quic_tls_ctx *ictx;
4882 TRACE_ENTER(QUIC_EV_CONN_INIT);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004883 /* TODO replace pool_zalloc by pool_alloc(). This requires special care
4884 * to properly initialized internal quic_conn members to safely use
4885 * quic_conn_release() on alloc failure.
4886 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004887 qc = pool_zalloc(pool_head_quic_conn);
4888 if (!qc) {
4889 TRACE_ERROR("Could not allocate a new connection", QUIC_EV_CONN_INIT);
4890 goto err;
4891 }
4892
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004893 /* Initialize in priority qc members required for a safe dealloc. */
4894
4895 /* required to use MTLIST_IN_LIST */
4896 MT_LIST_INIT(&qc->accept_list);
4897
4898 LIST_INIT(&qc->rx.pkt_list);
4899
Amaury Denoyelle42448332022-12-12 11:24:05 +01004900 qc_init_fd(qc);
4901
Amaury Denoyelle15c74702023-02-01 10:18:26 +01004902 LIST_INIT(&qc->back_refs);
4903
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004904 /* Now proceeds to allocation of qc members. */
4905
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004906 buf_area = pool_alloc(pool_head_quic_conn_rxbuf);
4907 if (!buf_area) {
4908 TRACE_ERROR("Could not allocate a new RX buffer", QUIC_EV_CONN_INIT, qc);
4909 goto err;
4910 }
4911
4912 qc->cids = EB_ROOT;
4913 /* QUIC Server (or listener). */
4914 if (server) {
4915 struct proxy *prx;
4916
4917 l = owner;
4918 prx = l->bind_conf->frontend;
4919 cc_algo = l->bind_conf->quic_cc_algo;
4920
4921 qc->prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe,
4922 &quic_stats_module);
4923 qc->flags |= QUIC_FL_CONN_LISTENER;
4924 qc->state = QUIC_HS_ST_SERVER_INITIAL;
4925 /* Copy the initial DCID with the address. */
4926 qc->odcid.len = dcid->len;
4927 qc->odcid.addrlen = dcid->addrlen;
4928 memcpy(qc->odcid.data, dcid->data, dcid->len + dcid->addrlen);
4929
4930 /* copy the packet SCID to reuse it as DCID for sending */
4931 if (scid->len)
4932 memcpy(qc->dcid.data, scid->data, scid->len);
4933 qc->dcid.len = scid->len;
4934 qc->tx.buf = BUF_NULL;
4935 qc->li = l;
4936 }
4937 /* QUIC Client (outgoing connection to servers) */
4938 else {
4939 qc->state = QUIC_HS_ST_CLIENT_INITIAL;
4940 if (dcid->len)
4941 memcpy(qc->dcid.data, dcid->data, dcid->len);
4942 qc->dcid.len = dcid->len;
4943 }
4944 qc->mux_state = QC_MUX_NULL;
4945 qc->err = quic_err_transport(QC_ERR_NO_ERROR);
4946
4947 icid = new_quic_cid(&qc->cids, qc, 0);
4948 if (!icid) {
4949 TRACE_ERROR("Could not allocate a new connection ID", QUIC_EV_CONN_INIT, qc);
4950 goto err;
4951 }
4952
Amaury Denoyelle40909df2022-10-24 17:08:43 +02004953 if ((global.tune.options & GTUNE_QUIC_SOCK_PER_CONN) &&
4954 is_addr(local_addr)) {
4955 TRACE_USER("Allocate a socket for QUIC connection", QUIC_EV_CONN_INIT, qc);
4956 qc_alloc_fd(qc, local_addr, peer_addr);
4957 }
Amaury Denoyelle40909df2022-10-24 17:08:43 +02004958
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004959 /* insert the allocated CID in the receiver datagram handler tree */
4960 if (server)
4961 ebmb_insert(&quic_dghdlrs[tid].cids, &icid->node, icid->cid.len);
4962
4963 /* Select our SCID which is the first CID with 0 as sequence number. */
4964 qc->scid = icid->cid;
4965
4966 /* Packet number spaces initialization. */
4967 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
4968 quic_pktns_init(&qc->pktns[i]);
4969 /* QUIC encryption level context initialization. */
4970 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
4971 if (!quic_conn_enc_level_init(qc, i)) {
4972 TRACE_ERROR("Could not initialize an encryption level", QUIC_EV_CONN_INIT, qc);
4973 goto err;
4974 }
4975 /* Initialize the packet number space. */
4976 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
4977 }
4978
4979 qc->original_version = qv;
4980 qc->tps_tls_ext = (qc->original_version->num & 0xff000000) == 0xff000000 ?
4981 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS_DRAFT:
4982 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS;
4983 /* TX part. */
4984 LIST_INIT(&qc->tx.frms_to_send);
4985 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
4986 qc->tx.wbuf = qc->tx.rbuf = 0;
4987 qc->tx.bytes = 0;
4988 qc->tx.buf = BUF_NULL;
4989 /* RX part. */
4990 qc->rx.bytes = 0;
4991 qc->rx.buf = b_make(buf_area, QUIC_CONN_RX_BUFSZ, 0, 0);
4992 for (i = 0; i < QCS_MAX_TYPES; i++)
4993 qc->rx.strms[i].nb_streams = 0;
4994
4995 qc->nb_pkt_for_cc = 1;
4996 qc->nb_pkt_since_cc = 0;
4997
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004998 if (!quic_tls_ku_init(qc)) {
4999 TRACE_ERROR("Key update initialization failed", QUIC_EV_CONN_INIT, qc);
5000 goto err;
5001 }
5002
5003 /* XXX TO DO: Only one path at this time. */
5004 qc->path = &qc->paths[0];
5005 quic_path_init(qc->path, ipv4, cc_algo ? cc_algo : default_quic_cc_algo, qc);
5006
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005007 qc->streams_by_id = EB_ROOT_UNIQUE;
5008 qc->stream_buf_count = 0;
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005009 memcpy(&qc->local_addr, local_addr, sizeof(qc->local_addr));
5010 memcpy(&qc->peer_addr, peer_addr, sizeof qc->peer_addr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005011
5012 if (server && !qc_lstnr_params_init(qc, &l->bind_conf->quic_params,
5013 icid->stateless_reset_token,
5014 dcid->data, dcid->len,
5015 qc->scid.data, qc->scid.len, token_odcid))
5016 goto err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005017
5018 qc->wait_event.tasklet = tasklet_new();
5019 if (!qc->wait_event.tasklet) {
5020 TRACE_ERROR("tasklet_new() failed", QUIC_EV_CONN_TXPKT);
5021 goto err;
5022 }
5023 qc->wait_event.tasklet->process = quic_conn_io_cb;
5024 qc->wait_event.tasklet->context = qc;
5025 qc->wait_event.events = 0;
5026 /* Set tasklet tid based on the SCID selected by us for this
5027 * connection. The upper layer will also be binded on the same thread.
5028 */
Willy Tarreaueed78262022-12-21 09:09:19 +01005029 qc->tid = quic_get_cid_tid(qc->scid.data, &l->rx);
Willy Tarreauf5a0c8a2022-10-13 16:14:11 +02005030 qc->wait_event.tasklet->tid = qc->tid;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02005031 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005032
5033 if (qc_conn_alloc_ssl_ctx(qc) ||
5034 !quic_conn_init_timer(qc) ||
5035 !quic_conn_init_idle_timer_task(qc))
5036 goto err;
5037
5038 ictx = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
5039 if (!qc_new_isecs(qc, ictx,qc->original_version, dcid->data, dcid->len, 1))
5040 goto err;
5041
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005042 LIST_APPEND(&th_ctx->quic_conns, &qc->el_th_ctx);
5043 qc->qc_epoch = HA_ATOMIC_LOAD(&qc_epoch);
5044
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005045 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc);
5046
5047 return qc;
5048
5049 err:
5050 pool_free(pool_head_quic_conn_rxbuf, buf_area);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005051 if (qc) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005052 qc->rx.buf.area = NULL;
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005053 quic_conn_release(qc);
5054 }
5055 TRACE_LEAVE(QUIC_EV_CONN_INIT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005056 return NULL;
5057}
5058
5059/* Release the quic_conn <qc>. The connection is removed from the CIDs tree.
5060 * The connection tasklet is killed.
5061 *
5062 * This function must only be called by the thread responsible of the quic_conn
5063 * tasklet.
5064 */
5065void quic_conn_release(struct quic_conn *qc)
5066{
5067 int i;
5068 struct ssl_sock_ctx *conn_ctx;
5069 struct eb64_node *node;
5070 struct quic_tls_ctx *app_tls_ctx;
5071 struct quic_rx_packet *pkt, *pktback;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005072 struct bref *bref, *back;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005073
5074 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5075
5076 /* We must not free the quic-conn if the MUX is still allocated. */
5077 BUG_ON(qc->mux_state == QC_MUX_READY);
5078
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005079 /* Close quic-conn socket fd. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01005080 qc_release_fd(qc, 0);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005081
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005082 /* in the unlikely (but possible) case the connection was just added to
5083 * the accept_list we must delete it from there.
5084 */
5085 MT_LIST_DELETE(&qc->accept_list);
5086
5087 /* free remaining stream descriptors */
5088 node = eb64_first(&qc->streams_by_id);
5089 while (node) {
5090 struct qc_stream_desc *stream;
5091
5092 stream = eb64_entry(node, struct qc_stream_desc, by_id);
5093 node = eb64_next(node);
5094
5095 /* all streams attached to the quic-conn are released, so
5096 * qc_stream_desc_free will liberate the stream instance.
5097 */
5098 BUG_ON(!stream->release);
5099 qc_stream_desc_free(stream, 1);
5100 }
5101
5102 /* Purge Rx packet list. */
5103 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
5104 LIST_DELETE(&pkt->qc_rx_pkt_list);
5105 pool_free(pool_head_quic_rx_packet, pkt);
5106 }
5107
5108 if (qc->idle_timer_task) {
5109 task_destroy(qc->idle_timer_task);
5110 qc->idle_timer_task = NULL;
5111 }
5112
5113 if (qc->timer_task) {
5114 task_destroy(qc->timer_task);
5115 qc->timer_task = NULL;
5116 }
5117
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005118 if (qc->wait_event.tasklet)
5119 tasklet_free(qc->wait_event.tasklet);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005120
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005121 /* remove the connection from receiver cids trees */
5122 ebmb_delete(&qc->odcid_node);
5123 ebmb_delete(&qc->scid_node);
5124 free_quic_conn_cids(qc);
5125
5126 conn_ctx = qc->xprt_ctx;
5127 if (conn_ctx) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005128 SSL_free(conn_ctx->ssl);
5129 pool_free(pool_head_quic_conn_ctx, conn_ctx);
5130 }
5131
5132 quic_tls_ku_free(qc);
5133 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5134 quic_tls_ctx_secs_free(&qc->els[i].tls_ctx);
5135 quic_conn_enc_level_uninit(qc, &qc->els[i]);
5136 }
5137 quic_tls_ctx_secs_free(&qc->negotiated_ictx);
5138
5139 app_tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
5140 pool_free(pool_head_quic_tls_secret, app_tls_ctx->rx.secret);
5141 pool_free(pool_head_quic_tls_secret, app_tls_ctx->tx.secret);
5142
5143 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++) {
5144 quic_pktns_tx_pkts_release(&qc->pktns[i], qc);
5145 quic_free_arngs(qc, &qc->pktns[i].rx.arngs);
5146 }
5147
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005148 /* Detach CLI context watchers currently dumping this connection.
5149 * Reattach them to the next quic_conn instance.
5150 */
5151 list_for_each_entry_safe(bref, back, &qc->back_refs, users) {
5152 /* Remove watcher from this quic_conn instance. */
5153 LIST_DEL_INIT(&bref->users);
5154
5155 /* Attach it to next instance unless it was the last list element. */
5156 if (qc->el_th_ctx.n != &th_ctx->quic_conns) {
5157 struct quic_conn *next = LIST_NEXT(&qc->el_th_ctx,
5158 struct quic_conn *,
5159 el_th_ctx);
5160 LIST_APPEND(&next->back_refs, &bref->users);
5161 }
5162 bref->ref = qc->el_th_ctx.n;
5163 __ha_barrier_store();
5164 }
5165 /* Remove quic_conn from global ha_thread_ctx list. */
5166 LIST_DELETE(&qc->el_th_ctx);
5167
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005168 pool_free(pool_head_quic_conn_rxbuf, qc->rx.buf.area);
5169 pool_free(pool_head_quic_conn, qc);
5170 TRACE_PROTO("QUIC conn. freed", QUIC_EV_CONN_FREED, qc);
5171
5172 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5173}
5174
5175/* Initialize the timer task of <qc> QUIC connection.
5176 * Returns 1 if succeeded, 0 if not.
5177 */
5178static int quic_conn_init_timer(struct quic_conn *qc)
5179{
5180 int ret = 0;
5181 /* Attach this task to the same thread ID used for the connection */
5182 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5183
5184 qc->timer_task = task_new_on(qc->tid);
5185 if (!qc->timer_task) {
5186 TRACE_ERROR("timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5187 goto leave;
5188 }
5189
5190 qc->timer = TICK_ETERNITY;
5191 qc->timer_task->process = qc_process_timer;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005192 qc->timer_task->context = qc;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005193
5194 ret = 1;
5195 leave:
5196 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5197 return ret;
5198}
5199
5200/* Rearm the idle timer for <qc> QUIC connection. */
5201static void qc_idle_timer_do_rearm(struct quic_conn *qc)
5202{
5203 unsigned int expire;
5204
5205 expire = QUIC_MAX(3 * quic_pto(qc), qc->max_idle_timeout);
5206 qc->idle_timer_task->expire = tick_add(now_ms, MS_TO_TICKS(expire));
5207}
5208
5209/* Rearm the idle timer for <qc> QUIC connection depending on <read> boolean
5210 * which is set to 1 when receiving a packet , and 0 when sending packet
5211 */
5212static void qc_idle_timer_rearm(struct quic_conn *qc, int read)
5213{
5214 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5215
5216 if (read) {
5217 qc->flags |= QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5218 }
5219 else {
5220 qc->flags &= ~QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5221 }
5222 qc_idle_timer_do_rearm(qc);
5223
5224 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5225}
5226
5227/* The task handling the idle timeout */
5228struct task *qc_idle_timer_task(struct task *t, void *ctx, unsigned int state)
5229{
5230 struct quic_conn *qc = ctx;
5231 struct quic_counters *prx_counters = qc->prx_counters;
5232 unsigned int qc_flags = qc->flags;
5233
5234 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5235
5236 /* Notify the MUX before settings QUIC_FL_CONN_EXP_TIMER or the MUX
5237 * might free the quic-conn too early via quic_close().
5238 */
5239 qc_notify_close(qc);
5240
5241 /* If the MUX is still alive, keep the quic-conn. The MUX is
5242 * responsible to call quic_close to release it.
5243 */
5244 qc->flags |= QUIC_FL_CONN_EXP_TIMER;
5245 if (qc->mux_state != QC_MUX_READY)
5246 quic_conn_release(qc);
5247
5248 /* TODO if the quic-conn cannot be freed because of the MUX, we may at
5249 * least clean some parts of it such as the tasklet.
5250 */
5251
5252 if (!(qc_flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
5253 qc_flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
5254 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
5255 HA_ATOMIC_DEC(&prx_counters->half_open_conn);
5256 }
5257
5258 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5259 return NULL;
5260}
5261
5262/* Initialize the idle timeout task for <qc>.
5263 * Returns 1 if succeeded, 0 if not.
5264 */
5265static int quic_conn_init_idle_timer_task(struct quic_conn *qc)
5266{
5267 int ret = 0;
5268
5269 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5270
5271 qc->idle_timer_task = task_new_here();
5272 if (!qc->idle_timer_task) {
5273 TRACE_ERROR("Idle timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5274 goto leave;
5275 }
5276
5277 qc->idle_timer_task->process = qc_idle_timer_task;
5278 qc->idle_timer_task->context = qc;
5279 qc_idle_timer_rearm(qc, 1);
5280 task_queue(qc->idle_timer_task);
5281
5282 ret = 1;
5283 leave:
5284 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5285 return ret;
5286}
5287
5288/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
5289 * past one byte of this buffer.
5290 */
5291static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
5292 struct quic_rx_packet *pkt)
5293{
5294 int ret = 0;
5295 unsigned char dcid_len, scid_len;
5296
5297 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5298
5299 if (end == *buf) {
5300 TRACE_ERROR("buffer data consumed", QUIC_EV_CONN_RXPKT);
5301 goto leave;
5302 }
5303
5304 /* Destination Connection ID Length */
5305 dcid_len = *(*buf)++;
5306 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
5307 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1) {
5308 TRACE_ERROR("too long DCID", QUIC_EV_CONN_RXPKT);
5309 goto leave;
5310 }
5311
5312 if (dcid_len) {
5313 /* Check that the length of this received DCID matches the CID lengths
5314 * of our implementation for non Initials packets only.
5315 */
5316 if (pkt->type != QUIC_PACKET_TYPE_INITIAL &&
5317 pkt->type != QUIC_PACKET_TYPE_0RTT &&
5318 dcid_len != QUIC_HAP_CID_LEN) {
5319 TRACE_ERROR("wrong DCID length", QUIC_EV_CONN_RXPKT);
5320 goto leave;
5321 }
5322
5323 memcpy(pkt->dcid.data, *buf, dcid_len);
5324 }
5325
5326 pkt->dcid.len = dcid_len;
5327 *buf += dcid_len;
5328
5329 /* Source Connection ID Length */
5330 scid_len = *(*buf)++;
5331 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len) {
5332 TRACE_ERROR("too long SCID", QUIC_EV_CONN_RXPKT);
5333 goto leave;
5334 }
5335
5336 if (scid_len)
5337 memcpy(pkt->scid.data, *buf, scid_len);
5338 pkt->scid.len = scid_len;
5339 *buf += scid_len;
5340
5341 ret = 1;
5342 leave:
5343 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5344 return ret;
5345}
5346
5347/* Insert <pkt> RX packet in its <qel> RX packets tree */
5348static void qc_pkt_insert(struct quic_conn *qc,
5349 struct quic_rx_packet *pkt, struct quic_enc_level *qel)
5350{
5351 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
5352
5353 pkt->pn_node.key = pkt->pn;
5354 quic_rx_packet_refinc(pkt);
5355 eb64_insert(&qel->rx.pkts, &pkt->pn_node);
5356
5357 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5358}
5359
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005360/* Try to remove the header protection of <pkt> QUIC packet with <beg> the
5361 * address of the packet first byte, using the keys from encryption level <el>.
5362 *
5363 * If header protection has been successfully removed, packet data are copied
5364 * into <qc> Rx buffer. If <el> secrets are not yet available, the copy is also
5365 * proceeded, and the packet is inserted into <qc> protected packets tree. In
5366 * both cases, packet can now be considered handled by the <qc> connection.
5367 *
5368 * If header protection cannot be removed due to <el> secrets already
5369 * discarded, no operation is conducted.
5370 *
5371 * Returns 1 on success : packet data is now handled by the connection. On
5372 * error 0 is returned : packet should be dropped by the caller.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005373 */
5374static inline int qc_try_rm_hp(struct quic_conn *qc,
5375 struct quic_rx_packet *pkt,
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005376 unsigned char *beg,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005377 struct quic_enc_level **el)
5378{
5379 int ret = 0;
5380 unsigned char *pn = NULL; /* Packet number field */
5381 enum quic_tls_enc_level tel;
5382 struct quic_enc_level *qel;
5383 /* Only for traces. */
5384 struct quic_rx_packet *qpkt_trace;
5385
5386 qpkt_trace = NULL;
5387 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005388 BUG_ON(!pkt->pn_offset);
5389
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005390 /* The packet number is here. This is also the start minus
5391 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
5392 * protection.
5393 */
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005394 pn = beg + pkt->pn_offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005395
5396 tel = quic_packet_type_enc_level(pkt->type);
5397 qel = &qc->els[tel];
5398
5399 if (qc_qel_may_rm_hp(qc, qel)) {
5400 /* Note that the following function enables us to unprotect the packet
5401 * number and its length subsequently used to decrypt the entire
5402 * packets.
5403 */
5404 if (!qc_do_rm_hp(qc, pkt, &qel->tls_ctx,
5405 qel->pktns->rx.largest_pn, pn, beg)) {
5406 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, qc);
5407 goto out;
5408 }
5409
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005410 /* The AAD includes the packet number field. */
5411 pkt->aad_len = pkt->pn_offset + pkt->pnl;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005412 if (pkt->len - pkt->aad_len < QUIC_TLS_TAG_LEN) {
5413 TRACE_PROTO("Too short packet", QUIC_EV_CONN_TRMHP, qc);
5414 goto out;
5415 }
5416
5417 qpkt_trace = pkt;
5418 }
5419 else {
5420 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
5421 /* If the packet number space has been discarded, this packet
5422 * will be not parsed.
5423 */
5424 TRACE_PROTO("Discarded pktns", QUIC_EV_CONN_TRMHP, qc, pkt);
5425 goto out;
5426 }
5427
5428 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005429 LIST_APPEND(&qel->rx.pqpkts, &pkt->list);
5430 quic_rx_packet_refinc(pkt);
5431 }
5432
5433 *el = qel;
5434 /* No reference counter incrementation here!!! */
5435 LIST_APPEND(&qc->rx.pkt_list, &pkt->qc_rx_pkt_list);
5436 memcpy(b_tail(&qc->rx.buf), beg, pkt->len);
5437 pkt->data = (unsigned char *)b_tail(&qc->rx.buf);
5438 b_add(&qc->rx.buf, pkt->len);
5439
5440 ret = 1;
5441 out:
5442 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc, qpkt_trace);
5443 return ret;
5444}
5445
5446/* Parse the header form from <byte0> first byte of <pkt> packet to set its type.
5447 * Also set <*long_header> to 1 if this form is long, 0 if not and the version
5448 * of this packet into <*version>.
5449 */
5450static inline int qc_parse_hd_form(struct quic_rx_packet *pkt,
5451 unsigned char **buf, const unsigned char *end,
5452 int *long_header, uint32_t *version)
5453{
5454 int ret = 0;
5455 const unsigned char byte0 = **buf;
5456
5457 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5458
5459 (*buf)++;
5460 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
5461 unsigned char type =
5462 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
5463
5464 *long_header = 1;
5465 /* Version */
5466 if (!quic_read_uint32(version, (const unsigned char **)buf, end)) {
5467 TRACE_ERROR("could not read the packet version", QUIC_EV_CONN_RXPKT);
5468 goto out;
5469 }
5470
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +01005471 if (*version != QUIC_PROTOCOL_VERSION_2) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005472 pkt->type = type;
5473 }
5474 else {
5475 switch (type) {
5476 case 0:
5477 pkt->type = QUIC_PACKET_TYPE_RETRY;
5478 break;
5479 case 1:
5480 pkt->type = QUIC_PACKET_TYPE_INITIAL;
5481 break;
5482 case 2:
5483 pkt->type = QUIC_PACKET_TYPE_0RTT;
5484 break;
5485 case 3:
5486 pkt->type = QUIC_PACKET_TYPE_HANDSHAKE;
5487 break;
5488 }
5489 }
5490 }
5491 else {
5492 pkt->type = QUIC_PACKET_TYPE_SHORT;
5493 *long_header = 0;
5494 }
5495
5496 ret = 1;
5497 out:
5498 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5499 return ret;
5500}
5501
5502/* Return the QUIC version (quic_version struct) with <version> as version number
5503 * if supported or NULL if not.
5504 */
5505static inline const struct quic_version *qc_supported_version(uint32_t version)
5506{
5507 int i;
5508
5509 for (i = 0; i < quic_versions_nb; i++)
5510 if (quic_versions[i].num == version)
5511 return &quic_versions[i];
5512
5513 return NULL;
5514}
5515
5516/*
5517 * Send a Version Negotiation packet on response to <pkt> on socket <fd> to
5518 * address <addr>.
5519 * Implementation of RFC9000 6. Version Negotiation
5520 *
5521 * TODO implement a rate-limiting sending of Version Negotiation packets
5522 *
5523 * Returns 0 on success else non-zero
5524 */
5525static int send_version_negotiation(int fd, struct sockaddr_storage *addr,
5526 struct quic_rx_packet *pkt)
5527{
5528 char buf[256];
5529 int ret = 0, i = 0, j;
5530 uint32_t version;
5531 const socklen_t addrlen = get_addr_len(addr);
5532
5533 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5534 /*
5535 * header form
5536 * long header, fixed bit to 0 for Version Negotiation
5537 */
5538 /* TODO: RAND_bytes() should be replaced? */
5539 if (RAND_bytes((unsigned char *)buf, 1) != 1) {
5540 TRACE_ERROR("RAND_bytes() error", QUIC_EV_CONN_TXPKT);
5541 goto out;
5542 }
5543
5544 buf[i++] |= '\x80';
5545 /* null version for Version Negotiation */
5546 buf[i++] = '\x00';
5547 buf[i++] = '\x00';
5548 buf[i++] = '\x00';
5549 buf[i++] = '\x00';
5550
5551 /* source connection id */
5552 buf[i++] = pkt->scid.len;
5553 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5554 i += pkt->scid.len;
5555
5556 /* destination connection id */
5557 buf[i++] = pkt->dcid.len;
5558 memcpy(&buf[i], pkt->dcid.data, pkt->dcid.len);
5559 i += pkt->dcid.len;
5560
5561 /* supported version */
5562 for (j = 0; j < quic_versions_nb; j++) {
5563 version = htonl(quic_versions[j].num);
5564 memcpy(&buf[i], &version, sizeof(version));
5565 i += sizeof(version);
5566 }
5567
5568 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0)
5569 goto out;
5570
5571 ret = 1;
5572 out:
5573 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5574 return !ret;
5575}
5576
5577/* Send a stateless reset packet depending on <pkt> RX packet information
5578 * from <fd> UDP socket to <dst>
5579 * Return 1 if succeeded, 0 if not.
5580 */
5581static int send_stateless_reset(struct listener *l, struct sockaddr_storage *dstaddr,
5582 struct quic_rx_packet *rxpkt)
5583{
5584 int ret = 0, pktlen, rndlen;
5585 unsigned char pkt[64];
5586 const socklen_t addrlen = get_addr_len(dstaddr);
5587 struct proxy *prx;
5588 struct quic_counters *prx_counters;
5589
5590 TRACE_ENTER(QUIC_EV_STATELESS_RST);
5591
5592 prx = l->bind_conf->frontend;
5593 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5594 /* 10.3 Stateless Reset (https://www.rfc-editor.org/rfc/rfc9000.html#section-10.3)
5595 * The resulting minimum size of 21 bytes does not guarantee that a Stateless
5596 * Reset is difficult to distinguish from other packets if the recipient requires
5597 * the use of a connection ID. To achieve that end, the endpoint SHOULD ensure
5598 * that all packets it sends are at least 22 bytes longer than the minimum
5599 * connection ID length that it requests the peer to include in its packets,
5600 * adding PADDING frames as necessary. This ensures that any Stateless Reset
5601 * sent by the peer is indistinguishable from a valid packet sent to the endpoint.
5602 * An endpoint that sends a Stateless Reset in response to a packet that is
5603 * 43 bytes or shorter SHOULD send a Stateless Reset that is one byte shorter
5604 * than the packet it responds to.
5605 */
5606
5607 /* Note that we build at most a 42 bytes QUIC packet to mimic a short packet */
5608 pktlen = rxpkt->len <= 43 ? rxpkt->len - 1 : 0;
5609 pktlen = QUIC_MAX(QUIC_STATELESS_RESET_PACKET_MINLEN, pktlen);
5610 rndlen = pktlen - QUIC_STATELESS_RESET_TOKEN_LEN;
5611
5612 /* Put a header of random bytes */
5613 /* TODO: RAND_bytes() should be replaced */
5614 if (RAND_bytes(pkt, rndlen) != 1) {
5615 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_STATELESS_RST);
5616 goto leave;
5617 }
5618
5619 /* Clear the most significant bit, and set the second one */
5620 *pkt = (*pkt & ~0x80) | 0x40;
5621 if (!quic_stateless_reset_token_cpy(NULL, pkt + rndlen, QUIC_STATELESS_RESET_TOKEN_LEN,
5622 rxpkt->dcid.data, rxpkt->dcid.len))
5623 goto leave;
5624
5625 if (sendto(l->rx.fd, pkt, pktlen, 0, (struct sockaddr *)dstaddr, addrlen) < 0)
5626 goto leave;
5627
5628 ret = 1;
5629 HA_ATOMIC_INC(&prx_counters->stateless_reset_sent);
5630 TRACE_PROTO("stateless reset sent", QUIC_EV_STATELESS_RST, NULL, &rxpkt->dcid);
5631 leave:
5632 TRACE_LEAVE(QUIC_EV_STATELESS_RST);
5633 return ret;
5634}
5635
5636/* QUIC server only function.
5637 * Add AAD to <add> buffer from <cid> connection ID and <addr> socket address.
5638 * This is the responsibility of the caller to check <aad> size is big enough
5639 * to contain these data.
5640 * Return the number of bytes copied to <aad>.
5641 */
5642static int quic_generate_retry_token_aad(unsigned char *aad,
5643 uint32_t version,
5644 const struct quic_cid *cid,
5645 const struct sockaddr_storage *addr)
5646{
5647 unsigned char *p;
5648
5649 p = aad;
5650 memcpy(p, &version, sizeof version);
5651 p += sizeof version;
5652 p += quic_saddr_cpy(p, addr);
5653 memcpy(p, cid->data, cid->len);
5654 p += cid->len;
5655
5656 return p - aad;
5657}
5658
5659/* QUIC server only function.
5660 * Generate the token to be used in Retry packets. The token is written to
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05005661 * <buf> with <len> as length. <odcid> is the original destination connection
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005662 * ID and <dcid> is our side destination connection ID (or client source
5663 * connection ID).
5664 * Returns the length of the encoded token or 0 on error.
5665 */
5666static int quic_generate_retry_token(unsigned char *buf, size_t len,
5667 const uint32_t version,
5668 const struct quic_cid *odcid,
5669 const struct quic_cid *dcid,
5670 struct sockaddr_storage *addr)
5671{
5672 int ret = 0;
5673 unsigned char *p;
5674 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005675 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005676 size_t aadlen;
5677 unsigned char salt[QUIC_RETRY_TOKEN_SALTLEN];
5678 unsigned char key[QUIC_TLS_KEY_LEN];
5679 unsigned char iv[QUIC_TLS_IV_LEN];
5680 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5681 size_t seclen = strlen(global.cluster_secret);
5682 EVP_CIPHER_CTX *ctx = NULL;
5683 const EVP_CIPHER *aead = EVP_aes_128_gcm();
5684 uint32_t timestamp = now_ms;
5685
5686 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5687
5688 /* We copy the odcid into the token, prefixed by its one byte
5689 * length, the format token byte. It is followed by an AEAD TAG, and finally
5690 * the random bytes used to derive the secret to encrypt the token.
5691 */
5692 if (1 + dcid->len + 1 + QUIC_TLS_TAG_LEN + sizeof salt > len)
5693 goto err;
5694
5695 aadlen = quic_generate_retry_token_aad(aad, version, dcid, addr);
5696 /* TODO: RAND_bytes() should be replaced */
5697 if (RAND_bytes(salt, sizeof salt) != 1) {
5698 TRACE_ERROR("RAND_bytes()", QUIC_EV_CONN_TXPKT);
5699 goto err;
5700 }
5701
5702 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5703 salt, sizeof salt, sec, seclen)) {
5704 TRACE_ERROR("quic_tls_derive_retry_token_secret() failed", QUIC_EV_CONN_TXPKT);
5705 goto err;
5706 }
5707
5708 if (!quic_tls_tx_ctx_init(&ctx, aead, key)) {
5709 TRACE_ERROR("quic_tls_tx_ctx_init() failed", QUIC_EV_CONN_TXPKT);
5710 goto err;
5711 }
5712
5713 /* Token build */
5714 p = buf;
5715 *p++ = QUIC_TOKEN_FMT_RETRY,
5716 *p++ = odcid->len;
5717 memcpy(p, odcid->data, odcid->len);
5718 p += odcid->len;
5719 write_u32(p, htonl(timestamp));
5720 p += sizeof timestamp;
5721
5722 /* Do not encrypt the QUIC_TOKEN_FMT_RETRY byte */
5723 if (!quic_tls_encrypt(buf + 1, p - buf - 1, aad, aadlen, ctx, aead, key, iv)) {
5724 TRACE_ERROR("quic_tls_encrypt() failed", QUIC_EV_CONN_TXPKT);
5725 goto err;
5726 }
5727
5728 p += QUIC_TLS_TAG_LEN;
5729 memcpy(p, salt, sizeof salt);
5730 p += sizeof salt;
5731 EVP_CIPHER_CTX_free(ctx);
5732
5733 ret = p - buf;
5734 leave:
5735 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5736 return ret;
5737
5738 err:
5739 if (ctx)
5740 EVP_CIPHER_CTX_free(ctx);
5741 goto leave;
5742}
5743
5744/* QUIC server only function.
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005745 *
5746 * Check the validity of the Retry token from Initial packet <pkt>. <dgram> is
5747 * the UDP datagram containing <pkt> and <l> is the listener instance on which
5748 * it was received. If the token is valid, the ODCID of <qc> QUIC connection
5749 * will be put into <odcid>. <qc> is used to retrieve the QUIC version needed
5750 * to validate the token but it can be NULL : in this case the version will be
5751 * retrieved from the packet.
5752 *
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005753 * Return 1 if succeeded, 0 if not.
5754 */
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005755
5756static int quic_retry_token_check(struct quic_rx_packet *pkt,
5757 struct quic_dgram *dgram,
5758 struct listener *l,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005759 struct quic_conn *qc,
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005760 struct quic_cid *odcid)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005761{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005762 struct proxy *prx;
5763 struct quic_counters *prx_counters;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005764 int ret = 0;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005765 unsigned char *token = pkt->token;
5766 const uint64_t tokenlen = pkt->token_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005767 unsigned char buf[128];
5768 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005769 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005770 size_t aadlen;
5771 const unsigned char *salt;
5772 unsigned char key[QUIC_TLS_KEY_LEN];
5773 unsigned char iv[QUIC_TLS_IV_LEN];
5774 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5775 size_t seclen = strlen(global.cluster_secret);
5776 EVP_CIPHER_CTX *ctx = NULL;
5777 const EVP_CIPHER *aead = EVP_aes_128_gcm();
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005778 const struct quic_version *qv = qc ? qc->original_version :
5779 pkt->version;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005780
5781 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5782
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005783 /* The caller must ensure this. */
5784 BUG_ON(!global.cluster_secret || !pkt->token_len);
5785
5786 prx = l->bind_conf->frontend;
5787 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5788
5789 if (*pkt->token != QUIC_TOKEN_FMT_RETRY) {
5790 /* TODO: New token check */
5791 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
5792 goto leave;
5793 }
5794
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005795 if (sizeof buf < tokenlen) {
5796 TRACE_ERROR("too short buffer", QUIC_EV_CONN_LPKT, qc);
5797 goto err;
5798 }
5799
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005800 aadlen = quic_generate_retry_token_aad(aad, qv->num, &pkt->scid, &dgram->saddr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005801 salt = token + tokenlen - QUIC_RETRY_TOKEN_SALTLEN;
5802 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5803 salt, QUIC_RETRY_TOKEN_SALTLEN, sec, seclen)) {
5804 TRACE_ERROR("Could not derive retry secret", QUIC_EV_CONN_LPKT, qc);
5805 goto err;
5806 }
5807
5808 if (!quic_tls_rx_ctx_init(&ctx, aead, key)) {
5809 TRACE_ERROR("quic_tls_rx_ctx_init() failed", QUIC_EV_CONN_LPKT, qc);
5810 goto err;
5811 }
5812
5813 /* Do not decrypt the QUIC_TOKEN_FMT_RETRY byte */
5814 if (!quic_tls_decrypt2(buf, token + 1, tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, aad, aadlen,
5815 ctx, aead, key, iv)) {
5816 TRACE_ERROR("Could not decrypt retry token", QUIC_EV_CONN_LPKT, qc);
5817 goto err;
5818 }
5819
5820 if (parse_retry_token(qc, buf, buf + tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, odcid)) {
5821 TRACE_ERROR("Error during Initial token parsing", QUIC_EV_CONN_LPKT, qc);
5822 goto err;
5823 }
5824
5825 EVP_CIPHER_CTX_free(ctx);
5826
5827 ret = 1;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005828 HA_ATOMIC_INC(&prx_counters->retry_validated);
5829
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005830 leave:
5831 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5832 return ret;
5833
5834 err:
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005835 HA_ATOMIC_INC(&prx_counters->retry_error);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005836 if (ctx)
5837 EVP_CIPHER_CTX_free(ctx);
5838 goto leave;
5839}
5840
5841/* Generate a Retry packet and send it on <fd> socket to <addr> in response to
5842 * the Initial <pkt> packet.
5843 *
5844 * Returns 0 on success else non-zero.
5845 */
5846static int send_retry(int fd, struct sockaddr_storage *addr,
5847 struct quic_rx_packet *pkt, const struct quic_version *qv)
5848{
5849 int ret = 0;
5850 unsigned char buf[128];
5851 int i = 0, token_len;
5852 const socklen_t addrlen = get_addr_len(addr);
5853 struct quic_cid scid;
5854
5855 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5856
5857 /* long header + fixed bit + packet type QUIC_PACKET_TYPE_RETRY */
5858 buf[i++] = (QUIC_PACKET_LONG_HEADER_BIT | QUIC_PACKET_FIXED_BIT) |
5859 (quic_pkt_type(QUIC_PACKET_TYPE_RETRY, qv->num) << QUIC_PACKET_TYPE_SHIFT);
5860 /* version */
5861 buf[i++] = *((unsigned char *)&qv->num + 3);
5862 buf[i++] = *((unsigned char *)&qv->num + 2);
5863 buf[i++] = *((unsigned char *)&qv->num + 1);
5864 buf[i++] = *(unsigned char *)&qv->num;
5865
5866 /* Use the SCID from <pkt> for Retry DCID. */
5867 buf[i++] = pkt->scid.len;
5868 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5869 i += pkt->scid.len;
5870
5871 /* Generate a new CID to be used as SCID for the Retry packet. */
5872 scid.len = QUIC_HAP_CID_LEN;
5873 /* TODO: RAND_bytes() should be replaced */
5874 if (RAND_bytes(scid.data, scid.len) != 1) {
5875 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT);
5876 goto out;
5877 }
5878
5879 buf[i++] = scid.len;
5880 memcpy(&buf[i], scid.data, scid.len);
5881 i += scid.len;
5882
5883 /* token */
5884 if (!(token_len = quic_generate_retry_token(&buf[i], sizeof(buf) - i, qv->num,
5885 &pkt->dcid, &pkt->scid, addr))) {
5886 TRACE_ERROR("quic_generate_retry_token() failed", QUIC_EV_CONN_TXPKT);
5887 goto out;
5888 }
5889
5890 i += token_len;
5891
5892 /* token integrity tag */
5893 if ((&buf[i] - buf < QUIC_TLS_TAG_LEN) ||
5894 !quic_tls_generate_retry_integrity_tag(pkt->dcid.data,
5895 pkt->dcid.len, buf, i, qv)) {
5896 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
5897 goto out;
5898 }
5899
5900 i += QUIC_TLS_TAG_LEN;
5901
5902 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0) {
5903 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
5904 goto out;
5905 }
5906
5907 ret = 1;
5908 out:
5909 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5910 return !ret;
5911}
5912
5913/* Retrieve a quic_conn instance from the <pkt> DCID field. If the packet is of
5914 * type INITIAL, the ODCID tree is first used. In this case, <saddr> is
5915 * concatenated to the <pkt> DCID field.
5916 *
5917 * Returns the instance or NULL if not found.
5918 */
5919static struct quic_conn *retrieve_qc_conn_from_cid(struct quic_rx_packet *pkt,
5920 struct listener *l,
5921 struct sockaddr_storage *saddr)
5922{
5923 struct quic_conn *qc = NULL;
5924 struct ebmb_node *node;
5925 struct quic_connection_id *id;
5926 /* set if the quic_conn is found in the second DCID tree */
5927
5928 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5929
5930 /* Look first into ODCIDs tree for INITIAL/0-RTT packets. */
5931 if (pkt->type == QUIC_PACKET_TYPE_INITIAL ||
5932 pkt->type == QUIC_PACKET_TYPE_0RTT) {
5933 /* DCIDs of first packets coming from multiple clients may have
5934 * the same values. Let's distinguish them by concatenating the
5935 * socket addresses.
5936 */
5937 quic_cid_saddr_cat(&pkt->dcid, saddr);
5938 node = ebmb_lookup(&quic_dghdlrs[tid].odcids, pkt->dcid.data,
5939 pkt->dcid.len + pkt->dcid.addrlen);
5940 if (node) {
5941 qc = ebmb_entry(node, struct quic_conn, odcid_node);
5942 goto end;
5943 }
5944 }
5945
5946 /* Look into DCIDs tree for non-INITIAL/0-RTT packets. This may be used
5947 * also for INITIAL/0-RTT non-first packets with the final DCID in
5948 * used.
5949 */
5950 node = ebmb_lookup(&quic_dghdlrs[tid].cids, pkt->dcid.data, pkt->dcid.len);
5951 if (!node)
5952 goto end;
5953
5954 id = ebmb_entry(node, struct quic_connection_id, node);
5955 qc = id->qc;
5956
5957 /* If found in DCIDs tree, remove the quic_conn from the ODCIDs tree.
5958 * If already done, this is a noop.
5959 */
5960 if (qc)
5961 ebmb_delete(&qc->odcid_node);
5962
5963 end:
5964 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5965 return qc;
5966}
5967
5968/* Try to allocate the <*ssl> SSL session object for <qc> QUIC connection
5969 * with <ssl_ctx> as SSL context inherited settings. Also set the transport
5970 * parameters of this session.
5971 * This is the responsibility of the caller to check the validity of all the
5972 * pointers passed as parameter to this function.
5973 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <qc->conn> to
5974 * CO_ER_SSL_NO_MEM.
5975 */
5976static int qc_ssl_sess_init(struct quic_conn *qc, SSL_CTX *ssl_ctx, SSL **ssl,
5977 unsigned char *params, size_t params_len)
5978{
5979 int retry, ret = -1;
5980
5981 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5982
5983 retry = 1;
5984 retry:
5985 *ssl = SSL_new(ssl_ctx);
5986 if (!*ssl) {
5987 if (!retry--)
5988 goto err;
5989
5990 pool_gc(NULL);
5991 goto retry;
5992 }
5993
5994 if (!SSL_set_quic_method(*ssl, &ha_quic_method) ||
5995 !SSL_set_ex_data(*ssl, ssl_qc_app_data_index, qc)) {
5996 SSL_free(*ssl);
5997 *ssl = NULL;
5998 if (!retry--)
5999 goto err;
6000
6001 pool_gc(NULL);
6002 goto retry;
6003 }
6004
6005 ret = 0;
6006 leave:
6007 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6008 return ret;
6009
6010 err:
6011 qc->conn->err_code = CO_ER_SSL_NO_MEM;
6012 goto leave;
6013}
6014
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006015/* Allocate the ssl_sock_ctx from connection <qc>. This creates the tasklet
6016 * used to process <qc> received packets. The allocated context is stored in
6017 * <qc.xprt_ctx>.
6018 *
6019 * Returns 0 on success else non-zero.
6020 */
6021static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc)
6022{
6023 int ret = 0;
6024 struct bind_conf *bc = qc->li->bind_conf;
6025 struct ssl_sock_ctx *ctx = NULL;
6026
6027 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6028
6029 ctx = pool_zalloc(pool_head_quic_conn_ctx);
6030 if (!ctx) {
6031 TRACE_ERROR("SSL context allocation failed", QUIC_EV_CONN_TXPKT);
6032 goto err;
6033 }
6034
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006035 ctx->subs = NULL;
6036 ctx->xprt_ctx = NULL;
6037 ctx->qc = qc;
6038
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006039 if (qc_is_listener(qc)) {
6040 if (qc_ssl_sess_init(qc, bc->initial_ctx, &ctx->ssl,
6041 qc->enc_params, qc->enc_params_len) == -1) {
6042 goto err;
6043 }
6044#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
6045 /* Enabling 0-RTT */
6046 if (bc->ssl_conf.early_data)
6047 SSL_set_quic_early_data_enabled(ctx->ssl, 1);
6048#endif
6049
6050 SSL_set_accept_state(ctx->ssl);
6051 }
6052
6053 ctx->xprt = xprt_get(XPRT_QUIC);
6054
6055 /* Store the allocated context in <qc>. */
6056 qc->xprt_ctx = ctx;
6057
6058 ret = 1;
6059 leave:
6060 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6061 return !ret;
6062
6063 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006064 pool_free(pool_head_quic_conn_ctx, ctx);
6065 goto leave;
6066}
6067
6068/* Check that all the bytes between <buf> included and <end> address
6069 * excluded are null. This is the responsibility of the caller to
6070 * check that there is at least one byte between <buf> end <end>.
6071 * Return 1 if this all the bytes are null, 0 if not.
6072 */
6073static inline int quic_padding_check(const unsigned char *buf,
6074 const unsigned char *end)
6075{
6076 while (buf < end && !*buf)
6077 buf++;
6078
6079 return buf == end;
6080}
6081
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006082/* Find the associated connection to the packet <pkt> or create a new one if
6083 * this is an Initial packet. <dgram> is the datagram containing the packet and
6084 * <l> is the listener instance on which it was received.
6085 *
6086 * Returns the quic-conn instance or NULL.
6087 */
6088static struct quic_conn *quic_rx_pkt_retrieve_conn(struct quic_rx_packet *pkt,
6089 struct quic_dgram *dgram,
6090 struct listener *l)
6091{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006092 struct quic_cid token_odcid = { .len = 0 };
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006093 struct quic_conn *qc = NULL;
6094 struct proxy *prx;
6095 struct quic_counters *prx_counters;
6096
6097 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6098
6099 prx = l->bind_conf->frontend;
6100 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6101
6102 qc = retrieve_qc_conn_from_cid(pkt, l, &dgram->saddr);
6103
6104 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6105 BUG_ON(!pkt->version); /* This must not happen. */
6106
6107 if (global.cluster_secret && pkt->token_len) {
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006108 if (!quic_retry_token_check(pkt, dgram, l, qc, &token_odcid))
6109 goto err;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006110 }
6111
6112 if (!qc) {
6113 int ipv4;
6114
6115 if (global.cluster_secret && !pkt->token_len && !(l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) &&
6116 HA_ATOMIC_LOAD(&prx_counters->half_open_conn) >= global.tune.quic_retry_threshold) {
6117 TRACE_PROTO("Initial without token, sending retry",
6118 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6119 if (send_retry(l->rx.fd, &dgram->saddr, pkt, pkt->version)) {
6120 TRACE_ERROR("Error during Retry generation",
6121 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6122 goto out;
6123 }
6124
6125 HA_ATOMIC_INC(&prx_counters->retry_sent);
6126 goto out;
6127 }
6128
6129 /* RFC 9000 7.2. Negotiating Connection IDs:
6130 * When an Initial packet is sent by a client that has not previously
6131 * received an Initial or Retry packet from the server, the client
6132 * populates the Destination Connection ID field with an unpredictable
6133 * value. This Destination Connection ID MUST be at least 8 bytes in length.
6134 */
6135 if (pkt->dcid.len < QUIC_ODCID_MINLEN) {
6136 TRACE_PROTO("dropped packet",
6137 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6138 goto err;
6139 }
6140
6141 pkt->saddr = dgram->saddr;
6142 ipv4 = dgram->saddr.ss_family == AF_INET;
6143
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006144 qc = qc_new_conn(pkt->version, ipv4, &pkt->dcid, &pkt->scid, &token_odcid,
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006145 &dgram->daddr, &pkt->saddr, 1,
6146 !!pkt->token_len, l);
6147 if (qc == NULL)
6148 goto err;
6149
6150 HA_ATOMIC_INC(&prx_counters->half_open_conn);
6151 /* Insert the DCID the QUIC client has chosen (only for listeners) */
6152 ebmb_insert(&quic_dghdlrs[tid].odcids, &qc->odcid_node,
6153 qc->odcid.len + qc->odcid.addrlen);
6154 }
6155 }
6156 else if (!qc) {
6157 TRACE_PROTO("No connection on a non Initial packet", QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6158 if (global.cluster_secret && !send_stateless_reset(l, &dgram->saddr, pkt))
6159 TRACE_ERROR("stateless reset not sent", QUIC_EV_CONN_LPKT, qc);
6160 goto err;
6161 }
6162
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006163 out:
6164 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6165 return qc;
6166
6167 err:
6168 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
6169 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
6170 return NULL;
6171}
6172
Amaury Denoyelle98289692022-10-19 15:37:44 +02006173/* Parse a QUIC packet starting at <buf>. Data won't be read after <end> even
6174 * if the packet is incomplete. This function will populate fields of <pkt>
6175 * instance, most notably its length. <dgram> is the UDP datagram which
6176 * contains the parsed packet. <l> is the listener instance on which it was
6177 * received.
6178 *
6179 * Returns 0 on success else non-zero. Packet length is guaranteed to be set to
6180 * the real packet value or to cover all data between <buf> and <end> : this is
6181 * useful to reject a whole datagram.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006182 */
Amaury Denoyelle98289692022-10-19 15:37:44 +02006183static int quic_rx_pkt_parse(struct quic_rx_packet *pkt,
6184 unsigned char *buf, const unsigned char *end,
6185 struct quic_dgram *dgram, struct listener *l)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006186{
Amaury Denoyelle98289692022-10-19 15:37:44 +02006187 const unsigned char *beg = buf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006188 struct proxy *prx;
6189 struct quic_counters *prx_counters;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006190 int long_header = 0;
Willy Tarreau33a68702022-11-24 09:16:41 +01006191 uint32_t version = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006192 const struct quic_version *qv = NULL;
6193
6194 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6195
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006196 prx = l->bind_conf->frontend;
6197 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6198 /* This ist only to please to traces and distinguish the
6199 * packet with parsed packet number from others.
6200 */
6201 pkt->pn_node.key = (uint64_t)-1;
6202 if (end <= buf) {
6203 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6204 goto drop;
6205 }
6206
6207 /* Fixed bit */
6208 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006209 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
6210 quic_padding_check(buf, end)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006211 /* Some browsers may pad the remaining datagram space with null bytes.
6212 * That is what we called add padding out of QUIC packets. Such
6213 * datagrams must be considered as valid. But we can only consume
6214 * the remaining space.
6215 */
6216 pkt->len = end - buf;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006217 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006218 }
6219
6220 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6221 goto drop;
6222 }
6223
6224 /* Header form */
6225 if (!qc_parse_hd_form(pkt, &buf, end, &long_header, &version)) {
6226 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6227 goto drop;
6228 }
6229
6230 if (long_header) {
6231 uint64_t len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006232
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006233 TRACE_PROTO("long header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006234 if (!quic_packet_read_long_header(&buf, end, pkt)) {
6235 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6236 goto drop;
6237 }
6238
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006239 if (pkt->type == QUIC_PACKET_TYPE_INITIAL &&
6240 dgram->len < QUIC_INITIAL_PACKET_MINLEN) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006241 TRACE_PROTO("Too short datagram with an Initial packet", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006242 HA_ATOMIC_INC(&prx_counters->too_short_initial_dgram);
6243 goto drop;
6244 }
6245
6246 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6247 * they must have the same DCID.
6248 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006249 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006250 (pkt->dcid.len != dgram->dcid_len ||
6251 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006252 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006253 goto drop;
6254 }
6255
6256 /* Retry of Version Negotiation packets are only sent by servers */
6257 if (pkt->type == QUIC_PACKET_TYPE_RETRY || !version) {
6258 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6259 goto drop;
6260 }
6261
6262 /* RFC9000 6. Version Negotiation */
6263 qv = qc_supported_version(version);
6264 if (!qv) {
6265 /* unsupported version, send Negotiation packet */
6266 if (send_version_negotiation(l->rx.fd, &dgram->saddr, pkt)) {
6267 TRACE_ERROR("VN packet not sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006268 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006269 }
6270
6271 TRACE_PROTO("VN packet sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006272 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006273 }
Amaury Denoyelle0eae5722022-10-17 18:05:18 +02006274 pkt->version = qv;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006275
6276 /* For Initial packets, and for servers (QUIC clients connections),
6277 * there is no Initial connection IDs storage.
6278 */
6279 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6280 uint64_t token_len;
6281
6282 if (!quic_dec_int(&token_len, (const unsigned char **)&buf, end) ||
6283 end - buf < token_len) {
6284 TRACE_PROTO("Packet dropped",
6285 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6286 goto drop;
6287 }
6288
6289 /* TODO Retry should be automatically activated if
6290 * suspect network usage is detected.
6291 */
6292 if (global.cluster_secret && !token_len) {
6293 if (l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) {
6294 TRACE_PROTO("Initial without token, sending retry",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006295 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006296 if (send_retry(l->rx.fd, &dgram->saddr, pkt, qv)) {
6297 TRACE_PROTO("Error during Retry generation",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006298 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006299 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006300 }
6301
6302 HA_ATOMIC_INC(&prx_counters->retry_sent);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006303 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006304 }
6305 }
6306 else if (!global.cluster_secret && token_len) {
6307 /* Impossible case: a token was received without configured
6308 * cluster secret.
6309 */
6310 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT,
6311 NULL, NULL, NULL, qv);
6312 goto drop;
6313 }
6314
6315 pkt->token = buf;
6316 pkt->token_len = token_len;
6317 buf += pkt->token_len;
6318 }
6319 else if (pkt->type != QUIC_PACKET_TYPE_0RTT) {
6320 if (pkt->dcid.len != QUIC_HAP_CID_LEN) {
6321 TRACE_PROTO("Packet dropped",
6322 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6323 goto drop;
6324 }
6325 }
6326
6327 if (!quic_dec_int(&len, (const unsigned char **)&buf, end) ||
6328 end - buf < len) {
6329 TRACE_PROTO("Packet dropped",
6330 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6331 goto drop;
6332 }
6333
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006334 /* Packet Number is stored here. Packet Length totalizes the
6335 * rest of the content.
6336 */
6337 pkt->pn_offset = buf - beg;
6338 pkt->len = pkt->pn_offset + len;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006339
6340 /* Interrupt parsing after packet length retrieval : this
6341 * ensures that only the packet is dropped but not the whole
6342 * datagram.
6343 */
6344 if (pkt->type == QUIC_PACKET_TYPE_0RTT && !l->bind_conf->ssl_conf.early_data) {
6345 TRACE_PROTO("0-RTT packet not supported", QUIC_EV_CONN_LPKT);
6346 goto drop;
6347 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006348 }
6349 else {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006350 TRACE_PROTO("short header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006351 if (end - buf < QUIC_HAP_CID_LEN) {
6352 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6353 goto drop;
6354 }
6355
6356 memcpy(pkt->dcid.data, buf, QUIC_HAP_CID_LEN);
6357 pkt->dcid.len = QUIC_HAP_CID_LEN;
6358
6359 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6360 * they must have the same DCID.
6361 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006362 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006363 (pkt->dcid.len != dgram->dcid_len ||
6364 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006365 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006366 goto drop;
6367 }
6368
6369 buf += QUIC_HAP_CID_LEN;
6370
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006371 pkt->pn_offset = buf - beg;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006372 /* A short packet is the last one of a UDP datagram. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006373 pkt->len = end - beg;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006374 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006375
Amaury Denoyelle98289692022-10-19 15:37:44 +02006376 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6377 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006378
Amaury Denoyelle98289692022-10-19 15:37:44 +02006379 drop:
6380 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006381 drop_silent:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006382 if (!pkt->len)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006383 pkt->len = end - beg;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006384 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6385 return -1;
6386}
6387
6388/* Check if received packet <pkt> should be drop due to <qc> already in closing
6389 * state. This can be true if a CONNECTION_CLOSE has already been emitted for
6390 * this connection.
6391 *
6392 * Returns false if connection is not in closing state else true. The caller
6393 * should drop the whole datagram in the last case to not mess up <qc>
6394 * CONNECTION_CLOSE rate limit counter.
6395 */
6396static int qc_rx_check_closing(struct quic_conn *qc,
6397 struct quic_rx_packet *pkt)
6398{
6399 if (!(qc->flags & QUIC_FL_CONN_CLOSING))
6400 return 0;
6401
6402 TRACE_STATE("Closing state connection", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6403
6404 /* Check if CONNECTION_CLOSE rate reemission is reached. */
6405 if (++qc->nb_pkt_since_cc >= qc->nb_pkt_for_cc) {
6406 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
6407 qc->nb_pkt_for_cc++;
6408 qc->nb_pkt_since_cc = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006409 }
6410
Amaury Denoyelle98289692022-10-19 15:37:44 +02006411 return 1;
6412}
6413
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006414/* React to a connection migration initiated on <qc> by a client with the new
6415 * path addresses <peer_addr>/<local_addr>.
6416 *
6417 * Returns 0 on success else non-zero.
6418 */
6419static int qc_handle_conn_migration(struct quic_conn *qc,
6420 const struct sockaddr_storage *peer_addr,
6421 const struct sockaddr_storage *local_addr)
6422{
6423 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6424
Frédéric Lécaille6fc86972023-01-12 08:29:23 +01006425 /* RFC 9000. Connection Migration
6426 *
6427 * If the peer sent the disable_active_migration transport parameter,
6428 * an endpoint also MUST NOT send packets (including probing packets;
6429 * see Section 9.1) from a different local address to the address the peer
6430 * used during the handshake, unless the endpoint has acted on a
6431 * preferred_address transport parameter from the peer.
6432 */
6433 if (qc->li->bind_conf->quic_params.disable_active_migration) {
6434 TRACE_ERROR("Active migration was disabled, datagram dropped", QUIC_EV_CONN_LPKT, qc);
6435 goto err;
6436 }
6437
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006438 /* RFC 9000 9. Connection Migration
6439 *
Amaury Denoyelleeb6be982022-11-21 11:14:45 +01006440 * The design of QUIC relies on endpoints retaining a stable address for
6441 * the duration of the handshake. An endpoint MUST NOT initiate
6442 * connection migration before the handshake is confirmed, as defined in
6443 * Section 4.1.2 of [QUIC-TLS].
6444 */
6445 if (qc->state < QUIC_HS_ST_COMPLETE) {
6446 TRACE_STATE("Connection migration during handshake rejected", QUIC_EV_CONN_LPKT, qc);
6447 goto err;
6448 }
6449
6450 /* RFC 9000 9. Connection Migration
6451 *
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006452 * TODO
6453 * An endpoint MUST
6454 * perform path validation (Section 8.2) if it detects any change to a
6455 * peer's address, unless it has previously validated that address.
6456 */
6457
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006458 /* Update quic-conn owned socket if in used.
6459 * TODO try to reuse it instead of closing and opening a new one.
6460 */
6461 if (qc_test_fd(qc)) {
6462 /* TODO try to reuse socket instead of closing it and opening a new one. */
6463 TRACE_STATE("Connection migration detected, allocate a new connection socket", QUIC_EV_CONN_LPKT, qc);
6464 qc_release_fd(qc, 1);
6465 qc_alloc_fd(qc, local_addr, peer_addr);
6466 }
6467
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006468 qc->local_addr = *local_addr;
6469 qc->peer_addr = *peer_addr;
6470 HA_ATOMIC_INC(&qc->prx_counters->conn_migration_done);
6471
6472 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6473 return 0;
6474
6475 err:
6476 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6477 return 1;
6478}
6479
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006480/* Release the memory for the RX packets which are no more referenced
6481 * and consume their payloads which have been copied to the RX buffer
6482 * for the connection.
6483 * Always succeeds.
6484 */
6485static inline void quic_rx_pkts_del(struct quic_conn *qc)
6486{
6487 struct quic_rx_packet *pkt, *pktback;
6488
6489 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
6490 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
6491 "pkt #%lld(type=%d,len=%zu,rawlen=%zu,refcnt=%u) (diff: %zd)",
6492 (long long)pkt->pn_node.key,
6493 pkt->type, pkt->len, pkt->raw_len, pkt->refcnt,
6494 (unsigned char *)b_head(&qc->rx.buf) - pkt->data);
6495 if (pkt->data != (unsigned char *)b_head(&qc->rx.buf)) {
6496 size_t cdata;
6497
6498 cdata = b_contig_data(&qc->rx.buf, 0);
6499 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
6500 "cdata=%zu *b_head()=0x%x", cdata, *b_head(&qc->rx.buf));
6501 if (cdata && !*b_head(&qc->rx.buf)) {
6502 /* Consume the remaining data */
6503 b_del(&qc->rx.buf, cdata);
6504 }
6505 break;
6506 }
6507
6508 if (pkt->refcnt)
6509 break;
6510
6511 b_del(&qc->rx.buf, pkt->raw_len);
6512 LIST_DELETE(&pkt->qc_rx_pkt_list);
6513 pool_free(pool_head_quic_rx_packet, pkt);
6514 }
6515
6516 /* In frequent cases the buffer will be emptied at this stage. */
6517 b_realign_if_empty(&qc->rx.buf);
6518}
6519
Amaury Denoyelle98289692022-10-19 15:37:44 +02006520/* Handle a parsed packet <pkt> by the connection <qc>. Data will be copied
6521 * into <qc> receive buffer after header protection removal procedure.
6522 *
6523 * <dgram> must be set to the datagram which contains the QUIC packet. <beg>
6524 * must point to packet buffer first byte.
6525 *
6526 * <tasklist_head> may be non-NULL when the caller treat several datagrams for
6527 * different quic-conn. In this case, each quic-conn tasklet will be appended
6528 * to it in order to be woken up after the current task.
6529 *
6530 * The caller can safely removed the packet data. If packet refcount was not
6531 * incremented by this function, it means that the connection did not handled
6532 * it and it should be freed by the caller.
6533 */
6534static void qc_rx_pkt_handle(struct quic_conn *qc, struct quic_rx_packet *pkt,
6535 struct quic_dgram *dgram, unsigned char *beg,
6536 struct list **tasklist_head)
6537{
6538 const struct quic_version *qv = pkt->version;
6539 struct quic_enc_level *qel = NULL;
6540 size_t b_cspace;
6541 int io_cb_wakeup = 1;
6542
Amaury Denoyelle3f474e62022-11-24 17:15:08 +01006543 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6544
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006545 if (pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST &&
6546 !quic_peer_validated_addr(qc) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006547 qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED) {
6548 TRACE_PROTO("PTO timer must be armed after anti-amplication was reached",
6549 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6550 /* Reset the anti-amplification bit. It will be set again
6551 * when sending the next packet if reached again.
6552 */
6553 qc->flags &= ~QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006554 io_cb_wakeup = 1;
6555 }
6556
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006557 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
6558 TRACE_PROTO("Connection error",
6559 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6560 goto out;
6561 }
6562
6563 pkt->raw_len = pkt->len;
6564 quic_rx_pkts_del(qc);
6565 b_cspace = b_contig_space(&qc->rx.buf);
6566 if (b_cspace < pkt->len) {
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006567 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
6568 "bspace=%zu pkt->len=%zu", b_cspace, pkt->len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006569 /* Do not consume buf if space not at the end. */
6570 if (b_tail(&qc->rx.buf) + b_cspace < b_wrap(&qc->rx.buf)) {
6571 TRACE_PROTO("Packet dropped",
6572 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006573 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006574 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006575 }
6576
6577 /* Let us consume the remaining contiguous space. */
6578 if (b_cspace) {
6579 b_putchr(&qc->rx.buf, 0x00);
6580 b_cspace--;
6581 }
6582 b_add(&qc->rx.buf, b_cspace);
6583 if (b_contig_space(&qc->rx.buf) < pkt->len) {
6584 TRACE_PROTO("Too big packet",
6585 QUIC_EV_CONN_LPKT, qc, pkt, &pkt->len, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006586 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006587 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006588 }
6589 }
6590
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006591 if (!qc_try_rm_hp(qc, pkt, beg, &qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006592 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6593 goto drop;
6594 }
6595
6596 TRACE_DATA("New packet", QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6597 if (pkt->aad_len)
6598 qc_pkt_insert(qc, pkt, qel);
6599 out:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006600 *tasklist_head = tasklet_wakeup_after(*tasklist_head,
6601 qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006602
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006603 drop_silent:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006604 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006605 return;
6606
6607 drop:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006608 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006609 err:
Frédéric Lécaille75c8ad52023-02-08 16:08:28 +01006610 if (io_cb_wakeup) {
6611 TRACE_DEVEL("needs to wakeup the timer task after the amplification limit was reached",
6612 QUIC_EV_CONN_LPKT, qc);
6613 qc_set_timer(qc);
6614 if (qc->timer_task && tick_isset(qc->timer) && tick_is_lt(qc->timer, now_ms))
6615 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
6616 }
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006617
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006618 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
6619}
6620
6621/* This function builds into <buf> buffer a QUIC long packet header.
6622 * Return 1 if enough room to build this header, 0 if not.
6623 */
6624static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
6625 int type, size_t pn_len,
6626 struct quic_conn *qc, const struct quic_version *ver)
6627{
6628 int ret = 0;
6629
6630 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6631
6632 if (end - *buf < sizeof ver->num + qc->dcid.len + qc->scid.len + 3) {
6633 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6634 goto leave;
6635 }
6636
6637 type = quic_pkt_type(type, ver->num);
6638 /* #0 byte flags */
6639 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
6640 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
6641 /* Version */
6642 quic_write_uint32(buf, end, ver->num);
6643 *(*buf)++ = qc->dcid.len;
6644 /* Destination connection ID */
6645 if (qc->dcid.len) {
6646 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6647 *buf += qc->dcid.len;
6648 }
6649 /* Source connection ID */
6650 *(*buf)++ = qc->scid.len;
6651 if (qc->scid.len) {
6652 memcpy(*buf, qc->scid.data, qc->scid.len);
6653 *buf += qc->scid.len;
6654 }
6655
6656 ret = 1;
6657 leave:
6658 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6659 return ret;
6660}
6661
6662/* This function builds into <buf> buffer a QUIC short packet header.
6663 * Return 1 if enough room to build this header, 0 if not.
6664 */
6665static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
6666 size_t pn_len, struct quic_conn *qc,
6667 unsigned char tls_flags)
6668{
6669 int ret = 0;
6670
6671 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6672
6673 if (end - *buf < 1 + qc->dcid.len) {
6674 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6675 goto leave;
6676 }
6677
6678 /* #0 byte flags */
6679 *(*buf)++ = QUIC_PACKET_FIXED_BIT |
6680 ((tls_flags & QUIC_FL_TLS_KP_BIT_SET) ? QUIC_PACKET_KEY_PHASE_BIT : 0) | (pn_len - 1);
6681 /* Destination connection ID */
6682 if (qc->dcid.len) {
6683 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6684 *buf += qc->dcid.len;
6685 }
6686
6687 ret = 1;
6688 leave:
6689 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6690 return ret;
6691}
6692
6693/* Apply QUIC header protection to the packet with <buf> as first byte address,
6694 * <pn> as address of the Packet number field, <pnlen> being this field length
6695 * with <aead> as AEAD cipher and <key> as secret key.
6696 * Returns 1 if succeeded or 0 if failed.
6697 */
6698static int quic_apply_header_protection(struct quic_conn *qc, unsigned char *buf,
6699 unsigned char *pn, size_t pnlen,
6700 struct quic_tls_ctx *tls_ctx)
6701
6702{
6703 int i, ret = 0;
6704 /* We need an IV of at least 5 bytes: one byte for bytes #0
6705 * and at most 4 bytes for the packet number
6706 */
6707 unsigned char mask[5] = {0};
6708 EVP_CIPHER_CTX *aes_ctx = tls_ctx->tx.hp_ctx;
6709
6710 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6711
6712 if (!quic_tls_aes_encrypt(mask, pn + QUIC_PACKET_PN_MAXLEN, sizeof mask, aes_ctx)) {
6713 TRACE_ERROR("could not apply header protection", QUIC_EV_CONN_TXPKT, qc);
6714 goto out;
6715 }
6716
6717 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
6718 for (i = 0; i < pnlen; i++)
6719 pn[i] ^= mask[i + 1];
6720
6721 ret = 1;
6722 out:
6723 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6724 return ret;
6725}
6726
6727/* Reduce the encoded size of <ack_frm> ACK frame removing the last
6728 * ACK ranges if needed to a value below <limit> in bytes.
6729 * Return 1 if succeeded, 0 if not.
6730 */
6731static int quic_ack_frm_reduce_sz(struct quic_conn *qc,
6732 struct quic_frame *ack_frm, size_t limit)
6733{
6734 size_t room, ack_delay_sz;
6735 int ret = 0;
6736
6737 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6738
6739 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
6740 /* A frame is made of 1 byte for the frame type. */
6741 room = limit - ack_delay_sz - 1;
6742 if (!quic_rm_last_ack_ranges(qc, ack_frm->tx_ack.arngs, room))
6743 goto leave;
6744
6745 ret = 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
6746 leave:
6747 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6748 return ret;
6749}
6750
6751/* Prepare into <outlist> as most as possible ack-eliciting frame from their
6752 * <inlist> prebuilt frames for <qel> encryption level to be encoded in a buffer
6753 * with <room> as available room, and <*len> the packet Length field initialized
6754 * with the number of bytes already present in this buffer which must be taken
6755 * into an account for the Length packet field value. <headlen> is the number of
6756 * bytes already present in this packet before building frames.
6757 *
6758 * Update consequently <*len> to reflect the size of these frames built
6759 * by this function. Also attach these frames to <l> frame list.
6760 * Return 1 if at least one ack-eleciting frame could be built, 0 if not.
6761 */
6762static inline int qc_build_frms(struct list *outlist, struct list *inlist,
6763 size_t room, size_t *len, size_t headlen,
6764 struct quic_enc_level *qel,
6765 struct quic_conn *qc)
6766{
6767 int ret;
6768 struct quic_frame *cf, *cfbak;
6769
6770 TRACE_ENTER(QUIC_EV_CONN_BCFRMS, qc);
6771
6772 ret = 0;
6773 if (*len > room)
6774 goto leave;
6775
6776 /* If we are not probing we must take into an account the congestion
6777 * control window.
6778 */
6779 if (!qel->pktns->tx.pto_probe) {
6780 size_t remain = quic_path_prep_data(qc->path);
6781
6782 if (headlen > remain)
6783 goto leave;
6784
6785 room = QUIC_MIN(room, remain - headlen);
6786 }
6787
6788 TRACE_PROTO("************** frames build (headlen)",
6789 QUIC_EV_CONN_BCFRMS, qc, &headlen);
6790
6791 /* NOTE: switch/case block inside a loop, a successful status must be
6792 * returned by this function only if at least one frame could be built
6793 * in the switch/case block.
6794 */
6795 list_for_each_entry_safe(cf, cfbak, inlist, list) {
6796 /* header length, data length, frame length. */
6797 size_t hlen, dlen, dlen_sz, avail_room, flen;
6798
6799 if (!room)
6800 break;
6801
6802 switch (cf->type) {
6803 case QUIC_FT_CRYPTO:
6804 TRACE_DEVEL(" New CRYPTO frame build (room, len)",
6805 QUIC_EV_CONN_BCFRMS, qc, &room, len);
6806 /* Compute the length of this CRYPTO frame header */
6807 hlen = 1 + quic_int_getsize(cf->crypto.offset);
6808 /* Compute the data length of this CRyPTO frame. */
6809 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
6810 TRACE_DEVEL(" CRYPTO data length (hlen, crypto.len, dlen)",
6811 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->crypto.len, &dlen);
6812 if (!dlen)
6813 continue;
6814
6815 /* CRYPTO frame length. */
6816 flen = hlen + quic_int_getsize(dlen) + dlen;
6817 TRACE_DEVEL(" CRYPTO frame length (flen)",
6818 QUIC_EV_CONN_BCFRMS, qc, &flen);
6819 /* Add the CRYPTO data length and its encoded length to the packet
6820 * length and the length of this length.
6821 */
6822 *len += flen;
6823 room -= flen;
6824 if (dlen == cf->crypto.len) {
6825 /* <cf> CRYPTO data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01006826 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006827 LIST_APPEND(outlist, &cf->list);
6828 }
6829 else {
6830 struct quic_frame *new_cf;
6831
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01006832 new_cf = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006833 if (!new_cf) {
6834 TRACE_ERROR("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, qc);
6835 continue;
6836 }
6837
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006838 new_cf->crypto.len = dlen;
6839 new_cf->crypto.offset = cf->crypto.offset;
6840 new_cf->crypto.qel = qel;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006841 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006842 if (cf->origin) {
6843 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
6844 /* This <cf> frame was duplicated */
6845 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
6846 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01006847 /* Detach the remaining CRYPTO frame from its original frame */
6848 LIST_DEL_INIT(&cf->ref);
6849 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006850 }
6851 LIST_APPEND(outlist, &new_cf->list);
6852 /* Consume <dlen> bytes of the current frame. */
6853 cf->crypto.len -= dlen;
6854 cf->crypto.offset += dlen;
6855 }
6856 break;
6857
6858 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
6859 if (cf->flags & QUIC_FL_TX_FRAME_LOST) {
6860 struct eb64_node *node = NULL;
6861 struct qc_stream_desc *stream_desc = NULL;
6862 struct quic_stream *strm = &cf->stream;
6863
6864 /* As this frame has been already lost, ensure the stream is always
6865 * available or the range of this frame is not consumed before
6866 * resending it.
6867 */
6868 node = eb64_lookup(&qc->streams_by_id, strm->id);
6869 if (!node) {
6870 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01006871 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006872 continue;
6873 }
6874
6875 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
6876 if (strm->offset.key + strm->len <= stream_desc->ack_offset) {
6877 TRACE_DEVEL("ignored frame frame in already acked range",
6878 QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01006879 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006880 continue;
6881 }
6882 else if (strm->offset.key < stream_desc->ack_offset) {
6883 strm->offset.key = stream_desc->ack_offset;
6884 TRACE_DEVEL("updated partially acked frame",
6885 QUIC_EV_CONN_PRSAFRM, qc, cf);
6886 }
6887 }
6888 /* Note that these frames are accepted in short packets only without
6889 * "Length" packet field. Here, <*len> is used only to compute the
6890 * sum of the lengths of the already built frames for this packet.
6891 *
6892 * Compute the length of this STREAM frame "header" made a all the field
6893 * excepting the variable ones. Note that +1 is for the type of this frame.
6894 */
6895 hlen = 1 + quic_int_getsize(cf->stream.id) +
6896 ((cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT) ? quic_int_getsize(cf->stream.offset.key) : 0);
6897 /* Compute the data length of this STREAM frame. */
6898 avail_room = room - hlen - *len;
6899 if ((ssize_t)avail_room <= 0)
6900 continue;
6901
6902 TRACE_DEVEL(" New STREAM frame build (room, len)",
6903 QUIC_EV_CONN_BCFRMS, qc, &room, len);
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01006904
6905 /* hlen contains STREAM id and offset. Ensure there is
6906 * enough room for length field.
6907 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006908 if (cf->type & QUIC_STREAM_FRAME_TYPE_LEN_BIT) {
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01006909 dlen = QUIC_MIN((uint64_t)max_available_room(avail_room, &dlen_sz),
6910 cf->stream.len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006911 dlen_sz = quic_int_getsize(dlen);
6912 flen = hlen + dlen_sz + dlen;
6913 }
6914 else {
6915 dlen = QUIC_MIN((uint64_t)avail_room, cf->stream.len);
6916 flen = hlen + dlen;
6917 }
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01006918
6919 if (cf->stream.len && !dlen) {
6920 /* Only a small gap is left on buffer, not
6921 * enough to encode the STREAM data length.
6922 */
6923 continue;
6924 }
6925
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006926 TRACE_DEVEL(" STREAM data length (hlen, stream.len, dlen)",
6927 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->stream.len, &dlen);
6928 TRACE_DEVEL(" STREAM frame length (flen)",
6929 QUIC_EV_CONN_BCFRMS, qc, &flen);
6930 /* Add the STREAM data length and its encoded length to the packet
6931 * length and the length of this length.
6932 */
6933 *len += flen;
6934 room -= flen;
6935 if (dlen == cf->stream.len) {
6936 /* <cf> STREAM data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01006937 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006938 LIST_APPEND(outlist, &cf->list);
6939
6940 /* Do not notify MUX on retransmission. */
6941 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
6942 qcc_streams_sent_done(cf->stream.stream->ctx,
6943 cf->stream.len,
6944 cf->stream.offset.key);
6945 }
6946 }
6947 else {
6948 struct quic_frame *new_cf;
6949 struct buffer cf_buf;
6950
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01006951 new_cf = qc_frm_alloc(cf->type);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006952 if (!new_cf) {
6953 TRACE_ERROR("No memory for new STREAM frame", QUIC_EV_CONN_BCFRMS, qc);
6954 continue;
6955 }
6956
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006957 new_cf->stream.stream = cf->stream.stream;
6958 new_cf->stream.buf = cf->stream.buf;
6959 new_cf->stream.id = cf->stream.id;
Amaury Denoyelle1dac0182023-02-02 16:45:07 +01006960 new_cf->stream.offset = cf->stream.offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006961 new_cf->stream.len = dlen;
6962 new_cf->type |= QUIC_STREAM_FRAME_TYPE_LEN_BIT;
6963 /* FIN bit reset */
6964 new_cf->type &= ~QUIC_STREAM_FRAME_TYPE_FIN_BIT;
6965 new_cf->stream.data = cf->stream.data;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006966 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006967 if (cf->origin) {
6968 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
6969 /* This <cf> frame was duplicated */
6970 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
6971 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01006972 /* Detach this STREAM frame from its origin */
6973 LIST_DEL_INIT(&cf->ref);
6974 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006975 }
6976 LIST_APPEND(outlist, &new_cf->list);
6977 cf->type |= QUIC_STREAM_FRAME_TYPE_OFF_BIT;
6978 /* Consume <dlen> bytes of the current frame. */
6979 cf_buf = b_make(b_orig(cf->stream.buf),
6980 b_size(cf->stream.buf),
6981 (char *)cf->stream.data - b_orig(cf->stream.buf), 0);
6982 cf->stream.len -= dlen;
6983 cf->stream.offset.key += dlen;
6984 cf->stream.data = (unsigned char *)b_peek(&cf_buf, dlen);
6985
6986 /* Do not notify MUX on retransmission. */
6987 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
6988 qcc_streams_sent_done(new_cf->stream.stream->ctx,
6989 new_cf->stream.len,
6990 new_cf->stream.offset.key);
6991 }
6992 }
6993
6994 /* TODO the MUX is notified about the frame sending via
6995 * previous qcc_streams_sent_done call. However, the
6996 * sending can fail later, for example if the sendto
6997 * system call returns an error. As the MUX has been
6998 * notified, the transport layer is responsible to
6999 * bufferize and resent the announced data later.
7000 */
7001
7002 break;
7003
7004 default:
7005 flen = qc_frm_len(cf);
7006 BUG_ON(!flen);
7007 if (flen > room)
7008 continue;
7009
7010 *len += flen;
7011 room -= flen;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007012 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007013 LIST_APPEND(outlist, &cf->list);
7014 break;
7015 }
7016
7017 /* Successful status as soon as a frame could be built */
7018 ret = 1;
7019 }
7020
7021 leave:
7022 TRACE_LEAVE(QUIC_EV_CONN_BCFRMS, qc);
7023 return ret;
7024}
7025
7026/* Generate a CONNECTION_CLOSE frame for <qc> on <qel> encryption level. <out>
7027 * is used as return parameter and should be zero'ed by the caller.
7028 */
7029static void qc_build_cc_frm(struct quic_conn *qc, struct quic_enc_level *qel,
7030 struct quic_frame *out)
7031{
7032 /* TODO improve CONNECTION_CLOSE on Initial/Handshake encryption levels
7033 *
7034 * A CONNECTION_CLOSE frame should be sent in several packets with
7035 * different encryption levels depending on the client context. This is
7036 * to ensure that the client can decrypt it. See RFC 9000 10.2.3 for
7037 * more details on how to implement it.
7038 */
7039 TRACE_ENTER(QUIC_EV_CONN_BFRM, qc);
7040
7041
7042 if (qc->err.app) {
7043 if (unlikely(qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
7044 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
7045 /* RFC 9000 10.2.3. Immediate Close during the Handshake
7046 *
7047 * Sending a CONNECTION_CLOSE of type 0x1d in an Initial or Handshake
7048 * packet could expose application state or be used to alter application
7049 * state. A CONNECTION_CLOSE of type 0x1d MUST be replaced by a
7050 * CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or
7051 * Handshake packets. Otherwise, information about the application
7052 * state might be revealed. Endpoints MUST clear the value of the
7053 * Reason Phrase field and SHOULD use the APPLICATION_ERROR code when
7054 * converting to a CONNECTION_CLOSE of type 0x1c.
7055 */
7056 out->type = QUIC_FT_CONNECTION_CLOSE;
7057 out->connection_close.error_code = QC_ERR_APPLICATION_ERROR;
7058 out->connection_close.reason_phrase_len = 0;
7059 }
7060 else {
7061 out->type = QUIC_FT_CONNECTION_CLOSE_APP;
7062 out->connection_close.error_code = qc->err.code;
7063 }
7064 }
7065 else {
7066 out->type = QUIC_FT_CONNECTION_CLOSE;
7067 out->connection_close.error_code = qc->err.code;
7068 }
7069 TRACE_LEAVE(QUIC_EV_CONN_BFRM, qc);
7070
7071}
7072
7073/* This function builds a clear packet from <pkt> information (its type)
7074 * into a buffer with <pos> as position pointer and <qel> as QUIC TLS encryption
7075 * level for <conn> QUIC connection and <qel> as QUIC TLS encryption level,
7076 * filling the buffer with as much frames as possible from <frms> list of
7077 * prebuilt frames.
7078 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
7079 * reserved so that to ensure there is enough room to build this AEAD TAG after
7080 * having returned from this function.
7081 * This function also updates the value of <buf_pn> pointer to point to the packet
7082 * number field in this packet. <pn_len> will also have the packet number
7083 * length as value.
7084 *
7085 * Return 1 if succeeded (enough room to buile this packet), O if not.
7086 */
7087static int qc_do_build_pkt(unsigned char *pos, const unsigned char *end,
7088 size_t dglen, struct quic_tx_packet *pkt,
7089 int64_t pn, size_t *pn_len, unsigned char **buf_pn,
7090 int force_ack, int padding, int cc, int probe,
7091 struct quic_enc_level *qel, struct quic_conn *qc,
7092 const struct quic_version *ver, struct list *frms)
7093{
7094 unsigned char *beg, *payload;
7095 size_t len, len_sz, len_frms, padding_len;
7096 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
7097 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
7098 struct quic_frame cc_frm = { };
7099 size_t ack_frm_len, head_len;
7100 int64_t rx_largest_acked_pn;
7101 int add_ping_frm;
7102 struct list frm_list = LIST_HEAD_INIT(frm_list);
7103 struct quic_frame *cf;
7104 int must_ack, ret = 0;
7105 int nb_aepkts_since_last_ack;
7106
7107 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7108
7109 /* Length field value with CRYPTO frames if present. */
7110 len_frms = 0;
7111 beg = pos;
7112 /* When not probing, and no immediate close is required, reduce the size of this
7113 * buffer to respect the congestion controller window.
7114 * This size will be limited if we have ack-eliciting frames to send from <frms>.
7115 */
7116 if (!probe && !LIST_ISEMPTY(frms) && !cc) {
7117 size_t path_room;
7118
7119 path_room = quic_path_prep_data(qc->path);
7120 if (end - beg > path_room)
7121 end = beg + path_room;
7122 }
7123
7124 /* Ensure there is enough room for the TLS encryption tag and a zero token
7125 * length field if any.
7126 */
7127 if (end - pos < QUIC_TLS_TAG_LEN +
7128 (pkt->type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0))
7129 goto no_room;
7130
7131 end -= QUIC_TLS_TAG_LEN;
7132 rx_largest_acked_pn = qel->pktns->rx.largest_acked_pn;
7133 /* packet number length */
7134 *pn_len = quic_packet_number_length(pn, rx_largest_acked_pn);
7135 /* Build the header */
7136 if ((pkt->type == QUIC_PACKET_TYPE_SHORT &&
7137 !quic_build_packet_short_header(&pos, end, *pn_len, qc, qel->tls_ctx.flags)) ||
7138 (pkt->type != QUIC_PACKET_TYPE_SHORT &&
7139 !quic_build_packet_long_header(&pos, end, pkt->type, *pn_len, qc, ver)))
7140 goto no_room;
7141
7142 /* Encode the token length (0) for an Initial packet. */
7143 if (pkt->type == QUIC_PACKET_TYPE_INITIAL)
7144 *pos++ = 0;
7145 head_len = pos - beg;
7146 /* Build an ACK frame if required. */
7147 ack_frm_len = 0;
7148 nb_aepkts_since_last_ack = qel->pktns->rx.nb_aepkts_since_last_ack;
7149 must_ack = !qel->pktns->tx.pto_probe &&
7150 (force_ack || ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
7151 (LIST_ISEMPTY(frms) || nb_aepkts_since_last_ack >= QUIC_MAX_RX_AEPKTS_SINCE_LAST_ACK)));
7152 if (must_ack) {
7153 struct quic_arngs *arngs = &qel->pktns->rx.arngs;
7154 BUG_ON(eb_is_empty(&qel->pktns->rx.arngs.root));
7155 ack_frm.tx_ack.arngs = arngs;
7156 if (qel->pktns->flags & QUIC_FL_PKTNS_NEW_LARGEST_PN) {
7157 qel->pktns->tx.ack_delay =
7158 quic_compute_ack_delay_us(qel->pktns->rx.largest_time_received, qc);
7159 qel->pktns->flags &= ~QUIC_FL_PKTNS_NEW_LARGEST_PN;
7160 }
7161 ack_frm.tx_ack.ack_delay = qel->pktns->tx.ack_delay;
7162 /* XXX BE CAREFUL XXX : here we reserved at least one byte for the
7163 * smallest frame (PING) and <*pn_len> more for the packet number. Note
7164 * that from here, we do not know if we will have to send a PING frame.
7165 * This will be decided after having computed the ack-eliciting frames
7166 * to be added to this packet.
7167 */
7168 ack_frm_len = quic_ack_frm_reduce_sz(qc, &ack_frm, end - 1 - *pn_len - pos);
7169 if (!ack_frm_len)
7170 goto no_room;
7171 }
7172
7173 /* Length field value without the ack-eliciting frames. */
7174 len = ack_frm_len + *pn_len;
7175 len_frms = 0;
7176 if (!cc && !LIST_ISEMPTY(frms)) {
7177 ssize_t room = end - pos;
7178
7179 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7180 /* Initialize the length of the frames built below to <len>.
7181 * If any frame could be successfully built by qc_build_frms(),
7182 * we will have len_frms > len.
7183 */
7184 len_frms = len;
7185 if (!qc_build_frms(&frm_list, frms,
7186 end - pos, &len_frms, pos - beg, qel, qc)) {
7187 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7188 qc, NULL, NULL, &room);
7189 if (!ack_frm_len && !qel->pktns->tx.pto_probe)
7190 goto no_room;
7191 }
7192 }
7193
7194 /* Length (of the remaining data). Must not fail because, the buffer size
7195 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
7196 * for the encryption tag. It must be taken into an account for the length
7197 * of this packet.
7198 */
7199 if (len_frms)
7200 len = len_frms + QUIC_TLS_TAG_LEN;
7201 else
7202 len += QUIC_TLS_TAG_LEN;
7203 /* CONNECTION_CLOSE frame */
7204 if (cc) {
7205 qc_build_cc_frm(qc, qel, &cc_frm);
7206 len += qc_frm_len(&cc_frm);
7207 }
7208 add_ping_frm = 0;
7209 padding_len = 0;
7210 len_sz = quic_int_getsize(len);
7211 /* Add this packet size to <dglen> */
7212 dglen += head_len + len_sz + len;
7213 if (padding && dglen < QUIC_INITIAL_PACKET_MINLEN) {
7214 /* This is a maximum padding size */
7215 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7216 /* The length field value is of this packet is <len> + <padding_len>
7217 * the size of which may be greater than the initial computed size
7218 * <len_sz>. So, let's deduce the difference between these to packet
7219 * sizes from <padding_len>.
7220 */
7221 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7222 len += padding_len;
7223 }
7224 else if (LIST_ISEMPTY(&frm_list) || len_frms == len) {
7225 if (qel->pktns->tx.pto_probe) {
7226 /* If we cannot send a frame, we send a PING frame. */
7227 add_ping_frm = 1;
7228 len += 1;
7229 }
7230 /* If there is no frame at all to follow, add at least a PADDING frame. */
7231 if (!ack_frm_len && !cc)
7232 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
7233 }
7234
7235 if (pkt->type != QUIC_PACKET_TYPE_SHORT && !quic_enc_int(&pos, end, len))
7236 goto no_room;
7237
7238 /* Packet number field address. */
7239 *buf_pn = pos;
7240
7241 /* Packet number encoding. */
7242 if (!quic_packet_number_encode(&pos, end, pn, *pn_len))
7243 goto no_room;
7244
7245 /* payload building (ack-eliciting or not frames) */
7246 payload = pos;
7247 if (ack_frm_len) {
7248 if (!qc_build_frm(&pos, end, &ack_frm, pkt, qc))
7249 goto no_room;
7250
7251 pkt->largest_acked_pn = quic_pktns_get_largest_acked_pn(qel->pktns);
7252 pkt->flags |= QUIC_FL_TX_PACKET_ACK;
7253 }
7254
7255 /* Ack-eliciting frames */
7256 if (!LIST_ISEMPTY(&frm_list)) {
7257 struct quic_frame *tmp_cf;
7258 list_for_each_entry_safe(cf, tmp_cf, &frm_list, list) {
7259 if (!qc_build_frm(&pos, end, cf, pkt, qc)) {
7260 ssize_t room = end - pos;
7261 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7262 qc, NULL, NULL, &room);
7263 /* Note that <cf> was added from <frms> to <frm_list> list by
7264 * qc_build_frms().
7265 */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007266 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007267 LIST_INSERT(frms, &cf->list);
7268 continue;
7269 }
7270
7271 quic_tx_packet_refinc(pkt);
7272 cf->pkt = pkt;
7273 }
7274 }
7275
7276 /* Build a PING frame if needed. */
7277 if (add_ping_frm) {
7278 frm.type = QUIC_FT_PING;
7279 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7280 goto no_room;
7281 }
7282
7283 /* Build a CONNECTION_CLOSE frame if needed. */
7284 if (cc) {
7285 if (!qc_build_frm(&pos, end, &cc_frm, pkt, qc))
7286 goto no_room;
7287
7288 pkt->flags |= QUIC_FL_TX_PACKET_CC;
7289 }
7290
7291 /* Build a PADDING frame if needed. */
7292 if (padding_len) {
7293 frm.type = QUIC_FT_PADDING;
7294 frm.padding.len = padding_len;
7295 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7296 goto no_room;
7297 }
7298
7299 if (pos == payload) {
7300 /* No payload was built because of congestion control */
7301 TRACE_DEVEL("limited by congestion control", QUIC_EV_CONN_TXPKT, qc);
7302 goto no_room;
7303 }
7304
7305 /* If this packet is ack-eliciting and we are probing let's
7306 * decrement the PTO probe counter.
7307 */
7308 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING &&
7309 qel->pktns->tx.pto_probe)
7310 qel->pktns->tx.pto_probe--;
7311
7312 pkt->len = pos - beg;
7313 LIST_SPLICE(&pkt->frms, &frm_list);
7314
7315 ret = 1;
7316 TRACE_DEVEL("Packet ack-eliciting frames", QUIC_EV_CONN_TXPKT, qc, pkt);
7317 leave:
7318 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7319 return ret;
7320
7321 no_room:
7322 /* Replace the pre-built frames which could not be add to this packet */
7323 LIST_SPLICE(frms, &frm_list);
7324 TRACE_DEVEL("Remaining ack-eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7325 goto leave;
7326}
7327
7328static inline void quic_tx_packet_init(struct quic_tx_packet *pkt, int type)
7329{
7330 pkt->type = type;
7331 pkt->len = 0;
7332 pkt->in_flight_len = 0;
7333 pkt->pn_node.key = (uint64_t)-1;
7334 LIST_INIT(&pkt->frms);
7335 pkt->time_sent = TICK_ETERNITY;
7336 pkt->next = NULL;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01007337 pkt->prev = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007338 pkt->largest_acked_pn = -1;
7339 pkt->flags = 0;
7340 pkt->refcnt = 0;
7341}
7342
7343/* Build a packet into <buf> packet buffer with <pkt_type> as packet
7344 * type for <qc> QUIC connection from <qel> encryption level from <frms> list
7345 * of prebuilt frames.
7346 *
7347 * Return -2 if the packet could not be allocated or encrypted for any reason,
7348 * -1 if there was not enough room to build a packet.
7349 * XXX NOTE XXX
7350 * If you provide provide qc_build_pkt() with a big enough buffer to build a packet as big as
7351 * possible (to fill an MTU), the unique reason why this function may fail is the congestion
7352 * control window limitation.
7353 */
7354static struct quic_tx_packet *qc_build_pkt(unsigned char **pos,
7355 const unsigned char *buf_end,
7356 struct quic_enc_level *qel,
7357 struct quic_tls_ctx *tls_ctx, struct list *frms,
7358 struct quic_conn *qc, const struct quic_version *ver,
7359 size_t dglen, int pkt_type, int force_ack,
7360 int padding, int probe, int cc, int *err)
7361{
7362 struct quic_tx_packet *ret_pkt = NULL;
7363 /* The pointer to the packet number field. */
7364 unsigned char *buf_pn;
7365 unsigned char *beg, *end, *payload;
7366 int64_t pn;
7367 size_t pn_len, payload_len, aad_len;
7368 struct quic_tx_packet *pkt;
7369
7370 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc, NULL, qel);
7371 *err = 0;
7372 pkt = pool_alloc(pool_head_quic_tx_packet);
7373 if (!pkt) {
7374 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_TXPKT, qc);
7375 *err = -2;
7376 goto err;
7377 }
7378
7379 quic_tx_packet_init(pkt, pkt_type);
7380 beg = *pos;
7381 pn_len = 0;
7382 buf_pn = NULL;
7383
7384 pn = qel->pktns->tx.next_pn + 1;
7385 if (!qc_do_build_pkt(*pos, buf_end, dglen, pkt, pn, &pn_len, &buf_pn,
7386 force_ack, padding, cc, probe, qel, qc, ver, frms)) {
7387 // trace already emitted by function above
7388 *err = -1;
7389 goto err;
7390 }
7391
7392 end = beg + pkt->len;
7393 payload = buf_pn + pn_len;
7394 payload_len = end - payload;
7395 aad_len = payload - beg;
7396
7397 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc)) {
7398 // trace already emitted by function above
7399 *err = -2;
7400 goto err;
7401 }
7402
7403 end += QUIC_TLS_TAG_LEN;
7404 pkt->len += QUIC_TLS_TAG_LEN;
7405 if (!quic_apply_header_protection(qc, beg, buf_pn, pn_len, tls_ctx)) {
7406 // trace already emitted by function above
7407 *err = -2;
7408 goto err;
7409 }
7410
7411 /* Consume a packet number */
7412 qel->pktns->tx.next_pn++;
7413 qc->tx.prep_bytes += pkt->len;
7414 if (qc->tx.prep_bytes >= 3 * qc->rx.bytes && !quic_peer_validated_addr(qc)) {
7415 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
7416 TRACE_PROTO("anti-amplification limit reached", QUIC_EV_CONN_TXPKT, qc);
7417 }
7418 /* Now that a correct packet is built, let us consume <*pos> buffer. */
7419 *pos = end;
7420 /* Attach the built packet to its tree. */
7421 pkt->pn_node.key = pn;
7422 /* Set the packet in fligth length for in flight packet only. */
7423 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
7424 pkt->in_flight_len = pkt->len;
7425 qc->path->prep_in_flight += pkt->len;
7426 }
7427 /* Always reset this flags */
7428 qc->flags &= ~QUIC_FL_CONN_IMMEDIATE_CLOSE;
7429 if (pkt->flags & QUIC_FL_TX_PACKET_ACK) {
7430 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
7431 qel->pktns->rx.nb_aepkts_since_last_ack = 0;
7432 }
7433
7434 pkt->pktns = qel->pktns;
7435
7436 ret_pkt = pkt;
7437 leave:
7438 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc, ret_pkt);
7439 return ret_pkt;
7440
7441 err:
7442 /* TODO: what about the frames which have been built
7443 * for this packet.
7444 */
7445 free_quic_tx_packet(qc, pkt);
7446 goto leave;
7447}
7448
7449
7450static void __quic_conn_init(void)
7451{
7452 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
7453}
7454INITCALL0(STG_REGISTER, __quic_conn_init);
7455
7456static void __quic_conn_deinit(void)
7457{
7458 BIO_meth_free(ha_quic_meth);
7459}
7460REGISTER_POST_DEINIT(__quic_conn_deinit);
7461
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007462/* Handle a new <dgram> received. Parse each QUIC packets and copied their
7463 * content to a quic-conn instance. The datagram content can be released after
7464 * this function.
7465 *
7466 * If datagram has been received on a quic-conn owned FD, <from_qc> must be set
7467 * to the connection instance. <li> is the attached listener. The caller is
7468 * responsible to ensure that the first packet is destined to this connection
7469 * by comparing CIDs.
7470 *
7471 * If datagram has been received on a receiver FD, <from_qc> will be NULL. This
7472 * function will thus retrieve the connection from the CID tree or allocate a
7473 * new one if possible. <li> is the listener attached to the receiver.
7474 *
7475 * Returns 0 on success else non-zero. If an error happens, some packets from
7476 * the datagram may not have been parsed.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007477 */
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007478int quic_dgram_parse(struct quic_dgram *dgram, struct quic_conn *from_qc,
7479 struct listener *li)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007480{
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007481 struct quic_rx_packet *pkt;
7482 struct quic_conn *qc = NULL;
7483 unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007484 struct list *tasklist_head = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007485
7486 TRACE_ENTER(QUIC_EV_CONN_LPKT);
7487
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007488 pos = dgram->buf;
7489 end = pos + dgram->len;
7490 do {
7491 /* TODO replace zalloc -> alloc. */
7492 pkt = pool_zalloc(pool_head_quic_rx_packet);
7493 if (!pkt) {
7494 TRACE_ERROR("RX packet allocation failed", QUIC_EV_CONN_LPKT);
7495 goto err;
7496 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007497
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007498 pkt->version = NULL;
7499 pkt->pn_offset = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007500
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007501 /* Set flag if pkt is the first one in dgram. */
7502 if (pos == dgram->buf)
7503 pkt->flags |= QUIC_FL_RX_PACKET_DGRAM_FIRST;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007504
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007505 LIST_INIT(&pkt->qc_rx_pkt_list);
7506 pkt->time_received = now_ms;
7507 quic_rx_packet_refinc(pkt);
7508 if (quic_rx_pkt_parse(pkt, pos, end, dgram, li))
7509 goto next;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007510
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007511 /* Search quic-conn instance for first packet of the datagram.
7512 * quic_rx_packet_parse() is responsible to discard packets
7513 * with different DCID as the first one in the same datagram.
7514 */
7515 if (!qc) {
7516 qc = from_qc ? from_qc : quic_rx_pkt_retrieve_conn(pkt, dgram, li);
7517 /* qc is NULL if receiving a non Initial packet for an
7518 * unknown connection.
7519 */
7520 if (!qc) {
Amaury Denoyelle98289692022-10-19 15:37:44 +02007521 /* Skip the entire datagram. */
7522 pkt->len = end - pos;
7523 goto next;
7524 }
7525
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007526 dgram->qc = qc;
7527 }
Amaury Denoyelle98289692022-10-19 15:37:44 +02007528
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007529 if (qc_rx_check_closing(qc, pkt)) {
7530 /* Skip the entire datagram. */
7531 pkt->len = end - pos;
7532 goto next;
7533 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007534
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007535 /* Detect QUIC connection migration. */
Frédéric Lécaillef6769542023-01-12 10:36:26 +01007536 if (ipcmp(&qc->peer_addr, &dgram->saddr, 1)) {
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007537 if (qc_handle_conn_migration(qc, &dgram->saddr, &dgram->daddr)) {
7538 /* Skip the entire datagram. */
7539 TRACE_ERROR("error during connection migration, datagram dropped", QUIC_EV_CONN_LPKT, qc);
7540 pkt->len = end - pos;
7541 goto next;
7542 }
7543 }
7544
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007545 qc_rx_pkt_handle(qc, pkt, dgram, pos, &tasklist_head);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007546
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007547 next:
7548 pos += pkt->len;
7549 quic_rx_packet_refdec(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007550
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007551 /* Free rejected packets */
7552 if (!pkt->refcnt) {
7553 BUG_ON(LIST_INLIST(&pkt->qc_rx_pkt_list));
7554 pool_free(pool_head_quic_rx_packet, pkt);
7555 }
7556 } while (pos < end);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007557
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007558 /* Increasing the received bytes counter by the UDP datagram length
7559 * if this datagram could be associated to a connection.
7560 */
7561 if (dgram->qc)
7562 dgram->qc->rx.bytes += dgram->len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007563
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007564 /* This must never happen. */
7565 BUG_ON(pos > end);
7566 BUG_ON(pos < end || pos > dgram->buf + dgram->len);
7567 /* Mark this datagram as consumed */
7568 HA_ATOMIC_STORE(&dgram->buf, NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007569
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007570 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
7571 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007572
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007573 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007574 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007575 return -1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007576}
7577
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01007578/* Check if connection ID <dcid> of length <dcid_len> belongs to <qc> local
7579 * CIDs. This can be used to determine if a datagram is addressed to the right
7580 * connection instance.
7581 *
7582 * Returns a boolean value.
7583 */
7584int qc_check_dcid(struct quic_conn *qc, unsigned char *dcid, size_t dcid_len)
7585{
7586 struct ebmb_node *node;
7587 struct quic_connection_id *id;
7588
7589 /* For ODCID, address is concatenated to it after qc.odcid.len so this
7590 * comparison is safe.
7591 */
7592 if ((qc->scid.len == dcid_len &&
7593 memcmp(qc->scid.data, dcid, dcid_len) == 0) ||
7594 (qc->odcid.len == dcid_len &&
Frédéric Lécaille07846cb2023-02-13 16:14:24 +01007595 memcmp(qc->odcid.data, dcid, dcid_len) == 0)) {
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01007596 return 1;
7597 }
7598
7599 node = ebmb_lookup(&quic_dghdlrs[tid].cids, dcid, dcid_len);
7600 if (node) {
7601 id = ebmb_entry(node, struct quic_connection_id, node);
7602 if (qc == id->qc)
7603 return 1;
7604 }
7605
7606 return 0;
7607}
7608
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007609/* Retrieve the DCID from a QUIC datagram or packet with <buf> as first octet.
7610 * Returns 1 if succeeded, 0 if not.
7611 */
7612int quic_get_dgram_dcid(unsigned char *buf, const unsigned char *end,
7613 unsigned char **dcid, size_t *dcid_len)
7614{
7615 int ret = 0, long_header;
7616 size_t minlen, skip;
7617
7618 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
7619
7620 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
7621 TRACE_PROTO("fixed bit not set", QUIC_EV_CONN_RXPKT);
7622 goto err;
7623 }
7624
7625 long_header = *buf & QUIC_PACKET_LONG_HEADER_BIT;
7626 minlen = long_header ? QUIC_LONG_PACKET_MINLEN :
7627 QUIC_SHORT_PACKET_MINLEN + QUIC_HAP_CID_LEN + QUIC_TLS_TAG_LEN;
7628 skip = long_header ? QUIC_LONG_PACKET_DCID_OFF : QUIC_SHORT_PACKET_DCID_OFF;
7629 if (end - buf < minlen)
7630 goto err;
7631
7632 buf += skip;
7633 *dcid_len = long_header ? *buf++ : QUIC_HAP_CID_LEN;
7634 if (*dcid_len > QUIC_CID_MAXLEN || end - buf <= *dcid_len)
7635 goto err;
7636
7637 *dcid = buf;
7638
7639 ret = 1;
7640 leave:
7641 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
7642 return ret;
7643
7644 err:
7645 TRACE_PROTO("wrong datagram", QUIC_EV_CONN_RXPKT);
7646 goto leave;
7647}
7648
7649/* Notify the MUX layer if alive about an imminent close of <qc>. */
7650void qc_notify_close(struct quic_conn *qc)
7651{
7652 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
7653
7654 if (qc->flags & QUIC_FL_CONN_NOTIFY_CLOSE)
7655 goto leave;
7656
7657 qc->flags |= QUIC_FL_CONN_NOTIFY_CLOSE;
7658 /* wake up the MUX */
7659 if (qc->mux_state == QC_MUX_READY && qc->conn->mux->wake) {
7660 TRACE_STATE("connection closure notidfied to mux",
7661 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7662 qc->conn->mux->wake(qc->conn);
7663 }
7664 else
7665 TRACE_STATE("connection closure not notidfied to mux",
7666 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7667 leave:
7668 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
7669}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007670
7671
7672/* appctx context used by "show quic" command */
7673struct show_quic_ctx {
7674 unsigned int epoch;
7675 struct bref bref; /* back-reference to the quic-conn being dumped */
7676 unsigned int thr;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007677 int flags;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007678};
7679
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007680#define QC_CLI_FL_SHOW_ALL 0x1 /* show closing/draining connections */
7681
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007682static int cli_parse_show_quic(char **args, char *payload, struct appctx *appctx, void *private)
7683{
7684 struct show_quic_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7685
7686 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
7687 return 1;
7688
7689 ctx->epoch = _HA_ATOMIC_FETCH_ADD(&qc_epoch, 1);
7690 ctx->thr = 0;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007691 ctx->flags = 0;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007692
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01007693 if (*args[2] && strcmp(args[2], "all") == 0)
7694 ctx->flags |= QC_CLI_FL_SHOW_ALL;
7695
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007696 LIST_INIT(&ctx->bref.users);
7697
7698 return 0;
7699}
7700
7701static int cli_io_handler_dump_quic(struct appctx *appctx)
7702{
7703 struct show_quic_ctx *ctx = appctx->svcctx;
7704 struct stconn *sc = appctx_sc(appctx);
7705 struct quic_conn *qc;
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01007706 struct quic_enc_level *qel;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007707 struct eb64_node *node;
7708 struct qc_stream_desc *stream;
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01007709 char bufaddr[INET6_ADDRSTRLEN], bufport[6];
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01007710 int expire;
7711 unsigned char cid_len;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007712
7713 thread_isolate();
7714
7715 if (ctx->thr >= global.nbthread)
7716 goto done;
7717
7718 if (unlikely(sc_ic(sc)->flags & CF_SHUTW)) {
7719 /* If we're forced to shut down, we might have to remove our
7720 * reference to the last stream being dumped.
7721 */
7722 if (!LIST_ISEMPTY(&ctx->bref.users))
7723 LIST_DEL_INIT(&ctx->bref.users);
7724 goto done;
7725 }
7726
7727 chunk_reset(&trash);
7728
7729 if (!LIST_ISEMPTY(&ctx->bref.users)) {
7730 /* Remove show_quic_ctx from previous quic_conn instance. */
7731 LIST_DEL_INIT(&ctx->bref.users);
7732 }
7733 else if (!ctx->bref.ref) {
7734 /* First invocation. */
7735 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
7736 }
7737
7738 while (1) {
7739 int done = 0;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007740 int i;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007741
7742 if (ctx->bref.ref == &ha_thread_ctx[ctx->thr].quic_conns) {
7743 done = 1;
7744 }
7745 else {
7746 qc = LIST_ELEM(ctx->bref.ref, struct quic_conn *, el_th_ctx);
7747 if ((int)(qc->qc_epoch - ctx->epoch) > 0)
7748 done = 1;
7749 }
7750
7751 if (done) {
7752 ++ctx->thr;
7753 if (ctx->thr >= global.nbthread)
7754 break;
7755 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
7756 continue;
7757 }
7758
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01007759 if (!(ctx->flags & QC_CLI_FL_SHOW_ALL) &&
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007760 qc->flags & (QUIC_FL_CONN_CLOSING|QUIC_FL_CONN_DRAINING)) {
7761 ctx->bref.ref = qc->el_th_ctx.n;
7762 continue;
7763 }
7764
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01007765 /* CIDs */
7766 chunk_appendf(&trash, "* %p[%02u]: scid=", qc, qc->tid);
7767 for (cid_len = 0; cid_len < qc->scid.len; ++cid_len)
7768 chunk_appendf(&trash, "%02x", qc->scid.data[cid_len]);
7769 while (cid_len++ < 20)
7770 chunk_appendf(&trash, "..");
7771
7772 chunk_appendf(&trash, " dcid=");
7773 for (cid_len = 0; cid_len < qc->dcid.len; ++cid_len)
7774 chunk_appendf(&trash, "%02x", qc->dcid.data[cid_len]);
7775 while (cid_len++ < 20)
7776 chunk_appendf(&trash, "..");
7777
7778 chunk_appendf(&trash, "\n");
7779
7780 /* Connection state */
7781 if (qc->flags & QUIC_FL_CONN_CLOSING)
7782 chunk_appendf(&trash, " st=closing ");
7783 else if (qc->flags & QUIC_FL_CONN_DRAINING)
7784 chunk_appendf(&trash, " st=draining ");
7785 else if (qc->state < QUIC_HS_ST_CONFIRMED)
7786 chunk_appendf(&trash, " st=handshake ");
7787 else
7788 chunk_appendf(&trash, " st=opened ");
7789
7790 if (qc->mux_state == QC_MUX_NULL)
7791 chunk_appendf(&trash, "mux=null ");
7792 else if (qc->mux_state == QC_MUX_READY)
7793 chunk_appendf(&trash, "mux=ready ");
7794 else
7795 chunk_appendf(&trash, "mux=released ");
7796
7797 expire = qc->idle_timer_task->expire;
7798 chunk_appendf(&trash, "expire=%02ds ",
7799 expire > now_ms ? (expire - now_ms) / 1000 : 0);
7800
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007801 chunk_appendf(&trash, "\n");
7802
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01007803 /* Socket */
7804 chunk_appendf(&trash, " fd=%d", qc->fd);
7805 if (qc->local_addr.ss_family == AF_INET ||
7806 qc->local_addr.ss_family == AF_INET6) {
7807 addr_to_str(&qc->local_addr, bufaddr, sizeof(bufaddr));
7808 port_to_str(&qc->local_addr, bufport, sizeof(bufport));
7809 chunk_appendf(&trash, " from=%s:%s", bufaddr, bufport);
7810
7811 addr_to_str(&qc->peer_addr, bufaddr, sizeof(bufaddr));
7812 port_to_str(&qc->peer_addr, bufport, sizeof(bufport));
7813 chunk_appendf(&trash, " to=%s:%s", bufaddr, bufport);
7814 }
7815
7816 chunk_appendf(&trash, "\n");
7817
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01007818 /* Encryption levels */
7819 qel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
7820 chunk_appendf(&trash, " [initl] rx.ackrng=%-6zu tx.inflight=%-6zu",
7821 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7822 qel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
7823 chunk_appendf(&trash, " [hndshk] rx.ackrng=%-6zu tx.inflight=%-6zu\n",
7824 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7825 qel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
7826 chunk_appendf(&trash, " [0-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
7827 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7828 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
7829 chunk_appendf(&trash, " [1-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
7830 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
7831
7832 chunk_appendf(&trash, "\n");
7833
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007834 /* Streams */
7835 node = eb64_first(&qc->streams_by_id);
7836 i = 0;
7837 while (node) {
7838 stream = eb64_entry(node, struct qc_stream_desc, by_id);
7839 node = eb64_next(node);
7840
Amaury Denoyellea9de25a2023-02-10 09:25:22 +01007841 chunk_appendf(&trash, " | stream=%-8llu", (unsigned long long)stream->by_id.key);
7842 chunk_appendf(&trash, " off=%-8llu ack=%-8llu",
7843 (unsigned long long)stream->buf_offset,
7844 (unsigned long long)stream->ack_offset);
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007845
7846 if (!(++i % 3)) {
7847 chunk_appendf(&trash, "\n");
7848 i = 0;
7849 }
7850 }
7851
7852 chunk_appendf(&trash, "\n");
7853
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007854 if (applet_putchk(appctx, &trash) == -1) {
7855 /* Register show_quic_ctx to quic_conn instance. */
7856 LIST_APPEND(&qc->back_refs, &ctx->bref.users);
7857 goto full;
7858 }
7859
7860 ctx->bref.ref = qc->el_th_ctx.n;
7861 }
7862
7863 done:
7864 thread_release();
7865 return 1;
7866
7867 full:
7868 thread_release();
7869 return 0;
7870}
7871
7872static void cli_release_show_quic(struct appctx *appctx)
7873{
7874 struct show_quic_ctx *ctx = appctx->svcctx;
7875
7876 if (ctx->thr < global.nbthread) {
7877 thread_isolate();
7878 if (!LIST_ISEMPTY(&ctx->bref.users))
7879 LIST_DEL_INIT(&ctx->bref.users);
7880 thread_release();
7881 }
7882}
7883
7884static struct cli_kw_list cli_kws = {{ }, {
7885 { { "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 +01007886 {{},}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007887}};
7888
7889INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
7890
7891static void init_quic()
7892{
7893 int thr;
7894
7895 for (thr = 0; thr < MAX_THREADS; ++thr)
7896 LIST_INIT(&ha_thread_ctx[thr].quic_conns);
7897}
7898INITCALL0(STG_INIT, init_quic);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007899
7900/*
7901 * Local variables:
7902 * c-indent-level: 8
7903 * c-basic-offset: 8
7904 * End:
7905 */