Debian Codegraph @

crt/s2n/bindings/rust/extended/s2n-tls/src/callbacks/async_cb.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! Support for asynchronous callbacks.
5 //!
6 //! The general flow for an async callback is:
7 //! 1. The application sets FooCallback on the [`crate::config::Config`] with
8 //! a method like Config::set_foo_callback.
9 //! 2. When the underlying C library reaches the trigger for that specific
10 //! callback (for example, the ClientHello for [`crate::callbacks::ClientHelloCallback`])
11 //! it calls the callback implementation to get a [`ConnectionFuture`].
12 //! 3. The [`ConnectionFuture`] is stored on the connection. Every time
13 //! the handshake is polled, the [`ConnectionFuture`] is polled instead.
14 //! 4. Once the [`ConnectionFuture`] returns a result, the connection
15 //! drops the future and proceeds as usual.
16
17 use crate::{connection::Connection, enums::CallbackResult, error::Error};
18 use core::task::Poll;
19 use pin_project_lite::pin_project;
20 use std::pin::Pin;
21
22 /// The Future associated with the async connection callback.
23 ///
24 /// The calling application can provide an instance of [`ConnectionFuture`]
25 /// when implementing an async callback, eg. [`crate::callbacks::ClientHelloCallback`],
26 /// if it wants to run an asynchronous operation (disk read, network call).
27 /// The application can return an error ([Err(Error::application())])
28 /// to indicate connection failure.
29 pub trait ConnectionFuture: 'static + Send + Sync {
30 fn poll(
31 self: Pin<&mut Self>,
32 connection: &mut Connection,
33 ctx: &mut core::task::Context,
34 ) -> Poll<Result<(), Error>>;
35 }
36
37 pub(crate) type ConnectionFutureResult = Result<Option<Pin<Box<dyn ConnectionFuture>>>, Error>;
38
39 // Useful for propagating [`error::Error`] from a C callback back to the Rust application.
40 pub(crate) struct ErrorFuture {
41 error: Option<Error>,
42 }
43
44 impl ConnectionFuture for ErrorFuture {
45 fn poll(
46 mut self: Pin<&mut Self>,
47 _connection: &mut Connection,
48 _ctx: &mut core::task::Context,
49 ) -> Poll<Result<(), Error>> {
50 let err = self.error.take().expect(
51 "ErrorFuture should be initialized with Some(error) and a Future should never
52 be polled after it returns Poll::Ready",
53 );
54 Poll::Ready(Err(err))
55 }
56 }
57
58 pin_project! {
59 /// A wrapper around an optional [`ConnectionFuture`]
60 /// which either polls the future or immediately reports success.
61 struct OptionalFuture {
62 option: Option<Pin<Box<dyn ConnectionFuture>>>,
63 }
64 }
65
66 impl OptionalFuture {
67 fn new(input: ConnectionFutureResult) -> Self {
68 match input {
69 Ok(option) => OptionalFuture { option },
70 Err(error) => {
71 let error = Some(error);
72 OptionalFuture {
73 option: Some(Box::pin(ErrorFuture { error })),
74 }
75 }
76 }
77 }
78 }
79
80 impl ConnectionFuture for OptionalFuture {
81 fn poll(
82 mut self: Pin<&mut Self>,
83 conn: &mut Connection,
84 ctx: &mut core::task::Context,
85 ) -> Poll<Result<(), Error>> {
86 match self.option.as_mut() {
87 Some(future) => future.as_mut().poll(conn, ctx),
88 None => Poll::Ready(Ok(())),
89 }
90 }
91 }
92
93 /// Any work necessary after the callback completes.
94 //
95 // We do not expect any callback except [`ClientHelloCallback`] to require MarkDone.
96 // More recent callbacks follow a different model that doesn't require separate cleanup.
97 //
98 // This enum is sufficient while only ClientHello is special-cased, but will not
99 // scale well. If we need more MarkDone variants, then we should consider a different
100 // solution, like another stored future.
101 #[non_exhaustive]
102 #[derive(PartialEq)]
103 enum MarkDone {
104 ClientHello,
105 None,
106 }
107
108 pin_project! {
109 // Stores the [`ConnectionFuture`] and associated state.
110 pub(crate) struct AsyncCallback {
111 #[pin]
112 future: OptionalFuture,
113 cleanup: MarkDone,
114 }
115 }
116
117 impl AsyncCallback {
118 pub(crate) fn poll(
119 self: Pin<&mut Self>,
120 conn: &mut Connection,
121 ctx: &mut core::task::Context,
122 ) -> Poll<Result<(), Error>> {
123 let this = self.project();
124 let poll = this.future.poll(conn, ctx);
125 if let Poll::Ready(Ok(())) = poll {
126 if this.cleanup == &MarkDone::ClientHello {
127 conn.mark_client_hello_cb_done()?;
128 }
129 }
130 poll
131 }
132
133 pub(crate) fn trigger_client_hello_cb(
134 future: ConnectionFutureResult,
135 conn: &mut Connection,
136 ) -> CallbackResult {
137 let future = OptionalFuture::new(future);
138 let cleanup = MarkDone::ClientHello;
139 let callback = AsyncCallback { future, cleanup };
140 conn.set_async_callback(callback);
141 CallbackResult::Success
142 }
143
144 pub(crate) fn trigger(future: ConnectionFutureResult, conn: &mut Connection) -> CallbackResult {
145 let future = OptionalFuture::new(future);
146 let cleanup = MarkDone::None;
147 let callback = AsyncCallback { future, cleanup };
148 conn.set_async_callback(callback);
149 CallbackResult::Success
150 }
151 }