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