-
-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathconn.rs
More file actions
536 lines (460 loc) · 14.4 KB
/
conn.rs
File metadata and controls
536 lines (460 loc) · 14.4 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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
mod connector;
mod http;
mod proxy;
mod tcp;
mod tls_info;
#[cfg(unix)]
mod uds;
mod verbose;
use std::{
fmt::{self, Debug, Formatter},
io,
io::IoSlice,
pin::Pin,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
task::{Context, Poll},
};
use ::http::{Extensions, HeaderMap, HeaderValue};
use pin_project_lite::pin_project;
#[cfg(unix)]
use tokio::net::UnixStream;
use tokio::{
io::{AsyncRead, AsyncWrite, ReadBuf},
net::TcpStream,
};
use tokio_btls::SslStream;
use tower::{
BoxError,
util::{BoxCloneSyncService, BoxCloneSyncServiceLayer},
};
#[cfg(feature = "socks")]
pub(super) use self::proxy::socks;
pub(super) use self::{
connector::Connector,
http::{HttpInfo, HttpTransport},
proxy::tunnel,
tcp::{SocketBindOptions, tokio::TokioTcpConnector},
tls_info::TlsInfoFactory,
};
use crate::{
client::ConnectRequest,
dns::DynResolver,
proxy::matcher::Intercept,
tls::{MaybeHttpsStream, TlsInfo},
};
/// HTTP connector with dynamic DNS resolver.
pub type HttpConnector = self::http::HttpConnector<DynResolver, TokioTcpConnector>;
/// Boxed connector service for establishing connections.
pub type BoxedConnectorService = BoxCloneSyncService<Unnameable, Conn, BoxError>;
/// Boxed layer for building a boxed connector service.
pub type BoxedConnectorLayer =
BoxCloneSyncServiceLayer<BoxedConnectorService, Unnameable, Conn, BoxError>;
/// A wrapper type for [`ConnectRequest`] used to erase its concrete type.
///
/// [`Unnameable`] allows passing connection requests through trait objects or
/// type-erased interfaces where the concrete type of the request is not important.
/// This is mainly used internally to simplify service composition and dynamic dispatch.
pub struct Unnameable(pub(super) ConnectRequest);
/// A trait alias for types that can be used as async connections.
///
/// This trait is automatically implemented for any type that satisfies the required bounds:
/// - [`AsyncRead`] + [`AsyncWrite`]: For I/O operations
/// - [`Connection`]: For connection metadata
/// - [`Send`] + [`Sync`] + [`Unpin`] + `'static`: For async/await compatibility
trait AsyncConn: AsyncRead + AsyncWrite + Connection + Send + Sync + Unpin + 'static {}
/// An async connection that can also provide TLS information.
///
/// This extends [`AsyncConn`] with the ability to extract TLS certificate information
/// when available. Useful for connections that may be either plain TCP or TLS-encrypted.
trait AsyncConnWithInfo: AsyncConn + TlsInfoFactory {}
impl<T> AsyncConn for T where T: AsyncRead + AsyncWrite + Connection + Send + Sync + Unpin + 'static {}
impl<T> AsyncConnWithInfo for T where T: AsyncConn + TlsInfoFactory {}
pin_project! {
/// Note: the `is_proxy` member means *is plain text HTTP proxy*.
/// This tells core whether the URI should be written in
/// * origin-form (`GET /just/a/path HTTP/1.1`), when `is_proxy == false`, or
/// * absolute-form (`GET http://foo.bar/and/a/path HTTP/1.1`), otherwise.
pub struct Conn {
tls_info: bool,
proxy: Option<Intercept>,
#[pin]
stream: Box<dyn AsyncConnWithInfo>,
}
}
pin_project! {
/// A wrapper around `SslStream` that adapts it for use as a generic async connection.
///
/// This type enables unified handling of plain TCP and TLS-encrypted streams by providing
/// implementations of `Connection`, `Read`, `Write`, and `TlsInfoFactory`.
/// It is mainly used internally to abstract over different connection types.
pub struct TlsConn<T> {
#[pin]
stream: SslStream<T>,
}
}
/// Describes a type returned by a connector.
pub trait Connection {
/// Return metadata describing the connection.
fn connected(&self) -> Connected;
}
/// Indicates the negotiated ALPN protocol.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Alpn {
H2,
None,
}
/// A pill that can be poisoned to indicate that a connection should not be reused.
#[derive(Clone)]
struct PoisonPill {
poisoned: Arc<AtomicBool>,
}
/// A boxed asynchronous connection with associated information.
#[derive(Debug)]
struct Extra(Box<dyn ExtraInner>);
/// Inner trait for extra connection information.
trait ExtraInner: Send + Sync + Debug {
fn clone_box(&self) -> Box<dyn ExtraInner>;
fn set(&self, res: &mut Extensions);
}
// This indirection allows the `Connected` to have a type-erased "extra" value,
// while that type still knows its inner extra type. This allows the correct
// TypeId to be used when inserting into `res.extensions_mut()`.
#[derive(Debug, Clone)]
struct ExtraEnvelope<T>(T);
/// Chains two `ExtraInner` implementations together, inserting both into
/// the extensions.
#[derive(Debug)]
struct ExtraChain<T>(Box<dyn ExtraInner>, T);
/// Information about an HTTP proxy identity.
#[derive(Debug, Default, Clone)]
struct ProxyIdentity {
is_proxied: bool,
auth: Option<HeaderValue>,
headers: Option<HeaderMap>,
}
/// Extra information about the connected transport.
///
/// This can be used to inform recipients about things like if ALPN
/// was used, or if connected to an HTTP proxy.
#[derive(Debug)]
pub struct Connected {
alpn: Alpn,
proxy: Box<ProxyIdentity>,
extra: Option<Extra>,
poisoned: PoisonPill,
}
// ==== impl Conn ====
impl Connection for Conn {
fn connected(&self) -> Connected {
let mut connected = self.stream.connected();
if let Some(proxy) = &self.proxy {
connected = connected.proxy(proxy.clone());
}
if self.tls_info {
if let Some(tls_info) = self.stream.tls_info() {
connected.extra(tls_info)
} else {
connected
}
} else {
connected
}
}
}
impl AsyncRead for Conn {
#[inline]
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
AsyncRead::poll_read(self.project().stream, cx, buf)
}
}
impl AsyncWrite for Conn {
#[inline]
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
AsyncWrite::poll_write(self.project().stream, cx, buf)
}
#[inline]
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<Result<usize, io::Error>> {
AsyncWrite::poll_write_vectored(self.project().stream, cx, bufs)
}
#[inline]
fn is_write_vectored(&self) -> bool {
self.stream.is_write_vectored()
}
#[inline]
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
AsyncWrite::poll_flush(self.project().stream, cx)
}
#[inline]
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> {
AsyncWrite::poll_shutdown(self.project().stream, cx)
}
}
// ===== impl TcpStream =====
impl Connection for TlsConn<TcpStream> {
fn connected(&self) -> Connected {
let connected = self.stream.get_ref().connected();
if self.stream.ssl().selected_alpn_protocol() == Some(b"h2") {
connected.negotiated_h2()
} else {
connected
}
}
}
impl Connection for TlsConn<MaybeHttpsStream<TcpStream>> {
fn connected(&self) -> Connected {
let connected = self.stream.get_ref().connected();
if self.stream.ssl().selected_alpn_protocol() == Some(b"h2") {
connected.negotiated_h2()
} else {
connected
}
}
}
// ===== impl UnixStream =====
#[cfg(unix)]
impl Connection for TlsConn<UnixStream> {
fn connected(&self) -> Connected {
let connected = self.stream.get_ref().connected();
if self.stream.ssl().selected_alpn_protocol() == Some(b"h2") {
connected.negotiated_h2()
} else {
connected
}
}
}
#[cfg(unix)]
impl Connection for TlsConn<MaybeHttpsStream<UnixStream>> {
fn connected(&self) -> Connected {
let connected = self.stream.get_ref().connected();
if self.stream.ssl().selected_alpn_protocol() == Some(b"h2") {
connected.negotiated_h2()
} else {
connected
}
}
}
impl<T: AsyncRead + AsyncWrite + Unpin> AsyncRead for TlsConn<T> {
#[inline]
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &mut ReadBuf<'_>,
) -> Poll<tokio::io::Result<()>> {
AsyncRead::poll_read(self.project().stream, cx, buf)
}
}
impl<T: AsyncRead + AsyncWrite + Unpin> AsyncWrite for TlsConn<T> {
#[inline]
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context,
buf: &[u8],
) -> Poll<Result<usize, tokio::io::Error>> {
AsyncWrite::poll_write(self.project().stream, cx, buf)
}
#[inline]
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<Result<usize, io::Error>> {
AsyncWrite::poll_write_vectored(self.project().stream, cx, bufs)
}
#[inline]
fn is_write_vectored(&self) -> bool {
self.stream.is_write_vectored()
}
#[inline]
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), tokio::io::Error>> {
AsyncWrite::poll_flush(self.project().stream, cx)
}
#[inline]
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), tokio::io::Error>> {
AsyncWrite::poll_shutdown(self.project().stream, cx)
}
}
impl<T> TlsInfoFactory for TlsConn<T>
where
SslStream<T>: TlsInfoFactory,
{
fn tls_info(&self) -> Option<TlsInfo> {
self.stream.tls_info()
}
}
// ===== impl PoisonPill =====
impl fmt::Debug for PoisonPill {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
// print the address of the pill—this makes debugging issues much easier
write!(
f,
"PoisonPill@{:p} {{ poisoned: {} }}",
self.poisoned,
self.poisoned.load(Ordering::Relaxed)
)
}
}
impl PoisonPill {
/// Create a healthy (not poisoned) pill.
#[inline]
fn healthy() -> Self {
Self {
poisoned: Arc::new(AtomicBool::new(false)),
}
}
/// Poison this pill.
#[inline]
fn poison(&self) {
self.poisoned.store(true, Ordering::Relaxed)
}
/// Check if this pill is poisoned.
#[inline]
fn poisoned(&self) -> bool {
self.poisoned.load(Ordering::Relaxed)
}
}
// ===== impl Connected =====
impl Connected {
/// Create new `Connected` type with empty metadata.
pub fn new() -> Connected {
Connected {
alpn: Alpn::None,
proxy: Box::new(ProxyIdentity::default()),
extra: None,
poisoned: PoisonPill::healthy(),
}
}
/// Set extra connection information to be set in the extensions of every `Response`.
pub fn extra<T: Clone + Send + Sync + Debug + 'static>(mut self, extra: T) -> Connected {
if let Some(prev) = self.extra {
self.extra = Some(Extra(Box::new(ExtraChain(prev.0, extra))));
} else {
self.extra = Some(Extra(Box::new(ExtraEnvelope(extra))));
}
self
}
/// Copies the extra connection information into an `Extensions` map.
pub fn set_extras(&self, extensions: &mut Extensions) {
if let Some(extra) = &self.extra {
extra.set(extensions);
}
}
/// Set that the proxy was used for this connected transport.
pub fn proxy(mut self, proxy: Intercept) -> Connected {
self.proxy.is_proxied = true;
if let Some(auth) = proxy.basic_auth() {
self.proxy.auth.replace(auth.clone());
}
if let Some(headers) = proxy.custom_headers() {
self.proxy.headers.replace(headers.clone());
}
self
}
/// Determines if the connected transport is to an HTTP proxy.
#[inline]
pub fn is_proxied(&self) -> bool {
self.proxy.is_proxied
}
/// Get the proxy identity information for the connected transport.
#[inline]
pub fn proxy_auth(&self) -> Option<&HeaderValue> {
self.proxy.auth.as_ref()
}
/// Get the custom proxy headers for the connected transport.
#[inline]
pub fn proxy_headers(&self) -> Option<&HeaderMap> {
self.proxy.headers.as_ref()
}
/// Set that the connected transport negotiated HTTP/2 as its next protocol.
#[inline]
pub fn negotiated_h2(mut self) -> Connected {
self.alpn = Alpn::H2;
self
}
/// Determines if the connected transport negotiated HTTP/2 as its next protocol.
#[inline]
pub fn is_negotiated_h2(&self) -> bool {
self.alpn == Alpn::H2
}
/// Determine if this connection is poisoned
#[inline]
pub fn poisoned(&self) -> bool {
self.poisoned.poisoned()
}
/// Poison this connection
///
/// A poisoned connection will not be reused for subsequent requests by the pool
#[inline]
pub fn poison(&self) {
self.poisoned.poison();
debug!(
"connection was poisoned. this connection will not be reused for subsequent requests"
);
}
// Don't public expose that `Connected` is `Clone`, unsure if we want to
// keep that contract...
pub(crate) fn clone(&self) -> Connected {
Connected {
alpn: self.alpn,
proxy: self.proxy.clone(),
extra: self.extra.clone(),
poisoned: self.poisoned.clone(),
}
}
}
// ===== impl Extra =====
impl Extra {
#[inline]
fn set(&self, res: &mut Extensions) {
self.0.set(res);
}
}
impl Clone for Extra {
fn clone(&self) -> Extra {
Extra(self.0.clone_box())
}
}
// ===== impl ExtraEnvelope =====
impl<T> ExtraInner for ExtraEnvelope<T>
where
T: Clone + Send + Sync + Debug + 'static,
{
fn clone_box(&self) -> Box<dyn ExtraInner> {
Box::new(self.clone())
}
fn set(&self, res: &mut Extensions) {
res.insert(self.0.clone());
}
}
// ===== impl ExtraChain =====
impl<T: Clone> Clone for ExtraChain<T> {
fn clone(&self) -> Self {
ExtraChain(self.0.clone_box(), self.1.clone())
}
}
impl<T> ExtraInner for ExtraChain<T>
where
T: Clone + Send + Sync + Debug + 'static,
{
fn clone_box(&self) -> Box<dyn ExtraInner> {
Box::new(self.clone())
}
fn set(&self, res: &mut Extensions) {
self.0.set(res);
res.insert(self.1.clone());
}
}