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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use std::fmt;
use std::marker::Unpin;
use crate::handshake::handshake;
use crate::runtime::{AsyncRead, AsyncReadExt, AsyncWrite};
use crate::TlsStream;
#[derive(Clone)]
pub struct TlsAcceptor(native_tls::TlsAcceptor);
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("NativeTls({})", 0)]
NativeTls(#[from] native_tls::Error),
#[error("Io({})", 0)]
Io(#[from] std::io::Error),
}
impl TlsAcceptor {
pub async fn new<R, S>(mut file: R, password: S) -> Result<Self, Error>
where
R: AsyncRead + Unpin,
S: AsRef<str>,
{
let mut identity = vec![];
file.read_to_end(&mut identity).await?;
let identity = native_tls::Identity::from_pkcs12(&identity, password.as_ref())?;
Ok(TlsAcceptor(native_tls::TlsAcceptor::new(identity)?))
}
pub async fn accept<S>(&self, stream: S) -> Result<TlsStream<S>, native_tls::Error>
where
S: AsyncRead + AsyncWrite + Unpin,
{
let stream = handshake(move |s| self.0.accept(s), stream).await?;
Ok(stream)
}
}
impl fmt::Debug for TlsAcceptor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TlsAcceptor").finish()
}
}
impl From<native_tls::TlsAcceptor> for TlsAcceptor {
fn from(inner: native_tls::TlsAcceptor) -> TlsAcceptor {
TlsAcceptor(inner)
}
}
#[cfg(all(test, feature = "runtime-async-std"))]
mod tests {
use super::*;
use crate::runtime::AsyncWriteExt;
use crate::TlsConnector;
use async_std::fs::File;
use async_std::net::{TcpListener, TcpStream};
use async_std::stream::StreamExt;
#[async_std::test]
async fn test_acceptor() {
let key = File::open("tests/identity.pfx").await.unwrap();
let acceptor = TlsAcceptor::new(key, "hello").await.unwrap();
let listener = TcpListener::bind("127.0.0.1:8443").await.unwrap();
async_std::task::spawn(async move {
let mut incoming = listener.incoming();
while let Some(stream) = incoming.next().await {
let acceptor = acceptor.clone();
let stream = stream.unwrap();
async_std::task::spawn(async move {
let mut stream = acceptor.accept(stream).await.unwrap();
stream.write_all(b"hello").await.unwrap();
});
}
});
let stream = TcpStream::connect("127.0.01:8443").await.unwrap();
let connector = TlsConnector::new().danger_accept_invalid_certs(true);
let mut stream = connector.connect("127.0.0.1", stream).await.unwrap();
let mut res = Vec::new();
stream.read_to_end(&mut res).await.unwrap();
assert_eq!(res, b"hello");
}
}