-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtls.rs
More file actions
64 lines (56 loc) · 1.75 KB
/
tls.rs
File metadata and controls
64 lines (56 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use native_tls::{TlsConnector, TlsStream};
use std::net::TcpStream;
use std::io::{self, Result};
use std::time::Duration;
pub(crate) enum MaybeTlsStream {
Tls(TlsStream<TcpStream>),
Plain(TcpStream),
}
impl MaybeTlsStream {
pub(crate) fn try_wrap_tls(plain: TcpStream, sni: &str) -> Result<MaybeTlsStream> {
let connector = TlsConnector::new().unwrap();
let stream = connector.connect(sni, plain).map_err(|_| io::Error::from(io::ErrorKind::Other))?;
Ok(Self::Tls(stream))
}
#[inline]
pub(crate) fn wrap_plain(plain: TcpStream) -> MaybeTlsStream {
Self::Plain(plain)
}
pub(crate) fn set_read_timeout(&self, dur: Option<Duration>) -> Result<()> {
match self {
Self::Tls(inner) => inner.get_ref().set_read_timeout(dur),
Self::Plain(inner) => inner.set_read_timeout(dur),
}
}
pub(crate) fn clone_plain_handle(&self) -> Result<TcpStream> {
match self {
Self::Tls(inner) => inner.get_ref().try_clone(),
Self::Plain(inner) => inner.try_clone(),
}
}
}
impl io::Read for MaybeTlsStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
match self {
Self::Tls(inner) => inner.read(buf),
Self::Plain(inner) => inner.read(buf),
}
}
}
impl io::Write for MaybeTlsStream {
#[inline]
fn write(&mut self, buf: &[u8]) -> Result<usize> {
match self {
Self::Tls(inner) => inner.write(buf),
Self::Plain(inner) => inner.write(buf),
}
}
#[inline]
fn flush(&mut self) -> Result<()> {
match self {
Self::Tls(inner) => inner.flush(),
Self::Plain(inner) => inner.flush(),
}
}
}