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