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