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
#[cfg(feature = "tls")]
use crate::errors::new_io_error;
use crate::errors::Result;
use crate::proxy::{Proxy, ProxySocket};
use crate::socket::Socket;
#[cfg(feature = "tls")]
use native_tls::{Certificate, HandshakeError, Identity, TlsConnector};
use socket2::Socket as RawSocket;
use socket2::{Domain, Protocol, Type};
use std::net::SocketAddr;
use std::time::Duration;

/// ConnectorBuilder
#[derive(Clone)]
pub struct ConnectorBuilder {
  hostname_verification: bool,
  certs_verification: bool,
  read_timeout: Option<Duration>,
  write_timeout: Option<Duration>,
  connect_timeout: Option<Duration>,
  nodelay: bool,
  #[cfg(feature = "tls")]
  tls_sni: bool,
  #[cfg(feature = "tls")]
  identity: Option<Identity>,
  #[cfg(feature = "tls")]
  certificate: Vec<Certificate>,
  proxy: Option<Proxy>,
}

impl Default for ConnectorBuilder {
  fn default() -> Self {
    Self {
      hostname_verification: true,
      certs_verification: true,
      read_timeout: None,
      write_timeout: None,
      connect_timeout: None,
      nodelay: false,
      #[cfg(feature = "tls")]
      tls_sni: true,
      #[cfg(feature = "tls")]
      identity: None,
      #[cfg(feature = "tls")]
      certificate: vec![],
      proxy: None,
    }
  }
}
impl ConnectorBuilder {
  /// Controls the use of hostname verification.
  ///
  /// Defaults to `false`.
  ///
  /// # Warning
  ///
  /// You should think very carefully before using this method. If invalid hostnames are trusted, *any* valid
  /// certificate for *any* site will be trusted for use. This introduces significant vulnerabilities, and should
  /// only be used as a last resort.
  pub fn hostname_verification(mut self, value: bool) -> ConnectorBuilder {
    self.hostname_verification = value;
    self
  }
  /// Controls the use of certificate validation.
  ///
  /// Defaults to `false`.
  ///
  /// # Warning
  ///
  /// You should think very carefully before using this method. If invalid certificates are trusted, *any*
  /// certificate for *any* site will be trusted for use. This includes expired certificates. This introduces
  /// significant vulnerabilities, and should only be used as a last resort.
  pub fn certs_verification(mut self, value: bool) -> ConnectorBuilder {
    self.certs_verification = value;
    self
  }
  /// Set that all sockets have `SO_NODELAY` set to the supplied value `nodelay`.
  ///
  /// Default is `false`.
  pub fn nodelay(mut self, value: bool) -> ConnectorBuilder {
    self.nodelay = value;
    self
  }
  /// Controls the use of Server Name Indication (SNI).
  ///
  /// Defaults to `true`.
  #[cfg(feature = "tls")]
  pub fn tls_sni(mut self, value: bool) -> ConnectorBuilder {
    self.tls_sni = value;
    self
  }
  /// Adds a certificate to the set of roots that the connector will trust.
  #[cfg(feature = "tls")]
  pub fn certificate(mut self, value: Vec<Certificate>) -> ConnectorBuilder {
    self.certificate = value;
    self
  }
  /// Sets the identity to be used for client certificate authentication.
  #[cfg(feature = "tls")]
  pub fn identity(mut self, value: Identity) -> ConnectorBuilder {
    self.identity = Some(value);
    self
  }
  /// Enables a read timeout.
  ///
  /// The timeout applies to each read operation, and resets after a
  /// successful read. This is more appropriate for detecting stalled
  /// connections when the size isn't known beforehand.
  ///
  /// Default is no timeout.
  pub fn read_timeout(mut self, timeout: Option<Duration>) -> ConnectorBuilder {
    self.read_timeout = timeout;
    self
  }
  /// Enables a write timeout.
  ///
  /// The timeout applies to each read operation, and resets after a
  /// successful read. This is more appropriate for detecting stalled
  /// connections when the size isn't known beforehand.
  ///
  /// Default is no timeout.
  pub fn write_timeout(mut self, timeout: Option<Duration>) -> ConnectorBuilder {
    self.write_timeout = timeout;
    self
  }
  /// Set a timeout for only the connect phase of a `Client`.
  ///
  /// Default is `None`.
  ///
  /// # Note
  ///
  /// This **requires** the futures be executed in a tokio runtime with
  /// a tokio timer enabled.
  pub fn connect_timeout(mut self, timeout: Option<Duration>) -> ConnectorBuilder {
    self.connect_timeout = timeout;
    self
  }
  // Proxy options

