rustls/server/
server_conn.rs

1use crate::builder::{ConfigBuilder, WantsCipherSuites};
2use crate::common_state::{CommonState, Context, Side, State};
3use crate::conn::{ConnectionCommon, ConnectionCore};
4use crate::dns_name::DnsName;
5use crate::enums::{CipherSuite, ProtocolVersion, SignatureScheme};
6use crate::error::Error;
7use crate::kx::SupportedKxGroup;
8#[cfg(feature = "logging")]
9use crate::log::trace;
10use crate::msgs::base::Payload;
11use crate::msgs::handshake::{ClientHelloPayload, ProtocolName, ServerExtension};
12use crate::msgs::message::Message;
13use crate::sign;
14use crate::suites::SupportedCipherSuite;
15use crate::vecbuf::ChunkVecBuffer;
16use crate::verify;
17#[cfg(feature = "secret_extraction")]
18use crate::ExtractedSecrets;
19use crate::KeyLog;
20
21use super::hs;
22
23use std::marker::PhantomData;
24use std::ops::{Deref, DerefMut};
25use std::sync::Arc;
26use std::{fmt, io};
27
28/// A trait for the ability to store server session data.
29///
30/// The keys and values are opaque.
31///
32/// Both the keys and values should be treated as
33/// **highly sensitive data**, containing enough key material
34/// to break all security of the corresponding sessions.
35///
36/// Implementations can be lossy (in other words, forgetting
37/// key/value pairs) without any negative security consequences.
38///
39/// However, note that `take` **must** reliably delete a returned
40/// value.  If it does not, there may be security consequences.
41///
42/// `put` and `take` are mutating operations; this isn't expressed
43/// in the type system to allow implementations freedom in
44/// how to achieve interior mutability.  `Mutex` is a common
45/// choice.
46pub trait StoresServerSessions: Send + Sync {
47    /// Store session secrets encoded in `value` against `key`,
48    /// overwrites any existing value against `key`.  Returns `true`
49    /// if the value was stored.
50    fn put(&self, key: Vec<u8>, value: Vec<u8>) -> bool;
51
52    /// Find a value with the given `key`.  Return it, or None
53    /// if it doesn't exist.
54    fn get(&self, key: &[u8]) -> Option<Vec<u8>>;
55
56    /// Find a value with the given `key`.  Return it and delete it;
57    /// or None if it doesn't exist.
58    fn take(&self, key: &[u8]) -> Option<Vec<u8>>;
59
60    /// Whether the store can cache another session. This is used to indicate to clients
61    /// whether their session can be resumed; the implementation is not required to remember
62    /// a session even if it returns `true` here.
63    fn can_cache(&self) -> bool;
64}
65
66/// A trait for the ability to encrypt and decrypt tickets.
67pub trait ProducesTickets: Send + Sync {
68    /// Returns true if this implementation will encrypt/decrypt
69    /// tickets.  Should return false if this is a dummy
70    /// implementation: the server will not send the SessionTicket
71    /// extension and will not call the other functions.
72    fn enabled(&self) -> bool;
73
74    /// Returns the lifetime in seconds of tickets produced now.
75    /// The lifetime is provided as a hint to clients that the
76    /// ticket will not be useful after the given time.
77    ///
78    /// This lifetime must be implemented by key rolling and
79    /// erasure, *not* by storing a lifetime in the ticket.
80    ///
81    /// The objective is to limit damage to forward secrecy caused
82    /// by tickets, not just limiting their lifetime.
83    fn lifetime(&self) -> u32;
84
85    /// Encrypt and authenticate `plain`, returning the resulting
86    /// ticket.  Return None if `plain` cannot be encrypted for
87    /// some reason: an empty ticket will be sent and the connection
88    /// will continue.
89    fn encrypt(&self, plain: &[u8]) -> Option<Vec<u8>>;
90
91    /// Decrypt `cipher`, validating its authenticity protection
92    /// and recovering the plaintext.  `cipher` is fully attacker
93    /// controlled, so this decryption must be side-channel free,
94    /// panic-proof, and otherwise bullet-proof.  If the decryption
95    /// fails, return None.
96    fn decrypt(&self, cipher: &[u8]) -> Option<Vec<u8>>;
97}
98
99/// How to choose a certificate chain and signing key for use
100/// in server authentication.
101pub trait ResolvesServerCert: Send + Sync {
102    /// Choose a certificate chain and matching key given simplified
103    /// ClientHello information.
104    ///
105    /// Return `None` to abort the handshake.
106    fn resolve(&self, client_hello: ClientHello) -> Option<Arc<sign::CertifiedKey>>;
107}
108
109/// A struct representing the received Client Hello
110pub struct ClientHello<'a> {
111    server_name: &'a Option<DnsName>,
112    signature_schemes: &'a [SignatureScheme],
113    alpn: Option<&'a Vec<ProtocolName>>,
114    cipher_suites: &'a [CipherSuite],
115}
116
117impl<'a> ClientHello<'a> {
118    /// Creates a new ClientHello
119    pub(super) fn new(
120        server_name: &'a Option<DnsName>,
121        signature_schemes: &'a [SignatureScheme],
122        alpn: Option<&'a Vec<ProtocolName>>,
123        cipher_suites: &'a [CipherSuite],
124    ) -> Self {
125        trace!("sni {:?}", server_name);
126        trace!("sig schemes {:?}", signature_schemes);
127        trace!("alpn protocols {:?}", alpn);
128        trace!("cipher suites {:?}", cipher_suites);
129
130        ClientHello {
131            server_name,
132            signature_schemes,
133            alpn,
134            cipher_suites,
135        }
136    }
137
138    /// Get the server name indicator.
139    ///
140    /// Returns `None` if the client did not supply a SNI.
141    pub fn server_name(&self) -> Option<&str> {
142        self.server_name
143            .as_ref()
144            .map(<DnsName as AsRef<str>>::as_ref)
145    }
146
147    /// Get the compatible signature schemes.
148    ///
149    /// Returns standard-specified default if the client omitted this extension.
150    pub fn signature_schemes(&self) -> &[SignatureScheme] {
151        self.signature_schemes
152    }
153
154    /// Get the ALPN protocol identifiers submitted by the client.
155    ///
156    /// Returns `None` if the client did not include an ALPN extension.
157    ///
158    /// Application Layer Protocol Negotiation (ALPN) is a TLS extension that lets a client
159    /// submit a set of identifiers that each a represent an application-layer protocol.
160    /// The server will then pick its preferred protocol from the set submitted by the client.
161    /// Each identifier is represented as a byte array, although common values are often ASCII-encoded.
162    /// See the official RFC-7301 specifications at <https://datatracker.ietf.org/doc/html/rfc7301>
163    /// for more information on ALPN.
164    ///
165    /// For example, a HTTP client might specify "http/1.1" and/or "h2". Other well-known values
166    /// are listed in the at IANA registry at
167    /// <https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids>.
168    ///
169    /// The server can specify supported ALPN protocols by setting [`ServerConfig::alpn_protocols`].
170    /// During the handshake, the server will select the first protocol configured that the client supports.
171    pub fn alpn(&self) -> Option<impl Iterator<Item = &'a [u8]>> {
172        self.alpn.map(|protocols| {
173            protocols
174                .iter()
175                .map(|proto| proto.as_ref())
176        })
177    }
178
179    /// Get cipher suites.
180    pub fn cipher_suites(&self) -> &[CipherSuite] {
181        self.cipher_suites
182    }
183}
184
185/// Common configuration for a set of server sessions.
186///
187/// Making one of these is cheap, though one of the inputs may be expensive: gathering trust roots
188/// from the operating system to add to the [`RootCertStore`] passed to a `ClientCertVerifier`
189/// builder may take on the order of a few hundred milliseconds.
190///
191/// These must be created via the [`ServerConfig::builder()`] function.
192///
193/// # Defaults
194///
195/// * [`ServerConfig::max_fragment_size`]: the default is `None`: TLS packets are not fragmented to a specific size.
196/// * [`ServerConfig::session_storage`]: the default stores 256 sessions in memory.
197/// * [`ServerConfig::alpn_protocols`]: the default is empty -- no ALPN protocol is negotiated.
198/// * [`ServerConfig::key_log`]: key material is not logged.
199/// * [`ServerConfig::send_tls13_tickets`]: 4 tickets are sent.
200///
201/// [`RootCertStore`]: crate::RootCertStore
202#[derive(Clone)]
203pub struct ServerConfig {
204    /// List of ciphersuites, in preference order.
205    pub(super) cipher_suites: Vec<SupportedCipherSuite>,
206
207    /// List of supported key exchange groups.
208    ///
209    /// The first is the highest priority: they will be
210    /// offered to the client in this order.
211    pub(super) kx_groups: Vec<&'static SupportedKxGroup>,
212
213    /// Ignore the client's ciphersuite order. Instead,
214    /// choose the top ciphersuite in the server list
215    /// which is supported by the client.
216    pub ignore_client_order: bool,
217
218    /// The maximum size of TLS message we'll emit.  If None, we don't limit TLS
219    /// message lengths except to the 2**16 limit specified in the standard.
220    ///
221    /// rustls enforces an arbitrary minimum of 32 bytes for this field.
222    /// Out of range values are reported as errors from ServerConnection::new.
223    ///
224    /// Setting this value to the TCP MSS may improve latency for stream-y workloads.
225    pub max_fragment_size: Option<usize>,
226
227    /// How to store client sessions.
228    pub session_storage: Arc<dyn StoresServerSessions + Send + Sync>,
229
230    /// How to produce tickets.
231    pub ticketer: Arc<dyn ProducesTickets>,
232
233    /// How to choose a server cert and key.
234    pub cert_resolver: Arc<dyn ResolvesServerCert>,
235
236    /// Protocol names we support, most preferred first.
237    /// If empty we don't do ALPN at all.
238    pub alpn_protocols: Vec<Vec<u8>>,
239
240    /// Supported protocol versions, in no particular order.
241    /// The default is all supported versions.
242    pub(super) versions: crate::versions::EnabledVersions,
243
244    /// How to verify client certificates.
245    pub(super) verifier: Arc<dyn verify::ClientCertVerifier>,
246
247    /// How to output key material for debugging.  The default
248    /// does nothing.
249    pub key_log: Arc<dyn KeyLog>,
250
251    /// Allows traffic secrets to be extracted after the handshake,
252    /// e.g. for kTLS setup.
253    #[cfg(feature = "secret_extraction")]
254    #[cfg_attr(docsrs, doc(cfg(feature = "secret_extraction")))]
255    pub enable_secret_extraction: bool,
256
257    /// Amount of early data to accept for sessions created by
258    /// this config.  Specify 0 to disable early data.  The
259    /// default is 0.
260    ///
261    /// Read the early data via [`ServerConnection::early_data`].
262    ///
263    /// The units for this are _both_ plaintext bytes, _and_ ciphertext
264    /// bytes, depending on whether the server accepts a client's early_data
265    /// or not.  It is therefore recommended to include some slop in
266    /// this value to account for the unknown amount of ciphertext
267    /// expansion in the latter case.
268    pub max_early_data_size: u32,
269
270    /// Whether the server should send "0.5RTT" data.  This means the server
271    /// sends data after its first flight of handshake messages, without
272    /// waiting for the client to complete the handshake.
273    ///
274    /// This can improve TTFB latency for either server-speaks-first protocols,
275    /// or client-speaks-first protocols when paired with "0RTT" data.  This
276    /// comes at the cost of a subtle weakening of the normal handshake
277    /// integrity guarantees that TLS provides.  Note that the initial
278    /// `ClientHello` is indirectly authenticated because it is included
279    /// in the transcript used to derive the keys used to encrypt the data.
280    ///
281    /// This only applies to TLS1.3 connections.  TLS1.2 connections cannot
282    /// do this optimisation and this setting is ignored for them.  It is
283    /// also ignored for TLS1.3 connections that even attempt client
284    /// authentication.
285    ///
286    /// This defaults to false.  This means the first application data
287    /// sent by the server comes after receiving and validating the client's
288    /// handshake up to the `Finished` message.  This is the safest option.
289    pub send_half_rtt_data: bool,
290
291    /// How many TLS1.3 tickets to send immediately after a successful
292    /// handshake.
293    ///
294    /// Because TLS1.3 tickets are single-use, this allows
295    /// a client to perform multiple resumptions.
296    ///
297    /// The default is 4.
298    ///
299    /// If this is 0, no tickets are sent and clients will not be able to
300    /// do any resumption.
301    pub send_tls13_tickets: usize,
302}
303
304impl fmt::Debug for ServerConfig {
305    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
306        f.debug_struct("ServerConfig")
307            .field("ignore_client_order", &self.ignore_client_order)
308            .field("max_fragment_size", &self.max_fragment_size)
309            .field("alpn_protocols", &self.alpn_protocols)
310            .field("max_early_data_size", &self.max_early_data_size)
311            .field("send_half_rtt_data", &self.send_half_rtt_data)
312            .field("send_tls13_tickets", &self.send_tls13_tickets)
313            .finish_non_exhaustive()
314    }
315}
316
317impl ServerConfig {
318    /// Create builder to build up the server configuration.
319    ///
320    /// For more information, see the [`ConfigBuilder`] documentation.
321    pub fn builder() -> ConfigBuilder<Self, WantsCipherSuites> {
322        ConfigBuilder {
323            state: WantsCipherSuites(()),
324            side: PhantomData,
325        }
326    }
327
328    /// We support a given TLS version if it's quoted in the configured
329    /// versions *and* at least one ciphersuite for this version is
330    /// also configured.
331    pub(crate) fn supports_version(&self, v: ProtocolVersion) -> bool {
332        self.versions.contains(v)
333            && self
334                .cipher_suites
335                .iter()
336                .any(|cs| cs.version().version == v)
337    }
338}
339
340/// Allows reading of early data in resumed TLS1.3 connections.
341///
342/// "Early data" is also known as "0-RTT data".
343///
344/// This structure implements [`std::io::Read`].
345pub struct ReadEarlyData<'a> {
346    early_data: &'a mut EarlyDataState,
347}
348
349impl<'a> ReadEarlyData<'a> {
350    fn new(early_data: &'a mut EarlyDataState) -> Self {
351        ReadEarlyData { early_data }
352    }
353}
354
355impl<'a> io::Read for ReadEarlyData<'a> {
356    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
357        self.early_data.read(buf)
358    }
359
360    #[cfg(read_buf)]
361    fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_>) -> io::Result<()> {
362        self.early_data.read_buf(cursor)
363    }
364}
365
366/// This represents a single TLS server connection.
367///
368/// Send TLS-protected data to the peer using the `io::Write` trait implementation.
369/// Read data from the peer using the `io::Read` trait implementation.
370pub struct ServerConnection {
371    inner: ConnectionCommon<ServerConnectionData>,
372}
373
374impl ServerConnection {
375    /// Make a new ServerConnection.  `config` controls how
376    /// we behave in the TLS protocol.
377    pub fn new(config: Arc<ServerConfig>) -> Result<Self, Error> {
378        Ok(Self {
379            inner: ConnectionCommon::from(ConnectionCore::for_server(config, Vec::new())?),
380        })
381    }
382
383    /// Retrieves the server name, if any, used to select the certificate and
384    /// private key.
385    ///
386    /// This returns `None` until some time after the client's server name indication
387    /// (SNI) extension value is processed during the handshake. It will never be
388    /// `None` when the connection is ready to send or process application data,
389    /// unless the client does not support SNI.
390    ///
391    /// This is useful for application protocols that need to enforce that the
392    /// server name matches an application layer protocol hostname. For
393    /// example, HTTP/1.1 servers commonly expect the `Host:` header field of
394    /// every request on a connection to match the hostname in the SNI extension
395    /// when the client provides the SNI extension.
396    ///
397    /// The server name is also used to match sessions during session resumption.
398    pub fn server_name(&self) -> Option<&str> {
399        self.inner.core.get_sni_str()
400    }
401
402    /// Application-controlled portion of the resumption ticket supplied by the client, if any.
403    ///
404    /// Recovered from the prior session's `set_resumption_data`. Integrity is guaranteed by rustls.
405    ///
406    /// Returns `Some` iff a valid resumption ticket has been received from the client.
407    pub fn received_resumption_data(&self) -> Option<&[u8]> {
408        self.inner
409            .core
410            .data
411            .received_resumption_data
412            .as_ref()
413            .map(|x| &x[..])
414    }
415
416    /// Set the resumption data to embed in future resumption tickets supplied to the client.
417    ///
418    /// Defaults to the empty byte string. Must be less than 2^15 bytes to allow room for other
419    /// data. Should be called while `is_handshaking` returns true to ensure all transmitted
420    /// resumption tickets are affected.
421    ///
422    /// Integrity will be assured by rustls, but the data will be visible to the client. If secrecy
423    /// from the client is desired, encrypt the data separately.
424    pub fn set_resumption_data(&mut self, data: &[u8]) {
425        assert!(data.len() < 2usize.pow(15));
426        self.inner.core.data.resumption_data = data.into();
427    }
428
429    /// Explicitly discard early data, notifying the client
430    ///
431    /// Useful if invariants encoded in `received_resumption_data()` cannot be respected.
432    ///
433    /// Must be called while `is_handshaking` is true.
434    pub fn reject_early_data(&mut self) {
435        self.inner.core.reject_early_data()
436    }
437
438    /// Returns an `io::Read` implementer you can read bytes from that are
439    /// received from a client as TLS1.3 0RTT/"early" data, during the handshake.
440    ///
441    /// This returns `None` in many circumstances, such as :
442    ///
443    /// - Early data is disabled if [`ServerConfig::max_early_data_size`] is zero (the default).
444    /// - The session negotiated with the client is not TLS1.3.
445    /// - The client just doesn't support early data.
446    /// - The connection doesn't resume an existing session.
447    /// - The client hasn't sent a full ClientHello yet.
448    pub fn early_data(&mut self) -> Option<ReadEarlyData> {
449        let data = &mut self.inner.core.data;
450        if data.early_data.was_accepted() {
451            Some(ReadEarlyData::new(&mut data.early_data))
452        } else {
453            None
454        }
455    }
456
457    /// Extract secrets, so they can be used when configuring kTLS, for example.
458    #[cfg(feature = "secret_extraction")]
459    #[cfg_attr(docsrs, doc(cfg(feature = "secret_extraction")))]
460    pub fn extract_secrets(self) -> Result<ExtractedSecrets, Error> {
461        self.inner.extract_secrets()
462    }
463}
464
465impl fmt::Debug for ServerConnection {
466    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
467        f.debug_struct("ServerConnection")
468            .finish()
469    }
470}
471
472impl Deref for ServerConnection {
473    type Target = ConnectionCommon<ServerConnectionData>;
474
475    fn deref(&self) -> &Self::Target {
476        &self.inner
477    }
478}
479
480impl DerefMut for ServerConnection {
481    fn deref_mut(&mut self) -> &mut Self::Target {
482        &mut self.inner
483    }
484}
485
486impl From<ServerConnection> for crate::Connection {
487    fn from(conn: ServerConnection) -> Self {
488        Self::Server(conn)
489    }
490}
491
492/// Handle on a server-side connection before configuration is available.
493///
494/// `Acceptor` allows the caller to choose a [`ServerConfig`] after reading
495/// the [`ClientHello`] of an incoming connection. This is useful for servers
496/// that choose different certificates or cipher suites based on the
497/// characteristics of the `ClientHello`. In particular it is useful for
498/// servers that need to do some I/O to load a certificate and its private key
499/// and don't want to use the blocking interface provided by
500/// [`ResolvesServerCert`].
501///
502/// Create an Acceptor with [`Acceptor::default()`].
503///
504/// # Example
505///
506/// ```no_run
507/// # fn choose_server_config(
508/// #     _: rustls::server::ClientHello,
509/// # ) -> std::sync::Arc<rustls::ServerConfig> {
510/// #     unimplemented!();
511/// # }
512/// # #[allow(unused_variables)]
513/// # fn main() {
514/// use rustls::server::{Acceptor, ServerConfig};
515/// let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
516/// for stream in listener.incoming() {
517///     let mut stream = stream.unwrap();
518///     let mut acceptor = Acceptor::default();
519///     let accepted = loop {
520///         acceptor.read_tls(&mut stream).unwrap();
521///         if let Some(accepted) = acceptor.accept().unwrap() {
522///             break accepted;
523///         }
524///     };
525///
526///     // For some user-defined choose_server_config:
527///     let config = choose_server_config(accepted.client_hello());
528///     let conn = accepted
529///         .into_connection(config)
530///         .unwrap();
531
532///     // Proceed with handling the ServerConnection.
533/// }
534/// # }
535/// ```
536pub struct Acceptor {
537    inner: Option<ConnectionCommon<ServerConnectionData>>,
538}
539
540impl Default for Acceptor {
541    /// Return an empty Acceptor, ready to receive bytes from a new client connection.
542    fn default() -> Self {
543        Self {
544            inner: Some(
545                ConnectionCore::new(
546                    Box::new(Accepting),
547                    ServerConnectionData::default(),
548                    CommonState::new(Side::Server),
549                )
550                .into(),
551            ),
552        }
553    }
554}
555
556impl Acceptor {
557    /// Read TLS content from `rd`.
558    ///
559    /// Returns an error if this `Acceptor` has already yielded an [`Accepted`]. For more details,
560    /// refer to [`Connection::read_tls()`].
561    ///
562    /// [`Connection::read_tls()`]: crate::Connection::read_tls
563    pub fn read_tls(&mut self, rd: &mut dyn io::Read) -> Result<usize, io::Error> {
564        match &mut self.inner {
565            Some(conn) => conn.read_tls(rd),
566            None => Err(io::Error::new(
567                io::ErrorKind::Other,
568                "acceptor cannot read after successful acceptance",
569            )),
570        }
571    }
572
573    /// Check if a `ClientHello` message has been received.
574    ///
575    /// Returns `Ok(None)` if the complete `ClientHello` has not yet been received.
576    /// Do more I/O and then call this function again.
577    ///
578    /// Returns `Ok(Some(accepted))` if the connection has been accepted. Call
579    /// `accepted.into_connection()` to continue. Do not call this function again.
580    ///
581    /// Returns `Err(err)` if an error occurred. Do not call this function again.
582    pub fn accept(&mut self) -> Result<Option<Accepted>, Error> {
583        let mut connection = match self.inner.take() {
584            Some(conn) => conn,
585            None => {
586                return Err(Error::General("Acceptor polled after completion".into()));
587            }
588        };
589
590        let message = match connection.first_handshake_message()? {
591            Some(msg) => msg,
592            None => {
593                self.inner = Some(connection);
594                return Ok(None);
595            }
596        };
597
598        let (_, sig_schemes) =
599            hs::process_client_hello(&message, false, &mut Context::from(&mut connection))?;
600
601        Ok(Some(Accepted {
602            connection,
603            message,
604            sig_schemes,
605        }))
606    }
607}
608
609/// Represents a `ClientHello` message received through the [`Acceptor`].
610///
611/// Contains the state required to resume the connection through [`Accepted::into_connection()`].
612pub struct Accepted {
613    connection: ConnectionCommon<ServerConnectionData>,
614    message: Message,
615    sig_schemes: Vec<SignatureScheme>,
616}
617
618impl Accepted {
619    /// Get the [`ClientHello`] for this connection.
620    pub fn client_hello(&self) -> ClientHello<'_> {
621        let payload = Self::client_hello_payload(&self.message);
622        ClientHello::new(
623            &self.connection.core.data.sni,
624            &self.sig_schemes,
625            payload.get_alpn_extension(),
626            &payload.cipher_suites,
627        )
628    }
629
630    /// Convert the [`Accepted`] into a [`ServerConnection`].
631    ///
632    /// Takes the state returned from [`Acceptor::accept()`] as well as the [`ServerConfig`] and
633    /// [`sign::CertifiedKey`] that should be used for the session. Returns an error if
634    /// configuration-dependent validation of the received `ClientHello` message fails.
635    pub fn into_connection(mut self, config: Arc<ServerConfig>) -> Result<ServerConnection, Error> {
636        self.connection
637            .set_max_fragment_size(config.max_fragment_size)?;
638
639        #[cfg(feature = "secret_extraction")]
640        {
641            self.connection.enable_secret_extraction = config.enable_secret_extraction;
642        }
643
644        let state = hs::ExpectClientHello::new(config, Vec::new());
645        let mut cx = hs::ServerContext::from(&mut self.connection);
646
647        let new = state.with_certified_key(
648            self.sig_schemes,
649            Self::client_hello_payload(&self.message),
650            &self.message,
651            &mut cx,
652        )?;
653
654        self.connection.replace_state(new);
655        Ok(ServerConnection {
656            inner: self.connection,
657        })
658    }
659
660    fn client_hello_payload(message: &Message) -> &ClientHelloPayload {
661        match &message.payload {
662            crate::msgs::message::MessagePayload::Handshake { parsed, .. } => match &parsed.payload
663            {
664                crate::msgs::handshake::HandshakePayload::ClientHello(ch) => ch,
665                _ => unreachable!(),
666            },
667            _ => unreachable!(),
668        }
669    }
670}
671
672struct Accepting;
673
674impl State<ServerConnectionData> for Accepting {
675    fn handle(
676        self: Box<Self>,
677        _cx: &mut hs::ServerContext<'_>,
678        _m: Message,
679    ) -> Result<Box<dyn State<ServerConnectionData>>, Error> {
680        Err(Error::General("unreachable state".into()))
681    }
682}
683
684pub(super) enum EarlyDataState {
685    New,
686    Accepted(ChunkVecBuffer),
687    Rejected,
688}
689
690impl Default for EarlyDataState {
691    fn default() -> Self {
692        Self::New
693    }
694}
695
696impl EarlyDataState {
697    pub(super) fn reject(&mut self) {
698        *self = Self::Rejected;
699    }
700
701    pub(super) fn accept(&mut self, max_size: usize) {
702        *self = Self::Accepted(ChunkVecBuffer::new(Some(max_size)));
703    }
704
705    fn was_accepted(&self) -> bool {
706        matches!(self, Self::Accepted(_))
707    }
708
709    pub(super) fn was_rejected(&self) -> bool {
710        matches!(self, Self::Rejected)
711    }
712
713    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
714        match self {
715            Self::Accepted(ref mut received) => received.read(buf),
716            _ => Err(io::Error::from(io::ErrorKind::BrokenPipe)),
717        }
718    }
719
720    #[cfg(read_buf)]
721    fn read_buf(&mut self, cursor: core::io::BorrowedCursor<'_>) -> io::Result<()> {
722        match self {
723            Self::Accepted(ref mut received) => received.read_buf(cursor),
724            _ => Err(io::Error::from(io::ErrorKind::BrokenPipe)),
725        }
726    }
727
728    pub(super) fn take_received_plaintext(&mut self, bytes: Payload) -> bool {
729        let available = bytes.0.len();
730        match self {
731            Self::Accepted(ref mut received) if received.apply_limit(available) == available => {
732                received.append(bytes.0);
733                true
734            }
735            _ => false,
736        }
737    }
738}
739
740// these branches not reachable externally, unless something else goes wrong.
741#[test]
742fn test_read_in_new_state() {
743    assert_eq!(
744        format!("{:?}", EarlyDataState::default().read(&mut [0u8; 5])),
745        "Err(Kind(BrokenPipe))"
746    );
747}
748
749#[cfg(read_buf)]
750#[test]
751fn test_read_buf_in_new_state() {
752    use std::io::BorrowedBuf;
753
754    let mut buf = [0u8; 5];
755    let mut buf: BorrowedBuf<'_> = buf.as_mut_slice().into();
756    assert_eq!(
757        format!("{:?}", EarlyDataState::default().read_buf(buf.unfilled())),
758        "Err(Kind(BrokenPipe))"
759    );
760}
761
762impl ConnectionCore<ServerConnectionData> {
763    pub(crate) fn for_server(
764        config: Arc<ServerConfig>,
765        extra_exts: Vec<ServerExtension>,
766    ) -> Result<Self, Error> {
767        let mut common = CommonState::new(Side::Server);
768        common.set_max_fragment_size(config.max_fragment_size)?;
769        #[cfg(feature = "secret_extraction")]
770        {
771            common.enable_secret_extraction = config.enable_secret_extraction;
772        }
773        Ok(Self::new(
774            Box::new(hs::ExpectClientHello::new(config, extra_exts)),
775            ServerConnectionData::default(),
776            common,
777        ))
778    }
779
780    pub(crate) fn reject_early_data(&mut self) {
781        assert!(
782            self.common_state.is_handshaking(),
783            "cannot retroactively reject early data"
784        );
785        self.data.early_data.reject();
786    }
787
788    pub(crate) fn get_sni_str(&self) -> Option<&str> {
789        self.data.get_sni_str()
790    }
791}
792
793/// State associated with a server connection.
794#[derive(Default)]
795pub struct ServerConnectionData {
796    pub(super) sni: Option<DnsName>,
797    pub(super) received_resumption_data: Option<Vec<u8>>,
798    pub(super) resumption_data: Vec<u8>,
799    pub(super) early_data: EarlyDataState,
800}
801
802impl ServerConnectionData {
803    pub(super) fn get_sni_str(&self) -> Option<&str> {
804        self.sni.as_ref().map(AsRef::as_ref)
805    }
806}
807
808impl crate::conn::SideData for ServerConnectionData {}