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