1use alloc::boxed::Box;
2use alloc::vec::Vec;
3use core::ops::Deref;
4use core::{fmt, mem};
5
6use pki_types::{DnsName, FipsStatus};
7
8use super::config::{ClientHello, ServerConfig};
9use crate::common_state::{
10 CommonState, ConnectionOutputs, EarlyDataEvent, Event, Protocol, Side, maybe_send_fatal_alert,
11};
12use crate::conn::private::SideOutput;
13use crate::conn::split::SplitConnection;
14use crate::conn::{
15 Connection, ConnectionCommon, KeyingMaterialExporter, MessageHandler, NeedsInput, SideData,
16 StateMachine, TlsInputBuffer, VerifyPeerIdentity,
17};
18#[cfg(doc)]
19use crate::crypto;
20use crate::crypto::cipher::OutboundPlain;
21use crate::error::Error;
22use crate::msgs::ServerExtensionsInput;
23use crate::server::hs::{ChooseConfig, ExpectClientHello, ReadClientHello, ServerState};
24use crate::suites::ExtractedSecrets;
25use crate::sync::Arc;
26use crate::tracing::trace;
27use crate::verify::ClientIdentity;
28
29pub struct ServerConnection {
34 pub(super) inner: ConnectionCommon<ServerSide>,
35}
36
37impl ServerConnection {
38 pub fn new(config: Arc<ServerConfig>) -> Result<Self, Error> {
41 Ok(Self {
42 inner: ConnectionCommon::for_server(
43 config,
44 ServerExtensionsInput::default(),
45 Protocol::Tcp,
46 )?,
47 })
48 }
49
50 pub fn split(self) -> Result<SplitConnection<ServerSide>, Error> {
65 self.inner.split()
66 }
67
68 pub fn server_name(&self) -> Option<&DnsName<'_>> {
84 self.inner.side.server_name()
85 }
86
87 pub fn received_resumption_data(&self) -> Option<&[u8]> {
93 self.inner
94 .side
95 .received_resumption_data()
96 }
97
98 pub fn set_resumption_data(&mut self, data: &[u8]) -> Result<(), Error> {
107 assert!(data.len() < 2usize.pow(15));
108 match &mut self.inner.state {
109 Ok(st) => st.set_resumption_data(data),
110 Err(e) => Err(e.clone()),
111 }
112 }
113
114 pub fn early_data(&mut self) -> Option<ReadEarlyData<'_>> {
128 if self
129 .inner
130 .side
131 .early_data
132 .was_accepted()
133 {
134 Some(ReadEarlyData::new(&mut self.inner))
135 } else {
136 None
137 }
138 }
139}
140
141impl Connection for ServerConnection {
142 type Side = ServerSide;
143
144 fn write(&mut self, plaintext: OutboundPlain<'_>, tls: &mut Vec<u8>) -> Result<(), Error> {
145 self.inner.write(plaintext, tls)
146 }
147
148 fn wants_read(&self) -> bool {
149 self.inner.wants_read()
150 }
151
152 fn read_tls<'a, 'm>(
153 &'a mut self,
154 input: &'m mut dyn TlsInputBuffer,
155 tls: &'a mut Vec<u8>,
156 ) -> MessageHandler<'a, 'm, ServerSide> {
157 self.inner.read_tls(input, tls)
158 }
159
160 fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
161 self.inner.exporter()
162 }
163
164 fn dangerous_extract_secrets(self) -> Result<ExtractedSecrets, Error> {
165 self.inner.dangerous_extract_secrets()
166 }
167
168 fn refresh_traffic_keys(&mut self, tls: &mut Vec<u8>) -> Result<(), Error> {
169 self.inner.refresh_traffic_keys(tls)
170 }
171
172 fn send_close_notify(&mut self, tls: &mut Vec<u8>) {
173 self.inner.send_close_notify(tls);
174 }
175
176 fn is_handshaking(&self) -> bool {
177 self.inner.is_handshaking()
178 }
179
180 fn fips(&self) -> FipsStatus {
181 self.inner.fips
182 }
183}
184
185impl Deref for ServerConnection {
186 type Target = ConnectionOutputs;
187
188 fn deref(&self) -> &Self::Target {
189 &self.inner
190 }
191}
192
193impl fmt::Debug for ServerConnection {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 f.debug_struct("ServerConnection")
196 .finish_non_exhaustive()
197 }
198}
199
200impl ConnectionCommon<ServerSide> {
201 pub(crate) fn for_server(
202 config: Arc<ServerConfig>,
203 extra_exts: ServerExtensionsInput,
204 protocol: Protocol,
205 ) -> Result<Self, Error> {
206 let mut common = CommonState::new(Side::Server, config.fips());
207 common
208 .send
209 .set_max_fragment_size(config.max_fragment_size)?;
210 Ok(Self::new(
211 Box::new(ExpectClientHello::new(
212 config,
213 extra_exts,
214 Vec::new(),
215 protocol,
216 ))
217 .into(),
218 ServerConnectionData::default(),
219 common,
220 ))
221 }
222
223 pub(crate) fn for_acceptor(protocol: Protocol) -> Self {
224 Self::new(
225 ReadClientHello::new(protocol).into(),
226 ServerConnectionData::default(),
227 CommonState::new(Side::Server, FipsStatus::Unvalidated),
228 )
229 }
230}
231
232#[non_exhaustive]
234#[derive(Debug)]
235pub enum ServerHandshake {
236 NeedsInput(NeedsInput<ServerSide>),
238
239 Accepted(Accepted),
244
245 VerifyClientIdentity(VerifyPeerIdentity<ServerSide>),
249
250 Complete(SplitConnection<ServerSide>),
254}
255
256impl ServerHandshake {
257 pub fn start() -> NeedsInput<ServerSide> {
267 NeedsInput {
268 inner: ConnectionCommon::for_acceptor(Protocol::Tcp),
269 }
270 }
271}
272
273impl TryFrom<ConnectionCommon<ServerSide>> for ServerHandshake {
274 type Error = Error;
275
276 fn try_from(mut inner: ConnectionCommon<ServerSide>) -> Result<Self, Error> {
277 const MISUSED: Error = Error::Unreachable("forgot to restore state");
278
279 Ok(match mem::replace(&mut inner.state, Err(MISUSED))? {
280 ServerState::ChooseConfig(choose_config) => Self::Accepted(Accepted {
281 inner,
282 choose_config,
283 }),
284
285 ServerState::VerifyClientIdentity(verify_identity) => {
286 Self::VerifyClientIdentity(VerifyPeerIdentity {
287 inner,
288 verify_identity,
289 })
290 }
291
292 state if state.is_traffic() => {
293 inner.state = Ok(state);
294 Self::Complete(SplitConnection::try_from(inner)?)
295 }
296
297 state => {
298 inner.state = Ok(state);
299 Self::NeedsInput(NeedsInput { inner })
300 }
301 })
302 }
303}
304
305pub struct Accepted {
310 inner: ConnectionCommon<ServerSide>,
312 choose_config: Box<ChooseConfig>,
313}
314
315impl Accepted {
316 pub fn client_hello(&self) -> ClientHello<'_> {
318 let ch = self.choose_config.client_hello();
319 trace!("Accepted::client_hello(): {ch:#?}");
320 ch
321 }
322
323 pub fn choose_config(
330 mut self,
331 config: Arc<ServerConfig>,
332 tls: &mut Vec<u8>,
333 ) -> Result<ServerHandshake, Error> {
334 let result = self.inner.accepted(
335 self.choose_config,
336 ServerExtensionsInput::default(),
337 None,
338 config,
339 tls,
340 );
341
342 let send_path = &mut self.inner.common.send;
343
344 if let Err(err) = &result {
345 maybe_send_fatal_alert(send_path, err, tls);
346 }
347
348 result?;
349
350 Ok(ServerHandshake::NeedsInput(NeedsInput {
351 inner: self.inner,
352 }))
353 }
354}
355
356impl fmt::Debug for Accepted {
357 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358 f.debug_struct("Accepted")
359 .finish_non_exhaustive()
360 }
361}
362
363#[expect(clippy::exhaustive_structs)]
365#[derive(Debug)]
366pub struct ServerSide;
367
368impl SideData for ServerSide {
369 type Handshake = ServerHandshake;
370
371 type PeerIdentity<'a> = ClientIdentity<'static, 'a>;
372
373 #[expect(private_interfaces)]
374 fn handshake_from_inner(common: ConnectionCommon<Self>) -> Result<Self::Handshake, Error> {
375 ServerHandshake::try_from(common)
376 }
377}
378
379impl crate::conn::private::Side for ServerSide {
380 type Data = ServerConnectionData;
381 type State = ServerState;
382}
383
384#[derive(Default)]
386pub(crate) struct ServerConnectionData {
387 sni: Option<DnsName<'static>>,
388 received_resumption_data: Option<Vec<u8>>,
389 early_data: EarlyDataState,
390}
391
392impl ServerConnectionData {
393 pub(crate) fn received_resumption_data(&self) -> Option<&[u8]> {
394 self.received_resumption_data.as_deref()
395 }
396
397 pub(crate) fn server_name(&self) -> Option<&DnsName<'static>> {
398 self.sni.as_ref()
399 }
400}
401
402impl SideOutput for ServerConnectionData {
403 fn emit(&mut self, ev: Event) {
404 match ev {
405 Event::EarlyData(EarlyDataEvent::Accepted) => self.early_data.accept(),
406 Event::ReceivedServerName(sni) => self.sni = sni,
407 Event::ResumptionData(data) => self.received_resumption_data = Some(data),
408 _ => unreachable!(),
409 }
410 }
411}
412
413pub struct ReadEarlyData<'a> {
420 common: &'a mut ConnectionCommon<ServerSide>,
421}
422
423impl<'a> ReadEarlyData<'a> {
424 fn new(common: &'a mut ConnectionCommon<ServerSide>) -> Self {
425 ReadEarlyData { common }
426 }
427
428 pub fn exporter(&mut self) -> Result<KeyingMaterialExporter, Error> {
448 self.common.common.early_exporter()
449 }
450}
451
452#[derive(Default)]
453pub(super) enum EarlyDataState {
454 #[default]
455 New,
456 Accepted,
457}
458
459impl EarlyDataState {
460 fn accept(&mut self) {
461 *self = Self::Accepted;
462 }
463
464 fn was_accepted(&self) -> bool {
465 matches!(self, Self::Accepted)
466 }
467}