1#![deny(missing_docs)]
2#![allow(clippy::large_enum_variant, clippy::result_large_err)]
3
4use cfg_if::cfg_if;
56use std::{
57 convert::TryFrom,
58 error::Error,
59 fmt,
60 io::{self, IoSlice, IoSliceMut, Read, Write},
61 net::{TcpStream as StdTcpStream, ToSocketAddrs},
62 ops::{Deref, DerefMut},
63 time::Duration,
64};
65
66#[cfg(feature = "rustls")]
67mod rustls_impl;
68#[cfg(feature = "rustls")]
69pub use rustls_impl::*;
70
71#[cfg(feature = "native-tls")]
72mod native_tls_impl;
73#[cfg(feature = "native-tls")]
74pub use native_tls_impl::*;
75
76#[cfg(feature = "openssl")]
77mod openssl_impl;
78#[cfg(feature = "openssl")]
79pub use openssl_impl::*;
80
81#[cfg(feature = "futures")]
82mod futures;
83#[cfg(feature = "futures")]
84pub use futures::*;
85
86#[non_exhaustive]
88pub enum TcpStream {
89 Plain(StdTcpStream),
91 #[cfg(feature = "native-tls")]
92 NativeTls(NativeTlsStream),
94 #[cfg(feature = "openssl")]
95 Openssl(OpensslStream),
97 #[cfg(feature = "rustls")]
98 Rustls(RustlsStream),
100}
101
102#[derive(Default, Debug, PartialEq)]
104pub struct TLSConfig<'data, 'key, 'chain> {
105 pub identity: Option<Identity<'data, 'key>>,
107 pub cert_chain: Option<&'chain str>,
109}
110
111#[derive(Default, Debug, PartialEq)]
113pub struct OwnedTLSConfig {
114 pub identity: Option<OwnedIdentity>,
116 pub cert_chain: Option<String>,
118}
119
120impl OwnedTLSConfig {
121 #[must_use]
123 pub fn as_ref(&self) -> TLSConfig<'_, '_, '_> {
124 TLSConfig {
125 identity: self.identity.as_ref().map(OwnedIdentity::as_ref),
126 cert_chain: self.cert_chain.as_deref(),
127 }
128 }
129}
130
131#[derive(Debug, PartialEq)]
135pub enum Identity<'data, 'key> {
136 PKCS12 {
138 der: &'data [u8],
140 password: &'key str,
142 },
143 PKCS8 {
145 pem: &'data [u8],
147 key: &'key [u8],
149 },
150}
151
152#[derive(Debug, PartialEq)]
156pub enum OwnedIdentity {
157 PKCS12 {
159 der: Vec<u8>,
161 password: String,
163 },
164 PKCS8 {
166 pem: Vec<u8>,
168 key: Vec<u8>,
170 },
171}
172
173impl OwnedIdentity {
174 #[must_use]
176 pub fn as_ref(&self) -> Identity<'_, '_> {
177 match self {
178 Self::PKCS8 { pem, key } => Identity::PKCS8 { pem, key },
179 Self::PKCS12 { der, password } => Identity::PKCS12 { der, password },
180 }
181 }
182}
183
184pub type HandshakeResult = Result<TcpStream, HandshakeError>;
186
187impl TcpStream {
188 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<Self> {
190 connect_std(addr, None).and_then(Self::try_from)
191 }
192
193 pub fn connect_timeout<A: ToSocketAddrs>(addr: A, timeout: Duration) -> io::Result<Self> {
195 connect_std(addr, Some(timeout)).and_then(Self::try_from)
196 }
197
198 pub fn from_std(stream: StdTcpStream) -> io::Result<Self> {
200 Self::try_from(stream)
201 }
202
203 pub fn is_readable(&self) -> io::Result<()> {
205 self.deref().read(&mut []).map(|_| ())
206 }
207
208 pub fn is_writable(&mut self) -> io::Result<()> {
210 is_writable(self.deref_mut())
211 }
212
213 pub fn try_connect(&mut self) -> io::Result<bool> {
218 try_connect(self)
219 }
220
221 pub fn into_tls(
223 self,
224 domain: &str,
225 config: TLSConfig<'_, '_, '_>,
226 ) -> Result<Self, HandshakeError> {
227 into_tls_impl(self, domain, config)
228 }
229
230 #[cfg(feature = "native-tls")]
231 pub fn into_native_tls(
233 self,
234 connector: &NativeTlsConnector,
235 domain: &str,
236 ) -> Result<Self, HandshakeError> {
237 Ok(connector.connect(domain, self.into_plain()?)?.into())
238 }
239
240 #[cfg(feature = "openssl")]
241 pub fn into_openssl(
243 self,
244 connector: &OpensslConnector,
245 domain: &str,
246 ) -> Result<Self, HandshakeError> {
247 Ok(connector.connect(domain, self.into_plain()?)?.into())
248 }
249
250 #[cfg(feature = "rustls")]
251 pub fn into_rustls(
253 self,
254 connector: &RustlsConnector,
255 domain: &str,
256 ) -> Result<Self, HandshakeError> {
257 Ok(connector.connect(domain, self.into_plain()?)?.into())
258 }
259
260 #[allow(irrefutable_let_patterns)]
261 fn into_plain(self) -> Result<StdTcpStream, io::Error> {
262 if let Self::Plain(plain) = self {
263 Ok(plain)
264 } else {
265 Err(io::Error::new(
266 io::ErrorKind::AlreadyExists,
267 "already a TLS stream",
268 ))
269 }
270 }
271}
272
273fn connect_std<A: ToSocketAddrs>(addr: A, timeout: Option<Duration>) -> io::Result<StdTcpStream> {
274 let stream = connect_std_raw(addr, timeout)?;
275 stream.set_nodelay(true)?;
276 Ok(stream)
277}
278
279fn connect_std_raw<A: ToSocketAddrs>(
280 addr: A,
281 timeout: Option<Duration>,
282) -> io::Result<StdTcpStream> {
283 if let Some(timeout) = timeout {
284 let addrs = addr.to_socket_addrs()?;
285 let mut err = None;
286 for addr in addrs {
287 match StdTcpStream::connect_timeout(&addr, timeout) {
288 Ok(stream) => return Ok(stream),
289 Err(error) => err = Some(error),
290 }
291 }
292 Err(err.unwrap_or_else(|| {
293 io::Error::new(io::ErrorKind::AddrNotAvailable, "couldn't resolve host")
294 }))
295 } else {
296 StdTcpStream::connect(addr)
297 }
298}
299
300fn try_connect(stream: &mut StdTcpStream) -> io::Result<bool> {
301 match is_writable(stream) {
302 Ok(()) => Ok(true),
303 Err(err)
304 if [io::ErrorKind::WouldBlock, io::ErrorKind::NotConnected].contains(&err.kind()) =>
305 {
306 Ok(false)
307 }
308 Err(err) => Err(err),
309 }
310}
311
312fn is_writable(stream: &mut StdTcpStream) -> io::Result<()> {
313 stream.write(&[]).map(|_| ())
314}
315
316fn into_tls_impl(s: TcpStream, domain: &str, config: TLSConfig<'_, '_, '_>) -> HandshakeResult {
317 cfg_if! {
318 if #[cfg(feature = "rustls-native-certs")] {
319 into_rustls_impl(s, RustlsConnectorConfig::new_with_native_certs()?, domain, config)
320 } else if #[cfg(feature = "rustls-webpki-roots-certs")] {
321 into_rustls_impl(s, RustlsConnectorConfig::new_with_webpki_roots_certs(), domain, config)
322 } else if #[cfg(feature = "rustls")] {
323 into_rustls_impl(s, RustlsConnectorConfig::default(), domain, config)
324 } else if #[cfg(feature = "openssl")] {
325 into_openssl_impl(s, domain, config)
326 } else if #[cfg(feature = "native-tls")] {
327 into_native_tls_impl(s, domain, config)
328 } else {
329 let _ = (domain, config);
330 Ok(TcpStream::Plain(s.into_plain()?))
331 }
332 }
333}
334
335impl TryFrom<StdTcpStream> for TcpStream {
336 type Error = io::Error;
337
338 fn try_from(s: StdTcpStream) -> io::Result<Self> {
339 let mut this = Self::Plain(s);
340 this.try_connect()?;
341 Ok(this)
342 }
343}
344
345impl Deref for TcpStream {
346 type Target = StdTcpStream;
347
348 fn deref(&self) -> &Self::Target {
349 match self {
350 Self::Plain(plain) => plain,
351 #[cfg(feature = "native-tls")]
352 Self::NativeTls(tls) => tls.get_ref(),
353 #[cfg(feature = "openssl")]
354 Self::Openssl(tls) => tls.get_ref(),
355 #[cfg(feature = "rustls")]
356 Self::Rustls(tls) => tls.get_ref(),
357 }
358 }
359}
360
361impl DerefMut for TcpStream {
362 fn deref_mut(&mut self) -> &mut Self::Target {
363 match self {
364 Self::Plain(plain) => plain,
365 #[cfg(feature = "native-tls")]
366 Self::NativeTls(tls) => tls.get_mut(),
367 #[cfg(feature = "openssl")]
368 Self::Openssl(tls) => tls.get_mut(),
369 #[cfg(feature = "rustls")]
370 Self::Rustls(tls) => tls.get_mut(),
371 }
372 }
373}
374
375macro_rules! fwd_impl {
376 ($self:ident, $method:ident, $($args:expr),*) => {
377 match $self {
378 Self::Plain(plain) => plain.$method($($args),*),
379 #[cfg(feature = "native-tls")]
380 Self::NativeTls(tls) => tls.$method($($args),*),
381 #[cfg(feature = "openssl")]
382 Self::Openssl(tls) => tls.$method($($args),*),
383 #[cfg(feature = "rustls")]
384 Self::Rustls(tls) => tls.$method($($args),*),
385 }
386 };
387}
388
389impl Read for TcpStream {
390 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
391 fwd_impl!(self, read, buf)
392 }
393
394 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
395 fwd_impl!(self, read_vectored, bufs)
396 }
397
398 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
399 fwd_impl!(self, read_to_end, buf)
400 }
401
402 fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
403 fwd_impl!(self, read_to_string, buf)
404 }
405
406 fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
407 fwd_impl!(self, read_exact, buf)
408 }
409}
410
411impl Write for TcpStream {
412 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
413 fwd_impl!(self, write, buf)
414 }
415
416 fn flush(&mut self) -> io::Result<()> {
417 fwd_impl!(self, flush,)
418 }
419
420 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
421 fwd_impl!(self, write_vectored, bufs)
422 }
423
424 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
425 fwd_impl!(self, write_all, buf)
426 }
427
428 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> {
429 fwd_impl!(self, write_fmt, fmt)
430 }
431}
432
433impl fmt::Debug for TcpStream {
434 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
435 f.debug_struct("TcpStream")
436 .field("inner", self.deref())
437 .finish()
438 }
439}
440
441#[derive(Debug)]
443pub enum MidHandshakeTlsStream {
444 Plain(TcpStream),
446 #[cfg(feature = "native-tls")]
447 NativeTls(NativeTlsMidHandshakeTlsStream),
449 #[cfg(feature = "openssl")]
450 Openssl(OpensslMidHandshakeTlsStream),
452 #[cfg(feature = "rustls")]
453 Rustls(RustlsMidHandshakeTlsStream),
455}
456
457impl MidHandshakeTlsStream {
458 #[must_use]
460 pub fn get_ref(&self) -> &StdTcpStream {
461 match self {
462 Self::Plain(mid) => mid,
463 #[cfg(feature = "native-tls")]
464 Self::NativeTls(mid) => mid.get_ref(),
465 #[cfg(feature = "openssl")]
466 Self::Openssl(mid) => mid.get_ref(),
467 #[cfg(feature = "rustls")]
468 Self::Rustls(mid) => mid.get_ref(),
469 }
470 }
471
472 #[must_use]
474 pub fn get_mut(&mut self) -> &mut StdTcpStream {
475 match self {
476 Self::Plain(mid) => mid,
477 #[cfg(feature = "native-tls")]
478 Self::NativeTls(mid) => mid.get_mut(),
479 #[cfg(feature = "openssl")]
480 Self::Openssl(mid) => mid.get_mut(),
481 #[cfg(feature = "rustls")]
482 Self::Rustls(mid) => mid.get_mut(),
483 }
484 }
485
486 pub fn handshake(mut self) -> HandshakeResult {
488 if !try_connect(self.get_mut())? {
489 return Err(HandshakeError::WouldBlock(self));
490 }
491
492 Ok(match self {
493 Self::Plain(mid) => mid,
494 #[cfg(feature = "native-tls")]
495 Self::NativeTls(mid) => mid.handshake()?.into(),
496 #[cfg(feature = "openssl")]
497 Self::Openssl(mid) => mid.handshake()?.into(),
498 #[cfg(feature = "rustls")]
499 Self::Rustls(mid) => mid.handshake()?.into(),
500 })
501 }
502}
503
504impl From<TcpStream> for MidHandshakeTlsStream {
505 fn from(mid: TcpStream) -> Self {
506 Self::Plain(mid)
507 }
508}
509
510impl fmt::Display for MidHandshakeTlsStream {
511 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512 f.write_str("MidHandshakeTlsStream")
513 }
514}
515
516#[derive(Debug)]
518pub enum HandshakeError {
519 WouldBlock(MidHandshakeTlsStream),
521 Failure(io::Error),
523}
524
525impl HandshakeError {
526 pub fn into_mid_handshake_tls_stream(self) -> io::Result<MidHandshakeTlsStream> {
528 match self {
529 Self::WouldBlock(mid) => Ok(mid),
530 Self::Failure(error) => Err(error),
531 }
532 }
533}
534
535impl fmt::Display for HandshakeError {
536 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
537 match self {
538 Self::WouldBlock(_) => f.write_str("WouldBlock hit during handshake"),
539 Self::Failure(err) => f.write_fmt(format_args!("IO error: {err}")),
540 }
541 }
542}
543
544impl Error for HandshakeError {
545 fn source(&self) -> Option<&(dyn Error + 'static)> {
546 match self {
547 Self::Failure(err) => Some(err),
548 _ => None,
549 }
550 }
551}
552
553impl From<io::Error> for HandshakeError {
554 fn from(err: io::Error) -> Self {
555 Self::Failure(err)
556 }
557}
558
559mod sys;