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