1use alloc::sync::Arc;
2use core::net::SocketAddr;
3use core::time::Duration;
4use std::io::{self, Read, Write};
5use std::net::TcpStream;
6
7use rustls::pki_types::{CertificateDer, ServerName};
8use rustls::{ClientConfig, ClientConnection, ServerConfig, ServerConnection, StreamOwned};
9
10use crate::error::{PeerError, Refusal};
11use crate::identity::PeerIdentity;
12use crate::source::scoped;
13use coqui_peer::{PeerId, ReadTimeout, WriteTimeout};
14
15pub const SERVER_NAME: &str = "coqui-peer.invalid";
20
21pub fn default_server_name() -> ServerName<'static> {
24 ServerName::try_from(SERVER_NAME).expect("SERVER_NAME is a valid DNS name")
25}
26
27pub(crate) fn identity_of(
28 certificates: Option<&[CertificateDer<'static>]>,
29) -> Result<PeerIdentity, PeerError> {
30 let certificate = certificates
31 .and_then(<[_]>::first)
32 .ok_or(PeerError::Certificate)?;
33 Ok(PeerIdentity {
34 fingerprint: PeerId::of(certificate.as_ref()),
35 certificate: certificate.as_ref().to_vec(),
36 })
37}
38
39pub fn dial<S: Read + Write>(
49 config: Arc<ClientConfig>,
50 io: S,
51) -> Result<(StreamOwned<ClientConnection, S>, PeerIdentity), PeerError> {
52 dial_named(config, default_server_name(), io)
53}
54
55pub fn dial_named<S: Read + Write>(
67 config: Arc<ClientConfig>,
68 name: ServerName<'static>,
69 mut io: S,
70) -> Result<(StreamOwned<ClientConnection, S>, PeerIdentity), PeerError> {
71 let mut connection = ClientConnection::new(config, name).map_err(|_| PeerError::Tls)?;
72 while connection.is_handshaking() {
73 connection.complete_io(&mut io).map_err(PeerError::Io)?;
74 }
75 let peer = identity_of(connection.peer_certificates())?;
76 Ok((StreamOwned::new(connection, io), peer))
77}
78
79pub trait PeerAddr {
84 fn peer_addr(&self) -> Option<SocketAddr>;
86
87 fn local_addr(&self) -> Option<SocketAddr> {
90 None
91 }
92}
93
94impl PeerAddr for TcpStream {
95 fn peer_addr(&self) -> Option<SocketAddr> {
96 TcpStream::peer_addr(self).ok()
97 }
98
99 fn local_addr(&self) -> Option<SocketAddr> {
100 TcpStream::local_addr(self).ok()
101 }
102}
103
104#[derive(Debug)]
113pub struct Addressed<S> {
114 io: S,
115 source: SocketAddr,
116 local: Option<SocketAddr>,
117}
118
119impl<S> Addressed<S> {
120 pub fn new(io: S, source: SocketAddr) -> Self {
122 Self {
123 io,
124 source,
125 local: None,
126 }
127 }
128
129 pub fn local(mut self, local: SocketAddr) -> Self {
132 self.local = Some(local);
133 self
134 }
135
136 pub fn get_ref(&self) -> &S {
138 &self.io
139 }
140
141 pub fn get_mut(&mut self) -> &mut S {
143 &mut self.io
144 }
145
146 pub fn into_inner(self) -> S {
148 self.io
149 }
150}
151
152impl<S> PeerAddr for Addressed<S> {
153 fn peer_addr(&self) -> Option<SocketAddr> {
154 Some(self.source)
155 }
156
157 fn local_addr(&self) -> Option<SocketAddr> {
158 self.local
159 }
160}
161
162impl<S: Read> Read for Addressed<S> {
163 fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
164 self.io.read(buffer)
165 }
166}
167
168impl<S: Write> Write for Addressed<S> {
169 fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
170 self.io.write(buffer)
171 }
172
173 fn flush(&mut self) -> io::Result<()> {
174 self.io.flush()
175 }
176}
177
178impl<S: ReadTimeout> ReadTimeout for Addressed<S> {
179 fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
180 self.io.set_read_timeout(timeout)
181 }
182}
183
184impl<S: WriteTimeout> WriteTimeout for Addressed<S> {
185 fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
186 self.io.set_write_timeout(timeout)
187 }
188}
189
190pub(crate) fn handshake_error(error: io::Error, refused: Option<Refusal>) -> PeerError {
193 match refused {
194 Some(refusal) => PeerError::Io(io::Error::new(
195 io::ErrorKind::PermissionDenied,
196 refusal.into_rustls(),
197 )),
198 None => PeerError::Io(error),
199 }
200}
201
202pub fn accept<S: Read + Write + PeerAddr>(
219 config: Arc<ServerConfig>,
220 io: S,
221) -> Result<(StreamOwned<ServerConnection, S>, PeerIdentity), PeerError> {
222 let (source, local) = (io.peer_addr(), io.local_addr());
223 accept_from_as(config, io, source, local)
224}
225
226pub(crate) fn accept_from_as<S: Read + Write>(
227 config: Arc<ServerConfig>,
228 mut io: S,
229 source: Option<SocketAddr>,
230 local: Option<SocketAddr>,
231) -> Result<(StreamOwned<ServerConnection, S>, PeerIdentity), PeerError> {
232 let mut connection = ServerConnection::new(config).map_err(|_| PeerError::Tls)?;
233 let (handshake, refused) = scoped(source, local, || {
234 while connection.is_handshaking() {
235 connection.complete_io(&mut io)?;
236 }
237 Ok::<(), io::Error>(())
238 });
239 handshake.map_err(|error| handshake_error(error, refused))?;
240 let peer = identity_of(connection.peer_certificates())?;
241 Ok((StreamOwned::new(connection, io), peer))
242}