blob: 795c1ab924453891df31d3825ae1baa7073c1a3b [file] [log] [blame]
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001/*
2 * QUIC protocol implementation. Lower layer with internal features implemented
3 * here such as QUIC encryption, idle timeout, acknowledgement and
4 * retransmission.
5 *
6 * Copyright 2020 HAProxy Technologies, Frederic Lecaille <flecaille@haproxy.com>
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version
11 * 2 of the License, or (at your option) any later version.
12 *
13 */
14
15#include <haproxy/quic_conn.h>
16
17#define _GNU_SOURCE
18#include <errno.h>
19#include <stdio.h>
20#include <stdlib.h>
21
22#include <sys/socket.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25
26#include <netinet/tcp.h>
27
28#include <import/ebmbtree.h>
29
30#include <haproxy/buf-t.h>
31#include <haproxy/compat.h>
32#include <haproxy/api.h>
33#include <haproxy/debug.h>
34#include <haproxy/tools.h>
35#include <haproxy/ticks.h>
36
37#include <haproxy/connection.h>
38#include <haproxy/fd.h>
39#include <haproxy/freq_ctr.h>
40#include <haproxy/global.h>
41#include <haproxy/h3.h>
42#include <haproxy/hq_interop.h>
43#include <haproxy/log.h>
44#include <haproxy/mux_quic.h>
45#include <haproxy/ncbuf.h>
46#include <haproxy/pipe.h>
47#include <haproxy/proxy.h>
48#include <haproxy/quic_cc.h>
49#include <haproxy/quic_frame.h>
50#include <haproxy/quic_enc.h>
51#include <haproxy/quic_loss.h>
52#include <haproxy/quic_sock.h>
53#include <haproxy/quic_stats.h>
54#include <haproxy/quic_stream.h>
55#include <haproxy/quic_tp.h>
56#include <haproxy/cbuf.h>
57#include <haproxy/proto_quic.h>
58#include <haproxy/quic_tls.h>
59#include <haproxy/ssl_sock.h>
60#include <haproxy/task.h>
61#include <haproxy/trace.h>
62
63/* list of supported QUIC versions by this implementation */
64const struct quic_version quic_versions[] = {
65 {
66 .num = QUIC_PROTOCOL_VERSION_DRAFT_29,
67 .initial_salt = initial_salt_draft_29,
68 .initial_salt_len = sizeof initial_salt_draft_29,
69 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V1,
70 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V1) - 1,
71 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V1,
72 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V1) - 1,
73 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V1,
74 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V1) - 1,
75 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V1,
76 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V1) - 1,
77 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_DRAFT,
78 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_DRAFT,
79 },
80 {
81 .num = QUIC_PROTOCOL_VERSION_1,
82 .initial_salt = initial_salt_v1,
83 .initial_salt_len = sizeof initial_salt_v1,
84 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V1,
85 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V1) - 1,
86 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V1,
87 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V1) - 1,
88 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V1,
89 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V1) - 1,
90 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V1,
91 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V1) - 1,
92 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V1,
93 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V1,
94 },
95 {
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +010096 .num = QUIC_PROTOCOL_VERSION_2,
97 .initial_salt = initial_salt_v2,
98 .initial_salt_len = sizeof initial_salt_v2,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +020099 .key_label = (const unsigned char *)QUIC_HKDF_KEY_LABEL_V2,
100 .key_label_len = sizeof(QUIC_HKDF_KEY_LABEL_V2) - 1,
101 .iv_label = (const unsigned char *)QUIC_HKDF_IV_LABEL_V2,
102 .iv_label_len = sizeof(QUIC_HKDF_IV_LABEL_V2) - 1,
103 .hp_label = (const unsigned char *)QUIC_HKDF_HP_LABEL_V2,
104 .hp_label_len = sizeof(QUIC_HKDF_HP_LABEL_V2) - 1,
105 .ku_label = (const unsigned char *)QUIC_HKDF_KU_LABEL_V2,
106 .ku_label_len = sizeof(QUIC_HKDF_KU_LABEL_V2) - 1,
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +0100107 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V2,
108 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V2,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200109 },
110};
111
112/* The total number of supported versions */
113const size_t quic_versions_nb = sizeof quic_versions / sizeof *quic_versions;
114/* Listener only preferred version */
115const struct quic_version *preferred_version;
116
117/* trace source and events */
118static void quic_trace(enum trace_level level, uint64_t mask, \
119 const struct trace_source *src,
120 const struct ist where, const struct ist func,
121 const void *a1, const void *a2, const void *a3, const void *a4);
122
123static const struct trace_event quic_trace_events[] = {
124 { .mask = QUIC_EV_CONN_NEW, .name = "new_conn", .desc = "new QUIC connection" },
125 { .mask = QUIC_EV_CONN_INIT, .name = "new_conn_init", .desc = "new QUIC connection initialization" },
126 { .mask = QUIC_EV_CONN_ISEC, .name = "init_secs", .desc = "initial secrets derivation" },
127 { .mask = QUIC_EV_CONN_RSEC, .name = "read_secs", .desc = "read secrets derivation" },
128 { .mask = QUIC_EV_CONN_WSEC, .name = "write_secs", .desc = "write secrets derivation" },
129 { .mask = QUIC_EV_CONN_LPKT, .name = "lstnr_packet", .desc = "new listener received packet" },
130 { .mask = QUIC_EV_CONN_SPKT, .name = "srv_packet", .desc = "new server received packet" },
131 { .mask = QUIC_EV_CONN_ENCPKT, .name = "enc_hdshk_pkt", .desc = "handhshake packet encryption" },
132 { .mask = QUIC_EV_CONN_TXPKT, .name = "tx_pkt", .desc = "TX packet" },
133 { .mask = QUIC_EV_CONN_PAPKT, .name = "phdshk_apkt", .desc = "post handhshake application packet preparation" },
134 { .mask = QUIC_EV_CONN_PAPKTS, .name = "phdshk_apkts", .desc = "post handhshake application packets preparation" },
135 { .mask = QUIC_EV_CONN_IO_CB, .name = "qc_io_cb", .desc = "QUIC conn. I/O processing" },
136 { .mask = QUIC_EV_CONN_RMHP, .name = "rm_hp", .desc = "Remove header protection" },
137 { .mask = QUIC_EV_CONN_PRSHPKT, .name = "parse_hpkt", .desc = "parse handshake packet" },
138 { .mask = QUIC_EV_CONN_PRSAPKT, .name = "parse_apkt", .desc = "parse application packet" },
139 { .mask = QUIC_EV_CONN_PRSFRM, .name = "parse_frm", .desc = "parse frame" },
140 { .mask = QUIC_EV_CONN_PRSAFRM, .name = "parse_ack_frm", .desc = "parse ACK frame" },
141 { .mask = QUIC_EV_CONN_BFRM, .name = "build_frm", .desc = "build frame" },
142 { .mask = QUIC_EV_CONN_PHPKTS, .name = "phdshk_pkts", .desc = "handhshake packets preparation" },
143 { .mask = QUIC_EV_CONN_TRMHP, .name = "rm_hp_try", .desc = "header protection removing try" },
144 { .mask = QUIC_EV_CONN_ELRMHP, .name = "el_rm_hp", .desc = "handshake enc. level header protection removing" },
145 { .mask = QUIC_EV_CONN_RXPKT, .name = "rx_pkt", .desc = "RX packet" },
146 { .mask = QUIC_EV_CONN_SSLDATA, .name = "ssl_provide_data", .desc = "CRYPTO data provision to TLS stack" },
147 { .mask = QUIC_EV_CONN_RXCDATA, .name = "el_treat_rx_cfrms",.desc = "enc. level RX CRYPTO frames processing"},
148 { .mask = QUIC_EV_CONN_ADDDATA, .name = "add_hdshk_data", .desc = "TLS stack ->add_handshake_data() call"},
149 { .mask = QUIC_EV_CONN_FFLIGHT, .name = "flush_flight", .desc = "TLS stack ->flush_flight() call"},
150 { .mask = QUIC_EV_CONN_SSLALERT, .name = "send_alert", .desc = "TLS stack ->send_alert() call"},
151 { .mask = QUIC_EV_CONN_RTTUPDT, .name = "rtt_updt", .desc = "RTT sampling" },
152 { .mask = QUIC_EV_CONN_SPPKTS, .name = "sppkts", .desc = "send prepared packets" },
153 { .mask = QUIC_EV_CONN_PKTLOSS, .name = "pktloss", .desc = "detect packet loss" },
154 { .mask = QUIC_EV_CONN_STIMER, .name = "stimer", .desc = "set timer" },
155 { .mask = QUIC_EV_CONN_PTIMER, .name = "ptimer", .desc = "process timer" },
156 { .mask = QUIC_EV_CONN_SPTO, .name = "spto", .desc = "set PTO" },
157 { .mask = QUIC_EV_CONN_BCFRMS, .name = "bcfrms", .desc = "build CRYPTO data frames" },
158 { .mask = QUIC_EV_CONN_XPRTSEND, .name = "xprt_send", .desc = "sending XRPT subscription" },
159 { .mask = QUIC_EV_CONN_XPRTRECV, .name = "xprt_recv", .desc = "receiving XRPT subscription" },
160 { .mask = QUIC_EV_CONN_FREED, .name = "conn_freed", .desc = "releasing conn. memory" },
161 { .mask = QUIC_EV_CONN_CLOSE, .name = "conn_close", .desc = "closing conn." },
162 { .mask = QUIC_EV_CONN_ACKSTRM, .name = "ack_strm", .desc = "STREAM ack."},
163 { .mask = QUIC_EV_CONN_FRMLIST, .name = "frm_list", .desc = "frame list"},
164 { .mask = QUIC_EV_STATELESS_RST, .name = "stateless_reset", .desc = "stateless reset sent"},
165 { .mask = QUIC_EV_TRANSP_PARAMS, .name = "transport_params", .desc = "transport parameters"},
166 { .mask = QUIC_EV_CONN_IDLE_TIMER, .name = "idle_timer", .desc = "idle timer task"},
167 { .mask = QUIC_EV_CONN_SUB, .name = "xprt_sub", .desc = "RX/TX subcription or unsubscription to QUIC xprt"},
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200168 { .mask = QUIC_EV_CONN_RCV, .name = "conn_recv", .desc = "RX on connection" },
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200169 { /* end */ }
170};
171
172static const struct name_desc quic_trace_lockon_args[4] = {
173 /* arg1 */ { /* already used by the connection */ },
174 /* arg2 */ { .name="quic", .desc="QUIC transport" },
175 /* arg3 */ { },
176 /* arg4 */ { }
177};
178
179static const struct name_desc quic_trace_decoding[] = {
180#define QUIC_VERB_CLEAN 1
181 { .name="clean", .desc="only user-friendly stuff, generally suitable for level \"user\"" },
182 { /* end */ }
183};
184
185
186struct trace_source trace_quic = {
187 .name = IST("quic"),
188 .desc = "QUIC xprt",
189 .arg_def = TRC_ARG1_QCON, /* TRACE()'s first argument is always a quic_conn */
190 .default_cb = quic_trace,
191 .known_events = quic_trace_events,
192 .lockon_args = quic_trace_lockon_args,
193 .decoding = quic_trace_decoding,
194 .report_events = ~0, /* report everything by default */
195};
196
197#define TRACE_SOURCE &trace_quic
198INITCALL1(STG_REGISTER, trace_register_source, TRACE_SOURCE);
199
200static BIO_METHOD *ha_quic_meth;
201
202DECLARE_POOL(pool_head_quic_tx_ring, "quic_tx_ring", QUIC_TX_RING_BUFSZ);
203DECLARE_POOL(pool_head_quic_conn_rxbuf, "quic_conn_rxbuf", QUIC_CONN_RX_BUFSZ);
204DECLARE_STATIC_POOL(pool_head_quic_conn_ctx,
205 "quic_conn_ctx", sizeof(struct ssl_sock_ctx));
206DECLARE_STATIC_POOL(pool_head_quic_conn, "quic_conn", sizeof(struct quic_conn));
207DECLARE_POOL(pool_head_quic_connection_id,
208 "quic_connnection_id", sizeof(struct quic_connection_id));
209DECLARE_POOL(pool_head_quic_dgram, "quic_dgram", sizeof(struct quic_dgram));
210DECLARE_POOL(pool_head_quic_rx_packet, "quic_rx_packet", sizeof(struct quic_rx_packet));
211DECLARE_POOL(pool_head_quic_tx_packet, "quic_tx_packet", sizeof(struct quic_tx_packet));
212DECLARE_STATIC_POOL(pool_head_quic_rx_crypto_frm, "quic_rx_crypto_frm", sizeof(struct quic_rx_crypto_frm));
213DECLARE_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 +0200214DECLARE_STATIC_POOL(pool_head_quic_cstream, "quic_cstream", sizeof(struct quic_cstream));
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200215DECLARE_POOL(pool_head_quic_frame, "quic_frame", sizeof(struct quic_frame));
216DECLARE_STATIC_POOL(pool_head_quic_arng, "quic_arng", sizeof(struct quic_arng_node));
217
218static struct quic_tx_packet *qc_build_pkt(unsigned char **pos, const unsigned char *buf_end,
219 struct quic_enc_level *qel, struct quic_tls_ctx *ctx,
220 struct list *frms, struct quic_conn *qc,
221 const struct quic_version *ver, size_t dglen, int pkt_type,
222 int force_ack, int padding, int probe, int cc, int *err);
223struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state);
224static void qc_idle_timer_do_rearm(struct quic_conn *qc);
225static void qc_idle_timer_rearm(struct quic_conn *qc, int read);
226static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc);
227static int quic_conn_init_timer(struct quic_conn *qc);
228static int quic_conn_init_idle_timer_task(struct quic_conn *qc);
229
230/* Only for debug purpose */
231struct enc_debug_info {
232 unsigned char *payload;
233 size_t payload_len;
234 unsigned char *aad;
235 size_t aad_len;
236 uint64_t pn;
237};
238
239/* Initializes a enc_debug_info struct (only for debug purpose) */
240static inline void enc_debug_info_init(struct enc_debug_info *edi,
241 unsigned char *payload, size_t payload_len,
242 unsigned char *aad, size_t aad_len, uint64_t pn)
243{
244 edi->payload = payload;
245 edi->payload_len = payload_len;
246 edi->aad = aad;
247 edi->aad_len = aad_len;
248 edi->pn = pn;
249}
250
251/* Trace callback for QUIC.
252 * These traces always expect that arg1, if non-null, is of type connection.
253 */
254static void quic_trace(enum trace_level level, uint64_t mask, const struct trace_source *src,
255 const struct ist where, const struct ist func,
256 const void *a1, const void *a2, const void *a3, const void *a4)
257{
258 const struct quic_conn *qc = a1;
259
260 if (qc) {
261 const struct quic_tls_ctx *tls_ctx;
262
263 chunk_appendf(&trace_buf, " : qc@%p", qc);
264 if (mask & QUIC_EV_CONN_INIT) {
265 chunk_appendf(&trace_buf, "\n odcid");
266 quic_cid_dump(&trace_buf, &qc->odcid);
267 chunk_appendf(&trace_buf, "\n dcid");
268 quic_cid_dump(&trace_buf, &qc->dcid);
269 chunk_appendf(&trace_buf, "\n scid");
270 quic_cid_dump(&trace_buf, &qc->scid);
271 }
272
273 if (mask & QUIC_EV_TRANSP_PARAMS) {
274 const struct quic_transport_params *p = a2;
275 quic_transport_params_dump(&trace_buf, qc, p);
276 }
277
278 if (mask & QUIC_EV_CONN_ADDDATA) {
279 const enum ssl_encryption_level_t *level = a2;
280 const size_t *len = a3;
281
282 if (level) {
283 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
284
285 chunk_appendf(&trace_buf, " el=%c(%d)", quic_enc_level_char(lvl), lvl);
286 }
287 if (len)
288 chunk_appendf(&trace_buf, " len=%llu", (unsigned long long)*len);
289 }
290 if ((mask & QUIC_EV_CONN_ISEC) && qc) {
291 /* Initial read & write secrets. */
292 enum quic_tls_enc_level level = QUIC_TLS_ENC_LEVEL_INITIAL;
293 const unsigned char *rx_sec = a2;
294 const unsigned char *tx_sec = a3;
295
296 tls_ctx = &qc->els[level].tls_ctx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200297 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(level));
298 if (rx_sec)
299 quic_tls_secret_hexdump(&trace_buf, rx_sec, 32);
300 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
301 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(level));
302 if (tx_sec)
303 quic_tls_secret_hexdump(&trace_buf, tx_sec, 32);
304 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200305 }
306 if (mask & (QUIC_EV_CONN_RSEC|QUIC_EV_CONN_RWSEC)) {
307 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200308
309 if (level) {
310 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
311
312 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200313 if (quic_tls_has_rx_sec(&qc->els[lvl])) {
314 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200315 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->rx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200316 }
317 else
318 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200319 }
320 }
321
322 if (mask & (QUIC_EV_CONN_WSEC|QUIC_EV_CONN_RWSEC)) {
323 const enum ssl_encryption_level_t *level = a2;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200324
325 if (level) {
326 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
327
328 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(lvl));
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200329 if (quic_tls_has_tx_sec(&qc->els[lvl])) {
330 tls_ctx = &qc->els[lvl].tls_ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200331 quic_tls_keys_hexdump(&trace_buf, &tls_ctx->tx);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200332 }
333 else
334 chunk_appendf(&trace_buf, " (none)");
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200335 }
336
337 }
338
339 if (mask & QUIC_EV_CONN_FRMLIST) {
340 const struct list *l = a2;
341
342 if (l) {
343 const struct quic_frame *frm;
344 list_for_each_entry(frm, l, list) {
345 chunk_appendf(&trace_buf, " frm@%p", frm);
346 chunk_frm_appendf(&trace_buf, frm);
347 }
348 }
349 }
350
351 if (mask & (QUIC_EV_CONN_TXPKT|QUIC_EV_CONN_PAPKT)) {
352 const struct quic_tx_packet *pkt = a2;
353 const struct quic_enc_level *qel = a3;
354 const ssize_t *room = a4;
355
356 if (qel) {
357 const struct quic_pktns *pktns = qel->pktns;
358 chunk_appendf(&trace_buf, " qel=%c cwnd=%llu ppif=%lld pif=%llu "
359 "if=%llu pp=%u",
360 quic_enc_level_char_from_qel(qel, qc),
361 (unsigned long long)qc->path->cwnd,
362 (unsigned long long)qc->path->prep_in_flight,
363 (unsigned long long)qc->path->in_flight,
364 (unsigned long long)pktns->tx.in_flight,
365 pktns->tx.pto_probe);
366 }
367 if (pkt) {
368 const struct quic_frame *frm;
369 if (pkt->pn_node.key != (uint64_t)-1)
370 chunk_appendf(&trace_buf, " pn=%llu",(ull)pkt->pn_node.key);
371 list_for_each_entry(frm, &pkt->frms, list) {
372 chunk_appendf(&trace_buf, " frm@%p", frm);
373 chunk_frm_appendf(&trace_buf, frm);
374 }
375 }
376
377 if (room) {
378 chunk_appendf(&trace_buf, " room=%lld", (long long)*room);
379 chunk_appendf(&trace_buf, " dcid.len=%llu scid.len=%llu",
380 (unsigned long long)qc->dcid.len, (unsigned long long)qc->scid.len);
381 }
382 }
383
384 if (mask & QUIC_EV_CONN_IO_CB) {
385 const enum quic_handshake_state *state = a2;
386 const int *err = a3;
387
388 if (state)
389 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(*state));
390 if (err)
391 chunk_appendf(&trace_buf, " err=%s", ssl_error_str(*err));
392 }
393
394 if (mask & (QUIC_EV_CONN_TRMHP|QUIC_EV_CONN_ELRMHP|QUIC_EV_CONN_SPKT)) {
395 const struct quic_rx_packet *pkt = a2;
396 const unsigned long *pktlen = a3;
397 const SSL *ssl = a4;
398
399 if (pkt) {
400 chunk_appendf(&trace_buf, " pkt@%p", pkt);
401 if (pkt->type == QUIC_PACKET_TYPE_SHORT && pkt->data)
402 chunk_appendf(&trace_buf, " kp=%d",
403 !!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT));
404 chunk_appendf(&trace_buf, " el=%c",
405 quic_packet_type_enc_level_char(pkt->type));
406 if (pkt->pnl)
407 chunk_appendf(&trace_buf, " pnl=%u pn=%llu", pkt->pnl,
408 (unsigned long long)pkt->pn);
409 if (pkt->token_len)
410 chunk_appendf(&trace_buf, " toklen=%llu",
411 (unsigned long long)pkt->token_len);
412 if (pkt->aad_len)
413 chunk_appendf(&trace_buf, " aadlen=%llu",
414 (unsigned long long)pkt->aad_len);
415 chunk_appendf(&trace_buf, " flags=0x%x len=%llu",
416 pkt->flags, (unsigned long long)pkt->len);
417 }
418 if (pktlen)
419 chunk_appendf(&trace_buf, " (%ld)", *pktlen);
420 if (ssl) {
421 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
422 chunk_appendf(&trace_buf, " el=%c",
423 quic_enc_level_char(ssl_to_quic_enc_level(level)));
424 }
425 }
426
427 if (mask & (QUIC_EV_CONN_RXPKT|QUIC_EV_CONN_PRSHPKT|QUIC_EV_CONN_SSLDATA)) {
428 const struct quic_rx_packet *pkt = a2;
429 const struct quic_rx_crypto_frm *cf = a3;
430 const SSL *ssl = a4;
431
432 if (pkt)
433 chunk_appendf(&trace_buf, " pkt@%p el=%c pn=%llu", pkt,
434 quic_packet_type_enc_level_char(pkt->type),
435 (unsigned long long)pkt->pn);
436 if (cf)
437 chunk_appendf(&trace_buf, " cfoff=%llu cflen=%llu",
438 (unsigned long long)cf->offset_node.key,
439 (unsigned long long)cf->len);
440 if (ssl) {
441 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
442 chunk_appendf(&trace_buf, " rel=%c",
443 quic_enc_level_char(ssl_to_quic_enc_level(level)));
444 }
445
446 if (qc->err.code)
447 chunk_appendf(&trace_buf, " err_code=0x%llx", (ull)qc->err.code);
448 }
449
450 if (mask & (QUIC_EV_CONN_PRSFRM|QUIC_EV_CONN_BFRM)) {
451 const struct quic_frame *frm = a2;
452
453 if (frm)
454 chunk_appendf(&trace_buf, " %s", quic_frame_type_string(frm->type));
455 }
456
457 if (mask & QUIC_EV_CONN_PHPKTS) {
458 const struct quic_enc_level *qel = a2;
459
460 if (qel) {
461 const struct quic_pktns *pktns = qel->pktns;
462 chunk_appendf(&trace_buf,
Amaury Denoyelle2f668f02022-11-18 15:24:08 +0100463 " qel=%c state=%s ack?%d cwnd=%llu ppif=%lld pif=%llu if=%llu pp=%u off=%llu",
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200464 quic_enc_level_char_from_qel(qel, qc),
465 quic_hdshk_state_str(qc->state),
466 !!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED),
467 (unsigned long long)qc->path->cwnd,
468 (unsigned long long)qc->path->prep_in_flight,
469 (unsigned long long)qc->path->in_flight,
470 (unsigned long long)pktns->tx.in_flight,
Amaury Denoyelle2f668f02022-11-18 15:24:08 +0100471 pktns->tx.pto_probe,
472 qel->cstream ? (unsigned long long)qel->cstream->rx.offset : 0);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200473 }
474 }
475
476 if (mask & QUIC_EV_CONN_ENCPKT) {
477 const struct enc_debug_info *edi = a2;
478
479 if (edi)
480 chunk_appendf(&trace_buf,
481 " payload=@%p payload_len=%llu"
482 " aad=@%p aad_len=%llu pn=%llu",
483 edi->payload, (unsigned long long)edi->payload_len,
484 edi->aad, (unsigned long long)edi->aad_len,
485 (unsigned long long)edi->pn);
486 }
487
488 if (mask & QUIC_EV_CONN_RMHP) {
489 const struct quic_rx_packet *pkt = a2;
490
491 if (pkt) {
492 const int *ret = a3;
493
494 chunk_appendf(&trace_buf, " pkt@%p", pkt);
495 if (ret && *ret)
496 chunk_appendf(&trace_buf, " pnl=%u pn=%llu",
497 pkt->pnl, (unsigned long long)pkt->pn);
498 }
499 }
500
501 if (mask & QUIC_EV_CONN_PRSAFRM) {
502 const struct quic_frame *frm = a2;
503 const unsigned long *val1 = a3;
504 const unsigned long *val2 = a4;
505
506 if (frm) {
507 chunk_appendf(&trace_buf, " frm@%p", frm);
508 chunk_frm_appendf(&trace_buf, frm);
509 }
510 if (val1)
511 chunk_appendf(&trace_buf, " %lu", *val1);
512 if (val2)
513 chunk_appendf(&trace_buf, "..%lu", *val2);
514 }
515
516 if (mask & QUIC_EV_CONN_ACKSTRM) {
517 const struct quic_stream *s = a2;
518 const struct qc_stream_desc *stream = a3;
519
520 if (s)
521 chunk_appendf(&trace_buf, " off=%llu len=%llu", (ull)s->offset.key, (ull)s->len);
522 if (stream)
523 chunk_appendf(&trace_buf, " ack_offset=%llu", (ull)stream->ack_offset);
524 }
525
526 if (mask & QUIC_EV_CONN_RTTUPDT) {
527 const unsigned int *rtt_sample = a2;
528 const unsigned int *ack_delay = a3;
529 const struct quic_loss *ql = a4;
530
531 if (rtt_sample)
532 chunk_appendf(&trace_buf, " rtt_sample=%ums", *rtt_sample);
533 if (ack_delay)
534 chunk_appendf(&trace_buf, " ack_delay=%ums", *ack_delay);
535 if (ql)
536 chunk_appendf(&trace_buf,
537 " srtt=%ums rttvar=%ums min_rtt=%ums",
538 ql->srtt >> 3, ql->rtt_var >> 2, ql->rtt_min);
539 }
540 if (mask & QUIC_EV_CONN_CC) {
541 const struct quic_cc_event *ev = a2;
542 const struct quic_cc *cc = a3;
543
544 if (a2)
545 quic_cc_event_trace(&trace_buf, ev);
546 if (a3)
547 quic_cc_state_trace(&trace_buf, cc);
548 }
549
550 if (mask & QUIC_EV_CONN_PKTLOSS) {
551 const struct quic_pktns *pktns = a2;
552 const struct list *lost_pkts = a3;
553
554 if (pktns) {
555 chunk_appendf(&trace_buf, " pktns=%s",
556 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
557 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H");
558 if (pktns->tx.loss_time)
559 chunk_appendf(&trace_buf, " loss_time=%dms",
560 TICKS_TO_MS(tick_remain(now_ms, pktns->tx.loss_time)));
561 }
562 if (lost_pkts && !LIST_ISEMPTY(lost_pkts)) {
563 struct quic_tx_packet *pkt;
564
565 chunk_appendf(&trace_buf, " lost_pkts:");
566 list_for_each_entry(pkt, lost_pkts, list)
567 chunk_appendf(&trace_buf, " %lu", (unsigned long)pkt->pn_node.key);
568 }
569 }
570
571 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_PTIMER|QUIC_EV_CONN_SPTO)) {
572 const struct quic_pktns *pktns = a2;
573 const int *duration = a3;
574 const uint64_t *ifae_pkts = a4;
575
576 if (ifae_pkts)
577 chunk_appendf(&trace_buf, " ifae_pkts=%llu",
578 (unsigned long long)*ifae_pkts);
579 if (pktns) {
580 chunk_appendf(&trace_buf, " pktns=%s pp=%d",
581 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
582 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
583 pktns->tx.pto_probe);
584 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_SPTO)) {
585 if (pktns->tx.in_flight)
586 chunk_appendf(&trace_buf, " if=%llu", (ull)pktns->tx.in_flight);
587 if (pktns->tx.loss_time)
588 chunk_appendf(&trace_buf, " loss_time=%dms",
589 TICKS_TO_MS(pktns->tx.loss_time - now_ms));
590 }
591 if (mask & QUIC_EV_CONN_SPTO) {
592 if (pktns->tx.time_of_last_eliciting)
593 chunk_appendf(&trace_buf, " tole=%dms",
594 TICKS_TO_MS(pktns->tx.time_of_last_eliciting - now_ms));
595 if (duration)
596 chunk_appendf(&trace_buf, " dur=%dms", TICKS_TO_MS(*duration));
597 }
598 }
599
600 if (!(mask & (QUIC_EV_CONN_SPTO|QUIC_EV_CONN_PTIMER)) && qc->timer_task) {
601 chunk_appendf(&trace_buf,
602 " expire=%dms", TICKS_TO_MS(qc->timer - now_ms));
603 }
604 }
605
606 if (mask & QUIC_EV_CONN_SPPKTS) {
607 const struct quic_tx_packet *pkt = a2;
608
609 chunk_appendf(&trace_buf, " cwnd=%llu ppif=%llu pif=%llu",
610 (unsigned long long)qc->path->cwnd,
611 (unsigned long long)qc->path->prep_in_flight,
612 (unsigned long long)qc->path->in_flight);
613 if (pkt) {
614 const struct quic_frame *frm;
615 chunk_appendf(&trace_buf, " pn=%lu(%s) iflen=%llu",
616 (unsigned long)pkt->pn_node.key,
617 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
618 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
619 (unsigned long long)pkt->in_flight_len);
620 chunk_appendf(&trace_buf, " rx.bytes=%llu tx.bytes=%llu",
621 (unsigned long long)qc->rx.bytes,
622 (unsigned long long)qc->tx.bytes);
623 list_for_each_entry(frm, &pkt->frms, list) {
624 chunk_appendf(&trace_buf, " frm@%p", frm);
625 chunk_frm_appendf(&trace_buf, frm);
626 }
627 }
628 }
629
630 if (mask & QUIC_EV_CONN_SSLALERT) {
631 const uint8_t *alert = a2;
632 const enum ssl_encryption_level_t *level = a3;
633
634 if (alert)
635 chunk_appendf(&trace_buf, " alert=0x%02x", *alert);
636 if (level)
637 chunk_appendf(&trace_buf, " el=%c",
638 quic_enc_level_char(ssl_to_quic_enc_level(*level)));
639 }
640
641 if (mask & QUIC_EV_CONN_BCFRMS) {
642 const size_t *sz1 = a2;
643 const size_t *sz2 = a3;
644 const size_t *sz3 = a4;
645
646 if (sz1)
647 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz1);
648 if (sz2)
649 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz2);
650 if (sz3)
651 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz3);
652 }
653
654 if (mask & QUIC_EV_CONN_PSTRM) {
655 const struct quic_frame *frm = a2;
656
657 if (frm) {
658 chunk_appendf(&trace_buf, " frm@%p", frm);
659 chunk_frm_appendf(&trace_buf, frm);
660 }
661 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +0200662
663 if (mask & QUIC_EV_CONN_ELEVELSEL) {
664 const enum quic_handshake_state *state = a2;
665 const enum quic_tls_enc_level *level = a3;
666 const enum quic_tls_enc_level *next_level = a4;
667
668 if (state)
669 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(qc->state));
670 if (level)
671 chunk_appendf(&trace_buf, " level=%c", quic_enc_level_char(*level));
672 if (next_level)
673 chunk_appendf(&trace_buf, " next_level=%c", quic_enc_level_char(*next_level));
674
675 }
Amaury Denoyelle5b414862022-10-24 17:40:37 +0200676
677 if (mask & QUIC_EV_CONN_RCV) {
678 const struct quic_dgram *dgram = a2;
679
680 if (dgram)
681 chunk_appendf(&trace_buf, " dgram.len=%zu", dgram->len);
682 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200683 }
684 if (mask & QUIC_EV_CONN_LPKT) {
685 const struct quic_rx_packet *pkt = a2;
686 const uint64_t *len = a3;
687 const struct quic_version *ver = a4;
688
689 if (pkt) {
690 chunk_appendf(&trace_buf, " pkt@%p type=0x%02x %s",
691 pkt, pkt->type, qc_pkt_long(pkt) ? "long" : "short");
692 if (pkt->pn_node.key != (uint64_t)-1)
693 chunk_appendf(&trace_buf, " pn=%llu", pkt->pn_node.key);
694 }
695
696 if (len)
697 chunk_appendf(&trace_buf, " len=%llu", (ull)*len);
698
699 if (ver)
700 chunk_appendf(&trace_buf, " ver=0x%08x", ver->num);
701 }
702
703 if (mask & QUIC_EV_STATELESS_RST) {
704 const struct quic_cid *cid = a2;
705
706 if (cid)
707 quic_cid_dump(&trace_buf, cid);
708 }
709
710}
711
712/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
713static inline int quic_peer_validated_addr(struct quic_conn *qc)
714{
715 struct quic_pktns *hdshk_pktns, *app_pktns;
716
717 if (!qc_is_listener(qc))
718 return 1;
719
720 hdshk_pktns = qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns;
721 app_pktns = qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns;
722 if ((hdshk_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
723 (app_pktns->flags & QUIC_FL_PKTNS_PKT_RECEIVED) ||
724 qc->state >= QUIC_HS_ST_COMPLETE)
725 return 1;
726
727 return 0;
728}
729
730/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
731 * both loss detection and PTO and schedule the task assiated to this timer if needed.
732 */
733static inline void qc_set_timer(struct quic_conn *qc)
734{
735 struct quic_pktns *pktns;
736 unsigned int pto;
737 int handshake_complete;
738
739 TRACE_ENTER(QUIC_EV_CONN_STIMER, qc,
740 NULL, NULL, &qc->path->ifae_pkts);
741
742 pktns = quic_loss_pktns(qc);
743 if (tick_isset(pktns->tx.loss_time)) {
744 qc->timer = pktns->tx.loss_time;
745 goto out;
746 }
747
748 /* anti-amplification: the timer must be
749 * cancelled for a server which reached the anti-amplification limit.
750 */
751 if (!quic_peer_validated_addr(qc) &&
752 (qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED)) {
753 TRACE_PROTO("anti-amplification reached", QUIC_EV_CONN_STIMER, qc);
754 qc->timer = TICK_ETERNITY;
755 goto out;
756 }
757
758 if (!qc->path->ifae_pkts && quic_peer_validated_addr(qc)) {
759 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, qc);
760 /* Timer cancellation. */
761 qc->timer = TICK_ETERNITY;
762 goto out;
763 }
764
765 handshake_complete = qc->state >= QUIC_HS_ST_COMPLETE;
766 pktns = quic_pto_pktns(qc, handshake_complete, &pto);
767 if (tick_isset(pto))
768 qc->timer = pto;
769 out:
770 if (qc->timer_task && qc->timer != TICK_ETERNITY) {
771 if (tick_is_expired(qc->timer, now_ms)) {
772 TRACE_DEVEL("wakeup asap timer task", QUIC_EV_CONN_STIMER, qc);
773 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
774 }
775 else {
776 TRACE_DEVEL("timer task scheduling", QUIC_EV_CONN_STIMER, qc);
777 task_schedule(qc->timer_task, qc->timer);
778 }
779 }
780 TRACE_LEAVE(QUIC_EV_CONN_STIMER, qc, pktns);
781}
782
783/* Derive new keys and ivs required for Key Update feature for <qc> QUIC
784 * connection.
785 * Return 1 if succeeded, 0 if not.
786 */
787static int quic_tls_key_update(struct quic_conn *qc)
788{
789 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
790 struct quic_tls_secrets *rx, *tx;
791 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
792 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
793 const struct quic_version *ver =
794 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
795 int ret = 0;
796
797 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
798
799 tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
800 rx = &tls_ctx->rx;
801 tx = &tls_ctx->tx;
802 nxt_rx = &qc->ku.nxt_rx;
803 nxt_tx = &qc->ku.nxt_tx;
804
805 /* Prepare new RX secrets */
806 if (!quic_tls_sec_update(rx->md, ver, nxt_rx->secret, nxt_rx->secretlen,
807 rx->secret, rx->secretlen)) {
808 TRACE_ERROR("New RX secret update failed", QUIC_EV_CONN_RWSEC, qc);
809 goto leave;
810 }
811
812 if (!quic_tls_derive_keys(rx->aead, NULL, rx->md, ver,
813 nxt_rx->key, nxt_rx->keylen,
814 nxt_rx->iv, nxt_rx->ivlen, NULL, 0,
815 nxt_rx->secret, nxt_rx->secretlen)) {
816 TRACE_ERROR("New RX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
817 goto leave;
818 }
819
820 /* Prepare new TX secrets */
821 if (!quic_tls_sec_update(tx->md, ver, nxt_tx->secret, nxt_tx->secretlen,
822 tx->secret, tx->secretlen)) {
823 TRACE_ERROR("New TX secret update failed", QUIC_EV_CONN_RWSEC, qc);
824 goto leave;
825 }
826
827 if (!quic_tls_derive_keys(tx->aead, NULL, tx->md, ver,
828 nxt_tx->key, nxt_tx->keylen,
829 nxt_tx->iv, nxt_tx->ivlen, NULL, 0,
830 nxt_tx->secret, nxt_tx->secretlen)) {
831 TRACE_ERROR("New TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
832 goto leave;
833 }
834
835 if (nxt_rx->ctx) {
836 EVP_CIPHER_CTX_free(nxt_rx->ctx);
837 nxt_rx->ctx = NULL;
838 }
839
840 if (!quic_tls_rx_ctx_init(&nxt_rx->ctx, tls_ctx->rx.aead, nxt_rx->key)) {
841 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
842 goto leave;
843 }
844
845 if (nxt_tx->ctx) {
846 EVP_CIPHER_CTX_free(nxt_tx->ctx);
847 nxt_tx->ctx = NULL;
848 }
849
850 if (!quic_tls_rx_ctx_init(&nxt_tx->ctx, tls_ctx->tx.aead, nxt_tx->key)) {
851 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
852 goto leave;
853 }
854
855 ret = 1;
856 leave:
857 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc);
858 return ret;
859}
860
861/* Rotate the Key Update information for <qc> QUIC connection.
862 * Must be used after having updated them.
863 * Always succeeds.
864 */
865static void quic_tls_rotate_keys(struct quic_conn *qc)
866{
867 struct quic_tls_ctx *tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
868 unsigned char *curr_secret, *curr_iv, *curr_key;
869 EVP_CIPHER_CTX *curr_ctx;
870
871 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
872
873 /* Rotate the RX secrets */
874 curr_ctx = tls_ctx->rx.ctx;
875 curr_secret = tls_ctx->rx.secret;
876 curr_iv = tls_ctx->rx.iv;
877 curr_key = tls_ctx->rx.key;
878
879 tls_ctx->rx.ctx = qc->ku.nxt_rx.ctx;
880 tls_ctx->rx.secret = qc->ku.nxt_rx.secret;
881 tls_ctx->rx.iv = qc->ku.nxt_rx.iv;
882 tls_ctx->rx.key = qc->ku.nxt_rx.key;
883
884 qc->ku.nxt_rx.ctx = qc->ku.prv_rx.ctx;
885 qc->ku.nxt_rx.secret = qc->ku.prv_rx.secret;
886 qc->ku.nxt_rx.iv = qc->ku.prv_rx.iv;
887 qc->ku.nxt_rx.key = qc->ku.prv_rx.key;
888
889 qc->ku.prv_rx.ctx = curr_ctx;
890 qc->ku.prv_rx.secret = curr_secret;
891 qc->ku.prv_rx.iv = curr_iv;
892 qc->ku.prv_rx.key = curr_key;
893 qc->ku.prv_rx.pn = tls_ctx->rx.pn;
894
895 /* Update the TX secrets */
896 curr_ctx = tls_ctx->tx.ctx;
897 curr_secret = tls_ctx->tx.secret;
898 curr_iv = tls_ctx->tx.iv;
899 curr_key = tls_ctx->tx.key;
900
901 tls_ctx->tx.ctx = qc->ku.nxt_tx.ctx;
902 tls_ctx->tx.secret = qc->ku.nxt_tx.secret;
903 tls_ctx->tx.iv = qc->ku.nxt_tx.iv;
904 tls_ctx->tx.key = qc->ku.nxt_tx.key;
905
906 qc->ku.nxt_tx.ctx = curr_ctx;
907 qc->ku.nxt_tx.secret = curr_secret;
908 qc->ku.nxt_tx.iv = curr_iv;
909 qc->ku.nxt_tx.key = curr_key;
910
911 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
912}
913
914/* returns 0 on error, 1 on success */
915int ha_quic_set_encryption_secrets(SSL *ssl, enum ssl_encryption_level_t level,
916 const uint8_t *read_secret,
917 const uint8_t *write_secret, size_t secret_len)
918{
919 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
920 struct quic_tls_ctx *tls_ctx = &qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
921 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200922 struct quic_tls_secrets *rx = NULL, *tx = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200923 const struct quic_version *ver =
924 qc->negotiated_version ? qc->negotiated_version : qc->original_version;
925 int ret = 0;
926
927 TRACE_ENTER(QUIC_EV_CONN_RWSEC, qc);
928 BUG_ON(secret_len > QUIC_TLS_SECRET_LEN);
929 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
930 TRACE_PROTO("CC required", QUIC_EV_CONN_RWSEC, qc);
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200931 goto out;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200932 }
933
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200934 if (!read_secret)
935 goto write;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200936
937 rx = &tls_ctx->rx;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200938 if (!quic_tls_secrets_keys_alloc(rx)) {
939 TRACE_ERROR("RX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
940 goto leave;
941 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200942
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200943 rx->aead = tls_aead(cipher);
944 rx->md = tls_md(cipher);
945 rx->hp = tls_hp(cipher);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200946
947 if (!quic_tls_derive_keys(rx->aead, rx->hp, rx->md, ver, rx->key, rx->keylen,
948 rx->iv, rx->ivlen, rx->hp_key, sizeof rx->hp_key,
949 read_secret, secret_len)) {
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200950 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200951 goto leave;
952 }
953
954 if (!quic_tls_rx_ctx_init(&rx->ctx, rx->aead, rx->key)) {
955 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
956 goto leave;
957 }
958
959 if (!quic_tls_dec_aes_ctx_init(&rx->hp_ctx, rx->hp, rx->hp_key)) {
960 TRACE_ERROR("could not initial RX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
961 goto leave;
962 }
963
964 /* Enqueue this connection asap if we could derive O-RTT secrets as
965 * listener. Note that a listener derives only RX secrets for this
966 * level.
967 */
968 if (qc_is_listener(qc) && level == ssl_encryption_early_data) {
969 TRACE_DEVEL("pushing connection into accept queue", QUIC_EV_CONN_RWSEC, qc);
970 quic_accept_push_qc(qc);
971 }
972
973write:
974
975 if (!write_secret)
976 goto out;
977
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +0200978 tx = &tls_ctx->tx;
979 if (!quic_tls_secrets_keys_alloc(tx)) {
980 TRACE_ERROR("TX keys allocation failed", QUIC_EV_CONN_RWSEC, qc);
981 goto leave;
982 }
983
984 tx->aead = tls_aead(cipher);
985 tx->md = tls_md(cipher);
986 tx->hp = tls_hp(cipher);
987
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +0200988 if (!quic_tls_derive_keys(tx->aead, tx->hp, tx->md, ver, tx->key, tx->keylen,
989 tx->iv, tx->ivlen, tx->hp_key, sizeof tx->hp_key,
990 write_secret, secret_len)) {
991 TRACE_ERROR("TX key derivation failed", QUIC_EV_CONN_RWSEC, qc);
992 goto leave;
993 }
994
995 if (!quic_tls_tx_ctx_init(&tx->ctx, tx->aead, tx->key)) {
996 TRACE_ERROR("could not initial RX TLS cipher context", QUIC_EV_CONN_RWSEC, qc);
997 goto leave;
998 }
999
1000 if (!quic_tls_enc_aes_ctx_init(&tx->hp_ctx, tx->hp, tx->hp_key)) {
1001 TRACE_ERROR("could not initial TX TLS cipher context for HP", QUIC_EV_CONN_RWSEC, qc);
1002 goto leave;
1003 }
1004
1005 if (level == ssl_encryption_application) {
1006 struct quic_tls_kp *prv_rx = &qc->ku.prv_rx;
1007 struct quic_tls_kp *nxt_rx = &qc->ku.nxt_rx;
1008 struct quic_tls_kp *nxt_tx = &qc->ku.nxt_tx;
1009
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001010 if (rx) {
1011 if (!(rx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1012 TRACE_ERROR("Could not allocate RX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1013 goto leave;
1014 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001015
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001016 memcpy(rx->secret, read_secret, secret_len);
1017 rx->secretlen = secret_len;
1018 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001019
1020 if (tx) {
1021 if (!(tx->secret = pool_alloc(pool_head_quic_tls_secret))) {
1022 TRACE_ERROR("Could not allocate TX Application secrete keys", QUIC_EV_CONN_RWSEC, qc);
1023 goto leave;
1024 }
1025
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001026 memcpy(tx->secret, write_secret, secret_len);
1027 tx->secretlen = secret_len;
1028 }
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02001029
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001030 /* Initialize all the secret keys lengths */
1031 prv_rx->secretlen = nxt_rx->secretlen = nxt_tx->secretlen = secret_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001032 }
1033
1034 out:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001035 ret = 1;
1036 leave:
1037 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, qc, &level);
1038 return ret;
1039}
1040
1041/* This function copies the CRYPTO data provided by the TLS stack found at <data>
1042 * with <len> as size in CRYPTO buffers dedicated to store the information about
1043 * outgoing CRYPTO frames so that to be able to replay the CRYPTO data streams.
1044 * It fails (returns 0) only if it could not managed to allocate enough CRYPTO
1045 * buffers to store all the data.
1046 * Note that CRYPTO data may exist at any encryption level except at 0-RTT.
1047 */
1048static int quic_crypto_data_cpy(struct quic_conn *qc, struct quic_enc_level *qel,
1049 const unsigned char *data, size_t len)
1050{
1051 struct quic_crypto_buf **qcb;
1052 /* The remaining byte to store in CRYPTO buffers. */
1053 size_t cf_offset, cf_len, *nb_buf;
1054 unsigned char *pos;
1055 int ret = 0;
1056
1057 nb_buf = &qel->tx.crypto.nb_buf;
1058 qcb = &qel->tx.crypto.bufs[*nb_buf - 1];
1059 cf_offset = (*nb_buf - 1) * QUIC_CRYPTO_BUF_SZ + (*qcb)->sz;
1060 cf_len = len;
1061
1062 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1063
1064 while (len) {
1065 size_t to_copy, room;
1066
1067 pos = (*qcb)->data + (*qcb)->sz;
1068 room = QUIC_CRYPTO_BUF_SZ - (*qcb)->sz;
1069 to_copy = len > room ? room : len;
1070 if (to_copy) {
1071 memcpy(pos, data, to_copy);
1072 /* Increment the total size of this CRYPTO buffers by <to_copy>. */
1073 qel->tx.crypto.sz += to_copy;
1074 (*qcb)->sz += to_copy;
1075 len -= to_copy;
1076 data += to_copy;
1077 }
1078 else {
1079 struct quic_crypto_buf **tmp;
1080
1081 // FIXME: realloc!
1082 tmp = realloc(qel->tx.crypto.bufs,
1083 (*nb_buf + 1) * sizeof *qel->tx.crypto.bufs);
1084 if (tmp) {
1085 qel->tx.crypto.bufs = tmp;
1086 qcb = &qel->tx.crypto.bufs[*nb_buf];
1087 *qcb = pool_alloc(pool_head_quic_crypto_buf);
1088 if (!*qcb) {
1089 TRACE_ERROR("Could not allocate crypto buf", QUIC_EV_CONN_ADDDATA, qc);
1090 goto leave;
1091 }
1092
1093 (*qcb)->sz = 0;
1094 ++*nb_buf;
1095 }
1096 else {
1097 break;
1098 }
1099 }
1100 }
1101
1102 /* Allocate a TX CRYPTO frame only if all the CRYPTO data
1103 * have been buffered.
1104 */
1105 if (!len) {
1106 struct quic_frame *frm;
1107 struct quic_frame *found = NULL;
1108
1109 /* There is at most one CRYPTO frame in this packet number
1110 * space. Let's look for it.
1111 */
1112 list_for_each_entry(frm, &qel->pktns->tx.frms, list) {
1113 if (frm->type != QUIC_FT_CRYPTO)
1114 continue;
1115
1116 /* Found */
1117 found = frm;
1118 break;
1119 }
1120
1121 if (found) {
1122 found->crypto.len += cf_len;
1123 }
1124 else {
1125 frm = pool_zalloc(pool_head_quic_frame);
1126 if (!frm) {
1127 TRACE_ERROR("Could not allocate quic frame", QUIC_EV_CONN_ADDDATA, qc);
1128 goto leave;
1129 }
1130
1131 LIST_INIT(&frm->reflist);
1132 frm->type = QUIC_FT_CRYPTO;
1133 frm->crypto.offset = cf_offset;
1134 frm->crypto.len = cf_len;
1135 frm->crypto.qel = qel;
1136 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
1137 }
1138 }
1139 ret = len == 0;
1140 leave:
1141 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1142 return ret;
1143}
1144
1145/* Prepare the emission of CONNECTION_CLOSE with error <err>. All send/receive
1146 * activity for <qc> will be interrupted.
1147 */
1148void quic_set_connection_close(struct quic_conn *qc, const struct quic_err err)
1149{
1150 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1151 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)
1152 goto leave;
1153
1154 TRACE_STATE("setting immediate close", QUIC_EV_CONN_CLOSE, qc);
1155 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
1156 qc->err.code = err.code;
1157 qc->err.app = err.app;
1158 leave:
1159 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1160}
1161
1162/* Set <alert> TLS alert as QUIC CRYPTO_ERROR error */
1163void quic_set_tls_alert(struct quic_conn *qc, int alert)
1164{
1165 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1166
1167 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
1168 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
1169 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
1170 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
1171 }
1172 quic_set_connection_close(qc, quic_err_tls(alert));
1173 qc->flags |= QUIC_FL_CONN_TLS_ALERT;
1174 TRACE_STATE("Alert set", QUIC_EV_CONN_SSLALERT, qc);
1175
1176 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1177}
1178
1179/* Set the application for <qc> QUIC connection.
1180 * Return 1 if succeeded, 0 if not.
1181 */
1182int quic_set_app_ops(struct quic_conn *qc, const unsigned char *alpn, size_t alpn_len)
1183{
1184 if (alpn_len >= 2 && memcmp(alpn, "h3", 2) == 0)
1185 qc->app_ops = &h3_ops;
1186 else if (alpn_len >= 10 && memcmp(alpn, "hq-interop", 10) == 0)
1187 qc->app_ops = &hq_interop_ops;
1188 else
1189 return 0;
1190
1191 return 1;
1192}
1193
1194/* ->add_handshake_data QUIC TLS callback used by the QUIC TLS stack when it
1195 * wants to provide the QUIC layer with CRYPTO data.
1196 * Returns 1 if succeeded, 0 if not.
1197 */
1198int ha_quic_add_handshake_data(SSL *ssl, enum ssl_encryption_level_t level,
1199 const uint8_t *data, size_t len)
1200{
1201 struct quic_conn *qc;
1202 enum quic_tls_enc_level tel;
1203 struct quic_enc_level *qel;
1204 int ret = 0;
1205
1206 qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1207 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, qc);
1208
1209 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
1210 TRACE_PROTO("CC required", QUIC_EV_CONN_ADDDATA, qc);
1211 goto out;
1212 }
1213
1214 tel = ssl_to_quic_enc_level(level);
1215 if (tel == -1) {
1216 TRACE_ERROR("Wrong encryption level", QUIC_EV_CONN_ADDDATA, qc);
1217 goto leave;
1218 }
1219
1220 qel = &qc->els[tel];
1221 if (!quic_crypto_data_cpy(qc, qel, data, len)) {
1222 TRACE_ERROR("Could not bufferize", QUIC_EV_CONN_ADDDATA, qc);
1223 goto leave;
1224 }
1225
1226 TRACE_DEVEL("CRYPTO data buffered", QUIC_EV_CONN_ADDDATA,
1227 qc, &level, &len);
1228 out:
1229 ret = 1;
1230 leave:
1231 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, qc);
1232 return ret;
1233}
1234
1235int ha_quic_flush_flight(SSL *ssl)
1236{
1237 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1238
1239 TRACE_ENTER(QUIC_EV_CONN_FFLIGHT, qc);
1240 TRACE_LEAVE(QUIC_EV_CONN_FFLIGHT, qc);
1241
1242 return 1;
1243}
1244
1245int ha_quic_send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
1246{
1247 struct quic_conn *qc = SSL_get_ex_data(ssl, ssl_qc_app_data_index);
1248
1249 TRACE_ENTER(QUIC_EV_CONN_SSLALERT, qc);
1250
1251 TRACE_PROTO("Received TLS alert", QUIC_EV_CONN_SSLALERT, qc, &alert, &level);
1252
1253 quic_set_tls_alert(qc, alert);
1254 TRACE_LEAVE(QUIC_EV_CONN_SSLALERT, qc);
1255 return 1;
1256}
1257
1258/* QUIC TLS methods */
1259static SSL_QUIC_METHOD ha_quic_method = {
1260 .set_encryption_secrets = ha_quic_set_encryption_secrets,
1261 .add_handshake_data = ha_quic_add_handshake_data,
1262 .flush_flight = ha_quic_flush_flight,
1263 .send_alert = ha_quic_send_alert,
1264};
1265
1266/* Initialize the TLS context of a listener with <bind_conf> as configuration.
1267 * Returns an error count.
1268 */
1269int ssl_quic_initial_ctx(struct bind_conf *bind_conf)
1270{
1271 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
1272 int cfgerr = 0;
1273
1274 long options =
1275 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
1276 SSL_OP_SINGLE_ECDH_USE |
1277 SSL_OP_CIPHER_SERVER_PREFERENCE;
1278 SSL_CTX *ctx;
1279
1280 ctx = SSL_CTX_new(TLS_server_method());
1281 bind_conf->initial_ctx = ctx;
1282
1283 SSL_CTX_set_options(ctx, options);
1284 SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
1285 SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
1286 SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
1287
1288#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
1289# if defined(HAVE_SSL_CLIENT_HELLO_CB)
1290# if defined(SSL_OP_NO_ANTI_REPLAY)
1291 if (bind_conf->ssl_conf.early_data) {
1292 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
1293 SSL_CTX_set_max_early_data(ctx, 0xffffffff);
1294 }
1295# endif /* !SSL_OP_NO_ANTI_REPLAY */
1296 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
1297 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
1298# else /* ! HAVE_SSL_CLIENT_HELLO_CB */
1299 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
1300# endif
1301 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
1302#endif
1303 SSL_CTX_set_quic_method(ctx, &ha_quic_method);
1304
1305 return cfgerr;
1306}
1307
1308/* Decode an expected packet number from <truncated_on> its truncated value,
1309 * depending on <largest_pn> the largest received packet number, and <pn_nbits>
1310 * the number of bits used to encode this packet number (its length in bytes * 8).
1311 * See https://quicwg.org/base-drafts/draft-ietf-quic-transport.html#packet-encoding
1312 */
1313static uint64_t decode_packet_number(uint64_t largest_pn,
1314 uint32_t truncated_pn, unsigned int pn_nbits)
1315{
1316 uint64_t expected_pn = largest_pn + 1;
1317 uint64_t pn_win = (uint64_t)1 << pn_nbits;
1318 uint64_t pn_hwin = pn_win / 2;
1319 uint64_t pn_mask = pn_win - 1;
1320 uint64_t candidate_pn;
1321
1322
1323 candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
1324 /* Note that <pn_win> > <pn_hwin>. */
1325 if (candidate_pn < QUIC_MAX_PACKET_NUM - pn_win &&
1326 candidate_pn + pn_hwin <= expected_pn)
1327 return candidate_pn + pn_win;
1328
1329 if (candidate_pn > expected_pn + pn_hwin && candidate_pn >= pn_win)
1330 return candidate_pn - pn_win;
1331
1332 return candidate_pn;
1333}
1334
1335/* Remove the header protection of <pkt> QUIC packet using <tls_ctx> as QUIC TLS
1336 * cryptographic context.
1337 * <largest_pn> is the largest received packet number and <pn> the address of
1338 * the packet number field for this packet with <byte0> address of its first byte.
1339 * <end> points to one byte past the end of this packet.
1340 * Returns 1 if succeeded, 0 if not.
1341 */
1342static int qc_do_rm_hp(struct quic_conn *qc,
1343 struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx,
1344 int64_t largest_pn, unsigned char *pn, unsigned char *byte0)
1345{
1346 int ret, i, pnlen;
1347 uint64_t packet_number;
1348 uint32_t truncated_pn = 0;
1349 unsigned char mask[5] = {0};
1350 unsigned char *sample;
1351 EVP_CIPHER_CTX *cctx = NULL;
1352
1353 TRACE_ENTER(QUIC_EV_CONN_RMHP, qc);
1354
1355 ret = 0;
1356
1357 /* Check there is enough data in this packet. */
1358 if (pkt->len - (pn - byte0) < QUIC_PACKET_PN_MAXLEN + sizeof mask) {
1359 TRACE_PROTO("too short packet", QUIC_EV_CONN_RMHP, qc, pkt);
1360 goto leave;
1361 }
1362
1363 cctx = EVP_CIPHER_CTX_new();
1364 if (!cctx) {
1365 TRACE_ERROR("memory allocation failed", QUIC_EV_CONN_RMHP, qc, pkt);
1366 goto leave;
1367 }
1368
1369 sample = pn + QUIC_PACKET_PN_MAXLEN;
1370
1371 if (!quic_tls_aes_decrypt(mask, sample, sizeof mask, tls_ctx->rx.hp_ctx)) {
1372 TRACE_ERROR("HP removing failed", QUIC_EV_CONN_RMHP, qc, pkt);
1373 goto leave;
1374 }
1375
1376 *byte0 ^= mask[0] & (*byte0 & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
1377 pnlen = (*byte0 & QUIC_PACKET_PNL_BITMASK) + 1;
1378 for (i = 0; i < pnlen; i++) {
1379 pn[i] ^= mask[i + 1];
1380 truncated_pn = (truncated_pn << 8) | pn[i];
1381 }
1382
1383 packet_number = decode_packet_number(largest_pn, truncated_pn, pnlen * 8);
1384 /* Store remaining information for this unprotected header */
1385 pkt->pn = packet_number;
1386 pkt->pnl = pnlen;
1387
1388 ret = 1;
1389 leave:
1390 if (cctx)
1391 EVP_CIPHER_CTX_free(cctx);
1392 TRACE_LEAVE(QUIC_EV_CONN_RMHP, qc);
1393 return ret;
1394}
1395
1396/* Encrypt the payload of a QUIC packet with <pn> as number found at <payload>
1397 * address, with <payload_len> as payload length, <aad> as address of
1398 * the ADD and <aad_len> as AAD length depending on the <tls_ctx> QUIC TLS
1399 * context.
1400 * Returns 1 if succeeded, 0 if not.
1401 */
1402static int quic_packet_encrypt(unsigned char *payload, size_t payload_len,
1403 unsigned char *aad, size_t aad_len, uint64_t pn,
1404 struct quic_tls_ctx *tls_ctx, struct quic_conn *qc)
1405{
1406 int ret = 0;
1407 unsigned char iv[QUIC_TLS_IV_LEN];
1408 unsigned char *tx_iv = tls_ctx->tx.iv;
1409 size_t tx_iv_sz = tls_ctx->tx.ivlen;
1410 struct enc_debug_info edi;
1411
1412 TRACE_ENTER(QUIC_EV_CONN_ENCPKT, qc);
1413
1414 if (!quic_aead_iv_build(iv, sizeof iv, tx_iv, tx_iv_sz, pn)) {
1415 TRACE_ERROR("AEAD IV building for encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1416 goto err;
1417 }
1418
1419 if (!quic_tls_encrypt(payload, payload_len, aad, aad_len,
1420 tls_ctx->tx.ctx, tls_ctx->tx.aead, tls_ctx->tx.key, iv)) {
1421 TRACE_ERROR("QUIC packet encryption failed", QUIC_EV_CONN_ENCPKT, qc);
1422 goto err;
1423 }
1424
1425 ret = 1;
1426 leave:
1427 TRACE_LEAVE(QUIC_EV_CONN_ENCPKT, qc);
1428 return ret;
1429
1430 err:
1431 enc_debug_info_init(&edi, payload, payload_len, aad, aad_len, pn);
1432 goto leave;
1433}
1434
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001435/* Decrypt <pkt> packet using encryption level <qel> for <qc> connection.
1436 * Decryption is done in place in packet buffer.
1437 *
Ilya Shipitsin5fa29b82022-12-07 09:46:19 +05001438 * Returns 1 on success else 0.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001439 */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001440static int qc_pkt_decrypt(struct quic_conn *qc, struct quic_enc_level *qel,
1441 struct quic_rx_packet *pkt)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001442{
1443 int ret, kp_changed;
1444 unsigned char iv[QUIC_TLS_IV_LEN];
1445 struct quic_tls_ctx *tls_ctx = &qel->tls_ctx;
1446 EVP_CIPHER_CTX *rx_ctx = tls_ctx->rx.ctx;
1447 unsigned char *rx_iv = tls_ctx->rx.iv;
1448 size_t rx_iv_sz = tls_ctx->rx.ivlen;
1449 unsigned char *rx_key = tls_ctx->rx.key;
1450
1451 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
1452
1453 ret = 0;
1454 kp_changed = 0;
1455
1456 if (pkt->type == QUIC_PACKET_TYPE_SHORT) {
1457 /* The two tested bits are not at the same position,
1458 * this is why they are first both inversed.
1459 */
1460 if (!(*pkt->data & QUIC_PACKET_KEY_PHASE_BIT) ^ !(tls_ctx->flags & QUIC_FL_TLS_KP_BIT_SET)) {
1461 if (pkt->pn < tls_ctx->rx.pn) {
1462 /* The lowest packet number of a previous key phase
1463 * cannot be null if it really stores previous key phase
1464 * secrets.
1465 */
1466 // TODO: check if BUG_ON() more suitable
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001467 if (!qc->ku.prv_rx.pn) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001468 TRACE_ERROR("null previous packet number", QUIC_EV_CONN_RXPKT, qc);
1469 goto leave;
1470 }
1471
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001472 rx_ctx = qc->ku.prv_rx.ctx;
1473 rx_iv = qc->ku.prv_rx.iv;
1474 rx_key = qc->ku.prv_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001475 }
1476 else if (pkt->pn > qel->pktns->rx.largest_pn) {
1477 /* Next key phase */
1478 kp_changed = 1;
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001479 rx_ctx = qc->ku.nxt_rx.ctx;
1480 rx_iv = qc->ku.nxt_rx.iv;
1481 rx_key = qc->ku.nxt_rx.key;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001482 }
1483 }
1484 }
1485
1486 if (!quic_aead_iv_build(iv, sizeof iv, rx_iv, rx_iv_sz, pkt->pn)) {
1487 TRACE_ERROR("quic_aead_iv_build() failed", QUIC_EV_CONN_RXPKT, qc);
1488 goto leave;
1489 }
1490
1491 ret = quic_tls_decrypt(pkt->data + pkt->aad_len, pkt->len - pkt->aad_len,
1492 pkt->data, pkt->aad_len,
1493 rx_ctx, tls_ctx->rx.aead, rx_key, iv);
1494 if (!ret) {
1495 TRACE_ERROR("quic_tls_decrypt() failed", QUIC_EV_CONN_RXPKT, qc);
1496 goto leave;
1497 }
1498
1499 /* Update the keys only if the packet decryption succeeded. */
1500 if (kp_changed) {
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001501 quic_tls_rotate_keys(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001502 /* Toggle the Key Phase bit */
1503 tls_ctx->flags ^= QUIC_FL_TLS_KP_BIT_SET;
1504 /* Store the lowest packet number received for the current key phase */
1505 tls_ctx->rx.pn = pkt->pn;
1506 /* Prepare the next key update */
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01001507 if (!quic_tls_key_update(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001508 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_RXPKT, qc);
1509 goto leave;
1510 }
1511 }
1512
1513 /* Update the packet length (required to parse the frames). */
1514 pkt->len -= QUIC_TLS_TAG_LEN;
1515 ret = 1;
1516 leave:
1517 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
1518 return ret;
1519}
1520
1521
1522/* Remove references to <frm> frame */
1523static void qc_frm_unref(struct quic_conn *qc, struct quic_frame *frm)
1524{
1525 struct quic_frame *f, *tmp;
1526
1527 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1528
1529 list_for_each_entry_safe(f, tmp, &frm->reflist, ref) {
1530 f->origin = NULL;
1531 LIST_DELETE(&f->ref);
1532 if (f->pkt) {
1533 TRACE_DEVEL("remove frame reference",
1534 QUIC_EV_CONN_PRSAFRM, qc, f, &f->pkt->pn_node.key);
1535 }
1536 else {
1537 TRACE_DEVEL("remove frame reference for unsent frame",
1538 QUIC_EV_CONN_PRSAFRM, qc, f);
1539 }
1540 }
1541
1542 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1543}
1544
1545/* Release <frm> frame and mark its copies as acknowledged */
1546void qc_release_frm(struct quic_conn *qc, struct quic_frame *frm)
1547{
1548 uint64_t pn;
1549 struct quic_frame *origin, *f, *tmp;
1550
1551 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1552
1553 /* Identify this frame: a frame copy or one of its copies */
1554 origin = frm->origin ? frm->origin : frm;
1555 /* Ensure the source of the copies is flagged as acked, <frm> being
1556 * possibly a copy of <origin>
1557 */
1558 origin->flags |= QUIC_FL_TX_FRAME_ACKED;
1559 /* Mark all the copy of <origin> as acknowledged. We must
1560 * not release the packets (releasing the frames) at this time as
1561 * they are possibly also to be acknowledged alongside the
1562 * the current one.
1563 */
1564 list_for_each_entry_safe(f, tmp, &origin->reflist, ref) {
1565 if (f->pkt) {
1566 f->flags |= QUIC_FL_TX_FRAME_ACKED;
1567 f->origin = NULL;
1568 LIST_DELETE(&f->ref);
1569 pn = f->pkt->pn_node.key;
1570 TRACE_DEVEL("mark frame as acked from packet",
1571 QUIC_EV_CONN_PRSAFRM, qc, f, &pn);
1572 }
1573 else {
1574 TRACE_DEVEL("freeing unsent frame",
1575 QUIC_EV_CONN_PRSAFRM, qc, f);
1576 LIST_DELETE(&f->ref);
1577 LIST_DELETE(&f->list);
1578 pool_free(pool_head_quic_frame, f);
1579 }
1580 }
1581 LIST_DELETE(&frm->list);
1582 pn = frm->pkt->pn_node.key;
1583 quic_tx_packet_refdec(frm->pkt);
1584 TRACE_DEVEL("freeing frame from packet",
1585 QUIC_EV_CONN_PRSAFRM, qc, frm, &pn);
1586 pool_free(pool_head_quic_frame, frm);
1587
1588 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1589}
1590
1591/* Schedule a CONNECTION_CLOSE emission on <qc> if the MUX has been released
1592 * and all STREAM data are acknowledged. The MUX is responsible to have set
1593 * <qc.err> before as it is reused for the CONNECTION_CLOSE frame.
1594 *
1595 * TODO this should also be called on lost packet detection
1596 */
1597void qc_check_close_on_released_mux(struct quic_conn *qc)
1598{
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001599 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
1600
1601 if (qc->mux_state == QC_MUX_RELEASED && eb_is_empty(&qc->streams_by_id)) {
1602 /* Reuse errcode which should have been previously set by the MUX on release. */
1603 quic_set_connection_close(qc, qc->err);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02001604 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001605 }
1606
1607 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
1608}
1609
1610/* Remove from <stream> the acknowledged frames.
1611 *
1612 * Returns 1 if at least one frame was removed else 0.
1613 */
1614static int quic_stream_try_to_consume(struct quic_conn *qc,
1615 struct qc_stream_desc *stream)
1616{
1617 int ret;
1618 struct eb64_node *frm_node;
1619
1620 TRACE_ENTER(QUIC_EV_CONN_ACKSTRM, qc);
1621
1622 ret = 0;
1623 frm_node = eb64_first(&stream->acked_frms);
1624 while (frm_node) {
1625 struct quic_stream *strm;
1626 struct quic_frame *frm;
1627 size_t offset, len;
1628
1629 strm = eb64_entry(frm_node, struct quic_stream, offset);
1630 offset = strm->offset.key;
1631 len = strm->len;
1632
1633 if (offset > stream->ack_offset)
1634 break;
1635
1636 if (qc_stream_desc_ack(&stream, offset, len)) {
1637 /* cf. next comment : frame may be freed at this stage. */
1638 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1639 qc, stream ? strm : NULL, stream);
1640 ret = 1;
1641 }
1642
1643 /* If stream is NULL after qc_stream_desc_ack(), it means frame
1644 * has been freed. with the stream frames tree. Nothing to do
1645 * anymore in here.
1646 */
1647 if (!stream) {
1648 qc_check_close_on_released_mux(qc);
1649 ret = 1;
1650 goto leave;
1651 }
1652
1653 frm_node = eb64_next(frm_node);
1654 eb64_delete(&strm->offset);
1655
1656 frm = container_of(strm, struct quic_frame, stream);
1657 qc_release_frm(qc, frm);
1658 }
1659
1660 leave:
1661 TRACE_LEAVE(QUIC_EV_CONN_ACKSTRM, qc);
1662 return ret;
1663}
1664
1665/* Treat <frm> frame whose packet it is attached to has just been acknowledged. */
1666static inline void qc_treat_acked_tx_frm(struct quic_conn *qc,
1667 struct quic_frame *frm)
1668{
1669 int stream_acked;
1670
1671 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc, frm);
1672
1673 stream_acked = 0;
1674 switch (frm->type) {
1675 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1676 {
1677 struct quic_stream *strm_frm = &frm->stream;
1678 struct eb64_node *node = NULL;
1679 struct qc_stream_desc *stream = NULL;
1680 const size_t offset = strm_frm->offset.key;
1681 const size_t len = strm_frm->len;
1682
1683 /* do not use strm_frm->stream as the qc_stream_desc instance
1684 * might be freed at this stage. Use the id to do a proper
1685 * lookup.
1686 *
1687 * TODO if lookup operation impact on the perf is noticeable,
1688 * implement a refcount on qc_stream_desc instances.
1689 */
1690 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1691 if (!node) {
1692 TRACE_DEVEL("acked stream for released stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm);
1693 qc_release_frm(qc, frm);
1694 /* early return */
1695 goto leave;
1696 }
1697 stream = eb64_entry(node, struct qc_stream_desc, by_id);
1698
1699 TRACE_DEVEL("acked stream", QUIC_EV_CONN_ACKSTRM, qc, strm_frm, stream);
1700 if (offset <= stream->ack_offset) {
1701 if (qc_stream_desc_ack(&stream, offset, len)) {
1702 stream_acked = 1;
1703 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1704 qc, strm_frm, stream);
1705 }
1706
1707 if (!stream) {
1708 /* no need to continue if stream freed. */
1709 TRACE_DEVEL("stream released and freed", QUIC_EV_CONN_ACKSTRM, qc);
1710 qc_release_frm(qc, frm);
1711 qc_check_close_on_released_mux(qc);
1712 break;
1713 }
1714
1715 TRACE_DEVEL("stream consumed", QUIC_EV_CONN_ACKSTRM,
1716 qc, strm_frm, stream);
1717 qc_release_frm(qc, frm);
1718 }
1719 else {
1720 eb64_insert(&stream->acked_frms, &strm_frm->offset);
1721 }
1722
1723 stream_acked |= quic_stream_try_to_consume(qc, stream);
1724 }
1725 break;
1726 default:
1727 qc_release_frm(qc, frm);
1728 }
1729
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02001730 if (stream_acked) {
1731 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
1732 tasklet_wakeup(qc->subs->tasklet);
1733 qc->subs->events &= ~SUB_RETRY_SEND;
1734 if (!qc->subs->events)
1735 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001736 }
1737 }
1738 leave:
1739 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1740}
1741
1742/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1743 * deallocating them, and their TX frames.
1744 * Returns the last node reached to be used for the next range.
1745 * May be NULL if <largest> node could not be found.
1746 */
1747static inline struct eb64_node *qc_ackrng_pkts(struct quic_conn *qc,
1748 struct eb_root *pkts,
1749 unsigned int *pkt_flags,
1750 struct list *newly_acked_pkts,
1751 struct eb64_node *largest_node,
1752 uint64_t largest, uint64_t smallest)
1753{
1754 struct eb64_node *node;
1755 struct quic_tx_packet *pkt;
1756
1757 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1758
1759 node = largest_node ? largest_node : eb64_lookup_le(pkts, largest);
1760 while (node && node->key >= smallest) {
1761 struct quic_frame *frm, *frmbak;
1762
1763 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
1764 *pkt_flags |= pkt->flags;
1765 LIST_INSERT(newly_acked_pkts, &pkt->list);
1766 TRACE_DEVEL("Removing packet #", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
1767 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1768 qc_treat_acked_tx_frm(qc, frm);
Frédéric Lécaille814645f2022-11-18 18:15:28 +01001769 /* If there are others packet in the same datagram <pkt> is attached to,
1770 * detach the previous one and the next one from <pkt>.
1771 */
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01001772 quic_tx_packet_dgram_detach(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02001773 node = eb64_prev(node);
1774 eb64_delete(&pkt->pn_node);
1775 }
1776
1777 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1778 return node;
1779}
1780
1781/* Remove all frames from <pkt_frm_list> and reinsert them in the
1782 * same order they have been sent into <pktns_frm_list>.
1783 */
1784static inline void qc_requeue_nacked_pkt_tx_frms(struct quic_conn *qc,
1785 struct quic_tx_packet *pkt,
1786 struct list *pktns_frm_list)
1787{
1788 struct quic_frame *frm, *frmbak;
1789 struct list tmp = LIST_HEAD_INIT(tmp);
1790 struct list *pkt_frm_list = &pkt->frms;
1791 uint64_t pn = pkt->pn_node.key;
1792
1793 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1794
1795 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
1796 /* First remove this frame from the packet it was attached to */
1797 LIST_DELETE(&frm->list);
1798 quic_tx_packet_refdec(pkt);
1799 /* At this time, this frame is not freed but removed from its packet */
1800 frm->pkt = NULL;
1801 /* Remove any reference to this frame */
1802 qc_frm_unref(qc, frm);
1803 switch (frm->type) {
1804 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
1805 {
1806 struct quic_stream *strm_frm = &frm->stream;
1807 struct eb64_node *node = NULL;
1808 struct qc_stream_desc *stream_desc;
1809
1810 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
1811 if (!node) {
1812 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
1813 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1814 qc, frm, &pn);
1815 pool_free(pool_head_quic_frame, frm);
1816 continue;
1817 }
1818
1819 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
1820 /* Do not resend this frame if in the "already acked range" */
1821 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
1822 TRACE_DEVEL("ignored frame in already acked range",
1823 QUIC_EV_CONN_PRSAFRM, qc, frm);
1824 pool_free(pool_head_quic_frame, frm);
1825 continue;
1826 }
1827 else if (strm_frm->offset.key < stream_desc->ack_offset) {
1828 strm_frm->offset.key = stream_desc->ack_offset;
1829 TRACE_DEVEL("updated partially acked frame",
1830 QUIC_EV_CONN_PRSAFRM, qc, frm);
1831 }
1832 break;
1833 }
1834
1835 default:
1836 break;
1837 }
1838
1839 /* Do not resend probing packet with old data */
1840 if (pkt->flags & QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA) {
1841 TRACE_DEVEL("ignored frame with old data from packet", QUIC_EV_CONN_PRSAFRM,
1842 qc, frm, &pn);
1843 if (frm->origin)
1844 LIST_DELETE(&frm->ref);
1845 pool_free(pool_head_quic_frame, frm);
1846 continue;
1847 }
1848
1849 if (frm->flags & QUIC_FL_TX_FRAME_ACKED) {
1850 TRACE_DEVEL("already acked frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
1851 TRACE_DEVEL("freeing frame from packet", QUIC_EV_CONN_PRSAFRM,
1852 qc, frm, &pn);
1853 pool_free(pool_head_quic_frame, frm);
1854 }
1855 else {
1856 if (QUIC_FT_STREAM_8 <= frm->type && frm->type <= QUIC_FT_STREAM_F) {
1857 /* Mark this STREAM frame as lost. A look up their stream descriptor
1858 * will be performed to check the stream is not consumed or released.
1859 */
1860 frm->flags |= QUIC_FL_TX_FRAME_LOST;
1861 }
1862 LIST_APPEND(&tmp, &frm->list);
1863 TRACE_DEVEL("frame requeued", QUIC_EV_CONN_PRSAFRM, qc, frm);
1864 }
1865 }
1866
1867 LIST_SPLICE(pktns_frm_list, &tmp);
1868
1869 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1870}
1871
1872/* Free <pkt> TX packet and its attached frames.
1873 * This is the responsibility of the caller to remove this packet of
1874 * any data structure it was possibly attached to.
1875 */
1876static inline void free_quic_tx_packet(struct quic_conn *qc,
1877 struct quic_tx_packet *pkt)
1878{
1879 struct quic_frame *frm, *frmbak;
1880
1881 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1882
1883 if (!pkt)
1884 goto leave;
1885
1886 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list) {
1887 LIST_DELETE(&frm->list);
1888 pool_free(pool_head_quic_frame, frm);
1889 }
1890 pool_free(pool_head_quic_tx_packet, pkt);
1891
1892 leave:
1893 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1894}
1895
1896/* Free the TX packets of <pkts> list */
1897static inline void free_quic_tx_pkts(struct quic_conn *qc, struct list *pkts)
1898{
1899 struct quic_tx_packet *pkt, *tmp;
1900
1901 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
1902
1903 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1904 LIST_DELETE(&pkt->list);
1905 eb64_delete(&pkt->pn_node);
1906 free_quic_tx_packet(qc, pkt);
1907 }
1908
1909 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
1910}
1911
1912/* Remove already sent ranges of acknowledged packet numbers from
1913 * <pktns> packet number space tree below <largest_acked_pn> possibly
1914 * updating the range which contains <largest_acked_pn>.
1915 * Never fails.
1916 */
1917static void qc_treat_ack_of_ack(struct quic_conn *qc,
1918 struct quic_pktns *pktns,
1919 int64_t largest_acked_pn)
1920{
1921 struct eb64_node *ar, *next_ar;
1922 struct quic_arngs *arngs = &pktns->rx.arngs;
1923
1924 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1925
1926 ar = eb64_first(&arngs->root);
1927 while (ar) {
1928 struct quic_arng_node *ar_node;
1929
1930 next_ar = eb64_next(ar);
1931 ar_node = eb64_entry(ar, struct quic_arng_node, first);
1932
1933 if ((int64_t)ar_node->first.key > largest_acked_pn) {
1934 TRACE_DEVEL("first.key > largest", QUIC_EV_CONN_PRSAFRM, qc);
1935 break;
1936 }
1937
1938 if (largest_acked_pn < ar_node->last) {
1939 eb64_delete(ar);
1940 ar_node->first.key = largest_acked_pn + 1;
1941 eb64_insert(&arngs->root, ar);
1942 break;
1943 }
1944
1945 eb64_delete(ar);
1946 pool_free(pool_head_quic_arng, ar_node);
1947 arngs->sz--;
1948 ar = next_ar;
1949 }
1950
1951 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1952}
1953
1954/* Send a packet ack event nofication for each newly acked packet of
1955 * <newly_acked_pkts> list and free them.
1956 * Always succeeds.
1957 */
1958static inline void qc_treat_newly_acked_pkts(struct quic_conn *qc,
1959 struct list *newly_acked_pkts)
1960{
1961 struct quic_tx_packet *pkt, *tmp;
1962 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
1963
1964 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
1965
1966 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
1967 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
1968 qc->path->prep_in_flight -= pkt->in_flight_len;
1969 qc->path->in_flight -= pkt->in_flight_len;
1970 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
1971 qc->path->ifae_pkts--;
1972 /* If this packet contained an ACK frame, proceed to the
1973 * acknowledging of range of acks from the largest acknowledged
1974 * packet number which was sent in an ACK frame by this packet.
1975 */
1976 if (pkt->largest_acked_pn != -1)
1977 qc_treat_ack_of_ack(qc, pkt->pktns, pkt->largest_acked_pn);
1978 ev.ack.acked = pkt->in_flight_len;
1979 ev.ack.time_sent = pkt->time_sent;
1980 quic_cc_event(&qc->path->cc, &ev);
1981 LIST_DELETE(&pkt->list);
1982 eb64_delete(&pkt->pn_node);
1983 quic_tx_packet_refdec(pkt);
1984 }
1985
1986 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
1987
1988}
1989
1990/* Release all the frames attached to <pktns> packet number space */
1991static inline void qc_release_pktns_frms(struct quic_conn *qc,
1992 struct quic_pktns *pktns)
1993{
1994 struct quic_frame *frm, *frmbak;
1995
1996 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
1997
1998 list_for_each_entry_safe(frm, frmbak, &pktns->tx.frms, list) {
1999 LIST_DELETE(&frm->list);
2000 pool_free(pool_head_quic_frame, frm);
2001 }
2002
2003 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
2004}
2005
2006/* Handle <pkts> list of lost packets detected at <now_us> handling
2007 * their TX frames.
2008 * Send a packet loss event to the congestion controller if
2009 * in flight packet have been lost.
2010 * Also frees the packet in <pkts> list.
2011 * Never fails.
2012 */
2013static inline void qc_release_lost_pkts(struct quic_conn *qc,
2014 struct quic_pktns *pktns,
2015 struct list *pkts,
2016 uint64_t now_us)
2017{
2018 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
2019
2020 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2021
2022 if (LIST_ISEMPTY(pkts))
2023 goto leave;
2024
2025 oldest_lost = newest_lost = NULL;
2026 list_for_each_entry_safe(pkt, tmp, pkts, list) {
2027 struct list tmp = LIST_HEAD_INIT(tmp);
2028
2029 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
2030 qc->path->prep_in_flight -= pkt->in_flight_len;
2031 qc->path->in_flight -= pkt->in_flight_len;
2032 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
2033 qc->path->ifae_pkts--;
2034 /* Treat the frames of this lost packet. */
2035 qc_requeue_nacked_pkt_tx_frms(qc, pkt, &pktns->tx.frms);
2036 LIST_DELETE(&pkt->list);
2037 if (!oldest_lost) {
2038 oldest_lost = newest_lost = pkt;
2039 }
2040 else {
2041 if (newest_lost != oldest_lost)
2042 quic_tx_packet_refdec(newest_lost);
2043 newest_lost = pkt;
2044 }
2045 }
2046
2047 if (newest_lost) {
2048 /* Sent a congestion event to the controller */
2049 struct quic_cc_event ev = { };
2050
2051 ev.type = QUIC_CC_EVT_LOSS;
2052 ev.loss.time_sent = newest_lost->time_sent;
2053
2054 quic_cc_event(&qc->path->cc, &ev);
2055 }
2056
2057 /* If an RTT have been already sampled, <rtt_min> has been set.
2058 * We must check if we are experiencing a persistent congestion.
2059 * If this is the case, the congestion controller must re-enter
2060 * slow start state.
2061 */
2062 if (qc->path->loss.rtt_min && newest_lost != oldest_lost) {
2063 unsigned int period = newest_lost->time_sent - oldest_lost->time_sent;
2064
2065 if (quic_loss_persistent_congestion(&qc->path->loss, period,
2066 now_ms, qc->max_ack_delay))
2067 qc->path->cc.algo->slow_start(&qc->path->cc);
2068 }
2069
Amaury Denoyelle3a72ba22022-11-14 11:41:34 +01002070 /* <oldest_lost> cannot be NULL at this stage because we have ensured
2071 * that <pkts> list is not empty. Without this, GCC 12.2.0 reports a
2072 * possible overflow on a 0 byte region with O2 optimization.
2073 */
2074 ALREADY_CHECKED(oldest_lost);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002075 quic_tx_packet_refdec(oldest_lost);
2076 if (newest_lost != oldest_lost)
2077 quic_tx_packet_refdec(newest_lost);
2078
2079 leave:
2080 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2081}
2082
2083/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
2084 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
2085 * if the largest acked packet was newly acked and if there was at least one newly
2086 * acked ack-eliciting packet.
2087 * Return 1, if succeeded, 0 if not.
2088 */
2089static inline int qc_parse_ack_frm(struct quic_conn *qc,
2090 struct quic_frame *frm,
2091 struct quic_enc_level *qel,
2092 unsigned int *rtt_sample,
2093 const unsigned char **pos, const unsigned char *end)
2094{
2095 struct quic_ack *ack = &frm->ack;
2096 uint64_t smallest, largest;
2097 struct eb_root *pkts;
2098 struct eb64_node *largest_node;
2099 unsigned int time_sent, pkt_flags;
2100 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
2101 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2102 int ret = 0;
2103
2104 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2105
2106 if (ack->largest_ack > qel->pktns->tx.next_pn) {
2107 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
2108 qc, NULL, &ack->largest_ack);
2109 goto err;
2110 }
2111
2112 if (ack->first_ack_range > ack->largest_ack) {
2113 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
2114 qc, NULL, &ack->first_ack_range);
2115 goto err;
2116 }
2117
2118 largest = ack->largest_ack;
2119 smallest = largest - ack->first_ack_range;
2120 pkts = &qel->pktns->tx.pkts;
2121 pkt_flags = 0;
2122 largest_node = NULL;
2123 time_sent = 0;
2124
2125 if ((int64_t)ack->largest_ack > qel->pktns->rx.largest_acked_pn) {
2126 largest_node = eb64_lookup(pkts, largest);
2127 if (!largest_node) {
2128 TRACE_DEVEL("Largest acked packet not found",
2129 QUIC_EV_CONN_PRSAFRM, qc);
2130 }
2131 else {
2132 time_sent = eb64_entry(largest_node,
2133 struct quic_tx_packet, pn_node)->time_sent;
2134 }
2135 }
2136
2137 TRACE_PROTO("rcvd ack range", QUIC_EV_CONN_PRSAFRM,
2138 qc, NULL, &largest, &smallest);
2139 do {
2140 uint64_t gap, ack_range;
2141
2142 qc_ackrng_pkts(qc, pkts, &pkt_flags, &newly_acked_pkts,
2143 largest_node, largest, smallest);
2144 if (!ack->ack_range_num--)
2145 break;
2146
2147 if (!quic_dec_int(&gap, pos, end)) {
2148 TRACE_ERROR("quic_dec_int(gap) failed", QUIC_EV_CONN_PRSAFRM, qc);
2149 goto err;
2150 }
2151
2152 if (smallest < gap + 2) {
2153 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
2154 qc, NULL, &gap, &smallest);
2155 goto err;
2156 }
2157
2158 largest = smallest - gap - 2;
2159 if (!quic_dec_int(&ack_range, pos, end)) {
2160 TRACE_ERROR("quic_dec_int(ack_range) failed", QUIC_EV_CONN_PRSAFRM, qc);
2161 goto err;
2162 }
2163
2164 if (largest < ack_range) {
2165 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
2166 qc, NULL, &largest, &ack_range);
2167 goto err;
2168 }
2169
2170 /* Do not use this node anymore. */
2171 largest_node = NULL;
2172 /* Next range */
2173 smallest = largest - ack_range;
2174
2175 TRACE_PROTO("rcvd next ack range", QUIC_EV_CONN_PRSAFRM,
2176 qc, NULL, &largest, &smallest);
2177 } while (1);
2178
2179 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
2180 *rtt_sample = tick_remain(time_sent, now_ms);
2181 qel->pktns->rx.largest_acked_pn = ack->largest_ack;
2182 }
2183
2184 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
2185 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
2186 qc_packet_loss_lookup(qel->pktns, qc, &lost_pkts);
2187 qc_release_lost_pkts(qc, qel->pktns, &lost_pkts, now_ms);
2188 }
2189 qc_treat_newly_acked_pkts(qc, &newly_acked_pkts);
2190 if (quic_peer_validated_addr(qc))
2191 qc->path->loss.pto_count = 0;
2192 qc_set_timer(qc);
2193 }
2194
2195 ret = 1;
2196 leave:
2197 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2198 return ret;
2199
2200 err:
2201 free_quic_tx_pkts(qc, &newly_acked_pkts);
2202 goto leave;
2203}
2204
2205/* This function gives the detail of the SSL error. It is used only
2206 * if the debug mode and the verbose mode are activated. It dump all
2207 * the SSL error until the stack was empty.
2208 */
2209static forceinline void qc_ssl_dump_errors(struct connection *conn)
2210{
2211 if (unlikely(global.mode & MODE_DEBUG)) {
2212 while (1) {
2213 const char *func = NULL;
2214 unsigned long ret;
2215
2216 ERR_peek_error_func(&func);
2217 ret = ERR_get_error();
2218 if (!ret)
2219 return;
2220
2221 fprintf(stderr, "conn. @%p OpenSSL error[0x%lx] %s: %s\n", conn, ret,
2222 func, ERR_reason_error_string(ret));
2223 }
2224 }
2225}
2226
2227int ssl_sock_get_alpn(const struct connection *conn, void *xprt_ctx,
2228 const char **str, int *len);
2229
2230/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
2231 * from <qel> encryption level with <ctx> as QUIC connection context.
2232 * Remaining parameter are there for debugging purposes.
2233 * Return 1 if succeeded, 0 if not.
2234 */
2235static inline int qc_provide_cdata(struct quic_enc_level *el,
2236 struct ssl_sock_ctx *ctx,
2237 const unsigned char *data, size_t len,
2238 struct quic_rx_packet *pkt,
2239 struct quic_rx_crypto_frm *cf)
2240{
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002241#ifdef DEBUG_STRICT
2242 enum ncb_ret ncb_ret;
2243#endif
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002244 int ssl_err, state;
2245 struct quic_conn *qc;
2246 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002247 struct ncbuf *ncbuf = &el->cstream->rx.ncbuf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002248
2249 ssl_err = SSL_ERROR_NONE;
2250 qc = ctx->qc;
2251
2252 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, qc);
2253
2254 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
2255 TRACE_ERROR("SSL_provide_quic_data() error",
2256 QUIC_EV_CONN_SSLDATA, qc, pkt, cf, ctx->ssl);
2257 goto leave;
2258 }
2259
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002260 TRACE_PROTO("in order CRYPTO data",
2261 QUIC_EV_CONN_SSLDATA, qc, NULL, cf, ctx->ssl);
2262
2263 state = qc->state;
2264 if (state < QUIC_HS_ST_COMPLETE) {
2265 ssl_err = SSL_do_handshake(ctx->ssl);
2266 if (ssl_err != 1) {
2267 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2268 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2269 TRACE_PROTO("SSL handshake in progress",
2270 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2271 goto out;
2272 }
2273
2274 /* TODO: Should close the connection asap */
2275 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2276 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2277 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2278 HA_ATOMIC_INC(&qc->prx_counters->hdshk_fail);
2279 }
2280 TRACE_ERROR("SSL handshake error", QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2281 qc_ssl_dump_errors(ctx->conn);
2282 ERR_clear_error();
2283 goto leave;
2284 }
2285
2286 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_IO_CB, qc, &state);
2287
2288 /* Check the alpn could be negotiated */
2289 if (!qc->app_ops) {
2290 TRACE_ERROR("No negotiated ALPN", QUIC_EV_CONN_IO_CB, qc, &state);
2291 quic_set_tls_alert(qc, SSL_AD_NO_APPLICATION_PROTOCOL);
2292 goto leave;
2293 }
2294
2295 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2296 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_IO_CB, qc, &state);
2297 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2298 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2299 }
2300 /* I/O callback switch */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002301 qc->wait_event.tasklet->process = quic_conn_app_io_cb;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002302 if (qc_is_listener(ctx->qc)) {
2303 qc->state = QUIC_HS_ST_CONFIRMED;
2304 /* The connection is ready to be accepted. */
2305 quic_accept_push_qc(qc);
2306 }
2307 else {
2308 qc->state = QUIC_HS_ST_COMPLETE;
2309 }
2310
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02002311 /* Prepare the next key update */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002312 if (!quic_tls_key_update(qc)) {
2313 TRACE_ERROR("quic_tls_key_update() failed", QUIC_EV_CONN_IO_CB, qc);
2314 goto leave;
2315 }
2316 } else {
2317 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
2318 if (ssl_err != 1) {
2319 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
2320 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2321 TRACE_PROTO("SSL post handshake in progress",
2322 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2323 goto out;
2324 }
2325
2326 TRACE_ERROR("SSL post handshake error",
2327 QUIC_EV_CONN_IO_CB, qc, &state, &ssl_err);
2328 goto leave;
2329 }
2330
2331 TRACE_STATE("SSL post handshake succeeded", QUIC_EV_CONN_IO_CB, qc, &state);
2332 }
2333
2334 out:
2335 ret = 1;
2336 leave:
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002337 /* The CRYPTO data are consumed even in case of an error to release
2338 * the memory asap.
2339 */
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002340 if (!ncb_is_null(ncbuf)) {
2341#ifdef DEBUG_STRICT
2342 ncb_ret = ncb_advance(ncbuf, len);
2343 /* ncb_advance() must always succeed. This is guaranteed as
2344 * this is only done inside a data block. If false, this will
2345 * lead to handshake failure with quic_enc_level offset shifted
2346 * from buffer data.
2347 */
2348 BUG_ON(ncb_ret != NCB_RET_OK);
2349#else
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002350 ncb_advance(ncbuf, len);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002351#endif
2352 }
2353
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002354 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, qc);
2355 return ret;
2356}
2357
2358/* Parse a STREAM frame <strm_frm>
2359 *
2360 * Return 1 on success. On error, 0 is returned. In this case, the packet
2361 * containing the frame must not be acknowledged.
2362 */
2363static inline int qc_handle_strm_frm(struct quic_rx_packet *pkt,
2364 struct quic_stream *strm_frm,
2365 struct quic_conn *qc)
2366{
2367 int ret;
2368
2369 /* RFC9000 13.1. Packet Processing
2370 *
2371 * A packet MUST NOT be acknowledged until packet protection has been
2372 * successfully removed and all frames contained in the packet have
2373 * been processed. For STREAM frames, this means the data has been
2374 * enqueued in preparation to be received by the application protocol,
2375 * but it does not require that data be delivered and consumed.
2376 */
2377 TRACE_ENTER(QUIC_EV_CONN_PRSFRM, qc);
2378
2379 ret = qcc_recv(qc->qcc, strm_frm->id, strm_frm->len,
2380 strm_frm->offset.key, strm_frm->fin,
2381 (char *)strm_frm->data);
2382
2383 /* frame rejected - packet must not be acknowledeged */
2384 TRACE_LEAVE(QUIC_EV_CONN_PRSFRM, qc);
2385 return !ret;
2386}
2387
2388/* Duplicate all frames from <pkt_frm_list> list into <out_frm_list> list
2389 * for <qc> QUIC connection.
2390 * This is a best effort function which never fails even if no memory could be
2391 * allocated to duplicate these frames.
2392 */
2393static void qc_dup_pkt_frms(struct quic_conn *qc,
2394 struct list *pkt_frm_list, struct list *out_frm_list)
2395{
2396 struct quic_frame *frm, *frmbak;
2397 struct list tmp = LIST_HEAD_INIT(tmp);
2398
2399 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2400
2401 list_for_each_entry_safe(frm, frmbak, pkt_frm_list, list) {
2402 struct quic_frame *dup_frm, *origin;
2403
2404 switch (frm->type) {
2405 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2406 {
2407 struct quic_stream *strm_frm = &frm->stream;
2408 struct eb64_node *node = NULL;
2409 struct qc_stream_desc *stream_desc;
2410
2411 node = eb64_lookup(&qc->streams_by_id, strm_frm->id);
2412 if (!node) {
2413 TRACE_DEVEL("ignored frame for a released stream", QUIC_EV_CONN_PRSAFRM, qc, frm);
2414 continue;
2415 }
2416
2417 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
2418 /* Do not resend this frame if in the "already acked range" */
2419 if (strm_frm->offset.key + strm_frm->len <= stream_desc->ack_offset) {
2420 TRACE_DEVEL("ignored frame in already acked range",
2421 QUIC_EV_CONN_PRSAFRM, qc, frm);
2422 continue;
2423 }
2424 else if (strm_frm->offset.key < stream_desc->ack_offset) {
2425 strm_frm->offset.key = stream_desc->ack_offset;
2426 TRACE_DEVEL("updated partially acked frame",
2427 QUIC_EV_CONN_PRSAFRM, qc, frm);
2428 }
2429 break;
2430 }
2431
2432 default:
2433 break;
2434 }
2435
2436 dup_frm = pool_alloc(pool_head_quic_frame);
2437 if (!dup_frm) {
2438 TRACE_ERROR("could not duplicate frame", QUIC_EV_CONN_PRSAFRM, qc, frm);
2439 break;
2440 }
2441
2442 /* If <frm> is already a copy of another frame, we must take
2443 * its original frame as source for the copy.
2444 */
2445 origin = frm->origin ? frm->origin : frm;
2446 TRACE_DEVEL("built probing frame", QUIC_EV_CONN_PRSAFRM, qc, origin);
2447 if (origin->pkt)
2448 TRACE_DEVEL("duplicated from packet", QUIC_EV_CONN_PRSAFRM,
2449 qc, NULL, &origin->pkt->pn_node.key);
2450 else {
2451 /* <origin> is a frame which was sent from a packet detected as lost. */
2452 TRACE_DEVEL("duplicated from lost packet", QUIC_EV_CONN_PRSAFRM, qc);
2453 }
2454 *dup_frm = *origin;
2455 dup_frm->pkt = NULL;
2456 dup_frm->origin = origin;
2457 dup_frm->flags = 0;
2458 LIST_INIT(&dup_frm->reflist);
2459 LIST_APPEND(&origin->reflist, &dup_frm->ref);
2460 LIST_APPEND(&tmp, &dup_frm->list);
2461 }
2462
2463 LIST_SPLICE(out_frm_list, &tmp);
2464
2465 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2466}
2467
2468/* Prepare a fast retransmission from <qel> encryption level */
2469static void qc_prep_fast_retrans(struct quic_conn *qc,
2470 struct quic_enc_level *qel,
2471 struct list *frms1, struct list *frms2)
2472{
2473 struct eb_root *pkts = &qel->pktns->tx.pkts;
2474 struct list *frms = frms1;
2475 struct eb64_node *node;
2476 struct quic_tx_packet *pkt;
2477
2478 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2479
2480 BUG_ON(frms1 == frms2);
2481
2482 pkt = NULL;
2483 node = eb64_first(pkts);
2484 start:
2485 while (node) {
2486 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
2487 node = eb64_next(node);
2488 /* Skip the empty and coalesced packets */
2489 if (!LIST_ISEMPTY(&pkt->frms) && !(pkt->flags & QUIC_FL_TX_PACKET_COALESCED))
2490 break;
2491 }
2492
2493 if (!pkt)
2494 goto leave;
2495
2496 /* When building a packet from another one, the field which may increase the
2497 * packet size is the packet number. And the maximum increase is 4 bytes.
2498 */
2499 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2500 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
2501 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_SPPKTS, qc, pkt);
2502 goto leave;
2503 }
2504
2505 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_SPPKTS, qc, pkt);
2506 qc_dup_pkt_frms(qc, &pkt->frms, frms);
2507 if (frms == frms1 && frms2) {
2508 frms = frms2;
2509 goto start;
2510 }
2511 leave:
2512 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
2513}
2514
2515/* Prepare a fast retransmission during a handshake after a client
2516 * has resent Initial packets. According to the RFC a server may retransmit
2517 * Initial packets send them coalescing with others (Handshake here).
2518 * (Listener only function).
2519 */
2520static void qc_prep_hdshk_fast_retrans(struct quic_conn *qc,
2521 struct list *ifrms, struct list *hfrms)
2522{
2523 struct list itmp = LIST_HEAD_INIT(itmp);
2524 struct list htmp = LIST_HEAD_INIT(htmp);
2525
2526 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2527 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2528 struct quic_enc_level *qel = iqel;
2529 struct eb_root *pkts;
2530 struct eb64_node *node;
2531 struct quic_tx_packet *pkt;
2532 struct list *tmp = &itmp;
2533
2534 TRACE_ENTER(QUIC_EV_CONN_PRSAFRM, qc);
2535 start:
2536 pkt = NULL;
2537 pkts = &qel->pktns->tx.pkts;
2538 node = eb64_first(pkts);
2539 /* Skip the empty packet (they have already been retransmitted) */
2540 while (node) {
2541 pkt = eb64_entry(node, struct quic_tx_packet, pn_node);
2542 if (!LIST_ISEMPTY(&pkt->frms) && !(pkt->flags & QUIC_FL_TX_PACKET_COALESCED))
2543 break;
2544 node = eb64_next(node);
2545 }
2546
2547 if (!pkt)
2548 goto end;
2549
2550 /* When building a packet from another one, the field which may increase the
2551 * packet size is the packet number. And the maximum increase is 4 bytes.
2552 */
2553 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc) &&
2554 pkt->len + 4 > 3 * qc->rx.bytes - qc->tx.prep_bytes) {
2555 TRACE_PROTO("anti-amplification limit would be reached", QUIC_EV_CONN_PRSAFRM, qc);
2556 goto end;
2557 }
2558
2559 qel->pktns->tx.pto_probe += 1;
2560
2561 /* No risk to loop here, #packet per datagram is bounded */
2562 requeue:
2563 TRACE_DEVEL("duplicating packet", QUIC_EV_CONN_PRSAFRM, qc, NULL, &pkt->pn_node.key);
2564 qc_dup_pkt_frms(qc, &pkt->frms, tmp);
2565 if (qel == iqel) {
2566 if (pkt->next && pkt->next->type == QUIC_PACKET_TYPE_HANDSHAKE) {
2567 pkt = pkt->next;
2568 tmp = &htmp;
2569 hqel->pktns->tx.pto_probe += 1;
2570 TRACE_DEVEL("looping for next packet", QUIC_EV_CONN_PRSAFRM, qc);
2571 goto requeue;
2572 }
2573 }
2574
2575 end:
2576 LIST_SPLICE(ifrms, &itmp);
2577 LIST_SPLICE(hfrms, &htmp);
2578
2579 TRACE_LEAVE(QUIC_EV_CONN_PRSAFRM, qc);
2580}
2581
2582static void qc_cc_err_count_inc(struct quic_conn *qc, struct quic_frame *frm)
2583{
2584 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
2585
2586 if (frm->type == QUIC_FT_CONNECTION_CLOSE)
2587 quic_stats_transp_err_count_inc(qc->prx_counters, frm->connection_close.error_code);
2588 else if (frm->type == QUIC_FT_CONNECTION_CLOSE_APP) {
2589 if (qc->mux_state != QC_MUX_READY || !qc->qcc->app_ops->inc_err_cnt)
2590 goto out;
2591
2592 qc->qcc->app_ops->inc_err_cnt(qc->qcc->ctx, frm->connection_close_app.error_code);
2593 }
2594
2595 out:
2596 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
2597}
2598
2599/* Enqueue a STOP_SENDING frame to send into 1RTT packet number space
2600 * frame list to send.
2601 * Return 1 if succeeded, 0 if not.
2602 */
2603static int qc_stop_sending_frm_enqueue(struct quic_conn *qc, uint64_t id)
2604{
2605 int ret = 0;
2606 struct quic_frame *frm;
2607 struct quic_enc_level *qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
2608 uint64_t app_error_code;
2609
2610 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2611
2612 /* TODO: the mux may be released, we cannot have more
2613 * information about the application error code to send
2614 * at this time.
2615 */
2616 app_error_code = H3_REQUEST_REJECTED;
2617 // fixme: zalloc
2618 frm = pool_zalloc(pool_head_quic_frame);
2619 if (!frm) {
2620 TRACE_ERROR("failed to allocate quic_frame", QUIC_EV_CONN_PRSHPKT, qc);
2621 goto out;
2622 }
2623
2624 frm->type = QUIC_FT_STOP_SENDING;
2625 frm->stop_sending.id = id;
2626 frm->stop_sending.app_error_code = app_error_code;
2627 LIST_INIT(&frm->reflist);
2628 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
2629 ret = 1;
2630 out:
2631 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2632 return ret;
2633}
2634
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002635/* Release the underlying memory use by <ncbuf> non-contiguous buffer */
2636static void quic_free_ncbuf(struct ncbuf *ncbuf)
2637{
2638 struct buffer buf;
2639
2640 if (ncb_is_null(ncbuf))
2641 return;
2642
2643 buf = b_make(ncbuf->area, ncbuf->size, 0, 0);
2644 b_free(&buf);
2645 offer_buffers(NULL, 1);
2646
2647 *ncbuf = NCBUF_NULL;
2648}
2649
2650/* Allocate the underlying required memory for <ncbuf> non-contiguous buffer */
2651static struct ncbuf *quic_get_ncbuf(struct ncbuf *ncbuf)
2652{
2653 struct buffer buf = BUF_NULL;
2654
2655 if (!ncb_is_null(ncbuf))
2656 return ncbuf;
2657
2658 b_alloc(&buf);
2659 BUG_ON(b_is_null(&buf));
2660
2661 *ncbuf = ncb_make(buf.area, buf.size, 0);
2662 ncb_init(ncbuf, 0);
2663
2664 return ncbuf;
2665}
2666
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002667/* Parse <frm> CRYPTO frame coming with <pkt> packet at <qel> <qc> connectionn.
2668 * Returns 1 if succeeded, 0 if not. Also set <*fast_retrans> to 1 if the
2669 * speed up handshake completion may be run after having received duplicated
2670 * CRYPTO data.
2671 */
2672static int qc_handle_crypto_frm(struct quic_conn *qc,
2673 struct quic_crypto *frm, struct quic_rx_packet *pkt,
2674 struct quic_enc_level *qel, int *fast_retrans)
2675{
2676 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002677 enum ncb_ret ncb_ret;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002678 /* XXX TO DO: <cfdebug> is used only for the traces. */
2679 struct quic_rx_crypto_frm cfdebug = {
2680 .offset_node.key = frm->offset,
2681 .len = frm->len,
2682 };
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002683 struct quic_cstream *cstream = qel->cstream;
2684 struct ncbuf *ncbuf = &qel->cstream->rx.ncbuf;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002685
2686 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2687 if (unlikely(qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD)) {
2688 TRACE_PROTO("CRYPTO data discarded",
2689 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2690 goto done;
2691 }
2692
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002693 if (unlikely(frm->offset < cstream->rx.offset)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002694 size_t diff;
2695
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002696 if (frm->offset + frm->len <= cstream->rx.offset) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002697 /* Nothing to do */
2698 TRACE_PROTO("Already received CRYPTO data",
2699 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2700 if (qc_is_listener(qc) && qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] &&
2701 !(qc->flags & QUIC_FL_CONN_HANDSHAKE_SPEED_UP))
2702 *fast_retrans = 1;
2703 goto done;
2704 }
2705
2706 TRACE_PROTO("Partially already received CRYPTO data",
2707 QUIC_EV_CONN_RXPKT, qc, pkt, &cfdebug);
2708
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002709 diff = cstream->rx.offset - frm->offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002710 frm->len -= diff;
2711 frm->data += diff;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002712 frm->offset = cstream->rx.offset;
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002713 }
2714
Amaury Denoyelleff95f2d2022-11-18 14:50:06 +01002715 if (frm->offset == cstream->rx.offset && ncb_is_empty(ncbuf)) {
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002716 if (!qc_provide_cdata(qel, qc->xprt_ctx, frm->data, frm->len,
2717 pkt, &cfdebug)) {
2718 // trace already emitted by function above
2719 goto leave;
2720 }
2721
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002722 cstream->rx.offset += frm->len;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01002723 TRACE_DEVEL("increment crypto level offset", QUIC_EV_CONN_PHPKTS, qc, qel);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002724 goto done;
2725 }
2726
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002727 if (!quic_get_ncbuf(ncbuf) ||
2728 ncb_is_null(ncbuf)) {
2729 TRACE_ERROR("CRYPTO ncbuf allocation failed", QUIC_EV_CONN_PRSHPKT, qc);
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002730 goto leave;
2731 }
2732
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02002733 /* frm->offset > cstream-trx.offset */
2734 ncb_ret = ncb_add(ncbuf, frm->offset - cstream->rx.offset,
2735 (const char *)frm->data, frm->len, NCB_ADD_COMPARE);
2736 if (ncb_ret != NCB_RET_OK) {
2737 if (ncb_ret == NCB_RET_DATA_REJ) {
2738 TRACE_ERROR("overlapping data rejected", QUIC_EV_CONN_PRSHPKT, qc);
2739 quic_set_connection_close(qc, quic_err_transport(QC_ERR_PROTOCOL_VIOLATION));
2740 }
2741 else if (ncb_ret == NCB_RET_GAP_SIZE) {
2742 TRACE_ERROR("cannot bufferize frame due to gap size limit",
2743 QUIC_EV_CONN_PRSHPKT, qc);
2744 }
2745 goto leave;
2746 }
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002747
2748 done:
2749 ret = 1;
2750 leave:
2751 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2752 return ret;
2753}
2754
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002755/* Parse all the frames of <pkt> QUIC packet for QUIC connection <qc> and <qel>
2756 * as encryption level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002757 * Returns 1 if succeeded, 0 if failed.
2758 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002759static int qc_parse_pkt_frms(struct quic_conn *qc, struct quic_rx_packet *pkt,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002760 struct quic_enc_level *qel)
2761{
2762 struct quic_frame frm;
2763 const unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002764 int fast_retrans = 0, ret = 0;
2765
2766 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, qc);
2767 /* Skip the AAD */
2768 pos = pkt->data + pkt->aad_len;
2769 end = pkt->data + pkt->len;
2770
2771 while (pos < end) {
2772 if (!qc_parse_frm(&frm, pkt, &pos, end, qc)) {
2773 // trace already emitted by function above
2774 goto leave;
2775 }
2776
2777 TRACE_PROTO("RX frame", QUIC_EV_CONN_PSTRM, qc, &frm);
2778 switch (frm.type) {
2779 case QUIC_FT_PADDING:
2780 break;
2781 case QUIC_FT_PING:
2782 break;
2783 case QUIC_FT_ACK:
2784 {
2785 unsigned int rtt_sample;
2786
2787 rtt_sample = 0;
2788 if (!qc_parse_ack_frm(qc, &frm, qel, &rtt_sample, &pos, end)) {
2789 // trace already emitted by function above
2790 goto leave;
2791 }
2792
2793 if (rtt_sample) {
2794 unsigned int ack_delay;
2795
2796 ack_delay = !quic_application_pktns(qel->pktns, qc) ? 0 :
2797 qc->state >= QUIC_HS_ST_CONFIRMED ?
2798 MS_TO_TICKS(QUIC_MIN(quic_ack_delay_ms(&frm.ack, qc), qc->max_ack_delay)) :
2799 MS_TO_TICKS(quic_ack_delay_ms(&frm.ack, qc));
2800 quic_loss_srtt_update(&qc->path->loss, rtt_sample, ack_delay, qc);
2801 }
2802 break;
2803 }
2804 case QUIC_FT_RESET_STREAM:
Amaury Denoyelle5854fc02022-12-09 16:25:48 +01002805 if (qc->mux_state == QC_MUX_READY) {
2806 struct quic_reset_stream *rs = &frm.reset_stream;
2807 qcc_recv_reset_stream(qc->qcc, rs->id, rs->app_error_code, rs->final_size);
2808 }
2809 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002810 case QUIC_FT_STOP_SENDING:
2811 {
2812 struct quic_stop_sending *stop_sending = &frm.stop_sending;
2813 if (qc->mux_state == QC_MUX_READY) {
2814 if (qcc_recv_stop_sending(qc->qcc, stop_sending->id,
2815 stop_sending->app_error_code)) {
2816 TRACE_ERROR("qcc_recv_stop_sending() failed", QUIC_EV_CONN_PRSHPKT, qc);
2817 goto leave;
2818 }
2819 }
2820 break;
2821 }
2822 case QUIC_FT_CRYPTO:
Frédéric Lécaillea20c93e2022-09-12 14:54:45 +02002823 if (!qc_handle_crypto_frm(qc, &frm.crypto, pkt, qel, &fast_retrans))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002824 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002825 break;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002826 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
2827 {
2828 struct quic_stream *stream = &frm.stream;
2829 unsigned nb_streams = qc->rx.strms[qcs_id_type(stream->id)].nb_streams;
2830
2831 /* The upper layer may not be allocated. */
2832 if (qc->mux_state != QC_MUX_READY) {
2833 if ((stream->id >> QCS_ID_TYPE_SHIFT) < nb_streams) {
2834 TRACE_DATA("Already closed stream", QUIC_EV_CONN_PRSHPKT, qc);
2835 break;
2836 }
2837 else {
2838 TRACE_DEVEL("No mux for new stream", QUIC_EV_CONN_PRSHPKT, qc);
Frédéric Lécailled18025e2023-01-20 15:33:50 +01002839 if (qc->app_ops == &h3_ops && quic_stream_is_uni(stream->id)) {
2840 /* Do not send STOP_SENDING frames for h3 unidirectional streams.
2841 * TODO: this test should be removed when the connection closure
2842 * will be more clean.
2843 * At quic_conn level there is no mean to know that an application
2844 * want to forbid stream closure requests to receivers. This is the
2845 * case for the Control and QPACK h3 unidirectional streams.
2846 */
2847 goto leave;
2848 }
2849
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002850 if (!qc_stop_sending_frm_enqueue(qc, stream->id))
2851 TRACE_ERROR("could not enqueue STOP_SENDING frame", QUIC_EV_CONN_PRSHPKT, qc);
2852 /* This packet will not be acknowledged */
2853 goto leave;
2854 }
2855 }
2856
2857 if (!qc_handle_strm_frm(pkt, stream, qc)) {
2858 TRACE_ERROR("qc_handle_strm_frm() failed", QUIC_EV_CONN_PRSHPKT, qc);
2859 goto leave;
2860 }
2861
2862 break;
2863 }
2864 case QUIC_FT_MAX_DATA:
2865 if (qc->mux_state == QC_MUX_READY) {
2866 struct quic_max_data *data = &frm.max_data;
2867 qcc_recv_max_data(qc->qcc, data->max_data);
2868 }
2869 break;
2870 case QUIC_FT_MAX_STREAM_DATA:
2871 if (qc->mux_state == QC_MUX_READY) {
2872 struct quic_max_stream_data *data = &frm.max_stream_data;
2873 if (qcc_recv_max_stream_data(qc->qcc, data->id,
2874 data->max_stream_data)) {
2875 TRACE_ERROR("qcc_recv_max_stream_data() failed", QUIC_EV_CONN_PRSHPKT, qc);
2876 goto leave;
2877 }
2878 }
2879 break;
2880 case QUIC_FT_MAX_STREAMS_BIDI:
2881 case QUIC_FT_MAX_STREAMS_UNI:
2882 break;
2883 case QUIC_FT_DATA_BLOCKED:
2884 HA_ATOMIC_INC(&qc->prx_counters->data_blocked);
2885 break;
2886 case QUIC_FT_STREAM_DATA_BLOCKED:
2887 HA_ATOMIC_INC(&qc->prx_counters->stream_data_blocked);
2888 break;
2889 case QUIC_FT_STREAMS_BLOCKED_BIDI:
2890 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_bidi);
2891 break;
2892 case QUIC_FT_STREAMS_BLOCKED_UNI:
2893 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_uni);
2894 break;
2895 case QUIC_FT_NEW_CONNECTION_ID:
2896 case QUIC_FT_RETIRE_CONNECTION_ID:
2897 /* XXX TO DO XXX */
2898 break;
2899 case QUIC_FT_CONNECTION_CLOSE:
2900 case QUIC_FT_CONNECTION_CLOSE_APP:
2901 /* Increment the error counters */
2902 qc_cc_err_count_inc(qc, &frm);
2903 if (!(qc->flags & QUIC_FL_CONN_DRAINING)) {
2904 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2905 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2906 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2907 }
2908 TRACE_STATE("Entering draining state", QUIC_EV_CONN_PRSHPKT, qc);
2909 /* RFC 9000 10.2. Immediate Close:
2910 * The closing and draining connection states exist to ensure
2911 * that connections close cleanly and that delayed or reordered
2912 * packets are properly discarded. These states SHOULD persist
2913 * for at least three times the current PTO interval...
2914 *
2915 * Rearm the idle timeout only one time when entering draining
2916 * state.
2917 */
2918 qc_idle_timer_do_rearm(qc);
2919 qc->flags |= QUIC_FL_CONN_DRAINING|QUIC_FL_CONN_IMMEDIATE_CLOSE;
2920 qc_notify_close(qc);
2921 }
2922 break;
2923 case QUIC_FT_HANDSHAKE_DONE:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002924 if (qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002925 TRACE_ERROR("non accepted QUIC_FT_HANDSHAKE_DONE frame",
2926 QUIC_EV_CONN_PRSHPKT, qc);
2927 goto leave;
2928 }
2929
2930 qc->state = QUIC_HS_ST_CONFIRMED;
2931 break;
2932 default:
2933 TRACE_ERROR("unknosw frame type", QUIC_EV_CONN_PRSHPKT, qc);
2934 goto leave;
2935 }
2936 }
2937
2938 /* Flag this packet number space as having received a packet. */
2939 qel->pktns->flags |= QUIC_FL_PKTNS_PKT_RECEIVED;
2940
2941 if (fast_retrans) {
2942 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2943 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2944
2945 TRACE_PROTO("speeding up handshake completion", QUIC_EV_CONN_PRSHPKT, qc);
2946 qc_prep_hdshk_fast_retrans(qc, &iqel->pktns->tx.frms, &hqel->pktns->tx.frms);
2947 qc->flags |= QUIC_FL_CONN_HANDSHAKE_SPEED_UP;
2948 }
2949
2950 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
2951 * has successfully parse a Handshake packet. The Initial encryption must also
2952 * be discarded.
2953 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002954 if (pkt->type == QUIC_PACKET_TYPE_HANDSHAKE && qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002955 if (qc->state >= QUIC_HS_ST_SERVER_INITIAL) {
2956 if (!(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx.flags &
2957 QUIC_FL_TLS_SECRETS_DCD)) {
2958 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
2959 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PRSHPKT, qc);
2960 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002961 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002962 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
2963 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
2964 }
2965 if (qc->state < QUIC_HS_ST_SERVER_HANDSHAKE)
2966 qc->state = QUIC_HS_ST_SERVER_HANDSHAKE;
2967 }
2968 }
2969
2970 ret = 1;
2971 leave:
2972 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2973 return ret;
2974}
2975
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002976
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002977/* Allocate Tx buffer from <qc> quic-conn if needed.
2978 *
2979 * Returns allocated buffer or NULL on error.
2980 */
2981static struct buffer *qc_txb_alloc(struct quic_conn *qc)
2982{
2983 struct buffer *buf = &qc->tx.buf;
2984 if (!b_alloc(buf))
2985 return NULL;
2986
2987 return buf;
2988}
2989
2990/* Free Tx buffer from <qc> if it is empty. */
2991static void qc_txb_release(struct quic_conn *qc)
2992{
2993 struct buffer *buf = &qc->tx.buf;
2994
2995 /* For the moment sending function is responsible to purge the buffer
2996 * entirely. It may change in the future but this requires to be able
2997 * to reuse old data.
2998 */
2999 BUG_ON_HOT(buf && b_data(buf));
3000
3001 if (!b_data(buf)) {
3002 b_free(buf);
3003 offer_buffers(NULL, 1);
3004 }
3005}
3006
3007/* Commit a datagram payload written into <buf> of length <length>. <first_pkt>
3008 * must contains the address of the first packet stored in the payload.
3009 *
3010 * Caller is responsible that there is enough space in the buffer.
3011 */
3012static void qc_txb_store(struct buffer *buf, uint16_t length,
3013 struct quic_tx_packet *first_pkt)
3014{
3015 const size_t hdlen = sizeof(uint16_t) + sizeof(void *);
3016 BUG_ON_HOT(b_contig_space(buf) < hdlen); /* this must not happen */
3017
3018 write_u16(b_tail(buf), length);
3019 write_ptr(b_tail(buf) + sizeof(length), first_pkt);
3020 b_add(buf, hdlen + length);
3021}
3022
3023/* Returns 1 if a packet may be built for <qc> from <qel> encryption level
3024 * with <frms> as ack-eliciting frame list to send, 0 if not.
3025 * <cc> must equal to 1 if an immediate close was asked, 0 if not.
3026 * <probe> must equalt to 1 if a probing packet is required, 0 if not.
3027 * <force_ack> may be set to 1 if you want to force an ack.
3028 */
3029static int qc_may_build_pkt(struct quic_conn *qc, struct list *frms,
3030 struct quic_enc_level *qel, int cc, int probe, int force_ack)
3031{
3032 unsigned int must_ack = force_ack ||
3033 (LIST_ISEMPTY(frms) && (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED));
3034
3035 /* Do not build any more packet if the TX secrets are not available or
3036 * if there is nothing to send, i.e. if no CONNECTION_CLOSE or ACK are required
3037 * and if there is no more packets to send upon PTO expiration
3038 * and if there is no more ack-eliciting frames to send or in flight
3039 * congestion control limit is reached for prepared data
3040 */
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02003041 if (!quic_tls_has_tx_sec(qel) ||
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003042 (!cc && !probe && !must_ack &&
3043 (LIST_ISEMPTY(frms) || qc->path->prep_in_flight >= qc->path->cwnd))) {
3044 return 0;
3045 }
3046
3047 return 1;
3048}
3049
3050/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3051 * <frms>. Each packet is stored in a distinct datagram written to <buf>.
3052 *
3053 * Each datagram is prepended by a two fields header : the datagram length and
3054 * the address of the packet contained in the datagram.
3055 *
3056 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3057 * -1 if something wrong happened.
3058 */
3059static int qc_prep_app_pkts(struct quic_conn *qc, struct buffer *buf,
3060 struct list *frms)
3061{
3062 int ret = -1;
3063 struct quic_enc_level *qel;
3064 unsigned char *end, *pos;
3065 struct quic_tx_packet *pkt;
3066 size_t total;
3067 /* Each datagram is prepended with its length followed by the address
3068 * of the first packet in the datagram.
3069 */
3070 const size_t dg_headlen = sizeof(uint16_t) + sizeof(pkt);
3071
3072 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3073
3074 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3075 total = 0;
3076 pos = (unsigned char *)b_tail(buf);
3077 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen) {
3078 int err, probe, cc;
3079
3080 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3081 probe = 0;
3082 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3083 /* We do not probe if an immediate close was asked */
3084 if (!cc)
3085 probe = qel->pktns->tx.pto_probe;
3086
3087 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, 0))
3088 break;
3089
3090 /* Leave room for the datagram header */
3091 pos += dg_headlen;
3092 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3093 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3094 }
3095 else {
3096 end = pos + qc->path->mtu;
3097 }
3098
3099 pkt = qc_build_pkt(&pos, end, qel, &qel->tls_ctx, frms, qc, NULL, 0,
3100 QUIC_PACKET_TYPE_SHORT, 0, 0, probe, cc, &err);
3101 switch (err) {
3102 case -2:
3103 // trace already emitted by function above
3104 goto leave;
3105 case -1:
3106 /* As we provide qc_build_pkt() with an enough big buffer to fulfill an
3107 * MTU, we are here because of the congestion control window. There is
3108 * no need to try to reuse this buffer.
3109 */
3110 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3111 goto out;
3112 default:
3113 break;
3114 }
3115
3116 /* This is to please to GCC. We cannot have (err >= 0 && !pkt) */
3117 BUG_ON(!pkt);
3118
3119 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3120 pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3121
3122 total += pkt->len;
3123
3124 /* Write datagram header. */
3125 qc_txb_store(buf, pkt->len, pkt);
3126 }
3127
3128 out:
3129 ret = total;
3130 leave:
3131 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3132 return ret;
3133}
3134
3135/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3136 * <frms>. Several packets can be regrouped in a single datagram. The result is
3137 * written into <buf>.
3138 *
3139 * Each datagram is prepended by a two fields header : the datagram length and
3140 * the address of first packet in the datagram.
3141 *
3142 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3143 * -1 if something wrong happened.
3144 */
3145static int qc_prep_pkts(struct quic_conn *qc, struct buffer *buf,
3146 enum quic_tls_enc_level tel, struct list *tel_frms,
3147 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
3148{
3149 struct quic_enc_level *qel;
3150 unsigned char *end, *pos;
3151 struct quic_tx_packet *first_pkt, *cur_pkt, *prv_pkt;
3152 /* length of datagrams */
3153 uint16_t dglen;
3154 size_t total;
3155 int ret = -1, padding;
3156 /* Each datagram is prepended with its length followed by the address
3157 * of the first packet in the datagram.
3158 */
3159 const size_t dg_headlen = sizeof(uint16_t) + sizeof(first_pkt);
3160 struct list *frms;
3161
3162 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3163
3164 /* Currently qc_prep_pkts() does not handle buffer wrapping so the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003165 * caller must ensure that buf is reset.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003166 */
3167 BUG_ON_HOT(buf->head || buf->data);
3168
3169 total = 0;
3170 qel = &qc->els[tel];
3171 frms = tel_frms;
3172 dglen = 0;
3173 padding = 0;
3174 pos = (unsigned char *)b_head(buf);
3175 first_pkt = prv_pkt = NULL;
3176 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen || prv_pkt) {
3177 int err, probe, cc;
3178 enum quic_pkt_type pkt_type;
3179 struct quic_tls_ctx *tls_ctx;
3180 const struct quic_version *ver;
3181 int force_ack = (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3182 (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
3183 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
3184
3185 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3186 probe = 0;
3187 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3188 /* We do not probe if an immediate close was asked */
3189 if (!cc)
3190 probe = qel->pktns->tx.pto_probe;
3191
3192 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, force_ack)) {
3193 if (prv_pkt)
3194 qc_txb_store(buf, dglen, first_pkt);
3195 /* Let's select the next encryption level */
3196 if (tel != next_tel && next_tel != QUIC_TLS_ENC_LEVEL_NONE) {
3197 tel = next_tel;
3198 frms = next_tel_frms;
3199 qel = &qc->els[tel];
3200 /* Build a new datagram */
3201 prv_pkt = NULL;
3202 TRACE_DEVEL("next encryption level selected", QUIC_EV_CONN_PHPKTS, qc);
3203 continue;
3204 }
3205 break;
3206 }
3207
3208 pkt_type = quic_tls_level_pkt_type(tel);
3209 if (!prv_pkt) {
3210 /* Leave room for the datagram header */
3211 pos += dg_headlen;
3212 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3213 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3214 }
3215 else {
3216 end = pos + qc->path->mtu;
3217 }
3218 }
3219
3220 if (qc->negotiated_version) {
3221 ver = qc->negotiated_version;
3222 if (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL])
3223 tls_ctx = &qc->negotiated_ictx;
3224 else
3225 tls_ctx = &qel->tls_ctx;
3226 }
3227 else {
3228 ver = qc->original_version;
3229 tls_ctx = &qel->tls_ctx;
3230 }
3231
3232 cur_pkt = qc_build_pkt(&pos, end, qel, tls_ctx, frms,
3233 qc, ver, dglen, pkt_type,
3234 force_ack, padding, probe, cc, &err);
3235 switch (err) {
3236 case -2:
3237 // trace already emitted by function above
3238 goto leave;
3239 case -1:
3240 /* If there was already a correct packet present, set the
3241 * current datagram as prepared into <cbuf>.
3242 */
3243 if (prv_pkt)
3244 qc_txb_store(buf, dglen, first_pkt);
3245 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3246 goto out;
3247 default:
3248 break;
3249 }
3250
3251 /* This is to please to GCC. We cannot have (err >= 0 && !cur_pkt) */
3252 BUG_ON(!cur_pkt);
3253
3254 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3255 cur_pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3256
3257 total += cur_pkt->len;
3258 /* keep trace of the first packet in the datagram */
3259 if (!first_pkt)
3260 first_pkt = cur_pkt;
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01003261 /* Attach the current one to the previous one and vice versa */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003262 if (prv_pkt) {
3263 prv_pkt->next = cur_pkt;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01003264 cur_pkt->prev = prv_pkt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003265 cur_pkt->flags |= QUIC_FL_TX_PACKET_COALESCED;
3266 }
3267 /* Let's say we have to build a new dgram */
3268 prv_pkt = NULL;
3269 dglen += cur_pkt->len;
3270 /* Client: discard the Initial encryption keys as soon as
3271 * a handshake packet could be built.
3272 */
3273 if (qc->state == QUIC_HS_ST_CLIENT_INITIAL &&
3274 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
3275 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3276 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PHPKTS, qc);
3277 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
3278 qc_set_timer(qc);
3279 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3280 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3281 qc->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
3282 }
3283 /* If the data for the current encryption level have all been sent,
3284 * select the next level.
3285 */
3286 if ((tel == QUIC_TLS_ENC_LEVEL_INITIAL || tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE) &&
3287 next_tel != QUIC_TLS_ENC_LEVEL_NONE && (LIST_ISEMPTY(frms) && !qel->pktns->tx.pto_probe)) {
3288 /* If QUIC_TLS_ENC_LEVEL_HANDSHAKE was already reached let's try QUIC_TLS_ENC_LEVEL_APP */
3289 if (tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE && next_tel == tel)
3290 next_tel = QUIC_TLS_ENC_LEVEL_APP;
3291 tel = next_tel;
3292 if (tel == QUIC_TLS_ENC_LEVEL_APP)
3293 frms = &qc->els[tel].pktns->tx.frms;
3294 else
3295 frms = next_tel_frms;
3296 qel = &qc->els[tel];
3297 if (!LIST_ISEMPTY(frms)) {
3298 /* If there is data for the next level, do not
3299 * consume a datagram.
3300 */
3301 prv_pkt = cur_pkt;
3302 }
3303 }
3304
3305 /* If we have to build a new datagram, set the current datagram as
3306 * prepared into <cbuf>.
3307 */
3308 if (!prv_pkt) {
3309 qc_txb_store(buf, dglen, first_pkt);
3310 first_pkt = NULL;
3311 dglen = 0;
3312 padding = 0;
3313 }
3314 else if (prv_pkt->type == QUIC_TLS_ENC_LEVEL_INITIAL &&
3315 (!qc_is_listener(qc) ||
3316 prv_pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
3317 padding = 1;
3318 }
3319 }
3320
3321 out:
3322 ret = total;
3323 leave:
3324 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3325 return ret;
3326}
3327
3328/* Send datagrams stored in <buf>.
3329 *
3330 * This function always returns 1 for success. Even if sendto() syscall failed,
3331 * buffer is drained and packets are considered as emitted. QUIC loss detection
3332 * mechanism is used as a back door way to retry sending.
3333 */
3334int qc_send_ppkts(struct buffer *buf, struct ssl_sock_ctx *ctx)
3335{
3336 struct quic_conn *qc;
3337 char skip_sendto = 0;
3338
3339 qc = ctx->qc;
3340 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
3341 while (b_contig_data(buf, 0)) {
3342 unsigned char *pos;
3343 struct buffer tmpbuf = { };
3344 struct quic_tx_packet *first_pkt, *pkt, *next_pkt;
3345 uint16_t dglen;
3346 size_t headlen = sizeof dglen + sizeof first_pkt;
3347 unsigned int time_sent;
3348
3349 pos = (unsigned char *)b_head(buf);
3350 dglen = read_u16(pos);
3351 BUG_ON_HOT(!dglen); /* this should not happen */
3352
3353 pos += sizeof dglen;
3354 first_pkt = read_ptr(pos);
3355 pos += sizeof first_pkt;
3356 tmpbuf.area = (char *)pos;
3357 tmpbuf.size = tmpbuf.data = dglen;
3358
3359 TRACE_DATA("send dgram", QUIC_EV_CONN_SPPKTS, qc);
3360 /* If sendto is on error just skip the call to it for the rest
3361 * of the loop but continue to purge the buffer. Data will be
3362 * transmitted when QUIC packets are detected as lost on our
3363 * side.
3364 *
3365 * TODO use fd-monitoring to detect when send operation can be
3366 * retry. This should improve the bandwidth without relying on
3367 * retransmission timer. However, it requires a major rework on
3368 * quic-conn fd management.
3369 */
3370 if (!skip_sendto) {
3371 if (qc_snd_buf(qc, &tmpbuf, tmpbuf.data, 0)) {
3372 skip_sendto = 1;
3373 TRACE_ERROR("sendto error, simulate sending for the rest of data", QUIC_EV_CONN_SPPKTS, qc);
3374 }
3375 }
3376
3377 b_del(buf, dglen + headlen);
3378 qc->tx.bytes += tmpbuf.data;
3379 time_sent = now_ms;
3380
3381 for (pkt = first_pkt; pkt; pkt = next_pkt) {
3382 pkt->time_sent = time_sent;
3383 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
3384 pkt->pktns->tx.time_of_last_eliciting = time_sent;
3385 qc->path->ifae_pkts++;
3386 if (qc->flags & QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ)
3387 qc_idle_timer_rearm(qc, 0);
3388 }
3389 if (!(qc->flags & QUIC_FL_CONN_CLOSING) &&
3390 (pkt->flags & QUIC_FL_TX_PACKET_CC)) {
3391 qc->flags |= QUIC_FL_CONN_CLOSING;
3392 qc_notify_close(qc);
3393
3394 /* RFC 9000 10.2. Immediate Close:
3395 * The closing and draining connection states exist to ensure
3396 * that connections close cleanly and that delayed or reordered
3397 * packets are properly discarded. These states SHOULD persist
3398 * for at least three times the current PTO interval...
3399 *
3400 * Rearm the idle timeout only one time when entering closing
3401 * state.
3402 */
3403 qc_idle_timer_do_rearm(qc);
3404 if (qc->timer_task) {
3405 task_destroy(qc->timer_task);
3406 qc->timer_task = NULL;
3407 }
3408 }
3409 qc->path->in_flight += pkt->in_flight_len;
3410 pkt->pktns->tx.in_flight += pkt->in_flight_len;
3411 if (pkt->in_flight_len)
3412 qc_set_timer(qc);
3413 TRACE_DATA("sent pkt", QUIC_EV_CONN_SPPKTS, qc, pkt);
3414 next_pkt = pkt->next;
3415 quic_tx_packet_refinc(pkt);
3416 eb64_insert(&pkt->pktns->tx.pkts, &pkt->pn_node);
3417 }
3418 }
3419
3420 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
3421
3422 return 1;
3423}
3424
3425/* Copy into <buf> buffer a stateless reset token depending on the
3426 * <salt> salt input. This is the cluster secret which will be derived
3427 * as HKDF input secret to generate this token.
3428 * Return 1 if succeeded, 0 if not.
3429 */
3430static int quic_stateless_reset_token_cpy(struct quic_conn *qc,
3431 unsigned char *buf, size_t len,
3432 const unsigned char *salt, size_t saltlen)
3433{
3434 /* Input secret */
3435 const unsigned char *key = (const unsigned char *)global.cluster_secret;
3436 size_t keylen = strlen(global.cluster_secret);
3437 /* Info */
3438 const unsigned char label[] = "stateless token";
3439 size_t labellen = sizeof label - 1;
3440 int ret;
3441
3442 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3443
3444 ret = quic_hkdf_extract_and_expand(EVP_sha256(), buf, len,
3445 key, keylen, salt, saltlen, label, labellen);
3446 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3447 return ret;
3448}
3449
3450/* Initialize the stateless reset token attached to <cid> connection ID.
3451 * Returns 1 if succeeded, 0 if not.
3452 */
3453static int quic_stateless_reset_token_init(struct quic_conn *qc,
3454 struct quic_connection_id *quic_cid)
3455{
3456 int ret;
3457
3458 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3459
3460 if (global.cluster_secret) {
3461 /* Output secret */
3462 unsigned char *token = quic_cid->stateless_reset_token;
3463 size_t tokenlen = sizeof quic_cid->stateless_reset_token;
3464 /* Salt */
3465 const unsigned char *cid = quic_cid->cid.data;
3466 size_t cidlen = quic_cid->cid.len;
3467
3468 ret = quic_stateless_reset_token_cpy(qc, token, tokenlen, cid, cidlen);
3469 }
3470 else {
3471 /* TODO: RAND_bytes() should be replaced */
3472 ret = RAND_bytes(quic_cid->stateless_reset_token,
3473 sizeof quic_cid->stateless_reset_token) == 1;
3474 }
3475
3476 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3477 return ret;
3478}
3479
3480/* Allocate a new CID with <seq_num> as sequence number and attach it to <root>
3481 * ebtree.
3482 *
3483 * The CID is randomly generated in part with the result altered to be
3484 * associated with the current thread ID. This means this function must only
3485 * be called by the quic_conn thread.
3486 *
3487 * Returns the new CID if succeeded, NULL if not.
3488 */
3489static struct quic_connection_id *new_quic_cid(struct eb_root *root,
3490 struct quic_conn *qc,
3491 int seq_num)
3492{
3493 struct quic_connection_id *cid;
3494
3495 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3496
3497 cid = pool_alloc(pool_head_quic_connection_id);
3498 if (!cid) {
3499 TRACE_ERROR("cid allocation failed", QUIC_EV_CONN_TXPKT, qc);
3500 goto err;
3501 }
3502
3503 cid->cid.len = QUIC_HAP_CID_LEN;
3504 /* TODO: RAND_bytes() should be replaced */
3505 if (RAND_bytes(cid->cid.data, cid->cid.len) != 1) {
3506 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT, qc);
3507 goto err;
3508 }
3509
3510 quic_pin_cid_to_tid(cid->cid.data, tid);
3511 if (quic_stateless_reset_token_init(qc, cid) != 1) {
3512 TRACE_ERROR("quic_stateless_reset_token_init() failed", QUIC_EV_CONN_TXPKT, qc);
3513 goto err;
3514 }
3515
3516 cid->qc = qc;
3517
3518 cid->seq_num.key = seq_num;
3519 cid->retire_prior_to = 0;
3520 /* insert the allocated CID in the quic_conn tree */
3521 eb64_insert(root, &cid->seq_num);
3522
3523 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3524 return cid;
3525
3526 err:
3527 pool_free(pool_head_quic_connection_id, cid);
3528 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3529 return NULL;
3530}
3531
3532/* Build all the frames which must be sent just after the handshake have succeeded.
3533 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
3534 * a HANDSHAKE_DONE frame.
3535 * Return 1 if succeeded, 0 if not.
3536 */
3537static int quic_build_post_handshake_frames(struct quic_conn *qc)
3538{
3539 int ret = 0, i, first, max;
3540 struct quic_enc_level *qel;
3541 struct quic_frame *frm, *frmbak;
3542 struct list frm_list = LIST_HEAD_INIT(frm_list);
3543 struct eb64_node *node;
3544
3545 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
3546
3547 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3548 /* Only servers must send a HANDSHAKE_DONE frame. */
3549 if (qc_is_listener(qc)) {
3550 frm = pool_zalloc(pool_head_quic_frame);
3551 if (!frm) {
3552 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3553 goto leave;
3554 }
3555
3556 LIST_INIT(&frm->reflist);
3557 frm->type = QUIC_FT_HANDSHAKE_DONE;
3558 LIST_APPEND(&frm_list, &frm->list);
3559 }
3560
3561 /* Initialize <max> connection IDs minus one: there is
3562 * already one connection ID used for the current connection.
3563 */
3564 first = 1;
3565 max = qc->tx.params.active_connection_id_limit;
3566
3567 /* TODO: check limit */
3568 for (i = first; i < max; i++) {
3569 struct quic_connection_id *cid;
3570
3571 frm = pool_zalloc(pool_head_quic_frame);
3572 if (!frm) {
3573 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3574 goto err;
3575 }
3576
3577 LIST_INIT(&frm->reflist);
3578 cid = new_quic_cid(&qc->cids, qc, i);
3579 if (!cid) {
3580 pool_free(pool_head_quic_frame, frm);
3581 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3582 goto err;
3583 }
3584
3585 /* insert the allocated CID in the receiver datagram handler tree */
3586 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3587
3588 quic_connection_id_to_frm_cpy(frm, cid);
3589 LIST_APPEND(&frm_list, &frm->list);
3590 }
3591
3592 LIST_SPLICE(&qel->pktns->tx.frms, &frm_list);
3593 qc->flags |= QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT;
3594
3595 ret = 1;
3596 leave:
3597 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
3598 return ret;
3599
3600 err:
3601 /* free the frames */
3602 list_for_each_entry_safe(frm, frmbak, &frm_list, list)
3603 pool_free(pool_head_quic_frame, frm);
3604
3605 node = eb64_lookup_ge(&qc->cids, first);
3606 while (node) {
3607 struct quic_connection_id *cid;
3608
3609 cid = eb64_entry(node, struct quic_connection_id, seq_num);
3610 if (cid->seq_num.key >= max)
3611 break;
3612
3613 node = eb64_next(node);
3614 ebmb_delete(&cid->node);
3615 eb64_delete(&cid->seq_num);
3616 pool_free(pool_head_quic_connection_id, cid);
3617 }
3618 goto leave;
3619}
3620
3621/* Deallocate <l> list of ACK ranges. */
3622void quic_free_arngs(struct quic_conn *qc, struct quic_arngs *arngs)
3623{
3624 struct eb64_node *n;
3625 struct quic_arng_node *ar;
3626
3627 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
3628
3629 n = eb64_first(&arngs->root);
3630 while (n) {
3631 struct eb64_node *next;
3632
3633 ar = eb64_entry(n, struct quic_arng_node, first);
3634 next = eb64_next(n);
3635 eb64_delete(n);
3636 pool_free(pool_head_quic_arng, ar);
3637 n = next;
3638 }
3639
3640 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
3641}
3642
3643/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
3644 * descending order.
3645 */
3646static inline size_t sack_gap(struct quic_arng_node *p,
3647 struct quic_arng_node *q)
3648{
3649 return p->first.key - q->last - 2;
3650}
3651
3652
3653/* Remove the last elements of <ack_ranges> list of ack range updating its
3654 * encoded size until it goes below <limit>.
3655 * Returns 1 if succeeded, 0 if not (no more element to remove).
3656 */
3657static int quic_rm_last_ack_ranges(struct quic_conn *qc,
3658 struct quic_arngs *arngs, size_t limit)
3659{
3660 int ret = 0;
3661 struct eb64_node *last, *prev;
3662
3663 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3664
3665 last = eb64_last(&arngs->root);
3666 while (last && arngs->enc_sz > limit) {
3667 struct quic_arng_node *last_node, *prev_node;
3668
3669 prev = eb64_prev(last);
3670 if (!prev) {
3671 TRACE_DEVEL("<last> not found", QUIC_EV_CONN_TXPKT, qc);
3672 goto out;
3673 }
3674
3675 last_node = eb64_entry(last, struct quic_arng_node, first);
3676 prev_node = eb64_entry(prev, struct quic_arng_node, first);
3677 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
3678 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
3679 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
3680 --arngs->sz;
3681 eb64_delete(last);
3682 pool_free(pool_head_quic_arng, last);
3683 last = prev;
3684 }
3685
3686 ret = 1;
3687 out:
3688 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3689 return ret;
3690}
3691
3692/* Set the encoded size of <arngs> QUIC ack ranges. */
3693static void quic_arngs_set_enc_sz(struct quic_conn *qc, struct quic_arngs *arngs)
3694{
3695 struct eb64_node *node, *next;
3696 struct quic_arng_node *ar, *ar_next;
3697
3698 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3699
3700 node = eb64_last(&arngs->root);
3701 if (!node)
3702 goto leave;
3703
3704 ar = eb64_entry(node, struct quic_arng_node, first);
3705 arngs->enc_sz = quic_int_getsize(ar->last) +
3706 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
3707
3708 while ((next = eb64_prev(node))) {
3709 ar_next = eb64_entry(next, struct quic_arng_node, first);
3710 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
3711 quic_int_getsize(ar_next->last - ar_next->first.key);
3712 node = next;
3713 ar = eb64_entry(node, struct quic_arng_node, first);
3714 }
3715
3716 leave:
3717 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3718}
3719
3720/* Insert <ar> ack range into <argns> tree of ack ranges.
3721 * Returns the ack range node which has been inserted if succeeded, NULL if not.
3722 */
3723static inline
3724struct quic_arng_node *quic_insert_new_range(struct quic_conn *qc,
3725 struct quic_arngs *arngs,
3726 struct quic_arng *ar)
3727{
3728 struct quic_arng_node *new_ar;
3729
3730 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3731
3732 new_ar = pool_alloc(pool_head_quic_arng);
3733 if (!new_ar) {
3734 TRACE_ERROR("ack range allocation failed", QUIC_EV_CONN_RXPKT, qc);
3735 goto leave;
3736 }
3737
3738 new_ar->first.key = ar->first;
3739 new_ar->last = ar->last;
3740 eb64_insert(&arngs->root, &new_ar->first);
3741 arngs->sz++;
3742
3743 leave:
3744 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3745 return new_ar;
3746}
3747
3748/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
3749 * Note that this function computes the number of bytes required to encode
3750 * this tree of ACK ranges in descending order.
3751 *
3752 * Descending order
3753 * ------------->
3754 * range1 range2
3755 * ..........|--------|..............|--------|
3756 * ^ ^ ^ ^
3757 * | | | |
3758 * last1 first1 last2 first2
3759 * ..........+--------+--------------+--------+......
3760 * diff1 gap12 diff2
3761 *
3762 * To encode the previous list of ranges we must encode integers as follows in
3763 * descending order:
3764 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
3765 * with diff1 = last1 - first1
3766 * diff2 = last2 - first2
3767 * gap12 = first1 - last2 - 2 (>= 0)
3768 *
3769
3770returns 0 on error
3771
3772 */
3773int quic_update_ack_ranges_list(struct quic_conn *qc,
3774 struct quic_arngs *arngs,
3775 struct quic_arng *ar)
3776{
3777 int ret = 0;
3778 struct eb64_node *le;
3779 struct quic_arng_node *new_node;
3780 struct eb64_node *new;
3781
3782 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3783
3784 new = NULL;
3785 if (eb_is_empty(&arngs->root)) {
3786 new_node = quic_insert_new_range(qc, arngs, ar);
3787 if (new_node)
3788 ret = 1;
3789
3790 goto leave;
3791 }
3792
3793 le = eb64_lookup_le(&arngs->root, ar->first);
3794 if (!le) {
3795 new_node = quic_insert_new_range(qc, arngs, ar);
3796 if (!new_node)
3797 goto leave;
3798
3799 new = &new_node->first;
3800 }
3801 else {
3802 struct quic_arng_node *le_ar =
3803 eb64_entry(le, struct quic_arng_node, first);
3804
3805 /* Already existing range */
3806 if (le_ar->last >= ar->last) {
3807 ret = 1;
3808 }
3809 else if (le_ar->last + 1 >= ar->first) {
3810 le_ar->last = ar->last;
3811 new = le;
3812 new_node = le_ar;
3813 }
3814 else {
3815 new_node = quic_insert_new_range(qc, arngs, ar);
3816 if (!new_node)
3817 goto leave;
3818
3819 new = &new_node->first;
3820 }
3821 }
3822
3823 /* Verify that the new inserted node does not overlap the nodes
3824 * which follow it.
3825 */
3826 if (new) {
3827 struct eb64_node *next;
3828 struct quic_arng_node *next_node;
3829
3830 while ((next = eb64_next(new))) {
3831 next_node =
3832 eb64_entry(next, struct quic_arng_node, first);
3833 if (new_node->last + 1 < next_node->first.key)
3834 break;
3835
3836 if (next_node->last > new_node->last)
3837 new_node->last = next_node->last;
3838 eb64_delete(next);
3839 pool_free(pool_head_quic_arng, next_node);
3840 /* Decrement the size of these ranges. */
3841 arngs->sz--;
3842 }
3843 }
3844
3845 ret = 1;
3846 leave:
3847 quic_arngs_set_enc_sz(qc, arngs);
3848 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3849 return ret;
3850}
3851/* Remove the header protection of packets at <el> encryption level.
3852 * Always succeeds.
3853 */
3854static inline void qc_rm_hp_pkts(struct quic_conn *qc, struct quic_enc_level *el)
3855{
3856 struct quic_tls_ctx *tls_ctx;
3857 struct quic_rx_packet *pqpkt, *pkttmp;
3858 struct quic_enc_level *app_qel;
3859
3860 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, qc);
3861 app_qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3862 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
3863 if (el == app_qel && qc_is_listener(qc) && qc->state < QUIC_HS_ST_COMPLETE) {
3864 TRACE_DEVEL("hp not removed (handshake not completed)",
3865 QUIC_EV_CONN_ELRMHP, qc);
3866 goto out;
3867 }
3868 tls_ctx = &el->tls_ctx;
3869 list_for_each_entry_safe(pqpkt, pkttmp, &el->rx.pqpkts, list) {
3870 if (!qc_do_rm_hp(qc, pqpkt, tls_ctx, el->pktns->rx.largest_pn,
3871 pqpkt->data + pqpkt->pn_offset, pqpkt->data)) {
3872 TRACE_ERROR("hp removing error", QUIC_EV_CONN_ELRMHP, qc);
3873 }
3874 else {
3875 /* The AAD includes the packet number field */
3876 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
3877 /* Store the packet into the tree of packets to decrypt. */
3878 pqpkt->pn_node.key = pqpkt->pn;
3879 eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
3880 quic_rx_packet_refinc(pqpkt);
3881 TRACE_DEVEL("hp removed", QUIC_EV_CONN_ELRMHP, qc, pqpkt);
3882 }
3883 LIST_DELETE(&pqpkt->list);
3884 quic_rx_packet_refdec(pqpkt);
3885 }
3886
3887 out:
3888 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, qc);
3889}
3890
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003891/* Process all the CRYPTO frame at <el> encryption level. This is the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003892 * responsibility of the called to ensure there exists a CRYPTO data
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003893 * stream for this level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003894 * Return 1 if succeeded, 0 if not.
3895 */
3896static inline int qc_treat_rx_crypto_frms(struct quic_conn *qc,
3897 struct quic_enc_level *el,
3898 struct ssl_sock_ctx *ctx)
3899{
3900 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003901 struct ncbuf *ncbuf;
3902 struct quic_cstream *cstream = el->cstream;
3903 ncb_sz_t data;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003904
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003905 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003906
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003907 BUG_ON(!cstream);
3908 ncbuf = &cstream->rx.ncbuf;
3909 if (ncb_is_null(ncbuf))
3910 goto done;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003911
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01003912 /* TODO not working if buffer is wrapping */
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003913 while ((data = ncb_data(ncbuf, 0))) {
3914 const unsigned char *cdata = (const unsigned char *)ncb_head(ncbuf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003915
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003916 if (!qc_provide_cdata(el, ctx, cdata, data, NULL, NULL))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003917 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003918
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003919 cstream->rx.offset += data;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01003920 TRACE_DEVEL("buffered crypto data were provided to TLS stack",
3921 QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003922 }
3923
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003924 done:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003925 ret = 1;
3926 leave:
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01003927 if (!ncb_is_null(ncbuf) && ncb_is_empty(ncbuf)) {
3928 TRACE_DEVEL("freeing crypto buf", QUIC_EV_CONN_PHPKTS, qc, el);
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003929 quic_free_ncbuf(ncbuf);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01003930 }
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003931 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003932 return ret;
3933}
3934
3935/* Process all the packets at <el> and <next_el> encryption level.
3936 * This is the caller responsibility to check that <cur_el> is different of <next_el>
3937 * as pointer value.
3938 * Return 1 if succeeded, 0 if not.
3939 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003940int qc_treat_rx_pkts(struct quic_conn *qc, struct quic_enc_level *cur_el,
3941 struct quic_enc_level *next_el, int force_ack)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003942{
3943 int ret = 0;
3944 struct eb64_node *node;
3945 int64_t largest_pn = -1;
3946 unsigned int largest_pn_time_received = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003947 struct quic_enc_level *qel = cur_el;
3948
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003949 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003950 qel = cur_el;
3951 next_tel:
3952 if (!qel)
3953 goto out;
3954
3955 node = eb64_first(&qel->rx.pkts);
3956 while (node) {
3957 struct quic_rx_packet *pkt;
3958
3959 pkt = eb64_entry(node, struct quic_rx_packet, pn_node);
3960 TRACE_DATA("new packet", QUIC_EV_CONN_RXPKT,
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003961 qc, pkt, NULL, qc->xprt_ctx->ssl);
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01003962 if (!qc_pkt_decrypt(qc, qel, pkt)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003963 /* Drop the packet */
3964 TRACE_ERROR("packet decryption failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003965 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003966 }
3967 else {
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003968 if (!qc_parse_pkt_frms(qc, pkt, qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003969 /* Drop the packet */
3970 TRACE_ERROR("packet parsing failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003971 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003972 HA_ATOMIC_INC(&qc->prx_counters->dropped_parsing);
3973 }
3974 else {
3975 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
3976
3977 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING || force_ack) {
3978 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
3979 qel->pktns->rx.nb_aepkts_since_last_ack++;
3980 qc_idle_timer_rearm(qc, 1);
3981 }
3982 if (pkt->pn > largest_pn) {
3983 largest_pn = pkt->pn;
3984 largest_pn_time_received = pkt->time_received;
3985 }
3986 /* Update the list of ranges to acknowledge. */
3987 if (!quic_update_ack_ranges_list(qc, &qel->pktns->rx.arngs, &ar))
3988 TRACE_ERROR("Could not update ack range list",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003989 QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003990 }
3991 }
3992 node = eb64_next(node);
3993 eb64_delete(&pkt->pn_node);
3994 quic_rx_packet_refdec(pkt);
3995 }
3996
3997 if (largest_pn != -1 && largest_pn > qel->pktns->rx.largest_pn) {
3998 /* Update the largest packet number. */
3999 qel->pktns->rx.largest_pn = largest_pn;
4000 /* Update the largest acknowledged packet timestamps */
4001 qel->pktns->rx.largest_time_received = largest_pn_time_received;
4002 qel->pktns->flags |= QUIC_FL_PKTNS_NEW_LARGEST_PN;
4003 }
4004
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02004005 if (qel->cstream && !qc_treat_rx_crypto_frms(qc, qel, qc->xprt_ctx)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004006 // trace already emitted by function above
4007 goto leave;
4008 }
4009
4010 if (qel == cur_el) {
4011 BUG_ON(qel == next_el);
4012 qel = next_el;
4013 largest_pn = -1;
4014 goto next_tel;
4015 }
4016
4017 out:
4018 ret = 1;
4019 leave:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004020 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004021 return ret;
4022}
4023
4024/* Check if it's possible to remove header protection for packets related to
4025 * encryption level <qel>. If <qel> is NULL, assume it's false.
4026 *
4027 * Return true if the operation is possible else false.
4028 */
4029static int qc_qel_may_rm_hp(struct quic_conn *qc, struct quic_enc_level *qel)
4030{
4031 int ret = 0;
4032 enum quic_tls_enc_level tel;
4033
4034 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
4035
4036 if (!qel)
4037 goto cant_rm_hp;
4038
4039 tel = ssl_to_quic_enc_level(qel->level);
4040
4041 /* check if tls secrets are available */
4042 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
4043 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, qc);
4044 goto cant_rm_hp;
4045 }
4046
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004047 if (!quic_tls_has_rx_sec(qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004048 TRACE_DEVEL("non available secrets", QUIC_EV_CONN_TRMHP, qc);
4049 goto cant_rm_hp;
4050 }
4051
4052 /* check if the connection layer is ready before using app level */
4053 if ((tel == QUIC_TLS_ENC_LEVEL_APP || tel == QUIC_TLS_ENC_LEVEL_EARLY_DATA) &&
4054 qc->mux_state == QC_MUX_NULL) {
4055 TRACE_DEVEL("connection layer not ready", QUIC_EV_CONN_TRMHP, qc);
4056 goto cant_rm_hp;
4057 }
4058
4059 ret = 1;
4060 cant_rm_hp:
4061 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc);
4062 return ret;
4063}
4064
4065/* Try to send application frames from list <frms> on connection <qc>.
4066 *
4067 * Use qc_send_app_probing wrapper when probing with old data.
4068 *
4069 * Returns 1 on success. Some data might not have been sent due to congestion,
4070 * in this case they are left in <frms> input list. The caller may subscribe on
4071 * quic-conn to retry later.
4072 *
4073 * Returns 0 on critical error.
4074 * TODO review and classify more distinctly transient from definitive errors to
4075 * allow callers to properly handle it.
4076 */
4077static int qc_send_app_pkts(struct quic_conn *qc, struct list *frms)
4078{
4079 int status = 0;
4080 struct buffer *buf;
4081
4082 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4083
4084 buf = qc_txb_alloc(qc);
4085 if (!buf) {
4086 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4087 goto leave;
4088 }
4089
4090 /* Prepare and send packets until we could not further prepare packets. */
4091 while (1) {
4092 int ret;
4093 /* Currently buf cannot be non-empty at this stage. Even if a
4094 * previous sendto() has failed it is emptied to simulate
4095 * packet emission and rely on QUIC lost detection to try to
4096 * emit it.
4097 */
4098 BUG_ON_HOT(b_data(buf));
4099 b_reset(buf);
4100
4101 ret = qc_prep_app_pkts(qc, buf, frms);
4102 if (ret == -1)
4103 goto err;
4104 else if (ret == 0)
4105 goto out;
4106
4107 if (!qc_send_ppkts(buf, qc->xprt_ctx))
4108 goto err;
4109 }
4110
4111 out:
4112 status = 1;
4113 qc_txb_release(qc);
4114 leave:
4115 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4116 return status;
4117
4118 err:
4119 qc_txb_release(qc);
4120 goto leave;
4121}
4122
4123/* Try to send application frames from list <frms> on connection <qc>. Use this
4124 * function when probing is required.
4125 *
4126 * Returns the result from qc_send_app_pkts function.
4127 */
4128static forceinline int qc_send_app_probing(struct quic_conn *qc,
4129 struct list *frms)
4130{
4131 int ret;
4132
4133 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4134
4135 TRACE_STATE("preparing old data (probing)", QUIC_EV_CONN_TXPKT, qc);
4136 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4137 ret = qc_send_app_pkts(qc, frms);
4138 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4139
4140 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4141 return ret;
4142}
4143
4144/* Try to send application frames from list <frms> on connection <qc>. This
4145 * function is provided for MUX upper layer usage only.
4146 *
4147 * Returns the result from qc_send_app_pkts function.
4148 */
4149int qc_send_mux(struct quic_conn *qc, struct list *frms)
4150{
4151 int ret;
4152
4153 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4154 BUG_ON(qc->mux_state != QC_MUX_READY); /* Only MUX can uses this function so it must be ready. */
4155
4156 TRACE_STATE("preparing data (from MUX)", QUIC_EV_CONN_TXPKT, qc);
4157 qc->flags |= QUIC_FL_CONN_TX_MUX_CONTEXT;
4158 ret = qc_send_app_pkts(qc, frms);
4159 qc->flags &= ~QUIC_FL_CONN_TX_MUX_CONTEXT;
4160
4161 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4162 return ret;
4163}
4164
4165/* Sends handshake packets from up to two encryption levels <tel> and <next_te>
4166 * with <tel_frms> and <next_tel_frms> as frame list respectively for <qc>
4167 * QUIC connection. <old_data> is used as boolean to send data already sent but
4168 * not already acknowledged (in flight).
4169 * Returns 1 if succeeded, 0 if not.
4170 */
4171int qc_send_hdshk_pkts(struct quic_conn *qc, int old_data,
4172 enum quic_tls_enc_level tel, struct list *tel_frms,
4173 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
4174{
4175 int ret, status = 0;
4176 struct buffer *buf = qc_txb_alloc(qc);
4177
4178 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4179
4180 if (!buf) {
4181 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4182 goto leave;
4183 }
4184
4185 /* Currently buf cannot be non-empty at this stage. Even if a previous
4186 * sendto() has failed it is emptied to simulate packet emission and
4187 * rely on QUIC lost detection to try to emit it.
4188 */
4189 BUG_ON_HOT(b_data(buf));
4190 b_reset(buf);
4191
4192 if (old_data) {
4193 TRACE_STATE("old data for probing asked", QUIC_EV_CONN_TXPKT, qc);
4194 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4195 }
4196
4197 ret = qc_prep_pkts(qc, buf, tel, tel_frms, next_tel, next_tel_frms);
4198 if (ret == -1)
4199 goto out;
4200 else if (ret == 0)
4201 goto skip_send;
4202
4203 if (!qc_send_ppkts(buf, qc->xprt_ctx))
4204 goto out;
4205
4206 skip_send:
4207 status = 1;
4208 out:
4209 TRACE_STATE("no more need old data for probing", QUIC_EV_CONN_TXPKT, qc);
4210 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4211 qc_txb_release(qc);
4212 leave:
4213 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4214 return status;
4215}
4216
4217/* Retransmit up to two datagrams depending on packet number space */
4218static void qc_dgrams_retransmit(struct quic_conn *qc)
4219{
4220 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4221 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4222 struct quic_enc_level *aqel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4223
4224 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4225
4226 if (iqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4227 struct list ifrms = LIST_HEAD_INIT(ifrms);
4228 struct list hfrms = LIST_HEAD_INIT(hfrms);
4229
4230 qc_prep_hdshk_fast_retrans(qc, &ifrms, &hfrms);
4231 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &ifrms);
4232 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4233 if (!LIST_ISEMPTY(&ifrms)) {
4234 iqel->pktns->tx.pto_probe = 1;
4235 if (!LIST_ISEMPTY(&hfrms)) {
4236 hqel->pktns->tx.pto_probe = 1;
4237 qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4238 QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms);
4239 /* Put back unsent frames in their packet number spaces */
4240 LIST_SPLICE(&iqel->pktns->tx.frms, &ifrms);
4241 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4242 }
4243 }
4244 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4245 /* This list has potentially been already used and spliced
4246 * to another one attached to the connection. We must reinitialize it.
4247 */
4248 LIST_INIT(&hfrms);
4249 qc_prep_fast_retrans(qc, hqel, &hfrms, NULL);
4250 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4251 if (!LIST_ISEMPTY(&hfrms)) {
4252 hqel->pktns->tx.pto_probe = 1;
4253 qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms,
4254 QUIC_TLS_ENC_LEVEL_NONE, NULL);
4255 /* Put back unsent frames into their packet number spaces */
4256 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4257 }
4258 TRACE_STATE("no more need to probe Handshake packet number space",
4259 QUIC_EV_CONN_TXPKT, qc);
4260 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4261 }
4262 TRACE_STATE("no more need to probe Initial packet number space",
4263 QUIC_EV_CONN_TXPKT, qc);
4264 iqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4265 }
4266 else {
4267 int i;
4268
4269 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004270 hqel->pktns->tx.pto_probe = 0;
4271 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
Frédéric Lécaille7b5d9b12022-11-28 17:21:45 +01004272 struct list frms1 = LIST_HEAD_INIT(frms1);
4273
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004274 qc_prep_fast_retrans(qc, hqel, &frms1, NULL);
4275 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4276 if (!LIST_ISEMPTY(&frms1)) {
4277 hqel->pktns->tx.pto_probe = 1;
4278 qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &frms1,
4279 QUIC_TLS_ENC_LEVEL_NONE, NULL);
4280 /* Put back unsent frames into their packet number spaces */
4281 LIST_SPLICE(&hqel->pktns->tx.frms, &frms1);
4282 }
4283 }
4284 TRACE_STATE("no more need to probe Handshake packet number space",
4285 QUIC_EV_CONN_TXPKT, qc);
4286 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4287 }
4288 else if (aqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4289 struct list frms2 = LIST_HEAD_INIT(frms2);
4290 struct list frms1 = LIST_HEAD_INIT(frms1);
4291
4292 aqel->pktns->tx.pto_probe = 0;
4293 qc_prep_fast_retrans(qc, aqel, &frms1, &frms2);
4294 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4295 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms2);
4296 if (!LIST_ISEMPTY(&frms1)) {
4297 aqel->pktns->tx.pto_probe = 1;
4298 qc_send_app_probing(qc, &frms1);
4299 /* Put back unsent frames into their packet number spaces */
4300 LIST_SPLICE(&aqel->pktns->tx.frms, &frms1);
4301 }
4302 if (!LIST_ISEMPTY(&frms2)) {
4303 aqel->pktns->tx.pto_probe = 1;
4304 qc_send_app_probing(qc, &frms2);
4305 /* Put back unsent frames into their packet number spaces */
4306 LIST_SPLICE(&aqel->pktns->tx.frms, &frms2);
4307 }
4308 TRACE_STATE("no more need to probe 01RTT packet number space",
4309 QUIC_EV_CONN_TXPKT, qc);
4310 aqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4311 }
4312 }
4313 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4314}
4315
4316/* QUIC connection packet handler task (post handshake) */
4317struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state)
4318{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004319 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004320 struct quic_enc_level *qel;
4321
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004322 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4323
4324 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
4325 TRACE_STATE("connection handshake state", QUIC_EV_CONN_IO_CB, qc, &qc->state);
4326
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004327 if (qc_test_fd(qc))
4328 qc_rcv_buf(qc);
4329
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004330 /* Retranmissions */
4331 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4332 TRACE_STATE("retransmission needed", QUIC_EV_CONN_IO_CB, qc);
4333 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
4334 qc_dgrams_retransmit(qc);
4335 }
4336
4337 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4338 qc_rm_hp_pkts(qc, qel);
4339
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004340 if (!qc_treat_rx_pkts(qc, qel, NULL, 0)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004341 TRACE_DEVEL("qc_treat_rx_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4342 goto out;
4343 }
4344
4345 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4346 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)) {
4347 TRACE_STATE("draining connection (must not send packets)", QUIC_EV_CONN_IO_CB, qc);
4348 goto out;
4349 }
4350
4351 /* XXX TODO: how to limit the list frames to send */
4352 if (!qc_send_app_pkts(qc, &qel->pktns->tx.frms)) {
4353 TRACE_DEVEL("qc_send_app_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4354 goto out;
4355 }
4356
4357 out:
4358 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
4359 return t;
4360}
4361
4362/* Returns a boolean if <qc> needs to emit frames for <qel> encryption level. */
4363static int qc_need_sending(struct quic_conn *qc, struct quic_enc_level *qel)
4364{
4365 return (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) ||
4366 (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) ||
4367 qel->pktns->tx.pto_probe ||
4368 !LIST_ISEMPTY(&qel->pktns->tx.frms);
4369}
4370
4371/* QUIC connection packet handler task. */
4372struct task *quic_conn_io_cb(struct task *t, void *context, unsigned int state)
4373{
4374 int ret, ssl_err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004375 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004376 enum quic_tls_enc_level tel, next_tel;
4377 struct quic_enc_level *qel, *next_qel;
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004378 /* Early-data encryption level */
4379 struct quic_enc_level *eqel;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004380 struct buffer *buf = NULL;
4381 int st, force_ack, zero_rtt;
4382
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004383 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004384 eqel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004385 st = qc->state;
4386 TRACE_PROTO("connection state", QUIC_EV_CONN_IO_CB, qc, &st);
4387
4388 /* Retranmissions */
4389 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4390 TRACE_DEVEL("retransmission needed", QUIC_EV_CONN_PHPKTS, qc);
4391 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
4392 qc_dgrams_retransmit(qc);
4393 }
4394
4395 if (qc->flags & QUIC_FL_CONN_IO_CB_WAKEUP) {
4396 qc->flags &= ~QUIC_FL_CONN_IO_CB_WAKEUP;
4397 TRACE_DEVEL("needs to wakeup the timer task after the anti-amplicaiton limit was reached",
4398 QUIC_EV_CONN_IO_CB, qc);
4399 /* The I/O handler has been woken up by the dgram parser (qc_lstnr_pkt_rcv())
4400 * after the anti-amplification was reached.
4401 *
4402 * TODO: this part should be removed. This was there because the
4403 * datagram parser was not executed by only one thread.
4404 */
4405 qc_set_timer(qc);
Amaury Denoyelle5ac6b3b2022-12-14 18:04:06 +01004406 if (qc->timer_task && tick_isset(qc->timer) && tick_is_lt(qc->timer, now_ms))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004407 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
4408 }
4409 ssl_err = SSL_ERROR_NONE;
4410 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004411 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004412 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004413
4414 if (qc_test_fd(qc))
4415 qc_rcv_buf(qc);
4416
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004417 if (st >= QUIC_HS_ST_COMPLETE &&
4418 qc_el_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
4419 TRACE_DEVEL("remaining Handshake packets", QUIC_EV_CONN_PHPKTS, qc);
4420 /* There may be remaining Handshake packets to treat and acknowledge. */
4421 tel = QUIC_TLS_ENC_LEVEL_HANDSHAKE;
4422 next_tel = QUIC_TLS_ENC_LEVEL_APP;
4423 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004424 else if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, zero_rtt))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004425 goto out;
4426
4427 qel = &qc->els[tel];
4428 next_qel = next_tel == QUIC_TLS_ENC_LEVEL_NONE ? NULL : &qc->els[next_tel];
4429
4430 next_level:
4431 /* Treat packets waiting for header packet protection decryption */
4432 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4433 qc_rm_hp_pkts(qc, qel);
4434
4435 force_ack = qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
4436 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004437 if (!qc_treat_rx_pkts(qc, qel, next_qel, force_ack))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004438 goto out;
4439
4440 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4441 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE))
4442 goto out;
4443
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004444 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004445 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004446 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
4447 if (next_qel && next_qel == eqel && zero_rtt) {
4448 TRACE_DEVEL("select 0RTT as next encryption level",
4449 QUIC_EV_CONN_PHPKTS, qc);
4450 qel = next_qel;
4451 next_qel = NULL;
4452 goto next_level;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004453 }
4454
4455 st = qc->state;
4456 if (st >= QUIC_HS_ST_COMPLETE) {
4457 if (!(qc->flags & QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT) &&
4458 !quic_build_post_handshake_frames(qc))
4459 goto out;
4460
4461 if (!(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].tls_ctx.flags &
4462 QUIC_FL_TLS_SECRETS_DCD)) {
4463 /* Discard the Handshake keys. */
4464 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4465 TRACE_PROTO("discarding Handshake pktns", QUIC_EV_CONN_PHPKTS, qc);
4466 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, qc);
4467 qc_set_timer(qc);
4468 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4469 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns);
4470 }
4471
4472 if (qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) {
4473 /* There may be remaining handshake to build (acks) */
4474 st = QUIC_HS_ST_SERVER_HANDSHAKE;
4475 }
4476 }
4477
4478 /* A listener does not send any O-RTT packet. O-RTT packet number space must not
4479 * be considered.
4480 */
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004481 if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, 0))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004482 goto out;
4483
4484 if (!qc_need_sending(qc, qel) &&
4485 (!next_qel || !qc_need_sending(qc, next_qel))) {
4486 goto skip_send;
4487 }
4488
4489 buf = qc_txb_alloc(qc);
4490 if (!buf)
4491 goto out;
4492
4493 /* Currently buf cannot be non-empty at this stage. Even if a previous
4494 * sendto() has failed it is emptied to simulate packet emission and
4495 * rely on QUIC lost detection to try to emit it.
4496 */
4497 BUG_ON_HOT(b_data(buf));
4498 b_reset(buf);
4499
4500 ret = qc_prep_pkts(qc, buf, tel, &qc->els[tel].pktns->tx.frms,
4501 next_tel, &qc->els[next_tel].pktns->tx.frms);
4502 if (ret == -1)
4503 goto out;
4504 else if (ret == 0)
4505 goto skip_send;
4506
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004507 if (!qc_send_ppkts(buf, qc->xprt_ctx))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004508 goto out;
4509
4510 skip_send:
4511 /* Check if there is something to do for the next level.
4512 */
4513 if (next_qel && next_qel != qel &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004514 quic_tls_has_rx_sec(next_qel) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004515 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || qc_el_rx_pkts(next_qel))) {
4516 qel = next_qel;
4517 next_qel = NULL;
4518 goto next_level;
4519 }
4520
4521 out:
4522 qc_txb_release(qc);
4523 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc, &st, &ssl_err);
4524 return t;
4525}
4526
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004527/* Release the memory allocated for <cs> CRYPTO stream */
4528void quic_cstream_free(struct quic_cstream *cs)
4529{
4530 if (!cs) {
4531 /* This is the case for ORTT encryption level */
4532 return;
4533 }
4534
Amaury Denoyellebc174b22022-11-17 10:12:52 +01004535 quic_free_ncbuf(&cs->rx.ncbuf);
4536
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004537 qc_stream_desc_release(cs->desc);
4538 pool_free(pool_head_quic_cstream, cs);
4539}
4540
4541/* Allocate a new QUIC stream for <qc>.
4542 * Return it if succeeded, NULL if not.
4543 */
4544struct quic_cstream *quic_cstream_new(struct quic_conn *qc)
4545{
4546 struct quic_cstream *cs, *ret_cs = NULL;
4547
4548 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4549 cs = pool_alloc(pool_head_quic_cstream);
4550 if (!cs) {
4551 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4552 goto leave;
4553 }
4554
4555 cs->rx.offset = 0;
4556 cs->rx.ncbuf = NCBUF_NULL;
4557 cs->rx.offset = 0;
4558
4559 cs->tx.offset = 0;
4560 cs->tx.sent_offset = 0;
4561 cs->tx.buf = BUF_NULL;
4562 cs->desc = qc_stream_desc_new((uint64_t)-1, -1, cs, qc);
4563 if (!cs->desc) {
4564 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4565 goto err;
4566 }
4567
4568 ret_cs = cs;
4569 leave:
4570 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4571 return ret_cs;
4572
4573 err:
4574 pool_free(pool_head_quic_cstream, cs);
4575 goto leave;
4576}
4577
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004578/* Uninitialize <qel> QUIC encryption level. Never fails. */
4579static void quic_conn_enc_level_uninit(struct quic_conn *qc, struct quic_enc_level *qel)
4580{
4581 int i;
4582
4583 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4584
4585 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
4586 if (qel->tx.crypto.bufs[i]) {
4587 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
4588 qel->tx.crypto.bufs[i] = NULL;
4589 }
4590 }
4591 ha_free(&qel->tx.crypto.bufs);
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004592 quic_cstream_free(qel->cstream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004593
4594 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4595}
4596
4597/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
4598 * connection allocating everything needed.
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004599 *
4600 * Returns 1 if succeeded, 0 if not. On error the caller is responsible to use
4601 * quic_conn_enc_level_uninit() to cleanup partially allocated content.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004602 */
4603static int quic_conn_enc_level_init(struct quic_conn *qc,
4604 enum quic_tls_enc_level level)
4605{
4606 int ret = 0;
4607 struct quic_enc_level *qel;
4608
4609 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4610
4611 qel = &qc->els[level];
4612 qel->level = quic_to_ssl_enc_level(level);
4613 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
4614 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
4615 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
4616 qel->tls_ctx.flags = 0;
4617
4618 qel->rx.pkts = EB_ROOT;
4619 LIST_INIT(&qel->rx.pqpkts);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004620
4621 /* Allocate only one buffer. */
4622 /* TODO: use a pool */
4623 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
4624 if (!qel->tx.crypto.bufs)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004625 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004626
4627 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
4628 if (!qel->tx.crypto.bufs[0])
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004629 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004630
4631 qel->tx.crypto.bufs[0]->sz = 0;
4632 qel->tx.crypto.nb_buf = 1;
4633
4634 qel->tx.crypto.sz = 0;
4635 qel->tx.crypto.offset = 0;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004636 /* No CRYPTO data for early data TLS encryption level */
4637 if (level == QUIC_TLS_ENC_LEVEL_EARLY_DATA)
4638 qel->cstream = NULL;
4639 else {
4640 qel->cstream = quic_cstream_new(qc);
4641 if (!qel->cstream)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004642 goto leave;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004643 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004644
4645 ret = 1;
4646 leave:
4647 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4648 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004649}
4650
4651/* Callback called upon loss detection and PTO timer expirations. */
4652struct task *qc_process_timer(struct task *task, void *ctx, unsigned int state)
4653{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004654 struct quic_conn *qc = ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004655 struct quic_pktns *pktns;
4656
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004657 TRACE_ENTER(QUIC_EV_CONN_PTIMER, qc,
4658 NULL, NULL, &qc->path->ifae_pkts);
4659 task->expire = TICK_ETERNITY;
4660 pktns = quic_loss_pktns(qc);
4661 if (tick_isset(pktns->tx.loss_time)) {
4662 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
4663
4664 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
4665 if (!LIST_ISEMPTY(&lost_pkts))
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004666 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004667 qc_release_lost_pkts(qc, pktns, &lost_pkts, now_ms);
4668 qc_set_timer(qc);
4669 goto out;
4670 }
4671
4672 if (qc->path->in_flight) {
4673 pktns = quic_pto_pktns(qc, qc->state >= QUIC_HS_ST_COMPLETE, NULL);
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02004674 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004675 pktns->tx.pto_probe = QUIC_MAX_NB_PTO_DGRAMS;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02004676 tasklet_wakeup(qc->subs->tasklet);
4677 qc->subs->events &= ~SUB_RETRY_SEND;
4678 if (!qc->subs->events)
4679 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004680 }
4681 else {
4682 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4683 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4684 if (pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL]) {
4685 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4686 if (qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].tx.in_flight) {
4687 qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4688 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
4689 }
4690 }
4691 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE]) {
4692 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
4693 }
4694 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT]) {
4695 TRACE_STATE("needs to probe 01RTT packet number space", QUIC_EV_CONN_TXPKT, qc);
4696 }
4697 }
4698 }
4699 else if (!qc_is_listener(qc) && qc->state <= QUIC_HS_ST_COMPLETE) {
4700 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4701 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4702
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004703 if (quic_tls_has_tx_sec(hel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004704 hel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004705 if (quic_tls_has_tx_sec(iel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004706 iel->pktns->tx.pto_probe = 1;
4707 }
4708
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004709 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004710 qc->path->loss.pto_count++;
4711
4712 out:
4713 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, qc, pktns);
4714
4715 return task;
4716}
4717
4718/* Parse the Retry token from buffer <token> with <end> a pointer to
4719 * one byte past the end of this buffer. This will extract the ODCID
4720 * which will be stored into <odcid>
4721 *
4722 * Returns 0 on success else non-zero.
4723 */
4724static int parse_retry_token(struct quic_conn *qc,
4725 const unsigned char *token, const unsigned char *end,
4726 struct quic_cid *odcid)
4727{
4728 int ret = 0;
4729 uint64_t odcid_len;
4730 uint32_t timestamp;
4731
4732 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4733
4734 if (!quic_dec_int(&odcid_len, &token, end)) {
4735 TRACE_ERROR("quic_dec_int() error", QUIC_EV_CONN_LPKT, qc);
4736 goto leave;
4737 }
4738
4739 /* RFC 9000 7.2. Negotiating Connection IDs:
4740 * When an Initial packet is sent by a client that has not previously
4741 * received an Initial or Retry packet from the server, the client
4742 * populates the Destination Connection ID field with an unpredictable
4743 * value. This Destination Connection ID MUST be at least 8 bytes in length.
4744 */
4745 if (odcid_len < QUIC_ODCID_MINLEN || odcid_len > QUIC_CID_MAXLEN) {
4746 TRACE_ERROR("wrong ODCID length", QUIC_EV_CONN_LPKT, qc);
4747 goto leave;
4748 }
4749
4750 if (end - token < odcid_len + sizeof timestamp) {
4751 TRACE_ERROR("too long ODCID length", QUIC_EV_CONN_LPKT, qc);
4752 goto leave;
4753 }
4754
4755 timestamp = ntohl(read_u32(token + odcid_len));
4756 if (timestamp + MS_TO_TICKS(QUIC_RETRY_DURATION_MS) <= now_ms) {
4757 TRACE_ERROR("token has expired", QUIC_EV_CONN_LPKT, qc);
4758 goto leave;
4759 }
4760
4761 ret = 1;
4762 memcpy(odcid->data, token, odcid_len);
4763 odcid->len = odcid_len;
4764 leave:
4765 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4766 return !ret;
4767}
4768
4769/* Allocate a new QUIC connection with <version> as QUIC version. <ipv4>
4770 * boolean is set to 1 for IPv4 connection, 0 for IPv6. <server> is set to 1
4771 * for QUIC servers (or haproxy listeners).
4772 * <dcid> is the destination connection ID, <scid> is the source connection ID,
4773 * <token> the token found to be used for this connection with <token_len> as
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004774 * length. Endpoints addresses are specified via <local_addr> and <peer_addr>.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004775 * Returns the connection if succeeded, NULL if not.
4776 */
4777static struct quic_conn *qc_new_conn(const struct quic_version *qv, int ipv4,
4778 struct quic_cid *dcid, struct quic_cid *scid,
4779 const struct quic_cid *token_odcid,
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004780 struct sockaddr_storage *local_addr,
4781 struct sockaddr_storage *peer_addr,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004782 int server, int token, void *owner)
4783{
4784 int i;
4785 struct quic_conn *qc;
4786 /* Initial CID. */
4787 struct quic_connection_id *icid;
4788 char *buf_area = NULL;
4789 struct listener *l = NULL;
4790 struct quic_cc_algo *cc_algo = NULL;
4791 struct quic_tls_ctx *ictx;
4792 TRACE_ENTER(QUIC_EV_CONN_INIT);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004793 /* TODO replace pool_zalloc by pool_alloc(). This requires special care
4794 * to properly initialized internal quic_conn members to safely use
4795 * quic_conn_release() on alloc failure.
4796 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004797 qc = pool_zalloc(pool_head_quic_conn);
4798 if (!qc) {
4799 TRACE_ERROR("Could not allocate a new connection", QUIC_EV_CONN_INIT);
4800 goto err;
4801 }
4802
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004803 /* Initialize in priority qc members required for a safe dealloc. */
4804
4805 /* required to use MTLIST_IN_LIST */
4806 MT_LIST_INIT(&qc->accept_list);
4807
4808 LIST_INIT(&qc->rx.pkt_list);
4809
Amaury Denoyelle42448332022-12-12 11:24:05 +01004810 qc_init_fd(qc);
4811
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004812 /* Now proceeds to allocation of qc members. */
4813
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004814 buf_area = pool_alloc(pool_head_quic_conn_rxbuf);
4815 if (!buf_area) {
4816 TRACE_ERROR("Could not allocate a new RX buffer", QUIC_EV_CONN_INIT, qc);
4817 goto err;
4818 }
4819
4820 qc->cids = EB_ROOT;
4821 /* QUIC Server (or listener). */
4822 if (server) {
4823 struct proxy *prx;
4824
4825 l = owner;
4826 prx = l->bind_conf->frontend;
4827 cc_algo = l->bind_conf->quic_cc_algo;
4828
4829 qc->prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe,
4830 &quic_stats_module);
4831 qc->flags |= QUIC_FL_CONN_LISTENER;
4832 qc->state = QUIC_HS_ST_SERVER_INITIAL;
4833 /* Copy the initial DCID with the address. */
4834 qc->odcid.len = dcid->len;
4835 qc->odcid.addrlen = dcid->addrlen;
4836 memcpy(qc->odcid.data, dcid->data, dcid->len + dcid->addrlen);
4837
4838 /* copy the packet SCID to reuse it as DCID for sending */
4839 if (scid->len)
4840 memcpy(qc->dcid.data, scid->data, scid->len);
4841 qc->dcid.len = scid->len;
4842 qc->tx.buf = BUF_NULL;
4843 qc->li = l;
4844 }
4845 /* QUIC Client (outgoing connection to servers) */
4846 else {
4847 qc->state = QUIC_HS_ST_CLIENT_INITIAL;
4848 if (dcid->len)
4849 memcpy(qc->dcid.data, dcid->data, dcid->len);
4850 qc->dcid.len = dcid->len;
4851 }
4852 qc->mux_state = QC_MUX_NULL;
4853 qc->err = quic_err_transport(QC_ERR_NO_ERROR);
4854
4855 icid = new_quic_cid(&qc->cids, qc, 0);
4856 if (!icid) {
4857 TRACE_ERROR("Could not allocate a new connection ID", QUIC_EV_CONN_INIT, qc);
4858 goto err;
4859 }
4860
Amaury Denoyelle40909df2022-10-24 17:08:43 +02004861 if ((global.tune.options & GTUNE_QUIC_SOCK_PER_CONN) &&
4862 is_addr(local_addr)) {
4863 TRACE_USER("Allocate a socket for QUIC connection", QUIC_EV_CONN_INIT, qc);
4864 qc_alloc_fd(qc, local_addr, peer_addr);
4865 }
Amaury Denoyelle40909df2022-10-24 17:08:43 +02004866
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004867 /* insert the allocated CID in the receiver datagram handler tree */
4868 if (server)
4869 ebmb_insert(&quic_dghdlrs[tid].cids, &icid->node, icid->cid.len);
4870
4871 /* Select our SCID which is the first CID with 0 as sequence number. */
4872 qc->scid = icid->cid;
4873
4874 /* Packet number spaces initialization. */
4875 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
4876 quic_pktns_init(&qc->pktns[i]);
4877 /* QUIC encryption level context initialization. */
4878 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
4879 if (!quic_conn_enc_level_init(qc, i)) {
4880 TRACE_ERROR("Could not initialize an encryption level", QUIC_EV_CONN_INIT, qc);
4881 goto err;
4882 }
4883 /* Initialize the packet number space. */
4884 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
4885 }
4886
4887 qc->original_version = qv;
4888 qc->tps_tls_ext = (qc->original_version->num & 0xff000000) == 0xff000000 ?
4889 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS_DRAFT:
4890 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS;
4891 /* TX part. */
4892 LIST_INIT(&qc->tx.frms_to_send);
4893 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
4894 qc->tx.wbuf = qc->tx.rbuf = 0;
4895 qc->tx.bytes = 0;
4896 qc->tx.buf = BUF_NULL;
4897 /* RX part. */
4898 qc->rx.bytes = 0;
4899 qc->rx.buf = b_make(buf_area, QUIC_CONN_RX_BUFSZ, 0, 0);
4900 for (i = 0; i < QCS_MAX_TYPES; i++)
4901 qc->rx.strms[i].nb_streams = 0;
4902
4903 qc->nb_pkt_for_cc = 1;
4904 qc->nb_pkt_since_cc = 0;
4905
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004906 if (!quic_tls_ku_init(qc)) {
4907 TRACE_ERROR("Key update initialization failed", QUIC_EV_CONN_INIT, qc);
4908 goto err;
4909 }
4910
4911 /* XXX TO DO: Only one path at this time. */
4912 qc->path = &qc->paths[0];
4913 quic_path_init(qc->path, ipv4, cc_algo ? cc_algo : default_quic_cc_algo, qc);
4914
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004915 qc->streams_by_id = EB_ROOT_UNIQUE;
4916 qc->stream_buf_count = 0;
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004917 memcpy(&qc->local_addr, local_addr, sizeof(qc->local_addr));
4918 memcpy(&qc->peer_addr, peer_addr, sizeof qc->peer_addr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004919
4920 if (server && !qc_lstnr_params_init(qc, &l->bind_conf->quic_params,
4921 icid->stateless_reset_token,
4922 dcid->data, dcid->len,
4923 qc->scid.data, qc->scid.len, token_odcid))
4924 goto err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004925
4926 qc->wait_event.tasklet = tasklet_new();
4927 if (!qc->wait_event.tasklet) {
4928 TRACE_ERROR("tasklet_new() failed", QUIC_EV_CONN_TXPKT);
4929 goto err;
4930 }
4931 qc->wait_event.tasklet->process = quic_conn_io_cb;
4932 qc->wait_event.tasklet->context = qc;
4933 qc->wait_event.events = 0;
4934 /* Set tasklet tid based on the SCID selected by us for this
4935 * connection. The upper layer will also be binded on the same thread.
4936 */
Willy Tarreaueed78262022-12-21 09:09:19 +01004937 qc->tid = quic_get_cid_tid(qc->scid.data, &l->rx);
Willy Tarreauf5a0c8a2022-10-13 16:14:11 +02004938 qc->wait_event.tasklet->tid = qc->tid;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02004939 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004940
4941 if (qc_conn_alloc_ssl_ctx(qc) ||
4942 !quic_conn_init_timer(qc) ||
4943 !quic_conn_init_idle_timer_task(qc))
4944 goto err;
4945
4946 ictx = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
4947 if (!qc_new_isecs(qc, ictx,qc->original_version, dcid->data, dcid->len, 1))
4948 goto err;
4949
4950 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc);
4951
4952 return qc;
4953
4954 err:
4955 pool_free(pool_head_quic_conn_rxbuf, buf_area);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004956 if (qc) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004957 qc->rx.buf.area = NULL;
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004958 quic_conn_release(qc);
4959 }
4960 TRACE_LEAVE(QUIC_EV_CONN_INIT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004961 return NULL;
4962}
4963
4964/* Release the quic_conn <qc>. The connection is removed from the CIDs tree.
4965 * The connection tasklet is killed.
4966 *
4967 * This function must only be called by the thread responsible of the quic_conn
4968 * tasklet.
4969 */
4970void quic_conn_release(struct quic_conn *qc)
4971{
4972 int i;
4973 struct ssl_sock_ctx *conn_ctx;
4974 struct eb64_node *node;
4975 struct quic_tls_ctx *app_tls_ctx;
4976 struct quic_rx_packet *pkt, *pktback;
4977
4978 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4979
4980 /* We must not free the quic-conn if the MUX is still allocated. */
4981 BUG_ON(qc->mux_state == QC_MUX_READY);
4982
Amaury Denoyelle40909df2022-10-24 17:08:43 +02004983 /* Close quic-conn socket fd. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01004984 qc_release_fd(qc, 0);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02004985
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004986 /* in the unlikely (but possible) case the connection was just added to
4987 * the accept_list we must delete it from there.
4988 */
4989 MT_LIST_DELETE(&qc->accept_list);
4990
4991 /* free remaining stream descriptors */
4992 node = eb64_first(&qc->streams_by_id);
4993 while (node) {
4994 struct qc_stream_desc *stream;
4995
4996 stream = eb64_entry(node, struct qc_stream_desc, by_id);
4997 node = eb64_next(node);
4998
4999 /* all streams attached to the quic-conn are released, so
5000 * qc_stream_desc_free will liberate the stream instance.
5001 */
5002 BUG_ON(!stream->release);
5003 qc_stream_desc_free(stream, 1);
5004 }
5005
5006 /* Purge Rx packet list. */
5007 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
5008 LIST_DELETE(&pkt->qc_rx_pkt_list);
5009 pool_free(pool_head_quic_rx_packet, pkt);
5010 }
5011
5012 if (qc->idle_timer_task) {
5013 task_destroy(qc->idle_timer_task);
5014 qc->idle_timer_task = NULL;
5015 }
5016
5017 if (qc->timer_task) {
5018 task_destroy(qc->timer_task);
5019 qc->timer_task = NULL;
5020 }
5021
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005022 if (qc->wait_event.tasklet)
5023 tasklet_free(qc->wait_event.tasklet);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005024
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005025 /* remove the connection from receiver cids trees */
5026 ebmb_delete(&qc->odcid_node);
5027 ebmb_delete(&qc->scid_node);
5028 free_quic_conn_cids(qc);
5029
5030 conn_ctx = qc->xprt_ctx;
5031 if (conn_ctx) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005032 SSL_free(conn_ctx->ssl);
5033 pool_free(pool_head_quic_conn_ctx, conn_ctx);
5034 }
5035
5036 quic_tls_ku_free(qc);
5037 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5038 quic_tls_ctx_secs_free(&qc->els[i].tls_ctx);
5039 quic_conn_enc_level_uninit(qc, &qc->els[i]);
5040 }
5041 quic_tls_ctx_secs_free(&qc->negotiated_ictx);
5042
5043 app_tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
5044 pool_free(pool_head_quic_tls_secret, app_tls_ctx->rx.secret);
5045 pool_free(pool_head_quic_tls_secret, app_tls_ctx->tx.secret);
5046
5047 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++) {
5048 quic_pktns_tx_pkts_release(&qc->pktns[i], qc);
5049 quic_free_arngs(qc, &qc->pktns[i].rx.arngs);
5050 }
5051
5052 pool_free(pool_head_quic_conn_rxbuf, qc->rx.buf.area);
5053 pool_free(pool_head_quic_conn, qc);
5054 TRACE_PROTO("QUIC conn. freed", QUIC_EV_CONN_FREED, qc);
5055
5056 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5057}
5058
5059/* Initialize the timer task of <qc> QUIC connection.
5060 * Returns 1 if succeeded, 0 if not.
5061 */
5062static int quic_conn_init_timer(struct quic_conn *qc)
5063{
5064 int ret = 0;
5065 /* Attach this task to the same thread ID used for the connection */
5066 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5067
5068 qc->timer_task = task_new_on(qc->tid);
5069 if (!qc->timer_task) {
5070 TRACE_ERROR("timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5071 goto leave;
5072 }
5073
5074 qc->timer = TICK_ETERNITY;
5075 qc->timer_task->process = qc_process_timer;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005076 qc->timer_task->context = qc;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005077
5078 ret = 1;
5079 leave:
5080 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5081 return ret;
5082}
5083
5084/* Rearm the idle timer for <qc> QUIC connection. */
5085static void qc_idle_timer_do_rearm(struct quic_conn *qc)
5086{
5087 unsigned int expire;
5088
5089 expire = QUIC_MAX(3 * quic_pto(qc), qc->max_idle_timeout);
5090 qc->idle_timer_task->expire = tick_add(now_ms, MS_TO_TICKS(expire));
5091}
5092
5093/* Rearm the idle timer for <qc> QUIC connection depending on <read> boolean
5094 * which is set to 1 when receiving a packet , and 0 when sending packet
5095 */
5096static void qc_idle_timer_rearm(struct quic_conn *qc, int read)
5097{
5098 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5099
5100 if (read) {
5101 qc->flags |= QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5102 }
5103 else {
5104 qc->flags &= ~QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5105 }
5106 qc_idle_timer_do_rearm(qc);
5107
5108 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5109}
5110
5111/* The task handling the idle timeout */
5112struct task *qc_idle_timer_task(struct task *t, void *ctx, unsigned int state)
5113{
5114 struct quic_conn *qc = ctx;
5115 struct quic_counters *prx_counters = qc->prx_counters;
5116 unsigned int qc_flags = qc->flags;
5117
5118 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5119
5120 /* Notify the MUX before settings QUIC_FL_CONN_EXP_TIMER or the MUX
5121 * might free the quic-conn too early via quic_close().
5122 */
5123 qc_notify_close(qc);
5124
5125 /* If the MUX is still alive, keep the quic-conn. The MUX is
5126 * responsible to call quic_close to release it.
5127 */
5128 qc->flags |= QUIC_FL_CONN_EXP_TIMER;
5129 if (qc->mux_state != QC_MUX_READY)
5130 quic_conn_release(qc);
5131
5132 /* TODO if the quic-conn cannot be freed because of the MUX, we may at
5133 * least clean some parts of it such as the tasklet.
5134 */
5135
5136 if (!(qc_flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
5137 qc_flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
5138 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
5139 HA_ATOMIC_DEC(&prx_counters->half_open_conn);
5140 }
5141
5142 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5143 return NULL;
5144}
5145
5146/* Initialize the idle timeout task for <qc>.
5147 * Returns 1 if succeeded, 0 if not.
5148 */
5149static int quic_conn_init_idle_timer_task(struct quic_conn *qc)
5150{
5151 int ret = 0;
5152
5153 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5154
5155 qc->idle_timer_task = task_new_here();
5156 if (!qc->idle_timer_task) {
5157 TRACE_ERROR("Idle timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5158 goto leave;
5159 }
5160
5161 qc->idle_timer_task->process = qc_idle_timer_task;
5162 qc->idle_timer_task->context = qc;
5163 qc_idle_timer_rearm(qc, 1);
5164 task_queue(qc->idle_timer_task);
5165
5166 ret = 1;
5167 leave:
5168 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5169 return ret;
5170}
5171
5172/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
5173 * past one byte of this buffer.
5174 */
5175static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
5176 struct quic_rx_packet *pkt)
5177{
5178 int ret = 0;
5179 unsigned char dcid_len, scid_len;
5180
5181 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5182
5183 if (end == *buf) {
5184 TRACE_ERROR("buffer data consumed", QUIC_EV_CONN_RXPKT);
5185 goto leave;
5186 }
5187
5188 /* Destination Connection ID Length */
5189 dcid_len = *(*buf)++;
5190 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
5191 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1) {
5192 TRACE_ERROR("too long DCID", QUIC_EV_CONN_RXPKT);
5193 goto leave;
5194 }
5195
5196 if (dcid_len) {
5197 /* Check that the length of this received DCID matches the CID lengths
5198 * of our implementation for non Initials packets only.
5199 */
5200 if (pkt->type != QUIC_PACKET_TYPE_INITIAL &&
5201 pkt->type != QUIC_PACKET_TYPE_0RTT &&
5202 dcid_len != QUIC_HAP_CID_LEN) {
5203 TRACE_ERROR("wrong DCID length", QUIC_EV_CONN_RXPKT);
5204 goto leave;
5205 }
5206
5207 memcpy(pkt->dcid.data, *buf, dcid_len);
5208 }
5209
5210 pkt->dcid.len = dcid_len;
5211 *buf += dcid_len;
5212
5213 /* Source Connection ID Length */
5214 scid_len = *(*buf)++;
5215 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len) {
5216 TRACE_ERROR("too long SCID", QUIC_EV_CONN_RXPKT);
5217 goto leave;
5218 }
5219
5220 if (scid_len)
5221 memcpy(pkt->scid.data, *buf, scid_len);
5222 pkt->scid.len = scid_len;
5223 *buf += scid_len;
5224
5225 ret = 1;
5226 leave:
5227 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5228 return ret;
5229}
5230
5231/* Insert <pkt> RX packet in its <qel> RX packets tree */
5232static void qc_pkt_insert(struct quic_conn *qc,
5233 struct quic_rx_packet *pkt, struct quic_enc_level *qel)
5234{
5235 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
5236
5237 pkt->pn_node.key = pkt->pn;
5238 quic_rx_packet_refinc(pkt);
5239 eb64_insert(&qel->rx.pkts, &pkt->pn_node);
5240
5241 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5242}
5243
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005244/* Try to remove the header protection of <pkt> QUIC packet with <beg> the
5245 * address of the packet first byte, using the keys from encryption level <el>.
5246 *
5247 * If header protection has been successfully removed, packet data are copied
5248 * into <qc> Rx buffer. If <el> secrets are not yet available, the copy is also
5249 * proceeded, and the packet is inserted into <qc> protected packets tree. In
5250 * both cases, packet can now be considered handled by the <qc> connection.
5251 *
5252 * If header protection cannot be removed due to <el> secrets already
5253 * discarded, no operation is conducted.
5254 *
5255 * Returns 1 on success : packet data is now handled by the connection. On
5256 * error 0 is returned : packet should be dropped by the caller.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005257 */
5258static inline int qc_try_rm_hp(struct quic_conn *qc,
5259 struct quic_rx_packet *pkt,
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005260 unsigned char *beg,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005261 struct quic_enc_level **el)
5262{
5263 int ret = 0;
5264 unsigned char *pn = NULL; /* Packet number field */
5265 enum quic_tls_enc_level tel;
5266 struct quic_enc_level *qel;
5267 /* Only for traces. */
5268 struct quic_rx_packet *qpkt_trace;
5269
5270 qpkt_trace = NULL;
5271 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005272 BUG_ON(!pkt->pn_offset);
5273
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005274 /* The packet number is here. This is also the start minus
5275 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
5276 * protection.
5277 */
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005278 pn = beg + pkt->pn_offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005279
5280 tel = quic_packet_type_enc_level(pkt->type);
5281 qel = &qc->els[tel];
5282
5283 if (qc_qel_may_rm_hp(qc, qel)) {
5284 /* Note that the following function enables us to unprotect the packet
5285 * number and its length subsequently used to decrypt the entire
5286 * packets.
5287 */
5288 if (!qc_do_rm_hp(qc, pkt, &qel->tls_ctx,
5289 qel->pktns->rx.largest_pn, pn, beg)) {
5290 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, qc);
5291 goto out;
5292 }
5293
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005294 /* The AAD includes the packet number field. */
5295 pkt->aad_len = pkt->pn_offset + pkt->pnl;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005296 if (pkt->len - pkt->aad_len < QUIC_TLS_TAG_LEN) {
5297 TRACE_PROTO("Too short packet", QUIC_EV_CONN_TRMHP, qc);
5298 goto out;
5299 }
5300
5301 qpkt_trace = pkt;
5302 }
5303 else {
5304 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
5305 /* If the packet number space has been discarded, this packet
5306 * will be not parsed.
5307 */
5308 TRACE_PROTO("Discarded pktns", QUIC_EV_CONN_TRMHP, qc, pkt);
5309 goto out;
5310 }
5311
5312 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005313 LIST_APPEND(&qel->rx.pqpkts, &pkt->list);
5314 quic_rx_packet_refinc(pkt);
5315 }
5316
5317 *el = qel;
5318 /* No reference counter incrementation here!!! */
5319 LIST_APPEND(&qc->rx.pkt_list, &pkt->qc_rx_pkt_list);
5320 memcpy(b_tail(&qc->rx.buf), beg, pkt->len);
5321 pkt->data = (unsigned char *)b_tail(&qc->rx.buf);
5322 b_add(&qc->rx.buf, pkt->len);
5323
5324 ret = 1;
5325 out:
5326 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc, qpkt_trace);
5327 return ret;
5328}
5329
5330/* Parse the header form from <byte0> first byte of <pkt> packet to set its type.
5331 * Also set <*long_header> to 1 if this form is long, 0 if not and the version
5332 * of this packet into <*version>.
5333 */
5334static inline int qc_parse_hd_form(struct quic_rx_packet *pkt,
5335 unsigned char **buf, const unsigned char *end,
5336 int *long_header, uint32_t *version)
5337{
5338 int ret = 0;
5339 const unsigned char byte0 = **buf;
5340
5341 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5342
5343 (*buf)++;
5344 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
5345 unsigned char type =
5346 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
5347
5348 *long_header = 1;
5349 /* Version */
5350 if (!quic_read_uint32(version, (const unsigned char **)buf, end)) {
5351 TRACE_ERROR("could not read the packet version", QUIC_EV_CONN_RXPKT);
5352 goto out;
5353 }
5354
Frédéric Lécaille21c4c9b2023-01-13 16:37:02 +01005355 if (*version != QUIC_PROTOCOL_VERSION_2) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005356 pkt->type = type;
5357 }
5358 else {
5359 switch (type) {
5360 case 0:
5361 pkt->type = QUIC_PACKET_TYPE_RETRY;
5362 break;
5363 case 1:
5364 pkt->type = QUIC_PACKET_TYPE_INITIAL;
5365 break;
5366 case 2:
5367 pkt->type = QUIC_PACKET_TYPE_0RTT;
5368 break;
5369 case 3:
5370 pkt->type = QUIC_PACKET_TYPE_HANDSHAKE;
5371 break;
5372 }
5373 }
5374 }
5375 else {
5376 pkt->type = QUIC_PACKET_TYPE_SHORT;
5377 *long_header = 0;
5378 }
5379
5380 ret = 1;
5381 out:
5382 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5383 return ret;
5384}
5385
5386/* Return the QUIC version (quic_version struct) with <version> as version number
5387 * if supported or NULL if not.
5388 */
5389static inline const struct quic_version *qc_supported_version(uint32_t version)
5390{
5391 int i;
5392
5393 for (i = 0; i < quic_versions_nb; i++)
5394 if (quic_versions[i].num == version)
5395 return &quic_versions[i];
5396
5397 return NULL;
5398}
5399
5400/*
5401 * Send a Version Negotiation packet on response to <pkt> on socket <fd> to
5402 * address <addr>.
5403 * Implementation of RFC9000 6. Version Negotiation
5404 *
5405 * TODO implement a rate-limiting sending of Version Negotiation packets
5406 *
5407 * Returns 0 on success else non-zero
5408 */
5409static int send_version_negotiation(int fd, struct sockaddr_storage *addr,
5410 struct quic_rx_packet *pkt)
5411{
5412 char buf[256];
5413 int ret = 0, i = 0, j;
5414 uint32_t version;
5415 const socklen_t addrlen = get_addr_len(addr);
5416
5417 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5418 /*
5419 * header form
5420 * long header, fixed bit to 0 for Version Negotiation
5421 */
5422 /* TODO: RAND_bytes() should be replaced? */
5423 if (RAND_bytes((unsigned char *)buf, 1) != 1) {
5424 TRACE_ERROR("RAND_bytes() error", QUIC_EV_CONN_TXPKT);
5425 goto out;
5426 }
5427
5428 buf[i++] |= '\x80';
5429 /* null version for Version Negotiation */
5430 buf[i++] = '\x00';
5431 buf[i++] = '\x00';
5432 buf[i++] = '\x00';
5433 buf[i++] = '\x00';
5434
5435 /* source connection id */
5436 buf[i++] = pkt->scid.len;
5437 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5438 i += pkt->scid.len;
5439
5440 /* destination connection id */
5441 buf[i++] = pkt->dcid.len;
5442 memcpy(&buf[i], pkt->dcid.data, pkt->dcid.len);
5443 i += pkt->dcid.len;
5444
5445 /* supported version */
5446 for (j = 0; j < quic_versions_nb; j++) {
5447 version = htonl(quic_versions[j].num);
5448 memcpy(&buf[i], &version, sizeof(version));
5449 i += sizeof(version);
5450 }
5451
5452 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0)
5453 goto out;
5454
5455 ret = 1;
5456 out:
5457 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5458 return !ret;
5459}
5460
5461/* Send a stateless reset packet depending on <pkt> RX packet information
5462 * from <fd> UDP socket to <dst>
5463 * Return 1 if succeeded, 0 if not.
5464 */
5465static int send_stateless_reset(struct listener *l, struct sockaddr_storage *dstaddr,
5466 struct quic_rx_packet *rxpkt)
5467{
5468 int ret = 0, pktlen, rndlen;
5469 unsigned char pkt[64];
5470 const socklen_t addrlen = get_addr_len(dstaddr);
5471 struct proxy *prx;
5472 struct quic_counters *prx_counters;
5473
5474 TRACE_ENTER(QUIC_EV_STATELESS_RST);
5475
5476 prx = l->bind_conf->frontend;
5477 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5478 /* 10.3 Stateless Reset (https://www.rfc-editor.org/rfc/rfc9000.html#section-10.3)
5479 * The resulting minimum size of 21 bytes does not guarantee that a Stateless
5480 * Reset is difficult to distinguish from other packets if the recipient requires
5481 * the use of a connection ID. To achieve that end, the endpoint SHOULD ensure
5482 * that all packets it sends are at least 22 bytes longer than the minimum
5483 * connection ID length that it requests the peer to include in its packets,
5484 * adding PADDING frames as necessary. This ensures that any Stateless Reset
5485 * sent by the peer is indistinguishable from a valid packet sent to the endpoint.
5486 * An endpoint that sends a Stateless Reset in response to a packet that is
5487 * 43 bytes or shorter SHOULD send a Stateless Reset that is one byte shorter
5488 * than the packet it responds to.
5489 */
5490
5491 /* Note that we build at most a 42 bytes QUIC packet to mimic a short packet */
5492 pktlen = rxpkt->len <= 43 ? rxpkt->len - 1 : 0;
5493 pktlen = QUIC_MAX(QUIC_STATELESS_RESET_PACKET_MINLEN, pktlen);
5494 rndlen = pktlen - QUIC_STATELESS_RESET_TOKEN_LEN;
5495
5496 /* Put a header of random bytes */
5497 /* TODO: RAND_bytes() should be replaced */
5498 if (RAND_bytes(pkt, rndlen) != 1) {
5499 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_STATELESS_RST);
5500 goto leave;
5501 }
5502
5503 /* Clear the most significant bit, and set the second one */
5504 *pkt = (*pkt & ~0x80) | 0x40;
5505 if (!quic_stateless_reset_token_cpy(NULL, pkt + rndlen, QUIC_STATELESS_RESET_TOKEN_LEN,
5506 rxpkt->dcid.data, rxpkt->dcid.len))
5507 goto leave;
5508
5509 if (sendto(l->rx.fd, pkt, pktlen, 0, (struct sockaddr *)dstaddr, addrlen) < 0)
5510 goto leave;
5511
5512 ret = 1;
5513 HA_ATOMIC_INC(&prx_counters->stateless_reset_sent);
5514 TRACE_PROTO("stateless reset sent", QUIC_EV_STATELESS_RST, NULL, &rxpkt->dcid);
5515 leave:
5516 TRACE_LEAVE(QUIC_EV_STATELESS_RST);
5517 return ret;
5518}
5519
5520/* QUIC server only function.
5521 * Add AAD to <add> buffer from <cid> connection ID and <addr> socket address.
5522 * This is the responsibility of the caller to check <aad> size is big enough
5523 * to contain these data.
5524 * Return the number of bytes copied to <aad>.
5525 */
5526static int quic_generate_retry_token_aad(unsigned char *aad,
5527 uint32_t version,
5528 const struct quic_cid *cid,
5529 const struct sockaddr_storage *addr)
5530{
5531 unsigned char *p;
5532
5533 p = aad;
5534 memcpy(p, &version, sizeof version);
5535 p += sizeof version;
5536 p += quic_saddr_cpy(p, addr);
5537 memcpy(p, cid->data, cid->len);
5538 p += cid->len;
5539
5540 return p - aad;
5541}
5542
5543/* QUIC server only function.
5544 * Generate the token to be used in Retry packets. The token is written to
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05005545 * <buf> with <len> as length. <odcid> is the original destination connection
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005546 * ID and <dcid> is our side destination connection ID (or client source
5547 * connection ID).
5548 * Returns the length of the encoded token or 0 on error.
5549 */
5550static int quic_generate_retry_token(unsigned char *buf, size_t len,
5551 const uint32_t version,
5552 const struct quic_cid *odcid,
5553 const struct quic_cid *dcid,
5554 struct sockaddr_storage *addr)
5555{
5556 int ret = 0;
5557 unsigned char *p;
5558 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005559 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005560 size_t aadlen;
5561 unsigned char salt[QUIC_RETRY_TOKEN_SALTLEN];
5562 unsigned char key[QUIC_TLS_KEY_LEN];
5563 unsigned char iv[QUIC_TLS_IV_LEN];
5564 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5565 size_t seclen = strlen(global.cluster_secret);
5566 EVP_CIPHER_CTX *ctx = NULL;
5567 const EVP_CIPHER *aead = EVP_aes_128_gcm();
5568 uint32_t timestamp = now_ms;
5569
5570 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5571
5572 /* We copy the odcid into the token, prefixed by its one byte
5573 * length, the format token byte. It is followed by an AEAD TAG, and finally
5574 * the random bytes used to derive the secret to encrypt the token.
5575 */
5576 if (1 + dcid->len + 1 + QUIC_TLS_TAG_LEN + sizeof salt > len)
5577 goto err;
5578
5579 aadlen = quic_generate_retry_token_aad(aad, version, dcid, addr);
5580 /* TODO: RAND_bytes() should be replaced */
5581 if (RAND_bytes(salt, sizeof salt) != 1) {
5582 TRACE_ERROR("RAND_bytes()", QUIC_EV_CONN_TXPKT);
5583 goto err;
5584 }
5585
5586 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5587 salt, sizeof salt, sec, seclen)) {
5588 TRACE_ERROR("quic_tls_derive_retry_token_secret() failed", QUIC_EV_CONN_TXPKT);
5589 goto err;
5590 }
5591
5592 if (!quic_tls_tx_ctx_init(&ctx, aead, key)) {
5593 TRACE_ERROR("quic_tls_tx_ctx_init() failed", QUIC_EV_CONN_TXPKT);
5594 goto err;
5595 }
5596
5597 /* Token build */
5598 p = buf;
5599 *p++ = QUIC_TOKEN_FMT_RETRY,
5600 *p++ = odcid->len;
5601 memcpy(p, odcid->data, odcid->len);
5602 p += odcid->len;
5603 write_u32(p, htonl(timestamp));
5604 p += sizeof timestamp;
5605
5606 /* Do not encrypt the QUIC_TOKEN_FMT_RETRY byte */
5607 if (!quic_tls_encrypt(buf + 1, p - buf - 1, aad, aadlen, ctx, aead, key, iv)) {
5608 TRACE_ERROR("quic_tls_encrypt() failed", QUIC_EV_CONN_TXPKT);
5609 goto err;
5610 }
5611
5612 p += QUIC_TLS_TAG_LEN;
5613 memcpy(p, salt, sizeof salt);
5614 p += sizeof salt;
5615 EVP_CIPHER_CTX_free(ctx);
5616
5617 ret = p - buf;
5618 leave:
5619 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5620 return ret;
5621
5622 err:
5623 if (ctx)
5624 EVP_CIPHER_CTX_free(ctx);
5625 goto leave;
5626}
5627
5628/* QUIC server only function.
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005629 *
5630 * Check the validity of the Retry token from Initial packet <pkt>. <dgram> is
5631 * the UDP datagram containing <pkt> and <l> is the listener instance on which
5632 * it was received. If the token is valid, the ODCID of <qc> QUIC connection
5633 * will be put into <odcid>. <qc> is used to retrieve the QUIC version needed
5634 * to validate the token but it can be NULL : in this case the version will be
5635 * retrieved from the packet.
5636 *
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005637 * Return 1 if succeeded, 0 if not.
5638 */
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005639
5640static int quic_retry_token_check(struct quic_rx_packet *pkt,
5641 struct quic_dgram *dgram,
5642 struct listener *l,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005643 struct quic_conn *qc,
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005644 struct quic_cid *odcid)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005645{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005646 struct proxy *prx;
5647 struct quic_counters *prx_counters;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005648 int ret = 0;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005649 unsigned char *token = pkt->token;
5650 const uint64_t tokenlen = pkt->token_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005651 unsigned char buf[128];
5652 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005653 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005654 size_t aadlen;
5655 const unsigned char *salt;
5656 unsigned char key[QUIC_TLS_KEY_LEN];
5657 unsigned char iv[QUIC_TLS_IV_LEN];
5658 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5659 size_t seclen = strlen(global.cluster_secret);
5660 EVP_CIPHER_CTX *ctx = NULL;
5661 const EVP_CIPHER *aead = EVP_aes_128_gcm();
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005662 const struct quic_version *qv = qc ? qc->original_version :
5663 pkt->version;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005664
5665 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5666
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005667 /* The caller must ensure this. */
5668 BUG_ON(!global.cluster_secret || !pkt->token_len);
5669
5670 prx = l->bind_conf->frontend;
5671 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5672
5673 if (*pkt->token != QUIC_TOKEN_FMT_RETRY) {
5674 /* TODO: New token check */
5675 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
5676 goto leave;
5677 }
5678
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005679 if (sizeof buf < tokenlen) {
5680 TRACE_ERROR("too short buffer", QUIC_EV_CONN_LPKT, qc);
5681 goto err;
5682 }
5683
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005684 aadlen = quic_generate_retry_token_aad(aad, qv->num, &pkt->scid, &dgram->saddr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005685 salt = token + tokenlen - QUIC_RETRY_TOKEN_SALTLEN;
5686 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5687 salt, QUIC_RETRY_TOKEN_SALTLEN, sec, seclen)) {
5688 TRACE_ERROR("Could not derive retry secret", QUIC_EV_CONN_LPKT, qc);
5689 goto err;
5690 }
5691
5692 if (!quic_tls_rx_ctx_init(&ctx, aead, key)) {
5693 TRACE_ERROR("quic_tls_rx_ctx_init() failed", QUIC_EV_CONN_LPKT, qc);
5694 goto err;
5695 }
5696
5697 /* Do not decrypt the QUIC_TOKEN_FMT_RETRY byte */
5698 if (!quic_tls_decrypt2(buf, token + 1, tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, aad, aadlen,
5699 ctx, aead, key, iv)) {
5700 TRACE_ERROR("Could not decrypt retry token", QUIC_EV_CONN_LPKT, qc);
5701 goto err;
5702 }
5703
5704 if (parse_retry_token(qc, buf, buf + tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, odcid)) {
5705 TRACE_ERROR("Error during Initial token parsing", QUIC_EV_CONN_LPKT, qc);
5706 goto err;
5707 }
5708
5709 EVP_CIPHER_CTX_free(ctx);
5710
5711 ret = 1;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005712 HA_ATOMIC_INC(&prx_counters->retry_validated);
5713
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005714 leave:
5715 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5716 return ret;
5717
5718 err:
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005719 HA_ATOMIC_INC(&prx_counters->retry_error);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005720 if (ctx)
5721 EVP_CIPHER_CTX_free(ctx);
5722 goto leave;
5723}
5724
5725/* Generate a Retry packet and send it on <fd> socket to <addr> in response to
5726 * the Initial <pkt> packet.
5727 *
5728 * Returns 0 on success else non-zero.
5729 */
5730static int send_retry(int fd, struct sockaddr_storage *addr,
5731 struct quic_rx_packet *pkt, const struct quic_version *qv)
5732{
5733 int ret = 0;
5734 unsigned char buf[128];
5735 int i = 0, token_len;
5736 const socklen_t addrlen = get_addr_len(addr);
5737 struct quic_cid scid;
5738
5739 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5740
5741 /* long header + fixed bit + packet type QUIC_PACKET_TYPE_RETRY */
5742 buf[i++] = (QUIC_PACKET_LONG_HEADER_BIT | QUIC_PACKET_FIXED_BIT) |
5743 (quic_pkt_type(QUIC_PACKET_TYPE_RETRY, qv->num) << QUIC_PACKET_TYPE_SHIFT);
5744 /* version */
5745 buf[i++] = *((unsigned char *)&qv->num + 3);
5746 buf[i++] = *((unsigned char *)&qv->num + 2);
5747 buf[i++] = *((unsigned char *)&qv->num + 1);
5748 buf[i++] = *(unsigned char *)&qv->num;
5749
5750 /* Use the SCID from <pkt> for Retry DCID. */
5751 buf[i++] = pkt->scid.len;
5752 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5753 i += pkt->scid.len;
5754
5755 /* Generate a new CID to be used as SCID for the Retry packet. */
5756 scid.len = QUIC_HAP_CID_LEN;
5757 /* TODO: RAND_bytes() should be replaced */
5758 if (RAND_bytes(scid.data, scid.len) != 1) {
5759 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT);
5760 goto out;
5761 }
5762
5763 buf[i++] = scid.len;
5764 memcpy(&buf[i], scid.data, scid.len);
5765 i += scid.len;
5766
5767 /* token */
5768 if (!(token_len = quic_generate_retry_token(&buf[i], sizeof(buf) - i, qv->num,
5769 &pkt->dcid, &pkt->scid, addr))) {
5770 TRACE_ERROR("quic_generate_retry_token() failed", QUIC_EV_CONN_TXPKT);
5771 goto out;
5772 }
5773
5774 i += token_len;
5775
5776 /* token integrity tag */
5777 if ((&buf[i] - buf < QUIC_TLS_TAG_LEN) ||
5778 !quic_tls_generate_retry_integrity_tag(pkt->dcid.data,
5779 pkt->dcid.len, buf, i, qv)) {
5780 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
5781 goto out;
5782 }
5783
5784 i += QUIC_TLS_TAG_LEN;
5785
5786 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0) {
5787 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
5788 goto out;
5789 }
5790
5791 ret = 1;
5792 out:
5793 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5794 return !ret;
5795}
5796
5797/* Retrieve a quic_conn instance from the <pkt> DCID field. If the packet is of
5798 * type INITIAL, the ODCID tree is first used. In this case, <saddr> is
5799 * concatenated to the <pkt> DCID field.
5800 *
5801 * Returns the instance or NULL if not found.
5802 */
5803static struct quic_conn *retrieve_qc_conn_from_cid(struct quic_rx_packet *pkt,
5804 struct listener *l,
5805 struct sockaddr_storage *saddr)
5806{
5807 struct quic_conn *qc = NULL;
5808 struct ebmb_node *node;
5809 struct quic_connection_id *id;
5810 /* set if the quic_conn is found in the second DCID tree */
5811
5812 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5813
5814 /* Look first into ODCIDs tree for INITIAL/0-RTT packets. */
5815 if (pkt->type == QUIC_PACKET_TYPE_INITIAL ||
5816 pkt->type == QUIC_PACKET_TYPE_0RTT) {
5817 /* DCIDs of first packets coming from multiple clients may have
5818 * the same values. Let's distinguish them by concatenating the
5819 * socket addresses.
5820 */
5821 quic_cid_saddr_cat(&pkt->dcid, saddr);
5822 node = ebmb_lookup(&quic_dghdlrs[tid].odcids, pkt->dcid.data,
5823 pkt->dcid.len + pkt->dcid.addrlen);
5824 if (node) {
5825 qc = ebmb_entry(node, struct quic_conn, odcid_node);
5826 goto end;
5827 }
5828 }
5829
5830 /* Look into DCIDs tree for non-INITIAL/0-RTT packets. This may be used
5831 * also for INITIAL/0-RTT non-first packets with the final DCID in
5832 * used.
5833 */
5834 node = ebmb_lookup(&quic_dghdlrs[tid].cids, pkt->dcid.data, pkt->dcid.len);
5835 if (!node)
5836 goto end;
5837
5838 id = ebmb_entry(node, struct quic_connection_id, node);
5839 qc = id->qc;
5840
5841 /* If found in DCIDs tree, remove the quic_conn from the ODCIDs tree.
5842 * If already done, this is a noop.
5843 */
5844 if (qc)
5845 ebmb_delete(&qc->odcid_node);
5846
5847 end:
5848 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5849 return qc;
5850}
5851
5852/* Try to allocate the <*ssl> SSL session object for <qc> QUIC connection
5853 * with <ssl_ctx> as SSL context inherited settings. Also set the transport
5854 * parameters of this session.
5855 * This is the responsibility of the caller to check the validity of all the
5856 * pointers passed as parameter to this function.
5857 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <qc->conn> to
5858 * CO_ER_SSL_NO_MEM.
5859 */
5860static int qc_ssl_sess_init(struct quic_conn *qc, SSL_CTX *ssl_ctx, SSL **ssl,
5861 unsigned char *params, size_t params_len)
5862{
5863 int retry, ret = -1;
5864
5865 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5866
5867 retry = 1;
5868 retry:
5869 *ssl = SSL_new(ssl_ctx);
5870 if (!*ssl) {
5871 if (!retry--)
5872 goto err;
5873
5874 pool_gc(NULL);
5875 goto retry;
5876 }
5877
5878 if (!SSL_set_quic_method(*ssl, &ha_quic_method) ||
5879 !SSL_set_ex_data(*ssl, ssl_qc_app_data_index, qc)) {
5880 SSL_free(*ssl);
5881 *ssl = NULL;
5882 if (!retry--)
5883 goto err;
5884
5885 pool_gc(NULL);
5886 goto retry;
5887 }
5888
5889 ret = 0;
5890 leave:
5891 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5892 return ret;
5893
5894 err:
5895 qc->conn->err_code = CO_ER_SSL_NO_MEM;
5896 goto leave;
5897}
5898
5899/* Finalize <qc> QUIC connection:
5900 * - initialize the Initial QUIC TLS context for negotiated version,
5901 * - derive the secrets for this context,
5902 * - encode the transport parameters to be sent,
5903 * - set them into the TLS stack,
5904 * - initialize ->max_ack_delay and max_idle_timeout,
5905 *
5906 * MUST be called after having received the remote transport parameters.
5907 * Return 1 if succeeded, 0 if not.
5908 */
5909int qc_conn_finalize(struct quic_conn *qc, int server)
5910{
5911 int ret = 0;
5912 struct quic_transport_params *tx_tp = &qc->tx.params;
5913 struct quic_transport_params *rx_tp = &qc->rx.params;
5914 const struct quic_version *ver;
5915
5916 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5917
5918 if (tx_tp->version_information.negotiated_version &&
5919 tx_tp->version_information.negotiated_version != qc->original_version) {
5920 qc->negotiated_version =
5921 qc->tx.params.version_information.negotiated_version;
5922 if (!qc_new_isecs(qc, &qc->negotiated_ictx, qc->negotiated_version,
5923 qc->odcid.data, qc->odcid.len, !server))
5924 goto out;
5925
5926 ver = qc->negotiated_version;
5927 }
5928 else {
5929 ver = qc->original_version;
5930 }
5931
5932 qc->enc_params_len =
5933 quic_transport_params_encode(qc->enc_params,
5934 qc->enc_params + sizeof qc->enc_params,
5935 &qc->rx.params, ver, 1);
5936 if (!qc->enc_params_len) {
5937 TRACE_ERROR("quic_transport_params_encode() failed", QUIC_EV_CONN_TXPKT);
5938 goto out;
5939 }
5940
5941 if (!SSL_set_quic_transport_params(qc->xprt_ctx->ssl, qc->enc_params, qc->enc_params_len)) {
5942 TRACE_ERROR("SSL_set_quic_transport_params() failed", QUIC_EV_CONN_TXPKT);
5943 goto out;
5944 }
5945
5946 if (tx_tp->max_ack_delay)
5947 qc->max_ack_delay = tx_tp->max_ack_delay;
5948
5949 if (tx_tp->max_idle_timeout && rx_tp->max_idle_timeout)
5950 qc->max_idle_timeout =
5951 QUIC_MIN(tx_tp->max_idle_timeout, rx_tp->max_idle_timeout);
5952 else
5953 qc->max_idle_timeout =
5954 QUIC_MAX(tx_tp->max_idle_timeout, rx_tp->max_idle_timeout);
5955
5956 TRACE_PROTO("\nTX(remote) transp. params.", QUIC_EV_TRANSP_PARAMS, qc, tx_tp);
5957
5958 ret = 1;
5959 out:
5960 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5961 return ret;
5962}
5963
5964/* Allocate the ssl_sock_ctx from connection <qc>. This creates the tasklet
5965 * used to process <qc> received packets. The allocated context is stored in
5966 * <qc.xprt_ctx>.
5967 *
5968 * Returns 0 on success else non-zero.
5969 */
5970static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc)
5971{
5972 int ret = 0;
5973 struct bind_conf *bc = qc->li->bind_conf;
5974 struct ssl_sock_ctx *ctx = NULL;
5975
5976 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5977
5978 ctx = pool_zalloc(pool_head_quic_conn_ctx);
5979 if (!ctx) {
5980 TRACE_ERROR("SSL context allocation failed", QUIC_EV_CONN_TXPKT);
5981 goto err;
5982 }
5983
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005984 ctx->subs = NULL;
5985 ctx->xprt_ctx = NULL;
5986 ctx->qc = qc;
5987
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005988 if (qc_is_listener(qc)) {
5989 if (qc_ssl_sess_init(qc, bc->initial_ctx, &ctx->ssl,
5990 qc->enc_params, qc->enc_params_len) == -1) {
5991 goto err;
5992 }
5993#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5994 /* Enabling 0-RTT */
5995 if (bc->ssl_conf.early_data)
5996 SSL_set_quic_early_data_enabled(ctx->ssl, 1);
5997#endif
5998
5999 SSL_set_accept_state(ctx->ssl);
6000 }
6001
6002 ctx->xprt = xprt_get(XPRT_QUIC);
6003
6004 /* Store the allocated context in <qc>. */
6005 qc->xprt_ctx = ctx;
6006
6007 ret = 1;
6008 leave:
6009 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
6010 return !ret;
6011
6012 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006013 pool_free(pool_head_quic_conn_ctx, ctx);
6014 goto leave;
6015}
6016
6017/* Check that all the bytes between <buf> included and <end> address
6018 * excluded are null. This is the responsibility of the caller to
6019 * check that there is at least one byte between <buf> end <end>.
6020 * Return 1 if this all the bytes are null, 0 if not.
6021 */
6022static inline int quic_padding_check(const unsigned char *buf,
6023 const unsigned char *end)
6024{
6025 while (buf < end && !*buf)
6026 buf++;
6027
6028 return buf == end;
6029}
6030
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006031/* Find the associated connection to the packet <pkt> or create a new one if
6032 * this is an Initial packet. <dgram> is the datagram containing the packet and
6033 * <l> is the listener instance on which it was received.
6034 *
6035 * Returns the quic-conn instance or NULL.
6036 */
6037static struct quic_conn *quic_rx_pkt_retrieve_conn(struct quic_rx_packet *pkt,
6038 struct quic_dgram *dgram,
6039 struct listener *l)
6040{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006041 struct quic_cid token_odcid = { .len = 0 };
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006042 struct quic_conn *qc = NULL;
6043 struct proxy *prx;
6044 struct quic_counters *prx_counters;
6045
6046 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6047
6048 prx = l->bind_conf->frontend;
6049 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6050
6051 qc = retrieve_qc_conn_from_cid(pkt, l, &dgram->saddr);
6052
6053 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6054 BUG_ON(!pkt->version); /* This must not happen. */
6055
6056 if (global.cluster_secret && pkt->token_len) {
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006057 if (!quic_retry_token_check(pkt, dgram, l, qc, &token_odcid))
6058 goto err;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006059 }
6060
6061 if (!qc) {
6062 int ipv4;
6063
6064 if (global.cluster_secret && !pkt->token_len && !(l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) &&
6065 HA_ATOMIC_LOAD(&prx_counters->half_open_conn) >= global.tune.quic_retry_threshold) {
6066 TRACE_PROTO("Initial without token, sending retry",
6067 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6068 if (send_retry(l->rx.fd, &dgram->saddr, pkt, pkt->version)) {
6069 TRACE_ERROR("Error during Retry generation",
6070 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6071 goto out;
6072 }
6073
6074 HA_ATOMIC_INC(&prx_counters->retry_sent);
6075 goto out;
6076 }
6077
6078 /* RFC 9000 7.2. Negotiating Connection IDs:
6079 * When an Initial packet is sent by a client that has not previously
6080 * received an Initial or Retry packet from the server, the client
6081 * populates the Destination Connection ID field with an unpredictable
6082 * value. This Destination Connection ID MUST be at least 8 bytes in length.
6083 */
6084 if (pkt->dcid.len < QUIC_ODCID_MINLEN) {
6085 TRACE_PROTO("dropped packet",
6086 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6087 goto err;
6088 }
6089
6090 pkt->saddr = dgram->saddr;
6091 ipv4 = dgram->saddr.ss_family == AF_INET;
6092
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006093 qc = qc_new_conn(pkt->version, ipv4, &pkt->dcid, &pkt->scid, &token_odcid,
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006094 &dgram->daddr, &pkt->saddr, 1,
6095 !!pkt->token_len, l);
6096 if (qc == NULL)
6097 goto err;
6098
6099 HA_ATOMIC_INC(&prx_counters->half_open_conn);
6100 /* Insert the DCID the QUIC client has chosen (only for listeners) */
6101 ebmb_insert(&quic_dghdlrs[tid].odcids, &qc->odcid_node,
6102 qc->odcid.len + qc->odcid.addrlen);
6103 }
6104 }
6105 else if (!qc) {
6106 TRACE_PROTO("No connection on a non Initial packet", QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6107 if (global.cluster_secret && !send_stateless_reset(l, &dgram->saddr, pkt))
6108 TRACE_ERROR("stateless reset not sent", QUIC_EV_CONN_LPKT, qc);
6109 goto err;
6110 }
6111
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006112 out:
6113 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6114 return qc;
6115
6116 err:
6117 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
6118 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
6119 return NULL;
6120}
6121
Amaury Denoyelle98289692022-10-19 15:37:44 +02006122/* Parse a QUIC packet starting at <buf>. Data won't be read after <end> even
6123 * if the packet is incomplete. This function will populate fields of <pkt>
6124 * instance, most notably its length. <dgram> is the UDP datagram which
6125 * contains the parsed packet. <l> is the listener instance on which it was
6126 * received.
6127 *
6128 * Returns 0 on success else non-zero. Packet length is guaranteed to be set to
6129 * the real packet value or to cover all data between <buf> and <end> : this is
6130 * useful to reject a whole datagram.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006131 */
Amaury Denoyelle98289692022-10-19 15:37:44 +02006132static int quic_rx_pkt_parse(struct quic_rx_packet *pkt,
6133 unsigned char *buf, const unsigned char *end,
6134 struct quic_dgram *dgram, struct listener *l)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006135{
Amaury Denoyelle98289692022-10-19 15:37:44 +02006136 const unsigned char *beg = buf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006137 struct proxy *prx;
6138 struct quic_counters *prx_counters;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006139 int long_header = 0;
Willy Tarreau33a68702022-11-24 09:16:41 +01006140 uint32_t version = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006141 const struct quic_version *qv = NULL;
6142
6143 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6144
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006145 prx = l->bind_conf->frontend;
6146 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6147 /* This ist only to please to traces and distinguish the
6148 * packet with parsed packet number from others.
6149 */
6150 pkt->pn_node.key = (uint64_t)-1;
6151 if (end <= buf) {
6152 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6153 goto drop;
6154 }
6155
6156 /* Fixed bit */
6157 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006158 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
6159 quic_padding_check(buf, end)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006160 /* Some browsers may pad the remaining datagram space with null bytes.
6161 * That is what we called add padding out of QUIC packets. Such
6162 * datagrams must be considered as valid. But we can only consume
6163 * the remaining space.
6164 */
6165 pkt->len = end - buf;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006166 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006167 }
6168
6169 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6170 goto drop;
6171 }
6172
6173 /* Header form */
6174 if (!qc_parse_hd_form(pkt, &buf, end, &long_header, &version)) {
6175 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6176 goto drop;
6177 }
6178
6179 if (long_header) {
6180 uint64_t len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006181
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006182 TRACE_PROTO("long header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006183 if (!quic_packet_read_long_header(&buf, end, pkt)) {
6184 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6185 goto drop;
6186 }
6187
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006188 if (pkt->type == QUIC_PACKET_TYPE_INITIAL &&
6189 dgram->len < QUIC_INITIAL_PACKET_MINLEN) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006190 TRACE_PROTO("Too short datagram with an Initial packet", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006191 HA_ATOMIC_INC(&prx_counters->too_short_initial_dgram);
6192 goto drop;
6193 }
6194
6195 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6196 * they must have the same DCID.
6197 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006198 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006199 (pkt->dcid.len != dgram->dcid_len ||
6200 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006201 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006202 goto drop;
6203 }
6204
6205 /* Retry of Version Negotiation packets are only sent by servers */
6206 if (pkt->type == QUIC_PACKET_TYPE_RETRY || !version) {
6207 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6208 goto drop;
6209 }
6210
6211 /* RFC9000 6. Version Negotiation */
6212 qv = qc_supported_version(version);
6213 if (!qv) {
6214 /* unsupported version, send Negotiation packet */
6215 if (send_version_negotiation(l->rx.fd, &dgram->saddr, pkt)) {
6216 TRACE_ERROR("VN packet not sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006217 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006218 }
6219
6220 TRACE_PROTO("VN packet sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006221 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006222 }
Amaury Denoyelle0eae5722022-10-17 18:05:18 +02006223 pkt->version = qv;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006224
6225 /* For Initial packets, and for servers (QUIC clients connections),
6226 * there is no Initial connection IDs storage.
6227 */
6228 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6229 uint64_t token_len;
6230
6231 if (!quic_dec_int(&token_len, (const unsigned char **)&buf, end) ||
6232 end - buf < token_len) {
6233 TRACE_PROTO("Packet dropped",
6234 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6235 goto drop;
6236 }
6237
6238 /* TODO Retry should be automatically activated if
6239 * suspect network usage is detected.
6240 */
6241 if (global.cluster_secret && !token_len) {
6242 if (l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) {
6243 TRACE_PROTO("Initial without token, sending retry",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006244 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006245 if (send_retry(l->rx.fd, &dgram->saddr, pkt, qv)) {
6246 TRACE_PROTO("Error during Retry generation",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006247 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006248 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006249 }
6250
6251 HA_ATOMIC_INC(&prx_counters->retry_sent);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006252 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006253 }
6254 }
6255 else if (!global.cluster_secret && token_len) {
6256 /* Impossible case: a token was received without configured
6257 * cluster secret.
6258 */
6259 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT,
6260 NULL, NULL, NULL, qv);
6261 goto drop;
6262 }
6263
6264 pkt->token = buf;
6265 pkt->token_len = token_len;
6266 buf += pkt->token_len;
6267 }
6268 else if (pkt->type != QUIC_PACKET_TYPE_0RTT) {
6269 if (pkt->dcid.len != QUIC_HAP_CID_LEN) {
6270 TRACE_PROTO("Packet dropped",
6271 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6272 goto drop;
6273 }
6274 }
6275
6276 if (!quic_dec_int(&len, (const unsigned char **)&buf, end) ||
6277 end - buf < len) {
6278 TRACE_PROTO("Packet dropped",
6279 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6280 goto drop;
6281 }
6282
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006283 /* Packet Number is stored here. Packet Length totalizes the
6284 * rest of the content.
6285 */
6286 pkt->pn_offset = buf - beg;
6287 pkt->len = pkt->pn_offset + len;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006288
6289 /* Interrupt parsing after packet length retrieval : this
6290 * ensures that only the packet is dropped but not the whole
6291 * datagram.
6292 */
6293 if (pkt->type == QUIC_PACKET_TYPE_0RTT && !l->bind_conf->ssl_conf.early_data) {
6294 TRACE_PROTO("0-RTT packet not supported", QUIC_EV_CONN_LPKT);
6295 goto drop;
6296 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006297 }
6298 else {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006299 TRACE_PROTO("short header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006300 if (end - buf < QUIC_HAP_CID_LEN) {
6301 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6302 goto drop;
6303 }
6304
6305 memcpy(pkt->dcid.data, buf, QUIC_HAP_CID_LEN);
6306 pkt->dcid.len = QUIC_HAP_CID_LEN;
6307
6308 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6309 * they must have the same DCID.
6310 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006311 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006312 (pkt->dcid.len != dgram->dcid_len ||
6313 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006314 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006315 goto drop;
6316 }
6317
6318 buf += QUIC_HAP_CID_LEN;
6319
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006320 pkt->pn_offset = buf - beg;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006321 /* A short packet is the last one of a UDP datagram. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006322 pkt->len = end - beg;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006323 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006324
Amaury Denoyelle98289692022-10-19 15:37:44 +02006325 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6326 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006327
Amaury Denoyelle98289692022-10-19 15:37:44 +02006328 drop:
6329 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006330 drop_silent:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006331 if (!pkt->len)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006332 pkt->len = end - beg;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006333 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6334 return -1;
6335}
6336
6337/* Check if received packet <pkt> should be drop due to <qc> already in closing
6338 * state. This can be true if a CONNECTION_CLOSE has already been emitted for
6339 * this connection.
6340 *
6341 * Returns false if connection is not in closing state else true. The caller
6342 * should drop the whole datagram in the last case to not mess up <qc>
6343 * CONNECTION_CLOSE rate limit counter.
6344 */
6345static int qc_rx_check_closing(struct quic_conn *qc,
6346 struct quic_rx_packet *pkt)
6347{
6348 if (!(qc->flags & QUIC_FL_CONN_CLOSING))
6349 return 0;
6350
6351 TRACE_STATE("Closing state connection", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6352
6353 /* Check if CONNECTION_CLOSE rate reemission is reached. */
6354 if (++qc->nb_pkt_since_cc >= qc->nb_pkt_for_cc) {
6355 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
6356 qc->nb_pkt_for_cc++;
6357 qc->nb_pkt_since_cc = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006358 }
6359
Amaury Denoyelle98289692022-10-19 15:37:44 +02006360 return 1;
6361}
6362
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006363/* React to a connection migration initiated on <qc> by a client with the new
6364 * path addresses <peer_addr>/<local_addr>.
6365 *
6366 * Returns 0 on success else non-zero.
6367 */
6368static int qc_handle_conn_migration(struct quic_conn *qc,
6369 const struct sockaddr_storage *peer_addr,
6370 const struct sockaddr_storage *local_addr)
6371{
6372 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6373
Frédéric Lécaille6fc86972023-01-12 08:29:23 +01006374 /* RFC 9000. Connection Migration
6375 *
6376 * If the peer sent the disable_active_migration transport parameter,
6377 * an endpoint also MUST NOT send packets (including probing packets;
6378 * see Section 9.1) from a different local address to the address the peer
6379 * used during the handshake, unless the endpoint has acted on a
6380 * preferred_address transport parameter from the peer.
6381 */
6382 if (qc->li->bind_conf->quic_params.disable_active_migration) {
6383 TRACE_ERROR("Active migration was disabled, datagram dropped", QUIC_EV_CONN_LPKT, qc);
6384 goto err;
6385 }
6386
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006387 /* RFC 9000 9. Connection Migration
6388 *
Amaury Denoyelleeb6be982022-11-21 11:14:45 +01006389 * The design of QUIC relies on endpoints retaining a stable address for
6390 * the duration of the handshake. An endpoint MUST NOT initiate
6391 * connection migration before the handshake is confirmed, as defined in
6392 * Section 4.1.2 of [QUIC-TLS].
6393 */
6394 if (qc->state < QUIC_HS_ST_COMPLETE) {
6395 TRACE_STATE("Connection migration during handshake rejected", QUIC_EV_CONN_LPKT, qc);
6396 goto err;
6397 }
6398
6399 /* RFC 9000 9. Connection Migration
6400 *
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006401 * TODO
6402 * An endpoint MUST
6403 * perform path validation (Section 8.2) if it detects any change to a
6404 * peer's address, unless it has previously validated that address.
6405 */
6406
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006407 /* Update quic-conn owned socket if in used.
6408 * TODO try to reuse it instead of closing and opening a new one.
6409 */
6410 if (qc_test_fd(qc)) {
6411 /* TODO try to reuse socket instead of closing it and opening a new one. */
6412 TRACE_STATE("Connection migration detected, allocate a new connection socket", QUIC_EV_CONN_LPKT, qc);
6413 qc_release_fd(qc, 1);
6414 qc_alloc_fd(qc, local_addr, peer_addr);
6415 }
6416
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006417 qc->local_addr = *local_addr;
6418 qc->peer_addr = *peer_addr;
6419 HA_ATOMIC_INC(&qc->prx_counters->conn_migration_done);
6420
6421 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6422 return 0;
6423
6424 err:
6425 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6426 return 1;
6427}
6428
Amaury Denoyelle98289692022-10-19 15:37:44 +02006429/* Handle a parsed packet <pkt> by the connection <qc>. Data will be copied
6430 * into <qc> receive buffer after header protection removal procedure.
6431 *
6432 * <dgram> must be set to the datagram which contains the QUIC packet. <beg>
6433 * must point to packet buffer first byte.
6434 *
6435 * <tasklist_head> may be non-NULL when the caller treat several datagrams for
6436 * different quic-conn. In this case, each quic-conn tasklet will be appended
6437 * to it in order to be woken up after the current task.
6438 *
6439 * The caller can safely removed the packet data. If packet refcount was not
6440 * incremented by this function, it means that the connection did not handled
6441 * it and it should be freed by the caller.
6442 */
6443static void qc_rx_pkt_handle(struct quic_conn *qc, struct quic_rx_packet *pkt,
6444 struct quic_dgram *dgram, unsigned char *beg,
6445 struct list **tasklist_head)
6446{
6447 const struct quic_version *qv = pkt->version;
6448 struct quic_enc_level *qel = NULL;
6449 size_t b_cspace;
6450 int io_cb_wakeup = 1;
6451
Amaury Denoyelle3f474e62022-11-24 17:15:08 +01006452 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6453
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006454 if (pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST &&
6455 !quic_peer_validated_addr(qc) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006456 qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED) {
6457 TRACE_PROTO("PTO timer must be armed after anti-amplication was reached",
6458 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6459 /* Reset the anti-amplification bit. It will be set again
6460 * when sending the next packet if reached again.
6461 */
6462 qc->flags &= ~QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
6463 qc->flags |= QUIC_FL_CONN_IO_CB_WAKEUP;
6464 io_cb_wakeup = 1;
6465 }
6466
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006467 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
6468 TRACE_PROTO("Connection error",
6469 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6470 goto out;
6471 }
6472
6473 pkt->raw_len = pkt->len;
6474 quic_rx_pkts_del(qc);
6475 b_cspace = b_contig_space(&qc->rx.buf);
6476 if (b_cspace < pkt->len) {
6477 /* Do not consume buf if space not at the end. */
6478 if (b_tail(&qc->rx.buf) + b_cspace < b_wrap(&qc->rx.buf)) {
6479 TRACE_PROTO("Packet dropped",
6480 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006481 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006482 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006483 }
6484
6485 /* Let us consume the remaining contiguous space. */
6486 if (b_cspace) {
6487 b_putchr(&qc->rx.buf, 0x00);
6488 b_cspace--;
6489 }
6490 b_add(&qc->rx.buf, b_cspace);
6491 if (b_contig_space(&qc->rx.buf) < pkt->len) {
6492 TRACE_PROTO("Too big packet",
6493 QUIC_EV_CONN_LPKT, qc, pkt, &pkt->len, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006494 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006495 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006496 }
6497 }
6498
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006499 if (!qc_try_rm_hp(qc, pkt, beg, &qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006500 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6501 goto drop;
6502 }
6503
6504 TRACE_DATA("New packet", QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6505 if (pkt->aad_len)
6506 qc_pkt_insert(qc, pkt, qel);
6507 out:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006508 *tasklist_head = tasklet_wakeup_after(*tasklist_head,
6509 qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006510
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006511 drop_silent:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006512 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006513 return;
6514
6515 drop:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006516 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006517 err:
6518 /* Wakeup the I/O handler callback if the PTO timer must be armed.
6519 * This cannot be done by this thread.
6520 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006521 if (io_cb_wakeup)
6522 tasklet_wakeup(qc->wait_event.tasklet);
6523
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006524 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
6525}
6526
6527/* This function builds into <buf> buffer a QUIC long packet header.
6528 * Return 1 if enough room to build this header, 0 if not.
6529 */
6530static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
6531 int type, size_t pn_len,
6532 struct quic_conn *qc, const struct quic_version *ver)
6533{
6534 int ret = 0;
6535
6536 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6537
6538 if (end - *buf < sizeof ver->num + qc->dcid.len + qc->scid.len + 3) {
6539 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6540 goto leave;
6541 }
6542
6543 type = quic_pkt_type(type, ver->num);
6544 /* #0 byte flags */
6545 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
6546 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
6547 /* Version */
6548 quic_write_uint32(buf, end, ver->num);
6549 *(*buf)++ = qc->dcid.len;
6550 /* Destination connection ID */
6551 if (qc->dcid.len) {
6552 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6553 *buf += qc->dcid.len;
6554 }
6555 /* Source connection ID */
6556 *(*buf)++ = qc->scid.len;
6557 if (qc->scid.len) {
6558 memcpy(*buf, qc->scid.data, qc->scid.len);
6559 *buf += qc->scid.len;
6560 }
6561
6562 ret = 1;
6563 leave:
6564 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6565 return ret;
6566}
6567
6568/* This function builds into <buf> buffer a QUIC short packet header.
6569 * Return 1 if enough room to build this header, 0 if not.
6570 */
6571static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
6572 size_t pn_len, struct quic_conn *qc,
6573 unsigned char tls_flags)
6574{
6575 int ret = 0;
6576
6577 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6578
6579 if (end - *buf < 1 + qc->dcid.len) {
6580 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6581 goto leave;
6582 }
6583
6584 /* #0 byte flags */
6585 *(*buf)++ = QUIC_PACKET_FIXED_BIT |
6586 ((tls_flags & QUIC_FL_TLS_KP_BIT_SET) ? QUIC_PACKET_KEY_PHASE_BIT : 0) | (pn_len - 1);
6587 /* Destination connection ID */
6588 if (qc->dcid.len) {
6589 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6590 *buf += qc->dcid.len;
6591 }
6592
6593 ret = 1;
6594 leave:
6595 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6596 return ret;
6597}
6598
6599/* Apply QUIC header protection to the packet with <buf> as first byte address,
6600 * <pn> as address of the Packet number field, <pnlen> being this field length
6601 * with <aead> as AEAD cipher and <key> as secret key.
6602 * Returns 1 if succeeded or 0 if failed.
6603 */
6604static int quic_apply_header_protection(struct quic_conn *qc, unsigned char *buf,
6605 unsigned char *pn, size_t pnlen,
6606 struct quic_tls_ctx *tls_ctx)
6607
6608{
6609 int i, ret = 0;
6610 /* We need an IV of at least 5 bytes: one byte for bytes #0
6611 * and at most 4 bytes for the packet number
6612 */
6613 unsigned char mask[5] = {0};
6614 EVP_CIPHER_CTX *aes_ctx = tls_ctx->tx.hp_ctx;
6615
6616 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6617
6618 if (!quic_tls_aes_encrypt(mask, pn + QUIC_PACKET_PN_MAXLEN, sizeof mask, aes_ctx)) {
6619 TRACE_ERROR("could not apply header protection", QUIC_EV_CONN_TXPKT, qc);
6620 goto out;
6621 }
6622
6623 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
6624 for (i = 0; i < pnlen; i++)
6625 pn[i] ^= mask[i + 1];
6626
6627 ret = 1;
6628 out:
6629 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6630 return ret;
6631}
6632
6633/* Reduce the encoded size of <ack_frm> ACK frame removing the last
6634 * ACK ranges if needed to a value below <limit> in bytes.
6635 * Return 1 if succeeded, 0 if not.
6636 */
6637static int quic_ack_frm_reduce_sz(struct quic_conn *qc,
6638 struct quic_frame *ack_frm, size_t limit)
6639{
6640 size_t room, ack_delay_sz;
6641 int ret = 0;
6642
6643 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6644
6645 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
6646 /* A frame is made of 1 byte for the frame type. */
6647 room = limit - ack_delay_sz - 1;
6648 if (!quic_rm_last_ack_ranges(qc, ack_frm->tx_ack.arngs, room))
6649 goto leave;
6650
6651 ret = 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
6652 leave:
6653 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6654 return ret;
6655}
6656
6657/* Prepare into <outlist> as most as possible ack-eliciting frame from their
6658 * <inlist> prebuilt frames for <qel> encryption level to be encoded in a buffer
6659 * with <room> as available room, and <*len> the packet Length field initialized
6660 * with the number of bytes already present in this buffer which must be taken
6661 * into an account for the Length packet field value. <headlen> is the number of
6662 * bytes already present in this packet before building frames.
6663 *
6664 * Update consequently <*len> to reflect the size of these frames built
6665 * by this function. Also attach these frames to <l> frame list.
6666 * Return 1 if at least one ack-eleciting frame could be built, 0 if not.
6667 */
6668static inline int qc_build_frms(struct list *outlist, struct list *inlist,
6669 size_t room, size_t *len, size_t headlen,
6670 struct quic_enc_level *qel,
6671 struct quic_conn *qc)
6672{
6673 int ret;
6674 struct quic_frame *cf, *cfbak;
6675
6676 TRACE_ENTER(QUIC_EV_CONN_BCFRMS, qc);
6677
6678 ret = 0;
6679 if (*len > room)
6680 goto leave;
6681
6682 /* If we are not probing we must take into an account the congestion
6683 * control window.
6684 */
6685 if (!qel->pktns->tx.pto_probe) {
6686 size_t remain = quic_path_prep_data(qc->path);
6687
6688 if (headlen > remain)
6689 goto leave;
6690
6691 room = QUIC_MIN(room, remain - headlen);
6692 }
6693
6694 TRACE_PROTO("************** frames build (headlen)",
6695 QUIC_EV_CONN_BCFRMS, qc, &headlen);
6696
6697 /* NOTE: switch/case block inside a loop, a successful status must be
6698 * returned by this function only if at least one frame could be built
6699 * in the switch/case block.
6700 */
6701 list_for_each_entry_safe(cf, cfbak, inlist, list) {
6702 /* header length, data length, frame length. */
6703 size_t hlen, dlen, dlen_sz, avail_room, flen;
6704
6705 if (!room)
6706 break;
6707
6708 switch (cf->type) {
6709 case QUIC_FT_CRYPTO:
6710 TRACE_DEVEL(" New CRYPTO frame build (room, len)",
6711 QUIC_EV_CONN_BCFRMS, qc, &room, len);
6712 /* Compute the length of this CRYPTO frame header */
6713 hlen = 1 + quic_int_getsize(cf->crypto.offset);
6714 /* Compute the data length of this CRyPTO frame. */
6715 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
6716 TRACE_DEVEL(" CRYPTO data length (hlen, crypto.len, dlen)",
6717 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->crypto.len, &dlen);
6718 if (!dlen)
6719 continue;
6720
6721 /* CRYPTO frame length. */
6722 flen = hlen + quic_int_getsize(dlen) + dlen;
6723 TRACE_DEVEL(" CRYPTO frame length (flen)",
6724 QUIC_EV_CONN_BCFRMS, qc, &flen);
6725 /* Add the CRYPTO data length and its encoded length to the packet
6726 * length and the length of this length.
6727 */
6728 *len += flen;
6729 room -= flen;
6730 if (dlen == cf->crypto.len) {
6731 /* <cf> CRYPTO data have been consumed. */
6732 LIST_DELETE(&cf->list);
6733 LIST_APPEND(outlist, &cf->list);
6734 }
6735 else {
6736 struct quic_frame *new_cf;
6737
6738 new_cf = pool_zalloc(pool_head_quic_frame);
6739 if (!new_cf) {
6740 TRACE_ERROR("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, qc);
6741 continue;
6742 }
6743
6744 LIST_INIT(&new_cf->reflist);
6745 new_cf->type = QUIC_FT_CRYPTO;
6746 new_cf->crypto.len = dlen;
6747 new_cf->crypto.offset = cf->crypto.offset;
6748 new_cf->crypto.qel = qel;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006749 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006750 if (cf->origin) {
6751 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
6752 /* This <cf> frame was duplicated */
6753 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
6754 new_cf->origin = cf->origin;
6755 }
6756 LIST_APPEND(outlist, &new_cf->list);
6757 /* Consume <dlen> bytes of the current frame. */
6758 cf->crypto.len -= dlen;
6759 cf->crypto.offset += dlen;
6760 }
6761 break;
6762
6763 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
6764 if (cf->flags & QUIC_FL_TX_FRAME_LOST) {
6765 struct eb64_node *node = NULL;
6766 struct qc_stream_desc *stream_desc = NULL;
6767 struct quic_stream *strm = &cf->stream;
6768
6769 /* As this frame has been already lost, ensure the stream is always
6770 * available or the range of this frame is not consumed before
6771 * resending it.
6772 */
6773 node = eb64_lookup(&qc->streams_by_id, strm->id);
6774 if (!node) {
6775 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, cf);
6776 LIST_DELETE(&cf->list);
6777 pool_free(pool_head_quic_frame, cf);
6778 continue;
6779 }
6780
6781 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
6782 if (strm->offset.key + strm->len <= stream_desc->ack_offset) {
6783 TRACE_DEVEL("ignored frame frame in already acked range",
6784 QUIC_EV_CONN_PRSAFRM, qc, cf);
6785 LIST_DELETE(&cf->list);
6786 pool_free(pool_head_quic_frame, cf);
6787 continue;
6788 }
6789 else if (strm->offset.key < stream_desc->ack_offset) {
6790 strm->offset.key = stream_desc->ack_offset;
6791 TRACE_DEVEL("updated partially acked frame",
6792 QUIC_EV_CONN_PRSAFRM, qc, cf);
6793 }
6794 }
6795 /* Note that these frames are accepted in short packets only without
6796 * "Length" packet field. Here, <*len> is used only to compute the
6797 * sum of the lengths of the already built frames for this packet.
6798 *
6799 * Compute the length of this STREAM frame "header" made a all the field
6800 * excepting the variable ones. Note that +1 is for the type of this frame.
6801 */
6802 hlen = 1 + quic_int_getsize(cf->stream.id) +
6803 ((cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT) ? quic_int_getsize(cf->stream.offset.key) : 0);
6804 /* Compute the data length of this STREAM frame. */
6805 avail_room = room - hlen - *len;
6806 if ((ssize_t)avail_room <= 0)
6807 continue;
6808
6809 TRACE_DEVEL(" New STREAM frame build (room, len)",
6810 QUIC_EV_CONN_BCFRMS, qc, &room, len);
6811 if (cf->type & QUIC_STREAM_FRAME_TYPE_LEN_BIT) {
6812 dlen = max_available_room(avail_room, &dlen_sz);
6813 if (dlen > cf->stream.len) {
6814 dlen = cf->stream.len;
6815 }
6816 dlen_sz = quic_int_getsize(dlen);
6817 flen = hlen + dlen_sz + dlen;
6818 }
6819 else {
6820 dlen = QUIC_MIN((uint64_t)avail_room, cf->stream.len);
6821 flen = hlen + dlen;
6822 }
6823 TRACE_DEVEL(" STREAM data length (hlen, stream.len, dlen)",
6824 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->stream.len, &dlen);
6825 TRACE_DEVEL(" STREAM frame length (flen)",
6826 QUIC_EV_CONN_BCFRMS, qc, &flen);
6827 /* Add the STREAM data length and its encoded length to the packet
6828 * length and the length of this length.
6829 */
6830 *len += flen;
6831 room -= flen;
6832 if (dlen == cf->stream.len) {
6833 /* <cf> STREAM data have been consumed. */
6834 LIST_DELETE(&cf->list);
6835 LIST_APPEND(outlist, &cf->list);
6836
6837 /* Do not notify MUX on retransmission. */
6838 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
6839 qcc_streams_sent_done(cf->stream.stream->ctx,
6840 cf->stream.len,
6841 cf->stream.offset.key);
6842 }
6843 }
6844 else {
6845 struct quic_frame *new_cf;
6846 struct buffer cf_buf;
6847
6848 new_cf = pool_zalloc(pool_head_quic_frame);
6849 if (!new_cf) {
6850 TRACE_ERROR("No memory for new STREAM frame", QUIC_EV_CONN_BCFRMS, qc);
6851 continue;
6852 }
6853
6854 LIST_INIT(&new_cf->reflist);
6855 new_cf->type = cf->type;
6856 new_cf->stream.stream = cf->stream.stream;
6857 new_cf->stream.buf = cf->stream.buf;
6858 new_cf->stream.id = cf->stream.id;
6859 if (cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT)
6860 new_cf->stream.offset = cf->stream.offset;
6861 new_cf->stream.len = dlen;
6862 new_cf->type |= QUIC_STREAM_FRAME_TYPE_LEN_BIT;
6863 /* FIN bit reset */
6864 new_cf->type &= ~QUIC_STREAM_FRAME_TYPE_FIN_BIT;
6865 new_cf->stream.data = cf->stream.data;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006866 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006867 if (cf->origin) {
6868 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
6869 /* This <cf> frame was duplicated */
6870 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
6871 new_cf->origin = cf->origin;
6872 }
6873 LIST_APPEND(outlist, &new_cf->list);
6874 cf->type |= QUIC_STREAM_FRAME_TYPE_OFF_BIT;
6875 /* Consume <dlen> bytes of the current frame. */
6876 cf_buf = b_make(b_orig(cf->stream.buf),
6877 b_size(cf->stream.buf),
6878 (char *)cf->stream.data - b_orig(cf->stream.buf), 0);
6879 cf->stream.len -= dlen;
6880 cf->stream.offset.key += dlen;
6881 cf->stream.data = (unsigned char *)b_peek(&cf_buf, dlen);
6882
6883 /* Do not notify MUX on retransmission. */
6884 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
6885 qcc_streams_sent_done(new_cf->stream.stream->ctx,
6886 new_cf->stream.len,
6887 new_cf->stream.offset.key);
6888 }
6889 }
6890
6891 /* TODO the MUX is notified about the frame sending via
6892 * previous qcc_streams_sent_done call. However, the
6893 * sending can fail later, for example if the sendto
6894 * system call returns an error. As the MUX has been
6895 * notified, the transport layer is responsible to
6896 * bufferize and resent the announced data later.
6897 */
6898
6899 break;
6900
6901 default:
6902 flen = qc_frm_len(cf);
6903 BUG_ON(!flen);
6904 if (flen > room)
6905 continue;
6906
6907 *len += flen;
6908 room -= flen;
6909 LIST_DELETE(&cf->list);
6910 LIST_APPEND(outlist, &cf->list);
6911 break;
6912 }
6913
6914 /* Successful status as soon as a frame could be built */
6915 ret = 1;
6916 }
6917
6918 leave:
6919 TRACE_LEAVE(QUIC_EV_CONN_BCFRMS, qc);
6920 return ret;
6921}
6922
6923/* Generate a CONNECTION_CLOSE frame for <qc> on <qel> encryption level. <out>
6924 * is used as return parameter and should be zero'ed by the caller.
6925 */
6926static void qc_build_cc_frm(struct quic_conn *qc, struct quic_enc_level *qel,
6927 struct quic_frame *out)
6928{
6929 /* TODO improve CONNECTION_CLOSE on Initial/Handshake encryption levels
6930 *
6931 * A CONNECTION_CLOSE frame should be sent in several packets with
6932 * different encryption levels depending on the client context. This is
6933 * to ensure that the client can decrypt it. See RFC 9000 10.2.3 for
6934 * more details on how to implement it.
6935 */
6936 TRACE_ENTER(QUIC_EV_CONN_BFRM, qc);
6937
6938
6939 if (qc->err.app) {
6940 if (unlikely(qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
6941 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
6942 /* RFC 9000 10.2.3. Immediate Close during the Handshake
6943 *
6944 * Sending a CONNECTION_CLOSE of type 0x1d in an Initial or Handshake
6945 * packet could expose application state or be used to alter application
6946 * state. A CONNECTION_CLOSE of type 0x1d MUST be replaced by a
6947 * CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or
6948 * Handshake packets. Otherwise, information about the application
6949 * state might be revealed. Endpoints MUST clear the value of the
6950 * Reason Phrase field and SHOULD use the APPLICATION_ERROR code when
6951 * converting to a CONNECTION_CLOSE of type 0x1c.
6952 */
6953 out->type = QUIC_FT_CONNECTION_CLOSE;
6954 out->connection_close.error_code = QC_ERR_APPLICATION_ERROR;
6955 out->connection_close.reason_phrase_len = 0;
6956 }
6957 else {
6958 out->type = QUIC_FT_CONNECTION_CLOSE_APP;
6959 out->connection_close.error_code = qc->err.code;
6960 }
6961 }
6962 else {
6963 out->type = QUIC_FT_CONNECTION_CLOSE;
6964 out->connection_close.error_code = qc->err.code;
6965 }
6966 TRACE_LEAVE(QUIC_EV_CONN_BFRM, qc);
6967
6968}
6969
6970/* This function builds a clear packet from <pkt> information (its type)
6971 * into a buffer with <pos> as position pointer and <qel> as QUIC TLS encryption
6972 * level for <conn> QUIC connection and <qel> as QUIC TLS encryption level,
6973 * filling the buffer with as much frames as possible from <frms> list of
6974 * prebuilt frames.
6975 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
6976 * reserved so that to ensure there is enough room to build this AEAD TAG after
6977 * having returned from this function.
6978 * This function also updates the value of <buf_pn> pointer to point to the packet
6979 * number field in this packet. <pn_len> will also have the packet number
6980 * length as value.
6981 *
6982 * Return 1 if succeeded (enough room to buile this packet), O if not.
6983 */
6984static int qc_do_build_pkt(unsigned char *pos, const unsigned char *end,
6985 size_t dglen, struct quic_tx_packet *pkt,
6986 int64_t pn, size_t *pn_len, unsigned char **buf_pn,
6987 int force_ack, int padding, int cc, int probe,
6988 struct quic_enc_level *qel, struct quic_conn *qc,
6989 const struct quic_version *ver, struct list *frms)
6990{
6991 unsigned char *beg, *payload;
6992 size_t len, len_sz, len_frms, padding_len;
6993 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
6994 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
6995 struct quic_frame cc_frm = { };
6996 size_t ack_frm_len, head_len;
6997 int64_t rx_largest_acked_pn;
6998 int add_ping_frm;
6999 struct list frm_list = LIST_HEAD_INIT(frm_list);
7000 struct quic_frame *cf;
7001 int must_ack, ret = 0;
7002 int nb_aepkts_since_last_ack;
7003
7004 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
7005
7006 /* Length field value with CRYPTO frames if present. */
7007 len_frms = 0;
7008 beg = pos;
7009 /* When not probing, and no immediate close is required, reduce the size of this
7010 * buffer to respect the congestion controller window.
7011 * This size will be limited if we have ack-eliciting frames to send from <frms>.
7012 */
7013 if (!probe && !LIST_ISEMPTY(frms) && !cc) {
7014 size_t path_room;
7015
7016 path_room = quic_path_prep_data(qc->path);
7017 if (end - beg > path_room)
7018 end = beg + path_room;
7019 }
7020
7021 /* Ensure there is enough room for the TLS encryption tag and a zero token
7022 * length field if any.
7023 */
7024 if (end - pos < QUIC_TLS_TAG_LEN +
7025 (pkt->type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0))
7026 goto no_room;
7027
7028 end -= QUIC_TLS_TAG_LEN;
7029 rx_largest_acked_pn = qel->pktns->rx.largest_acked_pn;
7030 /* packet number length */
7031 *pn_len = quic_packet_number_length(pn, rx_largest_acked_pn);
7032 /* Build the header */
7033 if ((pkt->type == QUIC_PACKET_TYPE_SHORT &&
7034 !quic_build_packet_short_header(&pos, end, *pn_len, qc, qel->tls_ctx.flags)) ||
7035 (pkt->type != QUIC_PACKET_TYPE_SHORT &&
7036 !quic_build_packet_long_header(&pos, end, pkt->type, *pn_len, qc, ver)))
7037 goto no_room;
7038
7039 /* Encode the token length (0) for an Initial packet. */
7040 if (pkt->type == QUIC_PACKET_TYPE_INITIAL)
7041 *pos++ = 0;
7042 head_len = pos - beg;
7043 /* Build an ACK frame if required. */
7044 ack_frm_len = 0;
7045 nb_aepkts_since_last_ack = qel->pktns->rx.nb_aepkts_since_last_ack;
7046 must_ack = !qel->pktns->tx.pto_probe &&
7047 (force_ack || ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
7048 (LIST_ISEMPTY(frms) || nb_aepkts_since_last_ack >= QUIC_MAX_RX_AEPKTS_SINCE_LAST_ACK)));
7049 if (must_ack) {
7050 struct quic_arngs *arngs = &qel->pktns->rx.arngs;
7051 BUG_ON(eb_is_empty(&qel->pktns->rx.arngs.root));
7052 ack_frm.tx_ack.arngs = arngs;
7053 if (qel->pktns->flags & QUIC_FL_PKTNS_NEW_LARGEST_PN) {
7054 qel->pktns->tx.ack_delay =
7055 quic_compute_ack_delay_us(qel->pktns->rx.largest_time_received, qc);
7056 qel->pktns->flags &= ~QUIC_FL_PKTNS_NEW_LARGEST_PN;
7057 }
7058 ack_frm.tx_ack.ack_delay = qel->pktns->tx.ack_delay;
7059 /* XXX BE CAREFUL XXX : here we reserved at least one byte for the
7060 * smallest frame (PING) and <*pn_len> more for the packet number. Note
7061 * that from here, we do not know if we will have to send a PING frame.
7062 * This will be decided after having computed the ack-eliciting frames
7063 * to be added to this packet.
7064 */
7065 ack_frm_len = quic_ack_frm_reduce_sz(qc, &ack_frm, end - 1 - *pn_len - pos);
7066 if (!ack_frm_len)
7067 goto no_room;
7068 }
7069
7070 /* Length field value without the ack-eliciting frames. */
7071 len = ack_frm_len + *pn_len;
7072 len_frms = 0;
7073 if (!cc && !LIST_ISEMPTY(frms)) {
7074 ssize_t room = end - pos;
7075
7076 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7077 /* Initialize the length of the frames built below to <len>.
7078 * If any frame could be successfully built by qc_build_frms(),
7079 * we will have len_frms > len.
7080 */
7081 len_frms = len;
7082 if (!qc_build_frms(&frm_list, frms,
7083 end - pos, &len_frms, pos - beg, qel, qc)) {
7084 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7085 qc, NULL, NULL, &room);
7086 if (!ack_frm_len && !qel->pktns->tx.pto_probe)
7087 goto no_room;
7088 }
7089 }
7090
7091 /* Length (of the remaining data). Must not fail because, the buffer size
7092 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
7093 * for the encryption tag. It must be taken into an account for the length
7094 * of this packet.
7095 */
7096 if (len_frms)
7097 len = len_frms + QUIC_TLS_TAG_LEN;
7098 else
7099 len += QUIC_TLS_TAG_LEN;
7100 /* CONNECTION_CLOSE frame */
7101 if (cc) {
7102 qc_build_cc_frm(qc, qel, &cc_frm);
7103 len += qc_frm_len(&cc_frm);
7104 }
7105 add_ping_frm = 0;
7106 padding_len = 0;
7107 len_sz = quic_int_getsize(len);
7108 /* Add this packet size to <dglen> */
7109 dglen += head_len + len_sz + len;
7110 if (padding && dglen < QUIC_INITIAL_PACKET_MINLEN) {
7111 /* This is a maximum padding size */
7112 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7113 /* The length field value is of this packet is <len> + <padding_len>
7114 * the size of which may be greater than the initial computed size
7115 * <len_sz>. So, let's deduce the difference between these to packet
7116 * sizes from <padding_len>.
7117 */
7118 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7119 len += padding_len;
7120 }
7121 else if (LIST_ISEMPTY(&frm_list) || len_frms == len) {
7122 if (qel->pktns->tx.pto_probe) {
7123 /* If we cannot send a frame, we send a PING frame. */
7124 add_ping_frm = 1;
7125 len += 1;
7126 }
7127 /* If there is no frame at all to follow, add at least a PADDING frame. */
7128 if (!ack_frm_len && !cc)
7129 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
7130 }
7131
7132 if (pkt->type != QUIC_PACKET_TYPE_SHORT && !quic_enc_int(&pos, end, len))
7133 goto no_room;
7134
7135 /* Packet number field address. */
7136 *buf_pn = pos;
7137
7138 /* Packet number encoding. */
7139 if (!quic_packet_number_encode(&pos, end, pn, *pn_len))
7140 goto no_room;
7141
7142 /* payload building (ack-eliciting or not frames) */
7143 payload = pos;
7144 if (ack_frm_len) {
7145 if (!qc_build_frm(&pos, end, &ack_frm, pkt, qc))
7146 goto no_room;
7147
7148 pkt->largest_acked_pn = quic_pktns_get_largest_acked_pn(qel->pktns);
7149 pkt->flags |= QUIC_FL_TX_PACKET_ACK;
7150 }
7151
7152 /* Ack-eliciting frames */
7153 if (!LIST_ISEMPTY(&frm_list)) {
7154 struct quic_frame *tmp_cf;
7155 list_for_each_entry_safe(cf, tmp_cf, &frm_list, list) {
7156 if (!qc_build_frm(&pos, end, cf, pkt, qc)) {
7157 ssize_t room = end - pos;
7158 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7159 qc, NULL, NULL, &room);
7160 /* Note that <cf> was added from <frms> to <frm_list> list by
7161 * qc_build_frms().
7162 */
7163 LIST_DELETE(&cf->list);
7164 LIST_INSERT(frms, &cf->list);
7165 continue;
7166 }
7167
7168 quic_tx_packet_refinc(pkt);
7169 cf->pkt = pkt;
7170 }
7171 }
7172
7173 /* Build a PING frame if needed. */
7174 if (add_ping_frm) {
7175 frm.type = QUIC_FT_PING;
7176 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7177 goto no_room;
7178 }
7179
7180 /* Build a CONNECTION_CLOSE frame if needed. */
7181 if (cc) {
7182 if (!qc_build_frm(&pos, end, &cc_frm, pkt, qc))
7183 goto no_room;
7184
7185 pkt->flags |= QUIC_FL_TX_PACKET_CC;
7186 }
7187
7188 /* Build a PADDING frame if needed. */
7189 if (padding_len) {
7190 frm.type = QUIC_FT_PADDING;
7191 frm.padding.len = padding_len;
7192 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7193 goto no_room;
7194 }
7195
7196 if (pos == payload) {
7197 /* No payload was built because of congestion control */
7198 TRACE_DEVEL("limited by congestion control", QUIC_EV_CONN_TXPKT, qc);
7199 goto no_room;
7200 }
7201
7202 /* If this packet is ack-eliciting and we are probing let's
7203 * decrement the PTO probe counter.
7204 */
7205 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING &&
7206 qel->pktns->tx.pto_probe)
7207 qel->pktns->tx.pto_probe--;
7208
7209 pkt->len = pos - beg;
7210 LIST_SPLICE(&pkt->frms, &frm_list);
7211
7212 ret = 1;
7213 TRACE_DEVEL("Packet ack-eliciting frames", QUIC_EV_CONN_TXPKT, qc, pkt);
7214 leave:
7215 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7216 return ret;
7217
7218 no_room:
7219 /* Replace the pre-built frames which could not be add to this packet */
7220 LIST_SPLICE(frms, &frm_list);
7221 TRACE_DEVEL("Remaining ack-eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7222 goto leave;
7223}
7224
7225static inline void quic_tx_packet_init(struct quic_tx_packet *pkt, int type)
7226{
7227 pkt->type = type;
7228 pkt->len = 0;
7229 pkt->in_flight_len = 0;
7230 pkt->pn_node.key = (uint64_t)-1;
7231 LIST_INIT(&pkt->frms);
7232 pkt->time_sent = TICK_ETERNITY;
7233 pkt->next = NULL;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01007234 pkt->prev = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007235 pkt->largest_acked_pn = -1;
7236 pkt->flags = 0;
7237 pkt->refcnt = 0;
7238}
7239
7240/* Build a packet into <buf> packet buffer with <pkt_type> as packet
7241 * type for <qc> QUIC connection from <qel> encryption level from <frms> list
7242 * of prebuilt frames.
7243 *
7244 * Return -2 if the packet could not be allocated or encrypted for any reason,
7245 * -1 if there was not enough room to build a packet.
7246 * XXX NOTE XXX
7247 * If you provide provide qc_build_pkt() with a big enough buffer to build a packet as big as
7248 * possible (to fill an MTU), the unique reason why this function may fail is the congestion
7249 * control window limitation.
7250 */
7251static struct quic_tx_packet *qc_build_pkt(unsigned char **pos,
7252 const unsigned char *buf_end,
7253 struct quic_enc_level *qel,
7254 struct quic_tls_ctx *tls_ctx, struct list *frms,
7255 struct quic_conn *qc, const struct quic_version *ver,
7256 size_t dglen, int pkt_type, int force_ack,
7257 int padding, int probe, int cc, int *err)
7258{
7259 struct quic_tx_packet *ret_pkt = NULL;
7260 /* The pointer to the packet number field. */
7261 unsigned char *buf_pn;
7262 unsigned char *beg, *end, *payload;
7263 int64_t pn;
7264 size_t pn_len, payload_len, aad_len;
7265 struct quic_tx_packet *pkt;
7266
7267 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc, NULL, qel);
7268 *err = 0;
7269 pkt = pool_alloc(pool_head_quic_tx_packet);
7270 if (!pkt) {
7271 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_TXPKT, qc);
7272 *err = -2;
7273 goto err;
7274 }
7275
7276 quic_tx_packet_init(pkt, pkt_type);
7277 beg = *pos;
7278 pn_len = 0;
7279 buf_pn = NULL;
7280
7281 pn = qel->pktns->tx.next_pn + 1;
7282 if (!qc_do_build_pkt(*pos, buf_end, dglen, pkt, pn, &pn_len, &buf_pn,
7283 force_ack, padding, cc, probe, qel, qc, ver, frms)) {
7284 // trace already emitted by function above
7285 *err = -1;
7286 goto err;
7287 }
7288
7289 end = beg + pkt->len;
7290 payload = buf_pn + pn_len;
7291 payload_len = end - payload;
7292 aad_len = payload - beg;
7293
7294 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc)) {
7295 // trace already emitted by function above
7296 *err = -2;
7297 goto err;
7298 }
7299
7300 end += QUIC_TLS_TAG_LEN;
7301 pkt->len += QUIC_TLS_TAG_LEN;
7302 if (!quic_apply_header_protection(qc, beg, buf_pn, pn_len, tls_ctx)) {
7303 // trace already emitted by function above
7304 *err = -2;
7305 goto err;
7306 }
7307
7308 /* Consume a packet number */
7309 qel->pktns->tx.next_pn++;
7310 qc->tx.prep_bytes += pkt->len;
7311 if (qc->tx.prep_bytes >= 3 * qc->rx.bytes && !quic_peer_validated_addr(qc)) {
7312 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
7313 TRACE_PROTO("anti-amplification limit reached", QUIC_EV_CONN_TXPKT, qc);
7314 }
7315 /* Now that a correct packet is built, let us consume <*pos> buffer. */
7316 *pos = end;
7317 /* Attach the built packet to its tree. */
7318 pkt->pn_node.key = pn;
7319 /* Set the packet in fligth length for in flight packet only. */
7320 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
7321 pkt->in_flight_len = pkt->len;
7322 qc->path->prep_in_flight += pkt->len;
7323 }
7324 /* Always reset this flags */
7325 qc->flags &= ~QUIC_FL_CONN_IMMEDIATE_CLOSE;
7326 if (pkt->flags & QUIC_FL_TX_PACKET_ACK) {
7327 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
7328 qel->pktns->rx.nb_aepkts_since_last_ack = 0;
7329 }
7330
7331 pkt->pktns = qel->pktns;
7332
7333 ret_pkt = pkt;
7334 leave:
7335 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc, ret_pkt);
7336 return ret_pkt;
7337
7338 err:
7339 /* TODO: what about the frames which have been built
7340 * for this packet.
7341 */
7342 free_quic_tx_packet(qc, pkt);
7343 goto leave;
7344}
7345
7346
7347static void __quic_conn_init(void)
7348{
7349 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
7350}
7351INITCALL0(STG_REGISTER, __quic_conn_init);
7352
7353static void __quic_conn_deinit(void)
7354{
7355 BIO_meth_free(ha_quic_meth);
7356}
7357REGISTER_POST_DEINIT(__quic_conn_deinit);
7358
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007359/* Handle a new <dgram> received. Parse each QUIC packets and copied their
7360 * content to a quic-conn instance. The datagram content can be released after
7361 * this function.
7362 *
7363 * If datagram has been received on a quic-conn owned FD, <from_qc> must be set
7364 * to the connection instance. <li> is the attached listener. The caller is
7365 * responsible to ensure that the first packet is destined to this connection
7366 * by comparing CIDs.
7367 *
7368 * If datagram has been received on a receiver FD, <from_qc> will be NULL. This
7369 * function will thus retrieve the connection from the CID tree or allocate a
7370 * new one if possible. <li> is the listener attached to the receiver.
7371 *
7372 * Returns 0 on success else non-zero. If an error happens, some packets from
7373 * the datagram may not have been parsed.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007374 */
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007375int quic_dgram_parse(struct quic_dgram *dgram, struct quic_conn *from_qc,
7376 struct listener *li)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007377{
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007378 struct quic_rx_packet *pkt;
7379 struct quic_conn *qc = NULL;
7380 unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007381 struct list *tasklist_head = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007382
7383 TRACE_ENTER(QUIC_EV_CONN_LPKT);
7384
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007385 pos = dgram->buf;
7386 end = pos + dgram->len;
7387 do {
7388 /* TODO replace zalloc -> alloc. */
7389 pkt = pool_zalloc(pool_head_quic_rx_packet);
7390 if (!pkt) {
7391 TRACE_ERROR("RX packet allocation failed", QUIC_EV_CONN_LPKT);
7392 goto err;
7393 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007394
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007395 pkt->version = NULL;
7396 pkt->pn_offset = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007397
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007398 /* Set flag if pkt is the first one in dgram. */
7399 if (pos == dgram->buf)
7400 pkt->flags |= QUIC_FL_RX_PACKET_DGRAM_FIRST;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007401
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007402 LIST_INIT(&pkt->qc_rx_pkt_list);
7403 pkt->time_received = now_ms;
7404 quic_rx_packet_refinc(pkt);
7405 if (quic_rx_pkt_parse(pkt, pos, end, dgram, li))
7406 goto next;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007407
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007408 /* Search quic-conn instance for first packet of the datagram.
7409 * quic_rx_packet_parse() is responsible to discard packets
7410 * with different DCID as the first one in the same datagram.
7411 */
7412 if (!qc) {
7413 qc = from_qc ? from_qc : quic_rx_pkt_retrieve_conn(pkt, dgram, li);
7414 /* qc is NULL if receiving a non Initial packet for an
7415 * unknown connection.
7416 */
7417 if (!qc) {
Amaury Denoyelle98289692022-10-19 15:37:44 +02007418 /* Skip the entire datagram. */
7419 pkt->len = end - pos;
7420 goto next;
7421 }
7422
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007423 dgram->qc = qc;
7424 }
Amaury Denoyelle98289692022-10-19 15:37:44 +02007425
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007426 if (qc_rx_check_closing(qc, pkt)) {
7427 /* Skip the entire datagram. */
7428 pkt->len = end - pos;
7429 goto next;
7430 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007431
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007432 /* Detect QUIC connection migration. */
Frédéric Lécaillef6769542023-01-12 10:36:26 +01007433 if (ipcmp(&qc->peer_addr, &dgram->saddr, 1)) {
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007434 if (qc_handle_conn_migration(qc, &dgram->saddr, &dgram->daddr)) {
7435 /* Skip the entire datagram. */
7436 TRACE_ERROR("error during connection migration, datagram dropped", QUIC_EV_CONN_LPKT, qc);
7437 pkt->len = end - pos;
7438 goto next;
7439 }
7440 }
7441
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007442 qc_rx_pkt_handle(qc, pkt, dgram, pos, &tasklist_head);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007443
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007444 next:
7445 pos += pkt->len;
7446 quic_rx_packet_refdec(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007447
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007448 /* Free rejected packets */
7449 if (!pkt->refcnt) {
7450 BUG_ON(LIST_INLIST(&pkt->qc_rx_pkt_list));
7451 pool_free(pool_head_quic_rx_packet, pkt);
7452 }
7453 } while (pos < end);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007454
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007455 /* Increasing the received bytes counter by the UDP datagram length
7456 * if this datagram could be associated to a connection.
7457 */
7458 if (dgram->qc)
7459 dgram->qc->rx.bytes += dgram->len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007460
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007461 /* This must never happen. */
7462 BUG_ON(pos > end);
7463 BUG_ON(pos < end || pos > dgram->buf + dgram->len);
7464 /* Mark this datagram as consumed */
7465 HA_ATOMIC_STORE(&dgram->buf, NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007466
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007467 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
7468 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007469
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007470 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007471 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007472 return -1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007473}
7474
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01007475/* Check if connection ID <dcid> of length <dcid_len> belongs to <qc> local
7476 * CIDs. This can be used to determine if a datagram is addressed to the right
7477 * connection instance.
7478 *
7479 * Returns a boolean value.
7480 */
7481int qc_check_dcid(struct quic_conn *qc, unsigned char *dcid, size_t dcid_len)
7482{
7483 struct ebmb_node *node;
7484 struct quic_connection_id *id;
7485
7486 /* For ODCID, address is concatenated to it after qc.odcid.len so this
7487 * comparison is safe.
7488 */
7489 if ((qc->scid.len == dcid_len &&
7490 memcmp(qc->scid.data, dcid, dcid_len) == 0) ||
7491 (qc->odcid.len == dcid_len &&
7492 memcmp(qc->odcid.data, dcid, dcid_len)) == 0) {
7493 return 1;
7494 }
7495
7496 node = ebmb_lookup(&quic_dghdlrs[tid].cids, dcid, dcid_len);
7497 if (node) {
7498 id = ebmb_entry(node, struct quic_connection_id, node);
7499 if (qc == id->qc)
7500 return 1;
7501 }
7502
7503 return 0;
7504}
7505
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007506/* Retrieve the DCID from a QUIC datagram or packet with <buf> as first octet.
7507 * Returns 1 if succeeded, 0 if not.
7508 */
7509int quic_get_dgram_dcid(unsigned char *buf, const unsigned char *end,
7510 unsigned char **dcid, size_t *dcid_len)
7511{
7512 int ret = 0, long_header;
7513 size_t minlen, skip;
7514
7515 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
7516
7517 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
7518 TRACE_PROTO("fixed bit not set", QUIC_EV_CONN_RXPKT);
7519 goto err;
7520 }
7521
7522 long_header = *buf & QUIC_PACKET_LONG_HEADER_BIT;
7523 minlen = long_header ? QUIC_LONG_PACKET_MINLEN :
7524 QUIC_SHORT_PACKET_MINLEN + QUIC_HAP_CID_LEN + QUIC_TLS_TAG_LEN;
7525 skip = long_header ? QUIC_LONG_PACKET_DCID_OFF : QUIC_SHORT_PACKET_DCID_OFF;
7526 if (end - buf < minlen)
7527 goto err;
7528
7529 buf += skip;
7530 *dcid_len = long_header ? *buf++ : QUIC_HAP_CID_LEN;
7531 if (*dcid_len > QUIC_CID_MAXLEN || end - buf <= *dcid_len)
7532 goto err;
7533
7534 *dcid = buf;
7535
7536 ret = 1;
7537 leave:
7538 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
7539 return ret;
7540
7541 err:
7542 TRACE_PROTO("wrong datagram", QUIC_EV_CONN_RXPKT);
7543 goto leave;
7544}
7545
7546/* Notify the MUX layer if alive about an imminent close of <qc>. */
7547void qc_notify_close(struct quic_conn *qc)
7548{
7549 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
7550
7551 if (qc->flags & QUIC_FL_CONN_NOTIFY_CLOSE)
7552 goto leave;
7553
7554 qc->flags |= QUIC_FL_CONN_NOTIFY_CLOSE;
7555 /* wake up the MUX */
7556 if (qc->mux_state == QC_MUX_READY && qc->conn->mux->wake) {
7557 TRACE_STATE("connection closure notidfied to mux",
7558 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7559 qc->conn->mux->wake(qc->conn);
7560 }
7561 else
7562 TRACE_STATE("connection closure not notidfied to mux",
7563 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7564 leave:
7565 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
7566}
7567
7568/*
7569 * Local variables:
7570 * c-indent-level: 8
7571 * c-basic-offset: 8
7572 * End:
7573 */