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