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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
use http;
use http::Uri;
use crate::{errors::WsError, protocol::Mode};

/// get websocket scheme
pub fn get_scheme(uri: &http::Uri) -> Result<Mode, WsError> {
    match uri.scheme_str().unwrap_or("ws").to_lowercase().as_str() {
        "ws" => Ok(Mode::WS),
        "wss" => Ok(Mode::WSS),
        s => Err(WsError::InvalidUri(format!("unknown scheme {s}"))),
    }
}

/// get host from uri
pub fn get_host(uri: &Uri) -> Result<&str, WsError> {
    uri.host()
        .ok_or_else(|| WsError::InvalidUri(format!("can not find host {}", uri)))
}

#[cfg(feature = "sync")]
mod blocking {
    use crate::errors::WsError;
    use http;
    use std::net::TcpStream;

    use super::{get_host, get_scheme};

    /// performance tcp connection
    pub fn tcp_connect(uri: &http::Uri) -> Result<TcpStream, WsError> {
        let mode = get_scheme(uri)?;
        let host = get_host(uri)?;
        let port = uri.port_u16().unwrap_or_else(|| mode.default_port());
        let stream = TcpStream::connect((host, port)).map_err(|e| {
            WsError::ConnectionFailed(format!("failed to create tcp connection {e}"))
        })?;
        Ok(stream)
    }

    // #[cfg(feature = "sync_tls_rustls")]
    // impl<S: std::io::Read + std::io::Write> crate::codec::Split for rustls_connector::TlsStream<S> {
    //     type R = tokio::io::ReadHalf<BufStream<S>>;
    //     type W = tokio::io::WriteHalf<BufStream<S>>;
    //     fn split(self) -> (Self::R, Self::W) {
    //         tokio::io::split(self)
    //     }
    // }

    #[cfg(feature = "sync_tls_rustls")]
    /// start tls session
    pub fn wrap_rustls<
        S: std::io::Read + std::io::Write + Sync + Send + std::fmt::Debug + 'static,
    >(
        stream: S,
        host: &str,
        certs: Vec<std::path::PathBuf>,
    ) -> Result<rustls_connector::TlsStream<S>, WsError> {
        use std::io::BufReader;

        let mut config = rustls_connector::RustlsConnectorConfig::new_with_webpki_roots_certs();
        let mut cert_data = vec![];
        for cert_path in certs.iter() {
            let mut pem = std::fs::File::open(cert_path).map_err(|_| {
                WsError::CertFileNotFound(cert_path.to_str().unwrap_or_default().to_string())
            })?;
            let mut cert = BufReader::new(&mut pem);
            let certs = rustls_pemfile::certs(&mut cert)
                .map_err(|e| WsError::LoadCertFailed(e.to_string()))?;
            cert_data.extend_from_slice(&certs);
        }
        config.add_parsable_certificates(&cert_data);
        let connector = config.connector_with_no_client_auth();
        let tls_stream = connector
            .connect(host, stream)
            .map_err(|e| WsError::ConnectionFailed(e.to_string()))?;
        tracing::debug!("tls connection established");
        Ok(tls_stream)
    }

    // #[cfg(feature = "sync_tls_native")]
    // impl<S: std::io::Read + std::io::Write> crate::codec::Split for rustls_connector::TlsStream<S> {
    //     type R = tokio::io::ReadHalf<BufStream<S>>;
    //     type W = tokio::io::WriteHalf<BufStream<S>>;
    //     fn split(self) -> (Self::R, Self::W) {
    //         tokio::io::split(self)
    //     }
    // }

    #[cfg(feature = "sync_tls_native")]
    /// start tls session
    pub fn wrap_native_tls<S: std::io::Read + std::io::Write>(
        stream: S,
        host: &str,
        certs: Vec<std::path::PathBuf>,
    ) -> Result<native_tls::TlsStream<S>, WsError> {
        let mut builder = native_tls::TlsConnector::builder();
        for cert_path in certs.iter() {
            let mut pem = std::fs::File::open(cert_path).map_err(|_| {
                WsError::CertFileNotFound(cert_path.to_str().unwrap_or_default().to_string())
            })?;
            let mut data = vec![];
            if let Err(e) = std::io::Read::read_to_end(&mut pem, &mut data) {
                tracing::error!(
                    "failed to read cert file {} {}",
                    cert_path.display(),
                    e.to_string()
                );
                continue;
            }
            match native_tls::Certificate::from_der(&data) {
                Ok(cert) => {
                    builder.add_root_certificate(cert);
                }
                Err(e) => {
                    tracing::error!(
                        "invalid cert file {} {}",
                        cert_path.display(),
                        e.to_string()
                    );
                    continue;
                }
            }
        }
        let connector = builder.build().unwrap();
        let tls_stream = connector
            .connect(host, stream)
            .map_err(|_| WsError::ConnectionFailed("tls connect failed".into()))?;
        tracing::debug!("tls connection established");
        Ok(tls_stream)
    }
}

#[cfg(feature = "sync")]
pub use blocking::*;

#[cfg(feature = "async")]
mod non_blocking {
    use http::Uri;
    use tokio::net::TcpStream;

    use crate::errors::WsError;

    use super::{get_host, get_scheme};

