Skip to main content

rustls/conn/
mod.rs

1use alloc::boxed::Box;
2use core::fmt::{self, Debug};
3use core::mem;
4use core::ops::{Deref, DerefMut, Range};
5#[cfg(feature = "std")]
6use std::io;
7
8use kernel::KernelConnection;
9
10#[cfg(feature = "std")]
11use crate::common_state::Input;
12use crate::common_state::{
13    CommonState, Context, DEFAULT_BUFFER_LIMIT, IoState, Output, State, process_main_protocol,
14};
15use crate::crypto::cipher::{Decrypted, EncodedMessage};
16use crate::enums::{ContentType, ProtocolVersion};
17use crate::error::{ApiMisuse, Error, PeerMisbehaved};
18#[cfg(feature = "std")]
19use crate::msgs::Message;
20use crate::msgs::{
21    BufferProgress, DeframerIter, DeframerVecBuffer, Delocator, HandshakeDeframer, Locator, Random,
22};
23use crate::suites::ExtractedSecrets;
24use crate::vecbuf::ChunkVecBuffer;
25
26// pub so that it can be re-exported from the crate root
27pub mod kernel;
28pub(crate) mod unbuffered;
29
30#[cfg(feature = "std")]
31mod connection {
32    use alloc::vec::Vec;
33    use core::fmt::Debug;
34    use core::ops::{Deref, DerefMut};
35    use std::io::{self, BufRead, Read};
36
37    use crate::common_state::{CommonState, IoState};
38    use crate::conn::{ConnectionCommon, KeyingMaterialExporter, SideData};
39    use crate::crypto::cipher::OutboundPlain;
40    use crate::error::Error;
41    use crate::suites::ExtractedSecrets;
42    use crate::vecbuf::ChunkVecBuffer;
43
44    /// A client or server connection.
45    #[expect(clippy::exhaustive_enums)]
46    #[derive(Debug)]
47    pub enum Connection {
48        /// A client connection
49        Client(crate::client::ClientConnection),
50        /// A server connection
51        Server(crate::server::ServerConnection),
52    }
53
54    impl Connection {
55        /// Read TLS content from `rd`.
56        ///
57        /// See [`ConnectionCommon::read_tls()`] for more information.
58        pub fn read_tls(&mut self, rd: &mut dyn Read) -> Result<usize, io::Error> {
59            match self {
60                Self::Client(conn) => conn.read_tls(rd),
61                Self::Server(conn) => conn.read_tls(rd),
62            }
63        }
64
65        /// Writes TLS messages to `wr`.
66        ///
67        /// See [`ConnectionCommon::write_tls()`] for more information.
68        pub fn write_tls(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error> {
69            self.sendable_tls.write_to(wr)
70        }
71
72        /// Returns an object that allows reading plaintext.
73        pub fn reader(&mut self) -> Reader<'_> {
74            match self {
75                Self::Client(conn) => conn.reader(),
76                Self::Server(conn) => conn.reader(),
77            }
78        }
79
80        /// Returns an object that allows writing plaintext.
81        pub fn writer(&mut self) -> Writer<'_> {
82            match self {
83                Self::Client(conn) => Writer::new(&mut **conn),
84                Self::Server(conn) => Writer::new(&mut **conn),
85            }
86        }
87
88        /// Processes any new packets read by a previous call to [`Connection::read_tls`].
89        ///
90        /// See [`ConnectionCommon::process_new_packets()`] for more information.
91        pub fn process_new_packets(&mut self) -> Result<IoState, Error> {
92            match self {
93                Self::Client(conn) => conn.process_new_packets(),
94                Self::Server(conn) => conn.process_new_packets(),
95            }
96        }
97
98        /// Returns an object that can derive key material from the agreed connection secrets.
99        ///
100        /// See [`ConnectionCommon::exporter()`] for more information.
101        pub fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
102            match self {
103                Self::Client(conn) => conn.exporter(),
104                Self::Server(conn) => conn.exporter(),
105            }
106        }
107
108        /// This function uses `io` to complete any outstanding IO for this connection.
109        ///
110        /// See [`ConnectionCommon::complete_io()`] for more information.
111        pub fn complete_io(
112            &mut self,
113            io: &mut (impl Read + io::Write),
114        ) -> Result<(usize, usize), io::Error> {
115            match self {
116                Self::Client(conn) => conn.complete_io(io),
117                Self::Server(conn) => conn.complete_io(io),
118            }
119        }
120
121        /// Extract secrets, so they can be used when configuring kTLS, for example.
122        /// Should be used with care as it exposes secret key material.
123        pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
124            match self {
125                Self::Client(client) => client.dangerous_extract_secrets(),
126                Self::Server(server) => server.dangerous_extract_secrets(),
127            }
128        }
129
130        /// Sets a limit on the internal buffers
131        ///
132        /// See [`ConnectionCommon::set_buffer_limit()`] for more information.
133        pub fn set_buffer_limit(&mut self, limit: Option<usize>) {
134            match self {
135                Self::Client(client) => client.set_buffer_limit(limit),
136                Self::Server(server) => server.set_buffer_limit(limit),
137            }
138        }
139
140        /// Sets a limit on the internal plaintext buffer.
141        ///
142        /// See [`ConnectionCommon::set_plaintext_buffer_limit()`] for more information.
143        pub fn set_plaintext_buffer_limit(&mut self, limit: Option<usize>) {
144            match self {
145                Self::Client(client) => client.set_plaintext_buffer_limit(limit),
146                Self::Server(server) => server.set_plaintext_buffer_limit(limit),
147            }
148        }
149
150        /// Sends a TLS1.3 `key_update` message to refresh a connection's keys
151        ///
152        /// See [`ConnectionCommon::refresh_traffic_keys()`] for more information.
153        pub fn refresh_traffic_keys(&mut self) -> Result<(), Error> {
154            match self {
155                Self::Client(client) => client.refresh_traffic_keys(),
156                Self::Server(server) => server.refresh_traffic_keys(),
157            }
158        }
159    }
160
161    impl Deref for Connection {
162        type Target = CommonState;
163
164        fn deref(&self) -> &Self::Target {
165            match self {
166                Self::Client(conn) => conn.core.side.deref(),
167                Self::Server(conn) => conn.core.side.deref(),
168            }
169        }
170    }
171
172    impl DerefMut for Connection {
173        fn deref_mut(&mut self) -> &mut Self::Target {
174            match self {
175                Self::Client(conn) => &mut conn.core.side,
176                Self::Server(conn) => &mut conn.core.side,
177            }
178        }
179    }
180
181    /// A structure that implements [`std::io::Read`] for reading plaintext.
182    pub struct Reader<'a> {
183        pub(super) received_plaintext: &'a mut ChunkVecBuffer,
184        pub(super) has_received_close_notify: bool,
185        pub(super) has_seen_eof: bool,
186    }
187
188    impl<'a> Reader<'a> {
189        /// Check the connection's state if no bytes are available for reading.
190        fn check_no_bytes_state(&self) -> io::Result<()> {
191            match (self.has_received_close_notify, self.has_seen_eof) {
192                // cleanly closed; don't care about TCP EOF: express this as Ok(0)
193                (true, _) => Ok(()),
194                // unclean closure
195                (false, true) => Err(io::Error::new(
196                    io::ErrorKind::UnexpectedEof,
197                    UNEXPECTED_EOF_MESSAGE,
198                )),
199                // connection still going, but needs more data: signal `WouldBlock` so that
200                // the caller knows this
201                (false, false) => Err(io::ErrorKind::WouldBlock.into()),
202            }
203        }
204
205        /// Obtain a chunk of plaintext data received from the peer over this TLS connection.
206        ///
207        /// This method consumes `self` so that it can return a slice whose lifetime is bounded by
208        /// the [`ConnectionCommon`] that created this `Reader`.
209        pub fn into_first_chunk(self) -> io::Result<&'a [u8]> {
210            match self.received_plaintext.chunk() {
211                Some(chunk) => Ok(chunk),
212                None => {
213                    self.check_no_bytes_state()?;
214                    Ok(&[])
215                }
216            }
217        }
218    }
219
220    impl Read for Reader<'_> {
221        /// Obtain plaintext data received from the peer over this TLS connection.
222        ///
223        /// If the peer closes the TLS session cleanly, this returns `Ok(0)`  once all
224        /// the pending data has been read. No further data can be received on that
225        /// connection, so the underlying TCP connection should be half-closed too.
226        ///
227        /// If the peer closes the TLS session uncleanly (a TCP EOF without sending a
228        /// `close_notify` alert) this function returns a `std::io::Error` of type
229        /// `ErrorKind::UnexpectedEof` once any pending data has been read.
230        ///
231        /// Note that support for `close_notify` varies in peer TLS libraries: many do not
232        /// support it and uncleanly close the TCP connection (this might be
233        /// vulnerable to truncation attacks depending on the application protocol).
234        /// This means applications using rustls must both handle EOF
235        /// from this function, *and* unexpected EOF of the underlying TCP connection.
236        ///
237        /// If there are no bytes to read, this returns `Err(ErrorKind::WouldBlock.into())`.
238        ///
239        /// You may learn the number of bytes available at any time by inspecting
240        /// the return of [`Connection::process_new_packets`].
241        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
242            let len = self.received_plaintext.read(buf)?;
243            if len > 0 || buf.is_empty() {
244                return Ok(len);
245            }
246
247            self.check_no_bytes_state()
248                .map(|()| len)
249        }
250    }
251
252    impl BufRead for Reader<'_> {
253        /// Obtain a chunk of plaintext data received from the peer over this TLS connection.
254        /// This reads the same data as [`Reader::read()`], but returns a reference instead of
255        /// copying the data.
256        ///
257        /// The caller should call [`Reader::consume()`] afterward to advance the buffer.
258        ///
259        /// See [`Reader::into_first_chunk()`] for a version of this function that returns a
260        /// buffer with a longer lifetime.
261        fn fill_buf(&mut self) -> io::Result<&[u8]> {
262            Reader {
263                // reborrow
264                received_plaintext: self.received_plaintext,
265                ..*self
266            }
267            .into_first_chunk()
268        }
269
270        fn consume(&mut self, amt: usize) {
271            self.received_plaintext
272                .consume_first_chunk(amt)
273        }
274    }
275
276    const UNEXPECTED_EOF_MESSAGE: &str = "peer closed connection without sending TLS close_notify: \
277https://docs.rs/rustls/latest/rustls/manual/_03_howto/index.html#unexpected-eof";
278
279    /// A structure that implements [`std::io::Write`] for writing plaintext.
280    pub struct Writer<'a> {
281        sink: &'a mut dyn PlaintextSink,
282    }
283
284    impl<'a> Writer<'a> {
285        /// Create a new Writer.
286        ///
287        /// This is not an external interface.  Get one of these objects
288        /// from [`Connection::writer`].
289        pub(crate) fn new(sink: &'a mut dyn PlaintextSink) -> Self {
290            Writer { sink }
291        }
292    }
293
294    impl io::Write for Writer<'_> {
295        /// Send the plaintext `buf` to the peer, encrypting
296        /// and authenticating it.  Once this function succeeds
297        /// you should call [`Connection::write_tls`] which will output the
298        /// corresponding TLS records.
299        ///
300        /// This function buffers plaintext sent before the
301        /// TLS handshake completes, and sends it as soon
302        /// as it can.  See [`ConnectionCommon::set_buffer_limit`] to control
303        /// the size of this buffer.
304        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
305            self.sink.write(buf)
306        }
307
308        fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
309            self.sink.write_vectored(bufs)
310        }
311
312        fn flush(&mut self) -> io::Result<()> {
313            self.sink.flush()
314        }
315    }
316
317    /// Internal trait implemented by the [`ServerConnection`]/[`ClientConnection`]
318    /// allowing them to be the subject of a [`Writer`].
319    ///
320    /// [`ServerConnection`]: crate::ServerConnection
321    /// [`ClientConnection`]: crate::ClientConnection
322    pub(crate) trait PlaintextSink {
323        fn write(&mut self, buf: &[u8]) -> io::Result<usize>;
324        fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize>;
325        fn flush(&mut self) -> io::Result<()>;
326    }
327
328    impl<Side: SideData> PlaintextSink for ConnectionCommon<Side> {
329        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
330            let len = self
331                .core
332                .side
333                .buffer_plaintext(buf.into(), &mut self.sendable_plaintext);
334            self.core.maybe_refresh_traffic_keys();
335            Ok(len)
336        }
337
338        fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
339            let payload_owner: Vec<&[u8]>;
340            let payload = match bufs.len() {
341                0 => return Ok(0),
342                1 => OutboundPlain::Single(bufs[0].deref()),
343                _ => {
344                    payload_owner = bufs
345                        .iter()
346                        .map(|io_slice| io_slice.deref())
347                        .collect();
348
349                    OutboundPlain::new(&payload_owner)
350                }
351            };
352            let len = self
353                .core
354                .side
355                .buffer_plaintext(payload, &mut self.sendable_plaintext);
356            self.core.maybe_refresh_traffic_keys();
357            Ok(len)
358        }
359
360        fn flush(&mut self) -> io::Result<()> {
361            Ok(())
362        }
363    }
364}
365
366#[cfg(feature = "std")]
367pub use connection::{Connection, Reader, Writer};
368
369/// An object of this type can export keying material.
370pub struct KeyingMaterialExporter {
371    pub(crate) inner: Box<dyn Exporter>,
372}
373
374impl KeyingMaterialExporter {
375    /// Derives key material from the agreed connection secrets.
376    ///
377    /// This function fills in `output` with `output.len()` bytes of key
378    /// material derived from a master connection secret using `label`
379    /// and `context` for diversification. Ownership of the buffer is taken
380    /// by the function and returned via the Ok result to ensure no key
381    /// material leaks if the function fails.
382    ///
383    /// See [RFC5705][] for more details on what this does and is for.  In
384    /// other libraries this is often named `SSL_export_keying_material()`
385    /// or `SslExportKeyingMaterial()`.
386    ///
387    /// This function is not meaningful if `output.len()` is zero and will
388    /// return an error in that case.
389    ///
390    /// [RFC5705]: https://datatracker.ietf.org/doc/html/rfc5705
391    pub fn derive<T: AsMut<[u8]>>(
392        &self,
393        label: &[u8],
394        context: Option<&[u8]>,
395        mut output: T,
396    ) -> Result<T, Error> {
397        if output.as_mut().is_empty() {
398            return Err(ApiMisuse::ExporterOutputZeroLength.into());
399        }
400
401        self.inner
402            .derive(label, context, output.as_mut())
403            .map(|_| output)
404    }
405}
406
407impl Debug for KeyingMaterialExporter {
408    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409        f.debug_struct("KeyingMaterialExporter")
410            .finish_non_exhaustive()
411    }
412}
413
414/// This trait is for any object that can export keying material.
415///
416/// The terminology comes from [RFC5705](https://datatracker.ietf.org/doc/html/rfc5705)
417/// but doesn't really involve "exporting" key material (in the usual meaning of "export"
418/// -- of moving an artifact from one domain to another) but is best thought of as key
419/// diversification using an existing secret.  That secret is implicit in this interface,
420/// so is assumed to be held by `self`. The secret should be zeroized in `drop()`.
421///
422/// There are several such internal implementations, depending on the context
423/// and protocol version.
424pub(crate) trait Exporter: Send + Sync {
425    /// Fills in `output` with derived keying material.
426    ///
427    /// This is deterministic depending on a base secret (implicit in `self`),
428    /// plus the `label` and `context` values.
429    ///
430    /// Must fill in `output` entirely, or return an error.
431    fn derive(&self, label: &[u8], context: Option<&[u8]>, output: &mut [u8]) -> Result<(), Error>;
432}
433
434#[derive(Debug)]
435pub(crate) struct ConnectionRandoms {
436    pub(crate) client: [u8; 32],
437    pub(crate) server: [u8; 32],
438}
439
440impl ConnectionRandoms {
441    pub(crate) fn new(client: Random, server: Random) -> Self {
442        Self {
443            client: client.0,
444            server: server.0,
445        }
446    }
447}
448
449/// TLS connection state with side-specific data (`Side`).
450///
451/// This is one of the core abstractions of the rustls API. It represents a single connection
452/// to a peer, and holds all the state associated with that connection. Note that it does
453/// not hold any IO objects: the application is responsible for reading and writing TLS records.
454/// If you want an object that does hold IO objects, see [`Stream`] and [`StreamOwned`].
455///
456/// This object is generic over the `Side` type parameter, which must implement the marker trait
457/// [`SideData`]. This is used to store side-specific data.
458///
459/// [`Stream`]: crate::Stream
460/// [`StreamOwned`]: crate::StreamOwned
461pub struct ConnectionCommon<Side: SideData> {
462    pub(crate) core: ConnectionCore<Side>,
463    deframer_buffer: DeframerVecBuffer,
464    pub(crate) sendable_plaintext: ChunkVecBuffer,
465}
466
467impl<Side: SideData> ConnectionCommon<Side> {
468    /// Processes any new packets read by a previous call to
469    /// [`Connection::read_tls`].
470    ///
471    /// Errors from this function relate to TLS protocol errors, and
472    /// are fatal to the connection.  Future calls after an error will do
473    /// no new work and will return the same error. After an error is
474    /// received from [`process_new_packets`], you should not call [`read_tls`]
475    /// any more (it will fill up buffers to no purpose). However, you
476    /// may call the other methods on the connection, including `write`,
477    /// `send_close_notify`, and `write_tls`. Most likely you will want to
478    /// call `write_tls` to send any alerts queued by the error and then
479    /// close the underlying connection.
480    ///
481    /// Success from this function comes with some sundry state data
482    /// about the connection.
483    ///
484    /// [`read_tls`]: Connection::read_tls
485    /// [`process_new_packets`]: Connection::process_new_packets
486    #[inline]
487    pub fn process_new_packets(&mut self) -> Result<IoState, Error> {
488        self.core
489            .process_new_packets(&mut self.deframer_buffer, &mut self.sendable_plaintext)
490    }
491
492    /// Returns an object that can derive key material from the agreed connection secrets.
493    ///
494    /// See [RFC5705][] for more details on what this is for.
495    ///
496    /// This function can be called at most once per connection.
497    ///
498    /// This function will error:
499    ///
500    /// - if called prior to the handshake completing; (check with
501    ///   [`CommonState::is_handshaking`] first).
502    /// - if called more than once per connection.
503    ///
504    /// [RFC5705]: https://datatracker.ietf.org/doc/html/rfc5705
505    pub fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
506        self.core.exporter()
507    }
508
509    /// Extract secrets, so they can be used when configuring kTLS, for example.
510    /// Should be used with care as it exposes secret key material.
511    pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
512        self.core.dangerous_extract_secrets()
513    }
514
515    /// Sets a limit on the internal buffers used to buffer
516    /// unsent plaintext (prior to completing the TLS handshake)
517    /// and unsent TLS records.  This limit acts only on application
518    /// data written through [`Connection::writer`].
519    ///
520    /// By default the limit is 64KB.  The limit can be set
521    /// at any time, even if the current buffer use is higher.
522    ///
523    /// [`None`] means no limit applies, and will mean that written
524    /// data is buffered without bound -- it is up to the application
525    /// to appropriately schedule its plaintext and TLS writes to bound
526    /// memory usage.
527    ///
528    /// For illustration: `Some(1)` means a limit of one byte applies:
529    /// [`Connection::writer`] will accept only one byte, encrypt it and
530    /// add a TLS header.  Once this is sent via [`Connection::write_tls`],
531    /// another byte may be sent.
532    ///
533    /// # Internal write-direction buffering
534    /// rustls has two buffers whose size are bounded by this setting:
535    ///
536    /// ## Buffering of unsent plaintext data prior to handshake completion
537    ///
538    /// Calls to [`Connection::writer`] before or during the handshake
539    /// are buffered (up to the limit specified here).  Once the
540    /// handshake completes this data is encrypted and the resulting
541    /// TLS records are added to the outgoing buffer.
542    ///
543    /// ## Buffering of outgoing TLS records
544    ///
545    /// This buffer is used to store TLS records that rustls needs to
546    /// send to the peer.  It is used in these two circumstances:
547    ///
548    /// - by [`Connection::process_new_packets`] when a handshake or alert
549    ///   TLS record needs to be sent.
550    /// - by [`Connection::writer`] post-handshake: the plaintext is
551    ///   encrypted and the resulting TLS record is buffered.
552    ///
553    /// This buffer is emptied by [`Connection::write_tls`].
554    ///
555    /// [`Connection::writer`]: crate::Connection::writer
556    /// [`Connection::write_tls`]: crate::Connection::write_tls
557    /// [`Connection::process_new_packets`]: crate::Connection::process_new_packets
558    pub fn set_buffer_limit(&mut self, limit: Option<usize>) {
559        self.sendable_plaintext.set_limit(limit);
560        self.sendable_tls.set_limit(limit);
561    }
562
563    /// Sets a limit on the internal buffers used to buffer decoded plaintext.
564    ///
565    /// See [`Self::set_buffer_limit`] for more information on how limits are applied.
566    pub fn set_plaintext_buffer_limit(&mut self, limit: Option<usize>) {
567        self.core
568            .side
569            .received_plaintext
570            .set_limit(limit);
571    }
572
573    /// Sends a TLS1.3 `key_update` message to refresh a connection's keys.
574    ///
575    /// This call refreshes our encryption keys. Once the peer receives the message,
576    /// it refreshes _its_ encryption and decryption keys and sends a response.
577    /// Once we receive that response, we refresh our decryption keys to match.
578    /// At the end of this process, keys in both directions have been refreshed.
579    ///
580    /// Note that this process does not happen synchronously: this call just
581    /// arranges that the `key_update` message will be included in the next
582    /// `write_tls` output.
583    ///
584    /// This fails with `Error::HandshakeNotComplete` if called before the initial
585    /// handshake is complete, or if a version prior to TLS1.3 is negotiated.
586    ///
587    /// # Usage advice
588    /// Note that other implementations (including rustls) may enforce limits on
589    /// the number of `key_update` messages allowed on a given connection to prevent
590    /// denial of service.  Therefore, this should be called sparingly.
591    ///
592    /// rustls implicitly and automatically refreshes traffic keys when needed
593    /// according to the selected cipher suite's cryptographic constraints.  There
594    /// is therefore no need to call this manually to avoid cryptographic keys
595    /// "wearing out".
596    ///
597    /// The main reason to call this manually is to roll keys when it is known
598    /// a connection will be idle for a long period.
599    pub fn refresh_traffic_keys(&mut self) -> Result<(), Error> {
600        self.core.refresh_traffic_keys()
601    }
602}
603
604#[cfg(feature = "std")]
605impl<Side: SideData> ConnectionCommon<Side> {
606    /// Returns an object that allows reading plaintext.
607    pub fn reader(&mut self) -> Reader<'_> {
608        let common = &mut self.core.side;
609        let has_seen_eof = common.has_seen_eof;
610        let has_received_close_notify = common.has_received_close_notify;
611        Reader {
612            received_plaintext: &mut common.received_plaintext,
613            // Are we done? i.e., have we processed all received messages, and received a
614            // close_notify to indicate that no new messages will arrive?
615            has_received_close_notify,
616            has_seen_eof,
617        }
618    }
619
620    /// Returns an object that allows writing plaintext.
621    pub fn writer(&mut self) -> Writer<'_> {
622        Writer::new(self)
623    }
624
625    /// This function uses `io` to complete any outstanding IO for
626    /// this connection.
627    ///
628    /// This is a convenience function which solely uses other parts
629    /// of the public API.
630    ///
631    /// What this means depends on the connection  state:
632    ///
633    /// - If the connection [`is_handshaking`], then IO is performed until
634    ///   the handshake is complete.
635    /// - Otherwise, if [`wants_write`] is true, [`write_tls`] is invoked
636    ///   until it is all written.
637    /// - Otherwise, if [`wants_read`] is true, [`read_tls`] is invoked
638    ///   once.
639    ///
640    /// The return value is the number of bytes read from and written
641    /// to `io`, respectively. Once both `read()` and `write()` yield `WouldBlock`,
642    /// this function will propagate the error.
643    ///
644    /// Errors from TLS record handling (i.e., from [`process_new_packets`])
645    /// are wrapped in an `io::ErrorKind::InvalidData`-kind error.
646    ///
647    /// [`is_handshaking`]: CommonState::is_handshaking
648    /// [`wants_read`]: CommonState::wants_read
649    /// [`wants_write`]: CommonState::wants_write
650    /// [`write_tls`]: ConnectionCommon::write_tls
651    /// [`read_tls`]: ConnectionCommon::read_tls
652    /// [`process_new_packets`]: ConnectionCommon::process_new_packets
653    pub fn complete_io(
654        &mut self,
655        io: &mut (impl io::Read + io::Write),
656    ) -> Result<(usize, usize), io::Error> {
657        let mut eof = false;
658        let mut wrlen = 0;
659        let mut rdlen = 0;
660        loop {
661            let (mut blocked_write, mut blocked_read) = (None, None);
662            let until_handshaked = self.is_handshaking();
663
664            if !self.wants_write() && !self.wants_read() {
665                // We will make no further progress.
666                return Ok((rdlen, wrlen));
667            }
668
669            while self.wants_write() {
670                match self.write_tls(io) {
671                    Ok(0) => {
672                        io.flush()?;
673                        return Ok((rdlen, wrlen)); // EOF.
674                    }
675                    Ok(n) => wrlen += n,
676                    Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
677                        blocked_write = Some(err);
678                        break;
679                    }
680                    Err(err) => return Err(err),
681                }
682            }
683            if wrlen > 0 {
684                io.flush()?;
685            }
686
687            if !until_handshaked && wrlen > 0 {
688                return Ok((rdlen, wrlen));
689            }
690
691            // If we want to write, but are WouldBlocked by the underlying IO, *and*
692            // have no desire to read; that is everything.
693            if let (Some(_), false) = (&blocked_write, self.wants_read()) {
694                return match wrlen {
695                    0 => Err(blocked_write.unwrap()),
696                    _ => Ok((rdlen, wrlen)),
697                };
698            }
699
700            while !eof && self.wants_read() {
701                let read_size = match self.read_tls(io) {
702                    Ok(0) => {
703                        eof = true;
704                        Some(0)
705                    }
706                    Ok(n) => {
707                        rdlen += n;
708                        Some(n)
709                    }
710                    Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
711                        blocked_read = Some(err);
712                        break;
713                    }
714                    Err(err) if err.kind() == io::ErrorKind::Interrupted => None, // nothing to do
715                    Err(err) => return Err(err),
716                };
717                if read_size.is_some() {
718                    break;
719                }
720            }
721
722            if let Err(e) = self.process_new_packets() {
723                // In case we have an alert to send describing this error, try a last-gasp
724                // write -- but don't predate the primary error.
725                let _ignored = self.write_tls(io);
726                let _ignored = io.flush();
727                return Err(io::Error::new(io::ErrorKind::InvalidData, e));
728            };
729
730            // If we want to read, but are WouldBlocked by the underlying IO, *and*
731            // have no desire to write; that is everything.
732            if let (Some(_), false) = (&blocked_read, self.wants_write()) {
733                return match rdlen {
734                    0 => Err(blocked_read.unwrap()),
735                    _ => Ok((rdlen, wrlen)),
736                };
737            }
738
739            // if we're doing IO until handshaked, and we believe we've finished handshaking,
740            // but process_new_packets() has queued TLS data to send, loop around again to write
741            // the queued messages.
742            if until_handshaked && !self.is_handshaking() && self.wants_write() {
743                continue;
744            }
745
746            let blocked = blocked_write.zip(blocked_read);
747            match (eof, until_handshaked, self.is_handshaking(), blocked) {
748                (_, true, false, _) => return Ok((rdlen, wrlen)),
749                (_, _, _, Some((e, _))) if rdlen == 0 && wrlen == 0 => return Err(e),
750                (_, false, _, _) => return Ok((rdlen, wrlen)),
751                (true, true, true, _) => return Err(io::Error::from(io::ErrorKind::UnexpectedEof)),
752                _ => {}
753            }
754        }
755    }
756
757    /// Extract the first handshake message.
758    ///
759    /// This is a shortcut to the `process_new_packets()` -> `process_msg()` ->
760    /// `process_handshake_messages()` path, specialized for the first handshake message.
761    pub(crate) fn first_handshake_message(&mut self) -> Result<Option<Input<'static>>, Error> {
762        let mut buffer_progress = self.core.hs_deframer.progress();
763
764        let res = self
765            .core
766            .deframe(self.deframer_buffer.filled_mut(), &mut buffer_progress)
767            .map(|opt| opt.map(|pm| Message::try_from(&pm).map(|m| m.into_owned())));
768
769        match res? {
770            Some(Ok(msg)) => {
771                self.deframer_buffer
772                    .discard(buffer_progress.take_discard());
773                Ok(Some(Input {
774                    message: msg,
775                    aligned_handshake: self.core.hs_deframer.aligned(),
776                }))
777            }
778            Some(Err(err)) => Err(err.into()),
779            None => Ok(None),
780        }
781    }
782
783    pub(crate) fn replace_state(&mut self, new: Box<dyn State<Side>>) {
784        self.core.state = Ok(new);
785    }
786
787    /// Read TLS content from `rd` into the internal buffer.
788    ///
789    /// Due to the internal buffering, `rd` can supply TLS messages in arbitrary-sized chunks (like
790    /// a socket or pipe might).
791    ///
792    /// You should call [`process_new_packets()`] each time a call to this function succeeds in order
793    /// to empty the incoming TLS data buffer.
794    ///
795    /// This function returns `Ok(0)` when the underlying `rd` does so. This typically happens when
796    /// a socket is cleanly closed, or a file is at EOF. Errors may result from the IO done through
797    /// `rd`; additionally, errors of `ErrorKind::Other` are emitted to signal backpressure:
798    ///
799    /// * In order to empty the incoming TLS data buffer, you should call [`process_new_packets()`]
800    ///   each time a call to this function succeeds.
801    /// * In order to empty the incoming plaintext data buffer, you should empty it through
802    ///   the [`reader()`] after the call to [`process_new_packets()`].
803    ///
804    /// This function also returns `Ok(0)` once a `close_notify` alert has been successfully
805    /// received.  No additional data is ever read in this state.
806    ///
807    /// [`process_new_packets()`]: ConnectionCommon::process_new_packets
808    /// [`reader()`]: ConnectionCommon::reader
809    pub fn read_tls(&mut self, rd: &mut dyn io::Read) -> Result<usize, io::Error> {
810        if self.received_plaintext.is_full() {
811            return Err(io::Error::other("received plaintext buffer full"));
812        }
813
814        if self.has_received_close_notify {
815            return Ok(0);
816        }
817
818        let res = self
819            .deframer_buffer
820            .read(rd, self.core.hs_deframer.is_active());
821        if let Ok(0) = res {
822            self.has_seen_eof = true;
823        }
824        res
825    }
826
827    /// Writes TLS messages to `wr`.
828    ///
829    /// On success, this function returns `Ok(n)` where `n` is a number of bytes written to `wr`
830    /// (after encoding and encryption).
831    ///
832    /// After this function returns, the connection buffer may not yet be fully flushed. The
833    /// [`CommonState::wants_write`] function can be used to check if the output buffer is empty.
834    pub fn write_tls(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error> {
835        self.sendable_tls.write_to(wr)
836    }
837}
838
839impl<Side: SideData> Deref for ConnectionCommon<Side> {
840    type Target = CommonState;
841
842    fn deref(&self) -> &Self::Target {
843        &self.core.side
844    }
845}
846
847impl<Side: SideData> DerefMut for ConnectionCommon<Side> {
848    fn deref_mut(&mut self) -> &mut Self::Target {
849        &mut self.core.side
850    }
851}
852
853impl<Side: SideData> From<ConnectionCore<Side>> for ConnectionCommon<Side> {
854    fn from(core: ConnectionCore<Side>) -> Self {
855        Self {
856            core,
857            deframer_buffer: DeframerVecBuffer::default(),
858            sendable_plaintext: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
859        }
860    }
861}
862
863/// Interface shared by unbuffered client and server connections.
864pub struct UnbufferedConnectionCommon<Side: SideData> {
865    pub(crate) core: ConnectionCore<Side>,
866    wants_write: bool,
867    emitted_peer_closed_state: bool,
868}
869
870impl<Side: SideData> From<ConnectionCore<Side>> for UnbufferedConnectionCommon<Side> {
871    fn from(core: ConnectionCore<Side>) -> Self {
872        Self {
873            core,
874            wants_write: false,
875            emitted_peer_closed_state: false,
876        }
877    }
878}
879
880impl<Side: SideData> UnbufferedConnectionCommon<Side> {
881    /// Extract secrets, so they can be used when configuring kTLS, for example.
882    /// Should be used with care as it exposes secret key material.
883    pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
884        self.core.dangerous_extract_secrets()
885    }
886}
887
888impl<Side: SideData> Deref for UnbufferedConnectionCommon<Side> {
889    type Target = CommonState;
890
891    fn deref(&self) -> &Self::Target {
892        &self.core.side
893    }
894}
895
896pub(crate) struct ConnectionCore<Side: SideData> {
897    pub(crate) state: Result<Box<dyn State<Side>>, Error>,
898    pub(crate) side: Side,
899    pub(crate) hs_deframer: HandshakeDeframer,
900
901    /// We limit consecutive empty fragments to avoid a route for the peer to send
902    /// us significant but fruitless traffic.
903    seen_consecutive_empty_fragments: u8,
904}
905
906impl<Side: SideData> ConnectionCore<Side> {
907    pub(crate) fn new(state: Box<dyn State<Side>>, side: Side) -> Self {
908        Self {
909            state: Ok(state),
910            side,
911            hs_deframer: HandshakeDeframer::default(),
912            seen_consecutive_empty_fragments: 0,
913        }
914    }
915
916    pub(crate) fn process_new_packets(
917        &mut self,
918        deframer_buffer: &mut DeframerVecBuffer,
919        sendable_plaintext: &mut ChunkVecBuffer,
920    ) -> Result<IoState, Error> {
921        let mut state = match mem::replace(&mut self.state, Err(Error::HandshakeNotComplete)) {
922            Ok(state) => state,
923            Err(e) => {
924                self.state = Err(e.clone());
925                return Err(e);
926            }
927        };
928
929        // Should `EncodedMessage<Payload>` resolve to plaintext application
930        // data it will be allocated within `plaintext` and written to
931        // `CommonState.received_plaintext` buffer.
932        //
933        // TODO `CommonState.received_plaintext` should be hoisted into
934        // `ConnectionCommon`
935        let mut plaintext = None;
936        let mut buffer_progress = self.hs_deframer.progress();
937
938        loop {
939            let buffer = deframer_buffer.filled_mut();
940            let locator = Locator::new(buffer);
941            let res = self.deframe(buffer, &mut buffer_progress);
942
943            let opt_msg = match res {
944                Ok(opt_msg) => opt_msg,
945                Err(e) => {
946                    self.side.maybe_send_fatal_alert(&e);
947                    if let Error::DecryptError = e {
948                        state.handle_decrypt_error();
949                    }
950                    self.state = Err(e.clone());
951                    deframer_buffer.discard(buffer_progress.take_discard());
952                    return Err(e);
953                }
954            };
955
956            let Some(msg) = opt_msg else {
957                break;
958            };
959
960            match process_main_protocol(
961                msg,
962                self.hs_deframer.aligned(),
963                state,
964                &locator,
965                &mut plaintext,
966                &mut self.side,
967            ) {
968                Ok(new) => state = new,
969                Err(e) => {
970                    self.side.maybe_send_fatal_alert(&e);
971                    self.state = Err(e.clone());
972                    deframer_buffer.discard(buffer_progress.take_discard());
973                    return Err(e);
974                }
975            }
976
977            if self.side.may_send_application_data && !sendable_plaintext.is_empty() {
978                self.side
979                    .send_buffered_plaintext(sendable_plaintext);
980            }
981
982            if self.side.has_received_close_notify {
983                // "Any data received after a closure alert has been received MUST be ignored."
984                // -- <https://datatracker.ietf.org/doc/html/rfc8446#section-6.1>
985                // This is data that has already been accepted in `read_tls`.
986                buffer_progress.add_discard(deframer_buffer.filled().len());
987                break;
988            }
989
990            if let Some(payload) = plaintext.take() {
991                let payload = payload.reborrow(&Delocator::new(buffer));
992                self.side
993                    .received_plaintext
994                    .append(payload.into_vec());
995            }
996
997            deframer_buffer.discard(buffer_progress.take_discard());
998        }
999
1000        deframer_buffer.discard(buffer_progress.take_discard());
1001        self.state = Ok(state);
1002        Ok(self.side.current_io_state())
1003    }
1004
1005    /// Pull a message out of the deframer and send any messages that need to be sent as a result.
1006    fn deframe<'b>(
1007        &mut self,
1008        buffer: &'b mut [u8],
1009        buffer_progress: &mut BufferProgress,
1010    ) -> Result<Option<EncodedMessage<&'b [u8]>>, Error> {
1011        // before processing any more of `buffer`, return any extant messages from `hs_deframer`
1012        if self.hs_deframer.has_message_ready() {
1013            Ok(self.take_handshake_message(buffer, buffer_progress))
1014        } else {
1015            self.process_more_input(buffer, buffer_progress)
1016        }
1017    }
1018
1019    fn take_handshake_message<'b>(
1020        &mut self,
1021        buffer: &'b [u8],
1022        buffer_progress: &mut BufferProgress,
1023    ) -> Option<EncodedMessage<&'b [u8]>> {
1024        self.hs_deframer
1025            .iter(buffer)
1026            .next()
1027            .map(|(message, discard)| {
1028                buffer_progress.add_discard(discard);
1029                message
1030            })
1031    }
1032
1033    fn process_more_input<'b>(
1034        &mut self,
1035        buffer: &'b mut [u8],
1036        buffer_progress: &mut BufferProgress,
1037    ) -> Result<Option<EncodedMessage<&'b [u8]>>, Error> {
1038        let version_is_tls13 =
1039            matches!(self.side.negotiated_version, Some(ProtocolVersion::TLSv1_3));
1040
1041        let locator = Locator::new(buffer);
1042
1043        loop {
1044            let mut iter = DeframerIter::new(&mut buffer[buffer_progress.processed()..]);
1045
1046            let (message, processed) = loop {
1047                let message = match iter.next().transpose() {
1048                    Ok(Some(message)) => message,
1049                    Ok(None) => return Ok(None),
1050                    Err(err) => return Err(err),
1051                };
1052
1053                let allowed_plaintext = match message.typ {
1054                    // CCS messages are always plaintext.
1055                    ContentType::ChangeCipherSpec => true,
1056                    // Alerts are allowed to be plaintext if-and-only-if:
1057                    // * The negotiated protocol version is TLS 1.3. - In TLS 1.2 it is unambiguous when
1058                    //   keying changes based on the CCS message. Only TLS 1.3 requires these heuristics.
1059                    // * We have not yet decrypted any messages from the peer - if we have we don't
1060                    //   expect any plaintext.
1061                    // * The payload size is indicative of a plaintext alert message.
1062                    ContentType::Alert
1063                        if version_is_tls13
1064                            && !self.side.decrypt_state.has_decrypted()
1065                            && message.payload.len() <= 2 =>
1066                    {
1067                        true
1068                    }
1069                    // In other circumstances, we expect all messages to be encrypted.
1070                    _ => false,
1071                };
1072
1073                if allowed_plaintext && !self.hs_deframer.is_active() {
1074                    break (message.into_plain_message(), iter.bytes_consumed());
1075                }
1076
1077                let message = match self
1078                    .side
1079                    .decrypt_state
1080                    .decrypt_incoming(message)
1081                {
1082                    // failed decryption during trial decryption is not allowed to be
1083                    // interleaved with partial handshake data.
1084                    Ok(None) if self.hs_deframer.aligned().is_none() => {
1085                        return Err(
1086                            PeerMisbehaved::RejectedEarlyDataInterleavedWithHandshakeMessage.into(),
1087                        );
1088                    }
1089
1090                    // failed decryption during trial decryption.
1091                    Ok(None) => continue,
1092
1093                    Ok(Some(message)) => message,
1094
1095                    Err(err) => return Err(err),
1096                };
1097
1098                let Decrypted {
1099                    want_close_before_decrypt,
1100                    plaintext,
1101                } = message;
1102
1103                if want_close_before_decrypt {
1104                    self.side.send_close_notify();
1105                }
1106
1107                break (plaintext, iter.bytes_consumed());
1108            };
1109
1110            if self.hs_deframer.aligned().is_none() && message.typ != ContentType::Handshake {
1111                // "Handshake messages MUST NOT be interleaved with other record
1112                // types.  That is, if a handshake message is split over two or more
1113                // records, there MUST NOT be any other records between them."
1114                // https://www.rfc-editor.org/rfc/rfc8446#section-5.1
1115                return Err(PeerMisbehaved::MessageInterleavedWithHandshakeMessage.into());
1116            }
1117
1118            match message.payload.len() {
1119                0 => {
1120                    if self.seen_consecutive_empty_fragments
1121                        == ALLOWED_CONSECUTIVE_EMPTY_FRAGMENTS_MAX
1122                    {
1123                        return Err(PeerMisbehaved::TooManyEmptyFragments.into());
1124                    }
1125                    self.seen_consecutive_empty_fragments += 1;
1126                }
1127                _ => {
1128                    self.seen_consecutive_empty_fragments = 0;
1129                }
1130            };
1131
1132            buffer_progress.add_processed(processed);
1133
1134            // do an end-run around the borrow checker, converting `message` (containing
1135            // a borrowed slice) to an unborrowed one (containing a `Range` into the
1136            // same buffer).  the reborrow happens inside the branch that returns the
1137            // message.
1138            //
1139            // is fixed by -Zpolonius
1140            // https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md#problem-case-3-conditional-control-flow-across-functions
1141            let unborrowed = InboundUnborrowedMessage::unborrow(&locator, message);
1142
1143            if unborrowed.typ != ContentType::Handshake {
1144                let message = unborrowed.reborrow(&Delocator::new(buffer));
1145                buffer_progress.add_discard(processed);
1146                return Ok(Some(message));
1147            }
1148
1149            let message = unborrowed.reborrow(&Delocator::new(buffer));
1150            self.hs_deframer
1151                .input_message(message, &locator, buffer_progress.processed());
1152            self.hs_deframer.coalesce(buffer)?;
1153
1154            if self.hs_deframer.has_message_ready() {
1155                // trial decryption finishes with the first handshake message after it started.
1156                self.side
1157                    .decrypt_state
1158                    .finish_trial_decryption();
1159
1160                return Ok(self.take_handshake_message(buffer, buffer_progress));
1161            }
1162        }
1163    }
1164
1165    pub(crate) fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
1166        Ok(self
1167            .dangerous_into_kernel_connection()?
1168            .0)
1169    }
1170
1171    pub(crate) fn dangerous_into_kernel_connection(
1172        self,
1173    ) -> Result<(ExtractedSecrets, KernelConnection<Side>), Error> {
1174        let common = self.side.into_common();
1175
1176        if common.is_handshaking() {
1177            return Err(Error::HandshakeNotComplete);
1178        }
1179
1180        if !common.sendable_tls.is_empty() {
1181            return Err(ApiMisuse::SecretExtractionWithPendingSendableData.into());
1182        }
1183
1184        let state = self.state?;
1185
1186        let read_seq = common.decrypt_state.read_seq();
1187        let write_seq = common.encrypt_state.write_seq();
1188
1189        let (secrets, state) = state.into_external_state()?;
1190        let secrets = ExtractedSecrets {
1191            tx: (write_seq, secrets.tx),
1192            rx: (read_seq, secrets.rx),
1193        };
1194        let external = KernelConnection::new(state, common)?;
1195
1196        Ok((secrets, external))
1197    }
1198
1199    pub(crate) fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
1200        match self.side.exporter.take() {
1201            Some(inner) => Ok(KeyingMaterialExporter { inner }),
1202            None if self.side.is_handshaking() => Err(Error::HandshakeNotComplete),
1203            None => Err(ApiMisuse::ExporterAlreadyUsed.into()),
1204        }
1205    }
1206
1207    #[cfg(feature = "std")]
1208    pub(crate) fn early_exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
1209        match self.side.early_exporter.take() {
1210            Some(inner) => Ok(KeyingMaterialExporter { inner }),
1211            None => Err(ApiMisuse::ExporterAlreadyUsed.into()),
1212        }
1213    }
1214
1215    /// Trigger a `refresh_traffic_keys` if required by `CommonState`.
1216    fn maybe_refresh_traffic_keys(&mut self) {
1217        if mem::take(&mut self.side.refresh_traffic_keys_pending) {
1218            let _ = self.refresh_traffic_keys();
1219        }
1220    }
1221
1222    fn refresh_traffic_keys(&mut self) -> Result<(), Error> {
1223        match &mut self.state {
1224            Ok(st) => st.send_key_update_request(&mut Context {
1225                data: &mut self.side,
1226                plaintext_locator: &Locator::new(&[]),
1227                received_plaintext: &mut None,
1228            }),
1229            Err(e) => Err(e.clone()),
1230        }
1231    }
1232}
1233
1234/// Data specific to the peer's side (client or server).
1235#[expect(private_bounds)]
1236pub trait SideData: private::SideData {}
1237
1238pub(crate) mod private {
1239    use super::*;
1240
1241    pub(crate) trait SideData:
1242        Output + Debug + Deref<Target = CommonState> + DerefMut
1243    {
1244        fn into_common(self) -> CommonState;
1245    }
1246}
1247
1248/// An [`EncodedMessage<Payload<'_>>`] which does not borrow its payload, but
1249/// references a range that can later be borrowed.
1250struct InboundUnborrowedMessage {
1251    typ: ContentType,
1252    version: ProtocolVersion,
1253    bounds: Range<usize>,
1254}
1255
1256impl InboundUnborrowedMessage {
1257    fn unborrow(locator: &Locator, msg: EncodedMessage<&'_ [u8]>) -> Self {
1258        Self {
1259            typ: msg.typ,
1260            version: msg.version,
1261            bounds: locator.locate(msg.payload),
1262        }
1263    }
1264
1265    fn reborrow<'b>(self, delocator: &Delocator<'b>) -> EncodedMessage<&'b [u8]> {
1266        EncodedMessage {
1267            typ: self.typ,
1268            version: self.version,
1269            payload: delocator.slice_from_range(&self.bounds),
1270        }
1271    }
1272}
1273
1274/// cf. BoringSSL's `kMaxEmptyRecords`
1275/// <https://github.com/google/boringssl/blob/dec5989b793c56ad4dd32173bd2d8595ca78b398/ssl/tls_record.cc#L124-L128>
1276const ALLOWED_CONSECUTIVE_EMPTY_FRAGMENTS_MAX: u8 = 32;