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