    /// performance tcp connection
    pub async fn async_tcp_connect(uri: &Uri) -> Result<TcpStream, WsError> {
        let mode = get_scheme(uri)?;
        let host = get_host(uri)?;
        let port = uri.port_u16().unwrap_or_else(|| mode.default_port());

        TcpStream::connect((host, port))
            .await
            .map_err(|e| WsError::ConnectionFailed(format!("failed to create tcp connection {e}")))
    }

    #[cfg(feature = "async_tls_rustls")]
    impl<S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin> crate::codec::Split
        for tokio_rustls::client::TlsStream<S>
    {
        type R = tokio::io::ReadHalf<tokio_rustls::client::TlsStream<S>>;
        type W = tokio::io::WriteHalf<tokio_rustls::client::TlsStream<S>>;
        fn split(self) -> (Self::R, Self::W) {
            tokio::io::split(self)
        }
    }

    #[cfg(feature = "async_tls_rustls")]
    impl<S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin> crate::codec::Split
        for tokio_rustls::server::TlsStream<S>
    {
        type R = tokio::io::ReadHalf<tokio_rustls::server::TlsStream<S>>;
        type W = tokio::io::WriteHalf<tokio_rustls::server::TlsStream<S>>;
        fn split(self) -> (Self::R, Self::W) {
            tokio::io::split(self)
        }
    }

    #[cfg(feature = "async_tls_rustls")]
    /// async version of starting tls session
    pub async fn async_wrap_rustls<S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin>(
        stream: S,
        host: &str,
        certs: Vec<std::path::PathBuf>,
    ) -> Result<tokio_rustls::client::TlsStream<S>, WsError> {
        use std::io::BufReader;

        let mut root_store = rustls_connector::rustls::RootCertStore::empty();
        root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(|ta| {
            rustls_connector::rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
                ta.subject,
                ta.spki,
                ta.name_constraints,
            )
        }));
        let mut trust_anchors = vec![];
        for cert_path in certs.iter() {
            let mut pem = std::fs::File::open(cert_path).map_err(|_| {
                WsError::CertFileNotFound(cert_path.to_str().unwrap_or_default().to_string())
            })?;
            let mut cert = BufReader::new(&mut pem);
            let certs = rustls_pemfile::certs(&mut cert)
                .map_err(|e| WsError::LoadCertFailed(e.to_string()))?;
            for item in certs {
                let ta = webpki::TrustAnchor::try_from_cert_der(&item[..])
                    .map_err(|e| WsError::LoadCertFailed(e.to_string()))?;
                let anchor =
                    rustls_connector::rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
                        ta.subject,
                        ta.spki,
                        ta.name_constraints,
                    );
                trust_anchors.push(anchor);
            }
        }
        root_store.add_server_trust_anchors(trust_anchors.into_iter());
        let config = rustls_connector::rustls::ClientConfig::builder()
            .with_safe_defaults()
            .with_root_certificates(root_store)
            .with_no_client_auth();
        let domain = tokio_rustls::rustls::ServerName::try_from(host)
            .map_err(|e| WsError::TlsDnsFailed(e.to_string()))?;
        let connector = tokio_rustls::TlsConnector::from(std::sync::Arc::new(config));
        let tls_stream = connector
            .connect(domain, stream)
            .await
            .map_err(|e| WsError::ConnectionFailed(e.to_string()))?;
        tracing::debug!("tls connection established");
        Ok(tls_stream)
    }

    #[cfg(feature = "async_tls_native")]
    impl<S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin> crate::codec::Split
        for tokio_native_tls::TlsStream<S>
    {
        type R = tokio::io::ReadHalf<tokio_native_tls::TlsStream<S>>;
        type W = tokio::io::WriteHalf<tokio_native_tls::TlsStream<S>>;
        fn split(self) -> (Self::R, Self::W) {
            tokio::io::split(self)
        }
    }

    #[cfg(feature = "async_tls_native")]
    /// start tls session
    pub async fn async_wrap_native_tls<S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin>(
        stream: S,
        host: &str,
        certs: Vec<std::path::PathBuf>,
    ) -> Result<tokio_native_tls::TlsStream<S>, WsError> {
        let mut builder = native_tls::TlsConnector::builder();
        for cert_path in certs.iter() {
            let mut pem = std::fs::File::open(cert_path).map_err(|_| {
                WsError::CertFileNotFound(cert_path.to_str().unwrap_or_default().to_string())
            })?;
            let mut data = vec![];
            if let Err(e) = std::io::Read::read_to_end(&mut pem, &mut data) {
                tracing::error!(
                    "failed to read cert file {} {}",
                    cert_path.display(),
                    e.to_string()
                );
                continue;
            }
            match native_tls::Certificate::from_der(&data) {
                Ok(cert) => {
                    builder.add_root_certificate(cert);
                }
                Err(e) => {
                    tracing::error!(
                        "invalid cert file {} {}",
                        cert_path.display(),
                        e.to_string()
                    );
                    continue;
                }
            }
        }
        let connector = builder.build().unwrap();
        let connector = tokio_native_tls::TlsConnector::from(connector);
        let tls_stream = connector
            .connect(host, stream)
            .await
            .map_err(|e| WsError::ConnectionFailed(e.to_string()))?;
        tracing::debug!("tls connection established");
        Ok(tls_stream)
    }
}

#[cfg(feature = "async")]
pub use non_blocking::*;