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