]> git.ipfire.org Git - thirdparty/openssl.git/blame - ssl/quic/quic_channel.c
QUIC Front End I/O API: Remove __owur from man pages
[thirdparty/openssl.git] / ssl / quic / quic_channel.c
CommitLineData
f538b421
HL
1/*
2 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10#include "internal/quic_channel.h"
11#include "internal/quic_error.h"
12#include "internal/quic_rx_depack.h"
13#include "../ssl_local.h"
14#include "quic_channel_local.h"
15#include <openssl/rand.h>
16
17#define INIT_DCID_LEN 8
18#define INIT_CRYPTO_BUF_LEN 8192
19#define INIT_APP_BUF_LEN 8192
20
3bf4dc8c 21static void ch_rx_pre(QUIC_CHANNEL *ch);
f538b421
HL
22static int ch_rx(QUIC_CHANNEL *ch);
23static int ch_tx(QUIC_CHANNEL *ch);
24static void ch_tick(QUIC_TICK_RESULT *res, void *arg);
25static void ch_rx_handle_packet(QUIC_CHANNEL *ch);
26static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch);
27static int ch_retry(QUIC_CHANNEL *ch,
28 const unsigned char *retry_token,
29 size_t retry_token_len,
30 const QUIC_CONN_ID *retry_scid);
31static void ch_cleanup(QUIC_CHANNEL *ch);
32static int ch_generate_transport_params(QUIC_CHANNEL *ch);
33static int ch_on_transport_params(const unsigned char *params,
34 size_t params_len,
35 void *arg);
36static int ch_on_handshake_alert(void *arg, unsigned char alert_code);
37static int ch_on_handshake_complete(void *arg);
38static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
39 uint32_t suite_id, EVP_MD *md,
40 const unsigned char *secret,
41 size_t secret_len,
42 void *arg);
43static int ch_on_crypto_recv(unsigned char *buf, size_t buf_len,
44 size_t *bytes_read, void *arg);
45static int crypto_ensure_empty(QUIC_RSTREAM *rstream);
46static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
47 size_t *consumed, void *arg);
48static OSSL_TIME get_time(void *arg);
49static uint64_t get_stream_limit(int uni, void *arg);
50static int rx_early_validate(QUIC_PN pn, int pn_space, void *arg);
51static int ch_retry(QUIC_CHANNEL *ch,
52 const unsigned char *retry_token,
53 size_t retry_token_len,
54 const QUIC_CONN_ID *retry_scid);
55static void ch_update_idle(QUIC_CHANNEL *ch);
56static int ch_discard_el(QUIC_CHANNEL *ch,
57 uint32_t enc_level);
58static void ch_on_idle_timeout(QUIC_CHANNEL *ch);
59static void ch_update_idle(QUIC_CHANNEL *ch);
60static void ch_on_terminating_timeout(QUIC_CHANNEL *ch);
61static void ch_start_terminating(QUIC_CHANNEL *ch,
62 const QUIC_TERMINATE_CAUSE *tcause);
63
64static int gen_rand_conn_id(OSSL_LIB_CTX *libctx, size_t len, QUIC_CONN_ID *cid)
65{
66 if (len > QUIC_MAX_CONN_ID_LEN)
67 return 0;
68
69 cid->id_len = (unsigned char)len;
70
71 if (RAND_bytes_ex(libctx, cid->id, len, len * 8) != 1) {
72 cid->id_len = 0;
73 return 0;
74 }
75
76 return 1;
77}
78
79/*
80 * QUIC Channel Initialization and Teardown
81 * ========================================
82 */
83static int ch_init(QUIC_CHANNEL *ch)
84{
85 OSSL_QUIC_TX_PACKETISER_ARGS txp_args = {0};
86 OSSL_QTX_ARGS qtx_args = {0};
87 OSSL_QRX_ARGS qrx_args = {0};
88 QUIC_DHS_ARGS dhs_args = {0};
89 uint32_t pn_space;
90
6292519c 91 /* TODO(QUIC): This is only applicable to clients. */
f538b421
HL
92 if (!gen_rand_conn_id(ch->libctx, INIT_DCID_LEN, &ch->init_dcid))
93 goto err;
94
95 /* We plug in a network write BIO to the QTX later when we get one. */
96 qtx_args.mdpl = QUIC_MIN_INITIAL_DGRAM_LEN;
97 ch->rx_max_udp_payload_size = qtx_args.mdpl;
98
99 ch->qtx = ossl_qtx_new(&qtx_args);
100 if (ch->qtx == NULL)
101 goto err;
102
103 ch->txpim = ossl_quic_txpim_new();
104 if (ch->txpim == NULL)
105 goto err;
106
107 ch->cfq = ossl_quic_cfq_new();
108 if (ch->cfq == NULL)
109 goto err;
110
111 if (!ossl_quic_txfc_init(&ch->conn_txfc, NULL))
112 goto err;
113
114 if (!ossl_quic_rxfc_init(&ch->conn_rxfc, NULL,
115 2 * 1024 * 1024,
116 10 * 1024 * 1024,
117 get_time, NULL))
118 goto err;
119
120 if (!ossl_statm_init(&ch->statm))
121 goto err;
122
123 ch->have_statm = 1;
124 ch->cc_method = &ossl_cc_dummy_method;
125 if ((ch->cc_data = ch->cc_method->new(NULL, NULL, NULL)) == NULL)
126 goto err;
127
128 if ((ch->ackm = ossl_ackm_new(get_time, NULL, &ch->statm,
129 ch->cc_method, ch->cc_data)) == NULL)
130 goto err;
131
132 if (!ossl_quic_stream_map_init(&ch->qsm, get_stream_limit, ch))
133 goto err;
134
135 ch->have_qsm = 1;
136
137 /* We use a zero-length SCID. */
138 txp_args.cur_dcid = ch->init_dcid;
139 txp_args.ack_delay_exponent = 3;
140 txp_args.qtx = ch->qtx;
141 txp_args.txpim = ch->txpim;
142 txp_args.cfq = ch->cfq;
143 txp_args.ackm = ch->ackm;
144 txp_args.qsm = &ch->qsm;
145 txp_args.conn_txfc = &ch->conn_txfc;
146 txp_args.conn_rxfc = &ch->conn_rxfc;
147 txp_args.cc_method = ch->cc_method;
148 txp_args.cc_data = ch->cc_data;
149 txp_args.now = get_time;
150 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
151 ch->crypto_send[pn_space] = ossl_quic_sstream_new(INIT_CRYPTO_BUF_LEN);
152 if (ch->crypto_send[pn_space] == NULL)
153 goto err;
154
155 txp_args.crypto[pn_space] = ch->crypto_send[pn_space];
156 }
157
158 ch->txp = ossl_quic_tx_packetiser_new(&txp_args);
159 if (ch->txp == NULL)
160 goto err;
161
162 if ((ch->demux = ossl_quic_demux_new(/*BIO=*/NULL, /*Short CID Len=*/0,
d7668ff2 163 get_time, NULL)) == NULL)
f538b421
HL
164 goto err;
165
166 qrx_args.demux = ch->demux;
167 qrx_args.short_conn_id_len = 0; /* We use a zero-length SCID. */
168 qrx_args.max_deferred = 32;
169
170 if ((ch->qrx = ossl_qrx_new(&qrx_args)) == NULL)
171 goto err;
172
173 if (!ossl_qrx_set_early_validation_cb(ch->qrx,
174 rx_early_validate,
175 ch))
176 goto err;
177
178 if (!ossl_qrx_add_dst_conn_id(ch->qrx, &txp_args.cur_scid))
179 goto err;
180
181 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
182 ch->crypto_recv[pn_space] = ossl_quic_rstream_new(NULL, NULL);
183 if (ch->crypto_recv[pn_space] == NULL)
184 goto err;
185 }
186
187 if ((ch->stream0 = ossl_quic_stream_map_alloc(&ch->qsm, 0,
188 QUIC_STREAM_INITIATOR_CLIENT
189 | QUIC_STREAM_DIR_BIDI)) == NULL)
190 goto err;
191
192 if ((ch->stream0->sstream = ossl_quic_sstream_new(INIT_APP_BUF_LEN)) == NULL)
193 goto err;
194
195 if ((ch->stream0->rstream = ossl_quic_rstream_new(NULL, NULL)) == NULL)
196 goto err;
197
198 if (!ossl_quic_txfc_init(&ch->stream0->txfc, &ch->conn_txfc))
199 goto err;
200
201 if (!ossl_quic_rxfc_init(&ch->stream0->rxfc, &ch->conn_rxfc,
202 1 * 1024 * 1024,
203 5 * 1024 * 1024,
204 get_time, NULL))
205 goto err;
206
207 /* Plug in the dummy handshake layer. */
208 dhs_args.crypto_send_cb = ch_on_crypto_send;
209 dhs_args.crypto_send_cb_arg = ch;
210 dhs_args.crypto_recv_cb = ch_on_crypto_recv;
211 dhs_args.crypto_recv_cb_arg = ch;
212 dhs_args.yield_secret_cb = ch_on_handshake_yield_secret;
213 dhs_args.yield_secret_cb_arg = ch;
214 dhs_args.got_transport_params_cb = ch_on_transport_params;
215 dhs_args.got_transport_params_cb_arg= ch;
216 dhs_args.handshake_complete_cb = ch_on_handshake_complete;
217 dhs_args.handshake_complete_cb_arg = ch;
218 dhs_args.alert_cb = ch_on_handshake_alert;
219 dhs_args.alert_cb_arg = ch;
220
221 if ((ch->dhs = ossl_quic_dhs_new(&dhs_args)) == NULL)
222 goto err;
223
224 /*
225 * Determine the QUIC Transport Parameters and serialize the transport
226 * parameters block. (For servers, we do this later as we must defer
227 * generation until we have received the client's transport parameters.)
228 */
229 if (!ch->is_server && !ch_generate_transport_params(ch))
230 goto err;
231
232 ch->rx_max_ack_delay = QUIC_DEFAULT_MAX_ACK_DELAY;
233 ch->rx_ack_delay_exp = QUIC_DEFAULT_ACK_DELAY_EXP;
234 ch->rx_active_conn_id_limit = QUIC_MIN_ACTIVE_CONN_ID_LIMIT;
235 ch->max_idle_timeout = QUIC_DEFAULT_IDLE_TIMEOUT;
236 ch->tx_enc_level = QUIC_ENC_LEVEL_INITIAL;
45ecfc9b 237 ch->rx_enc_level = QUIC_ENC_LEVEL_INITIAL;
f538b421
HL
238 ch_update_idle(ch);
239 ossl_quic_reactor_init(&ch->rtor, ch_tick, ch,
240 ch_determine_next_tick_deadline(ch));
241 return 1;
242
243err:
244 ch_cleanup(ch);
245 return 0;
246}
247
248static void ch_cleanup(QUIC_CHANNEL *ch)
249{
250 uint32_t pn_space;
251
252 if (ch->ackm != NULL)
253 for (pn_space = QUIC_PN_SPACE_INITIAL;
254 pn_space < QUIC_PN_SPACE_NUM;
255 ++pn_space)
256 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
257
258 ossl_quic_tx_packetiser_free(ch->txp);
259 ossl_quic_txpim_free(ch->txpim);
260 ossl_quic_cfq_free(ch->cfq);
261 ossl_qtx_free(ch->qtx);
262 if (ch->cc_data != NULL)
263 ch->cc_method->free(ch->cc_data);
264 if (ch->have_statm)
265 ossl_statm_destroy(&ch->statm);
266 ossl_ackm_free(ch->ackm);
267
268 if (ch->stream0 != NULL) {
269 assert(ch->have_qsm);
270 ossl_quic_stream_map_release(&ch->qsm, ch->stream0); /* frees sstream */
271 }
272
273 if (ch->have_qsm)
274 ossl_quic_stream_map_cleanup(&ch->qsm);
275
276 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space) {
277 ossl_quic_sstream_free(ch->crypto_send[pn_space]);
278 ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
279 }
280
281 ossl_qrx_pkt_release(ch->qrx_pkt);
282 ch->qrx_pkt = NULL;
283
284 ossl_quic_dhs_free(ch->dhs);
285 ossl_qrx_free(ch->qrx);
286 ossl_quic_demux_free(ch->demux);
287 OPENSSL_free(ch->local_transport_params);
f538b421
HL
288}
289
290QUIC_CHANNEL *ossl_quic_channel_new(const QUIC_CHANNEL_ARGS *args)
291{
292 QUIC_CHANNEL *ch = NULL;
293
294 if ((ch = OPENSSL_zalloc(sizeof(*ch))) == NULL)
295 return NULL;
296
297 ch->libctx = args->libctx;
298 ch->propq = args->propq;
299 ch->is_server = args->is_server;
300
301 if (!ch_init(ch)) {
302 OPENSSL_free(ch);
303 return NULL;
304 }
305
306 return ch;
307}
308
309void ossl_quic_channel_free(QUIC_CHANNEL *ch)
310{
311 if (ch == NULL)
312 return;
313
314 ch_cleanup(ch);
315 OPENSSL_free(ch);
316}
317
318int ossl_quic_channel_get_peer_addr(QUIC_CHANNEL *ch, BIO_ADDR *peer_addr)
319{
320 *peer_addr = ch->cur_peer_addr;
321 return 1;
322}
323
324int ossl_quic_channel_set_peer_addr(QUIC_CHANNEL *ch, const BIO_ADDR *peer_addr)
325{
326 ch->cur_peer_addr = *peer_addr;
327 return 1;
328}
329
330QUIC_REACTOR *ossl_quic_channel_get_reactor(QUIC_CHANNEL *ch)
331{
332 return &ch->rtor;
333}
334
335QUIC_STREAM_MAP *ossl_quic_channel_get_qsm(QUIC_CHANNEL *ch)
336{
337 return &ch->qsm;
338}
339
340OSSL_STATM *ossl_quic_channel_get_statm(QUIC_CHANNEL *ch)
341{
342 return &ch->statm;
343}
344
345QUIC_STREAM *ossl_quic_channel_get_stream_by_id(QUIC_CHANNEL *ch,
346 uint64_t stream_id)
347{
348 return ossl_quic_stream_map_get_by_id(&ch->qsm, stream_id);
349}
350
351int ossl_quic_channel_is_active(const QUIC_CHANNEL *ch)
352{
353 return ch != NULL && ch->state == QUIC_CHANNEL_STATE_ACTIVE;
354}
355
356int ossl_quic_channel_is_terminating(const QUIC_CHANNEL *ch)
357{
358 return ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING
359 || ch->state == QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
360}
361
362int ossl_quic_channel_is_terminated(const QUIC_CHANNEL *ch)
363{
364 return ch->state == QUIC_CHANNEL_STATE_TERMINATED;
365}
366
367int ossl_quic_channel_is_term_any(const QUIC_CHANNEL *ch)
368{
369 return ossl_quic_channel_is_terminating(ch)
370 || ossl_quic_channel_is_terminated(ch);
371}
372
373int ossl_quic_channel_is_handshake_complete(const QUIC_CHANNEL *ch)
374{
375 return ch->handshake_complete;
376}
377
378/*
379 * QUIC Channel: Callbacks from Miscellaneous Subsidiary Components
380 * ================================================================
381 */
382
383/* Used by various components. */
384static OSSL_TIME get_time(void *arg)
385{
386 return ossl_time_now();
387}
388
389/* Used by QSM. */
390static uint64_t get_stream_limit(int uni, void *arg)
391{
392 QUIC_CHANNEL *ch = arg;
393
394 return uni ? ch->max_local_streams_uni : ch->max_local_streams_bidi;
395}
396
397/*
398 * Called by QRX to determine if a packet is potentially invalid before trying
399 * to decrypt it.
400 */
401static int rx_early_validate(QUIC_PN pn, int pn_space, void *arg)
402{
403 QUIC_CHANNEL *ch = arg;
404
405 /* Potential duplicates should not be processed. */
406 if (!ossl_ackm_is_rx_pn_processable(ch->ackm, pn, pn_space))
407 return 0;
408
409 return 1;
410}
411
412/*
413 * QUIC Channel: Handshake Layer Event Handling
414 * ============================================
415 */
416static int ch_on_crypto_send(const unsigned char *buf, size_t buf_len,
417 size_t *consumed, void *arg)
418{
419 int ret;
420 QUIC_CHANNEL *ch = arg;
421 uint32_t enc_level = ch->tx_enc_level;
422 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
423 QUIC_SSTREAM *sstream = ch->crypto_send[pn_space];
424
425 if (!ossl_assert(sstream != NULL))
426 return 0;
427
428 ret = ossl_quic_sstream_append(sstream, buf, buf_len, consumed);
429 return ret;
430}
431
432static int crypto_ensure_empty(QUIC_RSTREAM *rstream)
433{
434 size_t avail = 0;
435 int is_fin = 0;
436
437 if (rstream == NULL)
438 return 1;
439
440 if (!ossl_quic_rstream_available(rstream, &avail, &is_fin))
441 return 0;
442
443 return avail == 0;
444}
445
446static int ch_on_crypto_recv(unsigned char *buf, size_t buf_len,
447 size_t *bytes_read, void *arg)
448{
449 QUIC_CHANNEL *ch = arg;
450 QUIC_RSTREAM *rstream;
451 int is_fin = 0; /* crypto stream is never finished, so we don't use this */
452 uint32_t i;
453
454 /*
455 * After we move to a later EL we must not allow our peer to send any new
456 * bytes in the crypto stream on a previous EL. Retransmissions of old bytes
457 * are allowed.
458 *
459 * In practice we will only move to a new EL when we have consumed all bytes
460 * which should be sent on the crypto stream at a previous EL. For example,
461 * the Handshake EL should not be provisioned until we have completely
462 * consumed a TLS 1.3 ServerHello. Thus when we provision an EL the output
463 * of ossl_quic_rstream_available() should be 0 for all lower ELs. Thus if a
464 * given EL is available we simply ensure we have not received any further
465 * bytes at a lower EL.
466 */
45ecfc9b 467 for (i = QUIC_ENC_LEVEL_INITIAL; i < ch->rx_enc_level; ++i)
f538b421
HL
468 if (i != QUIC_ENC_LEVEL_0RTT &&
469 !crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
470 /* Protocol violation (RFC 9001 s. 4.1.3) */
471 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
472 OSSL_QUIC_FRAME_TYPE_CRYPTO,
473 "crypto stream data in wrong EL");
474 return 0;
475 }
476
45ecfc9b 477 rstream = ch->crypto_recv[ossl_quic_enc_level_to_pn_space(ch->rx_enc_level)];
f538b421
HL
478 if (rstream == NULL)
479 return 0;
480
481 return ossl_quic_rstream_read(rstream, buf, buf_len, bytes_read,
482 &is_fin);
483}
484
485static int ch_on_handshake_yield_secret(uint32_t enc_level, int direction,
486 uint32_t suite_id, EVP_MD *md,
487 const unsigned char *secret,
488 size_t secret_len,
489 void *arg)
490{
491 QUIC_CHANNEL *ch = arg;
492 uint32_t i;
493
494 if (enc_level < QUIC_ENC_LEVEL_HANDSHAKE || enc_level >= QUIC_ENC_LEVEL_NUM)
495 /* Invalid EL. */
496 return 0;
497
f538b421
HL
498
499 if (direction) {
500 /* TX */
45ecfc9b
MC
501 if (enc_level <= ch->tx_enc_level)
502 /*
9f0ade7c
HL
503 * Does not make sense for us to try and provision an EL we have already
504 * attained.
505 */
45ecfc9b
MC
506 return 0;
507
f538b421
HL
508 if (!ossl_qtx_provide_secret(ch->qtx, enc_level,
509 suite_id, md,
510 secret, secret_len))
511 return 0;
512
513 ch->tx_enc_level = enc_level;
514 } else {
515 /* RX */
45ecfc9b
MC
516 if (enc_level <= ch->rx_enc_level)
517 /*
9f0ade7c
HL
518 * Does not make sense for us to try and provision an EL we have already
519 * attained.
520 */
45ecfc9b
MC
521 return 0;
522
523 /*
9f0ade7c
HL
524 * Ensure all crypto streams for previous ELs are now empty of available
525 * data.
526 */
45ecfc9b 527 for (i = QUIC_ENC_LEVEL_INITIAL; i < enc_level; ++i)
e28f512f 528 if (!crypto_ensure_empty(ch->crypto_recv[ossl_quic_enc_level_to_pn_space(i)])) {
45ecfc9b
MC
529 /* Protocol violation (RFC 9001 s. 4.1.3) */
530 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
531 OSSL_QUIC_FRAME_TYPE_CRYPTO,
532 "crypto stream data in wrong EL");
533 return 0;
534 }
535
f538b421
HL
536 if (!ossl_qrx_provide_secret(ch->qrx, enc_level,
537 suite_id, md,
538 secret, secret_len))
539 return 0;
92282a17
HL
540
541 ch->have_new_rx_secret = 1;
45ecfc9b 542 ch->rx_enc_level = enc_level;
f538b421
HL
543 }
544
545 return 1;
546}
547
548static int ch_on_handshake_complete(void *arg)
549{
550 QUIC_CHANNEL *ch = arg;
551
e28f512f 552 if (!ossl_assert(!ch->handshake_complete))
f538b421
HL
553 return 0; /* this should not happen twice */
554
555 if (!ossl_assert(ch->tx_enc_level == QUIC_ENC_LEVEL_1RTT))
556 return 0;
557
558 if (!ch->got_remote_transport_params)
559 /*
560 * Was not a valid QUIC handshake if we did not get valid transport
561 * params.
562 */
563 return 0;
564
565 /* Don't need transport parameters anymore. */
566 OPENSSL_free(ch->local_transport_params);
567 ch->local_transport_params = NULL;
568
569 /* Tell TXP the handshake is complete. */
570 ossl_quic_tx_packetiser_notify_handshake_complete(ch->txp);
571
572 ch->handshake_complete = 1;
573 return 1;
574}
575
576static int ch_on_handshake_alert(void *arg, unsigned char alert_code)
577{
578 QUIC_CHANNEL *ch = arg;
579
580 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_CRYPTO_ERR_BEGIN + alert_code,
581 0, "handshake alert");
582 return 1;
583}
584
585/*
586 * QUIC Channel: Transport Parameter Handling
587 * ==========================================
588 */
589
590/*
591 * Called by handshake layer when we receive QUIC Transport Parameters from the
592 * peer. Note that these are not authenticated until the handshake is marked
593 * as complete.
594 */
595static int ch_on_transport_params(const unsigned char *params,
596 size_t params_len,
597 void *arg)
598{
599 QUIC_CHANNEL *ch = arg;
600 PACKET pkt;
601 uint64_t id, v;
602 size_t len;
603 const unsigned char *body;
604 int got_orig_dcid = 0;
605 int got_initial_scid = 0;
606 int got_retry_scid = 0;
607 int got_initial_max_data = 0;
608 int got_initial_max_stream_data_bidi_local = 0;
609 int got_initial_max_stream_data_bidi_remote = 0;
610 int got_initial_max_stream_data_uni = 0;
611 int got_initial_max_streams_bidi = 0;
612 int got_initial_max_streams_uni = 0;
613 int got_ack_delay_exp = 0;
614 int got_max_ack_delay = 0;
615 int got_max_udp_payload_size = 0;
616 int got_max_idle_timeout = 0;
617 int got_active_conn_id_limit = 0;
618 QUIC_CONN_ID cid;
619
620 if (ch->got_remote_transport_params)
621 goto malformed;
622
623 if (!PACKET_buf_init(&pkt, params, params_len))
624 return 0;
625
626 while (PACKET_remaining(&pkt) > 0) {
627 if (!ossl_quic_wire_peek_transport_param(&pkt, &id))
628 goto malformed;
629
630 switch (id) {
631 case QUIC_TPARAM_ORIG_DCID:
632 if (got_orig_dcid)
633 /* must not appear more than once */
634 goto malformed;
635
636 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid))
637 goto malformed;
638
639 /* Must match our initial DCID. */
640 if (!ossl_quic_conn_id_eq(&ch->init_dcid, &cid))
641 goto malformed;
642
643 got_orig_dcid = 1;
644 break;
645
646 case QUIC_TPARAM_RETRY_SCID:
647 if (got_retry_scid || !ch->doing_retry)
648 /* must not appear more than once or if retry not done */
649 goto malformed;
650
651 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid))
652 goto malformed;
653
654 /* Must match Retry packet SCID. */
655 if (!ossl_quic_conn_id_eq(&ch->retry_scid, &cid))
656 goto malformed;
657
658 got_retry_scid = 1;
659 break;
660
661 case QUIC_TPARAM_INITIAL_SCID:
662 if (got_initial_scid)
663 /* must not appear more than once */
664 goto malformed;
665
666 if (!ossl_quic_wire_decode_transport_param_cid(&pkt, NULL, &cid))
667 goto malformed;
668
669 /* Must match SCID of first Initial packet from server. */
670 if (!ossl_quic_conn_id_eq(&ch->init_scid, &cid))
671 goto malformed;
672
673 got_initial_scid = 1;
674 break;
675
676 case QUIC_TPARAM_INITIAL_MAX_DATA:
677 if (got_initial_max_data)
678 /* must not appear more than once */
679 goto malformed;
680
681 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v))
682 goto malformed;
683
684 ossl_quic_txfc_bump_cwm(&ch->conn_txfc, v);
685 got_initial_max_data = 1;
686 break;
687
688 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL:
689 if (got_initial_max_stream_data_bidi_local)
690 /* must not appear more than once */
691 goto malformed;
692
693 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v))
694 goto malformed;
695
696 /*
697 * This is correct; the BIDI_LOCAL TP governs streams created by
698 * the endpoint which sends the TP, i.e., our peer.
699 */
700 ch->init_max_stream_data_bidi_remote = v;
701 got_initial_max_stream_data_bidi_local = 1;
702 break;
703
704 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE:
705 if (got_initial_max_stream_data_bidi_remote)
706 /* must not appear more than once */
707 goto malformed;
708
709 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v))
710 goto malformed;
711
712 /*
713 * This is correct; the BIDI_REMOTE TP governs streams created
714 * by the endpoint which receives the TP, i.e., us.
715 */
716 ch->init_max_stream_data_bidi_local = v;
717
718 /* Apply to stream 0. */
719 ossl_quic_txfc_bump_cwm(&ch->stream0->txfc, v);
720 got_initial_max_stream_data_bidi_remote = 1;
721 break;
722
723 case QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI:
724 if (got_initial_max_stream_data_uni)
725 /* must not appear more than once */
726 goto malformed;
727
728 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v))
729 goto malformed;
730
731 ch->init_max_stream_data_uni_remote = v;
732 got_initial_max_stream_data_uni = 1;
733 break;
734
735 case QUIC_TPARAM_ACK_DELAY_EXP:
736 if (got_ack_delay_exp)
737 /* must not appear more than once */
738 goto malformed;
739
740 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
741 || v > QUIC_MAX_ACK_DELAY_EXP)
742 goto malformed;
743
744 ch->rx_ack_delay_exp = (unsigned char)v;
745 got_ack_delay_exp = 1;
746 break;
747
748 case QUIC_TPARAM_MAX_ACK_DELAY:
749 if (got_max_ack_delay)
750 /* must not appear more than once */
751 return 0;
752
753 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
754 || v >= (((uint64_t)1) << 14))
755 goto malformed;
756
757 ch->rx_max_ack_delay = v;
758 got_max_ack_delay = 1;
759 break;
760
761 case QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI:
762 if (got_initial_max_streams_bidi)
763 /* must not appear more than once */
764 return 0;
765
766 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
767 || v > (((uint64_t)1) << 60))
768 goto malformed;
769
770 assert(ch->max_local_streams_bidi == 0);
771 ch->max_local_streams_bidi = v;
772 got_initial_max_streams_bidi = 1;
773 break;
774
775 case QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI:
776 if (got_initial_max_streams_uni)
777 /* must not appear more than once */
778 goto malformed;
779
780 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
781 || v > (((uint64_t)1) << 60))
782 goto malformed;
783
784 assert(ch->max_local_streams_uni == 0);
785 ch->max_local_streams_uni = v;
786 got_initial_max_streams_uni = 1;
787 break;
788
789 case QUIC_TPARAM_MAX_IDLE_TIMEOUT:
790 if (got_max_idle_timeout)
791 /* must not appear more than once */
792 goto malformed;
793
794 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v))
795 goto malformed;
796
797 if (v < ch->max_idle_timeout)
798 ch->max_idle_timeout = v;
799
800 ch_update_idle(ch);
801 got_max_idle_timeout = 1;
802 break;
803
804 case QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE:
805 if (got_max_udp_payload_size)
806 /* must not appear more than once */
807 goto malformed;
808
809 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
810 || v < QUIC_MIN_INITIAL_DGRAM_LEN)
811 goto malformed;
812
813 ch->rx_max_udp_payload_size = v;
814 got_max_udp_payload_size = 1;
815 break;
816
817 case QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT:
818 if (got_active_conn_id_limit)
819 /* must not appear more than once */
820 goto malformed;
821
822 if (!ossl_quic_wire_decode_transport_param_int(&pkt, &id, &v)
823 || v < QUIC_MIN_ACTIVE_CONN_ID_LIMIT)
824 goto malformed;
825
826 ch->rx_active_conn_id_limit = v;
827 got_active_conn_id_limit = 1;
828 break;
829
830 /*
831 * TODO(QUIC): Handle:
832 * QUIC_TPARAM_STATELESS_RESET_TOKEN
833 * QUIC_TPARAM_PREFERRED_ADDR
834 */
835
836 case QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION:
837 /* We do not currently handle migration, so nothing to do. */
838 default:
839 /* Skip over and ignore. */
840 body = ossl_quic_wire_decode_transport_param_bytes(&pkt, &id,
841 &len);
842 if (body == NULL)
843 goto malformed;
844
845 break;
846 }
847 }
848
849 if (!got_orig_dcid || !got_initial_scid || got_retry_scid != ch->doing_retry)
850 /* Transport parameters were not valid. */
851 goto malformed;
852
853 ch->got_remote_transport_params = 1;
854
855 if (got_initial_max_data || got_initial_max_stream_data_bidi_remote
856 || got_initial_max_streams_bidi || got_initial_max_streams_uni)
857 /* If FC credit was bumped, we may now be able to send. */
858 ossl_quic_stream_map_update_state(&ch->qsm, ch->stream0);
859
860 /* If we are a server, we now generate our own transport parameters. */
861 if (ch->is_server && !ch_generate_transport_params(ch)) {
862 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_INTERNAL_ERROR, 0,
863 "internal error");
864 return 0;
865 }
866
867 return 1;
868
869malformed:
870 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_TRANSPORT_PARAMETER_ERROR,
871 0, "bad transport parameter");
872 return 0;
873}
874
875/*
876 * Called when we want to generate transport parameters. This is called
877 * immediately at instantiation time for a client and after we receive the
878 * client's transport parameters for a server.
879 */
880static int ch_generate_transport_params(QUIC_CHANNEL *ch)
881{
882 int ok = 0;
883 BUF_MEM *buf_mem = NULL;
884 WPACKET wpkt;
885 int wpkt_valid = 0;
886 size_t buf_len = 0;
887
888 if (ch->local_transport_params != NULL)
889 goto err;
890
891 if ((buf_mem = BUF_MEM_new()) == NULL)
892 goto err;
893
894 if (!WPACKET_init(&wpkt, buf_mem))
895 goto err;
896
897 wpkt_valid = 1;
898
899 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_DISABLE_ACTIVE_MIGRATION,
900 NULL, 0) == NULL)
901 goto err;
902
903 if (ossl_quic_wire_encode_transport_param_bytes(&wpkt, QUIC_TPARAM_INITIAL_SCID,
904 NULL, 0) == NULL)
905 goto err;
906
907 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_IDLE_TIMEOUT,
908 ch->max_idle_timeout))
909 goto err;
910
911 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_MAX_UDP_PAYLOAD_SIZE,
912 QUIC_MIN_INITIAL_DGRAM_LEN))
913 goto err;
914
915 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_ACTIVE_CONN_ID_LIMIT,
916 4))
917 goto err;
918
919 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_DATA,
920 ossl_quic_rxfc_get_cwm(&ch->conn_rxfc)))
921 goto err;
922
923 /*
924 * We actually want the default CWM for a new RXFC, but here we just use
925 * stream0 as a representative specimen. TODO(QUIC): revisit this when we
926 * support multiple streams.
927 */
928 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_LOCAL,
929 ossl_quic_rxfc_get_cwm(&ch->stream0->rxfc)))
930 goto err;
931
932 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_BIDI_REMOTE,
933 ossl_quic_rxfc_get_cwm(&ch->stream0->rxfc)))
934 goto err;
935
936 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAM_DATA_UNI,
937 ossl_quic_rxfc_get_cwm(&ch->stream0->rxfc)))
938 goto err;
939
940 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_BIDI,
941 0))
942 goto err;
943
944 if (!ossl_quic_wire_encode_transport_param_int(&wpkt, QUIC_TPARAM_INITIAL_MAX_STREAMS_UNI,
945 0))
946 goto err;
947
948 if (!WPACKET_get_total_written(&wpkt, &buf_len))
949 goto err;
950
951 ch->local_transport_params = (unsigned char *)buf_mem->data;
952 buf_mem->data = NULL;
953
954 if (!WPACKET_finish(&wpkt))
955 goto err;
956
957 wpkt_valid = 0;
958
959 if (!ossl_quic_dhs_set_transport_params(ch->dhs, ch->local_transport_params,
960 buf_len))
961 goto err;
962
963 ok = 1;
964err:
965 if (wpkt_valid)
966 WPACKET_cleanup(&wpkt);
967 BUF_MEM_free(buf_mem);
968 return ok;
969}
970
971/*
972 * QUIC Channel: Ticker-Mutator
973 * ============================
974 */
975
976/*
977 * The central ticker function called by the reactor. This does everything, or
978 * at least everything network I/O related. Best effort - not allowed to fail
979 * "loudly".
980 */
981static void ch_tick(QUIC_TICK_RESULT *res, void *arg)
982{
983 OSSL_TIME now, deadline;
984 QUIC_CHANNEL *ch = arg;
985
986 /*
987 * When we tick the QUIC connection, we do everything we need to do
988 * periodically. In order, we:
989 *
990 * - handle any incoming data from the network;
991 * - handle any timer events which are due to fire (ACKM, etc.)
992 * - write any data to the network due to be sent, to the extent
993 * possible;
994 * - determine the time at which we should next be ticked.
995 */
996
997 /* If we are in the TERMINATED state, there is nothing to do. */
998 if (ossl_quic_channel_is_terminated(ch)) {
999 res->want_net_read = 0;
1000 res->want_net_write = 0;
1001 res->tick_deadline = ossl_time_infinite();
1002 return;
1003 }
1004
1005 /*
1006 * If we are in the TERMINATING state, check if the terminating timer has
1007 * expired.
1008 */
1009 if (ossl_quic_channel_is_terminating(ch)) {
1010 now = ossl_time_now();
1011
1012 if (ossl_time_compare(now, ch->terminate_deadline) >= 0) {
1013 ch_on_terminating_timeout(ch);
1014 res->want_net_read = 0;
1015 res->want_net_write = 0;
1016 res->tick_deadline = ossl_time_infinite();
1017 return; /* abort normal processing, nothing to do */
1018 }
1019 }
1020
3bf4dc8c
HL
1021 /* Handle any incoming data from network. */
1022 ch_rx_pre(ch);
1023
4e64437a 1024 do {
3bf4dc8c 1025 /* Process queued incoming packets. */
4e64437a 1026 ch_rx(ch);
f538b421 1027
4e64437a
HL
1028 /*
1029 * Allow the handshake layer to check for any new incoming data and generate
1030 * new outgoing data.
1031 */
92282a17 1032 ch->have_new_rx_secret = 0;
4e64437a
HL
1033 ossl_quic_dhs_tick(ch->dhs);
1034
1035 /*
1036 * If the handshake layer gave us a new secret, we need to do RX again
1037 * because packets that were not previously processable and were
1038 * deferred might now be processable.
9f0ade7c
HL
1039 *
1040 * TODO(QUIC): Consider handling this in the yield_secret callback.
4e64437a 1041 */
92282a17 1042 } while (ch->have_new_rx_secret);
f538b421
HL
1043
1044 /*
1045 * Handle any timer events which are due to fire; namely, the loss detection
1046 * deadline and the idle timeout.
1047 *
1048 * ACKM ACK generation deadline is polled by TXP, so we don't need to handle
1049 * it here.
1050 */
1051 now = ossl_time_now();
1052 if (ossl_time_compare(now, ch->idle_deadline) >= 0) {
1053 /*
1054 * Idle timeout differs from normal protocol violation because we do not
1055 * send a CONN_CLOSE frame; go straight to TERMINATED.
1056 */
1057 ch_on_idle_timeout(ch);
1058 res->want_net_read = 0;
1059 res->want_net_write = 0;
1060 res->tick_deadline = ossl_time_infinite();
1061 return;
1062 }
1063
1064 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1065 if (!ossl_time_is_zero(deadline) && ossl_time_compare(now, deadline) >= 0)
1066 ossl_ackm_on_timeout(ch->ackm);
1067
1068 /* Write any data to the network due to be sent. */
1069 ch_tx(ch);
1070
1071 /* Determine the time at which we should next be ticked. */
1072 res->tick_deadline = ch_determine_next_tick_deadline(ch);
1073
1074 /* Always process network input. */
1075 res->want_net_read = 1;
1076
1077 /* We want to write to the network if we have any in our queue. */
1078 res->want_net_write = (ossl_qtx_get_queue_len_datagrams(ch->qtx) > 0);
1079}
1080
3bf4dc8c
HL
1081/* Process incoming datagrams, if any. */
1082static void ch_rx_pre(QUIC_CHANNEL *ch)
1083{
1084 if (!ch->have_sent_any_pkt)
1085 return;
1086
1087 /*
1088 * Get DEMUX to BIO_recvmmsg from the network and queue incoming datagrams
1089 * to the appropriate QRX instance.
1090 */
1091 ossl_quic_demux_pump(ch->demux); /* best effort */
1092}
1093
1094/* Process queued incoming packets and handle frames, if any. */
f538b421
HL
1095static int ch_rx(QUIC_CHANNEL *ch)
1096{
1097 int handled_any = 0;
1098
1099 if (!ch->have_sent_any_pkt)
1100 /*
1101 * We have not sent anything yet, therefore there is no need to check
1102 * for incoming data. TODO SERVER
1103 */
1104 return 1;
1105
f538b421
HL
1106 for (;;) {
1107 assert(ch->qrx_pkt == NULL);
1108
1109 if (!ossl_qrx_read_pkt(ch->qrx, &ch->qrx_pkt))
1110 break;
1111
1112 if (!handled_any)
1113 ch_update_idle(ch);
1114
1115 ch_rx_handle_packet(ch); /* best effort */
1116
1117 /*
1118 * Regardless of the outcome of frame handling, unref the packet.
1119 * This will free the packet unless something added another
1120 * reference to it during frame processing.
1121 */
1122 ossl_qrx_pkt_release(ch->qrx_pkt);
1123 ch->qrx_pkt = NULL;
1124
1125 handled_any = 1;
1126 }
1127
1128 /*
1129 * When in TERMINATING - CLOSING, generate a CONN_CLOSE frame whenever we
1130 * process one or more incoming packets.
1131 */
1132 if (handled_any && ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING)
1133 ch->conn_close_queued = 1;
1134
1135 return 1;
1136}
1137
1138/* Handles the packet currently in ch->qrx_pkt->hdr. */
1139static void ch_rx_handle_packet(QUIC_CHANNEL *ch)
1140{
1141 uint32_t enc_level;
1142
1143 assert(ch->qrx_pkt != NULL);
1144
1145 if (ossl_quic_pkt_type_is_encrypted(ch->qrx_pkt->hdr->type)) {
1146 if (!ch->have_received_enc_pkt) {
1147 ch->init_scid = ch->qrx_pkt->hdr->src_conn_id;
1148 ch->have_received_enc_pkt = 1;
1149
1150 /*
1151 * We change to using the SCID in the first Initial packet as the
1152 * DCID.
1153 */
1154 ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, &ch->init_scid);
1155 }
1156
1157 enc_level = ossl_quic_pkt_type_to_enc_level(ch->qrx_pkt->hdr->type);
1158 if ((ch->el_discarded & (1U << enc_level)) != 0)
1159 /* Do not process packets from ELs we have already discarded. */
1160 return;
1161 }
1162
1163 /* Handle incoming packet. */
1164 switch (ch->qrx_pkt->hdr->type) {
1165 case QUIC_PKT_TYPE_RETRY:
1166 if (ch->doing_retry)
9f0ade7c
HL
1167 /*
1168 * It is not allowed to ask a client to do a retry more than
1169 * once.
1170 */
f538b421
HL
1171 return;
1172
9f0ade7c 1173 /* TODO(QUIC): handle server mode */
f538b421
HL
1174
1175 if (ch->qrx_pkt->hdr->len <= QUIC_RETRY_INTEGRITY_TAG_LEN)
1176 /* Packets with zero-length Retry Tokens are invalid. */
1177 return;
1178
1179 /*
1180 * TODO(QUIC): Theoretically this should probably be in the QRX.
1181 * However because validation is dependent on context (namely the
1182 * client's initial DCID) we can't do this cleanly. In the future we
1183 * should probably add a callback to the QRX to let it call us (via
1184 * the DEMUX) and ask us about the correct original DCID, rather
1185 * than allow the QRX to emit a potentially malformed packet to the
1186 * upper layers. However, special casing this will do for now.
1187 */
1188 if (!ossl_quic_validate_retry_integrity_tag(ch->libctx,
1189 ch->propq,
1190 ch->qrx_pkt->hdr,
1191 &ch->init_dcid))
1192 /* Malformed retry packet, ignore. */
1193 return;
1194
1195 ch_retry(ch, ch->qrx_pkt->hdr->data,
1196 ch->qrx_pkt->hdr->len - QUIC_RETRY_INTEGRITY_TAG_LEN,
1197 &ch->qrx_pkt->hdr->src_conn_id);
1198 break;
1199
1200 case QUIC_PKT_TYPE_VERSION_NEG:
1201 /* TODO(QUIC): Implement version negotiation */
1202 break;
1203
1204 case QUIC_PKT_TYPE_0RTT:
9f0ade7c 1205 /* TODO(QQUIC): handle if server */
f538b421
HL
1206 /* Clients should never receive 0-RTT packets */
1207 break;
1208
1209 default:
1210 if (ch->qrx_pkt->hdr->type == QUIC_PKT_TYPE_HANDSHAKE)
1211 /*
1212 * We automatically drop INITIAL EL keys when first successfully
1213 * decrypting a HANDSHAKE packet, as per the RFC.
1214 */
1215 ch_discard_el(ch, QUIC_ENC_LEVEL_INITIAL);
1216
1217 /* This packet contains frames, pass to the RXDP. */
1218 ossl_quic_handle_frames(ch, ch->qrx_pkt); /* best effort */
1219 break;
1220 }
1221}
1222
1223/* Try to generate packets and if possible, flush them to the network. */
1224static int ch_tx(QUIC_CHANNEL *ch)
1225{
1226 if (ch->state == QUIC_CHANNEL_STATE_TERMINATING_CLOSING) {
1227 /*
1228 * While closing, only send CONN_CLOSE if we've received more traffic
1229 * from the peer. Once we tell the TXP to generate CONN_CLOSE, all
1230 * future calls to it generate CONN_CLOSE frames, so otherwise we would
1231 * just constantly generate CONN_CLOSE frames.
1232 */
1233 if (!ch->conn_close_queued)
1234 return 0;
1235
1236 ch->conn_close_queued = 0;
1237 }
1238
1239 /*
1240 * Send a packet, if we need to. Best effort. The TXP consults the CC and
1241 * applies any limitations imposed by it, so we don't need to do it here.
1242 *
1243 * Best effort. In particular if TXP fails for some reason we should still
1244 * flush any queued packets which we already generated.
1245 */
1246 if (ossl_quic_tx_packetiser_generate(ch->txp,
1247 TX_PACKETISER_ARCHETYPE_NORMAL)
1248 == TX_PACKETISER_RES_SENT_PKT)
1249 ch->have_sent_any_pkt = 1;
1250
1251 ossl_qtx_flush_net(ch->qtx); /* best effort */
1252 return 1;
1253}
1254
1255/* Determine next tick deadline. */
1256static OSSL_TIME ch_determine_next_tick_deadline(QUIC_CHANNEL *ch)
1257{
1258 OSSL_TIME deadline;
1259 uint32_t pn_space;
1260
1261 deadline = ossl_ackm_get_loss_detection_deadline(ch->ackm);
1262 if (ossl_time_is_zero(deadline))
1263 deadline = ossl_time_infinite();
1264
1265 for (pn_space = QUIC_PN_SPACE_INITIAL; pn_space < QUIC_PN_SPACE_NUM; ++pn_space)
1266 deadline = ossl_time_min(deadline,
1267 ossl_ackm_get_ack_deadline(ch->ackm, pn_space));
1268
1269 /* When will CC let us send more? */
1270 if (ossl_quic_tx_packetiser_has_pending(ch->txp, TX_PACKETISER_ARCHETYPE_NORMAL,
1271 TX_PACKETISER_BYPASS_CC))
1272 deadline = ossl_time_min(deadline,
1273 ch->cc_method->get_next_credit_time(ch->cc_data));
1274
1275 /* Is the terminating timer armed? */
1276 if (ossl_quic_channel_is_terminating(ch))
1277 deadline = ossl_time_min(deadline,
1278 ch->terminate_deadline);
1279 else if (!ossl_time_is_infinite(ch->idle_deadline))
1280 deadline = ossl_time_min(deadline,
1281 ch->idle_deadline);
1282
1283 return deadline;
1284}
1285
1286/*
1287 * QUIC Channel: Network BIO Configuration
1288 * =======================================
1289 */
1290
1291/* Determines whether we can support a given poll descriptor. */
1292static int validate_poll_descriptor(const BIO_POLL_DESCRIPTOR *d)
1293{
1294 if (d->type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD && d->value.fd < 0)
1295 return 0;
1296
1297 return 1;
1298}
1299
1300BIO *ossl_quic_channel_get_net_rbio(QUIC_CHANNEL *ch)
1301{
1302 return ch->net_rbio;
1303}
1304
1305BIO *ossl_quic_channel_get_net_wbio(QUIC_CHANNEL *ch)
1306{
1307 return ch->net_wbio;
1308}
1309
d1ac77b1
HL
1310/*
1311 * QUIC_CHANNEL does not ref any BIO it is provided with, nor is any ref
1312 * transferred to it. The caller (i.e., QUIC_CONNECTION) is responsible for
1313 * ensuring the BIO lasts until the channel is freed or the BIO is switched out
1314 * for another BIO by a subsequent successful call to this function.
1315 */
1316int ossl_quic_channel_set_net_rbio(QUIC_CHANNEL *ch, BIO *net_rbio)
f538b421
HL
1317{
1318 BIO_POLL_DESCRIPTOR d = {0};
1319
1320 if (ch->net_rbio == net_rbio)
1321 return 1;
1322
1323 if (net_rbio != NULL) {
1324 if (!BIO_get_rpoll_descriptor(net_rbio, &d))
1325 /* Non-pollable BIO */
1326 d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
1327
1328 if (!validate_poll_descriptor(&d))
1329 return 0;
1330 }
1331
1332 ossl_quic_reactor_set_poll_r(&ch->rtor, &d);
f538b421
HL
1333 ossl_quic_demux_set_bio(ch->demux, net_rbio);
1334 ch->net_rbio = net_rbio;
1335 return 1;
1336}
1337
d1ac77b1 1338int ossl_quic_channel_set_net_wbio(QUIC_CHANNEL *ch, BIO *net_wbio)
f538b421
HL
1339{
1340 BIO_POLL_DESCRIPTOR d = {0};
1341
1342 if (ch->net_wbio == net_wbio)
1343 return 1;
1344
1345 if (net_wbio != NULL) {
1346 if (!BIO_get_wpoll_descriptor(net_wbio, &d))
1347 /* Non-pollable BIO */
1348 d.type = BIO_POLL_DESCRIPTOR_TYPE_NONE;
1349
1350 if (!validate_poll_descriptor(&d))
1351 return 0;
1352 }
1353
1354 ossl_quic_reactor_set_poll_w(&ch->rtor, &d);
f538b421
HL
1355 ossl_qtx_set_bio(ch->qtx, net_wbio);
1356 ch->net_wbio = net_wbio;
1357 return 1;
1358}
1359
1360/*
1361 * QUIC Channel: Lifecycle Events
1362 * ==============================
1363 */
1364
1365int ossl_quic_channel_start(QUIC_CHANNEL *ch)
1366{
9f0ade7c 1367 /* TODO(QUIC): handle server */
f538b421
HL
1368 if (ch->state != QUIC_CHANNEL_STATE_IDLE)
1369 /* Calls to connect are idempotent */
1370 return 1;
1371
1372 /* Inform QTX of peer address. */
1373 if (!ossl_quic_tx_packetiser_set_peer(ch->txp, &ch->cur_peer_addr))
1374 return 0;
1375
1376 /* Plug in secrets for the Initial EL. */
1377 if (!ossl_quic_provide_initial_secret(ch->libctx,
1378 ch->propq,
1379 &ch->init_dcid,
1380 /*is_server=*/0,
1381 ch->qrx, ch->qtx))
1382 return 0;
1383
1384 /* Change state. */
1385 ch->state = QUIC_CHANNEL_STATE_ACTIVE;
1386 ch->doing_proactive_ver_neg = 0; /* not currently supported */
1387
1388 /* Handshake layer: start (e.g. send CH). */
1389 if (!ossl_quic_dhs_tick(ch->dhs))
1390 return 0;
1391
1392 ossl_quic_reactor_tick(&ch->rtor); /* best effort */
1393 return 1;
1394}
1395
1396/* Start a locally initiated connection shutdown. */
1397void ossl_quic_channel_local_close(QUIC_CHANNEL *ch)
1398{
1399 QUIC_TERMINATE_CAUSE tcause = {0};
1400
1401 if (ossl_quic_channel_is_term_any(ch))
1402 return;
1403
1404 tcause.app = 1;
1405 ch_start_terminating(ch, &tcause);
1406}
1407
1408static void free_token(const unsigned char *buf, size_t buf_len, void *arg)
1409{
1410 OPENSSL_free((unsigned char *)buf);
1411}
1412
1413/* Called when a server asks us to do a retry. */
1414static int ch_retry(QUIC_CHANNEL *ch,
1415 const unsigned char *retry_token,
1416 size_t retry_token_len,
1417 const QUIC_CONN_ID *retry_scid)
1418{
1419 void *buf;
1420
1421 /* We change to using the SCID in the Retry packet as the DCID. */
1422 if (!ossl_quic_tx_packetiser_set_cur_dcid(ch->txp, retry_scid))
1423 return 0;
1424
1425 /*
1426 * Now we retry. We will release the Retry packet immediately, so copy
1427 * the token.
1428 */
e28f512f 1429 if ((buf = OPENSSL_memdup(retry_token, retry_token_len)) == NULL)
f538b421
HL
1430 return 0;
1431
f538b421
HL
1432 ossl_quic_tx_packetiser_set_initial_token(ch->txp, buf, retry_token_len,
1433 free_token, NULL);
1434
1435 ch->retry_scid = *retry_scid;
1436 ch->doing_retry = 1;
1437
1438 /*
1439 * We need to stimulate the Initial EL to generate the first CRYPTO frame
1440 * again. We can do this most cleanly by simply forcing the ACKM to consider
1441 * the first Initial packet as lost, which it effectively was as the server
1442 * hasn't processed it. This also maintains the desired behaviour with e.g.
1443 * PNs not resetting and so on.
1444 *
1445 * The PN we used initially is always zero, because QUIC does not allow
1446 * repeated retries.
1447 */
1448 if (!ossl_ackm_mark_packet_pseudo_lost(ch->ackm, QUIC_PN_SPACE_INITIAL,
1449 /*PN=*/0))
1450 return 0;
1451
1452 /*
1453 * Plug in new secrets for the Initial EL. This is the only time we change
1454 * the secrets for an EL after we already provisioned it.
1455 */
1456 if (!ossl_quic_provide_initial_secret(ch->libctx,
1457 ch->propq,
1458 &ch->retry_scid,
1459 /*is_server=*/0,
1460 ch->qrx, ch->qtx))
1461 return 0;
1462
1463 return 1;
1464}
1465
1466/* Called when an EL is to be discarded. */
1467static int ch_discard_el(QUIC_CHANNEL *ch,
1468 uint32_t enc_level)
1469{
1470 if (!ossl_assert(enc_level < QUIC_ENC_LEVEL_1RTT))
1471 return 0;
1472
1473 if ((ch->el_discarded & (1U << enc_level)) != 0)
1474 /* Already done. */
1475 return 1;
1476
1477 /* Best effort for all of these. */
1478 ossl_quic_tx_packetiser_discard_enc_level(ch->txp, enc_level);
1479 ossl_qrx_discard_enc_level(ch->qrx, enc_level);
1480 ossl_qtx_discard_enc_level(ch->qtx, enc_level);
1481
1482 if (enc_level != QUIC_ENC_LEVEL_0RTT) {
1483 uint32_t pn_space = ossl_quic_enc_level_to_pn_space(enc_level);
1484
1485 ossl_ackm_on_pkt_space_discarded(ch->ackm, pn_space);
1486
1487 /* We should still have crypto streams at this point. */
79534440
HL
1488 if (!ossl_assert(ch->crypto_send[pn_space] != NULL)
1489 || !ossl_assert(ch->crypto_recv[pn_space] != NULL))
1490 return 0;
f538b421
HL
1491
1492 /* Get rid of the crypto stream state for the EL. */
1493 ossl_quic_sstream_free(ch->crypto_send[pn_space]);
1494 ch->crypto_send[pn_space] = NULL;
1495
1496 ossl_quic_rstream_free(ch->crypto_recv[pn_space]);
1497 ch->crypto_recv[pn_space] = NULL;
1498 }
1499
1500 ch->el_discarded |= (1U << enc_level);
1501 return 1;
1502}
1503
1504/* Intended to be called by the RXDP. */
1505int ossl_quic_channel_on_handshake_confirmed(QUIC_CHANNEL *ch)
1506{
1507 if (ch->handshake_confirmed)
1508 return 1;
1509
1510 if (!ch->handshake_complete) {
1511 /*
1512 * Does not make sense for handshake to be confirmed before it is
1513 * completed.
1514 */
1515 ossl_quic_channel_raise_protocol_error(ch, QUIC_ERR_PROTOCOL_VIOLATION,
1516 OSSL_QUIC_FRAME_TYPE_HANDSHAKE_DONE,
1517 "handshake cannot be confirmed "
1518 "before it is completed");
1519 return 0;
1520 }
1521
1522 ch_discard_el(ch, QUIC_ENC_LEVEL_HANDSHAKE);
1523 ch->handshake_confirmed = 1;
1524 return 1;
1525}
1526
1527/*
1528 * Master function used when we want to start tearing down a connection:
1529 *
1530 * - If the connection is still IDLE we can go straight to TERMINATED;
1531 *
1532 * - If we are already TERMINATED this is a no-op.
1533 *
1534 * - If we are TERMINATING - CLOSING and we have now got a CONNECTION_CLOSE
9bbc5b54 1535 * from the peer (tcause->remote == 1), we move to TERMINATING - DRAINING.
f538b421
HL
1536 *
1537 * - If we are TERMINATING - DRAINING, we remain here until the terminating
1538 * timer expires.
1539 *
1540 * - Otherwise, we are in ACTIVE and move to TERMINATING - CLOSING.
1541 * if we caused the termination (e.g. we have sent a CONNECTION_CLOSE). Note
1542 * that we are considered to have caused a termination if we sent the first
1543 * CONNECTION_CLOSE frame, even if it is caused by a peer protocol
1544 * violation. If the peer sent the first CONNECTION_CLOSE frame, we move to
1545 * TERMINATING - DRAINING.
1546 *
1547 * We record the termination cause structure passed on the first call only.
1548 * Any successive calls have their termination cause data discarded;
1549 * once we start sending a CONNECTION_CLOSE frame, we don't change the details
1550 * in it.
1551 */
1552static void ch_start_terminating(QUIC_CHANNEL *ch,
1553 const QUIC_TERMINATE_CAUSE *tcause)
1554{
1555 switch (ch->state) {
1556 default:
1557 case QUIC_CHANNEL_STATE_IDLE:
1558 ch->terminate_cause = *tcause;
1559 ch_on_terminating_timeout(ch);
1560 break;
1561
1562 case QUIC_CHANNEL_STATE_ACTIVE:
1563 ch->state = tcause->remote ? QUIC_CHANNEL_STATE_TERMINATING_DRAINING
1564 : QUIC_CHANNEL_STATE_TERMINATING_CLOSING;
1565 ch->terminate_cause = *tcause;
1566 ch->terminate_deadline
1567 = ossl_time_add(ossl_time_now(),
1568 ossl_time_multiply(ossl_ackm_get_pto_duration(ch->ackm),
1569 3));
1570
1571 if (!tcause->remote) {
1572 OSSL_QUIC_FRAME_CONN_CLOSE f = {0};
1573
1574 /* best effort */
1575 f.error_code = ch->terminate_cause.error_code;
1576 f.frame_type = ch->terminate_cause.frame_type;
1577 f.is_app = ch->terminate_cause.app;
1578 ossl_quic_tx_packetiser_schedule_conn_close(ch->txp, &f);
1579 ch->conn_close_queued = 1;
1580 }
1581 break;
1582
1583 case QUIC_CHANNEL_STATE_TERMINATING_CLOSING:
1584 if (tcause->remote)
1585 ch->state = QUIC_CHANNEL_STATE_TERMINATING_DRAINING;
1586
1587 break;
1588
1589 case QUIC_CHANNEL_STATE_TERMINATING_DRAINING:
1590 /* We remain here until the timout expires. */
1591 break;
1592
1593 case QUIC_CHANNEL_STATE_TERMINATED:
1594 /* No-op. */
1595 break;
1596 }
1597}
1598
1599/* For RXDP use. */
1600void ossl_quic_channel_on_remote_conn_close(QUIC_CHANNEL *ch,
1601 OSSL_QUIC_FRAME_CONN_CLOSE *f)
1602{
1603 QUIC_TERMINATE_CAUSE tcause = {0};
1604
1605 if (!ossl_quic_channel_is_active(ch))
1606 return;
1607
1608 tcause.remote = 1;
1609 tcause.app = f->is_app;
1610 tcause.error_code = f->error_code;
1611 tcause.frame_type = f->frame_type;
1612
1613 ch_start_terminating(ch, &tcause);
1614}
1615
1616void ossl_quic_channel_raise_protocol_error(QUIC_CHANNEL *ch,
1617 uint64_t error_code,
1618 uint64_t frame_type,
1619 const char *reason)
1620{
1621 QUIC_TERMINATE_CAUSE tcause = {0};
1622
1623 tcause.error_code = error_code;
1624 tcause.frame_type = frame_type;
1625
1626 ch_start_terminating(ch, &tcause);
1627}
1628
1629/*
1630 * Called once the terminating timer expires, meaning we move from TERMINATING
1631 * to TERMINATED.
1632 */
1633static void ch_on_terminating_timeout(QUIC_CHANNEL *ch)
1634{
1635 ch->state = QUIC_CHANNEL_STATE_TERMINATED;
1636}
1637
1638/*
1639 * Updates our idle deadline. Called when an event happens which should bump the
1640 * idle timeout.
1641 */
1642static void ch_update_idle(QUIC_CHANNEL *ch)
1643{
1644 if (ch->max_idle_timeout == 0)
1645 ch->idle_deadline = ossl_time_infinite();
1646 else
1647 ch->idle_deadline = ossl_time_add(ossl_time_now(),
1648 ossl_ms2time(ch->max_idle_timeout));
1649}
1650
1651/* Called when the idle timeout expires. */
1652static void ch_on_idle_timeout(QUIC_CHANNEL *ch)
1653{
1654 /*
1655 * Idle timeout does not have an error code associated with it because a
1656 * CONN_CLOSE is never sent for it. We shouldn't use this data once we reach
1657 * TERMINATED anyway.
1658 */
1659 ch->terminate_cause.app = 0;
1660 ch->terminate_cause.error_code = UINT64_MAX;
1661 ch->terminate_cause.frame_type = 0;
1662
1663 ch->state = QUIC_CHANNEL_STATE_TERMINATED;
1664}