blob: f8e807c1ec3d474beec33c671fd9d771059d5d8b [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;
577 const struct quic_stream *s = &frm->stream;
578
579 chunk_appendf(&trace_buf, " uni=%d fin=%d id=%llu off=%llu len=%llu",
580 !!(s->id & QUIC_STREAM_FRAME_ID_DIR_BIT),
581 !!(frm->type & QUIC_STREAM_FRAME_TYPE_FIN_BIT),
582 (unsigned long long)s->id,
583 (unsigned long long)s->offset,
584 (unsigned long long)s->len);
585 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100586 }
587 if (mask & QUIC_EV_CONN_LPKT) {
588 const struct quic_rx_packet *pkt = a2;
589
590 if (conn)
591 chunk_appendf(&trace_buf, " xprt_ctx@%p", conn->xprt_ctx);
592 if (pkt)
593 chunk_appendf(&trace_buf, " type=0x%02x %s",
594 pkt->type, qc_pkt_long(pkt) ? "long" : "short");
595 }
596
597}
598
599/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
600static inline int quic_peer_validated_addr(struct quic_conn_ctx *ctx)
601{
602 struct quic_conn *qc;
603
604 qc = ctx->conn->qc;
605 if (objt_server(qc->conn->target))
606 return 1;
607
608 if ((qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_RECEIVED) ||
609 (qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns->flags & QUIC_FL_PKTNS_ACK_RECEIVED) ||
610 (ctx->state & QUIC_HS_ST_COMPLETE))
611 return 1;
612
613 return 0;
614}
615
616/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
617 * both loss detection and PTO and schedule the task assiated to this timer if needed.
618 */
619static inline void qc_set_timer(struct quic_conn_ctx *ctx)
620{
621 struct quic_conn *qc;
622 struct quic_pktns *pktns;
623 unsigned int pto;
624
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100625 TRACE_ENTER(QUIC_EV_CONN_STIMER, ctx->conn,
626 NULL, NULL, &ctx->conn->qc->path->ifae_pkts);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100627 qc = ctx->conn->qc;
628 pktns = quic_loss_pktns(qc);
629 if (tick_isset(pktns->tx.loss_time)) {
630 qc->timer = pktns->tx.loss_time;
631 goto out;
632 }
633
634 /* XXX TODO: anti-amplification: the timer must be
635 * cancelled for a server which reached the anti-amplification limit.
636 */
637
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100638 if (!qc->path->ifae_pkts && quic_peer_validated_addr(ctx)) {
639 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, ctx->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100640 /* Timer cancellation. */
641 qc->timer = TICK_ETERNITY;
642 goto out;
643 }
644
645 pktns = quic_pto_pktns(qc, ctx->state & QUIC_HS_ST_COMPLETE, &pto);
646 if (tick_isset(pto))
647 qc->timer = pto;
648 out:
649 task_schedule(qc->timer_task, qc->timer);
650 TRACE_LEAVE(QUIC_EV_CONN_STIMER, ctx->conn, pktns);
651}
652
653#ifndef OPENSSL_IS_BORINGSSL
654int ha_quic_set_encryption_secrets(SSL *ssl, enum ssl_encryption_level_t level,
655 const uint8_t *read_secret,
656 const uint8_t *write_secret, size_t secret_len)
657{
658 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
659 struct quic_tls_ctx *tls_ctx =
660 &conn->qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
661 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
662
663 TRACE_ENTER(QUIC_EV_CONN_RWSEC, conn);
664 tls_ctx->rx.aead = tls_ctx->tx.aead = tls_aead(cipher);
665 tls_ctx->rx.md = tls_ctx->tx.md = tls_md(cipher);
666 tls_ctx->rx.hp = tls_ctx->tx.hp = tls_hp(cipher);
667
668 if (!quic_tls_derive_keys(tls_ctx->rx.aead, tls_ctx->rx.hp, tls_ctx->rx.md,
669 tls_ctx->rx.key, sizeof tls_ctx->rx.key,
670 tls_ctx->rx.iv, sizeof tls_ctx->rx.iv,
671 tls_ctx->rx.hp_key, sizeof tls_ctx->rx.hp_key,
672 read_secret, secret_len)) {
673 TRACE_DEVEL("RX key derivation failed", QUIC_EV_CONN_RWSEC, conn);
674 return 0;
675 }
676
677 tls_ctx->rx.flags |= QUIC_FL_TLS_SECRETS_SET;
678 if (!quic_tls_derive_keys(tls_ctx->tx.aead, tls_ctx->tx.hp, tls_ctx->tx.md,
679 tls_ctx->tx.key, sizeof tls_ctx->tx.key,
680 tls_ctx->tx.iv, sizeof tls_ctx->tx.iv,
681 tls_ctx->tx.hp_key, sizeof tls_ctx->tx.hp_key,
682 write_secret, secret_len)) {
683 TRACE_DEVEL("TX key derivation failed", QUIC_EV_CONN_RWSEC, conn);
684 return 0;
685 }
686
687 tls_ctx->tx.flags |= QUIC_FL_TLS_SECRETS_SET;
688 if (objt_server(conn->target) && level == ssl_encryption_application) {
689 const unsigned char *buf;
690 size_t buflen;
691
692 SSL_get_peer_quic_transport_params(ssl, &buf, &buflen);
693 if (!buflen)
694 return 0;
695
696 if (!quic_transport_params_store(conn->qc, 1, buf, buf + buflen))
697 return 0;
698 }
699 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, conn, &level);
700
701 return 1;
702}
703#else
704/* ->set_read_secret callback to derive the RX secrets at <level> encryption
705 * level.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +0500706 * Returns 1 if succeeded, 0 if not.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100707 */
708int ha_set_rsec(SSL *ssl, enum ssl_encryption_level_t level,
709 const SSL_CIPHER *cipher,
710 const uint8_t *secret, size_t secret_len)
711{
712 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
713 struct quic_tls_ctx *tls_ctx =
714 &conn->qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
715
716 TRACE_ENTER(QUIC_EV_CONN_RSEC, conn);
717 tls_ctx->rx.aead = tls_aead(cipher);
718 tls_ctx->rx.md = tls_md(cipher);
719 tls_ctx->rx.hp = tls_hp(cipher);
720
721 if (!quic_tls_derive_keys(tls_ctx->rx.aead, tls_ctx->rx.hp, tls_ctx->rx.md,
722 tls_ctx->rx.key, sizeof tls_ctx->rx.key,
723 tls_ctx->rx.iv, sizeof tls_ctx->rx.iv,
724 tls_ctx->rx.hp_key, sizeof tls_ctx->rx.hp_key,
725 secret, secret_len)) {
726 TRACE_DEVEL("RX key derivation failed", QUIC_EV_CONN_RSEC, conn);
727 goto err;
728 }
729
730 if (objt_server(conn->target) && level == ssl_encryption_application) {
731 const unsigned char *buf;
732 size_t buflen;
733
734 SSL_get_peer_quic_transport_params(ssl, &buf, &buflen);
735 if (!buflen)
736 goto err;
737
738 if (!quic_transport_params_store(conn->qc, 1, buf, buf + buflen))
739 goto err;
740 }
741
742 tls_ctx->rx.flags |= QUIC_FL_TLS_SECRETS_SET;
743 TRACE_LEAVE(QUIC_EV_CONN_RSEC, conn, &level, secret, &secret_len);
744
745 return 1;
746
747 err:
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +0100748 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_RSEC, conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100749 return 0;
750}
751
752/* ->set_write_secret callback to derive the TX secrets at <level>
753 * encryption level.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +0500754 * Returns 1 if succeeded, 0 if not.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100755 */
756int ha_set_wsec(SSL *ssl, enum ssl_encryption_level_t level,
757 const SSL_CIPHER *cipher,
758 const uint8_t *secret, size_t secret_len)
759{
760 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
761 struct quic_tls_ctx *tls_ctx =
762 &conn->qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
763
764 TRACE_ENTER(QUIC_EV_CONN_WSEC, conn);
765 tls_ctx->tx.aead = tls_aead(cipher);
766 tls_ctx->tx.md = tls_md(cipher);
767 tls_ctx->tx.hp = tls_hp(cipher);
768
769 if (!quic_tls_derive_keys(tls_ctx->tx.aead, tls_ctx->tx.hp, tls_ctx->tx.md,
770 tls_ctx->tx.key, sizeof tls_ctx->tx.key,
771 tls_ctx->tx.iv, sizeof tls_ctx->tx.iv,
772 tls_ctx->tx.hp_key, sizeof tls_ctx->tx.hp_key,
773 secret, secret_len)) {
774 TRACE_DEVEL("TX key derivation failed", QUIC_EV_CONN_WSEC, conn);
775 goto err;
776 }
777
778 tls_ctx->tx.flags |= QUIC_FL_TLS_SECRETS_SET;
779 TRACE_LEAVE(QUIC_EV_CONN_WSEC, conn, &level, secret, &secret_len);
780
781 return 1;
782
783 err:
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +0100784 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_WSEC, conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100785 return 0;
786}
787#endif
788
789/* This function copies the CRYPTO data provided by the TLS stack found at <data>
790 * with <len> as size in CRYPTO buffers dedicated to store the information about
791 * outgoing CRYPTO frames so that to be able to replay the CRYPTO data streams.
792 * It fails only if it could not managed to allocate enough CRYPTO buffers to
793 * store all the data.
794 * Note that CRYPTO data may exist at any encryption level except at 0-RTT.
795 */
796static int quic_crypto_data_cpy(struct quic_enc_level *qel,
797 const unsigned char *data, size_t len)
798{
799 struct quic_crypto_buf **qcb;
800 /* The remaining byte to store in CRYPTO buffers. */
801 size_t cf_offset, cf_len, *nb_buf;
802 unsigned char *pos;
803
804 nb_buf = &qel->tx.crypto.nb_buf;
805 qcb = &qel->tx.crypto.bufs[*nb_buf - 1];
806 cf_offset = (*nb_buf - 1) * QUIC_CRYPTO_BUF_SZ + (*qcb)->sz;
807 cf_len = len;
808
809 while (len) {
810 size_t to_copy, room;
811
812 pos = (*qcb)->data + (*qcb)->sz;
813 room = QUIC_CRYPTO_BUF_SZ - (*qcb)->sz;
814 to_copy = len > room ? room : len;
815 if (to_copy) {
816 memcpy(pos, data, to_copy);
817 /* Increment the total size of this CRYPTO buffers by <to_copy>. */
818 qel->tx.crypto.sz += to_copy;
819 (*qcb)->sz += to_copy;
820 pos += to_copy;
821 len -= to_copy;
822 data += to_copy;
823 }
824 else {
825 struct quic_crypto_buf **tmp;
826
827 tmp = realloc(qel->tx.crypto.bufs,
828 (*nb_buf + 1) * sizeof *qel->tx.crypto.bufs);
829 if (tmp) {
830 qel->tx.crypto.bufs = tmp;
831 qcb = &qel->tx.crypto.bufs[*nb_buf];
832 *qcb = pool_alloc(pool_head_quic_crypto_buf);
833 if (!*qcb)
834 return 0;
835
836 (*qcb)->sz = 0;
837 ++*nb_buf;
838 }
839 else {
840 break;
841 }
842 }
843 }
844
845 /* Allocate a TX CRYPTO frame only if all the CRYPTO data
846 * have been buffered.
847 */
848 if (!len) {
849 struct quic_tx_frm *frm;
850
851 frm = pool_alloc(pool_head_quic_tx_frm);
852 if (!frm)
853 return 0;
854
855 frm->type = QUIC_FT_CRYPTO;
856 frm->crypto.offset = cf_offset;
857 frm->crypto.len = cf_len;
858 LIST_ADDQ(&qel->pktns->tx.frms, &frm->list);
859 }
860
861 return len == 0;
862}
863
864
865/* ->add_handshake_data QUIC TLS callback used by the QUIC TLS stack when it
866 * wants to provide the QUIC layer with CRYPTO data.
867 * Returns 1 if succeeded, 0 if not.
868 */
869int ha_quic_add_handshake_data(SSL *ssl, enum ssl_encryption_level_t level,
870 const uint8_t *data, size_t len)
871{
872 struct connection *conn;
873 enum quic_tls_enc_level tel;
874 struct quic_enc_level *qel;
875
876 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
877 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, conn);
878 tel = ssl_to_quic_enc_level(level);
879 qel = &conn->qc->els[tel];
880
881 if (tel == -1) {
882 TRACE_PROTO("Wrong encryption level", QUIC_EV_CONN_ADDDATA, conn);
883 goto err;
884 }
885
886 if (!quic_crypto_data_cpy(qel, data, len)) {
887 TRACE_PROTO("Could not bufferize", QUIC_EV_CONN_ADDDATA, conn);
888 goto err;
889 }
890
891 TRACE_PROTO("CRYPTO data buffered", QUIC_EV_CONN_ADDDATA,
892 conn, &level, &len);
893
894 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, conn);
895 return 1;
896
897 err:
898 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_ADDDATA, conn);
899 return 0;
900}
901
902int ha_quic_flush_flight(SSL *ssl)
903{
904 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
905
906 TRACE_ENTER(QUIC_EV_CONN_FFLIGHT, conn);
907 TRACE_LEAVE(QUIC_EV_CONN_FFLIGHT, conn);
908
909 return 1;
910}
911
912int ha_quic_send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
913{
914 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
915
Frédéric Lécaille47c433f2020-12-10 17:03:11 +0100916 TRACE_DEVEL("SSL alert", QUIC_EV_CONN_SSLALERT, conn, &alert, &level);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100917 return 1;
918}
919
920/* QUIC TLS methods */
921static SSL_QUIC_METHOD ha_quic_method = {
922#ifdef OPENSSL_IS_BORINGSSL
923 .set_read_secret = ha_set_rsec,
924 .set_write_secret = ha_set_wsec,
925#else
926 .set_encryption_secrets = ha_quic_set_encryption_secrets,
927#endif
928 .add_handshake_data = ha_quic_add_handshake_data,
929 .flush_flight = ha_quic_flush_flight,
930 .send_alert = ha_quic_send_alert,
931};
932
933/* Initialize the TLS context of a listener with <bind_conf> as configuration.
934 * Returns an error count.
935 */
936int ssl_quic_initial_ctx(struct bind_conf *bind_conf)
937{
938 struct proxy *curproxy = bind_conf->frontend;
939 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
940 int cfgerr = 0;
941
942#if 0
943 /* XXX Did not manage to use this. */
944 const char *ciphers =
945 "TLS_AES_128_GCM_SHA256:"
946 "TLS_AES_256_GCM_SHA384:"
947 "TLS_CHACHA20_POLY1305_SHA256:"
948 "TLS_AES_128_CCM_SHA256";
949#endif
950 const char *groups = "P-256:X25519:P-384:P-521";
951 long options =
952 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
953 SSL_OP_SINGLE_ECDH_USE |
954 SSL_OP_CIPHER_SERVER_PREFERENCE;
955 SSL_CTX *ctx;
956
957 ctx = SSL_CTX_new(TLS_server_method());
958 bind_conf->initial_ctx = ctx;
959
960 SSL_CTX_set_options(ctx, options);
961#if 0
962 if (SSL_CTX_set_cipher_list(ctx, ciphers) != 1) {
963 ha_alert("Proxy '%s': unable to set TLS 1.3 cipher list to '%s' "
964 "for bind '%s' at [%s:%d].\n",
965 curproxy->id, ciphers,
966 bind_conf->arg, bind_conf->file, bind_conf->line);
967 cfgerr++;
968 }
969#endif
970
971 if (SSL_CTX_set1_curves_list(ctx, groups) != 1) {
972 ha_alert("Proxy '%s': unable to set TLS 1.3 curves list to '%s' "
973 "for bind '%s' at [%s:%d].\n",
974 curproxy->id, groups,
975 bind_conf->arg, bind_conf->file, bind_conf->line);
976 cfgerr++;
977 }
978
979 SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
980 SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
981 SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
982 SSL_CTX_set_default_verify_paths(ctx);
983
984#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
985#ifdef OPENSSL_IS_BORINGSSL
986 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
987 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
988#elif (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
989 if (bind_conf->ssl_conf.early_data) {
990 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
991 SSL_CTX_set_max_early_data(ctx, global.tune.bufsize - global.tune.maxrewrite);
992 }
993 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
994 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
995#else
996 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
997#endif
998 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
999#endif
1000 SSL_CTX_set_quic_method(ctx, &ha_quic_method);
1001
1002 return cfgerr;
1003}
1004
1005/* Decode an expected packet number from <truncated_on> its truncated value,
1006 * depending on <largest_pn> the largest received packet number, and <pn_nbits>
1007 * the number of bits used to encode this packet number (its length in bytes * 8).
1008 * See https://quicwg.org/base-drafts/draft-ietf-quic-transport.html#packet-encoding
1009 */
1010static uint64_t decode_packet_number(uint64_t largest_pn,
1011 uint32_t truncated_pn, unsigned int pn_nbits)
1012{
1013 uint64_t expected_pn = largest_pn + 1;
1014 uint64_t pn_win = (uint64_t)1 << pn_nbits;
1015 uint64_t pn_hwin = pn_win / 2;
1016 uint64_t pn_mask = pn_win - 1;
1017 uint64_t candidate_pn;
1018
1019
1020 candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
1021 /* Note that <pn_win> > <pn_hwin>. */
1022 if (candidate_pn < QUIC_MAX_PACKET_NUM - pn_win &&
1023 candidate_pn + pn_hwin <= expected_pn)
1024 return candidate_pn + pn_win;
1025
1026 if (candidate_pn > expected_pn + pn_hwin && candidate_pn >= pn_win)
1027 return candidate_pn - pn_win;
1028
1029 return candidate_pn;
1030}
1031
1032/* Remove the header protection of <pkt> QUIC packet using <tls_ctx> as QUIC TLS
1033 * cryptographic context.
1034 * <largest_pn> is the largest received packet number and <pn> the address of
1035 * the packet number field for this packet with <byte0> address of its first byte.
1036 * <end> points to one byte past the end of this packet.
1037 * Returns 1 if succeeded, 0 if not.
1038 */
1039static int qc_do_rm_hp(struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx,
1040 int64_t largest_pn, unsigned char *pn,
1041 unsigned char *byte0, const unsigned char *end,
1042 struct quic_conn_ctx *ctx)
1043{
1044 int ret, outlen, i, pnlen;
1045 uint64_t packet_number;
1046 uint32_t truncated_pn = 0;
1047 unsigned char mask[5] = {0};
1048 unsigned char *sample;
1049 EVP_CIPHER_CTX *cctx;
1050 unsigned char *hp_key;
1051
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001052 /* Check there is enough data in this packet. */
1053 if (end - pn < QUIC_PACKET_PN_MAXLEN + sizeof mask) {
1054 TRACE_DEVEL("too short packet", QUIC_EV_CONN_RMHP, ctx->conn, pkt);
1055 return 0;
1056 }
1057
1058 cctx = EVP_CIPHER_CTX_new();
1059 if (!cctx) {
1060 TRACE_DEVEL("memory allocation failed", QUIC_EV_CONN_RMHP, ctx->conn, pkt);
1061 return 0;
1062 }
1063
1064 ret = 0;
1065 sample = pn + QUIC_PACKET_PN_MAXLEN;
1066
1067 hp_key = tls_ctx->rx.hp_key;
1068 if (!EVP_DecryptInit_ex(cctx, tls_ctx->rx.hp, NULL, hp_key, sample) ||
1069 !EVP_DecryptUpdate(cctx, mask, &outlen, mask, sizeof mask) ||
1070 !EVP_DecryptFinal_ex(cctx, mask, &outlen)) {
1071 TRACE_DEVEL("decryption failed", QUIC_EV_CONN_RMHP, ctx->conn, pkt);
1072 goto out;
1073 }
1074
1075 *byte0 ^= mask[0] & (*byte0 & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
1076 pnlen = (*byte0 & QUIC_PACKET_PNL_BITMASK) + 1;
1077 for (i = 0; i < pnlen; i++) {
1078 pn[i] ^= mask[i + 1];
1079 truncated_pn = (truncated_pn << 8) | pn[i];
1080 }
1081
1082 packet_number = decode_packet_number(largest_pn, truncated_pn, pnlen * 8);
1083 /* Store remaining information for this unprotected header */
1084 pkt->pn = packet_number;
1085 pkt->pnl = pnlen;
1086
1087 ret = 1;
1088
1089 out:
1090 EVP_CIPHER_CTX_free(cctx);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001091
1092 return ret;
1093}
1094
1095/* Encrypt the payload of a QUIC packet with <pn> as number found at <payload>
1096 * address, with <payload_len> as payload length, <aad> as address of
1097 * the ADD and <aad_len> as AAD length depending on the <tls_ctx> QUIC TLS
1098 * context.
1099 * Returns 1 if succeeded, 0 if not.
1100 */
1101static int quic_packet_encrypt(unsigned char *payload, size_t payload_len,
1102 unsigned char *aad, size_t aad_len, uint64_t pn,
1103 struct quic_tls_ctx *tls_ctx, struct connection *conn)
1104{
1105 unsigned char iv[12];
1106 unsigned char *tx_iv = tls_ctx->tx.iv;
1107 size_t tx_iv_sz = sizeof tls_ctx->tx.iv;
Frédéric Lécaillef63921f2020-12-18 09:48:20 +01001108 struct enc_debug_info edi;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001109
1110 if (!quic_aead_iv_build(iv, sizeof iv, tx_iv, tx_iv_sz, pn)) {
1111 TRACE_DEVEL("AEAD IV building for encryption failed", QUIC_EV_CONN_HPKT, conn);
Frédéric Lécaillef63921f2020-12-18 09:48:20 +01001112 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001113 }
1114
1115 if (!quic_tls_encrypt(payload, payload_len, aad, aad_len,
1116 tls_ctx->tx.aead, tls_ctx->tx.key, iv)) {
1117 TRACE_DEVEL("QUIC packet encryption failed", QUIC_EV_CONN_HPKT, conn);
Frédéric Lécaillef63921f2020-12-18 09:48:20 +01001118 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001119 }
1120
1121 return 1;
Frédéric Lécaillef63921f2020-12-18 09:48:20 +01001122
1123 err:
1124 enc_debug_info_init(&edi, payload, payload_len, aad, aad_len, pn);
1125 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_ENCPKT, conn, &edi);
1126 return 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001127}
1128
1129/* Decrypt <pkt> QUIC packet with <tls_ctx> as QUIC TLS cryptographic context.
1130 * Returns 1 if succeeded, 0 if not.
1131 */
1132static int qc_pkt_decrypt(struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx)
1133{
1134 int ret;
1135 unsigned char iv[12];
1136 unsigned char *rx_iv = tls_ctx->rx.iv;
1137 size_t rx_iv_sz = sizeof tls_ctx->rx.iv;
1138
1139 if (!quic_aead_iv_build(iv, sizeof iv, rx_iv, rx_iv_sz, pkt->pn))
1140 return 0;
1141
1142 ret = quic_tls_decrypt(pkt->data + pkt->aad_len, pkt->len - pkt->aad_len,
1143 pkt->data, pkt->aad_len,
1144 tls_ctx->rx.aead, tls_ctx->rx.key, iv);
1145 if (!ret)
1146 return 0;
1147
1148 /* Update the packet length (required to parse the frames). */
1149 pkt->len = pkt->aad_len + ret;
1150
1151 return 1;
1152}
1153
1154/* Treat <frm> frame whose packet it is attached to has just been acknowledged. */
1155static inline void qc_treat_acked_tx_frm(struct quic_tx_frm *frm,
1156 struct quic_conn_ctx *ctx)
1157{
1158 TRACE_PROTO("Removing frame", QUIC_EV_CONN_PRSAFRM, ctx->conn, frm);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001159 LIST_DEL(&frm->list);
1160 pool_free(pool_head_quic_tx_frm, frm);
1161}
1162
1163/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1164 * deallocating them, and their TX frames.
1165 * Returns the last node reached to be used for the next range.
1166 * May be NULL if <largest> node could not be found.
1167 */
1168static inline struct eb64_node *qc_ackrng_pkts(struct eb_root *pkts, unsigned int *pkt_flags,
1169 struct list *newly_acked_pkts,
1170 struct eb64_node *largest_node,
1171 uint64_t largest, uint64_t smallest,
1172 struct quic_conn_ctx *ctx)
1173{
1174 struct eb64_node *node;
1175 struct quic_tx_packet *pkt;
1176
1177 if (largest_node)
1178 node = largest_node;
1179 else {
1180 node = eb64_lookup(pkts, largest);
1181 while (!node && largest > smallest) {
1182 node = eb64_lookup(pkts, --largest);
1183 }
1184 }
1185
1186 while (node && node->key >= smallest) {
1187 struct quic_tx_frm *frm, *frmbak;
1188
1189 pkt = eb64_entry(&node->node, struct quic_tx_packet, pn_node);
1190 *pkt_flags |= pkt->flags;
1191 LIST_ADD(newly_acked_pkts, &pkt->list);
1192 TRACE_PROTO("Removing packet #", QUIC_EV_CONN_PRSAFRM, ctx->conn,, &pkt->pn_node.key);
1193 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1194 qc_treat_acked_tx_frm(frm, ctx);
1195 node = eb64_prev(node);
1196 eb64_delete(&pkt->pn_node);
1197 }
1198
1199 return node;
1200}
1201
1202/* Treat <frm> frame whose packet it is attached to has just been detected as non
1203 * acknowledged.
1204 */
1205static inline void qc_treat_nacked_tx_frm(struct quic_tx_frm *frm,
1206 struct quic_pktns *pktns,
1207 struct quic_conn_ctx *ctx)
1208{
1209 TRACE_PROTO("to resend frame", QUIC_EV_CONN_PRSAFRM, ctx->conn, frm);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001210 LIST_DEL(&frm->list);
1211 LIST_ADD(&pktns->tx.frms, &frm->list);
1212}
1213
1214
1215/* Free the TX packets of <pkts> list */
1216static inline void free_quic_tx_pkts(struct list *pkts)
1217{
1218 struct quic_tx_packet *pkt, *tmp;
1219
1220 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1221 LIST_DEL(&pkt->list);
1222 eb64_delete(&pkt->pn_node);
1223 pool_free(pool_head_quic_tx_packet, pkt);
1224 }
1225}
1226
1227/* Send a packet loss event nofification to the congestion controller
1228 * attached to <qc> connection with <lost_bytes> the number of lost bytes,
1229 * <oldest_lost>, <newest_lost> the oldest lost packet and newest lost packet
1230 * at <now_us> current time.
1231 * Always succeeds.
1232 */
1233static inline void qc_cc_loss_event(struct quic_conn *qc,
1234 unsigned int lost_bytes,
1235 unsigned int newest_time_sent,
1236 unsigned int period,
1237 unsigned int now_us)
1238{
1239 struct quic_cc_event ev = {
1240 .type = QUIC_CC_EVT_LOSS,
1241 .loss.now_ms = now_ms,
1242 .loss.max_ack_delay = qc->max_ack_delay,
1243 .loss.lost_bytes = lost_bytes,
1244 .loss.newest_time_sent = newest_time_sent,
1245 .loss.period = period,
1246 };
1247
1248 quic_cc_event(&qc->path->cc, &ev);
1249}
1250
1251/* Send a packet ack event nofication for each newly acked packet of
1252 * <newly_acked_pkts> list and free them.
1253 * Always succeeds.
1254 */
1255static inline void qc_treat_newly_acked_pkts(struct quic_conn_ctx *ctx,
1256 struct list *newly_acked_pkts)
1257{
1258 struct quic_conn *qc = ctx->conn->qc;
1259 struct quic_tx_packet *pkt, *tmp;
1260 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
1261
1262 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
1263 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001264 qc->path->prep_in_flight -= pkt->in_flight_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001265 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01001266 qc->path->ifae_pkts--;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001267 ev.ack.acked = pkt->in_flight_len;
1268 ev.ack.time_sent = pkt->time_sent;
1269 quic_cc_event(&qc->path->cc, &ev);
1270 LIST_DEL(&pkt->list);
1271 eb64_delete(&pkt->pn_node);
1272 pool_free(pool_head_quic_tx_packet, pkt);
1273 }
1274
1275}
1276
1277/* Handle <pkts> list of lost packets detected at <now_us> handling
1278 * their TX frames.
1279 * Send a packet loss event to the congestion controller if
1280 * in flight packet have been lost.
1281 * Also frees the packet in <pkts> list.
1282 * Never fails.
1283 */
1284static inline void qc_release_lost_pkts(struct quic_pktns *pktns,
1285 struct quic_conn_ctx *ctx,
1286 struct list *pkts,
1287 uint64_t now_us)
1288{
1289 struct quic_conn *qc = ctx->conn->qc;
1290 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
1291 struct quic_tx_frm *frm, *frmbak;
1292 uint64_t lost_bytes;
1293
1294 lost_bytes = 0;
1295 oldest_lost = newest_lost = NULL;
1296 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1297 lost_bytes += pkt->in_flight_len;
1298 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001299 qc->path->prep_in_flight -= pkt->in_flight_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001300 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01001301 qc->path->ifae_pkts--;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001302 /* Treat the frames of this lost packet. */
1303 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1304 qc_treat_nacked_tx_frm(frm, pktns, ctx);
1305 LIST_DEL(&pkt->list);
1306 if (!oldest_lost) {
1307 oldest_lost = newest_lost = pkt;
1308 }
1309 else {
1310 if (newest_lost != oldest_lost)
1311 pool_free(pool_head_quic_tx_packet, newest_lost);
1312 newest_lost = pkt;
1313 }
1314 }
1315
1316 if (lost_bytes) {
1317 /* Sent a packet loss event to the congestion controller. */
1318 qc_cc_loss_event(ctx->conn->qc, lost_bytes, newest_lost->time_sent,
1319 newest_lost->time_sent - oldest_lost->time_sent, now_us);
1320 pool_free(pool_head_quic_tx_packet, oldest_lost);
1321 if (newest_lost != oldest_lost)
1322 pool_free(pool_head_quic_tx_packet, newest_lost);
1323 }
1324}
1325
1326/* Look for packet loss from sent packets for <qel> encryption level of a
1327 * connection with <ctx> as I/O handler context. If remove is true, remove them from
1328 * their tree if deemed as lost or set the <loss_time> value the packet number
1329 * space if any not deemed lost.
1330 * Should be called after having received an ACK frame with newly acknowledged
1331 * packets or when the the loss detection timer has expired.
1332 * Always succeeds.
1333 */
1334static void qc_packet_loss_lookup(struct quic_pktns *pktns,
1335 struct quic_conn *qc,
1336 struct list *lost_pkts)
1337{
1338 struct eb_root *pkts;
1339 struct eb64_node *node;
1340 struct quic_loss *ql;
1341 unsigned int loss_delay;
1342
1343 TRACE_ENTER(QUIC_EV_CONN_PKTLOSS, qc->conn, pktns);
1344 pkts = &pktns->tx.pkts;
1345 pktns->tx.loss_time = TICK_ETERNITY;
1346 if (eb_is_empty(pkts))
1347 goto out;
1348
1349 ql = &qc->path->loss;
1350 loss_delay = QUIC_MAX(ql->latest_rtt, ql->srtt >> 3);
1351 loss_delay += loss_delay >> 3;
1352 loss_delay = QUIC_MAX(loss_delay, MS_TO_TICKS(QUIC_TIMER_GRANULARITY));
1353
1354 node = eb64_first(pkts);
1355 while (node) {
1356 struct quic_tx_packet *pkt;
1357 int64_t largest_acked_pn;
1358 unsigned int loss_time_limit, time_sent;
1359
1360 pkt = eb64_entry(&node->node, struct quic_tx_packet, pn_node);
1361 largest_acked_pn = pktns->tx.largest_acked_pn;
1362 node = eb64_next(node);
1363 if ((int64_t)pkt->pn_node.key > largest_acked_pn)
1364 break;
1365
1366 time_sent = pkt->time_sent;
1367 loss_time_limit = tick_add(time_sent, loss_delay);
1368 if (tick_is_le(time_sent, now_ms) ||
1369 (int64_t)largest_acked_pn >= pkt->pn_node.key + QUIC_LOSS_PACKET_THRESHOLD) {
1370 eb64_delete(&pkt->pn_node);
1371 LIST_ADDQ(lost_pkts, &pkt->list);
1372 }
1373 else {
1374 pktns->tx.loss_time = tick_first(pktns->tx.loss_time, loss_time_limit);
1375 }
1376 }
1377
1378 out:
1379 TRACE_LEAVE(QUIC_EV_CONN_PKTLOSS, qc->conn, pktns, lost_pkts);
1380}
1381
1382/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
1383 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05001384 * 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 +01001385 * acked ack-eliciting packet.
1386 * Return 1, if succeeded, 0 if not.
1387 */
1388static inline int qc_parse_ack_frm(struct quic_frame *frm, struct quic_conn_ctx *ctx,
1389 struct quic_enc_level *qel,
1390 unsigned int *rtt_sample,
1391 const unsigned char **pos, const unsigned char *end)
1392{
1393 struct quic_ack *ack = &frm->ack;
1394 uint64_t smallest, largest;
1395 struct eb_root *pkts;
1396 struct eb64_node *largest_node;
1397 unsigned int time_sent, pkt_flags;
1398 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
1399 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
1400
1401 if (ack->largest_ack > qel->pktns->tx.next_pn) {
1402 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
1403 ctx->conn,, &ack->largest_ack);
1404 goto err;
1405 }
1406
1407 if (ack->first_ack_range > ack->largest_ack) {
1408 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
1409 ctx->conn,, &ack->first_ack_range);
1410 goto err;
1411 }
1412
1413 largest = ack->largest_ack;
1414 smallest = largest - ack->first_ack_range;
1415 pkts = &qel->pktns->tx.pkts;
1416 pkt_flags = 0;
1417 largest_node = NULL;
1418 time_sent = 0;
1419
1420 if ((int64_t)ack->largest_ack > qel->pktns->tx.largest_acked_pn) {
1421 largest_node = eb64_lookup(pkts, largest);
1422 if (!largest_node) {
1423 TRACE_DEVEL("Largest acked packet not found",
1424 QUIC_EV_CONN_PRSAFRM, ctx->conn);
1425 goto err;
1426 }
1427
1428 time_sent = eb64_entry(&largest_node->node,
1429 struct quic_tx_packet, pn_node)->time_sent;
1430 }
1431
1432 TRACE_PROTO("ack range", QUIC_EV_CONN_PRSAFRM,
1433 ctx->conn,, &largest, &smallest);
1434 do {
1435 uint64_t gap, ack_range;
1436
1437 qc_ackrng_pkts(pkts, &pkt_flags, &newly_acked_pkts,
1438 largest_node, largest, smallest, ctx);
1439 if (!ack->ack_range_num--)
1440 break;
1441
1442 if (!quic_dec_int(&gap, pos, end))
1443 goto err;
1444
1445 if (smallest < gap + 2) {
1446 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
1447 ctx->conn,, &gap, &smallest);
1448 goto err;
1449 }
1450
1451 largest = smallest - gap - 2;
1452 if (!quic_dec_int(&ack_range, pos, end))
1453 goto err;
1454
1455 if (largest < ack_range) {
1456 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
1457 ctx->conn,, &largest, &ack_range);
1458 goto err;
1459 }
1460
1461 /* Do not use this node anymore. */
1462 largest_node = NULL;
1463 /* Next range */
1464 smallest = largest - ack_range;
1465
1466 TRACE_PROTO("ack range", QUIC_EV_CONN_PRSAFRM,
1467 ctx->conn,, &largest, &smallest);
1468 } while (1);
1469
1470 /* Flag this packet number space as having received an ACK. */
1471 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_RECEIVED;
1472
1473 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
1474 *rtt_sample = tick_remain(time_sent, now_ms);
1475 qel->pktns->tx.largest_acked_pn = ack->largest_ack;
1476 }
1477
1478 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
1479 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
1480 qc_packet_loss_lookup(qel->pktns, ctx->conn->qc, &lost_pkts);
1481 if (!LIST_ISEMPTY(&lost_pkts))
1482 qc_release_lost_pkts(qel->pktns, ctx, &lost_pkts, now_ms);
1483 }
1484 qc_treat_newly_acked_pkts(ctx, &newly_acked_pkts);
1485 if (quic_peer_validated_addr(ctx))
1486 ctx->conn->qc->path->loss.pto_count = 0;
1487 qc_set_timer(ctx);
1488 }
1489
1490
1491 return 1;
1492
1493 err:
1494 free_quic_tx_pkts(&newly_acked_pkts);
1495 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PRSAFRM, ctx->conn);
1496 return 0;
1497}
1498
1499/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
1500 * from <qel> encryption level with <ctx> as QUIC connection context.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05001501 * Remaining parameter are there for debugging purposes.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001502 * Return 1 if succeeded, 0 if not.
1503 */
1504static inline int qc_provide_cdata(struct quic_enc_level *el,
1505 struct quic_conn_ctx *ctx,
1506 const unsigned char *data, size_t len,
1507 struct quic_rx_packet *pkt,
1508 struct quic_rx_crypto_frm *cf)
1509{
1510 int ssl_err;
1511
1512 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, ctx->conn);
1513 ssl_err = SSL_ERROR_NONE;
1514 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
1515 TRACE_PROTO("SSL_provide_quic_data() error",
1516 QUIC_EV_CONN_SSLDATA, ctx->conn, pkt, cf, ctx->ssl);
1517 goto err;
1518 }
1519
1520 el->rx.crypto.offset += len;
1521 TRACE_PROTO("in order CRYPTO data",
1522 QUIC_EV_CONN_SSLDATA, ctx->conn,, cf, ctx->ssl);
1523
1524 if (ctx->state < QUIC_HS_ST_COMPLETE) {
1525 ssl_err = SSL_do_handshake(ctx->ssl);
1526 if (ssl_err != 1) {
1527 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
1528 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
1529 TRACE_PROTO("SSL handshake",
1530 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1531 goto out;
1532 }
1533
1534 TRACE_DEVEL("SSL handshake error",
1535 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1536 goto err;
1537 }
1538
1539 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
1540 if (objt_listener(ctx->conn->target))
1541 ctx->state = QUIC_HS_ST_CONFIRMED;
1542 else
1543 ctx->state = QUIC_HS_ST_COMPLETE;
1544 } else {
1545 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
1546 if (ssl_err != 1) {
1547 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
1548 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
1549 TRACE_DEVEL("SSL post handshake",
1550 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1551 goto out;
1552 }
1553
1554 TRACE_DEVEL("SSL post handshake error",
1555 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1556 goto err;
1557 }
1558
1559 TRACE_PROTO("SSL post handshake succeeded",
1560 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
1561 }
1562
1563 out:
1564 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, ctx->conn);
1565 return 1;
1566
1567 err:
1568 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_SSLDATA, ctx->conn);
1569 return 0;
1570}
1571
1572/* Parse all the frames of <pkt> QUIC packet for QUIC connection with <ctx>
1573 * as I/O handler context and <qel> as encryption level.
1574 * Returns 1 if succeeded, 0 if failed.
1575 */
1576static int qc_parse_pkt_frms(struct quic_rx_packet *pkt, struct quic_conn_ctx *ctx,
1577 struct quic_enc_level *qel)
1578{
1579 struct quic_frame frm;
1580 const unsigned char *pos, *end;
1581 struct quic_conn *conn = ctx->conn->qc;
1582
1583 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, ctx->conn);
1584 /* Skip the AAD */
1585 pos = pkt->data + pkt->aad_len;
1586 end = pkt->data + pkt->len;
1587
1588 while (pos < end) {
1589 if (!qc_parse_frm(&frm, pkt, &pos, end, conn))
1590 goto err;
1591
1592 switch (frm.type) {
Frédéric Lécaille0c140202020-12-09 15:56:48 +01001593 case QUIC_FT_PADDING:
1594 if (pos != end) {
1595 TRACE_DEVEL("wrong frame", QUIC_EV_CONN_PRSHPKT, ctx->conn, pkt);
1596 goto err;
1597 }
1598 break;
1599 case QUIC_FT_PING:
1600 break;
1601 case QUIC_FT_ACK:
1602 {
1603 unsigned int rtt_sample;
1604
1605 rtt_sample = 0;
1606 if (!qc_parse_ack_frm(&frm, ctx, qel, &rtt_sample, &pos, end))
1607 goto err;
1608
1609 if (rtt_sample) {
1610 unsigned int ack_delay;
1611
1612 ack_delay = !quic_application_pktns(qel->pktns, conn) ? 0 :
1613 MS_TO_TICKS(QUIC_MIN(quic_ack_delay_ms(&frm.ack, conn), conn->max_ack_delay));
1614 quic_loss_srtt_update(&conn->path->loss, rtt_sample, ack_delay, conn);
1615 }
1616 tasklet_wakeup(ctx->wait_event.tasklet);
1617 break;
1618 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001619 case QUIC_FT_CRYPTO:
1620 if (frm.crypto.offset != qel->rx.crypto.offset) {
1621 struct quic_rx_crypto_frm *cf;
1622
1623 cf = pool_alloc(pool_head_quic_rx_crypto_frm);
1624 if (!cf) {
1625 TRACE_DEVEL("CRYPTO frame allocation failed",
1626 QUIC_EV_CONN_PRSHPKT, ctx->conn);
1627 goto err;
1628 }
1629
1630 cf->offset_node.key = frm.crypto.offset;
1631 cf->len = frm.crypto.len;
1632 cf->data = frm.crypto.data;
1633 cf->pkt = pkt;
1634 eb64_insert(&qel->rx.crypto.frms, &cf->offset_node);
1635 quic_rx_packet_refinc(pkt);
1636 }
1637 else {
1638 /* XXX TO DO: <cf> is used only for the traces. */
1639 struct quic_rx_crypto_frm cf = { };
1640
1641 cf.offset_node.key = frm.crypto.offset;
1642 cf.len = frm.crypto.len;
1643 if (!qc_provide_cdata(qel, ctx,
1644 frm.crypto.data, frm.crypto.len,
1645 pkt, &cf))
1646 goto err;
1647 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001648 break;
Frédéric Lécaille0c140202020-12-09 15:56:48 +01001649 case QUIC_FT_STREAM_8:
1650 case QUIC_FT_STREAM_9:
1651 case QUIC_FT_STREAM_A:
1652 case QUIC_FT_STREAM_B:
1653 case QUIC_FT_STREAM_C:
1654 case QUIC_FT_STREAM_D:
1655 case QUIC_FT_STREAM_E:
1656 case QUIC_FT_STREAM_F:
Frédéric Lécaille242fb1b2020-12-31 12:45:38 +01001657 {
1658 struct quic_stream *stream = &frm.stream;
1659
1660 TRACE_PROTO("STREAM frame", QUIC_EV_CONN_PSTRM, ctx->conn, &frm);
1661 if (objt_listener(ctx->conn->target)) {
1662 if (stream->id & QUIC_STREAM_FRAME_ID_INITIATOR_BIT)
1663 goto err;
1664 } else if (!(stream->id & QUIC_STREAM_FRAME_ID_INITIATOR_BIT))
1665 goto err;
1666 break;
1667 }
Frédéric Lécaille0c140202020-12-09 15:56:48 +01001668 case QUIC_FT_NEW_CONNECTION_ID:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001669 break;
1670 case QUIC_FT_CONNECTION_CLOSE:
1671 case QUIC_FT_CONNECTION_CLOSE_APP:
1672 break;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001673 case QUIC_FT_HANDSHAKE_DONE:
1674 if (objt_listener(ctx->conn->target))
1675 goto err;
1676
1677 ctx->state = QUIC_HS_ST_CONFIRMED;
1678 break;
1679 default:
1680 goto err;
1681 }
1682 }
1683
1684 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
1685 * has successfully parse a Handshake packet. The Initial encryption must also
1686 * be discarded.
1687 */
1688 if (ctx->state == QUIC_HS_ST_SERVER_INITIAL &&
1689 pkt->type == QUIC_PACKET_TYPE_HANDSHAKE) {
1690 quic_tls_discard_keys(&conn->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
1691 quic_pktns_discard(conn->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, conn);
1692 qc_set_timer(ctx);
1693 ctx->state = QUIC_HS_ST_SERVER_HANDSHAKE;
1694 }
1695
1696 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, ctx->conn);
1697 return 1;
1698
1699 err:
1700 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PRSHPKT, ctx->conn);
1701 return 0;
1702}
1703
1704/* Prepare as much as possible handshake packets for the QUIC connection
1705 * with <ctx> as I/O handler context.
1706 * Returns 1 if succeeded, or 0 if something wrong happened.
1707 */
1708static int qc_prep_hdshk_pkts(struct quic_conn_ctx *ctx)
1709{
1710 struct quic_conn *qc;
1711 enum quic_tls_enc_level tel, next_tel;
1712 struct quic_enc_level *qel;
1713 struct q_buf *wbuf;
1714 /* A boolean to flag <wbuf> as reusable, even if not empty. */
1715 int reuse_wbuf;
1716
1717 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, ctx->conn);
1718 qc = ctx->conn->qc;
1719 if (!quic_get_tls_enc_levels(&tel, &next_tel, ctx->state)) {
1720 TRACE_DEVEL("unknown enc. levels",
1721 QUIC_EV_CONN_PHPKTS, ctx->conn);
1722 goto err;
1723 }
1724
1725 reuse_wbuf = 0;
1726 wbuf = q_wbuf(qc);
1727 qel = &qc->els[tel];
1728 /* When entering this function, the writter buffer must be empty.
1729 * Most of the time it points to the reader buffer.
1730 */
1731 while ((q_buf_empty(wbuf) || reuse_wbuf)) {
1732 ssize_t ret;
1733 enum quic_pkt_type pkt_type;
1734
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +01001735 TRACE_POINT(QUIC_EV_CONN_PHPKTS, ctx->conn, qel);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001736 /* Do not build any more packet f the TX secrets are not available or
1737 * f there is nothing to send, i.e. if no ACK are required
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001738 * and if there is no more packets to send upon PTO expiration
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001739 * and if there is no more CRYPTO data available or in flight
1740 * congestion control limit is reached for prepared data
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001741 */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001742 if (!(qel->tls_ctx.tx.flags & QUIC_FL_TLS_SECRETS_SET) ||
1743 (!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001744 !qc->tx.nb_pto_dgrams &&
1745 (LIST_ISEMPTY(&qel->pktns->tx.frms) ||
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001746 qc->path->prep_in_flight >= qc->path->cwnd))) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001747 TRACE_DEVEL("nothing more to do", QUIC_EV_CONN_PHPKTS, ctx->conn);
1748 /* Consume the buffer if we were supposed to reuse it. */
1749 if (reuse_wbuf)
1750 wbuf = q_next_wbuf(qc);
1751 break;
1752 }
1753
1754 pkt_type = quic_tls_level_pkt_type(tel);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001755 ret = qc_build_hdshk_pkt(wbuf, qc, pkt_type, qel);
1756 switch (ret) {
1757 case -2:
1758 goto err;
1759 case -1:
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001760 if (!reuse_wbuf)
1761 goto out;
1762
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001763 /* Not enough room in <wbuf>. */
1764 wbuf = q_next_wbuf(qc);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001765 reuse_wbuf = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001766 continue;
1767 case 0:
1768 goto out;
1769 default:
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001770 reuse_wbuf = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001771 /* Discard the Initial encryption keys as soon as
1772 * a handshake packet could be built.
1773 */
1774 if (ctx->state == QUIC_HS_ST_CLIENT_INITIAL &&
1775 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
1776 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
1777 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
1778 qc_set_timer(ctx);
1779 ctx->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
1780 }
1781 /* Special case for Initial packets: when they have all
1782 * been sent, select the next level.
1783 */
1784 if ((LIST_ISEMPTY(&qel->pktns->tx.frms) || qc->els[next_tel].pktns->tx.in_flight) &&
1785 tel == QUIC_TLS_ENC_LEVEL_INITIAL) {
1786 tel = next_tel;
1787 qel = &qc->els[tel];
1788 if (LIST_ISEMPTY(&qel->pktns->tx.frms)) {
1789 /* If there is no more data for the next level, let's
1790 * consume a buffer. This is the case for a client
1791 * which sends only one Initial packet, then wait
1792 * for additional CRYPTO data from the server to enter the
1793 * next level.
1794 */
1795 wbuf = q_next_wbuf(qc);
1796 }
1797 else {
1798 /* Let's try to reuse this buffer. */
1799 reuse_wbuf = 1;
1800 }
1801 }
1802 else {
1803 wbuf = q_next_wbuf(qc);
1804 }
1805 }
1806 }
1807
1808 out:
1809 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, ctx->conn);
1810 return 1;
1811
1812 err:
1813 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PHPKTS, ctx->conn);
1814 return 0;
1815}
1816
1817/* Send the QUIC packets which have been prepared for QUIC connections
1818 * with <ctx> as I/O handler context.
1819 */
1820int qc_send_ppkts(struct quic_conn_ctx *ctx)
1821{
1822 struct quic_conn *qc;
1823 struct buffer tmpbuf = { };
1824 struct q_buf *rbuf;
1825
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001826 qc = ctx->conn->qc;
1827 for (rbuf = q_rbuf(qc); !q_buf_empty(rbuf) ; rbuf = q_next_rbuf(qc)) {
1828 struct quic_tx_packet *p, *q;
1829 unsigned int time_sent;
1830
1831 tmpbuf.area = (char *)rbuf->area;
1832 tmpbuf.size = tmpbuf.data = rbuf->data;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001833 TRACE_PROTO("to send", QUIC_EV_CONN_SPPKTS, ctx->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001834 if (ctx->xprt->snd_buf(qc->conn, qc->conn->xprt_ctx,
1835 &tmpbuf, tmpbuf.data, 0) <= 0)
1836 break;
1837
1838 qc->tx.bytes += tmpbuf.data;
1839 time_sent = now_ms;
1840 /* Reset this buffer to make it available for the next packet to prepare. */
1841 q_buf_reset(rbuf);
1842 /* Remove from <rbuf> the packets which have just been sent. */
1843 list_for_each_entry_safe(p, q, &rbuf->pkts, list) {
1844 p->time_sent = time_sent;
1845 if (p->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
1846 p->pktns->tx.time_of_last_eliciting = time_sent;
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01001847 qc->path->ifae_pkts++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001848 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001849 qc->path->in_flight += p->in_flight_len;
1850 p->pktns->tx.in_flight += p->in_flight_len;
1851 if (p->in_flight_len)
1852 qc_set_timer(ctx);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001853 TRACE_PROTO("sent pkt", QUIC_EV_CONN_SPPKTS, ctx->conn, p);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001854 LIST_DEL(&p->list);
1855 }
1856 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001857
1858 return 1;
1859}
1860
1861/* Build all the frames which must be sent just after the handshake have succeeded.
1862 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
1863 * a HANDSHAKE_DONE frame.
1864 * Return 1 if succeeded, 0 if not.
1865 */
1866static int quic_build_post_handshake_frames(struct quic_conn *conn)
1867{
1868 int i;
1869 struct quic_frame *frm;
1870
1871 /* Only servers must send a HANDSHAKE_DONE frame. */
1872 if (!objt_server(conn->conn->target)) {
1873 frm = pool_alloc(pool_head_quic_frame);
Frédéric Lécaille153d4a82021-01-06 12:12:39 +01001874 if (!frm)
1875 return 0;
1876
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001877 frm->type = QUIC_FT_HANDSHAKE_DONE;
1878 LIST_ADDQ(&conn->tx.frms_to_send, &frm->list);
1879 }
1880
1881 for (i = 1; i < conn->rx_tps.active_connection_id_limit; i++) {
1882 struct quic_connection_id *cid;
1883
1884 frm = pool_alloc(pool_head_quic_frame);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001885 cid = new_quic_cid(&conn->cids, i);
1886 if (!frm || !cid)
1887 goto err;
1888
1889 quic_connection_id_to_frm_cpy(frm, cid);
1890 LIST_ADDQ(&conn->tx.frms_to_send, &frm->list);
1891 }
1892
1893 return 1;
1894
1895 err:
1896 free_quic_conn_cids(conn);
1897 return 0;
1898}
1899
1900/* Deallocate <l> list of ACK ranges. */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001901void free_quic_arngs(struct quic_arngs *arngs)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001902{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001903 struct eb64_node *n;
1904 struct quic_arng_node *ar;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001905
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001906 n = eb64_first(&arngs->root);
1907 while (n) {
1908 struct eb64_node *next;
1909
1910 ar = eb64_entry(&n->node, struct quic_arng_node, first);
1911 next = eb64_next(n);
1912 eb64_delete(n);
1913 free(ar);
1914 n = next;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001915 }
1916}
1917
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001918/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
1919 * descending order.
1920 */
1921static inline size_t sack_gap(struct quic_arng_node *p,
1922 struct quic_arng_node *q)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001923{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001924 return p->first.key - q->last - 2;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001925}
1926
1927
1928/* Remove the last elements of <ack_ranges> list of ack range updating its
1929 * encoded size until it goes below <limit>.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05001930 * Returns 1 if succeeded, 0 if not (no more element to remove).
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001931 */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001932static int quic_rm_last_ack_ranges(struct quic_arngs *arngs, size_t limit)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001933{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001934 struct eb64_node *last, *prev;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001935
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001936 last = eb64_last(&arngs->root);
1937 while (last && arngs->enc_sz > limit) {
1938 struct quic_arng_node *last_node, *prev_node;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001939
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001940 prev = eb64_prev(last);
1941 if (!prev)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001942 return 0;
1943
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001944 last_node = eb64_entry(&last->node, struct quic_arng_node, first);
1945 prev_node = eb64_entry(&prev->node, struct quic_arng_node, first);
1946 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
1947 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
1948 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
1949 --arngs->sz;
1950 eb64_delete(last);
1951 pool_free(pool_head_quic_arng, last);
1952 last = prev;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001953 }
1954
1955 return 1;
1956}
1957
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001958/* Set the encoded size of <arngs> QUIC ack ranges. */
1959static void quic_arngs_set_enc_sz(struct quic_arngs *arngs)
1960{
1961 struct eb64_node *node, *next;
1962 struct quic_arng_node *ar, *ar_next;
1963
1964 node = eb64_last(&arngs->root);
1965 if (!node)
1966 return;
1967
1968 ar = eb64_entry(&node->node, struct quic_arng_node, first);
1969 arngs->enc_sz = quic_int_getsize(ar->last) +
1970 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
1971
1972 while ((next = eb64_prev(node))) {
1973 ar_next = eb64_entry(&next->node, struct quic_arng_node, first);
1974 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
1975 quic_int_getsize(ar_next->last - ar_next->first.key);
1976 node = next;
1977 ar = eb64_entry(&node->node, struct quic_arng_node, first);
1978 }
1979}
1980
1981/* Insert in <root> ebtree <node> node with <ar> as range value.
1982 * Returns the ebtree node which has been inserted.
1983 */
1984static inline
1985struct eb64_node *quic_insert_new_range(struct eb_root *root,
1986 struct quic_arng_node *node,
1987 struct quic_arng *ar)
1988{
1989 node->first.key = ar->first;
1990 node->last = ar->last;
1991 return eb64_insert(root, &node->first);
1992}
1993
1994/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001995 * Note that this function computes the number of bytes required to encode
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001996 * this tree of ACK ranges in descending order.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001997 *
1998 * Descending order
1999 * ------------->
2000 * range1 range2
2001 * ..........|--------|..............|--------|
2002 * ^ ^ ^ ^
2003 * | | | |
2004 * last1 first1 last2 first2
2005 * ..........+--------+--------------+--------+......
2006 * diff1 gap12 diff2
2007 *
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002008 * To encode the previous list of ranges we must encode integers as follows in
2009 * descending order:
2010 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002011 * with diff1 = last1 - first1
2012 * diff2 = last2 - first2
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002013 * gap12 = first1 - last2 - 2 (>= 0)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002014 *
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002015 */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002016int quic_update_ack_ranges_list(struct quic_arngs *arngs,
2017 struct quic_arng *ar)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002018{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002019 struct eb64_node *le;
2020 struct quic_arng_node *new_node;
2021 struct eb64_node *new;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002022
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002023 new = NULL;
2024 if (eb_is_empty(&arngs->root)) {
2025 /* First range insertion. */
2026 new_node = pool_alloc(pool_head_quic_arng);
2027 if (!new_node)
2028 return 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002029
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002030 quic_insert_new_range(&arngs->root, new_node, ar);
2031 /* Increment the size of these ranges. */
2032 arngs->sz++;
2033 goto out;
2034 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002035
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002036 le = eb64_lookup_le(&arngs->root, ar->first);
2037 if (!le) {
2038 /* New insertion */
2039 new_node = pool_alloc(pool_head_quic_arng);
2040 if (!new_node)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002041 return 0;
2042
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002043 new = quic_insert_new_range(&arngs->root, new_node, ar);
2044 /* Increment the size of these ranges. */
2045 arngs->sz++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002046 }
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002047 else {
2048 struct quic_arng_node *le_ar =
2049 eb64_entry(&le->node, struct quic_arng_node, first);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002050
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002051 /* Already existing range */
2052 if (le_ar->first.key <= ar->first && le_ar->last >= ar->last)
2053 return 1;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002054
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002055 if (le_ar->last + 1 >= ar->first) {
2056 le_ar->last = ar->last;
2057 new = le;
2058 new_node = le_ar;
2059 }
2060 else {
2061 /* New insertion */
2062 new_node = pool_alloc(pool_head_quic_arng);
2063 if (!new_node)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002064 return 0;
2065
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002066 new = quic_insert_new_range(&arngs->root, new_node, ar);
2067 /* Increment the size of these ranges. */
2068 arngs->sz++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002069 }
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002070 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002071
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002072 /* Verify that the new inserted node does not overlap the nodes
2073 * which follow it.
2074 */
2075 if (new) {
2076 uint64_t new_node_last;
2077 struct eb64_node *next;
2078 struct quic_arng_node *next_node;
2079
2080 new_node_last = new_node->last;
2081 while ((next = eb64_next(new))) {
2082 next_node =
2083 eb64_entry(&next->node, struct quic_arng_node, first);
2084 if (new_node_last + 1 < next_node->first.key)
2085 break;
2086
2087 if (next_node->last > new_node->last)
2088 new_node->last = next_node->last;
2089 eb64_delete(next);
2090 free(next_node);
2091 /* Decrement the size of these ranges. */
2092 arngs->sz--;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002093 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002094 }
2095
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002096 quic_arngs_set_enc_sz(arngs);
2097
2098 out:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002099 return 1;
2100}
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002101/* Remove the header protection of packets at <el> encryption level.
2102 * Always succeeds.
2103 */
2104static inline void qc_rm_hp_pkts(struct quic_enc_level *el, struct quic_conn_ctx *ctx)
2105{
2106 struct quic_tls_ctx *tls_ctx;
2107 struct quic_rx_packet *pqpkt, *qqpkt;
2108 struct quic_enc_level *app_qel;
2109
2110 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, ctx->conn);
2111 app_qel = &ctx->conn->qc->els[QUIC_TLS_ENC_LEVEL_APP];
2112 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
2113 if (el == app_qel && objt_listener(ctx->conn->target) && ctx->state < QUIC_HS_ST_COMPLETE) {
2114 TRACE_PROTO("hp not removed (handshake not completed)",
2115 QUIC_EV_CONN_ELRMHP, ctx->conn);
2116 goto out;
2117 }
2118 tls_ctx = &el->tls_ctx;
2119 list_for_each_entry_safe(pqpkt, qqpkt, &el->rx.pqpkts, list) {
2120 if (!qc_do_rm_hp(pqpkt, tls_ctx, el->pktns->rx.largest_pn,
2121 pqpkt->data + pqpkt->pn_offset,
2122 pqpkt->data, pqpkt->data + pqpkt->len, ctx)) {
2123 TRACE_PROTO("hp removing error", QUIC_EV_CONN_ELRMHP, ctx->conn);
2124 /* XXX TO DO XXX */
2125 }
2126 else {
2127 /* The AAD includes the packet number field */
2128 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
2129 /* Store the packet into the tree of packets to decrypt. */
2130 pqpkt->pn_node.key = pqpkt->pn;
2131 quic_rx_packet_eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
2132 TRACE_PROTO("hp removed", QUIC_EV_CONN_ELRMHP, ctx->conn, pqpkt);
2133 }
2134 quic_rx_packet_list_del(pqpkt);
2135 }
2136
2137 out:
2138 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, ctx->conn);
2139}
2140
2141/* Process all the CRYPTO frame at <el> encryption level.
2142 * Return 1 if succeeded, 0 if not.
2143 */
2144static inline int qc_treat_rx_crypto_frms(struct quic_enc_level *el,
2145 struct quic_conn_ctx *ctx)
2146{
2147 struct eb64_node *node;
2148
2149 TRACE_ENTER(QUIC_EV_CONN_RXCDATA, ctx->conn);
2150 node = eb64_first(&el->rx.crypto.frms);
2151 while (node) {
2152 struct quic_rx_crypto_frm *cf;
2153
2154 cf = eb64_entry(&node->node, struct quic_rx_crypto_frm, offset_node);
2155 if (cf->offset_node.key != el->rx.crypto.offset)
2156 break;
2157
2158 if (!qc_provide_cdata(el, ctx, cf->data, cf->len, cf->pkt, cf))
2159 goto err;
2160
2161 node = eb64_next(node);
2162 quic_rx_packet_refdec(cf->pkt);
2163 eb64_delete(&cf->offset_node);
2164 pool_free(pool_head_quic_rx_crypto_frm, cf);
2165 }
2166
2167 TRACE_LEAVE(QUIC_EV_CONN_RXCDATA, ctx->conn);
2168 return 1;
2169
2170 err:
2171 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_RXCDATA, ctx->conn);
2172 return 0;
2173}
2174
2175/* Process all the packets at <el> encryption level.
2176 * Return 1 if succeeded, 0 if not.
2177 */
2178int qc_treat_rx_pkts(struct quic_enc_level *el, struct quic_conn_ctx *ctx)
2179{
2180 struct quic_tls_ctx *tls_ctx;
2181 struct eb64_node *node;
2182
2183 TRACE_ENTER(QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2184 tls_ctx = &el->tls_ctx;
2185 node = eb64_first(&el->rx.pkts);
2186 while (node) {
2187 struct quic_rx_packet *pkt;
2188
2189 pkt = eb64_entry(&node->node, struct quic_rx_packet, pn_node);
2190 if (!qc_pkt_decrypt(pkt, tls_ctx)) {
2191 /* Drop the packet */
2192 TRACE_PROTO("packet decryption failed -> dropped",
2193 QUIC_EV_CONN_ELRXPKTS, ctx->conn, pkt);
2194 }
2195 else {
2196 int drop;
2197
2198 drop = 0;
2199 if (!qc_parse_pkt_frms(pkt, ctx, el))
2200 drop = 1;
2201
2202 if (drop) {
2203 /* Drop the packet */
2204 TRACE_PROTO("packet parsing failed -> dropped",
2205 QUIC_EV_CONN_ELRXPKTS, ctx->conn, pkt);
2206 }
2207 else {
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002208 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
2209
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002210 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING) {
2211 el->pktns->rx.nb_ack_eliciting++;
2212 if (!(el->pktns->rx.nb_ack_eliciting & 1))
2213 el->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
2214 }
2215
2216 /* Update the largest packet number. */
2217 if (pkt->pn > el->pktns->rx.largest_pn)
2218 el->pktns->rx.largest_pn = pkt->pn;
2219
2220 /* Update the list of ranges to acknowledge. */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002221 if (!quic_update_ack_ranges_list(&el->pktns->rx.arngs, &ar)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002222 TRACE_DEVEL("Could not update ack range list",
2223 QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2224 node = eb64_next(node);
2225 quic_rx_packet_eb64_delete(&pkt->pn_node);
2226 free_quic_rx_packet(pkt);
2227 goto err;
2228 }
2229
2230 }
2231 }
2232 node = eb64_next(node);
2233 quic_rx_packet_eb64_delete(&pkt->pn_node);
2234 free_quic_rx_packet(pkt);
2235 }
2236
2237 if (!qc_treat_rx_crypto_frms(el, ctx))
2238 goto err;
2239
2240 TRACE_LEAVE(QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2241 return 1;
2242
2243 err:
2244 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2245 return 0;
2246}
2247
2248/* Called during handshakes to parse and build Initial and Handshake packets for QUIC
2249 * connections with <ctx> as I/O handler context.
2250 * Returns 1 if succeeded, 0 if not.
2251 */
2252int qc_do_hdshk(struct quic_conn_ctx *ctx)
2253{
2254 int ssl_err;
2255 struct quic_conn *quic_conn;
2256 enum quic_tls_enc_level tel, next_tel;
2257 struct quic_enc_level *qel, *next_qel;
2258 struct quic_tls_ctx *tls_ctx;
2259
2260 TRACE_ENTER(QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
2261
2262 ssl_err = SSL_ERROR_NONE;
2263 quic_conn = ctx->conn->qc;
2264 if (!quic_get_tls_enc_levels(&tel, &next_tel, ctx->state))
2265 goto err;
2266
2267 qel = &quic_conn->els[tel];
2268 next_qel = &quic_conn->els[next_tel];
2269
2270 next_level:
2271 tls_ctx = &qel->tls_ctx;
2272
2273 /* If the header protection key for this level has been derived,
2274 * remove the packet header protections.
2275 */
2276 if (!LIST_ISEMPTY(&qel->rx.pqpkts) &&
2277 (tls_ctx->rx.flags & QUIC_FL_TLS_SECRETS_SET))
2278 qc_rm_hp_pkts(qel, ctx);
2279
2280 if (!eb_is_empty(&qel->rx.pkts) &&
2281 !qc_treat_rx_pkts(qel, ctx))
2282 goto err;
2283
2284 if (!qc_prep_hdshk_pkts(ctx))
2285 goto err;
2286
2287 if (!qc_send_ppkts(ctx))
2288 goto err;
2289
2290 /* Check if there is something to do for the next level.
2291 */
2292 if ((next_qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_SET) &&
2293 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || !eb_is_empty(&next_qel->rx.pkts))) {
2294 qel = next_qel;
2295 goto next_level;
2296 }
2297
2298 /* If the handshake has not been completed -> out! */
2299 if (ctx->state < QUIC_HS_ST_COMPLETE)
2300 goto out;
2301
2302 /* Discard the Handshake keys. */
2303 quic_tls_discard_keys(&quic_conn->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
2304 quic_pktns_discard(quic_conn->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, quic_conn);
2305 qc_set_timer(ctx);
2306 if (!quic_build_post_handshake_frames(quic_conn) ||
2307 !qc_prep_phdshk_pkts(quic_conn) ||
2308 !qc_send_ppkts(ctx))
2309 goto err;
2310
2311 out:
2312 TRACE_LEAVE(QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
2313 return 1;
2314
2315 err:
2316 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
2317 return 0;
2318}
2319
2320/* Allocate a new QUIC connection and return it if succeeded, NULL if not. */
2321struct quic_conn *new_quic_conn(uint32_t version)
2322{
2323 struct quic_conn *quic_conn;
2324
2325 quic_conn = pool_alloc(pool_head_quic_conn);
2326 if (quic_conn) {
2327 memset(quic_conn, 0, sizeof *quic_conn);
2328 quic_conn->version = version;
2329 }
2330
2331 return quic_conn;
2332}
2333
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05002334/* Uninitialize <qel> QUIC encryption level. Never fails. */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002335static void quic_conn_enc_level_uninit(struct quic_enc_level *qel)
2336{
2337 int i;
2338
2339 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
2340 if (qel->tx.crypto.bufs[i]) {
2341 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
2342 qel->tx.crypto.bufs[i] = NULL;
2343 }
2344 }
2345 free(qel->tx.crypto.bufs);
2346 qel->tx.crypto.bufs = NULL;
2347}
2348
2349/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05002350 * connection allocating everything needed.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002351 * Returns 1 if succeeded, 0 if not.
2352 */
2353static int quic_conn_enc_level_init(struct quic_conn *qc,
2354 enum quic_tls_enc_level level)
2355{
2356 struct quic_enc_level *qel;
2357
2358 qel = &qc->els[level];
2359 qel->level = quic_to_ssl_enc_level(level);
2360 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
2361 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
2362 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
2363 qel->tls_ctx.rx.flags = 0;
2364 qel->tls_ctx.tx.flags = 0;
2365
2366 qel->rx.pkts = EB_ROOT;
2367 LIST_INIT(&qel->rx.pqpkts);
2368
2369 /* Allocate only one buffer. */
2370 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
2371 if (!qel->tx.crypto.bufs)
2372 goto err;
2373
2374 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
2375 if (!qel->tx.crypto.bufs[0])
2376 goto err;
2377
2378 qel->tx.crypto.bufs[0]->sz = 0;
2379 qel->tx.crypto.nb_buf = 1;
2380
2381 qel->tx.crypto.sz = 0;
2382 qel->tx.crypto.offset = 0;
2383
2384 return 1;
2385
2386 err:
2387 free(qel->tx.crypto.bufs);
2388 qel->tx.crypto.bufs = NULL;
2389 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 }
2408 free((*p)->area);
2409 (*p)->area = NULL;
2410 free(*p);
2411 *p = NULL;
2412 p++;
2413 }
2414 free(bufs);
2415}
2416
2417/* Allocate an array or <nb> buffers of <sz> bytes each.
2418 * Return this array if succeeded, NULL if failed.
2419 */
2420static inline struct q_buf **quic_conn_tx_bufs_alloc(size_t nb, size_t sz)
2421{
2422 int i;
2423 struct q_buf **bufs, **p;
2424
2425 bufs = calloc(nb, sizeof *bufs);
2426 if (!bufs)
2427 return NULL;
2428
2429 i = 0;
2430 p = bufs;
2431 while (i++ < nb) {
2432 *p = calloc(1, sizeof **p);
2433 if (!*p)
2434 goto err;
2435
2436 (*p)->area = malloc(sz);
2437 if (!(*p)->area)
2438 goto err;
2439
2440 (*p)->pos = (*p)->area;
2441 (*p)->end = (*p)->area + sz;
2442 (*p)->data = 0;
2443 LIST_INIT(&(*p)->pkts);
2444 p++;
2445 }
2446
2447 return bufs;
2448
2449 err:
2450 free_quic_conn_tx_bufs(bufs, nb);
2451 return NULL;
2452}
2453
2454/* Release all the memory allocated for <conn> QUIC connection. */
2455static void quic_conn_free(struct quic_conn *conn)
2456{
2457 int i;
2458
2459 free_quic_conn_cids(conn);
2460 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++)
2461 quic_conn_enc_level_uninit(&conn->els[i]);
2462 free_quic_conn_tx_bufs(conn->tx.bufs, conn->tx.nb_buf);
2463 if (conn->timer_task)
2464 task_destroy(conn->timer_task);
2465 pool_free(pool_head_quic_conn, conn);
2466}
2467
2468/* Callback called upon loss detection and PTO timer expirations. */
2469static struct task *process_timer(struct task *task, void *ctx, unsigned short state)
2470{
2471 struct quic_conn_ctx *conn_ctx;
2472 struct quic_conn *qc;
2473 struct quic_pktns *pktns;
2474
2475
2476 conn_ctx = task->context;
2477 qc = conn_ctx->conn->qc;
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01002478 TRACE_ENTER(QUIC_EV_CONN_PTIMER, conn_ctx->conn,
2479 NULL, NULL, &qc->path->ifae_pkts);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002480 task->expire = TICK_ETERNITY;
2481 pktns = quic_loss_pktns(qc);
2482 if (tick_isset(pktns->tx.loss_time)) {
2483 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2484
2485 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
2486 if (!LIST_ISEMPTY(&lost_pkts))
2487 qc_release_lost_pkts(pktns, ctx, &lost_pkts, now_ms);
2488 qc_set_timer(conn_ctx);
2489 goto out;
2490 }
2491
2492 if (qc->path->in_flight) {
2493 pktns = quic_pto_pktns(qc, conn_ctx->state >= QUIC_HS_ST_COMPLETE, NULL);
2494 pktns->tx.pto_probe = 1;
2495 }
2496 else if (objt_server(qc->conn->target) && conn_ctx->state <= QUIC_HS_ST_COMPLETE) {
2497 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2498 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2499
2500 if (hel->tls_ctx.rx.flags == QUIC_FL_TLS_SECRETS_SET)
2501 hel->pktns->tx.pto_probe = 1;
2502 if (iel->tls_ctx.rx.flags == QUIC_FL_TLS_SECRETS_SET)
2503 iel->pktns->tx.pto_probe = 1;
2504 }
2505 qc->tx.nb_pto_dgrams = QUIC_MAX_NB_PTO_DGRAMS;
2506 tasklet_wakeup(conn_ctx->wait_event.tasklet);
2507 qc->path->loss.pto_count++;
2508
2509 out:
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01002510 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, conn_ctx->conn, pktns);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002511
2512 return task;
2513}
2514
2515/* Initialize <conn> QUIC connection with <quic_initial_clients> as root of QUIC
2516 * connections used to identify the first Initial packets of client connecting
2517 * to listeners. This parameter must be NULL for QUIC connections attached
2518 * to listeners. <dcid> is the destination connection ID with <dcid_len> as length.
2519 * <scid> is the source connection ID with <scid_len> as length.
2520 * Returns 1 if succeeded, 0 if not.
2521 */
2522int qc_new_conn_init(struct quic_conn *qc, int ipv4,
2523 struct eb_root *quic_initial_clients,
2524 struct eb_root *quic_clients,
2525 unsigned char *dcid, size_t dcid_len,
2526 unsigned char *scid, size_t scid_len)
2527{
2528 int i;
2529 /* Initial CID. */
2530 struct quic_connection_id *icid;
2531
2532 TRACE_ENTER(QUIC_EV_CONN_INIT, qc->conn);
2533 qc->cids = EB_ROOT;
2534 /* QUIC Server (or listener). */
2535 if (objt_listener(qc->conn->target)) {
2536 /* Copy the initial DCID. */
2537 qc->odcid.len = dcid_len;
2538 if (qc->odcid.len)
2539 memcpy(qc->odcid.data, dcid, dcid_len);
2540
2541 /* Copy the SCID as our DCID for this connection. */
2542 if (scid_len)
2543 memcpy(qc->dcid.data, scid, scid_len);
2544 qc->dcid.len = scid_len;
2545 }
2546 /* QUIC Client (outgoing connection to servers) */
2547 else {
2548 if (dcid_len)
2549 memcpy(qc->dcid.data, dcid, dcid_len);
2550 qc->dcid.len = dcid_len;
2551 }
2552
2553 /* Initialize the output buffer */
2554 qc->obuf.pos = qc->obuf.data;
2555
2556 icid = new_quic_cid(&qc->cids, 0);
2557 if (!icid)
2558 return 0;
2559
2560 /* Select our SCID which is the first CID with 0 as sequence number. */
2561 qc->scid = icid->cid;
2562
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05002563 /* Insert the DCID the QUIC client has chosen (only for listeners) */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002564 if (objt_listener(qc->conn->target))
2565 ebmb_insert(quic_initial_clients, &qc->odcid_node, qc->odcid.len);
2566
2567 /* Insert our SCID, the connection ID for the QUIC client. */
2568 ebmb_insert(quic_clients, &qc->scid_node, qc->scid.len);
2569
2570 /* Packet number spaces initialization. */
2571 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
2572 quic_pktns_init(&qc->pktns[i]);
2573 /* QUIC encryption level context initialization. */
2574 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
2575 if (!quic_conn_enc_level_init(qc, i))
2576 goto err;
2577 /* Initialize the packet number space. */
2578 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
2579 }
2580
2581 /* TX part. */
2582 LIST_INIT(&qc->tx.frms_to_send);
2583 qc->tx.bufs = quic_conn_tx_bufs_alloc(QUIC_CONN_TX_BUFS_NB, QUIC_CONN_TX_BUF_SZ);
2584 if (!qc->tx.bufs)
2585 goto err;
2586
2587 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
2588 qc->tx.wbuf = qc->tx.rbuf = 0;
2589 qc->tx.bytes = 0;
2590 qc->tx.nb_pto_dgrams = 0;
2591 /* RX part. */
2592 qc->rx.bytes = 0;
2593
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002594 /* XXX TO DO: Only one path at this time. */
2595 qc->path = &qc->paths[0];
2596 quic_path_init(qc->path, ipv4, default_quic_cc_algo, qc);
2597
2598 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc->conn);
2599
2600 return 1;
2601
2602 err:
2603 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_INIT, qc->conn);
2604 quic_conn_free(qc);
2605 return 0;
2606}
2607
2608/* Initialize the timer task of <qc> QUIC connection.
2609 * Returns 1 if succeeded, 0 if not.
2610 */
2611static int quic_conn_init_timer(struct quic_conn *qc)
2612{
2613 qc->timer_task = task_new(MAX_THREADS_MASK);
2614 if (!qc->timer_task)
2615 return 0;
2616
2617 qc->timer = TICK_ETERNITY;
2618 qc->timer_task->process = process_timer;
2619 qc->timer_task->context = qc->conn->xprt_ctx;
2620
2621 return 1;
2622}
2623
2624/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
2625 * past one byte of this buffer.
2626 */
2627static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
2628 struct quic_rx_packet *pkt)
2629{
2630 unsigned char dcid_len, scid_len;
2631
2632 /* Version */
2633 if (!quic_read_uint32(&pkt->version, (const unsigned char **)buf, end))
2634 return 0;
2635
2636 if (!pkt->version) { /* XXX TO DO XXX Version negotiation packet */ };
2637
2638 /* Destination Connection ID Length */
2639 dcid_len = *(*buf)++;
2640 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
2641 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1)
2642 /* XXX MUST BE DROPPED */
2643 return 0;
2644
2645 if (dcid_len) {
2646 /* Check that the length of this received DCID matches the CID lengths
2647 * of our implementation for non Initials packets only.
2648 */
2649 if (pkt->type != QUIC_PACKET_TYPE_INITIAL && dcid_len != QUIC_CID_LEN)
2650 return 0;
2651
2652 memcpy(pkt->dcid.data, *buf, dcid_len);
2653 }
2654
2655 pkt->dcid.len = dcid_len;
2656 *buf += dcid_len;
2657
2658 /* Source Connection ID Length */
2659 scid_len = *(*buf)++;
2660 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len)
2661 /* XXX MUST BE DROPPED */
2662 return 0;
2663
2664 if (scid_len)
2665 memcpy(pkt->scid.data, *buf, scid_len);
2666 pkt->scid.len = scid_len;
2667 *buf += scid_len;
2668
2669 return 1;
2670}
2671
2672/* Try to remove the header protecttion of <pkt> QUIC packet attached to <conn>
2673 * QUIC connection with <buf> as packet number field address, <end> a pointer to one
2674 * byte past the end of the buffer containing this packet and <beg> the address of
2675 * the packet first byte.
2676 * If succeeded, this function updates <*buf> to point to the next packet in the buffer.
2677 * Returns 1 if succeeded, 0 if not.
2678 */
2679static inline int qc_try_rm_hp(struct quic_rx_packet *pkt,
2680 unsigned char **buf, unsigned char *beg,
2681 const unsigned char *end,
2682 struct quic_conn_ctx *ctx)
2683{
2684 unsigned char *pn = NULL; /* Packet number field */
2685 enum quic_tls_enc_level tel;
2686 struct quic_enc_level *qel;
2687 /* Only for traces. */
2688 struct quic_rx_packet *qpkt_trace;
2689
2690 qpkt_trace = NULL;
2691 TRACE_ENTER(QUIC_EV_CONN_TRMHP, ctx->conn);
2692 /* The packet number is here. This is also the start minus
2693 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
2694 * protection.
2695 */
2696 pn = *buf;
2697 tel = quic_packet_type_enc_level(pkt->type);
2698 if (tel == QUIC_TLS_ENC_LEVEL_NONE) {
2699 TRACE_DEVEL("Wrong enc. level", QUIC_EV_CONN_TRMHP, ctx->conn);
2700 goto err;
2701 }
2702
2703 qel = &ctx->conn->qc->els[tel];
2704
2705 if (qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_DCD) {
2706 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, ctx->conn);
2707 goto err;
2708 }
2709
2710 if ((qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_SET) &&
2711 (tel != QUIC_TLS_ENC_LEVEL_APP || ctx->state >= QUIC_HS_ST_COMPLETE)) {
2712 /* Note that the following function enables us to unprotect the packet
2713 * number and its length subsequently used to decrypt the entire
2714 * packets.
2715 */
2716 if (!qc_do_rm_hp(pkt, &qel->tls_ctx,
2717 qel->pktns->rx.largest_pn, pn, beg, end, ctx)) {
2718 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, ctx->conn);
2719 goto err;
2720 }
2721
2722 /* The AAD includes the packet number field found at <pn>. */
2723 pkt->aad_len = pn - beg + pkt->pnl;
2724 qpkt_trace = pkt;
2725 /* Store the packet */
2726 pkt->pn_node.key = pkt->pn;
2727 quic_rx_packet_eb64_insert(&qel->rx.pkts, &pkt->pn_node);
2728 }
2729 else {
2730 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, ctx->conn, pkt);
2731 pkt->pn_offset = pn - beg;
2732 quic_rx_packet_list_addq(&qel->rx.pqpkts, pkt);
2733 }
2734
2735 memcpy(pkt->data, beg, pkt->len);
2736 /* Updtate the offset of <*buf> for the next QUIC packet. */
2737 *buf = beg + pkt->len;
2738
2739 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, ctx->conn, qpkt_trace);
2740 return 1;
2741
2742 err:
2743 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TRMHP, ctx->conn, qpkt_trace);
2744 return 0;
2745}
2746
2747/* Parse the header form from <byte0> first byte of <pkt> pacekt to set type.
2748 * Also set <*long_header> to 1 if this form is long, 0 if not.
2749 */
2750static inline void qc_parse_hd_form(struct quic_rx_packet *pkt,
2751 unsigned char byte0, int *long_header)
2752{
2753 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
2754 pkt->type =
2755 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
2756 *long_header = 1;
2757 }
2758 else {
2759 pkt->type = QUIC_PACKET_TYPE_SHORT;
2760 *long_header = 0;
2761 }
2762}
2763
2764static ssize_t qc_srv_pkt_rcv(unsigned char **buf, const unsigned char *end,
2765 struct quic_rx_packet *pkt,
2766 struct quic_dgram_ctx *dgram_ctx,
2767 struct sockaddr_storage *saddr)
2768{
2769 unsigned char *beg;
2770 uint64_t len;
2771 struct quic_conn *qc;
2772 struct eb_root *cids;
2773 struct ebmb_node *node;
2774 struct connection *srv_conn;
2775 struct quic_conn_ctx *conn_ctx;
2776 int long_header;
2777
2778 qc = NULL;
2779 TRACE_ENTER(QUIC_EV_CONN_SPKT);
2780 if (end <= *buf)
2781 goto err;
2782
2783 /* Fixed bit */
2784 if (!(**buf & QUIC_PACKET_FIXED_BIT))
2785 /* XXX TO BE DISCARDED */
2786 goto err;
2787
2788 srv_conn = dgram_ctx->owner;
2789 beg = *buf;
2790 /* Header form */
2791 qc_parse_hd_form(pkt, *(*buf)++, &long_header);
2792 if (long_header) {
2793 size_t cid_lookup_len;
2794
2795 if (!quic_packet_read_long_header(buf, end, pkt))
2796 goto err;
2797
2798 /* For Initial packets, and for servers (QUIC clients connections),
2799 * there is no Initial connection IDs storage.
2800 */
2801 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2802 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2803 cid_lookup_len = pkt->dcid.len;
2804 }
2805 else {
2806 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2807 cid_lookup_len = QUIC_CID_LEN;
2808 }
2809
2810 node = ebmb_lookup(cids, pkt->dcid.data, cid_lookup_len);
2811 if (!node)
2812 goto err;
2813
2814 qc = ebmb_entry(node, struct quic_conn, scid_node);
2815
2816 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2817 qc->dcid.len = pkt->scid.len;
2818 if (pkt->scid.len)
2819 memcpy(qc->dcid.data, pkt->scid.data, pkt->scid.len);
2820 }
2821
2822 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2823 uint64_t token_len;
2824
2825 if (!quic_dec_int(&token_len, (const unsigned char **)buf, end) || end - *buf < token_len)
2826 goto err;
2827
2828 /* XXX TO DO XXX 0 value means "the token is not present".
2829 * A server which sends an Initial packet must not set the token.
2830 * So, a client which receives an Initial packet with a token
2831 * MUST discard the packet or generate a connection error with
2832 * PROTOCOL_VIOLATION as type.
2833 * The token must be provided in a Retry packet or NEW_TOKEN frame.
2834 */
2835 pkt->token_len = token_len;
2836 }
2837 }
2838 else {
2839 /* XXX TO DO: Short header XXX */
2840 if (end - *buf < QUIC_CID_LEN)
2841 goto err;
2842
2843 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2844 node = ebmb_lookup(cids, *buf, QUIC_CID_LEN);
2845 if (!node)
2846 goto err;
2847
2848 qc = ebmb_entry(node, struct quic_conn, scid_node);
2849 *buf += QUIC_CID_LEN;
2850 }
2851 /* Store the DCID used for this packet to check the packet which
2852 * come in this UDP datagram match with it.
2853 */
2854 if (!dgram_ctx->dcid_node)
2855 dgram_ctx->dcid_node = node;
2856 /* Only packets packets with long headers and not RETRY or VERSION as type
2857 * have a length field.
2858 */
2859 if (long_header && pkt->type != QUIC_PACKET_TYPE_RETRY && pkt->version) {
2860 if (!quic_dec_int(&len, (const unsigned char **)buf, end) || end - *buf < len)
2861 goto err;
2862
2863 pkt->len = len;
2864 }
2865 else if (!long_header) {
2866 /* A short packet is the last one of an UDP datagram. */
2867 pkt->len = end - *buf;
2868 }
2869
2870 conn_ctx = qc->conn->xprt_ctx;
2871
2872 /* Increase the total length of this packet by the header length. */
2873 pkt->len += *buf - beg;
2874 /* Do not check the DCID node before the length. */
2875 if (dgram_ctx->dcid_node != node) {
2876 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_SPKT, qc->conn);
2877 goto err;
2878 }
2879
2880 if (pkt->len > sizeof pkt->data) {
2881 TRACE_PROTO("Too big packet", QUIC_EV_CONN_SPKT, qc->conn, pkt, &pkt->len);
2882 goto err;
2883 }
2884
2885 if (!qc_try_rm_hp(pkt, buf, beg, end, conn_ctx))
2886 goto err;
2887
2888 /* Wake the tasklet of the QUIC connection packet handler. */
2889 if (conn_ctx)
2890 tasklet_wakeup(conn_ctx->wait_event.tasklet);
2891
2892 TRACE_LEAVE(QUIC_EV_CONN_SPKT, qc->conn);
2893
2894 return pkt->len;
2895
2896 err:
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01002897 TRACE_DEVEL("Leaing in error", QUIC_EV_CONN_SPKT, qc ? qc->conn : NULL);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002898 return -1;
2899}
2900
2901static ssize_t qc_lstnr_pkt_rcv(unsigned char **buf, const unsigned char *end,
2902 struct quic_rx_packet *pkt,
2903 struct quic_dgram_ctx *dgram_ctx,
2904 struct sockaddr_storage *saddr)
2905{
2906 unsigned char *beg;
2907 uint64_t len;
2908 struct quic_conn *qc;
2909 struct eb_root *cids;
2910 struct ebmb_node *node;
2911 struct listener *l;
2912 struct quic_conn_ctx *conn_ctx;
2913 int long_header = 0;
2914
2915 qc = NULL;
2916 TRACE_ENTER(QUIC_EV_CONN_LPKT);
2917 if (end <= *buf)
2918 goto err;
2919
2920 /* Fixed bit */
2921 if (!(**buf & QUIC_PACKET_FIXED_BIT)) {
2922 /* XXX TO BE DISCARDED */
2923 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2924 goto err;
2925 }
2926
2927 l = dgram_ctx->owner;
2928 beg = *buf;
2929 /* Header form */
2930 qc_parse_hd_form(pkt, *(*buf)++, &long_header);
2931 if (long_header) {
2932 unsigned char dcid_len;
2933
2934 if (!quic_packet_read_long_header(buf, end, pkt)) {
2935 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2936 goto err;
2937 }
2938
2939 dcid_len = pkt->dcid.len;
2940 /* For Initial packets, and for servers (QUIC clients connections),
2941 * there is no Initial connection IDs storage.
2942 */
2943 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2944 /* DCIDs of first packets coming from clients may have the same values.
2945 * Let's distinguish them concatenating the socket addresses to the DCIDs.
2946 */
2947 quic_cid_saddr_cat(&pkt->dcid, saddr);
2948 cids = &l->rx.odcids;
2949 }
2950 else {
2951 if (pkt->dcid.len != QUIC_CID_LEN) {
2952 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2953 goto err;
2954 }
2955
2956 cids = &l->rx.cids;
2957 }
2958
2959 node = ebmb_lookup(cids, pkt->dcid.data, pkt->dcid.len);
2960 if (!node && pkt->type == QUIC_PACKET_TYPE_INITIAL && dcid_len == QUIC_CID_LEN &&
2961 cids == &l->rx.odcids) {
2962 /* Switch to the definitive tree ->cids containing the final CIDs. */
2963 node = ebmb_lookup(&l->rx.cids, pkt->dcid.data, dcid_len);
2964 if (node) {
2965 /* If found, signal this with NULL as special value for <cids>. */
2966 pkt->dcid.len = dcid_len;
2967 cids = NULL;
2968 }
2969 }
2970
2971 if (!node) {
2972 if (pkt->type != QUIC_PACKET_TYPE_INITIAL) {
2973 TRACE_PROTO("Non Initiial packet", QUIC_EV_CONN_LPKT);
2974 goto err;
2975 }
2976
2977 qc = new_quic_conn(pkt->version);
2978 if (!qc) {
2979 TRACE_PROTO("Non allocated new connection", QUIC_EV_CONN_LPKT);
2980 goto err;
2981 }
2982
2983 pkt->qc = qc;
2984 pkt->saddr = *saddr;
2985 /* Note that here, odcid_len equals to pkt->dcid.len minus the length
2986 * of <saddr>.
2987 */
2988 pkt->odcid_len = dcid_len;
2989 /* Enqueue this packet. */
2990 LIST_ADDQ(&l->rx.qpkts, &pkt->rx_list);
2991 /* Try to accept a new connection. */
2992 listener_accept(l);
2993 if (!qc->conn) {
2994 TRACE_PROTO("Non accepted connection", QUIC_EV_CONN_LPKT, qc->conn);
2995 goto err;
2996 }
2997
2998 if (!quic_conn_init_timer(qc)) {
2999 TRACE_PROTO("Non initialized timer", QUIC_EV_CONN_LPKT, qc->conn);
3000 goto err;
3001 }
3002
3003 /* This is the DCID node sent in this packet by the client. */
3004 node = &qc->odcid_node;
3005 conn_ctx = qc->conn->xprt_ctx;
3006 SSL_set_quic_transport_params(conn_ctx->ssl,
3007 qc->enc_params, qc->enc_params_len);
3008 }
3009 else {
3010 if (pkt->type == QUIC_PACKET_TYPE_INITIAL && cids == &l->rx.odcids)
3011 qc = ebmb_entry(node, struct quic_conn, odcid_node);
3012 else
3013 qc = ebmb_entry(node, struct quic_conn, scid_node);
3014 }
3015
3016 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
3017 uint64_t token_len;
3018 struct quic_tls_ctx *ctx =
3019 &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
3020
3021 if (!quic_dec_int(&token_len, (const unsigned char **)buf, end) ||
3022 end - *buf < token_len) {
3023 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3024 goto err;
3025 }
3026
3027 /* XXX TO DO XXX 0 value means "the token is not present".
3028 * A server which sends an Initial packet must not set the token.
3029 * So, a client which receives an Initial packet with a token
3030 * MUST discard the packet or generate a connection error with
3031 * PROTOCOL_VIOLATION as type.
3032 * The token must be provided in a Retry packet or NEW_TOKEN frame.
3033 */
3034 pkt->token_len = token_len;
3035 /* NOTE: the socket address has been concatenated to the destination ID
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003036 * chosen by the client for Initial packets.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003037 */
3038 if (!ctx->rx.hp && !qc_new_isecs(qc->conn, pkt->dcid.data,
3039 pkt->odcid_len, 1)) {
3040 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3041 goto err;
3042 }
3043 }
3044 }
3045 else {
3046 if (end - *buf < QUIC_CID_LEN) {
3047 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
3048 goto err;
3049 }
3050
3051 cids = &l->rx.cids;
3052 node = ebmb_lookup(cids, *buf, QUIC_CID_LEN);
3053 if (!node) {
3054 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
3055 goto err;
3056 }
3057
3058 qc = ebmb_entry(node, struct quic_conn, scid_node);
3059 *buf += QUIC_CID_LEN;
3060 }
3061
3062 /* Store the DCID used for this packet to check the packet which
3063 * come in this UDP datagram match with it.
3064 */
3065 if (!dgram_ctx->dcid_node) {
3066 dgram_ctx->dcid_node = node;
3067 dgram_ctx->qc = qc;
3068 }
3069
3070 /* Only packets packets with long headers and not RETRY or VERSION as type
3071 * have a length field.
3072 */
3073 if (long_header && pkt->type != QUIC_PACKET_TYPE_RETRY && pkt->version) {
3074 if (!quic_dec_int(&len, (const unsigned char **)buf, end) ||
3075 end - *buf < len) {
3076 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3077 goto err;
3078 }
3079
3080 pkt->len = len;
3081 }
3082 else if (!long_header) {
3083 /* A short packet is the last one of an UDP datagram. */
3084 pkt->len = end - *buf;
3085 }
3086
3087 /* Update the state if needed. */
3088 conn_ctx = qc->conn->xprt_ctx;
3089
3090 /* Increase the total length of this packet by the header length. */
3091 pkt->len += *buf - beg;
3092 /* Do not check the DCID node before the length. */
3093 if (dgram_ctx->dcid_node != node) {
3094 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3095 goto err;
3096 }
3097
3098 if (pkt->len > sizeof pkt->data) {
3099 TRACE_PROTO("Too big packet", QUIC_EV_CONN_LPKT, qc->conn, pkt, &pkt->len);
3100 goto err;
3101 }
3102
3103 if (!qc_try_rm_hp(pkt, buf, beg, end, conn_ctx)) {
3104 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3105 goto err;
3106 }
3107
3108 /* Wake the tasklet of the QUIC connection packet handler. */
3109 if (conn_ctx)
3110 tasklet_wakeup(conn_ctx->wait_event.tasklet);
3111 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc->conn, pkt);
3112
3113 return pkt->len;
3114
3115 err:
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01003116 TRACE_DEVEL("Leaving in error", QUIC_EV_CONN_LPKT,
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003117 qc ? qc->conn : NULL, pkt);
3118 return -1;
3119}
3120
3121/* This function builds into <buf> buffer a QUIC long packet header whose size may be computed
3122 * in advance. This is the reponsability of the caller to check there is enough room in this
3123 * buffer to build a long header.
3124 * Returns 0 if <type> QUIC packet type is not supported by long header, or 1 if succeeded.
3125 */
3126static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
3127 int type, size_t pn_len, struct quic_conn *conn)
3128{
3129 if (type > QUIC_PACKET_TYPE_RETRY)
3130 return 0;
3131
3132 /* #0 byte flags */
3133 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
3134 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
3135 /* Version */
3136 quic_write_uint32(buf, end, conn->version);
3137 *(*buf)++ = conn->dcid.len;
3138 /* Destination connection ID */
3139 if (conn->dcid.len) {
3140 memcpy(*buf, conn->dcid.data, conn->dcid.len);
3141 *buf += conn->dcid.len;
3142 }
3143 /* Source connection ID */
3144 *(*buf)++ = conn->scid.len;
3145 if (conn->scid.len) {
3146 memcpy(*buf, conn->scid.data, conn->scid.len);
3147 *buf += conn->scid.len;
3148 }
3149
3150 return 1;
3151}
3152
3153/* This function builds into <buf> buffer a QUIC long packet header whose size may be computed
3154 * in advance. This is the reponsability of the caller to check there is enough room in this
3155 * buffer to build a long header.
3156 * Returns 0 if <type> QUIC packet type is not supported by long header, or 1 if succeeded.
3157 */
3158static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
3159 size_t pn_len, struct quic_conn *conn)
3160{
3161 /* #0 byte flags */
3162 *(*buf)++ = QUIC_PACKET_FIXED_BIT | (pn_len - 1);
3163 /* Destination connection ID */
3164 if (conn->dcid.len) {
3165 memcpy(*buf, conn->dcid.data, conn->dcid.len);
3166 *buf += conn->dcid.len;
3167 }
3168
3169 return 1;
3170}
3171
3172/* Apply QUIC header protection to the packet with <buf> as first byte address,
3173 * <pn> as address of the Packet number field, <pnlen> being this field length
3174 * with <aead> as AEAD cipher and <key> as secret key.
3175 * Returns 1 if succeeded or 0 if failed.
3176 */
3177static int quic_apply_header_protection(unsigned char *buf, unsigned char *pn, size_t pnlen,
3178 const EVP_CIPHER *aead, const unsigned char *key)
3179{
3180 int i, ret, outlen;
3181 EVP_CIPHER_CTX *ctx;
3182 /* We need an IV of at least 5 bytes: one byte for bytes #0
3183 * and at most 4 bytes for the packet number
3184 */
3185 unsigned char mask[5] = {0};
3186
3187 ret = 0;
3188 ctx = EVP_CIPHER_CTX_new();
3189 if (!ctx)
3190 return 0;
3191
3192 if (!EVP_EncryptInit_ex(ctx, aead, NULL, key, pn + QUIC_PACKET_PN_MAXLEN) ||
3193 !EVP_EncryptUpdate(ctx, mask, &outlen, mask, sizeof mask) ||
3194 !EVP_EncryptFinal_ex(ctx, mask, &outlen))
3195 goto out;
3196
3197 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
3198 for (i = 0; i < pnlen; i++)
3199 pn[i] ^= mask[i + 1];
3200
3201 ret = 1;
3202
3203 out:
3204 EVP_CIPHER_CTX_free(ctx);
3205
3206 return ret;
3207}
3208
3209/* Reduce the encoded size of <ack_frm> ACK frame removing the last
3210 * ACK ranges if needed to a value below <limit> in bytes.
3211 * Return 1 if succeeded, 0 if not.
3212 */
3213static int quic_ack_frm_reduce_sz(struct quic_frame *ack_frm, size_t limit)
3214{
3215 size_t room, ack_delay_sz;
3216
3217 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
3218 /* A frame is made of 1 byte for the frame type. */
3219 room = limit - ack_delay_sz - 1;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003220 if (!quic_rm_last_ack_ranges(ack_frm->tx_ack.arngs, room))
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003221 return 0;
3222
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003223 return 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003224}
3225
3226/* Prepare as most as possible CRYPTO frames from prebuilt CRYPTO frames for <qel>
3227 * encryption level to be encoded in a buffer with <room> as available room,
Frédéric Lécailleea604992020-12-24 13:01:37 +01003228 * and <*len> the packet Length field initialized with the number of bytes already present
3229 * in this buffer which must be taken into an account for the Length packet field value.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003230 * <headlen> is the number of bytes already present in this packet before building
Frédéric Lécailleea604992020-12-24 13:01:37 +01003231 * CRYPTO frames.
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003232 * This is the responsibility of the caller to check that <*len> < <room> as this is
3233 * the responsibility to check that <headlen> < quic_path_prep_data(conn->path).
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003234 * Update consequently <*len> to reflect the size of these CRYPTO frames built
3235 * by this function. Also attach these CRYPTO frames to <pkt> QUIC packet.
3236 * Return 1 if succeeded, 0 if not.
3237 */
3238static inline int qc_build_cfrms(struct quic_tx_packet *pkt,
Frédéric Lécailleea604992020-12-24 13:01:37 +01003239 size_t room, size_t *len, size_t headlen,
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003240 struct quic_enc_level *qel,
3241 struct quic_conn *conn)
3242{
Frédéric Lécailleea604992020-12-24 13:01:37 +01003243 int ret;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003244 struct quic_tx_frm *cf, *cfbak;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003245
Frédéric Lécailleea604992020-12-24 13:01:37 +01003246 ret = 0;
3247 /* If we are not probing we must take into an account the congestion
3248 * control window.
3249 */
3250 if (!conn->tx.nb_pto_dgrams)
3251 room = QUIC_MIN(room, quic_path_prep_data(conn->path) - headlen);
3252 TRACE_PROTO("************** CRYPTO frames build (headlen)",
3253 QUIC_EV_CONN_BCFRMS, conn->conn, &headlen);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003254 list_for_each_entry_safe(cf, cfbak, &qel->pktns->tx.frms, list) {
3255 /* header length, data length, frame length. */
3256 size_t hlen, dlen, cflen;
3257
Frédéric Lécailleea604992020-12-24 13:01:37 +01003258 TRACE_PROTO(" New CRYPTO frame build (room, len)",
3259 QUIC_EV_CONN_BCFRMS, conn->conn, &room, len);
3260 if (!room)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003261 break;
3262
3263 /* Compute the length of this CRYPTO frame header */
3264 hlen = 1 + quic_int_getsize(cf->crypto.offset);
3265 /* Compute the data length of this CRyPTO frame. */
3266 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
Frédéric Lécailleea604992020-12-24 13:01:37 +01003267 TRACE_PROTO(" CRYPTO data length (hlen, crypto.len, dlen)",
3268 QUIC_EV_CONN_BCFRMS, conn->conn, &hlen, &cf->crypto.len, &dlen);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003269 if (!dlen)
3270 break;
3271
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003272 pkt->cdata_len += dlen;
3273 /* CRYPTO frame length. */
3274 cflen = hlen + quic_int_getsize(dlen) + dlen;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003275 TRACE_PROTO(" CRYPTO frame length (cflen)",
3276 QUIC_EV_CONN_BCFRMS, conn->conn, &cflen);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003277 /* Add the CRYPTO data length and its encoded length to the packet
3278 * length and the length of this length.
3279 */
3280 *len += cflen;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003281 room -= cflen;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003282 if (dlen == cf->crypto.len) {
3283 /* <cf> CRYPTO data have been consumed. */
3284 LIST_DEL(&cf->list);
3285 LIST_ADDQ(&pkt->frms, &cf->list);
3286 }
3287 else {
3288 struct quic_tx_frm *new_cf;
3289
3290 new_cf = pool_alloc(pool_head_quic_tx_frm);
3291 if (!new_cf) {
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01003292 TRACE_PROTO("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003293 return 0;
3294 }
3295
3296 new_cf->type = QUIC_FT_CRYPTO;
3297 new_cf->crypto.len = dlen;
3298 new_cf->crypto.offset = cf->crypto.offset;
3299 LIST_ADDQ(&pkt->frms, &new_cf->list);
3300 /* Consume <dlen> bytes of the current frame. */
3301 cf->crypto.len -= dlen;
3302 cf->crypto.offset += dlen;
3303 }
Frédéric Lécailleea604992020-12-24 13:01:37 +01003304 ret = 1;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003305 }
3306
Frédéric Lécailleea604992020-12-24 13:01:37 +01003307 return ret;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003308}
3309
3310/* This function builds a clear handshake packet used during a QUIC TLS handshakes
3311 * into <wbuf> the current <wbuf> for <conn> QUIC connection with <qel> as QUIC
3312 * TLS encryption level for outgoing packets filling it with as much as CRYPTO
3313 * data as possible from <offset> offset in the CRYPTO data stream. Note that
3314 * this offset value is updated by the length of the CRYPTO frame used to embed
3315 * the CRYPTO data if this packet and only if the packet is successfully built.
3316 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
3317 * reserved so that to be sure there is enough room to build this AEAD TAG after
3318 * having successfully returned from this function and to be sure the position
3319 * pointer of <wbuf> may be safely incremented by QUIC_TLS_TAG_LEN. After having
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003320 * returned from this function, <wbuf> position will point one past the last
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003321 * byte of the payload with the confidence there is at least QUIC_TLS_TAG_LEN bytes
3322 * available packet to encrypt this packet.
3323 * This function also update the value of <buf_pn> pointer to point to the packet
3324 * number field in this packet. <pn_len> will also have the packet number
3325 * length as value.
3326 *
3327 * Return the length of the packet if succeeded minus QUIC_TLS_TAG_LEN, or -1 if
3328 * failed (not enough room in <wbuf> to build this packet plus QUIC_TLS_TAG_LEN
3329 * bytes), -2 if there are too much CRYPTO data in flight to build a packet.
3330 */
3331static ssize_t qc_do_build_hdshk_pkt(struct q_buf *wbuf,
3332 struct quic_tx_packet *pkt, int pkt_type,
3333 int64_t pn, size_t *pn_len,
3334 unsigned char **buf_pn,
3335 struct quic_enc_level *qel,
3336 struct quic_conn *conn)
3337{
3338 unsigned char *beg, *pos;
3339 const unsigned char *end;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003340 size_t len, len_frms, token_fields_len, padding_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003341 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
3342 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
3343 struct quic_crypto *crypto = &frm.crypto;
3344 size_t ack_frm_len;
3345 int64_t largest_acked_pn;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003346 int add_ping_frm;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003347
Frédéric Lécailleea604992020-12-24 13:01:37 +01003348 /* Length field value with CRYPTO frames if present. */
3349 len_frms = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003350 beg = pos = q_buf_getpos(wbuf);
3351 end = q_buf_end(wbuf);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003352 /* When not probing and not acking, reduce the size of this buffer to respect
3353 * the congestion controller window.
3354 */
3355 if (!conn->tx.nb_pto_dgrams && !(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED)) {
3356 size_t path_room;
3357
3358 path_room = quic_path_prep_data(conn->path);
3359 if (end - beg > path_room)
3360 end = beg + path_room;
3361 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003362
3363 /* For a server, the token field of an Initial packet is empty. */
3364 token_fields_len = pkt_type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0;
3365
3366 /* Check there is enough room to build the header followed by a token. */
3367 if (end - pos < QUIC_LONG_PACKET_MINLEN + conn->dcid.len +
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003368 conn->scid.len + token_fields_len + QUIC_TLS_TAG_LEN) {
3369 ssize_t room = end - pos;
3370 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3371 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003372 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003373 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003374
3375 /* Reserve enough room at the end of the packet for the AEAD TAG. */
3376 end -= QUIC_TLS_TAG_LEN;
3377 largest_acked_pn = qel->pktns->tx.largest_acked_pn;
3378 /* packet number length */
3379 *pn_len = quic_packet_number_length(pn, largest_acked_pn);
3380
3381 quic_build_packet_long_header(&pos, end, pkt_type, *pn_len, conn);
3382
3383 /* Encode the token length (0) for an Initial packet. */
3384 if (pkt_type == QUIC_PACKET_TYPE_INITIAL)
3385 *pos++ = 0;
3386
3387 /* Build an ACK frame if required. */
3388 ack_frm_len = 0;
3389 if ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003390 !eb_is_empty(&qel->pktns->rx.arngs.root)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003391 ack_frm.tx_ack.ack_delay = 0;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003392 ack_frm.tx_ack.arngs = &qel->pktns->rx.arngs;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003393 ack_frm_len = quic_ack_frm_reduce_sz(&ack_frm, end - pos);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003394 if (!ack_frm_len) {
3395 ssize_t room = end - pos;
3396 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3397 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003398 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003399 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003400
3401 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
3402 }
3403
3404 /* Length field value without the CRYPTO frames data length. */
3405 len = ack_frm_len + *pn_len;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003406 if (!LIST_ISEMPTY(&qel->pktns->tx.frms)) {
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003407 ssize_t room = end - pos;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003408
3409 len_frms = len + QUIC_TLS_TAG_LEN;
3410 if (!qc_build_cfrms(pkt, end - pos, &len_frms, pos - beg, qel, conn)) {
3411 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3412 conn->conn, NULL, NULL, &room);
3413 goto err;
3414 }
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003415 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003416
3417 add_ping_frm = 0;
3418 padding_len = 0;
3419 if (objt_server(conn->conn->target) &&
3420 pkt_type == QUIC_PACKET_TYPE_INITIAL &&
3421 len < QUIC_INITIAL_PACKET_MINLEN) {
3422 len += padding_len = QUIC_INITIAL_PACKET_MINLEN - len;
3423 }
3424 else if (LIST_ISEMPTY(&pkt->frms)) {
3425 if (qel->pktns->tx.pto_probe) {
3426 /* If we cannot send a CRYPTO frame, we send a PING frame. */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003427 add_ping_frm = 1;
3428 len += 1;
3429 }
3430 /* If there is no frame at all to follow, add at least a PADDING frame. */
3431 if (!ack_frm_len)
3432 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
3433 }
3434
3435 /* Length (of the remaining data). Must not fail because, the buffer size
3436 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
3437 * for the encryption TAG. It must be taken into an account for the length
3438 * of this packet.
3439 */
Frédéric Lécailleea604992020-12-24 13:01:37 +01003440 if (len_frms)
3441 len = len_frms;
3442 else
3443 len += QUIC_TLS_TAG_LEN;
3444 quic_enc_int(&pos, end, len);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003445
3446 /* Packet number field address. */
3447 *buf_pn = pos;
3448
3449 /* Packet number encoding. */
3450 quic_packet_number_encode(&pos, end, pn, *pn_len);
3451
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003452 if (ack_frm_len && !qc_build_frm(&pos, end, &ack_frm, pkt, conn)) {
3453 ssize_t room = end - pos;
3454 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3455 conn->conn, NULL, NULL, &room);
3456 goto err;
3457 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003458
3459 /* Crypto frame */
3460 if (!LIST_ISEMPTY(&pkt->frms)) {
3461 struct quic_tx_frm *cf;
3462
3463 list_for_each_entry(cf, &pkt->frms, list) {
3464 crypto->offset = cf->crypto.offset;
3465 crypto->len = cf->crypto.len;
3466 crypto->qel = qel;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003467 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3468 ssize_t room = end - pos;
3469 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3470 conn->conn, NULL, NULL, &room);
3471 goto err;
3472 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003473 }
3474 }
3475
3476 /* Build a PING frame if needed. */
3477 if (add_ping_frm) {
3478 frm.type = QUIC_FT_PING;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003479 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3480 ssize_t room = end - pos;
3481 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3482 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003483 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003484 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003485 }
3486
3487 /* Build a PADDING frame if needed. */
3488 if (padding_len) {
3489 frm.type = QUIC_FT_PADDING;
3490 frm.padding.len = padding_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003491 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3492 ssize_t room = end - pos;
3493 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3494 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003495 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003496 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003497 }
3498
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003499 /* Always reset this variable as this function has no idea
3500 * if it was set. It is handle by the loss detection timer.
3501 */
3502 qel->pktns->tx.pto_probe = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003503
3504 out:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003505 return pos - beg;
3506
3507 err:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003508 return -1;
3509}
3510
3511static inline void quic_tx_packet_init(struct quic_tx_packet *pkt)
3512{
3513 pkt->cdata_len = 0;
3514 pkt->in_flight_len = 0;
3515 LIST_INIT(&pkt->frms);
3516}
3517
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003518/* Free <pkt> TX packet which has not already attached to any tree. */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003519static inline void free_quic_tx_packet(struct quic_tx_packet *pkt)
3520{
3521 struct quic_tx_frm *frm, *frmbak;
3522
3523 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list) {
3524 LIST_DEL(&frm->list);
3525 pool_free(pool_head_quic_tx_frm, frm);
3526 }
3527 pool_free(pool_head_quic_tx_packet, pkt);
3528}
3529
3530/* Build a handshake packet into <buf> packet buffer with <pkt_type> as packet
3531 * type for <qc> QUIC connection from CRYPTO data stream at <*offset> offset to
3532 * be encrypted at <qel> encryption level.
3533 * Return -2 if the packet could not be encrypted for any reason, -1 if there was
3534 * not enough room in <buf> to build the packet, or the size of the built packet
3535 * if succeeded (may be zero if there is too much crypto data in flight to build the packet).
3536 */
3537static ssize_t qc_build_hdshk_pkt(struct q_buf *buf, struct quic_conn *qc, int pkt_type,
3538 struct quic_enc_level *qel)
3539{
3540 /* The pointer to the packet number field. */
3541 unsigned char *buf_pn;
3542 unsigned char *beg, *end, *payload;
3543 int64_t pn;
3544 size_t pn_len, payload_len, aad_len;
3545 ssize_t pkt_len;
3546 struct quic_tls_ctx *tls_ctx;
3547 struct quic_tx_packet *pkt;
3548
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003549 TRACE_ENTER(QUIC_EV_CONN_HPKT, qc->conn, NULL, qel);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003550 pkt = pool_alloc(pool_head_quic_tx_packet);
3551 if (!pkt) {
3552 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_HPKT, qc->conn);
3553 return -2;
3554 }
3555
3556 quic_tx_packet_init(pkt);
3557 beg = q_buf_getpos(buf);
3558 pn_len = 0;
3559 buf_pn = NULL;
3560 pn = qel->pktns->tx.next_pn + 1;
3561 pkt_len = qc_do_build_hdshk_pkt(buf, pkt, pkt_type, pn, &pn_len, &buf_pn, qel, qc);
3562 if (pkt_len <= 0) {
3563 free_quic_tx_packet(pkt);
3564 return pkt_len;
3565 }
3566
3567 end = beg + pkt_len;
3568 payload = buf_pn + pn_len;
3569 payload_len = end - payload;
3570 aad_len = payload - beg;
3571
3572 tls_ctx = &qel->tls_ctx;
3573 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc->conn))
3574 goto err;
3575
3576 end += QUIC_TLS_TAG_LEN;
3577 pkt_len += QUIC_TLS_TAG_LEN;
3578 if (!quic_apply_header_protection(beg, buf_pn, pn_len,
3579 tls_ctx->tx.hp, tls_ctx->tx.hp_key)) {
3580 TRACE_DEVEL("Could not apply the header protection", QUIC_EV_CONN_HPKT, qc->conn);
3581 goto err;
3582 }
3583
3584 /* Now that a correct packet is built, let us set the position pointer of
3585 * <buf> buffer for the next packet.
3586 */
3587 q_buf_setpos(buf, end);
3588 /* Consume a packet number. */
3589 ++qel->pktns->tx.next_pn;
3590 /* Attach the built packet to its tree. */
3591 pkt->pn_node.key = qel->pktns->tx.next_pn;
3592 /* Set the packet in fligth length for in flight packet only. */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003593 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003594 pkt->in_flight_len = pkt_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003595 qc->path->prep_in_flight += pkt_len;
3596 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003597 pkt->pktns = qel->pktns;
3598 eb64_insert(&qel->pktns->tx.pkts, &pkt->pn_node);
3599 /* Increment the number of bytes in <buf> buffer by the length of this packet. */
3600 buf->data += pkt_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003601 /* Attach this packet to <buf>. */
3602 LIST_ADDQ(&buf->pkts, &pkt->list);
3603 TRACE_LEAVE(QUIC_EV_CONN_HPKT, qc->conn, pkt);
3604
3605 return pkt_len;
3606
3607 err:
3608 free_quic_tx_packet(pkt);
3609 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_HPKT, qc->conn);
3610 return -2;
3611}
3612
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003613/* Prepare a clear post handhskake packet for <conn> QUIC connection.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003614 * Return the length of this packet if succeeded, -1 <wbuf> was full.
3615 */
3616static ssize_t qc_do_build_phdshk_apkt(struct q_buf *wbuf,
3617 struct quic_tx_packet *pkt,
3618 int64_t pn, size_t *pn_len,
3619 unsigned char **buf_pn, struct quic_enc_level *qel,
3620 struct quic_conn *conn)
3621{
3622 const unsigned char *beg, *end;
3623 unsigned char *pos;
3624 struct quic_frame *frm, *sfrm;
3625 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
3626 size_t fake_len, ack_frm_len;
3627 int64_t largest_acked_pn;
3628
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003629 TRACE_ENTER(QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003630 beg = pos = q_buf_getpos(wbuf);
3631 end = q_buf_end(wbuf);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003632 /* When not probing and not acking, reduce the size of this buffer to respect
3633 * the congestion controller window.
3634 */
3635 if (!conn->tx.nb_pto_dgrams && !(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED)) {
3636 size_t path_room;
3637
3638 path_room = quic_path_prep_data(conn->path);
3639 if (end - beg > path_room)
3640 end = beg + path_room;
3641 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003642 largest_acked_pn = qel->pktns->tx.largest_acked_pn;
3643 /* Packet number length */
3644 *pn_len = quic_packet_number_length(pn, largest_acked_pn);
3645 /* Check there is enough room to build this packet (without payload). */
3646 if (end - pos < QUIC_SHORT_PACKET_MINLEN + sizeof_quic_cid(&conn->dcid) +
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003647 *pn_len + QUIC_TLS_TAG_LEN) {
3648 ssize_t room = end - pos;
3649 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3650 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003651 goto err;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003652 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003653
3654 /* Reserve enough room at the end of the packet for the AEAD TAG. */
3655 end -= QUIC_TLS_TAG_LEN;
3656 quic_build_packet_short_header(&pos, end, *pn_len, conn);
3657 /* Packet number field. */
3658 *buf_pn = pos;
3659 /* Packet number encoding. */
3660 quic_packet_number_encode(&pos, end, pn, *pn_len);
3661
3662 /* Build an ACK frame if required. */
3663 ack_frm_len = 0;
3664 if ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003665 !eb_is_empty(&qel->pktns->rx.arngs.root)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003666 ack_frm.tx_ack.ack_delay = 0;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003667 ack_frm.tx_ack.arngs = &qel->pktns->rx.arngs;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003668 ack_frm_len = quic_ack_frm_reduce_sz(&ack_frm, end - pos);
3669 if (!ack_frm_len)
3670 goto err;
3671
3672 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
3673 }
3674
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003675 if (ack_frm_len && !qc_build_frm(&pos, end, &ack_frm, pkt, conn)) {
3676 ssize_t room = end - pos;
3677 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3678 conn->conn, NULL, NULL, &room);
3679 goto err;
3680 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003681
3682 fake_len = ack_frm_len;
3683 if (!LIST_ISEMPTY(&qel->pktns->tx.frms) &&
Frédéric Lécailleea604992020-12-24 13:01:37 +01003684 !qc_build_cfrms(pkt, end - pos, &fake_len, pos - beg, qel, conn)) {
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003685 ssize_t room = end - pos;
3686 TRACE_PROTO("some CRYPTO frames could not be built",
3687 QUIC_EV_CONN_PAPKT, conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003688 goto err;
3689 }
3690
3691 /* Crypto frame */
3692 if (!LIST_ISEMPTY(&pkt->frms)) {
3693 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
3694 struct quic_crypto *crypto = &frm.crypto;
3695 struct quic_tx_frm *cf;
3696
3697 list_for_each_entry(cf, &pkt->frms, list) {
3698 crypto->offset = cf->crypto.offset;
3699 crypto->len = cf->crypto.len;
3700 crypto->qel = qel;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003701 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3702 ssize_t room = end - pos;
3703 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3704 conn->conn, NULL, NULL, &room);
3705 goto err;
3706 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003707 }
3708 }
3709
3710 /* Encode a maximum of frames. */
3711 list_for_each_entry_safe(frm, sfrm, &conn->tx.frms_to_send, list) {
3712 unsigned char *ppos;
3713
3714 ppos = pos;
3715 if (!qc_build_frm(&ppos, end, frm, pkt, conn)) {
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003716 TRACE_DEVEL("Frames not built", QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003717 break;
3718 }
3719
3720 LIST_DEL(&frm->list);
3721 LIST_ADDQ(&pkt->frms, &frm->list);
3722 pos = ppos;
3723 }
3724
3725 out:
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003726 TRACE_LEAVE(QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003727 return pos - beg;
3728
3729 err:
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003730 TRACE_DEVEL("leaving in error (buffer full)", QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003731 return -1;
3732}
3733
3734/* Prepare a post handhskake packet at Application encryption level for <conn>
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003735 * QUIC connection.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003736 * Return the length of this packet if succeeded, -1 if <wbuf> was full,
3737 * -2 in case of major error (encryption failure).
3738 */
3739static ssize_t qc_build_phdshk_apkt(struct q_buf *wbuf, struct quic_conn *qc)
3740{
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05003741 /* A pointer to the packet number field in <buf> */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003742 unsigned char *buf_pn;
3743 unsigned char *beg, *end, *payload;
3744 int64_t pn;
3745 size_t pn_len, aad_len, payload_len;
3746 ssize_t pkt_len;
3747 struct quic_tls_ctx *tls_ctx;
3748 struct quic_enc_level *qel;
3749 struct quic_tx_packet *pkt;
3750
3751 TRACE_ENTER(QUIC_EV_CONN_PAPKT, qc->conn);
3752 pkt = pool_alloc(pool_head_quic_tx_packet);
3753 if (!pkt) {
3754 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_PAPKT, qc->conn);
3755 return -2;
3756 }
3757
3758 quic_tx_packet_init(pkt);
3759 beg = q_buf_getpos(wbuf);
3760 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3761 pn_len = 0;
3762 buf_pn = NULL;
3763 pn = qel->pktns->tx.next_pn + 1;
3764 pkt_len = qc_do_build_phdshk_apkt(wbuf, pkt, pn, &pn_len, &buf_pn, qel, qc);
3765 if (pkt_len <= 0) {
3766 free_quic_tx_packet(pkt);
3767 return pkt_len;
3768 }
3769
3770 end = beg + pkt_len;
3771 payload = buf_pn + pn_len;
3772 payload_len = end - payload;
3773 aad_len = payload - beg;
3774
3775 tls_ctx = &qel->tls_ctx;
3776 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 +01003777 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003778
3779 end += QUIC_TLS_TAG_LEN;
3780 pkt_len += QUIC_TLS_TAG_LEN;
3781 if (!quic_apply_header_protection(beg, buf_pn, pn_len,
3782 tls_ctx->tx.hp, tls_ctx->tx.hp_key))
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003783 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003784
3785 q_buf_setpos(wbuf, end);
3786 /* Consume a packet number. */
3787 ++qel->pktns->tx.next_pn;
3788 /* Attach the built packet to its tree. */
3789 pkt->pn_node.key = qel->pktns->tx.next_pn;
3790 eb64_insert(&qel->pktns->tx.pkts, &pkt->pn_node);
3791 /* Set the packet in fligth length for in flight packet only. */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003792 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003793 pkt->in_flight_len = pkt_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003794 qc->path->prep_in_flight += pkt_len;
3795 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003796 pkt->pktns = qel->pktns;
3797 /* Increment the number of bytes in <buf> buffer by the length of this packet. */
3798 wbuf->data += pkt_len;
3799 /* Attach this packet to <buf>. */
3800 LIST_ADDQ(&wbuf->pkts, &pkt->list);
3801
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003802 TRACE_LEAVE(QUIC_EV_CONN_PAPKT, qc->conn, pkt);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003803
3804 return pkt_len;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003805
3806 err:
3807 free_quic_tx_packet(pkt);
3808 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PAPKT, qc->conn);
3809 return -2;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003810}
3811
3812/* Prepare a maximum of QUIC Application level packets from <ctx> QUIC
3813 * connection I/O handler context.
3814 * Returns 1 if succeeded, 0 if not.
3815 */
3816int qc_prep_phdshk_pkts(struct quic_conn *qc)
3817{
3818 struct q_buf *wbuf;
3819 struct quic_enc_level *qel;
3820
3821 TRACE_ENTER(QUIC_EV_CONN_PAPKTS, qc->conn);
3822 wbuf = q_wbuf(qc);
3823 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3824 while (q_buf_empty(wbuf)) {
3825 ssize_t ret;
3826
3827 if (!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3828 (LIST_ISEMPTY(&qel->pktns->tx.frms) ||
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003829 qc->path->prep_in_flight >= qc->path->cwnd)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003830 TRACE_DEVEL("nothing more to do",
3831 QUIC_EV_CONN_PAPKTS, qc->conn);
3832 break;
3833 }
3834
3835 ret = qc_build_phdshk_apkt(wbuf, qc);
3836 switch (ret) {
3837 case -1:
3838 /* Not enough room left in <wbuf>. */
3839 wbuf = q_next_wbuf(qc);
3840 continue;
3841 case -2:
3842 return 0;
3843 default:
3844 /* XXX TO CHECK: consume a buffer. */
3845 wbuf = q_next_wbuf(qc);
3846 continue;
3847 }
3848 }
3849 TRACE_LEAVE(QUIC_EV_CONN_PAPKTS, qc->conn);
3850
3851 return 1;
3852}
3853
3854/* QUIC connection packet handler task. */
Willy Tarreau691d5032021-01-20 14:55:01 +01003855struct task *quic_conn_io_cb(struct task *t, void *context, unsigned short state)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003856{
3857 struct quic_conn_ctx *ctx = context;
3858
3859 if (ctx->state < QUIC_HS_ST_COMPLETE) {
3860 qc_do_hdshk(ctx);
3861 }
3862 else {
3863 struct quic_conn *qc = ctx->conn->qc;
3864
3865 /* XXX TO DO: may fail!!! XXX */
3866 qc_treat_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_APP], ctx);
3867 qc_prep_phdshk_pkts(qc);
3868 qc_send_ppkts(ctx);
3869 }
3870
3871 return NULL;
3872}
3873
3874/* Receive up to <count> bytes from connection <conn>'s socket and store them
3875 * into buffer <buf>. Only one call to recv() is performed, unless the
3876 * buffer wraps, in which case a second call may be performed. The connection's
3877 * flags are updated with whatever special event is detected (error, read0,
3878 * empty). The caller is responsible for taking care of those events and
3879 * avoiding the call if inappropriate. The function does not call the
3880 * connection's polling update function, so the caller is responsible for this.
3881 * errno is cleared before starting so that the caller knows that if it spots an
3882 * error without errno, it's pending and can be retrieved via getsockopt(SO_ERROR).
3883 */
3884static size_t quic_conn_to_buf(struct connection *conn, void *xprt_ctx, struct buffer *buf, size_t count, int flags)
3885{
3886 ssize_t ret;
3887 size_t try, done = 0;
3888
3889 if (!conn_ctrl_ready(conn))
3890 return 0;
3891
3892 if (!fd_recv_ready(conn->handle.fd))
3893 return 0;
3894
3895 conn->flags &= ~CO_FL_WAIT_ROOM;
3896 errno = 0;
3897
3898 if (unlikely(!(fdtab[conn->handle.fd].ev & FD_POLL_IN))) {
3899 /* stop here if we reached the end of data */
3900 if ((fdtab[conn->handle.fd].ev & (FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_HUP)
3901 goto read0;
3902
3903 /* report error on POLL_ERR before connection establishment */
3904 if ((fdtab[conn->handle.fd].ev & FD_POLL_ERR) && (conn->flags & CO_FL_WAIT_L4_CONN)) {
3905 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3906 goto leave;
3907 }
3908 }
3909
3910 /* read the largest possible block. For this, we perform only one call
3911 * to recv() unless the buffer wraps and we exactly fill the first hunk,
3912 * in which case we accept to do it once again. A new attempt is made on
3913 * EINTR too.
3914 */
3915 while (count > 0) {
3916 try = b_contig_space(buf);
3917 if (!try)
3918 break;
3919
3920 if (try > count)
3921 try = count;
3922
3923 ret = recvfrom(conn->handle.fd, b_tail(buf), try, 0, NULL, 0);
3924
3925 if (ret > 0) {
3926 b_add(buf, ret);
3927 done += ret;
3928 if (ret < try) {
3929 /* unfortunately, on level-triggered events, POLL_HUP
3930 * is generally delivered AFTER the system buffer is
3931 * empty, unless the poller supports POLL_RDHUP. If
3932 * we know this is the case, we don't try to read more
3933 * as we know there's no more available. Similarly, if
3934 * there's no problem with lingering we don't even try
3935 * to read an unlikely close from the client since we'll
3936 * close first anyway.
3937 */
3938 if (fdtab[conn->handle.fd].ev & FD_POLL_HUP)
3939 goto read0;
3940
3941 if ((!fdtab[conn->handle.fd].linger_risk) ||
3942 (cur_poller.flags & HAP_POLL_F_RDHUP)) {
3943 break;
3944 }
3945 }
3946 count -= ret;
3947 }
3948 else if (ret == 0) {
3949 goto read0;
3950 }
3951 else if (errno == EAGAIN || errno == ENOTCONN) {
3952 fd_cant_recv(conn->handle.fd);
3953 break;
3954 }
3955 else if (errno != EINTR) {
3956 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3957 break;
3958 }
3959 }
3960
3961 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) && done)
3962 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3963
3964 leave:
3965 return done;
3966
3967 read0:
3968 conn_sock_read0(conn);
3969 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3970
3971 /* Now a final check for a possible asynchronous low-level error
3972 * report. This can happen when a connection receives a reset
3973 * after a shutdown, both POLL_HUP and POLL_ERR are queued, and
3974 * we might have come from there by just checking POLL_HUP instead
3975 * of recv()'s return value 0, so we have no way to tell there was
3976 * an error without checking.
3977 */
3978 if (unlikely(fdtab[conn->handle.fd].ev & FD_POLL_ERR))
3979 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3980 goto leave;
3981}
3982
3983
3984/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
3985 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
3986 * other pending data for example, but this flag is ignored at the moment.
3987 * Only one call to send() is performed, unless the buffer wraps, in which case
3988 * a second call may be performed. The connection's flags are updated with
3989 * whatever special event is detected (error, empty). The caller is responsible
3990 * for taking care of those events and avoiding the call if inappropriate. The
3991 * function does not call the connection's polling update function, so the caller
3992 * is responsible for this. It's up to the caller to update the buffer's contents
3993 * based on the return value.
3994 */
3995static size_t quic_conn_from_buf(struct connection *conn, void *xprt_ctx, const struct buffer *buf, size_t count, int flags)
3996{
3997 ssize_t ret;
3998 size_t try, done;
3999 int send_flag;
4000
4001 if (!conn_ctrl_ready(conn))
4002 return 0;
4003
4004 if (!fd_send_ready(conn->handle.fd))
4005 return 0;
4006
4007 done = 0;
4008 /* send the largest possible block. For this we perform only one call
4009 * to send() unless the buffer wraps and we exactly fill the first hunk,
4010 * in which case we accept to do it once again.
4011 */
4012 while (count) {
4013 try = b_contig_data(buf, done);
4014 if (try > count)
4015 try = count;
4016
4017 send_flag = MSG_DONTWAIT | MSG_NOSIGNAL;
4018 if (try < count || flags & CO_SFL_MSG_MORE)
4019 send_flag |= MSG_MORE;
4020
4021 ret = sendto(conn->handle.fd, b_peek(buf, done), try, send_flag,
4022 (struct sockaddr *)conn->dst, get_addr_len(conn->dst));
4023 if (ret > 0) {
4024 count -= ret;
4025 done += ret;
4026
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05004027 /* A send succeeded, so we can consider ourself connected */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004028 conn->flags |= CO_FL_WAIT_L4L6;
4029 /* if the system buffer is full, don't insist */
4030 if (ret < try)
4031 break;
4032 }
4033 else if (ret == 0 || errno == EAGAIN || errno == ENOTCONN || errno == EINPROGRESS) {
4034 /* nothing written, we need to poll for write first */
4035 fd_cant_send(conn->handle.fd);
4036 break;
4037 }
4038 else if (errno != EINTR) {
4039 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
4040 break;
4041 }
4042 }
4043 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) && done)
4044 conn->flags &= ~CO_FL_WAIT_L4_CONN;
4045
4046 if (done > 0) {
4047 /* we count the total bytes sent, and the send rate for 32-byte
4048 * blocks. The reason for the latter is that freq_ctr are
4049 * limited to 4GB and that it's not enough per second.
4050 */
4051 _HA_ATOMIC_ADD(&global.out_bytes, done);
4052 update_freq_ctr(&global.out_32bps, (done + 16) / 32);
4053 }
4054 return done;
4055}
4056
4057/* Initialize a QUIC connection (quic_conn struct) to be attached to <conn>
4058 * connection with <xprt_ctx> as address of the xprt context.
4059 * Returns 1 if succeeded, 0 if not.
4060 */
4061static int qc_conn_init(struct connection *conn, void **xprt_ctx)
4062{
4063 struct quic_conn_ctx *ctx;
4064
4065 TRACE_ENTER(QUIC_EV_CONN_NEW, conn);
4066
4067 if (*xprt_ctx)
4068 goto out;
4069
4070 if (!conn_ctrl_ready(conn))
4071 goto out;
4072
4073 ctx = pool_alloc(pool_head_quic_conn_ctx);
4074 if (!ctx) {
4075 conn->err_code = CO_ER_SYS_MEMLIM;
4076 goto err;
4077 }
4078
4079 ctx->wait_event.tasklet = tasklet_new();
4080 if (!ctx->wait_event.tasklet) {
4081 conn->err_code = CO_ER_SYS_MEMLIM;
4082 goto err;
4083 }
4084
4085 ctx->wait_event.tasklet->process = quic_conn_io_cb;
4086 ctx->wait_event.tasklet->context = ctx;
4087 ctx->wait_event.events = 0;
4088 ctx->conn = conn;
4089 ctx->subs = NULL;
4090 ctx->xprt_ctx = NULL;
4091
4092 ctx->xprt = xprt_get(XPRT_QUIC);
4093 if (objt_server(conn->target)) {
4094 /* Server */
4095 struct server *srv = __objt_server(conn->target);
4096 unsigned char dcid[QUIC_CID_LEN];
4097 struct quic_conn *quic_conn;
4098 int ssl_err, ipv4;
4099
4100 ssl_err = SSL_ERROR_NONE;
4101 if (RAND_bytes(dcid, sizeof dcid) != 1)
4102 goto err;
4103
4104 conn->qc = new_quic_conn(QUIC_PROTOCOL_VERSION_DRAFT_28);
4105 if (!conn->qc)
4106 goto err;
4107
4108 quic_conn = conn->qc;
4109 quic_conn->conn = conn;
4110 ipv4 = conn->dst->ss_family == AF_INET;
4111 if (!qc_new_conn_init(quic_conn, ipv4, NULL, &srv->cids,
4112 dcid, sizeof dcid, NULL, 0))
4113 goto err;
4114
4115 if (!qc_new_isecs(conn, dcid, sizeof dcid, 0))
4116 goto err;
4117
4118 ctx->state = QUIC_HS_ST_CLIENT_INITIAL;
4119 if (ssl_bio_and_sess_init(conn, srv->ssl_ctx.ctx,
4120 &ctx->ssl, &ctx->bio, ha_quic_meth, ctx) == -1)
4121 goto err;
4122
4123 quic_conn->params = srv->quic_params;
4124 /* Copy the initial source connection ID. */
4125 quic_cid_cpy(&quic_conn->params.initial_source_connection_id, &quic_conn->scid);
4126 quic_conn->enc_params_len =
4127 quic_transport_params_encode(quic_conn->enc_params,
4128 quic_conn->enc_params + sizeof quic_conn->enc_params,
4129 &quic_conn->params, 0);
4130 if (!quic_conn->enc_params_len)
4131 goto err;
4132
4133 SSL_set_quic_transport_params(ctx->ssl, quic_conn->enc_params, quic_conn->enc_params_len);
4134 SSL_set_connect_state(ctx->ssl);
4135 ssl_err = SSL_do_handshake(ctx->ssl);
4136 if (ssl_err != 1) {
4137 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
4138 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
4139 TRACE_PROTO("SSL handshake",
4140 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
4141 }
4142 else {
4143 TRACE_DEVEL("SSL handshake error",
4144 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
4145 goto err;
4146 }
4147 }
4148 }
4149 else if (objt_listener(conn->target)) {
4150 /* Listener */
4151 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
4152
4153 ctx->state = QUIC_HS_ST_SERVER_INITIAL;
4154
4155 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
4156 &ctx->ssl, &ctx->bio, ha_quic_meth, ctx) == -1)
4157 goto err;
4158
4159 SSL_set_accept_state(ctx->ssl);
4160 }
4161
4162 *xprt_ctx = ctx;
4163
4164 /* Leave init state and start handshake */
4165 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
4166 /* Start the handshake */
4167 tasklet_wakeup(ctx->wait_event.tasklet);
4168
4169 out:
4170 TRACE_LEAVE(QUIC_EV_CONN_NEW, conn);
4171
4172 return 0;
4173
4174 err:
4175 if (ctx->wait_event.tasklet)
4176 tasklet_free(ctx->wait_event.tasklet);
4177 pool_free(pool_head_quic_conn_ctx, ctx);
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01004178 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_NEW, conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004179 return -1;
4180}
4181
4182/* transport-layer operations for QUIC connections. */
4183static struct xprt_ops ssl_quic = {
4184 .snd_buf = quic_conn_from_buf,
4185 .rcv_buf = quic_conn_to_buf,
4186 .init = qc_conn_init,
4187 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
4188 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
4189 .name = "QUIC",
4190};
4191
4192__attribute__((constructor))
4193static void __quic_conn_init(void)
4194{
4195 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
4196 xprt_register(XPRT_QUIC, &ssl_quic);
4197}
4198
4199__attribute__((destructor))
4200static void __quic_conn_deinit(void)
4201{
4202 BIO_meth_free(ha_quic_meth);
4203}
4204
4205/* Read all the QUIC packets found in <buf> with <len> as length (typically a UDP
4206 * datagram), <ctx> being the QUIC I/O handler context, from QUIC connections,
4207 * calling <func> function;
Ilya Shipitsin1e9a6662021-01-05 22:10:46 +05004208 * Return the number of bytes read if succeeded, -1 if not.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004209 */
4210static ssize_t quic_dgram_read(char *buf, size_t len, void *owner,
4211 struct sockaddr_storage *saddr, qpkt_read_func *func)
4212{
4213 unsigned char *pos;
4214 const unsigned char *end;
4215 struct quic_dgram_ctx dgram_ctx = {
4216 .dcid_node = NULL,
4217 .owner = owner,
4218 };
4219
4220 pos = (unsigned char *)buf;
4221 end = pos + len;
4222
4223 do {
4224 int ret;
4225 struct quic_rx_packet *pkt;
4226
4227 pkt = pool_alloc(pool_head_quic_rx_packet);
4228 if (!pkt)
4229 goto err;
4230
4231 memset(pkt, 0, sizeof(*pkt));
4232 quic_rx_packet_refinc(pkt);
4233 ret = func(&pos, end, pkt, &dgram_ctx, saddr);
4234 if (ret == -1) {
4235 size_t pkt_len;
4236
4237 pkt_len = pkt->len;
4238 free_quic_rx_packet(pkt);
4239 /* If the packet length could not be found, we cannot continue. */
4240 if (!pkt_len)
4241 break;
4242 }
4243 } while (pos < end);
4244
4245 /* Increasing the received bytes counter by the UDP datagram length
4246 * if this datagram could be associated to a connection.
4247 */
4248 if (dgram_ctx.qc)
4249 dgram_ctx.qc->rx.bytes += len;
4250
4251 return pos - (unsigned char *)buf;
4252
4253 err:
4254 return -1;
4255}
4256
4257ssize_t quic_lstnr_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_lstnr_pkt_rcv);
4261}
4262
4263ssize_t quic_srv_dgram_read(char *buf, size_t len, void *owner,
4264 struct sockaddr_storage *saddr)
4265{
4266 return quic_dgram_read(buf, len, owner, saddr, qc_srv_pkt_rcv);
4267}
4268
4269/* QUIC I/O handler for connection to local listeners or remove servers
4270 * depending on <listener> boolean value, with <fd> as socket file
4271 * descriptor and <ctx> as context.
4272 */
4273static size_t quic_conn_handler(int fd, void *ctx, qpkt_read_func *func)
4274{
4275 ssize_t ret;
4276 size_t done = 0;
4277 struct buffer *buf = get_trash_chunk();
4278 /* Source address */
4279 struct sockaddr_storage saddr = {0};
4280 socklen_t saddrlen = sizeof saddr;
4281
4282 if (!fd_recv_ready(fd))
4283 return 0;
4284
4285 do {
4286 ret = recvfrom(fd, buf->area, buf->size, 0,
4287 (struct sockaddr *)&saddr, &saddrlen);
4288 if (ret < 0) {
4289 if (errno == EINTR)
4290 continue;
4291 if (errno == EAGAIN)
4292 fd_cant_recv(fd);
4293 goto out;
4294 }
4295 } while (0);
4296
4297 done = buf->data = ret;
4298 quic_dgram_read(buf->area, buf->data, ctx, &saddr, func);
4299
4300 out:
4301 return done;
4302}
4303
4304/* QUIC I/O handler for connections to local listeners with <fd> as socket
4305 * file descriptor.
4306 */
4307void quic_fd_handler(int fd)
4308{
4309 if (fdtab[fd].ev & FD_POLL_IN)
4310 quic_conn_handler(fd, fdtab[fd].owner, &qc_lstnr_pkt_rcv);
4311}
4312
4313/* QUIC I/O handler for connections to remote servers with <fd> as socket
4314 * file descriptor.
4315 */
4316void quic_conn_fd_handler(int fd)
4317{
4318 if (fdtab[fd].ev & FD_POLL_IN)
4319 quic_conn_handler(fd, fdtab[fd].owner, &qc_srv_pkt_rcv);
4320}
4321
4322/*
4323 * Local variables:
4324 * c-indent-level: 8
4325 * c-basic-offset: 8
4326 * End:
4327 */