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