ktls_stream/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod log;
4
5use std::io::{self, Read, Write};
6use std::os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd};
7#[cfg(feature = "async-io-tokio")]
8use std::pin::Pin;
9#[cfg(feature = "async-io-tokio")]
10use std::task;
11
12use ktls_core::utils::Buffer;
13use ktls_core::{Context, TlsSession};
14#[cfg(feature = "async-io-tokio")]
15use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
16
17pin_project_lite::pin_project! {
18    #[derive(Debug)]
19    #[project = StreamProj]
20    /// A thin wrapper around a socket with kernel TLS (kTLS) offload configured.
21    ///
22    /// This implements traits [`Read`](std::io::Read) and
23    /// [`Write`](std::io::Write), [`AsyncRead`](tokio::io::AsyncRead) and
24    /// [`AsyncWrite`](tokio::io::AsyncWrite) (when feature `async-io-tokio` is
25    /// enabled).
26    ///
27    /// ## Behaviours
28    ///
29    /// Once a TLS `close_notify` alert from the peer is received, all subsequent
30    /// read operations will return EOF.
31    ///
32    /// Once the caller explicitly calls `(poll_)shutdown` on the stream, all
33    /// subsequent write operations will return 0 bytes, indicating that the
34    /// stream is closed for writing.
35    ///
36    /// Once the stream is being dropped, a `close_notify` alert would be sent to
37    /// the peer automatically before shutting down the inner socket, according to
38    /// [RFC 8446, section 6.1].
39    ///
40    /// The caller may call `(poll_)shutdown` on the stream to shutdown explicitly
41    /// both sides of the stream. Currently, there's no way provided by this crate
42    /// to shutdown the TLS stream write side only. For TLS 1.2, this is ideal since
43    /// once one party sends a `close_notify` alert, *the other party MUST respond
44    /// with a `close_notify` alert of its own and close down the connection
45    /// immediately*, according to [RFC 5246, section 7.2.1]; for TLS 1.3, *both
46    /// parties need not wait to receive a "`close_notify`" alert before
47    /// closing their read side of the connection*, according to [RFC 8446, section
48    /// 6.1].
49    ///
50    /// [RFC 5246, section 7.2.1]: https://tools.ietf.org/html/rfc5246#section-7.2.1
51    /// [RFC 8446, section 6.1]: https://tools.ietf.org/html/rfc8446#section-6.1
52    pub struct Stream<S: AsFd, C: TlsSession> {
53        #[pin]
54        inner: S,
55
56        // Context of the kTLS connection.
57        context: Context<C>,
58    }
59
60    impl<S: AsFd, C: TlsSession> PinnedDrop for Stream<S, C> {
61        fn drop(this: Pin<&mut Self>) {
62            let this = this.project();
63
64            this.context.shutdown(&*this.inner);
65        }
66    }
67}
68
69impl<S: AsFd, C: TlsSession> Stream<S, C> {
70    /// Creates a new kTLS stream from the given socket, TLS session and an
71    /// optional buffer (may be early data received from peer during
72    /// handshaking).
73    ///
74    /// # Prerequisites
75    ///
76    /// - The socket must have TLS ULP configured with
77    ///   [`setup_ulp`](ktls_core::setup_ulp).
78    /// - The TLS handshake must be completed.
79    pub fn new(socket: S, session: C, buffer: Option<Buffer>) -> Self {
80        Self {
81            inner: socket,
82            context: Context::new(session, buffer),
83        }
84    }
85
86    /// Returns a mutable reference to the inner socket if the TLS connection is
87    /// not closed (unidirectionally or bidirectionally).
88    ///
89    /// This requires a mutable reference to the [`Stream`] to ensure a
90    /// exclusive access to the inner socket.
91    ///
92    /// ## Notes
93    ///
94    /// * All buffered data **MUST** be properly consumed (See
95    ///   [`AccessRawStreamError::HasBufferedData`]).
96    ///
97    ///   The buffered data typically consists of:
98    ///
99    ///   - Early data received during handshake.
100    ///   - Application data received due to improper usage of
101    ///     [`StreamRefMutRaw::handle_io_error`].
102    ///
103    /// * The caller **MAY** handle any [`io::Result`]s returned by I/O
104    ///   operations directly on the inner socket with
105    ///   [`StreamRefMutRaw::handle_io_error`].
106    ///
107    /// * The caller **MUST NOT** shutdown the inner socket directly, which will
108    ///   lead to undefined behaviours. Instead, the caller **MAY**
109    ///   `(poll_)shutdown` explictly the [`Stream`] to gracefully shutdown the
110    ///   TLS stream (with `close_notify` be sent), or just drop the stream to
111    ///   do automatic graceful shutdown.
112    ///
113    /// # Errors
114    ///
115    /// See [`AccessRawStreamError`].
116    pub fn as_mut_raw(&mut self) -> Result<StreamRefMutRaw<'_, S, C>, AccessRawStreamError> {
117        if let Some(buffer) = self.context.buffer_mut().drain() {
118            return Err(AccessRawStreamError::HasBufferedData(buffer));
119        }
120
121        let state = self.context.state();
122
123        if state.is_closed() {
124            // Fully closed, just return error.
125            return Err(AccessRawStreamError::Closed);
126        }
127
128        Ok(StreamRefMutRaw { this: self })
129    }
130}
131
132#[cfg(feature = "shim-rustls")]
133impl<S, Data> Stream<S, rustls::kernel::KernelConnection<Data>>
134where
135    S: AsFd,
136    rustls::kernel::KernelConnection<Data>: TlsSession,
137{
138    /// Constructs a new [`Stream`] from a socket, TLS secrets, and TLS session
139    /// context.
140    ///
141    /// # Overview
142    ///
143    /// This creates a [`Stream`] from the provided socket, extracted TLS
144    /// secrets ([`rustls::ExtractedSecrets`]), and TLS session context
145    /// ([`rustls::kernel::KernelConnection`]). An optional buffer may be
146    /// provided for early data received during handshake.
147    ///
148    /// The secrets and context must be extracted from a
149    /// [`rustls::client::UnbufferedClientConnection`] or
150    /// [`rustls::client::UnbufferedClientConnection`]. See [`rustls::kernel`]
151    /// module documentation for more details.
152    ///
153    /// ## Prerequisites
154    ///
155    /// The socket must have TLS ULP configured with
156    /// [`setup_ulp`](ktls_core::setup_ulp).
157    ///
158    /// ## Errors
159    ///
160    /// Returns an error if prerequisites aren't met or kernel TLS setup fails.
161    pub fn from(
162        socket: S,
163        secrets: rustls::ExtractedSecrets,
164        session: rustls::kernel::KernelConnection<Data>,
165        buffer: Option<Buffer>,
166    ) -> Result<Self, ktls_core::Error> {
167        use ktls_core::{TlsCryptoInfoRx, TlsCryptoInfoTx};
168
169        let rustls::ExtractedSecrets {
170            tx: (seq_tx, secrets_tx),
171            rx: (seq_rx, secrets_rx),
172        } = secrets;
173
174        let tls_crypto_info_tx = TlsCryptoInfoTx::new(
175            session.protocol_version().into(),
176            secrets_tx.try_into()?,
177            seq_tx,
178        )?;
179
180        let tls_crypto_info_rx = TlsCryptoInfoRx::new(
181            session.protocol_version().into(),
182            secrets_rx.try_into()?,
183            seq_rx,
184        )?;
185
186        ktls_core::setup_tls_params(&socket, &tls_crypto_info_tx, &tls_crypto_info_rx)?;
187
188        Ok(Self::new(socket, session, buffer))
189    }
190}
191
192macro_rules! handle_ret {
193    ($this:expr, $($tt:tt)+) => {
194        loop {
195            let err = match $($tt)+ {
196                r @ Ok(_) => return r,
197                Err(err) => err,
198            };
199
200            $this.context.handle_io_error(&$this.inner, err)?;
201        }
202    };
203}
204
205impl<S, C> Read for Stream<S, C>
206where
207    S: AsFd + Read,
208    C: TlsSession,
209{
210    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
211        handle_ret!(self, {
212            if self.context.state().is_read_closed() {
213                crate::trace!("Read closed, returning EOF");
214
215                return Ok(0);
216            }
217
218            let read_from_buffer = self.context.buffer_mut().read(|data| {
219                crate::trace!("Read from buffer: remaining {} bytes", data.len());
220
221                let amt = buf.len().min(data.len());
222                buf[..amt].copy_from_slice(&data[..amt]);
223                amt
224            });
225
226            if let Some(read_from_buffer) = read_from_buffer {
227                return Ok(read_from_buffer.get());
228            }
229
230            // Retry is OK, the implementation of `Read` requires no data will be
231            // read into the buffer when error occurs.
232            self.inner.read(buf)
233        })
234    }
235}
236
237macro_rules! impl_shutdown {
238    ($ty:ty) => {
239        impl<C> Stream<$ty, C>
240        where
241            C: TlsSession,
242        {
243            /// Shuts down both read and write sides of the TLS stream.
244            pub fn shutdown(&mut self) {
245                let is_write_closed = self.context.state().is_write_closed();
246
247                self.context.shutdown(&self.inner);
248
249                if !is_write_closed {
250                    let _ = self
251                        .inner
252                        .shutdown(std::net::Shutdown::Write);
253                }
254            }
255        }
256    };
257}
258
259impl_shutdown!(std::net::TcpStream);
260impl_shutdown!(std::os::unix::net::UnixStream);
261
262impl<S, C> Write for Stream<S, C>
263where
264    S: AsFd + Write,
265    C: TlsSession,
266{
267    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
268        handle_ret!(self, {
269            if self.context.state().is_write_closed() {
270                crate::trace!("Write closed, returning EOF");
271
272                return Ok(0);
273            }
274
275            // Retry is OK, the implementation of `Write` requires no data will
276            // be written when error occurs.
277            self.inner.write(buf)
278        })
279    }
280
281    fn flush(&mut self) -> io::Result<()> {
282        handle_ret!(self, {
283            if self.context.state().is_write_closed() {
284                crate::trace!("Write closed, skipping flush");
285
286                return Ok(());
287            }
288
289            self.inner.flush()
290        })
291    }
292}
293
294#[cfg(feature = "async-io-tokio")]
295macro_rules! handle_ret_async {
296    ($this:expr, $($tt:tt)+) => {
297        loop {
298            let err = match $($tt)+ {
299                r @ std::task::Poll::Pending => return r,
300                r @ std::task::Poll::Ready(Ok(_)) => return r,
301                std::task::Poll::Ready(Err(err)) => err,
302            };
303
304            $this.context.handle_io_error(&*$this.inner, err)?;
305        }
306    };
307}
308
309#[cfg(feature = "async-io-tokio")]
310impl<S, C> AsyncRead for Stream<S, C>
311where
312    S: AsFd + AsyncRead,
313    C: TlsSession,
314{
315    fn poll_read(
316        self: Pin<&mut Self>,
317        cx: &mut task::Context<'_>,
318        buf: &mut ReadBuf<'_>,
319    ) -> task::Poll<io::Result<()>> {
320        let mut this = self.project();
321
322        handle_ret_async!(this, {
323            if this.context.state().is_read_closed() {
324                crate::trace!("Read closed, returning EOF");
325
326                return task::Poll::Ready(Ok(()));
327            }
328
329            this.context.buffer_mut().read(|data| {
330                crate::trace!("Read from buffer: remaining {} bytes", data.len());
331
332                let amt = buf.remaining().min(data.len());
333                buf.put_slice(&data[..amt]);
334                amt
335            });
336
337            // Retry is OK, the implementation of `poll_read` requires no data will be
338            // read into the buffer when error occurs.
339            this.inner.as_mut().poll_read(cx, buf)
340        })
341    }
342}
343
344#[cfg(feature = "async-io-tokio")]
345impl<S, C> AsyncWrite for Stream<S, C>
346where
347    S: AsFd + AsyncWrite,
348    C: TlsSession,
349{
350    fn poll_write(
351        self: Pin<&mut Self>,
352        cx: &mut task::Context<'_>,
353        buf: &[u8],
354    ) -> task::Poll<io::Result<usize>> {
355        let mut this = self.project();
356
357        handle_ret_async!(this, {
358            if this.context.state().is_write_closed() {
359                crate::trace!("Write closed, returning EOF");
360
361                return task::Poll::Ready(Ok(0));
362            }
363
364            this.inner.as_mut().poll_write(cx, buf)
365        })
366    }
367
368    fn poll_flush(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> task::Poll<io::Result<()>> {
369        let mut this = self.project();
370
371        handle_ret_async!(this, {
372            if this.context.state().is_write_closed() {
373                crate::trace!("Write closed, skipping flush");
374
375                return task::Poll::Ready(Ok(()));
376            }
377
378            this.inner.as_mut().poll_flush(cx)
379        })
380    }
381
382    fn poll_shutdown(
383        self: Pin<&mut Self>,
384        cx: &mut task::Context<'_>,
385    ) -> task::Poll<io::Result<()>> {
386        let this = self.project();
387
388        let is_write_closed = this.context.state().is_write_closed();
389
390        // Notify the peer that we're going to close the write side.
391        this.context.shutdown(&*this.inner);
392
393        if is_write_closed {
394            task::Poll::Ready(Ok(()))
395        } else {
396            this.inner.poll_shutdown(cx)
397        }
398    }
399}
400
401/// See [`Stream::as_mut_raw`].
402pub struct StreamRefMutRaw<'a, S: AsFd, C: TlsSession> {
403    this: &'a mut Stream<S, C>,
404}
405
406impl<S: AsFd, C: TlsSession> StreamRefMutRaw<'_, S, C> {
407    /// Performs read operation on the inner socket, handles possible errors
408    /// with [`Context::handle_io_error`] and retries the operation if the
409    /// error is recoverable (see [`Context::handle_io_error`] for details).
410    ///
411    /// # Prerequisites
412    ///
413    /// The caller SHOULD NOT perform any *write* operations in `f`.
414    ///
415    /// # Errors
416    ///
417    /// - If the read side of the TLS stream is closed, this will return an EOF.
418    /// - Returns the original I/O error returned by `f` that is unrecoverable.
419    ///
420    ///   See also [`Context::handle_io_error`].
421    pub fn try_read_io<F, R>(&mut self, mut f: F) -> io::Result<R>
422    where
423        F: FnMut(&mut S) -> io::Result<R>,
424    {
425        if self
426            .this
427            .context
428            .state()
429            .is_read_closed()
430        {
431            crate::trace!("Read closed, returning EOF");
432
433            return Err(io::Error::new(
434                io::ErrorKind::UnexpectedEof,
435                "TLS stream (read side) is closed",
436            ));
437        }
438
439        handle_ret!(self.this, f(&mut self.this.inner));
440    }
441
442    /// Performs write operation on the inner socket, handles possible errors
443    /// with [`Context::handle_io_error`] and retries the operation if the
444    /// error is recoverable (see [`Context::handle_io_error`] for details).
445    ///
446    /// # Prerequisites
447    ///
448    /// The caller SHOULD NOT perform any *read* operations in `f`.
449    ///
450    /// # Errors
451    ///
452    /// - If the write side of the TLS stream is closed, this will return an
453    ///   EOF.
454    /// - Returns the original I/O error returned by `f` that is unrecoverable.
455    ///
456    ///   See also [`Context::handle_io_error`].
457    pub fn try_write_io<F, R>(&mut self, mut f: F) -> io::Result<R>
458    where
459        F: FnMut(&mut S) -> io::Result<R>,
460    {
461        if self
462            .this
463            .context
464            .state()
465            .is_write_closed()
466        {
467            crate::trace!("Write closed, returning EOF");
468
469            return Err(io::Error::new(
470                io::ErrorKind::UnexpectedEof,
471                "TLS stream (write side) is closed",
472            ));
473        }
474
475        handle_ret!(self.this, f(&mut self.this.inner));
476    }
477
478    #[inline]
479    /// Since [`StreamRefMutRaw`] provides direct access to the inner socket,
480    /// the caller **MUST** handle any possible I/O errors returned by I/O
481    /// operations on the inner socket with this method.
482    ///
483    /// See also [`Context::handle_io_error`].
484    ///
485    /// # Errors
486    ///
487    /// See [`Context::handle_io_error`].
488    pub fn handle_io_error(&mut self, err: io::Error) -> io::Result<()> {
489        self.this
490            .context
491            .handle_io_error(&self.this.inner, err)
492    }
493}
494
495impl<S: AsFd, C: TlsSession> AsFd for StreamRefMutRaw<'_, S, C> {
496    #[inline]
497    fn as_fd(&self) -> BorrowedFd<'_> {
498        self.this.inner.as_fd()
499    }
500}
501
502impl<S: AsFd, C: TlsSession> AsRawFd for StreamRefMutRaw<'_, S, C> {
503    #[inline]
504    fn as_raw_fd(&self) -> RawFd {
505        self.this.inner.as_fd().as_raw_fd()
506    }
507}
508
509#[non_exhaustive]
510#[derive(Debug)]
511/// An error indicating that the inner socket cannot be accessed directly.
512pub enum AccessRawStreamError {
513    /// The TLS connection is fully closed (both read and write sides).
514    Closed,
515
516    /// There's still buffered data that has not been retrieved yet.
517    ///
518    /// The buffered data typically consists of:
519    ///
520    /// - Early data received during handshake.
521    /// - Application data received due to improper usage of
522    ///   [`StreamRefMutRaw::handle_io_error`].
523    HasBufferedData(Vec<u8>),
524}