QUIC APL: Send STOP_SENDING/RESET_STREAM when XSO is freed
[openssl.git] / ssl / quic / quic_impl.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 <openssl/macros.h>
11 #include <openssl/objects.h>
12 #include <openssl/sslerr.h>
13 #include <crypto/rand.h>
14 #include "quic_local.h"
15 #include "internal/quic_tls.h"
16 #include "internal/quic_rx_depack.h"
17 #include "internal/quic_error.h"
18 #include "internal/time.h"
19
20 static void aon_write_finish(QUIC_XSO *xso);
21 static int create_channel(QUIC_CONNECTION *qc);
22 static QUIC_XSO *create_xso_from_stream(QUIC_CONNECTION *qc, QUIC_STREAM *qs);
23 static int qc_try_create_default_xso_for_write(QUIC_CONNECTION *qc);
24 static int qc_wait_for_default_xso_for_read(QUIC_CONNECTION *qc);
25 static void quic_lock(QUIC_CONNECTION *qc);
26 static void quic_unlock(QUIC_CONNECTION *qc);
27 static int quic_do_handshake(QUIC_CONNECTION *qc);
28 static void qc_update_reject_policy(QUIC_CONNECTION *qc);
29 static void qc_touch_default_xso(QUIC_CONNECTION *qc);
30 static void qc_set_default_xso(QUIC_CONNECTION *qc, QUIC_XSO *xso, int touch);
31 static SSL *quic_conn_stream_new(QUIC_CONNECTION *qc, uint64_t flags,
32                                  int need_lock);
33
34 /*
35  * QUIC Front-End I/O API: Common Utilities
36  * ========================================
37  */
38
39 /*
40  * Block until a predicate is met.
41  *
42  * Precondition: Must have a channel.
43  * Precondition: Must hold channel lock (unchecked).
44  */
45 QUIC_NEEDS_LOCK
46 static int block_until_pred(QUIC_CONNECTION *qc,
47                             int (*pred)(void *arg), void *pred_arg,
48                             uint32_t flags)
49 {
50     QUIC_REACTOR *rtor;
51
52     assert(qc->ch != NULL);
53
54     rtor = ossl_quic_channel_get_reactor(qc->ch);
55     return ossl_quic_reactor_block_until_pred(rtor, pred, pred_arg, flags,
56                                               qc->mutex);
57 }
58
59 /*
60  * Raise a 'normal' error, meaning one that can be reported via SSL_get_error()
61  * rather than via ERR.
62  */
63 static int quic_raise_normal_error(QUIC_CONNECTION *qc,
64                                    int err)
65 {
66     qc->last_error = err;
67     return 0;
68 }
69
70 /*
71  * Raise a 'non-normal' error, meaning any error that is not reported via
72  * SSL_get_error() and must be reported via ERR.
73  *
74  * qc should be provided if available. In exceptional circumstances when qc is
75  * not known NULL may be passed. This should generally only happen when an
76  * expect_...() function defined below fails, which generally indicates a
77  * dispatch error or caller error.
78  */
79 static int quic_raise_non_normal_error(QUIC_CONNECTION *qc,
80                                        const char *file,
81                                        int line,
82                                        const char *func,
83                                        int reason,
84                                        const char *fmt,
85                                        ...)
86 {
87     va_list args;
88
89     ERR_new();
90     ERR_set_debug(file, line, func);
91
92     va_start(args, fmt);
93     ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
94     va_end(args);
95
96     if (qc != NULL)
97         qc->last_error = SSL_ERROR_SSL;
98
99     return 0;
100 }
101
102 #define QUIC_RAISE_NORMAL_ERROR(qc, err)                        \
103     quic_raise_normal_error((qc), (err))
104
105 #define QUIC_RAISE_NON_NORMAL_ERROR(qc, reason, msg)            \
106     quic_raise_non_normal_error((qc),                           \
107                                 OPENSSL_FILE, OPENSSL_LINE,     \
108                                 OPENSSL_FUNC,                   \
109                                 (reason),                       \
110                                 (msg))
111
112 /*
113  * QCTX is a utility structure which provides information we commonly wish to
114  * unwrap upon an API call being dispatched to us, namely:
115  *
116  *   - a pointer to the QUIC_CONNECTION (regardless of whether a QCSO or QSSO
117  *     was passed);
118  *   - a pointer to any applicable QUIC_XSO (e.g. if a QSSO was passed, or if
119  *     a QCSO with a default stream was passed);
120  *   - whether a QSSO was passed (xso == NULL must not be used to determine this
121  *     because it may be non-NULL when a QCSO is passed if that QCSO has a
122  *     default stream).
123  */
124 typedef struct qctx_st {
125     QUIC_CONNECTION *qc;
126     QUIC_XSO        *xso;
127     int             is_stream;
128 } QCTX;
129
130 /*
131  * Given a QCSO or QSSO, initialises a QCTX, determining the contextually
132  * applicable QUIC_CONNECTION pointer and, if applicable, QUIC_XSO pointer.
133  *
134  * After this returns 1, all fields of the passed QCTX are initialised.
135  * Returns 0 on failure. This function is intended to be used to provide API
136  * semantics and as such, it invokes QUIC_RAISE_NON_NORMAL_ERROR() on failure.
137  */
138 static int expect_quic(const SSL *s, QCTX *ctx)
139 {
140     QUIC_CONNECTION *qc;
141     QUIC_XSO *xso;
142
143     ctx->qc         = NULL;
144     ctx->xso        = NULL;
145     ctx->is_stream  = 0;
146
147     if (s == NULL)
148         return QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_PASSED_NULL_PARAMETER, NULL);
149
150     switch (s->type) {
151     case SSL_TYPE_QUIC_CONNECTION:
152         qc              = (QUIC_CONNECTION *)s;
153         ctx->qc         = qc;
154         ctx->xso        = qc->default_xso;
155         ctx->is_stream  = 0;
156         return 1;
157
158     case SSL_TYPE_QUIC_XSO:
159         xso             = (QUIC_XSO *)s;
160         ctx->qc         = xso->conn;
161         ctx->xso        = xso;
162         ctx->is_stream  = 1;
163         return 1;
164
165     default:
166         return QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL);
167     }
168 }
169
170 /*
171  * Like expect_quic(), but requires a QUIC_XSO be contextually available. In
172  * other words, requires that the passed QSO be a QSSO or a QCSO with a default
173  * stream.
174  *
175  * remote_init determines if we expect the default XSO to be remotely created or
176  * not. If it is -1, do not instantiate a default XSO if one does not yet exist.
177  *
178  * Channel mutex is acquired and retained on success.
179  */
180 QUIC_ACQUIRES_LOCK
181 static int ossl_unused expect_quic_with_stream_lock(const SSL *s, int remote_init,
182                                                     QCTX *ctx)
183 {
184     if (!expect_quic(s, ctx))
185         return 0;
186
187     quic_lock(ctx->qc);
188
189     if (ctx->xso == NULL && remote_init >= 0) {
190         if (ossl_quic_channel_is_term_any(ctx->qc->ch)) {
191             QUIC_RAISE_NON_NORMAL_ERROR(ctx->qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
192             goto err;
193         }
194
195         /* If we haven't finished the handshake, try to advance it. */
196         if (quic_do_handshake(ctx->qc) < 1)
197             /* ossl_quic_do_handshake raised error here */
198             goto err;
199
200         if (remote_init == 0) {
201             if (!qc_try_create_default_xso_for_write(ctx->qc))
202                 goto err;
203         } else {
204             if (!qc_wait_for_default_xso_for_read(ctx->qc))
205                 goto err;
206         }
207
208         ctx->xso = ctx->qc->default_xso;
209     }
210
211     if (ctx->xso == NULL) {
212         QUIC_RAISE_NON_NORMAL_ERROR(ctx->qc, SSL_R_NO_STREAM, NULL);
213         goto err;
214     }
215
216     return 1; /* lock held */
217
218 err:
219     quic_unlock(ctx->qc);
220     return 0;
221 }
222
223 /*
224  * Like expect_quic(), but fails if called on a QUIC_XSO. ctx->xso may still
225  * be non-NULL if the QCSO has a default stream.
226  */
227 static int ossl_unused expect_quic_conn_only(const SSL *s, QCTX *ctx)
228 {
229     if (!expect_quic(s, ctx))
230         return 0;
231
232     if (ctx->is_stream)
233         return QUIC_RAISE_NON_NORMAL_ERROR(ctx->qc, SSL_R_CONN_USE_ONLY, NULL);
234
235     return 1;
236 }
237
238 /*
239  * Ensures that the channel mutex is held for a method which touches channel
240  * state.
241  *
242  * Precondition: Channel mutex is not held (unchecked)
243  */
244 static void quic_lock(QUIC_CONNECTION *qc)
245 {
246     ossl_crypto_mutex_lock(qc->mutex);
247 }
248
249 /* Precondition: Channel mutex is held (unchecked) */
250 QUIC_NEEDS_LOCK
251 static void quic_unlock(QUIC_CONNECTION *qc)
252 {
253     ossl_crypto_mutex_unlock(qc->mutex);
254 }
255
256
257 /*
258  * QUIC Front-End I/O API: Initialization
259  * ======================================
260  *
261  *         SSL_new                  => ossl_quic_new
262  *                                     ossl_quic_init
263  *         SSL_reset                => ossl_quic_reset
264  *         SSL_clear                => ossl_quic_clear
265  *                                     ossl_quic_deinit
266  *         SSL_free                 => ossl_quic_free
267  *
268  */
269
270 /* SSL_new */
271 SSL *ossl_quic_new(SSL_CTX *ctx)
272 {
273     QUIC_CONNECTION *qc = NULL;
274     SSL *ssl_base = NULL;
275     SSL_CONNECTION *sc = NULL;
276
277     qc = OPENSSL_zalloc(sizeof(*qc));
278     if (qc == NULL)
279         goto err;
280
281     /* Initialise the QUIC_CONNECTION's stub header. */
282     ssl_base = &qc->ssl;
283     if (!ossl_ssl_init(ssl_base, ctx, ctx->method, SSL_TYPE_QUIC_CONNECTION)) {
284         ssl_base = NULL;
285         goto err;
286     }
287
288     qc->tls = ossl_ssl_connection_new_int(ctx, TLS_method());
289     if (qc->tls == NULL || (sc = SSL_CONNECTION_FROM_SSL(qc->tls)) == NULL)
290          goto err;
291
292     if ((qc->mutex = ossl_crypto_mutex_new()) == NULL)
293         goto err;
294
295     qc->is_thread_assisted
296         = (ssl_base->method == OSSL_QUIC_client_thread_method());
297
298     qc->as_server       = 0; /* TODO(QUIC): server support */
299     qc->as_server_state = qc->as_server;
300
301     qc->default_stream_mode     = SSL_DEFAULT_STREAM_MODE_AUTO_BIDI;
302     qc->default_ssl_mode        = qc->ssl.ctx->mode;
303     qc->default_blocking        = 1;
304     qc->incoming_stream_reject_policy
305         = SSL_INCOMING_STREAM_REJECT_POLICY_AUTO;
306     qc->last_error              = SSL_ERROR_NONE;
307
308     if (!create_channel(qc))
309         goto err;
310
311     qc_update_reject_policy(qc);
312
313     /*
314      * We do not create the default XSO yet. The reason for this is that the
315      * stream ID of the default XSO will depend on whether the stream is client
316      * or server-initiated, which depends on who transmits first. Since we do
317      * not know whether the application will be using a client-transmits-first
318      * or server-transmits-first protocol, we defer default XSO creation until
319      * the client calls SSL_read() or SSL_write(). If it calls SSL_read() first,
320      * we take that as a cue that the client is expecting a server-initiated
321      * stream, and vice versa if SSL_write() is called first.
322      */
323     return ssl_base;
324
325 err:
326     if (qc != NULL) {
327         ossl_quic_channel_free(qc->ch);
328         SSL_free(qc->tls);
329     }
330     OPENSSL_free(qc);
331     return NULL;
332 }
333
334 /* SSL_free */
335 QUIC_TAKES_LOCK
336 void ossl_quic_free(SSL *s)
337 {
338     QCTX ctx;
339
340     /* We should never be called on anything but a QSO. */
341     if (!expect_quic(s, &ctx))
342         return;
343
344     if (ctx.is_stream) {
345         /*
346          * When a QSSO is freed, the XSO is freed immediately, because the XSO
347          * itself only contains API personality layer data. However the
348          * underlying QUIC_STREAM is not freed immediately but is instead marked
349          * as deleted for later collection.
350          */
351
352         quic_lock(ctx.qc);
353
354         assert(ctx.qc->num_xso > 0);
355         --ctx.qc->num_xso;
356
357         /* If a stream's send part has not been finished, auto-reset it. */
358         if (ctx.xso->stream->sstream != NULL
359             && !ossl_quic_sstream_get_final_size(ctx.xso->stream->sstream, NULL))
360             ossl_quic_stream_map_reset_stream_send_part(ossl_quic_channel_get_qsm(ctx.qc->ch),
361                                                         ctx.xso->stream, 0);
362
363         /* Do STOP_SENDING for the receive part, if applicable. */
364         if (ctx.xso->stream->rstream != NULL)
365             ossl_quic_stream_map_stop_sending_recv_part(ossl_quic_channel_get_qsm(ctx.qc->ch),
366                                                         ctx.xso->stream, 0);
367
368         /* Update stream state. */
369         ctx.xso->stream->deleted = 1;
370         ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(ctx.qc->ch),
371                                           ctx.xso->stream);
372
373         quic_unlock(ctx.qc);
374
375         /* Note: SSL_free calls OPENSSL_free(xso) for us */
376         return;
377     }
378
379     quic_lock(ctx.qc);
380
381     /*
382      * Free the default XSO, if any. The QUIC_STREAM is not deleted at this
383      * stage, but is freed during the channel free when the whole QSM is freed.
384      */
385     if (ctx.qc->default_xso != NULL) {
386         QUIC_XSO *xso = ctx.qc->default_xso;
387
388         quic_unlock(ctx.qc);
389         SSL_free(&xso->ssl);
390         quic_lock(ctx.qc);
391     }
392
393     /* Ensure we have no remaining XSOs. */
394     assert(ctx.qc->num_xso == 0);
395
396     if (ctx.qc->is_thread_assisted && ctx.qc->started) {
397         ossl_quic_thread_assist_wait_stopped(&ctx.qc->thread_assist);
398         ossl_quic_thread_assist_cleanup(&ctx.qc->thread_assist);
399     }
400
401     ossl_quic_channel_free(ctx.qc->ch);
402
403     BIO_free(ctx.qc->net_rbio);
404     BIO_free(ctx.qc->net_wbio);
405
406     /* Note: SSL_free calls OPENSSL_free(qc) for us */
407
408     SSL_free(ctx.qc->tls);
409     ossl_crypto_mutex_free(&ctx.qc->mutex); /* freed while still locked */
410 }
411
412 /* SSL method init */
413 int ossl_quic_init(SSL *s)
414 {
415     /* Same op as SSL_clear, forward the call. */
416     return ossl_quic_clear(s);
417 }
418
419 /* SSL method deinit */
420 void ossl_quic_deinit(SSL *s)
421 {
422     /* No-op. */
423 }
424
425 /* SSL_reset */
426 int ossl_quic_reset(SSL *s)
427 {
428     QCTX ctx;
429
430     if (!expect_quic(s, &ctx))
431         return 0;
432
433     /* TODO(QUIC); Currently a no-op. */
434     return 1;
435 }
436
437 /* SSL_clear */
438 int ossl_quic_clear(SSL *s)
439 {
440     QCTX ctx;
441
442     if (!expect_quic(s, &ctx))
443         return 0;
444
445     /* TODO(QUIC): Currently a no-op. */
446     return 1;
447 }
448
449 void ossl_quic_conn_set_override_now_cb(SSL *s,
450                                         OSSL_TIME (*now_cb)(void *arg),
451                                         void *now_cb_arg)
452 {
453     QCTX ctx;
454
455     if (!expect_quic(s, &ctx))
456         return;
457
458     ctx.qc->override_now_cb     = now_cb;
459     ctx.qc->override_now_cb_arg = now_cb_arg;
460 }
461
462 void ossl_quic_conn_force_assist_thread_wake(SSL *s)
463 {
464     QCTX ctx;
465
466     if (!expect_quic(s, &ctx))
467         return;
468
469     if (ctx.qc->is_thread_assisted && ctx.qc->started)
470         ossl_quic_thread_assist_notify_deadline_changed(&ctx.qc->thread_assist);
471 }
472
473 QUIC_NEEDS_LOCK
474 static void qc_touch_default_xso(QUIC_CONNECTION *qc)
475 {
476     qc->default_xso_created = 1;
477     qc_update_reject_policy(qc);
478 }
479
480 QUIC_NEEDS_LOCK
481 static void qc_set_default_xso(QUIC_CONNECTION *qc, QUIC_XSO *xso, int touch)
482 {
483     qc->default_xso = xso;
484     if (touch)
485         qc_touch_default_xso(qc);
486 }
487
488 /*
489  * QUIC Front-End I/O API: Network BIO Configuration
490  * =================================================
491  *
492  * Handling the different BIOs is difficult:
493  *
494  *   - It is more or less a requirement that we use non-blocking network I/O;
495  *     we need to be able to have timeouts on recv() calls, and make best effort
496  *     (non blocking) send() and recv() calls.
497  *
498  *     The only sensible way to do this is to configure the socket into
499  *     non-blocking mode. We could try to do select() before calling send() or
500  *     recv() to get a guarantee that the call will not block, but this will
501  *     probably run into issues with buggy OSes which generate spurious socket
502  *     readiness events. In any case, relying on this to work reliably does not
503  *     seem sane.
504  *
505  *     Timeouts could be handled via setsockopt() socket timeout options, but
506  *     this depends on OS support and adds another syscall to every network I/O
507  *     operation. It also has obvious thread safety concerns if we want to move
508  *     to concurrent use of a single socket at some later date.
509  *
510  *     Some OSes support a MSG_DONTWAIT flag which allows a single I/O option to
511  *     be made non-blocking. However some OSes (e.g. Windows) do not support
512  *     this, so we cannot rely on this.
513  *
514  *     As such, we need to configure any FD in non-blocking mode. This may
515  *     confound users who pass a blocking socket to libssl. However, in practice
516  *     it would be extremely strange for a user of QUIC to pass an FD to us,
517  *     then also try and send receive traffic on the same socket(!). Thus the
518  *     impact of this should be limited, and can be documented.
519  *
520  *   - We support both blocking and non-blocking operation in terms of the API
521  *     presented to the user. One prospect is to set the blocking mode based on
522  *     whether the socket passed to us was already in blocking mode. However,
523  *     Windows has no API for determining if a socket is in blocking mode (!),
524  *     therefore this cannot be done portably. Currently therefore we expose an
525  *     explicit API call to set this, and default to blocking mode.
526  *
527  *   - We need to determine our initial destination UDP address. The "natural"
528  *     way for a user to do this is to set the peer variable on a BIO_dgram.
529  *     However, this has problems because BIO_dgram's peer variable is used for
530  *     both transmission and reception. This means it can be constantly being
531  *     changed to a malicious value (e.g. if some random unrelated entity on the
532  *     network starts sending traffic to us) on every read call. This is not a
533  *     direct issue because we use the 'stateless' BIO_sendmmsg and BIO_recvmmsg
534  *     calls only, which do not use this variable. However, we do need to let
535  *     the user specify the peer in a 'normal' manner. The compromise here is
536  *     that we grab the current peer value set at the time the write BIO is set
537  *     and do not read the value again.
538  *
539  *   - We also need to support memory BIOs (e.g. BIO_dgram_pair) or custom BIOs.
540  *     Currently we do this by only supporting non-blocking mode.
541  *
542  */
543
544 /*
545  * Determines what initial destination UDP address we should use, if possible.
546  * If this fails the client must set the destination address manually, or use a
547  * BIO which does not need a destination address.
548  */
549 static int csm_analyse_init_peer_addr(BIO *net_wbio, BIO_ADDR *peer)
550 {
551     if (BIO_dgram_get_peer(net_wbio, peer) <= 0)
552         return 0;
553
554     return 1;
555 }
556
557 void ossl_quic_conn_set0_net_rbio(SSL *s, BIO *net_rbio)
558 {
559     QCTX ctx;
560
561     if (!expect_quic(s, &ctx))
562         return;
563
564     if (ctx.qc->net_rbio == net_rbio)
565         return;
566
567     if (!ossl_quic_channel_set_net_rbio(ctx.qc->ch, net_rbio))
568         return;
569
570     BIO_free(ctx.qc->net_rbio);
571     ctx.qc->net_rbio = net_rbio;
572
573     /*
574      * If what we have is not pollable (e.g. a BIO_dgram_pair) disable blocking
575      * mode as we do not support it for non-pollable BIOs.
576      */
577     if (net_rbio != NULL) {
578         BIO_POLL_DESCRIPTOR d = {0};
579
580         if (!BIO_get_rpoll_descriptor(net_rbio, &d)
581             || d.type != BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD) {
582             ctx.qc->blocking          = 0;
583             ctx.qc->default_blocking  = 0;
584             ctx.qc->can_poll_net_rbio = 0;
585         } else {
586             ctx.qc->can_poll_net_rbio = 1;
587         }
588     }
589 }
590
591 void ossl_quic_conn_set0_net_wbio(SSL *s, BIO *net_wbio)
592 {
593     QCTX ctx;
594
595     if (!expect_quic(s, &ctx))
596         return;
597
598     if (ctx.qc->net_wbio == net_wbio)
599         return;
600
601     if (!ossl_quic_channel_set_net_wbio(ctx.qc->ch, net_wbio))
602         return;
603
604     BIO_free(ctx.qc->net_wbio);
605     ctx.qc->net_wbio = net_wbio;
606
607     if (net_wbio != NULL) {
608         BIO_POLL_DESCRIPTOR d = {0};
609
610         if (!BIO_get_wpoll_descriptor(net_wbio, &d)
611             || d.type != BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD) {
612             ctx.qc->blocking          = 0;
613             ctx.qc->default_blocking  = 0;
614             ctx.qc->can_poll_net_wbio = 0;
615         } else {
616             ctx.qc->can_poll_net_wbio = 1;
617         }
618
619         /*
620          * If we do not have a peer address yet, and we have not started trying
621          * to connect yet, try to autodetect one.
622          */
623         if (BIO_ADDR_family(&ctx.qc->init_peer_addr) == AF_UNSPEC
624             && !ctx.qc->started) {
625             if (!csm_analyse_init_peer_addr(net_wbio, &ctx.qc->init_peer_addr))
626                 /* best effort */
627                 BIO_ADDR_clear(&ctx.qc->init_peer_addr);
628
629             ossl_quic_channel_set_peer_addr(ctx.qc->ch,
630                                             &ctx.qc->init_peer_addr);
631         }
632     }
633 }
634
635 BIO *ossl_quic_conn_get_net_rbio(const SSL *s)
636 {
637     QCTX ctx;
638
639     if (!expect_quic(s, &ctx))
640         return NULL;
641
642     return ctx.qc->net_rbio;
643 }
644
645 BIO *ossl_quic_conn_get_net_wbio(const SSL *s)
646 {
647     QCTX ctx;
648
649     if (!expect_quic(s, &ctx))
650         return NULL;
651
652     return ctx.qc->net_wbio;
653 }
654
655 int ossl_quic_conn_get_blocking_mode(const SSL *s)
656 {
657     QCTX ctx;
658
659     if (!expect_quic(s, &ctx))
660         return 0;
661
662     if (ctx.is_stream)
663         return ctx.xso->blocking;
664
665     return ctx.qc->blocking;
666 }
667
668 int ossl_quic_conn_set_blocking_mode(SSL *s, int blocking)
669 {
670     QCTX ctx;
671
672     if (!expect_quic(s, &ctx))
673         return 0;
674
675     /* Cannot enable blocking mode if we do not have pollable FDs. */
676     if (blocking != 0 &&
677         (!ctx.qc->can_poll_net_rbio || !ctx.qc->can_poll_net_wbio))
678         return QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, ERR_R_UNSUPPORTED, NULL);
679
680     if (!ctx.is_stream) {
681         /*
682          * If called on a QCSO, update default and connection-level blocking
683          * modes.
684          */
685         ctx.qc->blocking         = (blocking != 0);
686         ctx.qc->default_blocking = ctx.qc->blocking;
687     }
688
689     if (ctx.xso != NULL)
690         /*
691          * If called on  a QSSO or QCSO with a default XSO, update blocking
692          * mode.
693          */
694         ctx.xso->blocking = (blocking != 0);
695
696     return 1;
697 }
698
699 int ossl_quic_conn_set_initial_peer_addr(SSL *s,
700                                          const BIO_ADDR *peer_addr)
701 {
702     QCTX ctx;
703
704     if (!expect_quic(s, &ctx))
705         return 0;
706
707     if (ctx.qc->started)
708         return QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED,
709                                            NULL);
710
711     if (peer_addr == NULL) {
712         BIO_ADDR_clear(&ctx.qc->init_peer_addr);
713         return 1;
714     }
715
716     ctx.qc->init_peer_addr = *peer_addr;
717     return 1;
718 }
719
720 /*
721  * QUIC Front-End I/O API: Asynchronous I/O Management
722  * ===================================================
723  *
724  *   (BIO/)SSL_tick                 => ossl_quic_tick
725  *   (BIO/)SSL_get_tick_timeout     => ossl_quic_get_tick_timeout
726  *   (BIO/)SSL_get_poll_fd          => ossl_quic_get_poll_fd
727  *
728  */
729
730 /* Returns 1 if the connection is being used in blocking mode. */
731 static int qc_blocking_mode(const QUIC_CONNECTION *qc)
732 {
733     return qc->blocking;
734 }
735
736 static int xso_blocking_mode(const QUIC_XSO *xso)
737 {
738     return xso->blocking
739         && xso->conn->can_poll_net_rbio
740         && xso->conn->can_poll_net_wbio;
741 }
742
743 /* SSL_tick; ticks the reactor. */
744 QUIC_TAKES_LOCK
745 int ossl_quic_tick(SSL *s)
746 {
747     QCTX ctx;
748
749     if (!expect_quic(s, &ctx))
750         return 0;
751
752     quic_lock(ctx.qc);
753     ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(ctx.qc->ch), 0);
754     quic_unlock(ctx.qc);
755     return 1;
756 }
757
758 /*
759  * SSL_get_tick_timeout. Get the time in milliseconds until the SSL object
760  * should be ticked by the application by calling SSL_tick(). tv is set to 0 if
761  * the object should be ticked immediately and tv->tv_sec is set to -1 if no
762  * timeout is currently active.
763  */
764 QUIC_TAKES_LOCK
765 int ossl_quic_get_tick_timeout(SSL *s, struct timeval *tv)
766 {
767     QCTX ctx;
768     OSSL_TIME deadline = ossl_time_infinite();
769
770     if (!expect_quic(s, &ctx))
771         return 0;
772
773     quic_lock(ctx.qc);
774
775     deadline
776         = ossl_quic_reactor_get_tick_deadline(ossl_quic_channel_get_reactor(ctx.qc->ch));
777
778     if (ossl_time_is_infinite(deadline)) {
779         tv->tv_sec  = -1;
780         tv->tv_usec = 0;
781         quic_unlock(ctx.qc);
782         return 1;
783     }
784
785     *tv = ossl_time_to_timeval(ossl_time_subtract(deadline, ossl_time_now()));
786     quic_unlock(ctx.qc);
787     return 1;
788 }
789
790 /* SSL_get_rpoll_descriptor */
791 int ossl_quic_get_rpoll_descriptor(SSL *s, BIO_POLL_DESCRIPTOR *desc)
792 {
793     QCTX ctx;
794
795     if (!expect_quic(s, &ctx))
796         return 0;
797
798     if (desc == NULL || ctx.qc->net_rbio == NULL)
799         return 0;
800
801     return BIO_get_rpoll_descriptor(ctx.qc->net_rbio, desc);
802 }
803
804 /* SSL_get_wpoll_descriptor */
805 int ossl_quic_get_wpoll_descriptor(SSL *s, BIO_POLL_DESCRIPTOR *desc)
806 {
807     QCTX ctx;
808
809     if (!expect_quic(s, &ctx))
810         return 0;
811
812     if (desc == NULL || ctx.qc->net_wbio == NULL)
813         return 0;
814
815     return BIO_get_wpoll_descriptor(ctx.qc->net_wbio, desc);
816 }
817
818 /* SSL_net_read_desired */
819 QUIC_TAKES_LOCK
820 int ossl_quic_get_net_read_desired(SSL *s)
821 {
822     QCTX ctx;
823     int ret;
824
825     if (!expect_quic(s, &ctx))
826         return 0;
827
828     quic_lock(ctx.qc);
829     ret = ossl_quic_reactor_net_read_desired(ossl_quic_channel_get_reactor(ctx.qc->ch));
830     quic_unlock(ctx.qc);
831     return ret;
832 }
833
834 /* SSL_net_write_desired */
835 QUIC_TAKES_LOCK
836 int ossl_quic_get_net_write_desired(SSL *s)
837 {
838     int ret;
839     QCTX ctx;
840
841     if (!expect_quic(s, &ctx))
842         return 0;
843
844     quic_lock(ctx.qc);
845     ret = ossl_quic_reactor_net_write_desired(ossl_quic_channel_get_reactor(ctx.qc->ch));
846     quic_unlock(ctx.qc);
847     return ret;
848 }
849
850 /*
851  * QUIC Front-End I/O API: Connection Lifecycle Operations
852  * =======================================================
853  *
854  *         SSL_do_handshake         => ossl_quic_do_handshake
855  *         SSL_set_connect_state    => ossl_quic_set_connect_state
856  *         SSL_set_accept_state     => ossl_quic_set_accept_state
857  *         SSL_shutdown             => ossl_quic_shutdown
858  *         SSL_ctrl                 => ossl_quic_ctrl
859  *   (BIO/)SSL_connect              => ossl_quic_connect
860  *   (BIO/)SSL_accept               => ossl_quic_accept
861  *
862  */
863
864 /* SSL_shutdown */
865 static int quic_shutdown_wait(void *arg)
866 {
867     QUIC_CONNECTION *qc = arg;
868
869     return ossl_quic_channel_is_terminated(qc->ch);
870 }
871
872 QUIC_TAKES_LOCK
873 int ossl_quic_conn_shutdown(SSL *s, uint64_t flags,
874                             const SSL_SHUTDOWN_EX_ARGS *args,
875                             size_t args_len)
876 {
877     int ret;
878     QCTX ctx;
879
880     if (!expect_quic(s, &ctx))
881         return 0;
882
883     if (ctx.is_stream)
884         /* TODO(QUIC): Semantics currently undefined for QSSOs */
885         return -1;
886
887     quic_lock(ctx.qc);
888
889     ossl_quic_channel_local_close(ctx.qc->ch,
890                                   args != NULL ? args->quic_error_code : 0);
891
892     /* TODO(QUIC): !SSL_SHUTDOWN_FLAG_NO_STREAM_FLUSH */
893
894     if (ossl_quic_channel_is_terminated(ctx.qc->ch)) {
895         quic_unlock(ctx.qc);
896         return 1;
897     }
898
899     if (qc_blocking_mode(ctx.qc) && (flags & SSL_SHUTDOWN_FLAG_RAPID) == 0)
900         block_until_pred(ctx.qc, quic_shutdown_wait, ctx.qc, 0);
901     else
902         ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(ctx.qc->ch), 0);
903
904     ret = ossl_quic_channel_is_terminated(ctx.qc->ch);
905     quic_unlock(ctx.qc);
906     return ret;
907 }
908
909 /* SSL_ctrl */
910 long ossl_quic_ctrl(SSL *s, int cmd, long larg, void *parg)
911 {
912     QCTX ctx;
913
914     if (!expect_quic(s, &ctx))
915         return 0;
916
917     switch (cmd) {
918     case SSL_CTRL_MODE:
919         /* If called on a QCSO, update the default mode. */
920         if (!ctx.is_stream)
921             ctx.qc->default_ssl_mode |= (uint32_t)larg;
922
923         /*
924          * If we were called on a QSSO or have a default stream, we also update
925          * that.
926          */
927         if (ctx.xso != NULL) {
928             /* Cannot enable EPW while AON write in progress. */
929             if (ctx.xso->aon_write_in_progress)
930                 larg &= ~SSL_MODE_ENABLE_PARTIAL_WRITE;
931
932             ctx.xso->ssl_mode |= (uint32_t)larg;
933             return ctx.xso->ssl_mode;
934         }
935
936         return ctx.qc->default_ssl_mode;
937     case SSL_CTRL_CLEAR_MODE:
938         if (!ctx.is_stream)
939             ctx.qc->default_ssl_mode &= ~(uint32_t)larg;
940
941         if (ctx.xso != NULL) {
942             ctx.xso->ssl_mode &= ~(uint32_t)larg;
943             return ctx.xso->ssl_mode;
944         }
945
946         return ctx.qc->default_ssl_mode;
947     default:
948         /* Probably a TLS related ctrl. Defer to our internal SSL object */
949         return SSL_ctrl(ctx.qc->tls, cmd, larg, parg);
950     }
951 }
952
953 /* SSL_set_connect_state */
954 void ossl_quic_set_connect_state(SSL *s)
955 {
956     QCTX ctx;
957
958     if (!expect_quic(s, &ctx))
959         return;
960
961     /* Cannot be changed after handshake started */
962     if (ctx.qc->started || ctx.is_stream)
963         return;
964
965     ctx.qc->as_server_state = 0;
966 }
967
968 /* SSL_set_accept_state */
969 void ossl_quic_set_accept_state(SSL *s)
970 {
971     QCTX ctx;
972
973     if (!expect_quic(s, &ctx))
974         return;
975
976     /* Cannot be changed after handshake started */
977     if (ctx.qc->started || ctx.is_stream)
978         return;
979
980     ctx.qc->as_server_state = 1;
981 }
982
983 /* SSL_do_handshake */
984 struct quic_handshake_wait_args {
985     QUIC_CONNECTION     *qc;
986 };
987
988 static int quic_handshake_wait(void *arg)
989 {
990     struct quic_handshake_wait_args *args = arg;
991
992     if (!ossl_quic_channel_is_active(args->qc->ch))
993         return -1;
994
995     if (ossl_quic_channel_is_handshake_complete(args->qc->ch))
996         return 1;
997
998     return 0;
999 }
1000
1001 static int configure_channel(QUIC_CONNECTION *qc)
1002 {
1003     assert(qc->ch != NULL);
1004
1005     if (!ossl_quic_channel_set_net_rbio(qc->ch, qc->net_rbio)
1006         || !ossl_quic_channel_set_net_wbio(qc->ch, qc->net_wbio)
1007         || !ossl_quic_channel_set_peer_addr(qc->ch, &qc->init_peer_addr))
1008         return 0;
1009
1010     return 1;
1011 }
1012
1013 QUIC_NEEDS_LOCK
1014 static int create_channel(QUIC_CONNECTION *qc)
1015 {
1016     QUIC_CHANNEL_ARGS args = {0};
1017
1018     args.libctx     = qc->ssl.ctx->libctx;
1019     args.propq      = qc->ssl.ctx->propq;
1020     args.is_server  = qc->as_server;
1021     args.tls        = qc->tls;
1022     args.mutex      = qc->mutex;
1023     args.now_cb     = qc->override_now_cb;
1024     args.now_cb_arg = qc->override_now_cb_arg;
1025
1026     qc->ch = ossl_quic_channel_new(&args);
1027     if (qc->ch == NULL)
1028         return 0;
1029
1030     return 1;
1031 }
1032
1033 /*
1034  * Creates a channel and configures it with the information we have accumulated
1035  * via calls made to us from the application prior to starting a handshake
1036  * attempt.
1037  */
1038 QUIC_NEEDS_LOCK
1039 static int ensure_channel_started(QUIC_CONNECTION *qc)
1040 {
1041     if (!qc->started) {
1042         if (!configure_channel(qc)
1043             || !ossl_quic_channel_start(qc->ch))
1044             goto err;
1045
1046         if (qc->is_thread_assisted)
1047             if (!ossl_quic_thread_assist_init_start(&qc->thread_assist, qc->ch))
1048                 goto err;
1049     }
1050
1051     qc->started = 1;
1052     return 1;
1053
1054 err:
1055     ossl_quic_channel_free(qc->ch);
1056     qc->ch = NULL;
1057     return 0;
1058 }
1059
1060 QUIC_NEEDS_LOCK
1061 static int quic_do_handshake(QUIC_CONNECTION *qc)
1062 {
1063     int ret;
1064
1065     if (ossl_quic_channel_is_handshake_complete(qc->ch))
1066         /* Handshake already completed. */
1067         return 1;
1068
1069     if (ossl_quic_channel_is_term_any(qc->ch))
1070         return QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
1071
1072     if (BIO_ADDR_family(&qc->init_peer_addr) == AF_UNSPEC) {
1073         /* Peer address must have been set. */
1074         QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_REMOTE_PEER_ADDRESS_NOT_SET, NULL);
1075         return -1; /* Non-protocol error */
1076     }
1077
1078     if (qc->as_server != qc->as_server_state) {
1079         /* TODO(QUIC): Must match the method used to create the QCSO */
1080         QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_PASSED_INVALID_ARGUMENT, NULL);
1081         return -1; /* Non-protocol error */
1082     }
1083
1084     if (qc->net_rbio == NULL || qc->net_wbio == NULL) {
1085         /* Need read and write BIOs. */
1086         QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_BIO_NOT_SET, NULL);
1087         return -1; /* Non-protocol error */
1088     }
1089
1090     /*
1091      * Start connection process. Note we may come here multiple times in
1092      * non-blocking mode, which is fine.
1093      */
1094     if (!ensure_channel_started(qc)) {
1095         QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1096         return -1; /* Non-protocol error */
1097     }
1098
1099     if (ossl_quic_channel_is_handshake_complete(qc->ch))
1100         /* The handshake is now done. */
1101         return 1;
1102
1103     if (qc_blocking_mode(qc)) {
1104         /* In blocking mode, wait for the handshake to complete. */
1105         struct quic_handshake_wait_args args;
1106
1107         args.qc     = qc;
1108
1109         ret = block_until_pred(qc, quic_handshake_wait, &args, 0);
1110         if (!ossl_quic_channel_is_active(qc->ch)) {
1111             QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
1112             return 0; /* Shutdown before completion */
1113         } else if (ret <= 0) {
1114             QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1115             return -1; /* Non-protocol error */
1116         }
1117
1118         assert(ossl_quic_channel_is_handshake_complete(qc->ch));
1119         return 1;
1120     } else {
1121         /* Try to advance the reactor. */
1122         ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(qc->ch), 0);
1123
1124         if (ossl_quic_channel_is_handshake_complete(qc->ch))
1125             /* The handshake is now done. */
1126             return 1;
1127
1128         /* Otherwise, indicate that the handshake isn't done yet. */
1129         QUIC_RAISE_NORMAL_ERROR(qc, SSL_ERROR_WANT_READ);
1130         return -1; /* Non-protocol error */
1131     }
1132 }
1133
1134 QUIC_TAKES_LOCK
1135 int ossl_quic_do_handshake(SSL *s)
1136 {
1137     int ret;
1138     QCTX ctx;
1139
1140     if (!expect_quic(s, &ctx))
1141         return 0;
1142
1143     quic_lock(ctx.qc);
1144
1145     ret = quic_do_handshake(ctx.qc);
1146     quic_unlock(ctx.qc);
1147     return ret;
1148 }
1149
1150 /* SSL_connect */
1151 int ossl_quic_connect(SSL *s)
1152 {
1153     /* Ensure we are in connect state (no-op if non-idle). */
1154     ossl_quic_set_connect_state(s);
1155
1156     /* Begin or continue the handshake */
1157     return ossl_quic_do_handshake(s);
1158 }
1159
1160 /* SSL_accept */
1161 int ossl_quic_accept(SSL *s)
1162 {
1163     /* Ensure we are in accept state (no-op if non-idle). */
1164     ossl_quic_set_accept_state(s);
1165
1166     /* Begin or continue the handshake */
1167     return ossl_quic_do_handshake(s);
1168 }
1169
1170 /*
1171  * QUIC Front-End I/O API: Stream Lifecycle Operations
1172  * ===================================================
1173  *
1174  *         SSL_stream_new       => ossl_quic_conn_stream_new
1175  *
1176  */
1177
1178 /*
1179  * Try to create the default XSO if it doesn't already exist. Returns 1 if the
1180  * default XSO was created. Returns 0 if it was not (e.g. because it already
1181  * exists). Note that this is NOT an error condition.
1182  */
1183 QUIC_NEEDS_LOCK
1184 static int qc_try_create_default_xso_for_write(QUIC_CONNECTION *qc)
1185 {
1186     uint64_t flags = 0;
1187
1188     if (qc->default_xso_created
1189         || qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE)
1190         /*
1191          * We only do this once. If the user detaches a previously created
1192          * default XSO we don't auto-create another one.
1193          */
1194         return QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_NO_STREAM, NULL);
1195
1196     /* Create a locally-initiated stream. */
1197     if (qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_AUTO_UNI)
1198         flags |= SSL_STREAM_FLAG_UNI;
1199
1200     qc_set_default_xso(qc, (QUIC_XSO *)quic_conn_stream_new(qc, flags,
1201                                                             /*needs_lock=*/0),
1202                        /*touch=*/0);
1203     if (qc->default_xso == NULL)
1204         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1205
1206     qc_touch_default_xso(qc);
1207     return 1;
1208 }
1209
1210 struct quic_wait_for_stream_args {
1211     QUIC_CONNECTION *qc;
1212     QUIC_STREAM     *qs;
1213     uint64_t        expect_id;
1214 };
1215
1216 QUIC_NEEDS_LOCK
1217 static int quic_wait_for_stream(void *arg)
1218 {
1219     struct quic_wait_for_stream_args *args = arg;
1220
1221     if (!ossl_quic_channel_is_active(args->qc->ch)) {
1222         /* If connection is torn down due to an error while blocking, stop. */
1223         QUIC_RAISE_NON_NORMAL_ERROR(args->qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
1224         return -1;
1225     }
1226
1227     args->qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(args->qc->ch),
1228                                               args->expect_id);
1229     if (args->qs != NULL)
1230         return 1; /* stream now exists */
1231
1232     return 0; /* did not get a stream, keep trying */
1233 }
1234
1235 QUIC_NEEDS_LOCK
1236 static int qc_wait_for_default_xso_for_read(QUIC_CONNECTION *qc)
1237 {
1238     /* Called on a QCSO and we don't currently have a default stream. */
1239     uint64_t expect_id;
1240     QUIC_STREAM *qs;
1241     int res;
1242     struct quic_wait_for_stream_args wargs;
1243
1244     /*
1245      * If default stream functionality is disabled or we already detached
1246      * one, don't make another default stream and just fail.
1247      */
1248     if (qc->default_xso_created
1249         || qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE)
1250         return QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_NO_STREAM, NULL);
1251
1252     /*
1253      * The peer may have opened a stream since we last ticked. So tick and
1254      * see if the stream with ordinal 0 (remote, bidi/uni based on stream
1255      * mode) exists yet. QUIC stream IDs must be allocated in order, so the
1256      * first stream created by a peer must have an ordinal of 0.
1257      */
1258     expect_id = qc->as_server
1259         ? QUIC_STREAM_INITIATOR_CLIENT
1260         : QUIC_STREAM_INITIATOR_SERVER;
1261
1262     expect_id |= (qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_AUTO_UNI)
1263         ? QUIC_STREAM_DIR_UNI
1264         : QUIC_STREAM_DIR_BIDI;
1265
1266     qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(qc->ch),
1267                                         expect_id);
1268     if (qs == NULL) {
1269         ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(qc->ch), 0);
1270
1271         qs = ossl_quic_stream_map_get_by_id(ossl_quic_channel_get_qsm(qc->ch),
1272                                             expect_id);
1273     }
1274
1275     if (qs == NULL) {
1276         if (!qc_blocking_mode(qc))
1277             /* Non-blocking mode, so just bail immediately. */
1278             return QUIC_RAISE_NORMAL_ERROR(qc, SSL_ERROR_WANT_READ);
1279
1280         /* Block until we have a stream. */
1281         wargs.qc        = qc;
1282         wargs.qs        = NULL;
1283         wargs.expect_id = expect_id;
1284
1285         res = block_until_pred(qc, quic_wait_for_stream, &wargs, 0);
1286         if (res == 0)
1287             return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1288         else if (res < 0 || wargs.qs == NULL)
1289             /* quic_wait_for_stream raised error here */
1290             return 0;
1291
1292         qs = wargs.qs;
1293     }
1294
1295     /*
1296      * We now have qs != NULL. Make it the default stream, creating the
1297      * necessary XSO.
1298      */
1299     qc_set_default_xso(qc, create_xso_from_stream(qc, qs), /*touch=*/0);
1300     if (qc->default_xso == NULL)
1301         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1302
1303     qc_touch_default_xso(qc); /* inhibits default XSO */
1304     return 1;
1305 }
1306
1307 QUIC_NEEDS_LOCK
1308 static QUIC_XSO *create_xso_from_stream(QUIC_CONNECTION *qc, QUIC_STREAM *qs)
1309 {
1310     QUIC_XSO *xso = NULL;
1311
1312     if ((xso = OPENSSL_zalloc(sizeof(*xso))) == NULL)
1313         goto err;
1314
1315     if (!ossl_ssl_init(&xso->ssl, qc->ssl.ctx, qc->ssl.method, SSL_TYPE_QUIC_XSO))
1316         goto err;
1317
1318     xso->conn       = qc;
1319     xso->blocking   = qc->default_blocking;
1320     xso->ssl_mode   = qc->default_ssl_mode;
1321
1322     xso->stream     = qs;
1323
1324     ++qc->num_xso;
1325     return xso;
1326
1327 err:
1328     OPENSSL_free(xso);
1329     return NULL;
1330 }
1331
1332 /* locking depends on need_lock */
1333 static SSL *quic_conn_stream_new(QUIC_CONNECTION *qc, uint64_t flags,
1334                                  int need_lock)
1335 {
1336     QUIC_XSO *xso = NULL;
1337     QUIC_STREAM *qs = NULL;
1338     int is_uni = ((flags & SSL_STREAM_FLAG_UNI) != 0);
1339
1340     if (need_lock)
1341         quic_lock(qc);
1342
1343     if (ossl_quic_channel_is_term_any(qc->ch)) {
1344         QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
1345         goto err;
1346     }
1347
1348     qs = ossl_quic_channel_new_stream_local(qc->ch, is_uni);
1349     if (qs == NULL)
1350         goto err;
1351
1352     xso = create_xso_from_stream(qc, qs);
1353     if (xso == NULL)
1354         goto err;
1355
1356     qc_touch_default_xso(qc); /* inhibits default XSO */
1357     if (need_lock)
1358         quic_unlock(qc);
1359
1360     return &xso->ssl;
1361
1362 err:
1363     OPENSSL_free(xso);
1364     ossl_quic_stream_map_release(ossl_quic_channel_get_qsm(qc->ch), qs);
1365     if (need_lock)
1366         quic_unlock(qc);
1367
1368     return NULL;
1369
1370 }
1371
1372 QUIC_TAKES_LOCK
1373 SSL *ossl_quic_conn_stream_new(SSL *s, uint64_t flags)
1374 {
1375     QCTX ctx;
1376
1377     if (!expect_quic_conn_only(s, &ctx))
1378         return NULL;
1379
1380     return quic_conn_stream_new(ctx.qc, flags, /*need_lock=*/1);
1381 }
1382
1383 /*
1384  * QUIC Front-End I/O API: Steady-State Operations
1385  * ===============================================
1386  *
1387  * Here we dispatch calls to the steady-state front-end I/O API functions; that
1388  * is, the functions used during the established phase of a QUIC connection
1389  * (e.g. SSL_read, SSL_write).
1390  *
1391  * Each function must handle both blocking and non-blocking modes. As discussed
1392  * above, all QUIC I/O is implemented using non-blocking mode internally.
1393  *
1394  *         SSL_get_error        => partially implemented by ossl_quic_get_error
1395  *   (BIO/)SSL_read             => ossl_quic_read
1396  *   (BIO/)SSL_write            => ossl_quic_write
1397  *         SSL_pending          => ossl_quic_pending
1398  *         SSL_stream_conclude  => ossl_quic_conn_stream_conclude
1399  */
1400
1401 /* SSL_get_error */
1402 int ossl_quic_get_error(const SSL *s, int i)
1403 {
1404     QCTX ctx;
1405
1406     if (!expect_quic(s, &ctx))
1407         return 0;
1408
1409     return ctx.qc->last_error;
1410 }
1411
1412 /*
1413  * SSL_write
1414  * ---------
1415  *
1416  * The set of functions below provide the implementation of the public SSL_write
1417  * function. We must handle:
1418  *
1419  *   - both blocking and non-blocking operation at the application level,
1420  *     depending on how we are configured;
1421  *
1422  *   - SSL_MODE_ENABLE_PARTIAL_WRITE being on or off;
1423  *
1424  *   - SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER.
1425  *
1426  */
1427 QUIC_NEEDS_LOCK
1428 static void quic_post_write(QUIC_XSO *xso, int did_append, int do_tick)
1429 {
1430     /*
1431      * We have appended at least one byte to the stream.
1432      * Potentially mark stream as active, depending on FC.
1433      */
1434     if (did_append)
1435         ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(xso->conn->ch),
1436                                           xso->stream);
1437
1438     /*
1439      * Try and send.
1440      *
1441      * TODO(QUIC): It is probably inefficient to try and do this immediately,
1442      * plus we should eventually consider Nagle's algorithm.
1443      */
1444     if (do_tick)
1445         ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(xso->conn->ch), 0);
1446 }
1447
1448 struct quic_write_again_args {
1449     QUIC_XSO            *xso;
1450     const unsigned char *buf;
1451     size_t              len;
1452     size_t              total_written;
1453 };
1454
1455 QUIC_NEEDS_LOCK
1456 static int quic_write_again(void *arg)
1457 {
1458     struct quic_write_again_args *args = arg;
1459     size_t actual_written = 0;
1460
1461     if (!ossl_quic_channel_is_active(args->xso->conn->ch))
1462         /* If connection is torn down due to an error while blocking, stop. */
1463         return -2;
1464
1465     if (!ossl_quic_sstream_append(args->xso->stream->sstream,
1466                                   args->buf, args->len, &actual_written))
1467         return -2;
1468
1469     quic_post_write(args->xso, actual_written > 0, 0);
1470
1471     args->buf           += actual_written;
1472     args->len           -= actual_written;
1473     args->total_written += actual_written;
1474
1475     if (args->len == 0)
1476         /* Written everything, done. */
1477         return 1;
1478
1479     /* Not written everything yet, keep trying. */
1480     return 0;
1481 }
1482
1483 QUIC_NEEDS_LOCK
1484 static int quic_write_blocking(QUIC_XSO *xso, const void *buf, size_t len,
1485                                size_t *written)
1486 {
1487     int res;
1488     struct quic_write_again_args args;
1489     size_t actual_written = 0;
1490
1491     /* First make a best effort to append as much of the data as possible. */
1492     if (!ossl_quic_sstream_append(xso->stream->sstream, buf, len,
1493                                   &actual_written)) {
1494         /* Stream already finished or allocation error. */
1495         *written = 0;
1496         return QUIC_RAISE_NON_NORMAL_ERROR(xso->conn, ERR_R_INTERNAL_ERROR, NULL);
1497     }
1498
1499     quic_post_write(xso, actual_written > 0, 1);
1500
1501     if (actual_written == len) {
1502         /* Managed to append everything on the first try. */
1503         *written = actual_written;
1504         return 1;
1505     }
1506
1507     /*
1508      * We did not manage to append all of the data immediately, so the stream
1509      * buffer has probably filled up. This means we need to block until some of
1510      * it is freed up.
1511      */
1512     args.xso            = xso;
1513     args.buf            = (const unsigned char *)buf + actual_written;
1514     args.len            = len - actual_written;
1515     args.total_written  = 0;
1516
1517     res = block_until_pred(xso->conn, quic_write_again, &args, 0);
1518     if (res <= 0) {
1519         if (!ossl_quic_channel_is_active(xso->conn->ch))
1520             return QUIC_RAISE_NON_NORMAL_ERROR(xso->conn, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
1521         else
1522             return QUIC_RAISE_NON_NORMAL_ERROR(xso->conn, ERR_R_INTERNAL_ERROR, NULL);
1523     }
1524
1525     *written = args.total_written;
1526     return 1;
1527 }
1528
1529 /*
1530  * Functions to manage All-or-Nothing (AON) (that is, non-ENABLE_PARTIAL_WRITE)
1531  * write semantics.
1532  */
1533 static void aon_write_begin(QUIC_XSO *xso, const unsigned char *buf,
1534                             size_t buf_len, size_t already_sent)
1535 {
1536     assert(!xso->aon_write_in_progress);
1537
1538     xso->aon_write_in_progress = 1;
1539     xso->aon_buf_base          = buf;
1540     xso->aon_buf_pos           = already_sent;
1541     xso->aon_buf_len           = buf_len;
1542 }
1543
1544 static void aon_write_finish(QUIC_XSO *xso)
1545 {
1546     xso->aon_write_in_progress   = 0;
1547     xso->aon_buf_base            = NULL;
1548     xso->aon_buf_pos             = 0;
1549     xso->aon_buf_len             = 0;
1550 }
1551
1552 QUIC_NEEDS_LOCK
1553 static int quic_write_nonblocking_aon(QUIC_XSO *xso, const void *buf,
1554                                       size_t len, size_t *written)
1555 {
1556     const void *actual_buf;
1557     size_t actual_len, actual_written = 0;
1558     int accept_moving_buffer
1559         = ((xso->ssl_mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER) != 0);
1560
1561     if (xso->aon_write_in_progress) {
1562         /*
1563          * We are in the middle of an AON write (i.e., a previous write did not
1564          * manage to append all data to the SSTREAM and we have Enable Partial
1565          * Write (EPW) mode disabled.)
1566          */
1567         if ((!accept_moving_buffer && xso->aon_buf_base != buf)
1568             || len != xso->aon_buf_len)
1569             /*
1570              * Pointer must not have changed if we are not in accept moving
1571              * buffer mode. Length must never change.
1572              */
1573             return QUIC_RAISE_NON_NORMAL_ERROR(xso->conn, SSL_R_BAD_WRITE_RETRY, NULL);
1574
1575         actual_buf = (unsigned char *)buf + xso->aon_buf_pos;
1576         actual_len = len - xso->aon_buf_pos;
1577         assert(actual_len > 0);
1578     } else {
1579         actual_buf = buf;
1580         actual_len = len;
1581     }
1582
1583     /* First make a best effort to append as much of the data as possible. */
1584     if (!ossl_quic_sstream_append(xso->stream->sstream, actual_buf, actual_len,
1585                                   &actual_written)) {
1586         /* Stream already finished or allocation error. */
1587         *written = 0;
1588         return QUIC_RAISE_NON_NORMAL_ERROR(xso->conn, ERR_R_INTERNAL_ERROR, NULL);
1589     }
1590
1591     quic_post_write(xso, actual_written > 0, 1);
1592
1593     if (actual_written == actual_len) {
1594         /* We have sent everything. */
1595         if (xso->aon_write_in_progress) {
1596             /*
1597              * We have sent everything, and we were in the middle of an AON
1598              * write. The output write length is the total length of the AON
1599              * buffer, not however many bytes we managed to write to the stream
1600              * in this call.
1601              */
1602             *written = xso->aon_buf_len;
1603             aon_write_finish(xso);
1604         } else {
1605             *written = actual_written;
1606         }
1607
1608         return 1;
1609     }
1610
1611     if (xso->aon_write_in_progress) {
1612         /*
1613          * AON write is in progress but we have not written everything yet. We
1614          * may have managed to send zero bytes, or some number of bytes less
1615          * than the total remaining which need to be appended during this
1616          * AON operation.
1617          */
1618         xso->aon_buf_pos += actual_written;
1619         assert(xso->aon_buf_pos < xso->aon_buf_len);
1620         return QUIC_RAISE_NORMAL_ERROR(xso->conn, SSL_ERROR_WANT_WRITE);
1621     }
1622
1623     /*
1624      * Not in an existing AON operation but partial write is not enabled, so we
1625      * need to begin a new AON operation. However we needn't bother if we didn't
1626      * actually append anything.
1627      */
1628     if (actual_written > 0)
1629         aon_write_begin(xso, buf, len, actual_written);
1630
1631     /*
1632      * AON - We do not publicly admit to having appended anything until AON
1633      * completes.
1634      */
1635     *written = 0;
1636     return QUIC_RAISE_NORMAL_ERROR(xso->conn, SSL_ERROR_WANT_WRITE);
1637 }
1638
1639 QUIC_NEEDS_LOCK
1640 static int quic_write_nonblocking_epw(QUIC_XSO *xso, const void *buf, size_t len,
1641                                       size_t *written)
1642 {
1643     /* Simple best effort operation. */
1644     if (!ossl_quic_sstream_append(xso->stream->sstream, buf, len, written)) {
1645         /* Stream already finished or allocation error. */
1646         *written = 0;
1647         return QUIC_RAISE_NON_NORMAL_ERROR(xso->conn, ERR_R_INTERNAL_ERROR, NULL);
1648     }
1649
1650     quic_post_write(xso, *written > 0, 1);
1651     return 1;
1652 }
1653
1654 QUIC_TAKES_LOCK
1655 int ossl_quic_write(SSL *s, const void *buf, size_t len, size_t *written)
1656 {
1657     int ret;
1658     QCTX ctx;
1659     int partial_write;
1660
1661     *written = 0;
1662
1663     if (len == 0)
1664         return 1;
1665
1666     if (!expect_quic_with_stream_lock(s, /*remote_init=*/0, &ctx))
1667         return 0;
1668
1669     partial_write = ((ctx.xso->ssl_mode & SSL_MODE_ENABLE_PARTIAL_WRITE) != 0);
1670
1671     if (ossl_quic_channel_is_term_any(ctx.qc->ch)) {
1672         ret = QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
1673         goto out;
1674     }
1675
1676     /*
1677      * If we haven't finished the handshake, try to advance it.
1678      * We don't accept writes until the handshake is completed.
1679      */
1680     if (quic_do_handshake(ctx.qc) < 1) {
1681         ret = 0;
1682         goto out;
1683     }
1684
1685     if (ctx.xso->stream == NULL || ctx.xso->stream->sstream == NULL) {
1686         ret = QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, ERR_R_INTERNAL_ERROR, NULL);
1687         goto out;
1688     }
1689
1690     if (xso_blocking_mode(ctx.xso))
1691         ret = quic_write_blocking(ctx.xso, buf, len, written);
1692     else if (partial_write)
1693         ret = quic_write_nonblocking_epw(ctx.xso, buf, len, written);
1694     else
1695         ret = quic_write_nonblocking_aon(ctx.xso, buf, len, written);
1696
1697 out:
1698     quic_unlock(ctx.qc);
1699     return ret;
1700 }
1701
1702 /*
1703  * SSL_read
1704  * --------
1705  */
1706 struct quic_read_again_args {
1707     QUIC_CONNECTION *qc;
1708     QUIC_STREAM     *stream;
1709     void            *buf;
1710     size_t          len;
1711     size_t          *bytes_read;
1712     int             peek;
1713 };
1714
1715 QUIC_NEEDS_LOCK
1716 static int quic_read_actual(QUIC_CONNECTION *qc,
1717                             QUIC_STREAM *stream,
1718                             void *buf, size_t buf_len,
1719                             size_t *bytes_read,
1720                             int peek)
1721 {
1722     int is_fin = 0;
1723
1724     /* If the receive part of the stream is over, issue EOF. */
1725     if (stream->recv_fin_retired)
1726         return QUIC_RAISE_NORMAL_ERROR(qc, SSL_ERROR_ZERO_RETURN);
1727
1728     if (stream->rstream == NULL)
1729         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1730
1731     if (peek) {
1732         if (!ossl_quic_rstream_peek(stream->rstream, buf, buf_len,
1733                                     bytes_read, &is_fin))
1734             return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1735
1736     } else {
1737         if (!ossl_quic_rstream_read(stream->rstream, buf, buf_len,
1738                                     bytes_read, &is_fin))
1739             return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1740     }
1741
1742     if (!peek) {
1743         if (*bytes_read > 0) {
1744             /*
1745              * We have read at least one byte from the stream. Inform stream-level
1746              * RXFC of the retirement of controlled bytes. Update the active stream
1747              * status (the RXFC may now want to emit a frame granting more credit to
1748              * the peer).
1749              */
1750             OSSL_RTT_INFO rtt_info;
1751
1752             ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(qc->ch), &rtt_info);
1753
1754             if (!ossl_quic_rxfc_on_retire(&stream->rxfc, *bytes_read,
1755                                           rtt_info.smoothed_rtt))
1756                 return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1757         }
1758
1759         if (is_fin)
1760             stream->recv_fin_retired = 1;
1761
1762         if (*bytes_read > 0)
1763             ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(qc->ch),
1764                                               stream);
1765     }
1766
1767     return 1;
1768 }
1769
1770 QUIC_NEEDS_LOCK
1771 static int quic_read_again(void *arg)
1772 {
1773     struct quic_read_again_args *args = arg;
1774
1775     if (!ossl_quic_channel_is_active(args->qc->ch)) {
1776         /* If connection is torn down due to an error while blocking, stop. */
1777         QUIC_RAISE_NON_NORMAL_ERROR(args->qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
1778         return -1;
1779     }
1780
1781     if (!quic_read_actual(args->qc, args->stream,
1782                           args->buf, args->len, args->bytes_read,
1783                           args->peek))
1784         return -1;
1785
1786     if (*args->bytes_read > 0)
1787         /* got at least one byte, the SSL_read op can finish now */
1788         return 1;
1789
1790     return 0; /* did not read anything, keep trying */
1791 }
1792
1793 QUIC_TAKES_LOCK
1794 static int quic_read(SSL *s, void *buf, size_t len, size_t *bytes_read, int peek)
1795 {
1796     int ret, res;
1797     QCTX ctx;
1798     struct quic_read_again_args args;
1799
1800     *bytes_read = 0;
1801
1802     if (!expect_quic(s, &ctx))
1803         return 0;
1804
1805     quic_lock(ctx.qc);
1806
1807     if (ossl_quic_channel_is_term_any(ctx.qc->ch)) {
1808         ret = QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
1809         goto out;
1810     }
1811
1812     /* If we haven't finished the handshake, try to advance it. */
1813     if (quic_do_handshake(ctx.qc) < 1) {
1814         ret = 0; /* ossl_quic_do_handshake raised error here */
1815         goto out;
1816     }
1817
1818     if (ctx.xso == NULL) {
1819         /*
1820          * Called on a QCSO and we don't currently have a default stream.
1821          *
1822          * Wait until we get a stream initiated by the peer (blocking mode) or
1823          * fail if we don't have one yet (non-blocking mode).
1824          */
1825         if (!qc_wait_for_default_xso_for_read(ctx.qc)) {
1826             ret = 0; /* error already raised here */
1827             goto out;
1828         }
1829
1830         ctx.xso = ctx.qc->default_xso;
1831     }
1832
1833     if (ctx.xso->stream == NULL) {
1834         ret = QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, ERR_R_INTERNAL_ERROR, NULL);
1835         goto out;
1836     }
1837
1838     if (!quic_read_actual(ctx.qc, ctx.xso->stream, buf, len, bytes_read, peek)) {
1839         ret = 0; /* quic_read_actual raised error here */
1840         goto out;
1841     }
1842
1843     if (*bytes_read > 0) {
1844         /*
1845          * Even though we succeeded, tick the reactor here to ensure we are
1846          * handling other aspects of the QUIC connection.
1847          */
1848         ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(ctx.qc->ch), 0);
1849         ret = 1;
1850     } else if (xso_blocking_mode(ctx.xso)) {
1851         /*
1852          * We were not able to read anything immediately, so our stream
1853          * buffer is empty. This means we need to block until we get
1854          * at least one byte.
1855          */
1856         args.qc         = ctx.qc;
1857         args.stream     = ctx.xso->stream;
1858         args.buf        = buf;
1859         args.len        = len;
1860         args.bytes_read = bytes_read;
1861         args.peek       = peek;
1862
1863         res = block_until_pred(ctx.qc, quic_read_again, &args, 0);
1864         if (res == 0) {
1865             ret = QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, ERR_R_INTERNAL_ERROR, NULL);
1866             goto out;
1867         } else if (res < 0) {
1868             ret = 0; /* quic_read_again raised error here */
1869             goto out;
1870         }
1871
1872         ret = 1;
1873     } else {
1874         /* We did not get any bytes and are not in blocking mode. */
1875         ret = QUIC_RAISE_NORMAL_ERROR(ctx.qc, SSL_ERROR_WANT_READ);
1876     }
1877
1878 out:
1879     quic_unlock(ctx.qc);
1880     return ret;
1881 }
1882
1883 int ossl_quic_read(SSL *s, void *buf, size_t len, size_t *bytes_read)
1884 {
1885     return quic_read(s, buf, len, bytes_read, 0);
1886 }
1887
1888 int ossl_quic_peek(SSL *s, void *buf, size_t len, size_t *bytes_read)
1889 {
1890     return quic_read(s, buf, len, bytes_read, 1);
1891 }
1892
1893 /*
1894  * SSL_pending
1895  * -----------
1896  */
1897 QUIC_TAKES_LOCK
1898 static size_t ossl_quic_pending_int(const SSL *s)
1899 {
1900     QCTX ctx;
1901     size_t avail = 0;
1902     int fin = 0;
1903
1904     if (!expect_quic_with_stream_lock(s, /*remote_init=*/-1, &ctx))
1905         return 0;
1906
1907     if (ctx.xso->stream == NULL || ctx.xso->stream->rstream == NULL)
1908         /* Cannot raise errors here because we are const, just fail. */
1909         goto out;
1910
1911     if (!ossl_quic_rstream_available(ctx.xso->stream->rstream, &avail, &fin))
1912         avail = 0;
1913
1914 out:
1915     quic_unlock(ctx.qc);
1916     return avail;
1917 }
1918
1919 size_t ossl_quic_pending(const SSL *s)
1920 {
1921     return ossl_quic_pending_int(s);
1922 }
1923
1924 int ossl_quic_has_pending(const SSL *s)
1925 {
1926     return ossl_quic_pending_int(s) > 0;
1927 }
1928
1929 /*
1930  * SSL_stream_conclude
1931  * -------------------
1932  */
1933 QUIC_TAKES_LOCK
1934 int ossl_quic_conn_stream_conclude(SSL *s)
1935 {
1936     QCTX ctx;
1937     QUIC_STREAM *qs;
1938
1939     if (!expect_quic_with_stream_lock(s, /*remote_init=*/0, &ctx))
1940         return 0;
1941
1942     qs = ctx.xso->stream;
1943
1944     if (qs == NULL || qs->sstream == NULL) {
1945         quic_unlock(ctx.qc);
1946         return 0;
1947     }
1948
1949     if (!ossl_quic_channel_is_active(ctx.qc->ch)
1950         || ossl_quic_sstream_get_final_size(qs->sstream, NULL)) {
1951         quic_unlock(ctx.qc);
1952         return 1;
1953     }
1954
1955     ossl_quic_sstream_fin(qs->sstream);
1956     quic_post_write(ctx.xso, 1, 1);
1957     quic_unlock(ctx.qc);
1958     return 1;
1959 }
1960
1961 /*
1962  * SSL_inject_net_dgram
1963  * --------------------
1964  */
1965 QUIC_TAKES_LOCK
1966 int SSL_inject_net_dgram(SSL *s, const unsigned char *buf,
1967                          size_t buf_len,
1968                          const BIO_ADDR *peer,
1969                          const BIO_ADDR *local)
1970 {
1971     int ret;
1972     QCTX ctx;
1973     QUIC_DEMUX *demux;
1974
1975     if (!expect_quic(s, &ctx))
1976         return 0;
1977
1978     quic_lock(ctx.qc);
1979
1980     demux = ossl_quic_channel_get0_demux(ctx.qc->ch);
1981     ret = ossl_quic_demux_inject(demux, buf, buf_len, peer, local);
1982
1983     quic_unlock(ctx.qc);
1984     return ret;
1985 }
1986
1987 /*
1988  * SSL_get0_connection
1989  * -------------------
1990  */
1991 SSL *ossl_quic_get0_connection(SSL *s)
1992 {
1993     QCTX ctx;
1994
1995     if (!expect_quic(s, &ctx))
1996         return NULL;
1997
1998     return &ctx.qc->ssl;
1999 }
2000
2001 /*
2002  * SSL_get_stream_type
2003  * -------------------
2004  */
2005 int ossl_quic_get_stream_type(SSL *s)
2006 {
2007     QCTX ctx;
2008
2009     if (!expect_quic(s, &ctx))
2010         return SSL_STREAM_TYPE_NONE;
2011
2012     if (ctx.xso == NULL) {
2013         /*
2014          * If we are deferring XSO creation, assume single stream mode and
2015          * default to BIDI, as the deferred XSO which will be created will be
2016          * bidirectional.
2017          */
2018         if (!ctx.qc->default_xso_created)
2019             return SSL_STREAM_TYPE_BIDI;
2020         else
2021             return SSL_STREAM_TYPE_NONE;
2022     }
2023
2024     if (ossl_quic_stream_is_bidi(ctx.xso->stream))
2025         return SSL_STREAM_TYPE_BIDI;
2026
2027     if (ossl_quic_stream_is_server_init(ctx.xso->stream) != ctx.qc->as_server)
2028         return SSL_STREAM_TYPE_READ;
2029     else
2030         return SSL_STREAM_TYPE_WRITE;
2031 }
2032
2033 /*
2034  * SSL_get_stream_id
2035  * -----------------
2036  */
2037 QUIC_TAKES_LOCK
2038 uint64_t ossl_quic_get_stream_id(SSL *s)
2039 {
2040     QCTX ctx;
2041     uint64_t id;
2042
2043     if (!expect_quic_with_stream_lock(s, /*remote_init=*/-1, &ctx))
2044         return UINT64_MAX;
2045
2046     id = ctx.xso->stream->id;
2047     quic_unlock(ctx.qc);
2048
2049     return id;
2050 }
2051
2052 /*
2053  * SSL_set_default_stream_mode
2054  * ---------------------------
2055  */
2056 QUIC_TAKES_LOCK
2057 int ossl_quic_set_default_stream_mode(SSL *s, uint32_t mode)
2058 {
2059     QCTX ctx;
2060
2061     if (!expect_quic_conn_only(s, &ctx))
2062         return 0;
2063
2064     quic_lock(ctx.qc);
2065
2066     if (ctx.qc->default_xso_created)
2067         return QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED,
2068                                            "too late to change default stream mode");
2069
2070     switch (mode) {
2071     case SSL_DEFAULT_STREAM_MODE_NONE:
2072     case SSL_DEFAULT_STREAM_MODE_AUTO_BIDI:
2073     case SSL_DEFAULT_STREAM_MODE_AUTO_UNI:
2074         ctx.qc->default_stream_mode = mode;
2075         break;
2076     default:
2077         quic_unlock(ctx.qc);
2078         return QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, ERR_R_PASSED_INVALID_ARGUMENT,
2079                                            "bad default stream type");
2080     }
2081
2082     quic_unlock(ctx.qc);
2083     return 1;
2084 }
2085
2086 /*
2087  * SSL_detach_stream
2088  * -----------------
2089  */
2090 QUIC_TAKES_LOCK
2091 SSL *ossl_quic_detach_stream(SSL *s)
2092 {
2093     QCTX ctx;
2094     QUIC_XSO *xso;
2095
2096     if (!expect_quic_conn_only(s, &ctx))
2097         return NULL;
2098
2099     quic_lock(ctx.qc);
2100
2101     /* Calling this function inhibits default XSO autocreation. */
2102     xso = ctx.qc->default_xso;
2103     qc_set_default_xso(ctx.qc, NULL, /*touch=*/1);
2104
2105     quic_unlock(ctx.qc);
2106
2107     return &xso->ssl;
2108 }
2109
2110 /*
2111  * SSL_attach_stream
2112  * -----------------
2113  */
2114 QUIC_TAKES_LOCK
2115 int ossl_quic_attach_stream(SSL *conn, SSL *stream)
2116 {
2117     QCTX ctx;
2118
2119     if (!expect_quic_conn_only(conn, &ctx))
2120         return 0;
2121
2122     if (stream == NULL || stream->type != SSL_TYPE_QUIC_XSO)
2123         return QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, ERR_R_PASSED_NULL_PARAMETER,
2124                                            "stream to attach must be a valid QUIC stream");
2125
2126     quic_lock(ctx.qc);
2127
2128     if (ctx.qc->default_xso != NULL) {
2129         quic_unlock(ctx.qc);
2130         return QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED,
2131                                            "connection already has a default stream");
2132     }
2133
2134     /* Calling this function inhibits default XSO autocreation. */
2135     qc_set_default_xso(ctx.qc, (QUIC_XSO *)stream, /*touch=*/1);
2136
2137     quic_unlock(ctx.qc);
2138     return 1;
2139 }
2140
2141 /*
2142  * SSL_set_incoming_stream_reject_policy
2143  * -------------------------------------
2144  */
2145 QUIC_NEEDS_LOCK
2146 static int qc_get_effective_incoming_stream_reject_policy(QUIC_CONNECTION *qc)
2147 {
2148     switch (qc->incoming_stream_reject_policy) {
2149         case SSL_INCOMING_STREAM_REJECT_POLICY_AUTO:
2150             if ((qc->default_xso == NULL && !qc->default_xso_created)
2151                 || qc->default_stream_mode == SSL_DEFAULT_STREAM_MODE_NONE)
2152                 return SSL_INCOMING_STREAM_REJECT_POLICY_ACCEPT;
2153             else
2154                 return SSL_INCOMING_STREAM_REJECT_POLICY_REJECT;
2155
2156         default:
2157             return qc->incoming_stream_reject_policy;
2158     }
2159 }
2160
2161 QUIC_NEEDS_LOCK
2162 static void qc_update_reject_policy(QUIC_CONNECTION *qc)
2163 {
2164     int policy = qc_get_effective_incoming_stream_reject_policy(qc);
2165     int enable_reject = (policy == SSL_INCOMING_STREAM_REJECT_POLICY_REJECT);
2166
2167     ossl_quic_channel_set_incoming_stream_auto_reject(qc->ch,
2168                                                       enable_reject,
2169                                                       qc->incoming_stream_reject_aec);
2170 }
2171
2172 QUIC_TAKES_LOCK
2173 int ossl_quic_set_incoming_stream_reject_policy(SSL *s, int policy,
2174                                                 uint64_t aec)
2175 {
2176     int ret = 1;
2177     QCTX ctx;
2178
2179     if (!expect_quic_conn_only(s, &ctx))
2180         return 0;
2181
2182     quic_lock(ctx.qc);
2183
2184     switch (policy) {
2185     case SSL_INCOMING_STREAM_REJECT_POLICY_AUTO:
2186     case SSL_INCOMING_STREAM_REJECT_POLICY_ACCEPT:
2187     case SSL_INCOMING_STREAM_REJECT_POLICY_REJECT:
2188         ctx.qc->incoming_stream_reject_policy = policy;
2189         ctx.qc->incoming_stream_reject_aec    = aec;
2190         break;
2191
2192     default:
2193         ret = 0;
2194         break;
2195     }
2196
2197     qc_update_reject_policy(ctx.qc);
2198     quic_unlock(ctx.qc);
2199     return ret;
2200 }
2201
2202 /*
2203  * SSL_accept_stream
2204  * -----------------
2205  */
2206 struct wait_for_incoming_stream_args {
2207     QUIC_CONNECTION *qc;
2208     QUIC_STREAM     *qs;
2209 };
2210
2211 QUIC_NEEDS_LOCK
2212 static int wait_for_incoming_stream(void *arg)
2213 {
2214     struct wait_for_incoming_stream_args *args = arg;
2215     QUIC_STREAM_MAP *qsm = ossl_quic_channel_get_qsm(args->qc->ch);
2216
2217     if (!ossl_quic_channel_is_active(args->qc->ch)) {
2218         /* If connection is torn down due to an error while blocking, stop. */
2219         QUIC_RAISE_NON_NORMAL_ERROR(args->qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
2220         return -1;
2221     }
2222
2223     args->qs = ossl_quic_stream_map_peek_accept_queue(qsm);
2224     if (args->qs != NULL)
2225         return 1; /* got a stream */
2226
2227     return 0; /* did not get a stream, keep trying */
2228 }
2229
2230 QUIC_TAKES_LOCK
2231 SSL *ossl_quic_accept_stream(SSL *s, uint64_t flags)
2232 {
2233     QCTX ctx;
2234     int ret;
2235     SSL *new_s = NULL;
2236     QUIC_STREAM_MAP *qsm;
2237     QUIC_STREAM *qs;
2238     QUIC_XSO *xso;
2239     OSSL_RTT_INFO rtt_info;
2240
2241     if (!expect_quic_conn_only(s, &ctx))
2242         return NULL;
2243
2244     quic_lock(ctx.qc);
2245
2246     if (qc_get_effective_incoming_stream_reject_policy(ctx.qc)
2247         == SSL_INCOMING_STREAM_REJECT_POLICY_REJECT)
2248         goto out;
2249
2250     qsm = ossl_quic_channel_get_qsm(ctx.qc->ch);
2251
2252     qs = ossl_quic_stream_map_peek_accept_queue(qsm);
2253     if (qs == NULL) {
2254         if (qc_blocking_mode(ctx.qc)
2255             && (flags & SSL_ACCEPT_STREAM_NO_BLOCK) == 0) {
2256             struct wait_for_incoming_stream_args args;
2257
2258             args.qc = ctx.qc;
2259             args.qs = NULL;
2260
2261             ret = block_until_pred(ctx.qc, wait_for_incoming_stream, &args, 0);
2262             if (ret == 0) {
2263                 QUIC_RAISE_NON_NORMAL_ERROR(ctx.qc, ERR_R_INTERNAL_ERROR, NULL);
2264                 goto out;
2265             } else if (ret < 0 || args.qs == NULL) {
2266                 goto out;
2267             }
2268
2269             qs = args.qs;
2270         } else {
2271             goto out;
2272         }
2273     }
2274
2275     xso = create_xso_from_stream(ctx.qc, qs);
2276     if (xso == NULL)
2277         goto out;
2278
2279     ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(ctx.qc->ch), &rtt_info);
2280     ossl_quic_stream_map_remove_from_accept_queue(qsm, qs,
2281                                                   rtt_info.smoothed_rtt);
2282     new_s = &xso->ssl;
2283
2284     /* Calling this function inhibits default XSO autocreation. */
2285     qc_touch_default_xso(ctx.qc); /* inhibits default XSO */
2286
2287 out:
2288     quic_unlock(ctx.qc);
2289     return new_s;
2290 }
2291
2292 /*
2293  * SSL_get_accept_stream_queue_len
2294  * -------------------------------
2295  */
2296 QUIC_TAKES_LOCK
2297 size_t ossl_quic_get_accept_stream_queue_len(SSL *s)
2298 {
2299     QCTX ctx;
2300     size_t v;
2301
2302     if (!expect_quic_conn_only(s, &ctx))
2303         return 0;
2304
2305     quic_lock(ctx.qc);
2306
2307     v = ossl_quic_stream_map_get_accept_queue_len(ossl_quic_channel_get_qsm(ctx.qc->ch));
2308
2309     quic_unlock(ctx.qc);
2310     return v;
2311 }
2312
2313 /*
2314  * SSL_stream_reset
2315  * ----------------
2316  */
2317 int ossl_quic_stream_reset(SSL *ssl,
2318                            const SSL_STREAM_RESET_ARGS *args,
2319                            size_t args_len)
2320 {
2321     QCTX ctx;
2322     QUIC_STREAM_MAP *qsm;
2323     QUIC_STREAM *qs;
2324     uint64_t error_code;
2325
2326     if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/0, &ctx))
2327         return 0;
2328
2329     qsm         = ossl_quic_channel_get_qsm(ctx.qc->ch);
2330     qs          = ctx.xso->stream;
2331     error_code  = (args != NULL ? args->quic_error_code : 0);
2332
2333     ossl_quic_stream_map_reset_stream_send_part(qsm, qs, error_code);
2334
2335     quic_unlock(ctx.qc);
2336     return 1;
2337 }
2338
2339 /*
2340  * SSL_get_stream_read_state
2341  * -------------------------
2342  */
2343 static void quic_classify_stream(QUIC_CONNECTION *qc,
2344                                  QUIC_STREAM *qs,
2345                                  int is_write,
2346                                  int *state,
2347                                  uint64_t *app_error_code)
2348 {
2349     int local_init;
2350     uint64_t final_size;
2351
2352     local_init = (ossl_quic_stream_is_server_init(qs) == qc->as_server);
2353
2354     if (app_error_code != NULL)
2355         *app_error_code = UINT64_MAX;
2356     else
2357         app_error_code = &final_size; /* throw away value */
2358
2359     if (!ossl_quic_stream_is_bidi(qs) && local_init != is_write) {
2360         /*
2361          * Unidirectional stream and this direction of transmission doesn't
2362          * exist.
2363          */
2364         *state = SSL_STREAM_STATE_WRONG_DIR;
2365     } else if (ossl_quic_channel_is_term_any(qc->ch)) {
2366         /* Connection already closed. */
2367         *state = SSL_STREAM_STATE_CONN_CLOSED;
2368     } else if (!is_write && qs->recv_fin_retired) {
2369         /* Application has read a FIN. */
2370         *state = SSL_STREAM_STATE_FINISHED;
2371     } else if ((!is_write && qs->stop_sending)
2372                || (is_write && qs->reset_stream)) {
2373         /*
2374          * Stream has been reset locally. FIN takes precedence over this for the
2375          * read case as the application need not care if the stream is reset
2376          * after a FIN has been successfully processed.
2377          */
2378         *state          = SSL_STREAM_STATE_RESET_LOCAL;
2379         *app_error_code = !is_write
2380             ? qs->stop_sending_aec
2381             : qs->reset_stream_aec;
2382     } else if ((!is_write && qs->peer_reset_stream)
2383                || (is_write && qs->peer_stop_sending)) {
2384         /*
2385          * Stream has been reset remotely. */
2386         *state          = SSL_STREAM_STATE_RESET_REMOTE;
2387         *app_error_code = !is_write
2388             ? qs->peer_reset_stream_aec
2389             : qs->peer_stop_sending_aec;
2390     } else if (is_write && ossl_quic_sstream_get_final_size(qs->sstream,
2391                                                             &final_size)) {
2392         /*
2393          * Stream has been finished. Stream reset takes precedence over this for
2394          * the write case as peer may not have received all data.
2395          */
2396         *state = SSL_STREAM_STATE_FINISHED;
2397     } else {
2398         /* Stream still healthy. */
2399         *state = SSL_STREAM_STATE_OK;
2400     }
2401 }
2402
2403 static int quic_get_stream_state(SSL *ssl, int is_write)
2404 {
2405     QCTX ctx;
2406     int state;
2407
2408     if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/-1, &ctx))
2409         return SSL_STREAM_STATE_NONE;
2410
2411     quic_classify_stream(ctx.qc, ctx.xso->stream, is_write, &state, NULL);
2412     quic_unlock(ctx.qc);
2413     return state;
2414 }
2415
2416 int ossl_quic_get_stream_read_state(SSL *ssl)
2417 {
2418     return quic_get_stream_state(ssl, /*is_write=*/0);
2419 }
2420
2421 /*
2422  * SSL_get_stream_write_state
2423  * --------------------------
2424  */
2425 int ossl_quic_get_stream_write_state(SSL *ssl)
2426 {
2427     return quic_get_stream_state(ssl, /*is_write=*/1);
2428 }
2429
2430 /*
2431  * SSL_get_stream_read_error_code
2432  * ------------------------------
2433  */
2434 static int quic_get_stream_error_code(SSL *ssl, int is_write,
2435                                       uint64_t *app_error_code)
2436 {
2437     QCTX ctx;
2438     int state;
2439
2440     if (!expect_quic_with_stream_lock(ssl, /*remote_init=*/-1, &ctx))
2441         return -1;
2442
2443     quic_classify_stream(ctx.qc, ctx.xso->stream, /*is_write=*/0,
2444                          &state, app_error_code);
2445
2446     quic_unlock(ctx.qc);
2447     switch (state) {
2448         case SSL_STREAM_STATE_FINISHED:
2449              return 0;
2450         case SSL_STREAM_STATE_RESET_LOCAL:
2451         case SSL_STREAM_STATE_RESET_REMOTE:
2452              return 1;
2453         default:
2454              return -1;
2455     }
2456 }
2457
2458 int ossl_quic_get_stream_read_error_code(SSL *ssl, uint64_t *app_error_code)
2459 {
2460     return quic_get_stream_error_code(ssl, /*is_write=*/0, app_error_code);
2461 }
2462
2463 /*
2464  * SSL_get_stream_write_error_code
2465  * -------------------------------
2466  */
2467 int ossl_quic_get_stream_write_error_code(SSL *ssl, uint64_t *app_error_code)
2468 {
2469     return quic_get_stream_error_code(ssl, /*is_write=*/1, app_error_code);
2470 }
2471
2472 /*
2473  * SSL_get_conn_close_info
2474  * -----------------------
2475  */
2476 int ossl_quic_get_conn_close_info(SSL *ssl,
2477                                   SSL_CONN_CLOSE_INFO *info,
2478                                   size_t info_len)
2479 {
2480     QCTX ctx;
2481     const QUIC_TERMINATE_CAUSE *tc;
2482
2483     if (!expect_quic_conn_only(ssl, &ctx))
2484         return -1;
2485
2486     tc = ossl_quic_channel_get_terminate_cause(ctx.qc->ch);
2487     if (tc == NULL)
2488         return 0;
2489
2490     info->error_code    = tc->error_code;
2491     info->reason        = NULL; /* TODO(QUIC): Wire reason */
2492     info->reason_len    = 0;
2493     info->is_local      = !tc->remote;
2494     info->is_transport  = !tc->app;
2495     return 1;
2496 }
2497
2498 /*
2499  * QUIC Front-End I/O API: SSL_CTX Management
2500  * ==========================================
2501  */
2502
2503 long ossl_quic_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
2504 {
2505     switch (cmd) {
2506     default:
2507         return ssl3_ctx_ctrl(ctx, cmd, larg, parg);
2508     }
2509 }
2510
2511 long ossl_quic_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
2512 {
2513     return ssl3_callback_ctrl(s, cmd, fp);
2514 }
2515
2516 long ossl_quic_ctx_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
2517 {
2518     return ssl3_ctx_callback_ctrl(ctx, cmd, fp);
2519 }
2520
2521 int ossl_quic_renegotiate_check(SSL *ssl, int initok)
2522 {
2523     /* We never do renegotiation. */
2524     return 0;
2525 }
2526
2527 /*
2528  * These functions define the TLSv1.2 (and below) ciphers that are supported by
2529  * the SSL_METHOD. Since QUIC only supports TLSv1.3 we don't support any.
2530  */
2531
2532 int ossl_quic_num_ciphers(void)
2533 {
2534     return 0;
2535 }
2536
2537 const SSL_CIPHER *ossl_quic_get_cipher(unsigned int u)
2538 {
2539     return NULL;
2540 }