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