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