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