Skip to main content

rustls/server/
connection.rs

1#[cfg(feature = "std")]
2use alloc::borrow::Cow;
3use alloc::boxed::Box;
4use alloc::vec::Vec;
5use core::fmt;
6use core::fmt::{Debug, Formatter};
7use core::ops::{Deref, DerefMut};
8#[cfg(feature = "std")]
9use std::io;
10
11use pki_types::DnsName;
12
13#[cfg(feature = "std")]
14use super::config::ClientHello;
15use super::config::ServerConfig;
16use super::hs;
17#[cfg(feature = "std")]
18use super::hs::ClientHelloInput;
19use crate::common_state::{CommonState, EarlyDataEvent, Event, Output, Protocol, Side};
20#[cfg(feature = "std")]
21use crate::common_state::{Input, State};
22#[cfg(feature = "std")]
23use crate::conn::ConnectionCommon;
24use crate::conn::{ConnectionCore, UnbufferedConnectionCommon};
25#[cfg(doc)]
26use crate::crypto;
27#[cfg(feature = "std")]
28use crate::crypto::SignatureScheme;
29use crate::crypto::cipher::Payload;
30use crate::error::Error;
31use crate::kernel::KernelConnection;
32#[cfg(feature = "std")]
33use crate::log::trace;
34use crate::msgs::ServerExtensionsInput;
35#[cfg(feature = "std")]
36use crate::msgs::{
37    ClientHelloPayload, HandshakePayload, Message, MessagePayload, ServerNamePayload,
38};
39use crate::suites::ExtractedSecrets;
40use crate::sync::Arc;
41use crate::vecbuf::ChunkVecBuffer;
42
43#[cfg(feature = "std")]
44mod buffered {
45    use alloc::boxed::Box;
46    use core::fmt;
47    use core::fmt::{Debug, Formatter};
48    use core::ops::{Deref, DerefMut};
49    use std::io;
50
51    use pki_types::DnsName;
52
53    use super::{
54        Accepted, Accepting, Protocol, ServerConfig, ServerConnectionData, ServerExtensionsInput,
55    };
56    use crate::KeyingMaterialExporter;
57    use crate::common_state::{CommonState, Side};
58    use crate::conn::private::SideData;
59    use crate::conn::{ConnectionCommon, ConnectionCore};
60    use crate::error::{ApiMisuse, Error};
61    use crate::server::hs::ClientHelloInput;
62    use crate::suites::ExtractedSecrets;
63    use crate::sync::Arc;
64    use crate::vecbuf::ChunkVecBuffer;
65
66    /// This represents a single TLS server connection.
67    ///
68    /// Send TLS-protected data to the peer using the `io::Write` trait implementation.
69    /// Read data from the peer using the `io::Read` trait implementation.
70    pub struct ServerConnection {
71        pub(super) inner: ConnectionCommon<ServerConnectionData>,
72    }
73
74    impl ServerConnection {
75        /// Make a new ServerConnection.  `config` controls how
76        /// we behave in the TLS protocol.
77        pub fn new(config: Arc<ServerConfig>) -> Result<Self, Error> {
78            Ok(Self {
79                inner: ConnectionCommon::from(ConnectionCore::for_server(
80                    config,
81                    ServerExtensionsInput::default(),
82                    Protocol::Tcp,
83                )?),
84            })
85        }
86
87        /// Retrieves the server name, if any, used to select the certificate and
88        /// private key.
89        ///
90        /// This returns `None` until some time after the client's server name indication
91        /// (SNI) extension value is processed during the handshake. It will never be
92        /// `None` when the connection is ready to send or process application data,
93        /// unless the client does not support SNI.
94        ///
95        /// This is useful for application protocols that need to enforce that the
96        /// server name matches an application layer protocol hostname. For
97        /// example, HTTP/1.1 servers commonly expect the `Host:` header field of
98        /// every request on a connection to match the hostname in the SNI extension
99        /// when the client provides the SNI extension.
100        ///
101        /// The server name is also used to match sessions during session resumption.
102        pub fn server_name(&self) -> Option<&DnsName<'_>> {
103            self.inner.core.side.server_name()
104        }
105
106        /// Application-controlled portion of the resumption ticket supplied by the client, if any.
107        ///
108        /// Recovered from the prior session's `set_resumption_data`. Integrity is guaranteed by rustls.
109        ///
110        /// Returns `Some` if and only if a valid resumption ticket has been received from the client.
111        pub fn received_resumption_data(&self) -> Option<&[u8]> {
112            self.inner
113                .core
114                .side
115                .received_resumption_data()
116        }
117
118        /// Set the resumption data to embed in future resumption tickets supplied to the client.
119        ///
120        /// Defaults to the empty byte string. Must be less than 2^15 bytes to allow room for other
121        /// data. Should be called while `is_handshaking` returns true to ensure all transmitted
122        /// resumption tickets are affected.
123        ///
124        /// Integrity will be assured by rustls, but the data will be visible to the client. If secrecy
125        /// from the client is desired, encrypt the data separately.
126        pub fn set_resumption_data(&mut self, data: &[u8]) -> Result<(), Error> {
127            assert!(data.len() < 2usize.pow(15));
128            match &mut self.core.state {
129                Ok(st) => st.set_resumption_data(data),
130                Err(e) => Err(e.clone()),
131            }
132        }
133
134        /// Returns an `io::Read` implementer you can read bytes from that are
135        /// received from a client as TLS1.3 0RTT/"early" data, during the handshake.
136        ///
137        /// This returns `None` in many circumstances, such as :
138        ///
139        /// - Early data is disabled if [`ServerConfig::max_early_data_size`] is zero (the default).
140        /// - The session negotiated with the client is not TLS1.3.
141        /// - The client just doesn't support early data.
142        /// - The connection doesn't resume an existing session.
143        /// - The client hasn't sent a full ClientHello yet.
144        pub fn early_data(&mut self) -> Option<ReadEarlyData<'_>> {
145            if self
146                .inner
147                .core
148                .side
149                .early_data
150                .was_accepted()
151            {
152                Some(ReadEarlyData::new(&mut self.inner))
153            } else {
154                None
155            }
156        }
157
158        /// Extract secrets, so they can be used when configuring kTLS, for example.
159        /// Should be used with care as it exposes secret key material.
160        pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
161            self.inner.dangerous_extract_secrets()
162        }
163    }
164
165    impl Debug for ServerConnection {
166        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
167            f.debug_struct("ServerConnection")
168                .finish_non_exhaustive()
169        }
170    }
171
172    impl Deref for ServerConnection {
173        type Target = ConnectionCommon<ServerConnectionData>;
174
175        fn deref(&self) -> &Self::Target {
176            &self.inner
177        }
178    }
179
180    impl DerefMut for ServerConnection {
181        fn deref_mut(&mut self) -> &mut Self::Target {
182            &mut self.inner
183        }
184    }
185
186    impl From<ServerConnection> for crate::Connection {
187        fn from(conn: ServerConnection) -> Self {
188            Self::Server(conn)
189        }
190    }
191
192    /// Handle a server-side connection before configuration is available.
193    ///
194    /// `Acceptor` allows the caller to choose a [`ServerConfig`] after reading
195    /// the [`ClientHello`][super::ClientHello] of an incoming connection. This is useful for
196    /// servers that choose different certificates or cipher suites based on the
197    /// characteristics of the `ClientHello`. In particular it is useful for
198    /// servers that need to do some I/O to load a certificate and its private key
199    /// and don't want to use the blocking interface provided by
200    /// [`ServerCredentialResolver`][crate::server::ServerCredentialResolver].
201    ///
202    /// Create an Acceptor with [`Acceptor::default()`].
203    ///
204    /// # Example
205    ///
206    /// ```no_run
207    /// # #[cfg(feature = "aws-lc-rs")] {
208    /// # fn choose_server_config(
209    /// #     _: rustls::server::ClientHello,
210    /// # ) -> std::sync::Arc<rustls::ServerConfig> {
211    /// #     unimplemented!();
212    /// # }
213    /// # #[allow(unused_variables)]
214    /// # fn main() {
215    /// use rustls::server::{Acceptor, ServerConfig};
216    /// let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
217    /// for stream in listener.incoming() {
218    ///     let mut stream = stream.unwrap();
219    ///     let mut acceptor = Acceptor::default();
220    ///     let accepted = loop {
221    ///         acceptor.read_tls(&mut stream).unwrap();
222    ///         if let Some(accepted) = acceptor.accept().unwrap() {
223    ///             break accepted;
224    ///         }
225    ///     };
226    ///
227    ///     // For some user-defined choose_server_config:
228    ///     let config = choose_server_config(accepted.client_hello());
229    ///     let conn = accepted
230    ///         .into_connection(config)
231    ///         .unwrap();
232    ///
233    ///     // Proceed with handling the ServerConnection.
234    /// }
235    /// # }
236    /// # }
237    /// ```
238    pub struct Acceptor {
239        inner: Option<ConnectionCommon<ServerConnectionData>>,
240    }
241
242    impl Default for Acceptor {
243        /// Return an empty Acceptor, ready to receive bytes from a new client connection.
244        fn default() -> Self {
245            Self {
246                inner: Some(
247                    ConnectionCore::new(
248                        Box::new(Accepting),
249                        ServerConnectionData::new(CommonState::new(Side::Server, Protocol::Tcp)),
250                    )
251                    .into(),
252                ),
253            }
254        }
255    }
256
257    impl Acceptor {
258        /// Read TLS content from `rd`.
259        ///
260        /// Returns an error if this `Acceptor` has already yielded an [`Accepted`]. For more details,
261        /// refer to [`Connection::read_tls()`].
262        ///
263        /// [`Connection::read_tls()`]: crate::Connection::read_tls
264        pub fn read_tls(&mut self, rd: &mut dyn io::Read) -> Result<usize, io::Error> {
265            match &mut self.inner {
266                Some(conn) => conn.read_tls(rd),
267                None => Err(io::Error::other(
268                    "acceptor cannot read after successful acceptance",
269                )),
270            }
271        }
272
273        /// Check if a `ClientHello` message has been received.
274        ///
275        /// Returns `Ok(None)` if the complete `ClientHello` has not yet been received.
276        /// Do more I/O and then call this function again.
277        ///
278        /// Returns `Ok(Some(accepted))` if the connection has been accepted. Call
279        /// `accepted.into_connection()` to continue. Do not call this function again.
280        ///
281        /// Returns `Err((err, alert))` if an error occurred. If an alert is returned, the
282        /// application should call `alert.write()` to send the alert to the client. It should
283        /// not call `accept()` again.
284        pub fn accept(&mut self) -> Result<Option<Accepted>, (Error, AcceptedAlert)> {
285            let Some(mut connection) = self.inner.take() else {
286                return Err((
287                    ApiMisuse::AcceptorPolledAfterCompletion.into(),
288                    AcceptedAlert::empty(),
289                ));
290            };
291
292            let input = match connection.first_handshake_message() {
293                Ok(Some(msg)) => msg,
294                Ok(None) => {
295                    self.inner = Some(connection);
296                    return Ok(None);
297                }
298                Err(err) => return Err(AcceptedAlert::from_error(err, connection.core.side)),
299            };
300
301            let sig_schemes = match ClientHelloInput::from_input(&input) {
302                Ok(ClientHelloInput { sig_schemes, .. }) => sig_schemes,
303                Err(err) => {
304                    return Err(AcceptedAlert::from_error(err, connection.core.side));
305                }
306            };
307
308            Ok(Some(Accepted {
309                connection,
310                input,
311                sig_schemes,
312            }))
313        }
314    }
315
316    /// Represents a TLS alert resulting from handling the client's `ClientHello` message.
317    ///
318    /// When [`Acceptor::accept()`] returns an error, it yields an `AcceptedAlert` such that the
319    /// application can communicate failure to the client via [`AcceptedAlert::write()`].
320    pub struct AcceptedAlert(ChunkVecBuffer);
321
322    impl AcceptedAlert {
323        pub(super) fn from_error(error: Error, side: ServerConnectionData) -> (Error, Self) {
324            let mut common = side.into_common();
325            common
326                .send
327                .maybe_send_fatal_alert(&error);
328            (error, Self(common.send.sendable_tls))
329        }
330
331        pub(super) fn empty() -> Self {
332            Self(ChunkVecBuffer::new(None))
333        }
334
335        /// Send the alert to the client.
336        ///
337        /// To account for short writes this function should be called repeatedly until it
338        /// returns `Ok(0)` or an error.
339        pub fn write(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error> {
340            self.0.write_to(wr)
341        }
342
343        /// Send the alert to the client.
344        ///
345        /// This function will invoke the writer until the buffer is empty.
346        pub fn write_all(&mut self, wr: &mut dyn io::Write) -> Result<(), io::Error> {
347            while self.write(wr)? != 0 {}
348            Ok(())
349        }
350    }
351
352    impl Debug for AcceptedAlert {
353        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
354            f.debug_struct("AcceptedAlert")
355                .finish_non_exhaustive()
356        }
357    }
358
359    /// Allows reading of early data in resumed TLS1.3 connections.
360    ///
361    /// "Early data" is also known as "0-RTT data".
362    ///
363    /// This type implements [`io::Read`].
364    pub struct ReadEarlyData<'a> {
365        common: &'a mut ConnectionCommon<ServerConnectionData>,
366    }
367
368    impl<'a> ReadEarlyData<'a> {
369        fn new(common: &'a mut ConnectionCommon<ServerConnectionData>) -> Self {
370            ReadEarlyData { common }
371        }
372
373        /// Returns the "early" exporter that can derive key material for use in early data
374        ///
375        /// See [RFC5705][] for general details on what exporters are, and [RFC8446 S7.5][] for
376        /// specific details on the "early" exporter.
377        ///
378        /// **Beware** that the early exporter requires care, as it is subject to the same
379        /// potential for replay as early data itself.  See [RFC8446 appendix E.5.1][] for
380        /// more detail.
381        ///
382        /// This function can be called at most once per connection. This function will error:
383        /// if called more than once per connection.
384        ///
385        /// If you are looking for the normal exporter, this is available from
386        /// [`ConnectionCommon::exporter()`].
387        ///
388        /// [RFC5705]: https://datatracker.ietf.org/doc/html/rfc5705
389        /// [RFC8446 S7.5]: https://datatracker.ietf.org/doc/html/rfc8446#section-7.5
390        /// [RFC8446 appendix E.5.1]: https://datatracker.ietf.org/doc/html/rfc8446#appendix-E.5.1
391        /// [`ConnectionCommon::exporter()`]: crate::conn::ConnectionCommon::exporter()
392        pub fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
393            self.common.core.early_exporter()
394        }
395    }
396
397    impl io::Read for ReadEarlyData<'_> {
398        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
399            self.common
400                .core
401                .side
402                .early_data
403                .read(buf)
404        }
405    }
406}
407#[cfg(feature = "std")]
408pub use buffered::{AcceptedAlert, Acceptor, ReadEarlyData, ServerConnection};
409
410/// Unbuffered version of `ServerConnection`
411///
412/// See the [`crate::unbuffered`] module docs for more details
413pub struct UnbufferedServerConnection {
414    inner: UnbufferedConnectionCommon<ServerConnectionData>,
415}
416
417impl UnbufferedServerConnection {
418    /// Make a new ServerConnection. `config` controls how we behave in the TLS protocol.
419    pub fn new(config: Arc<ServerConfig>) -> Result<Self, Error> {
420        Ok(Self {
421            inner: UnbufferedConnectionCommon::from(ConnectionCore::for_server(
422                config,
423                ServerExtensionsInput::default(),
424                Protocol::Tcp,
425            )?),
426        })
427    }
428
429    /// Extract secrets, so they can be used when configuring kTLS, for example.
430    /// Should be used with care as it exposes secret key material.
431    #[deprecated = "dangerous_extract_secrets() does not support session tickets or \
432                    key updates, use dangerous_into_kernel_connection() instead"]
433    pub fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
434        self.inner.dangerous_extract_secrets()
435    }
436
437    /// Extract secrets and an [`KernelConnection`] object.
438    ///
439    /// This allows you use rustls to manage keys and then manage encryption and
440    /// decryption yourself (e.g. for kTLS).
441    ///
442    /// Should be used with care as it exposes secret key material.
443    ///
444    /// See the [`crate::kernel`] documentations for details on prerequisites
445    /// for calling this method.
446    pub fn dangerous_into_kernel_connection(
447        self,
448    ) -> Result<(ExtractedSecrets, KernelConnection<ServerConnectionData>), Error> {
449        self.inner
450            .core
451            .dangerous_into_kernel_connection()
452    }
453}
454
455impl Deref for UnbufferedServerConnection {
456    type Target = UnbufferedConnectionCommon<ServerConnectionData>;
457
458    fn deref(&self) -> &Self::Target {
459        &self.inner
460    }
461}
462
463impl DerefMut for UnbufferedServerConnection {
464    fn deref_mut(&mut self) -> &mut Self::Target {
465        &mut self.inner
466    }
467}
468
469impl UnbufferedConnectionCommon<ServerConnectionData> {
470    pub(crate) fn pop_early_data(&mut self) -> Option<Vec<u8>> {
471        self.core.side.early_data.pop()
472    }
473
474    pub(crate) fn peek_early_data(&self) -> Option<&[u8]> {
475        self.core.side.early_data.peek()
476    }
477}
478
479/// Represents a `ClientHello` message received through the [`Acceptor`].
480///
481/// Contains the state required to resume the connection through [`Accepted::into_connection()`].
482#[cfg(feature = "std")]
483pub struct Accepted {
484    connection: ConnectionCommon<ServerConnectionData>,
485    input: Input<'static>,
486    sig_schemes: Vec<SignatureScheme>,
487}
488
489#[cfg(feature = "std")]
490impl Accepted {
491    /// Get the [`ClientHello`] for this connection.
492    pub fn client_hello(&self) -> ClientHello<'_> {
493        let payload = Self::client_hello_payload(&self.input.message);
494        let server_name = payload
495            .server_name
496            .as_ref()
497            .and_then(ServerNamePayload::to_dns_name_normalized)
498            .map(Cow::Owned);
499        let ch = ClientHello {
500            server_name,
501            signature_schemes: &self.sig_schemes,
502            alpn: payload.protocols.as_ref(),
503            server_cert_types: payload
504                .server_certificate_types
505                .as_deref(),
506            client_cert_types: payload
507                .client_certificate_types
508                .as_deref(),
509            cipher_suites: &payload.cipher_suites,
510            certificate_authorities: payload
511                .certificate_authority_names
512                .as_deref(),
513            named_groups: payload.named_groups.as_deref(),
514        };
515
516        trace!("Accepted::client_hello(): {ch:#?}");
517        ch
518    }
519
520    /// Convert the [`Accepted`] into a [`ServerConnection`].
521    ///
522    /// Takes the state returned from [`Acceptor::accept()`] as well as the [`ServerConfig`] that
523    /// should be used for the session. Returns an error if configuration-dependent validation of
524    /// the received `ClientHello` message fails.
525    pub fn into_connection(
526        mut self,
527        config: Arc<ServerConfig>,
528    ) -> Result<ServerConnection, (Error, AcceptedAlert)> {
529        if let Err(err) = self
530            .connection
531            .send
532            .set_max_fragment_size(config.max_fragment_size)
533        {
534            // We have a connection here, but it won't contain an alert since the error
535            // is with the fragment size configured in the `ServerConfig`.
536            return Err((err, AcceptedAlert::empty()));
537        }
538
539        let state =
540            hs::ExpectClientHello::new(config, ServerExtensionsInput::default(), Protocol::Tcp);
541        let proof = match self.input.check_aligned_handshake() {
542            Ok(proof) => proof,
543            Err(err) => {
544                return Err(AcceptedAlert::from_error(err, self.connection.core.side));
545            }
546        };
547
548        let input = ClientHelloInput {
549            message: &self.input.message,
550            client_hello: Self::client_hello_payload(&self.input.message),
551            sig_schemes: self.sig_schemes,
552            proof,
553        };
554
555        let new = match state.with_input(input, &mut self.connection.core.side) {
556            Ok(new) => new,
557            Err(err) => return Err(AcceptedAlert::from_error(err, self.connection.core.side)),
558        };
559
560        self.connection.replace_state(new);
561        Ok(ServerConnection {
562            inner: self.connection,
563        })
564    }
565
566    fn client_hello_payload<'a>(message: &'a Message<'_>) -> &'a ClientHelloPayload {
567        match &message.payload {
568            MessagePayload::Handshake { parsed, .. } => match &parsed.0 {
569                HandshakePayload::ClientHello(ch) => ch,
570                _ => unreachable!(),
571            },
572            _ => unreachable!(),
573        }
574    }
575}
576
577#[cfg(feature = "std")]
578impl Debug for Accepted {
579    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
580        f.debug_struct("Accepted")
581            .finish_non_exhaustive()
582    }
583}
584
585#[cfg(feature = "std")]
586struct Accepting;
587
588#[cfg(feature = "std")]
589impl State<ServerConnectionData> for Accepting {
590    #[cfg_attr(coverage_nightly, coverage(off))]
591    fn handle<'m>(
592        self: Box<Self>,
593        _input: Input<'m>,
594        _output: &mut dyn Output,
595    ) -> Result<Box<dyn State<ServerConnectionData>>, Error> {
596        Err(Error::Unreachable("unreachable state"))
597    }
598}
599
600#[derive(Default)]
601pub(super) enum EarlyDataState {
602    #[default]
603    New,
604    Accepted {
605        received: ChunkVecBuffer,
606    },
607}
608
609impl EarlyDataState {
610    fn accept(&mut self) {
611        *self = Self::Accepted {
612            received: ChunkVecBuffer::new(None),
613        };
614    }
615
616    #[cfg(feature = "std")]
617    fn was_accepted(&self) -> bool {
618        matches!(self, Self::Accepted { .. })
619    }
620
621    fn peek(&self) -> Option<&[u8]> {
622        match self {
623            Self::Accepted { received, .. } => received.peek(),
624            _ => None,
625        }
626    }
627
628    fn pop(&mut self) -> Option<Vec<u8>> {
629        match self {
630            Self::Accepted { received, .. } => received.pop(),
631            _ => None,
632        }
633    }
634
635    #[cfg(feature = "std")]
636    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
637        match self {
638            Self::Accepted { received, .. } => received.read(buf),
639            _ => Err(io::Error::from(io::ErrorKind::BrokenPipe)),
640        }
641    }
642
643    fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
644        let Self::Accepted { received } = self else {
645            return;
646        };
647
648        received.append(bytes.into_vec());
649    }
650}
651
652impl Debug for EarlyDataState {
653    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
654        match self {
655            Self::New => write!(f, "EarlyDataState::New"),
656            Self::Accepted { received } => write!(
657                f,
658                "EarlyDataState::Accepted {{ received: {} }}",
659                received.len(),
660            ),
661        }
662    }
663}
664
665impl ConnectionCore<ServerConnectionData> {
666    pub(crate) fn for_server(
667        config: Arc<ServerConfig>,
668        extra_exts: ServerExtensionsInput,
669        protocol: Protocol,
670    ) -> Result<Self, Error> {
671        let mut common = CommonState::new(Side::Server, protocol);
672        common
673            .send
674            .set_max_fragment_size(config.max_fragment_size)?;
675        common.fips = config.fips();
676        Ok(Self::new(
677            Box::new(hs::ExpectClientHello::new(config, extra_exts, protocol)),
678            ServerConnectionData::new(common),
679        ))
680    }
681}
682
683/// State associated with a server connection.
684#[derive(Debug)]
685pub struct ServerConnectionData {
686    common: CommonState,
687    sni: Option<DnsName<'static>>,
688    received_resumption_data: Option<Vec<u8>>,
689    early_data: EarlyDataState,
690}
691
692impl ServerConnectionData {
693    pub(crate) fn new(common: CommonState) -> Self {
694        Self {
695            common,
696            sni: None,
697            received_resumption_data: None,
698            early_data: EarlyDataState::default(),
699        }
700    }
701
702    #[cfg(feature = "std")]
703    pub(crate) fn received_resumption_data(&self) -> Option<&[u8]> {
704        self.received_resumption_data.as_deref()
705    }
706
707    #[cfg(feature = "std")]
708    pub(crate) fn server_name(&self) -> Option<&DnsName<'static>> {
709        self.sni.as_ref()
710    }
711}
712
713impl Output for ServerConnectionData {
714    fn emit(&mut self, ev: Event<'_>) {
715        match ev {
716            Event::EarlyApplicationData(data) => self
717                .early_data
718                .take_received_plaintext(data),
719            Event::EarlyData(EarlyDataEvent::Accepted) => self.early_data.accept(),
720            Event::ReceivedServerName(sni) => self.sni = sni,
721            Event::ResumptionData(data) => self.received_resumption_data = Some(data),
722            _ => self.common.emit(ev),
723        }
724    }
725}
726
727impl crate::conn::SideData for ServerConnectionData {}
728
729impl crate::conn::private::SideData for ServerConnectionData {
730    fn into_common(self) -> CommonState {
731        self.common
732    }
733}
734
735impl Deref for ServerConnectionData {
736    type Target = CommonState;
737
738    fn deref(&self) -> &Self::Target {
739        &self.common
740    }
741}
742
743impl DerefMut for ServerConnectionData {
744    fn deref_mut(&mut self) -> &mut Self::Target {
745        &mut self.common
746    }
747}
748
749#[cfg(feature = "std")]
750#[cfg(test)]
751mod tests {
752    use std::format;
753
754    use super::*;
755
756    // these branches not reachable externally, unless something else goes wrong.
757    #[test]
758    fn test_read_in_new_state() {
759        assert_eq!(
760            format!("{:?}", EarlyDataState::default().read(&mut [0u8; 5])),
761            "Err(Kind(BrokenPipe))"
762        );
763    }
764}