coqui_peer_tls/
handshake.rs1use alloc::sync::Arc;
2use core::net::SocketAddr;
3use std::io::Cursor;
4
5use coqui_peer::{Established, Framing, Handshake, Method};
6use rustls::pki_types::ServerName;
7use rustls::{ClientConfig, ClientConnection, Connection, ServerConfig, ServerConnection};
8
9use crate::certificate::key_of_presented;
10use crate::error::PeerError;
11use crate::identity::PeerIdentity;
12use crate::source::scoped;
13use crate::stream::handshake_error;
14use crate::stream::{default_server_name, identity_of};
15
16#[derive(Debug, Clone, Default)]
27pub struct Tls {
28 client: Option<Arc<ClientConfig>>,
29 server: Option<Arc<ServerConfig>>,
30}
31
32impl Tls {
33 pub fn new() -> Self {
35 Self::default()
36 }
37
38 #[must_use]
40 pub fn client(mut self, config: Arc<ClientConfig>) -> Self {
41 self.client = Some(config);
42 self
43 }
44
45 #[must_use]
47 pub fn server(mut self, config: Arc<ServerConfig>) -> Self {
48 self.server = Some(config);
49 self
50 }
51}
52
53impl Method for Tls {
54 type Handshake = TlsHandshake;
55
56 fn name(&self) -> &'static str {
57 crate::METHOD
58 }
59
60 fn initiate(&self) -> Result<TlsHandshake, PeerError> {
61 let config = self.client.clone().ok_or(PeerError::Unsupported)?;
62 TlsHandshake::client(config)
63 }
64
65 fn respond(&self, source: Option<SocketAddr>) -> Result<TlsHandshake, PeerError> {
66 let config = self.server.clone().ok_or(PeerError::Unsupported)?;
67 TlsHandshake::server(config, source)
68 }
69}
70
71#[derive(Debug)]
78pub struct TlsHandshake {
79 connection: Connection,
80 source: Option<SocketAddr>,
81 local: Option<SocketAddr>,
82}
83
84impl TlsHandshake {
85 pub fn client(config: Arc<ClientConfig>) -> Result<Self, PeerError> {
92 Self::client_named(config, default_server_name())
93 }
94
95 pub fn client_named(
103 config: Arc<ClientConfig>,
104 name: ServerName<'static>,
105 ) -> Result<Self, PeerError> {
106 let connection = ClientConnection::new(config, name).map_err(|_| PeerError::Tls)?;
107 Ok(Self {
108 connection: connection.into(),
109 source: None,
110 local: None,
111 })
112 }
113
114 pub fn server(
120 config: Arc<ServerConfig>,
121 source: Option<SocketAddr>,
122 ) -> Result<Self, PeerError> {
123 let connection = ServerConnection::new(config).map_err(|_| PeerError::Tls)?;
124 Ok(Self {
125 connection: connection.into(),
126 source,
127 local: None,
128 })
129 }
130
131 #[must_use]
136 pub fn local(mut self, local: SocketAddr) -> Self {
137 self.local = Some(local);
138 self
139 }
140
141 pub fn finish_unauthenticated(self) -> Result<(Connection, Option<PeerIdentity>), PeerError> {
154 if self.connection.is_handshaking() {
155 return Err(PeerError::Tls);
156 }
157 let peer = match self.connection.peer_certificates() {
158 Some(certificates) if !certificates.is_empty() => {
159 Some(identity_of(Some(certificates))?)
160 }
161 _ => None,
162 };
163 Ok((self.connection, peer))
164 }
165}
166
167impl Handshake for TlsHandshake {
168 type Output = Connection;
169 type Error = PeerError;
170
171 fn framing(&self) -> Framing {
172 Framing::Stream
173 }
174
175 fn receive(&mut self, input: &[u8]) -> Result<(), PeerError> {
176 let mut cursor = Cursor::new(input);
177 while usize::try_from(cursor.position()).unwrap_or(usize::MAX) < input.len() {
178 let read = self
179 .connection
180 .read_tls(&mut cursor)
181 .map_err(PeerError::Io)?;
182 let (processed, refused) = scoped(self.source, self.local, || {
183 self.connection.process_new_packets().map(|_| ())
184 });
185 processed.map_err(|error| {
186 handshake_error(
187 std::io::Error::new(std::io::ErrorKind::InvalidData, error),
188 refused,
189 )
190 })?;
191 if read == 0 {
192 return Err(PeerError::Tls);
193 }
194 }
195 Ok(())
196 }
197
198 fn transmit(&mut self) -> Result<Option<Vec<u8>>, PeerError> {
199 if !self.connection.wants_write() {
200 return Ok(None);
201 }
202 let mut out = Vec::new();
203 self.connection.write_tls(&mut out).map_err(PeerError::Io)?;
204 Ok((!out.is_empty()).then_some(out))
205 }
206
207 fn is_complete(&self) -> bool {
208 !self.connection.is_handshaking()
209 }
210
211 fn finish(self) -> Result<Established<Connection>, PeerError> {
212 if self.connection.is_handshaking() {
213 return Err(PeerError::Tls);
214 }
215 let peer = identity_of(self.connection.peer_certificates())?;
216 Ok(Established {
217 peer: peer.fingerprint,
218 key: Some(key_of_presented(&peer.certificate)?),
219 session: self.connection,
220 })
221 }
222}