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