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