blob: 931361cdfe5714081a6efe21eb2a73e26eda2fbe [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écaillea7e7ce92020-11-23 14:14:04 +010070 { .mask = QUIC_EV_CONN_HPKT, .name = "hdshk_pkt", .desc = "handhshake packet building" },
71 { .mask = QUIC_EV_CONN_PAPKT, .name = "phdshk_apkt", .desc = "post handhshake application packet preparation" },
72 { .mask = QUIC_EV_CONN_PAPKTS, .name = "phdshk_apkts", .desc = "post handhshake application packets preparation" },
73 { .mask = QUIC_EV_CONN_HDSHK, .name = "hdshk", .desc = "SSL handhshake processing" },
74 { .mask = QUIC_EV_CONN_RMHP, .name = "rm_hp", .desc = "Remove header protection" },
75 { .mask = QUIC_EV_CONN_PRSHPKT, .name = "parse_hpkt", .desc = "parse handshake packet" },
76 { .mask = QUIC_EV_CONN_PRSAPKT, .name = "parse_apkt", .desc = "parse application packet" },
77 { .mask = QUIC_EV_CONN_PRSFRM, .name = "parse_frm", .desc = "parse frame" },
78 { .mask = QUIC_EV_CONN_PRSAFRM, .name = "parse_ack_frm", .desc = "parse ACK frame" },
79 { .mask = QUIC_EV_CONN_BFRM, .name = "build_frm", .desc = "build frame" },
80 { .mask = QUIC_EV_CONN_PHPKTS, .name = "phdshk_pkts", .desc = "handhshake packets preparation" },
81 { .mask = QUIC_EV_CONN_TRMHP, .name = "rm_hp_try", .desc = "header protection removing try" },
82 { .mask = QUIC_EV_CONN_ELRMHP, .name = "el_rm_hp", .desc = "handshake enc. level header protection removing" },
83 { .mask = QUIC_EV_CONN_ELRXPKTS, .name = "el_treat_rx_pkts", .desc = "handshake enc. level rx packets treatment" },
84 { .mask = QUIC_EV_CONN_SSLDATA, .name = "ssl_provide_data", .desc = "CRYPTO data provision to TLS stack" },
85 { .mask = QUIC_EV_CONN_RXCDATA, .name = "el_treat_rx_cfrms",.desc = "enc. level RX CRYPTO frames processing"},
86 { .mask = QUIC_EV_CONN_ADDDATA, .name = "add_hdshk_data", .desc = "TLS stack ->add_handshake_data() call"},
87 { .mask = QUIC_EV_CONN_FFLIGHT, .name = "flush_flight", .desc = "TLS stack ->flush_flight() call"},
88 { .mask = QUIC_EV_CONN_SSLALERT, .name = "send_alert", .desc = "TLS stack ->send_alert() call"},
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +010089 { .mask = QUIC_EV_CONN_RTTUPDT, .name = "rtt_updt", .desc = "RTT sampling" },
90 { .mask = QUIC_EV_CONN_SPPKTS, .name = "sppkts", .desc = "send prepared packets" },
91 { .mask = QUIC_EV_CONN_PKTLOSS, .name = "pktloss", .desc = "detect packet loss" },
92 { .mask = QUIC_EV_CONN_STIMER, .name = "stimer", .desc = "set timer" },
93 { .mask = QUIC_EV_CONN_PTIMER, .name = "ptimer", .desc = "process timer" },
94 { .mask = QUIC_EV_CONN_SPTO, .name = "spto", .desc = "set PTO" },
95
96 { .mask = QUIC_EV_CONN_ENEW, .name = "new_conn_err", .desc = "error on new QUIC connection" },
97 { .mask = QUIC_EV_CONN_EISEC, .name = "init_secs_err", .desc = "error on initial secrets derivation" },
98 { .mask = QUIC_EV_CONN_ERSEC, .name = "read_secs_err", .desc = "error on read secrets derivation" },
99 { .mask = QUIC_EV_CONN_EWSEC, .name = "write_secs_err", .desc = "error on write secrets derivation" },
100 { .mask = QUIC_EV_CONN_ELPKT, .name = "lstnr_packet_err", .desc = "error on new listener received packet" },
101 { .mask = QUIC_EV_CONN_ESPKT, .name = "srv_packet_err", .desc = "error on new server received packet" },
102 { .mask = QUIC_EV_CONN_ECHPKT, .name = "chdshk_pkt_err", .desc = "error on clear handhshake packet building" },
103 { .mask = QUIC_EV_CONN_EHPKT, .name = "hdshk_pkt_err", .desc = "error on handhshake packet building" },
104 { .mask = QUIC_EV_CONN_EPAPKT, .name = "phdshk_apkt_err", .desc = "error on post handhshake application packet building" },
105 { /* end */ }
106};
107
108static const struct name_desc quic_trace_lockon_args[4] = {
109 /* arg1 */ { /* already used by the connection */ },
110 /* arg2 */ { .name="quic", .desc="QUIC transport" },
111 /* arg3 */ { },
112 /* arg4 */ { }
113};
114
115static const struct name_desc quic_trace_decoding[] = {
116#define QUIC_VERB_CLEAN 1
117 { .name="clean", .desc="only user-friendly stuff, generally suitable for level \"user\"" },
118 { /* end */ }
119};
120
121
122struct trace_source trace_quic = {
123 .name = IST("quic"),
124 .desc = "QUIC xprt",
125 .arg_def = TRC_ARG1_CONN, /* TRACE()'s first argument is always a connection */
126 .default_cb = quic_trace,
127 .known_events = quic_trace_events,
128 .lockon_args = quic_trace_lockon_args,
129 .decoding = quic_trace_decoding,
130 .report_events = ~0, /* report everything by default */
131};
132
133#define TRACE_SOURCE &trace_quic
134INITCALL1(STG_REGISTER, trace_register_source, TRACE_SOURCE);
135
136static BIO_METHOD *ha_quic_meth;
137
138/* QUIC xprt connection context. */
139struct quic_conn_ctx {
140 struct connection *conn;
141 SSL *ssl;
142 BIO *bio;
143 int state;
144 const struct xprt_ops *xprt;
145 void *xprt_ctx;
146 struct wait_event wait_event;
147 struct wait_event *subs;
148};
149
150DECLARE_STATIC_POOL(pool_head_quic_conn_ctx,
151 "quic_conn_ctx_pool", sizeof(struct quic_conn_ctx));
152
153DECLARE_STATIC_POOL(pool_head_quic_conn, "quic_conn", sizeof(struct quic_conn));
154
155DECLARE_POOL(pool_head_quic_connection_id,
156 "quic_connnection_id_pool", sizeof(struct quic_connection_id));
157
158DECLARE_POOL(pool_head_quic_rx_packet, "quic_rx_packet_pool", sizeof(struct quic_rx_packet));
159
160DECLARE_POOL(pool_head_quic_tx_packet, "quic_tx_packet_pool", sizeof(struct quic_tx_packet));
161
162DECLARE_STATIC_POOL(pool_head_quic_rx_crypto_frm, "quic_rx_crypto_frm_pool", sizeof(struct quic_rx_crypto_frm));
163
164DECLARE_POOL(pool_head_quic_tx_frm, "quic_tx_frm_pool", sizeof(struct quic_tx_frm));
165
166DECLARE_STATIC_POOL(pool_head_quic_crypto_buf, "quic_crypto_buf_pool", sizeof(struct quic_crypto_buf));
167
168DECLARE_STATIC_POOL(pool_head_quic_frame, "quic_frame_pool", sizeof(struct quic_frame));
169
Frédéric Lécaille8090b512020-11-30 16:19:22 +0100170DECLARE_STATIC_POOL(pool_head_quic_arng, "quic_arng_pool", sizeof(struct quic_arng_node));
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100171
172static ssize_t qc_build_hdshk_pkt(struct q_buf *buf, struct quic_conn *qc, int pkt_type,
173 struct quic_enc_level *qel);
174
175int qc_prep_phdshk_pkts(struct quic_conn *qc);
176
177/* Add traces to <buf> depending on <frm> TX frame type. */
178static inline void chunk_tx_frm_appendf(struct buffer *buf,
179 const struct quic_tx_frm *frm)
180{
181 switch (frm->type) {
182 case QUIC_FT_CRYPTO:
183 chunk_appendf(buf, " cfoff=%llu cflen=%llu",
184 (unsigned long long)frm->crypto.offset,
185 (unsigned long long)frm->crypto.len);
186 break;
187 default:
188 chunk_appendf(buf, " %s", quic_frame_type_string(frm->type));
189 }
190}
191
192/* Trace callback for QUIC.
193 * These traces always expect that arg1, if non-null, is of type connection.
194 */
195static void quic_trace(enum trace_level level, uint64_t mask, const struct trace_source *src,
196 const struct ist where, const struct ist func,
197 const void *a1, const void *a2, const void *a3, const void *a4)
198{
199 const struct connection *conn = a1;
200
201 if (conn) {
202 struct quic_tls_secrets *secs;
203 struct quic_conn *qc;
204
205 qc = conn->qc;
206 chunk_appendf(&trace_buf, " : conn@%p", conn);
207 if ((mask & QUIC_EV_CONN_INIT) && qc) {
208 chunk_appendf(&trace_buf, "\n odcid");
209 quic_cid_dump(&trace_buf, &qc->odcid);
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +0100210 chunk_appendf(&trace_buf, "\n dcid");
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100211 quic_cid_dump(&trace_buf, &qc->dcid);
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +0100212 chunk_appendf(&trace_buf, "\n scid");
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100213 quic_cid_dump(&trace_buf, &qc->scid);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100214 }
215
216 if (mask & QUIC_EV_CONN_ADDDATA) {
217 const enum ssl_encryption_level_t *level = a2;
218 const size_t *len = a3;
219
220 if (level) {
221 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
222
223 chunk_appendf(&trace_buf, " el=%c(%d)", quic_enc_level_char(lvl), lvl);
224 }
225 if (len)
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100226 chunk_appendf(&trace_buf, " len=%llu", (unsigned long long)*len);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100227 }
228 if ((mask & QUIC_EV_CONN_ISEC) && qc) {
229 /* Initial read & write secrets. */
230 enum quic_tls_enc_level level = QUIC_TLS_ENC_LEVEL_INITIAL;
231 const unsigned char *rx_sec = a2;
232 const unsigned char *tx_sec = a3;
233
234 secs = &qc->els[level].tls_ctx.rx;
235 if (secs->flags & QUIC_FL_TLS_SECRETS_SET) {
236 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(level));
237 if (rx_sec)
238 quic_tls_secret_hexdump(&trace_buf, rx_sec, 32);
239 quic_tls_keys_hexdump(&trace_buf, secs);
240 }
241 secs = &qc->els[level].tls_ctx.tx;
242 if (secs->flags & QUIC_FL_TLS_SECRETS_SET) {
243 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(level));
244 if (tx_sec)
245 quic_tls_secret_hexdump(&trace_buf, tx_sec, 32);
246 quic_tls_keys_hexdump(&trace_buf, secs);
247 }
248 }
249 if (mask & (QUIC_EV_CONN_RSEC|QUIC_EV_CONN_RWSEC)) {
250 const enum ssl_encryption_level_t *level = a2;
251 const unsigned char *secret = a3;
252 const size_t *secret_len = a4;
253
254 if (level) {
255 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
256
257 chunk_appendf(&trace_buf, "\n RX el=%c", quic_enc_level_char(lvl));
258 if (secret && secret_len)
259 quic_tls_secret_hexdump(&trace_buf, secret, *secret_len);
260 secs = &qc->els[lvl].tls_ctx.rx;
261 if (secs->flags & QUIC_FL_TLS_SECRETS_SET)
262 quic_tls_keys_hexdump(&trace_buf, secs);
263 }
264 }
265
266 if (mask & (QUIC_EV_CONN_WSEC|QUIC_EV_CONN_RWSEC)) {
267 const enum ssl_encryption_level_t *level = a2;
268 const unsigned char *secret = a3;
269 const size_t *secret_len = a4;
270
271 if (level) {
272 enum quic_tls_enc_level lvl = ssl_to_quic_enc_level(*level);
273
274 chunk_appendf(&trace_buf, "\n TX el=%c", quic_enc_level_char(lvl));
275 if (secret && secret_len)
276 quic_tls_secret_hexdump(&trace_buf, secret, *secret_len);
277 secs = &qc->els[lvl].tls_ctx.tx;
278 if (secs->flags & QUIC_FL_TLS_SECRETS_SET)
279 quic_tls_keys_hexdump(&trace_buf, secs);
280 }
281
282 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100283
Frédéric Lécaille133e8a72020-12-18 09:33:27 +0100284 if (mask & (QUIC_EV_CONN_HPKT|QUIC_EV_CONN_PAPKT)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100285 const struct quic_tx_packet *pkt = a2;
286 const struct quic_enc_level *qel = a3;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100287 const ssize_t *room = a4;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100288
289 if (qel) {
290 struct quic_pktns *pktns;
291
292 pktns = qc->pktns;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100293 chunk_appendf(&trace_buf, " qel=%c cwnd=%llu ppif=%lld pif=%llu "
294 "if=%llu pp=%u pdg=%d",
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100295 quic_enc_level_char_from_qel(qel, qc),
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100296 (unsigned long long)qc->path->cwnd,
297 (unsigned long long)qc->path->prep_in_flight,
298 (unsigned long long)qc->path->in_flight,
299 (unsigned long long)pktns->tx.in_flight,
300 pktns->tx.pto_probe, qc->tx.nb_pto_dgrams);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100301 }
302 if (pkt) {
303 const struct quic_tx_frm *frm;
304 chunk_appendf(&trace_buf, " pn=%llu cdlen=%u",
305 (unsigned long long)pkt->pn_node.key, pkt->cdata_len);
306 list_for_each_entry(frm, &pkt->frms, list)
307 chunk_tx_frm_appendf(&trace_buf, frm);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100308 chunk_appendf(&trace_buf, " tx.bytes=%llu", (unsigned long long)qc->tx.bytes);
309 }
310
311 if (room) {
312 chunk_appendf(&trace_buf, " room=%lld", (long long)*room);
313 chunk_appendf(&trace_buf, " dcid.len=%llu scid.len=%llu",
314 (unsigned long long)qc->dcid.len, (unsigned long long)qc->scid.len);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100315 }
316 }
317
318 if (mask & QUIC_EV_CONN_HDSHK) {
319 const enum quic_handshake_state *state = a2;
320 const int *err = a3;
321
322 if (state)
323 chunk_appendf(&trace_buf, " state=%s", quic_hdshk_state_str(*state));
324 if (err)
325 chunk_appendf(&trace_buf, " err=%s", ssl_error_str(*err));
326 }
327
328 if (mask & (QUIC_EV_CONN_TRMHP|QUIC_EV_CONN_ELRMHP|QUIC_EV_CONN_ESPKT|QUIC_EV_CONN_SPKT)) {
329 const struct quic_rx_packet *pkt = a2;
330 const unsigned long *pktlen = a3;
331 const SSL *ssl = a4;
332
333 if (pkt) {
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +0100334 chunk_appendf(&trace_buf, " pkt@%p el=%c",
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100335 pkt, quic_packet_type_enc_level_char(pkt->type));
336 if (pkt->pnl)
337 chunk_appendf(&trace_buf, " pnl=%u pn=%llu", pkt->pnl,
338 (unsigned long long)pkt->pn);
339 if (pkt->token_len)
340 chunk_appendf(&trace_buf, " toklen=%llu",
341 (unsigned long long)pkt->token_len);
342 if (pkt->aad_len)
343 chunk_appendf(&trace_buf, " aadlen=%llu",
344 (unsigned long long)pkt->aad_len);
345 chunk_appendf(&trace_buf, " flags=0x%x len=%llu",
346 pkt->flags, (unsigned long long)pkt->len);
347 }
348 if (pktlen)
349 chunk_appendf(&trace_buf, " (%ld)", *pktlen);
350 if (ssl) {
351 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
352 chunk_appendf(&trace_buf, " el=%c",
353 quic_enc_level_char(ssl_to_quic_enc_level(level)));
354 }
355 }
356
357 if (mask & (QUIC_EV_CONN_ELRXPKTS|QUIC_EV_CONN_PRSHPKT|QUIC_EV_CONN_SSLDATA)) {
358 const struct quic_rx_packet *pkt = a2;
359 const struct quic_rx_crypto_frm *cf = a3;
360 const SSL *ssl = a4;
361
362 if (pkt)
363 chunk_appendf(&trace_buf, " pkt@%p el=%c pn=%llu", pkt,
364 quic_packet_type_enc_level_char(pkt->type),
365 (unsigned long long)pkt->pn);
366 if (cf)
367 chunk_appendf(&trace_buf, " cfoff=%llu cflen=%llu",
368 (unsigned long long)cf->offset_node.key,
369 (unsigned long long)cf->len);
370 if (ssl) {
371 enum ssl_encryption_level_t level = SSL_quic_read_level(ssl);
372 chunk_appendf(&trace_buf, " el=%c",
373 quic_enc_level_char(ssl_to_quic_enc_level(level)));
374 }
375 }
376
377 if (mask & (QUIC_EV_CONN_PRSFRM|QUIC_EV_CONN_BFRM)) {
378 const struct quic_frame *frm = a2;
379
380 if (frm)
381 chunk_appendf(&trace_buf, " %s", quic_frame_type_string(frm->type));
382 }
383
384 if (mask & QUIC_EV_CONN_PHPKTS) {
385 const struct quic_enc_level *qel = a2;
386
387 if (qel) {
388 struct quic_pktns *pktns;
389
390 pktns = qc->pktns;
391 chunk_appendf(&trace_buf,
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100392 " 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 +0100393 quic_enc_level_char_from_qel(qel, qc),
394 !!(pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED),
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100395 (unsigned long long)qc->path->cwnd,
396 (unsigned long long)qc->path->prep_in_flight,
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100397 (unsigned long long)qc->path->in_flight,
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100398 (unsigned long long)pktns->tx.in_flight, pktns->tx.pto_probe,
399 (unsigned long long)qc->tx.nb_pto_dgrams);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100400 }
401 }
402
403 if (mask & QUIC_EV_CONN_RMHP) {
404 const struct quic_rx_packet *pkt = a2;
405
406 if (pkt) {
407 const int *ret = a3;
408
409 chunk_appendf(&trace_buf, " pkt@%p", pkt);
410 if (ret && *ret)
411 chunk_appendf(&trace_buf, " pnl=%u pn=%llu",
412 pkt->pnl, (unsigned long long)pkt->pn);
413 }
414 }
415
416 if (mask & QUIC_EV_CONN_PRSAFRM) {
417 const struct quic_tx_frm *frm = a2;
418 const unsigned long *val1 = a3;
419 const unsigned long *val2 = a4;
420
421 if (frm)
422 chunk_tx_frm_appendf(&trace_buf, frm);
423 if (val1)
424 chunk_appendf(&trace_buf, " %lu", *val1);
425 if (val2)
426 chunk_appendf(&trace_buf, "..%lu", *val2);
427 }
428
429 if (mask & QUIC_EV_CONN_RTTUPDT) {
430 const unsigned int *rtt_sample = a2;
431 const unsigned int *ack_delay = a3;
432 const struct quic_loss *ql = a4;
433
434 if (rtt_sample)
435 chunk_appendf(&trace_buf, " rtt_sample=%ums", *rtt_sample);
436 if (ack_delay)
437 chunk_appendf(&trace_buf, " ack_delay=%ums", *ack_delay);
438 if (ql)
439 chunk_appendf(&trace_buf,
440 " srtt=%ums rttvar=%ums min_rtt=%ums",
441 ql->srtt >> 3, ql->rtt_var >> 2, ql->rtt_min);
442 }
443 if (mask & QUIC_EV_CONN_CC) {
444 const struct quic_cc_event *ev = a2;
445 const struct quic_cc *cc = a3;
446
447 if (a2)
448 quic_cc_event_trace(&trace_buf, ev);
449 if (a3)
450 quic_cc_state_trace(&trace_buf, cc);
451 }
452
453 if (mask & QUIC_EV_CONN_PKTLOSS) {
454 const struct quic_pktns *pktns = a2;
455 const struct list *lost_pkts = a3;
456 struct quic_conn *qc = conn->qc;
457
458 if (pktns) {
459 chunk_appendf(&trace_buf, " pktns=%s",
460 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
461 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H");
462 if (pktns->tx.loss_time)
463 chunk_appendf(&trace_buf, " loss_time=%dms",
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100464 TICKS_TO_MS(tick_remain(now_ms, pktns->tx.loss_time)));
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100465 }
466 if (lost_pkts && !LIST_ISEMPTY(lost_pkts)) {
467 struct quic_tx_packet *pkt;
468
469 chunk_appendf(&trace_buf, " lost_pkts:");
470 list_for_each_entry(pkt, lost_pkts, list)
471 chunk_appendf(&trace_buf, " %lu", (unsigned long)pkt->pn_node.key);
472 }
473 }
474
475 if (mask & (QUIC_EV_CONN_STIMER|QUIC_EV_CONN_PTIMER|QUIC_EV_CONN_SPTO)) {
476 struct quic_conn *qc = conn->qc;
477 const struct quic_pktns *pktns = a2;
478 const int *duration = a3;
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100479 const uint64_t *ifae_pkts = a4;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100480
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100481 if (ifae_pkts)
482 chunk_appendf(&trace_buf, " ifae_pkts=%llu",
483 (unsigned long long)*ifae_pkts);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100484 if (pktns) {
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100485 chunk_appendf(&trace_buf, " pktns=%s pp=%d",
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100486 pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100487 pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
488 pktns->tx.pto_probe);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100489 if (mask & QUIC_EV_CONN_STIMER) {
490 if (pktns->tx.loss_time)
491 chunk_appendf(&trace_buf, " loss_time=%dms",
492 TICKS_TO_MS(pktns->tx.loss_time - now_ms));
493 }
494 if (mask & QUIC_EV_CONN_SPTO) {
495 if (pktns->tx.time_of_last_eliciting)
496 chunk_appendf(&trace_buf, " tole=%dms",
497 TICKS_TO_MS(pktns->tx.time_of_last_eliciting - now_ms));
498 if (duration)
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +0100499 chunk_appendf(&trace_buf, " dur=%dms", TICKS_TO_MS(*duration));
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100500 }
501 }
502
503 if (!(mask & QUIC_EV_CONN_SPTO) && qc->timer_task) {
504 chunk_appendf(&trace_buf,
505 " expire=%dms", TICKS_TO_MS(qc->timer - now_ms));
506 }
507 }
508
509 if (mask & QUIC_EV_CONN_SPPKTS) {
510 const struct quic_tx_packet *pkt = a2;
511
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100512 chunk_appendf(&trace_buf, " cwnd=%llu ppif=%llu pif=%llu",
513 (unsigned long long)qc->path->cwnd,
514 (unsigned long long)qc->path->prep_in_flight,
515 (unsigned long long)qc->path->in_flight);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100516 if (pkt) {
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100517 chunk_appendf(&trace_buf, " pn=%lu(%s) iflen=%llu cdlen=%llu",
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100518 (unsigned long)pkt->pn_node.key,
519 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_INITIAL] ? "I" :
520 pkt->pktns == &qc->pktns[QUIC_TLS_PKTNS_01RTT] ? "01RTT": "H",
Frédéric Lécaille04ffb662020-12-08 15:58:39 +0100521 (unsigned long long)pkt->in_flight_len,
522 (unsigned long long)pkt->cdata_len);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100523 }
524 }
Frédéric Lécaille47c433f2020-12-10 17:03:11 +0100525
526 if (mask & QUIC_EV_CONN_SSLALERT) {
527 const uint8_t *alert = a2;
528 const enum ssl_encryption_level_t *level = a3;
529
530 if (alert)
531 chunk_appendf(&trace_buf, " alert=0x%02x", *alert);
532 if (level)
533 chunk_appendf(&trace_buf, " el=%c",
534 quic_enc_level_char(ssl_to_quic_enc_level(*level)));
535 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100536 }
537 if (mask & QUIC_EV_CONN_LPKT) {
538 const struct quic_rx_packet *pkt = a2;
539
540 if (conn)
541 chunk_appendf(&trace_buf, " xprt_ctx@%p", conn->xprt_ctx);
542 if (pkt)
543 chunk_appendf(&trace_buf, " type=0x%02x %s",
544 pkt->type, qc_pkt_long(pkt) ? "long" : "short");
545 }
546
547}
548
549/* Returns 1 if the peer has validated <qc> QUIC connection address, 0 if not. */
550static inline int quic_peer_validated_addr(struct quic_conn_ctx *ctx)
551{
552 struct quic_conn *qc;
553
554 qc = ctx->conn->qc;
555 if (objt_server(qc->conn->target))
556 return 1;
557
558 if ((qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns->flags & QUIC_FL_PKTNS_ACK_RECEIVED) ||
559 (qc->els[QUIC_TLS_ENC_LEVEL_APP].pktns->flags & QUIC_FL_PKTNS_ACK_RECEIVED) ||
560 (ctx->state & QUIC_HS_ST_COMPLETE))
561 return 1;
562
563 return 0;
564}
565
566/* Set the timer attached to the QUIC connection with <ctx> as I/O handler and used for
567 * both loss detection and PTO and schedule the task assiated to this timer if needed.
568 */
569static inline void qc_set_timer(struct quic_conn_ctx *ctx)
570{
571 struct quic_conn *qc;
572 struct quic_pktns *pktns;
573 unsigned int pto;
574
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100575 TRACE_ENTER(QUIC_EV_CONN_STIMER, ctx->conn,
576 NULL, NULL, &ctx->conn->qc->path->ifae_pkts);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100577 qc = ctx->conn->qc;
578 pktns = quic_loss_pktns(qc);
579 if (tick_isset(pktns->tx.loss_time)) {
580 qc->timer = pktns->tx.loss_time;
581 goto out;
582 }
583
584 /* XXX TODO: anti-amplification: the timer must be
585 * cancelled for a server which reached the anti-amplification limit.
586 */
587
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +0100588 if (!qc->path->ifae_pkts && quic_peer_validated_addr(ctx)) {
589 TRACE_PROTO("timer cancellation", QUIC_EV_CONN_STIMER, ctx->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100590 /* Timer cancellation. */
591 qc->timer = TICK_ETERNITY;
592 goto out;
593 }
594
595 pktns = quic_pto_pktns(qc, ctx->state & QUIC_HS_ST_COMPLETE, &pto);
596 if (tick_isset(pto))
597 qc->timer = pto;
598 out:
599 task_schedule(qc->timer_task, qc->timer);
600 TRACE_LEAVE(QUIC_EV_CONN_STIMER, ctx->conn, pktns);
601}
602
603#ifndef OPENSSL_IS_BORINGSSL
604int ha_quic_set_encryption_secrets(SSL *ssl, enum ssl_encryption_level_t level,
605 const uint8_t *read_secret,
606 const uint8_t *write_secret, size_t secret_len)
607{
608 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
609 struct quic_tls_ctx *tls_ctx =
610 &conn->qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
611 const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
612
613 TRACE_ENTER(QUIC_EV_CONN_RWSEC, conn);
614 tls_ctx->rx.aead = tls_ctx->tx.aead = tls_aead(cipher);
615 tls_ctx->rx.md = tls_ctx->tx.md = tls_md(cipher);
616 tls_ctx->rx.hp = tls_ctx->tx.hp = tls_hp(cipher);
617
618 if (!quic_tls_derive_keys(tls_ctx->rx.aead, tls_ctx->rx.hp, tls_ctx->rx.md,
619 tls_ctx->rx.key, sizeof tls_ctx->rx.key,
620 tls_ctx->rx.iv, sizeof tls_ctx->rx.iv,
621 tls_ctx->rx.hp_key, sizeof tls_ctx->rx.hp_key,
622 read_secret, secret_len)) {
623 TRACE_DEVEL("RX key derivation failed", QUIC_EV_CONN_RWSEC, conn);
624 return 0;
625 }
626
627 tls_ctx->rx.flags |= QUIC_FL_TLS_SECRETS_SET;
628 if (!quic_tls_derive_keys(tls_ctx->tx.aead, tls_ctx->tx.hp, tls_ctx->tx.md,
629 tls_ctx->tx.key, sizeof tls_ctx->tx.key,
630 tls_ctx->tx.iv, sizeof tls_ctx->tx.iv,
631 tls_ctx->tx.hp_key, sizeof tls_ctx->tx.hp_key,
632 write_secret, secret_len)) {
633 TRACE_DEVEL("TX key derivation failed", QUIC_EV_CONN_RWSEC, conn);
634 return 0;
635 }
636
637 tls_ctx->tx.flags |= QUIC_FL_TLS_SECRETS_SET;
638 if (objt_server(conn->target) && level == ssl_encryption_application) {
639 const unsigned char *buf;
640 size_t buflen;
641
642 SSL_get_peer_quic_transport_params(ssl, &buf, &buflen);
643 if (!buflen)
644 return 0;
645
646 if (!quic_transport_params_store(conn->qc, 1, buf, buf + buflen))
647 return 0;
648 }
649 TRACE_LEAVE(QUIC_EV_CONN_RWSEC, conn, &level);
650
651 return 1;
652}
653#else
654/* ->set_read_secret callback to derive the RX secrets at <level> encryption
655 * level.
656 * Returns 1 if succedded, 0 if not.
657 */
658int ha_set_rsec(SSL *ssl, enum ssl_encryption_level_t level,
659 const SSL_CIPHER *cipher,
660 const uint8_t *secret, size_t secret_len)
661{
662 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
663 struct quic_tls_ctx *tls_ctx =
664 &conn->qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
665
666 TRACE_ENTER(QUIC_EV_CONN_RSEC, conn);
667 tls_ctx->rx.aead = tls_aead(cipher);
668 tls_ctx->rx.md = tls_md(cipher);
669 tls_ctx->rx.hp = tls_hp(cipher);
670
671 if (!quic_tls_derive_keys(tls_ctx->rx.aead, tls_ctx->rx.hp, tls_ctx->rx.md,
672 tls_ctx->rx.key, sizeof tls_ctx->rx.key,
673 tls_ctx->rx.iv, sizeof tls_ctx->rx.iv,
674 tls_ctx->rx.hp_key, sizeof tls_ctx->rx.hp_key,
675 secret, secret_len)) {
676 TRACE_DEVEL("RX key derivation failed", QUIC_EV_CONN_RSEC, conn);
677 goto err;
678 }
679
680 if (objt_server(conn->target) && level == ssl_encryption_application) {
681 const unsigned char *buf;
682 size_t buflen;
683
684 SSL_get_peer_quic_transport_params(ssl, &buf, &buflen);
685 if (!buflen)
686 goto err;
687
688 if (!quic_transport_params_store(conn->qc, 1, buf, buf + buflen))
689 goto err;
690 }
691
692 tls_ctx->rx.flags |= QUIC_FL_TLS_SECRETS_SET;
693 TRACE_LEAVE(QUIC_EV_CONN_RSEC, conn, &level, secret, &secret_len);
694
695 return 1;
696
697 err:
698 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_ERSEC, conn);
699 return 0;
700}
701
702/* ->set_write_secret callback to derive the TX secrets at <level>
703 * encryption level.
704 * Returns 1 if succedded, 0 if not.
705 */
706int ha_set_wsec(SSL *ssl, enum ssl_encryption_level_t level,
707 const SSL_CIPHER *cipher,
708 const uint8_t *secret, size_t secret_len)
709{
710 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
711 struct quic_tls_ctx *tls_ctx =
712 &conn->qc->els[ssl_to_quic_enc_level(level)].tls_ctx;
713
714 TRACE_ENTER(QUIC_EV_CONN_WSEC, conn);
715 tls_ctx->tx.aead = tls_aead(cipher);
716 tls_ctx->tx.md = tls_md(cipher);
717 tls_ctx->tx.hp = tls_hp(cipher);
718
719 if (!quic_tls_derive_keys(tls_ctx->tx.aead, tls_ctx->tx.hp, tls_ctx->tx.md,
720 tls_ctx->tx.key, sizeof tls_ctx->tx.key,
721 tls_ctx->tx.iv, sizeof tls_ctx->tx.iv,
722 tls_ctx->tx.hp_key, sizeof tls_ctx->tx.hp_key,
723 secret, secret_len)) {
724 TRACE_DEVEL("TX key derivation failed", QUIC_EV_CONN_WSEC, conn);
725 goto err;
726 }
727
728 tls_ctx->tx.flags |= QUIC_FL_TLS_SECRETS_SET;
729 TRACE_LEAVE(QUIC_EV_CONN_WSEC, conn, &level, secret, &secret_len);
730
731 return 1;
732
733 err:
734 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_EWSEC, conn);
735 return 0;
736}
737#endif
738
739/* This function copies the CRYPTO data provided by the TLS stack found at <data>
740 * with <len> as size in CRYPTO buffers dedicated to store the information about
741 * outgoing CRYPTO frames so that to be able to replay the CRYPTO data streams.
742 * It fails only if it could not managed to allocate enough CRYPTO buffers to
743 * store all the data.
744 * Note that CRYPTO data may exist at any encryption level except at 0-RTT.
745 */
746static int quic_crypto_data_cpy(struct quic_enc_level *qel,
747 const unsigned char *data, size_t len)
748{
749 struct quic_crypto_buf **qcb;
750 /* The remaining byte to store in CRYPTO buffers. */
751 size_t cf_offset, cf_len, *nb_buf;
752 unsigned char *pos;
753
754 nb_buf = &qel->tx.crypto.nb_buf;
755 qcb = &qel->tx.crypto.bufs[*nb_buf - 1];
756 cf_offset = (*nb_buf - 1) * QUIC_CRYPTO_BUF_SZ + (*qcb)->sz;
757 cf_len = len;
758
759 while (len) {
760 size_t to_copy, room;
761
762 pos = (*qcb)->data + (*qcb)->sz;
763 room = QUIC_CRYPTO_BUF_SZ - (*qcb)->sz;
764 to_copy = len > room ? room : len;
765 if (to_copy) {
766 memcpy(pos, data, to_copy);
767 /* Increment the total size of this CRYPTO buffers by <to_copy>. */
768 qel->tx.crypto.sz += to_copy;
769 (*qcb)->sz += to_copy;
770 pos += to_copy;
771 len -= to_copy;
772 data += to_copy;
773 }
774 else {
775 struct quic_crypto_buf **tmp;
776
777 tmp = realloc(qel->tx.crypto.bufs,
778 (*nb_buf + 1) * sizeof *qel->tx.crypto.bufs);
779 if (tmp) {
780 qel->tx.crypto.bufs = tmp;
781 qcb = &qel->tx.crypto.bufs[*nb_buf];
782 *qcb = pool_alloc(pool_head_quic_crypto_buf);
783 if (!*qcb)
784 return 0;
785
786 (*qcb)->sz = 0;
787 ++*nb_buf;
788 }
789 else {
790 break;
791 }
792 }
793 }
794
795 /* Allocate a TX CRYPTO frame only if all the CRYPTO data
796 * have been buffered.
797 */
798 if (!len) {
799 struct quic_tx_frm *frm;
800
801 frm = pool_alloc(pool_head_quic_tx_frm);
802 if (!frm)
803 return 0;
804
805 frm->type = QUIC_FT_CRYPTO;
806 frm->crypto.offset = cf_offset;
807 frm->crypto.len = cf_len;
808 LIST_ADDQ(&qel->pktns->tx.frms, &frm->list);
809 }
810
811 return len == 0;
812}
813
814
815/* ->add_handshake_data QUIC TLS callback used by the QUIC TLS stack when it
816 * wants to provide the QUIC layer with CRYPTO data.
817 * Returns 1 if succeeded, 0 if not.
818 */
819int ha_quic_add_handshake_data(SSL *ssl, enum ssl_encryption_level_t level,
820 const uint8_t *data, size_t len)
821{
822 struct connection *conn;
823 enum quic_tls_enc_level tel;
824 struct quic_enc_level *qel;
825
826 conn = SSL_get_ex_data(ssl, ssl_app_data_index);
827 TRACE_ENTER(QUIC_EV_CONN_ADDDATA, conn);
828 tel = ssl_to_quic_enc_level(level);
829 qel = &conn->qc->els[tel];
830
831 if (tel == -1) {
832 TRACE_PROTO("Wrong encryption level", QUIC_EV_CONN_ADDDATA, conn);
833 goto err;
834 }
835
836 if (!quic_crypto_data_cpy(qel, data, len)) {
837 TRACE_PROTO("Could not bufferize", QUIC_EV_CONN_ADDDATA, conn);
838 goto err;
839 }
840
841 TRACE_PROTO("CRYPTO data buffered", QUIC_EV_CONN_ADDDATA,
842 conn, &level, &len);
843
844 TRACE_LEAVE(QUIC_EV_CONN_ADDDATA, conn);
845 return 1;
846
847 err:
848 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_ADDDATA, conn);
849 return 0;
850}
851
852int ha_quic_flush_flight(SSL *ssl)
853{
854 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
855
856 TRACE_ENTER(QUIC_EV_CONN_FFLIGHT, conn);
857 TRACE_LEAVE(QUIC_EV_CONN_FFLIGHT, conn);
858
859 return 1;
860}
861
862int ha_quic_send_alert(SSL *ssl, enum ssl_encryption_level_t level, uint8_t alert)
863{
864 struct connection *conn = SSL_get_ex_data(ssl, ssl_app_data_index);
865
Frédéric Lécaille47c433f2020-12-10 17:03:11 +0100866 TRACE_DEVEL("SSL alert", QUIC_EV_CONN_SSLALERT, conn, &alert, &level);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +0100867 return 1;
868}
869
870/* QUIC TLS methods */
871static SSL_QUIC_METHOD ha_quic_method = {
872#ifdef OPENSSL_IS_BORINGSSL
873 .set_read_secret = ha_set_rsec,
874 .set_write_secret = ha_set_wsec,
875#else
876 .set_encryption_secrets = ha_quic_set_encryption_secrets,
877#endif
878 .add_handshake_data = ha_quic_add_handshake_data,
879 .flush_flight = ha_quic_flush_flight,
880 .send_alert = ha_quic_send_alert,
881};
882
883/* Initialize the TLS context of a listener with <bind_conf> as configuration.
884 * Returns an error count.
885 */
886int ssl_quic_initial_ctx(struct bind_conf *bind_conf)
887{
888 struct proxy *curproxy = bind_conf->frontend;
889 struct ssl_bind_conf __maybe_unused *ssl_conf_cur;
890 int cfgerr = 0;
891
892#if 0
893 /* XXX Did not manage to use this. */
894 const char *ciphers =
895 "TLS_AES_128_GCM_SHA256:"
896 "TLS_AES_256_GCM_SHA384:"
897 "TLS_CHACHA20_POLY1305_SHA256:"
898 "TLS_AES_128_CCM_SHA256";
899#endif
900 const char *groups = "P-256:X25519:P-384:P-521";
901 long options =
902 (SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) |
903 SSL_OP_SINGLE_ECDH_USE |
904 SSL_OP_CIPHER_SERVER_PREFERENCE;
905 SSL_CTX *ctx;
906
907 ctx = SSL_CTX_new(TLS_server_method());
908 bind_conf->initial_ctx = ctx;
909
910 SSL_CTX_set_options(ctx, options);
911#if 0
912 if (SSL_CTX_set_cipher_list(ctx, ciphers) != 1) {
913 ha_alert("Proxy '%s': unable to set TLS 1.3 cipher list to '%s' "
914 "for bind '%s' at [%s:%d].\n",
915 curproxy->id, ciphers,
916 bind_conf->arg, bind_conf->file, bind_conf->line);
917 cfgerr++;
918 }
919#endif
920
921 if (SSL_CTX_set1_curves_list(ctx, groups) != 1) {
922 ha_alert("Proxy '%s': unable to set TLS 1.3 curves list to '%s' "
923 "for bind '%s' at [%s:%d].\n",
924 curproxy->id, groups,
925 bind_conf->arg, bind_conf->file, bind_conf->line);
926 cfgerr++;
927 }
928
929 SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS);
930 SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
931 SSL_CTX_set_max_proto_version(ctx, TLS1_3_VERSION);
932 SSL_CTX_set_default_verify_paths(ctx);
933
934#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
935#ifdef OPENSSL_IS_BORINGSSL
936 SSL_CTX_set_select_certificate_cb(ctx, ssl_sock_switchctx_cbk);
937 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
938#elif (HA_OPENSSL_VERSION_NUMBER >= 0x10101000L)
939 if (bind_conf->ssl_conf.early_data) {
940 SSL_CTX_set_options(ctx, SSL_OP_NO_ANTI_REPLAY);
941 SSL_CTX_set_max_early_data(ctx, global.tune.bufsize - global.tune.maxrewrite);
942 }
943 SSL_CTX_set_client_hello_cb(ctx, ssl_sock_switchctx_cbk, NULL);
944 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_err_cbk);
945#else
946 SSL_CTX_set_tlsext_servername_callback(ctx, ssl_sock_switchctx_cbk);
947#endif
948 SSL_CTX_set_tlsext_servername_arg(ctx, bind_conf);
949#endif
950 SSL_CTX_set_quic_method(ctx, &ha_quic_method);
951
952 return cfgerr;
953}
954
955/* Decode an expected packet number from <truncated_on> its truncated value,
956 * depending on <largest_pn> the largest received packet number, and <pn_nbits>
957 * the number of bits used to encode this packet number (its length in bytes * 8).
958 * See https://quicwg.org/base-drafts/draft-ietf-quic-transport.html#packet-encoding
959 */
960static uint64_t decode_packet_number(uint64_t largest_pn,
961 uint32_t truncated_pn, unsigned int pn_nbits)
962{
963 uint64_t expected_pn = largest_pn + 1;
964 uint64_t pn_win = (uint64_t)1 << pn_nbits;
965 uint64_t pn_hwin = pn_win / 2;
966 uint64_t pn_mask = pn_win - 1;
967 uint64_t candidate_pn;
968
969
970 candidate_pn = (expected_pn & ~pn_mask) | truncated_pn;
971 /* Note that <pn_win> > <pn_hwin>. */
972 if (candidate_pn < QUIC_MAX_PACKET_NUM - pn_win &&
973 candidate_pn + pn_hwin <= expected_pn)
974 return candidate_pn + pn_win;
975
976 if (candidate_pn > expected_pn + pn_hwin && candidate_pn >= pn_win)
977 return candidate_pn - pn_win;
978
979 return candidate_pn;
980}
981
982/* Remove the header protection of <pkt> QUIC packet using <tls_ctx> as QUIC TLS
983 * cryptographic context.
984 * <largest_pn> is the largest received packet number and <pn> the address of
985 * the packet number field for this packet with <byte0> address of its first byte.
986 * <end> points to one byte past the end of this packet.
987 * Returns 1 if succeeded, 0 if not.
988 */
989static int qc_do_rm_hp(struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx,
990 int64_t largest_pn, unsigned char *pn,
991 unsigned char *byte0, const unsigned char *end,
992 struct quic_conn_ctx *ctx)
993{
994 int ret, outlen, i, pnlen;
995 uint64_t packet_number;
996 uint32_t truncated_pn = 0;
997 unsigned char mask[5] = {0};
998 unsigned char *sample;
999 EVP_CIPHER_CTX *cctx;
1000 unsigned char *hp_key;
1001
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001002 /* Check there is enough data in this packet. */
1003 if (end - pn < QUIC_PACKET_PN_MAXLEN + sizeof mask) {
1004 TRACE_DEVEL("too short packet", QUIC_EV_CONN_RMHP, ctx->conn, pkt);
1005 return 0;
1006 }
1007
1008 cctx = EVP_CIPHER_CTX_new();
1009 if (!cctx) {
1010 TRACE_DEVEL("memory allocation failed", QUIC_EV_CONN_RMHP, ctx->conn, pkt);
1011 return 0;
1012 }
1013
1014 ret = 0;
1015 sample = pn + QUIC_PACKET_PN_MAXLEN;
1016
1017 hp_key = tls_ctx->rx.hp_key;
1018 if (!EVP_DecryptInit_ex(cctx, tls_ctx->rx.hp, NULL, hp_key, sample) ||
1019 !EVP_DecryptUpdate(cctx, mask, &outlen, mask, sizeof mask) ||
1020 !EVP_DecryptFinal_ex(cctx, mask, &outlen)) {
1021 TRACE_DEVEL("decryption failed", QUIC_EV_CONN_RMHP, ctx->conn, pkt);
1022 goto out;
1023 }
1024
1025 *byte0 ^= mask[0] & (*byte0 & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
1026 pnlen = (*byte0 & QUIC_PACKET_PNL_BITMASK) + 1;
1027 for (i = 0; i < pnlen; i++) {
1028 pn[i] ^= mask[i + 1];
1029 truncated_pn = (truncated_pn << 8) | pn[i];
1030 }
1031
1032 packet_number = decode_packet_number(largest_pn, truncated_pn, pnlen * 8);
1033 /* Store remaining information for this unprotected header */
1034 pkt->pn = packet_number;
1035 pkt->pnl = pnlen;
1036
1037 ret = 1;
1038
1039 out:
1040 EVP_CIPHER_CTX_free(cctx);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001041
1042 return ret;
1043}
1044
1045/* Encrypt the payload of a QUIC packet with <pn> as number found at <payload>
1046 * address, with <payload_len> as payload length, <aad> as address of
1047 * the ADD and <aad_len> as AAD length depending on the <tls_ctx> QUIC TLS
1048 * context.
1049 * Returns 1 if succeeded, 0 if not.
1050 */
1051static int quic_packet_encrypt(unsigned char *payload, size_t payload_len,
1052 unsigned char *aad, size_t aad_len, uint64_t pn,
1053 struct quic_tls_ctx *tls_ctx, struct connection *conn)
1054{
1055 unsigned char iv[12];
1056 unsigned char *tx_iv = tls_ctx->tx.iv;
1057 size_t tx_iv_sz = sizeof tls_ctx->tx.iv;
1058
1059 if (!quic_aead_iv_build(iv, sizeof iv, tx_iv, tx_iv_sz, pn)) {
1060 TRACE_DEVEL("AEAD IV building for encryption failed", QUIC_EV_CONN_HPKT, conn);
1061 return 0;
1062 }
1063
1064 if (!quic_tls_encrypt(payload, payload_len, aad, aad_len,
1065 tls_ctx->tx.aead, tls_ctx->tx.key, iv)) {
1066 TRACE_DEVEL("QUIC packet encryption failed", QUIC_EV_CONN_HPKT, conn);
1067 return 0;
1068 }
1069
1070 return 1;
1071}
1072
1073/* Decrypt <pkt> QUIC packet with <tls_ctx> as QUIC TLS cryptographic context.
1074 * Returns 1 if succeeded, 0 if not.
1075 */
1076static int qc_pkt_decrypt(struct quic_rx_packet *pkt, struct quic_tls_ctx *tls_ctx)
1077{
1078 int ret;
1079 unsigned char iv[12];
1080 unsigned char *rx_iv = tls_ctx->rx.iv;
1081 size_t rx_iv_sz = sizeof tls_ctx->rx.iv;
1082
1083 if (!quic_aead_iv_build(iv, sizeof iv, rx_iv, rx_iv_sz, pkt->pn))
1084 return 0;
1085
1086 ret = quic_tls_decrypt(pkt->data + pkt->aad_len, pkt->len - pkt->aad_len,
1087 pkt->data, pkt->aad_len,
1088 tls_ctx->rx.aead, tls_ctx->rx.key, iv);
1089 if (!ret)
1090 return 0;
1091
1092 /* Update the packet length (required to parse the frames). */
1093 pkt->len = pkt->aad_len + ret;
1094
1095 return 1;
1096}
1097
1098/* Treat <frm> frame whose packet it is attached to has just been acknowledged. */
1099static inline void qc_treat_acked_tx_frm(struct quic_tx_frm *frm,
1100 struct quic_conn_ctx *ctx)
1101{
1102 TRACE_PROTO("Removing frame", QUIC_EV_CONN_PRSAFRM, ctx->conn, frm);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001103 LIST_DEL(&frm->list);
1104 pool_free(pool_head_quic_tx_frm, frm);
1105}
1106
1107/* Remove <largest> down to <smallest> node entries from <pkts> tree of TX packet,
1108 * deallocating them, and their TX frames.
1109 * Returns the last node reached to be used for the next range.
1110 * May be NULL if <largest> node could not be found.
1111 */
1112static inline struct eb64_node *qc_ackrng_pkts(struct eb_root *pkts, unsigned int *pkt_flags,
1113 struct list *newly_acked_pkts,
1114 struct eb64_node *largest_node,
1115 uint64_t largest, uint64_t smallest,
1116 struct quic_conn_ctx *ctx)
1117{
1118 struct eb64_node *node;
1119 struct quic_tx_packet *pkt;
1120
1121 if (largest_node)
1122 node = largest_node;
1123 else {
1124 node = eb64_lookup(pkts, largest);
1125 while (!node && largest > smallest) {
1126 node = eb64_lookup(pkts, --largest);
1127 }
1128 }
1129
1130 while (node && node->key >= smallest) {
1131 struct quic_tx_frm *frm, *frmbak;
1132
1133 pkt = eb64_entry(&node->node, struct quic_tx_packet, pn_node);
1134 *pkt_flags |= pkt->flags;
1135 LIST_ADD(newly_acked_pkts, &pkt->list);
1136 TRACE_PROTO("Removing packet #", QUIC_EV_CONN_PRSAFRM, ctx->conn,, &pkt->pn_node.key);
1137 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1138 qc_treat_acked_tx_frm(frm, ctx);
1139 node = eb64_prev(node);
1140 eb64_delete(&pkt->pn_node);
1141 }
1142
1143 return node;
1144}
1145
1146/* Treat <frm> frame whose packet it is attached to has just been detected as non
1147 * acknowledged.
1148 */
1149static inline void qc_treat_nacked_tx_frm(struct quic_tx_frm *frm,
1150 struct quic_pktns *pktns,
1151 struct quic_conn_ctx *ctx)
1152{
1153 TRACE_PROTO("to resend frame", QUIC_EV_CONN_PRSAFRM, ctx->conn, frm);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001154 LIST_DEL(&frm->list);
1155 LIST_ADD(&pktns->tx.frms, &frm->list);
1156}
1157
1158
1159/* Free the TX packets of <pkts> list */
1160static inline void free_quic_tx_pkts(struct list *pkts)
1161{
1162 struct quic_tx_packet *pkt, *tmp;
1163
1164 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1165 LIST_DEL(&pkt->list);
1166 eb64_delete(&pkt->pn_node);
1167 pool_free(pool_head_quic_tx_packet, pkt);
1168 }
1169}
1170
1171/* Send a packet loss event nofification to the congestion controller
1172 * attached to <qc> connection with <lost_bytes> the number of lost bytes,
1173 * <oldest_lost>, <newest_lost> the oldest lost packet and newest lost packet
1174 * at <now_us> current time.
1175 * Always succeeds.
1176 */
1177static inline void qc_cc_loss_event(struct quic_conn *qc,
1178 unsigned int lost_bytes,
1179 unsigned int newest_time_sent,
1180 unsigned int period,
1181 unsigned int now_us)
1182{
1183 struct quic_cc_event ev = {
1184 .type = QUIC_CC_EVT_LOSS,
1185 .loss.now_ms = now_ms,
1186 .loss.max_ack_delay = qc->max_ack_delay,
1187 .loss.lost_bytes = lost_bytes,
1188 .loss.newest_time_sent = newest_time_sent,
1189 .loss.period = period,
1190 };
1191
1192 quic_cc_event(&qc->path->cc, &ev);
1193}
1194
1195/* Send a packet ack event nofication for each newly acked packet of
1196 * <newly_acked_pkts> list and free them.
1197 * Always succeeds.
1198 */
1199static inline void qc_treat_newly_acked_pkts(struct quic_conn_ctx *ctx,
1200 struct list *newly_acked_pkts)
1201{
1202 struct quic_conn *qc = ctx->conn->qc;
1203 struct quic_tx_packet *pkt, *tmp;
1204 struct quic_cc_event ev = { .type = QUIC_CC_EVT_ACK, };
1205
1206 list_for_each_entry_safe(pkt, tmp, newly_acked_pkts, list) {
1207 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001208 qc->path->prep_in_flight -= pkt->in_flight_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001209 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01001210 qc->path->ifae_pkts--;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001211 ev.ack.acked = pkt->in_flight_len;
1212 ev.ack.time_sent = pkt->time_sent;
1213 quic_cc_event(&qc->path->cc, &ev);
1214 LIST_DEL(&pkt->list);
1215 eb64_delete(&pkt->pn_node);
1216 pool_free(pool_head_quic_tx_packet, pkt);
1217 }
1218
1219}
1220
1221/* Handle <pkts> list of lost packets detected at <now_us> handling
1222 * their TX frames.
1223 * Send a packet loss event to the congestion controller if
1224 * in flight packet have been lost.
1225 * Also frees the packet in <pkts> list.
1226 * Never fails.
1227 */
1228static inline void qc_release_lost_pkts(struct quic_pktns *pktns,
1229 struct quic_conn_ctx *ctx,
1230 struct list *pkts,
1231 uint64_t now_us)
1232{
1233 struct quic_conn *qc = ctx->conn->qc;
1234 struct quic_tx_packet *pkt, *tmp, *oldest_lost, *newest_lost;
1235 struct quic_tx_frm *frm, *frmbak;
1236 uint64_t lost_bytes;
1237
1238 lost_bytes = 0;
1239 oldest_lost = newest_lost = NULL;
1240 list_for_each_entry_safe(pkt, tmp, pkts, list) {
1241 lost_bytes += pkt->in_flight_len;
1242 pkt->pktns->tx.in_flight -= pkt->in_flight_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001243 qc->path->prep_in_flight -= pkt->in_flight_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001244 if (pkt->flags & QUIC_FL_TX_PACKET_ACK_ELICITING)
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01001245 qc->path->ifae_pkts--;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001246 /* Treat the frames of this lost packet. */
1247 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list)
1248 qc_treat_nacked_tx_frm(frm, pktns, ctx);
1249 LIST_DEL(&pkt->list);
1250 if (!oldest_lost) {
1251 oldest_lost = newest_lost = pkt;
1252 }
1253 else {
1254 if (newest_lost != oldest_lost)
1255 pool_free(pool_head_quic_tx_packet, newest_lost);
1256 newest_lost = pkt;
1257 }
1258 }
1259
1260 if (lost_bytes) {
1261 /* Sent a packet loss event to the congestion controller. */
1262 qc_cc_loss_event(ctx->conn->qc, lost_bytes, newest_lost->time_sent,
1263 newest_lost->time_sent - oldest_lost->time_sent, now_us);
1264 pool_free(pool_head_quic_tx_packet, oldest_lost);
1265 if (newest_lost != oldest_lost)
1266 pool_free(pool_head_quic_tx_packet, newest_lost);
1267 }
1268}
1269
1270/* Look for packet loss from sent packets for <qel> encryption level of a
1271 * connection with <ctx> as I/O handler context. If remove is true, remove them from
1272 * their tree if deemed as lost or set the <loss_time> value the packet number
1273 * space if any not deemed lost.
1274 * Should be called after having received an ACK frame with newly acknowledged
1275 * packets or when the the loss detection timer has expired.
1276 * Always succeeds.
1277 */
1278static void qc_packet_loss_lookup(struct quic_pktns *pktns,
1279 struct quic_conn *qc,
1280 struct list *lost_pkts)
1281{
1282 struct eb_root *pkts;
1283 struct eb64_node *node;
1284 struct quic_loss *ql;
1285 unsigned int loss_delay;
1286
1287 TRACE_ENTER(QUIC_EV_CONN_PKTLOSS, qc->conn, pktns);
1288 pkts = &pktns->tx.pkts;
1289 pktns->tx.loss_time = TICK_ETERNITY;
1290 if (eb_is_empty(pkts))
1291 goto out;
1292
1293 ql = &qc->path->loss;
1294 loss_delay = QUIC_MAX(ql->latest_rtt, ql->srtt >> 3);
1295 loss_delay += loss_delay >> 3;
1296 loss_delay = QUIC_MAX(loss_delay, MS_TO_TICKS(QUIC_TIMER_GRANULARITY));
1297
1298 node = eb64_first(pkts);
1299 while (node) {
1300 struct quic_tx_packet *pkt;
1301 int64_t largest_acked_pn;
1302 unsigned int loss_time_limit, time_sent;
1303
1304 pkt = eb64_entry(&node->node, struct quic_tx_packet, pn_node);
1305 largest_acked_pn = pktns->tx.largest_acked_pn;
1306 node = eb64_next(node);
1307 if ((int64_t)pkt->pn_node.key > largest_acked_pn)
1308 break;
1309
1310 time_sent = pkt->time_sent;
1311 loss_time_limit = tick_add(time_sent, loss_delay);
1312 if (tick_is_le(time_sent, now_ms) ||
1313 (int64_t)largest_acked_pn >= pkt->pn_node.key + QUIC_LOSS_PACKET_THRESHOLD) {
1314 eb64_delete(&pkt->pn_node);
1315 LIST_ADDQ(lost_pkts, &pkt->list);
1316 }
1317 else {
1318 pktns->tx.loss_time = tick_first(pktns->tx.loss_time, loss_time_limit);
1319 }
1320 }
1321
1322 out:
1323 TRACE_LEAVE(QUIC_EV_CONN_PKTLOSS, qc->conn, pktns, lost_pkts);
1324}
1325
1326/* Parse ACK frame into <frm> from a buffer at <buf> address with <end> being at
1327 * one byte past the end of this buffer. Also update <rtt_sample> if needed, i.e.
1328 * if the largest acked packet was newly acked and if there was at leas one newly
1329 * acked ack-eliciting packet.
1330 * Return 1, if succeeded, 0 if not.
1331 */
1332static inline int qc_parse_ack_frm(struct quic_frame *frm, struct quic_conn_ctx *ctx,
1333 struct quic_enc_level *qel,
1334 unsigned int *rtt_sample,
1335 const unsigned char **pos, const unsigned char *end)
1336{
1337 struct quic_ack *ack = &frm->ack;
1338 uint64_t smallest, largest;
1339 struct eb_root *pkts;
1340 struct eb64_node *largest_node;
1341 unsigned int time_sent, pkt_flags;
1342 struct list newly_acked_pkts = LIST_HEAD_INIT(newly_acked_pkts);
1343 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
1344
1345 if (ack->largest_ack > qel->pktns->tx.next_pn) {
1346 TRACE_DEVEL("ACK for not sent packet", QUIC_EV_CONN_PRSAFRM,
1347 ctx->conn,, &ack->largest_ack);
1348 goto err;
1349 }
1350
1351 if (ack->first_ack_range > ack->largest_ack) {
1352 TRACE_DEVEL("too big first ACK range", QUIC_EV_CONN_PRSAFRM,
1353 ctx->conn,, &ack->first_ack_range);
1354 goto err;
1355 }
1356
1357 largest = ack->largest_ack;
1358 smallest = largest - ack->first_ack_range;
1359 pkts = &qel->pktns->tx.pkts;
1360 pkt_flags = 0;
1361 largest_node = NULL;
1362 time_sent = 0;
1363
1364 if ((int64_t)ack->largest_ack > qel->pktns->tx.largest_acked_pn) {
1365 largest_node = eb64_lookup(pkts, largest);
1366 if (!largest_node) {
1367 TRACE_DEVEL("Largest acked packet not found",
1368 QUIC_EV_CONN_PRSAFRM, ctx->conn);
1369 goto err;
1370 }
1371
1372 time_sent = eb64_entry(&largest_node->node,
1373 struct quic_tx_packet, pn_node)->time_sent;
1374 }
1375
1376 TRACE_PROTO("ack range", QUIC_EV_CONN_PRSAFRM,
1377 ctx->conn,, &largest, &smallest);
1378 do {
1379 uint64_t gap, ack_range;
1380
1381 qc_ackrng_pkts(pkts, &pkt_flags, &newly_acked_pkts,
1382 largest_node, largest, smallest, ctx);
1383 if (!ack->ack_range_num--)
1384 break;
1385
1386 if (!quic_dec_int(&gap, pos, end))
1387 goto err;
1388
1389 if (smallest < gap + 2) {
1390 TRACE_DEVEL("wrong gap value", QUIC_EV_CONN_PRSAFRM,
1391 ctx->conn,, &gap, &smallest);
1392 goto err;
1393 }
1394
1395 largest = smallest - gap - 2;
1396 if (!quic_dec_int(&ack_range, pos, end))
1397 goto err;
1398
1399 if (largest < ack_range) {
1400 TRACE_DEVEL("wrong ack range value", QUIC_EV_CONN_PRSAFRM,
1401 ctx->conn,, &largest, &ack_range);
1402 goto err;
1403 }
1404
1405 /* Do not use this node anymore. */
1406 largest_node = NULL;
1407 /* Next range */
1408 smallest = largest - ack_range;
1409
1410 TRACE_PROTO("ack range", QUIC_EV_CONN_PRSAFRM,
1411 ctx->conn,, &largest, &smallest);
1412 } while (1);
1413
1414 /* Flag this packet number space as having received an ACK. */
1415 qel->pktns->flags |= QUIC_FL_PKTNS_ACK_RECEIVED;
1416
1417 if (time_sent && (pkt_flags & QUIC_FL_TX_PACKET_ACK_ELICITING)) {
1418 *rtt_sample = tick_remain(time_sent, now_ms);
1419 qel->pktns->tx.largest_acked_pn = ack->largest_ack;
1420 }
1421
1422 if (!LIST_ISEMPTY(&newly_acked_pkts)) {
1423 if (!eb_is_empty(&qel->pktns->tx.pkts)) {
1424 qc_packet_loss_lookup(qel->pktns, ctx->conn->qc, &lost_pkts);
1425 if (!LIST_ISEMPTY(&lost_pkts))
1426 qc_release_lost_pkts(qel->pktns, ctx, &lost_pkts, now_ms);
1427 }
1428 qc_treat_newly_acked_pkts(ctx, &newly_acked_pkts);
1429 if (quic_peer_validated_addr(ctx))
1430 ctx->conn->qc->path->loss.pto_count = 0;
1431 qc_set_timer(ctx);
1432 }
1433
1434
1435 return 1;
1436
1437 err:
1438 free_quic_tx_pkts(&newly_acked_pkts);
1439 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PRSAFRM, ctx->conn);
1440 return 0;
1441}
1442
1443/* Provide CRYPTO data to the TLS stack found at <data> with <len> as length
1444 * from <qel> encryption level with <ctx> as QUIC connection context.
1445 * Remaining parameter are there for debuging purposes.
1446 * Return 1 if succeeded, 0 if not.
1447 */
1448static inline int qc_provide_cdata(struct quic_enc_level *el,
1449 struct quic_conn_ctx *ctx,
1450 const unsigned char *data, size_t len,
1451 struct quic_rx_packet *pkt,
1452 struct quic_rx_crypto_frm *cf)
1453{
1454 int ssl_err;
1455
1456 TRACE_ENTER(QUIC_EV_CONN_SSLDATA, ctx->conn);
1457 ssl_err = SSL_ERROR_NONE;
1458 if (SSL_provide_quic_data(ctx->ssl, el->level, data, len) != 1) {
1459 TRACE_PROTO("SSL_provide_quic_data() error",
1460 QUIC_EV_CONN_SSLDATA, ctx->conn, pkt, cf, ctx->ssl);
1461 goto err;
1462 }
1463
1464 el->rx.crypto.offset += len;
1465 TRACE_PROTO("in order CRYPTO data",
1466 QUIC_EV_CONN_SSLDATA, ctx->conn,, cf, ctx->ssl);
1467
1468 if (ctx->state < QUIC_HS_ST_COMPLETE) {
1469 ssl_err = SSL_do_handshake(ctx->ssl);
1470 if (ssl_err != 1) {
1471 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
1472 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
1473 TRACE_PROTO("SSL handshake",
1474 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1475 goto out;
1476 }
1477
1478 TRACE_DEVEL("SSL handshake error",
1479 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1480 goto err;
1481 }
1482
1483 TRACE_PROTO("SSL handshake OK", QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
1484 if (objt_listener(ctx->conn->target))
1485 ctx->state = QUIC_HS_ST_CONFIRMED;
1486 else
1487 ctx->state = QUIC_HS_ST_COMPLETE;
1488 } else {
1489 ssl_err = SSL_process_quic_post_handshake(ctx->ssl);
1490 if (ssl_err != 1) {
1491 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
1492 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
1493 TRACE_DEVEL("SSL post handshake",
1494 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1495 goto out;
1496 }
1497
1498 TRACE_DEVEL("SSL post handshake error",
1499 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
1500 goto err;
1501 }
1502
1503 TRACE_PROTO("SSL post handshake succeeded",
1504 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
1505 }
1506
1507 out:
1508 TRACE_LEAVE(QUIC_EV_CONN_SSLDATA, ctx->conn);
1509 return 1;
1510
1511 err:
1512 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_SSLDATA, ctx->conn);
1513 return 0;
1514}
1515
1516/* Parse all the frames of <pkt> QUIC packet for QUIC connection with <ctx>
1517 * as I/O handler context and <qel> as encryption level.
1518 * Returns 1 if succeeded, 0 if failed.
1519 */
1520static int qc_parse_pkt_frms(struct quic_rx_packet *pkt, struct quic_conn_ctx *ctx,
1521 struct quic_enc_level *qel)
1522{
1523 struct quic_frame frm;
1524 const unsigned char *pos, *end;
1525 struct quic_conn *conn = ctx->conn->qc;
1526
1527 TRACE_ENTER(QUIC_EV_CONN_PRSHPKT, ctx->conn);
1528 /* Skip the AAD */
1529 pos = pkt->data + pkt->aad_len;
1530 end = pkt->data + pkt->len;
1531
1532 while (pos < end) {
1533 if (!qc_parse_frm(&frm, pkt, &pos, end, conn))
1534 goto err;
1535
1536 switch (frm.type) {
Frédéric Lécaille0c140202020-12-09 15:56:48 +01001537 case QUIC_FT_PADDING:
1538 if (pos != end) {
1539 TRACE_DEVEL("wrong frame", QUIC_EV_CONN_PRSHPKT, ctx->conn, pkt);
1540 goto err;
1541 }
1542 break;
1543 case QUIC_FT_PING:
1544 break;
1545 case QUIC_FT_ACK:
1546 {
1547 unsigned int rtt_sample;
1548
1549 rtt_sample = 0;
1550 if (!qc_parse_ack_frm(&frm, ctx, qel, &rtt_sample, &pos, end))
1551 goto err;
1552
1553 if (rtt_sample) {
1554 unsigned int ack_delay;
1555
1556 ack_delay = !quic_application_pktns(qel->pktns, conn) ? 0 :
1557 MS_TO_TICKS(QUIC_MIN(quic_ack_delay_ms(&frm.ack, conn), conn->max_ack_delay));
1558 quic_loss_srtt_update(&conn->path->loss, rtt_sample, ack_delay, conn);
1559 }
1560 tasklet_wakeup(ctx->wait_event.tasklet);
1561 break;
1562 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001563 case QUIC_FT_CRYPTO:
1564 if (frm.crypto.offset != qel->rx.crypto.offset) {
1565 struct quic_rx_crypto_frm *cf;
1566
1567 cf = pool_alloc(pool_head_quic_rx_crypto_frm);
1568 if (!cf) {
1569 TRACE_DEVEL("CRYPTO frame allocation failed",
1570 QUIC_EV_CONN_PRSHPKT, ctx->conn);
1571 goto err;
1572 }
1573
1574 cf->offset_node.key = frm.crypto.offset;
1575 cf->len = frm.crypto.len;
1576 cf->data = frm.crypto.data;
1577 cf->pkt = pkt;
1578 eb64_insert(&qel->rx.crypto.frms, &cf->offset_node);
1579 quic_rx_packet_refinc(pkt);
1580 }
1581 else {
1582 /* XXX TO DO: <cf> is used only for the traces. */
1583 struct quic_rx_crypto_frm cf = { };
1584
1585 cf.offset_node.key = frm.crypto.offset;
1586 cf.len = frm.crypto.len;
1587 if (!qc_provide_cdata(qel, ctx,
1588 frm.crypto.data, frm.crypto.len,
1589 pkt, &cf))
1590 goto err;
1591 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001592 break;
Frédéric Lécaille0c140202020-12-09 15:56:48 +01001593 case QUIC_FT_STREAM_8:
1594 case QUIC_FT_STREAM_9:
1595 case QUIC_FT_STREAM_A:
1596 case QUIC_FT_STREAM_B:
1597 case QUIC_FT_STREAM_C:
1598 case QUIC_FT_STREAM_D:
1599 case QUIC_FT_STREAM_E:
1600 case QUIC_FT_STREAM_F:
1601 case QUIC_FT_NEW_CONNECTION_ID:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001602 break;
1603 case QUIC_FT_CONNECTION_CLOSE:
1604 case QUIC_FT_CONNECTION_CLOSE_APP:
1605 break;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001606 case QUIC_FT_HANDSHAKE_DONE:
1607 if (objt_listener(ctx->conn->target))
1608 goto err;
1609
1610 ctx->state = QUIC_HS_ST_CONFIRMED;
1611 break;
1612 default:
1613 goto err;
1614 }
1615 }
1616
1617 /* The server must switch from INITIAL to HANDSHAKE handshake state when it
1618 * has successfully parse a Handshake packet. The Initial encryption must also
1619 * be discarded.
1620 */
1621 if (ctx->state == QUIC_HS_ST_SERVER_INITIAL &&
1622 pkt->type == QUIC_PACKET_TYPE_HANDSHAKE) {
1623 quic_tls_discard_keys(&conn->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
1624 quic_pktns_discard(conn->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, conn);
1625 qc_set_timer(ctx);
1626 ctx->state = QUIC_HS_ST_SERVER_HANDSHAKE;
1627 }
1628
1629 TRACE_LEAVE(QUIC_EV_CONN_PRSHPKT, ctx->conn);
1630 return 1;
1631
1632 err:
1633 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PRSHPKT, ctx->conn);
1634 return 0;
1635}
1636
1637/* Prepare as much as possible handshake packets for the QUIC connection
1638 * with <ctx> as I/O handler context.
1639 * Returns 1 if succeeded, or 0 if something wrong happened.
1640 */
1641static int qc_prep_hdshk_pkts(struct quic_conn_ctx *ctx)
1642{
1643 struct quic_conn *qc;
1644 enum quic_tls_enc_level tel, next_tel;
1645 struct quic_enc_level *qel;
1646 struct q_buf *wbuf;
1647 /* A boolean to flag <wbuf> as reusable, even if not empty. */
1648 int reuse_wbuf;
1649
1650 TRACE_ENTER(QUIC_EV_CONN_PHPKTS, ctx->conn);
1651 qc = ctx->conn->qc;
1652 if (!quic_get_tls_enc_levels(&tel, &next_tel, ctx->state)) {
1653 TRACE_DEVEL("unknown enc. levels",
1654 QUIC_EV_CONN_PHPKTS, ctx->conn);
1655 goto err;
1656 }
1657
1658 reuse_wbuf = 0;
1659 wbuf = q_wbuf(qc);
1660 qel = &qc->els[tel];
1661 /* When entering this function, the writter buffer must be empty.
1662 * Most of the time it points to the reader buffer.
1663 */
1664 while ((q_buf_empty(wbuf) || reuse_wbuf)) {
1665 ssize_t ret;
1666 enum quic_pkt_type pkt_type;
1667
Frédéric Lécaillec5e72b92020-12-02 16:11:40 +01001668 TRACE_POINT(QUIC_EV_CONN_PHPKTS, ctx->conn, qel);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001669 /* Do not build any more packet f the TX secrets are not available or
1670 * f there is nothing to send, i.e. if no ACK are required
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001671 * and if there is no more packets to send upon PTO expiration
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001672 * and if there is no more CRYPTO data available or in flight
1673 * congestion control limit is reached for prepared data
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001674 */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001675 if (!(qel->tls_ctx.tx.flags & QUIC_FL_TLS_SECRETS_SET) ||
1676 (!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001677 !qc->tx.nb_pto_dgrams &&
1678 (LIST_ISEMPTY(&qel->pktns->tx.frms) ||
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001679 qc->path->prep_in_flight >= qc->path->cwnd))) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001680 TRACE_DEVEL("nothing more to do", QUIC_EV_CONN_PHPKTS, ctx->conn);
1681 /* Consume the buffer if we were supposed to reuse it. */
1682 if (reuse_wbuf)
1683 wbuf = q_next_wbuf(qc);
1684 break;
1685 }
1686
1687 pkt_type = quic_tls_level_pkt_type(tel);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001688 ret = qc_build_hdshk_pkt(wbuf, qc, pkt_type, qel);
1689 switch (ret) {
1690 case -2:
1691 goto err;
1692 case -1:
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001693 if (!reuse_wbuf)
1694 goto out;
1695
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001696 /* Not enough room in <wbuf>. */
1697 wbuf = q_next_wbuf(qc);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001698 reuse_wbuf = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001699 continue;
1700 case 0:
1701 goto out;
1702 default:
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001703 reuse_wbuf = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001704 /* Discard the Initial encryption keys as soon as
1705 * a handshake packet could be built.
1706 */
1707 if (ctx->state == QUIC_HS_ST_CLIENT_INITIAL &&
1708 pkt_type == QUIC_PACKET_TYPE_HANDSHAKE) {
1709 quic_tls_discard_keys(&qc->els[QUIC_TLS_ENC_LEVEL_INITIAL]);
1710 quic_pktns_discard(qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].pktns, qc);
1711 qc_set_timer(ctx);
1712 ctx->state = QUIC_HS_ST_CLIENT_HANDSHAKE;
1713 }
1714 /* Special case for Initial packets: when they have all
1715 * been sent, select the next level.
1716 */
1717 if ((LIST_ISEMPTY(&qel->pktns->tx.frms) || qc->els[next_tel].pktns->tx.in_flight) &&
1718 tel == QUIC_TLS_ENC_LEVEL_INITIAL) {
1719 tel = next_tel;
1720 qel = &qc->els[tel];
1721 if (LIST_ISEMPTY(&qel->pktns->tx.frms)) {
1722 /* If there is no more data for the next level, let's
1723 * consume a buffer. This is the case for a client
1724 * which sends only one Initial packet, then wait
1725 * for additional CRYPTO data from the server to enter the
1726 * next level.
1727 */
1728 wbuf = q_next_wbuf(qc);
1729 }
1730 else {
1731 /* Let's try to reuse this buffer. */
1732 reuse_wbuf = 1;
1733 }
1734 }
1735 else {
1736 wbuf = q_next_wbuf(qc);
1737 }
1738 }
1739 }
1740
1741 out:
1742 TRACE_LEAVE(QUIC_EV_CONN_PHPKTS, ctx->conn);
1743 return 1;
1744
1745 err:
1746 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PHPKTS, ctx->conn);
1747 return 0;
1748}
1749
1750/* Send the QUIC packets which have been prepared for QUIC connections
1751 * with <ctx> as I/O handler context.
1752 */
1753int qc_send_ppkts(struct quic_conn_ctx *ctx)
1754{
1755 struct quic_conn *qc;
1756 struct buffer tmpbuf = { };
1757 struct q_buf *rbuf;
1758
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001759 qc = ctx->conn->qc;
1760 for (rbuf = q_rbuf(qc); !q_buf_empty(rbuf) ; rbuf = q_next_rbuf(qc)) {
1761 struct quic_tx_packet *p, *q;
1762 unsigned int time_sent;
1763
1764 tmpbuf.area = (char *)rbuf->area;
1765 tmpbuf.size = tmpbuf.data = rbuf->data;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001766 TRACE_PROTO("to send", QUIC_EV_CONN_SPPKTS, ctx->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001767 if (ctx->xprt->snd_buf(qc->conn, qc->conn->xprt_ctx,
1768 &tmpbuf, tmpbuf.data, 0) <= 0)
1769 break;
1770
1771 qc->tx.bytes += tmpbuf.data;
1772 time_sent = now_ms;
1773 /* Reset this buffer to make it available for the next packet to prepare. */
1774 q_buf_reset(rbuf);
1775 /* Remove from <rbuf> the packets which have just been sent. */
1776 list_for_each_entry_safe(p, q, &rbuf->pkts, list) {
1777 p->time_sent = time_sent;
1778 if (p->flags & QUIC_FL_TX_PACKET_ACK_ELICITING) {
1779 p->pktns->tx.time_of_last_eliciting = time_sent;
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01001780 qc->path->ifae_pkts++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001781 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001782 qc->path->in_flight += p->in_flight_len;
1783 p->pktns->tx.in_flight += p->in_flight_len;
1784 if (p->in_flight_len)
1785 qc_set_timer(ctx);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01001786 TRACE_PROTO("sent pkt", QUIC_EV_CONN_SPPKTS, ctx->conn, p);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001787 LIST_DEL(&p->list);
1788 }
1789 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001790
1791 return 1;
1792}
1793
1794/* Build all the frames which must be sent just after the handshake have succeeded.
1795 * This is essentially NEW_CONNECTION_ID frames. A QUIC server must also send
1796 * a HANDSHAKE_DONE frame.
1797 * Return 1 if succeeded, 0 if not.
1798 */
1799static int quic_build_post_handshake_frames(struct quic_conn *conn)
1800{
1801 int i;
1802 struct quic_frame *frm;
1803
1804 /* Only servers must send a HANDSHAKE_DONE frame. */
1805 if (!objt_server(conn->conn->target)) {
1806 frm = pool_alloc(pool_head_quic_frame);
1807 frm->type = QUIC_FT_HANDSHAKE_DONE;
1808 LIST_ADDQ(&conn->tx.frms_to_send, &frm->list);
1809 }
1810
1811 for (i = 1; i < conn->rx_tps.active_connection_id_limit; i++) {
1812 struct quic_connection_id *cid;
1813
1814 frm = pool_alloc(pool_head_quic_frame);
1815 memset(frm, 0, sizeof *frm);
1816 cid = new_quic_cid(&conn->cids, i);
1817 if (!frm || !cid)
1818 goto err;
1819
1820 quic_connection_id_to_frm_cpy(frm, cid);
1821 LIST_ADDQ(&conn->tx.frms_to_send, &frm->list);
1822 }
1823
1824 return 1;
1825
1826 err:
1827 free_quic_conn_cids(conn);
1828 return 0;
1829}
1830
1831/* Deallocate <l> list of ACK ranges. */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001832void free_quic_arngs(struct quic_arngs *arngs)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001833{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001834 struct eb64_node *n;
1835 struct quic_arng_node *ar;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001836
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001837 n = eb64_first(&arngs->root);
1838 while (n) {
1839 struct eb64_node *next;
1840
1841 ar = eb64_entry(&n->node, struct quic_arng_node, first);
1842 next = eb64_next(n);
1843 eb64_delete(n);
1844 free(ar);
1845 n = next;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001846 }
1847}
1848
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001849/* Return the gap value between <p> and <q> ACK ranges where <q> follows <p> in
1850 * descending order.
1851 */
1852static inline size_t sack_gap(struct quic_arng_node *p,
1853 struct quic_arng_node *q)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001854{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001855 return p->first.key - q->last - 2;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001856}
1857
1858
1859/* Remove the last elements of <ack_ranges> list of ack range updating its
1860 * encoded size until it goes below <limit>.
1861 * Returns 1 if succeded, 0 if not (no more element to remove).
1862 */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001863static int quic_rm_last_ack_ranges(struct quic_arngs *arngs, size_t limit)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001864{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001865 struct eb64_node *last, *prev;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001866
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001867 last = eb64_last(&arngs->root);
1868 while (last && arngs->enc_sz > limit) {
1869 struct quic_arng_node *last_node, *prev_node;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001870
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001871 prev = eb64_prev(last);
1872 if (!prev)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001873 return 0;
1874
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001875 last_node = eb64_entry(&last->node, struct quic_arng_node, first);
1876 prev_node = eb64_entry(&prev->node, struct quic_arng_node, first);
1877 arngs->enc_sz -= quic_int_getsize(last_node->last - last_node->first.key);
1878 arngs->enc_sz -= quic_int_getsize(sack_gap(prev_node, last_node));
1879 arngs->enc_sz -= quic_decint_size_diff(arngs->sz);
1880 --arngs->sz;
1881 eb64_delete(last);
1882 pool_free(pool_head_quic_arng, last);
1883 last = prev;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001884 }
1885
1886 return 1;
1887}
1888
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001889/* Set the encoded size of <arngs> QUIC ack ranges. */
1890static void quic_arngs_set_enc_sz(struct quic_arngs *arngs)
1891{
1892 struct eb64_node *node, *next;
1893 struct quic_arng_node *ar, *ar_next;
1894
1895 node = eb64_last(&arngs->root);
1896 if (!node)
1897 return;
1898
1899 ar = eb64_entry(&node->node, struct quic_arng_node, first);
1900 arngs->enc_sz = quic_int_getsize(ar->last) +
1901 quic_int_getsize(ar->last - ar->first.key) + quic_int_getsize(arngs->sz - 1);
1902
1903 while ((next = eb64_prev(node))) {
1904 ar_next = eb64_entry(&next->node, struct quic_arng_node, first);
1905 arngs->enc_sz += quic_int_getsize(sack_gap(ar, ar_next)) +
1906 quic_int_getsize(ar_next->last - ar_next->first.key);
1907 node = next;
1908 ar = eb64_entry(&node->node, struct quic_arng_node, first);
1909 }
1910}
1911
1912/* Insert in <root> ebtree <node> node with <ar> as range value.
1913 * Returns the ebtree node which has been inserted.
1914 */
1915static inline
1916struct eb64_node *quic_insert_new_range(struct eb_root *root,
1917 struct quic_arng_node *node,
1918 struct quic_arng *ar)
1919{
1920 node->first.key = ar->first;
1921 node->last = ar->last;
1922 return eb64_insert(root, &node->first);
1923}
1924
1925/* Update <arngs> tree of ACK ranges with <ar> as new ACK range value.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001926 * Note that this function computes the number of bytes required to encode
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001927 * this tree of ACK ranges in descending order.
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001928 *
1929 * Descending order
1930 * ------------->
1931 * range1 range2
1932 * ..........|--------|..............|--------|
1933 * ^ ^ ^ ^
1934 * | | | |
1935 * last1 first1 last2 first2
1936 * ..........+--------+--------------+--------+......
1937 * diff1 gap12 diff2
1938 *
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001939 * To encode the previous list of ranges we must encode integers as follows in
1940 * descending order:
1941 * enc(last2),enc(diff2),enc(gap12),enc(diff1)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001942 * with diff1 = last1 - first1
1943 * diff2 = last2 - first2
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001944 * gap12 = first1 - last2 - 2 (>= 0)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001945 *
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001946 */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001947int quic_update_ack_ranges_list(struct quic_arngs *arngs,
1948 struct quic_arng *ar)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001949{
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001950 struct eb64_node *le;
1951 struct quic_arng_node *new_node;
1952 struct eb64_node *new;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001953
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001954 new = NULL;
1955 if (eb_is_empty(&arngs->root)) {
1956 /* First range insertion. */
1957 new_node = pool_alloc(pool_head_quic_arng);
1958 if (!new_node)
1959 return 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001960
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001961 quic_insert_new_range(&arngs->root, new_node, ar);
1962 /* Increment the size of these ranges. */
1963 arngs->sz++;
1964 goto out;
1965 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001966
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001967 le = eb64_lookup_le(&arngs->root, ar->first);
1968 if (!le) {
1969 /* New insertion */
1970 new_node = pool_alloc(pool_head_quic_arng);
1971 if (!new_node)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001972 return 0;
1973
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001974 new = quic_insert_new_range(&arngs->root, new_node, ar);
1975 /* Increment the size of these ranges. */
1976 arngs->sz++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001977 }
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001978 else {
1979 struct quic_arng_node *le_ar =
1980 eb64_entry(&le->node, struct quic_arng_node, first);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001981
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001982 /* Already existing range */
1983 if (le_ar->first.key <= ar->first && le_ar->last >= ar->last)
1984 return 1;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001985
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001986 if (le_ar->last + 1 >= ar->first) {
1987 le_ar->last = ar->last;
1988 new = le;
1989 new_node = le_ar;
1990 }
1991 else {
1992 /* New insertion */
1993 new_node = pool_alloc(pool_head_quic_arng);
1994 if (!new_node)
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01001995 return 0;
1996
Frédéric Lécaille8090b512020-11-30 16:19:22 +01001997 new = quic_insert_new_range(&arngs->root, new_node, ar);
1998 /* Increment the size of these ranges. */
1999 arngs->sz++;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002000 }
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002001 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002002
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002003 /* Verify that the new inserted node does not overlap the nodes
2004 * which follow it.
2005 */
2006 if (new) {
2007 uint64_t new_node_last;
2008 struct eb64_node *next;
2009 struct quic_arng_node *next_node;
2010
2011 new_node_last = new_node->last;
2012 while ((next = eb64_next(new))) {
2013 next_node =
2014 eb64_entry(&next->node, struct quic_arng_node, first);
2015 if (new_node_last + 1 < next_node->first.key)
2016 break;
2017
2018 if (next_node->last > new_node->last)
2019 new_node->last = next_node->last;
2020 eb64_delete(next);
2021 free(next_node);
2022 /* Decrement the size of these ranges. */
2023 arngs->sz--;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002024 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002025 }
2026
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002027 quic_arngs_set_enc_sz(arngs);
2028
2029 out:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002030 return 1;
2031}
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002032/* Remove the header protection of packets at <el> encryption level.
2033 * Always succeeds.
2034 */
2035static inline void qc_rm_hp_pkts(struct quic_enc_level *el, struct quic_conn_ctx *ctx)
2036{
2037 struct quic_tls_ctx *tls_ctx;
2038 struct quic_rx_packet *pqpkt, *qqpkt;
2039 struct quic_enc_level *app_qel;
2040
2041 TRACE_ENTER(QUIC_EV_CONN_ELRMHP, ctx->conn);
2042 app_qel = &ctx->conn->qc->els[QUIC_TLS_ENC_LEVEL_APP];
2043 /* A server must not process incoming 1-RTT packets before the handshake is complete. */
2044 if (el == app_qel && objt_listener(ctx->conn->target) && ctx->state < QUIC_HS_ST_COMPLETE) {
2045 TRACE_PROTO("hp not removed (handshake not completed)",
2046 QUIC_EV_CONN_ELRMHP, ctx->conn);
2047 goto out;
2048 }
2049 tls_ctx = &el->tls_ctx;
2050 list_for_each_entry_safe(pqpkt, qqpkt, &el->rx.pqpkts, list) {
2051 if (!qc_do_rm_hp(pqpkt, tls_ctx, el->pktns->rx.largest_pn,
2052 pqpkt->data + pqpkt->pn_offset,
2053 pqpkt->data, pqpkt->data + pqpkt->len, ctx)) {
2054 TRACE_PROTO("hp removing error", QUIC_EV_CONN_ELRMHP, ctx->conn);
2055 /* XXX TO DO XXX */
2056 }
2057 else {
2058 /* The AAD includes the packet number field */
2059 pqpkt->aad_len = pqpkt->pn_offset + pqpkt->pnl;
2060 /* Store the packet into the tree of packets to decrypt. */
2061 pqpkt->pn_node.key = pqpkt->pn;
2062 quic_rx_packet_eb64_insert(&el->rx.pkts, &pqpkt->pn_node);
2063 TRACE_PROTO("hp removed", QUIC_EV_CONN_ELRMHP, ctx->conn, pqpkt);
2064 }
2065 quic_rx_packet_list_del(pqpkt);
2066 }
2067
2068 out:
2069 TRACE_LEAVE(QUIC_EV_CONN_ELRMHP, ctx->conn);
2070}
2071
2072/* Process all the CRYPTO frame at <el> encryption level.
2073 * Return 1 if succeeded, 0 if not.
2074 */
2075static inline int qc_treat_rx_crypto_frms(struct quic_enc_level *el,
2076 struct quic_conn_ctx *ctx)
2077{
2078 struct eb64_node *node;
2079
2080 TRACE_ENTER(QUIC_EV_CONN_RXCDATA, ctx->conn);
2081 node = eb64_first(&el->rx.crypto.frms);
2082 while (node) {
2083 struct quic_rx_crypto_frm *cf;
2084
2085 cf = eb64_entry(&node->node, struct quic_rx_crypto_frm, offset_node);
2086 if (cf->offset_node.key != el->rx.crypto.offset)
2087 break;
2088
2089 if (!qc_provide_cdata(el, ctx, cf->data, cf->len, cf->pkt, cf))
2090 goto err;
2091
2092 node = eb64_next(node);
2093 quic_rx_packet_refdec(cf->pkt);
2094 eb64_delete(&cf->offset_node);
2095 pool_free(pool_head_quic_rx_crypto_frm, cf);
2096 }
2097
2098 TRACE_LEAVE(QUIC_EV_CONN_RXCDATA, ctx->conn);
2099 return 1;
2100
2101 err:
2102 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_RXCDATA, ctx->conn);
2103 return 0;
2104}
2105
2106/* Process all the packets at <el> encryption level.
2107 * Return 1 if succeeded, 0 if not.
2108 */
2109int qc_treat_rx_pkts(struct quic_enc_level *el, struct quic_conn_ctx *ctx)
2110{
2111 struct quic_tls_ctx *tls_ctx;
2112 struct eb64_node *node;
2113
2114 TRACE_ENTER(QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2115 tls_ctx = &el->tls_ctx;
2116 node = eb64_first(&el->rx.pkts);
2117 while (node) {
2118 struct quic_rx_packet *pkt;
2119
2120 pkt = eb64_entry(&node->node, struct quic_rx_packet, pn_node);
2121 if (!qc_pkt_decrypt(pkt, tls_ctx)) {
2122 /* Drop the packet */
2123 TRACE_PROTO("packet decryption failed -> dropped",
2124 QUIC_EV_CONN_ELRXPKTS, ctx->conn, pkt);
2125 }
2126 else {
2127 int drop;
2128
2129 drop = 0;
2130 if (!qc_parse_pkt_frms(pkt, ctx, el))
2131 drop = 1;
2132
2133 if (drop) {
2134 /* Drop the packet */
2135 TRACE_PROTO("packet parsing failed -> dropped",
2136 QUIC_EV_CONN_ELRXPKTS, ctx->conn, pkt);
2137 }
2138 else {
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002139 struct quic_arng ar = { .first = pkt->pn, .last = pkt->pn };
2140
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002141 if (pkt->flags & QUIC_FL_RX_PACKET_ACK_ELICITING) {
2142 el->pktns->rx.nb_ack_eliciting++;
2143 if (!(el->pktns->rx.nb_ack_eliciting & 1))
2144 el->pktns->flags |= QUIC_FL_PKTNS_ACK_REQUIRED;
2145 }
2146
2147 /* Update the largest packet number. */
2148 if (pkt->pn > el->pktns->rx.largest_pn)
2149 el->pktns->rx.largest_pn = pkt->pn;
2150
2151 /* Update the list of ranges to acknowledge. */
Frédéric Lécaille8090b512020-11-30 16:19:22 +01002152 if (!quic_update_ack_ranges_list(&el->pktns->rx.arngs, &ar)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002153 TRACE_DEVEL("Could not update ack range list",
2154 QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2155 node = eb64_next(node);
2156 quic_rx_packet_eb64_delete(&pkt->pn_node);
2157 free_quic_rx_packet(pkt);
2158 goto err;
2159 }
2160
2161 }
2162 }
2163 node = eb64_next(node);
2164 quic_rx_packet_eb64_delete(&pkt->pn_node);
2165 free_quic_rx_packet(pkt);
2166 }
2167
2168 if (!qc_treat_rx_crypto_frms(el, ctx))
2169 goto err;
2170
2171 TRACE_LEAVE(QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2172 return 1;
2173
2174 err:
2175 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_ELRXPKTS, ctx->conn);
2176 return 0;
2177}
2178
2179/* Called during handshakes to parse and build Initial and Handshake packets for QUIC
2180 * connections with <ctx> as I/O handler context.
2181 * Returns 1 if succeeded, 0 if not.
2182 */
2183int qc_do_hdshk(struct quic_conn_ctx *ctx)
2184{
2185 int ssl_err;
2186 struct quic_conn *quic_conn;
2187 enum quic_tls_enc_level tel, next_tel;
2188 struct quic_enc_level *qel, *next_qel;
2189 struct quic_tls_ctx *tls_ctx;
2190
2191 TRACE_ENTER(QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
2192
2193 ssl_err = SSL_ERROR_NONE;
2194 quic_conn = ctx->conn->qc;
2195 if (!quic_get_tls_enc_levels(&tel, &next_tel, ctx->state))
2196 goto err;
2197
2198 qel = &quic_conn->els[tel];
2199 next_qel = &quic_conn->els[next_tel];
2200
2201 next_level:
2202 tls_ctx = &qel->tls_ctx;
2203
2204 /* If the header protection key for this level has been derived,
2205 * remove the packet header protections.
2206 */
2207 if (!LIST_ISEMPTY(&qel->rx.pqpkts) &&
2208 (tls_ctx->rx.flags & QUIC_FL_TLS_SECRETS_SET))
2209 qc_rm_hp_pkts(qel, ctx);
2210
2211 if (!eb_is_empty(&qel->rx.pkts) &&
2212 !qc_treat_rx_pkts(qel, ctx))
2213 goto err;
2214
2215 if (!qc_prep_hdshk_pkts(ctx))
2216 goto err;
2217
2218 if (!qc_send_ppkts(ctx))
2219 goto err;
2220
2221 /* Check if there is something to do for the next level.
2222 */
2223 if ((next_qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_SET) &&
2224 (!LIST_ISEMPTY(&next_qel->rx.pqpkts) || !eb_is_empty(&next_qel->rx.pkts))) {
2225 qel = next_qel;
2226 goto next_level;
2227 }
2228
2229 /* If the handshake has not been completed -> out! */
2230 if (ctx->state < QUIC_HS_ST_COMPLETE)
2231 goto out;
2232
2233 /* Discard the Handshake keys. */
2234 quic_tls_discard_keys(&quic_conn->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE]);
2235 quic_pktns_discard(quic_conn->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE].pktns, quic_conn);
2236 qc_set_timer(ctx);
2237 if (!quic_build_post_handshake_frames(quic_conn) ||
2238 !qc_prep_phdshk_pkts(quic_conn) ||
2239 !qc_send_ppkts(ctx))
2240 goto err;
2241
2242 out:
2243 TRACE_LEAVE(QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state);
2244 return 1;
2245
2246 err:
2247 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
2248 return 0;
2249}
2250
2251/* Allocate a new QUIC connection and return it if succeeded, NULL if not. */
2252struct quic_conn *new_quic_conn(uint32_t version)
2253{
2254 struct quic_conn *quic_conn;
2255
2256 quic_conn = pool_alloc(pool_head_quic_conn);
2257 if (quic_conn) {
2258 memset(quic_conn, 0, sizeof *quic_conn);
2259 quic_conn->version = version;
2260 }
2261
2262 return quic_conn;
2263}
2264
2265/* Unitialize <qel> QUIC encryption level. Never fails. */
2266static void quic_conn_enc_level_uninit(struct quic_enc_level *qel)
2267{
2268 int i;
2269
2270 for (i = 0; i < qel->tx.crypto.nb_buf; i++) {
2271 if (qel->tx.crypto.bufs[i]) {
2272 pool_free(pool_head_quic_crypto_buf, qel->tx.crypto.bufs[i]);
2273 qel->tx.crypto.bufs[i] = NULL;
2274 }
2275 }
2276 free(qel->tx.crypto.bufs);
2277 qel->tx.crypto.bufs = NULL;
2278}
2279
2280/* Initialize QUIC TLS encryption level with <level<> as level for <qc> QUIC
2281 * connetion allocating everything needed.
2282 * Returns 1 if succeeded, 0 if not.
2283 */
2284static int quic_conn_enc_level_init(struct quic_conn *qc,
2285 enum quic_tls_enc_level level)
2286{
2287 struct quic_enc_level *qel;
2288
2289 qel = &qc->els[level];
2290 qel->level = quic_to_ssl_enc_level(level);
2291 qel->tls_ctx.rx.aead = qel->tls_ctx.tx.aead = NULL;
2292 qel->tls_ctx.rx.md = qel->tls_ctx.tx.md = NULL;
2293 qel->tls_ctx.rx.hp = qel->tls_ctx.tx.hp = NULL;
2294 qel->tls_ctx.rx.flags = 0;
2295 qel->tls_ctx.tx.flags = 0;
2296
2297 qel->rx.pkts = EB_ROOT;
2298 LIST_INIT(&qel->rx.pqpkts);
2299
2300 /* Allocate only one buffer. */
2301 qel->tx.crypto.bufs = malloc(sizeof *qel->tx.crypto.bufs);
2302 if (!qel->tx.crypto.bufs)
2303 goto err;
2304
2305 qel->tx.crypto.bufs[0] = pool_alloc(pool_head_quic_crypto_buf);
2306 if (!qel->tx.crypto.bufs[0])
2307 goto err;
2308
2309 qel->tx.crypto.bufs[0]->sz = 0;
2310 qel->tx.crypto.nb_buf = 1;
2311
2312 qel->tx.crypto.sz = 0;
2313 qel->tx.crypto.offset = 0;
2314
2315 return 1;
2316
2317 err:
2318 free(qel->tx.crypto.bufs);
2319 qel->tx.crypto.bufs = NULL;
2320 return 0;
2321}
2322
2323/* Release the memory allocated for <buf> array of buffers, with <nb> as size.
2324 * Never fails.
2325 */
2326static inline void free_quic_conn_tx_bufs(struct q_buf **bufs, size_t nb)
2327{
2328 struct q_buf **p;
2329
2330 if (!bufs)
2331 return;
2332
2333 p = bufs;
2334 while (--nb) {
2335 if (!*p) {
2336 p++;
2337 continue;
2338 }
2339 free((*p)->area);
2340 (*p)->area = NULL;
2341 free(*p);
2342 *p = NULL;
2343 p++;
2344 }
2345 free(bufs);
2346}
2347
2348/* Allocate an array or <nb> buffers of <sz> bytes each.
2349 * Return this array if succeeded, NULL if failed.
2350 */
2351static inline struct q_buf **quic_conn_tx_bufs_alloc(size_t nb, size_t sz)
2352{
2353 int i;
2354 struct q_buf **bufs, **p;
2355
2356 bufs = calloc(nb, sizeof *bufs);
2357 if (!bufs)
2358 return NULL;
2359
2360 i = 0;
2361 p = bufs;
2362 while (i++ < nb) {
2363 *p = calloc(1, sizeof **p);
2364 if (!*p)
2365 goto err;
2366
2367 (*p)->area = malloc(sz);
2368 if (!(*p)->area)
2369 goto err;
2370
2371 (*p)->pos = (*p)->area;
2372 (*p)->end = (*p)->area + sz;
2373 (*p)->data = 0;
2374 LIST_INIT(&(*p)->pkts);
2375 p++;
2376 }
2377
2378 return bufs;
2379
2380 err:
2381 free_quic_conn_tx_bufs(bufs, nb);
2382 return NULL;
2383}
2384
2385/* Release all the memory allocated for <conn> QUIC connection. */
2386static void quic_conn_free(struct quic_conn *conn)
2387{
2388 int i;
2389
2390 free_quic_conn_cids(conn);
2391 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++)
2392 quic_conn_enc_level_uninit(&conn->els[i]);
2393 free_quic_conn_tx_bufs(conn->tx.bufs, conn->tx.nb_buf);
2394 if (conn->timer_task)
2395 task_destroy(conn->timer_task);
2396 pool_free(pool_head_quic_conn, conn);
2397}
2398
2399/* Callback called upon loss detection and PTO timer expirations. */
2400static struct task *process_timer(struct task *task, void *ctx, unsigned short state)
2401{
2402 struct quic_conn_ctx *conn_ctx;
2403 struct quic_conn *qc;
2404 struct quic_pktns *pktns;
2405
2406
2407 conn_ctx = task->context;
2408 qc = conn_ctx->conn->qc;
Frédéric Lécaillef7e0b8d2020-12-16 17:33:11 +01002409 TRACE_ENTER(QUIC_EV_CONN_PTIMER, conn_ctx->conn,
2410 NULL, NULL, &qc->path->ifae_pkts);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002411 task->expire = TICK_ETERNITY;
2412 pktns = quic_loss_pktns(qc);
2413 if (tick_isset(pktns->tx.loss_time)) {
2414 struct list lost_pkts = LIST_HEAD_INIT(lost_pkts);
2415
2416 qc_packet_loss_lookup(pktns, qc, &lost_pkts);
2417 if (!LIST_ISEMPTY(&lost_pkts))
2418 qc_release_lost_pkts(pktns, ctx, &lost_pkts, now_ms);
2419 qc_set_timer(conn_ctx);
2420 goto out;
2421 }
2422
2423 if (qc->path->in_flight) {
2424 pktns = quic_pto_pktns(qc, conn_ctx->state >= QUIC_HS_ST_COMPLETE, NULL);
2425 pktns->tx.pto_probe = 1;
2426 }
2427 else if (objt_server(qc->conn->target) && conn_ctx->state <= QUIC_HS_ST_COMPLETE) {
2428 struct quic_enc_level *iel = &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL];
2429 struct quic_enc_level *hel = &qc->els[QUIC_TLS_ENC_LEVEL_HANDSHAKE];
2430
2431 if (hel->tls_ctx.rx.flags == QUIC_FL_TLS_SECRETS_SET)
2432 hel->pktns->tx.pto_probe = 1;
2433 if (iel->tls_ctx.rx.flags == QUIC_FL_TLS_SECRETS_SET)
2434 iel->pktns->tx.pto_probe = 1;
2435 }
2436 qc->tx.nb_pto_dgrams = QUIC_MAX_NB_PTO_DGRAMS;
2437 tasklet_wakeup(conn_ctx->wait_event.tasklet);
2438 qc->path->loss.pto_count++;
2439
2440 out:
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01002441 TRACE_LEAVE(QUIC_EV_CONN_PTIMER, conn_ctx->conn, pktns);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002442
2443 return task;
2444}
2445
2446/* Initialize <conn> QUIC connection with <quic_initial_clients> as root of QUIC
2447 * connections used to identify the first Initial packets of client connecting
2448 * to listeners. This parameter must be NULL for QUIC connections attached
2449 * to listeners. <dcid> is the destination connection ID with <dcid_len> as length.
2450 * <scid> is the source connection ID with <scid_len> as length.
2451 * Returns 1 if succeeded, 0 if not.
2452 */
2453int qc_new_conn_init(struct quic_conn *qc, int ipv4,
2454 struct eb_root *quic_initial_clients,
2455 struct eb_root *quic_clients,
2456 unsigned char *dcid, size_t dcid_len,
2457 unsigned char *scid, size_t scid_len)
2458{
2459 int i;
2460 /* Initial CID. */
2461 struct quic_connection_id *icid;
2462
2463 TRACE_ENTER(QUIC_EV_CONN_INIT, qc->conn);
2464 qc->cids = EB_ROOT;
2465 /* QUIC Server (or listener). */
2466 if (objt_listener(qc->conn->target)) {
2467 /* Copy the initial DCID. */
2468 qc->odcid.len = dcid_len;
2469 if (qc->odcid.len)
2470 memcpy(qc->odcid.data, dcid, dcid_len);
2471
2472 /* Copy the SCID as our DCID for this connection. */
2473 if (scid_len)
2474 memcpy(qc->dcid.data, scid, scid_len);
2475 qc->dcid.len = scid_len;
2476 }
2477 /* QUIC Client (outgoing connection to servers) */
2478 else {
2479 if (dcid_len)
2480 memcpy(qc->dcid.data, dcid, dcid_len);
2481 qc->dcid.len = dcid_len;
2482 }
2483
2484 /* Initialize the output buffer */
2485 qc->obuf.pos = qc->obuf.data;
2486
2487 icid = new_quic_cid(&qc->cids, 0);
2488 if (!icid)
2489 return 0;
2490
2491 /* Select our SCID which is the first CID with 0 as sequence number. */
2492 qc->scid = icid->cid;
2493
2494 /* Insert the DCID the QUIC client has choosen (only for listeners) */
2495 if (objt_listener(qc->conn->target))
2496 ebmb_insert(quic_initial_clients, &qc->odcid_node, qc->odcid.len);
2497
2498 /* Insert our SCID, the connection ID for the QUIC client. */
2499 ebmb_insert(quic_clients, &qc->scid_node, qc->scid.len);
2500
2501 /* Packet number spaces initialization. */
2502 for (i = 0; i < QUIC_TLS_PKTNS_MAX; i++)
2503 quic_pktns_init(&qc->pktns[i]);
2504 /* QUIC encryption level context initialization. */
2505 for (i = 0; i < QUIC_TLS_ENC_LEVEL_MAX; i++) {
2506 if (!quic_conn_enc_level_init(qc, i))
2507 goto err;
2508 /* Initialize the packet number space. */
2509 qc->els[i].pktns = &qc->pktns[quic_tls_pktns(i)];
2510 }
2511
2512 /* TX part. */
2513 LIST_INIT(&qc->tx.frms_to_send);
2514 qc->tx.bufs = quic_conn_tx_bufs_alloc(QUIC_CONN_TX_BUFS_NB, QUIC_CONN_TX_BUF_SZ);
2515 if (!qc->tx.bufs)
2516 goto err;
2517
2518 qc->tx.nb_buf = QUIC_CONN_TX_BUFS_NB;
2519 qc->tx.wbuf = qc->tx.rbuf = 0;
2520 qc->tx.bytes = 0;
2521 qc->tx.nb_pto_dgrams = 0;
2522 /* RX part. */
2523 qc->rx.bytes = 0;
2524
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01002525 /* XXX TO DO: Only one path at this time. */
2526 qc->path = &qc->paths[0];
2527 quic_path_init(qc->path, ipv4, default_quic_cc_algo, qc);
2528
2529 TRACE_LEAVE(QUIC_EV_CONN_INIT, qc->conn);
2530
2531 return 1;
2532
2533 err:
2534 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_INIT, qc->conn);
2535 quic_conn_free(qc);
2536 return 0;
2537}
2538
2539/* Initialize the timer task of <qc> QUIC connection.
2540 * Returns 1 if succeeded, 0 if not.
2541 */
2542static int quic_conn_init_timer(struct quic_conn *qc)
2543{
2544 qc->timer_task = task_new(MAX_THREADS_MASK);
2545 if (!qc->timer_task)
2546 return 0;
2547
2548 qc->timer = TICK_ETERNITY;
2549 qc->timer_task->process = process_timer;
2550 qc->timer_task->context = qc->conn->xprt_ctx;
2551
2552 return 1;
2553}
2554
2555/* Parse into <pkt> a long header located at <*buf> buffer, <end> begin a pointer to the end
2556 * past one byte of this buffer.
2557 */
2558static inline int quic_packet_read_long_header(unsigned char **buf, const unsigned char *end,
2559 struct quic_rx_packet *pkt)
2560{
2561 unsigned char dcid_len, scid_len;
2562
2563 /* Version */
2564 if (!quic_read_uint32(&pkt->version, (const unsigned char **)buf, end))
2565 return 0;
2566
2567 if (!pkt->version) { /* XXX TO DO XXX Version negotiation packet */ };
2568
2569 /* Destination Connection ID Length */
2570 dcid_len = *(*buf)++;
2571 /* We want to be sure we can read <dcid_len> bytes and one more for <scid_len> value */
2572 if (dcid_len > QUIC_CID_MAXLEN || end - *buf < dcid_len + 1)
2573 /* XXX MUST BE DROPPED */
2574 return 0;
2575
2576 if (dcid_len) {
2577 /* Check that the length of this received DCID matches the CID lengths
2578 * of our implementation for non Initials packets only.
2579 */
2580 if (pkt->type != QUIC_PACKET_TYPE_INITIAL && dcid_len != QUIC_CID_LEN)
2581 return 0;
2582
2583 memcpy(pkt->dcid.data, *buf, dcid_len);
2584 }
2585
2586 pkt->dcid.len = dcid_len;
2587 *buf += dcid_len;
2588
2589 /* Source Connection ID Length */
2590 scid_len = *(*buf)++;
2591 if (scid_len > QUIC_CID_MAXLEN || end - *buf < scid_len)
2592 /* XXX MUST BE DROPPED */
2593 return 0;
2594
2595 if (scid_len)
2596 memcpy(pkt->scid.data, *buf, scid_len);
2597 pkt->scid.len = scid_len;
2598 *buf += scid_len;
2599
2600 return 1;
2601}
2602
2603/* Try to remove the header protecttion of <pkt> QUIC packet attached to <conn>
2604 * QUIC connection with <buf> as packet number field address, <end> a pointer to one
2605 * byte past the end of the buffer containing this packet and <beg> the address of
2606 * the packet first byte.
2607 * If succeeded, this function updates <*buf> to point to the next packet in the buffer.
2608 * Returns 1 if succeeded, 0 if not.
2609 */
2610static inline int qc_try_rm_hp(struct quic_rx_packet *pkt,
2611 unsigned char **buf, unsigned char *beg,
2612 const unsigned char *end,
2613 struct quic_conn_ctx *ctx)
2614{
2615 unsigned char *pn = NULL; /* Packet number field */
2616 enum quic_tls_enc_level tel;
2617 struct quic_enc_level *qel;
2618 /* Only for traces. */
2619 struct quic_rx_packet *qpkt_trace;
2620
2621 qpkt_trace = NULL;
2622 TRACE_ENTER(QUIC_EV_CONN_TRMHP, ctx->conn);
2623 /* The packet number is here. This is also the start minus
2624 * QUIC_PACKET_PN_MAXLEN of the sample used to add/remove the header
2625 * protection.
2626 */
2627 pn = *buf;
2628 tel = quic_packet_type_enc_level(pkt->type);
2629 if (tel == QUIC_TLS_ENC_LEVEL_NONE) {
2630 TRACE_DEVEL("Wrong enc. level", QUIC_EV_CONN_TRMHP, ctx->conn);
2631 goto err;
2632 }
2633
2634 qel = &ctx->conn->qc->els[tel];
2635
2636 if (qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_DCD) {
2637 TRACE_DEVEL("Discarded keys", QUIC_EV_CONN_TRMHP, ctx->conn);
2638 goto err;
2639 }
2640
2641 if ((qel->tls_ctx.rx.flags & QUIC_FL_TLS_SECRETS_SET) &&
2642 (tel != QUIC_TLS_ENC_LEVEL_APP || ctx->state >= QUIC_HS_ST_COMPLETE)) {
2643 /* Note that the following function enables us to unprotect the packet
2644 * number and its length subsequently used to decrypt the entire
2645 * packets.
2646 */
2647 if (!qc_do_rm_hp(pkt, &qel->tls_ctx,
2648 qel->pktns->rx.largest_pn, pn, beg, end, ctx)) {
2649 TRACE_PROTO("hp error", QUIC_EV_CONN_TRMHP, ctx->conn);
2650 goto err;
2651 }
2652
2653 /* The AAD includes the packet number field found at <pn>. */
2654 pkt->aad_len = pn - beg + pkt->pnl;
2655 qpkt_trace = pkt;
2656 /* Store the packet */
2657 pkt->pn_node.key = pkt->pn;
2658 quic_rx_packet_eb64_insert(&qel->rx.pkts, &pkt->pn_node);
2659 }
2660 else {
2661 TRACE_PROTO("hp not removed", QUIC_EV_CONN_TRMHP, ctx->conn, pkt);
2662 pkt->pn_offset = pn - beg;
2663 quic_rx_packet_list_addq(&qel->rx.pqpkts, pkt);
2664 }
2665
2666 memcpy(pkt->data, beg, pkt->len);
2667 /* Updtate the offset of <*buf> for the next QUIC packet. */
2668 *buf = beg + pkt->len;
2669
2670 TRACE_LEAVE(QUIC_EV_CONN_TRMHP, ctx->conn, qpkt_trace);
2671 return 1;
2672
2673 err:
2674 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_TRMHP, ctx->conn, qpkt_trace);
2675 return 0;
2676}
2677
2678/* Parse the header form from <byte0> first byte of <pkt> pacekt to set type.
2679 * Also set <*long_header> to 1 if this form is long, 0 if not.
2680 */
2681static inline void qc_parse_hd_form(struct quic_rx_packet *pkt,
2682 unsigned char byte0, int *long_header)
2683{
2684 if (byte0 & QUIC_PACKET_LONG_HEADER_BIT) {
2685 pkt->type =
2686 (byte0 >> QUIC_PACKET_TYPE_SHIFT) & QUIC_PACKET_TYPE_BITMASK;
2687 *long_header = 1;
2688 }
2689 else {
2690 pkt->type = QUIC_PACKET_TYPE_SHORT;
2691 *long_header = 0;
2692 }
2693}
2694
2695static ssize_t qc_srv_pkt_rcv(unsigned char **buf, const unsigned char *end,
2696 struct quic_rx_packet *pkt,
2697 struct quic_dgram_ctx *dgram_ctx,
2698 struct sockaddr_storage *saddr)
2699{
2700 unsigned char *beg;
2701 uint64_t len;
2702 struct quic_conn *qc;
2703 struct eb_root *cids;
2704 struct ebmb_node *node;
2705 struct connection *srv_conn;
2706 struct quic_conn_ctx *conn_ctx;
2707 int long_header;
2708
2709 qc = NULL;
2710 TRACE_ENTER(QUIC_EV_CONN_SPKT);
2711 if (end <= *buf)
2712 goto err;
2713
2714 /* Fixed bit */
2715 if (!(**buf & QUIC_PACKET_FIXED_BIT))
2716 /* XXX TO BE DISCARDED */
2717 goto err;
2718
2719 srv_conn = dgram_ctx->owner;
2720 beg = *buf;
2721 /* Header form */
2722 qc_parse_hd_form(pkt, *(*buf)++, &long_header);
2723 if (long_header) {
2724 size_t cid_lookup_len;
2725
2726 if (!quic_packet_read_long_header(buf, end, pkt))
2727 goto err;
2728
2729 /* For Initial packets, and for servers (QUIC clients connections),
2730 * there is no Initial connection IDs storage.
2731 */
2732 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2733 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2734 cid_lookup_len = pkt->dcid.len;
2735 }
2736 else {
2737 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2738 cid_lookup_len = QUIC_CID_LEN;
2739 }
2740
2741 node = ebmb_lookup(cids, pkt->dcid.data, cid_lookup_len);
2742 if (!node)
2743 goto err;
2744
2745 qc = ebmb_entry(node, struct quic_conn, scid_node);
2746
2747 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2748 qc->dcid.len = pkt->scid.len;
2749 if (pkt->scid.len)
2750 memcpy(qc->dcid.data, pkt->scid.data, pkt->scid.len);
2751 }
2752
2753 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2754 uint64_t token_len;
2755
2756 if (!quic_dec_int(&token_len, (const unsigned char **)buf, end) || end - *buf < token_len)
2757 goto err;
2758
2759 /* XXX TO DO XXX 0 value means "the token is not present".
2760 * A server which sends an Initial packet must not set the token.
2761 * So, a client which receives an Initial packet with a token
2762 * MUST discard the packet or generate a connection error with
2763 * PROTOCOL_VIOLATION as type.
2764 * The token must be provided in a Retry packet or NEW_TOKEN frame.
2765 */
2766 pkt->token_len = token_len;
2767 }
2768 }
2769 else {
2770 /* XXX TO DO: Short header XXX */
2771 if (end - *buf < QUIC_CID_LEN)
2772 goto err;
2773
2774 cids = &((struct server *)__objt_server(srv_conn->target))->cids;
2775 node = ebmb_lookup(cids, *buf, QUIC_CID_LEN);
2776 if (!node)
2777 goto err;
2778
2779 qc = ebmb_entry(node, struct quic_conn, scid_node);
2780 *buf += QUIC_CID_LEN;
2781 }
2782 /* Store the DCID used for this packet to check the packet which
2783 * come in this UDP datagram match with it.
2784 */
2785 if (!dgram_ctx->dcid_node)
2786 dgram_ctx->dcid_node = node;
2787 /* Only packets packets with long headers and not RETRY or VERSION as type
2788 * have a length field.
2789 */
2790 if (long_header && pkt->type != QUIC_PACKET_TYPE_RETRY && pkt->version) {
2791 if (!quic_dec_int(&len, (const unsigned char **)buf, end) || end - *buf < len)
2792 goto err;
2793
2794 pkt->len = len;
2795 }
2796 else if (!long_header) {
2797 /* A short packet is the last one of an UDP datagram. */
2798 pkt->len = end - *buf;
2799 }
2800
2801 conn_ctx = qc->conn->xprt_ctx;
2802
2803 /* Increase the total length of this packet by the header length. */
2804 pkt->len += *buf - beg;
2805 /* Do not check the DCID node before the length. */
2806 if (dgram_ctx->dcid_node != node) {
2807 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_SPKT, qc->conn);
2808 goto err;
2809 }
2810
2811 if (pkt->len > sizeof pkt->data) {
2812 TRACE_PROTO("Too big packet", QUIC_EV_CONN_SPKT, qc->conn, pkt, &pkt->len);
2813 goto err;
2814 }
2815
2816 if (!qc_try_rm_hp(pkt, buf, beg, end, conn_ctx))
2817 goto err;
2818
2819 /* Wake the tasklet of the QUIC connection packet handler. */
2820 if (conn_ctx)
2821 tasklet_wakeup(conn_ctx->wait_event.tasklet);
2822
2823 TRACE_LEAVE(QUIC_EV_CONN_SPKT, qc->conn);
2824
2825 return pkt->len;
2826
2827 err:
2828 TRACE_DEVEL("Leaing in error", QUIC_EV_CONN_ESPKT, qc ? qc->conn : NULL);
2829 return -1;
2830}
2831
2832static ssize_t qc_lstnr_pkt_rcv(unsigned char **buf, const unsigned char *end,
2833 struct quic_rx_packet *pkt,
2834 struct quic_dgram_ctx *dgram_ctx,
2835 struct sockaddr_storage *saddr)
2836{
2837 unsigned char *beg;
2838 uint64_t len;
2839 struct quic_conn *qc;
2840 struct eb_root *cids;
2841 struct ebmb_node *node;
2842 struct listener *l;
2843 struct quic_conn_ctx *conn_ctx;
2844 int long_header = 0;
2845
2846 qc = NULL;
2847 TRACE_ENTER(QUIC_EV_CONN_LPKT);
2848 if (end <= *buf)
2849 goto err;
2850
2851 /* Fixed bit */
2852 if (!(**buf & QUIC_PACKET_FIXED_BIT)) {
2853 /* XXX TO BE DISCARDED */
2854 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2855 goto err;
2856 }
2857
2858 l = dgram_ctx->owner;
2859 beg = *buf;
2860 /* Header form */
2861 qc_parse_hd_form(pkt, *(*buf)++, &long_header);
2862 if (long_header) {
2863 unsigned char dcid_len;
2864
2865 if (!quic_packet_read_long_header(buf, end, pkt)) {
2866 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2867 goto err;
2868 }
2869
2870 dcid_len = pkt->dcid.len;
2871 /* For Initial packets, and for servers (QUIC clients connections),
2872 * there is no Initial connection IDs storage.
2873 */
2874 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2875 /* DCIDs of first packets coming from clients may have the same values.
2876 * Let's distinguish them concatenating the socket addresses to the DCIDs.
2877 */
2878 quic_cid_saddr_cat(&pkt->dcid, saddr);
2879 cids = &l->rx.odcids;
2880 }
2881 else {
2882 if (pkt->dcid.len != QUIC_CID_LEN) {
2883 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2884 goto err;
2885 }
2886
2887 cids = &l->rx.cids;
2888 }
2889
2890 node = ebmb_lookup(cids, pkt->dcid.data, pkt->dcid.len);
2891 if (!node && pkt->type == QUIC_PACKET_TYPE_INITIAL && dcid_len == QUIC_CID_LEN &&
2892 cids == &l->rx.odcids) {
2893 /* Switch to the definitive tree ->cids containing the final CIDs. */
2894 node = ebmb_lookup(&l->rx.cids, pkt->dcid.data, dcid_len);
2895 if (node) {
2896 /* If found, signal this with NULL as special value for <cids>. */
2897 pkt->dcid.len = dcid_len;
2898 cids = NULL;
2899 }
2900 }
2901
2902 if (!node) {
2903 if (pkt->type != QUIC_PACKET_TYPE_INITIAL) {
2904 TRACE_PROTO("Non Initiial packet", QUIC_EV_CONN_LPKT);
2905 goto err;
2906 }
2907
2908 qc = new_quic_conn(pkt->version);
2909 if (!qc) {
2910 TRACE_PROTO("Non allocated new connection", QUIC_EV_CONN_LPKT);
2911 goto err;
2912 }
2913
2914 pkt->qc = qc;
2915 pkt->saddr = *saddr;
2916 /* Note that here, odcid_len equals to pkt->dcid.len minus the length
2917 * of <saddr>.
2918 */
2919 pkt->odcid_len = dcid_len;
2920 /* Enqueue this packet. */
2921 LIST_ADDQ(&l->rx.qpkts, &pkt->rx_list);
2922 /* Try to accept a new connection. */
2923 listener_accept(l);
2924 if (!qc->conn) {
2925 TRACE_PROTO("Non accepted connection", QUIC_EV_CONN_LPKT, qc->conn);
2926 goto err;
2927 }
2928
2929 if (!quic_conn_init_timer(qc)) {
2930 TRACE_PROTO("Non initialized timer", QUIC_EV_CONN_LPKT, qc->conn);
2931 goto err;
2932 }
2933
2934 /* This is the DCID node sent in this packet by the client. */
2935 node = &qc->odcid_node;
2936 conn_ctx = qc->conn->xprt_ctx;
2937 SSL_set_quic_transport_params(conn_ctx->ssl,
2938 qc->enc_params, qc->enc_params_len);
2939 }
2940 else {
2941 if (pkt->type == QUIC_PACKET_TYPE_INITIAL && cids == &l->rx.odcids)
2942 qc = ebmb_entry(node, struct quic_conn, odcid_node);
2943 else
2944 qc = ebmb_entry(node, struct quic_conn, scid_node);
2945 }
2946
2947 if (pkt->type == QUIC_PACKET_TYPE_INITIAL) {
2948 uint64_t token_len;
2949 struct quic_tls_ctx *ctx =
2950 &qc->els[QUIC_TLS_ENC_LEVEL_INITIAL].tls_ctx;
2951
2952 if (!quic_dec_int(&token_len, (const unsigned char **)buf, end) ||
2953 end - *buf < token_len) {
2954 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
2955 goto err;
2956 }
2957
2958 /* XXX TO DO XXX 0 value means "the token is not present".
2959 * A server which sends an Initial packet must not set the token.
2960 * So, a client which receives an Initial packet with a token
2961 * MUST discard the packet or generate a connection error with
2962 * PROTOCOL_VIOLATION as type.
2963 * The token must be provided in a Retry packet or NEW_TOKEN frame.
2964 */
2965 pkt->token_len = token_len;
2966 /* NOTE: the socket address has been concatenated to the destination ID
2967 * choosen by the client for Initial packets.
2968 */
2969 if (!ctx->rx.hp && !qc_new_isecs(qc->conn, pkt->dcid.data,
2970 pkt->odcid_len, 1)) {
2971 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
2972 goto err;
2973 }
2974 }
2975 }
2976 else {
2977 if (end - *buf < QUIC_CID_LEN) {
2978 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2979 goto err;
2980 }
2981
2982 cids = &l->rx.cids;
2983 node = ebmb_lookup(cids, *buf, QUIC_CID_LEN);
2984 if (!node) {
2985 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT);
2986 goto err;
2987 }
2988
2989 qc = ebmb_entry(node, struct quic_conn, scid_node);
2990 *buf += QUIC_CID_LEN;
2991 }
2992
2993 /* Store the DCID used for this packet to check the packet which
2994 * come in this UDP datagram match with it.
2995 */
2996 if (!dgram_ctx->dcid_node) {
2997 dgram_ctx->dcid_node = node;
2998 dgram_ctx->qc = qc;
2999 }
3000
3001 /* Only packets packets with long headers and not RETRY or VERSION as type
3002 * have a length field.
3003 */
3004 if (long_header && pkt->type != QUIC_PACKET_TYPE_RETRY && pkt->version) {
3005 if (!quic_dec_int(&len, (const unsigned char **)buf, end) ||
3006 end - *buf < len) {
3007 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3008 goto err;
3009 }
3010
3011 pkt->len = len;
3012 }
3013 else if (!long_header) {
3014 /* A short packet is the last one of an UDP datagram. */
3015 pkt->len = end - *buf;
3016 }
3017
3018 /* Update the state if needed. */
3019 conn_ctx = qc->conn->xprt_ctx;
3020
3021 /* Increase the total length of this packet by the header length. */
3022 pkt->len += *buf - beg;
3023 /* Do not check the DCID node before the length. */
3024 if (dgram_ctx->dcid_node != node) {
3025 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3026 goto err;
3027 }
3028
3029 if (pkt->len > sizeof pkt->data) {
3030 TRACE_PROTO("Too big packet", QUIC_EV_CONN_LPKT, qc->conn, pkt, &pkt->len);
3031 goto err;
3032 }
3033
3034 if (!qc_try_rm_hp(pkt, buf, beg, end, conn_ctx)) {
3035 TRACE_PROTO("Packet dropped", QUIC_EV_CONN_LPKT, qc->conn);
3036 goto err;
3037 }
3038
3039 /* Wake the tasklet of the QUIC connection packet handler. */
3040 if (conn_ctx)
3041 tasklet_wakeup(conn_ctx->wait_event.tasklet);
3042 TRACE_LEAVE(QUIC_EV_CONN_LPKT, qc->conn, pkt);
3043
3044 return pkt->len;
3045
3046 err:
3047 TRACE_DEVEL("Leaving in error", QUIC_EV_CONN_LPKT|QUIC_EV_CONN_ELPKT,
3048 qc ? qc->conn : NULL, pkt);
3049 return -1;
3050}
3051
3052/* This function builds into <buf> buffer a QUIC long packet header whose size may be computed
3053 * in advance. This is the reponsability of the caller to check there is enough room in this
3054 * buffer to build a long header.
3055 * Returns 0 if <type> QUIC packet type is not supported by long header, or 1 if succeeded.
3056 */
3057static int quic_build_packet_long_header(unsigned char **buf, const unsigned char *end,
3058 int type, size_t pn_len, struct quic_conn *conn)
3059{
3060 if (type > QUIC_PACKET_TYPE_RETRY)
3061 return 0;
3062
3063 /* #0 byte flags */
3064 *(*buf)++ = QUIC_PACKET_FIXED_BIT | QUIC_PACKET_LONG_HEADER_BIT |
3065 (type << QUIC_PACKET_TYPE_SHIFT) | (pn_len - 1);
3066 /* Version */
3067 quic_write_uint32(buf, end, conn->version);
3068 *(*buf)++ = conn->dcid.len;
3069 /* Destination connection ID */
3070 if (conn->dcid.len) {
3071 memcpy(*buf, conn->dcid.data, conn->dcid.len);
3072 *buf += conn->dcid.len;
3073 }
3074 /* Source connection ID */
3075 *(*buf)++ = conn->scid.len;
3076 if (conn->scid.len) {
3077 memcpy(*buf, conn->scid.data, conn->scid.len);
3078 *buf += conn->scid.len;
3079 }
3080
3081 return 1;
3082}
3083
3084/* This function builds into <buf> buffer a QUIC long packet header whose size may be computed
3085 * in advance. This is the reponsability of the caller to check there is enough room in this
3086 * buffer to build a long header.
3087 * Returns 0 if <type> QUIC packet type is not supported by long header, or 1 if succeeded.
3088 */
3089static int quic_build_packet_short_header(unsigned char **buf, const unsigned char *end,
3090 size_t pn_len, struct quic_conn *conn)
3091{
3092 /* #0 byte flags */
3093 *(*buf)++ = QUIC_PACKET_FIXED_BIT | (pn_len - 1);
3094 /* Destination connection ID */
3095 if (conn->dcid.len) {
3096 memcpy(*buf, conn->dcid.data, conn->dcid.len);
3097 *buf += conn->dcid.len;
3098 }
3099
3100 return 1;
3101}
3102
3103/* Apply QUIC header protection to the packet with <buf> as first byte address,
3104 * <pn> as address of the Packet number field, <pnlen> being this field length
3105 * with <aead> as AEAD cipher and <key> as secret key.
3106 * Returns 1 if succeeded or 0 if failed.
3107 */
3108static int quic_apply_header_protection(unsigned char *buf, unsigned char *pn, size_t pnlen,
3109 const EVP_CIPHER *aead, const unsigned char *key)
3110{
3111 int i, ret, outlen;
3112 EVP_CIPHER_CTX *ctx;
3113 /* We need an IV of at least 5 bytes: one byte for bytes #0
3114 * and at most 4 bytes for the packet number
3115 */
3116 unsigned char mask[5] = {0};
3117
3118 ret = 0;
3119 ctx = EVP_CIPHER_CTX_new();
3120 if (!ctx)
3121 return 0;
3122
3123 if (!EVP_EncryptInit_ex(ctx, aead, NULL, key, pn + QUIC_PACKET_PN_MAXLEN) ||
3124 !EVP_EncryptUpdate(ctx, mask, &outlen, mask, sizeof mask) ||
3125 !EVP_EncryptFinal_ex(ctx, mask, &outlen))
3126 goto out;
3127
3128 *buf ^= mask[0] & (*buf & QUIC_PACKET_LONG_HEADER_BIT ? 0xf : 0x1f);
3129 for (i = 0; i < pnlen; i++)
3130 pn[i] ^= mask[i + 1];
3131
3132 ret = 1;
3133
3134 out:
3135 EVP_CIPHER_CTX_free(ctx);
3136
3137 return ret;
3138}
3139
3140/* Reduce the encoded size of <ack_frm> ACK frame removing the last
3141 * ACK ranges if needed to a value below <limit> in bytes.
3142 * Return 1 if succeeded, 0 if not.
3143 */
3144static int quic_ack_frm_reduce_sz(struct quic_frame *ack_frm, size_t limit)
3145{
3146 size_t room, ack_delay_sz;
3147
3148 ack_delay_sz = quic_int_getsize(ack_frm->tx_ack.ack_delay);
3149 /* A frame is made of 1 byte for the frame type. */
3150 room = limit - ack_delay_sz - 1;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003151 if (!quic_rm_last_ack_ranges(ack_frm->tx_ack.arngs, room))
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003152 return 0;
3153
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003154 return 1 + ack_delay_sz + ack_frm->tx_ack.arngs->enc_sz;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003155}
3156
3157/* Prepare as most as possible CRYPTO frames from prebuilt CRYPTO frames for <qel>
3158 * encryption level to be encoded in a buffer with <room> as available room,
3159 * and <*len> as number of bytes already present in this buffer.
3160 * Update consequently <*len> to reflect the size of these CRYPTO frames built
3161 * by this function. Also attach these CRYPTO frames to <pkt> QUIC packet.
3162 * Return 1 if succeeded, 0 if not.
3163 */
3164static inline int qc_build_cfrms(struct quic_tx_packet *pkt,
3165 size_t room, size_t *len,
3166 struct quic_enc_level *qel,
3167 struct quic_conn *conn)
3168{
3169 struct quic_tx_frm *cf, *cfbak;
3170 size_t max_cdata_len;
3171
3172 if (conn->tx.nb_pto_dgrams)
3173 max_cdata_len = room;
3174 else
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003175 max_cdata_len = quic_path_prep_data(conn->path);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003176 list_for_each_entry_safe(cf, cfbak, &qel->pktns->tx.frms, list) {
3177 /* header length, data length, frame length. */
3178 size_t hlen, dlen, cflen;
3179
3180 if (!max_cdata_len)
3181 break;
3182
3183 /* Compute the length of this CRYPTO frame header */
3184 hlen = 1 + quic_int_getsize(cf->crypto.offset);
3185 /* Compute the data length of this CRyPTO frame. */
3186 dlen = max_stream_data_size(room, *len + hlen, cf->crypto.len);
3187 if (!dlen)
3188 break;
3189
3190 if (dlen > max_cdata_len)
3191 dlen = max_cdata_len;
3192 max_cdata_len -= dlen;
3193 pkt->cdata_len += dlen;
3194 /* CRYPTO frame length. */
3195 cflen = hlen + quic_int_getsize(dlen) + dlen;
3196 /* Add the CRYPTO data length and its encoded length to the packet
3197 * length and the length of this length.
3198 */
3199 *len += cflen;
3200 if (dlen == cf->crypto.len) {
3201 /* <cf> CRYPTO data have been consumed. */
3202 LIST_DEL(&cf->list);
3203 LIST_ADDQ(&pkt->frms, &cf->list);
3204 }
3205 else {
3206 struct quic_tx_frm *new_cf;
3207
3208 new_cf = pool_alloc(pool_head_quic_tx_frm);
3209 if (!new_cf) {
3210 TRACE_PROTO("No memory for new crypto frame", QUIC_EV_CONN_ECHPKT, conn->conn);
3211 return 0;
3212 }
3213
3214 new_cf->type = QUIC_FT_CRYPTO;
3215 new_cf->crypto.len = dlen;
3216 new_cf->crypto.offset = cf->crypto.offset;
3217 LIST_ADDQ(&pkt->frms, &new_cf->list);
3218 /* Consume <dlen> bytes of the current frame. */
3219 cf->crypto.len -= dlen;
3220 cf->crypto.offset += dlen;
3221 }
3222 }
3223
3224 return 1;
3225}
3226
3227/* This function builds a clear handshake packet used during a QUIC TLS handshakes
3228 * into <wbuf> the current <wbuf> for <conn> QUIC connection with <qel> as QUIC
3229 * TLS encryption level for outgoing packets filling it with as much as CRYPTO
3230 * data as possible from <offset> offset in the CRYPTO data stream. Note that
3231 * this offset value is updated by the length of the CRYPTO frame used to embed
3232 * the CRYPTO data if this packet and only if the packet is successfully built.
3233 * The trailing QUIC_TLS_TAG_LEN bytes of this packet are not built. But they are
3234 * reserved so that to be sure there is enough room to build this AEAD TAG after
3235 * having successfully returned from this function and to be sure the position
3236 * pointer of <wbuf> may be safely incremented by QUIC_TLS_TAG_LEN. After having
3237 * returned from this funciton, <wbuf> position will point one past the last
3238 * byte of the payload with the confidence there is at least QUIC_TLS_TAG_LEN bytes
3239 * available packet to encrypt this packet.
3240 * This function also update the value of <buf_pn> pointer to point to the packet
3241 * number field in this packet. <pn_len> will also have the packet number
3242 * length as value.
3243 *
3244 * Return the length of the packet if succeeded minus QUIC_TLS_TAG_LEN, or -1 if
3245 * failed (not enough room in <wbuf> to build this packet plus QUIC_TLS_TAG_LEN
3246 * bytes), -2 if there are too much CRYPTO data in flight to build a packet.
3247 */
3248static ssize_t qc_do_build_hdshk_pkt(struct q_buf *wbuf,
3249 struct quic_tx_packet *pkt, int pkt_type,
3250 int64_t pn, size_t *pn_len,
3251 unsigned char **buf_pn,
3252 struct quic_enc_level *qel,
3253 struct quic_conn *conn)
3254{
3255 unsigned char *beg, *pos;
3256 const unsigned char *end;
3257 /* This packet type. */
3258 /* Packet number. */
3259 /* The Length QUIC packet field value which is the length
3260 * of the remaining data after this field after encryption.
3261 */
3262 size_t len, token_fields_len, padding_len;
3263 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
3264 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
3265 struct quic_crypto *crypto = &frm.crypto;
3266 size_t ack_frm_len;
3267 int64_t largest_acked_pn;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003268 int add_ping_frm;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003269
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003270 beg = pos = q_buf_getpos(wbuf);
3271 end = q_buf_end(wbuf);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003272 /* When not probing and not acking, reduce the size of this buffer to respect
3273 * the congestion controller window.
3274 */
3275 if (!conn->tx.nb_pto_dgrams && !(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED)) {
3276 size_t path_room;
3277
3278 path_room = quic_path_prep_data(conn->path);
3279 if (end - beg > path_room)
3280 end = beg + path_room;
3281 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003282
3283 /* For a server, the token field of an Initial packet is empty. */
3284 token_fields_len = pkt_type == QUIC_PACKET_TYPE_INITIAL ? 1 : 0;
3285
3286 /* Check there is enough room to build the header followed by a token. */
3287 if (end - pos < QUIC_LONG_PACKET_MINLEN + conn->dcid.len +
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003288 conn->scid.len + token_fields_len + QUIC_TLS_TAG_LEN) {
3289 ssize_t room = end - pos;
3290 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3291 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003292 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003293 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003294
3295 /* Reserve enough room at the end of the packet for the AEAD TAG. */
3296 end -= QUIC_TLS_TAG_LEN;
3297 largest_acked_pn = qel->pktns->tx.largest_acked_pn;
3298 /* packet number length */
3299 *pn_len = quic_packet_number_length(pn, largest_acked_pn);
3300
3301 quic_build_packet_long_header(&pos, end, pkt_type, *pn_len, conn);
3302
3303 /* Encode the token length (0) for an Initial packet. */
3304 if (pkt_type == QUIC_PACKET_TYPE_INITIAL)
3305 *pos++ = 0;
3306
3307 /* Build an ACK frame if required. */
3308 ack_frm_len = 0;
3309 if ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003310 !eb_is_empty(&qel->pktns->rx.arngs.root)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003311 ack_frm.tx_ack.ack_delay = 0;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003312 ack_frm.tx_ack.arngs = &qel->pktns->rx.arngs;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003313 ack_frm_len = quic_ack_frm_reduce_sz(&ack_frm, end - pos);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003314 if (!ack_frm_len) {
3315 ssize_t room = end - pos;
3316 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3317 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003318 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003319 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003320
3321 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
3322 }
3323
3324 /* Length field value without the CRYPTO frames data length. */
3325 len = ack_frm_len + *pn_len;
3326 if (!LIST_ISEMPTY(&qel->pktns->tx.frms) &&
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003327 !qc_build_cfrms(pkt, end - pos, &len, qel, conn)) {
3328 ssize_t room = end - pos;
3329 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3330 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003331 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003332 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003333
3334 add_ping_frm = 0;
3335 padding_len = 0;
3336 if (objt_server(conn->conn->target) &&
3337 pkt_type == QUIC_PACKET_TYPE_INITIAL &&
3338 len < QUIC_INITIAL_PACKET_MINLEN) {
3339 len += padding_len = QUIC_INITIAL_PACKET_MINLEN - len;
3340 }
3341 else if (LIST_ISEMPTY(&pkt->frms)) {
3342 if (qel->pktns->tx.pto_probe) {
3343 /* If we cannot send a CRYPTO frame, we send a PING frame. */
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003344 add_ping_frm = 1;
3345 len += 1;
3346 }
3347 /* If there is no frame at all to follow, add at least a PADDING frame. */
3348 if (!ack_frm_len)
3349 len += padding_len = QUIC_PACKET_PN_MAXLEN - *pn_len;
3350 }
3351
3352 /* Length (of the remaining data). Must not fail because, the buffer size
3353 * has been checked above. Note that we have reserved QUIC_TLS_TAG_LEN bytes
3354 * for the encryption TAG. It must be taken into an account for the length
3355 * of this packet.
3356 */
3357 quic_enc_int(&pos, end, len + QUIC_TLS_TAG_LEN);
3358
3359 /* Packet number field address. */
3360 *buf_pn = pos;
3361
3362 /* Packet number encoding. */
3363 quic_packet_number_encode(&pos, end, pn, *pn_len);
3364
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003365 if (ack_frm_len && !qc_build_frm(&pos, end, &ack_frm, pkt, conn)) {
3366 ssize_t room = end - pos;
3367 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3368 conn->conn, NULL, NULL, &room);
3369 goto err;
3370 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003371
3372 /* Crypto frame */
3373 if (!LIST_ISEMPTY(&pkt->frms)) {
3374 struct quic_tx_frm *cf;
3375
3376 list_for_each_entry(cf, &pkt->frms, list) {
3377 crypto->offset = cf->crypto.offset;
3378 crypto->len = cf->crypto.len;
3379 crypto->qel = qel;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003380 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3381 ssize_t room = end - pos;
3382 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3383 conn->conn, NULL, NULL, &room);
3384 goto err;
3385 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003386 }
3387 }
3388
3389 /* Build a PING frame if needed. */
3390 if (add_ping_frm) {
3391 frm.type = QUIC_FT_PING;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003392 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
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
3400 /* Build a PADDING frame if needed. */
3401 if (padding_len) {
3402 frm.type = QUIC_FT_PADDING;
3403 frm.padding.len = padding_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003404 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3405 ssize_t room = end - pos;
3406 TRACE_PROTO("Not enough room", QUIC_EV_CONN_HPKT,
3407 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003408 goto err;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003409 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003410 }
3411
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003412 /* Always reset this variable as this function has no idea
3413 * if it was set. It is handle by the loss detection timer.
3414 */
3415 qel->pktns->tx.pto_probe = 0;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003416
3417 out:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003418 return pos - beg;
3419
3420 err:
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003421 return -1;
3422}
3423
3424static inline void quic_tx_packet_init(struct quic_tx_packet *pkt)
3425{
3426 pkt->cdata_len = 0;
3427 pkt->in_flight_len = 0;
3428 LIST_INIT(&pkt->frms);
3429}
3430
3431/* Free <pkt> TX packet which has not already attache to any tree. */
3432static inline void free_quic_tx_packet(struct quic_tx_packet *pkt)
3433{
3434 struct quic_tx_frm *frm, *frmbak;
3435
3436 list_for_each_entry_safe(frm, frmbak, &pkt->frms, list) {
3437 LIST_DEL(&frm->list);
3438 pool_free(pool_head_quic_tx_frm, frm);
3439 }
3440 pool_free(pool_head_quic_tx_packet, pkt);
3441}
3442
3443/* Build a handshake packet into <buf> packet buffer with <pkt_type> as packet
3444 * type for <qc> QUIC connection from CRYPTO data stream at <*offset> offset to
3445 * be encrypted at <qel> encryption level.
3446 * Return -2 if the packet could not be encrypted for any reason, -1 if there was
3447 * not enough room in <buf> to build the packet, or the size of the built packet
3448 * if succeeded (may be zero if there is too much crypto data in flight to build the packet).
3449 */
3450static ssize_t qc_build_hdshk_pkt(struct q_buf *buf, struct quic_conn *qc, int pkt_type,
3451 struct quic_enc_level *qel)
3452{
3453 /* The pointer to the packet number field. */
3454 unsigned char *buf_pn;
3455 unsigned char *beg, *end, *payload;
3456 int64_t pn;
3457 size_t pn_len, payload_len, aad_len;
3458 ssize_t pkt_len;
3459 struct quic_tls_ctx *tls_ctx;
3460 struct quic_tx_packet *pkt;
3461
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003462 TRACE_ENTER(QUIC_EV_CONN_HPKT, qc->conn, NULL, qel);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003463 pkt = pool_alloc(pool_head_quic_tx_packet);
3464 if (!pkt) {
3465 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_HPKT, qc->conn);
3466 return -2;
3467 }
3468
3469 quic_tx_packet_init(pkt);
3470 beg = q_buf_getpos(buf);
3471 pn_len = 0;
3472 buf_pn = NULL;
3473 pn = qel->pktns->tx.next_pn + 1;
3474 pkt_len = qc_do_build_hdshk_pkt(buf, pkt, pkt_type, pn, &pn_len, &buf_pn, qel, qc);
3475 if (pkt_len <= 0) {
3476 free_quic_tx_packet(pkt);
3477 return pkt_len;
3478 }
3479
3480 end = beg + pkt_len;
3481 payload = buf_pn + pn_len;
3482 payload_len = end - payload;
3483 aad_len = payload - beg;
3484
3485 tls_ctx = &qel->tls_ctx;
3486 if (!quic_packet_encrypt(payload, payload_len, beg, aad_len, pn, tls_ctx, qc->conn))
3487 goto err;
3488
3489 end += QUIC_TLS_TAG_LEN;
3490 pkt_len += QUIC_TLS_TAG_LEN;
3491 if (!quic_apply_header_protection(beg, buf_pn, pn_len,
3492 tls_ctx->tx.hp, tls_ctx->tx.hp_key)) {
3493 TRACE_DEVEL("Could not apply the header protection", QUIC_EV_CONN_HPKT, qc->conn);
3494 goto err;
3495 }
3496
3497 /* Now that a correct packet is built, let us set the position pointer of
3498 * <buf> buffer for the next packet.
3499 */
3500 q_buf_setpos(buf, end);
3501 /* Consume a packet number. */
3502 ++qel->pktns->tx.next_pn;
3503 /* Attach the built packet to its tree. */
3504 pkt->pn_node.key = qel->pktns->tx.next_pn;
3505 /* Set the packet in fligth length for in flight packet only. */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003506 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003507 pkt->in_flight_len = pkt_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003508 qc->path->prep_in_flight += pkt_len;
3509 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003510 pkt->pktns = qel->pktns;
3511 eb64_insert(&qel->pktns->tx.pkts, &pkt->pn_node);
3512 /* Increment the number of bytes in <buf> buffer by the length of this packet. */
3513 buf->data += pkt_len;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003514 /* Attach this packet to <buf>. */
3515 LIST_ADDQ(&buf->pkts, &pkt->list);
3516 TRACE_LEAVE(QUIC_EV_CONN_HPKT, qc->conn, pkt);
3517
3518 return pkt_len;
3519
3520 err:
3521 free_quic_tx_packet(pkt);
3522 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_HPKT, qc->conn);
3523 return -2;
3524}
3525
3526/* Prepare a clear post handhskake packet for <conn> QUIC connnection.
3527 * Return the length of this packet if succeeded, -1 <wbuf> was full.
3528 */
3529static ssize_t qc_do_build_phdshk_apkt(struct q_buf *wbuf,
3530 struct quic_tx_packet *pkt,
3531 int64_t pn, size_t *pn_len,
3532 unsigned char **buf_pn, struct quic_enc_level *qel,
3533 struct quic_conn *conn)
3534{
3535 const unsigned char *beg, *end;
3536 unsigned char *pos;
3537 struct quic_frame *frm, *sfrm;
3538 struct quic_frame ack_frm = { .type = QUIC_FT_ACK, };
3539 size_t fake_len, ack_frm_len;
3540 int64_t largest_acked_pn;
3541
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003542 TRACE_ENTER(QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003543 beg = pos = q_buf_getpos(wbuf);
3544 end = q_buf_end(wbuf);
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003545 /* When not probing and not acking, reduce the size of this buffer to respect
3546 * the congestion controller window.
3547 */
3548 if (!conn->tx.nb_pto_dgrams && !(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED)) {
3549 size_t path_room;
3550
3551 path_room = quic_path_prep_data(conn->path);
3552 if (end - beg > path_room)
3553 end = beg + path_room;
3554 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003555 largest_acked_pn = qel->pktns->tx.largest_acked_pn;
3556 /* Packet number length */
3557 *pn_len = quic_packet_number_length(pn, largest_acked_pn);
3558 /* Check there is enough room to build this packet (without payload). */
3559 if (end - pos < QUIC_SHORT_PACKET_MINLEN + sizeof_quic_cid(&conn->dcid) +
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003560 *pn_len + QUIC_TLS_TAG_LEN) {
3561 ssize_t room = end - pos;
3562 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3563 conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003564 goto err;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003565 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003566
3567 /* Reserve enough room at the end of the packet for the AEAD TAG. */
3568 end -= QUIC_TLS_TAG_LEN;
3569 quic_build_packet_short_header(&pos, end, *pn_len, conn);
3570 /* Packet number field. */
3571 *buf_pn = pos;
3572 /* Packet number encoding. */
3573 quic_packet_number_encode(&pos, end, pn, *pn_len);
3574
3575 /* Build an ACK frame if required. */
3576 ack_frm_len = 0;
3577 if ((qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003578 !eb_is_empty(&qel->pktns->rx.arngs.root)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003579 ack_frm.tx_ack.ack_delay = 0;
Frédéric Lécaille8090b512020-11-30 16:19:22 +01003580 ack_frm.tx_ack.arngs = &qel->pktns->rx.arngs;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003581 ack_frm_len = quic_ack_frm_reduce_sz(&ack_frm, end - pos);
3582 if (!ack_frm_len)
3583 goto err;
3584
3585 qel->pktns->flags &= ~QUIC_FL_PKTNS_ACK_REQUIRED;
3586 }
3587
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003588 if (ack_frm_len && !qc_build_frm(&pos, end, &ack_frm, pkt, conn)) {
3589 ssize_t room = end - pos;
3590 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3591 conn->conn, NULL, NULL, &room);
3592 goto err;
3593 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003594
3595 fake_len = ack_frm_len;
3596 if (!LIST_ISEMPTY(&qel->pktns->tx.frms) &&
3597 !qc_build_cfrms(pkt, end - pos, &fake_len, qel, conn)) {
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003598 ssize_t room = end - pos;
3599 TRACE_PROTO("some CRYPTO frames could not be built",
3600 QUIC_EV_CONN_PAPKT, conn->conn, NULL, NULL, &room);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003601 goto err;
3602 }
3603
3604 /* Crypto frame */
3605 if (!LIST_ISEMPTY(&pkt->frms)) {
3606 struct quic_frame frm = { .type = QUIC_FT_CRYPTO, };
3607 struct quic_crypto *crypto = &frm.crypto;
3608 struct quic_tx_frm *cf;
3609
3610 list_for_each_entry(cf, &pkt->frms, list) {
3611 crypto->offset = cf->crypto.offset;
3612 crypto->len = cf->crypto.len;
3613 crypto->qel = qel;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003614 if (!qc_build_frm(&pos, end, &frm, pkt, conn)) {
3615 ssize_t room = end - pos;
3616 TRACE_PROTO("Not enough room", QUIC_EV_CONN_PAPKT,
3617 conn->conn, NULL, NULL, &room);
3618 goto err;
3619 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003620 }
3621 }
3622
3623 /* Encode a maximum of frames. */
3624 list_for_each_entry_safe(frm, sfrm, &conn->tx.frms_to_send, list) {
3625 unsigned char *ppos;
3626
3627 ppos = pos;
3628 if (!qc_build_frm(&ppos, end, frm, pkt, conn)) {
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003629 TRACE_DEVEL("Frames not built", QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003630 break;
3631 }
3632
3633 LIST_DEL(&frm->list);
3634 LIST_ADDQ(&pkt->frms, &frm->list);
3635 pos = ppos;
3636 }
3637
3638 out:
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003639 TRACE_LEAVE(QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003640 return pos - beg;
3641
3642 err:
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003643 TRACE_DEVEL("leaving in error (buffer full)", QUIC_EV_CONN_PAPKT, conn->conn);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003644 return -1;
3645}
3646
3647/* Prepare a post handhskake packet at Application encryption level for <conn>
3648 * QUIC connnection.
3649 * Return the length of this packet if succeeded, -1 if <wbuf> was full,
3650 * -2 in case of major error (encryption failure).
3651 */
3652static ssize_t qc_build_phdshk_apkt(struct q_buf *wbuf, struct quic_conn *qc)
3653{
3654 /* A pointer to the packet number fiel in <buf> */
3655 unsigned char *buf_pn;
3656 unsigned char *beg, *end, *payload;
3657 int64_t pn;
3658 size_t pn_len, aad_len, payload_len;
3659 ssize_t pkt_len;
3660 struct quic_tls_ctx *tls_ctx;
3661 struct quic_enc_level *qel;
3662 struct quic_tx_packet *pkt;
3663
3664 TRACE_ENTER(QUIC_EV_CONN_PAPKT, qc->conn);
3665 pkt = pool_alloc(pool_head_quic_tx_packet);
3666 if (!pkt) {
3667 TRACE_DEVEL("Not enough memory for a new packet", QUIC_EV_CONN_PAPKT, qc->conn);
3668 return -2;
3669 }
3670
3671 quic_tx_packet_init(pkt);
3672 beg = q_buf_getpos(wbuf);
3673 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3674 pn_len = 0;
3675 buf_pn = NULL;
3676 pn = qel->pktns->tx.next_pn + 1;
3677 pkt_len = qc_do_build_phdshk_apkt(wbuf, pkt, pn, &pn_len, &buf_pn, qel, qc);
3678 if (pkt_len <= 0) {
3679 free_quic_tx_packet(pkt);
3680 return pkt_len;
3681 }
3682
3683 end = beg + pkt_len;
3684 payload = buf_pn + pn_len;
3685 payload_len = end - payload;
3686 aad_len = payload - beg;
3687
3688 tls_ctx = &qel->tls_ctx;
3689 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 +01003690 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003691
3692 end += QUIC_TLS_TAG_LEN;
3693 pkt_len += QUIC_TLS_TAG_LEN;
3694 if (!quic_apply_header_protection(beg, buf_pn, pn_len,
3695 tls_ctx->tx.hp, tls_ctx->tx.hp_key))
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003696 goto err;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003697
3698 q_buf_setpos(wbuf, end);
3699 /* Consume a packet number. */
3700 ++qel->pktns->tx.next_pn;
3701 /* Attach the built packet to its tree. */
3702 pkt->pn_node.key = qel->pktns->tx.next_pn;
3703 eb64_insert(&qel->pktns->tx.pkts, &pkt->pn_node);
3704 /* Set the packet in fligth length for in flight packet only. */
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003705 if (pkt->flags & QUIC_FL_TX_PACKET_IN_FLIGHT) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003706 pkt->in_flight_len = pkt_len;
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003707 qc->path->prep_in_flight += pkt_len;
3708 }
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003709 pkt->pktns = qel->pktns;
3710 /* Increment the number of bytes in <buf> buffer by the length of this packet. */
3711 wbuf->data += pkt_len;
3712 /* Attach this packet to <buf>. */
3713 LIST_ADDQ(&wbuf->pkts, &pkt->list);
3714
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003715 TRACE_LEAVE(QUIC_EV_CONN_PAPKT, qc->conn, pkt);
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003716
3717 return pkt_len;
Frédéric Lécaille133e8a72020-12-18 09:33:27 +01003718
3719 err:
3720 free_quic_tx_packet(pkt);
3721 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_PAPKT, qc->conn);
3722 return -2;
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003723}
3724
3725/* Prepare a maximum of QUIC Application level packets from <ctx> QUIC
3726 * connection I/O handler context.
3727 * Returns 1 if succeeded, 0 if not.
3728 */
3729int qc_prep_phdshk_pkts(struct quic_conn *qc)
3730{
3731 struct q_buf *wbuf;
3732 struct quic_enc_level *qel;
3733
3734 TRACE_ENTER(QUIC_EV_CONN_PAPKTS, qc->conn);
3735 wbuf = q_wbuf(qc);
3736 qel = &qc->els[QUIC_TLS_ENC_LEVEL_APP];
3737 while (q_buf_empty(wbuf)) {
3738 ssize_t ret;
3739
3740 if (!(qel->pktns->flags & QUIC_FL_PKTNS_ACK_REQUIRED) &&
3741 (LIST_ISEMPTY(&qel->pktns->tx.frms) ||
Frédéric Lécaille04ffb662020-12-08 15:58:39 +01003742 qc->path->prep_in_flight >= qc->path->cwnd)) {
Frédéric Lécaillea7e7ce92020-11-23 14:14:04 +01003743 TRACE_DEVEL("nothing more to do",
3744 QUIC_EV_CONN_PAPKTS, qc->conn);
3745 break;
3746 }
3747
3748 ret = qc_build_phdshk_apkt(wbuf, qc);
3749 switch (ret) {
3750 case -1:
3751 /* Not enough room left in <wbuf>. */
3752 wbuf = q_next_wbuf(qc);
3753 continue;
3754 case -2:
3755 return 0;
3756 default:
3757 /* XXX TO CHECK: consume a buffer. */
3758 wbuf = q_next_wbuf(qc);
3759 continue;
3760 }
3761 }
3762 TRACE_LEAVE(QUIC_EV_CONN_PAPKTS, qc->conn);
3763
3764 return 1;
3765}
3766
3767/* QUIC connection packet handler task. */
3768static struct task *quic_conn_io_cb(struct task *t, void *context, unsigned short state)
3769{
3770 struct quic_conn_ctx *ctx = context;
3771
3772 if (ctx->state < QUIC_HS_ST_COMPLETE) {
3773 qc_do_hdshk(ctx);
3774 }
3775 else {
3776 struct quic_conn *qc = ctx->conn->qc;
3777
3778 /* XXX TO DO: may fail!!! XXX */
3779 qc_treat_rx_pkts(&qc->els[QUIC_TLS_ENC_LEVEL_APP], ctx);
3780 qc_prep_phdshk_pkts(qc);
3781 qc_send_ppkts(ctx);
3782 }
3783
3784 return NULL;
3785}
3786
3787/* Receive up to <count> bytes from connection <conn>'s socket and store them
3788 * into buffer <buf>. Only one call to recv() is performed, unless the
3789 * buffer wraps, in which case a second call may be performed. The connection's
3790 * flags are updated with whatever special event is detected (error, read0,
3791 * empty). The caller is responsible for taking care of those events and
3792 * avoiding the call if inappropriate. The function does not call the
3793 * connection's polling update function, so the caller is responsible for this.
3794 * errno is cleared before starting so that the caller knows that if it spots an
3795 * error without errno, it's pending and can be retrieved via getsockopt(SO_ERROR).
3796 */
3797static size_t quic_conn_to_buf(struct connection *conn, void *xprt_ctx, struct buffer *buf, size_t count, int flags)
3798{
3799 ssize_t ret;
3800 size_t try, done = 0;
3801
3802 if (!conn_ctrl_ready(conn))
3803 return 0;
3804
3805 if (!fd_recv_ready(conn->handle.fd))
3806 return 0;
3807
3808 conn->flags &= ~CO_FL_WAIT_ROOM;
3809 errno = 0;
3810
3811 if (unlikely(!(fdtab[conn->handle.fd].ev & FD_POLL_IN))) {
3812 /* stop here if we reached the end of data */
3813 if ((fdtab[conn->handle.fd].ev & (FD_POLL_ERR|FD_POLL_HUP)) == FD_POLL_HUP)
3814 goto read0;
3815
3816 /* report error on POLL_ERR before connection establishment */
3817 if ((fdtab[conn->handle.fd].ev & FD_POLL_ERR) && (conn->flags & CO_FL_WAIT_L4_CONN)) {
3818 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3819 goto leave;
3820 }
3821 }
3822
3823 /* read the largest possible block. For this, we perform only one call
3824 * to recv() unless the buffer wraps and we exactly fill the first hunk,
3825 * in which case we accept to do it once again. A new attempt is made on
3826 * EINTR too.
3827 */
3828 while (count > 0) {
3829 try = b_contig_space(buf);
3830 if (!try)
3831 break;
3832
3833 if (try > count)
3834 try = count;
3835
3836 ret = recvfrom(conn->handle.fd, b_tail(buf), try, 0, NULL, 0);
3837
3838 if (ret > 0) {
3839 b_add(buf, ret);
3840 done += ret;
3841 if (ret < try) {
3842 /* unfortunately, on level-triggered events, POLL_HUP
3843 * is generally delivered AFTER the system buffer is
3844 * empty, unless the poller supports POLL_RDHUP. If
3845 * we know this is the case, we don't try to read more
3846 * as we know there's no more available. Similarly, if
3847 * there's no problem with lingering we don't even try
3848 * to read an unlikely close from the client since we'll
3849 * close first anyway.
3850 */
3851 if (fdtab[conn->handle.fd].ev & FD_POLL_HUP)
3852 goto read0;
3853
3854 if ((!fdtab[conn->handle.fd].linger_risk) ||
3855 (cur_poller.flags & HAP_POLL_F_RDHUP)) {
3856 break;
3857 }
3858 }
3859 count -= ret;
3860 }
3861 else if (ret == 0) {
3862 goto read0;
3863 }
3864 else if (errno == EAGAIN || errno == ENOTCONN) {
3865 fd_cant_recv(conn->handle.fd);
3866 break;
3867 }
3868 else if (errno != EINTR) {
3869 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3870 break;
3871 }
3872 }
3873
3874 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) && done)
3875 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3876
3877 leave:
3878 return done;
3879
3880 read0:
3881 conn_sock_read0(conn);
3882 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3883
3884 /* Now a final check for a possible asynchronous low-level error
3885 * report. This can happen when a connection receives a reset
3886 * after a shutdown, both POLL_HUP and POLL_ERR are queued, and
3887 * we might have come from there by just checking POLL_HUP instead
3888 * of recv()'s return value 0, so we have no way to tell there was
3889 * an error without checking.
3890 */
3891 if (unlikely(fdtab[conn->handle.fd].ev & FD_POLL_ERR))
3892 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3893 goto leave;
3894}
3895
3896
3897/* Send up to <count> pending bytes from buffer <buf> to connection <conn>'s
3898 * socket. <flags> may contain some CO_SFL_* flags to hint the system about
3899 * other pending data for example, but this flag is ignored at the moment.
3900 * Only one call to send() is performed, unless the buffer wraps, in which case
3901 * a second call may be performed. The connection's flags are updated with
3902 * whatever special event is detected (error, empty). The caller is responsible
3903 * for taking care of those events and avoiding the call if inappropriate. The
3904 * function does not call the connection's polling update function, so the caller
3905 * is responsible for this. It's up to the caller to update the buffer's contents
3906 * based on the return value.
3907 */
3908static size_t quic_conn_from_buf(struct connection *conn, void *xprt_ctx, const struct buffer *buf, size_t count, int flags)
3909{
3910 ssize_t ret;
3911 size_t try, done;
3912 int send_flag;
3913
3914 if (!conn_ctrl_ready(conn))
3915 return 0;
3916
3917 if (!fd_send_ready(conn->handle.fd))
3918 return 0;
3919
3920 done = 0;
3921 /* send the largest possible block. For this we perform only one call
3922 * to send() unless the buffer wraps and we exactly fill the first hunk,
3923 * in which case we accept to do it once again.
3924 */
3925 while (count) {
3926 try = b_contig_data(buf, done);
3927 if (try > count)
3928 try = count;
3929
3930 send_flag = MSG_DONTWAIT | MSG_NOSIGNAL;
3931 if (try < count || flags & CO_SFL_MSG_MORE)
3932 send_flag |= MSG_MORE;
3933
3934 ret = sendto(conn->handle.fd, b_peek(buf, done), try, send_flag,
3935 (struct sockaddr *)conn->dst, get_addr_len(conn->dst));
3936 if (ret > 0) {
3937 count -= ret;
3938 done += ret;
3939
3940 /* A send succeeded, so we can consier ourself connected */
3941 conn->flags |= CO_FL_WAIT_L4L6;
3942 /* if the system buffer is full, don't insist */
3943 if (ret < try)
3944 break;
3945 }
3946 else if (ret == 0 || errno == EAGAIN || errno == ENOTCONN || errno == EINPROGRESS) {
3947 /* nothing written, we need to poll for write first */
3948 fd_cant_send(conn->handle.fd);
3949 break;
3950 }
3951 else if (errno != EINTR) {
3952 conn->flags |= CO_FL_ERROR | CO_FL_SOCK_RD_SH | CO_FL_SOCK_WR_SH;
3953 break;
3954 }
3955 }
3956 if (unlikely(conn->flags & CO_FL_WAIT_L4_CONN) && done)
3957 conn->flags &= ~CO_FL_WAIT_L4_CONN;
3958
3959 if (done > 0) {
3960 /* we count the total bytes sent, and the send rate for 32-byte
3961 * blocks. The reason for the latter is that freq_ctr are
3962 * limited to 4GB and that it's not enough per second.
3963 */
3964 _HA_ATOMIC_ADD(&global.out_bytes, done);
3965 update_freq_ctr(&global.out_32bps, (done + 16) / 32);
3966 }
3967 return done;
3968}
3969
3970/* Initialize a QUIC connection (quic_conn struct) to be attached to <conn>
3971 * connection with <xprt_ctx> as address of the xprt context.
3972 * Returns 1 if succeeded, 0 if not.
3973 */
3974static int qc_conn_init(struct connection *conn, void **xprt_ctx)
3975{
3976 struct quic_conn_ctx *ctx;
3977
3978 TRACE_ENTER(QUIC_EV_CONN_NEW, conn);
3979
3980 if (*xprt_ctx)
3981 goto out;
3982
3983 if (!conn_ctrl_ready(conn))
3984 goto out;
3985
3986 ctx = pool_alloc(pool_head_quic_conn_ctx);
3987 if (!ctx) {
3988 conn->err_code = CO_ER_SYS_MEMLIM;
3989 goto err;
3990 }
3991
3992 ctx->wait_event.tasklet = tasklet_new();
3993 if (!ctx->wait_event.tasklet) {
3994 conn->err_code = CO_ER_SYS_MEMLIM;
3995 goto err;
3996 }
3997
3998 ctx->wait_event.tasklet->process = quic_conn_io_cb;
3999 ctx->wait_event.tasklet->context = ctx;
4000 ctx->wait_event.events = 0;
4001 ctx->conn = conn;
4002 ctx->subs = NULL;
4003 ctx->xprt_ctx = NULL;
4004
4005 ctx->xprt = xprt_get(XPRT_QUIC);
4006 if (objt_server(conn->target)) {
4007 /* Server */
4008 struct server *srv = __objt_server(conn->target);
4009 unsigned char dcid[QUIC_CID_LEN];
4010 struct quic_conn *quic_conn;
4011 int ssl_err, ipv4;
4012
4013 ssl_err = SSL_ERROR_NONE;
4014 if (RAND_bytes(dcid, sizeof dcid) != 1)
4015 goto err;
4016
4017 conn->qc = new_quic_conn(QUIC_PROTOCOL_VERSION_DRAFT_28);
4018 if (!conn->qc)
4019 goto err;
4020
4021 quic_conn = conn->qc;
4022 quic_conn->conn = conn;
4023 ipv4 = conn->dst->ss_family == AF_INET;
4024 if (!qc_new_conn_init(quic_conn, ipv4, NULL, &srv->cids,
4025 dcid, sizeof dcid, NULL, 0))
4026 goto err;
4027
4028 if (!qc_new_isecs(conn, dcid, sizeof dcid, 0))
4029 goto err;
4030
4031 ctx->state = QUIC_HS_ST_CLIENT_INITIAL;
4032 if (ssl_bio_and_sess_init(conn, srv->ssl_ctx.ctx,
4033 &ctx->ssl, &ctx->bio, ha_quic_meth, ctx) == -1)
4034 goto err;
4035
4036 quic_conn->params = srv->quic_params;
4037 /* Copy the initial source connection ID. */
4038 quic_cid_cpy(&quic_conn->params.initial_source_connection_id, &quic_conn->scid);
4039 quic_conn->enc_params_len =
4040 quic_transport_params_encode(quic_conn->enc_params,
4041 quic_conn->enc_params + sizeof quic_conn->enc_params,
4042 &quic_conn->params, 0);
4043 if (!quic_conn->enc_params_len)
4044 goto err;
4045
4046 SSL_set_quic_transport_params(ctx->ssl, quic_conn->enc_params, quic_conn->enc_params_len);
4047 SSL_set_connect_state(ctx->ssl);
4048 ssl_err = SSL_do_handshake(ctx->ssl);
4049 if (ssl_err != 1) {
4050 ssl_err = SSL_get_error(ctx->ssl, ssl_err);
4051 if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
4052 TRACE_PROTO("SSL handshake",
4053 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
4054 }
4055 else {
4056 TRACE_DEVEL("SSL handshake error",
4057 QUIC_EV_CONN_HDSHK, ctx->conn, &ctx->state, &ssl_err);
4058 goto err;
4059 }
4060 }
4061 }
4062 else if (objt_listener(conn->target)) {
4063 /* Listener */
4064 struct bind_conf *bc = __objt_listener(conn->target)->bind_conf;
4065
4066 ctx->state = QUIC_HS_ST_SERVER_INITIAL;
4067
4068 if (ssl_bio_and_sess_init(conn, bc->initial_ctx,
4069 &ctx->ssl, &ctx->bio, ha_quic_meth, ctx) == -1)
4070 goto err;
4071
4072 SSL_set_accept_state(ctx->ssl);
4073 }
4074
4075 *xprt_ctx = ctx;
4076
4077 /* Leave init state and start handshake */
4078 conn->flags |= CO_FL_SSL_WAIT_HS | CO_FL_WAIT_L6_CONN;
4079 /* Start the handshake */
4080 tasklet_wakeup(ctx->wait_event.tasklet);
4081
4082 out:
4083 TRACE_LEAVE(QUIC_EV_CONN_NEW, conn);
4084
4085 return 0;
4086
4087 err:
4088 if (ctx->wait_event.tasklet)
4089 tasklet_free(ctx->wait_event.tasklet);
4090 pool_free(pool_head_quic_conn_ctx, ctx);
4091 TRACE_DEVEL("leaving in error", QUIC_EV_CONN_NEW|QUIC_EV_CONN_ENEW, conn);
4092 return -1;
4093}
4094
4095/* transport-layer operations for QUIC connections. */
4096static struct xprt_ops ssl_quic = {
4097 .snd_buf = quic_conn_from_buf,
4098 .rcv_buf = quic_conn_to_buf,
4099 .init = qc_conn_init,
4100 .prepare_bind_conf = ssl_sock_prepare_bind_conf,
4101 .destroy_bind_conf = ssl_sock_destroy_bind_conf,
4102 .name = "QUIC",
4103};
4104
4105__attribute__((constructor))
4106static void __quic_conn_init(void)
4107{
4108 ha_quic_meth = BIO_meth_new(0x666, "ha QUIC methods");
4109 xprt_register(XPRT_QUIC, &ssl_quic);
4110}
4111
4112__attribute__((destructor))
4113static void __quic_conn_deinit(void)
4114{
4115 BIO_meth_free(ha_quic_meth);
4116}
4117
4118/* Read all the QUIC packets found in <buf> with <len> as length (typically a UDP
4119 * datagram), <ctx> being the QUIC I/O handler context, from QUIC connections,
4120 * calling <func> function;
4121 * Return the number of bytes read if succeded, -1 if not.
4122 */
4123static ssize_t quic_dgram_read(char *buf, size_t len, void *owner,
4124 struct sockaddr_storage *saddr, qpkt_read_func *func)
4125{
4126 unsigned char *pos;
4127 const unsigned char *end;
4128 struct quic_dgram_ctx dgram_ctx = {
4129 .dcid_node = NULL,
4130 .owner = owner,
4131 };
4132
4133 pos = (unsigned char *)buf;
4134 end = pos + len;
4135
4136 do {
4137 int ret;
4138 struct quic_rx_packet *pkt;
4139
4140 pkt = pool_alloc(pool_head_quic_rx_packet);
4141 if (!pkt)
4142 goto err;
4143
4144 memset(pkt, 0, sizeof(*pkt));
4145 quic_rx_packet_refinc(pkt);
4146 ret = func(&pos, end, pkt, &dgram_ctx, saddr);
4147 if (ret == -1) {
4148 size_t pkt_len;
4149
4150 pkt_len = pkt->len;
4151 free_quic_rx_packet(pkt);
4152 /* If the packet length could not be found, we cannot continue. */
4153 if (!pkt_len)
4154 break;
4155 }
4156 } while (pos < end);
4157
4158 /* Increasing the received bytes counter by the UDP datagram length
4159 * if this datagram could be associated to a connection.
4160 */
4161 if (dgram_ctx.qc)
4162 dgram_ctx.qc->rx.bytes += len;
4163
4164 return pos - (unsigned char *)buf;
4165
4166 err:
4167 return -1;
4168}
4169
4170ssize_t quic_lstnr_dgram_read(char *buf, size_t len, void *owner,
4171 struct sockaddr_storage *saddr)
4172{
4173 return quic_dgram_read(buf, len, owner, saddr, qc_lstnr_pkt_rcv);
4174}
4175
4176ssize_t quic_srv_dgram_read(char *buf, size_t len, void *owner,
4177 struct sockaddr_storage *saddr)
4178{
4179 return quic_dgram_read(buf, len, owner, saddr, qc_srv_pkt_rcv);
4180}
4181
4182/* QUIC I/O handler for connection to local listeners or remove servers
4183 * depending on <listener> boolean value, with <fd> as socket file
4184 * descriptor and <ctx> as context.
4185 */
4186static size_t quic_conn_handler(int fd, void *ctx, qpkt_read_func *func)
4187{
4188 ssize_t ret;
4189 size_t done = 0;
4190 struct buffer *buf = get_trash_chunk();
4191 /* Source address */
4192 struct sockaddr_storage saddr = {0};
4193 socklen_t saddrlen = sizeof saddr;
4194
4195 if (!fd_recv_ready(fd))
4196 return 0;
4197
4198 do {
4199 ret = recvfrom(fd, buf->area, buf->size, 0,
4200 (struct sockaddr *)&saddr, &saddrlen);
4201 if (ret < 0) {
4202 if (errno == EINTR)
4203 continue;
4204 if (errno == EAGAIN)
4205 fd_cant_recv(fd);
4206 goto out;
4207 }
4208 } while (0);
4209
4210 done = buf->data = ret;
4211 quic_dgram_read(buf->area, buf->data, ctx, &saddr, func);
4212
4213 out:
4214 return done;
4215}
4216
4217/* QUIC I/O handler for connections to local listeners with <fd> as socket
4218 * file descriptor.
4219 */
4220void quic_fd_handler(int fd)
4221{
4222 if (fdtab[fd].ev & FD_POLL_IN)
4223 quic_conn_handler(fd, fdtab[fd].owner, &qc_lstnr_pkt_rcv);
4224}
4225
4226/* QUIC I/O handler for connections to remote servers with <fd> as socket
4227 * file descriptor.
4228 */
4229void quic_conn_fd_handler(int fd)
4230{
4231 if (fdtab[fd].ev & FD_POLL_IN)
4232 quic_conn_handler(fd, fdtab[fd].owner, &qc_srv_pkt_rcv);
4233}
4234
4235/*
4236 * Local variables:
4237 * c-indent-level: 8
4238 * c-basic-offset: 8
4239 * End:
4240 */