QUIC Front End I/O API: Wire up SSL_CTX ctrls and remove unneeded functions
[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_dummy_handshake.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_CONNECTION *qc);
21
22 /*
23  * QUIC Front-End I/O API: Common Utilities
24  * ========================================
25  */
26
27 /*
28  * Block until a predicate is met.
29  *
30  * Precondition: Must have a channel.
31  */
32 static int block_until_pred(QUIC_CONNECTION *qc,
33                             int (*pred)(void *arg), void *pred_arg,
34                             uint32_t flags)
35 {
36     QUIC_REACTOR *rtor;
37
38     assert(qc->ch != NULL);
39
40     rtor = ossl_quic_channel_get_reactor(qc->ch);
41     return ossl_quic_reactor_block_until_pred(rtor, pred, pred_arg, flags);
42 }
43
44 /*
45  * Raise a 'normal' error, meaning one that can be reported via SSL_get_error()
46  * rather than via ERR.
47  */
48 static int quic_raise_normal_error(QUIC_CONNECTION *qc,
49                                    int err)
50 {
51     qc->last_error = err;
52     return 0;
53 }
54
55 /*
56  * Raise a 'non-normal' error, meaning any error that is not reported via
57  * SSL_get_error() and must be reported via ERR.
58  */
59 static int quic_raise_non_normal_error(QUIC_CONNECTION *qc,
60                                        const char *file,
61                                        int line,
62                                        const char *func,
63                                        int reason,
64                                        const char *fmt,
65                                        ...)
66 {
67     va_list args;
68
69     ERR_new();
70     ERR_set_debug(file, line, func);
71
72     va_start(args, fmt);
73     ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
74     va_end(args);
75
76     qc->last_error = SSL_ERROR_SSL;
77     return 0;
78 }
79
80 #define QUIC_RAISE_NORMAL_ERROR(qc, err)                        \
81     quic_raise_normal_error((qc), (err))
82
83 #define QUIC_RAISE_NON_NORMAL_ERROR(qc, reason, msg)            \
84     quic_raise_non_normal_error((qc),                           \
85                                 OPENSSL_FILE, OPENSSL_LINE,     \
86                                 OPENSSL_FUNC,                   \
87                                 (reason),                       \
88                                 (msg))
89
90 /*
91  * Should be called at entry of every public function to confirm we have a valid
92  * QUIC_CONNECTION.
93  */
94 static ossl_inline int expect_quic_conn(const QUIC_CONNECTION *qc)
95 {
96     if (!ossl_assert(qc != NULL))
97         return QUIC_RAISE_NON_NORMAL_ERROR(NULL, ERR_R_INTERNAL_ERROR, NULL);
98
99     return 1;
100
101 }
102
103 /*
104  * QUIC Front-End I/O API: Initialization
105  * ======================================
106  *
107  *         SSL_new                  => ossl_quic_new
108  *                                     ossl_quic_init
109  *         SSL_reset                => ossl_quic_reset
110  *         SSL_clear                => ossl_quic_clear
111  *                                     ossl_quic_deinit
112  *         SSL_free                 => ossl_quic_free
113  *
114  */
115
116 /* SSL_new */
117 SSL *ossl_quic_new(SSL_CTX *ctx)
118 {
119     QUIC_CONNECTION *qc = NULL;
120     SSL *ssl_base = NULL;
121
122     qc = OPENSSL_zalloc(sizeof(*qc));
123     if (qc == NULL)
124         goto err;
125
126     /* Initialise the QUIC_CONNECTION's stub header. */
127     ssl_base = &qc->ssl;
128     if (!ossl_ssl_init(ssl_base, ctx, SSL_TYPE_QUIC_CONNECTION)) {
129         ssl_base = NULL;
130         goto err;
131     }
132
133     /* Channel is not created yet. */
134     qc->ssl_mode   = qc->ssl.ctx->mode;
135     qc->last_error = SSL_ERROR_NONE;
136     qc->blocking   = 1;
137     return ssl_base;
138
139 err:
140     OPENSSL_free(qc);
141     return NULL;
142 }
143
144 /* SSL_free */
145 void ossl_quic_free(SSL *s)
146 {
147     QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(s);
148
149     /* We should never be called on anything but a QUIC_CONNECTION. */
150     if (!expect_quic_conn(qc))
151         return;
152
153     ossl_quic_channel_free(qc->ch);
154
155     BIO_free(qc->net_rbio);
156     BIO_free(qc->net_wbio);
157
158     /* Note: SSL_free calls OPENSSL_free(qc) for us */
159 }
160
161 /* SSL method init */
162 int ossl_quic_init(SSL *s)
163 {
164     QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(s);
165
166     if (!expect_quic_conn(qc))
167         return 0;
168
169     /* Same op as SSL_clear, forward the call. */
170     return ossl_quic_clear(s);
171 }
172
173 /* SSL method deinit */
174 void ossl_quic_deinit(SSL *s)
175 {
176     /* No-op. */
177 }
178
179 /* SSL_reset */
180 int ossl_quic_reset(SSL *s)
181 {
182     QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(s);
183
184     if (!expect_quic_conn(qc))
185         return 0;
186
187     /* TODO(QUIC); Currently a no-op. */
188     return 1;
189 }
190
191 /* SSL_clear */
192 int ossl_quic_clear(SSL *s)
193 {
194     QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(s);
195
196     if (!expect_quic_conn(qc))
197         return 0;
198
199     /* TODO(QUIC): Currently a no-op. */
200     return 1;
201 }
202
203 /*
204  * QUIC Front-End I/O API: Network BIO Configuration
205  * =================================================
206  *
207  * Handling the different BIOs is difficult:
208  *
209  *   - It is more or less a requirement that we use non-blocking network I/O;
210  *     we need to be able to have timeouts on recv() calls, and make best effort
211  *     (non blocking) send() and recv() calls.
212  *
213  *     The only sensible way to do this is to configure the socket into
214  *     non-blocking mode. We could try to do select() before calling send() or
215  *     recv() to get a guarantee that the call will not block, but this will
216  *     probably run into issues with buggy OSes which generate spurious socket
217  *     readiness events. In any case, relying on this to work reliably does not
218  *     seem sane.
219  *
220  *     Timeouts could be handled via setsockopt() socket timeout options, but
221  *     this depends on OS support and adds another syscall to every network I/O
222  *     operation. It also has obvious thread safety concerns if we want to move
223  *     to concurrent use of a single socket at some later date.
224  *
225  *     Some OSes support a MSG_DONTWAIT flag which allows a single I/O option to
226  *     be made non-blocking. However some OSes (e.g. Windows) do not support
227  *     this, so we cannot rely on this.
228  *
229  *     As such, we need to configure any FD in non-blocking mode. This may
230  *     confound users who pass a blocking socket to libssl. However, in practice
231  *     it would be extremely strange for a user of QUIC to pass an FD to us,
232  *     then also try and send receive traffic on the same socket(!). Thus the
233  *     impact of this should be limited, and can be documented.
234  *
235  *   - We support both blocking and non-blocking operation in terms of the API
236  *     presented to the user. One prospect is to set the blocking mode based on
237  *     whether the socket passed to us was already in blocking mode. However,
238  *     Windows has no API for determining if a socket is in blocking mode (!),
239  *     therefore this cannot be done portably. Currently therefore we expose an
240  *     explicit API call to set this, and default to blocking mode.
241  *
242  *   - We need to determine our initial destination UDP address. The "natural"
243  *     way for a user to do this is to set the peer variable on a BIO_dgram.
244  *     However, this has problems because BIO_dgram's peer variable is used for
245  *     both transmission and reception. This means it can be constantly being
246  *     changed to a malicious value (e.g. if some random unrelated entity on the
247  *     network starts sending traffic to us) on every read call. This is not a
248  *     direct issue because we use the 'stateless' BIO_sendmmsg and BIO_recvmmsg
249  *     calls only, which do not use this variable. However, we do need to let
250  *     the user specify the peer in a 'normal' manner. The compromise here is
251  *     that we grab the current peer value set at the time the write BIO is set
252  *     and do not read the value again.
253  *
254  *   - We also need to support memory BIOs (e.g. BIO_dgram_pair) or custom BIOs.
255  *     Currently we do this by only supporting non-blocking mode.
256  *
257  */
258
259 /*
260  * Determines what initial destination UDP address we should use, if possible.
261  * If this fails the client must set the destination address manually, or use a
262  * BIO which does not need a destination address.
263  */
264 static int csm_analyse_init_peer_addr(BIO *net_wbio, BIO_ADDR *peer)
265 {
266     if (!BIO_dgram_get_peer(net_wbio, peer))
267         return 0;
268
269     return 1;
270 }
271
272 void ossl_quic_conn_set0_net_rbio(QUIC_CONNECTION *qc, BIO *net_rbio)
273 {
274     if (qc->net_rbio == net_rbio)
275         return;
276
277     if (qc->ch != NULL && !ossl_quic_channel_set_net_rbio(qc->ch, net_rbio))
278         return;
279
280     BIO_free(qc->net_rbio);
281     qc->net_rbio = net_rbio;
282
283     /*
284      * If what we have is not pollable (e.g. a BIO_dgram_pair) disable blocking
285      * mode as we do not support it for non-pollable BIOs.
286      */
287     if (net_rbio != NULL) {
288         BIO_POLL_DESCRIPTOR d = {0};
289
290         if (!BIO_get_rpoll_descriptor(net_rbio, &d)
291             || d.type != BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD) {
292             qc->blocking = 0;
293             qc->can_poll_net_rbio = 0;
294         } else {
295             qc->can_poll_net_rbio = 1;
296         }
297     }
298 }
299
300 void ossl_quic_conn_set0_net_wbio(QUIC_CONNECTION *qc, BIO *net_wbio)
301 {
302     if (qc->net_wbio == net_wbio)
303         return;
304
305     if (qc->ch != NULL && !ossl_quic_channel_set_net_wbio(qc->ch, net_wbio))
306         return;
307
308     BIO_free(qc->net_wbio);
309     qc->net_wbio = net_wbio;
310
311     if (net_wbio != NULL) {
312         BIO_POLL_DESCRIPTOR d = {0};
313
314         if (!BIO_get_wpoll_descriptor(net_wbio, &d)
315             || d.type != BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD) {
316             qc->blocking = 0;
317             qc->can_poll_net_wbio = 0;
318         } else {
319             qc->can_poll_net_wbio = 1;
320         }
321
322         /*
323          * If we do not have a peer address yet, and we have not started trying
324          * to connect yet, try to autodetect one.
325          */
326         if (BIO_ADDR_family(&qc->init_peer_addr) == AF_UNSPEC
327             && !qc->started) {
328             if (!csm_analyse_init_peer_addr(net_wbio, &qc->init_peer_addr))
329                 /* best effort */
330                 BIO_ADDR_clear(&qc->init_peer_addr);
331
332             if (qc->ch != NULL)
333                 ossl_quic_channel_set_peer_addr(qc->ch, &qc->init_peer_addr);
334         }
335     }
336 }
337
338 BIO *ossl_quic_conn_get_net_rbio(const QUIC_CONNECTION *qc)
339 {
340     return qc->net_rbio;
341 }
342
343 BIO *ossl_quic_conn_get_net_wbio(const QUIC_CONNECTION *qc)
344 {
345     return qc->net_wbio;
346 }
347
348 int ossl_quic_conn_get_blocking_mode(const QUIC_CONNECTION *qc)
349 {
350     return qc->blocking;
351 }
352
353 int ossl_quic_conn_set_blocking_mode(QUIC_CONNECTION *qc, int blocking)
354 {
355     /* Cannot enable blocking mode if we do not have pollable FDs. */
356     if (blocking != 0 &&
357         (!qc->can_poll_net_rbio || !qc->can_poll_net_wbio))
358         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_UNSUPPORTED, NULL);
359
360     qc->blocking = (blocking != 0);
361     return 1;
362 }
363
364 int ossl_quic_conn_set_initial_peer_addr(QUIC_CONNECTION *qc,
365                                          const BIO_ADDR *peer_addr)
366 {
367     if (qc->started)
368         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED,
369                                            NULL);
370
371     if (peer_addr == NULL) {
372         BIO_ADDR_clear(&qc->init_peer_addr);
373         return 1;
374     }
375
376     qc->init_peer_addr = *peer_addr;
377     return 1;
378 }
379
380 /*
381  * QUIC Front-End I/O API: Asynchronous I/O Management
382  * ===================================================
383  *
384  *   (BIO/)SSL_tick                 => ossl_quic_tick
385  *   (BIO/)SSL_get_tick_timeout     => ossl_quic_get_tick_timeout
386  *   (BIO/)SSL_get_poll_fd          => ossl_quic_get_poll_fd
387  *
388  */
389
390 /* Returns 1 if the connection is being used in blocking mode. */
391 static int blocking_mode(const QUIC_CONNECTION *qc)
392 {
393     return qc->blocking;
394 }
395
396 /* SSL_tick; ticks the reactor. */
397 int ossl_quic_tick(QUIC_CONNECTION *qc)
398 {
399     if (qc->ch == NULL)
400         return 1;
401
402     ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(qc->ch));
403     return 1;
404 }
405
406 /*
407  * SSL_get_tick_timeout. Get the time in milliseconds until the SSL object
408  * should be ticked by the application by calling SSL_tick(). tv is set to 0 if
409  * the object should be ticked immediately and tv->tv_sec is set to -1 if no
410  * timeout is currently active.
411  */
412 int ossl_quic_get_tick_timeout(QUIC_CONNECTION *qc, struct timeval *tv)
413 {
414     OSSL_TIME now, deadline = ossl_time_infinite();
415
416     if (qc->ch != NULL)
417         deadline
418             = ossl_quic_reactor_get_tick_deadline(ossl_quic_channel_get_reactor(qc->ch));
419
420     if (ossl_time_is_infinite(deadline)) {
421         tv->tv_sec  = -1;
422         tv->tv_usec = 0;
423         return 1;
424     }
425
426     now = ossl_time_now();
427     if (ossl_time_compare(now, deadline) >= 0) {
428         tv->tv_sec  = 0;
429         tv->tv_usec = 0;
430         return 1;
431     }
432
433     *tv = ossl_time_to_timeval(ossl_time_subtract(deadline, now));
434     return 1;
435 }
436
437 /* SSL_get_rpoll_descriptor */
438 int ossl_quic_get_rpoll_descriptor(QUIC_CONNECTION *qc, BIO_POLL_DESCRIPTOR *desc)
439 {
440     if (desc == NULL || qc->net_rbio == NULL)
441         return 0;
442
443     return BIO_get_rpoll_descriptor(qc->net_rbio, desc);
444 }
445
446 /* SSL_get_wpoll_descriptor */
447 int ossl_quic_get_wpoll_descriptor(QUIC_CONNECTION *qc, BIO_POLL_DESCRIPTOR *desc)
448 {
449     if (desc == NULL || qc->net_wbio == NULL)
450         return 0;
451
452     return BIO_get_wpoll_descriptor(qc->net_wbio, desc);
453 }
454
455 /* SSL_want_net_read */
456 int ossl_quic_get_want_net_read(QUIC_CONNECTION *qc)
457 {
458     if (qc->ch == NULL)
459         return 0;
460
461     return ossl_quic_reactor_want_net_read(ossl_quic_channel_get_reactor(qc->ch));
462 }
463
464 /* SSL_want_net_write */
465 int ossl_quic_get_want_net_write(QUIC_CONNECTION *qc)
466 {
467     if (qc->ch == NULL)
468         return 0;
469
470     return ossl_quic_reactor_want_net_write(ossl_quic_channel_get_reactor(qc->ch));
471 }
472
473 /*
474  * QUIC Front-End I/O API: Connection Lifecycle Operations
475  * =======================================================
476  *
477  *         SSL_do_handshake         => ossl_quic_do_handshake
478  *         SSL_set_connect_state    => ossl_quic_set_connect_state
479  *         SSL_set_accept_state     => ossl_quic_set_accept_state
480  *         SSL_shutdown             => ossl_quic_shutdown
481  *         SSL_ctrl                 => ossl_quic_ctrl
482  *   (BIO/)SSL_connect              => ossl_quic_connect
483  *   (BIO/)SSL_accept               => ossl_quic_accept
484  *
485  */
486
487 /* SSL_shutdown */
488 int ossl_quic_shutdown(SSL *s)
489 {
490     QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(s);
491
492     if (!expect_quic_conn(qc))
493         return 0;
494
495     if (qc->ch != NULL)
496         ossl_quic_channel_local_close(qc->ch);
497
498     return 1;
499 }
500
501 /* SSL_ctrl */
502 static void fixup_mode_change(QUIC_CONNECTION *qc)
503 {
504     /* If enabling EPW mode, cancel any AON write */
505     if ((qc->ssl_mode & SSL_MODE_ENABLE_PARTIAL_WRITE) != 0)
506         aon_write_finish(qc);
507 }
508
509 long ossl_quic_ctrl(SSL *s, int cmd, long larg, void *parg)
510 {
511     QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(s);
512
513     if (!expect_quic_conn(qc))
514         return 0;
515
516     switch (cmd) {
517     case SSL_CTRL_MODE:
518         qc->ssl_mode |= (uint32_t)larg;
519         fixup_mode_change(qc);
520         return qc->ssl_mode;
521     case SSL_CTRL_CLEAR_MODE:
522         qc->ssl_mode &= ~(uint32_t)larg;
523         fixup_mode_change(qc);
524         return qc->ssl_mode;
525     default:
526         return 0;
527     }
528 }
529
530 /* SSL_set_connect_state */
531 void ossl_quic_set_connect_state(QUIC_CONNECTION *qc)
532 {
533     /* Cannot be changed after handshake started */
534     if (qc->started)
535         return;
536
537     qc->as_server = 0;
538 }
539
540 /* SSL_set_accept_state */
541 void ossl_quic_set_accept_state(QUIC_CONNECTION *qc)
542 {
543     /* Cannot be changed after handshake started */
544     if (qc->started)
545         return;
546
547     qc->as_server = 1;
548 }
549
550 /* SSL_do_handshake */
551 struct quic_handshake_wait_args {
552     QUIC_CONNECTION     *qc;
553 };
554
555 static int quic_handshake_wait(void *arg)
556 {
557     struct quic_handshake_wait_args *args = arg;
558
559     if (!ossl_quic_channel_is_active(args->qc->ch))
560         return -1;
561
562     if (ossl_quic_channel_is_handshake_complete(args->qc->ch))
563         return 1;
564
565     return 0;
566 }
567
568 static int configure_channel(QUIC_CONNECTION *qc)
569 {
570     assert(qc->ch != NULL);
571
572     if (!ossl_quic_channel_set_net_rbio(qc->ch, qc->net_rbio)
573         || !ossl_quic_channel_set_net_wbio(qc->ch, qc->net_wbio)
574         || !ossl_quic_channel_set_peer_addr(qc->ch, &qc->init_peer_addr))
575         return 0;
576
577     return 1;
578 }
579
580 /*
581  * Creates a channel and configures it with the information we have accumulated
582  * via calls made to us from the application prior to starting a handshake
583  * attempt.
584  */
585 static int ensure_channel_and_start(QUIC_CONNECTION *qc)
586 {
587     QUIC_CHANNEL_ARGS args = {0};
588
589     if (qc->ch != NULL)
590         return 1;
591
592     args.libctx     = qc->ssl.ctx->libctx;
593     args.propq      = qc->ssl.ctx->propq;
594     args.is_server  = 0;
595
596     qc->ch = ossl_quic_channel_new(&args);
597     if (qc->ch == NULL)
598         return 0;
599
600     if (!configure_channel(qc)
601         || !ossl_quic_channel_start(qc->ch)) {
602         ossl_quic_channel_free(qc->ch);
603         qc->ch = NULL;
604         return 0;
605     }
606
607     qc->stream0 = ossl_quic_channel_get_stream_by_id(qc->ch, 0);
608     if (qc->stream0 == NULL) {
609         ossl_quic_channel_free(qc->ch);
610         qc->ch = NULL;
611         return 0;
612     }
613
614     qc->started = 1;
615     return 1;
616 }
617
618 int ossl_quic_do_handshake(QUIC_CONNECTION *qc)
619 {
620     int ret;
621
622     if (qc->ch != NULL && ossl_quic_channel_is_term_any(qc->ch))
623         return QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
624
625     if (BIO_ADDR_family(&qc->init_peer_addr) == AF_UNSPEC)
626         /* Peer address must have been set. */
627         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_PASSED_INVALID_ARGUMENT, NULL);
628
629     if (qc->as_server)
630         /* TODO(QUIC): Server mode not currently supported */
631         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_PASSED_INVALID_ARGUMENT, NULL);
632
633     if (qc->net_rbio == NULL || qc->net_wbio == NULL)
634         /* Need read and write BIOs. */
635         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_PASSED_INVALID_ARGUMENT, NULL);
636
637     /*
638      * Start connection process. Note we may come here multiple times in
639      * non-blocking mode, which is fine.
640      */
641     if (!ensure_channel_and_start(qc))
642         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
643
644     if (ossl_quic_channel_is_handshake_complete(qc->ch))
645         /* The handshake is now done. */
646         return 1;
647
648     if (blocking_mode(qc)) {
649         /* In blocking mode, wait for the handshake to complete. */
650         struct quic_handshake_wait_args args;
651
652         args.qc     = qc;
653
654         ret = block_until_pred(qc, quic_handshake_wait, &args, 0);
655         if (!ossl_quic_channel_is_active(qc->ch))
656             return QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
657         else if (ret <= 0)
658             return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
659
660         assert(ossl_quic_channel_is_handshake_complete(qc->ch));
661         return 1;
662     } else {
663         /* Otherwise, indicate that the handshake isn't done yet. */
664         return QUIC_RAISE_NORMAL_ERROR(qc, SSL_ERROR_WANT_READ);
665     }
666 }
667
668 /* SSL_connect */
669 int ossl_quic_connect(SSL *s)
670 {
671     QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(s);
672
673     if (!expect_quic_conn(qc))
674         return 0;
675
676     /* Ensure we are in connect state (no-op if non-idle). */
677     ossl_quic_set_connect_state(qc);
678
679     /* Begin or continue the handshake */
680     return ossl_quic_do_handshake(qc);
681 }
682
683 /* SSL_accept */
684 int ossl_quic_accept(SSL *s)
685 {
686     QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(s);
687
688     if (!expect_quic_conn(qc))
689         return 0;
690
691     /* Ensure we are in accept state (no-op if non-idle). */
692     ossl_quic_set_accept_state(qc);
693
694     /* Begin or continue the handshake */
695     return ossl_quic_do_handshake(qc);
696 }
697
698 /*
699  * QUIC Front-End I/O API: Steady-State Operations
700  * ===============================================
701  *
702  * Here we dispatch calls to the steady-state front-end I/O API functions; that
703  * is, the functions used during the established phase of a QUIC connection
704  * (e.g. SSL_read, SSL_write).
705  *
706  * Each function must handle both blocking and non-blocking modes. As discussed
707  * above, all QUIC I/O is implemented using non-blocking mode internally.
708  *
709  *         SSL_get_error        => partially implemented by ossl_quic_get_error
710  *   (BIO/)SSL_read             => ossl_quic_read
711  *   (BIO/)SSL_write            => ossl_quic_write
712  *         SSL_pending          => ossl_quic_pending
713  */
714
715 /* SSL_get_error */
716 int ossl_quic_get_error(const QUIC_CONNECTION *qc, int i)
717 {
718     return qc->last_error;
719 }
720
721 /*
722  * SSL_write
723  * ---------
724  *
725  * The set of functions below provide the implementation of the public SSL_write
726  * function. We must handle:
727  *
728  *   - both blocking and non-blocking operation at the application level,
729  *     depending on how we are configured;
730  *
731  *   - SSL_MODE_ENABLE_PARTIAL_WRITE being on or off;
732  *
733  *   - SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER.
734  *
735  */
736 static void quic_post_write(QUIC_CONNECTION *qc, int did_append, int do_tick)
737 {
738     /*
739      * We have appended at least one byte to the stream.
740      * Potentially mark stream as active, depending on FC.
741      */
742     if (did_append)
743         ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(qc->ch),
744                                           qc->stream0);
745
746     /*
747      * Try and send.
748      *
749      * TODO(QUIC): It is probably inefficient to try and do this immediately,
750      * plus we should eventually consider Nagle's algorithm.
751      */
752     if (do_tick)
753         ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(qc->ch));
754 }
755
756 struct quic_write_again_args {
757     QUIC_CONNECTION     *qc;
758     const unsigned char *buf;
759     size_t              len;
760     size_t              total_written;
761 };
762
763 static int quic_write_again(void *arg)
764 {
765     struct quic_write_again_args *args = arg;
766     size_t actual_written = 0;
767
768     if (!ossl_quic_channel_is_active(args->qc->ch))
769         /* If connection is torn down due to an error while blocking, stop. */
770         return -2;
771
772     if (!ossl_quic_sstream_append(args->qc->stream0->sstream,
773                                   args->buf, args->len, &actual_written))
774         return -2;
775
776     quic_post_write(args->qc, actual_written > 0, 0);
777
778     args->buf           += actual_written;
779     args->len           -= actual_written;
780     args->total_written += actual_written;
781
782     if (actual_written == 0)
783         /* Written everything, done. */
784         return 1;
785
786     /* Not written everything yet, keep trying. */
787     return 0;
788 }
789
790 static int quic_write_blocking(QUIC_CONNECTION *qc, const void *buf, size_t len,
791                                size_t *written)
792 {
793     int res;
794     struct quic_write_again_args args;
795     size_t actual_written = 0;
796
797     /* First make a best effort to append as much of the data as possible. */
798     if (!ossl_quic_sstream_append(qc->stream0->sstream, buf, len,
799                                   &actual_written)) {
800         /* Stream already finished or allocation error. */
801         *written = 0;
802         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
803     }
804
805     quic_post_write(qc, actual_written > 0, 1);
806
807     if (actual_written == len) {
808         /* Managed to append everything on the first try. */
809         *written = actual_written;
810         return 1;
811     }
812
813     /*
814      * We did not manage to append all of the data immediately, so the stream
815      * buffer has probably filled up. This means we need to block until some of
816      * it is freed up.
817      */
818     args.qc             = qc;
819     args.buf            = (const unsigned char *)buf + actual_written;
820     args.len            = len - actual_written;
821     args.total_written  = 0;
822
823     res = block_until_pred(qc, quic_write_again, &args, 0);
824     if (res <= 0) {
825         if (!ossl_quic_channel_is_active(qc->ch))
826             return QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
827         else
828             return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
829     }
830
831     *written = args.total_written;
832     return 1;
833 }
834
835 static void aon_write_begin(QUIC_CONNECTION *qc, const unsigned char *buf,
836                             size_t buf_len, size_t already_sent)
837 {
838     assert(!qc->aon_write_in_progress);
839
840     qc->aon_write_in_progress = 1;
841     qc->aon_buf_base          = buf;
842     qc->aon_buf_pos           = already_sent;
843     qc->aon_buf_len           = buf_len;
844 }
845
846 static void aon_write_finish(QUIC_CONNECTION *qc)
847 {
848     qc->aon_write_in_progress   = 0;
849     qc->aon_buf_base            = NULL;
850     qc->aon_buf_pos             = 0;
851     qc->aon_buf_len             = 0;
852 }
853
854 static int quic_write_nonblocking_aon(QUIC_CONNECTION *qc, const void *buf,
855                                       size_t len, size_t *written)
856 {
857     const void *actual_buf;
858     size_t actual_len, actual_written = 0;
859     int accept_moving_buffer
860         = ((qc->ssl_mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER) != 0);
861
862     if (qc->aon_write_in_progress) {
863         /*
864          * We are in the middle of an AON write (i.e., a previous write did not
865          * manage to append all data to the SSTREAM and we have EPW mode
866          * disabled.)
867          */
868         if ((!accept_moving_buffer && qc->aon_buf_base != buf)
869             || len != qc->aon_buf_len)
870             /*
871              * Pointer must not have changed if we are not in accept moving
872              * buffer mode. Length must never change.
873              */
874             return QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_BAD_WRITE_RETRY, NULL);
875
876         actual_buf = (unsigned char *)buf + qc->aon_buf_pos;
877         actual_len = len - qc->aon_buf_pos;
878         assert(actual_len > 0);
879     } else {
880         actual_buf = buf;
881         actual_len = len;
882     }
883
884     /* First make a best effort to append as much of the data as possible. */
885     if (!ossl_quic_sstream_append(qc->stream0->sstream, actual_buf, actual_len,
886                                   &actual_written)) {
887         /* Stream already finished or allocation error. */
888         *written = 0;
889         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
890     }
891
892     quic_post_write(qc, actual_written > 0, 1);
893
894     if (actual_written == actual_len) {
895         /* We have sent everything. */
896         if (qc->aon_write_in_progress) {
897             /*
898              * We have sent everything, and we were in the middle of an AON
899              * write. The output write length is the total length of the AON
900              * buffer, not however many bytes we managed to write to the stream
901              * in this call.
902              */
903             *written = qc->aon_buf_len;
904             aon_write_finish(qc);
905         } else {
906             *written = actual_written;
907         }
908
909         return 1;
910     }
911
912     if (qc->aon_write_in_progress) {
913         /*
914          * AON write is in progress but we have not written everything yet. We
915          * may have managed to send zero bytes, or some number of bytes less
916          * than the total remaining which need to be appended during this
917          * AON operation.
918          */
919         qc->aon_buf_pos += actual_written;
920         assert(qc->aon_buf_pos < qc->aon_buf_len);
921         return QUIC_RAISE_NORMAL_ERROR(qc, SSL_ERROR_WANT_WRITE);
922     }
923
924     /*
925      * Not in an existing AON operation but partial write is not enabled, so we
926      * need to begin a new AON operation. However we needn't bother if we didn't
927      * actually append anything.
928      */
929     if (actual_written > 0)
930         aon_write_begin(qc, buf, len, actual_written);
931
932     /*
933      * AON - We do not publicly admit to having appended anything until AON
934      * completes.
935      */
936     *written = 0;
937     return QUIC_RAISE_NORMAL_ERROR(qc, SSL_ERROR_WANT_WRITE);
938 }
939
940 static int quic_write_nonblocking_epw(QUIC_CONNECTION *qc, const void *buf, size_t len,
941                                       size_t *written)
942 {
943     /* Simple best effort operation. */
944     if (!ossl_quic_sstream_append(qc->stream0->sstream, buf, len, written)) {
945         /* Stream already finished or allocation error. */
946         *written = 0;
947         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
948     }
949
950     quic_post_write(qc, *written > 0, 1);
951     return 1;
952 }
953
954 int ossl_quic_write(SSL *s, const void *buf, size_t len, size_t *written)
955 {
956     QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(s);
957     int partial_write = ((qc->ssl_mode & SSL_MODE_ENABLE_PARTIAL_WRITE) != 0);
958
959     *written = 0;
960
961     if (!expect_quic_conn(qc))
962         return 0;
963
964     /* If we haven't started the handshake, do so automatically. */
965     if (!qc->started && !ossl_quic_do_handshake(qc))
966         return 0;
967
968     if (qc->ch != NULL && ossl_quic_channel_is_term_any(qc->ch))
969         return QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
970
971     if (qc->stream0 == NULL || qc->stream0->sstream == NULL)
972         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
973
974     if (blocking_mode(qc))
975         return quic_write_blocking(qc, buf, len, written);
976     else if (partial_write)
977         return quic_write_nonblocking_epw(qc, buf, len, written);
978     else
979         return quic_write_nonblocking_aon(qc, buf, len, written);
980 }
981
982 /*
983  * SSL_read
984  * --------
985  */
986 struct quic_read_again_args {
987     QUIC_CONNECTION *qc;
988     QUIC_STREAM     *stream;
989     void            *buf;
990     size_t          len;
991     size_t          *bytes_read;
992     int             peek;
993 };
994
995 static int quic_read_actual(QUIC_CONNECTION *qc,
996                             QUIC_STREAM *stream,
997                             void *buf, size_t buf_len,
998                             size_t *bytes_read,
999                             int peek)
1000 {
1001     int is_fin = 0;
1002
1003     if (stream->rstream == NULL)
1004         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1005
1006     if (peek) {
1007         if (!ossl_quic_rstream_peek(stream->rstream, buf, buf_len,
1008                                     bytes_read, &is_fin))
1009             return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1010
1011     } else {
1012         if (!ossl_quic_rstream_read(stream->rstream, buf, buf_len,
1013                                     bytes_read, &is_fin))
1014             return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1015     }
1016
1017     if (!peek) {
1018         if (*bytes_read > 0) {
1019             /*
1020              * We have read at least one byte from the stream. Inform stream-level
1021              * RXFC of the retirement of controlled bytes. Update the active stream
1022              * status (the RXFC may now want to emit a frame granting more credit to
1023              * the peer).
1024              */
1025             OSSL_RTT_INFO rtt_info;
1026             ossl_statm_get_rtt_info(ossl_quic_channel_get_statm(qc->ch), &rtt_info);
1027
1028             if (!ossl_quic_rxfc_on_retire(&qc->stream0->rxfc, *bytes_read,
1029                                           rtt_info.smoothed_rtt))
1030                 return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1031         }
1032
1033         if (is_fin)
1034             stream->recv_fin_retired = 1;
1035
1036         if (*bytes_read > 0)
1037             ossl_quic_stream_map_update_state(ossl_quic_channel_get_qsm(qc->ch),
1038                                               qc->stream0);
1039     }
1040
1041     return 1;
1042 }
1043
1044 static int quic_read_again(void *arg)
1045 {
1046     struct quic_read_again_args *args = arg;
1047
1048     if (!ossl_quic_channel_is_active(args->qc->ch))
1049         /* If connection is torn down due to an error while blocking, stop. */
1050         return -2;
1051
1052     if (!quic_read_actual(args->qc, args->stream,
1053                           args->buf, args->len, args->bytes_read,
1054                           args->peek))
1055         return -1;
1056
1057     if (*args->bytes_read > 0)
1058         /* got at least one byte, the SSL_read op can finish now */
1059         return 1;
1060
1061     return 0; /* did not write anything, keep trying */
1062 }
1063
1064 static int quic_read(SSL *s, void *buf, size_t len, size_t *bytes_read, int peek)
1065 {
1066     int res;
1067     QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_SSL(s);
1068     struct quic_read_again_args args;
1069
1070     *bytes_read = 0;
1071
1072     if (!expect_quic_conn(qc))
1073         return 0;
1074
1075     if (qc->ch != NULL && ossl_quic_channel_is_term_any(qc->ch))
1076         return QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
1077
1078     /* If we haven't started the handshake, do so automatically. */
1079     if (!qc->started && !ossl_quic_do_handshake(qc))
1080         return 0;
1081
1082     if (qc->stream0 == NULL)
1083         return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1084
1085     if (!quic_read_actual(qc, qc->stream0, buf, len, bytes_read, peek))
1086         return 0;
1087
1088     if (*bytes_read > 0) {
1089         /*
1090          * Even though we succeeded, tick the reactor here to ensure we are
1091          * handling other aspects of the QUIC connection.
1092          */
1093         ossl_quic_reactor_tick(ossl_quic_channel_get_reactor(qc->ch));
1094         return 1;
1095     } else if (blocking_mode(qc)) {
1096         /*
1097          * We were not able to read anything immediately, so our stream
1098          * buffer is empty. This means we need to block until we get
1099          * at least one byte.
1100          */
1101         args.qc         = qc;
1102         args.stream     = qc->stream0;
1103         args.buf        = buf;
1104         args.len        = len;
1105         args.bytes_read = bytes_read;
1106         args.peek       = peek;
1107
1108         res = block_until_pred(qc, quic_read_again, &args, 0);
1109         if (res <= 0) {
1110             if (!ossl_quic_channel_is_active(qc->ch))
1111                 return QUIC_RAISE_NON_NORMAL_ERROR(qc, SSL_R_PROTOCOL_IS_SHUTDOWN, NULL);
1112             else
1113                 return QUIC_RAISE_NON_NORMAL_ERROR(qc, ERR_R_INTERNAL_ERROR, NULL);
1114         }
1115     }
1116
1117     return 1;
1118 }
1119
1120 int ossl_quic_read(SSL *s, void *buf, size_t len, size_t *bytes_read)
1121 {
1122     return quic_read(s, buf, len, bytes_read, 0);
1123 }
1124
1125 int ossl_quic_peek(SSL *s, void *buf, size_t len, size_t *bytes_read)
1126 {
1127     return quic_read(s, buf, len, bytes_read, 1);
1128 }
1129
1130 /*
1131  * SSL_pending
1132  * -----------
1133  */
1134 size_t ossl_quic_pending(const SSL *s)
1135 {
1136     const QUIC_CONNECTION *qc = QUIC_CONNECTION_FROM_CONST_SSL(s);
1137     size_t avail = 0;
1138     int fin = 0;
1139
1140     if (!expect_quic_conn(qc))
1141         return 0;
1142
1143     if (qc->stream0 == NULL || qc->stream0->rstream == NULL)
1144         /* Cannot raise errors here because we are const, just fail. */
1145         return 0;
1146
1147     if (!ossl_quic_rstream_available(qc->stream0->rstream, &avail, &fin))
1148         return 0;
1149
1150     return avail;
1151 }
1152
1153 /*
1154  * QUIC Front-End I/O API: SSL_CTX Management
1155  * ==========================================
1156  */
1157
1158 long ossl_quic_ctx_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg)
1159 {
1160     switch (cmd) {
1161     default:
1162         return ssl3_ctx_ctrl(ctx, cmd, larg, parg);
1163     }
1164 }
1165
1166 long ossl_quic_callback_ctrl(SSL *s, int cmd, void (*fp) (void))
1167 {
1168     return ssl3_callback_ctrl(s, cmd, fp);
1169 }
1170
1171 long ossl_quic_ctx_callback_ctrl(SSL_CTX *ctx, int cmd, void (*fp) (void))
1172 {
1173     return ssl3_ctx_callback_ctrl(ctx, cmd, fp);
1174 }
1175
1176 int ossl_quic_renegotiate_check(SSL *ssl, int initok)
1177 {
1178     /* We never do renegotiation. */
1179     return 0;
1180 }
1181
1182 /*
1183  * This is the subset of TLS1.3 ciphers which can be used with QUIC and which we
1184  * actually support.
1185  */
1186 static SSL_CIPHER tls13_quic_ciphers[] = {
1187     {
1188         1,
1189         TLS1_3_RFC_AES_128_GCM_SHA256,
1190         TLS1_3_RFC_AES_128_GCM_SHA256,
1191         TLS1_3_CK_AES_128_GCM_SHA256,
1192         SSL_kANY,
1193         SSL_aANY,
1194         SSL_AES128GCM,
1195         SSL_AEAD,
1196         TLS1_3_VERSION, TLS1_3_VERSION,
1197         0, 0,
1198         SSL_HIGH,
1199         SSL_HANDSHAKE_MAC_SHA256,
1200         128,
1201         128,
1202     }, {
1203         1,
1204         TLS1_3_RFC_AES_256_GCM_SHA384,
1205         TLS1_3_RFC_AES_256_GCM_SHA384,
1206         TLS1_3_CK_AES_256_GCM_SHA384,
1207         SSL_kANY,
1208         SSL_aANY,
1209         SSL_AES256GCM,
1210         SSL_AEAD,
1211         TLS1_3_VERSION, TLS1_3_VERSION,
1212         0, 0,
1213         SSL_HIGH,
1214         SSL_HANDSHAKE_MAC_SHA384,
1215         256,
1216         256,
1217     },
1218     {
1219         1,
1220         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
1221         TLS1_3_RFC_CHACHA20_POLY1305_SHA256,
1222         TLS1_3_CK_CHACHA20_POLY1305_SHA256,
1223         SSL_kANY,
1224         SSL_aANY,
1225         SSL_CHACHA20POLY1305,
1226         SSL_AEAD,
1227         TLS1_3_VERSION, TLS1_3_VERSION,
1228         0, 0,
1229         SSL_HIGH,
1230         SSL_HANDSHAKE_MAC_SHA256,
1231         256,
1232         256,
1233     }
1234 };
1235
1236 int ossl_quic_num_ciphers(void)
1237 {
1238     return OSSL_NELEM(tls13_quic_ciphers);
1239 }
1240
1241 const SSL_CIPHER *ossl_quic_get_cipher(unsigned int u)
1242 {
1243     if (u >= OSSL_NELEM(tls13_quic_ciphers))
1244         return NULL;
1245
1246     return &tls13_quic_ciphers[u];
1247 }