  /// Add a `Proxy` to the list of proxies the `Client` will use.
  ///
  /// # Note
  ///
  /// Adding a proxy will disable the automatic usage of the "system" proxy.
  pub fn proxy(mut self, addr: Option<Proxy>) -> ConnectorBuilder {
    self.proxy = addr;
    self
  }
}

impl ConnectorBuilder {
  /// Combine the configuration of this builder with a connector to create a `Connector`.
  pub fn build(&self) -> Result<Connector> {
    #[cfg(feature = "tls")]
    let tls = {
      let mut binding = TlsConnector::builder();
      let mut tls_builder = binding
        .use_sni(self.tls_sni)
        .danger_accept_invalid_hostnames(!self.hostname_verification)
        .danger_accept_invalid_certs(!self.certs_verification);
      for c in self.certificate.iter() {
        tls_builder = tls_builder.add_root_certificate(c.clone());
      }
      if let Some(identity) = &self.identity {
        tls_builder.identity(identity.clone());
      };
      tls_builder.build()?
    };
    let conn = Connector {
      connect_timeout: self.connect_timeout,
      nodelay: self.nodelay,
      read_timeout: self.read_timeout,
      write_timeout: self.write_timeout,
      proxy: self.proxy.clone(),
      #[cfg(feature = "tls")]
      tls,
    };
    Ok(conn)
  }
}

/// Connector
#[derive(Debug)]
pub struct Connector {
  connect_timeout: Option<Duration>,
  nodelay: bool,
  read_timeout: Option<Duration>,
  write_timeout: Option<Duration>,
  proxy: Option<Proxy>,
  #[cfg(feature = "tls")]
  tls: TlsConnector,
}

impl PartialEq for Connector {
  fn eq(&self, _other: &Self) -> bool {
    true
  }
}

impl Connector {
  /// Connect to a remote endpoint with addr
  pub fn connect_with_addr<S: Into<SocketAddr>>(&self, addr: S) -> Result<Socket> {
    let addr = addr.into();
    let socket = RawSocket::new(Domain::for_address(addr), Type::STREAM, Some(Protocol::TCP))?;
    if self.nodelay {
      socket.set_nodelay(self.nodelay)?;
    }
    socket.set_read_timeout(self.read_timeout)?;
    socket.set_write_timeout(self.write_timeout)?;
    match self.connect_timeout {
      None => {
        socket.connect(&addr.into())?;
      }
      Some(timeout) => {
        socket.connect_timeout(&addr.into(), timeout)?;
      }
    }
    Ok(Socket::TCP(socket))
  }
  /// Connect to a remote endpoint with url
  pub fn connect_with_uri(&self, target: &http::Uri) -> Result<Socket> {
    ProxySocket::new(target, &self.proxy).conn_with_connector(self)
  }
  #[cfg(feature = "tls")]
  /// A `Connector` will use transport layer security (TLS) by default to connect to destinations.
  pub fn upgrade_to_tls(&self, stream: Socket, domain: &str) -> Result<Socket> {
    // 上面是原始socket
    let i = match stream {
      Socket::TCP(s) => {
        let mut stream = self.tls.connect(domain, s);
        while let Err(HandshakeError::WouldBlock(mid_handshake)) = stream {
          stream = mid_handshake.handshake();
        }
        Socket::TLS(stream?)
      }
      // 本来就是tls了
      Socket::TLS(_t) => {
        return Err(new_io_error(
          std::io::ErrorKind::ConnectionAborted,
          "it's already tls",
        ));
      }
    };
    Ok(i)
  }
}

//
impl Default for Connector {
  fn default() -> Self {
    ConnectorBuilder::default()
      .build()
      .expect("new default connector failure")
  }
}