blob: 1c8e9de851cb9e353ec40ec1c048a1e60057fccc [file] [log] [blame]
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001/*
2 * QUIC transport layer over SOCK_DGRAM sockets.
3 *
4 * Copyright 2020 HAProxy Technologies, Frédéric Lécaille <flecaille@haproxy.com>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13#define _GNU_SOURCE
14#include <errno.h>
15#include <fcntl.h>
16#include <stdio.h>
17#include <stdlib.h>
18
19#include <sys/socket.h>
20#include <sys/stat.h>
21#include <sys/types.h>
22
23#include <netinet/tcp.h>
24
25#include <haproxy/buf-t.h>
26#include <haproxy/compat.h>
27#include <haproxy/api.h>
28#include <haproxy/debug.h>
29#include <haproxy/tools.h>
30#include <haproxy/ticks.h>
31#include <haproxy/time.h>
32
33#include <haproxy/connection.h>
34#include <haproxy/fd.h>
35#include <haproxy/freq_ctr.h>
36#include <haproxy/global.h>
37#include <haproxy/log.h>
38#include <haproxy/pipe.h>
39#include <haproxy/proxy.h>
40#include <haproxy/quic_cc.h>
41#include <haproxy/quic_frame.h>
42#include <haproxy/quic_loss.h>
43#include <haproxy/quic_tls.h>
44#include <haproxy/ssl_sock.h>
45#include <haproxy/stream_interface.h>
46#include <haproxy/task.h>
47#include <haproxy/trace.h>
48#include <haproxy/xprt_quic.h>
49
50struct quic_transport_params quic_dflt_transport_params = {
51 .max_packet_size = QUIC_DFLT_MAX_PACKET_SIZE,
52 .ack_delay_exponent = QUIC_DFLT_ACK_DELAY_COMPONENT,
53 .max_ack_delay = QUIC_DFLT_MAX_ACK_DELAY,
54};
55
56/* trace source and events */
57static void quic_trace(enum trace_level level, uint64_t mask, \
58 const struct trace_source *src,
59 const struct ist where, const struct ist func,
60 const void *a1, const void *a2, const void *a3, const void *a4);
61
62static const struct trace_event quic_trace_events[] = {
63 { .mask = QUIC_EV_CONN_NEW, .name = "new_conn", .desc = "new QUIC connection" },
64 { .mask = QUIC_EV_CONN_INIT, .name = "new_conn_init", .desc = "new QUIC connection initialization" },
65 { .mask = QUIC_EV_CONN_ISEC, .name = "init_secs", .desc = "initial secrets derivation" },
66 { .mask = QUIC_EV_CONN_RSEC, .name = "read_secs", .desc = "read secrets derivation" },
67 { .mask = QUIC_EV_CONN_WSEC, .name = "write_secs", .desc = "write secrets derivation" },
68 { .mask = QUIC_EV_CONN_LPKT, .name = "lstnr_packet", .desc = "new listener received packet" },
69 { .mask = QUIC_EV_CONN_SPKT, .name = "srv_packet", .desc = "new server received packet" },
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +050070 { .mask = QUIC_EV_CONN_ENCPKT, .name = "enc_hdshk_pkt", .desc = "handhshake packet encryption" },
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +010071 { .mask = QUIC_EV_CONN_HPKT, .name = "hdshk_pkt", .desc = "handhshake packet building" },
72 { .mask = QUIC_EV_CONN_PAPKT, .name = "phdshk_apkt", .desc = "post handhshake application packet preparation" },
73 { .mask = QUIC_EV_CONN_PAPKTS, .name = "phdshk_apkts", .desc = "post handhshake application packets preparation" },
74 { .mask = QUIC_EV_CONN_HDSHK, .name = "hdshk", .desc = "SSL handhshake processing" },
75 { .mask = QUIC_EV_CONN_RMHP, .name = "rm_hp", .desc = "Remove header protection" },
76 { .mask = QUIC_EV_CONN_PRSHPKT, .name = "parse_hpkt", .desc = "parse handshake packet" },
77 { .mask = QUIC_EV_CONN_PRSAPKT, .name = "parse_apkt", .desc = "parse application packet" },
78 { .mask = QUIC_EV_CONN_PRSFRM, .name = "parse_frm", .desc = "parse frame" },
79 { .mask = QUIC_EV_CONN_PRSAFRM, .name = "parse_ack_frm", .desc = "parse ACK frame" },
80 { .mask = QUIC_EV_CONN_BFRM, .name = "build_frm", .desc = "build frame" },
81 { .mask = QUIC_EV_CONN_PHPKTS, .name = "phdshk_pkts", .desc = "handhshake packets preparation" },
82 { .mask = QUIC_EV_CONN_TRMHP, .name = "rm_hp_try", .desc = "header protection removing try" },
83 { .mask = QUIC_EV_CONN_ELRMHP, .name = "el_rm_hp", .desc = "handshake enc. level header protection removing" },
84 { .mask = QUIC_EV_CONN_ELRXPKTS, .name = "el_treat_rx_pkts", .desc = "handshake enc. level rx packets treatment" },
85 { .mask = QUIC_EV_CONN_SSLDATA, .name = "ssl_provide_data", .desc = "CRYPTO data provision to TLS stack" },
86 { .mask = QUIC_EV_CONN_RXCDATA, .name = "el_treat_rx_cfrms",.desc = "enc. level RX CRYPTO frames processing"},
87 { .mask = QUIC_EV_CONN_ADDDATA, .name = "add_hdshk_data", .desc = "TLS stack ->add_handshake_data() call"},
88 { .mask = QUIC_EV_CONN_FFLIGHT, .name = "flush_flight", .desc = "TLS stack ->flush_flight() call"},
89 { .mask = QUIC_EV_CONN_SSLALERT, .name = "send_alert", .desc = "TLS stack ->send_alert() call"},
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +010090 { .mask = QUIC_EV_CONN_RTTUPDT, .name = "rtt_updt", .desc = "RTT sampling" },
91 { .mask = QUIC_EV_CONN_SPPKTS, .name = "sppkts", .desc = "send prepared packets" },
92 { .mask = QUIC_EV_CONN_PKTLOSS, .name = "pktloss", .desc = "detect packet loss" },
93 { .mask = QUIC_EV_CONN_STIMER, .name = "stimer", .desc = "set timer" },
94 { .mask = QUIC_EV_CONN_PTIMER, .name = "ptimer", .desc = "process timer" },
95 { .mask = QUIC_EV_CONN_SPTO, .name = "spto", .desc = "set PTO" },
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +010096 { .mask = QUIC_EV_CONN_BCFRMS, .name = "bcfrms", .desc = "build CRYPTO data frames" },
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +010097 { /* end */ }
98};
99
100static const struct name_desc quic_trace_lockon_args[4] = {
101 /* arg1 */ { /* already used by the connection */ },
102 /* arg2 */ { .name="quic", .desc="QUIC transport" },
103 /* arg3 */ { },
104 /* arg4 */ { }
105};
106
107static const struct name_desc quic_trace_decoding[] = {
108#define QUIC_VERB_CLEAN 1
109 { .name="clean", .desc="only user-friendly stuff, generally suitable for level \"user\"" },
110 { /* end */ }
111};
112
113
114struct trace_source trace_quic = {
115 .name = IST("quic"),
116 .desc = "QUIC xprt",
117 .arg_def = TRC_ARG1_CONN, /* TRACE()'s first argument is always a connection */
118 .default_cb = quic_trace,
119 .known_events = quic_trace_events,
120 .lockon_args = quic_trace_lockon_args,
121 .decoding = quic_trace_decoding,
122 .report_events = ~0, /* report everything by default */
123};
124
125#define TRACE_SOURCE &trace_quic
126INITCALL1(STG_REGISTER, trace_register_source, TRACE_SOURCE);
127
128static BIO_METHOD *ha_quic_meth;
129
130/* QUIC xprt connection context. */
131struct quic_conn_ctx {
132 struct connection *conn;
133 SSL *ssl;
134 BIO *bio;
135 int state;
136 const struct xprt_ops *xprt;
137 void *xprt_ctx;
138 struct wait_event wait_event;
139 struct wait_event *subs;
140};
141
142DECLARE_STATIC_POOL(pool_head_quic_conn_ctx,
143 "quic_conn_ctx_pool", sizeof(struct quic_conn_ctx));
144
145DECLARE_STATIC_POOL(pool_head_quic_conn, "quic_conn", sizeof(struct quic_conn));
146
147DECLARE_POOL(pool_head_quic_connection_id,
148 "quic_connnection_id_pool", sizeof(struct quic_connection_id));
149
150DECLARE_POOL(pool_head_quic_rx_packet, "quic_rx_packet_pool", sizeof(struct quic_rx_packet));
151
152DECLARE_POOL(pool_head_quic_tx_packet, "quic_tx_packet_pool", sizeof(struct quic_tx_packet));
153
154DECLARE_STATIC_POOL(pool_head_quic_rx_crypto_frm, "quic_rx_crypto_frm_pool", sizeof(struct quic_rx_crypto_frm));
155
156DECLARE_POOL(pool_head_quic_tx_frm, "quic_tx_frm_pool", sizeof(struct quic_tx_frm));
157
158DECLARE_STATIC_POOL(pool_head_quic_crypto_buf, "quic_crypto_buf_pool", sizeof(struct quic_crypto_buf));
159
160DECLARE_STATIC_POOL(pool_head_quic_frame, "quic_frame_pool", sizeof(struct quic_frame));
161
Frédéric Lécaille8090b512020-11-30 16:19:22 +0100162DECLARE_STATIC_POOL(pool_head_quic_arng, "quic_arng_pool", sizeof(struct quic_arng_node));
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100163
164static ssize_t qc_build_hdshk_pkt(struct q_buf *buf, struct quic_conn *qc, int pkt_type,
165 struct quic_enc_level *qel);
166
167int qc_prep_phdshk_pkts(struct quic_conn *qc);
168
169/* Add traces to <buf> depending on <frm> TX frame type. */
170static inline void chunk_tx_frm_appendf(struct buffer *buf,
171 const struct quic_tx_frm *frm)
172{
173 switch (frm->type) {
174 case QUIC_FT_CRYPTO:
175 chunk_appendf(buf, " cfoff=%llu cflen=%llu",
176 (unsigned long long)frm->crypto.offset,
177 (unsigned long long)frm->crypto.len);
178 break;
179 default:
180 chunk_appendf(buf, " %s", quic_frame_type_string(frm->type));
181 }
182}
183
Frédéric Lécaillef63921f2020-12-18 09:48:20 +0100184/* Only for debug purpose */
185struct enc_debug_info {
186 unsigned char *payload;
187 size_t payload_len;
188 unsigned char *aad;
189 size_t aad_len;
190 uint64_t pn;
191};
192
193/* Initializes a enc_debug_info struct (only for debug purpose) */
194static inline void enc_debug_info_init(struct enc_debug_info *edi,
195 unsigned char *payload, size_t payload_len,
196 unsigned char *aad, size_t aad_len, uint64_t pn)
197{
198 edi->payload = payload;
199 edi->payload_len = payload_len;
200 edi->aad = aad;
201 edi->aad_len = aad_len;
202 edi->pn = pn;
203}
204
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100205/* Trace callback for QUIC.
206 * These traces always expect that arg1, if non-null, is of type connection.
207 */
208static void quic_trace(enum trace_level level, uint64_t mask, const struct trace_source *src,
209 const struct ist where, const struct ist func,
210 const void *a1, const void *a2, const void *a3, const void *a4)
211{
212 const struct connection *conn = a1;
213
214 if (conn) {
215 struct quic_tls_secrets *secs;
216 struct quic_conn *qc;
217
218 qc = conn->qc;
219 chunk_appendf(&trace_buf, " : conn@%p", conn);
220 if ((mask & QUIC_EV_CONN_INIT) && qc) {
221 chunk_appendf(&trace_buf, "\n odcid");
222 quic_cid_dump(&trace_buf, &qc->odcid);
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +0100223 chunk_appendf(&trace_buf, "\n dcid");
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100224 quic_cid_dump(&trace_buf, &qc->dcid);
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +0100225 chunk_appendf(&trace_buf, "\n scid");
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100226 quic_cid_dump(&trace_buf, &qc->scid);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100227 }
228
229 if (mask & QUIC_EV_CONN_ADDDATA) {
230 const enum ssl_encryption_level_t *level = a2;
231 const size_t *len = a3;
232
233 if (level) {
234 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
235
236 chunk_appendf(&trace_buf, " el=%c(%d)", quic_enc_level_char(lvl), lvl);
237 }
238 if (len)
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100239 chunk_appendf(&trace_buf, " len=%llu", (unsigned long long)*len);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100240 }
241 if ((mask & QUIC_EV_CONN_ISEC) && qc) {
242 /* Initial read & write secrets. */
243 enum quic_tls_enc_level level = QUIC_TLS_ENC_LEVEL_INITIAL;
244 const unsigned char *rx_sec = a2;
245 const unsigned char *tx_sec = a3;
246
247 secs = &qc->els[level].tls_ctx.rx;
248 if (secs->flags & QUIC_FL_TLS_SECRETS_SET) {
249 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(level));
250 if (rx_sec)
251 quic_tls_secret_hexdump(&trace_buf, rx_sec, 32);
252 quic_tls_keys_hexdump(&trace_buf, secs);
253 }
254 secs = &qc->els[level].tls_ctx.tx;
255 if (secs->flags & QUIC_FL_TLS_SECRETS_SET) {
256 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(level));
257 if (tx_sec)
258 quic_tls_secret_hexdump(&trace_buf, tx_sec, 32);
259 quic_tls_keys_hexdump(&trace_buf, secs);
260 }
261 }
262 if (mask & (QUIC_EV_CONN_RSEC|QUIC_EV_CONN_RWSEC)) {
263 const enum ssl_encryption_level_t *level = a2;
264 const unsigned char *secret = a3;
265 const size_t *secret_len = a4;
266
267 if (level) {
268 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
269
270 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(lvl));
271 if (secret && secret_len)
272 quic_tls_secret_hexdump(&trace_buf, secret, *secret_len);
273 secs = &qc->els[lvl].tls_ctx.rx;
274 if (secs->flags & QUIC_FL_TLS_SECRETS_SET)
275 quic_tls_keys_hexdump(&trace_buf, secs);
276 }
277 }
278
279 if (mask & (QUIC_EV_CONN_WSEC|QUIC_EV_CONN_RWSEC)) {
280 const enum ssl_encryption_level_t *level = a2;
281 const unsigned char *secret = a3;
282 const size_t *secret_len = a4;
283
284 if (level) {
285 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
286
287 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(lvl));
288 if (secret && secret_len)
289 quic_tls_secret_hexdump(&trace_buf, secret, *secret_len);
290 secs = &qc->els[lvl].tls_ctx.tx;
291 if (secs->flags & QUIC_FL_TLS_SECRETS_SET)
292 quic_tls_keys_hexdump(&trace_buf, secs);
293 }
294
295 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100296
Frédéric Lécaille133e8a72020-12-18 09:33:27 +0100297 if (mask & (QUIC_EV_CONN_HPKT|QUIC_EV_CONN_PAPKT)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100298 const struct quic_tx_packet *pkt = a2;
299 const struct quic_enc_level *qel = a3;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100300 const ssize_t *room = a4;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100301
302 if (qel) {
303 struct quic_pktns *pktns;
304
305 pktns = qc->pktns;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100306 chunk_appendf(&trace_buf, " qel=%c cwnd=%llu ppif=%lld pif=%llu "
307 "if=%llu pp=%u pdg=%d",
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100308 quic_enc_level_char_from_qel(qel, qc),
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100309 (unsigned long long)qc->path->cwnd,
310 (unsigned long long)qc->path->prep_in_flight,
311 (unsigned long long)qc->path->in_flight,
312 (unsigned long long)pktns->tx.in_flight,
313 pktns->tx.pto_probe, qc->tx.nb_pto_dgrams);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100314 }
315 if (pkt) {
316 const struct quic_tx_frm *frm;
317 chunk_appendf(&trace_buf, " pn=%llu cdlen=%u",
318 (unsigned long long)pkt->pn_node.key, pkt->cdata_len);
319 list_for_each_entry(frm, &pkt->frms, list)
320 chunk_tx_frm_appendf(&trace_buf, frm);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100321 chunk_appendf(&trace_buf, " tx.bytes=%llu", (unsigned long long)qc->tx.bytes);
322 }
323
324 if (room) {
325 chunk_appendf(&trace_buf, " room=%lld", (long long)*room);
326 chunk_appendf(&trace_buf, " dcid.len=%llu scid.len=%llu",
327 (unsigned long long)qc->dcid.len, (unsigned long long)qc->scid.len);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100328 }
329 }
330
331 if (mask & QUIC_EV_CONN_HDSHK) {
332 const enum quic_handshake_state *state = a2;
333 const int *err = a3;
334
335 if (state)
336 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(*state));
337 if (err)
338 chunk_appendf(&trace_buf, " err=%s", ssl_error_str(*err));
339 }
340
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +0100341 if (mask & (QUIC_EV_CONN_TRMHP|QUIC_EV_CONN_ELRMHP|QUIC_EV_CONN_SPKT)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100342 const struct quic_rx_packet *pkt = a2;
343 const unsigned long *pktlen = a3;
344 const SSL *ssl = a4;
345
346 if (pkt) {
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +0100347 chunk_appendf(&trace_buf, " pkt@%p el=%c",
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100348 pkt, quic_packet_type_enc_level_char(pkt->type));
349 if (pkt->pnl)
350 chunk_appendf(&trace_buf, " pnl=%u pn=%llu", pkt->pnl,
351 (unsigned long long)pkt->pn);
352 if (pkt->token_len)
353 chunk_appendf(&trace_buf, " toklen=%llu",
354 (unsigned long long)pkt->token_len);
355 if (pkt->aad_len)
356 chunk_appendf(&trace_buf, " aadlen=%llu",
357 (unsigned long long)pkt->aad_len);
358 chunk_appendf(&trace_buf, " flags=0x%x len=%llu",
359 pkt->flags, (unsigned long long)pkt->len);
360 }
361 if (pktlen)
362 chunk_appendf(&trace_buf, " (%ld)", *pktlen);
363 if (ssl) {
364 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
365 chunk_appendf(&trace_buf, " el=%c",
366 quic_enc_level_char(ssl_to_quic_enc_level(level)));
367 }
368 }
369
370 if (mask & (QUIC_EV_CONN_ELRXPKTS|QUIC_EV_CONN_PRSHPKT|QUIC_EV_CONN_SSLDATA)) {
371 const struct quic_rx_packet *pkt = a2;
372 const struct quic_rx_crypto_frm *cf = a3;
373 const SSL *ssl = a4;
374
375 if (pkt)
376 chunk_appendf(&trace_buf, " pkt@%p el=%c pn=%llu", pkt,
377 quic_packet_type_enc_level_char(pkt->type),
378 (unsigned long long)pkt->pn);
379 if (cf)
380 chunk_appendf(&trace_buf, " cfoff=%llu cflen=%llu",
381 (unsigned long long)cf->offset_node.key,
382 (unsigned long long)cf->len);
383 if (ssl) {
384 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
385 chunk_appendf(&trace_buf, " el=%c",
386 quic_enc_level_char(ssl_to_quic_enc_level(level)));
387 }
388 }
389
390 if (mask & (QUIC_EV_CONN_PRSFRM|QUIC_EV_CONN_BFRM)) {
391 const struct quic_frame *frm = a2;
392
393 if (frm)
394 chunk_appendf(&trace_buf, " %s", quic_frame_type_string(frm->type));
395 }
396
397 if (mask & QUIC_EV_CONN_PHPKTS) {
398 const struct quic_enc_level *qel = a2;
399
400 if (qel) {
401 struct quic_pktns *pktns;
402
403 pktns = qc->pktns;
404 chunk_appendf(&trace_buf,
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100405 " qel=%c ack?%d cwnd=%llu ppif=%lld pif=%llu if=%llu pp=%u pdg=%llu",
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100406 quic_enc_level_char_from_qel(qel, qc),
407 !!(pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED),
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100408 (unsigned long long)qc->path->cwnd,
409 (unsigned long long)qc->path->prep_in_flight,
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100410 (unsigned long long)qc->path->in_flight,
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100411 (unsigned long long)pktns->tx.in_flight, pktns->tx.pto_probe,
412 (unsigned long long)qc->tx.nb_pto_dgrams);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100413 }
414 }
415
Frédéric Lécaillef63921f2020-12-18 09:48:20 +0100416 if (mask & QUIC_EV_CONN_ENCPKT) {
417 const struct enc_debug_info *edi = a2;
418
419 if (edi)
420 chunk_appendf(&trace_buf,
421 " payload=@%p payload_len=%llu"
422 " aad=@%p aad_len=%llu pn=%llu",
423 edi->payload, (unsigned long long)edi->payload_len,
424 edi->aad, (unsigned long long)edi->aad_len,
425 (unsigned long long)edi->pn);
426 }
427
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100428 if (mask & QUIC_EV_CONN_RMHP) {
429 const struct quic_rx_packet *pkt = a2;
430
431 if (pkt) {
432 const int *ret = a3;
433
434 chunk_appendf(&trace_buf, " pkt@%p", pkt);
435 if (ret && *ret)
436 chunk_appendf(&trace_buf, " pnl=%u pn=%llu",
437 pkt->pnl, (unsigned long long)pkt->pn);
438 }
439 }
440
441 if (mask & QUIC_EV_CONN_PRSAFRM) {
442 const struct quic_tx_frm *frm = a2;
443 const unsigned long *val1 = a3;
444 const unsigned long *val2 = a4;
445
446 if (frm)
447 chunk_tx_frm_appendf(&trace_buf, frm);
448 if (val1)
449 chunk_appendf(&trace_buf, " %lu", *val1);
450 if (val2)
451 chunk_appendf(&trace_buf, "..%lu", *val2);
452 }
453
454 if (mask & QUIC_EV_CONN_RTTUPDT) {
455 const unsigned int *rtt_sample = a2;
456 const unsigned int *ack_delay = a3;
457 const struct quic_loss *ql = a4;
458
459 if (rtt_sample)
460 chunk_appendf(&trace_buf, " rtt_sample=%ums", *rtt_sample);
461 if (ack_delay)
462 chunk_appendf(&trace_buf, " ack_delay=%ums", *ack_delay);
463 if (ql)
464 chunk_appendf(&trace_buf,
465 " srtt=%ums rttvar=%ums min_rtt=%ums",
466 ql->srtt >> 3, ql->rtt_var >> 2, ql->rtt_min);
467 }
468 if (mask & QUIC_EV_CONN_CC) {
469 const struct quic_cc_event *ev = a2;
470 const struct quic_cc *cc = a3;
471
472 if (a2)
473 quic_cc_event_trace(&trace_buf, ev);
474 if (a3)
475 quic_cc_state_trace(&trace_buf, cc);
476 }
477
478 if (mask & QUIC_EV_CONN_PKTLOSS) {
479 const struct quic_pktns *pktns = a2;
480 const struct list *lost_pkts = a3;
481 struct quic_conn *qc = conn->qc;
482
483 if (pktns) {
484 chunk_appendf(&trace_buf, " pktns=%s",
485 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
486 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H");
487 if (pktns->tx.loss_time)
488 chunk_appendf(&trace_buf, " loss_time=%dms",
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100489 TICKS_TO_MS(tick_remain(now_ms, pktns->tx.loss_time)));
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100490 }
491 if (lost_pkts && !LIST_ISEMPTY(lost_pkts)) {
492 struct quic_tx_packet *pkt;
493
494 chunk_appendf(&trace_buf, " lost_pkts:");
495 list_for_each_entry(pkt, lost_pkts, list)
496 chunk_appendf(&trace_buf, " %lu", (unsigned long)pkt->pn_node.key);
497 }
498 }
499
500 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_PTIMER|QUIC_EV_CONN_SPTO)) {
501 struct quic_conn *qc = conn->qc;
502 const struct quic_pktns *pktns = a2;
503 const int *duration = a3;
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100504 const uint64_t *ifae_pkts = a4;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100505
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100506 if (ifae_pkts)
507 chunk_appendf(&trace_buf, " ifae_pkts=%llu",
508 (unsigned long long)*ifae_pkts);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100509 if (pktns) {
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100510 chunk_appendf(&trace_buf, " pktns=%s pp=%d",
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100511 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100512 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
513 pktns->tx.pto_probe);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100514 if (mask & QUIC_EV_CONN_STIMER) {
515 if (pktns->tx.loss_time)
516 chunk_appendf(&trace_buf, " loss_time=%dms",
517 TICKS_TO_MS(pktns->tx.loss_time - now_ms));
518 }
519 if (mask & QUIC_EV_CONN_SPTO) {
520 if (pktns->tx.time_of_last_eliciting)
521 chunk_appendf(&trace_buf, " tole=%dms",
522 TICKS_TO_MS(pktns->tx.time_of_last_eliciting - now_ms));
523 if (duration)
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +0100524 chunk_appendf(&trace_buf, " dur=%dms", TICKS_TO_MS(*duration));
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100525 }
526 }
527
528 if (!(mask & QUIC_EV_CONN_SPTO) && qc->timer_task) {
529 chunk_appendf(&trace_buf,
530 " expire=%dms", TICKS_TO_MS(qc->timer - now_ms));
531 }
532 }
533
534 if (mask & QUIC_EV_CONN_SPPKTS) {
535 const struct quic_tx_packet *pkt = a2;
536
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100537 chunk_appendf(&trace_buf, " cwnd=%llu ppif=%llu pif=%llu",
538 (unsigned long long)qc->path->cwnd,
539 (unsigned long long)qc->path->prep_in_flight,
540 (unsigned long long)qc->path->in_flight);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100541 if (pkt) {
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100542 chunk_appendf(&trace_buf, " pn=%lu(%s) iflen=%llu cdlen=%llu",
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100543 (unsigned long)pkt->pn_node.key,
544 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
545 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100546 (unsigned long long)pkt->in_flight_len,
547 (unsigned long long)pkt->cdata_len);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100548 }
549 }
Frédéric Lécaille47c433f2020-12-10 17:03:11 +0100550
551 if (mask & QUIC_EV_CONN_SSLALERT) {
552 const uint8_t *alert = a2;
553 const enum ssl_encryption_level_t *level = a3;
554
555 if (alert)
556 chunk_appendf(&trace_buf, " alert=0x%02x", *alert);
557 if (level)
558 chunk_appendf(&trace_buf, " el=%c",
559 quic_enc_level_char(ssl_to_quic_enc_level(*level)));
560 }
Frédéric Lécailleea604992020-12-24 13:01:37 +0100561
562 if (mask & QUIC_EV_CONN_BCFRMS) {
563 const size_t *sz1 = a2;
564 const size_t *sz2 = a3;
565 const size_t *sz3 = a4;
566
567 if (sz1)
568 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz1);
569 if (sz2)
570 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz2);
571 if (sz3)
572 chunk_appendf(&trace_buf, " %llu", (unsigned long long)*sz3);
573 }
Frédéric Lécaille242fb1b2020-12-31 12:45:38 +0100574
575 if (mask & QUIC_EV_CONN_PSTRM) {
576 const struct quic_frame *frm = a2;
Frédéric Lécaille577fe482021-01-11 15:10:06 +0100577
578 if (a2) {
579 const struct quic_stream *s = &frm->stream;
Frédéric Lécaille242fb1b2020-12-31 12:45:38 +0100580
Frédéric Lécaille577fe482021-01-11 15:10:06 +0100581 chunk_appendf(&trace_buf, " uni=%d fin=%d id=%llu off=%llu len=%llu",
582 !!(s->id & QUIC_STREAM_FRAME_ID_DIR_BIT),
583 !!(frm->type & QUIC_STREAM_FRAME_TYPE_FIN_BIT),
584 (unsigned long long)s->id,
585 (unsigned long long)s->offset,
586 (unsigned long long)s->len);
587 }
Frédéric Lécaille242fb1b2020-12-31 12:45:38 +0100588 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100589 }
590 if (mask & QUIC_EV_CONN_LPKT) {
591 const struct quic_rx_packet *pkt = a2;
592
593 if (conn)
594 chunk_appendf(&trace_buf, " xprt_ctx@%p", conn->xprt_ctx);
595 if (pkt)
596 chunk_appendf(&trace_buf, " type=0x%02x %s",
597 pkt->type, qc_pkt_long(pkt) ? "long" : "short");
598 }
599
600}
601
602/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
603static inline int quic_peer_validated_addr(struct quic_conn_ctx *ctx)
604{
605 struct quic_conn *qc;
606
607 qc = ctx->conn->qc;
608 if (objt_server(qc->conn->target))
609 return 1;
610
611 if ((qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_RECEIVED) ||
612 (qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns->flags & QUIC_FL_PKTNS_ACK_RECEIVED) ||
613 (ctx->state & QUIC_HS_ST_COMPLETE))
614 return 1;
615
616 return 0;
617}
618
619/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
620 * both loss detection and PTO and schedule the task assiated to this timer if needed.
621 */
622static inline void qc_set_timer(struct quic_conn_ctx *ctx)
623{
624 struct quic_conn *qc;
625 struct quic_pktns *pktns;
626 unsigned int pto;
627
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100628 TRACE_ENTER(QUIC_EV_CONN_STIMER, ctx->conn,
629 NULL, NULL, &ctx->conn->qc->path->ifae_pkts);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100630 qc = ctx->conn->qc;
631 pktns = quic_loss_pktns(qc);
632 if (tick_isset(pktns->tx.loss_time)) {
633 qc->timer = pktns->tx.loss_time;
634 goto out;
635 }
636
637 /* XXX TODO: anti-amplification: the timer must be
638 * cancelled for a server which reached the anti-amplification limit.
639 */
640
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100641 if (!qc->path->ifae_pkts && quic_peer_validated_addr(ctx)) {
642 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, ctx->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100643 /* Timer cancellation. */
644 qc->timer = TICK_ETERNITY;
645 goto out;
646 }
647
648 pktns = quic_pto_pktns(qc, ctx->state & QUIC_HS_ST_COMPLETE, &pto);
649 if (tick_isset(pto))
650 qc->timer = pto;
651 out:
652 task_schedule(qc->timer_task, qc->timer);
653 TRACE_LEAVE(QUIC_EV_CONN_STIMER, ctx->conn, pktns);
654}
655
656#ifndef OPENSSL_IS_BORINGSSL
657int ha_quic_set_encryption_secrets(SSL *ssl, enum ssl_encryption_level_t level,
658 const uint8_t *read_secret,
659 const uint8_t *write_secret, size_t secret_len)
660{
661 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
662 struct quic_tls_ctx *tls_ctx =
663 &conn->qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
664 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
665
666 TRACE_ENTER(QUIC_EV_CONN_RWSEC, conn);
667 tls_ctx->rx.aead = tls_ctx->tx.aead = tls_aead(cipher);
668 tls_ctx->rx.md = tls_ctx->tx.md = tls_md(cipher);
669 tls_ctx->rx.hp = tls_ctx->tx.hp = tls_hp(cipher);
670
671 if (!quic_tls_derive_keys(tls_ctx->rx.aead, tls_ctx->rx.hp, tls_ctx->rx.md,
672 tls_ctx->rx.key, sizeof tls_ctx->rx.key,
673 tls_ctx->rx.iv, sizeof tls_ctx->rx.iv,
674 tls_ctx->rx.hp_key, sizeof tls_ctx->rx.hp_key,
675 read_secret, secret_len)) {
676 TRACE_DEVEL("RX key derivation failed", QUIC_EV_CONN_RWSEC, conn);
677 return 0;
678 }
679
680 tls_ctx->rx.flags |= QUIC_FL_TLS_SECRETS_SET;
681 if (!quic_tls_derive_keys(tls_ctx->tx.aead, tls_ctx->tx.hp, tls_ctx->tx.md,
682 tls_ctx->tx.key, sizeof tls_ctx->tx.key,
683 tls_ctx->tx.iv, sizeof tls_ctx->tx.iv,
684 tls_ctx->tx.hp_key, sizeof tls_ctx->tx.hp_key,
685 write_secret, secret_len)) {
686 TRACE_DEVEL("TX key derivation failed", QUIC_EV_CONN_RWSEC, conn);
687 return 0;
688 }
689
690 tls_ctx->tx.flags |= QUIC_FL_TLS_SECRETS_SET;
691 if (objt_server(conn->target) && level == ssl_encryption_application) {
692 const unsigned char *buf;
693 size_t buflen;
694
695 SSL_get_peer_quic_transport_params(ssl, &buf, &buflen);
696 if (!buflen)
697 return 0;
698
699 if (!quic_transport_params_store(conn->qc, 1, buf, buf + buflen))
700 return 0;
701 }
702 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, conn, &level);
703
704 return 1;
705}
706#else
707/* ->set_read_secret callback to derive the RX secrets at <level> encryption
708 * level.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +0500709 * Returns 1 if succeeded, 0 if not.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100710 */
711int ha_set_rsec(SSL *ssl, enum ssl_encryption_level_t level,
712 const SSL_CIPHER *cipher,
713 const uint8_t *secret, size_t secret_len)
714{
715 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
716 struct quic_tls_ctx *tls_ctx =
717 &conn->qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
718
719 TRACE_ENTER(QUIC_EV_CONN_RSEC, conn);
720 tls_ctx->rx.aead = tls_aead(cipher);
721 tls_ctx->rx.md = tls_md(cipher);
722 tls_ctx->rx.hp = tls_hp(cipher);
723
724 if (!quic_tls_derive_keys(tls_ctx->rx.aead, tls_ctx->rx.hp, tls_ctx->rx.md,
725 tls_ctx->rx.key, sizeof tls_ctx->rx.key,
726 tls_ctx->rx.iv, sizeof tls_ctx->rx.iv,
727 tls_ctx->rx.hp_key, sizeof tls_ctx->rx.hp_key,
728 secret, secret_len)) {
729 TRACE_DEVEL("RX key derivation failed", QUIC_EV_CONN_RSEC, conn);
730 goto err;
731 }
732
733 if (objt_server(conn->target) && level == ssl_encryption_application) {
734 const unsigned char *buf;
735 size_t buflen;
736
737 SSL_get_peer_quic_transport_params(ssl, &buf, &buflen);
738 if (!buflen)
739 goto err;
740
741 if (!quic_transport_params_store(conn->qc, 1, buf, buf + buflen))
742 goto err;
743 }
744
745 tls_ctx->rx.flags |= QUIC_FL_TLS_SECRETS_SET;
746 TRACE_LEAVE(QUIC_EV_CONN_RSEC, conn, &level, secret, &secret_len);
747
748 return 1;
749
750 err:
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +0100751 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_RSEC, conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100752 return 0;
753}
754
755/* ->set_write_secret callback to derive the TX secrets at <level>
756 * encryption level.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +0500757 * Returns 1 if succeeded, 0 if not.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100758 */
759int ha_set_wsec(SSL *ssl, enum ssl_encryption_level_t level,
760 const SSL_CIPHER *cipher,
761 const uint8_t *secret, size_t secret_len)
762{
763 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
764 struct quic_tls_ctx *tls_ctx =
765 &conn->qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
766
767 TRACE_ENTER(QUIC_EV_CONN_WSEC, conn);
768 tls_ctx->tx.aead = tls_aead(cipher);
769 tls_ctx->tx.md = tls_md(cipher);
770 tls_ctx->tx.hp = tls_hp(cipher);
771
772 if (!quic_tls_derive_keys(tls_ctx->tx.aead, tls_ctx->tx.hp, tls_ctx->tx.md,
773 tls_ctx->tx.key, sizeof tls_ctx->tx.key,
774 tls_ctx->tx.iv, sizeof tls_ctx->tx.iv,
775 tls_ctx->tx.hp_key, sizeof tls_ctx->tx.hp_key,
776 secret, secret_len)) {
777 TRACE_DEVEL("TX key derivation failed", QUIC_EV_CONN_WSEC, conn);
778 goto err;
779 }
780
781 tls_ctx->tx.flags |= QUIC_FL_TLS_SECRETS_SET;
782 TRACE_LEAVE(QUIC_EV_CONN_WSEC, conn, &level, secret, &secret_len);
783
784 return 1;
785
786 err:
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +0100787 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_WSEC, conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100788 return 0;
789}
790#endif
791
792/* This function copies the CRYPTO data provided by the TLS stack found at <data>
793 * with <len> as size in CRYPTO buffers dedicated to store the information about
794 * outgoing CRYPTO frames so that to be able to replay the CRYPTO data streams.
795 * It fails only if it could not managed to allocate enough CRYPTO buffers to
796 * store all the data.
797 * Note that CRYPTO data may exist at any encryption level except at 0-RTT.
798 */
799static int quic_crypto_data_cpy(struct quic_enc_level *qel,
800 const unsigned char *data, size_t len)
801{
802 struct quic_crypto_buf **qcb;
803 /* The remaining byte to store in CRYPTO buffers. */
804 size_t cf_offset, cf_len, *nb_buf;
805 unsigned char *pos;
806
807 nb_buf = &qel->tx.crypto.nb_buf;
808 qcb = &qel->tx.crypto.bufs[*nb_buf - 1];
809 cf_offset = (*nb_buf - 1) * QUIC_CRYPTO_BUF_SZ + (*qcb)->sz;
810 cf_len = len;
811
812 while (len) {
813 size_t to_copy, room;
814
815 pos = (*qcb)->data + (*qcb)->sz;
816 room = QUIC_CRYPTO_BUF_SZ - (*qcb)->sz;
817 to_copy = len > room ? room : len;
818 if (to_copy) {
819 memcpy(pos, data, to_copy);
820 /* Increment the total size of this CRYPTO buffers by <to_copy>. */
821 qel->tx.crypto.sz += to_copy;
822 (*qcb)->sz += to_copy;
823 pos += to_copy;
824 len -= to_copy;
825 data += to_copy;
826 }
827 else {
828 struct quic_crypto_buf **tmp;
829
830 tmp = realloc(qel->tx.crypto.bufs,
831 (*nb_buf + 1) * sizeof *qel->tx.crypto.bufs);
832 if (tmp) {
833 qel->tx.crypto.bufs = tmp;
834 qcb = &qel->tx.crypto.bufs[*nb_buf];
835 *qcb = pool_alloc(pool_head_quic_crypto_buf);
836 if (!*qcb)
837 return 0;
838
839 (*qcb)->sz = 0;
840 ++*nb_buf;
841 }
842 else {
843 break;
844 }
845 }
846 }
847
848 /* Allocate a TX CRYPTO frame only if all the CRYPTO data
849 * have been buffered.
850 */
851 if (!len) {
852 struct quic_tx_frm *frm;
853
854 frm = pool_alloc(pool_head_quic_tx_frm);
855 if (!frm)
856 return 0;
857
858 frm->type = QUIC_FT_CRYPTO;
859 frm->crypto.offset = cf_offset;
860 frm->crypto.len = cf_len;
Willy Tarreau2b718102021-04-21 07:32:39 +0200861 LIST_APPEND(&qel->pktns->tx.frms, &frm->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100862 }
863
864 return len == 0;
865}
866
867
868/* ->add_handshake_data QUIC TLS callback used by the QUIC TLS stack when it
869 * wants to provide the QUIC layer with CRYPTO data.
870 * Returns 1 if succeeded, 0 if not.
871 */
872int ha_quic_add_handshake_data(SSL *ssl, enum ssl_encryption_level_t level,
873 const uint8_t *data, size_t len)
874{
875 struct connection *conn;
876 enum quic_tls_enc_level tel;
877 struct quic_enc_level *qel;
878
879 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
880 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, conn);
881 tel = ssl_to_quic_enc_level(level);
882 qel = &conn->qc->els[tel];
883
884 if (tel == -1) {
885 TRACE_PROTO("Wrong encryption level", QUIC_EV_CONN_ADDDATA, conn);
886 goto err;
887 }
888
889 if (!quic_crypto_data_cpy(qel, data, len)) {
890 TRACE_PROTO("Could not bufferize", QUIC_EV_CONN_ADDDATA, conn);
891 goto err;
892 }
893
894 TRACE_PROTO("CRYPTO data buffered", QUIC_EV_CONN_ADDDATA,
895 conn, &level, &len);
896
897 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, conn);
898 return 1;
899
900 err:
901 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_ADDDATA, conn);
902 return 0;
903}
904
905int ha_quic_flush_flight(SSL *ssl)
906{
907 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
908
909 TRACE_ENTER(QUIC_EV_CONN_FFLIGHT, conn);
910 TRACE_LEAVE(QUIC_EV_CONN_FFLIGHT, conn);
911
912 return 1;
913}
914
915int ha_quic_send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
916{
917 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
918
Frédéric Lécaille47c433f2020-12-10 17:03:11 +0100919 TRACE_DEVEL("SSL alert", QUIC_EV_CONN_SSLALERT, conn, &alert, &level);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100920 return 1;
921}
922
923/* QUIC TLS methods */
924static SSL_QUIC_METHOD ha_quic_method = {
925#ifdef OPENSSL_IS_BORINGSSL
926 .set_read_secret = ha_set_rsec,
927 .set_write_secret = ha_set_wsec,
928#else
929 .set_encryption_secrets = ha_quic_set_encryption_secrets,
930#endif
931 .add_handshake_data = ha_quic_add_handshake_data,
932 .flush_flight = ha_quic_flush_flight,
933 .send_alert = ha_quic_send_alert,
934};
935
936/* Initialize the TLS context of a listener with <bind_conf> as configuration.
937 * Returns an error count.
938 */
939int ssl_quic_initial_ctx(struct bind_conf *bind_conf)
940{
941 struct proxy *curproxy = bind_conf->frontend;
942 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
943 int cfgerr = 0;
944
945#if 0
946 /* XXX Did not manage to use this. */
947 const char *ciphers =
948 "TLS_AES_128_GCM_SHA256:"
949 "TLS_AES_256_GCM_SHA384:"
950 "TLS_CHACHA20_POLY1305_SHA256:"
951 "TLS_AES_128_CCM_SHA256";
952#endif
953 const char *groups = "P-256:X25519:P-384:P-521";
954 long options =
955 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
956 SSL_OP_SINGLE_ECDH_USE |
957 SSL_OP_CIPHER_SERVER_PREFERENCE;
958 SSL_CTX *ctx;
959
960 ctx = SSL_CTX_new(TLS_server_method());
961 bind_conf->initial_ctx = ctx;
962
963 SSL_CTX_set_options(ctx, options);
964#if 0
965 if (SSL_CTX_set_cipher_list(ctx, ciphers) != 1) {
966 ha_alert("Proxy '%s': unable to set TLS 1.3 cipher list to '%s' "
967 "for bind '%s' at [%s:%d].\n",
968 curproxy->id, ciphers,
969 bind_conf->arg, bind_conf->file, bind_conf->line);
970 cfgerr++;
971 }
972#endif
973
974 if (SSL_CTX_set1_curves_list(ctx, groups) != 1) {
975 ha_alert("Proxy '%s': unable to set TLS 1.3 curves list to '%s' "
976 "for bind '%s' at [%s:%d].\n",
977 curproxy->id, groups,
978 bind_conf->arg, bind_conf->file, bind_conf->line);
979 cfgerr++;
980 }
981
982 SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
983 SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
984 SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
985 SSL_CTX_set_default_verify_paths(ctx);
986
987#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
988#ifdef OPENSSL_IS_BORINGSSL
989 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
990 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
991#elif (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
992 if (bind_conf->ssl_conf.early_data) {
993 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
994 SSL_CTX_set_max_early_data(ctx, global.tune.bufsize - global.tune.maxrewrite);
995 }
996 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
997 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
998#else
999 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
1000#endif
1001 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
1002#endif
1003 SSL_CTX_set_quic_method(ctx, &ha_quic_method);
1004
1005 return cfgerr;
1006}
1007
1008/* Decode an expected packet number from <truncated_on> its truncated value,
1009 * depending on <largest_pn> the largest received packet number, and <pn_nbits>
1010 * the number of bits used to encode this packet number (its length in bytes * 8).
1011 * See https://quicwg.org/base-drafts/draft-ietf-quic-transport.html#packet-encoding
1012 */
1013static uint64_t decode_packet_number(uint64_t largest_pn,
1014 uint32_t truncated_pn, unsigned int pn_nbits)
1015{
1016 uint64_t expected_pn = largest_pn + 1;
1017 uint64_t pn_win = (uint64_t)1 << pn_nbits;
1018 uint64_t pn_hwin = pn_win / 2;
1019 uint64_t pn_mask = pn_win - 1;
1020 uint64_t candidate_pn;
1021
1022
1023 candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
1024 /* Note that <pn_win> > <pn_hwin>. */
1025 if (candidate_pn < QUIC_MAX_PACKET_NUM - pn_win &&
1026 candidate_pn + pn_hwin <= expected_pn)
1027 return candidate_pn + pn_win;
1028
1029 if (candidate_pn > expected_pn + pn_hwin && candidate_pn >= pn_win)
1030 return candidate_pn - pn_win;
1031
1032 return candidate_pn;
1033}
1034
1035/* Remove the header protection of <pkt> QUIC packet using <tls_ctx> as QUIC TLS
1036 * cryptographic context.
1037 * <largest_pn> is the largest received packet number and <pn> the address of
1038 * the packet number field for this packet with <byte0> address of its first byte.
1039 * <end> points to one byte past the end of this packet.
1040 * Returns 1 if succeeded, 0 if not.
1041 */
1042static int qc_do_rm_hp(struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx,
1043 int64_t largest_pn, unsigned char *pn,
1044 unsigned char *byte0, const unsigned char *end,
1045 struct quic_conn_ctx *ctx)
1046{
1047 int ret, outlen, i, pnlen;
1048 uint64_t packet_number;
1049 uint32_t truncated_pn = 0;
1050 unsigned char mask[5] = {0};
1051 unsigned char *sample;
1052 EVP_CIPHER_CTX *cctx;
1053 unsigned char *hp_key;
1054
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001055 /* Check there is enough data in this packet. */
1056 if (end - pn < QUIC_PACKET_PN_MAXLEN + sizeof mask) {
1057 TRACE_DEVEL("too short packet", QUIC_EV_CONN_RMHP, ctx->conn, pkt);
1058 return 0;
1059 }
1060
1061 cctx = EVP_CIPHER_CTX_new();
1062 if (!cctx) {
1063 TRACE_DEVEL("memory allocation failed", QUIC_EV_CONN_RMHP, ctx->conn, pkt);
1064 return 0;
1065 }
1066
1067 ret = 0;
1068 sample = pn + QUIC_PACKET_PN_MAXLEN;
1069
1070 hp_key = tls_ctx->rx.hp_key;
1071 if (!EVP_DecryptInit_ex(cctx, tls_ctx->rx.hp, NULL, hp_key, sample) ||
1072 !EVP_DecryptUpdate(cctx, mask, &outlen, mask, sizeof mask) ||
1073 !EVP_DecryptFinal_ex(cctx, mask, &outlen)) {
1074 TRACE_DEVEL("decryption failed", QUIC_EV_CONN_RMHP, ctx->conn, pkt);
1075 goto out;
1076 }
1077
1078 *byte0 ^= mask[0] & (*byte0 & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
1079 pnlen = (*byte0 & QUIC_PACKET_PNL_BITMASK) + 1;
1080 for (i = 0; i < pnlen; i++) {
1081 pn[i] ^= mask[i + 1];
1082 truncated_pn = (truncated_pn << 8) | pn[i];
1083 }
1084
1085 packet_number = decode_packet_number(largest_pn, truncated_pn, pnlen * 8);
1086 /* Store remaining information for this unprotected header */
1087 pkt->pn = packet_number;
1088 pkt->pnl = pnlen;
1089
1090 ret = 1;
1091
1092 out:
1093 EVP_CIPHER_CTX_free(cctx);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001094
1095 return ret;
1096}
1097
1098/* Encrypt the payload of a QUIC packet with <pn> as number found at <payload>
1099 * address, with <payload_len> as payload length, <aad> as address of
1100 * the ADD and <aad_len> as AAD length depending on the <tls_ctx> QUIC TLS
1101 * context.
1102 * Returns 1 if succeeded, 0 if not.
1103 */
1104static int quic_packet_encrypt(unsigned char *payload, size_t payload_len,
1105 unsigned char *aad, size_t aad_len, uint64_t pn,
1106 struct quic_tls_ctx *tls_ctx, struct connection *conn)
1107{
1108 unsigned char iv[12];
1109 unsigned char *tx_iv = tls_ctx->tx.iv;
1110 size_t tx_iv_sz = sizeof tls_ctx->tx.iv;
Frédéric Lécaillef63921f2020-12-18 09:48:20 +01001111 struct enc_debug_info edi;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001112
1113 if (!quic_aead_iv_build(iv, sizeof iv, tx_iv, tx_iv_sz, pn)) {
1114 TRACE_DEVEL("AEAD IV building for encryption failed", QUIC_EV_CONN_HPKT, conn);
Frédéric Lécaillef63921f2020-12-18 09:48:20 +01001115 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001116 }
1117
1118 if (!quic_tls_encrypt(payload, payload_len, aad, aad_len,
1119 tls_ctx->tx.aead, tls_ctx->tx.key, iv)) {
1120 TRACE_DEVEL("QUIC packet encryption failed", QUIC_EV_CONN_HPKT, conn);
Frédéric Lécaillef63921f2020-12-18 09:48:20 +01001121 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001122 }
1123
1124 return 1;
Frédéric Lécaillef63921f2020-12-18 09:48:20 +01001125
1126 err:
1127 enc_debug_info_init(&edi, payload, payload_len, aad, aad_len, pn);
1128 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_ENCPKT, conn, &edi);
1129 return 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001130}
1131
1132/* Decrypt <pkt> QUIC packet with <tls_ctx> as QUIC TLS cryptographic context.
1133 * Returns 1 if succeeded, 0 if not.
1134 */
1135static int qc_pkt_decrypt(struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx)
1136{
1137 int ret;
1138 unsigned char iv[12];
1139 unsigned char *rx_iv = tls_ctx->rx.iv;
1140 size_t rx_iv_sz = sizeof tls_ctx->rx.iv;
1141
1142 if (!quic_aead_iv_build(iv, sizeof iv, rx_iv, rx_iv_sz, pkt->pn))
1143 return 0;
1144
1145 ret = quic_tls_decrypt(pkt->data + pkt->aad_len, pkt->len - pkt->aad_len,
1146 pkt->data, pkt->aad_len,
1147 tls_ctx->rx.aead, tls_ctx->rx.key, iv);
1148 if (!ret)
1149 return 0;
1150
1151 /* Update the packet length (required to parse the frames). */
1152 pkt->len = pkt->aad_len + ret;
1153
1154 return 1;
1155}
1156
1157/* Treat <frm> frame whose packet it is attached to has just been acknowledged. */
1158static inline void qc_treat_acked_tx_frm(struct quic_tx_frm *frm,
1159 struct quic_conn_ctx *ctx)
1160{
1161 TRACE_PROTO("Removing frame", QUIC_EV_CONN_PRSAFRM, ctx->conn, frm);
Willy Tarreau2b718102021-04-21 07:32:39 +02001162 LIST_DELETE(&frm->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001163 pool_free(pool_head_quic_tx_frm, frm);
1164}
1165
1166/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1167 * deallocating them, and their TX frames.
1168 * Returns the last node reached to be used for the next range.
1169 * May be NULL if <largest> node could not be found.
1170 */
1171static inline struct eb64_node *qc_ackrng_pkts(struct eb_root *pkts, unsigned int *pkt_flags,
1172 struct list *newly_acked_pkts,
1173 struct eb64_node *largest_node,
1174 uint64_t largest, uint64_t smallest,
1175 struct quic_conn_ctx *ctx)
1176{
1177 struct eb64_node *node;
1178 struct quic_tx_packet *pkt;
1179
1180 if (largest_node)
1181 node = largest_node;
1182 else {
1183 node = eb64_lookup(pkts, largest);
1184 while (!node && largest > smallest) {
1185 node = eb64_lookup(pkts, --largest);
1186 }
1187 }
1188
1189 while (node && node->key >= smallest) {
1190 struct quic_tx_frm *frm, *frmbak;
1191
1192 pkt = eb64_entry(&node->node, struct quic_tx_packet, pn_node);
1193 *pkt_flags |= pkt->flags;
Willy Tarreau2b718102021-04-21 07:32:39 +02001194 LIST_INSERT(newly_acked_pkts, &pkt->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001195 TRACE_PROTO("Removing packet #", QUIC_EV_CONN_PRSAFRM, ctx->conn,, &pkt->pn_node.key);
1196 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1197 qc_treat_acked_tx_frm(frm, ctx);
1198 node = eb64_prev(node);
1199 eb64_delete(&pkt->pn_node);
1200 }
1201
1202 return node;
1203}
1204
1205/* Treat <frm> frame whose packet it is attached to has just been detected as non
1206 * acknowledged.
1207 */
1208static inline void qc_treat_nacked_tx_frm(struct quic_tx_frm *frm,
1209 struct quic_pktns *pktns,
1210 struct quic_conn_ctx *ctx)
1211{
1212 TRACE_PROTO("to resend frame", QUIC_EV_CONN_PRSAFRM, ctx->conn, frm);
Willy Tarreau2b718102021-04-21 07:32:39 +02001213 LIST_DELETE(&frm->list);
1214 LIST_INSERT(&pktns->tx.frms, &frm->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001215}
1216
1217
1218/* Free the TX packets of <pkts> list */
1219static inline void free_quic_tx_pkts(struct list *pkts)
1220{
1221 struct quic_tx_packet *pkt, *tmp;
1222
1223 list_for_each_entry_safe(pkt, tmp, pkts, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02001224 LIST_DELETE(&pkt->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001225 eb64_delete(&pkt->pn_node);
1226 pool_free(pool_head_quic_tx_packet, pkt);
1227 }
1228}
1229
1230/* Send a packet loss event nofification to the congestion controller
1231 * attached to <qc> connection with <lost_bytes> the number of lost bytes,
1232 * <oldest_lost>, <newest_lost> the oldest lost packet and newest lost packet
1233 * at <now_us> current time.
1234 * Always succeeds.
1235 */
1236static inline void qc_cc_loss_event(struct quic_conn *qc,
1237 unsigned int lost_bytes,
1238 unsigned int newest_time_sent,
1239 unsigned int period,
1240 unsigned int now_us)
1241{
1242 struct quic_cc_event ev = {
1243 .type = QUIC_CC_EVT_LOSS,
1244 .loss.now_ms = now_ms,
1245 .loss.max_ack_delay = qc->max_ack_delay,
1246 .loss.lost_bytes = lost_bytes,
1247 .loss.newest_time_sent = newest_time_sent,
1248 .loss.period = period,
1249 };
1250
1251 quic_cc_event(&qc->path->cc, &ev);
1252}
1253
1254/* Send a packet ack event nofication for each newly acked packet of
1255 * <newly_acked_pkts> list and free them.
1256 * Always succeeds.
1257 */
1258static inline void qc_treat_newly_acked_pkts(struct quic_conn_ctx *ctx,
1259 struct list *newly_acked_pkts)
1260{
1261 struct quic_conn *qc = ctx->conn->qc;
1262 struct quic_tx_packet *pkt, *tmp;
1263 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
1264
1265 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
1266 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001267 qc->path->prep_in_flight -= pkt->in_flight_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001268 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01001269 qc->path->ifae_pkts--;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001270 ev.ack.acked = pkt->in_flight_len;
1271 ev.ack.time_sent = pkt->time_sent;
1272 quic_cc_event(&qc->path->cc, &ev);
Willy Tarreau2b718102021-04-21 07:32:39 +02001273 LIST_DELETE(&pkt->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001274 eb64_delete(&pkt->pn_node);
1275 pool_free(pool_head_quic_tx_packet, pkt);
1276 }
1277
1278}
1279
1280/* Handle <pkts> list of lost packets detected at <now_us> handling
1281 * their TX frames.
1282 * Send a packet loss event to the congestion controller if
1283 * in flight packet have been lost.
1284 * Also frees the packet in <pkts> list.
1285 * Never fails.
1286 */
1287static inline void qc_release_lost_pkts(struct quic_pktns *pktns,
1288 struct quic_conn_ctx *ctx,
1289 struct list *pkts,
1290 uint64_t now_us)
1291{
1292 struct quic_conn *qc = ctx->conn->qc;
1293 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
1294 struct quic_tx_frm *frm, *frmbak;
1295 uint64_t lost_bytes;
1296
1297 lost_bytes = 0;
1298 oldest_lost = newest_lost = NULL;
1299 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1300 lost_bytes += pkt->in_flight_len;
1301 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001302 qc->path->prep_in_flight -= pkt->in_flight_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001303 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01001304 qc->path->ifae_pkts--;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001305 /* Treat the frames of this lost packet. */
1306 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1307 qc_treat_nacked_tx_frm(frm, pktns, ctx);
Willy Tarreau2b718102021-04-21 07:32:39 +02001308 LIST_DELETE(&pkt->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001309 if (!oldest_lost) {
1310 oldest_lost = newest_lost = pkt;
1311 }
1312 else {
1313 if (newest_lost != oldest_lost)
1314 pool_free(pool_head_quic_tx_packet, newest_lost);
1315 newest_lost = pkt;
1316 }
1317 }
1318
1319 if (lost_bytes) {
1320 /* Sent a packet loss event to the congestion controller. */
1321 qc_cc_loss_event(ctx->conn->qc, lost_bytes, newest_lost->time_sent,
1322 newest_lost->time_sent - oldest_lost->time_sent, now_us);
1323 pool_free(pool_head_quic_tx_packet, oldest_lost);
1324 if (newest_lost != oldest_lost)
1325 pool_free(pool_head_quic_tx_packet, newest_lost);
1326 }
1327}
1328
1329/* Look for packet loss from sent packets for <qel> encryption level of a
1330 * connection with <ctx> as I/O handler context. If remove is true, remove them from
1331 * their tree if deemed as lost or set the <loss_time> value the packet number
1332 * space if any not deemed lost.
1333 * Should be called after having received an ACK frame with newly acknowledged
1334 * packets or when the the loss detection timer has expired.
1335 * Always succeeds.
1336 */
1337static void qc_packet_loss_lookup(struct quic_pktns *pktns,
1338 struct quic_conn *qc,
1339 struct list *lost_pkts)
1340{
1341 struct eb_root *pkts;
1342 struct eb64_node *node;
1343 struct quic_loss *ql;
1344 unsigned int loss_delay;
1345
1346 TRACE_ENTER(QUIC_EV_CONN_PKTLOSS, qc->conn, pktns);
1347 pkts = &pktns->tx.pkts;
1348 pktns->tx.loss_time = TICK_ETERNITY;
1349 if (eb_is_empty(pkts))
1350 goto out;
1351
1352 ql = &qc->path->loss;
1353 loss_delay = QUIC_MAX(ql->latest_rtt, ql->srtt >> 3);
1354 loss_delay += loss_delay >> 3;
1355 loss_delay = QUIC_MAX(loss_delay, MS_TO_TICKS(QUIC_TIMER_GRANULARITY));
1356
1357 node = eb64_first(pkts);
1358 while (node) {
1359 struct quic_tx_packet *pkt;
1360 int64_t largest_acked_pn;
1361 unsigned int loss_time_limit, time_sent;
1362
1363 pkt = eb64_entry(&node->node, struct quic_tx_packet, pn_node);
1364 largest_acked_pn = pktns->tx.largest_acked_pn;
1365 node = eb64_next(node);
1366 if ((int64_t)pkt->pn_node.key > largest_acked_pn)
1367 break;
1368
1369 time_sent = pkt->time_sent;
1370 loss_time_limit = tick_add(time_sent, loss_delay);
1371 if (tick_is_le(time_sent, now_ms) ||
1372 (int64_t)largest_acked_pn >= pkt->pn_node.key + QUIC_LOSS_PACKET_THRESHOLD) {
1373 eb64_delete(&pkt->pn_node);
Willy Tarreau2b718102021-04-21 07:32:39 +02001374 LIST_APPEND(lost_pkts, &pkt->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001375 }
1376 else {
1377 pktns->tx.loss_time = tick_first(pktns->tx.loss_time, loss_time_limit);
1378 }
1379 }
1380
1381 out:
1382 TRACE_LEAVE(QUIC_EV_CONN_PKTLOSS, qc->conn, pktns, lost_pkts);
1383}
1384
1385/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
1386 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05001387 * if the largest acked packet was newly acked and if there was at least one newly
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001388 * acked ack-eliciting packet.
1389 * Return 1, if succeeded, 0 if not.
1390 */
1391static inline int qc_parse_ack_frm(struct quic_frame *frm, struct quic_conn_ctx *ctx,
1392 struct quic_enc_level *qel,
1393 unsigned int *rtt_sample,
1394 const unsigned char **pos, const unsigned char *end)
1395{
1396 struct quic_ack *ack = &frm->ack;
1397 uint64_t smallest, largest;
1398 struct eb_root *pkts;
1399 struct eb64_node *largest_node;
1400 unsigned int time_sent, pkt_flags;
1401 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
1402 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
1403
1404 if (ack->largest_ack > qel->pktns->tx.next_pn) {
1405 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
1406 ctx->conn,, &ack->largest_ack);
1407 goto err;
1408 }
1409
1410 if (ack->first_ack_range > ack->largest_ack) {
1411 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
1412 ctx->conn,, &ack->first_ack_range);
1413 goto err;
1414 }
1415
1416 largest = ack->largest_ack;
1417 smallest = largest - ack->first_ack_range;
1418 pkts = &qel->pktns->tx.pkts;
1419 pkt_flags = 0;
1420 largest_node = NULL;
1421 time_sent = 0;
1422
1423 if ((int64_t)ack->largest_ack > qel->pktns->tx.largest_acked_pn) {
1424 largest_node = eb64_lookup(pkts, largest);
1425 if (!largest_node) {
1426 TRACE_DEVEL("Largest acked packet not found",
1427 QUIC_EV_CONN_PRSAFRM, ctx->conn);
1428 goto err;
1429 }
1430
1431 time_sent = eb64_entry(&largest_node->node,
1432 struct quic_tx_packet, pn_node)->time_sent;
1433 }
1434
1435 TRACE_PROTO("ack range", QUIC_EV_CONN_PRSAFRM,
1436 ctx->conn,, &largest, &smallest);
1437 do {
1438 uint64_t gap, ack_range;
1439
1440 qc_ackrng_pkts(pkts, &pkt_flags, &newly_acked_pkts,
1441 largest_node, largest, smallest, ctx);
1442 if (!ack->ack_range_num--)
1443 break;
1444
1445 if (!quic_dec_int(&gap, pos, end))
1446 goto err;
1447
1448 if (smallest < gap + 2) {
1449 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
1450 ctx->conn,, &gap, &smallest);
1451 goto err;
1452 }
1453
1454 largest = smallest - gap - 2;
1455 if (!quic_dec_int(&ack_range, pos, end))
1456 goto err;
1457
1458 if (largest < ack_range) {
1459 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
1460 ctx->conn,, &largest, &ack_range);
1461 goto err;
1462 }
1463
1464 /* Do not use this node anymore. */
1465 largest_node = NULL;
1466 /* Next range */
1467 smallest = largest - ack_range;
1468
1469 TRACE_PROTO("ack range", QUIC_EV_CONN_PRSAFRM,
1470 ctx->conn,, &largest, &smallest);
1471 } while (1);
1472
1473 /* Flag this packet number space as having received an ACK. */
1474 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_RECEIVED;
1475
1476 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
1477 *rtt_sample = tick_remain(time_sent, now_ms);
1478 qel->pktns->tx.largest_acked_pn = ack->largest_ack;
1479 }
1480
1481 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
1482 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
1483 qc_packet_loss_lookup(qel->pktns, ctx->conn->qc, &lost_pkts);
1484 if (!LIST_ISEMPTY(&lost_pkts))
1485 qc_release_lost_pkts(qel->pktns, ctx, &lost_pkts, now_ms);
1486 }
1487 qc_treat_newly_acked_pkts(ctx, &newly_acked_pkts);
1488 if (quic_peer_validated_addr(ctx))
1489 ctx->conn->qc->path->loss.pto_count = 0;
1490 qc_set_timer(ctx);
1491 }
1492
1493
1494 return 1;
1495
1496 err:
1497 free_quic_tx_pkts(&newly_acked_pkts);
1498 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PRSAFRM, ctx->conn);
1499 return 0;
1500}
1501
1502/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
1503 * from <qel> encryption level with <ctx> as QUIC connection context.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05001504 * Remaining parameter are there for debugging purposes.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001505 * Return 1 if succeeded, 0 if not.
1506 */
1507static inline int qc_provide_cdata(struct quic_enc_level *el,
1508 struct quic_conn_ctx *ctx,
1509 const unsigned char *data, size_t len,
1510 struct quic_rx_packet *pkt,
1511 struct quic_rx_crypto_frm *cf)
1512{
1513 int ssl_err;
1514
1515 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, ctx->conn);
1516 ssl_err = SSL_ERROR_NONE;
1517 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
1518 TRACE_PROTO("SSL_provide_quic_data() error",
1519 QUIC_EV_CONN_SSLDATA, ctx->conn, pkt, cf, ctx->ssl);
1520 goto err;
1521 }
1522
1523 el->rx.crypto.offset += len;
1524 TRACE_PROTO("in order CRYPTO data",
1525 QUIC_EV_CONN_SSLDATA, ctx->conn,, cf, ctx->ssl);
1526
1527 if (ctx->state < QUIC_HS_ST_COMPLETE) {
1528 ssl_err = SSL_do_handshake(ctx->ssl);
1529 if (ssl_err != 1) {
1530 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
1531 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
1532 TRACE_PROTO("SSL handshake",
1533 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1534 goto out;
1535 }
1536
1537 TRACE_DEVEL("SSL handshake error",
1538 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1539 goto err;
1540 }
1541
1542 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
1543 if (objt_listener(ctx->conn->target))
1544 ctx->state = QUIC_HS_ST_CONFIRMED;
1545 else
1546 ctx->state = QUIC_HS_ST_COMPLETE;
1547 } else {
1548 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
1549 if (ssl_err != 1) {
1550 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
1551 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
1552 TRACE_DEVEL("SSL post handshake",
1553 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1554 goto out;
1555 }
1556
1557 TRACE_DEVEL("SSL post handshake error",
1558 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1559 goto err;
1560 }
1561
1562 TRACE_PROTO("SSL post handshake succeeded",
1563 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
1564 }
1565
1566 out:
1567 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, ctx->conn);
1568 return 1;
1569
1570 err:
1571 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_SSLDATA, ctx->conn);
1572 return 0;
1573}
1574
1575/* Parse all the frames of <pkt> QUIC packet for QUIC connection with <ctx>
1576 * as I/O handler context and <qel> as encryption level.
1577 * Returns 1 if succeeded, 0 if failed.
1578 */
1579static int qc_parse_pkt_frms(struct quic_rx_packet *pkt, struct quic_conn_ctx *ctx,
1580 struct quic_enc_level *qel)
1581{
1582 struct quic_frame frm;
1583 const unsigned char *pos, *end;
1584 struct quic_conn *conn = ctx->conn->qc;
1585
1586 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, ctx->conn);
1587 /* Skip the AAD */
1588 pos = pkt->data + pkt->aad_len;
1589 end = pkt->data + pkt->len;
1590
1591 while (pos < end) {
1592 if (!qc_parse_frm(&frm, pkt, &pos, end, conn))
1593 goto err;
1594
1595 switch (frm.type) {
Frédéric Lécaille0c140202020-12-09 15:56:48 +01001596 case QUIC_FT_PADDING:
1597 if (pos != end) {
1598 TRACE_DEVEL("wrong frame", QUIC_EV_CONN_PRSHPKT, ctx->conn, pkt);
1599 goto err;
1600 }
1601 break;
1602 case QUIC_FT_PING:
1603 break;
1604 case QUIC_FT_ACK:
1605 {
1606 unsigned int rtt_sample;
1607
1608 rtt_sample = 0;
1609 if (!qc_parse_ack_frm(&frm, ctx, qel, &rtt_sample, &pos, end))
1610 goto err;
1611
1612 if (rtt_sample) {
1613 unsigned int ack_delay;
1614
1615 ack_delay = !quic_application_pktns(qel->pktns, conn) ? 0 :
1616 MS_TO_TICKS(QUIC_MIN(quic_ack_delay_ms(&frm.ack, conn), conn->max_ack_delay));
1617 quic_loss_srtt_update(&conn->path->loss, rtt_sample, ack_delay, conn);
1618 }
1619 tasklet_wakeup(ctx->wait_event.tasklet);
1620 break;
1621 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001622 case QUIC_FT_CRYPTO:
1623 if (frm.crypto.offset != qel->rx.crypto.offset) {
1624 struct quic_rx_crypto_frm *cf;
1625
1626 cf = pool_alloc(pool_head_quic_rx_crypto_frm);
1627 if (!cf) {
1628 TRACE_DEVEL("CRYPTO frame allocation failed",
1629 QUIC_EV_CONN_PRSHPKT, ctx->conn);
1630 goto err;
1631 }
1632
1633 cf->offset_node.key = frm.crypto.offset;
1634 cf->len = frm.crypto.len;
1635 cf->data = frm.crypto.data;
1636 cf->pkt = pkt;
1637 eb64_insert(&qel->rx.crypto.frms, &cf->offset_node);
1638 quic_rx_packet_refinc(pkt);
1639 }
1640 else {
1641 /* XXX TO DO: <cf> is used only for the traces. */
1642 struct quic_rx_crypto_frm cf = { };
1643
1644 cf.offset_node.key = frm.crypto.offset;
1645 cf.len = frm.crypto.len;
1646 if (!qc_provide_cdata(qel, ctx,
1647 frm.crypto.data, frm.crypto.len,
1648 pkt, &cf))
1649 goto err;
1650 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001651 break;
Frédéric Lécaille0c140202020-12-09 15:56:48 +01001652 case QUIC_FT_STREAM_8:
1653 case QUIC_FT_STREAM_9:
1654 case QUIC_FT_STREAM_A:
1655 case QUIC_FT_STREAM_B:
1656 case QUIC_FT_STREAM_C:
1657 case QUIC_FT_STREAM_D:
1658 case QUIC_FT_STREAM_E:
1659 case QUIC_FT_STREAM_F:
Frédéric Lécaille242fb1b2020-12-31 12:45:38 +01001660 {
1661 struct quic_stream *stream = &frm.stream;
1662
1663 TRACE_PROTO("STREAM frame", QUIC_EV_CONN_PSTRM, ctx->conn, &frm);
1664 if (objt_listener(ctx->conn->target)) {
1665 if (stream->id & QUIC_STREAM_FRAME_ID_INITIATOR_BIT)
1666 goto err;
1667 } else if (!(stream->id & QUIC_STREAM_FRAME_ID_INITIATOR_BIT))
1668 goto err;
1669 break;
1670 }
Frédéric Lécaille0c140202020-12-09 15:56:48 +01001671 case QUIC_FT_NEW_CONNECTION_ID:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001672 break;
1673 case QUIC_FT_CONNECTION_CLOSE:
1674 case QUIC_FT_CONNECTION_CLOSE_APP:
1675 break;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001676 case QUIC_FT_HANDSHAKE_DONE:
1677 if (objt_listener(ctx->conn->target))
1678 goto err;
1679
1680 ctx->state = QUIC_HS_ST_CONFIRMED;
1681 break;
1682 default:
1683 goto err;
1684 }
1685 }
1686
1687 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
1688 * has successfully parse a Handshake packet. The Initial encryption must also
1689 * be discarded.
1690 */
1691 if (ctx->state == QUIC_HS_ST_SERVER_INITIAL &&
1692 pkt->type == QUIC_PACKET_TYPE_HANDSHAKE) {
1693 quic_tls_discard_keys(&conn->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
1694 quic_pktns_discard(conn->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, conn);
1695 qc_set_timer(ctx);
1696 ctx->state = QUIC_HS_ST_SERVER_HANDSHAKE;
1697 }
1698
1699 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, ctx->conn);
1700 return 1;
1701
1702 err:
1703 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PRSHPKT, ctx->conn);
1704 return 0;
1705}
1706
1707/* Prepare as much as possible handshake packets for the QUIC connection
1708 * with <ctx> as I/O handler context.
1709 * Returns 1 if succeeded, or 0 if something wrong happened.
1710 */
1711static int qc_prep_hdshk_pkts(struct quic_conn_ctx *ctx)
1712{
1713 struct quic_conn *qc;
1714 enum quic_tls_enc_level tel, next_tel;
1715 struct quic_enc_level *qel;
1716 struct q_buf *wbuf;
1717 /* A boolean to flag <wbuf> as reusable, even if not empty. */
1718 int reuse_wbuf;
1719
1720 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, ctx->conn);
1721 qc = ctx->conn->qc;
1722 if (!quic_get_tls_enc_levels(&tel, &next_tel, ctx->state)) {
1723 TRACE_DEVEL("unknown enc. levels",
1724 QUIC_EV_CONN_PHPKTS, ctx->conn);
1725 goto err;
1726 }
1727
1728 reuse_wbuf = 0;
1729 wbuf = q_wbuf(qc);
1730 qel = &qc->els[tel];
Ilya Shipitsin01881082021-08-07 14:41:56 +05001731 /* When entering this function, the writer buffer must be empty.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001732 * Most of the time it points to the reader buffer.
1733 */
1734 while ((q_buf_empty(wbuf) || reuse_wbuf)) {
1735 ssize_t ret;
1736 enum quic_pkt_type pkt_type;
1737
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +01001738 TRACE_POINT(QUIC_EV_CONN_PHPKTS, ctx->conn, qel);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001739 /* Do not build any more packet f the TX secrets are not available or
1740 * f there is nothing to send, i.e. if no ACK are required
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001741 * and if there is no more packets to send upon PTO expiration
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001742 * and if there is no more CRYPTO data available or in flight
1743 * congestion control limit is reached for prepared data
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001744 */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001745 if (!(qel->tls_ctx.tx.flags & QUIC_FL_TLS_SECRETS_SET) ||
1746 (!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001747 !qc->tx.nb_pto_dgrams &&
1748 (LIST_ISEMPTY(&qel->pktns->tx.frms) ||
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001749 qc->path->prep_in_flight >= qc->path->cwnd))) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001750 TRACE_DEVEL("nothing more to do", QUIC_EV_CONN_PHPKTS, ctx->conn);
1751 /* Consume the buffer if we were supposed to reuse it. */
1752 if (reuse_wbuf)
1753 wbuf = q_next_wbuf(qc);
1754 break;
1755 }
1756
1757 pkt_type = quic_tls_level_pkt_type(tel);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001758 ret = qc_build_hdshk_pkt(wbuf, qc, pkt_type, qel);
1759 switch (ret) {
1760 case -2:
1761 goto err;
1762 case -1:
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001763 if (!reuse_wbuf)
1764 goto out;
1765
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001766 /* Not enough room in <wbuf>. */
1767 wbuf = q_next_wbuf(qc);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001768 reuse_wbuf = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001769 continue;
1770 case 0:
1771 goto out;
1772 default:
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001773 reuse_wbuf = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001774 /* Discard the Initial encryption keys as soon as
1775 * a handshake packet could be built.
1776 */
1777 if (ctx->state == QUIC_HS_ST_CLIENT_INITIAL &&
1778 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
1779 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
1780 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
1781 qc_set_timer(ctx);
1782 ctx->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
1783 }
1784 /* Special case for Initial packets: when they have all
1785 * been sent, select the next level.
1786 */
1787 if ((LIST_ISEMPTY(&qel->pktns->tx.frms) || qc->els[next_tel].pktns->tx.in_flight) &&
1788 tel == QUIC_TLS_ENC_LEVEL_INITIAL) {
1789 tel = next_tel;
1790 qel = &qc->els[tel];
1791 if (LIST_ISEMPTY(&qel->pktns->tx.frms)) {
1792 /* If there is no more data for the next level, let's
1793 * consume a buffer. This is the case for a client
1794 * which sends only one Initial packet, then wait
1795 * for additional CRYPTO data from the server to enter the
1796 * next level.
1797 */
1798 wbuf = q_next_wbuf(qc);
1799 }
1800 else {
1801 /* Let's try to reuse this buffer. */
1802 reuse_wbuf = 1;
1803 }
1804 }
1805 else {
1806 wbuf = q_next_wbuf(qc);
1807 }
1808 }
1809 }
1810
1811 out:
1812 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, ctx->conn);
1813 return 1;
1814
1815 err:
1816 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PHPKTS, ctx->conn);
1817 return 0;
1818}
1819
1820/* Send the QUIC packets which have been prepared for QUIC connections
1821 * with <ctx> as I/O handler context.
1822 */
1823int qc_send_ppkts(struct quic_conn_ctx *ctx)
1824{
1825 struct quic_conn *qc;
1826 struct buffer tmpbuf = { };
1827 struct q_buf *rbuf;
1828
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001829 qc = ctx->conn->qc;
1830 for (rbuf = q_rbuf(qc); !q_buf_empty(rbuf) ; rbuf = q_next_rbuf(qc)) {
1831 struct quic_tx_packet *p, *q;
1832 unsigned int time_sent;
1833
1834 tmpbuf.area = (char *)rbuf->area;
1835 tmpbuf.size = tmpbuf.data = rbuf->data;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001836 TRACE_PROTO("to send", QUIC_EV_CONN_SPPKTS, ctx->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001837 if (ctx->xprt->snd_buf(qc->conn, qc->conn->xprt_ctx,
1838 &tmpbuf, tmpbuf.data, 0) <= 0)
1839 break;
1840
1841 qc->tx.bytes += tmpbuf.data;
1842 time_sent = now_ms;
1843 /* Reset this buffer to make it available for the next packet to prepare. */
1844 q_buf_reset(rbuf);
1845 /* Remove from <rbuf> the packets which have just been sent. */
1846 list_for_each_entry_safe(p, q, &rbuf->pkts, list) {
1847 p->time_sent = time_sent;
1848 if (p->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
1849 p->pktns->tx.time_of_last_eliciting = time_sent;
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01001850 qc->path->ifae_pkts++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001851 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001852 qc->path->in_flight += p->in_flight_len;
1853 p->pktns->tx.in_flight += p->in_flight_len;
1854 if (p->in_flight_len)
1855 qc_set_timer(ctx);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001856 TRACE_PROTO("sent pkt", QUIC_EV_CONN_SPPKTS, ctx->conn, p);
Willy Tarreau2b718102021-04-21 07:32:39 +02001857 LIST_DELETE(&p->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001858 }
1859 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001860
1861 return 1;
1862}
1863
1864/* Build all the frames which must be sent just after the handshake have succeeded.
1865 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
1866 * a HANDSHAKE_DONE frame.
1867 * Return 1 if succeeded, 0 if not.
1868 */
1869static int quic_build_post_handshake_frames(struct quic_conn *conn)
1870{
1871 int i;
1872 struct quic_frame *frm;
1873
1874 /* Only servers must send a HANDSHAKE_DONE frame. */
1875 if (!objt_server(conn->conn->target)) {
1876 frm = pool_alloc(pool_head_quic_frame);
Frédéric Lécaille153d4a82021-01-06 12:12:39 +01001877 if (!frm)
1878 return 0;
1879
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001880 frm->type = QUIC_FT_HANDSHAKE_DONE;
Willy Tarreau2b718102021-04-21 07:32:39 +02001881 LIST_APPEND(&conn->tx.frms_to_send, &frm->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001882 }
1883
1884 for (i = 1; i < conn->rx_tps.active_connection_id_limit; i++) {
1885 struct quic_connection_id *cid;
1886
1887 frm = pool_alloc(pool_head_quic_frame);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001888 cid = new_quic_cid(&conn->cids, i);
1889 if (!frm || !cid)
1890 goto err;
1891
1892 quic_connection_id_to_frm_cpy(frm, cid);
Willy Tarreau2b718102021-04-21 07:32:39 +02001893 LIST_APPEND(&conn->tx.frms_to_send, &frm->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001894 }
1895
1896 return 1;
1897
1898 err:
1899 free_quic_conn_cids(conn);
1900 return 0;
1901}
1902
1903/* Deallocate <l> list of ACK ranges. */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001904void free_quic_arngs(struct quic_arngs *arngs)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001905{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001906 struct eb64_node *n;
1907 struct quic_arng_node *ar;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001908
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001909 n = eb64_first(&arngs->root);
1910 while (n) {
1911 struct eb64_node *next;
1912
1913 ar = eb64_entry(&n->node, struct quic_arng_node, first);
1914 next = eb64_next(n);
1915 eb64_delete(n);
1916 free(ar);
1917 n = next;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001918 }
1919}
1920
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001921/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
1922 * descending order.
1923 */
1924static inline size_t sack_gap(struct quic_arng_node *p,
1925 struct quic_arng_node *q)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001926{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001927 return p->first.key - q->last - 2;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001928}
1929
1930
1931/* Remove the last elements of <ack_ranges> list of ack range updating its
1932 * encoded size until it goes below <limit>.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05001933 * Returns 1 if succeeded, 0 if not (no more element to remove).
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001934 */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001935static int quic_rm_last_ack_ranges(struct quic_arngs *arngs, size_t limit)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001936{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001937 struct eb64_node *last, *prev;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001938
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001939 last = eb64_last(&arngs->root);
1940 while (last && arngs->enc_sz > limit) {
1941 struct quic_arng_node *last_node, *prev_node;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001942
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001943 prev = eb64_prev(last);
1944 if (!prev)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001945 return 0;
1946
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001947 last_node = eb64_entry(&last->node, struct quic_arng_node, first);
1948 prev_node = eb64_entry(&prev->node, struct quic_arng_node, first);
1949 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
1950 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
1951 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
1952 --arngs->sz;
1953 eb64_delete(last);
1954 pool_free(pool_head_quic_arng, last);
1955 last = prev;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001956 }
1957
1958 return 1;
1959}
1960
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001961/* Set the encoded size of <arngs> QUIC ack ranges. */
1962static void quic_arngs_set_enc_sz(struct quic_arngs *arngs)
1963{
1964 struct eb64_node *node, *next;
1965 struct quic_arng_node *ar, *ar_next;
1966
1967 node = eb64_last(&arngs->root);
1968 if (!node)
1969 return;
1970
1971 ar = eb64_entry(&node->node, struct quic_arng_node, first);
1972 arngs->enc_sz = quic_int_getsize(ar->last) +
1973 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
1974
1975 while ((next = eb64_prev(node))) {
1976 ar_next = eb64_entry(&next->node, struct quic_arng_node, first);
1977 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
1978 quic_int_getsize(ar_next->last - ar_next->first.key);
1979 node = next;
1980 ar = eb64_entry(&node->node, struct quic_arng_node, first);
1981 }
1982}
1983
1984/* Insert in <root> ebtree <node> node with <ar> as range value.
1985 * Returns the ebtree node which has been inserted.
1986 */
1987static inline
1988struct eb64_node *quic_insert_new_range(struct eb_root *root,
1989 struct quic_arng_node *node,
1990 struct quic_arng *ar)
1991{
1992 node->first.key = ar->first;
1993 node->last = ar->last;
1994 return eb64_insert(root, &node->first);
1995}
1996
1997/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001998 * Note that this function computes the number of bytes required to encode
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001999 * this tree of ACK ranges in descending order.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002000 *
2001 * Descending order
2002 * ------------->
2003 * range1 range2
2004 * ..........|--------|..............|--------|
2005 * ^ ^ ^ ^
2006 * | | | |
2007 * last1 first1 last2 first2
2008 * ..........+--------+--------------+--------+......
2009 * diff1 gap12 diff2
2010 *
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002011 * To encode the previous list of ranges we must encode integers as follows in
2012 * descending order:
2013 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002014 * with diff1 = last1 - first1
2015 * diff2 = last2 - first2
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002016 * gap12 = first1 - last2 - 2 (>= 0)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002017 *
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002018 */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002019int quic_update_ack_ranges_list(struct quic_arngs *arngs,
2020 struct quic_arng *ar)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002021{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002022 struct eb64_node *le;
2023 struct quic_arng_node *new_node;
2024 struct eb64_node *new;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002025
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002026 new = NULL;
2027 if (eb_is_empty(&arngs->root)) {
2028 /* First range insertion. */
2029 new_node = pool_alloc(pool_head_quic_arng);
2030 if (!new_node)
2031 return 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002032
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002033 quic_insert_new_range(&arngs->root, new_node, ar);
2034 /* Increment the size of these ranges. */
2035 arngs->sz++;
2036 goto out;
2037 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002038
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002039 le = eb64_lookup_le(&arngs->root, ar->first);
2040 if (!le) {
2041 /* New insertion */
2042 new_node = pool_alloc(pool_head_quic_arng);
2043 if (!new_node)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002044 return 0;
2045
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002046 new = quic_insert_new_range(&arngs->root, new_node, ar);
2047 /* Increment the size of these ranges. */
2048 arngs->sz++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002049 }
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002050 else {
2051 struct quic_arng_node *le_ar =
2052 eb64_entry(&le->node, struct quic_arng_node, first);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002053
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002054 /* Already existing range */
2055 if (le_ar->first.key <= ar->first && le_ar->last >= ar->last)
2056 return 1;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002057
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002058 if (le_ar->last + 1 >= ar->first) {
2059 le_ar->last = ar->last;
2060 new = le;
2061 new_node = le_ar;
2062 }
2063 else {
2064 /* New insertion */
2065 new_node = pool_alloc(pool_head_quic_arng);
2066 if (!new_node)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002067 return 0;
2068
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002069 new = quic_insert_new_range(&arngs->root, new_node, ar);
2070 /* Increment the size of these ranges. */
2071 arngs->sz++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002072 }
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002073 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002074
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002075 /* Verify that the new inserted node does not overlap the nodes
2076 * which follow it.
2077 */
2078 if (new) {
2079 uint64_t new_node_last;
2080 struct eb64_node *next;
2081 struct quic_arng_node *next_node;
2082
2083 new_node_last = new_node->last;
2084 while ((next = eb64_next(new))) {
2085 next_node =
2086 eb64_entry(&next->node, struct quic_arng_node, first);
2087 if (new_node_last + 1 < next_node->first.key)
2088 break;
2089
2090 if (next_node->last > new_node->last)
2091 new_node->last = next_node->last;
2092 eb64_delete(next);
2093 free(next_node);
2094 /* Decrement the size of these ranges. */
2095 arngs->sz--;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002096 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002097 }
2098
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002099 quic_arngs_set_enc_sz(arngs);
2100
2101 out:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002102 return 1;
2103}
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002104/* Remove the header protection of packets at <el> encryption level.
2105 * Always succeeds.
2106 */
2107static inline void qc_rm_hp_pkts(struct quic_enc_level *el, struct quic_conn_ctx *ctx)
2108{
2109 struct quic_tls_ctx *tls_ctx;
2110 struct quic_rx_packet *pqpkt, *qqpkt;
2111 struct quic_enc_level *app_qel;
2112
2113 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, ctx->conn);
2114 app_qel = &ctx->conn->qc->els[QUIC_TLS_ENC_LEVEL_APP];
2115 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
2116 if (el == app_qel && objt_listener(ctx->conn->target) && ctx->state < QUIC_HS_ST_COMPLETE) {
2117 TRACE_PROTO("hp not removed (handshake not completed)",
2118 QUIC_EV_CONN_ELRMHP, ctx->conn);
2119 goto out;
2120 }
2121 tls_ctx = &el->tls_ctx;
2122 list_for_each_entry_safe(pqpkt, qqpkt, &el->rx.pqpkts, list) {
2123 if (!qc_do_rm_hp(pqpkt, tls_ctx, el->pktns->rx.largest_pn,
2124 pqpkt->data + pqpkt->pn_offset,
2125 pqpkt->data, pqpkt->data + pqpkt->len, ctx)) {
2126 TRACE_PROTO("hp removing error", QUIC_EV_CONN_ELRMHP, ctx->conn);
2127 /* XXX TO DO XXX */
2128 }
2129 else {
2130 /* The AAD includes the packet number field */
2131 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
2132 /* Store the packet into the tree of packets to decrypt. */
2133 pqpkt->pn_node.key = pqpkt->pn;
2134 quic_rx_packet_eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
2135 TRACE_PROTO("hp removed", QUIC_EV_CONN_ELRMHP, ctx->conn, pqpkt);
2136 }
2137 quic_rx_packet_list_del(pqpkt);
2138 }
2139
2140 out:
2141 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, ctx->conn);
2142}
2143
2144/* Process all the CRYPTO frame at <el> encryption level.
2145 * Return 1 if succeeded, 0 if not.
2146 */
2147static inline int qc_treat_rx_crypto_frms(struct quic_enc_level *el,
2148 struct quic_conn_ctx *ctx)
2149{
2150 struct eb64_node *node;
2151
2152 TRACE_ENTER(QUIC_EV_CONN_RXCDATA, ctx->conn);
2153 node = eb64_first(&el->rx.crypto.frms);
2154 while (node) {
2155 struct quic_rx_crypto_frm *cf;
2156
2157 cf = eb64_entry(&node->node, struct quic_rx_crypto_frm, offset_node);
2158 if (cf->offset_node.key != el->rx.crypto.offset)
2159 break;
2160
2161 if (!qc_provide_cdata(el, ctx, cf->data, cf->len, cf->pkt, cf))
2162 goto err;
2163
2164 node = eb64_next(node);
2165 quic_rx_packet_refdec(cf->pkt);
2166 eb64_delete(&cf->offset_node);
2167 pool_free(pool_head_quic_rx_crypto_frm, cf);
2168 }
2169
2170 TRACE_LEAVE(QUIC_EV_CONN_RXCDATA, ctx->conn);
2171 return 1;
2172
2173 err:
2174 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_RXCDATA, ctx->conn);
2175 return 0;
2176}
2177
2178/* Process all the packets at <el> encryption level.
2179 * Return 1 if succeeded, 0 if not.
2180 */
2181int qc_treat_rx_pkts(struct quic_enc_level *el, struct quic_conn_ctx *ctx)
2182{
2183 struct quic_tls_ctx *tls_ctx;
2184 struct eb64_node *node;
2185
2186 TRACE_ENTER(QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2187 tls_ctx = &el->tls_ctx;
2188 node = eb64_first(&el->rx.pkts);
2189 while (node) {
2190 struct quic_rx_packet *pkt;
2191
2192 pkt = eb64_entry(&node->node, struct quic_rx_packet, pn_node);
2193 if (!qc_pkt_decrypt(pkt, tls_ctx)) {
2194 /* Drop the packet */
2195 TRACE_PROTO("packet decryption failed -> dropped",
2196 QUIC_EV_CONN_ELRXPKTS, ctx->conn, pkt);
2197 }
2198 else {
2199 int drop;
2200
2201 drop = 0;
2202 if (!qc_parse_pkt_frms(pkt, ctx, el))
2203 drop = 1;
2204
2205 if (drop) {
2206 /* Drop the packet */
2207 TRACE_PROTO("packet parsing failed -> dropped",
2208 QUIC_EV_CONN_ELRXPKTS, ctx->conn, pkt);
2209 }
2210 else {
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002211 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
2212
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002213 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING) {
2214 el->pktns->rx.nb_ack_eliciting++;
2215 if (!(el->pktns->rx.nb_ack_eliciting & 1))
2216 el->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
2217 }
2218
2219 /* Update the largest packet number. */
2220 if (pkt->pn > el->pktns->rx.largest_pn)
2221 el->pktns->rx.largest_pn = pkt->pn;
2222
2223 /* Update the list of ranges to acknowledge. */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002224 if (!quic_update_ack_ranges_list(&el->pktns->rx.arngs, &ar)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002225 TRACE_DEVEL("Could not update ack range list",
2226 QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2227 node = eb64_next(node);
2228 quic_rx_packet_eb64_delete(&pkt->pn_node);
2229 free_quic_rx_packet(pkt);
2230 goto err;
2231 }
2232
2233 }
2234 }
2235 node = eb64_next(node);
2236 quic_rx_packet_eb64_delete(&pkt->pn_node);
2237 free_quic_rx_packet(pkt);
2238 }
2239
2240 if (!qc_treat_rx_crypto_frms(el, ctx))
2241 goto err;
2242
2243 TRACE_LEAVE(QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2244 return 1;
2245
2246 err:
2247 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2248 return 0;
2249}
2250
2251/* Called during handshakes to parse and build Initial and Handshake packets for QUIC
2252 * connections with <ctx> as I/O handler context.
2253 * Returns 1 if succeeded, 0 if not.
2254 */
2255int qc_do_hdshk(struct quic_conn_ctx *ctx)
2256{
2257 int ssl_err;
2258 struct quic_conn *quic_conn;
2259 enum quic_tls_enc_level tel, next_tel;
2260 struct quic_enc_level *qel, *next_qel;
2261 struct quic_tls_ctx *tls_ctx;
2262
2263 TRACE_ENTER(QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
2264
2265 ssl_err = SSL_ERROR_NONE;
2266 quic_conn = ctx->conn->qc;
2267 if (!quic_get_tls_enc_levels(&tel, &next_tel, ctx->state))
2268 goto err;
2269
2270 qel = &quic_conn->els[tel];
2271 next_qel = &quic_conn->els[next_tel];
2272
2273 next_level:
2274 tls_ctx = &qel->tls_ctx;
2275
2276 /* If the header protection key for this level has been derived,
2277 * remove the packet header protections.
2278 */
2279 if (!LIST_ISEMPTY(&qel->rx.pqpkts) &&
2280 (tls_ctx->rx.flags & QUIC_FL_TLS_SECRETS_SET))
2281 qc_rm_hp_pkts(qel, ctx);
2282
2283 if (!eb_is_empty(&qel->rx.pkts) &&
2284 !qc_treat_rx_pkts(qel, ctx))
2285 goto err;
2286
2287 if (!qc_prep_hdshk_pkts(ctx))
2288 goto err;
2289
2290 if (!qc_send_ppkts(ctx))
2291 goto err;
2292
2293 /* Check if there is something to do for the next level.
2294 */
2295 if ((next_qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_SET) &&
2296 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || !eb_is_empty(&next_qel->rx.pkts))) {
2297 qel = next_qel;
2298 goto next_level;
2299 }
2300
2301 /* If the handshake has not been completed -> out! */
2302 if (ctx->state < QUIC_HS_ST_COMPLETE)
2303 goto out;
2304
2305 /* Discard the Handshake keys. */
2306 quic_tls_discard_keys(&quic_conn->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
2307 quic_pktns_discard(quic_conn->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, quic_conn);
2308 qc_set_timer(ctx);
2309 if (!quic_build_post_handshake_frames(quic_conn) ||
2310 !qc_prep_phdshk_pkts(quic_conn) ||
2311 !qc_send_ppkts(ctx))
2312 goto err;
2313
2314 out:
2315 TRACE_LEAVE(QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
2316 return 1;
2317
2318 err:
2319 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
2320 return 0;
2321}
2322
2323/* Allocate a new QUIC connection and return it if succeeded, NULL if not. */
2324struct quic_conn *new_quic_conn(uint32_t version)
2325{
2326 struct quic_conn *quic_conn;
2327
Willy Tarreaue4498932021-03-22 21:13:05 +01002328 quic_conn = pool_zalloc(pool_head_quic_conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002329 if (quic_conn) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002330 quic_conn->version = version;
2331 }
2332
2333 return quic_conn;
2334}
2335
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05002336/* Uninitialize <qel> QUIC encryption level. Never fails. */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002337static void quic_conn_enc_level_uninit(struct quic_enc_level *qel)
2338{
2339 int i;
2340
2341 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
2342 if (qel->tx.crypto.bufs[i]) {
2343 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
2344 qel->tx.crypto.bufs[i] = NULL;
2345 }
2346 }
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002347 ha_free(&qel->tx.crypto.bufs);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002348}
2349
2350/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05002351 * connection allocating everything needed.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002352 * Returns 1 if succeeded, 0 if not.
2353 */
2354static int quic_conn_enc_level_init(struct quic_conn *qc,
2355 enum quic_tls_enc_level level)
2356{
2357 struct quic_enc_level *qel;
2358
2359 qel = &qc->els[level];
2360 qel->level = quic_to_ssl_enc_level(level);
2361 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
2362 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
2363 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
2364 qel->tls_ctx.rx.flags = 0;
2365 qel->tls_ctx.tx.flags = 0;
2366
2367 qel->rx.pkts = EB_ROOT;
2368 LIST_INIT(&qel->rx.pqpkts);
2369
2370 /* Allocate only one buffer. */
2371 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
2372 if (!qel->tx.crypto.bufs)
2373 goto err;
2374
2375 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
2376 if (!qel->tx.crypto.bufs[0])
2377 goto err;
2378
2379 qel->tx.crypto.bufs[0]->sz = 0;
2380 qel->tx.crypto.nb_buf = 1;
2381
2382 qel->tx.crypto.sz = 0;
2383 qel->tx.crypto.offset = 0;
2384
2385 return 1;
2386
2387 err:
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002388 ha_free(&qel->tx.crypto.bufs);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002389 return 0;
2390}
2391
2392/* Release the memory allocated for <buf> array of buffers, with <nb> as size.
2393 * Never fails.
2394 */
2395static inline void free_quic_conn_tx_bufs(struct q_buf **bufs, size_t nb)
2396{
2397 struct q_buf **p;
2398
2399 if (!bufs)
2400 return;
2401
2402 p = bufs;
2403 while (--nb) {
2404 if (!*p) {
2405 p++;
2406 continue;
2407 }
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002408 ha_free(&(*p)->area);
2409 ha_free(p);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002410 p++;
2411 }
2412 free(bufs);
2413}
2414
2415/* Allocate an array or <nb> buffers of <sz> bytes each.
2416 * Return this array if succeeded, NULL if failed.
2417 */
2418static inline struct q_buf **quic_conn_tx_bufs_alloc(size_t nb, size_t sz)
2419{
2420 int i;
2421 struct q_buf **bufs, **p;
2422
2423 bufs = calloc(nb, sizeof *bufs);
2424 if (!bufs)
2425 return NULL;
2426
2427 i = 0;
2428 p = bufs;
2429 while (i++ < nb) {
2430 *p = calloc(1, sizeof **p);
2431 if (!*p)
2432 goto err;
2433
2434 (*p)->area = malloc(sz);
2435 if (!(*p)->area)
2436 goto err;
2437
2438 (*p)->pos = (*p)->area;
2439 (*p)->end = (*p)->area + sz;
2440 (*p)->data = 0;
2441 LIST_INIT(&(*p)->pkts);
2442 p++;
2443 }
2444
2445 return bufs;
2446
2447 err:
2448 free_quic_conn_tx_bufs(bufs, nb);
2449 return NULL;
2450}
2451
2452/* Release all the memory allocated for <conn> QUIC connection. */
2453static void quic_conn_free(struct quic_conn *conn)
2454{
2455 int i;
2456
2457 free_quic_conn_cids(conn);
2458 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++)
2459 quic_conn_enc_level_uninit(&conn->els[i]);
2460 free_quic_conn_tx_bufs(conn->tx.bufs, conn->tx.nb_buf);
2461 if (conn->timer_task)
2462 task_destroy(conn->timer_task);
2463 pool_free(pool_head_quic_conn, conn);
2464}
2465
2466/* Callback called upon loss detection and PTO timer expirations. */
Willy Tarreau144f84a2021-03-02 16:09:26 +01002467static struct task *process_timer(struct task *task, void *ctx, unsigned int state)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002468{
2469 struct quic_conn_ctx *conn_ctx;
2470 struct quic_conn *qc;
2471 struct quic_pktns *pktns;
2472
2473
2474 conn_ctx = task->context;
2475 qc = conn_ctx->conn->qc;
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01002476 TRACE_ENTER(QUIC_EV_CONN_PTIMER, conn_ctx->conn,
2477 NULL, NULL, &qc->path->ifae_pkts);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002478 task->expire = TICK_ETERNITY;
2479 pktns = quic_loss_pktns(qc);
2480 if (tick_isset(pktns->tx.loss_time)) {
2481 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2482
2483 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
2484 if (!LIST_ISEMPTY(&lost_pkts))
2485 qc_release_lost_pkts(pktns, ctx, &lost_pkts, now_ms);
2486 qc_set_timer(conn_ctx);
2487 goto out;
2488 }
2489
2490 if (qc->path->in_flight) {
2491 pktns = quic_pto_pktns(qc, conn_ctx->state >= QUIC_HS_ST_COMPLETE, NULL);
2492 pktns->tx.pto_probe = 1;
2493 }
2494 else if (objt_server(qc->conn->target) && conn_ctx->state <= QUIC_HS_ST_COMPLETE) {
2495 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2496 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2497
2498 if (hel->tls_ctx.rx.flags == QUIC_FL_TLS_SECRETS_SET)
2499 hel->pktns->tx.pto_probe = 1;
2500 if (iel->tls_ctx.rx.flags == QUIC_FL_TLS_SECRETS_SET)
2501 iel->pktns->tx.pto_probe = 1;
2502 }
2503 qc->tx.nb_pto_dgrams = QUIC_MAX_NB_PTO_DGRAMS;
2504 tasklet_wakeup(conn_ctx->wait_event.tasklet);
2505 qc->path->loss.pto_count++;
2506
2507 out:
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01002508 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, conn_ctx->conn, pktns);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002509
2510 return task;
2511}
2512
2513/* Initialize <conn> QUIC connection with <quic_initial_clients> as root of QUIC
2514 * connections used to identify the first Initial packets of client connecting
2515 * to listeners. This parameter must be NULL for QUIC connections attached
2516 * to listeners. <dcid> is the destination connection ID with <dcid_len> as length.
2517 * <scid> is the source connection ID with <scid_len> as length.
2518 * Returns 1 if succeeded, 0 if not.
2519 */
2520int qc_new_conn_init(struct quic_conn *qc, int ipv4,
2521 struct eb_root *quic_initial_clients,
2522 struct eb_root *quic_clients,
2523 unsigned char *dcid, size_t dcid_len,
2524 unsigned char *scid, size_t scid_len)
2525{
2526 int i;
2527 /* Initial CID. */
2528 struct quic_connection_id *icid;
2529
2530 TRACE_ENTER(QUIC_EV_CONN_INIT, qc->conn);
2531 qc->cids = EB_ROOT;
2532 /* QUIC Server (or listener). */
2533 if (objt_listener(qc->conn->target)) {
2534 /* Copy the initial DCID. */
2535 qc->odcid.len = dcid_len;
2536 if (qc->odcid.len)
2537 memcpy(qc->odcid.data, dcid, dcid_len);
2538
2539 /* Copy the SCID as our DCID for this connection. */
2540 if (scid_len)
2541 memcpy(qc->dcid.data, scid, scid_len);
2542 qc->dcid.len = scid_len;
2543 }
2544 /* QUIC Client (outgoing connection to servers) */
2545 else {
2546 if (dcid_len)
2547 memcpy(qc->dcid.data, dcid, dcid_len);
2548 qc->dcid.len = dcid_len;
2549 }
2550
2551 /* Initialize the output buffer */
2552 qc->obuf.pos = qc->obuf.data;
2553
2554 icid = new_quic_cid(&qc->cids, 0);
2555 if (!icid)
2556 return 0;
2557
2558 /* Select our SCID which is the first CID with 0 as sequence number. */
2559 qc->scid = icid->cid;
2560
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05002561 /* Insert the DCID the QUIC client has chosen (only for listeners) */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002562 if (objt_listener(qc->conn->target))
2563 ebmb_insert(quic_initial_clients, &qc->odcid_node, qc->odcid.len);
2564
2565 /* Insert our SCID, the connection ID for the QUIC client. */
2566 ebmb_insert(quic_clients, &qc->scid_node, qc->scid.len);
2567
2568 /* Packet number spaces initialization. */
2569 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
2570 quic_pktns_init(&qc->pktns[i]);
2571 /* QUIC encryption level context initialization. */
2572 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
2573 if (!quic_conn_enc_level_init(qc, i))
2574 goto err;
2575 /* Initialize the packet number space. */
2576 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
2577 }
2578
2579 /* TX part. */
2580 LIST_INIT(&qc->tx.frms_to_send);
2581 qc->tx.bufs = quic_conn_tx_bufs_alloc(QUIC_CONN_TX_BUFS_NB, QUIC_CONN_TX_BUF_SZ);
2582 if (!qc->tx.bufs)
2583 goto err;
2584
2585 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
2586 qc->tx.wbuf = qc->tx.rbuf = 0;
2587 qc->tx.bytes = 0;
2588 qc->tx.nb_pto_dgrams = 0;
2589 /* RX part. */
2590 qc->rx.bytes = 0;
2591
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002592 /* XXX TO DO: Only one path at this time. */
2593 qc->path = &qc->paths[0];
2594 quic_path_init(qc->path, ipv4, default_quic_cc_algo, qc);
2595
2596 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc->conn);
2597
2598 return 1;
2599
2600 err:
2601 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_INIT, qc->conn);
2602 quic_conn_free(qc);
2603 return 0;
2604}
2605
2606/* Initialize the timer task of <qc> QUIC connection.
2607 * Returns 1 if succeeded, 0 if not.
2608 */
2609static int quic_conn_init_timer(struct quic_conn *qc)
2610{
2611 qc->timer_task = task_new(MAX_THREADS_MASK);
2612 if (!qc->timer_task)
2613 return 0;
2614
2615 qc->timer = TICK_ETERNITY;
2616 qc->timer_task->process = process_timer;
2617 qc->timer_task->context = qc->conn->xprt_ctx;
2618
2619 return 1;
2620}
2621
2622/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
2623 * past one byte of this buffer.
2624 */
2625static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
2626 struct quic_rx_packet *pkt)
2627{
2628 unsigned char dcid_len, scid_len;
2629
2630 /* Version */
2631 if (!quic_read_uint32(&pkt->version, (const unsigned char **)buf, end))
2632 return 0;
2633
2634 if (!pkt->version) { /* XXX TO DO XXX Version negotiation packet */ };
2635
2636 /* Destination Connection ID Length */
2637 dcid_len = *(*buf)++;
2638 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
2639 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1)
2640 /* XXX MUST BE DROPPED */
2641 return 0;
2642
2643 if (dcid_len) {
2644 /* Check that the length of this received DCID matches the CID lengths
2645 * of our implementation for non Initials packets only.
2646 */
2647 if (pkt->type != QUIC_PACKET_TYPE_INITIAL && dcid_len != QUIC_CID_LEN)
2648 return 0;
2649
2650 memcpy(pkt->dcid.data, *buf, dcid_len);
2651 }
2652
2653 pkt->dcid.len = dcid_len;
2654 *buf += dcid_len;
2655
2656 /* Source Connection ID Length */
2657 scid_len = *(*buf)++;
2658 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len)
2659 /* XXX MUST BE DROPPED */
2660 return 0;
2661
2662 if (scid_len)
2663 memcpy(pkt->scid.data, *buf, scid_len);
2664 pkt->scid.len = scid_len;
2665 *buf += scid_len;
2666
2667 return 1;
2668}
2669
2670/* Try to remove the header protecttion of <pkt> QUIC packet attached to <conn>
2671 * QUIC connection with <buf> as packet number field address, <end> a pointer to one
2672 * byte past the end of the buffer containing this packet and <beg> the address of
2673 * the packet first byte.
2674 * If succeeded, this function updates <*buf> to point to the next packet in the buffer.
2675 * Returns 1 if succeeded, 0 if not.
2676 */
2677static inline int qc_try_rm_hp(struct quic_rx_packet *pkt,
2678 unsigned char **buf, unsigned char *beg,
2679 const unsigned char *end,
2680 struct quic_conn_ctx *ctx)
2681{
2682 unsigned char *pn = NULL; /* Packet number field */
2683 enum quic_tls_enc_level tel;
2684 struct quic_enc_level *qel;
2685 /* Only for traces. */
2686 struct quic_rx_packet *qpkt_trace;
2687
2688 qpkt_trace = NULL;
2689 TRACE_ENTER(QUIC_EV_CONN_TRMHP, ctx->conn);
2690 /* The packet number is here. This is also the start minus
2691 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
2692 * protection.
2693 */
2694 pn = *buf;
2695 tel = quic_packet_type_enc_level(pkt->type);
2696 if (tel == QUIC_TLS_ENC_LEVEL_NONE) {
2697 TRACE_DEVEL("Wrong enc. level", QUIC_EV_CONN_TRMHP, ctx->conn);
2698 goto err;
2699 }
2700
2701 qel = &ctx->conn->qc->els[tel];
2702
2703 if (qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_DCD) {
2704 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, ctx->conn);
2705 goto err;
2706 }
2707
2708 if ((qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_SET) &&
2709 (tel != QUIC_TLS_ENC_LEVEL_APP || ctx->state >= QUIC_HS_ST_COMPLETE)) {
2710 /* Note that the following function enables us to unprotect the packet
2711 * number and its length subsequently used to decrypt the entire
2712 * packets.
2713 */
2714 if (!qc_do_rm_hp(pkt, &qel->tls_ctx,
2715 qel->pktns->rx.largest_pn, pn, beg, end, ctx)) {
2716 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, ctx->conn);
2717 goto err;
2718 }
2719
2720 /* The AAD includes the packet number field found at <pn>. */
2721 pkt->aad_len = pn - beg + pkt->pnl;
2722 qpkt_trace = pkt;
2723 /* Store the packet */
2724 pkt->pn_node.key = pkt->pn;
2725 quic_rx_packet_eb64_insert(&qel->rx.pkts, &pkt->pn_node);
2726 }
2727 else {
2728 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, ctx->conn, pkt);
2729 pkt->pn_offset = pn - beg;
2730 quic_rx_packet_list_addq(&qel->rx.pqpkts, pkt);
2731 }
2732
2733 memcpy(pkt->data, beg, pkt->len);
2734 /* Updtate the offset of <*buf> for the next QUIC packet. */
2735 *buf = beg + pkt->len;
2736
2737 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, ctx->conn, qpkt_trace);
2738 return 1;
2739
2740 err:
2741 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TRMHP, ctx->conn, qpkt_trace);
2742 return 0;
2743}
2744
2745/* Parse the header form from <byte0> first byte of <pkt> pacekt to set type.
2746 * Also set <*long_header> to 1 if this form is long, 0 if not.
2747 */
2748static inline void qc_parse_hd_form(struct quic_rx_packet *pkt,
2749 unsigned char byte0, int *long_header)
2750{
2751 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
2752 pkt->type =
2753 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
2754 *long_header = 1;
2755 }
2756 else {
2757 pkt->type = QUIC_PACKET_TYPE_SHORT;
2758 *long_header = 0;
2759 }
2760}
2761
2762static ssize_t qc_srv_pkt_rcv(unsigned char **buf, const unsigned char *end,
2763 struct quic_rx_packet *pkt,
2764 struct quic_dgram_ctx *dgram_ctx,
2765 struct sockaddr_storage *saddr)
2766{
2767 unsigned char *beg;
2768 uint64_t len;
2769 struct quic_conn *qc;
2770 struct eb_root *cids;
2771 struct ebmb_node *node;
2772 struct connection *srv_conn;
2773 struct quic_conn_ctx *conn_ctx;
2774 int long_header;
2775
2776 qc = NULL;
2777 TRACE_ENTER(QUIC_EV_CONN_SPKT);
2778 if (end <= *buf)
2779 goto err;
2780
2781 /* Fixed bit */
2782 if (!(**buf & QUIC_PACKET_FIXED_BIT))
2783 /* XXX TO BE DISCARDED */
2784 goto err;
2785
2786 srv_conn = dgram_ctx->owner;
2787 beg = *buf;
2788 /* Header form */
2789 qc_parse_hd_form(pkt, *(*buf)++, &long_header);
2790 if (long_header) {
2791 size_t cid_lookup_len;
2792
2793 if (!quic_packet_read_long_header(buf, end, pkt))
2794 goto err;
2795
2796 /* For Initial packets, and for servers (QUIC clients connections),
2797 * there is no Initial connection IDs storage.
2798 */
2799 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2800 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2801 cid_lookup_len = pkt->dcid.len;
2802 }
2803 else {
2804 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2805 cid_lookup_len = QUIC_CID_LEN;
2806 }
2807
2808 node = ebmb_lookup(cids, pkt->dcid.data, cid_lookup_len);
2809 if (!node)
2810 goto err;
2811
2812 qc = ebmb_entry(node, struct quic_conn, scid_node);
2813
2814 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2815 qc->dcid.len = pkt->scid.len;
2816 if (pkt->scid.len)
2817 memcpy(qc->dcid.data, pkt->scid.data, pkt->scid.len);
2818 }
2819
2820 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2821 uint64_t token_len;
2822
2823 if (!quic_dec_int(&token_len, (const unsigned char **)buf, end) || end - *buf < token_len)
2824 goto err;
2825
2826 /* XXX TO DO XXX 0 value means "the token is not present".
2827 * A server which sends an Initial packet must not set the token.
2828 * So, a client which receives an Initial packet with a token
2829 * MUST discard the packet or generate a connection error with
2830 * PROTOCOL_VIOLATION as type.
2831 * The token must be provided in a Retry packet or NEW_TOKEN frame.
2832 */
2833 pkt->token_len = token_len;
2834 }
2835 }
2836 else {
2837 /* XXX TO DO: Short header XXX */
2838 if (end - *buf < QUIC_CID_LEN)
2839 goto err;
2840
2841 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2842 node = ebmb_lookup(cids, *buf, QUIC_CID_LEN);
2843 if (!node)
2844 goto err;
2845
2846 qc = ebmb_entry(node, struct quic_conn, scid_node);
2847 *buf += QUIC_CID_LEN;
2848 }
2849 /* Store the DCID used for this packet to check the packet which
2850 * come in this UDP datagram match with it.
2851 */
2852 if (!dgram_ctx->dcid_node)
2853 dgram_ctx->dcid_node = node;
2854 /* Only packets packets with long headers and not RETRY or VERSION as type
2855 * have a length field.
2856 */
2857 if (long_header && pkt->type != QUIC_PACKET_TYPE_RETRY && pkt->version) {
2858 if (!quic_dec_int(&len, (const unsigned char **)buf, end) || end - *buf < len)
2859 goto err;
2860
2861 pkt->len = len;
2862 }
2863 else if (!long_header) {
2864 /* A short packet is the last one of an UDP datagram. */
2865 pkt->len = end - *buf;
2866 }
2867
2868 conn_ctx = qc->conn->xprt_ctx;
2869
2870 /* Increase the total length of this packet by the header length. */
2871 pkt->len += *buf - beg;
2872 /* Do not check the DCID node before the length. */
2873 if (dgram_ctx->dcid_node != node) {
2874 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_SPKT, qc->conn);
2875 goto err;
2876 }
2877
2878 if (pkt->len > sizeof pkt->data) {
2879 TRACE_PROTO("Too big packet", QUIC_EV_CONN_SPKT, qc->conn, pkt, &pkt->len);
2880 goto err;
2881 }
2882
2883 if (!qc_try_rm_hp(pkt, buf, beg, end, conn_ctx))
2884 goto err;
2885
2886 /* Wake the tasklet of the QUIC connection packet handler. */
2887 if (conn_ctx)
2888 tasklet_wakeup(conn_ctx->wait_event.tasklet);
2889
2890 TRACE_LEAVE(QUIC_EV_CONN_SPKT, qc->conn);
2891
2892 return pkt->len;
2893
2894 err:
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01002895 TRACE_DEVEL("Leaing in error", QUIC_EV_CONN_SPKT, qc ? qc->conn : NULL);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002896 return -1;
2897}
2898
2899static ssize_t qc_lstnr_pkt_rcv(unsigned char **buf, const unsigned char *end,
2900 struct quic_rx_packet *pkt,
2901 struct quic_dgram_ctx *dgram_ctx,
2902 struct sockaddr_storage *saddr)
2903{
2904 unsigned char *beg;
2905 uint64_t len;
2906 struct quic_conn *qc;
2907 struct eb_root *cids;
2908 struct ebmb_node *node;
2909 struct listener *l;
2910 struct quic_conn_ctx *conn_ctx;
2911 int long_header = 0;
2912
2913 qc = NULL;
2914 TRACE_ENTER(QUIC_EV_CONN_LPKT);
2915 if (end <= *buf)
2916 goto err;
2917
2918 /* Fixed bit */
2919 if (!(**buf & QUIC_PACKET_FIXED_BIT)) {
2920 /* XXX TO BE DISCARDED */
2921 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2922 goto err;
2923 }
2924
2925 l = dgram_ctx->owner;
2926 beg = *buf;
2927 /* Header form */
2928 qc_parse_hd_form(pkt, *(*buf)++, &long_header);
2929 if (long_header) {
2930 unsigned char dcid_len;
2931
2932 if (!quic_packet_read_long_header(buf, end, pkt)) {
2933 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2934 goto err;
2935 }
2936
2937 dcid_len = pkt->dcid.len;
2938 /* For Initial packets, and for servers (QUIC clients connections),
2939 * there is no Initial connection IDs storage.
2940 */
2941 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2942 /* DCIDs of first packets coming from clients may have the same values.
2943 * Let's distinguish them concatenating the socket addresses to the DCIDs.
2944 */
2945 quic_cid_saddr_cat(&pkt->dcid, saddr);
2946 cids = &l->rx.odcids;
2947 }
2948 else {
2949 if (pkt->dcid.len != QUIC_CID_LEN) {
2950 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2951 goto err;
2952 }
2953
2954 cids = &l->rx.cids;
2955 }
2956
2957 node = ebmb_lookup(cids, pkt->dcid.data, pkt->dcid.len);
2958 if (!node && pkt->type == QUIC_PACKET_TYPE_INITIAL && dcid_len == QUIC_CID_LEN &&
2959 cids == &l->rx.odcids) {
2960 /* Switch to the definitive tree ->cids containing the final CIDs. */
2961 node = ebmb_lookup(&l->rx.cids, pkt->dcid.data, dcid_len);
2962 if (node) {
2963 /* If found, signal this with NULL as special value for <cids>. */
2964 pkt->dcid.len = dcid_len;
2965 cids = NULL;
2966 }
2967 }
2968
2969 if (!node) {
2970 if (pkt->type != QUIC_PACKET_TYPE_INITIAL) {
2971 TRACE_PROTO("Non Initiial packet", QUIC_EV_CONN_LPKT);
2972 goto err;
2973 }
2974
2975 qc = new_quic_conn(pkt->version);
2976 if (!qc) {
2977 TRACE_PROTO("Non allocated new connection", QUIC_EV_CONN_LPKT);
2978 goto err;
2979 }
2980
2981 pkt->qc = qc;
2982 pkt->saddr = *saddr;
2983 /* Note that here, odcid_len equals to pkt->dcid.len minus the length
2984 * of <saddr>.
2985 */
2986 pkt->odcid_len = dcid_len;
2987 /* Enqueue this packet. */
Willy Tarreau2b718102021-04-21 07:32:39 +02002988 LIST_APPEND(&l->rx.qpkts, &pkt->rx_list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002989 /* Try to accept a new connection. */
2990 listener_accept(l);
2991 if (!qc->conn) {
2992 TRACE_PROTO("Non accepted connection", QUIC_EV_CONN_LPKT, qc->conn);
2993 goto err;
2994 }
2995
2996 if (!quic_conn_init_timer(qc)) {
2997 TRACE_PROTO("Non initialized timer", QUIC_EV_CONN_LPKT, qc->conn);
2998 goto err;
2999 }
3000
3001 /* This is the DCID node sent in this packet by the client. */
3002 node = &qc->odcid_node;
3003 conn_ctx = qc->conn->xprt_ctx;
3004 SSL_set_quic_transport_params(conn_ctx->ssl,
3005 qc->enc_params, qc->enc_params_len);
3006 }
3007 else {
3008 if (pkt->type == QUIC_PACKET_TYPE_INITIAL && cids == &l->rx.odcids)
3009 qc = ebmb_entry(node, struct quic_conn, odcid_node);
3010 else
3011 qc = ebmb_entry(node, struct quic_conn, scid_node);
3012 }
3013
3014 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
3015 uint64_t token_len;
3016 struct quic_tls_ctx *ctx =
3017 &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
3018
3019 if (!quic_dec_int(&token_len, (const unsigned char **)buf, end) ||
3020 end - *buf < token_len) {
3021 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3022 goto err;
3023 }
3024
3025 /* XXX TO DO XXX 0 value means "the token is not present".
3026 * A server which sends an Initial packet must not set the token.
3027 * So, a client which receives an Initial packet with a token
3028 * MUST discard the packet or generate a connection error with
3029 * PROTOCOL_VIOLATION as type.
3030 * The token must be provided in a Retry packet or NEW_TOKEN frame.
3031 */
3032 pkt->token_len = token_len;
3033 /* NOTE: the socket address has been concatenated to the destination ID
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003034 * chosen by the client for Initial packets.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003035 */
3036 if (!ctx->rx.hp && !qc_new_isecs(qc->conn, pkt->dcid.data,
3037 pkt->odcid_len, 1)) {
3038 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3039 goto err;
3040 }
3041 }
3042 }
3043 else {
3044 if (end - *buf < QUIC_CID_LEN) {
3045 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
3046 goto err;
3047 }
3048
3049 cids = &l->rx.cids;
3050 node = ebmb_lookup(cids, *buf, QUIC_CID_LEN);
3051 if (!node) {
3052 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
3053 goto err;
3054 }
3055
3056 qc = ebmb_entry(node, struct quic_conn, scid_node);
3057 *buf += QUIC_CID_LEN;
3058 }
3059
3060 /* Store the DCID used for this packet to check the packet which
3061 * come in this UDP datagram match with it.
3062 */
3063 if (!dgram_ctx->dcid_node) {
3064 dgram_ctx->dcid_node = node;
3065 dgram_ctx->qc = qc;
3066 }
3067
3068 /* Only packets packets with long headers and not RETRY or VERSION as type
3069 * have a length field.
3070 */
3071 if (long_header && pkt->type != QUIC_PACKET_TYPE_RETRY && pkt->version) {
3072 if (!quic_dec_int(&len, (const unsigned char **)buf, end) ||
3073 end - *buf < len) {
3074 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3075 goto err;
3076 }
3077
3078 pkt->len = len;
3079 }
3080 else if (!long_header) {
3081 /* A short packet is the last one of an UDP datagram. */
3082 pkt->len = end - *buf;
3083 }
3084
3085 /* Update the state if needed. */
3086 conn_ctx = qc->conn->xprt_ctx;
3087
3088 /* Increase the total length of this packet by the header length. */
3089 pkt->len += *buf - beg;
3090 /* Do not check the DCID node before the length. */
3091 if (dgram_ctx->dcid_node != node) {
3092 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3093 goto err;
3094 }
3095
3096 if (pkt->len > sizeof pkt->data) {
3097 TRACE_PROTO("Too big packet", QUIC_EV_CONN_LPKT, qc->conn, pkt, &pkt->len);
3098 goto err;
3099 }
3100
3101 if (!qc_try_rm_hp(pkt, buf, beg, end, conn_ctx)) {
3102 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3103 goto err;
3104 }
3105
3106 /* Wake the tasklet of the QUIC connection packet handler. */
3107 if (conn_ctx)
3108 tasklet_wakeup(conn_ctx->wait_event.tasklet);
3109 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc->conn, pkt);
3110
3111 return pkt->len;
3112
3113 err:
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01003114 TRACE_DEVEL("Leaving in error", QUIC_EV_CONN_LPKT,
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003115 qc ? qc->conn : NULL, pkt);
3116 return -1;
3117}
3118
3119/* This function builds into <buf> buffer a QUIC long packet header whose size may be computed
3120 * in advance. This is the reponsability of the caller to check there is enough room in this
3121 * buffer to build a long header.
3122 * Returns 0 if <type> QUIC packet type is not supported by long header, or 1 if succeeded.
3123 */
3124static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
3125 int type, size_t pn_len, struct quic_conn *conn)
3126{
3127 if (type > QUIC_PACKET_TYPE_RETRY)
3128 return 0;
3129
3130 /* #0 byte flags */
3131 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
3132 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
3133 /* Version */
3134 quic_write_uint32(buf, end, conn->version);
3135 *(*buf)++ = conn->dcid.len;
3136 /* Destination connection ID */
3137 if (conn->dcid.len) {
3138 memcpy(*buf, conn->dcid.data, conn->dcid.len);
3139 *buf += conn->dcid.len;
3140 }
3141 /* Source connection ID */
3142 *(*buf)++ = conn->scid.len;
3143 if (conn->scid.len) {
3144 memcpy(*buf, conn->scid.data, conn->scid.len);
3145 *buf += conn->scid.len;
3146 }
3147
3148 return 1;
3149}
3150
3151/* This function builds into <buf> buffer a QUIC long packet header whose size may be computed
3152 * in advance. This is the reponsability of the caller to check there is enough room in this
3153 * buffer to build a long header.
3154 * Returns 0 if <type> QUIC packet type is not supported by long header, or 1 if succeeded.
3155 */
3156static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
3157 size_t pn_len, struct quic_conn *conn)
3158{
3159 /* #0 byte flags */
3160 *(*buf)++ = QUIC_PACKET_FIXED_BIT | (pn_len - 1);
3161 /* Destination connection ID */
3162 if (conn->dcid.len) {
3163 memcpy(*buf, conn->dcid.data, conn->dcid.len);
3164 *buf += conn->dcid.len;
3165 }
3166
3167 return 1;
3168}
3169
3170/* Apply QUIC header protection to the packet with <buf> as first byte address,
3171 * <pn> as address of the Packet number field, <pnlen> being this field length
3172 * with <aead> as AEAD cipher and <key> as secret key.
3173 * Returns 1 if succeeded or 0 if failed.
3174 */
3175static int quic_apply_header_protection(unsigned char *buf, unsigned char *pn, size_t pnlen,
3176 const EVP_CIPHER *aead, const unsigned char *key)
3177{
3178 int i, ret, outlen;
3179 EVP_CIPHER_CTX *ctx;
3180 /* We need an IV of at least 5 bytes: one byte for bytes #0
3181 * and at most 4 bytes for the packet number
3182 */
3183 unsigned char mask[5] = {0};
3184
3185 ret = 0;
3186 ctx = EVP_CIPHER_CTX_new();
3187 if (!ctx)
3188 return 0;
3189
3190 if (!EVP_EncryptInit_ex(ctx, aead, NULL, key, pn + QUIC_PACKET_PN_MAXLEN) ||
3191 !EVP_EncryptUpdate(ctx, mask, &outlen, mask, sizeof mask) ||
3192 !EVP_EncryptFinal_ex(ctx, mask, &outlen))
3193 goto out;
3194
3195 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
3196 for (i = 0; i < pnlen; i++)
3197 pn[i] ^= mask[i + 1];
3198
3199 ret = 1;
3200
3201 out:
3202 EVP_CIPHER_CTX_free(ctx);
3203
3204 return ret;
3205}
3206
3207/* Reduce the encoded size of <ack_frm> ACK frame removing the last
3208 * ACK ranges if needed to a value below <limit> in bytes.
3209 * Return 1 if succeeded, 0 if not.
3210 */
3211static int quic_ack_frm_reduce_sz(struct quic_frame *ack_frm, size_t limit)
3212{
3213 size_t room, ack_delay_sz;
3214
3215 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
3216 /* A frame is made of 1 byte for the frame type. */
3217 room = limit - ack_delay_sz - 1;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003218 if (!quic_rm_last_ack_ranges(ack_frm->tx_ack.arngs, room))
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003219 return 0;
3220
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003221 return 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003222}
3223
3224/* Prepare as most as possible CRYPTO frames from prebuilt CRYPTO frames for <qel>
3225 * encryption level to be encoded in a buffer with <room> as available room,
Frédéric Lécailleea604992020-12-24 13:01:37 +01003226 * and <*len> the packet Length field initialized with the number of bytes already present
3227 * in this buffer which must be taken into an account for the Length packet field value.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003228 * <headlen> is the number of bytes already present in this packet before building
Frédéric Lécailleea604992020-12-24 13:01:37 +01003229 * CRYPTO frames.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003230 * This is the responsibility of the caller to check that <*len> < <room> as this is
3231 * the responsibility to check that <headlen> < quic_path_prep_data(conn->path).
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003232 * Update consequently <*len> to reflect the size of these CRYPTO frames built
3233 * by this function. Also attach these CRYPTO frames to <pkt> QUIC packet.
3234 * Return 1 if succeeded, 0 if not.
3235 */
3236static inline int qc_build_cfrms(struct quic_tx_packet *pkt,
Frédéric Lécailleea604992020-12-24 13:01:37 +01003237 size_t room, size_t *len, size_t headlen,
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003238 struct quic_enc_level *qel,
3239 struct quic_conn *conn)
3240{
Frédéric Lécailleea604992020-12-24 13:01:37 +01003241 int ret;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003242 struct quic_tx_frm *cf, *cfbak;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003243
Frédéric Lécailleea604992020-12-24 13:01:37 +01003244 ret = 0;
3245 /* If we are not probing we must take into an account the congestion
3246 * control window.
3247 */
3248 if (!conn->tx.nb_pto_dgrams)
3249 room = QUIC_MIN(room, quic_path_prep_data(conn->path) - headlen);
3250 TRACE_PROTO("************** CRYPTO frames build (headlen)",
3251 QUIC_EV_CONN_BCFRMS, conn->conn, &headlen);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003252 list_for_each_entry_safe(cf, cfbak, &qel->pktns->tx.frms, list) {
3253 /* header length, data length, frame length. */
3254 size_t hlen, dlen, cflen;
3255
Frédéric Lécailleea604992020-12-24 13:01:37 +01003256 TRACE_PROTO(" New CRYPTO frame build (room, len)",
3257 QUIC_EV_CONN_BCFRMS, conn->conn, &room, len);
3258 if (!room)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003259 break;
3260
3261 /* Compute the length of this CRYPTO frame header */
3262 hlen = 1 + quic_int_getsize(cf->crypto.offset);
3263 /* Compute the data length of this CRyPTO frame. */
3264 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
Frédéric Lécailleea604992020-12-24 13:01:37 +01003265 TRACE_PROTO(" CRYPTO data length (hlen, crypto.len, dlen)",
3266 QUIC_EV_CONN_BCFRMS, conn->conn, &hlen, &cf->crypto.len, &dlen);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003267 if (!dlen)
3268 break;
3269
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003270 pkt->cdata_len += dlen;
3271 /* CRYPTO frame length. */
3272 cflen = hlen + quic_int_getsize(dlen) + dlen;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003273 TRACE_PROTO(" CRYPTO frame length (cflen)",
3274 QUIC_EV_CONN_BCFRMS, conn->conn, &cflen);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003275 /* Add the CRYPTO data length and its encoded length to the packet
3276 * length and the length of this length.
3277 */
3278 *len += cflen;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003279 room -= cflen;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003280 if (dlen == cf->crypto.len) {
3281 /* <cf> CRYPTO data have been consumed. */
Willy Tarreau2b718102021-04-21 07:32:39 +02003282 LIST_DELETE(&cf->list);
3283 LIST_APPEND(&pkt->frms, &cf->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003284 }
3285 else {
3286 struct quic_tx_frm *new_cf;
3287
3288 new_cf = pool_alloc(pool_head_quic_tx_frm);
3289 if (!new_cf) {
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01003290 TRACE_PROTO("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003291 return 0;
3292 }
3293
3294 new_cf->type = QUIC_FT_CRYPTO;
3295 new_cf->crypto.len = dlen;
3296 new_cf->crypto.offset = cf->crypto.offset;
Willy Tarreau2b718102021-04-21 07:32:39 +02003297 LIST_APPEND(&pkt->frms, &new_cf->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003298 /* Consume <dlen> bytes of the current frame. */
3299 cf->crypto.len -= dlen;
3300 cf->crypto.offset += dlen;
3301 }
Frédéric Lécailleea604992020-12-24 13:01:37 +01003302 ret = 1;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003303 }
3304
Frédéric Lécailleea604992020-12-24 13:01:37 +01003305 return ret;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003306}
3307
3308/* This function builds a clear handshake packet used during a QUIC TLS handshakes
3309 * into <wbuf> the current <wbuf> for <conn> QUIC connection with <qel> as QUIC
3310 * TLS encryption level for outgoing packets filling it with as much as CRYPTO
3311 * data as possible from <offset> offset in the CRYPTO data stream. Note that
3312 * this offset value is updated by the length of the CRYPTO frame used to embed
3313 * the CRYPTO data if this packet and only if the packet is successfully built.
3314 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
3315 * reserved so that to be sure there is enough room to build this AEAD TAG after
3316 * having successfully returned from this function and to be sure the position
3317 * pointer of <wbuf> may be safely incremented by QUIC_TLS_TAG_LEN. After having
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003318 * returned from this function, <wbuf> position will point one past the last
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003319 * byte of the payload with the confidence there is at least QUIC_TLS_TAG_LEN bytes
3320 * available packet to encrypt this packet.
3321 * This function also update the value of <buf_pn> pointer to point to the packet
3322 * number field in this packet. <pn_len> will also have the packet number
3323 * length as value.
3324 *
3325 * Return the length of the packet if succeeded minus QUIC_TLS_TAG_LEN, or -1 if
3326 * failed (not enough room in <wbuf> to build this packet plus QUIC_TLS_TAG_LEN
3327 * bytes), -2 if there are too much CRYPTO data in flight to build a packet.
3328 */
3329static ssize_t qc_do_build_hdshk_pkt(struct q_buf *wbuf,
3330 struct quic_tx_packet *pkt, int pkt_type,
3331 int64_t pn, size_t *pn_len,
3332 unsigned char **buf_pn,
3333 struct quic_enc_level *qel,
3334 struct quic_conn *conn)
3335{
3336 unsigned char *beg, *pos;
3337 const unsigned char *end;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003338 size_t len, len_frms, token_fields_len, padding_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003339 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
3340 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
3341 struct quic_crypto *crypto = &frm.crypto;
3342 size_t ack_frm_len;
3343 int64_t largest_acked_pn;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003344 int add_ping_frm;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003345
Frédéric Lécailleea604992020-12-24 13:01:37 +01003346 /* Length field value with CRYPTO frames if present. */
3347 len_frms = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003348 beg = pos = q_buf_getpos(wbuf);
3349 end = q_buf_end(wbuf);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003350 /* When not probing and not acking, reduce the size of this buffer to respect
3351 * the congestion controller window.
3352 */
3353 if (!conn->tx.nb_pto_dgrams && !(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED)) {
3354 size_t path_room;
3355
3356 path_room = quic_path_prep_data(conn->path);
3357 if (end - beg > path_room)
3358 end = beg + path_room;
3359 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003360
3361 /* For a server, the token field of an Initial packet is empty. */
3362 token_fields_len = pkt_type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0;
3363
3364 /* Check there is enough room to build the header followed by a token. */
3365 if (end - pos < QUIC_LONG_PACKET_MINLEN + conn->dcid.len +
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003366 conn->scid.len + token_fields_len + QUIC_TLS_TAG_LEN) {
3367 ssize_t room = end - pos;
3368 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3369 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003370 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003371 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003372
3373 /* Reserve enough room at the end of the packet for the AEAD TAG. */
3374 end -= QUIC_TLS_TAG_LEN;
3375 largest_acked_pn = qel->pktns->tx.largest_acked_pn;
3376 /* packet number length */
3377 *pn_len = quic_packet_number_length(pn, largest_acked_pn);
3378
3379 quic_build_packet_long_header(&pos, end, pkt_type, *pn_len, conn);
3380
3381 /* Encode the token length (0) for an Initial packet. */
3382 if (pkt_type == QUIC_PACKET_TYPE_INITIAL)
3383 *pos++ = 0;
3384
3385 /* Build an ACK frame if required. */
3386 ack_frm_len = 0;
3387 if ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003388 !eb_is_empty(&qel->pktns->rx.arngs.root)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003389 ack_frm.tx_ack.ack_delay = 0;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003390 ack_frm.tx_ack.arngs = &qel->pktns->rx.arngs;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003391 ack_frm_len = quic_ack_frm_reduce_sz(&ack_frm, end - pos);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003392 if (!ack_frm_len) {
3393 ssize_t room = end - pos;
3394 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3395 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003396 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003397 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003398
3399 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
3400 }
3401
3402 /* Length field value without the CRYPTO frames data length. */
3403 len = ack_frm_len + *pn_len;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003404 if (!LIST_ISEMPTY(&qel->pktns->tx.frms)) {
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003405 ssize_t room = end - pos;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003406
3407 len_frms = len + QUIC_TLS_TAG_LEN;
3408 if (!qc_build_cfrms(pkt, end - pos, &len_frms, pos - beg, qel, conn)) {
3409 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3410 conn->conn, NULL, NULL, &room);
3411 goto err;
3412 }
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003413 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003414
3415 add_ping_frm = 0;
3416 padding_len = 0;
3417 if (objt_server(conn->conn->target) &&
3418 pkt_type == QUIC_PACKET_TYPE_INITIAL &&
3419 len < QUIC_INITIAL_PACKET_MINLEN) {
3420 len += padding_len = QUIC_INITIAL_PACKET_MINLEN - len;
3421 }
3422 else if (LIST_ISEMPTY(&pkt->frms)) {
3423 if (qel->pktns->tx.pto_probe) {
3424 /* If we cannot send a CRYPTO frame, we send a PING frame. */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003425 add_ping_frm = 1;
3426 len += 1;
3427 }
3428 /* If there is no frame at all to follow, add at least a PADDING frame. */
3429 if (!ack_frm_len)
3430 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
3431 }
3432
3433 /* Length (of the remaining data). Must not fail because, the buffer size
3434 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
3435 * for the encryption TAG. It must be taken into an account for the length
3436 * of this packet.
3437 */
Frédéric Lécailleea604992020-12-24 13:01:37 +01003438 if (len_frms)
3439 len = len_frms;
3440 else
3441 len += QUIC_TLS_TAG_LEN;
3442 quic_enc_int(&pos, end, len);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003443
3444 /* Packet number field address. */
3445 *buf_pn = pos;
3446
3447 /* Packet number encoding. */
3448 quic_packet_number_encode(&pos, end, pn, *pn_len);
3449
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003450 if (ack_frm_len && !qc_build_frm(&pos, end, &ack_frm, pkt, conn)) {
3451 ssize_t room = end - pos;
3452 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3453 conn->conn, NULL, NULL, &room);
3454 goto err;
3455 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003456
3457 /* Crypto frame */
3458 if (!LIST_ISEMPTY(&pkt->frms)) {
3459 struct quic_tx_frm *cf;
3460
3461 list_for_each_entry(cf, &pkt->frms, list) {
3462 crypto->offset = cf->crypto.offset;
3463 crypto->len = cf->crypto.len;
3464 crypto->qel = qel;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003465 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3466 ssize_t room = end - pos;
3467 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3468 conn->conn, NULL, NULL, &room);
3469 goto err;
3470 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003471 }
3472 }
3473
3474 /* Build a PING frame if needed. */
3475 if (add_ping_frm) {
3476 frm.type = QUIC_FT_PING;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003477 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3478 ssize_t room = end - pos;
3479 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3480 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003481 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003482 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003483 }
3484
3485 /* Build a PADDING frame if needed. */
3486 if (padding_len) {
3487 frm.type = QUIC_FT_PADDING;
3488 frm.padding.len = padding_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003489 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3490 ssize_t room = end - pos;
3491 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3492 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003493 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003494 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003495 }
3496
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003497 /* Always reset this variable as this function has no idea
3498 * if it was set. It is handle by the loss detection timer.
3499 */
3500 qel->pktns->tx.pto_probe = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003501
3502 out:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003503 return pos - beg;
3504
3505 err:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003506 return -1;
3507}
3508
3509static inline void quic_tx_packet_init(struct quic_tx_packet *pkt)
3510{
3511 pkt->cdata_len = 0;
3512 pkt->in_flight_len = 0;
3513 LIST_INIT(&pkt->frms);
3514}
3515
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003516/* Free <pkt> TX packet which has not already attached to any tree. */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003517static inline void free_quic_tx_packet(struct quic_tx_packet *pkt)
3518{
3519 struct quic_tx_frm *frm, *frmbak;
3520
3521 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list) {
Willy Tarreau2b718102021-04-21 07:32:39 +02003522 LIST_DELETE(&frm->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003523 pool_free(pool_head_quic_tx_frm, frm);
3524 }
3525 pool_free(pool_head_quic_tx_packet, pkt);
3526}
3527
3528/* Build a handshake packet into <buf> packet buffer with <pkt_type> as packet
3529 * type for <qc> QUIC connection from CRYPTO data stream at <*offset> offset to
3530 * be encrypted at <qel> encryption level.
3531 * Return -2 if the packet could not be encrypted for any reason, -1 if there was
3532 * not enough room in <buf> to build the packet, or the size of the built packet
3533 * if succeeded (may be zero if there is too much crypto data in flight to build the packet).
3534 */
3535static ssize_t qc_build_hdshk_pkt(struct q_buf *buf, struct quic_conn *qc, int pkt_type,
3536 struct quic_enc_level *qel)
3537{
3538 /* The pointer to the packet number field. */
3539 unsigned char *buf_pn;
3540 unsigned char *beg, *end, *payload;
3541 int64_t pn;
3542 size_t pn_len, payload_len, aad_len;
3543 ssize_t pkt_len;
3544 struct quic_tls_ctx *tls_ctx;
3545 struct quic_tx_packet *pkt;
3546
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003547 TRACE_ENTER(QUIC_EV_CONN_HPKT, qc->conn, NULL, qel);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003548 pkt = pool_alloc(pool_head_quic_tx_packet);
3549 if (!pkt) {
3550 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_HPKT, qc->conn);
3551 return -2;
3552 }
3553
3554 quic_tx_packet_init(pkt);
3555 beg = q_buf_getpos(buf);
3556 pn_len = 0;
3557 buf_pn = NULL;
3558 pn = qel->pktns->tx.next_pn + 1;
3559 pkt_len = qc_do_build_hdshk_pkt(buf, pkt, pkt_type, pn, &pn_len, &buf_pn, qel, qc);
3560 if (pkt_len <= 0) {
3561 free_quic_tx_packet(pkt);
3562 return pkt_len;
3563 }
3564
3565 end = beg + pkt_len;
3566 payload = buf_pn + pn_len;
3567 payload_len = end - payload;
3568 aad_len = payload - beg;
3569
3570 tls_ctx = &qel->tls_ctx;
3571 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc->conn))
3572 goto err;
3573
3574 end += QUIC_TLS_TAG_LEN;
3575 pkt_len += QUIC_TLS_TAG_LEN;
3576 if (!quic_apply_header_protection(beg, buf_pn, pn_len,
3577 tls_ctx->tx.hp, tls_ctx->tx.hp_key)) {
3578 TRACE_DEVEL("Could not apply the header protection", QUIC_EV_CONN_HPKT, qc->conn);
3579 goto err;
3580 }
3581
3582 /* Now that a correct packet is built, let us set the position pointer of
3583 * <buf> buffer for the next packet.
3584 */
3585 q_buf_setpos(buf, end);
3586 /* Consume a packet number. */
3587 ++qel->pktns->tx.next_pn;
3588 /* Attach the built packet to its tree. */
3589 pkt->pn_node.key = qel->pktns->tx.next_pn;
3590 /* Set the packet in fligth length for in flight packet only. */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003591 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003592 pkt->in_flight_len = pkt_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003593 qc->path->prep_in_flight += pkt_len;
3594 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003595 pkt->pktns = qel->pktns;
3596 eb64_insert(&qel->pktns->tx.pkts, &pkt->pn_node);
3597 /* Increment the number of bytes in <buf> buffer by the length of this packet. */
3598 buf->data += pkt_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003599 /* Attach this packet to <buf>. */
Willy Tarreau2b718102021-04-21 07:32:39 +02003600 LIST_APPEND(&buf->pkts, &pkt->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003601 TRACE_LEAVE(QUIC_EV_CONN_HPKT, qc->conn, pkt);
3602
3603 return pkt_len;
3604
3605 err:
3606 free_quic_tx_packet(pkt);
3607 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_HPKT, qc->conn);
3608 return -2;
3609}
3610
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003611/* Prepare a clear post handhskake packet for <conn> QUIC connection.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003612 * Return the length of this packet if succeeded, -1 <wbuf> was full.
3613 */
3614static ssize_t qc_do_build_phdshk_apkt(struct q_buf *wbuf,
3615 struct quic_tx_packet *pkt,
3616 int64_t pn, size_t *pn_len,
3617 unsigned char **buf_pn, struct quic_enc_level *qel,
3618 struct quic_conn *conn)
3619{
3620 const unsigned char *beg, *end;
3621 unsigned char *pos;
3622 struct quic_frame *frm, *sfrm;
3623 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
3624 size_t fake_len, ack_frm_len;
3625 int64_t largest_acked_pn;
3626
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003627 TRACE_ENTER(QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003628 beg = pos = q_buf_getpos(wbuf);
3629 end = q_buf_end(wbuf);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003630 /* When not probing and not acking, reduce the size of this buffer to respect
3631 * the congestion controller window.
3632 */
3633 if (!conn->tx.nb_pto_dgrams && !(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED)) {
3634 size_t path_room;
3635
3636 path_room = quic_path_prep_data(conn->path);
3637 if (end - beg > path_room)
3638 end = beg + path_room;
3639 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003640 largest_acked_pn = qel->pktns->tx.largest_acked_pn;
3641 /* Packet number length */
3642 *pn_len = quic_packet_number_length(pn, largest_acked_pn);
3643 /* Check there is enough room to build this packet (without payload). */
3644 if (end - pos < QUIC_SHORT_PACKET_MINLEN + sizeof_quic_cid(&conn->dcid) +
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003645 *pn_len + QUIC_TLS_TAG_LEN) {
3646 ssize_t room = end - pos;
3647 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3648 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003649 goto err;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003650 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003651
3652 /* Reserve enough room at the end of the packet for the AEAD TAG. */
3653 end -= QUIC_TLS_TAG_LEN;
3654 quic_build_packet_short_header(&pos, end, *pn_len, conn);
3655 /* Packet number field. */
3656 *buf_pn = pos;
3657 /* Packet number encoding. */
3658 quic_packet_number_encode(&pos, end, pn, *pn_len);
3659
3660 /* Build an ACK frame if required. */
3661 ack_frm_len = 0;
3662 if ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003663 !eb_is_empty(&qel->pktns->rx.arngs.root)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003664 ack_frm.tx_ack.ack_delay = 0;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003665 ack_frm.tx_ack.arngs = &qel->pktns->rx.arngs;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003666 ack_frm_len = quic_ack_frm_reduce_sz(&ack_frm, end - pos);
3667 if (!ack_frm_len)
3668 goto err;
3669
3670 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
3671 }
3672
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003673 if (ack_frm_len && !qc_build_frm(&pos, end, &ack_frm, pkt, conn)) {
3674 ssize_t room = end - pos;
3675 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3676 conn->conn, NULL, NULL, &room);
3677 goto err;
3678 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003679
3680 fake_len = ack_frm_len;
3681 if (!LIST_ISEMPTY(&qel->pktns->tx.frms) &&
Frédéric Lécailleea604992020-12-24 13:01:37 +01003682 !qc_build_cfrms(pkt, end - pos, &fake_len, pos - beg, qel, conn)) {
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003683 ssize_t room = end - pos;
3684 TRACE_PROTO("some CRYPTO frames could not be built",
3685 QUIC_EV_CONN_PAPKT, conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003686 goto err;
3687 }
3688
3689 /* Crypto frame */
3690 if (!LIST_ISEMPTY(&pkt->frms)) {
3691 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
3692 struct quic_crypto *crypto = &frm.crypto;
3693 struct quic_tx_frm *cf;
3694
3695 list_for_each_entry(cf, &pkt->frms, list) {
3696 crypto->offset = cf->crypto.offset;
3697 crypto->len = cf->crypto.len;
3698 crypto->qel = qel;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003699 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3700 ssize_t room = end - pos;
3701 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3702 conn->conn, NULL, NULL, &room);
3703 goto err;
3704 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003705 }
3706 }
3707
3708 /* Encode a maximum of frames. */
3709 list_for_each_entry_safe(frm, sfrm, &conn->tx.frms_to_send, list) {
3710 unsigned char *ppos;
3711
3712 ppos = pos;
3713 if (!qc_build_frm(&ppos, end, frm, pkt, conn)) {
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003714 TRACE_DEVEL("Frames not built", QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003715 break;
3716 }
3717
Willy Tarreau2b718102021-04-21 07:32:39 +02003718 LIST_DELETE(&frm->list);
3719 LIST_APPEND(&pkt->frms, &frm->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003720 pos = ppos;
3721 }
3722
3723 out:
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003724 TRACE_LEAVE(QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003725 return pos - beg;
3726
3727 err:
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003728 TRACE_DEVEL("leaving in error (buffer full)", QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003729 return -1;
3730}
3731
3732/* Prepare a post handhskake packet at Application encryption level for <conn>
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003733 * QUIC connection.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003734 * Return the length of this packet if succeeded, -1 if <wbuf> was full,
3735 * -2 in case of major error (encryption failure).
3736 */
3737static ssize_t qc_build_phdshk_apkt(struct q_buf *wbuf, struct quic_conn *qc)
3738{
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003739 /* A pointer to the packet number field in <buf> */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003740 unsigned char *buf_pn;
3741 unsigned char *beg, *end, *payload;
3742 int64_t pn;
3743 size_t pn_len, aad_len, payload_len;
3744 ssize_t pkt_len;
3745 struct quic_tls_ctx *tls_ctx;
3746 struct quic_enc_level *qel;
3747 struct quic_tx_packet *pkt;
3748
3749 TRACE_ENTER(QUIC_EV_CONN_PAPKT, qc->conn);
3750 pkt = pool_alloc(pool_head_quic_tx_packet);
3751 if (!pkt) {
3752 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_PAPKT, qc->conn);
3753 return -2;
3754 }
3755
3756 quic_tx_packet_init(pkt);
3757 beg = q_buf_getpos(wbuf);
3758 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3759 pn_len = 0;
3760 buf_pn = NULL;
3761 pn = qel->pktns->tx.next_pn + 1;
3762 pkt_len = qc_do_build_phdshk_apkt(wbuf, pkt, pn, &pn_len, &buf_pn, qel, qc);
3763 if (pkt_len <= 0) {
3764 free_quic_tx_packet(pkt);
3765 return pkt_len;
3766 }
3767
3768 end = beg + pkt_len;
3769 payload = buf_pn + pn_len;
3770 payload_len = end - payload;
3771 aad_len = payload - beg;
3772
3773 tls_ctx = &qel->tls_ctx;
3774 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc->conn))
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003775 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003776
3777 end += QUIC_TLS_TAG_LEN;
3778 pkt_len += QUIC_TLS_TAG_LEN;
3779 if (!quic_apply_header_protection(beg, buf_pn, pn_len,
3780 tls_ctx->tx.hp, tls_ctx->tx.hp_key))
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003781 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003782
3783 q_buf_setpos(wbuf, end);
3784 /* Consume a packet number. */
3785 ++qel->pktns->tx.next_pn;
3786 /* Attach the built packet to its tree. */
3787 pkt->pn_node.key = qel->pktns->tx.next_pn;
3788 eb64_insert(&qel->pktns->tx.pkts, &pkt->pn_node);
3789 /* Set the packet in fligth length for in flight packet only. */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003790 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003791 pkt->in_flight_len = pkt_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003792 qc->path->prep_in_flight += pkt_len;
3793 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003794 pkt->pktns = qel->pktns;
3795 /* Increment the number of bytes in <buf> buffer by the length of this packet. */
3796 wbuf->data += pkt_len;
3797 /* Attach this packet to <buf>. */
Willy Tarreau2b718102021-04-21 07:32:39 +02003798 LIST_APPEND(&wbuf->pkts, &pkt->list);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003799
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003800 TRACE_LEAVE(QUIC_EV_CONN_PAPKT, qc->conn, pkt);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003801
3802 return pkt_len;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003803
3804 err:
3805 free_quic_tx_packet(pkt);
3806 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PAPKT, qc->conn);
3807 return -2;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003808}
3809
3810/* Prepare a maximum of QUIC Application level packets from <ctx> QUIC
3811 * connection I/O handler context.
3812 * Returns 1 if succeeded, 0 if not.
3813 */
3814int qc_prep_phdshk_pkts(struct quic_conn *qc)
3815{
3816 struct q_buf *wbuf;
3817 struct quic_enc_level *qel;
3818
3819 TRACE_ENTER(QUIC_EV_CONN_PAPKTS, qc->conn);
3820 wbuf = q_wbuf(qc);
3821 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3822 while (q_buf_empty(wbuf)) {
3823 ssize_t ret;
3824
3825 if (!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3826 (LIST_ISEMPTY(&qel->pktns->tx.frms) ||
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003827 qc->path->prep_in_flight >= qc->path->cwnd)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003828 TRACE_DEVEL("nothing more to do",
3829 QUIC_EV_CONN_PAPKTS, qc->conn);
3830 break;
3831 }
3832
3833 ret = qc_build_phdshk_apkt(wbuf, qc);
3834 switch (ret) {
3835 case -1:
3836 /* Not enough room left in <wbuf>. */
3837 wbuf = q_next_wbuf(qc);
3838 continue;
3839 case -2:
3840 return 0;
3841 default:
3842 /* XXX TO CHECK: consume a buffer. */
3843 wbuf = q_next_wbuf(qc);
3844 continue;
3845 }
3846 }
3847 TRACE_LEAVE(QUIC_EV_CONN_PAPKTS, qc->conn);
3848
3849 return 1;
3850}
3851
3852/* QUIC connection packet handler task. */
Willy Tarreau144f84a2021-03-02 16:09:26 +01003853struct task *quic_conn_io_cb(struct task *t, void *context, unsigned int state)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003854{
3855 struct quic_conn_ctx *ctx = context;
3856
3857 if (ctx->state < QUIC_HS_ST_COMPLETE) {
3858 qc_do_hdshk(ctx);
3859 }
3860 else {
3861 struct quic_conn *qc = ctx->conn->qc;
3862
3863 /* XXX TO DO: may fail!!! XXX */
3864 qc_treat_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_APP], ctx);
3865 qc_prep_phdshk_pkts(qc);
3866 qc_send_ppkts(ctx);
3867 }
3868
Willy Tarreau74163142021-03-13 11:30:19 +01003869 return t;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003870}
3871
3872/* Receive up to <count> bytes from connection <conn>'s socket and store them
3873 * into buffer <buf>. Only one call to recv() is performed, unless the
3874 * buffer wraps, in which case a second call may be performed. The connection's
3875 * flags are updated with whatever special event is detected (error, read0,
3876 * empty). The caller is responsible for taking care of those events and
3877 * avoiding the call if inappropriate. The function does not call the
3878 * connection's polling update function, so the caller is responsible for this.
3879 * errno is cleared before starting so that the caller knows that if it spots an
3880 * error without errno, it's pending and can be retrieved via getsockopt(SO_ERROR).
3881 */
3882static size_t quic_conn_to_buf(struct connection *conn, void *xprt_ctx, struct buffer *buf, size_t count, int flags)
3883{
3884 ssize_t ret;
3885 size_t try, done = 0;
3886
3887 if (!conn_ctrl_ready(conn))
3888 return 0;
3889
3890 if (!fd_recv_ready(conn->handle.fd))
3891 return 0;
3892
3893 conn->flags &= ~CO_FL_WAIT_ROOM;
3894 errno = 0;
3895
Willy Tarreauf5090652021-04-06 17:23:40 +02003896 if (unlikely(!(fdtab[conn->handle.fd].state & FD_POLL_IN))) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003897 /* stop here if we reached the end of data */
Willy Tarreauf5090652021-04-06 17:23:40 +02003898 if ((fdtab[conn->handle.fd].state & (FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_HUP)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003899 goto read0;
3900
3901 /* report error on POLL_ERR before connection establishment */
Willy Tarreauf5090652021-04-06 17:23:40 +02003902 if ((fdtab[conn->handle.fd].state & FD_POLL_ERR) && (conn->flags & CO_FL_WAIT_L4_CONN)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003903 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3904 goto leave;
3905 }
3906 }
3907
3908 /* read the largest possible block. For this, we perform only one call
3909 * to recv() unless the buffer wraps and we exactly fill the first hunk,
3910 * in which case we accept to do it once again. A new attempt is made on
3911 * EINTR too.
3912 */
3913 while (count > 0) {
3914 try = b_contig_space(buf);
3915 if (!try)
3916 break;
3917
3918 if (try > count)
3919 try = count;
3920
3921 ret = recvfrom(conn->handle.fd, b_tail(buf), try, 0, NULL, 0);
3922
3923 if (ret > 0) {
3924 b_add(buf, ret);
3925 done += ret;
3926 if (ret < try) {
3927 /* unfortunately, on level-triggered events, POLL_HUP
3928 * is generally delivered AFTER the system buffer is
3929 * empty, unless the poller supports POLL_RDHUP. If
3930 * we know this is the case, we don't try to read more
3931 * as we know there's no more available. Similarly, if
3932 * there's no problem with lingering we don't even try
3933 * to read an unlikely close from the client since we'll
3934 * close first anyway.
3935 */
Willy Tarreauf5090652021-04-06 17:23:40 +02003936 if (fdtab[conn->handle.fd].state & FD_POLL_HUP)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003937 goto read0;
3938
Willy Tarreaub41a6e92021-04-06 17:49:19 +02003939 if (!(fdtab[conn->handle.fd].state & FD_LINGER_RISK) ||
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003940 (cur_poller.flags & HAP_POLL_F_RDHUP)) {
3941 break;
3942 }
3943 }
3944 count -= ret;
3945 }
3946 else if (ret == 0) {
3947 goto read0;
3948 }
3949 else if (errno == EAGAIN || errno == ENOTCONN) {
3950 fd_cant_recv(conn->handle.fd);
3951 break;
3952 }
3953 else if (errno != EINTR) {
3954 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3955 break;
3956 }
3957 }
3958
3959 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) && done)
3960 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3961
3962 leave:
3963 return done;
3964
3965 read0:
3966 conn_sock_read0(conn);
3967 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3968
3969 /* Now a final check for a possible asynchronous low-level error
3970 * report. This can happen when a connection receives a reset
3971 * after a shutdown, both POLL_HUP and POLL_ERR are queued, and
3972 * we might have come from there by just checking POLL_HUP instead
3973 * of recv()'s return value 0, so we have no way to tell there was
3974 * an error without checking.
3975 */
Willy Tarreauf5090652021-04-06 17:23:40 +02003976 if (unlikely(fdtab[conn->handle.fd].state & FD_POLL_ERR))
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003977 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3978 goto leave;
3979}
3980
3981
3982/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
3983 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
3984 * other pending data for example, but this flag is ignored at the moment.
3985 * Only one call to send() is performed, unless the buffer wraps, in which case
3986 * a second call may be performed. The connection's flags are updated with
3987 * whatever special event is detected (error, empty). The caller is responsible
3988 * for taking care of those events and avoiding the call if inappropriate. The
3989 * function does not call the connection's polling update function, so the caller
3990 * is responsible for this. It's up to the caller to update the buffer's contents
3991 * based on the return value.
3992 */
3993static size_t quic_conn_from_buf(struct connection *conn, void *xprt_ctx, const struct buffer *buf, size_t count, int flags)
3994{
3995 ssize_t ret;
3996 size_t try, done;
3997 int send_flag;
3998
3999 if (!conn_ctrl_ready(conn))
4000 return 0;
4001
4002 if (!fd_send_ready(conn->handle.fd))
4003 return 0;
4004
4005 done = 0;
4006 /* send the largest possible block. For this we perform only one call
4007 * to send() unless the buffer wraps and we exactly fill the first hunk,
4008 * in which case we accept to do it once again.
4009 */
4010 while (count) {
4011 try = b_contig_data(buf, done);
4012 if (try > count)
4013 try = count;
4014
4015 send_flag = MSG_DONTWAIT | MSG_NOSIGNAL;
4016 if (try < count || flags & CO_SFL_MSG_MORE)
4017 send_flag |= MSG_MORE;
4018
4019 ret = sendto(conn->handle.fd, b_peek(buf, done), try, send_flag,
4020 (struct sockaddr *)conn->dst, get_addr_len(conn->dst));
4021 if (ret > 0) {
4022 count -= ret;
4023 done += ret;
4024
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05004025 /* A send succeeded, so we can consider ourself connected */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004026 conn->flags |= CO_FL_WAIT_L4L6;
4027 /* if the system buffer is full, don't insist */
4028 if (ret < try)
4029 break;
4030 }
4031 else if (ret == 0 || errno == EAGAIN || errno == ENOTCONN || errno == EINPROGRESS) {
4032 /* nothing written, we need to poll for write first */
4033 fd_cant_send(conn->handle.fd);
4034 break;
4035 }
4036 else if (errno != EINTR) {
4037 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
4038 break;
4039 }
4040 }
4041 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) && done)
4042 conn->flags &= ~CO_FL_WAIT_L4_CONN;
4043
4044 if (done > 0) {
4045 /* we count the total bytes sent, and the send rate for 32-byte
4046 * blocks. The reason for the latter is that freq_ctr are
4047 * limited to 4GB and that it's not enough per second.
4048 */
4049 _HA_ATOMIC_ADD(&global.out_bytes, done);
4050 update_freq_ctr(&global.out_32bps, (done + 16) / 32);
4051 }
4052 return done;
4053}
4054
4055/* Initialize a QUIC connection (quic_conn struct) to be attached to <conn>
4056 * connection with <xprt_ctx> as address of the xprt context.
4057 * Returns 1 if succeeded, 0 if not.
4058 */
4059static int qc_conn_init(struct connection *conn, void **xprt_ctx)
4060{
4061 struct quic_conn_ctx *ctx;
4062
4063 TRACE_ENTER(QUIC_EV_CONN_NEW, conn);
4064
4065 if (*xprt_ctx)
4066 goto out;
4067
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004068 ctx = pool_alloc(pool_head_quic_conn_ctx);
4069 if (!ctx) {
4070 conn->err_code = CO_ER_SYS_MEMLIM;
4071 goto err;
4072 }
4073
4074 ctx->wait_event.tasklet = tasklet_new();
4075 if (!ctx->wait_event.tasklet) {
4076 conn->err_code = CO_ER_SYS_MEMLIM;
4077 goto err;
4078 }
4079
4080 ctx->wait_event.tasklet->process = quic_conn_io_cb;
4081 ctx->wait_event.tasklet->context = ctx;
4082 ctx->wait_event.events = 0;
4083 ctx->conn = conn;
4084 ctx->subs = NULL;
4085 ctx->xprt_ctx = NULL;
4086
4087 ctx->xprt = xprt_get(XPRT_QUIC);
4088 if (objt_server(conn->target)) {
4089 /* Server */
4090 struct server *srv = __objt_server(conn->target);
4091 unsigned char dcid[QUIC_CID_LEN];
4092 struct quic_conn *quic_conn;
4093 int ssl_err, ipv4;
4094
4095 ssl_err = SSL_ERROR_NONE;
4096 if (RAND_bytes(dcid, sizeof dcid) != 1)
4097 goto err;
4098
4099 conn->qc = new_quic_conn(QUIC_PROTOCOL_VERSION_DRAFT_28);
4100 if (!conn->qc)
4101 goto err;
4102
4103 quic_conn = conn->qc;
4104 quic_conn->conn = conn;
4105 ipv4 = conn->dst->ss_family == AF_INET;
4106 if (!qc_new_conn_init(quic_conn, ipv4, NULL, &srv->cids,
4107 dcid, sizeof dcid, NULL, 0))
4108 goto err;
4109
4110 if (!qc_new_isecs(conn, dcid, sizeof dcid, 0))
4111 goto err;
4112
4113 ctx->state = QUIC_HS_ST_CLIENT_INITIAL;
4114 if (ssl_bio_and_sess_init(conn, srv->ssl_ctx.ctx,
4115 &ctx->ssl, &ctx->bio, ha_quic_meth, ctx) == -1)
4116 goto err;
4117
4118 quic_conn->params = srv->quic_params;
4119 /* Copy the initial source connection ID. */
4120 quic_cid_cpy(&quic_conn->params.initial_source_connection_id, &quic_conn->scid);
4121 quic_conn->enc_params_len =
4122 quic_transport_params_encode(quic_conn->enc_params,
4123 quic_conn->enc_params + sizeof quic_conn->enc_params,
4124 &quic_conn->params, 0);
4125 if (!quic_conn->enc_params_len)
4126 goto err;
4127
4128 SSL_set_quic_transport_params(ctx->ssl, quic_conn->enc_params, quic_conn->enc_params_len);
4129 SSL_set_connect_state(ctx->ssl);
4130 ssl_err = SSL_do_handshake(ctx->ssl);
4131 if (ssl_err != 1) {
4132 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
4133 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
4134 TRACE_PROTO("SSL handshake",
4135 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
4136 }
4137 else {
4138 TRACE_DEVEL("SSL handshake error",
4139 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
4140 goto err;
4141 }
4142 }
4143 }
4144 else if (objt_listener(conn->target)) {
4145 /* Listener */
4146 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
4147
4148 ctx->state = QUIC_HS_ST_SERVER_INITIAL;
4149
4150 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
4151 &ctx->ssl, &ctx->bio, ha_quic_meth, ctx) == -1)
4152 goto err;
4153
4154 SSL_set_accept_state(ctx->ssl);
4155 }
4156
4157 *xprt_ctx = ctx;
4158
4159 /* Leave init state and start handshake */
4160 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
4161 /* Start the handshake */
4162 tasklet_wakeup(ctx->wait_event.tasklet);
4163
4164 out:
4165 TRACE_LEAVE(QUIC_EV_CONN_NEW, conn);
4166
4167 return 0;
4168
4169 err:
Willy Tarreau7deb28c2021-05-10 07:40:27 +02004170 if (ctx && ctx->wait_event.tasklet)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004171 tasklet_free(ctx->wait_event.tasklet);
4172 pool_free(pool_head_quic_conn_ctx, ctx);
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01004173 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_NEW, conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004174 return -1;
4175}
4176
4177/* transport-layer operations for QUIC connections. */
4178static struct xprt_ops ssl_quic = {
4179 .snd_buf = quic_conn_from_buf,
4180 .rcv_buf = quic_conn_to_buf,
4181 .init = qc_conn_init,
4182 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
4183 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
4184 .name = "QUIC",
4185};
4186
4187__attribute__((constructor))
4188static void __quic_conn_init(void)
4189{
4190 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
4191 xprt_register(XPRT_QUIC, &ssl_quic);
4192}
4193
4194__attribute__((destructor))
4195static void __quic_conn_deinit(void)
4196{
4197 BIO_meth_free(ha_quic_meth);
4198}
4199
4200/* Read all the QUIC packets found in <buf> with <len> as length (typically a UDP
4201 * datagram), <ctx> being the QUIC I/O handler context, from QUIC connections,
4202 * calling <func> function;
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05004203 * Return the number of bytes read if succeeded, -1 if not.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004204 */
4205static ssize_t quic_dgram_read(char *buf, size_t len, void *owner,
4206 struct sockaddr_storage *saddr, qpkt_read_func *func)
4207{
4208 unsigned char *pos;
4209 const unsigned char *end;
4210 struct quic_dgram_ctx dgram_ctx = {
4211 .dcid_node = NULL,
4212 .owner = owner,
4213 };
4214
4215 pos = (unsigned char *)buf;
4216 end = pos + len;
4217
4218 do {
4219 int ret;
4220 struct quic_rx_packet *pkt;
4221
Willy Tarreaue4498932021-03-22 21:13:05 +01004222 pkt = pool_zalloc(pool_head_quic_rx_packet);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004223 if (!pkt)
4224 goto err;
4225
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004226 quic_rx_packet_refinc(pkt);
4227 ret = func(&pos, end, pkt, &dgram_ctx, saddr);
4228 if (ret == -1) {
4229 size_t pkt_len;
4230
4231 pkt_len = pkt->len;
4232 free_quic_rx_packet(pkt);
4233 /* If the packet length could not be found, we cannot continue. */
4234 if (!pkt_len)
4235 break;
4236 }
4237 } while (pos < end);
4238
4239 /* Increasing the received bytes counter by the UDP datagram length
4240 * if this datagram could be associated to a connection.
4241 */
4242 if (dgram_ctx.qc)
4243 dgram_ctx.qc->rx.bytes += len;
4244
4245 return pos - (unsigned char *)buf;
4246
4247 err:
4248 return -1;
4249}
4250
4251ssize_t quic_lstnr_dgram_read(char *buf, size_t len, void *owner,
4252 struct sockaddr_storage *saddr)
4253{
4254 return quic_dgram_read(buf, len, owner, saddr, qc_lstnr_pkt_rcv);
4255}
4256
4257ssize_t quic_srv_dgram_read(char *buf, size_t len, void *owner,
4258 struct sockaddr_storage *saddr)
4259{
4260 return quic_dgram_read(buf, len, owner, saddr, qc_srv_pkt_rcv);
4261}
4262
4263/* QUIC I/O handler for connection to local listeners or remove servers
4264 * depending on <listener> boolean value, with <fd> as socket file
4265 * descriptor and <ctx> as context.
4266 */
4267static size_t quic_conn_handler(int fd, void *ctx, qpkt_read_func *func)
4268{
4269 ssize_t ret;
4270 size_t done = 0;
4271 struct buffer *buf = get_trash_chunk();
4272 /* Source address */
4273 struct sockaddr_storage saddr = {0};
4274 socklen_t saddrlen = sizeof saddr;
4275
4276 if (!fd_recv_ready(fd))
4277 return 0;
4278
4279 do {
4280 ret = recvfrom(fd, buf->area, buf->size, 0,
4281 (struct sockaddr *)&saddr, &saddrlen);
4282 if (ret < 0) {
4283 if (errno == EINTR)
4284 continue;
4285 if (errno == EAGAIN)
4286 fd_cant_recv(fd);
4287 goto out;
4288 }
4289 } while (0);
4290
4291 done = buf->data = ret;
4292 quic_dgram_read(buf->area, buf->data, ctx, &saddr, func);
4293
4294 out:
4295 return done;
4296}
4297
4298/* QUIC I/O handler for connections to local listeners with <fd> as socket
4299 * file descriptor.
4300 */
4301void quic_fd_handler(int fd)
4302{
Willy Tarreauf5090652021-04-06 17:23:40 +02004303 if (fdtab[fd].state & FD_POLL_IN)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004304 quic_conn_handler(fd, fdtab[fd].owner, &qc_lstnr_pkt_rcv);
4305}
4306
4307/* QUIC I/O handler for connections to remote servers with <fd> as socket
4308 * file descriptor.
4309 */
4310void quic_conn_fd_handler(int fd)
4311{
Willy Tarreauf5090652021-04-06 17:23:40 +02004312 if (fdtab[fd].state & FD_POLL_IN)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004313 quic_conn_handler(fd, fdtab[fd].owner, &qc_srv_pkt_rcv);
4314}
4315
4316/*
4317 * Local variables:
4318 * c-indent-level: 8
4319 * c-basic-offset: 8
4320 * End:
4321 */