blob: e3a8b4634677d0bd2ff105e445d5c7c646d34e44 [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 {
96 .num = QUIC_PROTOCOL_VERSION_2_DRAFT,
97 .initial_salt = initial_salt_v2_draft,
98 .initial_salt_len = sizeof initial_salt_v2_draft,
99 .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,
107 .retry_tag_key = (const unsigned char *)QUIC_TLS_RETRY_KEY_V2_DRAFT,
108 .retry_tag_nonce = (const unsigned char *)QUIC_TLS_RETRY_NONCE_V2_DRAFT,
109 },
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);
2839 if (!qc_stop_sending_frm_enqueue(qc, stream->id))
2840 TRACE_ERROR("could not enqueue STOP_SENDING frame", QUIC_EV_CONN_PRSHPKT, qc);
2841 /* This packet will not be acknowledged */
2842 goto leave;
2843 }
2844 }
2845
2846 if (!qc_handle_strm_frm(pkt, stream, qc)) {
2847 TRACE_ERROR("qc_handle_strm_frm() failed", QUIC_EV_CONN_PRSHPKT, qc);
2848 goto leave;
2849 }
2850
2851 break;
2852 }
2853 case QUIC_FT_MAX_DATA:
2854 if (qc->mux_state == QC_MUX_READY) {
2855 struct quic_max_data *data = &frm.max_data;
2856 qcc_recv_max_data(qc->qcc, data->max_data);
2857 }
2858 break;
2859 case QUIC_FT_MAX_STREAM_DATA:
2860 if (qc->mux_state == QC_MUX_READY) {
2861 struct quic_max_stream_data *data = &frm.max_stream_data;
2862 if (qcc_recv_max_stream_data(qc->qcc, data->id,
2863 data->max_stream_data)) {
2864 TRACE_ERROR("qcc_recv_max_stream_data() failed", QUIC_EV_CONN_PRSHPKT, qc);
2865 goto leave;
2866 }
2867 }
2868 break;
2869 case QUIC_FT_MAX_STREAMS_BIDI:
2870 case QUIC_FT_MAX_STREAMS_UNI:
2871 break;
2872 case QUIC_FT_DATA_BLOCKED:
2873 HA_ATOMIC_INC(&qc->prx_counters->data_blocked);
2874 break;
2875 case QUIC_FT_STREAM_DATA_BLOCKED:
2876 HA_ATOMIC_INC(&qc->prx_counters->stream_data_blocked);
2877 break;
2878 case QUIC_FT_STREAMS_BLOCKED_BIDI:
2879 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_bidi);
2880 break;
2881 case QUIC_FT_STREAMS_BLOCKED_UNI:
2882 HA_ATOMIC_INC(&qc->prx_counters->streams_data_blocked_uni);
2883 break;
2884 case QUIC_FT_NEW_CONNECTION_ID:
2885 case QUIC_FT_RETIRE_CONNECTION_ID:
2886 /* XXX TO DO XXX */
2887 break;
2888 case QUIC_FT_CONNECTION_CLOSE:
2889 case QUIC_FT_CONNECTION_CLOSE_APP:
2890 /* Increment the error counters */
2891 qc_cc_err_count_inc(qc, &frm);
2892 if (!(qc->flags & QUIC_FL_CONN_DRAINING)) {
2893 if (!(qc->flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
2894 qc->flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
2895 HA_ATOMIC_DEC(&qc->prx_counters->half_open_conn);
2896 }
2897 TRACE_STATE("Entering draining state", QUIC_EV_CONN_PRSHPKT, qc);
2898 /* RFC 9000 10.2. Immediate Close:
2899 * The closing and draining connection states exist to ensure
2900 * that connections close cleanly and that delayed or reordered
2901 * packets are properly discarded. These states SHOULD persist
2902 * for at least three times the current PTO interval...
2903 *
2904 * Rearm the idle timeout only one time when entering draining
2905 * state.
2906 */
2907 qc_idle_timer_do_rearm(qc);
2908 qc->flags |= QUIC_FL_CONN_DRAINING|QUIC_FL_CONN_IMMEDIATE_CLOSE;
2909 qc_notify_close(qc);
2910 }
2911 break;
2912 case QUIC_FT_HANDSHAKE_DONE:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002913 if (qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002914 TRACE_ERROR("non accepted QUIC_FT_HANDSHAKE_DONE frame",
2915 QUIC_EV_CONN_PRSHPKT, qc);
2916 goto leave;
2917 }
2918
2919 qc->state = QUIC_HS_ST_CONFIRMED;
2920 break;
2921 default:
2922 TRACE_ERROR("unknosw frame type", QUIC_EV_CONN_PRSHPKT, qc);
2923 goto leave;
2924 }
2925 }
2926
2927 /* Flag this packet number space as having received a packet. */
2928 qel->pktns->flags |= QUIC_FL_PKTNS_PKT_RECEIVED;
2929
2930 if (fast_retrans) {
2931 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2932 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2933
2934 TRACE_PROTO("speeding up handshake completion", QUIC_EV_CONN_PRSHPKT, qc);
2935 qc_prep_hdshk_fast_retrans(qc, &iqel->pktns->tx.frms, &hqel->pktns->tx.frms);
2936 qc->flags |= QUIC_FL_CONN_HANDSHAKE_SPEED_UP;
2937 }
2938
2939 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
2940 * has successfully parse a Handshake packet. The Initial encryption must also
2941 * be discarded.
2942 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002943 if (pkt->type == QUIC_PACKET_TYPE_HANDSHAKE && qc_is_listener(qc)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002944 if (qc->state >= QUIC_HS_ST_SERVER_INITIAL) {
2945 if (!(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx.flags &
2946 QUIC_FL_TLS_SECRETS_DCD)) {
2947 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
2948 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PRSHPKT, qc);
2949 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002950 qc_set_timer(qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002951 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
2952 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
2953 }
2954 if (qc->state < QUIC_HS_ST_SERVER_HANDSHAKE)
2955 qc->state = QUIC_HS_ST_SERVER_HANDSHAKE;
2956 }
2957 }
2958
2959 ret = 1;
2960 leave:
2961 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, qc);
2962 return ret;
2963}
2964
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02002965
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02002966/* Allocate Tx buffer from <qc> quic-conn if needed.
2967 *
2968 * Returns allocated buffer or NULL on error.
2969 */
2970static struct buffer *qc_txb_alloc(struct quic_conn *qc)
2971{
2972 struct buffer *buf = &qc->tx.buf;
2973 if (!b_alloc(buf))
2974 return NULL;
2975
2976 return buf;
2977}
2978
2979/* Free Tx buffer from <qc> if it is empty. */
2980static void qc_txb_release(struct quic_conn *qc)
2981{
2982 struct buffer *buf = &qc->tx.buf;
2983
2984 /* For the moment sending function is responsible to purge the buffer
2985 * entirely. It may change in the future but this requires to be able
2986 * to reuse old data.
2987 */
2988 BUG_ON_HOT(buf && b_data(buf));
2989
2990 if (!b_data(buf)) {
2991 b_free(buf);
2992 offer_buffers(NULL, 1);
2993 }
2994}
2995
2996/* Commit a datagram payload written into <buf> of length <length>. <first_pkt>
2997 * must contains the address of the first packet stored in the payload.
2998 *
2999 * Caller is responsible that there is enough space in the buffer.
3000 */
3001static void qc_txb_store(struct buffer *buf, uint16_t length,
3002 struct quic_tx_packet *first_pkt)
3003{
3004 const size_t hdlen = sizeof(uint16_t) + sizeof(void *);
3005 BUG_ON_HOT(b_contig_space(buf) < hdlen); /* this must not happen */
3006
3007 write_u16(b_tail(buf), length);
3008 write_ptr(b_tail(buf) + sizeof(length), first_pkt);
3009 b_add(buf, hdlen + length);
3010}
3011
3012/* Returns 1 if a packet may be built for <qc> from <qel> encryption level
3013 * with <frms> as ack-eliciting frame list to send, 0 if not.
3014 * <cc> must equal to 1 if an immediate close was asked, 0 if not.
3015 * <probe> must equalt to 1 if a probing packet is required, 0 if not.
3016 * <force_ack> may be set to 1 if you want to force an ack.
3017 */
3018static int qc_may_build_pkt(struct quic_conn *qc, struct list *frms,
3019 struct quic_enc_level *qel, int cc, int probe, int force_ack)
3020{
3021 unsigned int must_ack = force_ack ||
3022 (LIST_ISEMPTY(frms) && (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED));
3023
3024 /* Do not build any more packet if the TX secrets are not available or
3025 * if there is nothing to send, i.e. if no CONNECTION_CLOSE or ACK are required
3026 * and if there is no more packets to send upon PTO expiration
3027 * and if there is no more ack-eliciting frames to send or in flight
3028 * congestion control limit is reached for prepared data
3029 */
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02003030 if (!quic_tls_has_tx_sec(qel) ||
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003031 (!cc && !probe && !must_ack &&
3032 (LIST_ISEMPTY(frms) || qc->path->prep_in_flight >= qc->path->cwnd))) {
3033 return 0;
3034 }
3035
3036 return 1;
3037}
3038
3039/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3040 * <frms>. Each packet is stored in a distinct datagram written to <buf>.
3041 *
3042 * Each datagram is prepended by a two fields header : the datagram length and
3043 * the address of the packet contained in the datagram.
3044 *
3045 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3046 * -1 if something wrong happened.
3047 */
3048static int qc_prep_app_pkts(struct quic_conn *qc, struct buffer *buf,
3049 struct list *frms)
3050{
3051 int ret = -1;
3052 struct quic_enc_level *qel;
3053 unsigned char *end, *pos;
3054 struct quic_tx_packet *pkt;
3055 size_t total;
3056 /* Each datagram is prepended with its length followed by the address
3057 * of the first packet in the datagram.
3058 */
3059 const size_t dg_headlen = sizeof(uint16_t) + sizeof(pkt);
3060
3061 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3062
3063 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3064 total = 0;
3065 pos = (unsigned char *)b_tail(buf);
3066 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen) {
3067 int err, probe, cc;
3068
3069 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3070 probe = 0;
3071 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3072 /* We do not probe if an immediate close was asked */
3073 if (!cc)
3074 probe = qel->pktns->tx.pto_probe;
3075
3076 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, 0))
3077 break;
3078
3079 /* Leave room for the datagram header */
3080 pos += dg_headlen;
3081 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3082 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3083 }
3084 else {
3085 end = pos + qc->path->mtu;
3086 }
3087
3088 pkt = qc_build_pkt(&pos, end, qel, &qel->tls_ctx, frms, qc, NULL, 0,
3089 QUIC_PACKET_TYPE_SHORT, 0, 0, probe, cc, &err);
3090 switch (err) {
3091 case -2:
3092 // trace already emitted by function above
3093 goto leave;
3094 case -1:
3095 /* As we provide qc_build_pkt() with an enough big buffer to fulfill an
3096 * MTU, we are here because of the congestion control window. There is
3097 * no need to try to reuse this buffer.
3098 */
3099 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3100 goto out;
3101 default:
3102 break;
3103 }
3104
3105 /* This is to please to GCC. We cannot have (err >= 0 && !pkt) */
3106 BUG_ON(!pkt);
3107
3108 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3109 pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3110
3111 total += pkt->len;
3112
3113 /* Write datagram header. */
3114 qc_txb_store(buf, pkt->len, pkt);
3115 }
3116
3117 out:
3118 ret = total;
3119 leave:
3120 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3121 return ret;
3122}
3123
3124/* Prepare as much as possible QUIC packets for sending from prebuilt frames
3125 * <frms>. Several packets can be regrouped in a single datagram. The result is
3126 * written into <buf>.
3127 *
3128 * Each datagram is prepended by a two fields header : the datagram length and
3129 * the address of first packet in the datagram.
3130 *
3131 * Returns the number of bytes prepared in packets if succeeded (may be 0), or
3132 * -1 if something wrong happened.
3133 */
3134static int qc_prep_pkts(struct quic_conn *qc, struct buffer *buf,
3135 enum quic_tls_enc_level tel, struct list *tel_frms,
3136 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
3137{
3138 struct quic_enc_level *qel;
3139 unsigned char *end, *pos;
3140 struct quic_tx_packet *first_pkt, *cur_pkt, *prv_pkt;
3141 /* length of datagrams */
3142 uint16_t dglen;
3143 size_t total;
3144 int ret = -1, padding;
3145 /* Each datagram is prepended with its length followed by the address
3146 * of the first packet in the datagram.
3147 */
3148 const size_t dg_headlen = sizeof(uint16_t) + sizeof(first_pkt);
3149 struct list *frms;
3150
3151 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc);
3152
3153 /* Currently qc_prep_pkts() does not handle buffer wrapping so the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003154 * caller must ensure that buf is reset.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003155 */
3156 BUG_ON_HOT(buf->head || buf->data);
3157
3158 total = 0;
3159 qel = &qc->els[tel];
3160 frms = tel_frms;
3161 dglen = 0;
3162 padding = 0;
3163 pos = (unsigned char *)b_head(buf);
3164 first_pkt = prv_pkt = NULL;
3165 while (b_contig_space(buf) >= (int)qc->path->mtu + dg_headlen || prv_pkt) {
3166 int err, probe, cc;
3167 enum quic_pkt_type pkt_type;
3168 struct quic_tls_ctx *tls_ctx;
3169 const struct quic_version *ver;
3170 int force_ack = (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3171 (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
3172 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
3173
3174 TRACE_POINT(QUIC_EV_CONN_PHPKTS, qc, qel);
3175 probe = 0;
3176 cc = qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE;
3177 /* We do not probe if an immediate close was asked */
3178 if (!cc)
3179 probe = qel->pktns->tx.pto_probe;
3180
3181 if (!qc_may_build_pkt(qc, frms, qel, cc, probe, force_ack)) {
3182 if (prv_pkt)
3183 qc_txb_store(buf, dglen, first_pkt);
3184 /* Let's select the next encryption level */
3185 if (tel != next_tel && next_tel != QUIC_TLS_ENC_LEVEL_NONE) {
3186 tel = next_tel;
3187 frms = next_tel_frms;
3188 qel = &qc->els[tel];
3189 /* Build a new datagram */
3190 prv_pkt = NULL;
3191 TRACE_DEVEL("next encryption level selected", QUIC_EV_CONN_PHPKTS, qc);
3192 continue;
3193 }
3194 break;
3195 }
3196
3197 pkt_type = quic_tls_level_pkt_type(tel);
3198 if (!prv_pkt) {
3199 /* Leave room for the datagram header */
3200 pos += dg_headlen;
3201 if (!quic_peer_validated_addr(qc) && qc_is_listener(qc)) {
3202 end = pos + QUIC_MIN((uint64_t)qc->path->mtu, 3 * qc->rx.bytes - qc->tx.prep_bytes);
3203 }
3204 else {
3205 end = pos + qc->path->mtu;
3206 }
3207 }
3208
3209 if (qc->negotiated_version) {
3210 ver = qc->negotiated_version;
3211 if (qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL])
3212 tls_ctx = &qc->negotiated_ictx;
3213 else
3214 tls_ctx = &qel->tls_ctx;
3215 }
3216 else {
3217 ver = qc->original_version;
3218 tls_ctx = &qel->tls_ctx;
3219 }
3220
3221 cur_pkt = qc_build_pkt(&pos, end, qel, tls_ctx, frms,
3222 qc, ver, dglen, pkt_type,
3223 force_ack, padding, probe, cc, &err);
3224 switch (err) {
3225 case -2:
3226 // trace already emitted by function above
3227 goto leave;
3228 case -1:
3229 /* If there was already a correct packet present, set the
3230 * current datagram as prepared into <cbuf>.
3231 */
3232 if (prv_pkt)
3233 qc_txb_store(buf, dglen, first_pkt);
3234 TRACE_DEVEL("could not prepare anymore packet", QUIC_EV_CONN_PHPKTS, qc);
3235 goto out;
3236 default:
3237 break;
3238 }
3239
3240 /* This is to please to GCC. We cannot have (err >= 0 && !cur_pkt) */
3241 BUG_ON(!cur_pkt);
3242
3243 if (qc->flags & QUIC_FL_CONN_RETRANS_OLD_DATA)
3244 cur_pkt->flags |= QUIC_FL_TX_PACKET_PROBE_WITH_OLD_DATA;
3245
3246 total += cur_pkt->len;
3247 /* keep trace of the first packet in the datagram */
3248 if (!first_pkt)
3249 first_pkt = cur_pkt;
Frédéric Lécaille74b5f7b2022-11-20 18:35:35 +01003250 /* Attach the current one to the previous one and vice versa */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003251 if (prv_pkt) {
3252 prv_pkt->next = cur_pkt;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01003253 cur_pkt->prev = prv_pkt;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003254 cur_pkt->flags |= QUIC_FL_TX_PACKET_COALESCED;
3255 }
3256 /* Let's say we have to build a new dgram */
3257 prv_pkt = NULL;
3258 dglen += cur_pkt->len;
3259 /* Client: discard the Initial encryption keys as soon as
3260 * a handshake packet could be built.
3261 */
3262 if (qc->state == QUIC_HS_ST_CLIENT_INITIAL &&
3263 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
3264 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3265 TRACE_PROTO("discarding Initial pktns", QUIC_EV_CONN_PHPKTS, qc);
3266 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
3267 qc_set_timer(qc);
3268 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
3269 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns);
3270 qc->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
3271 }
3272 /* If the data for the current encryption level have all been sent,
3273 * select the next level.
3274 */
3275 if ((tel == QUIC_TLS_ENC_LEVEL_INITIAL || tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE) &&
3276 next_tel != QUIC_TLS_ENC_LEVEL_NONE && (LIST_ISEMPTY(frms) && !qel->pktns->tx.pto_probe)) {
3277 /* If QUIC_TLS_ENC_LEVEL_HANDSHAKE was already reached let's try QUIC_TLS_ENC_LEVEL_APP */
3278 if (tel == QUIC_TLS_ENC_LEVEL_HANDSHAKE && next_tel == tel)
3279 next_tel = QUIC_TLS_ENC_LEVEL_APP;
3280 tel = next_tel;
3281 if (tel == QUIC_TLS_ENC_LEVEL_APP)
3282 frms = &qc->els[tel].pktns->tx.frms;
3283 else
3284 frms = next_tel_frms;
3285 qel = &qc->els[tel];
3286 if (!LIST_ISEMPTY(frms)) {
3287 /* If there is data for the next level, do not
3288 * consume a datagram.
3289 */
3290 prv_pkt = cur_pkt;
3291 }
3292 }
3293
3294 /* If we have to build a new datagram, set the current datagram as
3295 * prepared into <cbuf>.
3296 */
3297 if (!prv_pkt) {
3298 qc_txb_store(buf, dglen, first_pkt);
3299 first_pkt = NULL;
3300 dglen = 0;
3301 padding = 0;
3302 }
3303 else if (prv_pkt->type == QUIC_TLS_ENC_LEVEL_INITIAL &&
3304 (!qc_is_listener(qc) ||
3305 prv_pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
3306 padding = 1;
3307 }
3308 }
3309
3310 out:
3311 ret = total;
3312 leave:
3313 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
3314 return ret;
3315}
3316
3317/* Send datagrams stored in <buf>.
3318 *
3319 * This function always returns 1 for success. Even if sendto() syscall failed,
3320 * buffer is drained and packets are considered as emitted. QUIC loss detection
3321 * mechanism is used as a back door way to retry sending.
3322 */
3323int qc_send_ppkts(struct buffer *buf, struct ssl_sock_ctx *ctx)
3324{
3325 struct quic_conn *qc;
3326 char skip_sendto = 0;
3327
3328 qc = ctx->qc;
3329 TRACE_ENTER(QUIC_EV_CONN_SPPKTS, qc);
3330 while (b_contig_data(buf, 0)) {
3331 unsigned char *pos;
3332 struct buffer tmpbuf = { };
3333 struct quic_tx_packet *first_pkt, *pkt, *next_pkt;
3334 uint16_t dglen;
3335 size_t headlen = sizeof dglen + sizeof first_pkt;
3336 unsigned int time_sent;
3337
3338 pos = (unsigned char *)b_head(buf);
3339 dglen = read_u16(pos);
3340 BUG_ON_HOT(!dglen); /* this should not happen */
3341
3342 pos += sizeof dglen;
3343 first_pkt = read_ptr(pos);
3344 pos += sizeof first_pkt;
3345 tmpbuf.area = (char *)pos;
3346 tmpbuf.size = tmpbuf.data = dglen;
3347
3348 TRACE_DATA("send dgram", QUIC_EV_CONN_SPPKTS, qc);
3349 /* If sendto is on error just skip the call to it for the rest
3350 * of the loop but continue to purge the buffer. Data will be
3351 * transmitted when QUIC packets are detected as lost on our
3352 * side.
3353 *
3354 * TODO use fd-monitoring to detect when send operation can be
3355 * retry. This should improve the bandwidth without relying on
3356 * retransmission timer. However, it requires a major rework on
3357 * quic-conn fd management.
3358 */
3359 if (!skip_sendto) {
3360 if (qc_snd_buf(qc, &tmpbuf, tmpbuf.data, 0)) {
3361 skip_sendto = 1;
3362 TRACE_ERROR("sendto error, simulate sending for the rest of data", QUIC_EV_CONN_SPPKTS, qc);
3363 }
3364 }
3365
3366 b_del(buf, dglen + headlen);
3367 qc->tx.bytes += tmpbuf.data;
3368 time_sent = now_ms;
3369
3370 for (pkt = first_pkt; pkt; pkt = next_pkt) {
3371 pkt->time_sent = time_sent;
3372 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
3373 pkt->pktns->tx.time_of_last_eliciting = time_sent;
3374 qc->path->ifae_pkts++;
3375 if (qc->flags & QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ)
3376 qc_idle_timer_rearm(qc, 0);
3377 }
3378 if (!(qc->flags & QUIC_FL_CONN_CLOSING) &&
3379 (pkt->flags & QUIC_FL_TX_PACKET_CC)) {
3380 qc->flags |= QUIC_FL_CONN_CLOSING;
3381 qc_notify_close(qc);
3382
3383 /* RFC 9000 10.2. Immediate Close:
3384 * The closing and draining connection states exist to ensure
3385 * that connections close cleanly and that delayed or reordered
3386 * packets are properly discarded. These states SHOULD persist
3387 * for at least three times the current PTO interval...
3388 *
3389 * Rearm the idle timeout only one time when entering closing
3390 * state.
3391 */
3392 qc_idle_timer_do_rearm(qc);
3393 if (qc->timer_task) {
3394 task_destroy(qc->timer_task);
3395 qc->timer_task = NULL;
3396 }
3397 }
3398 qc->path->in_flight += pkt->in_flight_len;
3399 pkt->pktns->tx.in_flight += pkt->in_flight_len;
3400 if (pkt->in_flight_len)
3401 qc_set_timer(qc);
3402 TRACE_DATA("sent pkt", QUIC_EV_CONN_SPPKTS, qc, pkt);
3403 next_pkt = pkt->next;
3404 quic_tx_packet_refinc(pkt);
3405 eb64_insert(&pkt->pktns->tx.pkts, &pkt->pn_node);
3406 }
3407 }
3408
3409 TRACE_LEAVE(QUIC_EV_CONN_SPPKTS, qc);
3410
3411 return 1;
3412}
3413
3414/* Copy into <buf> buffer a stateless reset token depending on the
3415 * <salt> salt input. This is the cluster secret which will be derived
3416 * as HKDF input secret to generate this token.
3417 * Return 1 if succeeded, 0 if not.
3418 */
3419static int quic_stateless_reset_token_cpy(struct quic_conn *qc,
3420 unsigned char *buf, size_t len,
3421 const unsigned char *salt, size_t saltlen)
3422{
3423 /* Input secret */
3424 const unsigned char *key = (const unsigned char *)global.cluster_secret;
3425 size_t keylen = strlen(global.cluster_secret);
3426 /* Info */
3427 const unsigned char label[] = "stateless token";
3428 size_t labellen = sizeof label - 1;
3429 int ret;
3430
3431 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3432
3433 ret = quic_hkdf_extract_and_expand(EVP_sha256(), buf, len,
3434 key, keylen, salt, saltlen, label, labellen);
3435 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3436 return ret;
3437}
3438
3439/* Initialize the stateless reset token attached to <cid> connection ID.
3440 * Returns 1 if succeeded, 0 if not.
3441 */
3442static int quic_stateless_reset_token_init(struct quic_conn *qc,
3443 struct quic_connection_id *quic_cid)
3444{
3445 int ret;
3446
3447 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3448
3449 if (global.cluster_secret) {
3450 /* Output secret */
3451 unsigned char *token = quic_cid->stateless_reset_token;
3452 size_t tokenlen = sizeof quic_cid->stateless_reset_token;
3453 /* Salt */
3454 const unsigned char *cid = quic_cid->cid.data;
3455 size_t cidlen = quic_cid->cid.len;
3456
3457 ret = quic_stateless_reset_token_cpy(qc, token, tokenlen, cid, cidlen);
3458 }
3459 else {
3460 /* TODO: RAND_bytes() should be replaced */
3461 ret = RAND_bytes(quic_cid->stateless_reset_token,
3462 sizeof quic_cid->stateless_reset_token) == 1;
3463 }
3464
3465 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3466 return ret;
3467}
3468
3469/* Allocate a new CID with <seq_num> as sequence number and attach it to <root>
3470 * ebtree.
3471 *
3472 * The CID is randomly generated in part with the result altered to be
3473 * associated with the current thread ID. This means this function must only
3474 * be called by the quic_conn thread.
3475 *
3476 * Returns the new CID if succeeded, NULL if not.
3477 */
3478static struct quic_connection_id *new_quic_cid(struct eb_root *root,
3479 struct quic_conn *qc,
3480 int seq_num)
3481{
3482 struct quic_connection_id *cid;
3483
3484 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3485
3486 cid = pool_alloc(pool_head_quic_connection_id);
3487 if (!cid) {
3488 TRACE_ERROR("cid allocation failed", QUIC_EV_CONN_TXPKT, qc);
3489 goto err;
3490 }
3491
3492 cid->cid.len = QUIC_HAP_CID_LEN;
3493 /* TODO: RAND_bytes() should be replaced */
3494 if (RAND_bytes(cid->cid.data, cid->cid.len) != 1) {
3495 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT, qc);
3496 goto err;
3497 }
3498
3499 quic_pin_cid_to_tid(cid->cid.data, tid);
3500 if (quic_stateless_reset_token_init(qc, cid) != 1) {
3501 TRACE_ERROR("quic_stateless_reset_token_init() failed", QUIC_EV_CONN_TXPKT, qc);
3502 goto err;
3503 }
3504
3505 cid->qc = qc;
3506
3507 cid->seq_num.key = seq_num;
3508 cid->retire_prior_to = 0;
3509 /* insert the allocated CID in the quic_conn tree */
3510 eb64_insert(root, &cid->seq_num);
3511
3512 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3513 return cid;
3514
3515 err:
3516 pool_free(pool_head_quic_connection_id, cid);
3517 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3518 return NULL;
3519}
3520
3521/* Build all the frames which must be sent just after the handshake have succeeded.
3522 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
3523 * a HANDSHAKE_DONE frame.
3524 * Return 1 if succeeded, 0 if not.
3525 */
3526static int quic_build_post_handshake_frames(struct quic_conn *qc)
3527{
3528 int ret = 0, i, first, max;
3529 struct quic_enc_level *qel;
3530 struct quic_frame *frm, *frmbak;
3531 struct list frm_list = LIST_HEAD_INIT(frm_list);
3532 struct eb64_node *node;
3533
3534 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
3535
3536 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3537 /* Only servers must send a HANDSHAKE_DONE frame. */
3538 if (qc_is_listener(qc)) {
3539 frm = pool_zalloc(pool_head_quic_frame);
3540 if (!frm) {
3541 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3542 goto leave;
3543 }
3544
3545 LIST_INIT(&frm->reflist);
3546 frm->type = QUIC_FT_HANDSHAKE_DONE;
3547 LIST_APPEND(&frm_list, &frm->list);
3548 }
3549
3550 /* Initialize <max> connection IDs minus one: there is
3551 * already one connection ID used for the current connection.
3552 */
3553 first = 1;
3554 max = qc->tx.params.active_connection_id_limit;
3555
3556 /* TODO: check limit */
3557 for (i = first; i < max; i++) {
3558 struct quic_connection_id *cid;
3559
3560 frm = pool_zalloc(pool_head_quic_frame);
3561 if (!frm) {
3562 TRACE_ERROR("frame allocation error", QUIC_EV_CONN_IO_CB, qc);
3563 goto err;
3564 }
3565
3566 LIST_INIT(&frm->reflist);
3567 cid = new_quic_cid(&qc->cids, qc, i);
3568 if (!cid) {
3569 pool_free(pool_head_quic_frame, frm);
3570 TRACE_ERROR("CID allocation error", QUIC_EV_CONN_IO_CB, qc);
3571 goto err;
3572 }
3573
3574 /* insert the allocated CID in the receiver datagram handler tree */
3575 ebmb_insert(&quic_dghdlrs[tid].cids, &cid->node, cid->cid.len);
3576
3577 quic_connection_id_to_frm_cpy(frm, cid);
3578 LIST_APPEND(&frm_list, &frm->list);
3579 }
3580
3581 LIST_SPLICE(&qel->pktns->tx.frms, &frm_list);
3582 qc->flags |= QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT;
3583
3584 ret = 1;
3585 leave:
3586 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
3587 return ret;
3588
3589 err:
3590 /* free the frames */
3591 list_for_each_entry_safe(frm, frmbak, &frm_list, list)
3592 pool_free(pool_head_quic_frame, frm);
3593
3594 node = eb64_lookup_ge(&qc->cids, first);
3595 while (node) {
3596 struct quic_connection_id *cid;
3597
3598 cid = eb64_entry(node, struct quic_connection_id, seq_num);
3599 if (cid->seq_num.key >= max)
3600 break;
3601
3602 node = eb64_next(node);
3603 ebmb_delete(&cid->node);
3604 eb64_delete(&cid->seq_num);
3605 pool_free(pool_head_quic_connection_id, cid);
3606 }
3607 goto leave;
3608}
3609
3610/* Deallocate <l> list of ACK ranges. */
3611void quic_free_arngs(struct quic_conn *qc, struct quic_arngs *arngs)
3612{
3613 struct eb64_node *n;
3614 struct quic_arng_node *ar;
3615
3616 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
3617
3618 n = eb64_first(&arngs->root);
3619 while (n) {
3620 struct eb64_node *next;
3621
3622 ar = eb64_entry(n, struct quic_arng_node, first);
3623 next = eb64_next(n);
3624 eb64_delete(n);
3625 pool_free(pool_head_quic_arng, ar);
3626 n = next;
3627 }
3628
3629 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
3630}
3631
3632/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
3633 * descending order.
3634 */
3635static inline size_t sack_gap(struct quic_arng_node *p,
3636 struct quic_arng_node *q)
3637{
3638 return p->first.key - q->last - 2;
3639}
3640
3641
3642/* Remove the last elements of <ack_ranges> list of ack range updating its
3643 * encoded size until it goes below <limit>.
3644 * Returns 1 if succeeded, 0 if not (no more element to remove).
3645 */
3646static int quic_rm_last_ack_ranges(struct quic_conn *qc,
3647 struct quic_arngs *arngs, size_t limit)
3648{
3649 int ret = 0;
3650 struct eb64_node *last, *prev;
3651
3652 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3653
3654 last = eb64_last(&arngs->root);
3655 while (last && arngs->enc_sz > limit) {
3656 struct quic_arng_node *last_node, *prev_node;
3657
3658 prev = eb64_prev(last);
3659 if (!prev) {
3660 TRACE_DEVEL("<last> not found", QUIC_EV_CONN_TXPKT, qc);
3661 goto out;
3662 }
3663
3664 last_node = eb64_entry(last, struct quic_arng_node, first);
3665 prev_node = eb64_entry(prev, struct quic_arng_node, first);
3666 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
3667 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
3668 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
3669 --arngs->sz;
3670 eb64_delete(last);
3671 pool_free(pool_head_quic_arng, last);
3672 last = prev;
3673 }
3674
3675 ret = 1;
3676 out:
3677 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3678 return ret;
3679}
3680
3681/* Set the encoded size of <arngs> QUIC ack ranges. */
3682static void quic_arngs_set_enc_sz(struct quic_conn *qc, struct quic_arngs *arngs)
3683{
3684 struct eb64_node *node, *next;
3685 struct quic_arng_node *ar, *ar_next;
3686
3687 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
3688
3689 node = eb64_last(&arngs->root);
3690 if (!node)
3691 goto leave;
3692
3693 ar = eb64_entry(node, struct quic_arng_node, first);
3694 arngs->enc_sz = quic_int_getsize(ar->last) +
3695 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
3696
3697 while ((next = eb64_prev(node))) {
3698 ar_next = eb64_entry(next, struct quic_arng_node, first);
3699 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
3700 quic_int_getsize(ar_next->last - ar_next->first.key);
3701 node = next;
3702 ar = eb64_entry(node, struct quic_arng_node, first);
3703 }
3704
3705 leave:
3706 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
3707}
3708
3709/* Insert <ar> ack range into <argns> tree of ack ranges.
3710 * Returns the ack range node which has been inserted if succeeded, NULL if not.
3711 */
3712static inline
3713struct quic_arng_node *quic_insert_new_range(struct quic_conn *qc,
3714 struct quic_arngs *arngs,
3715 struct quic_arng *ar)
3716{
3717 struct quic_arng_node *new_ar;
3718
3719 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3720
3721 new_ar = pool_alloc(pool_head_quic_arng);
3722 if (!new_ar) {
3723 TRACE_ERROR("ack range allocation failed", QUIC_EV_CONN_RXPKT, qc);
3724 goto leave;
3725 }
3726
3727 new_ar->first.key = ar->first;
3728 new_ar->last = ar->last;
3729 eb64_insert(&arngs->root, &new_ar->first);
3730 arngs->sz++;
3731
3732 leave:
3733 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3734 return new_ar;
3735}
3736
3737/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
3738 * Note that this function computes the number of bytes required to encode
3739 * this tree of ACK ranges in descending order.
3740 *
3741 * Descending order
3742 * ------------->
3743 * range1 range2
3744 * ..........|--------|..............|--------|
3745 * ^ ^ ^ ^
3746 * | | | |
3747 * last1 first1 last2 first2
3748 * ..........+--------+--------------+--------+......
3749 * diff1 gap12 diff2
3750 *
3751 * To encode the previous list of ranges we must encode integers as follows in
3752 * descending order:
3753 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
3754 * with diff1 = last1 - first1
3755 * diff2 = last2 - first2
3756 * gap12 = first1 - last2 - 2 (>= 0)
3757 *
3758
3759returns 0 on error
3760
3761 */
3762int quic_update_ack_ranges_list(struct quic_conn *qc,
3763 struct quic_arngs *arngs,
3764 struct quic_arng *ar)
3765{
3766 int ret = 0;
3767 struct eb64_node *le;
3768 struct quic_arng_node *new_node;
3769 struct eb64_node *new;
3770
3771 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
3772
3773 new = NULL;
3774 if (eb_is_empty(&arngs->root)) {
3775 new_node = quic_insert_new_range(qc, arngs, ar);
3776 if (new_node)
3777 ret = 1;
3778
3779 goto leave;
3780 }
3781
3782 le = eb64_lookup_le(&arngs->root, ar->first);
3783 if (!le) {
3784 new_node = quic_insert_new_range(qc, arngs, ar);
3785 if (!new_node)
3786 goto leave;
3787
3788 new = &new_node->first;
3789 }
3790 else {
3791 struct quic_arng_node *le_ar =
3792 eb64_entry(le, struct quic_arng_node, first);
3793
3794 /* Already existing range */
3795 if (le_ar->last >= ar->last) {
3796 ret = 1;
3797 }
3798 else if (le_ar->last + 1 >= ar->first) {
3799 le_ar->last = ar->last;
3800 new = le;
3801 new_node = le_ar;
3802 }
3803 else {
3804 new_node = quic_insert_new_range(qc, arngs, ar);
3805 if (!new_node)
3806 goto leave;
3807
3808 new = &new_node->first;
3809 }
3810 }
3811
3812 /* Verify that the new inserted node does not overlap the nodes
3813 * which follow it.
3814 */
3815 if (new) {
3816 struct eb64_node *next;
3817 struct quic_arng_node *next_node;
3818
3819 while ((next = eb64_next(new))) {
3820 next_node =
3821 eb64_entry(next, struct quic_arng_node, first);
3822 if (new_node->last + 1 < next_node->first.key)
3823 break;
3824
3825 if (next_node->last > new_node->last)
3826 new_node->last = next_node->last;
3827 eb64_delete(next);
3828 pool_free(pool_head_quic_arng, next_node);
3829 /* Decrement the size of these ranges. */
3830 arngs->sz--;
3831 }
3832 }
3833
3834 ret = 1;
3835 leave:
3836 quic_arngs_set_enc_sz(qc, arngs);
3837 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
3838 return ret;
3839}
3840/* Remove the header protection of packets at <el> encryption level.
3841 * Always succeeds.
3842 */
3843static inline void qc_rm_hp_pkts(struct quic_conn *qc, struct quic_enc_level *el)
3844{
3845 struct quic_tls_ctx *tls_ctx;
3846 struct quic_rx_packet *pqpkt, *pkttmp;
3847 struct quic_enc_level *app_qel;
3848
3849 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, qc);
3850 app_qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3851 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
3852 if (el == app_qel && qc_is_listener(qc) && qc->state < QUIC_HS_ST_COMPLETE) {
3853 TRACE_DEVEL("hp not removed (handshake not completed)",
3854 QUIC_EV_CONN_ELRMHP, qc);
3855 goto out;
3856 }
3857 tls_ctx = &el->tls_ctx;
3858 list_for_each_entry_safe(pqpkt, pkttmp, &el->rx.pqpkts, list) {
3859 if (!qc_do_rm_hp(qc, pqpkt, tls_ctx, el->pktns->rx.largest_pn,
3860 pqpkt->data + pqpkt->pn_offset, pqpkt->data)) {
3861 TRACE_ERROR("hp removing error", QUIC_EV_CONN_ELRMHP, qc);
3862 }
3863 else {
3864 /* The AAD includes the packet number field */
3865 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
3866 /* Store the packet into the tree of packets to decrypt. */
3867 pqpkt->pn_node.key = pqpkt->pn;
3868 eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
3869 quic_rx_packet_refinc(pqpkt);
3870 TRACE_DEVEL("hp removed", QUIC_EV_CONN_ELRMHP, qc, pqpkt);
3871 }
3872 LIST_DELETE(&pqpkt->list);
3873 quic_rx_packet_refdec(pqpkt);
3874 }
3875
3876 out:
3877 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, qc);
3878}
3879
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003880/* Process all the CRYPTO frame at <el> encryption level. This is the
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05003881 * responsibility of the called to ensure there exists a CRYPTO data
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003882 * stream for this level.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003883 * Return 1 if succeeded, 0 if not.
3884 */
3885static inline int qc_treat_rx_crypto_frms(struct quic_conn *qc,
3886 struct quic_enc_level *el,
3887 struct ssl_sock_ctx *ctx)
3888{
3889 int ret = 0;
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003890 struct ncbuf *ncbuf;
3891 struct quic_cstream *cstream = el->cstream;
3892 ncb_sz_t data;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003893
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003894 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003895
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003896 BUG_ON(!cstream);
3897 ncbuf = &cstream->rx.ncbuf;
3898 if (ncb_is_null(ncbuf))
3899 goto done;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003900
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01003901 /* TODO not working if buffer is wrapping */
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003902 while ((data = ncb_data(ncbuf, 0))) {
3903 const unsigned char *cdata = (const unsigned char *)ncb_head(ncbuf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003904
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003905 if (!qc_provide_cdata(el, ctx, cdata, data, NULL, NULL))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003906 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003907
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003908 cstream->rx.offset += data;
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01003909 TRACE_DEVEL("buffered crypto data were provided to TLS stack",
3910 QUIC_EV_CONN_PHPKTS, qc, el);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003911 }
3912
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003913 done:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003914 ret = 1;
3915 leave:
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01003916 if (!ncb_is_null(ncbuf) && ncb_is_empty(ncbuf)) {
3917 TRACE_DEVEL("freeing crypto buf", QUIC_EV_CONN_PHPKTS, qc, el);
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003918 quic_free_ncbuf(ncbuf);
Amaury Denoyelle2f668f02022-11-18 15:24:08 +01003919 }
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003920 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003921 return ret;
3922}
3923
3924/* Process all the packets at <el> and <next_el> encryption level.
3925 * This is the caller responsibility to check that <cur_el> is different of <next_el>
3926 * as pointer value.
3927 * Return 1 if succeeded, 0 if not.
3928 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003929int qc_treat_rx_pkts(struct quic_conn *qc, struct quic_enc_level *cur_el,
3930 struct quic_enc_level *next_el, int force_ack)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003931{
3932 int ret = 0;
3933 struct eb64_node *node;
3934 int64_t largest_pn = -1;
3935 unsigned int largest_pn_time_received = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003936 struct quic_enc_level *qel = cur_el;
3937
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003938 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003939 qel = cur_el;
3940 next_tel:
3941 if (!qel)
3942 goto out;
3943
3944 node = eb64_first(&qel->rx.pkts);
3945 while (node) {
3946 struct quic_rx_packet *pkt;
3947
3948 pkt = eb64_entry(node, struct quic_rx_packet, pn_node);
3949 TRACE_DATA("new packet", QUIC_EV_CONN_RXPKT,
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003950 qc, pkt, NULL, qc->xprt_ctx->ssl);
Amaury Denoyelle518c98f2022-11-24 17:12:25 +01003951 if (!qc_pkt_decrypt(qc, qel, pkt)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003952 /* Drop the packet */
3953 TRACE_ERROR("packet decryption failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003954 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003955 }
3956 else {
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003957 if (!qc_parse_pkt_frms(qc, pkt, qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003958 /* Drop the packet */
3959 TRACE_ERROR("packet parsing failed -> dropped",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003960 QUIC_EV_CONN_RXPKT, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003961 HA_ATOMIC_INC(&qc->prx_counters->dropped_parsing);
3962 }
3963 else {
3964 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
3965
3966 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING || force_ack) {
3967 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
3968 qel->pktns->rx.nb_aepkts_since_last_ack++;
3969 qc_idle_timer_rearm(qc, 1);
3970 }
3971 if (pkt->pn > largest_pn) {
3972 largest_pn = pkt->pn;
3973 largest_pn_time_received = pkt->time_received;
3974 }
3975 /* Update the list of ranges to acknowledge. */
3976 if (!quic_update_ack_ranges_list(qc, &qel->pktns->rx.arngs, &ar))
3977 TRACE_ERROR("Could not update ack range list",
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02003978 QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003979 }
3980 }
3981 node = eb64_next(node);
3982 eb64_delete(&pkt->pn_node);
3983 quic_rx_packet_refdec(pkt);
3984 }
3985
3986 if (largest_pn != -1 && largest_pn > qel->pktns->rx.largest_pn) {
3987 /* Update the largest packet number. */
3988 qel->pktns->rx.largest_pn = largest_pn;
3989 /* Update the largest acknowledged packet timestamps */
3990 qel->pktns->rx.largest_time_received = largest_pn_time_received;
3991 qel->pktns->flags |= QUIC_FL_PKTNS_NEW_LARGEST_PN;
3992 }
3993
Frédéric Lécaille9f9263e2022-09-13 14:36:44 +02003994 if (qel->cstream && !qc_treat_rx_crypto_frms(qc, qel, qc->xprt_ctx)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02003995 // trace already emitted by function above
3996 goto leave;
3997 }
3998
3999 if (qel == cur_el) {
4000 BUG_ON(qel == next_el);
4001 qel = next_el;
4002 largest_pn = -1;
4003 goto next_tel;
4004 }
4005
4006 out:
4007 ret = 1;
4008 leave:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004009 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004010 return ret;
4011}
4012
4013/* Check if it's possible to remove header protection for packets related to
4014 * encryption level <qel>. If <qel> is NULL, assume it's false.
4015 *
4016 * Return true if the operation is possible else false.
4017 */
4018static int qc_qel_may_rm_hp(struct quic_conn *qc, struct quic_enc_level *qel)
4019{
4020 int ret = 0;
4021 enum quic_tls_enc_level tel;
4022
4023 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
4024
4025 if (!qel)
4026 goto cant_rm_hp;
4027
4028 tel = ssl_to_quic_enc_level(qel->level);
4029
4030 /* check if tls secrets are available */
4031 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
4032 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, qc);
4033 goto cant_rm_hp;
4034 }
4035
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004036 if (!quic_tls_has_rx_sec(qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004037 TRACE_DEVEL("non available secrets", QUIC_EV_CONN_TRMHP, qc);
4038 goto cant_rm_hp;
4039 }
4040
4041 /* check if the connection layer is ready before using app level */
4042 if ((tel == QUIC_TLS_ENC_LEVEL_APP || tel == QUIC_TLS_ENC_LEVEL_EARLY_DATA) &&
4043 qc->mux_state == QC_MUX_NULL) {
4044 TRACE_DEVEL("connection layer not ready", QUIC_EV_CONN_TRMHP, qc);
4045 goto cant_rm_hp;
4046 }
4047
4048 ret = 1;
4049 cant_rm_hp:
4050 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc);
4051 return ret;
4052}
4053
4054/* Try to send application frames from list <frms> on connection <qc>.
4055 *
4056 * Use qc_send_app_probing wrapper when probing with old data.
4057 *
4058 * Returns 1 on success. Some data might not have been sent due to congestion,
4059 * in this case they are left in <frms> input list. The caller may subscribe on
4060 * quic-conn to retry later.
4061 *
4062 * Returns 0 on critical error.
4063 * TODO review and classify more distinctly transient from definitive errors to
4064 * allow callers to properly handle it.
4065 */
4066static int qc_send_app_pkts(struct quic_conn *qc, struct list *frms)
4067{
4068 int status = 0;
4069 struct buffer *buf;
4070
4071 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4072
4073 buf = qc_txb_alloc(qc);
4074 if (!buf) {
4075 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4076 goto leave;
4077 }
4078
4079 /* Prepare and send packets until we could not further prepare packets. */
4080 while (1) {
4081 int ret;
4082 /* Currently buf cannot be non-empty at this stage. Even if a
4083 * previous sendto() has failed it is emptied to simulate
4084 * packet emission and rely on QUIC lost detection to try to
4085 * emit it.
4086 */
4087 BUG_ON_HOT(b_data(buf));
4088 b_reset(buf);
4089
4090 ret = qc_prep_app_pkts(qc, buf, frms);
4091 if (ret == -1)
4092 goto err;
4093 else if (ret == 0)
4094 goto out;
4095
4096 if (!qc_send_ppkts(buf, qc->xprt_ctx))
4097 goto err;
4098 }
4099
4100 out:
4101 status = 1;
4102 qc_txb_release(qc);
4103 leave:
4104 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4105 return status;
4106
4107 err:
4108 qc_txb_release(qc);
4109 goto leave;
4110}
4111
4112/* Try to send application frames from list <frms> on connection <qc>. Use this
4113 * function when probing is required.
4114 *
4115 * Returns the result from qc_send_app_pkts function.
4116 */
4117static forceinline int qc_send_app_probing(struct quic_conn *qc,
4118 struct list *frms)
4119{
4120 int ret;
4121
4122 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4123
4124 TRACE_STATE("preparing old data (probing)", QUIC_EV_CONN_TXPKT, qc);
4125 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4126 ret = qc_send_app_pkts(qc, frms);
4127 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4128
4129 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4130 return ret;
4131}
4132
4133/* Try to send application frames from list <frms> on connection <qc>. This
4134 * function is provided for MUX upper layer usage only.
4135 *
4136 * Returns the result from qc_send_app_pkts function.
4137 */
4138int qc_send_mux(struct quic_conn *qc, struct list *frms)
4139{
4140 int ret;
4141
4142 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4143 BUG_ON(qc->mux_state != QC_MUX_READY); /* Only MUX can uses this function so it must be ready. */
4144
4145 TRACE_STATE("preparing data (from MUX)", QUIC_EV_CONN_TXPKT, qc);
4146 qc->flags |= QUIC_FL_CONN_TX_MUX_CONTEXT;
4147 ret = qc_send_app_pkts(qc, frms);
4148 qc->flags &= ~QUIC_FL_CONN_TX_MUX_CONTEXT;
4149
4150 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4151 return ret;
4152}
4153
4154/* Sends handshake packets from up to two encryption levels <tel> and <next_te>
4155 * with <tel_frms> and <next_tel_frms> as frame list respectively for <qc>
4156 * QUIC connection. <old_data> is used as boolean to send data already sent but
4157 * not already acknowledged (in flight).
4158 * Returns 1 if succeeded, 0 if not.
4159 */
4160int qc_send_hdshk_pkts(struct quic_conn *qc, int old_data,
4161 enum quic_tls_enc_level tel, struct list *tel_frms,
4162 enum quic_tls_enc_level next_tel, struct list *next_tel_frms)
4163{
4164 int ret, status = 0;
4165 struct buffer *buf = qc_txb_alloc(qc);
4166
4167 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4168
4169 if (!buf) {
4170 TRACE_ERROR("buffer allocation failed", QUIC_EV_CONN_TXPKT, qc);
4171 goto leave;
4172 }
4173
4174 /* Currently buf cannot be non-empty at this stage. Even if a previous
4175 * sendto() has failed it is emptied to simulate packet emission and
4176 * rely on QUIC lost detection to try to emit it.
4177 */
4178 BUG_ON_HOT(b_data(buf));
4179 b_reset(buf);
4180
4181 if (old_data) {
4182 TRACE_STATE("old data for probing asked", QUIC_EV_CONN_TXPKT, qc);
4183 qc->flags |= QUIC_FL_CONN_RETRANS_OLD_DATA;
4184 }
4185
4186 ret = qc_prep_pkts(qc, buf, tel, tel_frms, next_tel, next_tel_frms);
4187 if (ret == -1)
4188 goto out;
4189 else if (ret == 0)
4190 goto skip_send;
4191
4192 if (!qc_send_ppkts(buf, qc->xprt_ctx))
4193 goto out;
4194
4195 skip_send:
4196 status = 1;
4197 out:
4198 TRACE_STATE("no more need old data for probing", QUIC_EV_CONN_TXPKT, qc);
4199 qc->flags &= ~QUIC_FL_CONN_RETRANS_OLD_DATA;
4200 qc_txb_release(qc);
4201 leave:
4202 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4203 return status;
4204}
4205
4206/* Retransmit up to two datagrams depending on packet number space */
4207static void qc_dgrams_retransmit(struct quic_conn *qc)
4208{
4209 struct quic_enc_level *iqel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4210 struct quic_enc_level *hqel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4211 struct quic_enc_level *aqel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4212
4213 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
4214
4215 if (iqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4216 struct list ifrms = LIST_HEAD_INIT(ifrms);
4217 struct list hfrms = LIST_HEAD_INIT(hfrms);
4218
4219 qc_prep_hdshk_fast_retrans(qc, &ifrms, &hfrms);
4220 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &ifrms);
4221 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4222 if (!LIST_ISEMPTY(&ifrms)) {
4223 iqel->pktns->tx.pto_probe = 1;
4224 if (!LIST_ISEMPTY(&hfrms)) {
4225 hqel->pktns->tx.pto_probe = 1;
4226 qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_INITIAL, &ifrms,
4227 QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms);
4228 /* Put back unsent frames in their packet number spaces */
4229 LIST_SPLICE(&iqel->pktns->tx.frms, &ifrms);
4230 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4231 }
4232 }
4233 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4234 /* This list has potentially been already used and spliced
4235 * to another one attached to the connection. We must reinitialize it.
4236 */
4237 LIST_INIT(&hfrms);
4238 qc_prep_fast_retrans(qc, hqel, &hfrms, NULL);
4239 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &hfrms);
4240 if (!LIST_ISEMPTY(&hfrms)) {
4241 hqel->pktns->tx.pto_probe = 1;
4242 qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &hfrms,
4243 QUIC_TLS_ENC_LEVEL_NONE, NULL);
4244 /* Put back unsent frames into their packet number spaces */
4245 LIST_SPLICE(&hqel->pktns->tx.frms, &hfrms);
4246 }
4247 TRACE_STATE("no more need to probe Handshake packet number space",
4248 QUIC_EV_CONN_TXPKT, qc);
4249 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4250 }
4251 TRACE_STATE("no more need to probe Initial packet number space",
4252 QUIC_EV_CONN_TXPKT, qc);
4253 iqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4254 }
4255 else {
4256 int i;
4257
4258 if (hqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004259 hqel->pktns->tx.pto_probe = 0;
4260 for (i = 0; i < QUIC_MAX_NB_PTO_DGRAMS; i++) {
Frédéric Lécaille7b5d9b12022-11-28 17:21:45 +01004261 struct list frms1 = LIST_HEAD_INIT(frms1);
4262
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004263 qc_prep_fast_retrans(qc, hqel, &frms1, NULL);
4264 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4265 if (!LIST_ISEMPTY(&frms1)) {
4266 hqel->pktns->tx.pto_probe = 1;
4267 qc_send_hdshk_pkts(qc, 1, QUIC_TLS_ENC_LEVEL_HANDSHAKE, &frms1,
4268 QUIC_TLS_ENC_LEVEL_NONE, NULL);
4269 /* Put back unsent frames into their packet number spaces */
4270 LIST_SPLICE(&hqel->pktns->tx.frms, &frms1);
4271 }
4272 }
4273 TRACE_STATE("no more need to probe Handshake packet number space",
4274 QUIC_EV_CONN_TXPKT, qc);
4275 hqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4276 }
4277 else if (aqel->pktns->flags & QUIC_FL_PKTNS_PROBE_NEEDED) {
4278 struct list frms2 = LIST_HEAD_INIT(frms2);
4279 struct list frms1 = LIST_HEAD_INIT(frms1);
4280
4281 aqel->pktns->tx.pto_probe = 0;
4282 qc_prep_fast_retrans(qc, aqel, &frms1, &frms2);
4283 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms1);
4284 TRACE_PROTO("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, &frms2);
4285 if (!LIST_ISEMPTY(&frms1)) {
4286 aqel->pktns->tx.pto_probe = 1;
4287 qc_send_app_probing(qc, &frms1);
4288 /* Put back unsent frames into their packet number spaces */
4289 LIST_SPLICE(&aqel->pktns->tx.frms, &frms1);
4290 }
4291 if (!LIST_ISEMPTY(&frms2)) {
4292 aqel->pktns->tx.pto_probe = 1;
4293 qc_send_app_probing(qc, &frms2);
4294 /* Put back unsent frames into their packet number spaces */
4295 LIST_SPLICE(&aqel->pktns->tx.frms, &frms2);
4296 }
4297 TRACE_STATE("no more need to probe 01RTT packet number space",
4298 QUIC_EV_CONN_TXPKT, qc);
4299 aqel->pktns->flags &= ~QUIC_FL_PKTNS_PROBE_NEEDED;
4300 }
4301 }
4302 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
4303}
4304
4305/* QUIC connection packet handler task (post handshake) */
4306struct task *quic_conn_app_io_cb(struct task *t, void *context, unsigned int state)
4307{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004308 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004309 struct quic_enc_level *qel;
4310
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004311 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
4312
4313 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
4314 TRACE_STATE("connection handshake state", QUIC_EV_CONN_IO_CB, qc, &qc->state);
4315
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004316 if (qc_test_fd(qc))
4317 qc_rcv_buf(qc);
4318
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004319 /* Retranmissions */
4320 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4321 TRACE_STATE("retransmission needed", QUIC_EV_CONN_IO_CB, qc);
4322 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
4323 qc_dgrams_retransmit(qc);
4324 }
4325
4326 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4327 qc_rm_hp_pkts(qc, qel);
4328
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004329 if (!qc_treat_rx_pkts(qc, qel, NULL, 0)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004330 TRACE_DEVEL("qc_treat_rx_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4331 goto out;
4332 }
4333
4334 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4335 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE)) {
4336 TRACE_STATE("draining connection (must not send packets)", QUIC_EV_CONN_IO_CB, qc);
4337 goto out;
4338 }
4339
4340 /* XXX TODO: how to limit the list frames to send */
4341 if (!qc_send_app_pkts(qc, &qel->pktns->tx.frms)) {
4342 TRACE_DEVEL("qc_send_app_pkts() failed", QUIC_EV_CONN_IO_CB, qc);
4343 goto out;
4344 }
4345
4346 out:
4347 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc);
4348 return t;
4349}
4350
4351/* Returns a boolean if <qc> needs to emit frames for <qel> encryption level. */
4352static int qc_need_sending(struct quic_conn *qc, struct quic_enc_level *qel)
4353{
4354 return (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) ||
4355 (qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) ||
4356 qel->pktns->tx.pto_probe ||
4357 !LIST_ISEMPTY(&qel->pktns->tx.frms);
4358}
4359
4360/* QUIC connection packet handler task. */
4361struct task *quic_conn_io_cb(struct task *t, void *context, unsigned int state)
4362{
4363 int ret, ssl_err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004364 struct quic_conn *qc = context;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004365 enum quic_tls_enc_level tel, next_tel;
4366 struct quic_enc_level *qel, *next_qel;
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004367 /* Early-data encryption level */
4368 struct quic_enc_level *eqel;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004369 struct buffer *buf = NULL;
4370 int st, force_ack, zero_rtt;
4371
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004372 TRACE_ENTER(QUIC_EV_CONN_IO_CB, qc);
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004373 eqel = &qc->els[QUIC_TLS_ENC_LEVEL_EARLY_DATA];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004374 st = qc->state;
4375 TRACE_PROTO("connection state", QUIC_EV_CONN_IO_CB, qc, &st);
4376
4377 /* Retranmissions */
4378 if (qc->flags & QUIC_FL_CONN_RETRANS_NEEDED) {
4379 TRACE_DEVEL("retransmission needed", QUIC_EV_CONN_PHPKTS, qc);
4380 qc->flags &= ~QUIC_FL_CONN_RETRANS_NEEDED;
4381 qc_dgrams_retransmit(qc);
4382 }
4383
4384 if (qc->flags & QUIC_FL_CONN_IO_CB_WAKEUP) {
4385 qc->flags &= ~QUIC_FL_CONN_IO_CB_WAKEUP;
4386 TRACE_DEVEL("needs to wakeup the timer task after the anti-amplicaiton limit was reached",
4387 QUIC_EV_CONN_IO_CB, qc);
4388 /* The I/O handler has been woken up by the dgram parser (qc_lstnr_pkt_rcv())
4389 * after the anti-amplification was reached.
4390 *
4391 * TODO: this part should be removed. This was there because the
4392 * datagram parser was not executed by only one thread.
4393 */
4394 qc_set_timer(qc);
Amaury Denoyelle5ac6b3b2022-12-14 18:04:06 +01004395 if (qc->timer_task && tick_isset(qc->timer) && tick_is_lt(qc->timer, now_ms))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004396 task_wakeup(qc->timer_task, TASK_WOKEN_MSG);
4397 }
4398 ssl_err = SSL_ERROR_NONE;
4399 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004400 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004401 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01004402
4403 if (qc_test_fd(qc))
4404 qc_rcv_buf(qc);
4405
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004406 if (st >= QUIC_HS_ST_COMPLETE &&
4407 qc_el_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
4408 TRACE_DEVEL("remaining Handshake packets", QUIC_EV_CONN_PHPKTS, qc);
4409 /* There may be remaining Handshake packets to treat and acknowledge. */
4410 tel = QUIC_TLS_ENC_LEVEL_HANDSHAKE;
4411 next_tel = QUIC_TLS_ENC_LEVEL_APP;
4412 }
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004413 else if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, zero_rtt))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004414 goto out;
4415
4416 qel = &qc->els[tel];
4417 next_qel = next_tel == QUIC_TLS_ENC_LEVEL_NONE ? NULL : &qc->els[next_tel];
4418
4419 next_level:
4420 /* Treat packets waiting for header packet protection decryption */
4421 if (!LIST_ISEMPTY(&qel->rx.pqpkts) && qc_qel_may_rm_hp(qc, qel))
4422 qc_rm_hp_pkts(qc, qel);
4423
4424 force_ack = qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
4425 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004426 if (!qc_treat_rx_pkts(qc, qel, next_qel, force_ack))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004427 goto out;
4428
4429 if ((qc->flags & QUIC_FL_CONN_DRAINING) &&
4430 !(qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE))
4431 goto out;
4432
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004433 zero_rtt = st < QUIC_HS_ST_COMPLETE &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004434 quic_tls_has_rx_sec(eqel) &&
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004435 (!LIST_ISEMPTY(&eqel->rx.pqpkts) || qc_el_rx_pkts(eqel));
4436 if (next_qel && next_qel == eqel && zero_rtt) {
4437 TRACE_DEVEL("select 0RTT as next encryption level",
4438 QUIC_EV_CONN_PHPKTS, qc);
4439 qel = next_qel;
4440 next_qel = NULL;
4441 goto next_level;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004442 }
4443
4444 st = qc->state;
4445 if (st >= QUIC_HS_ST_COMPLETE) {
4446 if (!(qc->flags & QUIC_FL_CONN_POST_HANDSHAKE_FRAMES_BUILT) &&
4447 !quic_build_post_handshake_frames(qc))
4448 goto out;
4449
4450 if (!(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].tls_ctx.flags &
4451 QUIC_FL_TLS_SECRETS_DCD)) {
4452 /* Discard the Handshake keys. */
4453 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4454 TRACE_PROTO("discarding Handshake pktns", QUIC_EV_CONN_PHPKTS, qc);
4455 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, qc);
4456 qc_set_timer(qc);
4457 qc_el_rx_pkts_del(&qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
4458 qc_release_pktns_frms(qc, qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns);
4459 }
4460
4461 if (qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) {
4462 /* There may be remaining handshake to build (acks) */
4463 st = QUIC_HS_ST_SERVER_HANDSHAKE;
4464 }
4465 }
4466
4467 /* A listener does not send any O-RTT packet. O-RTT packet number space must not
4468 * be considered.
4469 */
Frédéric Lécaille4aa7d812022-09-16 10:15:58 +02004470 if (!quic_get_tls_enc_levels(&tel, &next_tel, qc, st, 0))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004471 goto out;
4472
4473 if (!qc_need_sending(qc, qel) &&
4474 (!next_qel || !qc_need_sending(qc, next_qel))) {
4475 goto skip_send;
4476 }
4477
4478 buf = qc_txb_alloc(qc);
4479 if (!buf)
4480 goto out;
4481
4482 /* Currently buf cannot be non-empty at this stage. Even if a previous
4483 * sendto() has failed it is emptied to simulate packet emission and
4484 * rely on QUIC lost detection to try to emit it.
4485 */
4486 BUG_ON_HOT(b_data(buf));
4487 b_reset(buf);
4488
4489 ret = qc_prep_pkts(qc, buf, tel, &qc->els[tel].pktns->tx.frms,
4490 next_tel, &qc->els[next_tel].pktns->tx.frms);
4491 if (ret == -1)
4492 goto out;
4493 else if (ret == 0)
4494 goto skip_send;
4495
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004496 if (!qc_send_ppkts(buf, qc->xprt_ctx))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004497 goto out;
4498
4499 skip_send:
4500 /* Check if there is something to do for the next level.
4501 */
4502 if (next_qel && next_qel != qel &&
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004503 quic_tls_has_rx_sec(next_qel) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004504 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || qc_el_rx_pkts(next_qel))) {
4505 qel = next_qel;
4506 next_qel = NULL;
4507 goto next_level;
4508 }
4509
4510 out:
4511 qc_txb_release(qc);
4512 TRACE_LEAVE(QUIC_EV_CONN_IO_CB, qc, &st, &ssl_err);
4513 return t;
4514}
4515
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004516/* Release the memory allocated for <cs> CRYPTO stream */
4517void quic_cstream_free(struct quic_cstream *cs)
4518{
4519 if (!cs) {
4520 /* This is the case for ORTT encryption level */
4521 return;
4522 }
4523
Amaury Denoyellebc174b22022-11-17 10:12:52 +01004524 quic_free_ncbuf(&cs->rx.ncbuf);
4525
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004526 qc_stream_desc_release(cs->desc);
4527 pool_free(pool_head_quic_cstream, cs);
4528}
4529
4530/* Allocate a new QUIC stream for <qc>.
4531 * Return it if succeeded, NULL if not.
4532 */
4533struct quic_cstream *quic_cstream_new(struct quic_conn *qc)
4534{
4535 struct quic_cstream *cs, *ret_cs = NULL;
4536
4537 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4538 cs = pool_alloc(pool_head_quic_cstream);
4539 if (!cs) {
4540 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4541 goto leave;
4542 }
4543
4544 cs->rx.offset = 0;
4545 cs->rx.ncbuf = NCBUF_NULL;
4546 cs->rx.offset = 0;
4547
4548 cs->tx.offset = 0;
4549 cs->tx.sent_offset = 0;
4550 cs->tx.buf = BUF_NULL;
4551 cs->desc = qc_stream_desc_new((uint64_t)-1, -1, cs, qc);
4552 if (!cs->desc) {
4553 TRACE_ERROR("crypto stream allocation failed", QUIC_EV_CONN_INIT, qc);
4554 goto err;
4555 }
4556
4557 ret_cs = cs;
4558 leave:
4559 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4560 return ret_cs;
4561
4562 err:
4563 pool_free(pool_head_quic_cstream, cs);
4564 goto leave;
4565}
4566
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004567/* Uninitialize <qel> QUIC encryption level. Never fails. */
4568static void quic_conn_enc_level_uninit(struct quic_conn *qc, struct quic_enc_level *qel)
4569{
4570 int i;
4571
4572 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4573
4574 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
4575 if (qel->tx.crypto.bufs[i]) {
4576 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
4577 qel->tx.crypto.bufs[i] = NULL;
4578 }
4579 }
4580 ha_free(&qel->tx.crypto.bufs);
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004581 quic_cstream_free(qel->cstream);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004582
4583 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4584}
4585
4586/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
4587 * connection allocating everything needed.
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004588 *
4589 * Returns 1 if succeeded, 0 if not. On error the caller is responsible to use
4590 * quic_conn_enc_level_uninit() to cleanup partially allocated content.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004591 */
4592static int quic_conn_enc_level_init(struct quic_conn *qc,
4593 enum quic_tls_enc_level level)
4594{
4595 int ret = 0;
4596 struct quic_enc_level *qel;
4597
4598 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4599
4600 qel = &qc->els[level];
4601 qel->level = quic_to_ssl_enc_level(level);
4602 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
4603 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
4604 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
4605 qel->tls_ctx.flags = 0;
4606
4607 qel->rx.pkts = EB_ROOT;
4608 LIST_INIT(&qel->rx.pqpkts);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004609
4610 /* Allocate only one buffer. */
4611 /* TODO: use a pool */
4612 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
4613 if (!qel->tx.crypto.bufs)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004614 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004615
4616 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
4617 if (!qel->tx.crypto.bufs[0])
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004618 goto leave;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004619
4620 qel->tx.crypto.bufs[0]->sz = 0;
4621 qel->tx.crypto.nb_buf = 1;
4622
4623 qel->tx.crypto.sz = 0;
4624 qel->tx.crypto.offset = 0;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004625 /* No CRYPTO data for early data TLS encryption level */
4626 if (level == QUIC_TLS_ENC_LEVEL_EARLY_DATA)
4627 qel->cstream = NULL;
4628 else {
4629 qel->cstream = quic_cstream_new(qc);
4630 if (!qel->cstream)
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004631 goto leave;
Frédéric Lécaille7e3f7c42022-09-09 18:05:45 +02004632 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004633
4634 ret = 1;
4635 leave:
4636 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
4637 return ret;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004638}
4639
4640/* Callback called upon loss detection and PTO timer expirations. */
4641struct task *qc_process_timer(struct task *task, void *ctx, unsigned int state)
4642{
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004643 struct quic_conn *qc = ctx;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004644 struct quic_pktns *pktns;
4645
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004646 TRACE_ENTER(QUIC_EV_CONN_PTIMER, qc,
4647 NULL, NULL, &qc->path->ifae_pkts);
4648 task->expire = TICK_ETERNITY;
4649 pktns = quic_loss_pktns(qc);
4650 if (tick_isset(pktns->tx.loss_time)) {
4651 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
4652
4653 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
4654 if (!LIST_ISEMPTY(&lost_pkts))
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004655 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004656 qc_release_lost_pkts(qc, pktns, &lost_pkts, now_ms);
4657 qc_set_timer(qc);
4658 goto out;
4659 }
4660
4661 if (qc->path->in_flight) {
4662 pktns = quic_pto_pktns(qc, qc->state >= QUIC_HS_ST_COMPLETE, NULL);
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02004663 if (qc->subs && qc->subs->events & SUB_RETRY_SEND) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004664 pktns->tx.pto_probe = QUIC_MAX_NB_PTO_DGRAMS;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02004665 tasklet_wakeup(qc->subs->tasklet);
4666 qc->subs->events &= ~SUB_RETRY_SEND;
4667 if (!qc->subs->events)
4668 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004669 }
4670 else {
4671 qc->flags |= QUIC_FL_CONN_RETRANS_NEEDED;
4672 pktns->flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4673 if (pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL]) {
4674 TRACE_STATE("needs to probe Initial packet number space", QUIC_EV_CONN_TXPKT, qc);
4675 if (qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].tx.in_flight) {
4676 qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE].flags |= QUIC_FL_PKTNS_PROBE_NEEDED;
4677 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
4678 }
4679 }
4680 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_HANDSHAKE]) {
4681 TRACE_STATE("needs to probe Handshake packet number space", QUIC_EV_CONN_TXPKT, qc);
4682 }
4683 else if (pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT]) {
4684 TRACE_STATE("needs to probe 01RTT packet number space", QUIC_EV_CONN_TXPKT, qc);
4685 }
4686 }
4687 }
4688 else if (!qc_is_listener(qc) && qc->state <= QUIC_HS_ST_COMPLETE) {
4689 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
4690 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
4691
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004692 if (quic_tls_has_tx_sec(hel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004693 hel->pktns->tx.pto_probe = 1;
Frédéric Lécaillee1a49cf2022-09-16 16:24:47 +02004694 if (quic_tls_has_tx_sec(iel))
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004695 iel->pktns->tx.pto_probe = 1;
4696 }
4697
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004698 tasklet_wakeup(qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004699 qc->path->loss.pto_count++;
4700
4701 out:
4702 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, qc, pktns);
4703
4704 return task;
4705}
4706
4707/* Parse the Retry token from buffer <token> with <end> a pointer to
4708 * one byte past the end of this buffer. This will extract the ODCID
4709 * which will be stored into <odcid>
4710 *
4711 * Returns 0 on success else non-zero.
4712 */
4713static int parse_retry_token(struct quic_conn *qc,
4714 const unsigned char *token, const unsigned char *end,
4715 struct quic_cid *odcid)
4716{
4717 int ret = 0;
4718 uint64_t odcid_len;
4719 uint32_t timestamp;
4720
4721 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
4722
4723 if (!quic_dec_int(&odcid_len, &token, end)) {
4724 TRACE_ERROR("quic_dec_int() error", QUIC_EV_CONN_LPKT, qc);
4725 goto leave;
4726 }
4727
4728 /* RFC 9000 7.2. Negotiating Connection IDs:
4729 * When an Initial packet is sent by a client that has not previously
4730 * received an Initial or Retry packet from the server, the client
4731 * populates the Destination Connection ID field with an unpredictable
4732 * value. This Destination Connection ID MUST be at least 8 bytes in length.
4733 */
4734 if (odcid_len < QUIC_ODCID_MINLEN || odcid_len > QUIC_CID_MAXLEN) {
4735 TRACE_ERROR("wrong ODCID length", QUIC_EV_CONN_LPKT, qc);
4736 goto leave;
4737 }
4738
4739 if (end - token < odcid_len + sizeof timestamp) {
4740 TRACE_ERROR("too long ODCID length", QUIC_EV_CONN_LPKT, qc);
4741 goto leave;
4742 }
4743
4744 timestamp = ntohl(read_u32(token + odcid_len));
4745 if (timestamp + MS_TO_TICKS(QUIC_RETRY_DURATION_MS) <= now_ms) {
4746 TRACE_ERROR("token has expired", QUIC_EV_CONN_LPKT, qc);
4747 goto leave;
4748 }
4749
4750 ret = 1;
4751 memcpy(odcid->data, token, odcid_len);
4752 odcid->len = odcid_len;
4753 leave:
4754 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
4755 return !ret;
4756}
4757
4758/* Allocate a new QUIC connection with <version> as QUIC version. <ipv4>
4759 * boolean is set to 1 for IPv4 connection, 0 for IPv6. <server> is set to 1
4760 * for QUIC servers (or haproxy listeners).
4761 * <dcid> is the destination connection ID, <scid> is the source connection ID,
4762 * <token> the token found to be used for this connection with <token_len> as
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004763 * length. Endpoints addresses are specified via <local_addr> and <peer_addr>.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004764 * Returns the connection if succeeded, NULL if not.
4765 */
4766static struct quic_conn *qc_new_conn(const struct quic_version *qv, int ipv4,
4767 struct quic_cid *dcid, struct quic_cid *scid,
4768 const struct quic_cid *token_odcid,
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004769 struct sockaddr_storage *local_addr,
4770 struct sockaddr_storage *peer_addr,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004771 int server, int token, void *owner)
4772{
4773 int i;
4774 struct quic_conn *qc;
4775 /* Initial CID. */
4776 struct quic_connection_id *icid;
4777 char *buf_area = NULL;
4778 struct listener *l = NULL;
4779 struct quic_cc_algo *cc_algo = NULL;
4780 struct quic_tls_ctx *ictx;
4781 TRACE_ENTER(QUIC_EV_CONN_INIT);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004782 /* TODO replace pool_zalloc by pool_alloc(). This requires special care
4783 * to properly initialized internal quic_conn members to safely use
4784 * quic_conn_release() on alloc failure.
4785 */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004786 qc = pool_zalloc(pool_head_quic_conn);
4787 if (!qc) {
4788 TRACE_ERROR("Could not allocate a new connection", QUIC_EV_CONN_INIT);
4789 goto err;
4790 }
4791
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004792 /* Initialize in priority qc members required for a safe dealloc. */
4793
4794 /* required to use MTLIST_IN_LIST */
4795 MT_LIST_INIT(&qc->accept_list);
4796
4797 LIST_INIT(&qc->rx.pkt_list);
4798
Amaury Denoyelle42448332022-12-12 11:24:05 +01004799 qc_init_fd(qc);
4800
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004801 /* Now proceeds to allocation of qc members. */
4802
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004803 buf_area = pool_alloc(pool_head_quic_conn_rxbuf);
4804 if (!buf_area) {
4805 TRACE_ERROR("Could not allocate a new RX buffer", QUIC_EV_CONN_INIT, qc);
4806 goto err;
4807 }
4808
4809 qc->cids = EB_ROOT;
4810 /* QUIC Server (or listener). */
4811 if (server) {
4812 struct proxy *prx;
4813
4814 l = owner;
4815 prx = l->bind_conf->frontend;
4816 cc_algo = l->bind_conf->quic_cc_algo;
4817
4818 qc->prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe,
4819 &quic_stats_module);
4820 qc->flags |= QUIC_FL_CONN_LISTENER;
4821 qc->state = QUIC_HS_ST_SERVER_INITIAL;
4822 /* Copy the initial DCID with the address. */
4823 qc->odcid.len = dcid->len;
4824 qc->odcid.addrlen = dcid->addrlen;
4825 memcpy(qc->odcid.data, dcid->data, dcid->len + dcid->addrlen);
4826
4827 /* copy the packet SCID to reuse it as DCID for sending */
4828 if (scid->len)
4829 memcpy(qc->dcid.data, scid->data, scid->len);
4830 qc->dcid.len = scid->len;
4831 qc->tx.buf = BUF_NULL;
4832 qc->li = l;
4833 }
4834 /* QUIC Client (outgoing connection to servers) */
4835 else {
4836 qc->state = QUIC_HS_ST_CLIENT_INITIAL;
4837 if (dcid->len)
4838 memcpy(qc->dcid.data, dcid->data, dcid->len);
4839 qc->dcid.len = dcid->len;
4840 }
4841 qc->mux_state = QC_MUX_NULL;
4842 qc->err = quic_err_transport(QC_ERR_NO_ERROR);
4843
4844 icid = new_quic_cid(&qc->cids, qc, 0);
4845 if (!icid) {
4846 TRACE_ERROR("Could not allocate a new connection ID", QUIC_EV_CONN_INIT, qc);
4847 goto err;
4848 }
4849
Amaury Denoyelle40909df2022-10-24 17:08:43 +02004850 if ((global.tune.options & GTUNE_QUIC_SOCK_PER_CONN) &&
4851 is_addr(local_addr)) {
4852 TRACE_USER("Allocate a socket for QUIC connection", QUIC_EV_CONN_INIT, qc);
4853 qc_alloc_fd(qc, local_addr, peer_addr);
4854 }
Amaury Denoyelle40909df2022-10-24 17:08:43 +02004855
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004856 /* insert the allocated CID in the receiver datagram handler tree */
4857 if (server)
4858 ebmb_insert(&quic_dghdlrs[tid].cids, &icid->node, icid->cid.len);
4859
4860 /* Select our SCID which is the first CID with 0 as sequence number. */
4861 qc->scid = icid->cid;
4862
4863 /* Packet number spaces initialization. */
4864 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
4865 quic_pktns_init(&qc->pktns[i]);
4866 /* QUIC encryption level context initialization. */
4867 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
4868 if (!quic_conn_enc_level_init(qc, i)) {
4869 TRACE_ERROR("Could not initialize an encryption level", QUIC_EV_CONN_INIT, qc);
4870 goto err;
4871 }
4872 /* Initialize the packet number space. */
4873 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
4874 }
4875
4876 qc->original_version = qv;
4877 qc->tps_tls_ext = (qc->original_version->num & 0xff000000) == 0xff000000 ?
4878 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS_DRAFT:
4879 TLS_EXTENSION_QUIC_TRANSPORT_PARAMETERS;
4880 /* TX part. */
4881 LIST_INIT(&qc->tx.frms_to_send);
4882 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
4883 qc->tx.wbuf = qc->tx.rbuf = 0;
4884 qc->tx.bytes = 0;
4885 qc->tx.buf = BUF_NULL;
4886 /* RX part. */
4887 qc->rx.bytes = 0;
4888 qc->rx.buf = b_make(buf_area, QUIC_CONN_RX_BUFSZ, 0, 0);
4889 for (i = 0; i < QCS_MAX_TYPES; i++)
4890 qc->rx.strms[i].nb_streams = 0;
4891
4892 qc->nb_pkt_for_cc = 1;
4893 qc->nb_pkt_since_cc = 0;
4894
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004895 if (!quic_tls_ku_init(qc)) {
4896 TRACE_ERROR("Key update initialization failed", QUIC_EV_CONN_INIT, qc);
4897 goto err;
4898 }
4899
4900 /* XXX TO DO: Only one path at this time. */
4901 qc->path = &qc->paths[0];
4902 quic_path_init(qc->path, ipv4, cc_algo ? cc_algo : default_quic_cc_algo, qc);
4903
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004904 qc->streams_by_id = EB_ROOT_UNIQUE;
4905 qc->stream_buf_count = 0;
Amaury Denoyelle97ecc7a2022-09-23 17:15:58 +02004906 memcpy(&qc->local_addr, local_addr, sizeof(qc->local_addr));
4907 memcpy(&qc->peer_addr, peer_addr, sizeof qc->peer_addr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004908
4909 if (server && !qc_lstnr_params_init(qc, &l->bind_conf->quic_params,
4910 icid->stateless_reset_token,
4911 dcid->data, dcid->len,
4912 qc->scid.data, qc->scid.len, token_odcid))
4913 goto err;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02004914
4915 qc->wait_event.tasklet = tasklet_new();
4916 if (!qc->wait_event.tasklet) {
4917 TRACE_ERROR("tasklet_new() failed", QUIC_EV_CONN_TXPKT);
4918 goto err;
4919 }
4920 qc->wait_event.tasklet->process = quic_conn_io_cb;
4921 qc->wait_event.tasklet->context = qc;
4922 qc->wait_event.events = 0;
4923 /* Set tasklet tid based on the SCID selected by us for this
4924 * connection. The upper layer will also be binded on the same thread.
4925 */
Willy Tarreaueed78262022-12-21 09:09:19 +01004926 qc->tid = quic_get_cid_tid(qc->scid.data, &l->rx);
Willy Tarreauf5a0c8a2022-10-13 16:14:11 +02004927 qc->wait_event.tasklet->tid = qc->tid;
Amaury Denoyellebbb1c682022-09-28 15:15:51 +02004928 qc->subs = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004929
4930 if (qc_conn_alloc_ssl_ctx(qc) ||
4931 !quic_conn_init_timer(qc) ||
4932 !quic_conn_init_idle_timer_task(qc))
4933 goto err;
4934
4935 ictx = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
4936 if (!qc_new_isecs(qc, ictx,qc->original_version, dcid->data, dcid->len, 1))
4937 goto err;
4938
4939 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc);
4940
4941 return qc;
4942
4943 err:
4944 pool_free(pool_head_quic_conn_rxbuf, buf_area);
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004945 if (qc) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004946 qc->rx.buf.area = NULL;
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01004947 quic_conn_release(qc);
4948 }
4949 TRACE_LEAVE(QUIC_EV_CONN_INIT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004950 return NULL;
4951}
4952
4953/* Release the quic_conn <qc>. The connection is removed from the CIDs tree.
4954 * The connection tasklet is killed.
4955 *
4956 * This function must only be called by the thread responsible of the quic_conn
4957 * tasklet.
4958 */
4959void quic_conn_release(struct quic_conn *qc)
4960{
4961 int i;
4962 struct ssl_sock_ctx *conn_ctx;
4963 struct eb64_node *node;
4964 struct quic_tls_ctx *app_tls_ctx;
4965 struct quic_rx_packet *pkt, *pktback;
4966
4967 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
4968
4969 /* We must not free the quic-conn if the MUX is still allocated. */
4970 BUG_ON(qc->mux_state == QC_MUX_READY);
4971
Amaury Denoyelle40909df2022-10-24 17:08:43 +02004972 /* Close quic-conn socket fd. */
Amaury Denoyelled3083c92022-12-01 16:20:06 +01004973 qc_release_fd(qc, 0);
Amaury Denoyelle40909df2022-10-24 17:08:43 +02004974
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02004975 /* in the unlikely (but possible) case the connection was just added to
4976 * the accept_list we must delete it from there.
4977 */
4978 MT_LIST_DELETE(&qc->accept_list);
4979
4980 /* free remaining stream descriptors */
4981 node = eb64_first(&qc->streams_by_id);
4982 while (node) {
4983 struct qc_stream_desc *stream;
4984
4985 stream = eb64_entry(node, struct qc_stream_desc, by_id);
4986 node = eb64_next(node);
4987
4988 /* all streams attached to the quic-conn are released, so
4989 * qc_stream_desc_free will liberate the stream instance.
4990 */
4991 BUG_ON(!stream->release);
4992 qc_stream_desc_free(stream, 1);
4993 }
4994
4995 /* Purge Rx packet list. */
4996 list_for_each_entry_safe(pkt, pktback, &qc->rx.pkt_list, qc_rx_pkt_list) {
4997 LIST_DELETE(&pkt->qc_rx_pkt_list);
4998 pool_free(pool_head_quic_rx_packet, pkt);
4999 }
5000
5001 if (qc->idle_timer_task) {
5002 task_destroy(qc->idle_timer_task);
5003 qc->idle_timer_task = NULL;
5004 }
5005
5006 if (qc->timer_task) {
5007 task_destroy(qc->timer_task);
5008 qc->timer_task = NULL;
5009 }
5010
Amaury Denoyelledbf6ad42022-12-12 11:22:42 +01005011 if (qc->wait_event.tasklet)
5012 tasklet_free(qc->wait_event.tasklet);
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005013
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005014 /* remove the connection from receiver cids trees */
5015 ebmb_delete(&qc->odcid_node);
5016 ebmb_delete(&qc->scid_node);
5017 free_quic_conn_cids(qc);
5018
5019 conn_ctx = qc->xprt_ctx;
5020 if (conn_ctx) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005021 SSL_free(conn_ctx->ssl);
5022 pool_free(pool_head_quic_conn_ctx, conn_ctx);
5023 }
5024
5025 quic_tls_ku_free(qc);
5026 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
5027 quic_tls_ctx_secs_free(&qc->els[i].tls_ctx);
5028 quic_conn_enc_level_uninit(qc, &qc->els[i]);
5029 }
5030 quic_tls_ctx_secs_free(&qc->negotiated_ictx);
5031
5032 app_tls_ctx = &qc->els[QUIC_TLS_ENC_LEVEL_APP].tls_ctx;
5033 pool_free(pool_head_quic_tls_secret, app_tls_ctx->rx.secret);
5034 pool_free(pool_head_quic_tls_secret, app_tls_ctx->tx.secret);
5035
5036 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++) {
5037 quic_pktns_tx_pkts_release(&qc->pktns[i], qc);
5038 quic_free_arngs(qc, &qc->pktns[i].rx.arngs);
5039 }
5040
5041 pool_free(pool_head_quic_conn_rxbuf, qc->rx.buf.area);
5042 pool_free(pool_head_quic_conn, qc);
5043 TRACE_PROTO("QUIC conn. freed", QUIC_EV_CONN_FREED, qc);
5044
5045 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
5046}
5047
5048/* Initialize the timer task of <qc> QUIC connection.
5049 * Returns 1 if succeeded, 0 if not.
5050 */
5051static int quic_conn_init_timer(struct quic_conn *qc)
5052{
5053 int ret = 0;
5054 /* Attach this task to the same thread ID used for the connection */
5055 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5056
5057 qc->timer_task = task_new_on(qc->tid);
5058 if (!qc->timer_task) {
5059 TRACE_ERROR("timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5060 goto leave;
5061 }
5062
5063 qc->timer = TICK_ETERNITY;
5064 qc->timer_task->process = qc_process_timer;
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02005065 qc->timer_task->context = qc;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005066
5067 ret = 1;
5068 leave:
5069 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5070 return ret;
5071}
5072
5073/* Rearm the idle timer for <qc> QUIC connection. */
5074static void qc_idle_timer_do_rearm(struct quic_conn *qc)
5075{
5076 unsigned int expire;
5077
5078 expire = QUIC_MAX(3 * quic_pto(qc), qc->max_idle_timeout);
5079 qc->idle_timer_task->expire = tick_add(now_ms, MS_TO_TICKS(expire));
5080}
5081
5082/* Rearm the idle timer for <qc> QUIC connection depending on <read> boolean
5083 * which is set to 1 when receiving a packet , and 0 when sending packet
5084 */
5085static void qc_idle_timer_rearm(struct quic_conn *qc, int read)
5086{
5087 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5088
5089 if (read) {
5090 qc->flags |= QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5091 }
5092 else {
5093 qc->flags &= ~QUIC_FL_CONN_IDLE_TIMER_RESTARTED_AFTER_READ;
5094 }
5095 qc_idle_timer_do_rearm(qc);
5096
5097 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5098}
5099
5100/* The task handling the idle timeout */
5101struct task *qc_idle_timer_task(struct task *t, void *ctx, unsigned int state)
5102{
5103 struct quic_conn *qc = ctx;
5104 struct quic_counters *prx_counters = qc->prx_counters;
5105 unsigned int qc_flags = qc->flags;
5106
5107 TRACE_ENTER(QUIC_EV_CONN_IDLE_TIMER, qc);
5108
5109 /* Notify the MUX before settings QUIC_FL_CONN_EXP_TIMER or the MUX
5110 * might free the quic-conn too early via quic_close().
5111 */
5112 qc_notify_close(qc);
5113
5114 /* If the MUX is still alive, keep the quic-conn. The MUX is
5115 * responsible to call quic_close to release it.
5116 */
5117 qc->flags |= QUIC_FL_CONN_EXP_TIMER;
5118 if (qc->mux_state != QC_MUX_READY)
5119 quic_conn_release(qc);
5120
5121 /* TODO if the quic-conn cannot be freed because of the MUX, we may at
5122 * least clean some parts of it such as the tasklet.
5123 */
5124
5125 if (!(qc_flags & QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED)) {
5126 qc_flags |= QUIC_FL_CONN_HALF_OPEN_CNT_DECREMENTED;
5127 TRACE_DEVEL("dec half open counter", QUIC_EV_CONN_SSLALERT, qc);
5128 HA_ATOMIC_DEC(&prx_counters->half_open_conn);
5129 }
5130
5131 TRACE_LEAVE(QUIC_EV_CONN_IDLE_TIMER, qc);
5132 return NULL;
5133}
5134
5135/* Initialize the idle timeout task for <qc>.
5136 * Returns 1 if succeeded, 0 if not.
5137 */
5138static int quic_conn_init_idle_timer_task(struct quic_conn *qc)
5139{
5140 int ret = 0;
5141
5142 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5143
5144 qc->idle_timer_task = task_new_here();
5145 if (!qc->idle_timer_task) {
5146 TRACE_ERROR("Idle timer task allocation failed", QUIC_EV_CONN_NEW, qc);
5147 goto leave;
5148 }
5149
5150 qc->idle_timer_task->process = qc_idle_timer_task;
5151 qc->idle_timer_task->context = qc;
5152 qc_idle_timer_rearm(qc, 1);
5153 task_queue(qc->idle_timer_task);
5154
5155 ret = 1;
5156 leave:
5157 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5158 return ret;
5159}
5160
5161/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
5162 * past one byte of this buffer.
5163 */
5164static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
5165 struct quic_rx_packet *pkt)
5166{
5167 int ret = 0;
5168 unsigned char dcid_len, scid_len;
5169
5170 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5171
5172 if (end == *buf) {
5173 TRACE_ERROR("buffer data consumed", QUIC_EV_CONN_RXPKT);
5174 goto leave;
5175 }
5176
5177 /* Destination Connection ID Length */
5178 dcid_len = *(*buf)++;
5179 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
5180 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1) {
5181 TRACE_ERROR("too long DCID", QUIC_EV_CONN_RXPKT);
5182 goto leave;
5183 }
5184
5185 if (dcid_len) {
5186 /* Check that the length of this received DCID matches the CID lengths
5187 * of our implementation for non Initials packets only.
5188 */
5189 if (pkt->type != QUIC_PACKET_TYPE_INITIAL &&
5190 pkt->type != QUIC_PACKET_TYPE_0RTT &&
5191 dcid_len != QUIC_HAP_CID_LEN) {
5192 TRACE_ERROR("wrong DCID length", QUIC_EV_CONN_RXPKT);
5193 goto leave;
5194 }
5195
5196 memcpy(pkt->dcid.data, *buf, dcid_len);
5197 }
5198
5199 pkt->dcid.len = dcid_len;
5200 *buf += dcid_len;
5201
5202 /* Source Connection ID Length */
5203 scid_len = *(*buf)++;
5204 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len) {
5205 TRACE_ERROR("too long SCID", QUIC_EV_CONN_RXPKT);
5206 goto leave;
5207 }
5208
5209 if (scid_len)
5210 memcpy(pkt->scid.data, *buf, scid_len);
5211 pkt->scid.len = scid_len;
5212 *buf += scid_len;
5213
5214 ret = 1;
5215 leave:
5216 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5217 return ret;
5218}
5219
5220/* Insert <pkt> RX packet in its <qel> RX packets tree */
5221static void qc_pkt_insert(struct quic_conn *qc,
5222 struct quic_rx_packet *pkt, struct quic_enc_level *qel)
5223{
5224 TRACE_ENTER(QUIC_EV_CONN_RXPKT, qc);
5225
5226 pkt->pn_node.key = pkt->pn;
5227 quic_rx_packet_refinc(pkt);
5228 eb64_insert(&qel->rx.pkts, &pkt->pn_node);
5229
5230 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5231}
5232
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005233/* Try to remove the header protection of <pkt> QUIC packet with <beg> the
5234 * address of the packet first byte, using the keys from encryption level <el>.
5235 *
5236 * If header protection has been successfully removed, packet data are copied
5237 * into <qc> Rx buffer. If <el> secrets are not yet available, the copy is also
5238 * proceeded, and the packet is inserted into <qc> protected packets tree. In
5239 * both cases, packet can now be considered handled by the <qc> connection.
5240 *
5241 * If header protection cannot be removed due to <el> secrets already
5242 * discarded, no operation is conducted.
5243 *
5244 * Returns 1 on success : packet data is now handled by the connection. On
5245 * error 0 is returned : packet should be dropped by the caller.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005246 */
5247static inline int qc_try_rm_hp(struct quic_conn *qc,
5248 struct quic_rx_packet *pkt,
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005249 unsigned char *beg,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005250 struct quic_enc_level **el)
5251{
5252 int ret = 0;
5253 unsigned char *pn = NULL; /* Packet number field */
5254 enum quic_tls_enc_level tel;
5255 struct quic_enc_level *qel;
5256 /* Only for traces. */
5257 struct quic_rx_packet *qpkt_trace;
5258
5259 qpkt_trace = NULL;
5260 TRACE_ENTER(QUIC_EV_CONN_TRMHP, qc);
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005261 BUG_ON(!pkt->pn_offset);
5262
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005263 /* The packet number is here. This is also the start minus
5264 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
5265 * protection.
5266 */
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005267 pn = beg + pkt->pn_offset;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005268
5269 tel = quic_packet_type_enc_level(pkt->type);
5270 qel = &qc->els[tel];
5271
5272 if (qc_qel_may_rm_hp(qc, qel)) {
5273 /* Note that the following function enables us to unprotect the packet
5274 * number and its length subsequently used to decrypt the entire
5275 * packets.
5276 */
5277 if (!qc_do_rm_hp(qc, pkt, &qel->tls_ctx,
5278 qel->pktns->rx.largest_pn, pn, beg)) {
5279 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, qc);
5280 goto out;
5281 }
5282
Amaury Denoyelle845169d2022-10-17 18:05:26 +02005283 /* The AAD includes the packet number field. */
5284 pkt->aad_len = pkt->pn_offset + pkt->pnl;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005285 if (pkt->len - pkt->aad_len < QUIC_TLS_TAG_LEN) {
5286 TRACE_PROTO("Too short packet", QUIC_EV_CONN_TRMHP, qc);
5287 goto out;
5288 }
5289
5290 qpkt_trace = pkt;
5291 }
5292 else {
5293 if (qel->tls_ctx.flags & QUIC_FL_TLS_SECRETS_DCD) {
5294 /* If the packet number space has been discarded, this packet
5295 * will be not parsed.
5296 */
5297 TRACE_PROTO("Discarded pktns", QUIC_EV_CONN_TRMHP, qc, pkt);
5298 goto out;
5299 }
5300
5301 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, qc, pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005302 LIST_APPEND(&qel->rx.pqpkts, &pkt->list);
5303 quic_rx_packet_refinc(pkt);
5304 }
5305
5306 *el = qel;
5307 /* No reference counter incrementation here!!! */
5308 LIST_APPEND(&qc->rx.pkt_list, &pkt->qc_rx_pkt_list);
5309 memcpy(b_tail(&qc->rx.buf), beg, pkt->len);
5310 pkt->data = (unsigned char *)b_tail(&qc->rx.buf);
5311 b_add(&qc->rx.buf, pkt->len);
5312
5313 ret = 1;
5314 out:
5315 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, qc, qpkt_trace);
5316 return ret;
5317}
5318
5319/* Parse the header form from <byte0> first byte of <pkt> packet to set its type.
5320 * Also set <*long_header> to 1 if this form is long, 0 if not and the version
5321 * of this packet into <*version>.
5322 */
5323static inline int qc_parse_hd_form(struct quic_rx_packet *pkt,
5324 unsigned char **buf, const unsigned char *end,
5325 int *long_header, uint32_t *version)
5326{
5327 int ret = 0;
5328 const unsigned char byte0 = **buf;
5329
5330 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5331
5332 (*buf)++;
5333 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
5334 unsigned char type =
5335 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
5336
5337 *long_header = 1;
5338 /* Version */
5339 if (!quic_read_uint32(version, (const unsigned char **)buf, end)) {
5340 TRACE_ERROR("could not read the packet version", QUIC_EV_CONN_RXPKT);
5341 goto out;
5342 }
5343
5344 if (*version != QUIC_PROTOCOL_VERSION_2_DRAFT) {
5345 pkt->type = type;
5346 }
5347 else {
5348 switch (type) {
5349 case 0:
5350 pkt->type = QUIC_PACKET_TYPE_RETRY;
5351 break;
5352 case 1:
5353 pkt->type = QUIC_PACKET_TYPE_INITIAL;
5354 break;
5355 case 2:
5356 pkt->type = QUIC_PACKET_TYPE_0RTT;
5357 break;
5358 case 3:
5359 pkt->type = QUIC_PACKET_TYPE_HANDSHAKE;
5360 break;
5361 }
5362 }
5363 }
5364 else {
5365 pkt->type = QUIC_PACKET_TYPE_SHORT;
5366 *long_header = 0;
5367 }
5368
5369 ret = 1;
5370 out:
5371 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
5372 return ret;
5373}
5374
5375/* Return the QUIC version (quic_version struct) with <version> as version number
5376 * if supported or NULL if not.
5377 */
5378static inline const struct quic_version *qc_supported_version(uint32_t version)
5379{
5380 int i;
5381
5382 for (i = 0; i < quic_versions_nb; i++)
5383 if (quic_versions[i].num == version)
5384 return &quic_versions[i];
5385
5386 return NULL;
5387}
5388
5389/*
5390 * Send a Version Negotiation packet on response to <pkt> on socket <fd> to
5391 * address <addr>.
5392 * Implementation of RFC9000 6. Version Negotiation
5393 *
5394 * TODO implement a rate-limiting sending of Version Negotiation packets
5395 *
5396 * Returns 0 on success else non-zero
5397 */
5398static int send_version_negotiation(int fd, struct sockaddr_storage *addr,
5399 struct quic_rx_packet *pkt)
5400{
5401 char buf[256];
5402 int ret = 0, i = 0, j;
5403 uint32_t version;
5404 const socklen_t addrlen = get_addr_len(addr);
5405
5406 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5407 /*
5408 * header form
5409 * long header, fixed bit to 0 for Version Negotiation
5410 */
5411 /* TODO: RAND_bytes() should be replaced? */
5412 if (RAND_bytes((unsigned char *)buf, 1) != 1) {
5413 TRACE_ERROR("RAND_bytes() error", QUIC_EV_CONN_TXPKT);
5414 goto out;
5415 }
5416
5417 buf[i++] |= '\x80';
5418 /* null version for Version Negotiation */
5419 buf[i++] = '\x00';
5420 buf[i++] = '\x00';
5421 buf[i++] = '\x00';
5422 buf[i++] = '\x00';
5423
5424 /* source connection id */
5425 buf[i++] = pkt->scid.len;
5426 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5427 i += pkt->scid.len;
5428
5429 /* destination connection id */
5430 buf[i++] = pkt->dcid.len;
5431 memcpy(&buf[i], pkt->dcid.data, pkt->dcid.len);
5432 i += pkt->dcid.len;
5433
5434 /* supported version */
5435 for (j = 0; j < quic_versions_nb; j++) {
5436 version = htonl(quic_versions[j].num);
5437 memcpy(&buf[i], &version, sizeof(version));
5438 i += sizeof(version);
5439 }
5440
5441 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0)
5442 goto out;
5443
5444 ret = 1;
5445 out:
5446 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5447 return !ret;
5448}
5449
5450/* Send a stateless reset packet depending on <pkt> RX packet information
5451 * from <fd> UDP socket to <dst>
5452 * Return 1 if succeeded, 0 if not.
5453 */
5454static int send_stateless_reset(struct listener *l, struct sockaddr_storage *dstaddr,
5455 struct quic_rx_packet *rxpkt)
5456{
5457 int ret = 0, pktlen, rndlen;
5458 unsigned char pkt[64];
5459 const socklen_t addrlen = get_addr_len(dstaddr);
5460 struct proxy *prx;
5461 struct quic_counters *prx_counters;
5462
5463 TRACE_ENTER(QUIC_EV_STATELESS_RST);
5464
5465 prx = l->bind_conf->frontend;
5466 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5467 /* 10.3 Stateless Reset (https://www.rfc-editor.org/rfc/rfc9000.html#section-10.3)
5468 * The resulting minimum size of 21 bytes does not guarantee that a Stateless
5469 * Reset is difficult to distinguish from other packets if the recipient requires
5470 * the use of a connection ID. To achieve that end, the endpoint SHOULD ensure
5471 * that all packets it sends are at least 22 bytes longer than the minimum
5472 * connection ID length that it requests the peer to include in its packets,
5473 * adding PADDING frames as necessary. This ensures that any Stateless Reset
5474 * sent by the peer is indistinguishable from a valid packet sent to the endpoint.
5475 * An endpoint that sends a Stateless Reset in response to a packet that is
5476 * 43 bytes or shorter SHOULD send a Stateless Reset that is one byte shorter
5477 * than the packet it responds to.
5478 */
5479
5480 /* Note that we build at most a 42 bytes QUIC packet to mimic a short packet */
5481 pktlen = rxpkt->len <= 43 ? rxpkt->len - 1 : 0;
5482 pktlen = QUIC_MAX(QUIC_STATELESS_RESET_PACKET_MINLEN, pktlen);
5483 rndlen = pktlen - QUIC_STATELESS_RESET_TOKEN_LEN;
5484
5485 /* Put a header of random bytes */
5486 /* TODO: RAND_bytes() should be replaced */
5487 if (RAND_bytes(pkt, rndlen) != 1) {
5488 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_STATELESS_RST);
5489 goto leave;
5490 }
5491
5492 /* Clear the most significant bit, and set the second one */
5493 *pkt = (*pkt & ~0x80) | 0x40;
5494 if (!quic_stateless_reset_token_cpy(NULL, pkt + rndlen, QUIC_STATELESS_RESET_TOKEN_LEN,
5495 rxpkt->dcid.data, rxpkt->dcid.len))
5496 goto leave;
5497
5498 if (sendto(l->rx.fd, pkt, pktlen, 0, (struct sockaddr *)dstaddr, addrlen) < 0)
5499 goto leave;
5500
5501 ret = 1;
5502 HA_ATOMIC_INC(&prx_counters->stateless_reset_sent);
5503 TRACE_PROTO("stateless reset sent", QUIC_EV_STATELESS_RST, NULL, &rxpkt->dcid);
5504 leave:
5505 TRACE_LEAVE(QUIC_EV_STATELESS_RST);
5506 return ret;
5507}
5508
5509/* QUIC server only function.
5510 * Add AAD to <add> buffer from <cid> connection ID and <addr> socket address.
5511 * This is the responsibility of the caller to check <aad> size is big enough
5512 * to contain these data.
5513 * Return the number of bytes copied to <aad>.
5514 */
5515static int quic_generate_retry_token_aad(unsigned char *aad,
5516 uint32_t version,
5517 const struct quic_cid *cid,
5518 const struct sockaddr_storage *addr)
5519{
5520 unsigned char *p;
5521
5522 p = aad;
5523 memcpy(p, &version, sizeof version);
5524 p += sizeof version;
5525 p += quic_saddr_cpy(p, addr);
5526 memcpy(p, cid->data, cid->len);
5527 p += cid->len;
5528
5529 return p - aad;
5530}
5531
5532/* QUIC server only function.
5533 * Generate the token to be used in Retry packets. The token is written to
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05005534 * <buf> with <len> as length. <odcid> is the original destination connection
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005535 * ID and <dcid> is our side destination connection ID (or client source
5536 * connection ID).
5537 * Returns the length of the encoded token or 0 on error.
5538 */
5539static int quic_generate_retry_token(unsigned char *buf, size_t len,
5540 const uint32_t version,
5541 const struct quic_cid *odcid,
5542 const struct quic_cid *dcid,
5543 struct sockaddr_storage *addr)
5544{
5545 int ret = 0;
5546 unsigned char *p;
5547 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005548 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005549 size_t aadlen;
5550 unsigned char salt[QUIC_RETRY_TOKEN_SALTLEN];
5551 unsigned char key[QUIC_TLS_KEY_LEN];
5552 unsigned char iv[QUIC_TLS_IV_LEN];
5553 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5554 size_t seclen = strlen(global.cluster_secret);
5555 EVP_CIPHER_CTX *ctx = NULL;
5556 const EVP_CIPHER *aead = EVP_aes_128_gcm();
5557 uint32_t timestamp = now_ms;
5558
5559 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5560
5561 /* We copy the odcid into the token, prefixed by its one byte
5562 * length, the format token byte. It is followed by an AEAD TAG, and finally
5563 * the random bytes used to derive the secret to encrypt the token.
5564 */
5565 if (1 + dcid->len + 1 + QUIC_TLS_TAG_LEN + sizeof salt > len)
5566 goto err;
5567
5568 aadlen = quic_generate_retry_token_aad(aad, version, dcid, addr);
5569 /* TODO: RAND_bytes() should be replaced */
5570 if (RAND_bytes(salt, sizeof salt) != 1) {
5571 TRACE_ERROR("RAND_bytes()", QUIC_EV_CONN_TXPKT);
5572 goto err;
5573 }
5574
5575 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5576 salt, sizeof salt, sec, seclen)) {
5577 TRACE_ERROR("quic_tls_derive_retry_token_secret() failed", QUIC_EV_CONN_TXPKT);
5578 goto err;
5579 }
5580
5581 if (!quic_tls_tx_ctx_init(&ctx, aead, key)) {
5582 TRACE_ERROR("quic_tls_tx_ctx_init() failed", QUIC_EV_CONN_TXPKT);
5583 goto err;
5584 }
5585
5586 /* Token build */
5587 p = buf;
5588 *p++ = QUIC_TOKEN_FMT_RETRY,
5589 *p++ = odcid->len;
5590 memcpy(p, odcid->data, odcid->len);
5591 p += odcid->len;
5592 write_u32(p, htonl(timestamp));
5593 p += sizeof timestamp;
5594
5595 /* Do not encrypt the QUIC_TOKEN_FMT_RETRY byte */
5596 if (!quic_tls_encrypt(buf + 1, p - buf - 1, aad, aadlen, ctx, aead, key, iv)) {
5597 TRACE_ERROR("quic_tls_encrypt() failed", QUIC_EV_CONN_TXPKT);
5598 goto err;
5599 }
5600
5601 p += QUIC_TLS_TAG_LEN;
5602 memcpy(p, salt, sizeof salt);
5603 p += sizeof salt;
5604 EVP_CIPHER_CTX_free(ctx);
5605
5606 ret = p - buf;
5607 leave:
5608 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5609 return ret;
5610
5611 err:
5612 if (ctx)
5613 EVP_CIPHER_CTX_free(ctx);
5614 goto leave;
5615}
5616
5617/* QUIC server only function.
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005618 *
5619 * Check the validity of the Retry token from Initial packet <pkt>. <dgram> is
5620 * the UDP datagram containing <pkt> and <l> is the listener instance on which
5621 * it was received. If the token is valid, the ODCID of <qc> QUIC connection
5622 * will be put into <odcid>. <qc> is used to retrieve the QUIC version needed
5623 * to validate the token but it can be NULL : in this case the version will be
5624 * retrieved from the packet.
5625 *
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005626 * Return 1 if succeeded, 0 if not.
5627 */
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005628
5629static int quic_retry_token_check(struct quic_rx_packet *pkt,
5630 struct quic_dgram *dgram,
5631 struct listener *l,
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005632 struct quic_conn *qc,
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005633 struct quic_cid *odcid)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005634{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005635 struct proxy *prx;
5636 struct quic_counters *prx_counters;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005637 int ret = 0;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005638 unsigned char *token = pkt->token;
5639 const uint64_t tokenlen = pkt->token_len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005640 unsigned char buf[128];
5641 unsigned char aad[sizeof(uint32_t) + sizeof(in_port_t) +
Amaury Denoyelle6c940562022-10-18 11:05:02 +02005642 sizeof(struct in6_addr) + QUIC_CID_MAXLEN];
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005643 size_t aadlen;
5644 const unsigned char *salt;
5645 unsigned char key[QUIC_TLS_KEY_LEN];
5646 unsigned char iv[QUIC_TLS_IV_LEN];
5647 const unsigned char *sec = (const unsigned char *)global.cluster_secret;
5648 size_t seclen = strlen(global.cluster_secret);
5649 EVP_CIPHER_CTX *ctx = NULL;
5650 const EVP_CIPHER *aead = EVP_aes_128_gcm();
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005651 const struct quic_version *qv = qc ? qc->original_version :
5652 pkt->version;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005653
5654 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
5655
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005656 /* The caller must ensure this. */
5657 BUG_ON(!global.cluster_secret || !pkt->token_len);
5658
5659 prx = l->bind_conf->frontend;
5660 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
5661
5662 if (*pkt->token != QUIC_TOKEN_FMT_RETRY) {
5663 /* TODO: New token check */
5664 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
5665 goto leave;
5666 }
5667
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005668 if (sizeof buf < tokenlen) {
5669 TRACE_ERROR("too short buffer", QUIC_EV_CONN_LPKT, qc);
5670 goto err;
5671 }
5672
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005673 aadlen = quic_generate_retry_token_aad(aad, qv->num, &pkt->scid, &dgram->saddr);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005674 salt = token + tokenlen - QUIC_RETRY_TOKEN_SALTLEN;
5675 if (!quic_tls_derive_retry_token_secret(EVP_sha256(), key, sizeof key, iv, sizeof iv,
5676 salt, QUIC_RETRY_TOKEN_SALTLEN, sec, seclen)) {
5677 TRACE_ERROR("Could not derive retry secret", QUIC_EV_CONN_LPKT, qc);
5678 goto err;
5679 }
5680
5681 if (!quic_tls_rx_ctx_init(&ctx, aead, key)) {
5682 TRACE_ERROR("quic_tls_rx_ctx_init() failed", QUIC_EV_CONN_LPKT, qc);
5683 goto err;
5684 }
5685
5686 /* Do not decrypt the QUIC_TOKEN_FMT_RETRY byte */
5687 if (!quic_tls_decrypt2(buf, token + 1, tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, aad, aadlen,
5688 ctx, aead, key, iv)) {
5689 TRACE_ERROR("Could not decrypt retry token", QUIC_EV_CONN_LPKT, qc);
5690 goto err;
5691 }
5692
5693 if (parse_retry_token(qc, buf, buf + tokenlen - QUIC_RETRY_TOKEN_SALTLEN - 1, odcid)) {
5694 TRACE_ERROR("Error during Initial token parsing", QUIC_EV_CONN_LPKT, qc);
5695 goto err;
5696 }
5697
5698 EVP_CIPHER_CTX_free(ctx);
5699
5700 ret = 1;
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005701 HA_ATOMIC_INC(&prx_counters->retry_validated);
5702
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005703 leave:
5704 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
5705 return ret;
5706
5707 err:
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02005708 HA_ATOMIC_INC(&prx_counters->retry_error);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005709 if (ctx)
5710 EVP_CIPHER_CTX_free(ctx);
5711 goto leave;
5712}
5713
5714/* Generate a Retry packet and send it on <fd> socket to <addr> in response to
5715 * the Initial <pkt> packet.
5716 *
5717 * Returns 0 on success else non-zero.
5718 */
5719static int send_retry(int fd, struct sockaddr_storage *addr,
5720 struct quic_rx_packet *pkt, const struct quic_version *qv)
5721{
5722 int ret = 0;
5723 unsigned char buf[128];
5724 int i = 0, token_len;
5725 const socklen_t addrlen = get_addr_len(addr);
5726 struct quic_cid scid;
5727
5728 TRACE_ENTER(QUIC_EV_CONN_TXPKT);
5729
5730 /* long header + fixed bit + packet type QUIC_PACKET_TYPE_RETRY */
5731 buf[i++] = (QUIC_PACKET_LONG_HEADER_BIT | QUIC_PACKET_FIXED_BIT) |
5732 (quic_pkt_type(QUIC_PACKET_TYPE_RETRY, qv->num) << QUIC_PACKET_TYPE_SHIFT);
5733 /* version */
5734 buf[i++] = *((unsigned char *)&qv->num + 3);
5735 buf[i++] = *((unsigned char *)&qv->num + 2);
5736 buf[i++] = *((unsigned char *)&qv->num + 1);
5737 buf[i++] = *(unsigned char *)&qv->num;
5738
5739 /* Use the SCID from <pkt> for Retry DCID. */
5740 buf[i++] = pkt->scid.len;
5741 memcpy(&buf[i], pkt->scid.data, pkt->scid.len);
5742 i += pkt->scid.len;
5743
5744 /* Generate a new CID to be used as SCID for the Retry packet. */
5745 scid.len = QUIC_HAP_CID_LEN;
5746 /* TODO: RAND_bytes() should be replaced */
5747 if (RAND_bytes(scid.data, scid.len) != 1) {
5748 TRACE_ERROR("RAND_bytes() failed", QUIC_EV_CONN_TXPKT);
5749 goto out;
5750 }
5751
5752 buf[i++] = scid.len;
5753 memcpy(&buf[i], scid.data, scid.len);
5754 i += scid.len;
5755
5756 /* token */
5757 if (!(token_len = quic_generate_retry_token(&buf[i], sizeof(buf) - i, qv->num,
5758 &pkt->dcid, &pkt->scid, addr))) {
5759 TRACE_ERROR("quic_generate_retry_token() failed", QUIC_EV_CONN_TXPKT);
5760 goto out;
5761 }
5762
5763 i += token_len;
5764
5765 /* token integrity tag */
5766 if ((&buf[i] - buf < QUIC_TLS_TAG_LEN) ||
5767 !quic_tls_generate_retry_integrity_tag(pkt->dcid.data,
5768 pkt->dcid.len, buf, i, qv)) {
5769 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
5770 goto out;
5771 }
5772
5773 i += QUIC_TLS_TAG_LEN;
5774
5775 if (sendto(fd, buf, i, 0, (struct sockaddr *)addr, addrlen) < 0) {
5776 TRACE_ERROR("quic_tls_generate_retry_integrity_tag() failed", QUIC_EV_CONN_TXPKT);
5777 goto out;
5778 }
5779
5780 ret = 1;
5781 out:
5782 TRACE_LEAVE(QUIC_EV_CONN_TXPKT);
5783 return !ret;
5784}
5785
5786/* Retrieve a quic_conn instance from the <pkt> DCID field. If the packet is of
5787 * type INITIAL, the ODCID tree is first used. In this case, <saddr> is
5788 * concatenated to the <pkt> DCID field.
5789 *
5790 * Returns the instance or NULL if not found.
5791 */
5792static struct quic_conn *retrieve_qc_conn_from_cid(struct quic_rx_packet *pkt,
5793 struct listener *l,
5794 struct sockaddr_storage *saddr)
5795{
5796 struct quic_conn *qc = NULL;
5797 struct ebmb_node *node;
5798 struct quic_connection_id *id;
5799 /* set if the quic_conn is found in the second DCID tree */
5800
5801 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
5802
5803 /* Look first into ODCIDs tree for INITIAL/0-RTT packets. */
5804 if (pkt->type == QUIC_PACKET_TYPE_INITIAL ||
5805 pkt->type == QUIC_PACKET_TYPE_0RTT) {
5806 /* DCIDs of first packets coming from multiple clients may have
5807 * the same values. Let's distinguish them by concatenating the
5808 * socket addresses.
5809 */
5810 quic_cid_saddr_cat(&pkt->dcid, saddr);
5811 node = ebmb_lookup(&quic_dghdlrs[tid].odcids, pkt->dcid.data,
5812 pkt->dcid.len + pkt->dcid.addrlen);
5813 if (node) {
5814 qc = ebmb_entry(node, struct quic_conn, odcid_node);
5815 goto end;
5816 }
5817 }
5818
5819 /* Look into DCIDs tree for non-INITIAL/0-RTT packets. This may be used
5820 * also for INITIAL/0-RTT non-first packets with the final DCID in
5821 * used.
5822 */
5823 node = ebmb_lookup(&quic_dghdlrs[tid].cids, pkt->dcid.data, pkt->dcid.len);
5824 if (!node)
5825 goto end;
5826
5827 id = ebmb_entry(node, struct quic_connection_id, node);
5828 qc = id->qc;
5829
5830 /* If found in DCIDs tree, remove the quic_conn from the ODCIDs tree.
5831 * If already done, this is a noop.
5832 */
5833 if (qc)
5834 ebmb_delete(&qc->odcid_node);
5835
5836 end:
5837 TRACE_LEAVE(QUIC_EV_CONN_RXPKT, qc);
5838 return qc;
5839}
5840
5841/* Try to allocate the <*ssl> SSL session object for <qc> QUIC connection
5842 * with <ssl_ctx> as SSL context inherited settings. Also set the transport
5843 * parameters of this session.
5844 * This is the responsibility of the caller to check the validity of all the
5845 * pointers passed as parameter to this function.
5846 * Return 0 if succeeded, -1 if not. If failed, sets the ->err_code member of <qc->conn> to
5847 * CO_ER_SSL_NO_MEM.
5848 */
5849static int qc_ssl_sess_init(struct quic_conn *qc, SSL_CTX *ssl_ctx, SSL **ssl,
5850 unsigned char *params, size_t params_len)
5851{
5852 int retry, ret = -1;
5853
5854 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5855
5856 retry = 1;
5857 retry:
5858 *ssl = SSL_new(ssl_ctx);
5859 if (!*ssl) {
5860 if (!retry--)
5861 goto err;
5862
5863 pool_gc(NULL);
5864 goto retry;
5865 }
5866
5867 if (!SSL_set_quic_method(*ssl, &ha_quic_method) ||
5868 !SSL_set_ex_data(*ssl, ssl_qc_app_data_index, qc)) {
5869 SSL_free(*ssl);
5870 *ssl = NULL;
5871 if (!retry--)
5872 goto err;
5873
5874 pool_gc(NULL);
5875 goto retry;
5876 }
5877
5878 ret = 0;
5879 leave:
5880 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5881 return ret;
5882
5883 err:
5884 qc->conn->err_code = CO_ER_SSL_NO_MEM;
5885 goto leave;
5886}
5887
5888/* Finalize <qc> QUIC connection:
5889 * - initialize the Initial QUIC TLS context for negotiated version,
5890 * - derive the secrets for this context,
5891 * - encode the transport parameters to be sent,
5892 * - set them into the TLS stack,
5893 * - initialize ->max_ack_delay and max_idle_timeout,
5894 *
5895 * MUST be called after having received the remote transport parameters.
5896 * Return 1 if succeeded, 0 if not.
5897 */
5898int qc_conn_finalize(struct quic_conn *qc, int server)
5899{
5900 int ret = 0;
5901 struct quic_transport_params *tx_tp = &qc->tx.params;
5902 struct quic_transport_params *rx_tp = &qc->rx.params;
5903 const struct quic_version *ver;
5904
5905 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5906
5907 if (tx_tp->version_information.negotiated_version &&
5908 tx_tp->version_information.negotiated_version != qc->original_version) {
5909 qc->negotiated_version =
5910 qc->tx.params.version_information.negotiated_version;
5911 if (!qc_new_isecs(qc, &qc->negotiated_ictx, qc->negotiated_version,
5912 qc->odcid.data, qc->odcid.len, !server))
5913 goto out;
5914
5915 ver = qc->negotiated_version;
5916 }
5917 else {
5918 ver = qc->original_version;
5919 }
5920
5921 qc->enc_params_len =
5922 quic_transport_params_encode(qc->enc_params,
5923 qc->enc_params + sizeof qc->enc_params,
5924 &qc->rx.params, ver, 1);
5925 if (!qc->enc_params_len) {
5926 TRACE_ERROR("quic_transport_params_encode() failed", QUIC_EV_CONN_TXPKT);
5927 goto out;
5928 }
5929
5930 if (!SSL_set_quic_transport_params(qc->xprt_ctx->ssl, qc->enc_params, qc->enc_params_len)) {
5931 TRACE_ERROR("SSL_set_quic_transport_params() failed", QUIC_EV_CONN_TXPKT);
5932 goto out;
5933 }
5934
5935 if (tx_tp->max_ack_delay)
5936 qc->max_ack_delay = tx_tp->max_ack_delay;
5937
5938 if (tx_tp->max_idle_timeout && rx_tp->max_idle_timeout)
5939 qc->max_idle_timeout =
5940 QUIC_MIN(tx_tp->max_idle_timeout, rx_tp->max_idle_timeout);
5941 else
5942 qc->max_idle_timeout =
5943 QUIC_MAX(tx_tp->max_idle_timeout, rx_tp->max_idle_timeout);
5944
5945 TRACE_PROTO("\nTX(remote) transp. params.", QUIC_EV_TRANSP_PARAMS, qc, tx_tp);
5946
5947 ret = 1;
5948 out:
5949 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5950 return ret;
5951}
5952
5953/* Allocate the ssl_sock_ctx from connection <qc>. This creates the tasklet
5954 * used to process <qc> received packets. The allocated context is stored in
5955 * <qc.xprt_ctx>.
5956 *
5957 * Returns 0 on success else non-zero.
5958 */
5959static int qc_conn_alloc_ssl_ctx(struct quic_conn *qc)
5960{
5961 int ret = 0;
5962 struct bind_conf *bc = qc->li->bind_conf;
5963 struct ssl_sock_ctx *ctx = NULL;
5964
5965 TRACE_ENTER(QUIC_EV_CONN_NEW, qc);
5966
5967 ctx = pool_zalloc(pool_head_quic_conn_ctx);
5968 if (!ctx) {
5969 TRACE_ERROR("SSL context allocation failed", QUIC_EV_CONN_TXPKT);
5970 goto err;
5971 }
5972
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005973 ctx->subs = NULL;
5974 ctx->xprt_ctx = NULL;
5975 ctx->qc = qc;
5976
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02005977 if (qc_is_listener(qc)) {
5978 if (qc_ssl_sess_init(qc, bc->initial_ctx, &ctx->ssl,
5979 qc->enc_params, qc->enc_params_len) == -1) {
5980 goto err;
5981 }
5982#if (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
5983 /* Enabling 0-RTT */
5984 if (bc->ssl_conf.early_data)
5985 SSL_set_quic_early_data_enabled(ctx->ssl, 1);
5986#endif
5987
5988 SSL_set_accept_state(ctx->ssl);
5989 }
5990
5991 ctx->xprt = xprt_get(XPRT_QUIC);
5992
5993 /* Store the allocated context in <qc>. */
5994 qc->xprt_ctx = ctx;
5995
5996 ret = 1;
5997 leave:
5998 TRACE_LEAVE(QUIC_EV_CONN_NEW, qc);
5999 return !ret;
6000
6001 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006002 pool_free(pool_head_quic_conn_ctx, ctx);
6003 goto leave;
6004}
6005
6006/* Check that all the bytes between <buf> included and <end> address
6007 * excluded are null. This is the responsibility of the caller to
6008 * check that there is at least one byte between <buf> end <end>.
6009 * Return 1 if this all the bytes are null, 0 if not.
6010 */
6011static inline int quic_padding_check(const unsigned char *buf,
6012 const unsigned char *end)
6013{
6014 while (buf < end && !*buf)
6015 buf++;
6016
6017 return buf == end;
6018}
6019
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006020/* Find the associated connection to the packet <pkt> or create a new one if
6021 * this is an Initial packet. <dgram> is the datagram containing the packet and
6022 * <l> is the listener instance on which it was received.
6023 *
6024 * Returns the quic-conn instance or NULL.
6025 */
6026static struct quic_conn *quic_rx_pkt_retrieve_conn(struct quic_rx_packet *pkt,
6027 struct quic_dgram *dgram,
6028 struct listener *l)
6029{
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006030 struct quic_cid token_odcid = { .len = 0 };
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006031 struct quic_conn *qc = NULL;
6032 struct proxy *prx;
6033 struct quic_counters *prx_counters;
6034
6035 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6036
6037 prx = l->bind_conf->frontend;
6038 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6039
6040 qc = retrieve_qc_conn_from_cid(pkt, l, &dgram->saddr);
6041
6042 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6043 BUG_ON(!pkt->version); /* This must not happen. */
6044
6045 if (global.cluster_secret && pkt->token_len) {
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006046 if (!quic_retry_token_check(pkt, dgram, l, qc, &token_odcid))
6047 goto err;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006048 }
6049
6050 if (!qc) {
6051 int ipv4;
6052
6053 if (global.cluster_secret && !pkt->token_len && !(l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) &&
6054 HA_ATOMIC_LOAD(&prx_counters->half_open_conn) >= global.tune.quic_retry_threshold) {
6055 TRACE_PROTO("Initial without token, sending retry",
6056 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6057 if (send_retry(l->rx.fd, &dgram->saddr, pkt, pkt->version)) {
6058 TRACE_ERROR("Error during Retry generation",
6059 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6060 goto out;
6061 }
6062
6063 HA_ATOMIC_INC(&prx_counters->retry_sent);
6064 goto out;
6065 }
6066
6067 /* RFC 9000 7.2. Negotiating Connection IDs:
6068 * When an Initial packet is sent by a client that has not previously
6069 * received an Initial or Retry packet from the server, the client
6070 * populates the Destination Connection ID field with an unpredictable
6071 * value. This Destination Connection ID MUST be at least 8 bytes in length.
6072 */
6073 if (pkt->dcid.len < QUIC_ODCID_MINLEN) {
6074 TRACE_PROTO("dropped packet",
6075 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6076 goto err;
6077 }
6078
6079 pkt->saddr = dgram->saddr;
6080 ipv4 = dgram->saddr.ss_family == AF_INET;
6081
Amaury Denoyelle9e3026c2022-10-17 11:13:07 +02006082 qc = qc_new_conn(pkt->version, ipv4, &pkt->dcid, &pkt->scid, &token_odcid,
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006083 &dgram->daddr, &pkt->saddr, 1,
6084 !!pkt->token_len, l);
6085 if (qc == NULL)
6086 goto err;
6087
6088 HA_ATOMIC_INC(&prx_counters->half_open_conn);
6089 /* Insert the DCID the QUIC client has chosen (only for listeners) */
6090 ebmb_insert(&quic_dghdlrs[tid].odcids, &qc->odcid_node,
6091 qc->odcid.len + qc->odcid.addrlen);
6092 }
6093 }
6094 else if (!qc) {
6095 TRACE_PROTO("No connection on a non Initial packet", QUIC_EV_CONN_LPKT, NULL, NULL, NULL, pkt->version);
6096 if (global.cluster_secret && !send_stateless_reset(l, &dgram->saddr, pkt))
6097 TRACE_ERROR("stateless reset not sent", QUIC_EV_CONN_LPKT, qc);
6098 goto err;
6099 }
6100
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006101 out:
6102 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6103 return qc;
6104
6105 err:
6106 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
6107 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
6108 return NULL;
6109}
6110
Amaury Denoyelle98289692022-10-19 15:37:44 +02006111/* Parse a QUIC packet starting at <buf>. Data won't be read after <end> even
6112 * if the packet is incomplete. This function will populate fields of <pkt>
6113 * instance, most notably its length. <dgram> is the UDP datagram which
6114 * contains the parsed packet. <l> is the listener instance on which it was
6115 * received.
6116 *
6117 * Returns 0 on success else non-zero. Packet length is guaranteed to be set to
6118 * the real packet value or to cover all data between <buf> and <end> : this is
6119 * useful to reject a whole datagram.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006120 */
Amaury Denoyelle98289692022-10-19 15:37:44 +02006121static int quic_rx_pkt_parse(struct quic_rx_packet *pkt,
6122 unsigned char *buf, const unsigned char *end,
6123 struct quic_dgram *dgram, struct listener *l)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006124{
Amaury Denoyelle98289692022-10-19 15:37:44 +02006125 const unsigned char *beg = buf;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006126 struct proxy *prx;
6127 struct quic_counters *prx_counters;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006128 int long_header = 0;
Willy Tarreau33a68702022-11-24 09:16:41 +01006129 uint32_t version = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006130 const struct quic_version *qv = NULL;
6131
6132 TRACE_ENTER(QUIC_EV_CONN_LPKT);
6133
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006134 prx = l->bind_conf->frontend;
6135 prx_counters = EXTRA_COUNTERS_GET(prx->extra_counters_fe, &quic_stats_module);
6136 /* This ist only to please to traces and distinguish the
6137 * packet with parsed packet number from others.
6138 */
6139 pkt->pn_node.key = (uint64_t)-1;
6140 if (end <= buf) {
6141 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6142 goto drop;
6143 }
6144
6145 /* Fixed bit */
6146 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006147 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
6148 quic_padding_check(buf, end)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006149 /* Some browsers may pad the remaining datagram space with null bytes.
6150 * That is what we called add padding out of QUIC packets. Such
6151 * datagrams must be considered as valid. But we can only consume
6152 * the remaining space.
6153 */
6154 pkt->len = end - buf;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006155 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006156 }
6157
6158 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6159 goto drop;
6160 }
6161
6162 /* Header form */
6163 if (!qc_parse_hd_form(pkt, &buf, end, &long_header, &version)) {
6164 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6165 goto drop;
6166 }
6167
6168 if (long_header) {
6169 uint64_t len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006170
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006171 TRACE_PROTO("long header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006172 if (!quic_packet_read_long_header(&buf, end, pkt)) {
6173 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6174 goto drop;
6175 }
6176
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006177 if (pkt->type == QUIC_PACKET_TYPE_INITIAL &&
6178 dgram->len < QUIC_INITIAL_PACKET_MINLEN) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006179 TRACE_PROTO("Too short datagram with an Initial packet", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006180 HA_ATOMIC_INC(&prx_counters->too_short_initial_dgram);
6181 goto drop;
6182 }
6183
6184 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6185 * they must have the same DCID.
6186 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006187 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006188 (pkt->dcid.len != dgram->dcid_len ||
6189 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006190 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006191 goto drop;
6192 }
6193
6194 /* Retry of Version Negotiation packets are only sent by servers */
6195 if (pkt->type == QUIC_PACKET_TYPE_RETRY || !version) {
6196 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6197 goto drop;
6198 }
6199
6200 /* RFC9000 6. Version Negotiation */
6201 qv = qc_supported_version(version);
6202 if (!qv) {
6203 /* unsupported version, send Negotiation packet */
6204 if (send_version_negotiation(l->rx.fd, &dgram->saddr, pkt)) {
6205 TRACE_ERROR("VN packet not sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006206 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006207 }
6208
6209 TRACE_PROTO("VN packet sent", QUIC_EV_CONN_LPKT);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006210 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006211 }
Amaury Denoyelle0eae5722022-10-17 18:05:18 +02006212 pkt->version = qv;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006213
6214 /* For Initial packets, and for servers (QUIC clients connections),
6215 * there is no Initial connection IDs storage.
6216 */
6217 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
6218 uint64_t token_len;
6219
6220 if (!quic_dec_int(&token_len, (const unsigned char **)&buf, end) ||
6221 end - buf < token_len) {
6222 TRACE_PROTO("Packet dropped",
6223 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6224 goto drop;
6225 }
6226
6227 /* TODO Retry should be automatically activated if
6228 * suspect network usage is detected.
6229 */
6230 if (global.cluster_secret && !token_len) {
6231 if (l->bind_conf->options & BC_O_QUIC_FORCE_RETRY) {
6232 TRACE_PROTO("Initial without token, sending retry",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006233 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006234 if (send_retry(l->rx.fd, &dgram->saddr, pkt, qv)) {
6235 TRACE_PROTO("Error during Retry generation",
Amaury Denoyelle90121b32022-09-27 10:35:29 +02006236 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006237 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006238 }
6239
6240 HA_ATOMIC_INC(&prx_counters->retry_sent);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006241 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006242 }
6243 }
6244 else if (!global.cluster_secret && token_len) {
6245 /* Impossible case: a token was received without configured
6246 * cluster secret.
6247 */
6248 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT,
6249 NULL, NULL, NULL, qv);
6250 goto drop;
6251 }
6252
6253 pkt->token = buf;
6254 pkt->token_len = token_len;
6255 buf += pkt->token_len;
6256 }
6257 else if (pkt->type != QUIC_PACKET_TYPE_0RTT) {
6258 if (pkt->dcid.len != QUIC_HAP_CID_LEN) {
6259 TRACE_PROTO("Packet dropped",
6260 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6261 goto drop;
6262 }
6263 }
6264
6265 if (!quic_dec_int(&len, (const unsigned char **)&buf, end) ||
6266 end - buf < len) {
6267 TRACE_PROTO("Packet dropped",
6268 QUIC_EV_CONN_LPKT, NULL, NULL, NULL, qv);
6269 goto drop;
6270 }
6271
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006272 /* Packet Number is stored here. Packet Length totalizes the
6273 * rest of the content.
6274 */
6275 pkt->pn_offset = buf - beg;
6276 pkt->len = pkt->pn_offset + len;
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006277
6278 /* Interrupt parsing after packet length retrieval : this
6279 * ensures that only the packet is dropped but not the whole
6280 * datagram.
6281 */
6282 if (pkt->type == QUIC_PACKET_TYPE_0RTT && !l->bind_conf->ssl_conf.early_data) {
6283 TRACE_PROTO("0-RTT packet not supported", QUIC_EV_CONN_LPKT);
6284 goto drop;
6285 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006286 }
6287 else {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006288 TRACE_PROTO("short header packet received", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006289 if (end - buf < QUIC_HAP_CID_LEN) {
6290 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
6291 goto drop;
6292 }
6293
6294 memcpy(pkt->dcid.data, buf, QUIC_HAP_CID_LEN);
6295 pkt->dcid.len = QUIC_HAP_CID_LEN;
6296
6297 /* When multiple QUIC packets are coalesced on the same UDP datagram,
6298 * they must have the same DCID.
6299 */
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006300 if (!(pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006301 (pkt->dcid.len != dgram->dcid_len ||
6302 memcmp(dgram->dcid, pkt->dcid.data, pkt->dcid.len))) {
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006303 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006304 goto drop;
6305 }
6306
6307 buf += QUIC_HAP_CID_LEN;
6308
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006309 pkt->pn_offset = buf - beg;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006310 /* A short packet is the last one of a UDP datagram. */
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006311 pkt->len = end - beg;
Amaury Denoyelle449b1a82022-10-19 15:28:44 +02006312 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006313
Amaury Denoyelle98289692022-10-19 15:37:44 +02006314 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6315 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006316
Amaury Denoyelle98289692022-10-19 15:37:44 +02006317 drop:
6318 HA_ATOMIC_INC(&prx_counters->dropped_pkt);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006319 drop_silent:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006320 if (!pkt->len)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006321 pkt->len = end - beg;
Amaury Denoyelle98289692022-10-19 15:37:44 +02006322 TRACE_LEAVE(QUIC_EV_CONN_LPKT, NULL, pkt, NULL, qv);
6323 return -1;
6324}
6325
6326/* Check if received packet <pkt> should be drop due to <qc> already in closing
6327 * state. This can be true if a CONNECTION_CLOSE has already been emitted for
6328 * this connection.
6329 *
6330 * Returns false if connection is not in closing state else true. The caller
6331 * should drop the whole datagram in the last case to not mess up <qc>
6332 * CONNECTION_CLOSE rate limit counter.
6333 */
6334static int qc_rx_check_closing(struct quic_conn *qc,
6335 struct quic_rx_packet *pkt)
6336{
6337 if (!(qc->flags & QUIC_FL_CONN_CLOSING))
6338 return 0;
6339
6340 TRACE_STATE("Closing state connection", QUIC_EV_CONN_LPKT, qc, NULL, NULL, pkt->version);
6341
6342 /* Check if CONNECTION_CLOSE rate reemission is reached. */
6343 if (++qc->nb_pkt_since_cc >= qc->nb_pkt_for_cc) {
6344 qc->flags |= QUIC_FL_CONN_IMMEDIATE_CLOSE;
6345 qc->nb_pkt_for_cc++;
6346 qc->nb_pkt_since_cc = 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006347 }
6348
Amaury Denoyelle98289692022-10-19 15:37:44 +02006349 return 1;
6350}
6351
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006352/* React to a connection migration initiated on <qc> by a client with the new
6353 * path addresses <peer_addr>/<local_addr>.
6354 *
6355 * Returns 0 on success else non-zero.
6356 */
6357static int qc_handle_conn_migration(struct quic_conn *qc,
6358 const struct sockaddr_storage *peer_addr,
6359 const struct sockaddr_storage *local_addr)
6360{
6361 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6362
6363 /* RFC 9000 9. Connection Migration
6364 *
Amaury Denoyelleeb6be982022-11-21 11:14:45 +01006365 * The design of QUIC relies on endpoints retaining a stable address for
6366 * the duration of the handshake. An endpoint MUST NOT initiate
6367 * connection migration before the handshake is confirmed, as defined in
6368 * Section 4.1.2 of [QUIC-TLS].
6369 */
6370 if (qc->state < QUIC_HS_ST_COMPLETE) {
6371 TRACE_STATE("Connection migration during handshake rejected", QUIC_EV_CONN_LPKT, qc);
6372 goto err;
6373 }
6374
6375 /* RFC 9000 9. Connection Migration
6376 *
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006377 * TODO
6378 * An endpoint MUST
6379 * perform path validation (Section 8.2) if it detects any change to a
6380 * peer's address, unless it has previously validated that address.
6381 */
6382
Amaury Denoyelled3083c92022-12-01 16:20:06 +01006383 /* Update quic-conn owned socket if in used.
6384 * TODO try to reuse it instead of closing and opening a new one.
6385 */
6386 if (qc_test_fd(qc)) {
6387 /* TODO try to reuse socket instead of closing it and opening a new one. */
6388 TRACE_STATE("Connection migration detected, allocate a new connection socket", QUIC_EV_CONN_LPKT, qc);
6389 qc_release_fd(qc, 1);
6390 qc_alloc_fd(qc, local_addr, peer_addr);
6391 }
6392
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01006393 qc->local_addr = *local_addr;
6394 qc->peer_addr = *peer_addr;
6395 HA_ATOMIC_INC(&qc->prx_counters->conn_migration_done);
6396
6397 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6398 return 0;
6399
6400 err:
6401 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6402 return 1;
6403}
6404
Amaury Denoyelle98289692022-10-19 15:37:44 +02006405/* Handle a parsed packet <pkt> by the connection <qc>. Data will be copied
6406 * into <qc> receive buffer after header protection removal procedure.
6407 *
6408 * <dgram> must be set to the datagram which contains the QUIC packet. <beg>
6409 * must point to packet buffer first byte.
6410 *
6411 * <tasklist_head> may be non-NULL when the caller treat several datagrams for
6412 * different quic-conn. In this case, each quic-conn tasklet will be appended
6413 * to it in order to be woken up after the current task.
6414 *
6415 * The caller can safely removed the packet data. If packet refcount was not
6416 * incremented by this function, it means that the connection did not handled
6417 * it and it should be freed by the caller.
6418 */
6419static void qc_rx_pkt_handle(struct quic_conn *qc, struct quic_rx_packet *pkt,
6420 struct quic_dgram *dgram, unsigned char *beg,
6421 struct list **tasklist_head)
6422{
6423 const struct quic_version *qv = pkt->version;
6424 struct quic_enc_level *qel = NULL;
6425 size_t b_cspace;
6426 int io_cb_wakeup = 1;
6427
Amaury Denoyelle3f474e62022-11-24 17:15:08 +01006428 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6429
Amaury Denoyelledeb7c872022-10-19 17:14:28 +02006430 if (pkt->flags & QUIC_FL_RX_PACKET_DGRAM_FIRST &&
6431 !quic_peer_validated_addr(qc) &&
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006432 qc->flags & QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED) {
6433 TRACE_PROTO("PTO timer must be armed after anti-amplication was reached",
6434 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6435 /* Reset the anti-amplification bit. It will be set again
6436 * when sending the next packet if reached again.
6437 */
6438 qc->flags &= ~QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
6439 qc->flags |= QUIC_FL_CONN_IO_CB_WAKEUP;
6440 io_cb_wakeup = 1;
6441 }
6442
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006443 if (qc->flags & QUIC_FL_CONN_IMMEDIATE_CLOSE) {
6444 TRACE_PROTO("Connection error",
6445 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6446 goto out;
6447 }
6448
6449 pkt->raw_len = pkt->len;
6450 quic_rx_pkts_del(qc);
6451 b_cspace = b_contig_space(&qc->rx.buf);
6452 if (b_cspace < pkt->len) {
6453 /* Do not consume buf if space not at the end. */
6454 if (b_tail(&qc->rx.buf) + b_cspace < b_wrap(&qc->rx.buf)) {
6455 TRACE_PROTO("Packet dropped",
6456 QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006457 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006458 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006459 }
6460
6461 /* Let us consume the remaining contiguous space. */
6462 if (b_cspace) {
6463 b_putchr(&qc->rx.buf, 0x00);
6464 b_cspace--;
6465 }
6466 b_add(&qc->rx.buf, b_cspace);
6467 if (b_contig_space(&qc->rx.buf) < pkt->len) {
6468 TRACE_PROTO("Too big packet",
6469 QUIC_EV_CONN_LPKT, qc, pkt, &pkt->len, qv);
Amaury Denoyelle98289692022-10-19 15:37:44 +02006470 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt_bufoverrun);
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006471 goto drop_silent;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006472 }
6473 }
6474
Amaury Denoyelle845169d2022-10-17 18:05:26 +02006475 if (!qc_try_rm_hp(qc, pkt, beg, &qel)) {
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006476 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc, NULL, NULL, qv);
6477 goto drop;
6478 }
6479
6480 TRACE_DATA("New packet", QUIC_EV_CONN_LPKT, qc, pkt, NULL, qv);
6481 if (pkt->aad_len)
6482 qc_pkt_insert(qc, pkt, qel);
6483 out:
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006484 *tasklist_head = tasklet_wakeup_after(*tasklist_head,
6485 qc->wait_event.tasklet);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006486
Amaury Denoyelle6e56a9e2022-10-17 12:04:49 +02006487 drop_silent:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006488 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006489 return;
6490
6491 drop:
Amaury Denoyelle98289692022-10-19 15:37:44 +02006492 HA_ATOMIC_INC(&qc->prx_counters->dropped_pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006493 err:
6494 /* Wakeup the I/O handler callback if the PTO timer must be armed.
6495 * This cannot be done by this thread.
6496 */
Amaury Denoyelle2ed84002022-09-26 14:53:59 +02006497 if (io_cb_wakeup)
6498 tasklet_wakeup(qc->wait_event.tasklet);
6499
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006500 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc ? qc : NULL, pkt, NULL, qv);
6501}
6502
6503/* This function builds into <buf> buffer a QUIC long packet header.
6504 * Return 1 if enough room to build this header, 0 if not.
6505 */
6506static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
6507 int type, size_t pn_len,
6508 struct quic_conn *qc, const struct quic_version *ver)
6509{
6510 int ret = 0;
6511
6512 TRACE_ENTER(QUIC_EV_CONN_LPKT, qc);
6513
6514 if (end - *buf < sizeof ver->num + qc->dcid.len + qc->scid.len + 3) {
6515 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6516 goto leave;
6517 }
6518
6519 type = quic_pkt_type(type, ver->num);
6520 /* #0 byte flags */
6521 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
6522 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
6523 /* Version */
6524 quic_write_uint32(buf, end, ver->num);
6525 *(*buf)++ = qc->dcid.len;
6526 /* Destination connection ID */
6527 if (qc->dcid.len) {
6528 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6529 *buf += qc->dcid.len;
6530 }
6531 /* Source connection ID */
6532 *(*buf)++ = qc->scid.len;
6533 if (qc->scid.len) {
6534 memcpy(*buf, qc->scid.data, qc->scid.len);
6535 *buf += qc->scid.len;
6536 }
6537
6538 ret = 1;
6539 leave:
6540 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc);
6541 return ret;
6542}
6543
6544/* This function builds into <buf> buffer a QUIC short packet header.
6545 * Return 1 if enough room to build this header, 0 if not.
6546 */
6547static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
6548 size_t pn_len, struct quic_conn *qc,
6549 unsigned char tls_flags)
6550{
6551 int ret = 0;
6552
6553 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6554
6555 if (end - *buf < 1 + qc->dcid.len) {
6556 TRACE_DEVEL("not enough room", QUIC_EV_CONN_LPKT, qc);
6557 goto leave;
6558 }
6559
6560 /* #0 byte flags */
6561 *(*buf)++ = QUIC_PACKET_FIXED_BIT |
6562 ((tls_flags & QUIC_FL_TLS_KP_BIT_SET) ? QUIC_PACKET_KEY_PHASE_BIT : 0) | (pn_len - 1);
6563 /* Destination connection ID */
6564 if (qc->dcid.len) {
6565 memcpy(*buf, qc->dcid.data, qc->dcid.len);
6566 *buf += qc->dcid.len;
6567 }
6568
6569 ret = 1;
6570 leave:
6571 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6572 return ret;
6573}
6574
6575/* Apply QUIC header protection to the packet with <buf> as first byte address,
6576 * <pn> as address of the Packet number field, <pnlen> being this field length
6577 * with <aead> as AEAD cipher and <key> as secret key.
6578 * Returns 1 if succeeded or 0 if failed.
6579 */
6580static int quic_apply_header_protection(struct quic_conn *qc, unsigned char *buf,
6581 unsigned char *pn, size_t pnlen,
6582 struct quic_tls_ctx *tls_ctx)
6583
6584{
6585 int i, ret = 0;
6586 /* We need an IV of at least 5 bytes: one byte for bytes #0
6587 * and at most 4 bytes for the packet number
6588 */
6589 unsigned char mask[5] = {0};
6590 EVP_CIPHER_CTX *aes_ctx = tls_ctx->tx.hp_ctx;
6591
6592 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6593
6594 if (!quic_tls_aes_encrypt(mask, pn + QUIC_PACKET_PN_MAXLEN, sizeof mask, aes_ctx)) {
6595 TRACE_ERROR("could not apply header protection", QUIC_EV_CONN_TXPKT, qc);
6596 goto out;
6597 }
6598
6599 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
6600 for (i = 0; i < pnlen; i++)
6601 pn[i] ^= mask[i + 1];
6602
6603 ret = 1;
6604 out:
6605 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6606 return ret;
6607}
6608
6609/* Reduce the encoded size of <ack_frm> ACK frame removing the last
6610 * ACK ranges if needed to a value below <limit> in bytes.
6611 * Return 1 if succeeded, 0 if not.
6612 */
6613static int quic_ack_frm_reduce_sz(struct quic_conn *qc,
6614 struct quic_frame *ack_frm, size_t limit)
6615{
6616 size_t room, ack_delay_sz;
6617 int ret = 0;
6618
6619 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6620
6621 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
6622 /* A frame is made of 1 byte for the frame type. */
6623 room = limit - ack_delay_sz - 1;
6624 if (!quic_rm_last_ack_ranges(qc, ack_frm->tx_ack.arngs, room))
6625 goto leave;
6626
6627 ret = 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
6628 leave:
6629 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
6630 return ret;
6631}
6632
6633/* Prepare into <outlist> as most as possible ack-eliciting frame from their
6634 * <inlist> prebuilt frames for <qel> encryption level to be encoded in a buffer
6635 * with <room> as available room, and <*len> the packet Length field initialized
6636 * with the number of bytes already present in this buffer which must be taken
6637 * into an account for the Length packet field value. <headlen> is the number of
6638 * bytes already present in this packet before building frames.
6639 *
6640 * Update consequently <*len> to reflect the size of these frames built
6641 * by this function. Also attach these frames to <l> frame list.
6642 * Return 1 if at least one ack-eleciting frame could be built, 0 if not.
6643 */
6644static inline int qc_build_frms(struct list *outlist, struct list *inlist,
6645 size_t room, size_t *len, size_t headlen,
6646 struct quic_enc_level *qel,
6647 struct quic_conn *qc)
6648{
6649 int ret;
6650 struct quic_frame *cf, *cfbak;
6651
6652 TRACE_ENTER(QUIC_EV_CONN_BCFRMS, qc);
6653
6654 ret = 0;
6655 if (*len > room)
6656 goto leave;
6657
6658 /* If we are not probing we must take into an account the congestion
6659 * control window.
6660 */
6661 if (!qel->pktns->tx.pto_probe) {
6662 size_t remain = quic_path_prep_data(qc->path);
6663
6664 if (headlen > remain)
6665 goto leave;
6666
6667 room = QUIC_MIN(room, remain - headlen);
6668 }
6669
6670 TRACE_PROTO("************** frames build (headlen)",
6671 QUIC_EV_CONN_BCFRMS, qc, &headlen);
6672
6673 /* NOTE: switch/case block inside a loop, a successful status must be
6674 * returned by this function only if at least one frame could be built
6675 * in the switch/case block.
6676 */
6677 list_for_each_entry_safe(cf, cfbak, inlist, list) {
6678 /* header length, data length, frame length. */
6679 size_t hlen, dlen, dlen_sz, avail_room, flen;
6680
6681 if (!room)
6682 break;
6683
6684 switch (cf->type) {
6685 case QUIC_FT_CRYPTO:
6686 TRACE_DEVEL(" New CRYPTO frame build (room, len)",
6687 QUIC_EV_CONN_BCFRMS, qc, &room, len);
6688 /* Compute the length of this CRYPTO frame header */
6689 hlen = 1 + quic_int_getsize(cf->crypto.offset);
6690 /* Compute the data length of this CRyPTO frame. */
6691 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
6692 TRACE_DEVEL(" CRYPTO data length (hlen, crypto.len, dlen)",
6693 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->crypto.len, &dlen);
6694 if (!dlen)
6695 continue;
6696
6697 /* CRYPTO frame length. */
6698 flen = hlen + quic_int_getsize(dlen) + dlen;
6699 TRACE_DEVEL(" CRYPTO frame length (flen)",
6700 QUIC_EV_CONN_BCFRMS, qc, &flen);
6701 /* Add the CRYPTO data length and its encoded length to the packet
6702 * length and the length of this length.
6703 */
6704 *len += flen;
6705 room -= flen;
6706 if (dlen == cf->crypto.len) {
6707 /* <cf> CRYPTO data have been consumed. */
6708 LIST_DELETE(&cf->list);
6709 LIST_APPEND(outlist, &cf->list);
6710 }
6711 else {
6712 struct quic_frame *new_cf;
6713
6714 new_cf = pool_zalloc(pool_head_quic_frame);
6715 if (!new_cf) {
6716 TRACE_ERROR("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, qc);
6717 continue;
6718 }
6719
6720 LIST_INIT(&new_cf->reflist);
6721 new_cf->type = QUIC_FT_CRYPTO;
6722 new_cf->crypto.len = dlen;
6723 new_cf->crypto.offset = cf->crypto.offset;
6724 new_cf->crypto.qel = qel;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006725 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006726 if (cf->origin) {
6727 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
6728 /* This <cf> frame was duplicated */
6729 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
6730 new_cf->origin = cf->origin;
6731 }
6732 LIST_APPEND(outlist, &new_cf->list);
6733 /* Consume <dlen> bytes of the current frame. */
6734 cf->crypto.len -= dlen;
6735 cf->crypto.offset += dlen;
6736 }
6737 break;
6738
6739 case QUIC_FT_STREAM_8 ... QUIC_FT_STREAM_F:
6740 if (cf->flags & QUIC_FL_TX_FRAME_LOST) {
6741 struct eb64_node *node = NULL;
6742 struct qc_stream_desc *stream_desc = NULL;
6743 struct quic_stream *strm = &cf->stream;
6744
6745 /* As this frame has been already lost, ensure the stream is always
6746 * available or the range of this frame is not consumed before
6747 * resending it.
6748 */
6749 node = eb64_lookup(&qc->streams_by_id, strm->id);
6750 if (!node) {
6751 TRACE_DEVEL("released stream", QUIC_EV_CONN_PRSAFRM, qc, cf);
6752 LIST_DELETE(&cf->list);
6753 pool_free(pool_head_quic_frame, cf);
6754 continue;
6755 }
6756
6757 stream_desc = eb64_entry(node, struct qc_stream_desc, by_id);
6758 if (strm->offset.key + strm->len <= stream_desc->ack_offset) {
6759 TRACE_DEVEL("ignored frame frame in already acked range",
6760 QUIC_EV_CONN_PRSAFRM, qc, cf);
6761 LIST_DELETE(&cf->list);
6762 pool_free(pool_head_quic_frame, cf);
6763 continue;
6764 }
6765 else if (strm->offset.key < stream_desc->ack_offset) {
6766 strm->offset.key = stream_desc->ack_offset;
6767 TRACE_DEVEL("updated partially acked frame",
6768 QUIC_EV_CONN_PRSAFRM, qc, cf);
6769 }
6770 }
6771 /* Note that these frames are accepted in short packets only without
6772 * "Length" packet field. Here, <*len> is used only to compute the
6773 * sum of the lengths of the already built frames for this packet.
6774 *
6775 * Compute the length of this STREAM frame "header" made a all the field
6776 * excepting the variable ones. Note that +1 is for the type of this frame.
6777 */
6778 hlen = 1 + quic_int_getsize(cf->stream.id) +
6779 ((cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT) ? quic_int_getsize(cf->stream.offset.key) : 0);
6780 /* Compute the data length of this STREAM frame. */
6781 avail_room = room - hlen - *len;
6782 if ((ssize_t)avail_room <= 0)
6783 continue;
6784
6785 TRACE_DEVEL(" New STREAM frame build (room, len)",
6786 QUIC_EV_CONN_BCFRMS, qc, &room, len);
6787 if (cf->type & QUIC_STREAM_FRAME_TYPE_LEN_BIT) {
6788 dlen = max_available_room(avail_room, &dlen_sz);
6789 if (dlen > cf->stream.len) {
6790 dlen = cf->stream.len;
6791 }
6792 dlen_sz = quic_int_getsize(dlen);
6793 flen = hlen + dlen_sz + dlen;
6794 }
6795 else {
6796 dlen = QUIC_MIN((uint64_t)avail_room, cf->stream.len);
6797 flen = hlen + dlen;
6798 }
6799 TRACE_DEVEL(" STREAM data length (hlen, stream.len, dlen)",
6800 QUIC_EV_CONN_BCFRMS, qc, &hlen, &cf->stream.len, &dlen);
6801 TRACE_DEVEL(" STREAM frame length (flen)",
6802 QUIC_EV_CONN_BCFRMS, qc, &flen);
6803 /* Add the STREAM data length and its encoded length to the packet
6804 * length and the length of this length.
6805 */
6806 *len += flen;
6807 room -= flen;
6808 if (dlen == cf->stream.len) {
6809 /* <cf> STREAM data have been consumed. */
6810 LIST_DELETE(&cf->list);
6811 LIST_APPEND(outlist, &cf->list);
6812
6813 /* Do not notify MUX on retransmission. */
6814 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
6815 qcc_streams_sent_done(cf->stream.stream->ctx,
6816 cf->stream.len,
6817 cf->stream.offset.key);
6818 }
6819 }
6820 else {
6821 struct quic_frame *new_cf;
6822 struct buffer cf_buf;
6823
6824 new_cf = pool_zalloc(pool_head_quic_frame);
6825 if (!new_cf) {
6826 TRACE_ERROR("No memory for new STREAM frame", QUIC_EV_CONN_BCFRMS, qc);
6827 continue;
6828 }
6829
6830 LIST_INIT(&new_cf->reflist);
6831 new_cf->type = cf->type;
6832 new_cf->stream.stream = cf->stream.stream;
6833 new_cf->stream.buf = cf->stream.buf;
6834 new_cf->stream.id = cf->stream.id;
6835 if (cf->type & QUIC_STREAM_FRAME_TYPE_OFF_BIT)
6836 new_cf->stream.offset = cf->stream.offset;
6837 new_cf->stream.len = dlen;
6838 new_cf->type |= QUIC_STREAM_FRAME_TYPE_LEN_BIT;
6839 /* FIN bit reset */
6840 new_cf->type &= ~QUIC_STREAM_FRAME_TYPE_FIN_BIT;
6841 new_cf->stream.data = cf->stream.data;
Ilya Shipitsin4a689da2022-10-29 09:34:32 +05006842 TRACE_DEVEL("split frame", QUIC_EV_CONN_PRSAFRM, qc, new_cf);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02006843 if (cf->origin) {
6844 TRACE_DEVEL("duplicated frame", QUIC_EV_CONN_PRSAFRM, qc);
6845 /* This <cf> frame was duplicated */
6846 LIST_APPEND(&cf->origin->reflist, &new_cf->ref);
6847 new_cf->origin = cf->origin;
6848 }
6849 LIST_APPEND(outlist, &new_cf->list);
6850 cf->type |= QUIC_STREAM_FRAME_TYPE_OFF_BIT;
6851 /* Consume <dlen> bytes of the current frame. */
6852 cf_buf = b_make(b_orig(cf->stream.buf),
6853 b_size(cf->stream.buf),
6854 (char *)cf->stream.data - b_orig(cf->stream.buf), 0);
6855 cf->stream.len -= dlen;
6856 cf->stream.offset.key += dlen;
6857 cf->stream.data = (unsigned char *)b_peek(&cf_buf, dlen);
6858
6859 /* Do not notify MUX on retransmission. */
6860 if (qc->flags & QUIC_FL_CONN_TX_MUX_CONTEXT) {
6861 qcc_streams_sent_done(new_cf->stream.stream->ctx,
6862 new_cf->stream.len,
6863 new_cf->stream.offset.key);
6864 }
6865 }
6866
6867 /* TODO the MUX is notified about the frame sending via
6868 * previous qcc_streams_sent_done call. However, the
6869 * sending can fail later, for example if the sendto
6870 * system call returns an error. As the MUX has been
6871 * notified, the transport layer is responsible to
6872 * bufferize and resent the announced data later.
6873 */
6874
6875 break;
6876
6877 default:
6878 flen = qc_frm_len(cf);
6879 BUG_ON(!flen);
6880 if (flen > room)
6881 continue;
6882
6883 *len += flen;
6884 room -= flen;
6885 LIST_DELETE(&cf->list);
6886 LIST_APPEND(outlist, &cf->list);
6887 break;
6888 }
6889
6890 /* Successful status as soon as a frame could be built */
6891 ret = 1;
6892 }
6893
6894 leave:
6895 TRACE_LEAVE(QUIC_EV_CONN_BCFRMS, qc);
6896 return ret;
6897}
6898
6899/* Generate a CONNECTION_CLOSE frame for <qc> on <qel> encryption level. <out>
6900 * is used as return parameter and should be zero'ed by the caller.
6901 */
6902static void qc_build_cc_frm(struct quic_conn *qc, struct quic_enc_level *qel,
6903 struct quic_frame *out)
6904{
6905 /* TODO improve CONNECTION_CLOSE on Initial/Handshake encryption levels
6906 *
6907 * A CONNECTION_CLOSE frame should be sent in several packets with
6908 * different encryption levels depending on the client context. This is
6909 * to ensure that the client can decrypt it. See RFC 9000 10.2.3 for
6910 * more details on how to implement it.
6911 */
6912 TRACE_ENTER(QUIC_EV_CONN_BFRM, qc);
6913
6914
6915 if (qc->err.app) {
6916 if (unlikely(qel == &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL] ||
6917 qel == &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE])) {
6918 /* RFC 9000 10.2.3. Immediate Close during the Handshake
6919 *
6920 * Sending a CONNECTION_CLOSE of type 0x1d in an Initial or Handshake
6921 * packet could expose application state or be used to alter application
6922 * state. A CONNECTION_CLOSE of type 0x1d MUST be replaced by a
6923 * CONNECTION_CLOSE of type 0x1c when sending the frame in Initial or
6924 * Handshake packets. Otherwise, information about the application
6925 * state might be revealed. Endpoints MUST clear the value of the
6926 * Reason Phrase field and SHOULD use the APPLICATION_ERROR code when
6927 * converting to a CONNECTION_CLOSE of type 0x1c.
6928 */
6929 out->type = QUIC_FT_CONNECTION_CLOSE;
6930 out->connection_close.error_code = QC_ERR_APPLICATION_ERROR;
6931 out->connection_close.reason_phrase_len = 0;
6932 }
6933 else {
6934 out->type = QUIC_FT_CONNECTION_CLOSE_APP;
6935 out->connection_close.error_code = qc->err.code;
6936 }
6937 }
6938 else {
6939 out->type = QUIC_FT_CONNECTION_CLOSE;
6940 out->connection_close.error_code = qc->err.code;
6941 }
6942 TRACE_LEAVE(QUIC_EV_CONN_BFRM, qc);
6943
6944}
6945
6946/* This function builds a clear packet from <pkt> information (its type)
6947 * into a buffer with <pos> as position pointer and <qel> as QUIC TLS encryption
6948 * level for <conn> QUIC connection and <qel> as QUIC TLS encryption level,
6949 * filling the buffer with as much frames as possible from <frms> list of
6950 * prebuilt frames.
6951 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
6952 * reserved so that to ensure there is enough room to build this AEAD TAG after
6953 * having returned from this function.
6954 * This function also updates the value of <buf_pn> pointer to point to the packet
6955 * number field in this packet. <pn_len> will also have the packet number
6956 * length as value.
6957 *
6958 * Return 1 if succeeded (enough room to buile this packet), O if not.
6959 */
6960static int qc_do_build_pkt(unsigned char *pos, const unsigned char *end,
6961 size_t dglen, struct quic_tx_packet *pkt,
6962 int64_t pn, size_t *pn_len, unsigned char **buf_pn,
6963 int force_ack, int padding, int cc, int probe,
6964 struct quic_enc_level *qel, struct quic_conn *qc,
6965 const struct quic_version *ver, struct list *frms)
6966{
6967 unsigned char *beg, *payload;
6968 size_t len, len_sz, len_frms, padding_len;
6969 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
6970 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
6971 struct quic_frame cc_frm = { };
6972 size_t ack_frm_len, head_len;
6973 int64_t rx_largest_acked_pn;
6974 int add_ping_frm;
6975 struct list frm_list = LIST_HEAD_INIT(frm_list);
6976 struct quic_frame *cf;
6977 int must_ack, ret = 0;
6978 int nb_aepkts_since_last_ack;
6979
6980 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc);
6981
6982 /* Length field value with CRYPTO frames if present. */
6983 len_frms = 0;
6984 beg = pos;
6985 /* When not probing, and no immediate close is required, reduce the size of this
6986 * buffer to respect the congestion controller window.
6987 * This size will be limited if we have ack-eliciting frames to send from <frms>.
6988 */
6989 if (!probe && !LIST_ISEMPTY(frms) && !cc) {
6990 size_t path_room;
6991
6992 path_room = quic_path_prep_data(qc->path);
6993 if (end - beg > path_room)
6994 end = beg + path_room;
6995 }
6996
6997 /* Ensure there is enough room for the TLS encryption tag and a zero token
6998 * length field if any.
6999 */
7000 if (end - pos < QUIC_TLS_TAG_LEN +
7001 (pkt->type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0))
7002 goto no_room;
7003
7004 end -= QUIC_TLS_TAG_LEN;
7005 rx_largest_acked_pn = qel->pktns->rx.largest_acked_pn;
7006 /* packet number length */
7007 *pn_len = quic_packet_number_length(pn, rx_largest_acked_pn);
7008 /* Build the header */
7009 if ((pkt->type == QUIC_PACKET_TYPE_SHORT &&
7010 !quic_build_packet_short_header(&pos, end, *pn_len, qc, qel->tls_ctx.flags)) ||
7011 (pkt->type != QUIC_PACKET_TYPE_SHORT &&
7012 !quic_build_packet_long_header(&pos, end, pkt->type, *pn_len, qc, ver)))
7013 goto no_room;
7014
7015 /* Encode the token length (0) for an Initial packet. */
7016 if (pkt->type == QUIC_PACKET_TYPE_INITIAL)
7017 *pos++ = 0;
7018 head_len = pos - beg;
7019 /* Build an ACK frame if required. */
7020 ack_frm_len = 0;
7021 nb_aepkts_since_last_ack = qel->pktns->rx.nb_aepkts_since_last_ack;
7022 must_ack = !qel->pktns->tx.pto_probe &&
7023 (force_ack || ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
7024 (LIST_ISEMPTY(frms) || nb_aepkts_since_last_ack >= QUIC_MAX_RX_AEPKTS_SINCE_LAST_ACK)));
7025 if (must_ack) {
7026 struct quic_arngs *arngs = &qel->pktns->rx.arngs;
7027 BUG_ON(eb_is_empty(&qel->pktns->rx.arngs.root));
7028 ack_frm.tx_ack.arngs = arngs;
7029 if (qel->pktns->flags & QUIC_FL_PKTNS_NEW_LARGEST_PN) {
7030 qel->pktns->tx.ack_delay =
7031 quic_compute_ack_delay_us(qel->pktns->rx.largest_time_received, qc);
7032 qel->pktns->flags &= ~QUIC_FL_PKTNS_NEW_LARGEST_PN;
7033 }
7034 ack_frm.tx_ack.ack_delay = qel->pktns->tx.ack_delay;
7035 /* XXX BE CAREFUL XXX : here we reserved at least one byte for the
7036 * smallest frame (PING) and <*pn_len> more for the packet number. Note
7037 * that from here, we do not know if we will have to send a PING frame.
7038 * This will be decided after having computed the ack-eliciting frames
7039 * to be added to this packet.
7040 */
7041 ack_frm_len = quic_ack_frm_reduce_sz(qc, &ack_frm, end - 1 - *pn_len - pos);
7042 if (!ack_frm_len)
7043 goto no_room;
7044 }
7045
7046 /* Length field value without the ack-eliciting frames. */
7047 len = ack_frm_len + *pn_len;
7048 len_frms = 0;
7049 if (!cc && !LIST_ISEMPTY(frms)) {
7050 ssize_t room = end - pos;
7051
7052 TRACE_DEVEL("Avail. ack eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7053 /* Initialize the length of the frames built below to <len>.
7054 * If any frame could be successfully built by qc_build_frms(),
7055 * we will have len_frms > len.
7056 */
7057 len_frms = len;
7058 if (!qc_build_frms(&frm_list, frms,
7059 end - pos, &len_frms, pos - beg, qel, qc)) {
7060 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7061 qc, NULL, NULL, &room);
7062 if (!ack_frm_len && !qel->pktns->tx.pto_probe)
7063 goto no_room;
7064 }
7065 }
7066
7067 /* Length (of the remaining data). Must not fail because, the buffer size
7068 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
7069 * for the encryption tag. It must be taken into an account for the length
7070 * of this packet.
7071 */
7072 if (len_frms)
7073 len = len_frms + QUIC_TLS_TAG_LEN;
7074 else
7075 len += QUIC_TLS_TAG_LEN;
7076 /* CONNECTION_CLOSE frame */
7077 if (cc) {
7078 qc_build_cc_frm(qc, qel, &cc_frm);
7079 len += qc_frm_len(&cc_frm);
7080 }
7081 add_ping_frm = 0;
7082 padding_len = 0;
7083 len_sz = quic_int_getsize(len);
7084 /* Add this packet size to <dglen> */
7085 dglen += head_len + len_sz + len;
7086 if (padding && dglen < QUIC_INITIAL_PACKET_MINLEN) {
7087 /* This is a maximum padding size */
7088 padding_len = QUIC_INITIAL_PACKET_MINLEN - dglen;
7089 /* The length field value is of this packet is <len> + <padding_len>
7090 * the size of which may be greater than the initial computed size
7091 * <len_sz>. So, let's deduce the difference between these to packet
7092 * sizes from <padding_len>.
7093 */
7094 padding_len -= quic_int_getsize(len + padding_len) - len_sz;
7095 len += padding_len;
7096 }
7097 else if (LIST_ISEMPTY(&frm_list) || len_frms == len) {
7098 if (qel->pktns->tx.pto_probe) {
7099 /* If we cannot send a frame, we send a PING frame. */
7100 add_ping_frm = 1;
7101 len += 1;
7102 }
7103 /* If there is no frame at all to follow, add at least a PADDING frame. */
7104 if (!ack_frm_len && !cc)
7105 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
7106 }
7107
7108 if (pkt->type != QUIC_PACKET_TYPE_SHORT && !quic_enc_int(&pos, end, len))
7109 goto no_room;
7110
7111 /* Packet number field address. */
7112 *buf_pn = pos;
7113
7114 /* Packet number encoding. */
7115 if (!quic_packet_number_encode(&pos, end, pn, *pn_len))
7116 goto no_room;
7117
7118 /* payload building (ack-eliciting or not frames) */
7119 payload = pos;
7120 if (ack_frm_len) {
7121 if (!qc_build_frm(&pos, end, &ack_frm, pkt, qc))
7122 goto no_room;
7123
7124 pkt->largest_acked_pn = quic_pktns_get_largest_acked_pn(qel->pktns);
7125 pkt->flags |= QUIC_FL_TX_PACKET_ACK;
7126 }
7127
7128 /* Ack-eliciting frames */
7129 if (!LIST_ISEMPTY(&frm_list)) {
7130 struct quic_frame *tmp_cf;
7131 list_for_each_entry_safe(cf, tmp_cf, &frm_list, list) {
7132 if (!qc_build_frm(&pos, end, cf, pkt, qc)) {
7133 ssize_t room = end - pos;
7134 TRACE_DEVEL("Not enough room", QUIC_EV_CONN_TXPKT,
7135 qc, NULL, NULL, &room);
7136 /* Note that <cf> was added from <frms> to <frm_list> list by
7137 * qc_build_frms().
7138 */
7139 LIST_DELETE(&cf->list);
7140 LIST_INSERT(frms, &cf->list);
7141 continue;
7142 }
7143
7144 quic_tx_packet_refinc(pkt);
7145 cf->pkt = pkt;
7146 }
7147 }
7148
7149 /* Build a PING frame if needed. */
7150 if (add_ping_frm) {
7151 frm.type = QUIC_FT_PING;
7152 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7153 goto no_room;
7154 }
7155
7156 /* Build a CONNECTION_CLOSE frame if needed. */
7157 if (cc) {
7158 if (!qc_build_frm(&pos, end, &cc_frm, pkt, qc))
7159 goto no_room;
7160
7161 pkt->flags |= QUIC_FL_TX_PACKET_CC;
7162 }
7163
7164 /* Build a PADDING frame if needed. */
7165 if (padding_len) {
7166 frm.type = QUIC_FT_PADDING;
7167 frm.padding.len = padding_len;
7168 if (!qc_build_frm(&pos, end, &frm, pkt, qc))
7169 goto no_room;
7170 }
7171
7172 if (pos == payload) {
7173 /* No payload was built because of congestion control */
7174 TRACE_DEVEL("limited by congestion control", QUIC_EV_CONN_TXPKT, qc);
7175 goto no_room;
7176 }
7177
7178 /* If this packet is ack-eliciting and we are probing let's
7179 * decrement the PTO probe counter.
7180 */
7181 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING &&
7182 qel->pktns->tx.pto_probe)
7183 qel->pktns->tx.pto_probe--;
7184
7185 pkt->len = pos - beg;
7186 LIST_SPLICE(&pkt->frms, &frm_list);
7187
7188 ret = 1;
7189 TRACE_DEVEL("Packet ack-eliciting frames", QUIC_EV_CONN_TXPKT, qc, pkt);
7190 leave:
7191 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc);
7192 return ret;
7193
7194 no_room:
7195 /* Replace the pre-built frames which could not be add to this packet */
7196 LIST_SPLICE(frms, &frm_list);
7197 TRACE_DEVEL("Remaining ack-eliciting frames", QUIC_EV_CONN_FRMLIST, qc, frms);
7198 goto leave;
7199}
7200
7201static inline void quic_tx_packet_init(struct quic_tx_packet *pkt, int type)
7202{
7203 pkt->type = type;
7204 pkt->len = 0;
7205 pkt->in_flight_len = 0;
7206 pkt->pn_node.key = (uint64_t)-1;
7207 LIST_INIT(&pkt->frms);
7208 pkt->time_sent = TICK_ETERNITY;
7209 pkt->next = NULL;
Frédéric Lécaille814645f2022-11-18 18:15:28 +01007210 pkt->prev = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007211 pkt->largest_acked_pn = -1;
7212 pkt->flags = 0;
7213 pkt->refcnt = 0;
7214}
7215
7216/* Build a packet into <buf> packet buffer with <pkt_type> as packet
7217 * type for <qc> QUIC connection from <qel> encryption level from <frms> list
7218 * of prebuilt frames.
7219 *
7220 * Return -2 if the packet could not be allocated or encrypted for any reason,
7221 * -1 if there was not enough room to build a packet.
7222 * XXX NOTE XXX
7223 * If you provide provide qc_build_pkt() with a big enough buffer to build a packet as big as
7224 * possible (to fill an MTU), the unique reason why this function may fail is the congestion
7225 * control window limitation.
7226 */
7227static struct quic_tx_packet *qc_build_pkt(unsigned char **pos,
7228 const unsigned char *buf_end,
7229 struct quic_enc_level *qel,
7230 struct quic_tls_ctx *tls_ctx, struct list *frms,
7231 struct quic_conn *qc, const struct quic_version *ver,
7232 size_t dglen, int pkt_type, int force_ack,
7233 int padding, int probe, int cc, int *err)
7234{
7235 struct quic_tx_packet *ret_pkt = NULL;
7236 /* The pointer to the packet number field. */
7237 unsigned char *buf_pn;
7238 unsigned char *beg, *end, *payload;
7239 int64_t pn;
7240 size_t pn_len, payload_len, aad_len;
7241 struct quic_tx_packet *pkt;
7242
7243 TRACE_ENTER(QUIC_EV_CONN_TXPKT, qc, NULL, qel);
7244 *err = 0;
7245 pkt = pool_alloc(pool_head_quic_tx_packet);
7246 if (!pkt) {
7247 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_TXPKT, qc);
7248 *err = -2;
7249 goto err;
7250 }
7251
7252 quic_tx_packet_init(pkt, pkt_type);
7253 beg = *pos;
7254 pn_len = 0;
7255 buf_pn = NULL;
7256
7257 pn = qel->pktns->tx.next_pn + 1;
7258 if (!qc_do_build_pkt(*pos, buf_end, dglen, pkt, pn, &pn_len, &buf_pn,
7259 force_ack, padding, cc, probe, qel, qc, ver, frms)) {
7260 // trace already emitted by function above
7261 *err = -1;
7262 goto err;
7263 }
7264
7265 end = beg + pkt->len;
7266 payload = buf_pn + pn_len;
7267 payload_len = end - payload;
7268 aad_len = payload - beg;
7269
7270 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc)) {
7271 // trace already emitted by function above
7272 *err = -2;
7273 goto err;
7274 }
7275
7276 end += QUIC_TLS_TAG_LEN;
7277 pkt->len += QUIC_TLS_TAG_LEN;
7278 if (!quic_apply_header_protection(qc, beg, buf_pn, pn_len, tls_ctx)) {
7279 // trace already emitted by function above
7280 *err = -2;
7281 goto err;
7282 }
7283
7284 /* Consume a packet number */
7285 qel->pktns->tx.next_pn++;
7286 qc->tx.prep_bytes += pkt->len;
7287 if (qc->tx.prep_bytes >= 3 * qc->rx.bytes && !quic_peer_validated_addr(qc)) {
7288 qc->flags |= QUIC_FL_CONN_ANTI_AMPLIFICATION_REACHED;
7289 TRACE_PROTO("anti-amplification limit reached", QUIC_EV_CONN_TXPKT, qc);
7290 }
7291 /* Now that a correct packet is built, let us consume <*pos> buffer. */
7292 *pos = end;
7293 /* Attach the built packet to its tree. */
7294 pkt->pn_node.key = pn;
7295 /* Set the packet in fligth length for in flight packet only. */
7296 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
7297 pkt->in_flight_len = pkt->len;
7298 qc->path->prep_in_flight += pkt->len;
7299 }
7300 /* Always reset this flags */
7301 qc->flags &= ~QUIC_FL_CONN_IMMEDIATE_CLOSE;
7302 if (pkt->flags & QUIC_FL_TX_PACKET_ACK) {
7303 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
7304 qel->pktns->rx.nb_aepkts_since_last_ack = 0;
7305 }
7306
7307 pkt->pktns = qel->pktns;
7308
7309 ret_pkt = pkt;
7310 leave:
7311 TRACE_LEAVE(QUIC_EV_CONN_TXPKT, qc, ret_pkt);
7312 return ret_pkt;
7313
7314 err:
7315 /* TODO: what about the frames which have been built
7316 * for this packet.
7317 */
7318 free_quic_tx_packet(qc, pkt);
7319 goto leave;
7320}
7321
7322
7323static void __quic_conn_init(void)
7324{
7325 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
7326}
7327INITCALL0(STG_REGISTER, __quic_conn_init);
7328
7329static void __quic_conn_deinit(void)
7330{
7331 BIO_meth_free(ha_quic_meth);
7332}
7333REGISTER_POST_DEINIT(__quic_conn_deinit);
7334
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007335/* Handle a new <dgram> received. Parse each QUIC packets and copied their
7336 * content to a quic-conn instance. The datagram content can be released after
7337 * this function.
7338 *
7339 * If datagram has been received on a quic-conn owned FD, <from_qc> must be set
7340 * to the connection instance. <li> is the attached listener. The caller is
7341 * responsible to ensure that the first packet is destined to this connection
7342 * by comparing CIDs.
7343 *
7344 * If datagram has been received on a receiver FD, <from_qc> will be NULL. This
7345 * function will thus retrieve the connection from the CID tree or allocate a
7346 * new one if possible. <li> is the listener attached to the receiver.
7347 *
7348 * Returns 0 on success else non-zero. If an error happens, some packets from
7349 * the datagram may not have been parsed.
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007350 */
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007351int quic_dgram_parse(struct quic_dgram *dgram, struct quic_conn *from_qc,
7352 struct listener *li)
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007353{
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007354 struct quic_rx_packet *pkt;
7355 struct quic_conn *qc = NULL;
7356 unsigned char *pos, *end;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007357 struct list *tasklist_head = NULL;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007358
7359 TRACE_ENTER(QUIC_EV_CONN_LPKT);
7360
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007361 pos = dgram->buf;
7362 end = pos + dgram->len;
7363 do {
7364 /* TODO replace zalloc -> alloc. */
7365 pkt = pool_zalloc(pool_head_quic_rx_packet);
7366 if (!pkt) {
7367 TRACE_ERROR("RX packet allocation failed", QUIC_EV_CONN_LPKT);
7368 goto err;
7369 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007370
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007371 pkt->version = NULL;
7372 pkt->pn_offset = 0;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007373
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007374 /* Set flag if pkt is the first one in dgram. */
7375 if (pos == dgram->buf)
7376 pkt->flags |= QUIC_FL_RX_PACKET_DGRAM_FIRST;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007377
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007378 LIST_INIT(&pkt->qc_rx_pkt_list);
7379 pkt->time_received = now_ms;
7380 quic_rx_packet_refinc(pkt);
7381 if (quic_rx_pkt_parse(pkt, pos, end, dgram, li))
7382 goto next;
Amaury Denoyelle98289692022-10-19 15:37:44 +02007383
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007384 /* Search quic-conn instance for first packet of the datagram.
7385 * quic_rx_packet_parse() is responsible to discard packets
7386 * with different DCID as the first one in the same datagram.
7387 */
7388 if (!qc) {
7389 qc = from_qc ? from_qc : quic_rx_pkt_retrieve_conn(pkt, dgram, li);
7390 /* qc is NULL if receiving a non Initial packet for an
7391 * unknown connection.
7392 */
7393 if (!qc) {
Amaury Denoyelle98289692022-10-19 15:37:44 +02007394 /* Skip the entire datagram. */
7395 pkt->len = end - pos;
7396 goto next;
7397 }
7398
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007399 dgram->qc = qc;
7400 }
Amaury Denoyelle98289692022-10-19 15:37:44 +02007401
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007402 if (qc_rx_check_closing(qc, pkt)) {
7403 /* Skip the entire datagram. */
7404 pkt->len = end - pos;
7405 goto next;
7406 }
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007407
Amaury Denoyelleeec0b3c2022-12-02 09:57:32 +01007408 /* Detect QUIC connection migration. */
7409 if (ipcmp(&qc->peer_addr, &dgram->saddr, 1) ||
7410 ipcmp(&qc->local_addr, &dgram->daddr, 1)) {
7411 if (qc_handle_conn_migration(qc, &dgram->saddr, &dgram->daddr)) {
7412 /* Skip the entire datagram. */
7413 TRACE_ERROR("error during connection migration, datagram dropped", QUIC_EV_CONN_LPKT, qc);
7414 pkt->len = end - pos;
7415 goto next;
7416 }
7417 }
7418
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007419 qc_rx_pkt_handle(qc, pkt, dgram, pos, &tasklist_head);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007420
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007421 next:
7422 pos += pkt->len;
7423 quic_rx_packet_refdec(pkt);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007424
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007425 /* Free rejected packets */
7426 if (!pkt->refcnt) {
7427 BUG_ON(LIST_INLIST(&pkt->qc_rx_pkt_list));
7428 pool_free(pool_head_quic_rx_packet, pkt);
7429 }
7430 } while (pos < end);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007431
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007432 /* Increasing the received bytes counter by the UDP datagram length
7433 * if this datagram could be associated to a connection.
7434 */
7435 if (dgram->qc)
7436 dgram->qc->rx.bytes += dgram->len;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007437
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007438 /* This must never happen. */
7439 BUG_ON(pos > end);
7440 BUG_ON(pos < end || pos > dgram->buf + dgram->len);
7441 /* Mark this datagram as consumed */
7442 HA_ATOMIC_STORE(&dgram->buf, NULL);
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007443
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007444 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
7445 return 0;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007446
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007447 err:
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007448 TRACE_LEAVE(QUIC_EV_CONN_LPKT);
Amaury Denoyelle8687b632022-09-27 14:22:09 +02007449 return -1;
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007450}
7451
Amaury Denoyelle7c9fdd92022-11-16 11:01:02 +01007452/* Check if connection ID <dcid> of length <dcid_len> belongs to <qc> local
7453 * CIDs. This can be used to determine if a datagram is addressed to the right
7454 * connection instance.
7455 *
7456 * Returns a boolean value.
7457 */
7458int qc_check_dcid(struct quic_conn *qc, unsigned char *dcid, size_t dcid_len)
7459{
7460 struct ebmb_node *node;
7461 struct quic_connection_id *id;
7462
7463 /* For ODCID, address is concatenated to it after qc.odcid.len so this
7464 * comparison is safe.
7465 */
7466 if ((qc->scid.len == dcid_len &&
7467 memcmp(qc->scid.data, dcid, dcid_len) == 0) ||
7468 (qc->odcid.len == dcid_len &&
7469 memcmp(qc->odcid.data, dcid, dcid_len)) == 0) {
7470 return 1;
7471 }
7472
7473 node = ebmb_lookup(&quic_dghdlrs[tid].cids, dcid, dcid_len);
7474 if (node) {
7475 id = ebmb_entry(node, struct quic_connection_id, node);
7476 if (qc == id->qc)
7477 return 1;
7478 }
7479
7480 return 0;
7481}
7482
Amaury Denoyelle92fa63f2022-09-30 18:11:13 +02007483/* Retrieve the DCID from a QUIC datagram or packet with <buf> as first octet.
7484 * Returns 1 if succeeded, 0 if not.
7485 */
7486int quic_get_dgram_dcid(unsigned char *buf, const unsigned char *end,
7487 unsigned char **dcid, size_t *dcid_len)
7488{
7489 int ret = 0, long_header;
7490 size_t minlen, skip;
7491
7492 TRACE_ENTER(QUIC_EV_CONN_RXPKT);
7493
7494 if (!(*buf & QUIC_PACKET_FIXED_BIT)) {
7495 TRACE_PROTO("fixed bit not set", QUIC_EV_CONN_RXPKT);
7496 goto err;
7497 }
7498
7499 long_header = *buf & QUIC_PACKET_LONG_HEADER_BIT;
7500 minlen = long_header ? QUIC_LONG_PACKET_MINLEN :
7501 QUIC_SHORT_PACKET_MINLEN + QUIC_HAP_CID_LEN + QUIC_TLS_TAG_LEN;
7502 skip = long_header ? QUIC_LONG_PACKET_DCID_OFF : QUIC_SHORT_PACKET_DCID_OFF;
7503 if (end - buf < minlen)
7504 goto err;
7505
7506 buf += skip;
7507 *dcid_len = long_header ? *buf++ : QUIC_HAP_CID_LEN;
7508 if (*dcid_len > QUIC_CID_MAXLEN || end - buf <= *dcid_len)
7509 goto err;
7510
7511 *dcid = buf;
7512
7513 ret = 1;
7514 leave:
7515 TRACE_LEAVE(QUIC_EV_CONN_RXPKT);
7516 return ret;
7517
7518 err:
7519 TRACE_PROTO("wrong datagram", QUIC_EV_CONN_RXPKT);
7520 goto leave;
7521}
7522
7523/* Notify the MUX layer if alive about an imminent close of <qc>. */
7524void qc_notify_close(struct quic_conn *qc)
7525{
7526 TRACE_ENTER(QUIC_EV_CONN_CLOSE, qc);
7527
7528 if (qc->flags & QUIC_FL_CONN_NOTIFY_CLOSE)
7529 goto leave;
7530
7531 qc->flags |= QUIC_FL_CONN_NOTIFY_CLOSE;
7532 /* wake up the MUX */
7533 if (qc->mux_state == QC_MUX_READY && qc->conn->mux->wake) {
7534 TRACE_STATE("connection closure notidfied to mux",
7535 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7536 qc->conn->mux->wake(qc->conn);
7537 }
7538 else
7539 TRACE_STATE("connection closure not notidfied to mux",
7540 QUIC_FL_CONN_NOTIFY_CLOSE, qc);
7541 leave:
7542 TRACE_LEAVE(QUIC_EV_CONN_CLOSE, qc);
7543}
7544
7545/*
7546 * Local variables:
7547 * c-indent-level: 8
7548 * c-basic-offset: 8
7549 * End:
7550 */