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