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 pub struct ServerConnection {
71 pub(super) inner: ConnectionCommon<ServerConnectionData>,
72 }
73
74 impl ServerConnection {
75 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 pub fn server_name(&self) -> Option<&DnsName<'_>> {
103 self.inner.core.side.server_name()
104 }
105
106 pub fn received_resumption_data(&self) -> Option<&[u8]> {
112 self.inner
113 .core
114 .side
115 .received_resumption_data()
116 }
117
118 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 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 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 pub struct Acceptor {
239 inner: Option<ConnectionCommon<ServerConnectionData>>,
240 }
241
242 impl Default for Acceptor {
243 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 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 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 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 pub fn write(&mut self, wr: &mut dyn io::Write) -> Result<usize, io::Error> {
340 self.0.write_to(wr)
341 }
342
343 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 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 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
410pub struct UnbufferedServerConnection {
414 inner: UnbufferedConnectionCommon<ServerConnectionData>,
415}
416
417impl UnbufferedServerConnection {
418 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 #[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 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#[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 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 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 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#[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 #[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}