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