blob: c20d877c3930bc04491bd16f5f3ee419caf2ec7c [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" },
Frédéric Lécaillef63921f2020-12-18 09:48:20 +010070 { .mask = QUIC_EV_CONN_ENCPKT, .name = "enc_hdshk_pkt", .desc = "handhshake packet encrytion" },
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.
706 * Returns 1 if succedded, 0 if not.
707 */
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.
754 * Returns 1 if succedded, 0 if not.
755 */
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.
1384 * if the largest acked packet was newly acked and if there was at leas one newly
1385 * 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.
1501 * Remaining parameter are there for debuging purposes.
1502 * 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);
1874 frm->type = QUIC_FT_HANDSHAKE_DONE;
1875 LIST_ADDQ(&conn->tx.frms_to_send, &frm->list);
1876 }
1877
1878 for (i = 1; i < conn->rx_tps.active_connection_id_limit; i++) {
1879 struct quic_connection_id *cid;
1880
1881 frm = pool_alloc(pool_head_quic_frame);
1882 memset(frm, 0, sizeof *frm);
1883 cid = new_quic_cid(&conn->cids, i);
1884 if (!frm || !cid)
1885 goto err;
1886
1887 quic_connection_id_to_frm_cpy(frm, cid);
1888 LIST_ADDQ(&conn->tx.frms_to_send, &frm->list);
1889 }
1890
1891 return 1;
1892
1893 err:
1894 free_quic_conn_cids(conn);
1895 return 0;
1896}
1897
1898/* Deallocate <l> list of ACK ranges. */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001899void free_quic_arngs(struct quic_arngs *arngs)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001900{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001901 struct eb64_node *n;
1902 struct quic_arng_node *ar;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001903
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001904 n = eb64_first(&arngs->root);
1905 while (n) {
1906 struct eb64_node *next;
1907
1908 ar = eb64_entry(&n->node, struct quic_arng_node, first);
1909 next = eb64_next(n);
1910 eb64_delete(n);
1911 free(ar);
1912 n = next;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001913 }
1914}
1915
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001916/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
1917 * descending order.
1918 */
1919static inline size_t sack_gap(struct quic_arng_node *p,
1920 struct quic_arng_node *q)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001921{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001922 return p->first.key - q->last - 2;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001923}
1924
1925
1926/* Remove the last elements of <ack_ranges> list of ack range updating its
1927 * encoded size until it goes below <limit>.
1928 * Returns 1 if succeded, 0 if not (no more element to remove).
1929 */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001930static int quic_rm_last_ack_ranges(struct quic_arngs *arngs, size_t limit)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001931{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001932 struct eb64_node *last, *prev;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001933
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001934 last = eb64_last(&arngs->root);
1935 while (last && arngs->enc_sz > limit) {
1936 struct quic_arng_node *last_node, *prev_node;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001937
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001938 prev = eb64_prev(last);
1939 if (!prev)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001940 return 0;
1941
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001942 last_node = eb64_entry(&last->node, struct quic_arng_node, first);
1943 prev_node = eb64_entry(&prev->node, struct quic_arng_node, first);
1944 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
1945 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
1946 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
1947 --arngs->sz;
1948 eb64_delete(last);
1949 pool_free(pool_head_quic_arng, last);
1950 last = prev;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001951 }
1952
1953 return 1;
1954}
1955
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001956/* Set the encoded size of <arngs> QUIC ack ranges. */
1957static void quic_arngs_set_enc_sz(struct quic_arngs *arngs)
1958{
1959 struct eb64_node *node, *next;
1960 struct quic_arng_node *ar, *ar_next;
1961
1962 node = eb64_last(&arngs->root);
1963 if (!node)
1964 return;
1965
1966 ar = eb64_entry(&node->node, struct quic_arng_node, first);
1967 arngs->enc_sz = quic_int_getsize(ar->last) +
1968 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
1969
1970 while ((next = eb64_prev(node))) {
1971 ar_next = eb64_entry(&next->node, struct quic_arng_node, first);
1972 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
1973 quic_int_getsize(ar_next->last - ar_next->first.key);
1974 node = next;
1975 ar = eb64_entry(&node->node, struct quic_arng_node, first);
1976 }
1977}
1978
1979/* Insert in <root> ebtree <node> node with <ar> as range value.
1980 * Returns the ebtree node which has been inserted.
1981 */
1982static inline
1983struct eb64_node *quic_insert_new_range(struct eb_root *root,
1984 struct quic_arng_node *node,
1985 struct quic_arng *ar)
1986{
1987 node->first.key = ar->first;
1988 node->last = ar->last;
1989 return eb64_insert(root, &node->first);
1990}
1991
1992/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001993 * Note that this function computes the number of bytes required to encode
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001994 * this tree of ACK ranges in descending order.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001995 *
1996 * Descending order
1997 * ------------->
1998 * range1 range2
1999 * ..........|--------|..............|--------|
2000 * ^ ^ ^ ^
2001 * | | | |
2002 * last1 first1 last2 first2
2003 * ..........+--------+--------------+--------+......
2004 * diff1 gap12 diff2
2005 *
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002006 * To encode the previous list of ranges we must encode integers as follows in
2007 * descending order:
2008 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002009 * with diff1 = last1 - first1
2010 * diff2 = last2 - first2
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002011 * gap12 = first1 - last2 - 2 (>= 0)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002012 *
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002013 */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002014int quic_update_ack_ranges_list(struct quic_arngs *arngs,
2015 struct quic_arng *ar)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002016{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002017 struct eb64_node *le;
2018 struct quic_arng_node *new_node;
2019 struct eb64_node *new;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002020
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002021 new = NULL;
2022 if (eb_is_empty(&arngs->root)) {
2023 /* First range insertion. */
2024 new_node = pool_alloc(pool_head_quic_arng);
2025 if (!new_node)
2026 return 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002027
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002028 quic_insert_new_range(&arngs->root, new_node, ar);
2029 /* Increment the size of these ranges. */
2030 arngs->sz++;
2031 goto out;
2032 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002033
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002034 le = eb64_lookup_le(&arngs->root, ar->first);
2035 if (!le) {
2036 /* New insertion */
2037 new_node = pool_alloc(pool_head_quic_arng);
2038 if (!new_node)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002039 return 0;
2040
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002041 new = quic_insert_new_range(&arngs->root, new_node, ar);
2042 /* Increment the size of these ranges. */
2043 arngs->sz++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002044 }
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002045 else {
2046 struct quic_arng_node *le_ar =
2047 eb64_entry(&le->node, struct quic_arng_node, first);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002048
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002049 /* Already existing range */
2050 if (le_ar->first.key <= ar->first && le_ar->last >= ar->last)
2051 return 1;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002052
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002053 if (le_ar->last + 1 >= ar->first) {
2054 le_ar->last = ar->last;
2055 new = le;
2056 new_node = le_ar;
2057 }
2058 else {
2059 /* New insertion */
2060 new_node = pool_alloc(pool_head_quic_arng);
2061 if (!new_node)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002062 return 0;
2063
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002064 new = quic_insert_new_range(&arngs->root, new_node, ar);
2065 /* Increment the size of these ranges. */
2066 arngs->sz++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002067 }
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002068 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002069
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002070 /* Verify that the new inserted node does not overlap the nodes
2071 * which follow it.
2072 */
2073 if (new) {
2074 uint64_t new_node_last;
2075 struct eb64_node *next;
2076 struct quic_arng_node *next_node;
2077
2078 new_node_last = new_node->last;
2079 while ((next = eb64_next(new))) {
2080 next_node =
2081 eb64_entry(&next->node, struct quic_arng_node, first);
2082 if (new_node_last + 1 < next_node->first.key)
2083 break;
2084
2085 if (next_node->last > new_node->last)
2086 new_node->last = next_node->last;
2087 eb64_delete(next);
2088 free(next_node);
2089 /* Decrement the size of these ranges. */
2090 arngs->sz--;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002091 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002092 }
2093
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002094 quic_arngs_set_enc_sz(arngs);
2095
2096 out:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002097 return 1;
2098}
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002099/* Remove the header protection of packets at <el> encryption level.
2100 * Always succeeds.
2101 */
2102static inline void qc_rm_hp_pkts(struct quic_enc_level *el, struct quic_conn_ctx *ctx)
2103{
2104 struct quic_tls_ctx *tls_ctx;
2105 struct quic_rx_packet *pqpkt, *qqpkt;
2106 struct quic_enc_level *app_qel;
2107
2108 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, ctx->conn);
2109 app_qel = &ctx->conn->qc->els[QUIC_TLS_ENC_LEVEL_APP];
2110 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
2111 if (el == app_qel && objt_listener(ctx->conn->target) && ctx->state < QUIC_HS_ST_COMPLETE) {
2112 TRACE_PROTO("hp not removed (handshake not completed)",
2113 QUIC_EV_CONN_ELRMHP, ctx->conn);
2114 goto out;
2115 }
2116 tls_ctx = &el->tls_ctx;
2117 list_for_each_entry_safe(pqpkt, qqpkt, &el->rx.pqpkts, list) {
2118 if (!qc_do_rm_hp(pqpkt, tls_ctx, el->pktns->rx.largest_pn,
2119 pqpkt->data + pqpkt->pn_offset,
2120 pqpkt->data, pqpkt->data + pqpkt->len, ctx)) {
2121 TRACE_PROTO("hp removing error", QUIC_EV_CONN_ELRMHP, ctx->conn);
2122 /* XXX TO DO XXX */
2123 }
2124 else {
2125 /* The AAD includes the packet number field */
2126 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
2127 /* Store the packet into the tree of packets to decrypt. */
2128 pqpkt->pn_node.key = pqpkt->pn;
2129 quic_rx_packet_eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
2130 TRACE_PROTO("hp removed", QUIC_EV_CONN_ELRMHP, ctx->conn, pqpkt);
2131 }
2132 quic_rx_packet_list_del(pqpkt);
2133 }
2134
2135 out:
2136 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, ctx->conn);
2137}
2138
2139/* Process all the CRYPTO frame at <el> encryption level.
2140 * Return 1 if succeeded, 0 if not.
2141 */
2142static inline int qc_treat_rx_crypto_frms(struct quic_enc_level *el,
2143 struct quic_conn_ctx *ctx)
2144{
2145 struct eb64_node *node;
2146
2147 TRACE_ENTER(QUIC_EV_CONN_RXCDATA, ctx->conn);
2148 node = eb64_first(&el->rx.crypto.frms);
2149 while (node) {
2150 struct quic_rx_crypto_frm *cf;
2151
2152 cf = eb64_entry(&node->node, struct quic_rx_crypto_frm, offset_node);
2153 if (cf->offset_node.key != el->rx.crypto.offset)
2154 break;
2155
2156 if (!qc_provide_cdata(el, ctx, cf->data, cf->len, cf->pkt, cf))
2157 goto err;
2158
2159 node = eb64_next(node);
2160 quic_rx_packet_refdec(cf->pkt);
2161 eb64_delete(&cf->offset_node);
2162 pool_free(pool_head_quic_rx_crypto_frm, cf);
2163 }
2164
2165 TRACE_LEAVE(QUIC_EV_CONN_RXCDATA, ctx->conn);
2166 return 1;
2167
2168 err:
2169 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_RXCDATA, ctx->conn);
2170 return 0;
2171}
2172
2173/* Process all the packets at <el> encryption level.
2174 * Return 1 if succeeded, 0 if not.
2175 */
2176int qc_treat_rx_pkts(struct quic_enc_level *el, struct quic_conn_ctx *ctx)
2177{
2178 struct quic_tls_ctx *tls_ctx;
2179 struct eb64_node *node;
2180
2181 TRACE_ENTER(QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2182 tls_ctx = &el->tls_ctx;
2183 node = eb64_first(&el->rx.pkts);
2184 while (node) {
2185 struct quic_rx_packet *pkt;
2186
2187 pkt = eb64_entry(&node->node, struct quic_rx_packet, pn_node);
2188 if (!qc_pkt_decrypt(pkt, tls_ctx)) {
2189 /* Drop the packet */
2190 TRACE_PROTO("packet decryption failed -> dropped",
2191 QUIC_EV_CONN_ELRXPKTS, ctx->conn, pkt);
2192 }
2193 else {
2194 int drop;
2195
2196 drop = 0;
2197 if (!qc_parse_pkt_frms(pkt, ctx, el))
2198 drop = 1;
2199
2200 if (drop) {
2201 /* Drop the packet */
2202 TRACE_PROTO("packet parsing failed -> dropped",
2203 QUIC_EV_CONN_ELRXPKTS, ctx->conn, pkt);
2204 }
2205 else {
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002206 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
2207
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002208 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING) {
2209 el->pktns->rx.nb_ack_eliciting++;
2210 if (!(el->pktns->rx.nb_ack_eliciting & 1))
2211 el->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
2212 }
2213
2214 /* Update the largest packet number. */
2215 if (pkt->pn > el->pktns->rx.largest_pn)
2216 el->pktns->rx.largest_pn = pkt->pn;
2217
2218 /* Update the list of ranges to acknowledge. */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002219 if (!quic_update_ack_ranges_list(&el->pktns->rx.arngs, &ar)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002220 TRACE_DEVEL("Could not update ack range list",
2221 QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2222 node = eb64_next(node);
2223 quic_rx_packet_eb64_delete(&pkt->pn_node);
2224 free_quic_rx_packet(pkt);
2225 goto err;
2226 }
2227
2228 }
2229 }
2230 node = eb64_next(node);
2231 quic_rx_packet_eb64_delete(&pkt->pn_node);
2232 free_quic_rx_packet(pkt);
2233 }
2234
2235 if (!qc_treat_rx_crypto_frms(el, ctx))
2236 goto err;
2237
2238 TRACE_LEAVE(QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2239 return 1;
2240
2241 err:
2242 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2243 return 0;
2244}
2245
2246/* Called during handshakes to parse and build Initial and Handshake packets for QUIC
2247 * connections with <ctx> as I/O handler context.
2248 * Returns 1 if succeeded, 0 if not.
2249 */
2250int qc_do_hdshk(struct quic_conn_ctx *ctx)
2251{
2252 int ssl_err;
2253 struct quic_conn *quic_conn;
2254 enum quic_tls_enc_level tel, next_tel;
2255 struct quic_enc_level *qel, *next_qel;
2256 struct quic_tls_ctx *tls_ctx;
2257
2258 TRACE_ENTER(QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
2259
2260 ssl_err = SSL_ERROR_NONE;
2261 quic_conn = ctx->conn->qc;
2262 if (!quic_get_tls_enc_levels(&tel, &next_tel, ctx->state))
2263 goto err;
2264
2265 qel = &quic_conn->els[tel];
2266 next_qel = &quic_conn->els[next_tel];
2267
2268 next_level:
2269 tls_ctx = &qel->tls_ctx;
2270
2271 /* If the header protection key for this level has been derived,
2272 * remove the packet header protections.
2273 */
2274 if (!LIST_ISEMPTY(&qel->rx.pqpkts) &&
2275 (tls_ctx->rx.flags & QUIC_FL_TLS_SECRETS_SET))
2276 qc_rm_hp_pkts(qel, ctx);
2277
2278 if (!eb_is_empty(&qel->rx.pkts) &&
2279 !qc_treat_rx_pkts(qel, ctx))
2280 goto err;
2281
2282 if (!qc_prep_hdshk_pkts(ctx))
2283 goto err;
2284
2285 if (!qc_send_ppkts(ctx))
2286 goto err;
2287
2288 /* Check if there is something to do for the next level.
2289 */
2290 if ((next_qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_SET) &&
2291 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || !eb_is_empty(&next_qel->rx.pkts))) {
2292 qel = next_qel;
2293 goto next_level;
2294 }
2295
2296 /* If the handshake has not been completed -> out! */
2297 if (ctx->state < QUIC_HS_ST_COMPLETE)
2298 goto out;
2299
2300 /* Discard the Handshake keys. */
2301 quic_tls_discard_keys(&quic_conn->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
2302 quic_pktns_discard(quic_conn->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, quic_conn);
2303 qc_set_timer(ctx);
2304 if (!quic_build_post_handshake_frames(quic_conn) ||
2305 !qc_prep_phdshk_pkts(quic_conn) ||
2306 !qc_send_ppkts(ctx))
2307 goto err;
2308
2309 out:
2310 TRACE_LEAVE(QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
2311 return 1;
2312
2313 err:
2314 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
2315 return 0;
2316}
2317
2318/* Allocate a new QUIC connection and return it if succeeded, NULL if not. */
2319struct quic_conn *new_quic_conn(uint32_t version)
2320{
2321 struct quic_conn *quic_conn;
2322
2323 quic_conn = pool_alloc(pool_head_quic_conn);
2324 if (quic_conn) {
2325 memset(quic_conn, 0, sizeof *quic_conn);
2326 quic_conn->version = version;
2327 }
2328
2329 return quic_conn;
2330}
2331
2332/* Unitialize <qel> QUIC encryption level. Never fails. */
2333static void quic_conn_enc_level_uninit(struct quic_enc_level *qel)
2334{
2335 int i;
2336
2337 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
2338 if (qel->tx.crypto.bufs[i]) {
2339 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
2340 qel->tx.crypto.bufs[i] = NULL;
2341 }
2342 }
2343 free(qel->tx.crypto.bufs);
2344 qel->tx.crypto.bufs = NULL;
2345}
2346
2347/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
2348 * connetion allocating everything needed.
2349 * Returns 1 if succeeded, 0 if not.
2350 */
2351static int quic_conn_enc_level_init(struct quic_conn *qc,
2352 enum quic_tls_enc_level level)
2353{
2354 struct quic_enc_level *qel;
2355
2356 qel = &qc->els[level];
2357 qel->level = quic_to_ssl_enc_level(level);
2358 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
2359 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
2360 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
2361 qel->tls_ctx.rx.flags = 0;
2362 qel->tls_ctx.tx.flags = 0;
2363
2364 qel->rx.pkts = EB_ROOT;
2365 LIST_INIT(&qel->rx.pqpkts);
2366
2367 /* Allocate only one buffer. */
2368 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
2369 if (!qel->tx.crypto.bufs)
2370 goto err;
2371
2372 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
2373 if (!qel->tx.crypto.bufs[0])
2374 goto err;
2375
2376 qel->tx.crypto.bufs[0]->sz = 0;
2377 qel->tx.crypto.nb_buf = 1;
2378
2379 qel->tx.crypto.sz = 0;
2380 qel->tx.crypto.offset = 0;
2381
2382 return 1;
2383
2384 err:
2385 free(qel->tx.crypto.bufs);
2386 qel->tx.crypto.bufs = NULL;
2387 return 0;
2388}
2389
2390/* Release the memory allocated for <buf> array of buffers, with <nb> as size.
2391 * Never fails.
2392 */
2393static inline void free_quic_conn_tx_bufs(struct q_buf **bufs, size_t nb)
2394{
2395 struct q_buf **p;
2396
2397 if (!bufs)
2398 return;
2399
2400 p = bufs;
2401 while (--nb) {
2402 if (!*p) {
2403 p++;
2404 continue;
2405 }
2406 free((*p)->area);
2407 (*p)->area = NULL;
2408 free(*p);
2409 *p = NULL;
2410 p++;
2411 }
2412 free(bufs);
2413}
2414
2415/* Allocate an array or <nb> buffers of <sz> bytes each.
2416 * Return this array if succeeded, NULL if failed.
2417 */
2418static inline struct q_buf **quic_conn_tx_bufs_alloc(size_t nb, size_t sz)
2419{
2420 int i;
2421 struct q_buf **bufs, **p;
2422
2423 bufs = calloc(nb, sizeof *bufs);
2424 if (!bufs)
2425 return NULL;
2426
2427 i = 0;
2428 p = bufs;
2429 while (i++ < nb) {
2430 *p = calloc(1, sizeof **p);
2431 if (!*p)
2432 goto err;
2433
2434 (*p)->area = malloc(sz);
2435 if (!(*p)->area)
2436 goto err;
2437
2438 (*p)->pos = (*p)->area;
2439 (*p)->end = (*p)->area + sz;
2440 (*p)->data = 0;
2441 LIST_INIT(&(*p)->pkts);
2442 p++;
2443 }
2444
2445 return bufs;
2446
2447 err:
2448 free_quic_conn_tx_bufs(bufs, nb);
2449 return NULL;
2450}
2451
2452/* Release all the memory allocated for <conn> QUIC connection. */
2453static void quic_conn_free(struct quic_conn *conn)
2454{
2455 int i;
2456
2457 free_quic_conn_cids(conn);
2458 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++)
2459 quic_conn_enc_level_uninit(&conn->els[i]);
2460 free_quic_conn_tx_bufs(conn->tx.bufs, conn->tx.nb_buf);
2461 if (conn->timer_task)
2462 task_destroy(conn->timer_task);
2463 pool_free(pool_head_quic_conn, conn);
2464}
2465
2466/* Callback called upon loss detection and PTO timer expirations. */
2467static struct task *process_timer(struct task *task, void *ctx, unsigned short state)
2468{
2469 struct quic_conn_ctx *conn_ctx;
2470 struct quic_conn *qc;
2471 struct quic_pktns *pktns;
2472
2473
2474 conn_ctx = task->context;
2475 qc = conn_ctx->conn->qc;
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01002476 TRACE_ENTER(QUIC_EV_CONN_PTIMER, conn_ctx->conn,
2477 NULL, NULL, &qc->path->ifae_pkts);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002478 task->expire = TICK_ETERNITY;
2479 pktns = quic_loss_pktns(qc);
2480 if (tick_isset(pktns->tx.loss_time)) {
2481 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2482
2483 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
2484 if (!LIST_ISEMPTY(&lost_pkts))
2485 qc_release_lost_pkts(pktns, ctx, &lost_pkts, now_ms);
2486 qc_set_timer(conn_ctx);
2487 goto out;
2488 }
2489
2490 if (qc->path->in_flight) {
2491 pktns = quic_pto_pktns(qc, conn_ctx->state >= QUIC_HS_ST_COMPLETE, NULL);
2492 pktns->tx.pto_probe = 1;
2493 }
2494 else if (objt_server(qc->conn->target) && conn_ctx->state <= QUIC_HS_ST_COMPLETE) {
2495 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2496 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2497
2498 if (hel->tls_ctx.rx.flags == QUIC_FL_TLS_SECRETS_SET)
2499 hel->pktns->tx.pto_probe = 1;
2500 if (iel->tls_ctx.rx.flags == QUIC_FL_TLS_SECRETS_SET)
2501 iel->pktns->tx.pto_probe = 1;
2502 }
2503 qc->tx.nb_pto_dgrams = QUIC_MAX_NB_PTO_DGRAMS;
2504 tasklet_wakeup(conn_ctx->wait_event.tasklet);
2505 qc->path->loss.pto_count++;
2506
2507 out:
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01002508 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, conn_ctx->conn, pktns);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002509
2510 return task;
2511}
2512
2513/* Initialize <conn> QUIC connection with <quic_initial_clients> as root of QUIC
2514 * connections used to identify the first Initial packets of client connecting
2515 * to listeners. This parameter must be NULL for QUIC connections attached
2516 * to listeners. <dcid> is the destination connection ID with <dcid_len> as length.
2517 * <scid> is the source connection ID with <scid_len> as length.
2518 * Returns 1 if succeeded, 0 if not.
2519 */
2520int qc_new_conn_init(struct quic_conn *qc, int ipv4,
2521 struct eb_root *quic_initial_clients,
2522 struct eb_root *quic_clients,
2523 unsigned char *dcid, size_t dcid_len,
2524 unsigned char *scid, size_t scid_len)
2525{
2526 int i;
2527 /* Initial CID. */
2528 struct quic_connection_id *icid;
2529
2530 TRACE_ENTER(QUIC_EV_CONN_INIT, qc->conn);
2531 qc->cids = EB_ROOT;
2532 /* QUIC Server (or listener). */
2533 if (objt_listener(qc->conn->target)) {
2534 /* Copy the initial DCID. */
2535 qc->odcid.len = dcid_len;
2536 if (qc->odcid.len)
2537 memcpy(qc->odcid.data, dcid, dcid_len);
2538
2539 /* Copy the SCID as our DCID for this connection. */
2540 if (scid_len)
2541 memcpy(qc->dcid.data, scid, scid_len);
2542 qc->dcid.len = scid_len;
2543 }
2544 /* QUIC Client (outgoing connection to servers) */
2545 else {
2546 if (dcid_len)
2547 memcpy(qc->dcid.data, dcid, dcid_len);
2548 qc->dcid.len = dcid_len;
2549 }
2550
2551 /* Initialize the output buffer */
2552 qc->obuf.pos = qc->obuf.data;
2553
2554 icid = new_quic_cid(&qc->cids, 0);
2555 if (!icid)
2556 return 0;
2557
2558 /* Select our SCID which is the first CID with 0 as sequence number. */
2559 qc->scid = icid->cid;
2560
2561 /* Insert the DCID the QUIC client has choosen (only for listeners) */
2562 if (objt_listener(qc->conn->target))
2563 ebmb_insert(quic_initial_clients, &qc->odcid_node, qc->odcid.len);
2564
2565 /* Insert our SCID, the connection ID for the QUIC client. */
2566 ebmb_insert(quic_clients, &qc->scid_node, qc->scid.len);
2567
2568 /* Packet number spaces initialization. */
2569 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
2570 quic_pktns_init(&qc->pktns[i]);
2571 /* QUIC encryption level context initialization. */
2572 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
2573 if (!quic_conn_enc_level_init(qc, i))
2574 goto err;
2575 /* Initialize the packet number space. */
2576 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
2577 }
2578
2579 /* TX part. */
2580 LIST_INIT(&qc->tx.frms_to_send);
2581 qc->tx.bufs = quic_conn_tx_bufs_alloc(QUIC_CONN_TX_BUFS_NB, QUIC_CONN_TX_BUF_SZ);
2582 if (!qc->tx.bufs)
2583 goto err;
2584
2585 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
2586 qc->tx.wbuf = qc->tx.rbuf = 0;
2587 qc->tx.bytes = 0;
2588 qc->tx.nb_pto_dgrams = 0;
2589 /* RX part. */
2590 qc->rx.bytes = 0;
2591
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002592 /* XXX TO DO: Only one path at this time. */
2593 qc->path = &qc->paths[0];
2594 quic_path_init(qc->path, ipv4, default_quic_cc_algo, qc);
2595
2596 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc->conn);
2597
2598 return 1;
2599
2600 err:
2601 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_INIT, qc->conn);
2602 quic_conn_free(qc);
2603 return 0;
2604}
2605
2606/* Initialize the timer task of <qc> QUIC connection.
2607 * Returns 1 if succeeded, 0 if not.
2608 */
2609static int quic_conn_init_timer(struct quic_conn *qc)
2610{
2611 qc->timer_task = task_new(MAX_THREADS_MASK);
2612 if (!qc->timer_task)
2613 return 0;
2614
2615 qc->timer = TICK_ETERNITY;
2616 qc->timer_task->process = process_timer;
2617 qc->timer_task->context = qc->conn->xprt_ctx;
2618
2619 return 1;
2620}
2621
2622/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
2623 * past one byte of this buffer.
2624 */
2625static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
2626 struct quic_rx_packet *pkt)
2627{
2628 unsigned char dcid_len, scid_len;
2629
2630 /* Version */
2631 if (!quic_read_uint32(&pkt->version, (const unsigned char **)buf, end))
2632 return 0;
2633
2634 if (!pkt->version) { /* XXX TO DO XXX Version negotiation packet */ };
2635
2636 /* Destination Connection ID Length */
2637 dcid_len = *(*buf)++;
2638 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
2639 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1)
2640 /* XXX MUST BE DROPPED */
2641 return 0;
2642
2643 if (dcid_len) {
2644 /* Check that the length of this received DCID matches the CID lengths
2645 * of our implementation for non Initials packets only.
2646 */
2647 if (pkt->type != QUIC_PACKET_TYPE_INITIAL && dcid_len != QUIC_CID_LEN)
2648 return 0;
2649
2650 memcpy(pkt->dcid.data, *buf, dcid_len);
2651 }
2652
2653 pkt->dcid.len = dcid_len;
2654 *buf += dcid_len;
2655
2656 /* Source Connection ID Length */
2657 scid_len = *(*buf)++;
2658 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len)
2659 /* XXX MUST BE DROPPED */
2660 return 0;
2661
2662 if (scid_len)
2663 memcpy(pkt->scid.data, *buf, scid_len);
2664 pkt->scid.len = scid_len;
2665 *buf += scid_len;
2666
2667 return 1;
2668}
2669
2670/* Try to remove the header protecttion of <pkt> QUIC packet attached to <conn>
2671 * QUIC connection with <buf> as packet number field address, <end> a pointer to one
2672 * byte past the end of the buffer containing this packet and <beg> the address of
2673 * the packet first byte.
2674 * If succeeded, this function updates <*buf> to point to the next packet in the buffer.
2675 * Returns 1 if succeeded, 0 if not.
2676 */
2677static inline int qc_try_rm_hp(struct quic_rx_packet *pkt,
2678 unsigned char **buf, unsigned char *beg,
2679 const unsigned char *end,
2680 struct quic_conn_ctx *ctx)
2681{
2682 unsigned char *pn = NULL; /* Packet number field */
2683 enum quic_tls_enc_level tel;
2684 struct quic_enc_level *qel;
2685 /* Only for traces. */
2686 struct quic_rx_packet *qpkt_trace;
2687
2688 qpkt_trace = NULL;
2689 TRACE_ENTER(QUIC_EV_CONN_TRMHP, ctx->conn);
2690 /* The packet number is here. This is also the start minus
2691 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
2692 * protection.
2693 */
2694 pn = *buf;
2695 tel = quic_packet_type_enc_level(pkt->type);
2696 if (tel == QUIC_TLS_ENC_LEVEL_NONE) {
2697 TRACE_DEVEL("Wrong enc. level", QUIC_EV_CONN_TRMHP, ctx->conn);
2698 goto err;
2699 }
2700
2701 qel = &ctx->conn->qc->els[tel];
2702
2703 if (qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_DCD) {
2704 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, ctx->conn);
2705 goto err;
2706 }
2707
2708 if ((qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_SET) &&
2709 (tel != QUIC_TLS_ENC_LEVEL_APP || ctx->state >= QUIC_HS_ST_COMPLETE)) {
2710 /* Note that the following function enables us to unprotect the packet
2711 * number and its length subsequently used to decrypt the entire
2712 * packets.
2713 */
2714 if (!qc_do_rm_hp(pkt, &qel->tls_ctx,
2715 qel->pktns->rx.largest_pn, pn, beg, end, ctx)) {
2716 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, ctx->conn);
2717 goto err;
2718 }
2719
2720 /* The AAD includes the packet number field found at <pn>. */
2721 pkt->aad_len = pn - beg + pkt->pnl;
2722 qpkt_trace = pkt;
2723 /* Store the packet */
2724 pkt->pn_node.key = pkt->pn;
2725 quic_rx_packet_eb64_insert(&qel->rx.pkts, &pkt->pn_node);
2726 }
2727 else {
2728 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, ctx->conn, pkt);
2729 pkt->pn_offset = pn - beg;
2730 quic_rx_packet_list_addq(&qel->rx.pqpkts, pkt);
2731 }
2732
2733 memcpy(pkt->data, beg, pkt->len);
2734 /* Updtate the offset of <*buf> for the next QUIC packet. */
2735 *buf = beg + pkt->len;
2736
2737 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, ctx->conn, qpkt_trace);
2738 return 1;
2739
2740 err:
2741 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TRMHP, ctx->conn, qpkt_trace);
2742 return 0;
2743}
2744
2745/* Parse the header form from <byte0> first byte of <pkt> pacekt to set type.
2746 * Also set <*long_header> to 1 if this form is long, 0 if not.
2747 */
2748static inline void qc_parse_hd_form(struct quic_rx_packet *pkt,
2749 unsigned char byte0, int *long_header)
2750{
2751 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
2752 pkt->type =
2753 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
2754 *long_header = 1;
2755 }
2756 else {
2757 pkt->type = QUIC_PACKET_TYPE_SHORT;
2758 *long_header = 0;
2759 }
2760}
2761
2762static ssize_t qc_srv_pkt_rcv(unsigned char **buf, const unsigned char *end,
2763 struct quic_rx_packet *pkt,
2764 struct quic_dgram_ctx *dgram_ctx,
2765 struct sockaddr_storage *saddr)
2766{
2767 unsigned char *beg;
2768 uint64_t len;
2769 struct quic_conn *qc;
2770 struct eb_root *cids;
2771 struct ebmb_node *node;
2772 struct connection *srv_conn;
2773 struct quic_conn_ctx *conn_ctx;
2774 int long_header;
2775
2776 qc = NULL;
2777 TRACE_ENTER(QUIC_EV_CONN_SPKT);
2778 if (end <= *buf)
2779 goto err;
2780
2781 /* Fixed bit */
2782 if (!(**buf & QUIC_PACKET_FIXED_BIT))
2783 /* XXX TO BE DISCARDED */
2784 goto err;
2785
2786 srv_conn = dgram_ctx->owner;
2787 beg = *buf;
2788 /* Header form */
2789 qc_parse_hd_form(pkt, *(*buf)++, &long_header);
2790 if (long_header) {
2791 size_t cid_lookup_len;
2792
2793 if (!quic_packet_read_long_header(buf, end, pkt))
2794 goto err;
2795
2796 /* For Initial packets, and for servers (QUIC clients connections),
2797 * there is no Initial connection IDs storage.
2798 */
2799 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2800 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2801 cid_lookup_len = pkt->dcid.len;
2802 }
2803 else {
2804 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2805 cid_lookup_len = QUIC_CID_LEN;
2806 }
2807
2808 node = ebmb_lookup(cids, pkt->dcid.data, cid_lookup_len);
2809 if (!node)
2810 goto err;
2811
2812 qc = ebmb_entry(node, struct quic_conn, scid_node);
2813
2814 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2815 qc->dcid.len = pkt->scid.len;
2816 if (pkt->scid.len)
2817 memcpy(qc->dcid.data, pkt->scid.data, pkt->scid.len);
2818 }
2819
2820 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2821 uint64_t token_len;
2822
2823 if (!quic_dec_int(&token_len, (const unsigned char **)buf, end) || end - *buf < token_len)
2824 goto err;
2825
2826 /* XXX TO DO XXX 0 value means "the token is not present".
2827 * A server which sends an Initial packet must not set the token.
2828 * So, a client which receives an Initial packet with a token
2829 * MUST discard the packet or generate a connection error with
2830 * PROTOCOL_VIOLATION as type.
2831 * The token must be provided in a Retry packet or NEW_TOKEN frame.
2832 */
2833 pkt->token_len = token_len;
2834 }
2835 }
2836 else {
2837 /* XXX TO DO: Short header XXX */
2838 if (end - *buf < QUIC_CID_LEN)
2839 goto err;
2840
2841 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2842 node = ebmb_lookup(cids, *buf, QUIC_CID_LEN);
2843 if (!node)
2844 goto err;
2845
2846 qc = ebmb_entry(node, struct quic_conn, scid_node);
2847 *buf += QUIC_CID_LEN;
2848 }
2849 /* Store the DCID used for this packet to check the packet which
2850 * come in this UDP datagram match with it.
2851 */
2852 if (!dgram_ctx->dcid_node)
2853 dgram_ctx->dcid_node = node;
2854 /* Only packets packets with long headers and not RETRY or VERSION as type
2855 * have a length field.
2856 */
2857 if (long_header && pkt->type != QUIC_PACKET_TYPE_RETRY && pkt->version) {
2858 if (!quic_dec_int(&len, (const unsigned char **)buf, end) || end - *buf < len)
2859 goto err;
2860
2861 pkt->len = len;
2862 }
2863 else if (!long_header) {
2864 /* A short packet is the last one of an UDP datagram. */
2865 pkt->len = end - *buf;
2866 }
2867
2868 conn_ctx = qc->conn->xprt_ctx;
2869
2870 /* Increase the total length of this packet by the header length. */
2871 pkt->len += *buf - beg;
2872 /* Do not check the DCID node before the length. */
2873 if (dgram_ctx->dcid_node != node) {
2874 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_SPKT, qc->conn);
2875 goto err;
2876 }
2877
2878 if (pkt->len > sizeof pkt->data) {
2879 TRACE_PROTO("Too big packet", QUIC_EV_CONN_SPKT, qc->conn, pkt, &pkt->len);
2880 goto err;
2881 }
2882
2883 if (!qc_try_rm_hp(pkt, buf, beg, end, conn_ctx))
2884 goto err;
2885
2886 /* Wake the tasklet of the QUIC connection packet handler. */
2887 if (conn_ctx)
2888 tasklet_wakeup(conn_ctx->wait_event.tasklet);
2889
2890 TRACE_LEAVE(QUIC_EV_CONN_SPKT, qc->conn);
2891
2892 return pkt->len;
2893
2894 err:
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01002895 TRACE_DEVEL("Leaing in error", QUIC_EV_CONN_SPKT, qc ? qc->conn : NULL);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002896 return -1;
2897}
2898
2899static ssize_t qc_lstnr_pkt_rcv(unsigned char **buf, const unsigned char *end,
2900 struct quic_rx_packet *pkt,
2901 struct quic_dgram_ctx *dgram_ctx,
2902 struct sockaddr_storage *saddr)
2903{
2904 unsigned char *beg;
2905 uint64_t len;
2906 struct quic_conn *qc;
2907 struct eb_root *cids;
2908 struct ebmb_node *node;
2909 struct listener *l;
2910 struct quic_conn_ctx *conn_ctx;
2911 int long_header = 0;
2912
2913 qc = NULL;
2914 TRACE_ENTER(QUIC_EV_CONN_LPKT);
2915 if (end <= *buf)
2916 goto err;
2917
2918 /* Fixed bit */
2919 if (!(**buf & QUIC_PACKET_FIXED_BIT)) {
2920 /* XXX TO BE DISCARDED */
2921 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2922 goto err;
2923 }
2924
2925 l = dgram_ctx->owner;
2926 beg = *buf;
2927 /* Header form */
2928 qc_parse_hd_form(pkt, *(*buf)++, &long_header);
2929 if (long_header) {
2930 unsigned char dcid_len;
2931
2932 if (!quic_packet_read_long_header(buf, end, pkt)) {
2933 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2934 goto err;
2935 }
2936
2937 dcid_len = pkt->dcid.len;
2938 /* For Initial packets, and for servers (QUIC clients connections),
2939 * there is no Initial connection IDs storage.
2940 */
2941 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2942 /* DCIDs of first packets coming from clients may have the same values.
2943 * Let's distinguish them concatenating the socket addresses to the DCIDs.
2944 */
2945 quic_cid_saddr_cat(&pkt->dcid, saddr);
2946 cids = &l->rx.odcids;
2947 }
2948 else {
2949 if (pkt->dcid.len != QUIC_CID_LEN) {
2950 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2951 goto err;
2952 }
2953
2954 cids = &l->rx.cids;
2955 }
2956
2957 node = ebmb_lookup(cids, pkt->dcid.data, pkt->dcid.len);
2958 if (!node && pkt->type == QUIC_PACKET_TYPE_INITIAL && dcid_len == QUIC_CID_LEN &&
2959 cids == &l->rx.odcids) {
2960 /* Switch to the definitive tree ->cids containing the final CIDs. */
2961 node = ebmb_lookup(&l->rx.cids, pkt->dcid.data, dcid_len);
2962 if (node) {
2963 /* If found, signal this with NULL as special value for <cids>. */
2964 pkt->dcid.len = dcid_len;
2965 cids = NULL;
2966 }
2967 }
2968
2969 if (!node) {
2970 if (pkt->type != QUIC_PACKET_TYPE_INITIAL) {
2971 TRACE_PROTO("Non Initiial packet", QUIC_EV_CONN_LPKT);
2972 goto err;
2973 }
2974
2975 qc = new_quic_conn(pkt->version);
2976 if (!qc) {
2977 TRACE_PROTO("Non allocated new connection", QUIC_EV_CONN_LPKT);
2978 goto err;
2979 }
2980
2981 pkt->qc = qc;
2982 pkt->saddr = *saddr;
2983 /* Note that here, odcid_len equals to pkt->dcid.len minus the length
2984 * of <saddr>.
2985 */
2986 pkt->odcid_len = dcid_len;
2987 /* Enqueue this packet. */
2988 LIST_ADDQ(&l->rx.qpkts, &pkt->rx_list);
2989 /* Try to accept a new connection. */
2990 listener_accept(l);
2991 if (!qc->conn) {
2992 TRACE_PROTO("Non accepted connection", QUIC_EV_CONN_LPKT, qc->conn);
2993 goto err;
2994 }
2995
2996 if (!quic_conn_init_timer(qc)) {
2997 TRACE_PROTO("Non initialized timer", QUIC_EV_CONN_LPKT, qc->conn);
2998 goto err;
2999 }
3000
3001 /* This is the DCID node sent in this packet by the client. */
3002 node = &qc->odcid_node;
3003 conn_ctx = qc->conn->xprt_ctx;
3004 SSL_set_quic_transport_params(conn_ctx->ssl,
3005 qc->enc_params, qc->enc_params_len);
3006 }
3007 else {
3008 if (pkt->type == QUIC_PACKET_TYPE_INITIAL && cids == &l->rx.odcids)
3009 qc = ebmb_entry(node, struct quic_conn, odcid_node);
3010 else
3011 qc = ebmb_entry(node, struct quic_conn, scid_node);
3012 }
3013
3014 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
3015 uint64_t token_len;
3016 struct quic_tls_ctx *ctx =
3017 &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
3018
3019 if (!quic_dec_int(&token_len, (const unsigned char **)buf, end) ||
3020 end - *buf < token_len) {
3021 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3022 goto err;
3023 }
3024
3025 /* XXX TO DO XXX 0 value means "the token is not present".
3026 * A server which sends an Initial packet must not set the token.
3027 * So, a client which receives an Initial packet with a token
3028 * MUST discard the packet or generate a connection error with
3029 * PROTOCOL_VIOLATION as type.
3030 * The token must be provided in a Retry packet or NEW_TOKEN frame.
3031 */
3032 pkt->token_len = token_len;
3033 /* NOTE: the socket address has been concatenated to the destination ID
3034 * choosen by the client for Initial packets.
3035 */
3036 if (!ctx->rx.hp && !qc_new_isecs(qc->conn, pkt->dcid.data,
3037 pkt->odcid_len, 1)) {
3038 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3039 goto err;
3040 }
3041 }
3042 }
3043 else {
3044 if (end - *buf < QUIC_CID_LEN) {
3045 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
3046 goto err;
3047 }
3048
3049 cids = &l->rx.cids;
3050 node = ebmb_lookup(cids, *buf, QUIC_CID_LEN);
3051 if (!node) {
3052 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
3053 goto err;
3054 }
3055
3056 qc = ebmb_entry(node, struct quic_conn, scid_node);
3057 *buf += QUIC_CID_LEN;
3058 }
3059
3060 /* Store the DCID used for this packet to check the packet which
3061 * come in this UDP datagram match with it.
3062 */
3063 if (!dgram_ctx->dcid_node) {
3064 dgram_ctx->dcid_node = node;
3065 dgram_ctx->qc = qc;
3066 }
3067
3068 /* Only packets packets with long headers and not RETRY or VERSION as type
3069 * have a length field.
3070 */
3071 if (long_header && pkt->type != QUIC_PACKET_TYPE_RETRY && pkt->version) {
3072 if (!quic_dec_int(&len, (const unsigned char **)buf, end) ||
3073 end - *buf < len) {
3074 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3075 goto err;
3076 }
3077
3078 pkt->len = len;
3079 }
3080 else if (!long_header) {
3081 /* A short packet is the last one of an UDP datagram. */
3082 pkt->len = end - *buf;
3083 }
3084
3085 /* Update the state if needed. */
3086 conn_ctx = qc->conn->xprt_ctx;
3087
3088 /* Increase the total length of this packet by the header length. */
3089 pkt->len += *buf - beg;
3090 /* Do not check the DCID node before the length. */
3091 if (dgram_ctx->dcid_node != node) {
3092 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3093 goto err;
3094 }
3095
3096 if (pkt->len > sizeof pkt->data) {
3097 TRACE_PROTO("Too big packet", QUIC_EV_CONN_LPKT, qc->conn, pkt, &pkt->len);
3098 goto err;
3099 }
3100
3101 if (!qc_try_rm_hp(pkt, buf, beg, end, conn_ctx)) {
3102 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3103 goto err;
3104 }
3105
3106 /* Wake the tasklet of the QUIC connection packet handler. */
3107 if (conn_ctx)
3108 tasklet_wakeup(conn_ctx->wait_event.tasklet);
3109 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc->conn, pkt);
3110
3111 return pkt->len;
3112
3113 err:
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01003114 TRACE_DEVEL("Leaving in error", QUIC_EV_CONN_LPKT,
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003115 qc ? qc->conn : NULL, pkt);
3116 return -1;
3117}
3118
3119/* This function builds into <buf> buffer a QUIC long packet header whose size may be computed
3120 * in advance. This is the reponsability of the caller to check there is enough room in this
3121 * buffer to build a long header.
3122 * Returns 0 if <type> QUIC packet type is not supported by long header, or 1 if succeeded.
3123 */
3124static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
3125 int type, size_t pn_len, struct quic_conn *conn)
3126{
3127 if (type > QUIC_PACKET_TYPE_RETRY)
3128 return 0;
3129
3130 /* #0 byte flags */
3131 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
3132 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
3133 /* Version */
3134 quic_write_uint32(buf, end, conn->version);
3135 *(*buf)++ = conn->dcid.len;
3136 /* Destination connection ID */
3137 if (conn->dcid.len) {
3138 memcpy(*buf, conn->dcid.data, conn->dcid.len);
3139 *buf += conn->dcid.len;
3140 }
3141 /* Source connection ID */
3142 *(*buf)++ = conn->scid.len;
3143 if (conn->scid.len) {
3144 memcpy(*buf, conn->scid.data, conn->scid.len);
3145 *buf += conn->scid.len;
3146 }
3147
3148 return 1;
3149}
3150
3151/* This function builds into <buf> buffer a QUIC long packet header whose size may be computed
3152 * in advance. This is the reponsability of the caller to check there is enough room in this
3153 * buffer to build a long header.
3154 * Returns 0 if <type> QUIC packet type is not supported by long header, or 1 if succeeded.
3155 */
3156static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
3157 size_t pn_len, struct quic_conn *conn)
3158{
3159 /* #0 byte flags */
3160 *(*buf)++ = QUIC_PACKET_FIXED_BIT | (pn_len - 1);
3161 /* Destination connection ID */
3162 if (conn->dcid.len) {
3163 memcpy(*buf, conn->dcid.data, conn->dcid.len);
3164 *buf += conn->dcid.len;
3165 }
3166
3167 return 1;
3168}
3169
3170/* Apply QUIC header protection to the packet with <buf> as first byte address,
3171 * <pn> as address of the Packet number field, <pnlen> being this field length
3172 * with <aead> as AEAD cipher and <key> as secret key.
3173 * Returns 1 if succeeded or 0 if failed.
3174 */
3175static int quic_apply_header_protection(unsigned char *buf, unsigned char *pn, size_t pnlen,
3176 const EVP_CIPHER *aead, const unsigned char *key)
3177{
3178 int i, ret, outlen;
3179 EVP_CIPHER_CTX *ctx;
3180 /* We need an IV of at least 5 bytes: one byte for bytes #0
3181 * and at most 4 bytes for the packet number
3182 */
3183 unsigned char mask[5] = {0};
3184
3185 ret = 0;
3186 ctx = EVP_CIPHER_CTX_new();
3187 if (!ctx)
3188 return 0;
3189
3190 if (!EVP_EncryptInit_ex(ctx, aead, NULL, key, pn + QUIC_PACKET_PN_MAXLEN) ||
3191 !EVP_EncryptUpdate(ctx, mask, &outlen, mask, sizeof mask) ||
3192 !EVP_EncryptFinal_ex(ctx, mask, &outlen))
3193 goto out;
3194
3195 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
3196 for (i = 0; i < pnlen; i++)
3197 pn[i] ^= mask[i + 1];
3198
3199 ret = 1;
3200
3201 out:
3202 EVP_CIPHER_CTX_free(ctx);
3203
3204 return ret;
3205}
3206
3207/* Reduce the encoded size of <ack_frm> ACK frame removing the last
3208 * ACK ranges if needed to a value below <limit> in bytes.
3209 * Return 1 if succeeded, 0 if not.
3210 */
3211static int quic_ack_frm_reduce_sz(struct quic_frame *ack_frm, size_t limit)
3212{
3213 size_t room, ack_delay_sz;
3214
3215 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
3216 /* A frame is made of 1 byte for the frame type. */
3217 room = limit - ack_delay_sz - 1;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003218 if (!quic_rm_last_ack_ranges(ack_frm->tx_ack.arngs, room))
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003219 return 0;
3220
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003221 return 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003222}
3223
3224/* Prepare as most as possible CRYPTO frames from prebuilt CRYPTO frames for <qel>
3225 * encryption level to be encoded in a buffer with <room> as available room,
Frédéric Lécailleea604992020-12-24 13:01:37 +01003226 * and <*len> the packet Length field initialized with the number of bytes already present
3227 * in this buffer which must be taken into an account for the Length packet field value.
3228 * <headlen> is the number of bytes already present in this packet befor building
3229 * CRYPTO frames.
3230 * This is the responsability of the caller to check that <*len> < <room> as this is
3231 * the responsability to check that <headlen> < quic_path_prep_data(conn->path).
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003232 * Update consequently <*len> to reflect the size of these CRYPTO frames built
3233 * by this function. Also attach these CRYPTO frames to <pkt> QUIC packet.
3234 * Return 1 if succeeded, 0 if not.
3235 */
3236static inline int qc_build_cfrms(struct quic_tx_packet *pkt,
Frédéric Lécailleea604992020-12-24 13:01:37 +01003237 size_t room, size_t *len, size_t headlen,
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003238 struct quic_enc_level *qel,
3239 struct quic_conn *conn)
3240{
Frédéric Lécailleea604992020-12-24 13:01:37 +01003241 int ret;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003242 struct quic_tx_frm *cf, *cfbak;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003243
Frédéric Lécailleea604992020-12-24 13:01:37 +01003244 ret = 0;
3245 /* If we are not probing we must take into an account the congestion
3246 * control window.
3247 */
3248 if (!conn->tx.nb_pto_dgrams)
3249 room = QUIC_MIN(room, quic_path_prep_data(conn->path) - headlen);
3250 TRACE_PROTO("************** CRYPTO frames build (headlen)",
3251 QUIC_EV_CONN_BCFRMS, conn->conn, &headlen);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003252 list_for_each_entry_safe(cf, cfbak, &qel->pktns->tx.frms, list) {
3253 /* header length, data length, frame length. */
3254 size_t hlen, dlen, cflen;
3255
Frédéric Lécailleea604992020-12-24 13:01:37 +01003256 TRACE_PROTO(" New CRYPTO frame build (room, len)",
3257 QUIC_EV_CONN_BCFRMS, conn->conn, &room, len);
3258 if (!room)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003259 break;
3260
3261 /* Compute the length of this CRYPTO frame header */
3262 hlen = 1 + quic_int_getsize(cf->crypto.offset);
3263 /* Compute the data length of this CRyPTO frame. */
3264 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
Frédéric Lécailleea604992020-12-24 13:01:37 +01003265 TRACE_PROTO(" CRYPTO data length (hlen, crypto.len, dlen)",
3266 QUIC_EV_CONN_BCFRMS, conn->conn, &hlen, &cf->crypto.len, &dlen);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003267 if (!dlen)
3268 break;
3269
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003270 pkt->cdata_len += dlen;
3271 /* CRYPTO frame length. */
3272 cflen = hlen + quic_int_getsize(dlen) + dlen;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003273 TRACE_PROTO(" CRYPTO frame length (cflen)",
3274 QUIC_EV_CONN_BCFRMS, conn->conn, &cflen);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003275 /* Add the CRYPTO data length and its encoded length to the packet
3276 * length and the length of this length.
3277 */
3278 *len += cflen;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003279 room -= cflen;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003280 if (dlen == cf->crypto.len) {
3281 /* <cf> CRYPTO data have been consumed. */
3282 LIST_DEL(&cf->list);
3283 LIST_ADDQ(&pkt->frms, &cf->list);
3284 }
3285 else {
3286 struct quic_tx_frm *new_cf;
3287
3288 new_cf = pool_alloc(pool_head_quic_tx_frm);
3289 if (!new_cf) {
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01003290 TRACE_PROTO("No memory for new crypto frame", QUIC_EV_CONN_BCFRMS, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003291 return 0;
3292 }
3293
3294 new_cf->type = QUIC_FT_CRYPTO;
3295 new_cf->crypto.len = dlen;
3296 new_cf->crypto.offset = cf->crypto.offset;
3297 LIST_ADDQ(&pkt->frms, &new_cf->list);
3298 /* Consume <dlen> bytes of the current frame. */
3299 cf->crypto.len -= dlen;
3300 cf->crypto.offset += dlen;
3301 }
Frédéric Lécailleea604992020-12-24 13:01:37 +01003302 ret = 1;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003303 }
3304
Frédéric Lécailleea604992020-12-24 13:01:37 +01003305 return ret;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003306}
3307
3308/* This function builds a clear handshake packet used during a QUIC TLS handshakes
3309 * into <wbuf> the current <wbuf> for <conn> QUIC connection with <qel> as QUIC
3310 * TLS encryption level for outgoing packets filling it with as much as CRYPTO
3311 * data as possible from <offset> offset in the CRYPTO data stream. Note that
3312 * this offset value is updated by the length of the CRYPTO frame used to embed
3313 * the CRYPTO data if this packet and only if the packet is successfully built.
3314 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
3315 * reserved so that to be sure there is enough room to build this AEAD TAG after
3316 * having successfully returned from this function and to be sure the position
3317 * pointer of <wbuf> may be safely incremented by QUIC_TLS_TAG_LEN. After having
3318 * returned from this funciton, <wbuf> position will point one past the last
3319 * byte of the payload with the confidence there is at least QUIC_TLS_TAG_LEN bytes
3320 * available packet to encrypt this packet.
3321 * This function also update the value of <buf_pn> pointer to point to the packet
3322 * number field in this packet. <pn_len> will also have the packet number
3323 * length as value.
3324 *
3325 * Return the length of the packet if succeeded minus QUIC_TLS_TAG_LEN, or -1 if
3326 * failed (not enough room in <wbuf> to build this packet plus QUIC_TLS_TAG_LEN
3327 * bytes), -2 if there are too much CRYPTO data in flight to build a packet.
3328 */
3329static ssize_t qc_do_build_hdshk_pkt(struct q_buf *wbuf,
3330 struct quic_tx_packet *pkt, int pkt_type,
3331 int64_t pn, size_t *pn_len,
3332 unsigned char **buf_pn,
3333 struct quic_enc_level *qel,
3334 struct quic_conn *conn)
3335{
3336 unsigned char *beg, *pos;
3337 const unsigned char *end;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003338 size_t len, len_frms, token_fields_len, padding_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003339 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
3340 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
3341 struct quic_crypto *crypto = &frm.crypto;
3342 size_t ack_frm_len;
3343 int64_t largest_acked_pn;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003344 int add_ping_frm;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003345
Frédéric Lécailleea604992020-12-24 13:01:37 +01003346 /* Length field value with CRYPTO frames if present. */
3347 len_frms = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003348 beg = pos = q_buf_getpos(wbuf);
3349 end = q_buf_end(wbuf);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003350 /* When not probing and not acking, reduce the size of this buffer to respect
3351 * the congestion controller window.
3352 */
3353 if (!conn->tx.nb_pto_dgrams && !(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED)) {
3354 size_t path_room;
3355
3356 path_room = quic_path_prep_data(conn->path);
3357 if (end - beg > path_room)
3358 end = beg + path_room;
3359 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003360
3361 /* For a server, the token field of an Initial packet is empty. */
3362 token_fields_len = pkt_type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0;
3363
3364 /* Check there is enough room to build the header followed by a token. */
3365 if (end - pos < QUIC_LONG_PACKET_MINLEN + conn->dcid.len +
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003366 conn->scid.len + token_fields_len + QUIC_TLS_TAG_LEN) {
3367 ssize_t room = end - pos;
3368 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3369 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003370 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003371 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003372
3373 /* Reserve enough room at the end of the packet for the AEAD TAG. */
3374 end -= QUIC_TLS_TAG_LEN;
3375 largest_acked_pn = qel->pktns->tx.largest_acked_pn;
3376 /* packet number length */
3377 *pn_len = quic_packet_number_length(pn, largest_acked_pn);
3378
3379 quic_build_packet_long_header(&pos, end, pkt_type, *pn_len, conn);
3380
3381 /* Encode the token length (0) for an Initial packet. */
3382 if (pkt_type == QUIC_PACKET_TYPE_INITIAL)
3383 *pos++ = 0;
3384
3385 /* Build an ACK frame if required. */
3386 ack_frm_len = 0;
3387 if ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003388 !eb_is_empty(&qel->pktns->rx.arngs.root)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003389 ack_frm.tx_ack.ack_delay = 0;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003390 ack_frm.tx_ack.arngs = &qel->pktns->rx.arngs;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003391 ack_frm_len = quic_ack_frm_reduce_sz(&ack_frm, end - pos);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003392 if (!ack_frm_len) {
3393 ssize_t room = end - pos;
3394 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3395 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003396 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003397 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003398
3399 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
3400 }
3401
3402 /* Length field value without the CRYPTO frames data length. */
3403 len = ack_frm_len + *pn_len;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003404 if (!LIST_ISEMPTY(&qel->pktns->tx.frms)) {
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003405 ssize_t room = end - pos;
Frédéric Lécailleea604992020-12-24 13:01:37 +01003406
3407 len_frms = len + QUIC_TLS_TAG_LEN;
3408 if (!qc_build_cfrms(pkt, end - pos, &len_frms, pos - beg, qel, conn)) {
3409 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3410 conn->conn, NULL, NULL, &room);
3411 goto err;
3412 }
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003413 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003414
3415 add_ping_frm = 0;
3416 padding_len = 0;
3417 if (objt_server(conn->conn->target) &&
3418 pkt_type == QUIC_PACKET_TYPE_INITIAL &&
3419 len < QUIC_INITIAL_PACKET_MINLEN) {
3420 len += padding_len = QUIC_INITIAL_PACKET_MINLEN - len;
3421 }
3422 else if (LIST_ISEMPTY(&pkt->frms)) {
3423 if (qel->pktns->tx.pto_probe) {
3424 /* If we cannot send a CRYPTO frame, we send a PING frame. */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003425 add_ping_frm = 1;
3426 len += 1;
3427 }
3428 /* If there is no frame at all to follow, add at least a PADDING frame. */
3429 if (!ack_frm_len)
3430 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
3431 }
3432
3433 /* Length (of the remaining data). Must not fail because, the buffer size
3434 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
3435 * for the encryption TAG. It must be taken into an account for the length
3436 * of this packet.
3437 */
Frédéric Lécailleea604992020-12-24 13:01:37 +01003438 if (len_frms)
3439 len = len_frms;
3440 else
3441 len += QUIC_TLS_TAG_LEN;
3442 quic_enc_int(&pos, end, len);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003443
3444 /* Packet number field address. */
3445 *buf_pn = pos;
3446
3447 /* Packet number encoding. */
3448 quic_packet_number_encode(&pos, end, pn, *pn_len);
3449
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003450 if (ack_frm_len && !qc_build_frm(&pos, end, &ack_frm, pkt, conn)) {
3451 ssize_t room = end - pos;
3452 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3453 conn->conn, NULL, NULL, &room);
3454 goto err;
3455 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003456
3457 /* Crypto frame */
3458 if (!LIST_ISEMPTY(&pkt->frms)) {
3459 struct quic_tx_frm *cf;
3460
3461 list_for_each_entry(cf, &pkt->frms, list) {
3462 crypto->offset = cf->crypto.offset;
3463 crypto->len = cf->crypto.len;
3464 crypto->qel = qel;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003465 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3466 ssize_t room = end - pos;
3467 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3468 conn->conn, NULL, NULL, &room);
3469 goto err;
3470 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003471 }
3472 }
3473
3474 /* Build a PING frame if needed. */
3475 if (add_ping_frm) {
3476 frm.type = QUIC_FT_PING;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003477 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3478 ssize_t room = end - pos;
3479 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3480 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003481 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003482 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003483 }
3484
3485 /* Build a PADDING frame if needed. */
3486 if (padding_len) {
3487 frm.type = QUIC_FT_PADDING;
3488 frm.padding.len = padding_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003489 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3490 ssize_t room = end - pos;
3491 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3492 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003493 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003494 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003495 }
3496
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003497 /* Always reset this variable as this function has no idea
3498 * if it was set. It is handle by the loss detection timer.
3499 */
3500 qel->pktns->tx.pto_probe = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003501
3502 out:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003503 return pos - beg;
3504
3505 err:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003506 return -1;
3507}
3508
3509static inline void quic_tx_packet_init(struct quic_tx_packet *pkt)
3510{
3511 pkt->cdata_len = 0;
3512 pkt->in_flight_len = 0;
3513 LIST_INIT(&pkt->frms);
3514}
3515
3516/* Free <pkt> TX packet which has not already attache to any tree. */
3517static inline void free_quic_tx_packet(struct quic_tx_packet *pkt)
3518{
3519 struct quic_tx_frm *frm, *frmbak;
3520
3521 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list) {
3522 LIST_DEL(&frm->list);
3523 pool_free(pool_head_quic_tx_frm, frm);
3524 }
3525 pool_free(pool_head_quic_tx_packet, pkt);
3526}
3527
3528/* Build a handshake packet into <buf> packet buffer with <pkt_type> as packet
3529 * type for <qc> QUIC connection from CRYPTO data stream at <*offset> offset to
3530 * be encrypted at <qel> encryption level.
3531 * Return -2 if the packet could not be encrypted for any reason, -1 if there was
3532 * not enough room in <buf> to build the packet, or the size of the built packet
3533 * if succeeded (may be zero if there is too much crypto data in flight to build the packet).
3534 */
3535static ssize_t qc_build_hdshk_pkt(struct q_buf *buf, struct quic_conn *qc, int pkt_type,
3536 struct quic_enc_level *qel)
3537{
3538 /* The pointer to the packet number field. */
3539 unsigned char *buf_pn;
3540 unsigned char *beg, *end, *payload;
3541 int64_t pn;
3542 size_t pn_len, payload_len, aad_len;
3543 ssize_t pkt_len;
3544 struct quic_tls_ctx *tls_ctx;
3545 struct quic_tx_packet *pkt;
3546
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003547 TRACE_ENTER(QUIC_EV_CONN_HPKT, qc->conn, NULL, qel);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003548 pkt = pool_alloc(pool_head_quic_tx_packet);
3549 if (!pkt) {
3550 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_HPKT, qc->conn);
3551 return -2;
3552 }
3553
3554 quic_tx_packet_init(pkt);
3555 beg = q_buf_getpos(buf);
3556 pn_len = 0;
3557 buf_pn = NULL;
3558 pn = qel->pktns->tx.next_pn + 1;
3559 pkt_len = qc_do_build_hdshk_pkt(buf, pkt, pkt_type, pn, &pn_len, &buf_pn, qel, qc);
3560 if (pkt_len <= 0) {
3561 free_quic_tx_packet(pkt);
3562 return pkt_len;
3563 }
3564
3565 end = beg + pkt_len;
3566 payload = buf_pn + pn_len;
3567 payload_len = end - payload;
3568 aad_len = payload - beg;
3569
3570 tls_ctx = &qel->tls_ctx;
3571 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc->conn))
3572 goto err;
3573
3574 end += QUIC_TLS_TAG_LEN;
3575 pkt_len += QUIC_TLS_TAG_LEN;
3576 if (!quic_apply_header_protection(beg, buf_pn, pn_len,
3577 tls_ctx->tx.hp, tls_ctx->tx.hp_key)) {
3578 TRACE_DEVEL("Could not apply the header protection", QUIC_EV_CONN_HPKT, qc->conn);
3579 goto err;
3580 }
3581
3582 /* Now that a correct packet is built, let us set the position pointer of
3583 * <buf> buffer for the next packet.
3584 */
3585 q_buf_setpos(buf, end);
3586 /* Consume a packet number. */
3587 ++qel->pktns->tx.next_pn;
3588 /* Attach the built packet to its tree. */
3589 pkt->pn_node.key = qel->pktns->tx.next_pn;
3590 /* Set the packet in fligth length for in flight packet only. */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003591 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003592 pkt->in_flight_len = pkt_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003593 qc->path->prep_in_flight += pkt_len;
3594 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003595 pkt->pktns = qel->pktns;
3596 eb64_insert(&qel->pktns->tx.pkts, &pkt->pn_node);
3597 /* Increment the number of bytes in <buf> buffer by the length of this packet. */
3598 buf->data += pkt_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003599 /* Attach this packet to <buf>. */
3600 LIST_ADDQ(&buf->pkts, &pkt->list);
3601 TRACE_LEAVE(QUIC_EV_CONN_HPKT, qc->conn, pkt);
3602
3603 return pkt_len;
3604
3605 err:
3606 free_quic_tx_packet(pkt);
3607 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_HPKT, qc->conn);
3608 return -2;
3609}
3610
3611/* Prepare a clear post handhskake packet for <conn> QUIC connnection.
3612 * Return the length of this packet if succeeded, -1 <wbuf> was full.
3613 */
3614static ssize_t qc_do_build_phdshk_apkt(struct q_buf *wbuf,
3615 struct quic_tx_packet *pkt,
3616 int64_t pn, size_t *pn_len,
3617 unsigned char **buf_pn, struct quic_enc_level *qel,
3618 struct quic_conn *conn)
3619{
3620 const unsigned char *beg, *end;
3621 unsigned char *pos;
3622 struct quic_frame *frm, *sfrm;
3623 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
3624 size_t fake_len, ack_frm_len;
3625 int64_t largest_acked_pn;
3626
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003627 TRACE_ENTER(QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003628 beg = pos = q_buf_getpos(wbuf);
3629 end = q_buf_end(wbuf);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003630 /* When not probing and not acking, reduce the size of this buffer to respect
3631 * the congestion controller window.
3632 */
3633 if (!conn->tx.nb_pto_dgrams && !(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED)) {
3634 size_t path_room;
3635
3636 path_room = quic_path_prep_data(conn->path);
3637 if (end - beg > path_room)
3638 end = beg + path_room;
3639 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003640 largest_acked_pn = qel->pktns->tx.largest_acked_pn;
3641 /* Packet number length */
3642 *pn_len = quic_packet_number_length(pn, largest_acked_pn);
3643 /* Check there is enough room to build this packet (without payload). */
3644 if (end - pos < QUIC_SHORT_PACKET_MINLEN + sizeof_quic_cid(&conn->dcid) +
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003645 *pn_len + QUIC_TLS_TAG_LEN) {
3646 ssize_t room = end - pos;
3647 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3648 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003649 goto err;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003650 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003651
3652 /* Reserve enough room at the end of the packet for the AEAD TAG. */
3653 end -= QUIC_TLS_TAG_LEN;
3654 quic_build_packet_short_header(&pos, end, *pn_len, conn);
3655 /* Packet number field. */
3656 *buf_pn = pos;
3657 /* Packet number encoding. */
3658 quic_packet_number_encode(&pos, end, pn, *pn_len);
3659
3660 /* Build an ACK frame if required. */
3661 ack_frm_len = 0;
3662 if ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003663 !eb_is_empty(&qel->pktns->rx.arngs.root)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003664 ack_frm.tx_ack.ack_delay = 0;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003665 ack_frm.tx_ack.arngs = &qel->pktns->rx.arngs;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003666 ack_frm_len = quic_ack_frm_reduce_sz(&ack_frm, end - pos);
3667 if (!ack_frm_len)
3668 goto err;
3669
3670 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
3671 }
3672
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003673 if (ack_frm_len && !qc_build_frm(&pos, end, &ack_frm, pkt, conn)) {
3674 ssize_t room = end - pos;
3675 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3676 conn->conn, NULL, NULL, &room);
3677 goto err;
3678 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003679
3680 fake_len = ack_frm_len;
3681 if (!LIST_ISEMPTY(&qel->pktns->tx.frms) &&
Frédéric Lécailleea604992020-12-24 13:01:37 +01003682 !qc_build_cfrms(pkt, end - pos, &fake_len, pos - beg, qel, conn)) {
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003683 ssize_t room = end - pos;
3684 TRACE_PROTO("some CRYPTO frames could not be built",
3685 QUIC_EV_CONN_PAPKT, conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003686 goto err;
3687 }
3688
3689 /* Crypto frame */
3690 if (!LIST_ISEMPTY(&pkt->frms)) {
3691 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
3692 struct quic_crypto *crypto = &frm.crypto;
3693 struct quic_tx_frm *cf;
3694
3695 list_for_each_entry(cf, &pkt->frms, list) {
3696 crypto->offset = cf->crypto.offset;
3697 crypto->len = cf->crypto.len;
3698 crypto->qel = qel;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003699 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3700 ssize_t room = end - pos;
3701 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3702 conn->conn, NULL, NULL, &room);
3703 goto err;
3704 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003705 }
3706 }
3707
3708 /* Encode a maximum of frames. */
3709 list_for_each_entry_safe(frm, sfrm, &conn->tx.frms_to_send, list) {
3710 unsigned char *ppos;
3711
3712 ppos = pos;
3713 if (!qc_build_frm(&ppos, end, frm, pkt, conn)) {
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003714 TRACE_DEVEL("Frames not built", QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003715 break;
3716 }
3717
3718 LIST_DEL(&frm->list);
3719 LIST_ADDQ(&pkt->frms, &frm->list);
3720 pos = ppos;
3721 }
3722
3723 out:
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003724 TRACE_LEAVE(QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003725 return pos - beg;
3726
3727 err:
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003728 TRACE_DEVEL("leaving in error (buffer full)", QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003729 return -1;
3730}
3731
3732/* Prepare a post handhskake packet at Application encryption level for <conn>
3733 * QUIC connnection.
3734 * Return the length of this packet if succeeded, -1 if <wbuf> was full,
3735 * -2 in case of major error (encryption failure).
3736 */
3737static ssize_t qc_build_phdshk_apkt(struct q_buf *wbuf, struct quic_conn *qc)
3738{
3739 /* A pointer to the packet number fiel in <buf> */
3740 unsigned char *buf_pn;
3741 unsigned char *beg, *end, *payload;
3742 int64_t pn;
3743 size_t pn_len, aad_len, payload_len;
3744 ssize_t pkt_len;
3745 struct quic_tls_ctx *tls_ctx;
3746 struct quic_enc_level *qel;
3747 struct quic_tx_packet *pkt;
3748
3749 TRACE_ENTER(QUIC_EV_CONN_PAPKT, qc->conn);
3750 pkt = pool_alloc(pool_head_quic_tx_packet);
3751 if (!pkt) {
3752 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_PAPKT, qc->conn);
3753 return -2;
3754 }
3755
3756 quic_tx_packet_init(pkt);
3757 beg = q_buf_getpos(wbuf);
3758 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3759 pn_len = 0;
3760 buf_pn = NULL;
3761 pn = qel->pktns->tx.next_pn + 1;
3762 pkt_len = qc_do_build_phdshk_apkt(wbuf, pkt, pn, &pn_len, &buf_pn, qel, qc);
3763 if (pkt_len <= 0) {
3764 free_quic_tx_packet(pkt);
3765 return pkt_len;
3766 }
3767
3768 end = beg + pkt_len;
3769 payload = buf_pn + pn_len;
3770 payload_len = end - payload;
3771 aad_len = payload - beg;
3772
3773 tls_ctx = &qel->tls_ctx;
3774 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc->conn))
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003775 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003776
3777 end += QUIC_TLS_TAG_LEN;
3778 pkt_len += QUIC_TLS_TAG_LEN;
3779 if (!quic_apply_header_protection(beg, buf_pn, pn_len,
3780 tls_ctx->tx.hp, tls_ctx->tx.hp_key))
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003781 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003782
3783 q_buf_setpos(wbuf, end);
3784 /* Consume a packet number. */
3785 ++qel->pktns->tx.next_pn;
3786 /* Attach the built packet to its tree. */
3787 pkt->pn_node.key = qel->pktns->tx.next_pn;
3788 eb64_insert(&qel->pktns->tx.pkts, &pkt->pn_node);
3789 /* Set the packet in fligth length for in flight packet only. */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003790 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003791 pkt->in_flight_len = pkt_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003792 qc->path->prep_in_flight += pkt_len;
3793 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003794 pkt->pktns = qel->pktns;
3795 /* Increment the number of bytes in <buf> buffer by the length of this packet. */
3796 wbuf->data += pkt_len;
3797 /* Attach this packet to <buf>. */
3798 LIST_ADDQ(&wbuf->pkts, &pkt->list);
3799
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003800 TRACE_LEAVE(QUIC_EV_CONN_PAPKT, qc->conn, pkt);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003801
3802 return pkt_len;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003803
3804 err:
3805 free_quic_tx_packet(pkt);
3806 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PAPKT, qc->conn);
3807 return -2;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003808}
3809
3810/* Prepare a maximum of QUIC Application level packets from <ctx> QUIC
3811 * connection I/O handler context.
3812 * Returns 1 if succeeded, 0 if not.
3813 */
3814int qc_prep_phdshk_pkts(struct quic_conn *qc)
3815{
3816 struct q_buf *wbuf;
3817 struct quic_enc_level *qel;
3818
3819 TRACE_ENTER(QUIC_EV_CONN_PAPKTS, qc->conn);
3820 wbuf = q_wbuf(qc);
3821 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3822 while (q_buf_empty(wbuf)) {
3823 ssize_t ret;
3824
3825 if (!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3826 (LIST_ISEMPTY(&qel->pktns->tx.frms) ||
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003827 qc->path->prep_in_flight >= qc->path->cwnd)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003828 TRACE_DEVEL("nothing more to do",
3829 QUIC_EV_CONN_PAPKTS, qc->conn);
3830 break;
3831 }
3832
3833 ret = qc_build_phdshk_apkt(wbuf, qc);
3834 switch (ret) {
3835 case -1:
3836 /* Not enough room left in <wbuf>. */
3837 wbuf = q_next_wbuf(qc);
3838 continue;
3839 case -2:
3840 return 0;
3841 default:
3842 /* XXX TO CHECK: consume a buffer. */
3843 wbuf = q_next_wbuf(qc);
3844 continue;
3845 }
3846 }
3847 TRACE_LEAVE(QUIC_EV_CONN_PAPKTS, qc->conn);
3848
3849 return 1;
3850}
3851
3852/* QUIC connection packet handler task. */
3853static struct task *quic_conn_io_cb(struct task *t, void *context, unsigned short state)
3854{
3855 struct quic_conn_ctx *ctx = context;
3856
3857 if (ctx->state < QUIC_HS_ST_COMPLETE) {
3858 qc_do_hdshk(ctx);
3859 }
3860 else {
3861 struct quic_conn *qc = ctx->conn->qc;
3862
3863 /* XXX TO DO: may fail!!! XXX */
3864 qc_treat_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_APP], ctx);
3865 qc_prep_phdshk_pkts(qc);
3866 qc_send_ppkts(ctx);
3867 }
3868
3869 return NULL;
3870}
3871
3872/* Receive up to <count> bytes from connection <conn>'s socket and store them
3873 * into buffer <buf>. Only one call to recv() is performed, unless the
3874 * buffer wraps, in which case a second call may be performed. The connection's
3875 * flags are updated with whatever special event is detected (error, read0,
3876 * empty). The caller is responsible for taking care of those events and
3877 * avoiding the call if inappropriate. The function does not call the
3878 * connection's polling update function, so the caller is responsible for this.
3879 * errno is cleared before starting so that the caller knows that if it spots an
3880 * error without errno, it's pending and can be retrieved via getsockopt(SO_ERROR).
3881 */
3882static size_t quic_conn_to_buf(struct connection *conn, void *xprt_ctx, struct buffer *buf, size_t count, int flags)
3883{
3884 ssize_t ret;
3885 size_t try, done = 0;
3886
3887 if (!conn_ctrl_ready(conn))
3888 return 0;
3889
3890 if (!fd_recv_ready(conn->handle.fd))
3891 return 0;
3892
3893 conn->flags &= ~CO_FL_WAIT_ROOM;
3894 errno = 0;
3895
3896 if (unlikely(!(fdtab[conn->handle.fd].ev & FD_POLL_IN))) {
3897 /* stop here if we reached the end of data */
3898 if ((fdtab[conn->handle.fd].ev & (FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_HUP)
3899 goto read0;
3900
3901 /* report error on POLL_ERR before connection establishment */
3902 if ((fdtab[conn->handle.fd].ev & FD_POLL_ERR) && (conn->flags & CO_FL_WAIT_L4_CONN)) {
3903 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3904 goto leave;
3905 }
3906 }
3907
3908 /* read the largest possible block. For this, we perform only one call
3909 * to recv() unless the buffer wraps and we exactly fill the first hunk,
3910 * in which case we accept to do it once again. A new attempt is made on
3911 * EINTR too.
3912 */
3913 while (count > 0) {
3914 try = b_contig_space(buf);
3915 if (!try)
3916 break;
3917
3918 if (try > count)
3919 try = count;
3920
3921 ret = recvfrom(conn->handle.fd, b_tail(buf), try, 0, NULL, 0);
3922
3923 if (ret > 0) {
3924 b_add(buf, ret);
3925 done += ret;
3926 if (ret < try) {
3927 /* unfortunately, on level-triggered events, POLL_HUP
3928 * is generally delivered AFTER the system buffer is
3929 * empty, unless the poller supports POLL_RDHUP. If
3930 * we know this is the case, we don't try to read more
3931 * as we know there's no more available. Similarly, if
3932 * there's no problem with lingering we don't even try
3933 * to read an unlikely close from the client since we'll
3934 * close first anyway.
3935 */
3936 if (fdtab[conn->handle.fd].ev & FD_POLL_HUP)
3937 goto read0;
3938
3939 if ((!fdtab[conn->handle.fd].linger_risk) ||
3940 (cur_poller.flags & HAP_POLL_F_RDHUP)) {
3941 break;
3942 }
3943 }
3944 count -= ret;
3945 }
3946 else if (ret == 0) {
3947 goto read0;
3948 }
3949 else if (errno == EAGAIN || errno == ENOTCONN) {
3950 fd_cant_recv(conn->handle.fd);
3951 break;
3952 }
3953 else if (errno != EINTR) {
3954 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3955 break;
3956 }
3957 }
3958
3959 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) && done)
3960 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3961
3962 leave:
3963 return done;
3964
3965 read0:
3966 conn_sock_read0(conn);
3967 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3968
3969 /* Now a final check for a possible asynchronous low-level error
3970 * report. This can happen when a connection receives a reset
3971 * after a shutdown, both POLL_HUP and POLL_ERR are queued, and
3972 * we might have come from there by just checking POLL_HUP instead
3973 * of recv()'s return value 0, so we have no way to tell there was
3974 * an error without checking.
3975 */
3976 if (unlikely(fdtab[conn->handle.fd].ev & FD_POLL_ERR))
3977 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3978 goto leave;
3979}
3980
3981
3982/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
3983 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
3984 * other pending data for example, but this flag is ignored at the moment.
3985 * Only one call to send() is performed, unless the buffer wraps, in which case
3986 * a second call may be performed. The connection's flags are updated with
3987 * whatever special event is detected (error, empty). The caller is responsible
3988 * for taking care of those events and avoiding the call if inappropriate. The
3989 * function does not call the connection's polling update function, so the caller
3990 * is responsible for this. It's up to the caller to update the buffer's contents
3991 * based on the return value.
3992 */
3993static size_t quic_conn_from_buf(struct connection *conn, void *xprt_ctx, const struct buffer *buf, size_t count, int flags)
3994{
3995 ssize_t ret;
3996 size_t try, done;
3997 int send_flag;
3998
3999 if (!conn_ctrl_ready(conn))
4000 return 0;
4001
4002 if (!fd_send_ready(conn->handle.fd))
4003 return 0;
4004
4005 done = 0;
4006 /* send the largest possible block. For this we perform only one call
4007 * to send() unless the buffer wraps and we exactly fill the first hunk,
4008 * in which case we accept to do it once again.
4009 */
4010 while (count) {
4011 try = b_contig_data(buf, done);
4012 if (try > count)
4013 try = count;
4014
4015 send_flag = MSG_DONTWAIT | MSG_NOSIGNAL;
4016 if (try < count || flags & CO_SFL_MSG_MORE)
4017 send_flag |= MSG_MORE;
4018
4019 ret = sendto(conn->handle.fd, b_peek(buf, done), try, send_flag,
4020 (struct sockaddr *)conn->dst, get_addr_len(conn->dst));
4021 if (ret > 0) {
4022 count -= ret;
4023 done += ret;
4024
4025 /* A send succeeded, so we can consier ourself connected */
4026 conn->flags |= CO_FL_WAIT_L4L6;
4027 /* if the system buffer is full, don't insist */
4028 if (ret < try)
4029 break;
4030 }
4031 else if (ret == 0 || errno == EAGAIN || errno == ENOTCONN || errno == EINPROGRESS) {
4032 /* nothing written, we need to poll for write first */
4033 fd_cant_send(conn->handle.fd);
4034 break;
4035 }
4036 else if (errno != EINTR) {
4037 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
4038 break;
4039 }
4040 }
4041 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) && done)
4042 conn->flags &= ~CO_FL_WAIT_L4_CONN;
4043
4044 if (done > 0) {
4045 /* we count the total bytes sent, and the send rate for 32-byte
4046 * blocks. The reason for the latter is that freq_ctr are
4047 * limited to 4GB and that it's not enough per second.
4048 */
4049 _HA_ATOMIC_ADD(&global.out_bytes, done);
4050 update_freq_ctr(&global.out_32bps, (done + 16) / 32);
4051 }
4052 return done;
4053}
4054
4055/* Initialize a QUIC connection (quic_conn struct) to be attached to <conn>
4056 * connection with <xprt_ctx> as address of the xprt context.
4057 * Returns 1 if succeeded, 0 if not.
4058 */
4059static int qc_conn_init(struct connection *conn, void **xprt_ctx)
4060{
4061 struct quic_conn_ctx *ctx;
4062
4063 TRACE_ENTER(QUIC_EV_CONN_NEW, conn);
4064
4065 if (*xprt_ctx)
4066 goto out;
4067
4068 if (!conn_ctrl_ready(conn))
4069 goto out;
4070
4071 ctx = pool_alloc(pool_head_quic_conn_ctx);
4072 if (!ctx) {
4073 conn->err_code = CO_ER_SYS_MEMLIM;
4074 goto err;
4075 }
4076
4077 ctx->wait_event.tasklet = tasklet_new();
4078 if (!ctx->wait_event.tasklet) {
4079 conn->err_code = CO_ER_SYS_MEMLIM;
4080 goto err;
4081 }
4082
4083 ctx->wait_event.tasklet->process = quic_conn_io_cb;
4084 ctx->wait_event.tasklet->context = ctx;
4085 ctx->wait_event.events = 0;
4086 ctx->conn = conn;
4087 ctx->subs = NULL;
4088 ctx->xprt_ctx = NULL;
4089
4090 ctx->xprt = xprt_get(XPRT_QUIC);
4091 if (objt_server(conn->target)) {
4092 /* Server */
4093 struct server *srv = __objt_server(conn->target);
4094 unsigned char dcid[QUIC_CID_LEN];
4095 struct quic_conn *quic_conn;
4096 int ssl_err, ipv4;
4097
4098 ssl_err = SSL_ERROR_NONE;
4099 if (RAND_bytes(dcid, sizeof dcid) != 1)
4100 goto err;
4101
4102 conn->qc = new_quic_conn(QUIC_PROTOCOL_VERSION_DRAFT_28);
4103 if (!conn->qc)
4104 goto err;
4105
4106 quic_conn = conn->qc;
4107 quic_conn->conn = conn;
4108 ipv4 = conn->dst->ss_family == AF_INET;
4109 if (!qc_new_conn_init(quic_conn, ipv4, NULL, &srv->cids,
4110 dcid, sizeof dcid, NULL, 0))
4111 goto err;
4112
4113 if (!qc_new_isecs(conn, dcid, sizeof dcid, 0))
4114 goto err;
4115
4116 ctx->state = QUIC_HS_ST_CLIENT_INITIAL;
4117 if (ssl_bio_and_sess_init(conn, srv->ssl_ctx.ctx,
4118 &ctx->ssl, &ctx->bio, ha_quic_meth, ctx) == -1)
4119 goto err;
4120
4121 quic_conn->params = srv->quic_params;
4122 /* Copy the initial source connection ID. */
4123 quic_cid_cpy(&quic_conn->params.initial_source_connection_id, &quic_conn->scid);
4124 quic_conn->enc_params_len =
4125 quic_transport_params_encode(quic_conn->enc_params,
4126 quic_conn->enc_params + sizeof quic_conn->enc_params,
4127 &quic_conn->params, 0);
4128 if (!quic_conn->enc_params_len)
4129 goto err;
4130
4131 SSL_set_quic_transport_params(ctx->ssl, quic_conn->enc_params, quic_conn->enc_params_len);
4132 SSL_set_connect_state(ctx->ssl);
4133 ssl_err = SSL_do_handshake(ctx->ssl);
4134 if (ssl_err != 1) {
4135 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
4136 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
4137 TRACE_PROTO("SSL handshake",
4138 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
4139 }
4140 else {
4141 TRACE_DEVEL("SSL handshake error",
4142 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
4143 goto err;
4144 }
4145 }
4146 }
4147 else if (objt_listener(conn->target)) {
4148 /* Listener */
4149 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
4150
4151 ctx->state = QUIC_HS_ST_SERVER_INITIAL;
4152
4153 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
4154 &ctx->ssl, &ctx->bio, ha_quic_meth, ctx) == -1)
4155 goto err;
4156
4157 SSL_set_accept_state(ctx->ssl);
4158 }
4159
4160 *xprt_ctx = ctx;
4161
4162 /* Leave init state and start handshake */
4163 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
4164 /* Start the handshake */
4165 tasklet_wakeup(ctx->wait_event.tasklet);
4166
4167 out:
4168 TRACE_LEAVE(QUIC_EV_CONN_NEW, conn);
4169
4170 return 0;
4171
4172 err:
4173 if (ctx->wait_event.tasklet)
4174 tasklet_free(ctx->wait_event.tasklet);
4175 pool_free(pool_head_quic_conn_ctx, ctx);
Frédéric Lécaille6c1e36c2020-12-23 17:17:37 +01004176 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_NEW, conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01004177 return -1;
4178}
4179
4180/* transport-layer operations for QUIC connections. */
4181static struct xprt_ops ssl_quic = {
4182 .snd_buf = quic_conn_from_buf,
4183 .rcv_buf = quic_conn_to_buf,
4184 .init = qc_conn_init,
4185 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
4186 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
4187 .name = "QUIC",
4188};
4189
4190__attribute__((constructor))
4191static void __quic_conn_init(void)
4192{
4193 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
4194 xprt_register(XPRT_QUIC, &ssl_quic);
4195}
4196
4197__attribute__((destructor))
4198static void __quic_conn_deinit(void)
4199{
4200 BIO_meth_free(ha_quic_meth);
4201}
4202
4203/* Read all the QUIC packets found in <buf> with <len> as length (typically a UDP
4204 * datagram), <ctx> being the QUIC I/O handler context, from QUIC connections,
4205 * calling <func> function;
4206 * Return the number of bytes read if succeded, -1 if not.
4207 */
4208static ssize_t quic_dgram_read(char *buf, size_t len, void *owner,
4209 struct sockaddr_storage *saddr, qpkt_read_func *func)
4210{
4211 unsigned char *pos;
4212 const unsigned char *end;
4213 struct quic_dgram_ctx dgram_ctx = {
4214 .dcid_node = NULL,
4215 .owner = owner,
4216 };
4217
4218 pos = (unsigned char *)buf;
4219 end = pos + len;
4220
4221 do {
4222 int ret;
4223 struct quic_rx_packet *pkt;
4224
4225 pkt = pool_alloc(pool_head_quic_rx_packet);
4226 if (!pkt)
4227 goto err;
4228
4229 memset(pkt, 0, sizeof(*pkt));
4230 quic_rx_packet_refinc(pkt);
4231 ret = func(&pos, end, pkt, &dgram_ctx, saddr);
4232 if (ret == -1) {
4233 size_t pkt_len;
4234
4235 pkt_len = pkt->len;
4236 free_quic_rx_packet(pkt);
4237 /* If the packet length could not be found, we cannot continue. */
4238 if (!pkt_len)
4239 break;
4240 }
4241 } while (pos < end);
4242
4243 /* Increasing the received bytes counter by the UDP datagram length
4244 * if this datagram could be associated to a connection.
4245 */
4246 if (dgram_ctx.qc)
4247 dgram_ctx.qc->rx.bytes += len;
4248
4249 return pos - (unsigned char *)buf;
4250
4251 err:
4252 return -1;
4253}
4254
4255ssize_t quic_lstnr_dgram_read(char *buf, size_t len, void *owner,
4256 struct sockaddr_storage *saddr)
4257{
4258 return quic_dgram_read(buf, len, owner, saddr, qc_lstnr_pkt_rcv);
4259}
4260
4261ssize_t quic_srv_dgram_read(char *buf, size_t len, void *owner,
4262 struct sockaddr_storage *saddr)
4263{
4264 return quic_dgram_read(buf, len, owner, saddr, qc_srv_pkt_rcv);
4265}
4266
4267/* QUIC I/O handler for connection to local listeners or remove servers
4268 * depending on <listener> boolean value, with <fd> as socket file
4269 * descriptor and <ctx> as context.
4270 */
4271static size_t quic_conn_handler(int fd, void *ctx, qpkt_read_func *func)
4272{
4273 ssize_t ret;
4274 size_t done = 0;
4275 struct buffer *buf = get_trash_chunk();
4276 /* Source address */
4277 struct sockaddr_storage saddr = {0};
4278 socklen_t saddrlen = sizeof saddr;
4279
4280 if (!fd_recv_ready(fd))
4281 return 0;
4282
4283 do {
4284 ret = recvfrom(fd, buf->area, buf->size, 0,
4285 (struct sockaddr *)&saddr, &saddrlen);
4286 if (ret < 0) {
4287 if (errno == EINTR)
4288 continue;
4289 if (errno == EAGAIN)
4290 fd_cant_recv(fd);
4291 goto out;
4292 }
4293 } while (0);
4294
4295 done = buf->data = ret;
4296 quic_dgram_read(buf->area, buf->data, ctx, &saddr, func);
4297
4298 out:
4299 return done;
4300}
4301
4302/* QUIC I/O handler for connections to local listeners with <fd> as socket
4303 * file descriptor.
4304 */
4305void quic_fd_handler(int fd)
4306{
4307 if (fdtab[fd].ev & FD_POLL_IN)
4308 quic_conn_handler(fd, fdtab[fd].owner, &qc_lstnr_pkt_rcv);
4309}
4310
4311/* QUIC I/O handler for connections to remote servers with <fd> as socket
4312 * file descriptor.
4313 */
4314void quic_conn_fd_handler(int fd)
4315{
4316 if (fdtab[fd].ev & FD_POLL_IN)
4317 quic_conn_handler(fd, fdtab[fd].owner, &qc_srv_pkt_rcv);
4318}
4319
4320/*
4321 * Local variables:
4322 * c-indent-level: 8
4323 * c-basic-offset: 8
4324 * End:
4325 */