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