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