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