blob: 463b897515c5e62a7c141db18f9708deb8803a46 [file] [log] [blame]
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001/*
2 * QUIC protocol implementation. Lower layer with internal features implemented
3 * here such as QUIC encryption, idle timeout, acknowledgement and
4 * retransmission.
5 *
6 * Copyright 2020 HAProxy Technologies, Frederic Lecaille <flecaille@haproxy.com>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version
11 * 2 of the License, or (at your option) any later version.
12 *
13 */
14
15#include <haproxy/quic_conn.h>
16
17#define _GNU_SOURCE
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020018#include <stdio.h>
19#include <stdlib.h>
20
21#include <sys/socket.h>
22#include <sys/stat.h>
23#include <sys/types.h>
24
25#include <netinet/tcp.h>
26
27#include <import/ebmbtree.h>
28
29#include <haproxy/buf-t.h>
30#include <haproxy/compat.h>
31#include <haproxy/api.h>
32#include <haproxy/debug.h>
33#include <haproxy/tools.h>
34#include <haproxy/ticks.h>
35
Amaury Denoyelle15c74702023-02-01 10:18:26 +010036#include <haproxy/applet-t.h>
37#include <haproxy/cli.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020038#include <haproxy/connection.h>
39#include <haproxy/fd.h>
40#include <haproxy/freq_ctr.h>
41#include <haproxy/global.h>
42#include <haproxy/h3.h>
43#include <haproxy/hq_interop.h>
44#include <haproxy/log.h>
45#include <haproxy/mux_quic.h>
46#include <haproxy/ncbuf.h>
47#include <haproxy/pipe.h>
48#include <haproxy/proxy.h>
49#include <haproxy/quic_cc.h>
50#include <haproxy/quic_frame.h>
51#include <haproxy/quic_enc.h>
52#include <haproxy/quic_loss.h>
53#include <haproxy/quic_sock.h>
54#include <haproxy/quic_stats.h>
55#include <haproxy/quic_stream.h>
56#include <haproxy/quic_tp.h>
57#include <haproxy/cbuf.h>
58#include <haproxy/proto_quic.h>
59#include <haproxy/quic_tls.h>
60#include <haproxy/ssl_sock.h>
61#include <haproxy/task.h>
Amaury Denoyelle15c74702023-02-01 10:18:26 +010062#include <haproxy/thread.h>
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020063#include <haproxy/trace.h>
64
Amaury Denoyelle15c74702023-02-01 10:18:26 +010065/* incremented by each "show quic". */
66static unsigned int qc_epoch = 0;
67
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020068/* list of supported QUIC versions by this implementation */
69const struct quic_version quic_versions[] = {
70 {
71 .num = QUIC_PROTOCOL_VERSION_DRAFT_29,
72 .initial_salt = initial_salt_draft_29,
73 .initial_salt_len = sizeof initial_salt_draft_29,
74 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V1,
75 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V1) - 1,
76 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V1,
77 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V1) - 1,
78 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V1,
79 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V1) - 1,
80 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V1,
81 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V1) - 1,
82 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_DRAFT,
83 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_DRAFT,
84 },
85 {
86 .num = QUIC_PROTOCOL_VERSION_1,
87 .initial_salt = initial_salt_v1,
88 .initial_salt_len = sizeof initial_salt_v1,
89 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V1,
90 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V1) - 1,
91 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V1,
92 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V1) - 1,
93 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V1,
94 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V1) - 1,
95 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V1,
96 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V1) - 1,
97 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V1,
98 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V1,
99 },
100 {
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +0100101 .num = QUIC_PROTOCOL_VERSION_2,
102 .initial_salt = initial_salt_v2,
103 .initial_salt_len = sizeof initial_salt_v2,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200104 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V2,
105 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V2) - 1,
106 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V2,
107 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V2) - 1,
108 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V2,
109 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V2) - 1,
110 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V2,
111 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V2) - 1,
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +0100112 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V2,
113 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V2,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200114 },
115};
116
117/* The total number of supported versions */
118const size_t quic_versions_nb = sizeof quic_versions / sizeof *quic_versions;
119/* Listener only preferred version */
120const struct quic_version *preferred_version;
121
122/* trace source and events */
123static void quic_trace(enum trace_level level, uint64_t mask, \
124 const struct trace_source *src,
125 const struct ist where, const struct ist func,
126 const void *a1, const void *a2, const void *a3, const void *a4);
127
128static const struct trace_event quic_trace_events[] = {
129 { .mask = QUIC_EV_CONN_NEW, .name = "new_conn", .desc = "new QUIC connection" },
130 { .mask = QUIC_EV_CONN_INIT, .name = "new_conn_init", .desc = "new QUIC connection initialization" },
131 { .mask = QUIC_EV_CONN_ISEC, .name = "init_secs", .desc = "initial secrets derivation" },
132 { .mask = QUIC_EV_CONN_RSEC, .name = "read_secs", .desc = "read secrets derivation" },
133 { .mask = QUIC_EV_CONN_WSEC, .name = "write_secs", .desc = "write secrets derivation" },
134 { .mask = QUIC_EV_CONN_LPKT, .name = "lstnr_packet", .desc = "new listener received packet" },
135 { .mask = QUIC_EV_CONN_SPKT, .name = "srv_packet", .desc = "new server received packet" },
136 { .mask = QUIC_EV_CONN_ENCPKT, .name = "enc_hdshk_pkt", .desc = "handhshake packet encryption" },
137 { .mask = QUIC_EV_CONN_TXPKT, .name = "tx_pkt", .desc = "TX packet" },
138 { .mask = QUIC_EV_CONN_PAPKT, .name = "phdshk_apkt", .desc = "post handhshake application packet preparation" },
139 { .mask = QUIC_EV_CONN_PAPKTS, .name = "phdshk_apkts", .desc = "post handhshake application packets preparation" },
140 { .mask = QUIC_EV_CONN_IO_CB, .name = "qc_io_cb", .desc = "QUIC conn. I/O processing" },
141 { .mask = QUIC_EV_CONN_RMHP, .name = "rm_hp", .desc = "Remove header protection" },
142 { .mask = QUIC_EV_CONN_PRSHPKT, .name = "parse_hpkt", .desc = "parse handshake packet" },
143 { .mask = QUIC_EV_CONN_PRSAPKT, .name = "parse_apkt", .desc = "parse application packet" },
144 { .mask = QUIC_EV_CONN_PRSFRM, .name = "parse_frm", .desc = "parse frame" },
145 { .mask = QUIC_EV_CONN_PRSAFRM, .name = "parse_ack_frm", .desc = "parse ACK frame" },
146 { .mask = QUIC_EV_CONN_BFRM, .name = "build_frm", .desc = "build frame" },
147 { .mask = QUIC_EV_CONN_PHPKTS, .name = "phdshk_pkts", .desc = "handhshake packets preparation" },
148 { .mask = QUIC_EV_CONN_TRMHP, .name = "rm_hp_try", .desc = "header protection removing try" },
149 { .mask = QUIC_EV_CONN_ELRMHP, .name = "el_rm_hp", .desc = "handshake enc. level header protection removing" },
150 { .mask = QUIC_EV_CONN_RXPKT, .name = "rx_pkt", .desc = "RX packet" },
151 { .mask = QUIC_EV_CONN_SSLDATA, .name = "ssl_provide_data", .desc = "CRYPTO data provision to TLS stack" },
152 { .mask = QUIC_EV_CONN_RXCDATA, .name = "el_treat_rx_cfrms",.desc = "enc. level RX CRYPTO frames processing"},
153 { .mask = QUIC_EV_CONN_ADDDATA, .name = "add_hdshk_data", .desc = "TLS stack ->add_handshake_data() call"},
154 { .mask = QUIC_EV_CONN_FFLIGHT, .name = "flush_flight", .desc = "TLS stack ->flush_flight() call"},
155 { .mask = QUIC_EV_CONN_SSLALERT, .name = "send_alert", .desc = "TLS stack ->send_alert() call"},
156 { .mask = QUIC_EV_CONN_RTTUPDT, .name = "rtt_updt", .desc = "RTT sampling" },
157 { .mask = QUIC_EV_CONN_SPPKTS, .name = "sppkts", .desc = "send prepared packets" },
158 { .mask = QUIC_EV_CONN_PKTLOSS, .name = "pktloss", .desc = "detect packet loss" },
159 { .mask = QUIC_EV_CONN_STIMER, .name = "stimer", .desc = "set timer" },
160 { .mask = QUIC_EV_CONN_PTIMER, .name = "ptimer", .desc = "process timer" },
161 { .mask = QUIC_EV_CONN_SPTO, .name = "spto", .desc = "set PTO" },
162 { .mask = QUIC_EV_CONN_BCFRMS, .name = "bcfrms", .desc = "build CRYPTO data frames" },
163 { .mask = QUIC_EV_CONN_XPRTSEND, .name = "xprt_send", .desc = "sending XRPT subscription" },
164 { .mask = QUIC_EV_CONN_XPRTRECV, .name = "xprt_recv", .desc = "receiving XRPT subscription" },
165 { .mask = QUIC_EV_CONN_FREED, .name = "conn_freed", .desc = "releasing conn. memory" },
166 { .mask = QUIC_EV_CONN_CLOSE, .name = "conn_close", .desc = "closing conn." },
167 { .mask = QUIC_EV_CONN_ACKSTRM, .name = "ack_strm", .desc = "STREAM ack."},
168 { .mask = QUIC_EV_CONN_FRMLIST, .name = "frm_list", .desc = "frame list"},
169 { .mask = QUIC_EV_STATELESS_RST, .name = "stateless_reset", .desc = "stateless reset sent"},
170 { .mask = QUIC_EV_TRANSP_PARAMS, .name = "transport_params", .desc = "transport parameters"},
171 { .mask = QUIC_EV_CONN_IDLE_TIMER, .name = "idle_timer", .desc = "idle timer task"},
172 { .mask = QUIC_EV_CONN_SUB, .name = "xprt_sub", .desc = "RX/TX subcription or unsubscription to QUIC xprt"},
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200173 { .mask = QUIC_EV_CONN_RCV, .name = "conn_recv", .desc = "RX on connection" },
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200174 { /* end */ }
175};
176
177static const struct name_desc quic_trace_lockon_args[4] = {
178 /* arg1 */ { /* already used by the connection */ },
179 /* arg2 */ { .name="quic", .desc="QUIC transport" },
180 /* arg3 */ { },
181 /* arg4 */ { }
182};
183
184static const struct name_desc quic_trace_decoding[] = {
185#define QUIC_VERB_CLEAN 1
186 { .name="clean", .desc="only user-friendly stuff, generally suitable for level \"user\"" },
187 { /* end */ }
188};
189
190
191struct trace_source trace_quic = {
192 .name = IST("quic"),
193 .desc = "QUIC xprt",
194 .arg_def = TRC_ARG1_QCON, /* TRACE()'s first argument is always a quic_conn */
195 .default_cb = quic_trace,
196 .known_events = quic_trace_events,
197 .lockon_args = quic_trace_lockon_args,
198 .decoding = quic_trace_decoding,
199 .report_events = ~0, /* report everything by default */
200};
201
202#define TRACE_SOURCE &trace_quic
203INITCALL1(STG_REGISTER, trace_register_source, TRACE_SOURCE);
204
205static BIO_METHOD *ha_quic_meth;
206
207DECLARE_POOL(pool_head_quic_tx_ring, "quic_tx_ring", QUIC_TX_RING_BUFSZ);
208DECLARE_POOL(pool_head_quic_conn_rxbuf, "quic_conn_rxbuf", QUIC_CONN_RX_BUFSZ);
209DECLARE_STATIC_POOL(pool_head_quic_conn_ctx,
210 "quic_conn_ctx", sizeof(struct ssl_sock_ctx));
211DECLARE_STATIC_POOL(pool_head_quic_conn, "quic_conn", sizeof(struct quic_conn));
212DECLARE_POOL(pool_head_quic_connection_id,
213 "quic_connnection_id", sizeof(struct quic_connection_id));
214DECLARE_POOL(pool_head_quic_dgram, "quic_dgram", sizeof(struct quic_dgram));
215DECLARE_POOL(pool_head_quic_rx_packet, "quic_rx_packet", sizeof(struct quic_rx_packet));
216DECLARE_POOL(pool_head_quic_tx_packet, "quic_tx_packet", sizeof(struct quic_tx_packet));
217DECLARE_STATIC_POOL(pool_head_quic_rx_crypto_frm, "quic_rx_crypto_frm", sizeof(struct quic_rx_crypto_frm));
218DECLARE_STATIC_POOL(pool_head_quic_crypto_buf, "quic_crypto_buf", sizeof(struct quic_crypto_buf));
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +0200219DECLARE_STATIC_POOL(pool_head_quic_cstream, "quic_cstream", sizeof(struct quic_cstream));
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200220DECLARE_POOL(pool_head_quic_frame, "quic_frame", sizeof(struct quic_frame));
221DECLARE_STATIC_POOL(pool_head_quic_arng, "quic_arng", sizeof(struct quic_arng_node));
222
223static struct quic_tx_packet *qc_build_pkt(unsigned char **pos, const unsigned char *buf_end,
224 struct quic_enc_level *qel, struct quic_tls_ctx *ctx,
225 struct list *frms, struct quic_conn *qc,
226 const struct quic_version *ver, size_t dglen, int pkt_type,
227 int force_ack, int padding, int probe, int cc, int *err);
228struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state);
229static void qc_idle_timer_do_rearm(struct quic_conn *qc);
230static void qc_idle_timer_rearm(struct quic_conn *qc, int read);
231static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc);
232static int quic_conn_init_timer(struct quic_conn *qc);
233static int quic_conn_init_idle_timer_task(struct quic_conn *qc);
234
235/* Only for debug purpose */
236struct enc_debug_info {
237 unsigned char *payload;
238 size_t payload_len;
239 unsigned char *aad;
240 size_t aad_len;
241 uint64_t pn;
242};
243
244/* Initializes a enc_debug_info struct (only for debug purpose) */
245static inline void enc_debug_info_init(struct enc_debug_info *edi,
246 unsigned char *payload, size_t payload_len,
247 unsigned char *aad, size_t aad_len, uint64_t pn)
248{
249 edi->payload = payload;
250 edi->payload_len = payload_len;
251 edi->aad = aad;
252 edi->aad_len = aad_len;
253 edi->pn = pn;
254}
255
256/* Trace callback for QUIC.
257 * These traces always expect that arg1, if non-null, is of type connection.
258 */
259static void quic_trace(enum trace_level level, uint64_t mask, const struct trace_source *src,
260 const struct ist where, const struct ist func,
261 const void *a1, const void *a2, const void *a3, const void *a4)
262{
263 const struct quic_conn *qc = a1;
264
265 if (qc) {
266 const struct quic_tls_ctx *tls_ctx;
267
268 chunk_appendf(&trace_buf, " : qc@%p", qc);
269 if (mask & QUIC_EV_CONN_INIT) {
270 chunk_appendf(&trace_buf, "\n odcid");
271 quic_cid_dump(&trace_buf, &qc->odcid);
272 chunk_appendf(&trace_buf, "\n dcid");
273 quic_cid_dump(&trace_buf, &qc->dcid);
274 chunk_appendf(&trace_buf, "\n scid");
275 quic_cid_dump(&trace_buf, &qc->scid);
276 }
277
278 if (mask & QUIC_EV_TRANSP_PARAMS) {
279 const struct quic_transport_params *p = a2;
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100280
281 if (p)
282 quic_transport_params_dump(&trace_buf, qc, p);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200283 }
284
285 if (mask & QUIC_EV_CONN_ADDDATA) {
286 const enum ssl_encryption_level_t *level = a2;
287 const size_t *len = a3;
288
289 if (level) {
290 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
291
292 chunk_appendf(&trace_buf, " el=%c(%d)", quic_enc_level_char(lvl), lvl);
293 }
294 if (len)
295 chunk_appendf(&trace_buf, " len=%llu", (unsigned long long)*len);
296 }
297 if ((mask & QUIC_EV_CONN_ISEC) && qc) {
298 /* Initial read & write secrets. */
299 enum quic_tls_enc_level level = QUIC_TLS_ENC_LEVEL_INITIAL;
300 const unsigned char *rx_sec = a2;
301 const unsigned char *tx_sec = a3;
302
303 tls_ctx = &qc->els[level].tls_ctx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200304 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(level));
305 if (rx_sec)
306 quic_tls_secret_hexdump(&trace_buf, rx_sec, 32);
307 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
308 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(level));
309 if (tx_sec)
310 quic_tls_secret_hexdump(&trace_buf, tx_sec, 32);
311 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200312 }
313 if (mask & (QUIC_EV_CONN_RSEC|QUIC_EV_CONN_RWSEC)) {
314 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200315
316 if (level) {
317 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
318
319 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200320 if (quic_tls_has_rx_sec(&qc->els[lvl])) {
321 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200322 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200323 }
324 else
325 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200326 }
327 }
328
329 if (mask & (QUIC_EV_CONN_WSEC|QUIC_EV_CONN_RWSEC)) {
330 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200331
332 if (level) {
333 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
334
335 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200336 if (quic_tls_has_tx_sec(&qc->els[lvl])) {
337 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200338 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200339 }
340 else
341 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200342 }
343
344 }
345
346 if (mask & QUIC_EV_CONN_FRMLIST) {
347 const struct list *l = a2;
348
349 if (l) {
350 const struct quic_frame *frm;
351 list_for_each_entry(frm, l, list) {
352 chunk_appendf(&trace_buf, " frm@%p", frm);
353 chunk_frm_appendf(&trace_buf, frm);
354 }
355 }
356 }
357
358 if (mask & (QUIC_EV_CONN_TXPKT|QUIC_EV_CONN_PAPKT)) {
359 const struct quic_tx_packet *pkt = a2;
360 const struct quic_enc_level *qel = a3;
361 const ssize_t *room = a4;
362
363 if (qel) {
364 const struct quic_pktns *pktns = qel->pktns;
Frédéric Lécaille45400532023-02-13 18:39:19 +0100365 chunk_appendf(&trace_buf, " qel=%c pto_count=%d cwnd=%llu ppif=%lld pif=%llu "
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200366 "if=%llu pp=%u",
367 quic_enc_level_char_from_qel(qel, qc),
Frédéric Lécaille45400532023-02-13 18:39:19 +0100368 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200369 (unsigned long long)qc->path->cwnd,
370 (unsigned long long)qc->path->prep_in_flight,
371 (unsigned long long)qc->path->in_flight,
372 (unsigned long long)pktns->tx.in_flight,
373 pktns->tx.pto_probe);
374 }
375 if (pkt) {
376 const struct quic_frame *frm;
377 if (pkt->pn_node.key != (uint64_t)-1)
378 chunk_appendf(&trace_buf, " pn=%llu",(ull)pkt->pn_node.key);
379 list_for_each_entry(frm, &pkt->frms, list) {
380 chunk_appendf(&trace_buf, " frm@%p", frm);
381 chunk_frm_appendf(&trace_buf, frm);
382 }
383 }
384
385 if (room) {
386 chunk_appendf(&trace_buf, " room=%lld", (long long)*room);
387 chunk_appendf(&trace_buf, " dcid.len=%llu scid.len=%llu",
388 (unsigned long long)qc->dcid.len, (unsigned long long)qc->scid.len);
389 }
390 }
391
392 if (mask & QUIC_EV_CONN_IO_CB) {
393 const enum quic_handshake_state *state = a2;
394 const int *err = a3;
395
396 if (state)
397 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(*state));
398 if (err)
399 chunk_appendf(&trace_buf, " err=%s", ssl_error_str(*err));
400 }
401
402 if (mask & (QUIC_EV_CONN_TRMHP|QUIC_EV_CONN_ELRMHP|QUIC_EV_CONN_SPKT)) {
403 const struct quic_rx_packet *pkt = a2;
404 const unsigned long *pktlen = a3;
405 const SSL *ssl = a4;
406
407 if (pkt) {
408 chunk_appendf(&trace_buf, " pkt@%p", pkt);
409 if (pkt->type == QUIC_PACKET_TYPE_SHORT && pkt->data)
410 chunk_appendf(&trace_buf, " kp=%d",
411 !!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT));
412 chunk_appendf(&trace_buf, " el=%c",
413 quic_packet_type_enc_level_char(pkt->type));
414 if (pkt->pnl)
415 chunk_appendf(&trace_buf, " pnl=%u pn=%llu", pkt->pnl,
416 (unsigned long long)pkt->pn);
417 if (pkt->token_len)
418 chunk_appendf(&trace_buf, " toklen=%llu",
419 (unsigned long long)pkt->token_len);
420 if (pkt->aad_len)
421 chunk_appendf(&trace_buf, " aadlen=%llu",
422 (unsigned long long)pkt->aad_len);
423 chunk_appendf(&trace_buf, " flags=0x%x len=%llu",
424 pkt->flags, (unsigned long long)pkt->len);
425 }
426 if (pktlen)
427 chunk_appendf(&trace_buf, " (%ld)", *pktlen);
428 if (ssl) {
429 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
430 chunk_appendf(&trace_buf, " el=%c",
431 quic_enc_level_char(ssl_to_quic_enc_level(level)));
432 }
433 }
434
435 if (mask & (QUIC_EV_CONN_RXPKT|QUIC_EV_CONN_PRSHPKT|QUIC_EV_CONN_SSLDATA)) {
436 const struct quic_rx_packet *pkt = a2;
437 const struct quic_rx_crypto_frm *cf = a3;
438 const SSL *ssl = a4;
439
440 if (pkt)
441 chunk_appendf(&trace_buf, " pkt@%p el=%c pn=%llu", pkt,
442 quic_packet_type_enc_level_char(pkt->type),
443 (unsigned long long)pkt->pn);
444 if (cf)
445 chunk_appendf(&trace_buf, " cfoff=%llu cflen=%llu",
446 (unsigned long long)cf->offset_node.key,
447 (unsigned long long)cf->len);
448 if (ssl) {
449 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
450 chunk_appendf(&trace_buf, " rel=%c",
451 quic_enc_level_char(ssl_to_quic_enc_level(level)));
452 }
453
454 if (qc->err.code)
455 chunk_appendf(&trace_buf, " err_code=0x%llx", (ull)qc->err.code);
456 }
457
458 if (mask & (QUIC_EV_CONN_PRSFRM|QUIC_EV_CONN_BFRM)) {
459 const struct quic_frame *frm = a2;
460
461 if (frm)
462 chunk_appendf(&trace_buf, " %s", quic_frame_type_string(frm->type));
463 }
464
465 if (mask & QUIC_EV_CONN_PHPKTS) {
466 const struct quic_enc_level *qel = a2;
467
468 if (qel) {
469 const struct quic_pktns *pktns = qel->pktns;
470 chunk_appendf(&trace_buf,
Frédéric Lécaille45400532023-02-13 18:39:19 +0100471 " qel=%c state=%s ack?%d pto_count=%d cwnd=%llu ppif=%lld pif=%llu if=%llu pp=%u off=%llu",
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200472 quic_enc_level_char_from_qel(qel, qc),
473 quic_hdshk_state_str(qc->state),
474 !!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED),
Frédéric Lécaille45400532023-02-13 18:39:19 +0100475 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200476 (unsigned long long)qc->path->cwnd,
477 (unsigned long long)qc->path->prep_in_flight,
478 (unsigned long long)qc->path->in_flight,
479 (unsigned long long)pktns->tx.in_flight,
Amaury Denoyelle2f668f02022-11-18 15:24:08 +0100480 pktns->tx.pto_probe,
481 qel->cstream ? (unsigned long long)qel->cstream->rx.offset : 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200482 }
483 }
484
485 if (mask & QUIC_EV_CONN_ENCPKT) {
486 const struct enc_debug_info *edi = a2;
487
488 if (edi)
489 chunk_appendf(&trace_buf,
490 " payload=@%p payload_len=%llu"
491 " aad=@%p aad_len=%llu pn=%llu",
492 edi->payload, (unsigned long long)edi->payload_len,
493 edi->aad, (unsigned long long)edi->aad_len,
494 (unsigned long long)edi->pn);
495 }
496
497 if (mask & QUIC_EV_CONN_RMHP) {
498 const struct quic_rx_packet *pkt = a2;
499
500 if (pkt) {
501 const int *ret = a3;
502
503 chunk_appendf(&trace_buf, " pkt@%p", pkt);
504 if (ret && *ret)
505 chunk_appendf(&trace_buf, " pnl=%u pn=%llu",
506 pkt->pnl, (unsigned long long)pkt->pn);
507 }
508 }
509
510 if (mask & QUIC_EV_CONN_PRSAFRM) {
511 const struct quic_frame *frm = a2;
512 const unsigned long *val1 = a3;
513 const unsigned long *val2 = a4;
514
515 if (frm) {
516 chunk_appendf(&trace_buf, " frm@%p", frm);
517 chunk_frm_appendf(&trace_buf, frm);
518 }
519 if (val1)
520 chunk_appendf(&trace_buf, " %lu", *val1);
521 if (val2)
522 chunk_appendf(&trace_buf, "..%lu", *val2);
523 }
524
525 if (mask & QUIC_EV_CONN_ACKSTRM) {
526 const struct quic_stream *s = a2;
527 const struct qc_stream_desc *stream = a3;
528
529 if (s)
530 chunk_appendf(&trace_buf, " off=%llu len=%llu", (ull)s->offset.key, (ull)s->len);
531 if (stream)
532 chunk_appendf(&trace_buf, " ack_offset=%llu", (ull)stream->ack_offset);
533 }
534
535 if (mask & QUIC_EV_CONN_RTTUPDT) {
536 const unsigned int *rtt_sample = a2;
537 const unsigned int *ack_delay = a3;
538 const struct quic_loss *ql = a4;
539
540 if (rtt_sample)
541 chunk_appendf(&trace_buf, " rtt_sample=%ums", *rtt_sample);
542 if (ack_delay)
543 chunk_appendf(&trace_buf, " ack_delay=%ums", *ack_delay);
544 if (ql)
545 chunk_appendf(&trace_buf,
546 " srtt=%ums rttvar=%ums min_rtt=%ums",
547 ql->srtt >> 3, ql->rtt_var >> 2, ql->rtt_min);
548 }
549 if (mask & QUIC_EV_CONN_CC) {
550 const struct quic_cc_event *ev = a2;
551 const struct quic_cc *cc = a3;
552
553 if (a2)
554 quic_cc_event_trace(&trace_buf, ev);
555 if (a3)
556 quic_cc_state_trace(&trace_buf, cc);
557 }
558
559 if (mask & QUIC_EV_CONN_PKTLOSS) {
560 const struct quic_pktns *pktns = a2;
561 const struct list *lost_pkts = a3;
562
563 if (pktns) {
564 chunk_appendf(&trace_buf, " pktns=%s",
565 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
566 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H");
567 if (pktns->tx.loss_time)
568 chunk_appendf(&trace_buf, " loss_time=%dms",
569 TICKS_TO_MS(tick_remain(now_ms, pktns->tx.loss_time)));
570 }
571 if (lost_pkts && !LIST_ISEMPTY(lost_pkts)) {
572 struct quic_tx_packet *pkt;
573
574 chunk_appendf(&trace_buf, " lost_pkts:");
575 list_for_each_entry(pkt, lost_pkts, list)
576 chunk_appendf(&trace_buf, " %lu", (unsigned long)pkt->pn_node.key);
577 }
578 }
579
580 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_PTIMER|QUIC_EV_CONN_SPTO)) {
581 const struct quic_pktns *pktns = a2;
582 const int *duration = a3;
583 const uint64_t *ifae_pkts = a4;
584
585 if (ifae_pkts)
586 chunk_appendf(&trace_buf, " ifae_pkts=%llu",
587 (unsigned long long)*ifae_pkts);
588 if (pktns) {
589 chunk_appendf(&trace_buf, " pktns=%s pp=%d",
590 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
591 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
592 pktns->tx.pto_probe);
593 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_SPTO)) {
594 if (pktns->tx.in_flight)
595 chunk_appendf(&trace_buf, " if=%llu", (ull)pktns->tx.in_flight);
596 if (pktns->tx.loss_time)
597 chunk_appendf(&trace_buf, " loss_time=%dms",
598 TICKS_TO_MS(pktns->tx.loss_time - now_ms));
599 }
600 if (mask & QUIC_EV_CONN_SPTO) {
601 if (pktns->tx.time_of_last_eliciting)
602 chunk_appendf(&trace_buf, " tole=%dms",
603 TICKS_TO_MS(pktns->tx.time_of_last_eliciting - now_ms));
604 if (duration)
605 chunk_appendf(&trace_buf, " dur=%dms", TICKS_TO_MS(*duration));
606 }
607 }
608
609 if (!(mask & (QUIC_EV_CONN_SPTO|QUIC_EV_CONN_PTIMER)) && qc->timer_task) {
610 chunk_appendf(&trace_buf,
611 " expire=%dms", TICKS_TO_MS(qc->timer - now_ms));
612 }
613 }
614
615 if (mask & QUIC_EV_CONN_SPPKTS) {
616 const struct quic_tx_packet *pkt = a2;
617
Frédéric Lécaille45400532023-02-13 18:39:19 +0100618 chunk_appendf(&trace_buf, " pto_count=%d cwnd=%llu ppif=%llu pif=%llu",
619 qc->path->loss.pto_count,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200620 (unsigned long long)qc->path->cwnd,
621 (unsigned long long)qc->path->prep_in_flight,
622 (unsigned long long)qc->path->in_flight);
623 if (pkt) {
624 const struct quic_frame *frm;
625 chunk_appendf(&trace_buf, " pn=%lu(%s) iflen=%llu",
626 (unsigned long)pkt->pn_node.key,
627 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
628 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
629 (unsigned long long)pkt->in_flight_len);
630 chunk_appendf(&trace_buf, " rx.bytes=%llu tx.bytes=%llu",
631 (unsigned long long)qc->rx.bytes,
632 (unsigned long long)qc->tx.bytes);
633 list_for_each_entry(frm, &pkt->frms, list) {
634 chunk_appendf(&trace_buf, " frm@%p", frm);
635 chunk_frm_appendf(&trace_buf, frm);
636 }
Frédéric Lécaillebc09f742023-02-13 17:45:36 +0100637
638 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
639 chunk_appendf(&trace_buf, " with scid");
640 quic_cid_dump(&trace_buf, &qc->scid);
641 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200642 }
643 }
644
645 if (mask & QUIC_EV_CONN_SSLALERT) {
646 const uint8_t *alert = a2;
647 const enum ssl_encryption_level_t *level = a3;
648
649 if (alert)
650 chunk_appendf(&trace_buf, " alert=0x%02x", *alert);
651 if (level)
652 chunk_appendf(&trace_buf, " el=%c",
653 quic_enc_level_char(ssl_to_quic_enc_level(*level)));
654 }
655
656 if (mask & QUIC_EV_CONN_BCFRMS) {
657 const size_t *sz1 = a2;
658 const size_t *sz2 = a3;
659 const size_t *sz3 = a4;
660
661 if (sz1)
662 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz1);
663 if (sz2)
664 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz2);
665 if (sz3)
666 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz3);
667 }
668
669 if (mask & QUIC_EV_CONN_PSTRM) {
670 const struct quic_frame *frm = a2;
671
672 if (frm) {
673 chunk_appendf(&trace_buf, " frm@%p", frm);
674 chunk_frm_appendf(&trace_buf, frm);
675 }
676 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +0200677
678 if (mask & QUIC_EV_CONN_ELEVELSEL) {
679 const enum quic_handshake_state *state = a2;
680 const enum quic_tls_enc_level *level = a3;
681 const enum quic_tls_enc_level *next_level = a4;
682
683 if (state)
684 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(qc->state));
685 if (level)
686 chunk_appendf(&trace_buf, " level=%c", quic_enc_level_char(*level));
687 if (next_level)
688 chunk_appendf(&trace_buf, " next_level=%c", quic_enc_level_char(*next_level));
689
690 }
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200691
692 if (mask & QUIC_EV_CONN_RCV) {
693 const struct quic_dgram *dgram = a2;
694
695 if (dgram)
696 chunk_appendf(&trace_buf, " dgram.len=%zu", dgram->len);
697 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200698 }
699 if (mask & QUIC_EV_CONN_LPKT) {
700 const struct quic_rx_packet *pkt = a2;
701 const uint64_t *len = a3;
702 const struct quic_version *ver = a4;
703
704 if (pkt) {
705 chunk_appendf(&trace_buf, " pkt@%p type=0x%02x %s",
706 pkt, pkt->type, qc_pkt_long(pkt) ? "long" : "short");
707 if (pkt->pn_node.key != (uint64_t)-1)
708 chunk_appendf(&trace_buf, " pn=%llu", pkt->pn_node.key);
709 }
710
711 if (len)
712 chunk_appendf(&trace_buf, " len=%llu", (ull)*len);
713
714 if (ver)
715 chunk_appendf(&trace_buf, " ver=0x%08x", ver->num);
716 }
717
718 if (mask & QUIC_EV_STATELESS_RST) {
719 const struct quic_cid *cid = a2;
720
721 if (cid)
722 quic_cid_dump(&trace_buf, cid);
723 }
724
725}
726
727/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
728static inline int quic_peer_validated_addr(struct quic_conn *qc)
729{
730 struct quic_pktns *hdshk_pktns, *app_pktns;
731
732 if (!qc_is_listener(qc))
733 return 1;
734
735 hdshk_pktns = qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns;
736 app_pktns = qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns;
737 if ((hdshk_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
738 (app_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
739 qc->state >= QUIC_HS_ST_COMPLETE)
740 return 1;
741
742 return 0;
743}
744
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100745/* To be called to kill a connection as soon as possible (without sending any packet). */
746void qc_kill_conn(struct quic_conn *qc)
747{
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100748 TRACE_ENTER(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100749 qc->flags |= QUIC_FL_CONN_TO_KILL;
750 task_wakeup(qc->idle_timer_task, TASK_WOKEN_OTHER);
Frédéric Lécaille2f531112023-02-10 14:44:51 +0100751 TRACE_LEAVE(QUIC_EV_CONN_KILL, qc);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100752}
753
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200754/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
755 * both loss detection and PTO and schedule the task assiated to this timer if needed.
756 */
757static inline void qc_set_timer(struct quic_conn *qc)
758{
759 struct quic_pktns *pktns;
760 unsigned int pto;
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100761 int handshake_confirmed;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200762
763 TRACE_ENTER(QUIC_EV_CONN_STIMER, qc,
764 NULL, NULL, &qc->path->ifae_pkts);
765
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100766 pktns = NULL;
767 if (!qc->timer_task) {
768 TRACE_PROTO("already released timer task", QUIC_EV_CONN_STIMER, qc);
769 goto leave;
770 }
771
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200772 pktns = quic_loss_pktns(qc);
773 if (tick_isset(pktns->tx.loss_time)) {
774 qc->timer = pktns->tx.loss_time;
775 goto out;
776 }
777
778 /* anti-amplification: the timer must be
779 * cancelled for a server which reached the anti-amplification limit.
780 */
781 if (!quic_peer_validated_addr(qc) &&
782 (qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
783 TRACE_PROTO("anti-amplification reached", QUIC_EV_CONN_STIMER, qc);
784 qc->timer = TICK_ETERNITY;
785 goto out;
786 }
787
788 if (!qc->path->ifae_pkts && quic_peer_validated_addr(qc)) {
789 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, qc);
790 /* Timer cancellation. */
791 qc->timer = TICK_ETERNITY;
792 goto out;
793 }
794
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +0100795 handshake_confirmed = qc->state >= QUIC_HS_ST_CONFIRMED;
796 pktns = quic_pto_pktns(qc, handshake_confirmed, &pto);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200797 if (tick_isset(pto))
798 qc->timer = pto;
799 out:
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100800 if (qc->timer == TICK_ETERNITY) {
801 qc->timer_task->expire = TICK_ETERNITY;
802 }
803 else if (tick_is_expired(qc->timer, now_ms)) {
804 TRACE_DEVEL("wakeup asap timer task", QUIC_EV_CONN_STIMER, qc);
805 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
806 }
807 else {
808 TRACE_DEVEL("timer task scheduling", QUIC_EV_CONN_STIMER, qc);
809 task_schedule(qc->timer_task, qc->timer);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200810 }
Frédéric Lécailledd41a452023-02-09 07:48:33 +0100811 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200812 TRACE_LEAVE(QUIC_EV_CONN_STIMER, qc, pktns);
813}
814
815/* Derive new keys and ivs required for Key Update feature for <qc> QUIC
816 * connection.
817 * Return 1 if succeeded, 0 if not.
818 */
819static int quic_tls_key_update(struct quic_conn *qc)
820{
821 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
822 struct quic_tls_secrets *rx, *tx;
823 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
824 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
825 const struct quic_version *ver =
826 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
827 int ret = 0;
828
829 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
830
831 tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
832 rx = &tls_ctx->rx;
833 tx = &tls_ctx->tx;
834 nxt_rx = &qc->ku.nxt_rx;
835 nxt_tx = &qc->ku.nxt_tx;
836
837 /* Prepare new RX secrets */
838 if (!quic_tls_sec_update(rx->md, ver, nxt_rx->secret, nxt_rx->secretlen,
839 rx->secret, rx->secretlen)) {
840 TRACE_ERROR("New RX secret update failed", QUIC_EV_CONN_RWSEC, qc);
841 goto leave;
842 }
843
844 if (!quic_tls_derive_keys(rx->aead, NULL, rx->md, ver,
845 nxt_rx->key, nxt_rx->keylen,
846 nxt_rx->iv, nxt_rx->ivlen, NULL, 0,
847 nxt_rx->secret, nxt_rx->secretlen)) {
848 TRACE_ERROR("New RX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
849 goto leave;
850 }
851
852 /* Prepare new TX secrets */
853 if (!quic_tls_sec_update(tx->md, ver, nxt_tx->secret, nxt_tx->secretlen,
854 tx->secret, tx->secretlen)) {
855 TRACE_ERROR("New TX secret update failed", QUIC_EV_CONN_RWSEC, qc);
856 goto leave;
857 }
858
859 if (!quic_tls_derive_keys(tx->aead, NULL, tx->md, ver,
860 nxt_tx->key, nxt_tx->keylen,
861 nxt_tx->iv, nxt_tx->ivlen, NULL, 0,
862 nxt_tx->secret, nxt_tx->secretlen)) {
863 TRACE_ERROR("New TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
864 goto leave;
865 }
866
867 if (nxt_rx->ctx) {
868 EVP_CIPHER_CTX_free(nxt_rx->ctx);
869 nxt_rx->ctx = NULL;
870 }
871
872 if (!quic_tls_rx_ctx_init(&nxt_rx->ctx, tls_ctx->rx.aead, nxt_rx->key)) {
873 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
874 goto leave;
875 }
876
877 if (nxt_tx->ctx) {
878 EVP_CIPHER_CTX_free(nxt_tx->ctx);
879 nxt_tx->ctx = NULL;
880 }
881
882 if (!quic_tls_rx_ctx_init(&nxt_tx->ctx, tls_ctx->tx.aead, nxt_tx->key)) {
883 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
884 goto leave;
885 }
886
887 ret = 1;
888 leave:
889 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc);
890 return ret;
891}
892
893/* Rotate the Key Update information for <qc> QUIC connection.
894 * Must be used after having updated them.
895 * Always succeeds.
896 */
897static void quic_tls_rotate_keys(struct quic_conn *qc)
898{
899 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
900 unsigned char *curr_secret, *curr_iv, *curr_key;
901 EVP_CIPHER_CTX *curr_ctx;
902
903 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
904
905 /* Rotate the RX secrets */
906 curr_ctx = tls_ctx->rx.ctx;
907 curr_secret = tls_ctx->rx.secret;
908 curr_iv = tls_ctx->rx.iv;
909 curr_key = tls_ctx->rx.key;
910
911 tls_ctx->rx.ctx = qc->ku.nxt_rx.ctx;
912 tls_ctx->rx.secret = qc->ku.nxt_rx.secret;
913 tls_ctx->rx.iv = qc->ku.nxt_rx.iv;
914 tls_ctx->rx.key = qc->ku.nxt_rx.key;
915
916 qc->ku.nxt_rx.ctx = qc->ku.prv_rx.ctx;
917 qc->ku.nxt_rx.secret = qc->ku.prv_rx.secret;
918 qc->ku.nxt_rx.iv = qc->ku.prv_rx.iv;
919 qc->ku.nxt_rx.key = qc->ku.prv_rx.key;
920
921 qc->ku.prv_rx.ctx = curr_ctx;
922 qc->ku.prv_rx.secret = curr_secret;
923 qc->ku.prv_rx.iv = curr_iv;
924 qc->ku.prv_rx.key = curr_key;
925 qc->ku.prv_rx.pn = tls_ctx->rx.pn;
926
927 /* Update the TX secrets */
928 curr_ctx = tls_ctx->tx.ctx;
929 curr_secret = tls_ctx->tx.secret;
930 curr_iv = tls_ctx->tx.iv;
931 curr_key = tls_ctx->tx.key;
932
933 tls_ctx->tx.ctx = qc->ku.nxt_tx.ctx;
934 tls_ctx->tx.secret = qc->ku.nxt_tx.secret;
935 tls_ctx->tx.iv = qc->ku.nxt_tx.iv;
936 tls_ctx->tx.key = qc->ku.nxt_tx.key;
937
938 qc->ku.nxt_tx.ctx = curr_ctx;
939 qc->ku.nxt_tx.secret = curr_secret;
940 qc->ku.nxt_tx.iv = curr_iv;
941 qc->ku.nxt_tx.key = curr_key;
942
943 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
944}
945
946/* returns 0 on error, 1 on success */
947int ha_quic_set_encryption_secrets(SSL *ssl, enum ssl_encryption_level_t level,
948 const uint8_t *read_secret,
949 const uint8_t *write_secret, size_t secret_len)
950{
951 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
952 struct quic_tls_ctx *tls_ctx = &qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
953 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200954 struct quic_tls_secrets *rx = NULL, *tx = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200955 const struct quic_version *ver =
956 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
957 int ret = 0;
958
959 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
960 BUG_ON(secret_len > QUIC_TLS_SECRET_LEN);
Frédéric Lécaille0aa79952023-02-03 16:15:08 +0100961
962 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
963 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
964 goto out;
965 }
966
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200967 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
968 TRACE_PROTO("CC required", QUIC_EV_CONN_RWSEC, qc);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200969 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200970 }
971
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200972 if (!read_secret)
973 goto write;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200974
975 rx = &tls_ctx->rx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200976 if (!quic_tls_secrets_keys_alloc(rx)) {
977 TRACE_ERROR("RX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
978 goto leave;
979 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200980
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200981 rx->aead = tls_aead(cipher);
982 rx->md = tls_md(cipher);
983 rx->hp = tls_hp(cipher);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200984
985 if (!quic_tls_derive_keys(rx->aead, rx->hp, rx->md, ver, rx->key, rx->keylen,
986 rx->iv, rx->ivlen, rx->hp_key, sizeof rx->hp_key,
987 read_secret, secret_len)) {
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200988 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200989 goto leave;
990 }
991
992 if (!quic_tls_rx_ctx_init(&rx->ctx, rx->aead, rx->key)) {
993 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
994 goto leave;
995 }
996
997 if (!quic_tls_dec_aes_ctx_init(&rx->hp_ctx, rx->hp, rx->hp_key)) {
998 TRACE_ERROR("could not initial RX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
999 goto leave;
1000 }
1001
1002 /* Enqueue this connection asap if we could derive O-RTT secrets as
1003 * listener. Note that a listener derives only RX secrets for this
1004 * level.
1005 */
1006 if (qc_is_listener(qc) && level == ssl_encryption_early_data) {
1007 TRACE_DEVEL("pushing connection into accept queue", QUIC_EV_CONN_RWSEC, qc);
1008 quic_accept_push_qc(qc);
1009 }
1010
1011write:
1012
1013 if (!write_secret)
1014 goto out;
1015
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001016 tx = &tls_ctx->tx;
1017 if (!quic_tls_secrets_keys_alloc(tx)) {
1018 TRACE_ERROR("TX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
1019 goto leave;
1020 }
1021
1022 tx->aead = tls_aead(cipher);
1023 tx->md = tls_md(cipher);
1024 tx->hp = tls_hp(cipher);
1025
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001026 if (!quic_tls_derive_keys(tx->aead, tx->hp, tx->md, ver, tx->key, tx->keylen,
1027 tx->iv, tx->ivlen, tx->hp_key, sizeof tx->hp_key,
1028 write_secret, secret_len)) {
1029 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
1030 goto leave;
1031 }
1032
1033 if (!quic_tls_tx_ctx_init(&tx->ctx, tx->aead, tx->key)) {
1034 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
1035 goto leave;
1036 }
1037
1038 if (!quic_tls_enc_aes_ctx_init(&tx->hp_ctx, tx->hp, tx->hp_key)) {
1039 TRACE_ERROR("could not initial TX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
1040 goto leave;
1041 }
1042
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01001043 if (level == ssl_encryption_handshake && qc_is_listener(qc)) {
1044 qc->enc_params_len =
1045 quic_transport_params_encode(qc->enc_params,
1046 qc->enc_params + sizeof qc->enc_params,
1047 &qc->rx.params, ver, 1);
1048 if (!qc->enc_params_len) {
1049 TRACE_ERROR("quic_transport_params_encode() failed", QUIC_EV_CONN_RWSEC);
1050 goto leave;
1051 }
1052
1053 if (!SSL_set_quic_transport_params(qc->xprt_ctx->ssl, qc->enc_params, qc->enc_params_len)) {
1054 TRACE_ERROR("SSL_set_quic_transport_params() failed", QUIC_EV_CONN_RWSEC);
1055 goto leave;
1056 }
1057 }
1058
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001059 if (level == ssl_encryption_application) {
1060 struct quic_tls_kp *prv_rx = &qc->ku.prv_rx;
1061 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
1062 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
1063
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001064 if (rx) {
1065 if (!(rx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1066 TRACE_ERROR("Could not allocate RX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1067 goto leave;
1068 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001069
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001070 memcpy(rx->secret, read_secret, secret_len);
1071 rx->secretlen = secret_len;
1072 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001073
1074 if (tx) {
1075 if (!(tx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1076 TRACE_ERROR("Could not allocate TX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1077 goto leave;
1078 }
1079
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001080 memcpy(tx->secret, write_secret, secret_len);
1081 tx->secretlen = secret_len;
1082 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001083
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001084 /* Initialize all the secret keys lengths */
1085 prv_rx->secretlen = nxt_rx->secretlen = nxt_tx->secretlen = secret_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001086 }
1087
1088 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001089 ret = 1;
1090 leave:
1091 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc, &level);
1092 return ret;
1093}
1094
1095/* This function copies the CRYPTO data provided by the TLS stack found at <data>
1096 * with <len> as size in CRYPTO buffers dedicated to store the information about
1097 * outgoing CRYPTO frames so that to be able to replay the CRYPTO data streams.
1098 * It fails (returns 0) only if it could not managed to allocate enough CRYPTO
1099 * buffers to store all the data.
1100 * Note that CRYPTO data may exist at any encryption level except at 0-RTT.
1101 */
1102static int quic_crypto_data_cpy(struct quic_conn *qc, struct quic_enc_level *qel,
1103 const unsigned char *data, size_t len)
1104{
1105 struct quic_crypto_buf **qcb;
1106 /* The remaining byte to store in CRYPTO buffers. */
1107 size_t cf_offset, cf_len, *nb_buf;
1108 unsigned char *pos;
1109 int ret = 0;
1110
1111 nb_buf = &qel->tx.crypto.nb_buf;
1112 qcb = &qel->tx.crypto.bufs[*nb_buf - 1];
1113 cf_offset = (*nb_buf - 1) * QUIC_CRYPTO_BUF_SZ + (*qcb)->sz;
1114 cf_len = len;
1115
1116 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1117
1118 while (len) {
1119 size_t to_copy, room;
1120
1121 pos = (*qcb)->data + (*qcb)->sz;
1122 room = QUIC_CRYPTO_BUF_SZ - (*qcb)->sz;
1123 to_copy = len > room ? room : len;
1124 if (to_copy) {
1125 memcpy(pos, data, to_copy);
1126 /* Increment the total size of this CRYPTO buffers by <to_copy>. */
1127 qel->tx.crypto.sz += to_copy;
1128 (*qcb)->sz += to_copy;
1129 len -= to_copy;
1130 data += to_copy;
1131 }
1132 else {
1133 struct quic_crypto_buf **tmp;
1134
1135 // FIXME: realloc!
1136 tmp = realloc(qel->tx.crypto.bufs,
1137 (*nb_buf + 1) * sizeof *qel->tx.crypto.bufs);
1138 if (tmp) {
1139 qel->tx.crypto.bufs = tmp;
1140 qcb = &qel->tx.crypto.bufs[*nb_buf];
1141 *qcb = pool_alloc(pool_head_quic_crypto_buf);
1142 if (!*qcb) {
1143 TRACE_ERROR("Could not allocate crypto buf", QUIC_EV_CONN_ADDDATA, qc);
1144 goto leave;
1145 }
1146
1147 (*qcb)->sz = 0;
1148 ++*nb_buf;
1149 }
1150 else {
1151 break;
1152 }
1153 }
1154 }
1155
1156 /* Allocate a TX CRYPTO frame only if all the CRYPTO data
1157 * have been buffered.
1158 */
1159 if (!len) {
1160 struct quic_frame *frm;
1161 struct quic_frame *found = NULL;
1162
1163 /* There is at most one CRYPTO frame in this packet number
1164 * space. Let's look for it.
1165 */
1166 list_for_each_entry(frm, &qel->pktns->tx.frms, list) {
1167 if (frm->type != QUIC_FT_CRYPTO)
1168 continue;
1169
1170 /* Found */
1171 found = frm;
1172 break;
1173 }
1174
1175 if (found) {
1176 found->crypto.len += cf_len;
1177 }
1178 else {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01001179 frm = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001180 if (!frm) {
1181 TRACE_ERROR("Could not allocate quic frame", QUIC_EV_CONN_ADDDATA, qc);
1182 goto leave;
1183 }
1184
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001185 frm->crypto.offset = cf_offset;
1186 frm->crypto.len = cf_len;
1187 frm->crypto.qel = qel;
1188 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
1189 }
1190 }
1191 ret = len == 0;
1192 leave:
1193 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1194 return ret;
1195}
1196
1197/* Prepare the emission of CONNECTION_CLOSE with error <err>. All send/receive
1198 * activity for <qc> will be interrupted.
1199 */
1200void quic_set_connection_close(struct quic_conn *qc, const struct quic_err err)
1201{
1202 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1203 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)
1204 goto leave;
1205
1206 TRACE_STATE("setting immediate close", QUIC_EV_CONN_CLOSE, qc);
1207 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
1208 qc->err.code = err.code;
1209 qc->err.app = err.app;
1210 leave:
1211 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1212}
1213
1214/* Set <alert> TLS alert as QUIC CRYPTO_ERROR error */
1215void quic_set_tls_alert(struct quic_conn *qc, int alert)
1216{
1217 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1218
1219 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
1220 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
1221 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
1222 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
1223 }
1224 quic_set_connection_close(qc, quic_err_tls(alert));
1225 qc->flags |= QUIC_FL_CONN_TLS_ALERT;
1226 TRACE_STATE("Alert set", QUIC_EV_CONN_SSLALERT, qc);
1227
1228 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1229}
1230
1231/* Set the application for <qc> QUIC connection.
1232 * Return 1 if succeeded, 0 if not.
1233 */
1234int quic_set_app_ops(struct quic_conn *qc, const unsigned char *alpn, size_t alpn_len)
1235{
1236 if (alpn_len >= 2 && memcmp(alpn, "h3", 2) == 0)
1237 qc->app_ops = &h3_ops;
1238 else if (alpn_len >= 10 && memcmp(alpn, "hq-interop", 10) == 0)
1239 qc->app_ops = &hq_interop_ops;
1240 else
1241 return 0;
1242
1243 return 1;
1244}
1245
1246/* ->add_handshake_data QUIC TLS callback used by the QUIC TLS stack when it
1247 * wants to provide the QUIC layer with CRYPTO data.
1248 * Returns 1 if succeeded, 0 if not.
1249 */
1250int ha_quic_add_handshake_data(SSL *ssl, enum ssl_encryption_level_t level,
1251 const uint8_t *data, size_t len)
1252{
1253 struct quic_conn *qc;
1254 enum quic_tls_enc_level tel;
1255 struct quic_enc_level *qel;
1256 int ret = 0;
1257
1258 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1259 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1260
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01001261 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
1262 TRACE_PROTO("connection to be killed", QUIC_EV_CONN_ADDDATA, qc);
1263 goto out;
1264 }
1265
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001266 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
1267 TRACE_PROTO("CC required", QUIC_EV_CONN_ADDDATA, qc);
1268 goto out;
1269 }
1270
1271 tel = ssl_to_quic_enc_level(level);
1272 if (tel == -1) {
1273 TRACE_ERROR("Wrong encryption level", QUIC_EV_CONN_ADDDATA, qc);
1274 goto leave;
1275 }
1276
1277 qel = &qc->els[tel];
1278 if (!quic_crypto_data_cpy(qc, qel, data, len)) {
1279 TRACE_ERROR("Could not bufferize", QUIC_EV_CONN_ADDDATA, qc);
1280 goto leave;
1281 }
1282
1283 TRACE_DEVEL("CRYPTO data buffered", QUIC_EV_CONN_ADDDATA,
1284 qc, &level, &len);
1285 out:
1286 ret = 1;
1287 leave:
1288 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1289 return ret;
1290}
1291
1292int ha_quic_flush_flight(SSL *ssl)
1293{
1294 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1295
1296 TRACE_ENTER(QUIC_EV_CONN_FFLIGHT, qc);
1297 TRACE_LEAVE(QUIC_EV_CONN_FFLIGHT, qc);
1298
1299 return 1;
1300}
1301
1302int ha_quic_send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
1303{
1304 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1305
1306 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1307
1308 TRACE_PROTO("Received TLS alert", QUIC_EV_CONN_SSLALERT, qc, &alert, &level);
1309
1310 quic_set_tls_alert(qc, alert);
1311 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1312 return 1;
1313}
1314
1315/* QUIC TLS methods */
1316static SSL_QUIC_METHOD ha_quic_method = {
1317 .set_encryption_secrets = ha_quic_set_encryption_secrets,
1318 .add_handshake_data = ha_quic_add_handshake_data,
1319 .flush_flight = ha_quic_flush_flight,
1320 .send_alert = ha_quic_send_alert,
1321};
1322
1323/* Initialize the TLS context of a listener with <bind_conf> as configuration.
1324 * Returns an error count.
1325 */
1326int ssl_quic_initial_ctx(struct bind_conf *bind_conf)
1327{
1328 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
1329 int cfgerr = 0;
1330
1331 long options =
1332 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1333 SSL_OP_SINGLE_ECDH_USE |
1334 SSL_OP_CIPHER_SERVER_PREFERENCE;
1335 SSL_CTX *ctx;
1336
1337 ctx = SSL_CTX_new(TLS_server_method());
1338 bind_conf->initial_ctx = ctx;
1339
1340 SSL_CTX_set_options(ctx, options);
1341 SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
1342 SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
1343 SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
1344
1345#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1346# if defined(HAVE_SSL_CLIENT_HELLO_CB)
1347# if defined(SSL_OP_NO_ANTI_REPLAY)
1348 if (bind_conf->ssl_conf.early_data) {
1349 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
1350 SSL_CTX_set_max_early_data(ctx, 0xffffffff);
1351 }
1352# endif /* !SSL_OP_NO_ANTI_REPLAY */
1353 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
1354 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
1355# else /* ! HAVE_SSL_CLIENT_HELLO_CB */
1356 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
1357# endif
1358 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
1359#endif
1360 SSL_CTX_set_quic_method(ctx, &ha_quic_method);
1361
1362 return cfgerr;
1363}
1364
1365/* Decode an expected packet number from <truncated_on> its truncated value,
1366 * depending on <largest_pn> the largest received packet number, and <pn_nbits>
1367 * the number of bits used to encode this packet number (its length in bytes * 8).
1368 * See https://quicwg.org/base-drafts/draft-ietf-quic-transport.html#packet-encoding
1369 */
1370static uint64_t decode_packet_number(uint64_t largest_pn,
1371 uint32_t truncated_pn, unsigned int pn_nbits)
1372{
1373 uint64_t expected_pn = largest_pn + 1;
1374 uint64_t pn_win = (uint64_t)1 << pn_nbits;
1375 uint64_t pn_hwin = pn_win / 2;
1376 uint64_t pn_mask = pn_win - 1;
1377 uint64_t candidate_pn;
1378
1379
1380 candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
1381 /* Note that <pn_win> > <pn_hwin>. */
1382 if (candidate_pn < QUIC_MAX_PACKET_NUM - pn_win &&
1383 candidate_pn + pn_hwin <= expected_pn)
1384 return candidate_pn + pn_win;
1385
1386 if (candidate_pn > expected_pn + pn_hwin && candidate_pn >= pn_win)
1387 return candidate_pn - pn_win;
1388
1389 return candidate_pn;
1390}
1391
1392/* Remove the header protection of <pkt> QUIC packet using <tls_ctx> as QUIC TLS
1393 * cryptographic context.
1394 * <largest_pn> is the largest received packet number and <pn> the address of
1395 * the packet number field for this packet with <byte0> address of its first byte.
1396 * <end> points to one byte past the end of this packet.
1397 * Returns 1 if succeeded, 0 if not.
1398 */
1399static int qc_do_rm_hp(struct quic_conn *qc,
1400 struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx,
1401 int64_t largest_pn, unsigned char *pn, unsigned char *byte0)
1402{
1403 int ret, i, pnlen;
1404 uint64_t packet_number;
1405 uint32_t truncated_pn = 0;
1406 unsigned char mask[5] = {0};
1407 unsigned char *sample;
1408 EVP_CIPHER_CTX *cctx = NULL;
1409
1410 TRACE_ENTER(QUIC_EV_CONN_RMHP, qc);
1411
1412 ret = 0;
1413
1414 /* Check there is enough data in this packet. */
1415 if (pkt->len - (pn - byte0) < QUIC_PACKET_PN_MAXLEN + sizeof mask) {
1416 TRACE_PROTO("too short packet", QUIC_EV_CONN_RMHP, qc, pkt);
1417 goto leave;
1418 }
1419
1420 cctx = EVP_CIPHER_CTX_new();
1421 if (!cctx) {
1422 TRACE_ERROR("memory allocation failed", QUIC_EV_CONN_RMHP, qc, pkt);
1423 goto leave;
1424 }
1425
1426 sample = pn + QUIC_PACKET_PN_MAXLEN;
1427
1428 if (!quic_tls_aes_decrypt(mask, sample, sizeof mask, tls_ctx->rx.hp_ctx)) {
1429 TRACE_ERROR("HP removing failed", QUIC_EV_CONN_RMHP, qc, pkt);
1430 goto leave;
1431 }
1432
1433 *byte0 ^= mask[0] & (*byte0 & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
1434 pnlen = (*byte0 & QUIC_PACKET_PNL_BITMASK) + 1;
1435 for (i = 0; i < pnlen; i++) {
1436 pn[i] ^= mask[i + 1];
1437 truncated_pn = (truncated_pn << 8) | pn[i];
1438 }
1439
1440 packet_number = decode_packet_number(largest_pn, truncated_pn, pnlen * 8);
1441 /* Store remaining information for this unprotected header */
1442 pkt->pn = packet_number;
1443 pkt->pnl = pnlen;
1444
1445 ret = 1;
1446 leave:
1447 if (cctx)
1448 EVP_CIPHER_CTX_free(cctx);
1449 TRACE_LEAVE(QUIC_EV_CONN_RMHP, qc);
1450 return ret;
1451}
1452
1453/* Encrypt the payload of a QUIC packet with <pn> as number found at <payload>
1454 * address, with <payload_len> as payload length, <aad> as address of
1455 * the ADD and <aad_len> as AAD length depending on the <tls_ctx> QUIC TLS
1456 * context.
1457 * Returns 1 if succeeded, 0 if not.
1458 */
1459static int quic_packet_encrypt(unsigned char *payload, size_t payload_len,
1460 unsigned char *aad, size_t aad_len, uint64_t pn,
1461 struct quic_tls_ctx *tls_ctx, struct quic_conn *qc)
1462{
1463 int ret = 0;
1464 unsigned char iv[QUIC_TLS_IV_LEN];
1465 unsigned char *tx_iv = tls_ctx->tx.iv;
1466 size_t tx_iv_sz = tls_ctx->tx.ivlen;
1467 struct enc_debug_info edi;
1468
1469 TRACE_ENTER(QUIC_EV_CONN_ENCPKT, qc);
1470
1471 if (!quic_aead_iv_build(iv, sizeof iv, tx_iv, tx_iv_sz, pn)) {
1472 TRACE_ERROR("AEAD IV building for encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1473 goto err;
1474 }
1475
1476 if (!quic_tls_encrypt(payload, payload_len, aad, aad_len,
1477 tls_ctx->tx.ctx, tls_ctx->tx.aead, tls_ctx->tx.key, iv)) {
1478 TRACE_ERROR("QUIC packet encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1479 goto err;
1480 }
1481
1482 ret = 1;
1483 leave:
1484 TRACE_LEAVE(QUIC_EV_CONN_ENCPKT, qc);
1485 return ret;
1486
1487 err:
1488 enc_debug_info_init(&edi, payload, payload_len, aad, aad_len, pn);
1489 goto leave;
1490}
1491
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001492/* Decrypt <pkt> packet using encryption level <qel> for <qc> connection.
1493 * Decryption is done in place in packet buffer.
1494 *
Ilya Shipitsin5fa29b82022-12-07 09:46:19 +05001495 * Returns 1 on success else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001496 */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001497static int qc_pkt_decrypt(struct quic_conn *qc, struct quic_enc_level *qel,
1498 struct quic_rx_packet *pkt)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001499{
1500 int ret, kp_changed;
1501 unsigned char iv[QUIC_TLS_IV_LEN];
1502 struct quic_tls_ctx *tls_ctx = &qel->tls_ctx;
1503 EVP_CIPHER_CTX *rx_ctx = tls_ctx->rx.ctx;
1504 unsigned char *rx_iv = tls_ctx->rx.iv;
1505 size_t rx_iv_sz = tls_ctx->rx.ivlen;
1506 unsigned char *rx_key = tls_ctx->rx.key;
1507
1508 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
1509
1510 ret = 0;
1511 kp_changed = 0;
1512
1513 if (pkt->type == QUIC_PACKET_TYPE_SHORT) {
1514 /* The two tested bits are not at the same position,
1515 * this is why they are first both inversed.
1516 */
1517 if (!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT) ^ !(tls_ctx->flags & QUIC_FL_TLS_KP_BIT_SET)) {
1518 if (pkt->pn < tls_ctx->rx.pn) {
1519 /* The lowest packet number of a previous key phase
1520 * cannot be null if it really stores previous key phase
1521 * secrets.
1522 */
1523 // TODO: check if BUG_ON() more suitable
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001524 if (!qc->ku.prv_rx.pn) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001525 TRACE_ERROR("null previous packet number", QUIC_EV_CONN_RXPKT, qc);
1526 goto leave;
1527 }
1528
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001529 rx_ctx = qc->ku.prv_rx.ctx;
1530 rx_iv = qc->ku.prv_rx.iv;
1531 rx_key = qc->ku.prv_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001532 }
1533 else if (pkt->pn > qel->pktns->rx.largest_pn) {
1534 /* Next key phase */
1535 kp_changed = 1;
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001536 rx_ctx = qc->ku.nxt_rx.ctx;
1537 rx_iv = qc->ku.nxt_rx.iv;
1538 rx_key = qc->ku.nxt_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001539 }
1540 }
1541 }
1542
1543 if (!quic_aead_iv_build(iv, sizeof iv, rx_iv, rx_iv_sz, pkt->pn)) {
1544 TRACE_ERROR("quic_aead_iv_build() failed", QUIC_EV_CONN_RXPKT, qc);
1545 goto leave;
1546 }
1547
1548 ret = quic_tls_decrypt(pkt->data + pkt->aad_len, pkt->len - pkt->aad_len,
1549 pkt->data, pkt->aad_len,
1550 rx_ctx, tls_ctx->rx.aead, rx_key, iv);
1551 if (!ret) {
1552 TRACE_ERROR("quic_tls_decrypt() failed", QUIC_EV_CONN_RXPKT, qc);
1553 goto leave;
1554 }
1555
1556 /* Update the keys only if the packet decryption succeeded. */
1557 if (kp_changed) {
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001558 quic_tls_rotate_keys(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001559 /* Toggle the Key Phase bit */
1560 tls_ctx->flags ^= QUIC_FL_TLS_KP_BIT_SET;
1561 /* Store the lowest packet number received for the current key phase */
1562 tls_ctx->rx.pn = pkt->pn;
1563 /* Prepare the next key update */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001564 if (!quic_tls_key_update(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001565 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_RXPKT, qc);
1566 goto leave;
1567 }
1568 }
1569
1570 /* Update the packet length (required to parse the frames). */
1571 pkt->len -= QUIC_TLS_TAG_LEN;
1572 ret = 1;
1573 leave:
1574 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
1575 return ret;
1576}
1577
1578
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001579/* Release <frm> frame and mark its copies as acknowledged */
1580void qc_release_frm(struct quic_conn *qc, struct quic_frame *frm)
1581{
1582 uint64_t pn;
1583 struct quic_frame *origin, *f, *tmp;
1584
1585 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1586
1587 /* Identify this frame: a frame copy or one of its copies */
1588 origin = frm->origin ? frm->origin : frm;
1589 /* Ensure the source of the copies is flagged as acked, <frm> being
1590 * possibly a copy of <origin>
1591 */
1592 origin->flags |= QUIC_FL_TX_FRAME_ACKED;
1593 /* Mark all the copy of <origin> as acknowledged. We must
1594 * not release the packets (releasing the frames) at this time as
1595 * they are possibly also to be acknowledged alongside the
1596 * the current one.
1597 */
1598 list_for_each_entry_safe(f, tmp, &origin->reflist, ref) {
1599 if (f->pkt) {
1600 f->flags |= QUIC_FL_TX_FRAME_ACKED;
1601 f->origin = NULL;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001602 LIST_DEL_INIT(&f->ref);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001603 pn = f->pkt->pn_node.key;
1604 TRACE_DEVEL("mark frame as acked from packet",
1605 QUIC_EV_CONN_PRSAFRM, qc, f, &pn);
1606 }
1607 else {
1608 TRACE_DEVEL("freeing unsent frame",
1609 QUIC_EV_CONN_PRSAFRM, qc, f);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001610 LIST_DEL_INIT(&f->ref);
1611 qc_frm_free(&f);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001612 }
1613 }
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001614 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001615 pn = frm->pkt->pn_node.key;
1616 quic_tx_packet_refdec(frm->pkt);
1617 TRACE_DEVEL("freeing frame from packet",
1618 QUIC_EV_CONN_PRSAFRM, qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001619 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001620
1621 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1622}
1623
1624/* Schedule a CONNECTION_CLOSE emission on <qc> if the MUX has been released
1625 * and all STREAM data are acknowledged. The MUX is responsible to have set
1626 * <qc.err> before as it is reused for the CONNECTION_CLOSE frame.
1627 *
1628 * TODO this should also be called on lost packet detection
1629 */
1630void qc_check_close_on_released_mux(struct quic_conn *qc)
1631{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001632 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1633
1634 if (qc->mux_state == QC_MUX_RELEASED && eb_is_empty(&qc->streams_by_id)) {
1635 /* Reuse errcode which should have been previously set by the MUX on release. */
1636 quic_set_connection_close(qc, qc->err);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02001637 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001638 }
1639
1640 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1641}
1642
1643/* Remove from <stream> the acknowledged frames.
1644 *
1645 * Returns 1 if at least one frame was removed else 0.
1646 */
1647static int quic_stream_try_to_consume(struct quic_conn *qc,
1648 struct qc_stream_desc *stream)
1649{
1650 int ret;
1651 struct eb64_node *frm_node;
1652
1653 TRACE_ENTER(QUIC_EV_CONN_ACKSTRM, qc);
1654
1655 ret = 0;
1656 frm_node = eb64_first(&stream->acked_frms);
1657 while (frm_node) {
1658 struct quic_stream *strm;
1659 struct quic_frame *frm;
1660 size_t offset, len;
1661
1662 strm = eb64_entry(frm_node, struct quic_stream, offset);
1663 offset = strm->offset.key;
1664 len = strm->len;
1665
1666 if (offset > stream->ack_offset)
1667 break;
1668
1669 if (qc_stream_desc_ack(&stream, offset, len)) {
1670 /* cf. next comment : frame may be freed at this stage. */
1671 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1672 qc, stream ? strm : NULL, stream);
1673 ret = 1;
1674 }
1675
1676 /* If stream is NULL after qc_stream_desc_ack(), it means frame
1677 * has been freed. with the stream frames tree. Nothing to do
1678 * anymore in here.
1679 */
1680 if (!stream) {
1681 qc_check_close_on_released_mux(qc);
1682 ret = 1;
1683 goto leave;
1684 }
1685
1686 frm_node = eb64_next(frm_node);
1687 eb64_delete(&strm->offset);
1688
1689 frm = container_of(strm, struct quic_frame, stream);
1690 qc_release_frm(qc, frm);
1691 }
1692
1693 leave:
1694 TRACE_LEAVE(QUIC_EV_CONN_ACKSTRM, qc);
1695 return ret;
1696}
1697
1698/* Treat <frm> frame whose packet it is attached to has just been acknowledged. */
1699static inline void qc_treat_acked_tx_frm(struct quic_conn *qc,
1700 struct quic_frame *frm)
1701{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001702 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc, frm);
1703
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001704 switch (frm->type) {
1705 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1706 {
1707 struct quic_stream *strm_frm = &frm->stream;
1708 struct eb64_node *node = NULL;
1709 struct qc_stream_desc *stream = NULL;
1710 const size_t offset = strm_frm->offset.key;
1711 const size_t len = strm_frm->len;
1712
1713 /* do not use strm_frm->stream as the qc_stream_desc instance
1714 * might be freed at this stage. Use the id to do a proper
1715 * lookup.
1716 *
1717 * TODO if lookup operation impact on the perf is noticeable,
1718 * implement a refcount on qc_stream_desc instances.
1719 */
1720 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1721 if (!node) {
1722 TRACE_DEVEL("acked stream for released stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm);
1723 qc_release_frm(qc, frm);
1724 /* early return */
1725 goto leave;
1726 }
1727 stream = eb64_entry(node, struct qc_stream_desc, by_id);
1728
1729 TRACE_DEVEL("acked stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm, stream);
1730 if (offset <= stream->ack_offset) {
1731 if (qc_stream_desc_ack(&stream, offset, len)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001732 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1733 qc, strm_frm, stream);
1734 }
1735
1736 if (!stream) {
1737 /* no need to continue if stream freed. */
1738 TRACE_DEVEL("stream released and freed", QUIC_EV_CONN_ACKSTRM, qc);
1739 qc_release_frm(qc, frm);
1740 qc_check_close_on_released_mux(qc);
1741 break;
1742 }
1743
1744 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1745 qc, strm_frm, stream);
1746 qc_release_frm(qc, frm);
1747 }
1748 else {
1749 eb64_insert(&stream->acked_frms, &strm_frm->offset);
1750 }
1751
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01001752 quic_stream_try_to_consume(qc, stream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001753 }
1754 break;
1755 default:
1756 qc_release_frm(qc, frm);
1757 }
1758
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001759 leave:
1760 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1761}
1762
1763/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1764 * deallocating them, and their TX frames.
1765 * Returns the last node reached to be used for the next range.
1766 * May be NULL if <largest> node could not be found.
1767 */
1768static inline struct eb64_node *qc_ackrng_pkts(struct quic_conn *qc,
1769 struct eb_root *pkts,
1770 unsigned int *pkt_flags,
1771 struct list *newly_acked_pkts,
1772 struct eb64_node *largest_node,
1773 uint64_t largest, uint64_t smallest)
1774{
1775 struct eb64_node *node;
1776 struct quic_tx_packet *pkt;
1777
1778 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1779
1780 node = largest_node ? largest_node : eb64_lookup_le(pkts, largest);
1781 while (node && node->key >= smallest) {
1782 struct quic_frame *frm, *frmbak;
1783
1784 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
1785 *pkt_flags |= pkt->flags;
1786 LIST_INSERT(newly_acked_pkts, &pkt->list);
1787 TRACE_DEVEL("Removing packet #", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
1788 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1789 qc_treat_acked_tx_frm(qc, frm);
Frédéric Lécaille814645f2022-11-18 18:15:28 +01001790 /* If there are others packet in the same datagram <pkt> is attached to,
1791 * detach the previous one and the next one from <pkt>.
1792 */
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01001793 quic_tx_packet_dgram_detach(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001794 node = eb64_prev(node);
1795 eb64_delete(&pkt->pn_node);
1796 }
1797
1798 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1799 return node;
1800}
1801
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001802/* Remove all frames from <pkt_frm_list> and reinsert them in the same order
1803 * they have been sent into <pktns_frm_list>. The loss counter of each frame is
1804 * incremented and checked if it does not exceed retransmission limit.
1805 *
1806 * Returns 1 on success, 0 if a frame loss limit is exceeded. A
1807 * CONNECTION_CLOSE is scheduled in this case.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001808 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001809static inline int qc_requeue_nacked_pkt_tx_frms(struct quic_conn *qc,
1810 struct quic_tx_packet *pkt,
1811 struct list *pktns_frm_list)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001812{
1813 struct quic_frame *frm, *frmbak;
1814 struct list tmp = LIST_HEAD_INIT(tmp);
1815 struct list *pkt_frm_list = &pkt->frms;
1816 uint64_t pn = pkt->pn_node.key;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001817 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001818
1819 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1820
1821 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
1822 /* First remove this frame from the packet it was attached to */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001823 LIST_DEL_INIT(&frm->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001824 quic_tx_packet_refdec(pkt);
1825 /* At this time, this frame is not freed but removed from its packet */
1826 frm->pkt = NULL;
1827 /* Remove any reference to this frame */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001828 qc_frm_unref(frm, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001829 switch (frm->type) {
1830 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1831 {
1832 struct quic_stream *strm_frm = &frm->stream;
1833 struct eb64_node *node = NULL;
1834 struct qc_stream_desc *stream_desc;
1835
1836 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1837 if (!node) {
1838 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
1839 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1840 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001841 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001842 continue;
1843 }
1844
1845 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
1846 /* Do not resend this frame if in the "already acked range" */
1847 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
1848 TRACE_DEVEL("ignored frame in already acked range",
1849 QUIC_EV_CONN_PRSAFRM, qc, frm);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001850 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001851 continue;
1852 }
1853 else if (strm_frm->offset.key < stream_desc->ack_offset) {
1854 strm_frm->offset.key = stream_desc->ack_offset;
1855 TRACE_DEVEL("updated partially acked frame",
1856 QUIC_EV_CONN_PRSAFRM, qc, frm);
1857 }
1858 break;
1859 }
1860
1861 default:
1862 break;
1863 }
1864
1865 /* Do not resend probing packet with old data */
1866 if (pkt->flags & QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA) {
1867 TRACE_DEVEL("ignored frame with old data from packet", QUIC_EV_CONN_PRSAFRM,
1868 qc, frm, &pn);
1869 if (frm->origin)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001870 LIST_DEL_INIT(&frm->ref);
1871 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001872 continue;
1873 }
1874
1875 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
1876 TRACE_DEVEL("already acked frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
1877 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1878 qc, frm, &pn);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001879 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001880 }
1881 else {
Amaury Denoyelle24d5b722023-01-31 11:44:50 +01001882 if (++frm->loss_count >= global.tune.quic_max_frame_loss) {
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001883 TRACE_ERROR("retransmission limit reached, closing the connection", QUIC_EV_CONN_PRSAFRM, qc);
1884 quic_set_connection_close(qc, quic_err_transport(QC_ERR_INTERNAL_ERROR));
1885 close = 1;
1886 }
1887
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001888 LIST_APPEND(&tmp, &frm->list);
1889 TRACE_DEVEL("frame requeued", QUIC_EV_CONN_PRSAFRM, qc, frm);
1890 }
1891 }
1892
1893 LIST_SPLICE(pktns_frm_list, &tmp);
1894
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001895 end:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001896 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01001897 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001898}
1899
1900/* Free <pkt> TX packet and its attached frames.
1901 * This is the responsibility of the caller to remove this packet of
1902 * any data structure it was possibly attached to.
1903 */
1904static inline void free_quic_tx_packet(struct quic_conn *qc,
1905 struct quic_tx_packet *pkt)
1906{
1907 struct quic_frame *frm, *frmbak;
1908
1909 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1910
1911 if (!pkt)
1912 goto leave;
1913
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01001914 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1915 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001916 pool_free(pool_head_quic_tx_packet, pkt);
1917
1918 leave:
1919 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1920}
1921
1922/* Free the TX packets of <pkts> list */
1923static inline void free_quic_tx_pkts(struct quic_conn *qc, struct list *pkts)
1924{
1925 struct quic_tx_packet *pkt, *tmp;
1926
1927 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1928
1929 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1930 LIST_DELETE(&pkt->list);
1931 eb64_delete(&pkt->pn_node);
1932 free_quic_tx_packet(qc, pkt);
1933 }
1934
1935 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1936}
1937
1938/* Remove already sent ranges of acknowledged packet numbers from
1939 * <pktns> packet number space tree below <largest_acked_pn> possibly
1940 * updating the range which contains <largest_acked_pn>.
1941 * Never fails.
1942 */
1943static void qc_treat_ack_of_ack(struct quic_conn *qc,
1944 struct quic_pktns *pktns,
1945 int64_t largest_acked_pn)
1946{
1947 struct eb64_node *ar, *next_ar;
1948 struct quic_arngs *arngs = &pktns->rx.arngs;
1949
1950 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1951
1952 ar = eb64_first(&arngs->root);
1953 while (ar) {
1954 struct quic_arng_node *ar_node;
1955
1956 next_ar = eb64_next(ar);
1957 ar_node = eb64_entry(ar, struct quic_arng_node, first);
1958
1959 if ((int64_t)ar_node->first.key > largest_acked_pn) {
1960 TRACE_DEVEL("first.key > largest", QUIC_EV_CONN_PRSAFRM, qc);
1961 break;
1962 }
1963
1964 if (largest_acked_pn < ar_node->last) {
1965 eb64_delete(ar);
1966 ar_node->first.key = largest_acked_pn + 1;
1967 eb64_insert(&arngs->root, ar);
1968 break;
1969 }
1970
1971 eb64_delete(ar);
1972 pool_free(pool_head_quic_arng, ar_node);
1973 arngs->sz--;
1974 ar = next_ar;
1975 }
1976
1977 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1978}
1979
1980/* Send a packet ack event nofication for each newly acked packet of
1981 * <newly_acked_pkts> list and free them.
1982 * Always succeeds.
1983 */
1984static inline void qc_treat_newly_acked_pkts(struct quic_conn *qc,
1985 struct list *newly_acked_pkts)
1986{
1987 struct quic_tx_packet *pkt, *tmp;
1988 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
1989
1990 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1991
1992 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
1993 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
1994 qc->path->prep_in_flight -= pkt->in_flight_len;
1995 qc->path->in_flight -= pkt->in_flight_len;
1996 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
1997 qc->path->ifae_pkts--;
1998 /* If this packet contained an ACK frame, proceed to the
1999 * acknowledging of range of acks from the largest acknowledged
2000 * packet number which was sent in an ACK frame by this packet.
2001 */
2002 if (pkt->largest_acked_pn != -1)
2003 qc_treat_ack_of_ack(qc, pkt->pktns, pkt->largest_acked_pn);
2004 ev.ack.acked = pkt->in_flight_len;
2005 ev.ack.time_sent = pkt->time_sent;
2006 quic_cc_event(&qc->path->cc, &ev);
2007 LIST_DELETE(&pkt->list);
2008 eb64_delete(&pkt->pn_node);
2009 quic_tx_packet_refdec(pkt);
2010 }
2011
2012 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2013
2014}
2015
2016/* Release all the frames attached to <pktns> packet number space */
2017static inline void qc_release_pktns_frms(struct quic_conn *qc,
2018 struct quic_pktns *pktns)
2019{
2020 struct quic_frame *frm, *frmbak;
2021
2022 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
2023
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01002024 list_for_each_entry_safe(frm, frmbak, &pktns->tx.frms, list)
2025 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002026
2027 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
2028}
2029
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002030/* Handle <pkts> list of lost packets detected at <now_us> handling their TX
2031 * frames. Send a packet loss event to the congestion controller if in flight
2032 * packet have been lost. Also frees the packet in <pkts> list.
2033 *
2034 * Returns 1 on success else 0 if loss limit has been exceeded. A
2035 * CONNECTION_CLOSE was prepared to close the connection ASAP.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002036 */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002037static inline int qc_release_lost_pkts(struct quic_conn *qc,
2038 struct quic_pktns *pktns,
2039 struct list *pkts,
2040 uint64_t now_us)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002041{
2042 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002043 int close = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002044
2045 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2046
2047 if (LIST_ISEMPTY(pkts))
2048 goto leave;
2049
2050 oldest_lost = newest_lost = NULL;
2051 list_for_each_entry_safe(pkt, tmp, pkts, list) {
2052 struct list tmp = LIST_HEAD_INIT(tmp);
2053
2054 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2055 qc->path->prep_in_flight -= pkt->in_flight_len;
2056 qc->path->in_flight -= pkt->in_flight_len;
2057 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2058 qc->path->ifae_pkts--;
2059 /* Treat the frames of this lost packet. */
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002060 if (!qc_requeue_nacked_pkt_tx_frms(qc, pkt, &pktns->tx.frms))
2061 close = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002062 LIST_DELETE(&pkt->list);
2063 if (!oldest_lost) {
2064 oldest_lost = newest_lost = pkt;
2065 }
2066 else {
2067 if (newest_lost != oldest_lost)
2068 quic_tx_packet_refdec(newest_lost);
2069 newest_lost = pkt;
2070 }
2071 }
2072
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002073 if (!close) {
2074 if (newest_lost) {
2075 /* Sent a congestion event to the controller */
2076 struct quic_cc_event ev = { };
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002077
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002078 ev.type = QUIC_CC_EVT_LOSS;
2079 ev.loss.time_sent = newest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002080
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002081 quic_cc_event(&qc->path->cc, &ev);
2082 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002083
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002084 /* If an RTT have been already sampled, <rtt_min> has been set.
2085 * We must check if we are experiencing a persistent congestion.
2086 * If this is the case, the congestion controller must re-enter
2087 * slow start state.
2088 */
2089 if (qc->path->loss.rtt_min && newest_lost != oldest_lost) {
2090 unsigned int period = newest_lost->time_sent - oldest_lost->time_sent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002091
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002092 if (quic_loss_persistent_congestion(&qc->path->loss, period,
2093 now_ms, qc->max_ack_delay))
2094 qc->path->cc.algo->slow_start(&qc->path->cc);
2095 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002096 }
2097
Amaury Denoyelle3a72ba22022-11-14 11:41:34 +01002098 /* <oldest_lost> cannot be NULL at this stage because we have ensured
2099 * that <pkts> list is not empty. Without this, GCC 12.2.0 reports a
2100 * possible overflow on a 0 byte region with O2 optimization.
2101 */
2102 ALREADY_CHECKED(oldest_lost);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002103 quic_tx_packet_refdec(oldest_lost);
2104 if (newest_lost != oldest_lost)
2105 quic_tx_packet_refdec(newest_lost);
2106
2107 leave:
2108 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002109 return !close;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002110}
2111
2112/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
2113 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
2114 * if the largest acked packet was newly acked and if there was at least one newly
2115 * acked ack-eliciting packet.
2116 * Return 1, if succeeded, 0 if not.
2117 */
2118static inline int qc_parse_ack_frm(struct quic_conn *qc,
2119 struct quic_frame *frm,
2120 struct quic_enc_level *qel,
2121 unsigned int *rtt_sample,
2122 const unsigned char **pos, const unsigned char *end)
2123{
2124 struct quic_ack *ack = &frm->ack;
2125 uint64_t smallest, largest;
2126 struct eb_root *pkts;
2127 struct eb64_node *largest_node;
2128 unsigned int time_sent, pkt_flags;
2129 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
2130 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2131 int ret = 0;
2132
2133 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2134
2135 if (ack->largest_ack > qel->pktns->tx.next_pn) {
2136 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
2137 qc, NULL, &ack->largest_ack);
2138 goto err;
2139 }
2140
2141 if (ack->first_ack_range > ack->largest_ack) {
2142 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
2143 qc, NULL, &ack->first_ack_range);
2144 goto err;
2145 }
2146
2147 largest = ack->largest_ack;
2148 smallest = largest - ack->first_ack_range;
2149 pkts = &qel->pktns->tx.pkts;
2150 pkt_flags = 0;
2151 largest_node = NULL;
2152 time_sent = 0;
2153
2154 if ((int64_t)ack->largest_ack > qel->pktns->rx.largest_acked_pn) {
2155 largest_node = eb64_lookup(pkts, largest);
2156 if (!largest_node) {
2157 TRACE_DEVEL("Largest acked packet not found",
2158 QUIC_EV_CONN_PRSAFRM, qc);
2159 }
2160 else {
2161 time_sent = eb64_entry(largest_node,
2162 struct quic_tx_packet, pn_node)->time_sent;
2163 }
2164 }
2165
2166 TRACE_PROTO("rcvd ack range", QUIC_EV_CONN_PRSAFRM,
2167 qc, NULL, &largest, &smallest);
2168 do {
2169 uint64_t gap, ack_range;
2170
2171 qc_ackrng_pkts(qc, pkts, &pkt_flags, &newly_acked_pkts,
2172 largest_node, largest, smallest);
2173 if (!ack->ack_range_num--)
2174 break;
2175
2176 if (!quic_dec_int(&gap, pos, end)) {
2177 TRACE_ERROR("quic_dec_int(gap) failed", QUIC_EV_CONN_PRSAFRM, qc);
2178 goto err;
2179 }
2180
2181 if (smallest < gap + 2) {
2182 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
2183 qc, NULL, &gap, &smallest);
2184 goto err;
2185 }
2186
2187 largest = smallest - gap - 2;
2188 if (!quic_dec_int(&ack_range, pos, end)) {
2189 TRACE_ERROR("quic_dec_int(ack_range) failed", QUIC_EV_CONN_PRSAFRM, qc);
2190 goto err;
2191 }
2192
2193 if (largest < ack_range) {
2194 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
2195 qc, NULL, &largest, &ack_range);
2196 goto err;
2197 }
2198
2199 /* Do not use this node anymore. */
2200 largest_node = NULL;
2201 /* Next range */
2202 smallest = largest - ack_range;
2203
2204 TRACE_PROTO("rcvd next ack range", QUIC_EV_CONN_PRSAFRM,
2205 qc, NULL, &largest, &smallest);
2206 } while (1);
2207
2208 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
2209 *rtt_sample = tick_remain(time_sent, now_ms);
2210 qel->pktns->rx.largest_acked_pn = ack->largest_ack;
2211 }
2212
2213 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
2214 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
2215 qc_packet_loss_lookup(qel->pktns, qc, &lost_pkts);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01002216 if (!qc_release_lost_pkts(qc, qel->pktns, &lost_pkts, now_ms))
2217 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002218 }
2219 qc_treat_newly_acked_pkts(qc, &newly_acked_pkts);
2220 if (quic_peer_validated_addr(qc))
2221 qc->path->loss.pto_count = 0;
2222 qc_set_timer(qc);
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01002223 qc_notify_send(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002224 }
2225
2226 ret = 1;
2227 leave:
2228 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2229 return ret;
2230
2231 err:
2232 free_quic_tx_pkts(qc, &newly_acked_pkts);
2233 goto leave;
2234}
2235
2236/* This function gives the detail of the SSL error. It is used only
2237 * if the debug mode and the verbose mode are activated. It dump all
2238 * the SSL error until the stack was empty.
2239 */
2240static forceinline void qc_ssl_dump_errors(struct connection *conn)
2241{
2242 if (unlikely(global.mode & MODE_DEBUG)) {
2243 while (1) {
2244 const char *func = NULL;
2245 unsigned long ret;
2246
2247 ERR_peek_error_func(&func);
2248 ret = ERR_get_error();
2249 if (!ret)
2250 return;
2251
2252 fprintf(stderr, "conn. @%p OpenSSL error[0x%lx] %s: %s\n", conn, ret,
2253 func, ERR_reason_error_string(ret));
2254 }
2255 }
2256}
2257
2258int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx,
2259 const char **str, int *len);
2260
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002261/* Finalize <qc> QUIC connection:
2262 * - initialize the Initial QUIC TLS context for negotiated version,
2263 * - derive the secrets for this context,
2264 * - set them into the TLS stack,
2265 *
2266 * MUST be called after having received the remote transport parameters which
2267 * are parsed when the TLS callback for the ClientHello message is called upon
2268 * SSL_do_handshake() calls, not necessarily at the first time as this TLS
2269 * message may be splitted between packets
2270 * Return 1 if succeeded, 0 if not.
2271 */
2272static int qc_conn_finalize(struct quic_conn *qc, int server)
2273{
2274 int ret = 0;
2275
2276 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
2277
2278 if (qc->flags & QUIC_FL_CONN_FINALIZED)
2279 goto finalized;
2280
2281 if (qc->negotiated_version &&
2282 !qc_new_isecs(qc, &qc->negotiated_ictx, qc->negotiated_version,
2283 qc->odcid.data, qc->odcid.len, server))
2284 goto out;
2285
2286 /* This connection is functional (ready to send/receive) */
2287 qc->flags |= QUIC_FL_CONN_FINALIZED;
2288
2289 finalized:
2290 ret = 1;
2291 out:
2292 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
2293 return ret;
2294}
2295
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002296/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
2297 * from <qel> encryption level with <ctx> as QUIC connection context.
2298 * Remaining parameter are there for debugging purposes.
2299 * Return 1 if succeeded, 0 if not.
2300 */
2301static inline int qc_provide_cdata(struct quic_enc_level *el,
2302 struct ssl_sock_ctx *ctx,
2303 const unsigned char *data, size_t len,
2304 struct quic_rx_packet *pkt,
2305 struct quic_rx_crypto_frm *cf)
2306{
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002307#ifdef DEBUG_STRICT
2308 enum ncb_ret ncb_ret;
2309#endif
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002310 int ssl_err, state;
2311 struct quic_conn *qc;
2312 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002313 struct ncbuf *ncbuf = &el->cstream->rx.ncbuf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002314
2315 ssl_err = SSL_ERROR_NONE;
2316 qc = ctx->qc;
2317
2318 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, qc);
2319
2320 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
2321 TRACE_ERROR("SSL_provide_quic_data() error",
2322 QUIC_EV_CONN_SSLDATA, qc, pkt, cf, ctx->ssl);
2323 goto leave;
2324 }
2325
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002326 TRACE_PROTO("in order CRYPTO data",
2327 QUIC_EV_CONN_SSLDATA, qc, NULL, cf, ctx->ssl);
2328
2329 state = qc->state;
2330 if (state < QUIC_HS_ST_COMPLETE) {
2331 ssl_err = SSL_do_handshake(ctx->ssl);
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002332
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01002333 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
2334 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
2335 goto leave;
2336 }
2337
Frédéric Lécailleaf25a692023-02-01 17:56:57 +01002338 /* Finalize the connection as soon as possible if the peer transport parameters
2339 * have been received. This may be useful to send packets even if this
2340 * handshake fails.
2341 */
2342 if ((qc->flags & QUIC_FL_CONN_TX_TP_RECEIVED) && !qc_conn_finalize(qc, 1)) {
2343 TRACE_ERROR("connection finalization failed", QUIC_EV_CONN_IO_CB, qc, &state);
2344 goto leave;
2345 }
2346
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002347 if (ssl_err != 1) {
2348 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2349 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2350 TRACE_PROTO("SSL handshake in progress",
2351 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2352 goto out;
2353 }
2354
2355 /* TODO: Should close the connection asap */
2356 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2357 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2358 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2359 HA_ATOMIC_INC(&qc->prx_counters->hdshk_fail);
2360 }
2361 TRACE_ERROR("SSL handshake error", QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2362 qc_ssl_dump_errors(ctx->conn);
2363 ERR_clear_error();
2364 goto leave;
2365 }
2366
2367 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_IO_CB, qc, &state);
2368
2369 /* Check the alpn could be negotiated */
2370 if (!qc->app_ops) {
2371 TRACE_ERROR("No negotiated ALPN", QUIC_EV_CONN_IO_CB, qc, &state);
2372 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
2373 goto leave;
2374 }
2375
2376 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2377 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_IO_CB, qc, &state);
2378 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2379 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2380 }
2381 /* I/O callback switch */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002382 qc->wait_event.tasklet->process = quic_conn_app_io_cb;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002383 if (qc_is_listener(ctx->qc)) {
2384 qc->state = QUIC_HS_ST_CONFIRMED;
2385 /* The connection is ready to be accepted. */
2386 quic_accept_push_qc(qc);
2387 }
2388 else {
2389 qc->state = QUIC_HS_ST_COMPLETE;
2390 }
2391
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02002392 /* Prepare the next key update */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002393 if (!quic_tls_key_update(qc)) {
2394 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_IO_CB, qc);
2395 goto leave;
2396 }
2397 } else {
2398 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
2399 if (ssl_err != 1) {
2400 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2401 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2402 TRACE_PROTO("SSL post handshake in progress",
2403 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2404 goto out;
2405 }
2406
2407 TRACE_ERROR("SSL post handshake error",
2408 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2409 goto leave;
2410 }
2411
2412 TRACE_STATE("SSL post handshake succeeded", QUIC_EV_CONN_IO_CB, qc, &state);
2413 }
2414
2415 out:
2416 ret = 1;
2417 leave:
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002418 /* The CRYPTO data are consumed even in case of an error to release
2419 * the memory asap.
2420 */
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002421 if (!ncb_is_null(ncbuf)) {
2422#ifdef DEBUG_STRICT
2423 ncb_ret = ncb_advance(ncbuf, len);
2424 /* ncb_advance() must always succeed. This is guaranteed as
2425 * this is only done inside a data block. If false, this will
2426 * lead to handshake failure with quic_enc_level offset shifted
2427 * from buffer data.
2428 */
2429 BUG_ON(ncb_ret != NCB_RET_OK);
2430#else
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002431 ncb_advance(ncbuf, len);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002432#endif
2433 }
2434
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002435 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, qc);
2436 return ret;
2437}
2438
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002439/* Parse a STREAM frame <strm_frm> received in <pkt> packet for <qc>
2440 * connection. <fin> is true if FIN bit is set on frame type.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002441 *
2442 * Return 1 on success. On error, 0 is returned. In this case, the packet
2443 * containing the frame must not be acknowledged.
2444 */
2445static inline int qc_handle_strm_frm(struct quic_rx_packet *pkt,
2446 struct quic_stream *strm_frm,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002447 struct quic_conn *qc, char fin)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002448{
2449 int ret;
2450
2451 /* RFC9000 13.1. Packet Processing
2452 *
2453 * A packet MUST NOT be acknowledged until packet protection has been
2454 * successfully removed and all frames contained in the packet have
2455 * been processed. For STREAM frames, this means the data has been
2456 * enqueued in preparation to be received by the application protocol,
2457 * but it does not require that data be delivered and consumed.
2458 */
2459 TRACE_ENTER(QUIC_EV_CONN_PRSFRM, qc);
2460
2461 ret = qcc_recv(qc->qcc, strm_frm->id, strm_frm->len,
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002462 strm_frm->offset.key, fin, (char *)strm_frm->data);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002463
2464 /* frame rejected - packet must not be acknowledeged */
2465 TRACE_LEAVE(QUIC_EV_CONN_PRSFRM, qc);
2466 return !ret;
2467}
2468
2469/* Duplicate all frames from <pkt_frm_list> list into <out_frm_list> list
2470 * for <qc> QUIC connection.
2471 * This is a best effort function which never fails even if no memory could be
2472 * allocated to duplicate these frames.
2473 */
2474static void qc_dup_pkt_frms(struct quic_conn *qc,
2475 struct list *pkt_frm_list, struct list *out_frm_list)
2476{
2477 struct quic_frame *frm, *frmbak;
2478 struct list tmp = LIST_HEAD_INIT(tmp);
2479
2480 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2481
2482 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
2483 struct quic_frame *dup_frm, *origin;
2484
2485 switch (frm->type) {
2486 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2487 {
2488 struct quic_stream *strm_frm = &frm->stream;
2489 struct eb64_node *node = NULL;
2490 struct qc_stream_desc *stream_desc;
2491
2492 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
2493 if (!node) {
2494 TRACE_DEVEL("ignored frame for a released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
2495 continue;
2496 }
2497
2498 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
2499 /* Do not resend this frame if in the "already acked range" */
2500 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
2501 TRACE_DEVEL("ignored frame in already acked range",
2502 QUIC_EV_CONN_PRSAFRM, qc, frm);
2503 continue;
2504 }
2505 else if (strm_frm->offset.key < stream_desc->ack_offset) {
2506 strm_frm->offset.key = stream_desc->ack_offset;
2507 TRACE_DEVEL("updated partially acked frame",
2508 QUIC_EV_CONN_PRSAFRM, qc, frm);
2509 }
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01002510
2511 strm_frm->dup = 1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002512 break;
2513 }
2514
2515 default:
2516 break;
2517 }
2518
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002519 /* If <frm> is already a copy of another frame, we must take
2520 * its original frame as source for the copy.
2521 */
2522 origin = frm->origin ? frm->origin : frm;
2523 dup_frm = qc_frm_dup(origin);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002524 if (!dup_frm) {
2525 TRACE_ERROR("could not duplicate frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2526 break;
2527 }
2528
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002529 TRACE_DEVEL("built probing frame", QUIC_EV_CONN_PRSAFRM, qc, origin);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002530 if (origin->pkt) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002531 TRACE_DEVEL("duplicated from packet", QUIC_EV_CONN_PRSAFRM,
2532 qc, NULL, &origin->pkt->pn_node.key);
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002533 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002534 else {
2535 /* <origin> is a frame which was sent from a packet detected as lost. */
2536 TRACE_DEVEL("duplicated from lost packet", QUIC_EV_CONN_PRSAFRM, qc);
2537 }
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01002538
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002539 LIST_APPEND(&tmp, &dup_frm->list);
2540 }
2541
2542 LIST_SPLICE(out_frm_list, &tmp);
2543
2544 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2545}
2546
2547/* Prepare a fast retransmission from <qel> encryption level */
2548static void qc_prep_fast_retrans(struct quic_conn *qc,
2549 struct quic_enc_level *qel,
2550 struct list *frms1, struct list *frms2)
2551{
2552 struct eb_root *pkts = &qel->pktns->tx.pkts;
2553 struct list *frms = frms1;
2554 struct eb64_node *node;
2555 struct quic_tx_packet *pkt;
2556
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002557 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002558
2559 BUG_ON(frms1 == frms2);
2560
2561 pkt = NULL;
2562 node = eb64_first(pkts);
2563 start:
2564 while (node) {
2565 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
2566 node = eb64_next(node);
2567 /* Skip the empty and coalesced packets */
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002568 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
2569 "--> pn=%llu (%d %d)", (ull)pkt->pn_node.key,
2570 LIST_ISEMPTY(&pkt->frms), !!(pkt->flags & QUIC_FL_TX_PACKET_COALESCED));
Frédéric Lécaille055e8262023-01-31 10:10:06 +01002571 if (!LIST_ISEMPTY(&pkt->frms))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002572 break;
2573 }
2574
2575 if (!pkt)
2576 goto leave;
2577
2578 /* When building a packet from another one, the field which may increase the
2579 * packet size is the packet number. And the maximum increase is 4 bytes.
2580 */
2581 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2582 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
2583 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2584 goto leave;
2585 }
2586
2587 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_SPPKTS, qc, pkt);
2588 qc_dup_pkt_frms(qc, &pkt->frms, frms);
2589 if (frms == frms1 && frms2) {
2590 frms = frms2;
2591 goto start;
2592 }
2593 leave:
2594 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
2595}
2596
2597/* Prepare a fast retransmission during a handshake after a client
2598 * has resent Initial packets. According to the RFC a server may retransmit
2599 * Initial packets send them coalescing with others (Handshake here).
2600 * (Listener only function).
2601 */
2602static void qc_prep_hdshk_fast_retrans(struct quic_conn *qc,
2603 struct list *ifrms, struct list *hfrms)
2604{
2605 struct list itmp = LIST_HEAD_INIT(itmp);
2606 struct list htmp = LIST_HEAD_INIT(htmp);
2607
2608 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2609 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2610 struct quic_enc_level *qel = iqel;
2611 struct eb_root *pkts;
2612 struct eb64_node *node;
2613 struct quic_tx_packet *pkt;
2614 struct list *tmp = &itmp;
2615
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002616 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002617 start:
2618 pkt = NULL;
2619 pkts = &qel->pktns->tx.pkts;
2620 node = eb64_first(pkts);
2621 /* Skip the empty packet (they have already been retransmitted) */
2622 while (node) {
2623 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
Frédéric Lécaille6dead912023-01-30 17:27:32 +01002624 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_SPPKTS, qc, 0, 0, 0,
2625 "--> pn=%llu (%d %d)", (ull)pkt->pn_node.key,
2626 LIST_ISEMPTY(&pkt->frms), !!(pkt->flags & QUIC_FL_TX_PACKET_COALESCED));
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002627 if (!LIST_ISEMPTY(&pkt->frms) && !(pkt->flags & QUIC_FL_TX_PACKET_COALESCED))
2628 break;
2629 node = eb64_next(node);
2630 }
2631
2632 if (!pkt)
2633 goto end;
2634
2635 /* When building a packet from another one, the field which may increase the
2636 * packet size is the packet number. And the maximum increase is 4 bytes.
2637 */
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002638 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
2639 size_t dglen = pkt->len + 4;
2640
2641 dglen += pkt->next ? pkt->next->len + 4 : 0;
2642 if (dglen > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
2643 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2644 if (pkt->next)
2645 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt->next);
2646 goto end;
2647 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002648 }
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;
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002661 TRACE_DEVEL("looping for next packet", QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002662 goto requeue;
2663 }
2664 }
2665
2666 end:
2667 LIST_SPLICE(ifrms, &itmp);
2668 LIST_SPLICE(hfrms, &htmp);
2669
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01002670 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002671}
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
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002690/* Cancel a request on connection <qc> for stream id <id>. This is useful when
2691 * the client opens a new stream but the MUX has already been released. A
Amaury Denoyelle75463012023-02-20 10:31:27 +01002692 * STOP_SENDING + RESET_STREAM frames are prepared for emission.
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002693 *
2694 * TODO this function is closely related to H3. Its place should be in H3 layer
2695 * instead of quic-conn but this requires an architecture adjustment.
2696 *
2697 * Returns 1 on sucess else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002698 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002699static int qc_h3_request_reject(struct quic_conn *qc, uint64_t id)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002700{
2701 int ret = 0;
Amaury Denoyelle75463012023-02-20 10:31:27 +01002702 struct quic_frame *ss, *rs;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002703 struct quic_enc_level *qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002704 const uint64_t app_error_code = H3_REQUEST_REJECTED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002705
2706 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2707
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002708 /* Do not emit rejection for unknown unidirectional stream as it is
2709 * forbidden to close some of them (H3 control stream and QPACK
2710 * encoder/decoder streams).
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002711 */
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002712 if (quic_stream_is_uni(id)) {
2713 ret = 1;
2714 goto out;
2715 }
2716
Amaury Denoyelle75463012023-02-20 10:31:27 +01002717 ss = qc_frm_alloc(QUIC_FT_STOP_SENDING);
2718 if (!ss) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002719 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2720 goto out;
2721 }
2722
Amaury Denoyelle75463012023-02-20 10:31:27 +01002723 ss->stop_sending.id = id;
2724 ss->stop_sending.app_error_code = app_error_code;
2725
2726 rs = qc_frm_alloc(QUIC_FT_RESET_STREAM);
2727 if (!rs) {
2728 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2729 qc_frm_free(&ss);
2730 goto out;
2731 }
2732
2733 rs->reset_stream.id = id;
2734 rs->reset_stream.app_error_code = app_error_code;
2735 rs->reset_stream.final_size = 0;
2736
2737 LIST_APPEND(&qel->pktns->tx.frms, &ss->list);
2738 LIST_APPEND(&qel->pktns->tx.frms, &rs->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002739 ret = 1;
2740 out:
2741 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2742 return ret;
2743}
2744
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002745/* Release the underlying memory use by <ncbuf> non-contiguous buffer */
2746static void quic_free_ncbuf(struct ncbuf *ncbuf)
2747{
2748 struct buffer buf;
2749
2750 if (ncb_is_null(ncbuf))
2751 return;
2752
2753 buf = b_make(ncbuf->area, ncbuf->size, 0, 0);
2754 b_free(&buf);
2755 offer_buffers(NULL, 1);
2756
2757 *ncbuf = NCBUF_NULL;
2758}
2759
2760/* Allocate the underlying required memory for <ncbuf> non-contiguous buffer */
2761static struct ncbuf *quic_get_ncbuf(struct ncbuf *ncbuf)
2762{
2763 struct buffer buf = BUF_NULL;
2764
2765 if (!ncb_is_null(ncbuf))
2766 return ncbuf;
2767
2768 b_alloc(&buf);
2769 BUG_ON(b_is_null(&buf));
2770
2771 *ncbuf = ncb_make(buf.area, buf.size, 0);
2772 ncb_init(ncbuf, 0);
2773
2774 return ncbuf;
2775}
2776
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002777/* Parse <frm> CRYPTO frame coming with <pkt> packet at <qel> <qc> connectionn.
2778 * Returns 1 if succeeded, 0 if not. Also set <*fast_retrans> to 1 if the
2779 * speed up handshake completion may be run after having received duplicated
2780 * CRYPTO data.
2781 */
2782static int qc_handle_crypto_frm(struct quic_conn *qc,
2783 struct quic_crypto *frm, struct quic_rx_packet *pkt,
2784 struct quic_enc_level *qel, int *fast_retrans)
2785{
2786 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002787 enum ncb_ret ncb_ret;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002788 /* XXX TO DO: <cfdebug> is used only for the traces. */
2789 struct quic_rx_crypto_frm cfdebug = {
2790 .offset_node.key = frm->offset,
2791 .len = frm->len,
2792 };
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002793 struct quic_cstream *cstream = qel->cstream;
2794 struct ncbuf *ncbuf = &qel->cstream->rx.ncbuf;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002795
2796 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2797 if (unlikely(qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD)) {
2798 TRACE_PROTO("CRYPTO data discarded",
2799 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2800 goto done;
2801 }
2802
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002803 if (unlikely(frm->offset < cstream->rx.offset)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002804 size_t diff;
2805
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002806 if (frm->offset + frm->len <= cstream->rx.offset) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002807 /* Nothing to do */
2808 TRACE_PROTO("Already received CRYPTO data",
2809 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2810 if (qc_is_listener(qc) && qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] &&
2811 !(qc->flags & QUIC_FL_CONN_HANDSHAKE_SPEED_UP))
2812 *fast_retrans = 1;
2813 goto done;
2814 }
2815
2816 TRACE_PROTO("Partially already received CRYPTO data",
2817 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2818
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002819 diff = cstream->rx.offset - frm->offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002820 frm->len -= diff;
2821 frm->data += diff;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002822 frm->offset = cstream->rx.offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002823 }
2824
Amaury Denoyelleff95f2d2022-11-18 14:50:06 +01002825 if (frm->offset == cstream->rx.offset && ncb_is_empty(ncbuf)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002826 if (!qc_provide_cdata(qel, qc->xprt_ctx, frm->data, frm->len,
2827 pkt, &cfdebug)) {
2828 // trace already emitted by function above
2829 goto leave;
2830 }
2831
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002832 cstream->rx.offset += frm->len;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002833 TRACE_DEVEL("increment crypto level offset", QUIC_EV_CONN_PHPKTS, qc, qel);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002834 goto done;
2835 }
2836
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002837 if (!quic_get_ncbuf(ncbuf) ||
2838 ncb_is_null(ncbuf)) {
2839 TRACE_ERROR("CRYPTO ncbuf allocation failed", QUIC_EV_CONN_PRSHPKT, qc);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002840 goto leave;
2841 }
2842
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002843 /* frm->offset > cstream-trx.offset */
2844 ncb_ret = ncb_add(ncbuf, frm->offset - cstream->rx.offset,
2845 (const char *)frm->data, frm->len, NCB_ADD_COMPARE);
2846 if (ncb_ret != NCB_RET_OK) {
2847 if (ncb_ret == NCB_RET_DATA_REJ) {
2848 TRACE_ERROR("overlapping data rejected", QUIC_EV_CONN_PRSHPKT, qc);
2849 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
2850 }
2851 else if (ncb_ret == NCB_RET_GAP_SIZE) {
2852 TRACE_ERROR("cannot bufferize frame due to gap size limit",
2853 QUIC_EV_CONN_PRSHPKT, qc);
2854 }
2855 goto leave;
2856 }
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002857
2858 done:
2859 ret = 1;
2860 leave:
2861 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2862 return ret;
2863}
2864
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002865/* Parse all the frames of <pkt> QUIC packet for QUIC connection <qc> and <qel>
2866 * as encryption level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002867 * Returns 1 if succeeded, 0 if failed.
2868 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002869static int qc_parse_pkt_frms(struct quic_conn *qc, struct quic_rx_packet *pkt,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002870 struct quic_enc_level *qel)
2871{
2872 struct quic_frame frm;
2873 const unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002874 int fast_retrans = 0, ret = 0;
2875
2876 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2877 /* Skip the AAD */
2878 pos = pkt->data + pkt->aad_len;
2879 end = pkt->data + pkt->len;
2880
2881 while (pos < end) {
2882 if (!qc_parse_frm(&frm, pkt, &pos, end, qc)) {
2883 // trace already emitted by function above
2884 goto leave;
2885 }
2886
2887 TRACE_PROTO("RX frame", QUIC_EV_CONN_PSTRM, qc, &frm);
2888 switch (frm.type) {
2889 case QUIC_FT_PADDING:
2890 break;
2891 case QUIC_FT_PING:
2892 break;
2893 case QUIC_FT_ACK:
2894 {
2895 unsigned int rtt_sample;
2896
2897 rtt_sample = 0;
2898 if (!qc_parse_ack_frm(qc, &frm, qel, &rtt_sample, &pos, end)) {
2899 // trace already emitted by function above
2900 goto leave;
2901 }
2902
2903 if (rtt_sample) {
2904 unsigned int ack_delay;
2905
2906 ack_delay = !quic_application_pktns(qel->pktns, qc) ? 0 :
2907 qc->state >= QUIC_HS_ST_CONFIRMED ?
2908 MS_TO_TICKS(QUIC_MIN(quic_ack_delay_ms(&frm.ack, qc), qc->max_ack_delay)) :
2909 MS_TO_TICKS(quic_ack_delay_ms(&frm.ack, qc));
2910 quic_loss_srtt_update(&qc->path->loss, rtt_sample, ack_delay, qc);
2911 }
2912 break;
2913 }
2914 case QUIC_FT_RESET_STREAM:
Amaury Denoyelle5854fc02022-12-09 16:25:48 +01002915 if (qc->mux_state == QC_MUX_READY) {
2916 struct quic_reset_stream *rs = &frm.reset_stream;
2917 qcc_recv_reset_stream(qc->qcc, rs->id, rs->app_error_code, rs->final_size);
2918 }
2919 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002920 case QUIC_FT_STOP_SENDING:
2921 {
2922 struct quic_stop_sending *stop_sending = &frm.stop_sending;
2923 if (qc->mux_state == QC_MUX_READY) {
2924 if (qcc_recv_stop_sending(qc->qcc, stop_sending->id,
2925 stop_sending->app_error_code)) {
2926 TRACE_ERROR("qcc_recv_stop_sending() failed", QUIC_EV_CONN_PRSHPKT, qc);
2927 goto leave;
2928 }
2929 }
2930 break;
2931 }
2932 case QUIC_FT_CRYPTO:
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002933 if (!qc_handle_crypto_frm(qc, &frm.crypto, pkt, qel, &fast_retrans))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002934 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002935 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002936 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2937 {
2938 struct quic_stream *stream = &frm.stream;
2939 unsigned nb_streams = qc->rx.strms[qcs_id_type(stream->id)].nb_streams;
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002940 const char fin = frm.type & QUIC_STREAM_FRAME_TYPE_FIN_BIT;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002941
2942 /* The upper layer may not be allocated. */
2943 if (qc->mux_state != QC_MUX_READY) {
2944 if ((stream->id >> QCS_ID_TYPE_SHIFT) < nb_streams) {
2945 TRACE_DATA("Already closed stream", QUIC_EV_CONN_PRSHPKT, qc);
2946 break;
2947 }
2948 else {
2949 TRACE_DEVEL("No mux for new stream", QUIC_EV_CONN_PRSHPKT, qc);
Amaury Denoyelle38836b62023-02-07 14:24:54 +01002950 if (qc->app_ops == &h3_ops) {
Amaury Denoyelle156a89a2023-02-20 10:32:16 +01002951 if (!qc_h3_request_reject(qc, stream->id)) {
2952 TRACE_ERROR("error on request rejection", QUIC_EV_CONN_PRSHPKT, qc);
2953 /* This packet will not be acknowledged */
2954 goto leave;
2955 }
2956 }
2957 else {
2958 /* This packet will not be acknowledged */
2959 goto leave;
Frédéric Lécailled18025e2023-01-20 15:33:50 +01002960 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002961 }
2962 }
2963
Amaury Denoyelle2216b082023-02-02 14:59:36 +01002964 if (!qc_handle_strm_frm(pkt, stream, qc, fin)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002965 TRACE_ERROR("qc_handle_strm_frm() failed", QUIC_EV_CONN_PRSHPKT, qc);
2966 goto leave;
2967 }
2968
2969 break;
2970 }
2971 case QUIC_FT_MAX_DATA:
2972 if (qc->mux_state == QC_MUX_READY) {
2973 struct quic_max_data *data = &frm.max_data;
2974 qcc_recv_max_data(qc->qcc, data->max_data);
2975 }
2976 break;
2977 case QUIC_FT_MAX_STREAM_DATA:
2978 if (qc->mux_state == QC_MUX_READY) {
2979 struct quic_max_stream_data *data = &frm.max_stream_data;
2980 if (qcc_recv_max_stream_data(qc->qcc, data->id,
2981 data->max_stream_data)) {
2982 TRACE_ERROR("qcc_recv_max_stream_data() failed", QUIC_EV_CONN_PRSHPKT, qc);
2983 goto leave;
2984 }
2985 }
2986 break;
2987 case QUIC_FT_MAX_STREAMS_BIDI:
2988 case QUIC_FT_MAX_STREAMS_UNI:
2989 break;
2990 case QUIC_FT_DATA_BLOCKED:
2991 HA_ATOMIC_INC(&qc->prx_counters->data_blocked);
2992 break;
2993 case QUIC_FT_STREAM_DATA_BLOCKED:
2994 HA_ATOMIC_INC(&qc->prx_counters->stream_data_blocked);
2995 break;
2996 case QUIC_FT_STREAMS_BLOCKED_BIDI:
2997 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_bidi);
2998 break;
2999 case QUIC_FT_STREAMS_BLOCKED_UNI:
3000 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_uni);
3001 break;
3002 case QUIC_FT_NEW_CONNECTION_ID:
3003 case QUIC_FT_RETIRE_CONNECTION_ID:
3004 /* XXX TO DO XXX */
3005 break;
3006 case QUIC_FT_CONNECTION_CLOSE:
3007 case QUIC_FT_CONNECTION_CLOSE_APP:
3008 /* Increment the error counters */
3009 qc_cc_err_count_inc(qc, &frm);
3010 if (!(qc->flags & QUIC_FL_CONN_DRAINING)) {
3011 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
3012 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
3013 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
3014 }
3015 TRACE_STATE("Entering draining state", QUIC_EV_CONN_PRSHPKT, qc);
3016 /* RFC 9000 10.2. Immediate Close:
3017 * The closing and draining connection states exist to ensure
3018 * that connections close cleanly and that delayed or reordered
3019 * packets are properly discarded. These states SHOULD persist
3020 * for at least three times the current PTO interval...
3021 *
3022 * Rearm the idle timeout only one time when entering draining
3023 * state.
3024 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003025 qc->flags |= QUIC_FL_CONN_DRAINING|QUIC_FL_CONN_IMMEDIATE_CLOSE;
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01003026 qc_idle_timer_do_rearm(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003027 qc_notify_close(qc);
3028 }
3029 break;
3030 case QUIC_FT_HANDSHAKE_DONE:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003031 if (qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003032 TRACE_ERROR("non accepted QUIC_FT_HANDSHAKE_DONE frame",
3033 QUIC_EV_CONN_PRSHPKT, qc);
3034 goto leave;
3035 }
3036
3037 qc->state = QUIC_HS_ST_CONFIRMED;
3038 break;
3039 default:
3040 TRACE_ERROR("unknosw frame type", QUIC_EV_CONN_PRSHPKT, qc);
3041 goto leave;
3042 }
3043 }
3044
3045 /* Flag this packet number space as having received a packet. */
3046 qel->pktns->flags |= QUIC_FL_PKTNS_PKT_RECEIVED;
3047
3048 if (fast_retrans) {
3049 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
3050 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
3051
3052 TRACE_PROTO("speeding up handshake completion", QUIC_EV_CONN_PRSHPKT, qc);
3053 qc_prep_hdshk_fast_retrans(qc, &iqel->pktns->tx.frms, &hqel->pktns->tx.frms);
3054 qc->flags |= QUIC_FL_CONN_HANDSHAKE_SPEED_UP;
3055 }
3056
3057 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
3058 * has successfully parse a Handshake packet. The Initial encryption must also
3059 * be discarded.
3060 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003061 if (pkt->type == QUIC_PACKET_TYPE_HANDSHAKE && qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003062 if (qc->state >= QUIC_HS_ST_SERVER_INITIAL) {
3063 if (!(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx.flags &
3064 QUIC_FL_TLS_SECRETS_DCD)) {
3065 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3066 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PRSHPKT, qc);
3067 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003068 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003069 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3070 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3071 }
3072 if (qc->state < QUIC_HS_ST_SERVER_HANDSHAKE)
3073 qc->state = QUIC_HS_ST_SERVER_HANDSHAKE;
3074 }
3075 }
3076
3077 ret = 1;
3078 leave:
3079 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
3080 return ret;
3081}
3082
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003083
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003084/* Allocate Tx buffer from <qc> quic-conn if needed.
3085 *
3086 * Returns allocated buffer or NULL on error.
3087 */
3088static struct buffer *qc_txb_alloc(struct quic_conn *qc)
3089{
3090 struct buffer *buf = &qc->tx.buf;
3091 if (!b_alloc(buf))
3092 return NULL;
3093
3094 return buf;
3095}
3096
3097/* Free Tx buffer from <qc> if it is empty. */
3098static void qc_txb_release(struct quic_conn *qc)
3099{
3100 struct buffer *buf = &qc->tx.buf;
3101
3102 /* For the moment sending function is responsible to purge the buffer
3103 * entirely. It may change in the future but this requires to be able
3104 * to reuse old data.
Frédéric Lécaillebbf86be2023-02-20 09:28:58 +01003105 * For the momemt we do not care to leave data in the buffer for
3106 * a connection which is supposed to be killed asap.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003107 */
3108 BUG_ON_HOT(buf && b_data(buf));
3109
3110 if (!b_data(buf)) {
3111 b_free(buf);
3112 offer_buffers(NULL, 1);
3113 }
3114}
3115
3116/* Commit a datagram payload written into <buf> of length <length>. <first_pkt>
3117 * must contains the address of the first packet stored in the payload.
3118 *
3119 * Caller is responsible that there is enough space in the buffer.
3120 */
3121static void qc_txb_store(struct buffer *buf, uint16_t length,
3122 struct quic_tx_packet *first_pkt)
3123{
3124 const size_t hdlen = sizeof(uint16_t) + sizeof(void *);
3125 BUG_ON_HOT(b_contig_space(buf) < hdlen); /* this must not happen */
3126
3127 write_u16(b_tail(buf), length);
3128 write_ptr(b_tail(buf) + sizeof(length), first_pkt);
3129 b_add(buf, hdlen + length);
3130}
3131
3132/* Returns 1 if a packet may be built for <qc> from <qel> encryption level
3133 * with <frms> as ack-eliciting frame list to send, 0 if not.
3134 * <cc> must equal to 1 if an immediate close was asked, 0 if not.
3135 * <probe> must equalt to 1 if a probing packet is required, 0 if not.
3136 * <force_ack> may be set to 1 if you want to force an ack.
3137 */
3138static int qc_may_build_pkt(struct quic_conn *qc, struct list *frms,
3139 struct quic_enc_level *qel, int cc, int probe, int force_ack)
3140{
3141 unsigned int must_ack = force_ack ||
3142 (LIST_ISEMPTY(frms) && (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED));
3143
3144 /* Do not build any more packet if the TX secrets are not available or
3145 * if there is nothing to send, i.e. if no CONNECTION_CLOSE or ACK are required
3146 * and if there is no more packets to send upon PTO expiration
3147 * and if there is no more ack-eliciting frames to send or in flight
3148 * congestion control limit is reached for prepared data
3149 */
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02003150 if (!quic_tls_has_tx_sec(qel) ||
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003151 (!cc && !probe && !must_ack &&
3152 (LIST_ISEMPTY(frms) || qc->path->prep_in_flight >= qc->path->cwnd))) {
3153 return 0;
3154 }
3155
3156 return 1;
3157}
3158
3159/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3160 * <frms>. Each packet is stored in a distinct datagram written to <buf>.
3161 *
3162 * Each datagram is prepended by a two fields header : the datagram length and
3163 * the address of the packet contained in the datagram.
3164 *
3165 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3166 * -1 if something wrong happened.
3167 */
3168static int qc_prep_app_pkts(struct quic_conn *qc, struct buffer *buf,
3169 struct list *frms)
3170{
3171 int ret = -1;
3172 struct quic_enc_level *qel;
3173 unsigned char *end, *pos;
3174 struct quic_tx_packet *pkt;
3175 size_t total;
3176 /* Each datagram is prepended with its length followed by the address
3177 * of the first packet in the datagram.
3178 */
3179 const size_t dg_headlen = sizeof(uint16_t) + sizeof(pkt);
3180
3181 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3182
3183 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3184 total = 0;
3185 pos = (unsigned char *)b_tail(buf);
3186 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen) {
3187 int err, probe, cc;
3188
3189 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3190 probe = 0;
3191 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3192 /* We do not probe if an immediate close was asked */
3193 if (!cc)
3194 probe = qel->pktns->tx.pto_probe;
3195
3196 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, 0))
3197 break;
3198
3199 /* Leave room for the datagram header */
3200 pos += dg_headlen;
3201 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3202 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3203 }
3204 else {
3205 end = pos + qc->path->mtu;
3206 }
3207
3208 pkt = qc_build_pkt(&pos, end, qel, &qel->tls_ctx, frms, qc, NULL, 0,
3209 QUIC_PACKET_TYPE_SHORT, 0, 0, probe, cc, &err);
3210 switch (err) {
3211 case -2:
3212 // trace already emitted by function above
3213 goto leave;
3214 case -1:
3215 /* As we provide qc_build_pkt() with an enough big buffer to fulfill an
3216 * MTU, we are here because of the congestion control window. There is
3217 * no need to try to reuse this buffer.
3218 */
3219 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3220 goto out;
3221 default:
3222 break;
3223 }
3224
3225 /* This is to please to GCC. We cannot have (err >= 0 && !pkt) */
3226 BUG_ON(!pkt);
3227
3228 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3229 pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3230
3231 total += pkt->len;
3232
3233 /* Write datagram header. */
3234 qc_txb_store(buf, pkt->len, pkt);
3235 }
3236
3237 out:
3238 ret = total;
3239 leave:
3240 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3241 return ret;
3242}
3243
3244/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3245 * <frms>. Several packets can be regrouped in a single datagram. The result is
3246 * written into <buf>.
3247 *
3248 * Each datagram is prepended by a two fields header : the datagram length and
3249 * the address of first packet in the datagram.
3250 *
3251 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3252 * -1 if something wrong happened.
3253 */
3254static int qc_prep_pkts(struct quic_conn *qc, struct buffer *buf,
3255 enum quic_tls_enc_level tel, struct list *tel_frms,
3256 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
3257{
3258 struct quic_enc_level *qel;
3259 unsigned char *end, *pos;
3260 struct quic_tx_packet *first_pkt, *cur_pkt, *prv_pkt;
3261 /* length of datagrams */
3262 uint16_t dglen;
3263 size_t total;
3264 int ret = -1, padding;
3265 /* Each datagram is prepended with its length followed by the address
3266 * of the first packet in the datagram.
3267 */
3268 const size_t dg_headlen = sizeof(uint16_t) + sizeof(first_pkt);
3269 struct list *frms;
3270
3271 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3272
3273 /* Currently qc_prep_pkts() does not handle buffer wrapping so the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003274 * caller must ensure that buf is reset.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003275 */
3276 BUG_ON_HOT(buf->head || buf->data);
3277
3278 total = 0;
3279 qel = &qc->els[tel];
3280 frms = tel_frms;
3281 dglen = 0;
3282 padding = 0;
3283 pos = (unsigned char *)b_head(buf);
3284 first_pkt = prv_pkt = NULL;
3285 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen || prv_pkt) {
3286 int err, probe, cc;
3287 enum quic_pkt_type pkt_type;
3288 struct quic_tls_ctx *tls_ctx;
3289 const struct quic_version *ver;
3290 int force_ack = (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3291 (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
3292 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
3293
3294 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3295 probe = 0;
3296 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3297 /* We do not probe if an immediate close was asked */
3298 if (!cc)
3299 probe = qel->pktns->tx.pto_probe;
3300
3301 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, force_ack)) {
3302 if (prv_pkt)
3303 qc_txb_store(buf, dglen, first_pkt);
3304 /* Let's select the next encryption level */
3305 if (tel != next_tel && next_tel != QUIC_TLS_ENC_LEVEL_NONE) {
3306 tel = next_tel;
3307 frms = next_tel_frms;
3308 qel = &qc->els[tel];
3309 /* Build a new datagram */
3310 prv_pkt = NULL;
3311 TRACE_DEVEL("next encryption level selected", QUIC_EV_CONN_PHPKTS, qc);
3312 continue;
3313 }
3314 break;
3315 }
3316
3317 pkt_type = quic_tls_level_pkt_type(tel);
3318 if (!prv_pkt) {
3319 /* Leave room for the datagram header */
3320 pos += dg_headlen;
3321 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3322 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3323 }
3324 else {
3325 end = pos + qc->path->mtu;
3326 }
3327 }
3328
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003329 /* RFC 9000 14.1 Initial datagram size
3330 * a server MUST expand the payload of all UDP datagrams carrying ack-eliciting
3331 * Initial packets to at least the smallest allowed maximum datagram size of
3332 * 1200 bytes.
3333 *
3334 * Ensure that no ack-eliciting packets are sent into too small datagrams
3335 */
3336 if (pkt_type == QUIC_PACKET_TYPE_INITIAL && !LIST_ISEMPTY(tel_frms)) {
3337 if (end - pos < QUIC_INITIAL_PACKET_MINLEN) {
Frédéric Lécailled30a04a2023-02-21 16:44:05 +01003338 TRACE_PROTO("No more enough room to build an Initial packet",
Frédéric Lécaille69e71182023-02-20 14:39:41 +01003339 QUIC_EV_CONN_PHPKTS, qc);
3340 goto out;
3341 }
3342
3343 /* Pad this Initial packet if there is no ack-eliciting frames to send from
3344 * the next packet number space.
3345 */
3346 if (LIST_ISEMPTY(next_tel_frms))
3347 padding = 1;
3348 }
3349
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003350 if (qc->negotiated_version) {
3351 ver = qc->negotiated_version;
3352 if (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL])
3353 tls_ctx = &qc->negotiated_ictx;
3354 else
3355 tls_ctx = &qel->tls_ctx;
3356 }
3357 else {
3358 ver = qc->original_version;
3359 tls_ctx = &qel->tls_ctx;
3360 }
3361
3362 cur_pkt = qc_build_pkt(&pos, end, qel, tls_ctx, frms,
3363 qc, ver, dglen, pkt_type,
3364 force_ack, padding, probe, cc, &err);
3365 switch (err) {
3366 case -2:
3367 // trace already emitted by function above
3368 goto leave;
3369 case -1:
3370 /* If there was already a correct packet present, set the
3371 * current datagram as prepared into <cbuf>.
3372 */
3373 if (prv_pkt)
3374 qc_txb_store(buf, dglen, first_pkt);
3375 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3376 goto out;
3377 default:
3378 break;
3379 }
3380
3381 /* This is to please to GCC. We cannot have (err >= 0 && !cur_pkt) */
3382 BUG_ON(!cur_pkt);
3383
3384 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3385 cur_pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3386
3387 total += cur_pkt->len;
3388 /* keep trace of the first packet in the datagram */
3389 if (!first_pkt)
3390 first_pkt = cur_pkt;
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01003391 /* Attach the current one to the previous one and vice versa */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003392 if (prv_pkt) {
3393 prv_pkt->next = cur_pkt;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01003394 cur_pkt->prev = prv_pkt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003395 cur_pkt->flags |= QUIC_FL_TX_PACKET_COALESCED;
3396 }
3397 /* Let's say we have to build a new dgram */
3398 prv_pkt = NULL;
3399 dglen += cur_pkt->len;
3400 /* Client: discard the Initial encryption keys as soon as
3401 * a handshake packet could be built.
3402 */
3403 if (qc->state == QUIC_HS_ST_CLIENT_INITIAL &&
3404 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
3405 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3406 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PHPKTS, qc);
3407 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
3408 qc_set_timer(qc);
3409 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3410 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3411 qc->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
3412 }
3413 /* If the data for the current encryption level have all been sent,
3414 * select the next level.
3415 */
3416 if ((tel == QUIC_TLS_ENC_LEVEL_INITIAL || tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE) &&
3417 next_tel != QUIC_TLS_ENC_LEVEL_NONE && (LIST_ISEMPTY(frms) && !qel->pktns->tx.pto_probe)) {
3418 /* If QUIC_TLS_ENC_LEVEL_HANDSHAKE was already reached let's try QUIC_TLS_ENC_LEVEL_APP */
3419 if (tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE && next_tel == tel)
3420 next_tel = QUIC_TLS_ENC_LEVEL_APP;
3421 tel = next_tel;
3422 if (tel == QUIC_TLS_ENC_LEVEL_APP)
3423 frms = &qc->els[tel].pktns->tx.frms;
3424 else
3425 frms = next_tel_frms;
3426 qel = &qc->els[tel];
3427 if (!LIST_ISEMPTY(frms)) {
3428 /* If there is data for the next level, do not
3429 * consume a datagram.
3430 */
3431 prv_pkt = cur_pkt;
3432 }
3433 }
3434
3435 /* If we have to build a new datagram, set the current datagram as
3436 * prepared into <cbuf>.
3437 */
3438 if (!prv_pkt) {
3439 qc_txb_store(buf, dglen, first_pkt);
3440 first_pkt = NULL;
3441 dglen = 0;
3442 padding = 0;
3443 }
3444 else if (prv_pkt->type == QUIC_TLS_ENC_LEVEL_INITIAL &&
3445 (!qc_is_listener(qc) ||
3446 prv_pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
3447 padding = 1;
3448 }
3449 }
3450
3451 out:
3452 ret = total;
3453 leave:
3454 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3455 return ret;
3456}
3457
3458/* Send datagrams stored in <buf>.
3459 *
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003460 * This function returns 1 for success. On error, there is several behavior
3461 * depending on underlying sendto() error :
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003462 * - for an unrecoverable error, 0 is returned and connection is killed.
3463 * - a transient error is handled differently if connection has its owned
3464 * socket. If this is the case, 0 is returned and socket is subscribed on the
3465 * poller. The other case is assimilated to a success case with 1 returned.
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003466 * Remaining data are purged from the buffer and will eventually be detected
3467 * as lost which gives the opportunity to retry sending.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003468 */
3469int qc_send_ppkts(struct buffer *buf, struct ssl_sock_ctx *ctx)
3470{
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003471 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003472 struct quic_conn *qc;
3473 char skip_sendto = 0;
3474
3475 qc = ctx->qc;
3476 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
3477 while (b_contig_data(buf, 0)) {
3478 unsigned char *pos;
3479 struct buffer tmpbuf = { };
3480 struct quic_tx_packet *first_pkt, *pkt, *next_pkt;
3481 uint16_t dglen;
3482 size_t headlen = sizeof dglen + sizeof first_pkt;
3483 unsigned int time_sent;
3484
3485 pos = (unsigned char *)b_head(buf);
3486 dglen = read_u16(pos);
3487 BUG_ON_HOT(!dglen); /* this should not happen */
3488
3489 pos += sizeof dglen;
3490 first_pkt = read_ptr(pos);
3491 pos += sizeof first_pkt;
3492 tmpbuf.area = (char *)pos;
3493 tmpbuf.size = tmpbuf.data = dglen;
3494
3495 TRACE_DATA("send dgram", QUIC_EV_CONN_SPPKTS, qc);
3496 /* If sendto is on error just skip the call to it for the rest
3497 * of the loop but continue to purge the buffer. Data will be
3498 * transmitted when QUIC packets are detected as lost on our
3499 * side.
3500 *
3501 * TODO use fd-monitoring to detect when send operation can be
3502 * retry. This should improve the bandwidth without relying on
3503 * retransmission timer. However, it requires a major rework on
3504 * quic-conn fd management.
3505 */
3506 if (!skip_sendto) {
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003507 int ret = qc_snd_buf(qc, &tmpbuf, tmpbuf.data, 0);
3508 if (ret < 0) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003509 TRACE_ERROR("sendto fatal error", QUIC_EV_CONN_SPPKTS, qc);
Amaury Denoyelle1febc2d2023-02-23 11:18:38 +01003510 qc_kill_conn(qc);
3511 b_del(buf, buf->data);
3512 goto leave;
3513 }
3514 else if (!ret) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01003515 /* Connection owned socket : poller will wake us up when transient error is cleared. */
3516 if (qc_test_fd(qc)) {
3517 TRACE_ERROR("sendto error, subscribe to poller", QUIC_EV_CONN_SPPKTS, qc);
3518 goto leave;
3519 }
3520
3521 /* No connection owned-socket : rely on retransmission to retry sending. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003522 skip_sendto = 1;
3523 TRACE_ERROR("sendto error, simulate sending for the rest of data", QUIC_EV_CONN_SPPKTS, qc);
3524 }
3525 }
3526
3527 b_del(buf, dglen + headlen);
3528 qc->tx.bytes += tmpbuf.data;
3529 time_sent = now_ms;
3530
3531 for (pkt = first_pkt; pkt; pkt = next_pkt) {
Frédéric Lécailleceb88b82023-02-20 14:43:55 +01003532 /* RFC 9000 14.1 Initial datagram size
3533 * a server MUST expand the payload of all UDP datagrams carrying ack-eliciting
3534 * Initial packets to at least the smallest allowed maximum datagram size of
3535 * 1200 bytes.
3536 */
3537 BUG_ON_HOT(pkt->type == QUIC_PACKET_TYPE_INITIAL &&
3538 (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) &&
3539 dglen < QUIC_INITIAL_PACKET_MINLEN);
3540
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003541 pkt->time_sent = time_sent;
3542 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
3543 pkt->pktns->tx.time_of_last_eliciting = time_sent;
3544 qc->path->ifae_pkts++;
3545 if (qc->flags & QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ)
3546 qc_idle_timer_rearm(qc, 0);
3547 }
3548 if (!(qc->flags & QUIC_FL_CONN_CLOSING) &&
3549 (pkt->flags & QUIC_FL_TX_PACKET_CC)) {
3550 qc->flags |= QUIC_FL_CONN_CLOSING;
3551 qc_notify_close(qc);
3552
3553 /* RFC 9000 10.2. Immediate Close:
3554 * The closing and draining connection states exist to ensure
3555 * that connections close cleanly and that delayed or reordered
3556 * packets are properly discarded. These states SHOULD persist
3557 * for at least three times the current PTO interval...
3558 *
3559 * Rearm the idle timeout only one time when entering closing
3560 * state.
3561 */
3562 qc_idle_timer_do_rearm(qc);
3563 if (qc->timer_task) {
3564 task_destroy(qc->timer_task);
3565 qc->timer_task = NULL;
3566 }
3567 }
3568 qc->path->in_flight += pkt->in_flight_len;
3569 pkt->pktns->tx.in_flight += pkt->in_flight_len;
3570 if (pkt->in_flight_len)
3571 qc_set_timer(qc);
3572 TRACE_DATA("sent pkt", QUIC_EV_CONN_SPPKTS, qc, pkt);
3573 next_pkt = pkt->next;
3574 quic_tx_packet_refinc(pkt);
3575 eb64_insert(&pkt->pktns->tx.pkts, &pkt->pn_node);
3576 }
3577 }
3578
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003579 ret = 1;
3580leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003581 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
3582
Frédéric Lécaillea2c62c32023-02-10 14:13:43 +01003583 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003584}
3585
3586/* Copy into <buf> buffer a stateless reset token depending on the
3587 * <salt> salt input. This is the cluster secret which will be derived
3588 * as HKDF input secret to generate this token.
3589 * Return 1 if succeeded, 0 if not.
3590 */
3591static int quic_stateless_reset_token_cpy(struct quic_conn *qc,
3592 unsigned char *buf, size_t len,
3593 const unsigned char *salt, size_t saltlen)
3594{
3595 /* Input secret */
3596 const unsigned char *key = (const unsigned char *)global.cluster_secret;
3597 size_t keylen = strlen(global.cluster_secret);
3598 /* Info */
3599 const unsigned char label[] = "stateless token";
3600 size_t labellen = sizeof label - 1;
3601 int ret;
3602
3603 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3604
3605 ret = quic_hkdf_extract_and_expand(EVP_sha256(), buf, len,
3606 key, keylen, salt, saltlen, label, labellen);
3607 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3608 return ret;
3609}
3610
3611/* Initialize the stateless reset token attached to <cid> connection ID.
3612 * Returns 1 if succeeded, 0 if not.
3613 */
3614static int quic_stateless_reset_token_init(struct quic_conn *qc,
3615 struct quic_connection_id *quic_cid)
3616{
3617 int ret;
3618
3619 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3620
3621 if (global.cluster_secret) {
3622 /* Output secret */
3623 unsigned char *token = quic_cid->stateless_reset_token;
3624 size_t tokenlen = sizeof quic_cid->stateless_reset_token;
3625 /* Salt */
3626 const unsigned char *cid = quic_cid->cid.data;
3627 size_t cidlen = quic_cid->cid.len;
3628
3629 ret = quic_stateless_reset_token_cpy(qc, token, tokenlen, cid, cidlen);
3630 }
3631 else {
3632 /* TODO: RAND_bytes() should be replaced */
3633 ret = RAND_bytes(quic_cid->stateless_reset_token,
3634 sizeof quic_cid->stateless_reset_token) == 1;
3635 }
3636
3637 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3638 return ret;
3639}
3640
3641/* Allocate a new CID with <seq_num> as sequence number and attach it to <root>
3642 * ebtree.
3643 *
3644 * The CID is randomly generated in part with the result altered to be
3645 * associated with the current thread ID. This means this function must only
3646 * be called by the quic_conn thread.
3647 *
3648 * Returns the new CID if succeeded, NULL if not.
3649 */
3650static struct quic_connection_id *new_quic_cid(struct eb_root *root,
3651 struct quic_conn *qc,
3652 int seq_num)
3653{
3654 struct quic_connection_id *cid;
3655
3656 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3657
3658 cid = pool_alloc(pool_head_quic_connection_id);
3659 if (!cid) {
3660 TRACE_ERROR("cid allocation failed", QUIC_EV_CONN_TXPKT, qc);
3661 goto err;
3662 }
3663
3664 cid->cid.len = QUIC_HAP_CID_LEN;
3665 /* TODO: RAND_bytes() should be replaced */
3666 if (RAND_bytes(cid->cid.data, cid->cid.len) != 1) {
3667 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT, qc);
3668 goto err;
3669 }
3670
3671 quic_pin_cid_to_tid(cid->cid.data, tid);
3672 if (quic_stateless_reset_token_init(qc, cid) != 1) {
3673 TRACE_ERROR("quic_stateless_reset_token_init() failed", QUIC_EV_CONN_TXPKT, qc);
3674 goto err;
3675 }
3676
3677 cid->qc = qc;
3678
3679 cid->seq_num.key = seq_num;
3680 cid->retire_prior_to = 0;
3681 /* insert the allocated CID in the quic_conn tree */
3682 eb64_insert(root, &cid->seq_num);
3683
3684 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3685 return cid;
3686
3687 err:
3688 pool_free(pool_head_quic_connection_id, cid);
3689 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3690 return NULL;
3691}
3692
3693/* Build all the frames which must be sent just after the handshake have succeeded.
3694 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
3695 * a HANDSHAKE_DONE frame.
3696 * Return 1 if succeeded, 0 if not.
3697 */
3698static int quic_build_post_handshake_frames(struct quic_conn *qc)
3699{
3700 int ret = 0, i, first, max;
3701 struct quic_enc_level *qel;
3702 struct quic_frame *frm, *frmbak;
3703 struct list frm_list = LIST_HEAD_INIT(frm_list);
3704 struct eb64_node *node;
3705
3706 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
3707
3708 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3709 /* Only servers must send a HANDSHAKE_DONE frame. */
3710 if (qc_is_listener(qc)) {
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003711 frm = qc_frm_alloc(QUIC_FT_HANDSHAKE_DONE);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003712 if (!frm) {
3713 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3714 goto leave;
3715 }
3716
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003717 LIST_APPEND(&frm_list, &frm->list);
3718 }
3719
3720 /* Initialize <max> connection IDs minus one: there is
3721 * already one connection ID used for the current connection.
3722 */
3723 first = 1;
3724 max = qc->tx.params.active_connection_id_limit;
3725
3726 /* TODO: check limit */
3727 for (i = first; i < max; i++) {
3728 struct quic_connection_id *cid;
3729
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01003730 frm = qc_frm_alloc(QUIC_FT_NEW_CONNECTION_ID);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003731 if (!frm) {
3732 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3733 goto err;
3734 }
3735
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003736 cid = new_quic_cid(&qc->cids, qc, i);
3737 if (!cid) {
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003738 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003739 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3740 goto err;
3741 }
3742
3743 /* insert the allocated CID in the receiver datagram handler tree */
3744 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3745
3746 quic_connection_id_to_frm_cpy(frm, cid);
3747 LIST_APPEND(&frm_list, &frm->list);
3748 }
3749
3750 LIST_SPLICE(&qel->pktns->tx.frms, &frm_list);
3751 qc->flags |= QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT;
3752
3753 ret = 1;
3754 leave:
3755 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
3756 return ret;
3757
3758 err:
3759 /* free the frames */
3760 list_for_each_entry_safe(frm, frmbak, &frm_list, list)
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01003761 qc_frm_free(&frm);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003762
3763 node = eb64_lookup_ge(&qc->cids, first);
3764 while (node) {
3765 struct quic_connection_id *cid;
3766
3767 cid = eb64_entry(node, struct quic_connection_id, seq_num);
3768 if (cid->seq_num.key >= max)
3769 break;
3770
3771 node = eb64_next(node);
3772 ebmb_delete(&cid->node);
3773 eb64_delete(&cid->seq_num);
3774 pool_free(pool_head_quic_connection_id, cid);
3775 }
3776 goto leave;
3777}
3778
3779/* Deallocate <l> list of ACK ranges. */
3780void quic_free_arngs(struct quic_conn *qc, struct quic_arngs *arngs)
3781{
3782 struct eb64_node *n;
3783 struct quic_arng_node *ar;
3784
3785 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
3786
3787 n = eb64_first(&arngs->root);
3788 while (n) {
3789 struct eb64_node *next;
3790
3791 ar = eb64_entry(n, struct quic_arng_node, first);
3792 next = eb64_next(n);
3793 eb64_delete(n);
3794 pool_free(pool_head_quic_arng, ar);
3795 n = next;
3796 }
3797
3798 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
3799}
3800
3801/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
3802 * descending order.
3803 */
3804static inline size_t sack_gap(struct quic_arng_node *p,
3805 struct quic_arng_node *q)
3806{
3807 return p->first.key - q->last - 2;
3808}
3809
3810
3811/* Remove the last elements of <ack_ranges> list of ack range updating its
3812 * encoded size until it goes below <limit>.
3813 * Returns 1 if succeeded, 0 if not (no more element to remove).
3814 */
3815static int quic_rm_last_ack_ranges(struct quic_conn *qc,
3816 struct quic_arngs *arngs, size_t limit)
3817{
3818 int ret = 0;
3819 struct eb64_node *last, *prev;
3820
3821 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3822
3823 last = eb64_last(&arngs->root);
3824 while (last && arngs->enc_sz > limit) {
3825 struct quic_arng_node *last_node, *prev_node;
3826
3827 prev = eb64_prev(last);
3828 if (!prev) {
3829 TRACE_DEVEL("<last> not found", QUIC_EV_CONN_TXPKT, qc);
3830 goto out;
3831 }
3832
3833 last_node = eb64_entry(last, struct quic_arng_node, first);
3834 prev_node = eb64_entry(prev, struct quic_arng_node, first);
3835 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
3836 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
3837 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
3838 --arngs->sz;
3839 eb64_delete(last);
3840 pool_free(pool_head_quic_arng, last);
3841 last = prev;
3842 }
3843
3844 ret = 1;
3845 out:
3846 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3847 return ret;
3848}
3849
3850/* Set the encoded size of <arngs> QUIC ack ranges. */
3851static void quic_arngs_set_enc_sz(struct quic_conn *qc, struct quic_arngs *arngs)
3852{
3853 struct eb64_node *node, *next;
3854 struct quic_arng_node *ar, *ar_next;
3855
3856 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3857
3858 node = eb64_last(&arngs->root);
3859 if (!node)
3860 goto leave;
3861
3862 ar = eb64_entry(node, struct quic_arng_node, first);
3863 arngs->enc_sz = quic_int_getsize(ar->last) +
3864 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
3865
3866 while ((next = eb64_prev(node))) {
3867 ar_next = eb64_entry(next, struct quic_arng_node, first);
3868 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
3869 quic_int_getsize(ar_next->last - ar_next->first.key);
3870 node = next;
3871 ar = eb64_entry(node, struct quic_arng_node, first);
3872 }
3873
3874 leave:
3875 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3876}
3877
3878/* Insert <ar> ack range into <argns> tree of ack ranges.
3879 * Returns the ack range node which has been inserted if succeeded, NULL if not.
3880 */
3881static inline
3882struct quic_arng_node *quic_insert_new_range(struct quic_conn *qc,
3883 struct quic_arngs *arngs,
3884 struct quic_arng *ar)
3885{
3886 struct quic_arng_node *new_ar;
3887
3888 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3889
3890 new_ar = pool_alloc(pool_head_quic_arng);
3891 if (!new_ar) {
3892 TRACE_ERROR("ack range allocation failed", QUIC_EV_CONN_RXPKT, qc);
3893 goto leave;
3894 }
3895
3896 new_ar->first.key = ar->first;
3897 new_ar->last = ar->last;
3898 eb64_insert(&arngs->root, &new_ar->first);
3899 arngs->sz++;
3900
3901 leave:
3902 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3903 return new_ar;
3904}
3905
3906/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
3907 * Note that this function computes the number of bytes required to encode
3908 * this tree of ACK ranges in descending order.
3909 *
3910 * Descending order
3911 * ------------->
3912 * range1 range2
3913 * ..........|--------|..............|--------|
3914 * ^ ^ ^ ^
3915 * | | | |
3916 * last1 first1 last2 first2
3917 * ..........+--------+--------------+--------+......
3918 * diff1 gap12 diff2
3919 *
3920 * To encode the previous list of ranges we must encode integers as follows in
3921 * descending order:
3922 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
3923 * with diff1 = last1 - first1
3924 * diff2 = last2 - first2
3925 * gap12 = first1 - last2 - 2 (>= 0)
3926 *
3927
3928returns 0 on error
3929
3930 */
3931int quic_update_ack_ranges_list(struct quic_conn *qc,
3932 struct quic_arngs *arngs,
3933 struct quic_arng *ar)
3934{
3935 int ret = 0;
3936 struct eb64_node *le;
3937 struct quic_arng_node *new_node;
3938 struct eb64_node *new;
3939
3940 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3941
3942 new = NULL;
3943 if (eb_is_empty(&arngs->root)) {
3944 new_node = quic_insert_new_range(qc, arngs, ar);
3945 if (new_node)
3946 ret = 1;
3947
3948 goto leave;
3949 }
3950
3951 le = eb64_lookup_le(&arngs->root, ar->first);
3952 if (!le) {
3953 new_node = quic_insert_new_range(qc, arngs, ar);
3954 if (!new_node)
3955 goto leave;
3956
3957 new = &new_node->first;
3958 }
3959 else {
3960 struct quic_arng_node *le_ar =
3961 eb64_entry(le, struct quic_arng_node, first);
3962
3963 /* Already existing range */
3964 if (le_ar->last >= ar->last) {
3965 ret = 1;
3966 }
3967 else if (le_ar->last + 1 >= ar->first) {
3968 le_ar->last = ar->last;
3969 new = le;
3970 new_node = le_ar;
3971 }
3972 else {
3973 new_node = quic_insert_new_range(qc, arngs, ar);
3974 if (!new_node)
3975 goto leave;
3976
3977 new = &new_node->first;
3978 }
3979 }
3980
3981 /* Verify that the new inserted node does not overlap the nodes
3982 * which follow it.
3983 */
3984 if (new) {
3985 struct eb64_node *next;
3986 struct quic_arng_node *next_node;
3987
3988 while ((next = eb64_next(new))) {
3989 next_node =
3990 eb64_entry(next, struct quic_arng_node, first);
3991 if (new_node->last + 1 < next_node->first.key)
3992 break;
3993
3994 if (next_node->last > new_node->last)
3995 new_node->last = next_node->last;
3996 eb64_delete(next);
3997 pool_free(pool_head_quic_arng, next_node);
3998 /* Decrement the size of these ranges. */
3999 arngs->sz--;
4000 }
4001 }
4002
4003 ret = 1;
4004 leave:
4005 quic_arngs_set_enc_sz(qc, arngs);
4006 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
4007 return ret;
4008}
4009/* Remove the header protection of packets at <el> encryption level.
4010 * Always succeeds.
4011 */
4012static inline void qc_rm_hp_pkts(struct quic_conn *qc, struct quic_enc_level *el)
4013{
4014 struct quic_tls_ctx *tls_ctx;
4015 struct quic_rx_packet *pqpkt, *pkttmp;
4016 struct quic_enc_level *app_qel;
4017
4018 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, qc);
4019 app_qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4020 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
4021 if (el == app_qel && qc_is_listener(qc) && qc->state < QUIC_HS_ST_COMPLETE) {
4022 TRACE_DEVEL("hp not removed (handshake not completed)",
4023 QUIC_EV_CONN_ELRMHP, qc);
4024 goto out;
4025 }
4026 tls_ctx = &el->tls_ctx;
4027 list_for_each_entry_safe(pqpkt, pkttmp, &el->rx.pqpkts, list) {
4028 if (!qc_do_rm_hp(qc, pqpkt, tls_ctx, el->pktns->rx.largest_pn,
4029 pqpkt->data + pqpkt->pn_offset, pqpkt->data)) {
4030 TRACE_ERROR("hp removing error", QUIC_EV_CONN_ELRMHP, qc);
4031 }
4032 else {
4033 /* The AAD includes the packet number field */
4034 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
4035 /* Store the packet into the tree of packets to decrypt. */
4036 pqpkt->pn_node.key = pqpkt->pn;
4037 eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
4038 quic_rx_packet_refinc(pqpkt);
4039 TRACE_DEVEL("hp removed", QUIC_EV_CONN_ELRMHP, qc, pqpkt);
4040 }
4041 LIST_DELETE(&pqpkt->list);
4042 quic_rx_packet_refdec(pqpkt);
4043 }
4044
4045 out:
4046 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, qc);
4047}
4048
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004049/* Process all the CRYPTO frame at <el> encryption level. This is the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05004050 * responsibility of the called to ensure there exists a CRYPTO data
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004051 * stream for this level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004052 * Return 1 if succeeded, 0 if not.
4053 */
4054static inline int qc_treat_rx_crypto_frms(struct quic_conn *qc,
4055 struct quic_enc_level *el,
4056 struct ssl_sock_ctx *ctx)
4057{
4058 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004059 struct ncbuf *ncbuf;
4060 struct quic_cstream *cstream = el->cstream;
4061 ncb_sz_t data;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004062
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004063 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004064
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004065 BUG_ON(!cstream);
4066 ncbuf = &cstream->rx.ncbuf;
4067 if (ncb_is_null(ncbuf))
4068 goto done;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004069
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004070 /* TODO not working if buffer is wrapping */
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004071 while ((data = ncb_data(ncbuf, 0))) {
4072 const unsigned char *cdata = (const unsigned char *)ncb_head(ncbuf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004073
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004074 if (!qc_provide_cdata(el, ctx, cdata, data, NULL, NULL))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004075 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004076
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004077 cstream->rx.offset += data;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004078 TRACE_DEVEL("buffered crypto data were provided to TLS stack",
4079 QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004080 }
4081
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004082 done:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004083 ret = 1;
4084 leave:
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004085 if (!ncb_is_null(ncbuf) && ncb_is_empty(ncbuf)) {
4086 TRACE_DEVEL("freeing crypto buf", QUIC_EV_CONN_PHPKTS, qc, el);
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004087 quic_free_ncbuf(ncbuf);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01004088 }
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004089 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004090 return ret;
4091}
4092
4093/* Process all the packets at <el> and <next_el> encryption level.
4094 * This is the caller responsibility to check that <cur_el> is different of <next_el>
4095 * as pointer value.
4096 * Return 1 if succeeded, 0 if not.
4097 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004098int qc_treat_rx_pkts(struct quic_conn *qc, struct quic_enc_level *cur_el,
4099 struct quic_enc_level *next_el, int force_ack)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004100{
4101 int ret = 0;
4102 struct eb64_node *node;
4103 int64_t largest_pn = -1;
4104 unsigned int largest_pn_time_received = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004105 struct quic_enc_level *qel = cur_el;
4106
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004107 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004108 qel = cur_el;
4109 next_tel:
4110 if (!qel)
4111 goto out;
4112
4113 node = eb64_first(&qel->rx.pkts);
4114 while (node) {
4115 struct quic_rx_packet *pkt;
4116
4117 pkt = eb64_entry(node, struct quic_rx_packet, pn_node);
4118 TRACE_DATA("new packet", QUIC_EV_CONN_RXPKT,
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004119 qc, pkt, NULL, qc->xprt_ctx->ssl);
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01004120 if (!qc_pkt_decrypt(qc, qel, pkt)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004121 /* Drop the packet */
4122 TRACE_ERROR("packet decryption failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004123 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004124 }
4125 else {
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004126 if (!qc_parse_pkt_frms(qc, pkt, qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004127 /* Drop the packet */
4128 TRACE_ERROR("packet parsing failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004129 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004130 HA_ATOMIC_INC(&qc->prx_counters->dropped_parsing);
4131 }
4132 else {
4133 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
4134
4135 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING || force_ack) {
4136 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
4137 qel->pktns->rx.nb_aepkts_since_last_ack++;
4138 qc_idle_timer_rearm(qc, 1);
4139 }
4140 if (pkt->pn > largest_pn) {
4141 largest_pn = pkt->pn;
4142 largest_pn_time_received = pkt->time_received;
4143 }
4144 /* Update the list of ranges to acknowledge. */
4145 if (!quic_update_ack_ranges_list(qc, &qel->pktns->rx.arngs, &ar))
4146 TRACE_ERROR("Could not update ack range list",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004147 QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004148 }
4149 }
4150 node = eb64_next(node);
4151 eb64_delete(&pkt->pn_node);
4152 quic_rx_packet_refdec(pkt);
4153 }
4154
4155 if (largest_pn != -1 && largest_pn > qel->pktns->rx.largest_pn) {
4156 /* Update the largest packet number. */
4157 qel->pktns->rx.largest_pn = largest_pn;
4158 /* Update the largest acknowledged packet timestamps */
4159 qel->pktns->rx.largest_time_received = largest_pn_time_received;
4160 qel->pktns->flags |= QUIC_FL_PKTNS_NEW_LARGEST_PN;
4161 }
4162
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004163 if (qel->cstream && !qc_treat_rx_crypto_frms(qc, qel, qc->xprt_ctx)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004164 // trace already emitted by function above
4165 goto leave;
4166 }
4167
4168 if (qel == cur_el) {
4169 BUG_ON(qel == next_el);
4170 qel = next_el;
4171 largest_pn = -1;
4172 goto next_tel;
4173 }
4174
4175 out:
4176 ret = 1;
4177 leave:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004178 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004179 return ret;
4180}
4181
4182/* Check if it's possible to remove header protection for packets related to
4183 * encryption level <qel>. If <qel> is NULL, assume it's false.
4184 *
4185 * Return true if the operation is possible else false.
4186 */
4187static int qc_qel_may_rm_hp(struct quic_conn *qc, struct quic_enc_level *qel)
4188{
4189 int ret = 0;
4190 enum quic_tls_enc_level tel;
4191
4192 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
4193
4194 if (!qel)
4195 goto cant_rm_hp;
4196
4197 tel = ssl_to_quic_enc_level(qel->level);
4198
4199 /* check if tls secrets are available */
4200 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
4201 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, qc);
4202 goto cant_rm_hp;
4203 }
4204
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004205 if (!quic_tls_has_rx_sec(qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004206 TRACE_DEVEL("non available secrets", QUIC_EV_CONN_TRMHP, qc);
4207 goto cant_rm_hp;
4208 }
4209
Frédéric Lécaille8417beb2023-02-01 10:31:35 +01004210 if (tel == QUIC_TLS_ENC_LEVEL_APP && qc->state < QUIC_HS_ST_COMPLETE) {
4211 TRACE_DEVEL("handshake not complete", QUIC_EV_CONN_TRMHP, qc);
4212 goto cant_rm_hp;
4213 }
4214
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004215 /* check if the connection layer is ready before using app level */
4216 if ((tel == QUIC_TLS_ENC_LEVEL_APP || tel == QUIC_TLS_ENC_LEVEL_EARLY_DATA) &&
4217 qc->mux_state == QC_MUX_NULL) {
4218 TRACE_DEVEL("connection layer not ready", QUIC_EV_CONN_TRMHP, qc);
4219 goto cant_rm_hp;
4220 }
4221
4222 ret = 1;
4223 cant_rm_hp:
4224 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc);
4225 return ret;
4226}
4227
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004228/* Flush txbuf for <qc> connection. This must be called prior to a packet
4229 * preparation when txbuf contains older data. A send will be conducted for
4230 * these data.
4231 *
4232 * Returns 1 on success : buffer is empty and can be use for packet
4233 * preparation. On error 0 is returned.
4234 */
4235static int qc_purge_txbuf(struct quic_conn *qc, struct buffer *buf)
4236{
4237 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4238
4239 /* This operation can only be conducted if txbuf is not empty. This
4240 * case only happens for connection with their owned socket due to an
4241 * older transient sendto() error.
4242 */
4243 BUG_ON(!qc_test_fd(qc));
4244
4245 if (b_data(buf) && !qc_send_ppkts(buf, qc->xprt_ctx)) {
4246 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4247 qc_txb_release(qc);
4248 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TXPKT, qc);
4249 return 0;
4250 }
4251
4252 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4253 return 1;
4254}
4255
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004256/* Try to send application frames from list <frms> on connection <qc>.
4257 *
4258 * Use qc_send_app_probing wrapper when probing with old data.
4259 *
4260 * Returns 1 on success. Some data might not have been sent due to congestion,
4261 * in this case they are left in <frms> input list. The caller may subscribe on
4262 * quic-conn to retry later.
4263 *
4264 * Returns 0 on critical error.
4265 * TODO review and classify more distinctly transient from definitive errors to
4266 * allow callers to properly handle it.
4267 */
4268static int qc_send_app_pkts(struct quic_conn *qc, struct list *frms)
4269{
4270 int status = 0;
4271 struct buffer *buf;
4272
4273 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4274
4275 buf = qc_txb_alloc(qc);
4276 if (!buf) {
4277 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004278 goto err;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004279 }
4280
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004281 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4282 goto err;
4283
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004284 /* Prepare and send packets until we could not further prepare packets. */
4285 while (1) {
4286 int ret;
4287 /* Currently buf cannot be non-empty at this stage. Even if a
4288 * previous sendto() has failed it is emptied to simulate
4289 * packet emission and rely on QUIC lost detection to try to
4290 * emit it.
4291 */
4292 BUG_ON_HOT(b_data(buf));
4293 b_reset(buf);
4294
4295 ret = qc_prep_app_pkts(qc, buf, frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004296 if (ret == -1) {
4297 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004298 goto err;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004299 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004300
Amaury Denoyelle37333862023-02-28 11:53:48 +01004301 if (!ret)
4302 break;
4303
4304 if (!qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004305 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4306 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004307 goto err;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004308 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004309 }
4310
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004311 status = 1;
4312 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004313 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4314 return status;
4315
4316 err:
Amaury Denoyelle37333862023-02-28 11:53:48 +01004317 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TXPKT, qc);
4318 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004319}
4320
4321/* Try to send application frames from list <frms> on connection <qc>. Use this
4322 * function when probing is required.
4323 *
4324 * Returns the result from qc_send_app_pkts function.
4325 */
4326static forceinline int qc_send_app_probing(struct quic_conn *qc,
4327 struct list *frms)
4328{
4329 int ret;
4330
4331 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4332
4333 TRACE_STATE("preparing old data (probing)", QUIC_EV_CONN_TXPKT, qc);
4334 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4335 ret = qc_send_app_pkts(qc, frms);
4336 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4337
4338 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4339 return ret;
4340}
4341
4342/* Try to send application frames from list <frms> on connection <qc>. This
4343 * function is provided for MUX upper layer usage only.
4344 *
4345 * Returns the result from qc_send_app_pkts function.
4346 */
4347int qc_send_mux(struct quic_conn *qc, struct list *frms)
4348{
4349 int ret;
4350
4351 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4352 BUG_ON(qc->mux_state != QC_MUX_READY); /* Only MUX can uses this function so it must be ready. */
4353
4354 TRACE_STATE("preparing data (from MUX)", QUIC_EV_CONN_TXPKT, qc);
4355 qc->flags |= QUIC_FL_CONN_TX_MUX_CONTEXT;
4356 ret = qc_send_app_pkts(qc, frms);
4357 qc->flags &= ~QUIC_FL_CONN_TX_MUX_CONTEXT;
4358
4359 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4360 return ret;
4361}
4362
4363/* Sends handshake packets from up to two encryption levels <tel> and <next_te>
4364 * with <tel_frms> and <next_tel_frms> as frame list respectively for <qc>
4365 * QUIC connection. <old_data> is used as boolean to send data already sent but
4366 * not already acknowledged (in flight).
4367 * Returns 1 if succeeded, 0 if not.
4368 */
4369int qc_send_hdshk_pkts(struct quic_conn *qc, int old_data,
4370 enum quic_tls_enc_level tel, struct list *tel_frms,
4371 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
4372{
4373 int ret, status = 0;
4374 struct buffer *buf = qc_txb_alloc(qc);
4375
4376 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4377
4378 if (!buf) {
4379 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4380 goto leave;
4381 }
4382
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004383 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4384 goto out;
4385
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004386 /* Currently buf cannot be non-empty at this stage. Even if a previous
4387 * sendto() has failed it is emptied to simulate packet emission and
4388 * rely on QUIC lost detection to try to emit it.
4389 */
4390 BUG_ON_HOT(b_data(buf));
4391 b_reset(buf);
4392
4393 if (old_data) {
4394 TRACE_STATE("old data for probing asked", QUIC_EV_CONN_TXPKT, qc);
4395 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4396 }
4397
4398 ret = qc_prep_pkts(qc, buf, tel, tel_frms, next_tel, next_tel_frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004399 if (ret == -1) {
4400 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004401 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004402 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004403
Amaury Denoyelle37333862023-02-28 11:53:48 +01004404 if (ret && !qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004405 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4406 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004407 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004408 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004409
Amaury Denoyelle37333862023-02-28 11:53:48 +01004410 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004411 status = 1;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004412
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004413 out:
4414 TRACE_STATE("no more need old data for probing", QUIC_EV_CONN_TXPKT, qc);
4415 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004416 leave:
4417 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4418 return status;
4419}
4420
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004421/* Retransmit up to two datagrams depending on packet number space.
4422 * Return 0 when failed, 0 if not.
4423 */
4424static int qc_dgrams_retransmit(struct quic_conn *qc)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004425{
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004426 int ret = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004427 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4428 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4429 struct quic_enc_level *aqel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4430
4431 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4432
4433 if (iqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004434 int i;
4435
4436 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
4437 struct list ifrms = LIST_HEAD_INIT(ifrms);
4438 struct list hfrms = LIST_HEAD_INIT(hfrms);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004439
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004440 qc_prep_hdshk_fast_retrans(qc, &ifrms, &hfrms);
4441 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &ifrms);
4442 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4443 if (!LIST_ISEMPTY(&ifrms)) {
4444 iqel->pktns->tx.pto_probe = 1;
4445 if (!LIST_ISEMPTY(&hfrms))
4446 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004447 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4448 QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms))
4449 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004450 /* Put back unsent frames in their packet number spaces */
4451 LIST_SPLICE(&iqel->pktns->tx.frms, &ifrms);
4452 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4453 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004454 }
4455 TRACE_STATE("no more need to probe Initial packet number space",
4456 QUIC_EV_CONN_TXPKT, qc);
4457 iqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004458 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004459 }
4460 else {
4461 int i;
4462
4463 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004464 hqel->pktns->tx.pto_probe = 0;
4465 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
Frédéric Lécaille7b5d9b12022-11-28 17:21:45 +01004466 struct list frms1 = LIST_HEAD_INIT(frms1);
4467
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004468 qc_prep_fast_retrans(qc, hqel, &frms1, NULL);
4469 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4470 if (!LIST_ISEMPTY(&frms1)) {
4471 hqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004472 if (!qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &frms1,
4473 QUIC_TLS_ENC_LEVEL_NONE, NULL))
4474 goto leave;
4475
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004476 /* Put back unsent frames into their packet number spaces */
4477 LIST_SPLICE(&hqel->pktns->tx.frms, &frms1);
4478 }
4479 }
4480 TRACE_STATE("no more need to probe Handshake packet number space",
4481 QUIC_EV_CONN_TXPKT, qc);
4482 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4483 }
4484 else if (aqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4485 struct list frms2 = LIST_HEAD_INIT(frms2);
4486 struct list frms1 = LIST_HEAD_INIT(frms1);
4487
4488 aqel->pktns->tx.pto_probe = 0;
4489 qc_prep_fast_retrans(qc, aqel, &frms1, &frms2);
4490 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4491 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms2);
4492 if (!LIST_ISEMPTY(&frms1)) {
4493 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004494 if (!qc_send_app_probing(qc, &frms1))
4495 goto leave;
4496
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004497 /* Put back unsent frames into their packet number spaces */
4498 LIST_SPLICE(&aqel->pktns->tx.frms, &frms1);
4499 }
4500 if (!LIST_ISEMPTY(&frms2)) {
4501 aqel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004502 if (!qc_send_app_probing(qc, &frms2))
4503 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004504 /* Put back unsent frames into their packet number spaces */
4505 LIST_SPLICE(&aqel->pktns->tx.frms, &frms2);
4506 }
4507 TRACE_STATE("no more need to probe 01RTT packet number space",
4508 QUIC_EV_CONN_TXPKT, qc);
4509 aqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4510 }
4511 }
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004512
4513 ret = 1;
4514 leave:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004515 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004516 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004517}
4518
4519/* QUIC connection packet handler task (post handshake) */
4520struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state)
4521{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004522 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004523 struct quic_enc_level *qel;
4524
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004525 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4526
4527 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
4528 TRACE_STATE("connection handshake state", QUIC_EV_CONN_IO_CB, qc, &qc->state);
4529
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004530 if (qc_test_fd(qc))
4531 qc_rcv_buf(qc);
4532
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004533 /* Retranmissions */
4534 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4535 TRACE_STATE("retransmission needed", QUIC_EV_CONN_IO_CB, qc);
4536 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004537 if (!qc_dgrams_retransmit(qc))
4538 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004539 }
4540
4541 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4542 qc_rm_hp_pkts(qc, qel);
4543
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004544 if (!qc_treat_rx_pkts(qc, qel, NULL, 0)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004545 TRACE_DEVEL("qc_treat_rx_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4546 goto out;
4547 }
4548
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004549 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4550 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_IO_CB, qc);
4551 goto out;
4552 }
4553
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004554 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4555 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)) {
4556 TRACE_STATE("draining connection (must not send packets)", QUIC_EV_CONN_IO_CB, qc);
4557 goto out;
4558 }
4559
4560 /* XXX TODO: how to limit the list frames to send */
4561 if (!qc_send_app_pkts(qc, &qel->pktns->tx.frms)) {
4562 TRACE_DEVEL("qc_send_app_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4563 goto out;
4564 }
4565
4566 out:
4567 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
4568 return t;
4569}
4570
4571/* Returns a boolean if <qc> needs to emit frames for <qel> encryption level. */
4572static int qc_need_sending(struct quic_conn *qc, struct quic_enc_level *qel)
4573{
4574 return (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) ||
4575 (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) ||
4576 qel->pktns->tx.pto_probe ||
4577 !LIST_ISEMPTY(&qel->pktns->tx.frms);
4578}
4579
4580/* QUIC connection packet handler task. */
4581struct task *quic_conn_io_cb(struct task *t, void *context, unsigned int state)
4582{
4583 int ret, ssl_err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004584 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004585 enum quic_tls_enc_level tel, next_tel;
4586 struct quic_enc_level *qel, *next_qel;
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004587 /* Early-data encryption level */
4588 struct quic_enc_level *eqel;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004589 struct buffer *buf = NULL;
4590 int st, force_ack, zero_rtt;
4591
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004592 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004593 eqel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004594 st = qc->state;
4595 TRACE_PROTO("connection state", QUIC_EV_CONN_IO_CB, qc, &st);
4596
4597 /* Retranmissions */
4598 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4599 TRACE_DEVEL("retransmission needed", QUIC_EV_CONN_PHPKTS, qc);
4600 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
Frédéric Lécaillee1738df2023-02-10 14:46:39 +01004601 if (!qc_dgrams_retransmit(qc))
4602 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004603 }
4604
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004605 ssl_err = SSL_ERROR_NONE;
4606 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004607 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004608 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004609
4610 if (qc_test_fd(qc))
4611 qc_rcv_buf(qc);
4612
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004613 if (st >= QUIC_HS_ST_COMPLETE &&
4614 qc_el_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
4615 TRACE_DEVEL("remaining Handshake packets", QUIC_EV_CONN_PHPKTS, qc);
4616 /* There may be remaining Handshake packets to treat and acknowledge. */
4617 tel = QUIC_TLS_ENC_LEVEL_HANDSHAKE;
4618 next_tel = QUIC_TLS_ENC_LEVEL_APP;
4619 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004620 else if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, zero_rtt))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004621 goto out;
4622
4623 qel = &qc->els[tel];
4624 next_qel = next_tel == QUIC_TLS_ENC_LEVEL_NONE ? NULL : &qc->els[next_tel];
4625
4626 next_level:
4627 /* Treat packets waiting for header packet protection decryption */
4628 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4629 qc_rm_hp_pkts(qc, qel);
4630
4631 force_ack = qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
4632 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004633 if (!qc_treat_rx_pkts(qc, qel, next_qel, force_ack))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004634 goto out;
4635
Frédéric Lécaille0aa79952023-02-03 16:15:08 +01004636 if (qc->flags & QUIC_FL_CONN_TO_KILL) {
4637 TRACE_DEVEL("connection to be killed", QUIC_EV_CONN_PHPKTS, qc);
4638 goto out;
4639 }
4640
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004641 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4642 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE))
4643 goto out;
4644
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004645 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004646 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004647 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
4648 if (next_qel && next_qel == eqel && zero_rtt) {
4649 TRACE_DEVEL("select 0RTT as next encryption level",
4650 QUIC_EV_CONN_PHPKTS, qc);
4651 qel = next_qel;
4652 next_qel = NULL;
4653 goto next_level;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004654 }
4655
4656 st = qc->state;
4657 if (st >= QUIC_HS_ST_COMPLETE) {
4658 if (!(qc->flags & QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT) &&
4659 !quic_build_post_handshake_frames(qc))
4660 goto out;
4661
4662 if (!(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].tls_ctx.flags &
4663 QUIC_FL_TLS_SECRETS_DCD)) {
4664 /* Discard the Handshake keys. */
4665 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4666 TRACE_PROTO("discarding Handshake pktns", QUIC_EV_CONN_PHPKTS, qc);
4667 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, qc);
4668 qc_set_timer(qc);
4669 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4670 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns);
4671 }
4672
4673 if (qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) {
4674 /* There may be remaining handshake to build (acks) */
4675 st = QUIC_HS_ST_SERVER_HANDSHAKE;
4676 }
4677 }
4678
4679 /* A listener does not send any O-RTT packet. O-RTT packet number space must not
4680 * be considered.
4681 */
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004682 if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, 0))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004683 goto out;
4684
4685 if (!qc_need_sending(qc, qel) &&
4686 (!next_qel || !qc_need_sending(qc, next_qel))) {
4687 goto skip_send;
4688 }
4689
4690 buf = qc_txb_alloc(qc);
4691 if (!buf)
4692 goto out;
4693
Amaury Denoyelle147862d2023-02-28 15:10:00 +01004694 if (b_data(buf) && !qc_purge_txbuf(qc, buf))
4695 goto skip_send;
4696
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004697 /* Currently buf cannot be non-empty at this stage. Even if a previous
4698 * sendto() has failed it is emptied to simulate packet emission and
4699 * rely on QUIC lost detection to try to emit it.
4700 */
4701 BUG_ON_HOT(b_data(buf));
4702 b_reset(buf);
4703
4704 ret = qc_prep_pkts(qc, buf, tel, &qc->els[tel].pktns->tx.frms,
4705 next_tel, &qc->els[next_tel].pktns->tx.frms);
Amaury Denoyelle37333862023-02-28 11:53:48 +01004706 if (ret == -1) {
4707 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004708 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004709 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004710
Amaury Denoyelle37333862023-02-28 11:53:48 +01004711 if (ret && !qc_send_ppkts(buf, qc->xprt_ctx)) {
Amaury Denoyellee1a0ee32023-02-28 15:11:09 +01004712 if (qc->flags & QUIC_FL_CONN_TO_KILL)
4713 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004714 goto out;
Amaury Denoyelle37333862023-02-28 11:53:48 +01004715 }
4716
4717 qc_txb_release(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004718
4719 skip_send:
4720 /* Check if there is something to do for the next level.
4721 */
4722 if (next_qel && next_qel != qel &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004723 quic_tls_has_rx_sec(next_qel) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004724 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || qc_el_rx_pkts(next_qel))) {
4725 qel = next_qel;
4726 next_qel = NULL;
4727 goto next_level;
4728 }
4729
4730 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004731 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc, &st, &ssl_err);
4732 return t;
4733}
4734
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004735/* Release the memory allocated for <cs> CRYPTO stream */
4736void quic_cstream_free(struct quic_cstream *cs)
4737{
4738 if (!cs) {
4739 /* This is the case for ORTT encryption level */
4740 return;
4741 }
4742
Amaury Denoyellebc174b22022-11-17 10:12:52 +01004743 quic_free_ncbuf(&cs->rx.ncbuf);
4744
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004745 qc_stream_desc_release(cs->desc);
4746 pool_free(pool_head_quic_cstream, cs);
4747}
4748
4749/* Allocate a new QUIC stream for <qc>.
4750 * Return it if succeeded, NULL if not.
4751 */
4752struct quic_cstream *quic_cstream_new(struct quic_conn *qc)
4753{
4754 struct quic_cstream *cs, *ret_cs = NULL;
4755
4756 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4757 cs = pool_alloc(pool_head_quic_cstream);
4758 if (!cs) {
4759 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4760 goto leave;
4761 }
4762
4763 cs->rx.offset = 0;
4764 cs->rx.ncbuf = NCBUF_NULL;
4765 cs->rx.offset = 0;
4766
4767 cs->tx.offset = 0;
4768 cs->tx.sent_offset = 0;
4769 cs->tx.buf = BUF_NULL;
4770 cs->desc = qc_stream_desc_new((uint64_t)-1, -1, cs, qc);
4771 if (!cs->desc) {
4772 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4773 goto err;
4774 }
4775
4776 ret_cs = cs;
4777 leave:
4778 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4779 return ret_cs;
4780
4781 err:
4782 pool_free(pool_head_quic_cstream, cs);
4783 goto leave;
4784}
4785
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004786/* Uninitialize <qel> QUIC encryption level. Never fails. */
4787static void quic_conn_enc_level_uninit(struct quic_conn *qc, struct quic_enc_level *qel)
4788{
4789 int i;
4790
4791 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4792
4793 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
4794 if (qel->tx.crypto.bufs[i]) {
4795 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
4796 qel->tx.crypto.bufs[i] = NULL;
4797 }
4798 }
4799 ha_free(&qel->tx.crypto.bufs);
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004800 quic_cstream_free(qel->cstream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004801
4802 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4803}
4804
4805/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
4806 * connection allocating everything needed.
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004807 *
4808 * Returns 1 if succeeded, 0 if not. On error the caller is responsible to use
4809 * quic_conn_enc_level_uninit() to cleanup partially allocated content.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004810 */
4811static int quic_conn_enc_level_init(struct quic_conn *qc,
4812 enum quic_tls_enc_level level)
4813{
4814 int ret = 0;
4815 struct quic_enc_level *qel;
4816
4817 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4818
4819 qel = &qc->els[level];
4820 qel->level = quic_to_ssl_enc_level(level);
4821 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
4822 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
4823 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
4824 qel->tls_ctx.flags = 0;
4825
4826 qel->rx.pkts = EB_ROOT;
4827 LIST_INIT(&qel->rx.pqpkts);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004828
4829 /* Allocate only one buffer. */
4830 /* TODO: use a pool */
4831 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
4832 if (!qel->tx.crypto.bufs)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004833 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004834
4835 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
4836 if (!qel->tx.crypto.bufs[0])
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004837 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004838
4839 qel->tx.crypto.bufs[0]->sz = 0;
4840 qel->tx.crypto.nb_buf = 1;
4841
4842 qel->tx.crypto.sz = 0;
4843 qel->tx.crypto.offset = 0;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004844 /* No CRYPTO data for early data TLS encryption level */
4845 if (level == QUIC_TLS_ENC_LEVEL_EARLY_DATA)
4846 qel->cstream = NULL;
4847 else {
4848 qel->cstream = quic_cstream_new(qc);
4849 if (!qel->cstream)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004850 goto leave;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004851 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004852
4853 ret = 1;
4854 leave:
4855 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4856 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004857}
4858
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004859/* Return 1 if <qc> connection may probe the Initial packet number space, 0 if not.
4860 * This is not the case if the remote peer address is not validated and if
4861 * it cannot send at least QUIC_INITIAL_PACKET_MINLEN bytes.
4862 */
4863static int qc_may_probe_ipktns(struct quic_conn *qc)
4864{
4865 return quic_peer_validated_addr(qc) ||
4866 (int)(3 * qc->rx.bytes - qc->tx.prep_bytes) >= QUIC_INITIAL_PACKET_MINLEN;
4867}
4868
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004869/* Callback called upon loss detection and PTO timer expirations. */
4870struct task *qc_process_timer(struct task *task, void *ctx, unsigned int state)
4871{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004872 struct quic_conn *qc = ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004873 struct quic_pktns *pktns;
4874
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004875 TRACE_ENTER(QUIC_EV_CONN_PTIMER, qc,
4876 NULL, NULL, &qc->path->ifae_pkts);
4877 task->expire = TICK_ETERNITY;
4878 pktns = quic_loss_pktns(qc);
4879 if (tick_isset(pktns->tx.loss_time)) {
4880 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
4881
4882 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
4883 if (!LIST_ISEMPTY(&lost_pkts))
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004884 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyellee4abb1f2023-01-27 17:54:15 +01004885 if (qc_release_lost_pkts(qc, pktns, &lost_pkts, now_ms))
4886 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004887 goto out;
4888 }
4889
4890 if (qc->path->in_flight) {
Frédéric Lécailleb75eecc2023-01-26 15:18:17 +01004891 pktns = quic_pto_pktns(qc, qc->state >= QUIC_HS_ST_CONFIRMED, NULL);
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01004892 if (!qc_notify_send(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004893 if (pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL]) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004894 if (qc_may_probe_ipktns(qc)) {
4895 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4896 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4897 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4898 }
4899 else {
4900 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4901 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004902 if (qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].tx.in_flight) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004903 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004904 qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4905 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
4906 }
4907 }
4908 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE]) {
4909 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004910 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4911 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004912 if (qc->pktns[QUIC_TLS_PKTNS_INITIAL].tx.in_flight) {
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004913 if (qc_may_probe_ipktns(qc)) {
4914 qc->pktns[QUIC_TLS_PKTNS_INITIAL].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4915 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4916 }
4917 else {
4918 TRACE_STATE("Cannot probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4919 }
Frédéric Lécaille37ed4a32023-01-31 17:32:06 +01004920 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004921 }
4922 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT]) {
4923 TRACE_STATE("needs to probe 01RTT packet number space", QUIC_EV_CONN_TXPKT, qc);
Frédéric Lécaille7c6d8f82023-02-14 16:00:18 +01004924 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4925 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004926 }
4927 }
4928 }
4929 else if (!qc_is_listener(qc) && qc->state <= QUIC_HS_ST_COMPLETE) {
4930 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4931 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4932
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004933 if (quic_tls_has_tx_sec(hel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004934 hel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004935 if (quic_tls_has_tx_sec(iel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004936 iel->pktns->tx.pto_probe = 1;
4937 }
4938
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004939 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004940 qc->path->loss.pto_count++;
4941
4942 out:
4943 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, qc, pktns);
4944
4945 return task;
4946}
4947
4948/* Parse the Retry token from buffer <token> with <end> a pointer to
4949 * one byte past the end of this buffer. This will extract the ODCID
4950 * which will be stored into <odcid>
4951 *
4952 * Returns 0 on success else non-zero.
4953 */
4954static int parse_retry_token(struct quic_conn *qc,
4955 const unsigned char *token, const unsigned char *end,
4956 struct quic_cid *odcid)
4957{
4958 int ret = 0;
4959 uint64_t odcid_len;
4960 uint32_t timestamp;
4961
4962 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4963
4964 if (!quic_dec_int(&odcid_len, &token, end)) {
4965 TRACE_ERROR("quic_dec_int() error", QUIC_EV_CONN_LPKT, qc);
4966 goto leave;
4967 }
4968
4969 /* RFC 9000 7.2. Negotiating Connection IDs:
4970 * When an Initial packet is sent by a client that has not previously
4971 * received an Initial or Retry packet from the server, the client
4972 * populates the Destination Connection ID field with an unpredictable
4973 * value. This Destination Connection ID MUST be at least 8 bytes in length.
4974 */
4975 if (odcid_len < QUIC_ODCID_MINLEN || odcid_len > QUIC_CID_MAXLEN) {
4976 TRACE_ERROR("wrong ODCID length", QUIC_EV_CONN_LPKT, qc);
4977 goto leave;
4978 }
4979
4980 if (end - token < odcid_len + sizeof timestamp) {
4981 TRACE_ERROR("too long ODCID length", QUIC_EV_CONN_LPKT, qc);
4982 goto leave;
4983 }
4984
4985 timestamp = ntohl(read_u32(token + odcid_len));
4986 if (timestamp + MS_TO_TICKS(QUIC_RETRY_DURATION_MS) <= now_ms) {
4987 TRACE_ERROR("token has expired", QUIC_EV_CONN_LPKT, qc);
4988 goto leave;
4989 }
4990
4991 ret = 1;
4992 memcpy(odcid->data, token, odcid_len);
4993 odcid->len = odcid_len;
4994 leave:
4995 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4996 return !ret;
4997}
4998
4999/* Allocate a new QUIC connection with <version> as QUIC version. <ipv4>
5000 * boolean is set to 1 for IPv4 connection, 0 for IPv6. <server> is set to 1
5001 * for QUIC servers (or haproxy listeners).
5002 * <dcid> is the destination connection ID, <scid> is the source connection ID,
5003 * <token> the token found to be used for this connection with <token_len> as
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005004 * length. Endpoints addresses are specified via <local_addr> and <peer_addr>.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005005 * Returns the connection if succeeded, NULL if not.
5006 */
5007static struct quic_conn *qc_new_conn(const struct quic_version *qv, int ipv4,
5008 struct quic_cid *dcid, struct quic_cid *scid,
5009 const struct quic_cid *token_odcid,
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005010 struct sockaddr_storage *local_addr,
5011 struct sockaddr_storage *peer_addr,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005012 int server, int token, void *owner)
5013{
5014 int i;
5015 struct quic_conn *qc;
5016 /* Initial CID. */
5017 struct quic_connection_id *icid;
5018 char *buf_area = NULL;
5019 struct listener *l = NULL;
5020 struct quic_cc_algo *cc_algo = NULL;
5021 struct quic_tls_ctx *ictx;
5022 TRACE_ENTER(QUIC_EV_CONN_INIT);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005023 /* TODO replace pool_zalloc by pool_alloc(). This requires special care
5024 * to properly initialized internal quic_conn members to safely use
5025 * quic_conn_release() on alloc failure.
5026 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005027 qc = pool_zalloc(pool_head_quic_conn);
5028 if (!qc) {
5029 TRACE_ERROR("Could not allocate a new connection", QUIC_EV_CONN_INIT);
5030 goto err;
5031 }
5032
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005033 /* Initialize in priority qc members required for a safe dealloc. */
5034
5035 /* required to use MTLIST_IN_LIST */
5036 MT_LIST_INIT(&qc->accept_list);
5037
5038 LIST_INIT(&qc->rx.pkt_list);
5039
Amaury Denoyelle42448332022-12-12 11:24:05 +01005040 qc_init_fd(qc);
5041
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005042 LIST_INIT(&qc->back_refs);
5043
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005044 /* Now proceeds to allocation of qc members. */
5045
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005046 buf_area = pool_alloc(pool_head_quic_conn_rxbuf);
5047 if (!buf_area) {
5048 TRACE_ERROR("Could not allocate a new RX buffer", QUIC_EV_CONN_INIT, qc);
5049 goto err;
5050 }
5051
5052 qc->cids = EB_ROOT;
5053 /* QUIC Server (or listener). */
5054 if (server) {
5055 struct proxy *prx;
5056
5057 l = owner;
5058 prx = l->bind_conf->frontend;
5059 cc_algo = l->bind_conf->quic_cc_algo;
5060
5061 qc->prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe,
5062 &quic_stats_module);
5063 qc->flags |= QUIC_FL_CONN_LISTENER;
5064 qc->state = QUIC_HS_ST_SERVER_INITIAL;
5065 /* Copy the initial DCID with the address. */
5066 qc->odcid.len = dcid->len;
5067 qc->odcid.addrlen = dcid->addrlen;
5068 memcpy(qc->odcid.data, dcid->data, dcid->len + dcid->addrlen);
5069
5070 /* copy the packet SCID to reuse it as DCID for sending */
5071 if (scid->len)
5072 memcpy(qc->dcid.data, scid->data, scid->len);
5073 qc->dcid.len = scid->len;
5074 qc->tx.buf = BUF_NULL;
5075 qc->li = l;
5076 }
5077 /* QUIC Client (outgoing connection to servers) */
5078 else {
5079 qc->state = QUIC_HS_ST_CLIENT_INITIAL;
5080 if (dcid->len)
5081 memcpy(qc->dcid.data, dcid->data, dcid->len);
5082 qc->dcid.len = dcid->len;
5083 }
5084 qc->mux_state = QC_MUX_NULL;
5085 qc->err = quic_err_transport(QC_ERR_NO_ERROR);
5086
5087 icid = new_quic_cid(&qc->cids, qc, 0);
5088 if (!icid) {
5089 TRACE_ERROR("Could not allocate a new connection ID", QUIC_EV_CONN_INIT, qc);
5090 goto err;
5091 }
5092
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005093 if ((global.tune.options & GTUNE_QUIC_SOCK_PER_CONN) &&
5094 is_addr(local_addr)) {
5095 TRACE_USER("Allocate a socket for QUIC connection", QUIC_EV_CONN_INIT, qc);
5096 qc_alloc_fd(qc, local_addr, peer_addr);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005097
5098 /* haproxy soft-stop is supported only for QUIC connections
5099 * with their owned socket.
5100 */
5101 if (qc_test_fd(qc))
5102 _HA_ATOMIC_INC(&jobs);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005103 }
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005104
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005105 /* insert the allocated CID in the receiver datagram handler tree */
5106 if (server)
5107 ebmb_insert(&quic_dghdlrs[tid].cids, &icid->node, icid->cid.len);
5108
5109 /* Select our SCID which is the first CID with 0 as sequence number. */
5110 qc->scid = icid->cid;
5111
5112 /* Packet number spaces initialization. */
5113 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
5114 quic_pktns_init(&qc->pktns[i]);
5115 /* QUIC encryption level context initialization. */
5116 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5117 if (!quic_conn_enc_level_init(qc, i)) {
5118 TRACE_ERROR("Could not initialize an encryption level", QUIC_EV_CONN_INIT, qc);
5119 goto err;
5120 }
5121 /* Initialize the packet number space. */
5122 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
5123 }
5124
5125 qc->original_version = qv;
5126 qc->tps_tls_ext = (qc->original_version->num & 0xff000000) == 0xff000000 ?
5127 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS_DRAFT:
5128 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS;
5129 /* TX part. */
5130 LIST_INIT(&qc->tx.frms_to_send);
5131 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
5132 qc->tx.wbuf = qc->tx.rbuf = 0;
5133 qc->tx.bytes = 0;
5134 qc->tx.buf = BUF_NULL;
5135 /* RX part. */
5136 qc->rx.bytes = 0;
5137 qc->rx.buf = b_make(buf_area, QUIC_CONN_RX_BUFSZ, 0, 0);
5138 for (i = 0; i < QCS_MAX_TYPES; i++)
5139 qc->rx.strms[i].nb_streams = 0;
5140
5141 qc->nb_pkt_for_cc = 1;
5142 qc->nb_pkt_since_cc = 0;
5143
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005144 if (!quic_tls_ku_init(qc)) {
5145 TRACE_ERROR("Key update initialization failed", QUIC_EV_CONN_INIT, qc);
5146 goto err;
5147 }
5148
5149 /* XXX TO DO: Only one path at this time. */
5150 qc->path = &qc->paths[0];
5151 quic_path_init(qc->path, ipv4, cc_algo ? cc_algo : default_quic_cc_algo, qc);
5152
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005153 qc->streams_by_id = EB_ROOT_UNIQUE;
5154 qc->stream_buf_count = 0;
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02005155 memcpy(&qc->local_addr, local_addr, sizeof(qc->local_addr));
5156 memcpy(&qc->peer_addr, peer_addr, sizeof qc->peer_addr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005157
5158 if (server && !qc_lstnr_params_init(qc, &l->bind_conf->quic_params,
5159 icid->stateless_reset_token,
5160 dcid->data, dcid->len,
5161 qc->scid.data, qc->scid.len, token_odcid))
5162 goto err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005163
5164 qc->wait_event.tasklet = tasklet_new();
5165 if (!qc->wait_event.tasklet) {
5166 TRACE_ERROR("tasklet_new() failed", QUIC_EV_CONN_TXPKT);
5167 goto err;
5168 }
5169 qc->wait_event.tasklet->process = quic_conn_io_cb;
5170 qc->wait_event.tasklet->context = qc;
5171 qc->wait_event.events = 0;
5172 /* Set tasklet tid based on the SCID selected by us for this
5173 * connection. The upper layer will also be binded on the same thread.
5174 */
Willy Tarreaueed78262022-12-21 09:09:19 +01005175 qc->tid = quic_get_cid_tid(qc->scid.data, &l->rx);
Willy Tarreauf5a0c8a2022-10-13 16:14:11 +02005176 qc->wait_event.tasklet->tid = qc->tid;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02005177 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005178
5179 if (qc_conn_alloc_ssl_ctx(qc) ||
5180 !quic_conn_init_timer(qc) ||
5181 !quic_conn_init_idle_timer_task(qc))
5182 goto err;
5183
5184 ictx = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
5185 if (!qc_new_isecs(qc, ictx,qc->original_version, dcid->data, dcid->len, 1))
5186 goto err;
5187
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005188 LIST_APPEND(&th_ctx->quic_conns, &qc->el_th_ctx);
5189 qc->qc_epoch = HA_ATOMIC_LOAD(&qc_epoch);
5190
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005191 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc);
5192
5193 return qc;
5194
5195 err:
5196 pool_free(pool_head_quic_conn_rxbuf, buf_area);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005197 if (qc) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005198 qc->rx.buf.area = NULL;
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005199 quic_conn_release(qc);
5200 }
5201 TRACE_LEAVE(QUIC_EV_CONN_INIT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005202 return NULL;
5203}
5204
5205/* Release the quic_conn <qc>. The connection is removed from the CIDs tree.
5206 * The connection tasklet is killed.
5207 *
5208 * This function must only be called by the thread responsible of the quic_conn
5209 * tasklet.
5210 */
5211void quic_conn_release(struct quic_conn *qc)
5212{
5213 int i;
5214 struct ssl_sock_ctx *conn_ctx;
5215 struct eb64_node *node;
5216 struct quic_tls_ctx *app_tls_ctx;
5217 struct quic_rx_packet *pkt, *pktback;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005218 struct bref *bref, *back;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005219
5220 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
5221
5222 /* We must not free the quic-conn if the MUX is still allocated. */
5223 BUG_ON(qc->mux_state == QC_MUX_READY);
5224
Amaury Denoyellefb375572023-02-01 09:28:32 +01005225 if (qc_test_fd(qc))
5226 _HA_ATOMIC_DEC(&jobs);
5227
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005228 /* Close quic-conn socket fd. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01005229 qc_release_fd(qc, 0);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02005230
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005231 /* in the unlikely (but possible) case the connection was just added to
5232 * the accept_list we must delete it from there.
5233 */
5234 MT_LIST_DELETE(&qc->accept_list);
5235
5236 /* free remaining stream descriptors */
5237 node = eb64_first(&qc->streams_by_id);
5238 while (node) {
5239 struct qc_stream_desc *stream;
5240
5241 stream = eb64_entry(node, struct qc_stream_desc, by_id);
5242 node = eb64_next(node);
5243
5244 /* all streams attached to the quic-conn are released, so
5245 * qc_stream_desc_free will liberate the stream instance.
5246 */
5247 BUG_ON(!stream->release);
5248 qc_stream_desc_free(stream, 1);
5249 }
5250
5251 /* Purge Rx packet list. */
5252 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
5253 LIST_DELETE(&pkt->qc_rx_pkt_list);
5254 pool_free(pool_head_quic_rx_packet, pkt);
5255 }
5256
5257 if (qc->idle_timer_task) {
5258 task_destroy(qc->idle_timer_task);
5259 qc->idle_timer_task = NULL;
5260 }
5261
5262 if (qc->timer_task) {
5263 task_destroy(qc->timer_task);
5264 qc->timer_task = NULL;
5265 }
5266
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005267 if (qc->wait_event.tasklet)
5268 tasklet_free(qc->wait_event.tasklet);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005269
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005270 /* remove the connection from receiver cids trees */
5271 ebmb_delete(&qc->odcid_node);
5272 ebmb_delete(&qc->scid_node);
5273 free_quic_conn_cids(qc);
5274
5275 conn_ctx = qc->xprt_ctx;
5276 if (conn_ctx) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005277 SSL_free(conn_ctx->ssl);
5278 pool_free(pool_head_quic_conn_ctx, conn_ctx);
5279 }
5280
5281 quic_tls_ku_free(qc);
5282 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5283 quic_tls_ctx_secs_free(&qc->els[i].tls_ctx);
5284 quic_conn_enc_level_uninit(qc, &qc->els[i]);
5285 }
5286 quic_tls_ctx_secs_free(&qc->negotiated_ictx);
5287
5288 app_tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
5289 pool_free(pool_head_quic_tls_secret, app_tls_ctx->rx.secret);
5290 pool_free(pool_head_quic_tls_secret, app_tls_ctx->tx.secret);
5291
5292 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++) {
5293 quic_pktns_tx_pkts_release(&qc->pktns[i], qc);
5294 quic_free_arngs(qc, &qc->pktns[i].rx.arngs);
5295 }
5296
Amaury Denoyelle15c74702023-02-01 10:18:26 +01005297 /* Detach CLI context watchers currently dumping this connection.
5298 * Reattach them to the next quic_conn instance.
5299 */
5300 list_for_each_entry_safe(bref, back, &qc->back_refs, users) {
5301 /* Remove watcher from this quic_conn instance. */
5302 LIST_DEL_INIT(&bref->users);
5303
5304 /* Attach it to next instance unless it was the last list element. */
5305 if (qc->el_th_ctx.n != &th_ctx->quic_conns) {
5306 struct quic_conn *next = LIST_NEXT(&qc->el_th_ctx,
5307 struct quic_conn *,
5308 el_th_ctx);
5309 LIST_APPEND(&next->back_refs, &bref->users);
5310 }
5311 bref->ref = qc->el_th_ctx.n;
5312 __ha_barrier_store();
5313 }
5314 /* Remove quic_conn from global ha_thread_ctx list. */
5315 LIST_DELETE(&qc->el_th_ctx);
5316
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005317 pool_free(pool_head_quic_conn_rxbuf, qc->rx.buf.area);
5318 pool_free(pool_head_quic_conn, qc);
Amaury Denoyellefb375572023-02-01 09:28:32 +01005319
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005320 TRACE_PROTO("QUIC conn. freed", QUIC_EV_CONN_FREED, qc);
5321
5322 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5323}
5324
5325/* Initialize the timer task of <qc> QUIC connection.
5326 * Returns 1 if succeeded, 0 if not.
5327 */
5328static int quic_conn_init_timer(struct quic_conn *qc)
5329{
5330 int ret = 0;
5331 /* Attach this task to the same thread ID used for the connection */
5332 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5333
5334 qc->timer_task = task_new_on(qc->tid);
5335 if (!qc->timer_task) {
5336 TRACE_ERROR("timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5337 goto leave;
5338 }
5339
5340 qc->timer = TICK_ETERNITY;
5341 qc->timer_task->process = qc_process_timer;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005342 qc->timer_task->context = qc;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005343
5344 ret = 1;
5345 leave:
5346 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5347 return ret;
5348}
5349
5350/* Rearm the idle timer for <qc> QUIC connection. */
5351static void qc_idle_timer_do_rearm(struct quic_conn *qc)
5352{
5353 unsigned int expire;
5354
Amaury Denoyelle77ed6312023-02-01 09:28:55 +01005355 if (stopping && qc->flags & (QUIC_FL_CONN_CLOSING|QUIC_FL_CONN_DRAINING)) {
5356 TRACE_STATE("executing idle timer immediately on stopping", QUIC_EV_CONN_IDLE_TIMER, qc);
5357 task_wakeup(qc->idle_timer_task, TASK_WOKEN_MSG);
5358 }
5359 else {
5360 expire = QUIC_MAX(3 * quic_pto(qc), qc->max_idle_timeout);
5361 qc->idle_timer_task->expire = tick_add(now_ms, MS_TO_TICKS(expire));
5362 task_queue(qc->idle_timer_task);
5363 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005364}
5365
5366/* Rearm the idle timer for <qc> QUIC connection depending on <read> boolean
5367 * which is set to 1 when receiving a packet , and 0 when sending packet
5368 */
5369static void qc_idle_timer_rearm(struct quic_conn *qc, int read)
5370{
5371 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5372
5373 if (read) {
5374 qc->flags |= QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5375 }
5376 else {
5377 qc->flags &= ~QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5378 }
5379 qc_idle_timer_do_rearm(qc);
5380
5381 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5382}
5383
5384/* The task handling the idle timeout */
5385struct task *qc_idle_timer_task(struct task *t, void *ctx, unsigned int state)
5386{
5387 struct quic_conn *qc = ctx;
5388 struct quic_counters *prx_counters = qc->prx_counters;
5389 unsigned int qc_flags = qc->flags;
5390
5391 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5392
5393 /* Notify the MUX before settings QUIC_FL_CONN_EXP_TIMER or the MUX
5394 * might free the quic-conn too early via quic_close().
5395 */
5396 qc_notify_close(qc);
5397
5398 /* If the MUX is still alive, keep the quic-conn. The MUX is
5399 * responsible to call quic_close to release it.
5400 */
5401 qc->flags |= QUIC_FL_CONN_EXP_TIMER;
5402 if (qc->mux_state != QC_MUX_READY)
5403 quic_conn_release(qc);
5404
5405 /* TODO if the quic-conn cannot be freed because of the MUX, we may at
5406 * least clean some parts of it such as the tasklet.
5407 */
5408
5409 if (!(qc_flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
5410 qc_flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
5411 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
5412 HA_ATOMIC_DEC(&prx_counters->half_open_conn);
5413 }
5414
5415 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5416 return NULL;
5417}
5418
5419/* Initialize the idle timeout task for <qc>.
5420 * Returns 1 if succeeded, 0 if not.
5421 */
5422static int quic_conn_init_idle_timer_task(struct quic_conn *qc)
5423{
5424 int ret = 0;
5425
5426 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5427
5428 qc->idle_timer_task = task_new_here();
5429 if (!qc->idle_timer_task) {
5430 TRACE_ERROR("Idle timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5431 goto leave;
5432 }
5433
5434 qc->idle_timer_task->process = qc_idle_timer_task;
5435 qc->idle_timer_task->context = qc;
5436 qc_idle_timer_rearm(qc, 1);
5437 task_queue(qc->idle_timer_task);
5438
5439 ret = 1;
5440 leave:
5441 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5442 return ret;
5443}
5444
5445/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
5446 * past one byte of this buffer.
5447 */
5448static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
5449 struct quic_rx_packet *pkt)
5450{
5451 int ret = 0;
5452 unsigned char dcid_len, scid_len;
5453
5454 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5455
5456 if (end == *buf) {
5457 TRACE_ERROR("buffer data consumed", QUIC_EV_CONN_RXPKT);
5458 goto leave;
5459 }
5460
5461 /* Destination Connection ID Length */
5462 dcid_len = *(*buf)++;
5463 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
5464 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1) {
5465 TRACE_ERROR("too long DCID", QUIC_EV_CONN_RXPKT);
5466 goto leave;
5467 }
5468
5469 if (dcid_len) {
5470 /* Check that the length of this received DCID matches the CID lengths
5471 * of our implementation for non Initials packets only.
5472 */
5473 if (pkt->type != QUIC_PACKET_TYPE_INITIAL &&
5474 pkt->type != QUIC_PACKET_TYPE_0RTT &&
5475 dcid_len != QUIC_HAP_CID_LEN) {
5476 TRACE_ERROR("wrong DCID length", QUIC_EV_CONN_RXPKT);
5477 goto leave;
5478 }
5479
5480 memcpy(pkt->dcid.data, *buf, dcid_len);
5481 }
5482
5483 pkt->dcid.len = dcid_len;
5484 *buf += dcid_len;
5485
5486 /* Source Connection ID Length */
5487 scid_len = *(*buf)++;
5488 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len) {
5489 TRACE_ERROR("too long SCID", QUIC_EV_CONN_RXPKT);
5490 goto leave;
5491 }
5492
5493 if (scid_len)
5494 memcpy(pkt->scid.data, *buf, scid_len);
5495 pkt->scid.len = scid_len;
5496 *buf += scid_len;
5497
5498 ret = 1;
5499 leave:
5500 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5501 return ret;
5502}
5503
5504/* Insert <pkt> RX packet in its <qel> RX packets tree */
5505static void qc_pkt_insert(struct quic_conn *qc,
5506 struct quic_rx_packet *pkt, struct quic_enc_level *qel)
5507{
5508 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
5509
5510 pkt->pn_node.key = pkt->pn;
5511 quic_rx_packet_refinc(pkt);
5512 eb64_insert(&qel->rx.pkts, &pkt->pn_node);
5513
5514 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5515}
5516
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005517/* Try to remove the header protection of <pkt> QUIC packet with <beg> the
5518 * address of the packet first byte, using the keys from encryption level <el>.
5519 *
5520 * If header protection has been successfully removed, packet data are copied
5521 * into <qc> Rx buffer. If <el> secrets are not yet available, the copy is also
5522 * proceeded, and the packet is inserted into <qc> protected packets tree. In
5523 * both cases, packet can now be considered handled by the <qc> connection.
5524 *
5525 * If header protection cannot be removed due to <el> secrets already
5526 * discarded, no operation is conducted.
5527 *
5528 * Returns 1 on success : packet data is now handled by the connection. On
5529 * error 0 is returned : packet should be dropped by the caller.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005530 */
5531static inline int qc_try_rm_hp(struct quic_conn *qc,
5532 struct quic_rx_packet *pkt,
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005533 unsigned char *beg,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005534 struct quic_enc_level **el)
5535{
5536 int ret = 0;
5537 unsigned char *pn = NULL; /* Packet number field */
5538 enum quic_tls_enc_level tel;
5539 struct quic_enc_level *qel;
5540 /* Only for traces. */
5541 struct quic_rx_packet *qpkt_trace;
5542
5543 qpkt_trace = NULL;
5544 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005545 BUG_ON(!pkt->pn_offset);
5546
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005547 /* The packet number is here. This is also the start minus
5548 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
5549 * protection.
5550 */
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005551 pn = beg + pkt->pn_offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005552
5553 tel = quic_packet_type_enc_level(pkt->type);
5554 qel = &qc->els[tel];
5555
5556 if (qc_qel_may_rm_hp(qc, qel)) {
5557 /* Note that the following function enables us to unprotect the packet
5558 * number and its length subsequently used to decrypt the entire
5559 * packets.
5560 */
5561 if (!qc_do_rm_hp(qc, pkt, &qel->tls_ctx,
5562 qel->pktns->rx.largest_pn, pn, beg)) {
5563 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, qc);
5564 goto out;
5565 }
5566
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005567 /* The AAD includes the packet number field. */
5568 pkt->aad_len = pkt->pn_offset + pkt->pnl;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005569 if (pkt->len - pkt->aad_len < QUIC_TLS_TAG_LEN) {
5570 TRACE_PROTO("Too short packet", QUIC_EV_CONN_TRMHP, qc);
5571 goto out;
5572 }
5573
5574 qpkt_trace = pkt;
5575 }
5576 else {
5577 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
5578 /* If the packet number space has been discarded, this packet
5579 * will be not parsed.
5580 */
5581 TRACE_PROTO("Discarded pktns", QUIC_EV_CONN_TRMHP, qc, pkt);
5582 goto out;
5583 }
5584
5585 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005586 LIST_APPEND(&qel->rx.pqpkts, &pkt->list);
5587 quic_rx_packet_refinc(pkt);
5588 }
5589
5590 *el = qel;
5591 /* No reference counter incrementation here!!! */
5592 LIST_APPEND(&qc->rx.pkt_list, &pkt->qc_rx_pkt_list);
5593 memcpy(b_tail(&qc->rx.buf), beg, pkt->len);
5594 pkt->data = (unsigned char *)b_tail(&qc->rx.buf);
5595 b_add(&qc->rx.buf, pkt->len);
5596
5597 ret = 1;
5598 out:
5599 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc, qpkt_trace);
5600 return ret;
5601}
5602
5603/* Parse the header form from <byte0> first byte of <pkt> packet to set its type.
5604 * Also set <*long_header> to 1 if this form is long, 0 if not and the version
5605 * of this packet into <*version>.
5606 */
5607static inline int qc_parse_hd_form(struct quic_rx_packet *pkt,
5608 unsigned char **buf, const unsigned char *end,
5609 int *long_header, uint32_t *version)
5610{
5611 int ret = 0;
5612 const unsigned char byte0 = **buf;
5613
5614 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5615
5616 (*buf)++;
5617 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
5618 unsigned char type =
5619 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
5620
5621 *long_header = 1;
5622 /* Version */
5623 if (!quic_read_uint32(version, (const unsigned char **)buf, end)) {
5624 TRACE_ERROR("could not read the packet version", QUIC_EV_CONN_RXPKT);
5625 goto out;
5626 }
5627
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +01005628 if (*version != QUIC_PROTOCOL_VERSION_2) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005629 pkt->type = type;
5630 }
5631 else {
5632 switch (type) {
5633 case 0:
5634 pkt->type = QUIC_PACKET_TYPE_RETRY;
5635 break;
5636 case 1:
5637 pkt->type = QUIC_PACKET_TYPE_INITIAL;
5638 break;
5639 case 2:
5640 pkt->type = QUIC_PACKET_TYPE_0RTT;
5641 break;
5642 case 3:
5643 pkt->type = QUIC_PACKET_TYPE_HANDSHAKE;
5644 break;
5645 }
5646 }
5647 }
5648 else {
5649 pkt->type = QUIC_PACKET_TYPE_SHORT;
5650 *long_header = 0;
5651 }
5652
5653 ret = 1;
5654 out:
5655 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5656 return ret;
5657}
5658
5659/* Return the QUIC version (quic_version struct) with <version> as version number
5660 * if supported or NULL if not.
5661 */
5662static inline const struct quic_version *qc_supported_version(uint32_t version)
5663{
5664 int i;
5665
5666 for (i = 0; i < quic_versions_nb; i++)
5667 if (quic_versions[i].num == version)
5668 return &quic_versions[i];
5669
5670 return NULL;
5671}
5672
5673/*
5674 * Send a Version Negotiation packet on response to <pkt> on socket <fd> to
5675 * address <addr>.
5676 * Implementation of RFC9000 6. Version Negotiation
5677 *
5678 * TODO implement a rate-limiting sending of Version Negotiation packets
5679 *
5680 * Returns 0 on success else non-zero
5681 */
5682static int send_version_negotiation(int fd, struct sockaddr_storage *addr,
5683 struct quic_rx_packet *pkt)
5684{
5685 char buf[256];
5686 int ret = 0, i = 0, j;
5687 uint32_t version;
5688 const socklen_t addrlen = get_addr_len(addr);
5689
5690 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5691 /*
5692 * header form
5693 * long header, fixed bit to 0 for Version Negotiation
5694 */
5695 /* TODO: RAND_bytes() should be replaced? */
5696 if (RAND_bytes((unsigned char *)buf, 1) != 1) {
5697 TRACE_ERROR("RAND_bytes() error", QUIC_EV_CONN_TXPKT);
5698 goto out;
5699 }
5700
5701 buf[i++] |= '\x80';
5702 /* null version for Version Negotiation */
5703 buf[i++] = '\x00';
5704 buf[i++] = '\x00';
5705 buf[i++] = '\x00';
5706 buf[i++] = '\x00';
5707
5708 /* source connection id */
5709 buf[i++] = pkt->scid.len;
5710 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5711 i += pkt->scid.len;
5712
5713 /* destination connection id */
5714 buf[i++] = pkt->dcid.len;
5715 memcpy(&buf[i], pkt->dcid.data, pkt->dcid.len);
5716 i += pkt->dcid.len;
5717
5718 /* supported version */
5719 for (j = 0; j < quic_versions_nb; j++) {
5720 version = htonl(quic_versions[j].num);
5721 memcpy(&buf[i], &version, sizeof(version));
5722 i += sizeof(version);
5723 }
5724
5725 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0)
5726 goto out;
5727
5728 ret = 1;
5729 out:
5730 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5731 return !ret;
5732}
5733
5734/* Send a stateless reset packet depending on <pkt> RX packet information
5735 * from <fd> UDP socket to <dst>
5736 * Return 1 if succeeded, 0 if not.
5737 */
5738static int send_stateless_reset(struct listener *l, struct sockaddr_storage *dstaddr,
5739 struct quic_rx_packet *rxpkt)
5740{
5741 int ret = 0, pktlen, rndlen;
5742 unsigned char pkt[64];
5743 const socklen_t addrlen = get_addr_len(dstaddr);
5744 struct proxy *prx;
5745 struct quic_counters *prx_counters;
5746
5747 TRACE_ENTER(QUIC_EV_STATELESS_RST);
5748
5749 prx = l->bind_conf->frontend;
5750 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5751 /* 10.3 Stateless Reset (https://www.rfc-editor.org/rfc/rfc9000.html#section-10.3)
5752 * The resulting minimum size of 21 bytes does not guarantee that a Stateless
5753 * Reset is difficult to distinguish from other packets if the recipient requires
5754 * the use of a connection ID. To achieve that end, the endpoint SHOULD ensure
5755 * that all packets it sends are at least 22 bytes longer than the minimum
5756 * connection ID length that it requests the peer to include in its packets,
5757 * adding PADDING frames as necessary. This ensures that any Stateless Reset
5758 * sent by the peer is indistinguishable from a valid packet sent to the endpoint.
5759 * An endpoint that sends a Stateless Reset in response to a packet that is
5760 * 43 bytes or shorter SHOULD send a Stateless Reset that is one byte shorter
5761 * than the packet it responds to.
5762 */
5763
5764 /* Note that we build at most a 42 bytes QUIC packet to mimic a short packet */
5765 pktlen = rxpkt->len <= 43 ? rxpkt->len - 1 : 0;
5766 pktlen = QUIC_MAX(QUIC_STATELESS_RESET_PACKET_MINLEN, pktlen);
5767 rndlen = pktlen - QUIC_STATELESS_RESET_TOKEN_LEN;
5768
5769 /* Put a header of random bytes */
5770 /* TODO: RAND_bytes() should be replaced */
5771 if (RAND_bytes(pkt, rndlen) != 1) {
5772 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_STATELESS_RST);
5773 goto leave;
5774 }
5775
5776 /* Clear the most significant bit, and set the second one */
5777 *pkt = (*pkt & ~0x80) | 0x40;
5778 if (!quic_stateless_reset_token_cpy(NULL, pkt + rndlen, QUIC_STATELESS_RESET_TOKEN_LEN,
5779 rxpkt->dcid.data, rxpkt->dcid.len))
5780 goto leave;
5781
5782 if (sendto(l->rx.fd, pkt, pktlen, 0, (struct sockaddr *)dstaddr, addrlen) < 0)
5783 goto leave;
5784
5785 ret = 1;
5786 HA_ATOMIC_INC(&prx_counters->stateless_reset_sent);
5787 TRACE_PROTO("stateless reset sent", QUIC_EV_STATELESS_RST, NULL, &rxpkt->dcid);
5788 leave:
5789 TRACE_LEAVE(QUIC_EV_STATELESS_RST);
5790 return ret;
5791}
5792
5793/* QUIC server only function.
5794 * Add AAD to <add> buffer from <cid> connection ID and <addr> socket address.
5795 * This is the responsibility of the caller to check <aad> size is big enough
5796 * to contain these data.
5797 * Return the number of bytes copied to <aad>.
5798 */
5799static int quic_generate_retry_token_aad(unsigned char *aad,
5800 uint32_t version,
5801 const struct quic_cid *cid,
5802 const struct sockaddr_storage *addr)
5803{
5804 unsigned char *p;
5805
5806 p = aad;
5807 memcpy(p, &version, sizeof version);
5808 p += sizeof version;
5809 p += quic_saddr_cpy(p, addr);
5810 memcpy(p, cid->data, cid->len);
5811 p += cid->len;
5812
5813 return p - aad;
5814}
5815
5816/* QUIC server only function.
5817 * Generate the token to be used in Retry packets. The token is written to
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05005818 * <buf> with <len> as length. <odcid> is the original destination connection
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005819 * ID and <dcid> is our side destination connection ID (or client source
5820 * connection ID).
5821 * Returns the length of the encoded token or 0 on error.
5822 */
5823static int quic_generate_retry_token(unsigned char *buf, size_t len,
5824 const uint32_t version,
5825 const struct quic_cid *odcid,
5826 const struct quic_cid *dcid,
5827 struct sockaddr_storage *addr)
5828{
5829 int ret = 0;
5830 unsigned char *p;
5831 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005832 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005833 size_t aadlen;
5834 unsigned char salt[QUIC_RETRY_TOKEN_SALTLEN];
5835 unsigned char key[QUIC_TLS_KEY_LEN];
5836 unsigned char iv[QUIC_TLS_IV_LEN];
5837 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5838 size_t seclen = strlen(global.cluster_secret);
5839 EVP_CIPHER_CTX *ctx = NULL;
5840 const EVP_CIPHER *aead = EVP_aes_128_gcm();
5841 uint32_t timestamp = now_ms;
5842
5843 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5844
5845 /* We copy the odcid into the token, prefixed by its one byte
5846 * length, the format token byte. It is followed by an AEAD TAG, and finally
5847 * the random bytes used to derive the secret to encrypt the token.
5848 */
5849 if (1 + dcid->len + 1 + QUIC_TLS_TAG_LEN + sizeof salt > len)
5850 goto err;
5851
5852 aadlen = quic_generate_retry_token_aad(aad, version, dcid, addr);
5853 /* TODO: RAND_bytes() should be replaced */
5854 if (RAND_bytes(salt, sizeof salt) != 1) {
5855 TRACE_ERROR("RAND_bytes()", QUIC_EV_CONN_TXPKT);
5856 goto err;
5857 }
5858
5859 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5860 salt, sizeof salt, sec, seclen)) {
5861 TRACE_ERROR("quic_tls_derive_retry_token_secret() failed", QUIC_EV_CONN_TXPKT);
5862 goto err;
5863 }
5864
5865 if (!quic_tls_tx_ctx_init(&ctx, aead, key)) {
5866 TRACE_ERROR("quic_tls_tx_ctx_init() failed", QUIC_EV_CONN_TXPKT);
5867 goto err;
5868 }
5869
5870 /* Token build */
5871 p = buf;
5872 *p++ = QUIC_TOKEN_FMT_RETRY,
5873 *p++ = odcid->len;
5874 memcpy(p, odcid->data, odcid->len);
5875 p += odcid->len;
5876 write_u32(p, htonl(timestamp));
5877 p += sizeof timestamp;
5878
5879 /* Do not encrypt the QUIC_TOKEN_FMT_RETRY byte */
5880 if (!quic_tls_encrypt(buf + 1, p - buf - 1, aad, aadlen, ctx, aead, key, iv)) {
5881 TRACE_ERROR("quic_tls_encrypt() failed", QUIC_EV_CONN_TXPKT);
5882 goto err;
5883 }
5884
5885 p += QUIC_TLS_TAG_LEN;
5886 memcpy(p, salt, sizeof salt);
5887 p += sizeof salt;
5888 EVP_CIPHER_CTX_free(ctx);
5889
5890 ret = p - buf;
5891 leave:
5892 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5893 return ret;
5894
5895 err:
5896 if (ctx)
5897 EVP_CIPHER_CTX_free(ctx);
5898 goto leave;
5899}
5900
5901/* QUIC server only function.
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005902 *
5903 * Check the validity of the Retry token from Initial packet <pkt>. <dgram> is
5904 * the UDP datagram containing <pkt> and <l> is the listener instance on which
5905 * it was received. If the token is valid, the ODCID of <qc> QUIC connection
5906 * will be put into <odcid>. <qc> is used to retrieve the QUIC version needed
5907 * to validate the token but it can be NULL : in this case the version will be
5908 * retrieved from the packet.
5909 *
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005910 * Return 1 if succeeded, 0 if not.
5911 */
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005912
5913static int quic_retry_token_check(struct quic_rx_packet *pkt,
5914 struct quic_dgram *dgram,
5915 struct listener *l,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005916 struct quic_conn *qc,
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005917 struct quic_cid *odcid)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005918{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005919 struct proxy *prx;
5920 struct quic_counters *prx_counters;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005921 int ret = 0;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005922 unsigned char *token = pkt->token;
5923 const uint64_t tokenlen = pkt->token_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005924 unsigned char buf[128];
5925 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005926 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005927 size_t aadlen;
5928 const unsigned char *salt;
5929 unsigned char key[QUIC_TLS_KEY_LEN];
5930 unsigned char iv[QUIC_TLS_IV_LEN];
5931 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5932 size_t seclen = strlen(global.cluster_secret);
5933 EVP_CIPHER_CTX *ctx = NULL;
5934 const EVP_CIPHER *aead = EVP_aes_128_gcm();
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005935 const struct quic_version *qv = qc ? qc->original_version :
5936 pkt->version;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005937
5938 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5939
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005940 /* The caller must ensure this. */
5941 BUG_ON(!global.cluster_secret || !pkt->token_len);
5942
5943 prx = l->bind_conf->frontend;
5944 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5945
5946 if (*pkt->token != QUIC_TOKEN_FMT_RETRY) {
5947 /* TODO: New token check */
5948 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
5949 goto leave;
5950 }
5951
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005952 if (sizeof buf < tokenlen) {
5953 TRACE_ERROR("too short buffer", QUIC_EV_CONN_LPKT, qc);
5954 goto err;
5955 }
5956
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005957 aadlen = quic_generate_retry_token_aad(aad, qv->num, &pkt->scid, &dgram->saddr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005958 salt = token + tokenlen - QUIC_RETRY_TOKEN_SALTLEN;
5959 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5960 salt, QUIC_RETRY_TOKEN_SALTLEN, sec, seclen)) {
5961 TRACE_ERROR("Could not derive retry secret", QUIC_EV_CONN_LPKT, qc);
5962 goto err;
5963 }
5964
5965 if (!quic_tls_rx_ctx_init(&ctx, aead, key)) {
5966 TRACE_ERROR("quic_tls_rx_ctx_init() failed", QUIC_EV_CONN_LPKT, qc);
5967 goto err;
5968 }
5969
5970 /* Do not decrypt the QUIC_TOKEN_FMT_RETRY byte */
5971 if (!quic_tls_decrypt2(buf, token + 1, tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, aad, aadlen,
5972 ctx, aead, key, iv)) {
5973 TRACE_ERROR("Could not decrypt retry token", QUIC_EV_CONN_LPKT, qc);
5974 goto err;
5975 }
5976
5977 if (parse_retry_token(qc, buf, buf + tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, odcid)) {
5978 TRACE_ERROR("Error during Initial token parsing", QUIC_EV_CONN_LPKT, qc);
5979 goto err;
5980 }
5981
5982 EVP_CIPHER_CTX_free(ctx);
5983
5984 ret = 1;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005985 HA_ATOMIC_INC(&prx_counters->retry_validated);
5986
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005987 leave:
5988 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5989 return ret;
5990
5991 err:
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005992 HA_ATOMIC_INC(&prx_counters->retry_error);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005993 if (ctx)
5994 EVP_CIPHER_CTX_free(ctx);
5995 goto leave;
5996}
5997
5998/* Generate a Retry packet and send it on <fd> socket to <addr> in response to
5999 * the Initial <pkt> packet.
6000 *
6001 * Returns 0 on success else non-zero.
6002 */
6003static int send_retry(int fd, struct sockaddr_storage *addr,
6004 struct quic_rx_packet *pkt, const struct quic_version *qv)
6005{
6006 int ret = 0;
6007 unsigned char buf[128];
6008 int i = 0, token_len;
6009 const socklen_t addrlen = get_addr_len(addr);
6010 struct quic_cid scid;
6011
6012 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
6013
6014 /* long header + fixed bit + packet type QUIC_PACKET_TYPE_RETRY */
6015 buf[i++] = (QUIC_PACKET_LONG_HEADER_BIT | QUIC_PACKET_FIXED_BIT) |
6016 (quic_pkt_type(QUIC_PACKET_TYPE_RETRY, qv->num) << QUIC_PACKET_TYPE_SHIFT);
6017 /* version */
6018 buf[i++] = *((unsigned char *)&qv->num + 3);
6019 buf[i++] = *((unsigned char *)&qv->num + 2);
6020 buf[i++] = *((unsigned char *)&qv->num + 1);
6021 buf[i++] = *(unsigned char *)&qv->num;
6022
6023 /* Use the SCID from <pkt> for Retry DCID. */
6024 buf[i++] = pkt->scid.len;
6025 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
6026 i += pkt->scid.len;
6027
6028 /* Generate a new CID to be used as SCID for the Retry packet. */
6029 scid.len = QUIC_HAP_CID_LEN;
6030 /* TODO: RAND_bytes() should be replaced */
6031 if (RAND_bytes(scid.data, scid.len) != 1) {
6032 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT);
6033 goto out;
6034 }
6035
6036 buf[i++] = scid.len;
6037 memcpy(&buf[i], scid.data, scid.len);
6038 i += scid.len;
6039
6040 /* token */
6041 if (!(token_len = quic_generate_retry_token(&buf[i], sizeof(buf) - i, qv->num,
6042 &pkt->dcid, &pkt->scid, addr))) {
6043 TRACE_ERROR("quic_generate_retry_token() failed", QUIC_EV_CONN_TXPKT);
6044 goto out;
6045 }
6046
6047 i += token_len;
6048
6049 /* token integrity tag */
6050 if ((&buf[i] - buf < QUIC_TLS_TAG_LEN) ||
6051 !quic_tls_generate_retry_integrity_tag(pkt->dcid.data,
6052 pkt->dcid.len, buf, i, qv)) {
6053 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
6054 goto out;
6055 }
6056
6057 i += QUIC_TLS_TAG_LEN;
6058
6059 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0) {
6060 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
6061 goto out;
6062 }
6063
6064 ret = 1;
6065 out:
6066 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
6067 return !ret;
6068}
6069
6070/* Retrieve a quic_conn instance from the <pkt> DCID field. If the packet is of
6071 * type INITIAL, the ODCID tree is first used. In this case, <saddr> is
6072 * concatenated to the <pkt> DCID field.
6073 *
6074 * Returns the instance or NULL if not found.
6075 */
6076static struct quic_conn *retrieve_qc_conn_from_cid(struct quic_rx_packet *pkt,
6077 struct listener *l,
6078 struct sockaddr_storage *saddr)
6079{
6080 struct quic_conn *qc = NULL;
6081 struct ebmb_node *node;
6082 struct quic_connection_id *id;
6083 /* set if the quic_conn is found in the second DCID tree */
6084
6085 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
6086
6087 /* Look first into ODCIDs tree for INITIAL/0-RTT packets. */
6088 if (pkt->type == QUIC_PACKET_TYPE_INITIAL ||
6089 pkt->type == QUIC_PACKET_TYPE_0RTT) {
6090 /* DCIDs of first packets coming from multiple clients may have
6091 * the same values. Let's distinguish them by concatenating the
6092 * socket addresses.
6093 */
6094 quic_cid_saddr_cat(&pkt->dcid, saddr);
6095 node = ebmb_lookup(&quic_dghdlrs[tid].odcids, pkt->dcid.data,
6096 pkt->dcid.len + pkt->dcid.addrlen);
6097 if (node) {
6098 qc = ebmb_entry(node, struct quic_conn, odcid_node);
6099 goto end;
6100 }
6101 }
6102
6103 /* Look into DCIDs tree for non-INITIAL/0-RTT packets. This may be used
6104 * also for INITIAL/0-RTT non-first packets with the final DCID in
6105 * used.
6106 */
6107 node = ebmb_lookup(&quic_dghdlrs[tid].cids, pkt->dcid.data, pkt->dcid.len);
6108 if (!node)
6109 goto end;
6110
6111 id = ebmb_entry(node, struct quic_connection_id, node);
6112 qc = id->qc;
6113
6114 /* If found in DCIDs tree, remove the quic_conn from the ODCIDs tree.
6115 * If already done, this is a noop.
6116 */
6117 if (qc)
6118 ebmb_delete(&qc->odcid_node);
6119
6120 end:
6121 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
6122 return qc;
6123}
6124
6125/* Try to allocate the <*ssl> SSL session object for <qc> QUIC connection
6126 * with <ssl_ctx> as SSL context inherited settings. Also set the transport
6127 * parameters of this session.
6128 * This is the responsibility of the caller to check the validity of all the
6129 * pointers passed as parameter to this function.
6130 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <qc->conn> to
6131 * CO_ER_SSL_NO_MEM.
6132 */
6133static int qc_ssl_sess_init(struct quic_conn *qc, SSL_CTX *ssl_ctx, SSL **ssl,
6134 unsigned char *params, size_t params_len)
6135{
6136 int retry, ret = -1;
6137
6138 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6139
6140 retry = 1;
6141 retry:
6142 *ssl = SSL_new(ssl_ctx);
6143 if (!*ssl) {
6144 if (!retry--)
6145 goto err;
6146
6147 pool_gc(NULL);
6148 goto retry;
6149 }
6150
6151 if (!SSL_set_quic_method(*ssl, &ha_quic_method) ||
6152 !SSL_set_ex_data(*ssl, ssl_qc_app_data_index, qc)) {
6153 SSL_free(*ssl);
6154 *ssl = NULL;
6155 if (!retry--)
6156 goto err;
6157
6158 pool_gc(NULL);
6159 goto retry;
6160 }
6161
6162 ret = 0;
6163 leave:
6164 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6165 return ret;
6166
6167 err:
6168 qc->conn->err_code = CO_ER_SSL_NO_MEM;
6169 goto leave;
6170}
6171
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006172/* Allocate the ssl_sock_ctx from connection <qc>. This creates the tasklet
6173 * used to process <qc> received packets. The allocated context is stored in
6174 * <qc.xprt_ctx>.
6175 *
6176 * Returns 0 on success else non-zero.
6177 */
6178static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc)
6179{
6180 int ret = 0;
6181 struct bind_conf *bc = qc->li->bind_conf;
6182 struct ssl_sock_ctx *ctx = NULL;
6183
6184 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
6185
6186 ctx = pool_zalloc(pool_head_quic_conn_ctx);
6187 if (!ctx) {
6188 TRACE_ERROR("SSL context allocation failed", QUIC_EV_CONN_TXPKT);
6189 goto err;
6190 }
6191
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006192 ctx->subs = NULL;
6193 ctx->xprt_ctx = NULL;
6194 ctx->qc = qc;
6195
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006196 if (qc_is_listener(qc)) {
6197 if (qc_ssl_sess_init(qc, bc->initial_ctx, &ctx->ssl,
6198 qc->enc_params, qc->enc_params_len) == -1) {
6199 goto err;
6200 }
6201#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
6202 /* Enabling 0-RTT */
6203 if (bc->ssl_conf.early_data)
6204 SSL_set_quic_early_data_enabled(ctx->ssl, 1);
6205#endif
6206
6207 SSL_set_accept_state(ctx->ssl);
6208 }
6209
6210 ctx->xprt = xprt_get(XPRT_QUIC);
6211
6212 /* Store the allocated context in <qc>. */
6213 qc->xprt_ctx = ctx;
6214
6215 ret = 1;
6216 leave:
6217 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6218 return !ret;
6219
6220 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006221 pool_free(pool_head_quic_conn_ctx, ctx);
6222 goto leave;
6223}
6224
6225/* Check that all the bytes between <buf> included and <end> address
6226 * excluded are null. This is the responsibility of the caller to
6227 * check that there is at least one byte between <buf> end <end>.
6228 * Return 1 if this all the bytes are null, 0 if not.
6229 */
6230static inline int quic_padding_check(const unsigned char *buf,
6231 const unsigned char *end)
6232{
6233 while (buf < end && !*buf)
6234 buf++;
6235
6236 return buf == end;
6237}
6238
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006239/* Find the associated connection to the packet <pkt> or create a new one if
6240 * this is an Initial packet. <dgram> is the datagram containing the packet and
6241 * <l> is the listener instance on which it was received.
6242 *
6243 * Returns the quic-conn instance or NULL.
6244 */
6245static struct quic_conn *quic_rx_pkt_retrieve_conn(struct quic_rx_packet *pkt,
6246 struct quic_dgram *dgram,
6247 struct listener *l)
6248{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006249 struct quic_cid token_odcid = { .len = 0 };
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006250 struct quic_conn *qc = NULL;
6251 struct proxy *prx;
6252 struct quic_counters *prx_counters;
6253
6254 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6255
6256 prx = l->bind_conf->frontend;
6257 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6258
6259 qc = retrieve_qc_conn_from_cid(pkt, l, &dgram->saddr);
6260
6261 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6262 BUG_ON(!pkt->version); /* This must not happen. */
6263
6264 if (global.cluster_secret && pkt->token_len) {
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006265 if (!quic_retry_token_check(pkt, dgram, l, qc, &token_odcid))
6266 goto err;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006267 }
6268
6269 if (!qc) {
6270 int ipv4;
6271
6272 if (global.cluster_secret && !pkt->token_len && !(l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) &&
6273 HA_ATOMIC_LOAD(&prx_counters->half_open_conn) >= global.tune.quic_retry_threshold) {
6274 TRACE_PROTO("Initial without token, sending retry",
6275 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6276 if (send_retry(l->rx.fd, &dgram->saddr, pkt, pkt->version)) {
6277 TRACE_ERROR("Error during Retry generation",
6278 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6279 goto out;
6280 }
6281
6282 HA_ATOMIC_INC(&prx_counters->retry_sent);
6283 goto out;
6284 }
6285
6286 /* RFC 9000 7.2. Negotiating Connection IDs:
6287 * When an Initial packet is sent by a client that has not previously
6288 * received an Initial or Retry packet from the server, the client
6289 * populates the Destination Connection ID field with an unpredictable
6290 * value. This Destination Connection ID MUST be at least 8 bytes in length.
6291 */
6292 if (pkt->dcid.len < QUIC_ODCID_MINLEN) {
6293 TRACE_PROTO("dropped packet",
6294 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6295 goto err;
6296 }
6297
6298 pkt->saddr = dgram->saddr;
6299 ipv4 = dgram->saddr.ss_family == AF_INET;
6300
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006301 qc = qc_new_conn(pkt->version, ipv4, &pkt->dcid, &pkt->scid, &token_odcid,
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006302 &dgram->daddr, &pkt->saddr, 1,
6303 !!pkt->token_len, l);
6304 if (qc == NULL)
6305 goto err;
6306
6307 HA_ATOMIC_INC(&prx_counters->half_open_conn);
6308 /* Insert the DCID the QUIC client has chosen (only for listeners) */
6309 ebmb_insert(&quic_dghdlrs[tid].odcids, &qc->odcid_node,
6310 qc->odcid.len + qc->odcid.addrlen);
6311 }
6312 }
6313 else if (!qc) {
6314 TRACE_PROTO("No connection on a non Initial packet", QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6315 if (global.cluster_secret && !send_stateless_reset(l, &dgram->saddr, pkt))
6316 TRACE_ERROR("stateless reset not sent", QUIC_EV_CONN_LPKT, qc);
6317 goto err;
6318 }
6319
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006320 out:
6321 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6322 return qc;
6323
6324 err:
6325 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
6326 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
6327 return NULL;
6328}
6329
Amaury Denoyelle98289692022-10-19 15:37:44 +02006330/* Parse a QUIC packet starting at <buf>. Data won't be read after <end> even
6331 * if the packet is incomplete. This function will populate fields of <pkt>
6332 * instance, most notably its length. <dgram> is the UDP datagram which
6333 * contains the parsed packet. <l> is the listener instance on which it was
6334 * received.
6335 *
6336 * Returns 0 on success else non-zero. Packet length is guaranteed to be set to
6337 * the real packet value or to cover all data between <buf> and <end> : this is
6338 * useful to reject a whole datagram.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006339 */
Amaury Denoyelle98289692022-10-19 15:37:44 +02006340static int quic_rx_pkt_parse(struct quic_rx_packet *pkt,
6341 unsigned char *buf, const unsigned char *end,
6342 struct quic_dgram *dgram, struct listener *l)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006343{
Amaury Denoyelle98289692022-10-19 15:37:44 +02006344 const unsigned char *beg = buf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006345 struct proxy *prx;
6346 struct quic_counters *prx_counters;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006347 int long_header = 0;
Willy Tarreau33a68702022-11-24 09:16:41 +01006348 uint32_t version = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006349 const struct quic_version *qv = NULL;
6350
6351 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6352
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006353 prx = l->bind_conf->frontend;
6354 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6355 /* This ist only to please to traces and distinguish the
6356 * packet with parsed packet number from others.
6357 */
6358 pkt->pn_node.key = (uint64_t)-1;
6359 if (end <= buf) {
6360 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6361 goto drop;
6362 }
6363
6364 /* Fixed bit */
6365 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006366 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
6367 quic_padding_check(buf, end)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006368 /* Some browsers may pad the remaining datagram space with null bytes.
6369 * That is what we called add padding out of QUIC packets. Such
6370 * datagrams must be considered as valid. But we can only consume
6371 * the remaining space.
6372 */
6373 pkt->len = end - buf;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006374 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006375 }
6376
6377 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6378 goto drop;
6379 }
6380
6381 /* Header form */
6382 if (!qc_parse_hd_form(pkt, &buf, end, &long_header, &version)) {
6383 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6384 goto drop;
6385 }
6386
6387 if (long_header) {
6388 uint64_t len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006389
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006390 TRACE_PROTO("long header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006391 if (!quic_packet_read_long_header(&buf, end, pkt)) {
6392 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6393 goto drop;
6394 }
6395
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006396 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6397 * they must have the same DCID.
6398 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006399 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006400 (pkt->dcid.len != dgram->dcid_len ||
6401 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006402 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006403 goto drop;
6404 }
6405
6406 /* Retry of Version Negotiation packets are only sent by servers */
6407 if (pkt->type == QUIC_PACKET_TYPE_RETRY || !version) {
6408 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6409 goto drop;
6410 }
6411
6412 /* RFC9000 6. Version Negotiation */
6413 qv = qc_supported_version(version);
6414 if (!qv) {
6415 /* unsupported version, send Negotiation packet */
6416 if (send_version_negotiation(l->rx.fd, &dgram->saddr, pkt)) {
6417 TRACE_ERROR("VN packet not sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006418 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006419 }
6420
6421 TRACE_PROTO("VN packet sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006422 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006423 }
Amaury Denoyelle0eae5722022-10-17 18:05:18 +02006424 pkt->version = qv;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006425
6426 /* For Initial packets, and for servers (QUIC clients connections),
6427 * there is no Initial connection IDs storage.
6428 */
6429 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6430 uint64_t token_len;
6431
6432 if (!quic_dec_int(&token_len, (const unsigned char **)&buf, end) ||
6433 end - buf < token_len) {
6434 TRACE_PROTO("Packet dropped",
6435 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6436 goto drop;
6437 }
6438
6439 /* TODO Retry should be automatically activated if
6440 * suspect network usage is detected.
6441 */
6442 if (global.cluster_secret && !token_len) {
6443 if (l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) {
6444 TRACE_PROTO("Initial without token, sending retry",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006445 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006446 if (send_retry(l->rx.fd, &dgram->saddr, pkt, qv)) {
6447 TRACE_PROTO("Error during Retry generation",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006448 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006449 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006450 }
6451
6452 HA_ATOMIC_INC(&prx_counters->retry_sent);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006453 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006454 }
6455 }
6456 else if (!global.cluster_secret && token_len) {
6457 /* Impossible case: a token was received without configured
6458 * cluster secret.
6459 */
6460 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT,
6461 NULL, NULL, NULL, qv);
6462 goto drop;
6463 }
6464
6465 pkt->token = buf;
6466 pkt->token_len = token_len;
6467 buf += pkt->token_len;
6468 }
6469 else if (pkt->type != QUIC_PACKET_TYPE_0RTT) {
6470 if (pkt->dcid.len != QUIC_HAP_CID_LEN) {
6471 TRACE_PROTO("Packet dropped",
6472 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6473 goto drop;
6474 }
6475 }
6476
6477 if (!quic_dec_int(&len, (const unsigned char **)&buf, end) ||
6478 end - buf < len) {
6479 TRACE_PROTO("Packet dropped",
6480 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6481 goto drop;
6482 }
6483
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006484 /* Packet Number is stored here. Packet Length totalizes the
6485 * rest of the content.
6486 */
6487 pkt->pn_offset = buf - beg;
6488 pkt->len = pkt->pn_offset + len;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006489
Frédéric Lécaille35218c62023-02-16 11:40:11 +01006490 /* RFC 9000. Initial Datagram Size
6491 *
6492 * A server MUST discard an Initial packet that is carried in a UDP datagram
6493 * with a payload that is smaller than the smallest allowed maximum datagram
6494 * size of 1200 bytes.
6495 */
6496 if (pkt->type == QUIC_PACKET_TYPE_INITIAL &&
6497 dgram->len < QUIC_INITIAL_PACKET_MINLEN) {
6498 TRACE_PROTO("Too short datagram with an Initial packet", QUIC_EV_CONN_LPKT);
6499 HA_ATOMIC_INC(&prx_counters->too_short_initial_dgram);
6500 goto drop;
6501 }
6502
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006503 /* Interrupt parsing after packet length retrieval : this
6504 * ensures that only the packet is dropped but not the whole
6505 * datagram.
6506 */
6507 if (pkt->type == QUIC_PACKET_TYPE_0RTT && !l->bind_conf->ssl_conf.early_data) {
6508 TRACE_PROTO("0-RTT packet not supported", QUIC_EV_CONN_LPKT);
6509 goto drop;
6510 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006511 }
6512 else {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006513 TRACE_PROTO("short header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006514 if (end - buf < QUIC_HAP_CID_LEN) {
6515 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6516 goto drop;
6517 }
6518
6519 memcpy(pkt->dcid.data, buf, QUIC_HAP_CID_LEN);
6520 pkt->dcid.len = QUIC_HAP_CID_LEN;
6521
6522 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6523 * they must have the same DCID.
6524 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006525 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006526 (pkt->dcid.len != dgram->dcid_len ||
6527 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006528 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006529 goto drop;
6530 }
6531
6532 buf += QUIC_HAP_CID_LEN;
6533
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006534 pkt->pn_offset = buf - beg;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006535 /* A short packet is the last one of a UDP datagram. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006536 pkt->len = end - beg;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006537 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006538
Amaury Denoyelle98289692022-10-19 15:37:44 +02006539 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6540 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006541
Amaury Denoyelle98289692022-10-19 15:37:44 +02006542 drop:
6543 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006544 drop_silent:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006545 if (!pkt->len)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006546 pkt->len = end - beg;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006547 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6548 return -1;
6549}
6550
6551/* Check if received packet <pkt> should be drop due to <qc> already in closing
6552 * state. This can be true if a CONNECTION_CLOSE has already been emitted for
6553 * this connection.
6554 *
6555 * Returns false if connection is not in closing state else true. The caller
6556 * should drop the whole datagram in the last case to not mess up <qc>
6557 * CONNECTION_CLOSE rate limit counter.
6558 */
6559static int qc_rx_check_closing(struct quic_conn *qc,
6560 struct quic_rx_packet *pkt)
6561{
6562 if (!(qc->flags & QUIC_FL_CONN_CLOSING))
6563 return 0;
6564
6565 TRACE_STATE("Closing state connection", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6566
6567 /* Check if CONNECTION_CLOSE rate reemission is reached. */
6568 if (++qc->nb_pkt_since_cc >= qc->nb_pkt_for_cc) {
6569 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
6570 qc->nb_pkt_for_cc++;
6571 qc->nb_pkt_since_cc = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006572 }
6573
Amaury Denoyelle98289692022-10-19 15:37:44 +02006574 return 1;
6575}
6576
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006577/* React to a connection migration initiated on <qc> by a client with the new
6578 * path addresses <peer_addr>/<local_addr>.
6579 *
6580 * Returns 0 on success else non-zero.
6581 */
6582static int qc_handle_conn_migration(struct quic_conn *qc,
6583 const struct sockaddr_storage *peer_addr,
6584 const struct sockaddr_storage *local_addr)
6585{
6586 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6587
Frédéric Lécaille6fc86972023-01-12 08:29:23 +01006588 /* RFC 9000. Connection Migration
6589 *
6590 * If the peer sent the disable_active_migration transport parameter,
6591 * an endpoint also MUST NOT send packets (including probing packets;
6592 * see Section 9.1) from a different local address to the address the peer
6593 * used during the handshake, unless the endpoint has acted on a
6594 * preferred_address transport parameter from the peer.
6595 */
6596 if (qc->li->bind_conf->quic_params.disable_active_migration) {
6597 TRACE_ERROR("Active migration was disabled, datagram dropped", QUIC_EV_CONN_LPKT, qc);
6598 goto err;
6599 }
6600
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006601 /* RFC 9000 9. Connection Migration
6602 *
Amaury Denoyelleeb6be982022-11-21 11:14:45 +01006603 * The design of QUIC relies on endpoints retaining a stable address for
6604 * the duration of the handshake. An endpoint MUST NOT initiate
6605 * connection migration before the handshake is confirmed, as defined in
6606 * Section 4.1.2 of [QUIC-TLS].
6607 */
6608 if (qc->state < QUIC_HS_ST_COMPLETE) {
6609 TRACE_STATE("Connection migration during handshake rejected", QUIC_EV_CONN_LPKT, qc);
6610 goto err;
6611 }
6612
6613 /* RFC 9000 9. Connection Migration
6614 *
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006615 * TODO
6616 * An endpoint MUST
6617 * perform path validation (Section 8.2) if it detects any change to a
6618 * peer's address, unless it has previously validated that address.
6619 */
6620
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006621 /* Update quic-conn owned socket if in used.
6622 * TODO try to reuse it instead of closing and opening a new one.
6623 */
6624 if (qc_test_fd(qc)) {
6625 /* TODO try to reuse socket instead of closing it and opening a new one. */
6626 TRACE_STATE("Connection migration detected, allocate a new connection socket", QUIC_EV_CONN_LPKT, qc);
6627 qc_release_fd(qc, 1);
Amaury Denoyellefb375572023-02-01 09:28:32 +01006628 /* TODO need to adjust <jobs> on socket allocation failure. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006629 qc_alloc_fd(qc, local_addr, peer_addr);
6630 }
6631
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006632 qc->local_addr = *local_addr;
6633 qc->peer_addr = *peer_addr;
6634 HA_ATOMIC_INC(&qc->prx_counters->conn_migration_done);
6635
6636 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6637 return 0;
6638
6639 err:
6640 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6641 return 1;
6642}
6643
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006644/* Release the memory for the RX packets which are no more referenced
6645 * and consume their payloads which have been copied to the RX buffer
6646 * for the connection.
6647 * Always succeeds.
6648 */
6649static inline void quic_rx_pkts_del(struct quic_conn *qc)
6650{
6651 struct quic_rx_packet *pkt, *pktback;
6652
6653 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
6654 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006655 "pkt #%lld(type=%d,len=%llu,rawlen=%llu,refcnt=%u) (diff: %zd)",
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006656 (long long)pkt->pn_node.key,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006657 pkt->type, (ull)pkt->len, (ull)pkt->raw_len, pkt->refcnt,
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006658 (unsigned char *)b_head(&qc->rx.buf) - pkt->data);
6659 if (pkt->data != (unsigned char *)b_head(&qc->rx.buf)) {
6660 size_t cdata;
6661
6662 cdata = b_contig_data(&qc->rx.buf, 0);
6663 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006664 "cdata=%llu *b_head()=0x%x", (ull)cdata, *b_head(&qc->rx.buf));
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006665 if (cdata && !*b_head(&qc->rx.buf)) {
6666 /* Consume the remaining data */
6667 b_del(&qc->rx.buf, cdata);
6668 }
6669 break;
6670 }
6671
6672 if (pkt->refcnt)
6673 break;
6674
6675 b_del(&qc->rx.buf, pkt->raw_len);
6676 LIST_DELETE(&pkt->qc_rx_pkt_list);
6677 pool_free(pool_head_quic_rx_packet, pkt);
6678 }
6679
6680 /* In frequent cases the buffer will be emptied at this stage. */
6681 b_realign_if_empty(&qc->rx.buf);
6682}
6683
Amaury Denoyelle98289692022-10-19 15:37:44 +02006684/* Handle a parsed packet <pkt> by the connection <qc>. Data will be copied
6685 * into <qc> receive buffer after header protection removal procedure.
6686 *
6687 * <dgram> must be set to the datagram which contains the QUIC packet. <beg>
6688 * must point to packet buffer first byte.
6689 *
6690 * <tasklist_head> may be non-NULL when the caller treat several datagrams for
6691 * different quic-conn. In this case, each quic-conn tasklet will be appended
6692 * to it in order to be woken up after the current task.
6693 *
6694 * The caller can safely removed the packet data. If packet refcount was not
6695 * incremented by this function, it means that the connection did not handled
6696 * it and it should be freed by the caller.
6697 */
6698static void qc_rx_pkt_handle(struct quic_conn *qc, struct quic_rx_packet *pkt,
6699 struct quic_dgram *dgram, unsigned char *beg,
6700 struct list **tasklist_head)
6701{
6702 const struct quic_version *qv = pkt->version;
6703 struct quic_enc_level *qel = NULL;
6704 size_t b_cspace;
Frédéric Lécaille8f7d2242023-02-15 11:55:21 +01006705 int io_cb_wakeup = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006706
Amaury Denoyelle3f474e62022-11-24 17:15:08 +01006707 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6708
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006709 if (pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST &&
6710 !quic_peer_validated_addr(qc) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006711 qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED) {
6712 TRACE_PROTO("PTO timer must be armed after anti-amplication was reached",
6713 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6714 /* Reset the anti-amplification bit. It will be set again
6715 * when sending the next packet if reached again.
6716 */
6717 qc->flags &= ~QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006718 io_cb_wakeup = 1;
6719 }
6720
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006721 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
6722 TRACE_PROTO("Connection error",
6723 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6724 goto out;
6725 }
6726
6727 pkt->raw_len = pkt->len;
6728 quic_rx_pkts_del(qc);
6729 b_cspace = b_contig_space(&qc->rx.buf);
6730 if (b_cspace < pkt->len) {
Frédéric Lécaille1dbeb352023-02-07 11:40:21 +01006731 TRACE_PRINTF(TRACE_LEVEL_DEVELOPER, QUIC_EV_CONN_LPKT, qc, 0, 0, 0,
Frédéric Lécailleb7a13be2023-02-22 17:24:23 +01006732 "bspace=%llu pkt->len=%llu", (ull)b_cspace, (ull)pkt->len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006733 /* Do not consume buf if space not at the end. */
6734 if (b_tail(&qc->rx.buf) + b_cspace < b_wrap(&qc->rx.buf)) {
6735 TRACE_PROTO("Packet dropped",
6736 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006737 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006738 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006739 }
6740
6741 /* Let us consume the remaining contiguous space. */
6742 if (b_cspace) {
6743 b_putchr(&qc->rx.buf, 0x00);
6744 b_cspace--;
6745 }
6746 b_add(&qc->rx.buf, b_cspace);
6747 if (b_contig_space(&qc->rx.buf) < pkt->len) {
6748 TRACE_PROTO("Too big packet",
6749 QUIC_EV_CONN_LPKT, qc, pkt, &pkt->len, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006750 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006751 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006752 }
6753 }
6754
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006755 if (!qc_try_rm_hp(qc, pkt, beg, &qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006756 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6757 goto drop;
6758 }
6759
6760 TRACE_DATA("New packet", QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6761 if (pkt->aad_len)
6762 qc_pkt_insert(qc, pkt, qel);
6763 out:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006764 *tasklist_head = tasklet_wakeup_after(*tasklist_head,
6765 qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006766
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006767 drop_silent:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006768 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006769 return;
6770
6771 drop:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006772 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt);
Frédéric Lécaille75c8ad52023-02-08 16:08:28 +01006773 if (io_cb_wakeup) {
6774 TRACE_DEVEL("needs to wakeup the timer task after the amplification limit was reached",
6775 QUIC_EV_CONN_LPKT, qc);
6776 qc_set_timer(qc);
6777 if (qc->timer_task && tick_isset(qc->timer) && tick_is_lt(qc->timer, now_ms))
6778 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
6779 }
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006780
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006781 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
6782}
6783
6784/* This function builds into <buf> buffer a QUIC long packet header.
6785 * Return 1 if enough room to build this header, 0 if not.
6786 */
6787static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
6788 int type, size_t pn_len,
6789 struct quic_conn *qc, const struct quic_version *ver)
6790{
6791 int ret = 0;
6792
6793 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6794
6795 if (end - *buf < sizeof ver->num + qc->dcid.len + qc->scid.len + 3) {
6796 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6797 goto leave;
6798 }
6799
6800 type = quic_pkt_type(type, ver->num);
6801 /* #0 byte flags */
6802 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
6803 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
6804 /* Version */
6805 quic_write_uint32(buf, end, ver->num);
6806 *(*buf)++ = qc->dcid.len;
6807 /* Destination connection ID */
6808 if (qc->dcid.len) {
6809 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6810 *buf += qc->dcid.len;
6811 }
6812 /* Source connection ID */
6813 *(*buf)++ = qc->scid.len;
6814 if (qc->scid.len) {
6815 memcpy(*buf, qc->scid.data, qc->scid.len);
6816 *buf += qc->scid.len;
6817 }
6818
6819 ret = 1;
6820 leave:
6821 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6822 return ret;
6823}
6824
6825/* This function builds into <buf> buffer a QUIC short packet header.
6826 * Return 1 if enough room to build this header, 0 if not.
6827 */
6828static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
6829 size_t pn_len, struct quic_conn *qc,
6830 unsigned char tls_flags)
6831{
6832 int ret = 0;
6833
6834 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6835
6836 if (end - *buf < 1 + qc->dcid.len) {
6837 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6838 goto leave;
6839 }
6840
6841 /* #0 byte flags */
6842 *(*buf)++ = QUIC_PACKET_FIXED_BIT |
6843 ((tls_flags & QUIC_FL_TLS_KP_BIT_SET) ? QUIC_PACKET_KEY_PHASE_BIT : 0) | (pn_len - 1);
6844 /* Destination connection ID */
6845 if (qc->dcid.len) {
6846 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6847 *buf += qc->dcid.len;
6848 }
6849
6850 ret = 1;
6851 leave:
6852 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6853 return ret;
6854}
6855
6856/* Apply QUIC header protection to the packet with <buf> as first byte address,
6857 * <pn> as address of the Packet number field, <pnlen> being this field length
6858 * with <aead> as AEAD cipher and <key> as secret key.
6859 * Returns 1 if succeeded or 0 if failed.
6860 */
6861static int quic_apply_header_protection(struct quic_conn *qc, unsigned char *buf,
6862 unsigned char *pn, size_t pnlen,
6863 struct quic_tls_ctx *tls_ctx)
6864
6865{
6866 int i, ret = 0;
6867 /* We need an IV of at least 5 bytes: one byte for bytes #0
6868 * and at most 4 bytes for the packet number
6869 */
6870 unsigned char mask[5] = {0};
6871 EVP_CIPHER_CTX *aes_ctx = tls_ctx->tx.hp_ctx;
6872
6873 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6874
6875 if (!quic_tls_aes_encrypt(mask, pn + QUIC_PACKET_PN_MAXLEN, sizeof mask, aes_ctx)) {
6876 TRACE_ERROR("could not apply header protection", QUIC_EV_CONN_TXPKT, qc);
6877 goto out;
6878 }
6879
6880 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
6881 for (i = 0; i < pnlen; i++)
6882 pn[i] ^= mask[i + 1];
6883
6884 ret = 1;
6885 out:
6886 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6887 return ret;
6888}
6889
6890/* Reduce the encoded size of <ack_frm> ACK frame removing the last
6891 * ACK ranges if needed to a value below <limit> in bytes.
6892 * Return 1 if succeeded, 0 if not.
6893 */
6894static int quic_ack_frm_reduce_sz(struct quic_conn *qc,
6895 struct quic_frame *ack_frm, size_t limit)
6896{
6897 size_t room, ack_delay_sz;
6898 int ret = 0;
6899
6900 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6901
6902 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
6903 /* A frame is made of 1 byte for the frame type. */
6904 room = limit - ack_delay_sz - 1;
6905 if (!quic_rm_last_ack_ranges(qc, ack_frm->tx_ack.arngs, room))
6906 goto leave;
6907
6908 ret = 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
6909 leave:
6910 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6911 return ret;
6912}
6913
6914/* Prepare into <outlist> as most as possible ack-eliciting frame from their
6915 * <inlist> prebuilt frames for <qel> encryption level to be encoded in a buffer
6916 * with <room> as available room, and <*len> the packet Length field initialized
6917 * with the number of bytes already present in this buffer which must be taken
6918 * into an account for the Length packet field value. <headlen> is the number of
6919 * bytes already present in this packet before building frames.
6920 *
6921 * Update consequently <*len> to reflect the size of these frames built
6922 * by this function. Also attach these frames to <l> frame list.
6923 * Return 1 if at least one ack-eleciting frame could be built, 0 if not.
6924 */
6925static inline int qc_build_frms(struct list *outlist, struct list *inlist,
6926 size_t room, size_t *len, size_t headlen,
6927 struct quic_enc_level *qel,
6928 struct quic_conn *qc)
6929{
6930 int ret;
6931 struct quic_frame *cf, *cfbak;
6932
6933 TRACE_ENTER(QUIC_EV_CONN_BCFRMS, qc);
6934
6935 ret = 0;
6936 if (*len > room)
6937 goto leave;
6938
6939 /* If we are not probing we must take into an account the congestion
6940 * control window.
6941 */
6942 if (!qel->pktns->tx.pto_probe) {
6943 size_t remain = quic_path_prep_data(qc->path);
6944
6945 if (headlen > remain)
6946 goto leave;
6947
6948 room = QUIC_MIN(room, remain - headlen);
6949 }
6950
6951 TRACE_PROTO("************** frames build (headlen)",
6952 QUIC_EV_CONN_BCFRMS, qc, &headlen);
6953
6954 /* NOTE: switch/case block inside a loop, a successful status must be
6955 * returned by this function only if at least one frame could be built
6956 * in the switch/case block.
6957 */
6958 list_for_each_entry_safe(cf, cfbak, inlist, list) {
6959 /* header length, data length, frame length. */
6960 size_t hlen, dlen, dlen_sz, avail_room, flen;
6961
6962 if (!room)
6963 break;
6964
6965 switch (cf->type) {
6966 case QUIC_FT_CRYPTO:
6967 TRACE_DEVEL(" New CRYPTO frame build (room, len)",
6968 QUIC_EV_CONN_BCFRMS, qc, &room, len);
6969 /* Compute the length of this CRYPTO frame header */
6970 hlen = 1 + quic_int_getsize(cf->crypto.offset);
6971 /* Compute the data length of this CRyPTO frame. */
6972 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
6973 TRACE_DEVEL(" CRYPTO data length (hlen, crypto.len, dlen)",
6974 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->crypto.len, &dlen);
6975 if (!dlen)
6976 continue;
6977
6978 /* CRYPTO frame length. */
6979 flen = hlen + quic_int_getsize(dlen) + dlen;
6980 TRACE_DEVEL(" CRYPTO frame length (flen)",
6981 QUIC_EV_CONN_BCFRMS, qc, &flen);
6982 /* Add the CRYPTO data length and its encoded length to the packet
6983 * length and the length of this length.
6984 */
6985 *len += flen;
6986 room -= flen;
6987 if (dlen == cf->crypto.len) {
6988 /* <cf> CRYPTO data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01006989 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006990 LIST_APPEND(outlist, &cf->list);
6991 }
6992 else {
6993 struct quic_frame *new_cf;
6994
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01006995 new_cf = qc_frm_alloc(QUIC_FT_CRYPTO);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006996 if (!new_cf) {
6997 TRACE_ERROR("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, qc);
6998 continue;
6999 }
7000
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007001 new_cf->crypto.len = dlen;
7002 new_cf->crypto.offset = cf->crypto.offset;
7003 new_cf->crypto.qel = qel;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05007004 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007005 if (cf->origin) {
7006 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
7007 /* This <cf> frame was duplicated */
7008 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
7009 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01007010 /* Detach the remaining CRYPTO frame from its original frame */
7011 LIST_DEL_INIT(&cf->ref);
7012 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007013 }
7014 LIST_APPEND(outlist, &new_cf->list);
7015 /* Consume <dlen> bytes of the current frame. */
7016 cf->crypto.len -= dlen;
7017 cf->crypto.offset += dlen;
7018 }
7019 break;
7020
7021 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01007022 if (cf->stream.dup) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007023 struct eb64_node *node = NULL;
7024 struct qc_stream_desc *stream_desc = NULL;
7025 struct quic_stream *strm = &cf->stream;
7026
7027 /* As this frame has been already lost, ensure the stream is always
7028 * available or the range of this frame is not consumed before
7029 * resending it.
7030 */
7031 node = eb64_lookup(&qc->streams_by_id, strm->id);
7032 if (!node) {
7033 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007034 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007035 continue;
7036 }
7037
7038 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
7039 if (strm->offset.key + strm->len <= stream_desc->ack_offset) {
7040 TRACE_DEVEL("ignored frame frame in already acked range",
7041 QUIC_EV_CONN_PRSAFRM, qc, cf);
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007042 qc_frm_free(&cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007043 continue;
7044 }
7045 else if (strm->offset.key < stream_desc->ack_offset) {
7046 strm->offset.key = stream_desc->ack_offset;
7047 TRACE_DEVEL("updated partially acked frame",
7048 QUIC_EV_CONN_PRSAFRM, qc, cf);
7049 }
7050 }
7051 /* Note that these frames are accepted in short packets only without
7052 * "Length" packet field. Here, <*len> is used only to compute the
7053 * sum of the lengths of the already built frames for this packet.
7054 *
7055 * Compute the length of this STREAM frame "header" made a all the field
7056 * excepting the variable ones. Note that +1 is for the type of this frame.
7057 */
7058 hlen = 1 + quic_int_getsize(cf->stream.id) +
7059 ((cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT) ? quic_int_getsize(cf->stream.offset.key) : 0);
7060 /* Compute the data length of this STREAM frame. */
7061 avail_room = room - hlen - *len;
7062 if ((ssize_t)avail_room <= 0)
7063 continue;
7064
7065 TRACE_DEVEL(" New STREAM frame build (room, len)",
7066 QUIC_EV_CONN_BCFRMS, qc, &room, len);
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007067
7068 /* hlen contains STREAM id and offset. Ensure there is
7069 * enough room for length field.
7070 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007071 if (cf->type & QUIC_STREAM_FRAME_TYPE_LEN_BIT) {
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007072 dlen = QUIC_MIN((uint64_t)max_available_room(avail_room, &dlen_sz),
7073 cf->stream.len);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007074 dlen_sz = quic_int_getsize(dlen);
7075 flen = hlen + dlen_sz + dlen;
7076 }
7077 else {
7078 dlen = QUIC_MIN((uint64_t)avail_room, cf->stream.len);
7079 flen = hlen + dlen;
7080 }
Amaury Denoyellef2f08f82023-02-03 18:39:06 +01007081
7082 if (cf->stream.len && !dlen) {
7083 /* Only a small gap is left on buffer, not
7084 * enough to encode the STREAM data length.
7085 */
7086 continue;
7087 }
7088
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007089 TRACE_DEVEL(" STREAM data length (hlen, stream.len, dlen)",
7090 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->stream.len, &dlen);
7091 TRACE_DEVEL(" STREAM frame length (flen)",
7092 QUIC_EV_CONN_BCFRMS, qc, &flen);
7093 /* Add the STREAM data length and its encoded length to the packet
7094 * length and the length of this length.
7095 */
7096 *len += flen;
7097 room -= flen;
7098 if (dlen == cf->stream.len) {
7099 /* <cf> STREAM data have been consumed. */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007100 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007101 LIST_APPEND(outlist, &cf->list);
7102
7103 /* Do not notify MUX on retransmission. */
7104 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7105 qcc_streams_sent_done(cf->stream.stream->ctx,
7106 cf->stream.len,
7107 cf->stream.offset.key);
7108 }
7109 }
7110 else {
7111 struct quic_frame *new_cf;
7112 struct buffer cf_buf;
7113
Amaury Denoyelle40c24f12023-01-27 17:47:49 +01007114 new_cf = qc_frm_alloc(cf->type);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007115 if (!new_cf) {
7116 TRACE_ERROR("No memory for new STREAM frame", QUIC_EV_CONN_BCFRMS, qc);
7117 continue;
7118 }
7119
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007120 new_cf->stream.stream = cf->stream.stream;
7121 new_cf->stream.buf = cf->stream.buf;
7122 new_cf->stream.id = cf->stream.id;
Amaury Denoyelle1dac0182023-02-02 16:45:07 +01007123 new_cf->stream.offset = cf->stream.offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007124 new_cf->stream.len = dlen;
7125 new_cf->type |= QUIC_STREAM_FRAME_TYPE_LEN_BIT;
7126 /* FIN bit reset */
7127 new_cf->type &= ~QUIC_STREAM_FRAME_TYPE_FIN_BIT;
7128 new_cf->stream.data = cf->stream.data;
Amaury Denoyellec8a0efb2023-02-22 10:44:27 +01007129 new_cf->stream.dup = cf->stream.dup;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05007130 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007131 if (cf->origin) {
7132 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
7133 /* This <cf> frame was duplicated */
7134 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
7135 new_cf->origin = cf->origin;
Frédéric Lécailledd419462023-01-26 15:07:39 +01007136 /* Detach this STREAM frame from its origin */
7137 LIST_DEL_INIT(&cf->ref);
7138 cf->origin = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007139 }
7140 LIST_APPEND(outlist, &new_cf->list);
7141 cf->type |= QUIC_STREAM_FRAME_TYPE_OFF_BIT;
7142 /* Consume <dlen> bytes of the current frame. */
7143 cf_buf = b_make(b_orig(cf->stream.buf),
7144 b_size(cf->stream.buf),
7145 (char *)cf->stream.data - b_orig(cf->stream.buf), 0);
7146 cf->stream.len -= dlen;
7147 cf->stream.offset.key += dlen;
7148 cf->stream.data = (unsigned char *)b_peek(&cf_buf, dlen);
7149
7150 /* Do not notify MUX on retransmission. */
7151 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
7152 qcc_streams_sent_done(new_cf->stream.stream->ctx,
7153 new_cf->stream.len,
7154 new_cf->stream.offset.key);
7155 }
7156 }
7157
7158 /* TODO the MUX is notified about the frame sending via
7159 * previous qcc_streams_sent_done call. However, the
7160 * sending can fail later, for example if the sendto
7161 * system call returns an error. As the MUX has been
7162 * notified, the transport layer is responsible to
7163 * bufferize and resent the announced data later.
7164 */
7165
7166 break;
7167
7168 default:
7169 flen = qc_frm_len(cf);
7170 BUG_ON(!flen);
7171 if (flen > room)
7172 continue;
7173
7174 *len += flen;
7175 room -= flen;
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007176 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007177 LIST_APPEND(outlist, &cf->list);
7178 break;
7179 }
7180
7181 /* Successful status as soon as a frame could be built */
7182 ret = 1;
7183 }
7184
7185 leave:
7186 TRACE_LEAVE(QUIC_EV_CONN_BCFRMS, qc);
7187 return ret;
7188}
7189
7190/* Generate a CONNECTION_CLOSE frame for <qc> on <qel> encryption level. <out>
7191 * is used as return parameter and should be zero'ed by the caller.
7192 */
7193static void qc_build_cc_frm(struct quic_conn *qc, struct quic_enc_level *qel,
7194 struct quic_frame *out)
7195{
7196 /* TODO improve CONNECTION_CLOSE on Initial/Handshake encryption levels
7197 *
7198 * A CONNECTION_CLOSE frame should be sent in several packets with
7199 * different encryption levels depending on the client context. This is
7200 * to ensure that the client can decrypt it. See RFC 9000 10.2.3 for
7201 * more details on how to implement it.
7202 */
7203 TRACE_ENTER(QUIC_EV_CONN_BFRM, qc);
7204
7205
7206 if (qc->err.app) {
7207 if (unlikely(qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
7208 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
7209 /* RFC 9000 10.2.3. Immediate Close during the Handshake
7210 *
7211 * Sending a CONNECTION_CLOSE of type 0x1d in an Initial or Handshake
7212 * packet could expose application state or be used to alter application
7213 * state. A CONNECTION_CLOSE of type 0x1d MUST be replaced by a
7214 * CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or
7215 * Handshake packets. Otherwise, information about the application
7216 * state might be revealed. Endpoints MUST clear the value of the
7217 * Reason Phrase field and SHOULD use the APPLICATION_ERROR code when
7218 * converting to a CONNECTION_CLOSE of type 0x1c.
7219 */
7220 out->type = QUIC_FT_CONNECTION_CLOSE;
7221 out->connection_close.error_code = QC_ERR_APPLICATION_ERROR;
7222 out->connection_close.reason_phrase_len = 0;
7223 }
7224 else {
7225 out->type = QUIC_FT_CONNECTION_CLOSE_APP;
7226 out->connection_close.error_code = qc->err.code;
7227 }
7228 }
7229 else {
7230 out->type = QUIC_FT_CONNECTION_CLOSE;
7231 out->connection_close.error_code = qc->err.code;
7232 }
7233 TRACE_LEAVE(QUIC_EV_CONN_BFRM, qc);
7234
7235}
7236
7237/* This function builds a clear packet from <pkt> information (its type)
7238 * into a buffer with <pos> as position pointer and <qel> as QUIC TLS encryption
7239 * level for <conn> QUIC connection and <qel> as QUIC TLS encryption level,
7240 * filling the buffer with as much frames as possible from <frms> list of
7241 * prebuilt frames.
7242 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
7243 * reserved so that to ensure there is enough room to build this AEAD TAG after
7244 * having returned from this function.
7245 * This function also updates the value of <buf_pn> pointer to point to the packet
7246 * number field in this packet. <pn_len> will also have the packet number
7247 * length as value.
7248 *
7249 * Return 1 if succeeded (enough room to buile this packet), O if not.
7250 */
7251static int qc_do_build_pkt(unsigned char *pos, const unsigned char *end,
7252 size_t dglen, struct quic_tx_packet *pkt,
7253 int64_t pn, size_t *pn_len, unsigned char **buf_pn,
7254 int force_ack, int padding, int cc, int probe,
7255 struct quic_enc_level *qel, struct quic_conn *qc,
7256 const struct quic_version *ver, struct list *frms)
7257{
7258 unsigned char *beg, *payload;
7259 size_t len, len_sz, len_frms, padding_len;
7260 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
7261 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
7262 struct quic_frame cc_frm = { };
7263 size_t ack_frm_len, head_len;
7264 int64_t rx_largest_acked_pn;
7265 int add_ping_frm;
7266 struct list frm_list = LIST_HEAD_INIT(frm_list);
7267 struct quic_frame *cf;
7268 int must_ack, ret = 0;
7269 int nb_aepkts_since_last_ack;
7270
7271 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7272
7273 /* Length field value with CRYPTO frames if present. */
7274 len_frms = 0;
7275 beg = pos;
7276 /* When not probing, and no immediate close is required, reduce the size of this
7277 * buffer to respect the congestion controller window.
7278 * This size will be limited if we have ack-eliciting frames to send from <frms>.
7279 */
7280 if (!probe && !LIST_ISEMPTY(frms) && !cc) {
7281 size_t path_room;
7282
7283 path_room = quic_path_prep_data(qc->path);
7284 if (end - beg > path_room)
7285 end = beg + path_room;
7286 }
7287
7288 /* Ensure there is enough room for the TLS encryption tag and a zero token
7289 * length field if any.
7290 */
7291 if (end - pos < QUIC_TLS_TAG_LEN +
7292 (pkt->type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0))
7293 goto no_room;
7294
7295 end -= QUIC_TLS_TAG_LEN;
7296 rx_largest_acked_pn = qel->pktns->rx.largest_acked_pn;
7297 /* packet number length */
7298 *pn_len = quic_packet_number_length(pn, rx_largest_acked_pn);
7299 /* Build the header */
7300 if ((pkt->type == QUIC_PACKET_TYPE_SHORT &&
7301 !quic_build_packet_short_header(&pos, end, *pn_len, qc, qel->tls_ctx.flags)) ||
7302 (pkt->type != QUIC_PACKET_TYPE_SHORT &&
7303 !quic_build_packet_long_header(&pos, end, pkt->type, *pn_len, qc, ver)))
7304 goto no_room;
7305
7306 /* Encode the token length (0) for an Initial packet. */
7307 if (pkt->type == QUIC_PACKET_TYPE_INITIAL)
7308 *pos++ = 0;
7309 head_len = pos - beg;
7310 /* Build an ACK frame if required. */
7311 ack_frm_len = 0;
7312 nb_aepkts_since_last_ack = qel->pktns->rx.nb_aepkts_since_last_ack;
7313 must_ack = !qel->pktns->tx.pto_probe &&
7314 (force_ack || ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
7315 (LIST_ISEMPTY(frms) || nb_aepkts_since_last_ack >= QUIC_MAX_RX_AEPKTS_SINCE_LAST_ACK)));
7316 if (must_ack) {
7317 struct quic_arngs *arngs = &qel->pktns->rx.arngs;
7318 BUG_ON(eb_is_empty(&qel->pktns->rx.arngs.root));
7319 ack_frm.tx_ack.arngs = arngs;
7320 if (qel->pktns->flags & QUIC_FL_PKTNS_NEW_LARGEST_PN) {
7321 qel->pktns->tx.ack_delay =
7322 quic_compute_ack_delay_us(qel->pktns->rx.largest_time_received, qc);
7323 qel->pktns->flags &= ~QUIC_FL_PKTNS_NEW_LARGEST_PN;
7324 }
7325 ack_frm.tx_ack.ack_delay = qel->pktns->tx.ack_delay;
7326 /* XXX BE CAREFUL XXX : here we reserved at least one byte for the
7327 * smallest frame (PING) and <*pn_len> more for the packet number. Note
7328 * that from here, we do not know if we will have to send a PING frame.
7329 * This will be decided after having computed the ack-eliciting frames
7330 * to be added to this packet.
7331 */
7332 ack_frm_len = quic_ack_frm_reduce_sz(qc, &ack_frm, end - 1 - *pn_len - pos);
7333 if (!ack_frm_len)
7334 goto no_room;
7335 }
7336
7337 /* Length field value without the ack-eliciting frames. */
7338 len = ack_frm_len + *pn_len;
7339 len_frms = 0;
7340 if (!cc && !LIST_ISEMPTY(frms)) {
7341 ssize_t room = end - pos;
7342
7343 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7344 /* Initialize the length of the frames built below to <len>.
7345 * If any frame could be successfully built by qc_build_frms(),
7346 * we will have len_frms > len.
7347 */
7348 len_frms = len;
7349 if (!qc_build_frms(&frm_list, frms,
7350 end - pos, &len_frms, pos - beg, qel, qc)) {
7351 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7352 qc, NULL, NULL, &room);
7353 if (!ack_frm_len && !qel->pktns->tx.pto_probe)
7354 goto no_room;
7355 }
7356 }
7357
7358 /* Length (of the remaining data). Must not fail because, the buffer size
7359 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
7360 * for the encryption tag. It must be taken into an account for the length
7361 * of this packet.
7362 */
7363 if (len_frms)
7364 len = len_frms + QUIC_TLS_TAG_LEN;
7365 else
7366 len += QUIC_TLS_TAG_LEN;
7367 /* CONNECTION_CLOSE frame */
7368 if (cc) {
7369 qc_build_cc_frm(qc, qel, &cc_frm);
7370 len += qc_frm_len(&cc_frm);
7371 }
7372 add_ping_frm = 0;
7373 padding_len = 0;
7374 len_sz = quic_int_getsize(len);
7375 /* Add this packet size to <dglen> */
7376 dglen += head_len + len_sz + len;
7377 if (padding && dglen < QUIC_INITIAL_PACKET_MINLEN) {
7378 /* This is a maximum padding size */
7379 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7380 /* The length field value is of this packet is <len> + <padding_len>
7381 * the size of which may be greater than the initial computed size
7382 * <len_sz>. So, let's deduce the difference between these to packet
7383 * sizes from <padding_len>.
7384 */
7385 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7386 len += padding_len;
7387 }
Frédéric Lécaille5faf5772023-02-16 17:30:53 +01007388 else if (len_frms && len_frms < QUIC_PACKET_PN_MAXLEN) {
7389 len += padding_len = QUIC_PACKET_PN_MAXLEN - len_frms;
7390 }
7391 else if (LIST_ISEMPTY(&frm_list)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007392 if (qel->pktns->tx.pto_probe) {
7393 /* If we cannot send a frame, we send a PING frame. */
7394 add_ping_frm = 1;
7395 len += 1;
7396 }
7397 /* If there is no frame at all to follow, add at least a PADDING frame. */
7398 if (!ack_frm_len && !cc)
7399 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
7400 }
7401
7402 if (pkt->type != QUIC_PACKET_TYPE_SHORT && !quic_enc_int(&pos, end, len))
7403 goto no_room;
7404
7405 /* Packet number field address. */
7406 *buf_pn = pos;
7407
7408 /* Packet number encoding. */
7409 if (!quic_packet_number_encode(&pos, end, pn, *pn_len))
7410 goto no_room;
7411
7412 /* payload building (ack-eliciting or not frames) */
7413 payload = pos;
7414 if (ack_frm_len) {
7415 if (!qc_build_frm(&pos, end, &ack_frm, pkt, qc))
7416 goto no_room;
7417
7418 pkt->largest_acked_pn = quic_pktns_get_largest_acked_pn(qel->pktns);
7419 pkt->flags |= QUIC_FL_TX_PACKET_ACK;
7420 }
7421
7422 /* Ack-eliciting frames */
7423 if (!LIST_ISEMPTY(&frm_list)) {
7424 struct quic_frame *tmp_cf;
7425 list_for_each_entry_safe(cf, tmp_cf, &frm_list, list) {
7426 if (!qc_build_frm(&pos, end, cf, pkt, qc)) {
7427 ssize_t room = end - pos;
7428 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7429 qc, NULL, NULL, &room);
7430 /* Note that <cf> was added from <frms> to <frm_list> list by
7431 * qc_build_frms().
7432 */
Amaury Denoyelle57b3eaa2023-02-02 16:12:09 +01007433 LIST_DEL_INIT(&cf->list);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007434 LIST_INSERT(frms, &cf->list);
7435 continue;
7436 }
7437
7438 quic_tx_packet_refinc(pkt);
7439 cf->pkt = pkt;
7440 }
7441 }
7442
7443 /* Build a PING frame if needed. */
7444 if (add_ping_frm) {
7445 frm.type = QUIC_FT_PING;
7446 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7447 goto no_room;
7448 }
7449
7450 /* Build a CONNECTION_CLOSE frame if needed. */
7451 if (cc) {
7452 if (!qc_build_frm(&pos, end, &cc_frm, pkt, qc))
7453 goto no_room;
7454
7455 pkt->flags |= QUIC_FL_TX_PACKET_CC;
7456 }
7457
7458 /* Build a PADDING frame if needed. */
7459 if (padding_len) {
7460 frm.type = QUIC_FT_PADDING;
7461 frm.padding.len = padding_len;
7462 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7463 goto no_room;
7464 }
7465
7466 if (pos == payload) {
7467 /* No payload was built because of congestion control */
7468 TRACE_DEVEL("limited by congestion control", QUIC_EV_CONN_TXPKT, qc);
7469 goto no_room;
7470 }
7471
7472 /* If this packet is ack-eliciting and we are probing let's
7473 * decrement the PTO probe counter.
7474 */
7475 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING &&
7476 qel->pktns->tx.pto_probe)
7477 qel->pktns->tx.pto_probe--;
7478
7479 pkt->len = pos - beg;
7480 LIST_SPLICE(&pkt->frms, &frm_list);
7481
7482 ret = 1;
7483 TRACE_DEVEL("Packet ack-eliciting frames", QUIC_EV_CONN_TXPKT, qc, pkt);
7484 leave:
7485 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7486 return ret;
7487
7488 no_room:
7489 /* Replace the pre-built frames which could not be add to this packet */
7490 LIST_SPLICE(frms, &frm_list);
7491 TRACE_DEVEL("Remaining ack-eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7492 goto leave;
7493}
7494
7495static inline void quic_tx_packet_init(struct quic_tx_packet *pkt, int type)
7496{
7497 pkt->type = type;
7498 pkt->len = 0;
7499 pkt->in_flight_len = 0;
7500 pkt->pn_node.key = (uint64_t)-1;
7501 LIST_INIT(&pkt->frms);
7502 pkt->time_sent = TICK_ETERNITY;
7503 pkt->next = NULL;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01007504 pkt->prev = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007505 pkt->largest_acked_pn = -1;
7506 pkt->flags = 0;
7507 pkt->refcnt = 0;
7508}
7509
7510/* Build a packet into <buf> packet buffer with <pkt_type> as packet
7511 * type for <qc> QUIC connection from <qel> encryption level from <frms> list
7512 * of prebuilt frames.
7513 *
7514 * Return -2 if the packet could not be allocated or encrypted for any reason,
7515 * -1 if there was not enough room to build a packet.
7516 * XXX NOTE XXX
7517 * If you provide provide qc_build_pkt() with a big enough buffer to build a packet as big as
7518 * possible (to fill an MTU), the unique reason why this function may fail is the congestion
7519 * control window limitation.
7520 */
7521static struct quic_tx_packet *qc_build_pkt(unsigned char **pos,
7522 const unsigned char *buf_end,
7523 struct quic_enc_level *qel,
7524 struct quic_tls_ctx *tls_ctx, struct list *frms,
7525 struct quic_conn *qc, const struct quic_version *ver,
7526 size_t dglen, int pkt_type, int force_ack,
7527 int padding, int probe, int cc, int *err)
7528{
7529 struct quic_tx_packet *ret_pkt = NULL;
7530 /* The pointer to the packet number field. */
7531 unsigned char *buf_pn;
7532 unsigned char *beg, *end, *payload;
7533 int64_t pn;
7534 size_t pn_len, payload_len, aad_len;
7535 struct quic_tx_packet *pkt;
7536
7537 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc, NULL, qel);
7538 *err = 0;
7539 pkt = pool_alloc(pool_head_quic_tx_packet);
7540 if (!pkt) {
7541 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_TXPKT, qc);
7542 *err = -2;
7543 goto err;
7544 }
7545
7546 quic_tx_packet_init(pkt, pkt_type);
7547 beg = *pos;
7548 pn_len = 0;
7549 buf_pn = NULL;
7550
7551 pn = qel->pktns->tx.next_pn + 1;
7552 if (!qc_do_build_pkt(*pos, buf_end, dglen, pkt, pn, &pn_len, &buf_pn,
7553 force_ack, padding, cc, probe, qel, qc, ver, frms)) {
7554 // trace already emitted by function above
7555 *err = -1;
7556 goto err;
7557 }
7558
7559 end = beg + pkt->len;
7560 payload = buf_pn + pn_len;
7561 payload_len = end - payload;
7562 aad_len = payload - beg;
7563
7564 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc)) {
7565 // trace already emitted by function above
7566 *err = -2;
7567 goto err;
7568 }
7569
7570 end += QUIC_TLS_TAG_LEN;
7571 pkt->len += QUIC_TLS_TAG_LEN;
7572 if (!quic_apply_header_protection(qc, beg, buf_pn, pn_len, tls_ctx)) {
7573 // trace already emitted by function above
7574 *err = -2;
7575 goto err;
7576 }
7577
7578 /* Consume a packet number */
7579 qel->pktns->tx.next_pn++;
7580 qc->tx.prep_bytes += pkt->len;
7581 if (qc->tx.prep_bytes >= 3 * qc->rx.bytes && !quic_peer_validated_addr(qc)) {
7582 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
7583 TRACE_PROTO("anti-amplification limit reached", QUIC_EV_CONN_TXPKT, qc);
7584 }
7585 /* Now that a correct packet is built, let us consume <*pos> buffer. */
7586 *pos = end;
7587 /* Attach the built packet to its tree. */
7588 pkt->pn_node.key = pn;
7589 /* Set the packet in fligth length for in flight packet only. */
7590 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
7591 pkt->in_flight_len = pkt->len;
7592 qc->path->prep_in_flight += pkt->len;
7593 }
7594 /* Always reset this flags */
7595 qc->flags &= ~QUIC_FL_CONN_IMMEDIATE_CLOSE;
7596 if (pkt->flags & QUIC_FL_TX_PACKET_ACK) {
7597 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
7598 qel->pktns->rx.nb_aepkts_since_last_ack = 0;
7599 }
7600
7601 pkt->pktns = qel->pktns;
7602
7603 ret_pkt = pkt;
7604 leave:
7605 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc, ret_pkt);
7606 return ret_pkt;
7607
7608 err:
7609 /* TODO: what about the frames which have been built
7610 * for this packet.
7611 */
7612 free_quic_tx_packet(qc, pkt);
7613 goto leave;
7614}
7615
7616
7617static void __quic_conn_init(void)
7618{
7619 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
7620}
7621INITCALL0(STG_REGISTER, __quic_conn_init);
7622
7623static void __quic_conn_deinit(void)
7624{
7625 BIO_meth_free(ha_quic_meth);
7626}
7627REGISTER_POST_DEINIT(__quic_conn_deinit);
7628
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007629/* Handle a new <dgram> received. Parse each QUIC packets and copied their
7630 * content to a quic-conn instance. The datagram content can be released after
7631 * this function.
7632 *
7633 * If datagram has been received on a quic-conn owned FD, <from_qc> must be set
7634 * to the connection instance. <li> is the attached listener. The caller is
7635 * responsible to ensure that the first packet is destined to this connection
7636 * by comparing CIDs.
7637 *
7638 * If datagram has been received on a receiver FD, <from_qc> will be NULL. This
7639 * function will thus retrieve the connection from the CID tree or allocate a
7640 * new one if possible. <li> is the listener attached to the receiver.
7641 *
7642 * Returns 0 on success else non-zero. If an error happens, some packets from
7643 * the datagram may not have been parsed.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007644 */
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007645int quic_dgram_parse(struct quic_dgram *dgram, struct quic_conn *from_qc,
7646 struct listener *li)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007647{
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007648 struct quic_rx_packet *pkt;
7649 struct quic_conn *qc = NULL;
7650 unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007651 struct list *tasklist_head = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007652
7653 TRACE_ENTER(QUIC_EV_CONN_LPKT);
7654
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007655 pos = dgram->buf;
7656 end = pos + dgram->len;
7657 do {
7658 /* TODO replace zalloc -> alloc. */
7659 pkt = pool_zalloc(pool_head_quic_rx_packet);
7660 if (!pkt) {
7661 TRACE_ERROR("RX packet allocation failed", QUIC_EV_CONN_LPKT);
7662 goto err;
7663 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007664
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007665 pkt->version = NULL;
7666 pkt->pn_offset = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007667
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007668 /* Set flag if pkt is the first one in dgram. */
7669 if (pos == dgram->buf)
7670 pkt->flags |= QUIC_FL_RX_PACKET_DGRAM_FIRST;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007671
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007672 LIST_INIT(&pkt->qc_rx_pkt_list);
7673 pkt->time_received = now_ms;
7674 quic_rx_packet_refinc(pkt);
7675 if (quic_rx_pkt_parse(pkt, pos, end, dgram, li))
7676 goto next;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007677
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007678 /* Search quic-conn instance for first packet of the datagram.
7679 * quic_rx_packet_parse() is responsible to discard packets
7680 * with different DCID as the first one in the same datagram.
7681 */
7682 if (!qc) {
7683 qc = from_qc ? from_qc : quic_rx_pkt_retrieve_conn(pkt, dgram, li);
7684 /* qc is NULL if receiving a non Initial packet for an
7685 * unknown connection.
7686 */
7687 if (!qc) {
Amaury Denoyelle98289692022-10-19 15:37:44 +02007688 /* Skip the entire datagram. */
7689 pkt->len = end - pos;
7690 goto next;
7691 }
7692
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007693 dgram->qc = qc;
7694 }
Amaury Denoyelle98289692022-10-19 15:37:44 +02007695
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007696 if (qc_rx_check_closing(qc, pkt)) {
7697 /* Skip the entire datagram. */
7698 pkt->len = end - pos;
7699 goto next;
7700 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007701
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007702 /* Detect QUIC connection migration. */
Frédéric Lécaillef6769542023-01-12 10:36:26 +01007703 if (ipcmp(&qc->peer_addr, &dgram->saddr, 1)) {
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007704 if (qc_handle_conn_migration(qc, &dgram->saddr, &dgram->daddr)) {
7705 /* Skip the entire datagram. */
7706 TRACE_ERROR("error during connection migration, datagram dropped", QUIC_EV_CONN_LPKT, qc);
7707 pkt->len = end - pos;
7708 goto next;
7709 }
7710 }
7711
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007712 qc_rx_pkt_handle(qc, pkt, dgram, pos, &tasklist_head);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007713
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007714 next:
7715 pos += pkt->len;
7716 quic_rx_packet_refdec(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007717
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007718 /* Free rejected packets */
7719 if (!pkt->refcnt) {
7720 BUG_ON(LIST_INLIST(&pkt->qc_rx_pkt_list));
7721 pool_free(pool_head_quic_rx_packet, pkt);
7722 }
7723 } while (pos < end);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007724
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007725 /* Increasing the received bytes counter by the UDP datagram length
7726 * if this datagram could be associated to a connection.
7727 */
7728 if (dgram->qc)
7729 dgram->qc->rx.bytes += dgram->len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007730
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007731 /* This must never happen. */
7732 BUG_ON(pos > end);
7733 BUG_ON(pos < end || pos > dgram->buf + dgram->len);
7734 /* Mark this datagram as consumed */
7735 HA_ATOMIC_STORE(&dgram->buf, NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007736
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007737 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
7738 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007739
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007740 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007741 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007742 return -1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007743}
7744
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01007745/* Check if connection ID <dcid> of length <dcid_len> belongs to <qc> local
7746 * CIDs. This can be used to determine if a datagram is addressed to the right
7747 * connection instance.
7748 *
7749 * Returns a boolean value.
7750 */
7751int qc_check_dcid(struct quic_conn *qc, unsigned char *dcid, size_t dcid_len)
7752{
7753 struct ebmb_node *node;
7754 struct quic_connection_id *id;
7755
7756 /* For ODCID, address is concatenated to it after qc.odcid.len so this
7757 * comparison is safe.
7758 */
7759 if ((qc->scid.len == dcid_len &&
7760 memcmp(qc->scid.data, dcid, dcid_len) == 0) ||
7761 (qc->odcid.len == dcid_len &&
Frédéric Lécaille07846cb2023-02-13 16:14:24 +01007762 memcmp(qc->odcid.data, dcid, dcid_len) == 0)) {
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01007763 return 1;
7764 }
7765
7766 node = ebmb_lookup(&quic_dghdlrs[tid].cids, dcid, dcid_len);
7767 if (node) {
7768 id = ebmb_entry(node, struct quic_connection_id, node);
7769 if (qc == id->qc)
7770 return 1;
7771 }
7772
7773 return 0;
7774}
7775
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007776/* Retrieve the DCID from a QUIC datagram or packet with <buf> as first octet.
7777 * Returns 1 if succeeded, 0 if not.
7778 */
7779int quic_get_dgram_dcid(unsigned char *buf, const unsigned char *end,
7780 unsigned char **dcid, size_t *dcid_len)
7781{
7782 int ret = 0, long_header;
7783 size_t minlen, skip;
7784
7785 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
7786
7787 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
7788 TRACE_PROTO("fixed bit not set", QUIC_EV_CONN_RXPKT);
7789 goto err;
7790 }
7791
7792 long_header = *buf & QUIC_PACKET_LONG_HEADER_BIT;
7793 minlen = long_header ? QUIC_LONG_PACKET_MINLEN :
7794 QUIC_SHORT_PACKET_MINLEN + QUIC_HAP_CID_LEN + QUIC_TLS_TAG_LEN;
7795 skip = long_header ? QUIC_LONG_PACKET_DCID_OFF : QUIC_SHORT_PACKET_DCID_OFF;
7796 if (end - buf < minlen)
7797 goto err;
7798
7799 buf += skip;
7800 *dcid_len = long_header ? *buf++ : QUIC_HAP_CID_LEN;
7801 if (*dcid_len > QUIC_CID_MAXLEN || end - buf <= *dcid_len)
7802 goto err;
7803
7804 *dcid = buf;
7805
7806 ret = 1;
7807 leave:
7808 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
7809 return ret;
7810
7811 err:
7812 TRACE_PROTO("wrong datagram", QUIC_EV_CONN_RXPKT);
7813 goto leave;
7814}
7815
7816/* Notify the MUX layer if alive about an imminent close of <qc>. */
7817void qc_notify_close(struct quic_conn *qc)
7818{
7819 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
7820
7821 if (qc->flags & QUIC_FL_CONN_NOTIFY_CLOSE)
7822 goto leave;
7823
7824 qc->flags |= QUIC_FL_CONN_NOTIFY_CLOSE;
7825 /* wake up the MUX */
7826 if (qc->mux_state == QC_MUX_READY && qc->conn->mux->wake) {
7827 TRACE_STATE("connection closure notidfied to mux",
7828 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7829 qc->conn->mux->wake(qc->conn);
7830 }
7831 else
7832 TRACE_STATE("connection closure not notidfied to mux",
7833 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7834 leave:
7835 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
7836}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007837
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01007838/* Wake-up upper layer if waiting for send to be ready.
7839 *
7840 * Returns 1 if upper layer has been woken up else 0.
7841 */
7842int qc_notify_send(struct quic_conn *qc)
7843{
7844 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
Amaury Denoyellecaa16542023-02-28 15:11:26 +01007845 if (quic_path_prep_data(qc->path) &&
7846 (!qc_test_fd(qc) || !fd_send_active(qc->fd))) {
Amaury Denoyellee0fe1182023-02-28 15:08:59 +01007847 tasklet_wakeup(qc->subs->tasklet);
7848 qc->subs->events &= ~SUB_RETRY_SEND;
7849 if (!qc->subs->events)
7850 qc->subs = NULL;
7851
7852 return 1;
7853 }
7854 }
7855
7856 return 0;
7857}
7858
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007859
7860/* appctx context used by "show quic" command */
7861struct show_quic_ctx {
7862 unsigned int epoch;
7863 struct bref bref; /* back-reference to the quic-conn being dumped */
7864 unsigned int thr;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007865 int flags;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007866};
7867
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007868#define QC_CLI_FL_SHOW_ALL 0x1 /* show closing/draining connections */
7869
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007870static int cli_parse_show_quic(char **args, char *payload, struct appctx *appctx, void *private)
7871{
7872 struct show_quic_ctx *ctx = applet_reserve_svcctx(appctx, sizeof(*ctx));
7873
7874 if (!cli_has_level(appctx, ACCESS_LVL_OPER))
7875 return 1;
7876
7877 ctx->epoch = _HA_ATOMIC_FETCH_ADD(&qc_epoch, 1);
7878 ctx->thr = 0;
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007879 ctx->flags = 0;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007880
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01007881 if (*args[2] && strcmp(args[2], "all") == 0)
7882 ctx->flags |= QC_CLI_FL_SHOW_ALL;
7883
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007884 LIST_INIT(&ctx->bref.users);
7885
7886 return 0;
7887}
7888
7889static int cli_io_handler_dump_quic(struct appctx *appctx)
7890{
7891 struct show_quic_ctx *ctx = appctx->svcctx;
7892 struct stconn *sc = appctx_sc(appctx);
7893 struct quic_conn *qc;
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01007894 struct quic_enc_level *qel;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007895 struct eb64_node *node;
7896 struct qc_stream_desc *stream;
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01007897 char bufaddr[INET6_ADDRSTRLEN], bufport[6];
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01007898 int expire;
7899 unsigned char cid_len;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007900
7901 thread_isolate();
7902
7903 if (ctx->thr >= global.nbthread)
7904 goto done;
7905
7906 if (unlikely(sc_ic(sc)->flags & CF_SHUTW)) {
7907 /* If we're forced to shut down, we might have to remove our
7908 * reference to the last stream being dumped.
7909 */
7910 if (!LIST_ISEMPTY(&ctx->bref.users))
7911 LIST_DEL_INIT(&ctx->bref.users);
7912 goto done;
7913 }
7914
7915 chunk_reset(&trash);
7916
7917 if (!LIST_ISEMPTY(&ctx->bref.users)) {
7918 /* Remove show_quic_ctx from previous quic_conn instance. */
7919 LIST_DEL_INIT(&ctx->bref.users);
7920 }
7921 else if (!ctx->bref.ref) {
7922 /* First invocation. */
7923 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
7924 }
7925
7926 while (1) {
7927 int done = 0;
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01007928 int i;
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007929
7930 if (ctx->bref.ref == &ha_thread_ctx[ctx->thr].quic_conns) {
7931 done = 1;
7932 }
7933 else {
7934 qc = LIST_ELEM(ctx->bref.ref, struct quic_conn *, el_th_ctx);
7935 if ((int)(qc->qc_epoch - ctx->epoch) > 0)
7936 done = 1;
7937 }
7938
7939 if (done) {
7940 ++ctx->thr;
7941 if (ctx->thr >= global.nbthread)
7942 break;
7943 ctx->bref.ref = ha_thread_ctx[ctx->thr].quic_conns.n;
7944 continue;
7945 }
7946
Amaury Denoyelle10a46de2023-02-09 18:18:45 +01007947 if (!(ctx->flags & QC_CLI_FL_SHOW_ALL) &&
Amaury Denoyelle3f9758e2023-02-01 17:31:02 +01007948 qc->flags & (QUIC_FL_CONN_CLOSING|QUIC_FL_CONN_DRAINING)) {
7949 ctx->bref.ref = qc->el_th_ctx.n;
7950 continue;
7951 }
7952
Amaury Denoyelle58d9d5d2023-02-01 11:54:43 +01007953 /* CIDs */
7954 chunk_appendf(&trash, "* %p[%02u]: scid=", qc, qc->tid);
7955 for (cid_len = 0; cid_len < qc->scid.len; ++cid_len)
7956 chunk_appendf(&trash, "%02x", qc->scid.data[cid_len]);
7957 while (cid_len++ < 20)
7958 chunk_appendf(&trash, "..");
7959
7960 chunk_appendf(&trash, " dcid=");
7961 for (cid_len = 0; cid_len < qc->dcid.len; ++cid_len)
7962 chunk_appendf(&trash, "%02x", qc->dcid.data[cid_len]);
7963 while (cid_len++ < 20)
7964 chunk_appendf(&trash, "..");
7965
7966 chunk_appendf(&trash, "\n");
7967
7968 /* Connection state */
7969 if (qc->flags & QUIC_FL_CONN_CLOSING)
7970 chunk_appendf(&trash, " st=closing ");
7971 else if (qc->flags & QUIC_FL_CONN_DRAINING)
7972 chunk_appendf(&trash, " st=draining ");
7973 else if (qc->state < QUIC_HS_ST_CONFIRMED)
7974 chunk_appendf(&trash, " st=handshake ");
7975 else
7976 chunk_appendf(&trash, " st=opened ");
7977
7978 if (qc->mux_state == QC_MUX_NULL)
7979 chunk_appendf(&trash, "mux=null ");
7980 else if (qc->mux_state == QC_MUX_READY)
7981 chunk_appendf(&trash, "mux=ready ");
7982 else
7983 chunk_appendf(&trash, "mux=released ");
7984
7985 expire = qc->idle_timer_task->expire;
7986 chunk_appendf(&trash, "expire=%02ds ",
7987 expire > now_ms ? (expire - now_ms) / 1000 : 0);
7988
Amaury Denoyelle15c74702023-02-01 10:18:26 +01007989 chunk_appendf(&trash, "\n");
7990
Amaury Denoyelleb89c0e22023-02-01 17:04:26 +01007991 /* Socket */
7992 chunk_appendf(&trash, " fd=%d", qc->fd);
7993 if (qc->local_addr.ss_family == AF_INET ||
7994 qc->local_addr.ss_family == AF_INET6) {
7995 addr_to_str(&qc->local_addr, bufaddr, sizeof(bufaddr));
7996 port_to_str(&qc->local_addr, bufport, sizeof(bufport));
7997 chunk_appendf(&trash, " from=%s:%s", bufaddr, bufport);
7998
7999 addr_to_str(&qc->peer_addr, bufaddr, sizeof(bufaddr));
8000 port_to_str(&qc->peer_addr, bufport, sizeof(bufport));
8001 chunk_appendf(&trash, " to=%s:%s", bufaddr, bufport);
8002 }
8003
8004 chunk_appendf(&trash, "\n");
8005
Amaury Denoyelle1b0fc432023-02-01 17:05:10 +01008006 /* Encryption levels */
8007 qel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
8008 chunk_appendf(&trash, " [initl] rx.ackrng=%-6zu tx.inflight=%-6zu",
8009 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8010 qel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
8011 chunk_appendf(&trash, " [hndshk] rx.ackrng=%-6zu tx.inflight=%-6zu\n",
8012 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8013 qel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
8014 chunk_appendf(&trash, " [0-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
8015 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8016 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
8017 chunk_appendf(&trash, " [1-rtt] rx.ackrng=%-6zu tx.inflight=%-6zu",
8018 qel->pktns->rx.arngs.sz, qel->pktns->tx.in_flight);
8019
8020 chunk_appendf(&trash, "\n");
8021
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008022 /* Streams */
8023 node = eb64_first(&qc->streams_by_id);
8024 i = 0;
8025 while (node) {
8026 stream = eb64_entry(node, struct qc_stream_desc, by_id);
8027 node = eb64_next(node);
8028
Amaury Denoyellea9de25a2023-02-10 09:25:22 +01008029 chunk_appendf(&trash, " | stream=%-8llu", (unsigned long long)stream->by_id.key);
8030 chunk_appendf(&trash, " off=%-8llu ack=%-8llu",
8031 (unsigned long long)stream->buf_offset,
8032 (unsigned long long)stream->ack_offset);
Amaury Denoyelle2eda63b2023-02-01 17:05:36 +01008033
8034 if (!(++i % 3)) {
8035 chunk_appendf(&trash, "\n");
8036 i = 0;
8037 }
8038 }
8039
8040 chunk_appendf(&trash, "\n");
8041
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008042 if (applet_putchk(appctx, &trash) == -1) {
8043 /* Register show_quic_ctx to quic_conn instance. */
8044 LIST_APPEND(&qc->back_refs, &ctx->bref.users);
8045 goto full;
8046 }
8047
8048 ctx->bref.ref = qc->el_th_ctx.n;
8049 }
8050
8051 done:
8052 thread_release();
8053 return 1;
8054
8055 full:
8056 thread_release();
8057 return 0;
8058}
8059
8060static void cli_release_show_quic(struct appctx *appctx)
8061{
8062 struct show_quic_ctx *ctx = appctx->svcctx;
8063
8064 if (ctx->thr < global.nbthread) {
8065 thread_isolate();
8066 if (!LIST_ISEMPTY(&ctx->bref.users))
8067 LIST_DEL_INIT(&ctx->bref.users);
8068 thread_release();
8069 }
8070}
8071
8072static struct cli_kw_list cli_kws = {{ }, {
8073 { { "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 +01008074 {{},}
Amaury Denoyelle15c74702023-02-01 10:18:26 +01008075}};
8076
8077INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
8078
8079static void init_quic()
8080{
8081 int thr;
8082
8083 for (thr = 0; thr < MAX_THREADS; ++thr)
8084 LIST_INIT(&ha_thread_ctx[thr].quic_conns);
8085}
8086INITCALL0(STG_INIT, init_quic);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02008087
8088/*
8089 * Local variables:
8090 * c-indent-level: 8
8091 * c-basic-offset: 8
8092 * End:
8093 */