connectrpc-hyper 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,825 @@
1
+ //! Connection setup: resolution (getaddrinfo on tokio's blocking pool), TCP
2
+ //! with Go-style dual-stack fallback, an optional proxy CONNECT tunnel,
3
+ //! rustls, then a hyper HTTP/2 or HTTP/1.1 handshake. Failures are classified
4
+ //! by type and errno, never by text.
5
+ use std::future::Future;
6
+ use std::io;
7
+ use std::net::{IpAddr, SocketAddr};
8
+ use std::pin::Pin;
9
+ use std::sync::Arc;
10
+ use std::task::{Context, Poll};
11
+ use std::time::Duration;
12
+
13
+ use hyper::client::conn::{http1, http2};
14
+ use hyper_util::rt::{TokioIo, TokioTimer};
15
+ use rustls::pki_types::ServerName;
16
+ use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf};
17
+ use tokio::net::TcpStream;
18
+ use tokio::time::Instant;
19
+
20
+ use crate::body::CallBody;
21
+ use crate::failure::{Failure, TlsFault};
22
+ use crate::gvl::Signal;
23
+ use crate::holds::Holds;
24
+ use crate::runtime::{Task, TrackedExec, Tracker};
25
+ use crate::wire::{Tap, Wire};
26
+ use proxy::{Mode, Route};
27
+
28
+ /// Go's net.Dialer FallbackDelay for RFC 6555 dual-stack dialing.
29
+ const FALLBACK_DELAY: Duration = Duration::from_millis(300);
30
+ /// grpc-go's default maximum header list size; h2 only marks larger blocks,
31
+ /// so it must sit far above core's 64 KiB gRPC field limit.
32
+ const MAX_HEADER_LIST_SIZE: u32 = 16 << 20;
33
+ /// Bounds what h2 buffers for one stream beyond its send window.
34
+ const MAX_SEND_BUF_SIZE: usize = 1 << 20;
35
+ /// Go net/http's default MaxResponseHeaderBytes, for HTTP/1.1 response heads
36
+ /// (status line included) and chunked trailers. hyper's read buffer must be
37
+ /// able to hold a whole head, so it may grow to this size on a busy
38
+ /// connection; hyper's default (about 400 KiB) is below Go's bound.
39
+ const MAX_H1_HEAD: usize = 10 << 20;
40
+ /// Response header fields per HTTP/1.1 head. Go counts only bytes; hyper
41
+ /// also caps fields (default 100) and allocates this many slots per response.
42
+ const MAX_H1_HEADERS: usize = 1024;
43
+ /// Go's net.Dialer minimum per-address share of the setup budget
44
+ /// (saneMinimum in partialDeadline).
45
+ const MIN_ATTEMPT: Duration = Duration::from_secs(2);
46
+
47
+ /// A request's destination and the proxy it goes through, if any: the pool
48
+ /// key, so direct and proxied connections never mix.
49
+ #[derive(Clone, Debug, PartialEq, Eq, Hash)]
50
+ pub struct Origin {
51
+ pub https: bool,
52
+ pub host: String,
53
+ pub port: u16,
54
+ pub proxy: Option<Route>,
55
+ }
56
+
57
+ impl Origin {
58
+ pub fn parse(uri: &http::Uri) -> Result<Self, Failure> {
59
+ let https = match uri.scheme_str() {
60
+ Some("https") => true,
61
+ Some("http") => false,
62
+ _ => return Err(Failure::new("request", "URL must be HTTP(S)")),
63
+ };
64
+ let host = uri
65
+ .host()
66
+ .ok_or_else(|| Failure::new("request", "URL has no host"))?
67
+ .trim_start_matches('[')
68
+ .trim_end_matches(']')
69
+ .to_ascii_lowercase();
70
+ let port = uri.port_u16().unwrap_or(if https { 443 } else { 80 });
71
+ Ok(Self {
72
+ https,
73
+ host,
74
+ port,
75
+ proxy: None,
76
+ })
77
+ }
78
+
79
+ /// True when requests go to a forwarding proxy in absolute form.
80
+ pub fn forwarded(&self) -> bool {
81
+ self.proxy.as_ref().is_some_and(|p| p.mode == Mode::Forward)
82
+ }
83
+
84
+ /// host:port as a CONNECT request names it, IPv6 literals bracketed.
85
+ fn authority(&self) -> String {
86
+ if self.host.contains(':') {
87
+ format!("[{}]:{}", self.host, self.port)
88
+ } else {
89
+ format!("{}:{}", self.host, self.port)
90
+ }
91
+ }
92
+ }
93
+
94
+ /// A connected TCP socket listed in the fork-safe registry while it is open.
95
+ pub struct Socket {
96
+ stream: TcpStream,
97
+ #[cfg(unix)]
98
+ slot: Option<usize>,
99
+ holds: Arc<Holds>,
100
+ }
101
+
102
+ impl Socket {
103
+ fn new(stream: TcpStream, holds: &Arc<Holds>) -> Self {
104
+ let holds = holds.clone();
105
+ #[cfg(unix)]
106
+ {
107
+ use std::os::fd::AsRawFd;
108
+ let slot = crate::runtime::sockets::register(stream.as_raw_fd());
109
+ Self {
110
+ stream,
111
+ slot,
112
+ holds,
113
+ }
114
+ }
115
+ #[cfg(not(unix))]
116
+ Self { stream, holds }
117
+ }
118
+
119
+ /// Copies bytes waiting to be read without consuming them.
120
+ pub async fn peek(&self, buffer: &mut [u8]) -> io::Result<usize> {
121
+ self.stream.peek(buffer).await
122
+ }
123
+
124
+ /// Reads exactly `buffer.len()` bytes.
125
+ pub async fn consume(&mut self, buffer: &mut [u8]) -> io::Result<()> {
126
+ self.stream.read_exact(buffer).await.map(|_| ())
127
+ }
128
+ }
129
+
130
+ impl Drop for Socket {
131
+ fn drop(&mut self) {
132
+ // Spec hold point while the socket is still open, in whatever thread
133
+ // drops it: an owned task's socket closes before close returns.
134
+ self.holds.block("socket:drop");
135
+ // Deregister before the stream field drops and closes the fd.
136
+ #[cfg(unix)]
137
+ if let Some(slot) = self.slot.take() {
138
+ crate::runtime::sockets::deregister(slot);
139
+ }
140
+ }
141
+ }
142
+
143
+ impl AsyncRead for Socket {
144
+ fn poll_read(
145
+ self: Pin<&mut Self>,
146
+ cx: &mut Context<'_>,
147
+ buf: &mut ReadBuf<'_>,
148
+ ) -> Poll<io::Result<()>> {
149
+ Pin::new(&mut self.get_mut().stream).poll_read(cx, buf)
150
+ }
151
+ }
152
+
153
+ impl AsyncWrite for Socket {
154
+ fn poll_write(
155
+ self: Pin<&mut Self>,
156
+ cx: &mut Context<'_>,
157
+ buf: &[u8],
158
+ ) -> Poll<io::Result<usize>> {
159
+ let this = self.get_mut();
160
+ // Spec hold point: armed, it holds every write back until released,
161
+ // as a socket whose send buffer is full would.
162
+ std::task::ready!(this.holds.poll_stall("socket:write", cx));
163
+ Pin::new(&mut this.stream).poll_write(cx, buf)
164
+ }
165
+
166
+ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
167
+ Pin::new(&mut self.get_mut().stream).poll_flush(cx)
168
+ }
169
+
170
+ fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
171
+ Pin::new(&mut self.get_mut().stream).poll_shutdown(cx)
172
+ }
173
+
174
+ fn poll_write_vectored(
175
+ self: Pin<&mut Self>,
176
+ cx: &mut Context<'_>,
177
+ bufs: &[io::IoSlice<'_>],
178
+ ) -> Poll<io::Result<usize>> {
179
+ let this = self.get_mut();
180
+ std::task::ready!(this.holds.poll_stall("socket:write", cx));
181
+ Pin::new(&mut this.stream).poll_write_vectored(cx, bufs)
182
+ }
183
+
184
+ fn is_write_vectored(&self) -> bool {
185
+ self.stream.is_write_vectored()
186
+ }
187
+ }
188
+
189
+ /// A TLS stream that records the first TLS failure any read or write on it
190
+ /// returns (see `TlsFault`), and is otherwise transparent.
191
+ struct Recorded<T> {
192
+ inner: T,
193
+ fault: Arc<TlsFault>,
194
+ }
195
+
196
+ impl<T> Recorded<T> {
197
+ fn record<R>(&self, result: Poll<io::Result<R>>) -> Poll<io::Result<R>> {
198
+ if let Poll::Ready(Err(error)) = &result {
199
+ self.fault.record(error);
200
+ }
201
+ result
202
+ }
203
+ }
204
+
205
+ impl<T: AsyncRead + Unpin> AsyncRead for Recorded<T> {
206
+ fn poll_read(
207
+ self: Pin<&mut Self>,
208
+ cx: &mut Context<'_>,
209
+ buf: &mut ReadBuf<'_>,
210
+ ) -> Poll<io::Result<()>> {
211
+ let this = self.get_mut();
212
+ let result = Pin::new(&mut this.inner).poll_read(cx, buf);
213
+ this.record(result)
214
+ }
215
+ }
216
+
217
+ impl<T: AsyncWrite + Unpin> AsyncWrite for Recorded<T> {
218
+ fn poll_write(
219
+ self: Pin<&mut Self>,
220
+ cx: &mut Context<'_>,
221
+ buf: &[u8],
222
+ ) -> Poll<io::Result<usize>> {
223
+ let this = self.get_mut();
224
+ let result = Pin::new(&mut this.inner).poll_write(cx, buf);
225
+ this.record(result)
226
+ }
227
+
228
+ fn poll_write_vectored(
229
+ self: Pin<&mut Self>,
230
+ cx: &mut Context<'_>,
231
+ bufs: &[io::IoSlice<'_>],
232
+ ) -> Poll<io::Result<usize>> {
233
+ let this = self.get_mut();
234
+ let result = Pin::new(&mut this.inner).poll_write_vectored(cx, bufs);
235
+ this.record(result)
236
+ }
237
+
238
+ fn is_write_vectored(&self) -> bool {
239
+ self.inner.is_write_vectored()
240
+ }
241
+
242
+ fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
243
+ let this = self.get_mut();
244
+ let result = Pin::new(&mut this.inner).poll_flush(cx);
245
+ this.record(result)
246
+ }
247
+
248
+ fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
249
+ let this = self.get_mut();
250
+ let result = Pin::new(&mut this.inner).poll_shutdown(cx);
251
+ this.record(result)
252
+ }
253
+ }
254
+
255
+ pub trait Io: AsyncRead + AsyncWrite + Unpin + Send {}
256
+ impl<T: AsyncRead + AsyncWrite + Unpin + Send> Io for T {}
257
+
258
+ pub struct Settings {
259
+ pub http2: bool,
260
+ pub keepalive: Option<(Duration, Duration, bool)>,
261
+ pub tunnel: proxy::Limits,
262
+ }
263
+
264
+ pub enum Handshake {
265
+ H2 {
266
+ sender: http2::SendRequest<CallBody>,
267
+ /// Fires once hyper's dispatcher has ended and been dropped (see
268
+ /// `Dispatcher`): the connection admits no more requests (GOAWAY,
269
+ /// error or close).
270
+ closed: Arc<Signal>,
271
+ wire: Arc<Wire>,
272
+ },
273
+ H1 {
274
+ sender: http1::SendRequest<CallBody>,
275
+ task: Task,
276
+ /// As for HTTP/2.
277
+ closed: Arc<Signal>,
278
+ },
279
+ }
280
+
281
+ /// Owns hyper's connection future (the HTTP/1.1 dispatcher, or HTTP/2's
282
+ /// `ClientTask`) and fires `closed` only after dropping it. By then every
283
+ /// request the dispatcher held is answered. Since hyper 1.13.0 a dispatcher
284
+ /// that shuts down closes its request channel and drains it, waiting for a
285
+ /// send already under way, before its future completes; an HTTP/1.1 upgrade
286
+ /// (a 101 response, or a 2xx reply to CONNECT other than 204) completes
287
+ /// without that drain. Dropping the future drains what the channel's receiver
288
+ /// can read, and an HTTP/1.1 in-flight callback or an HTTP/2 request still
289
+ /// waiting for a stream slot answers "connection closed". When hyper 1.13's
290
+ /// dispatch finds its connection failed while a request waits for a slot,
291
+ /// and keepalive has not timed out, it fails that request first: with the
292
+ /// connection's code, or a cancellation for NO_ERROR or an error without a
293
+ /// code (see `Failure::from_hyper`).
294
+ /// HTTP/2 requests already passed to h2 are answered by their own response
295
+ /// tasks. So once `closed` fires, a pending request the dispatcher never took
296
+ /// is stranded (see `call::send`). It exists before the task does: a sealed
297
+ /// tracker drops a refused task at once, and an aborted or finished task
298
+ /// drops its future before it deregisters, so every exit fires.
299
+ struct Dispatcher {
300
+ connection: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
301
+ closed: Arc<Signal>,
302
+ holds: Arc<Holds>,
303
+ /// An HTTP/2 connection's stream record, for the `dispatch:returned`
304
+ /// hold point.
305
+ wire: Option<Arc<Wire>>,
306
+ }
307
+
308
+ impl Future for Dispatcher {
309
+ type Output = ();
310
+
311
+ fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
312
+ if let Some(connection) = self.connection.as_mut() {
313
+ let polled = connection.as_mut().poll(cx);
314
+ if polled.is_pending() && self.holds.armed() {
315
+ if let Some(wire) = &self.wire {
316
+ // Spec hold point: armed with a zero bound, it counts the
317
+ // dispatch polls that returned with N stream indexes
318
+ // taken. hyper takes them in that poll, so the first such
319
+ // return means the poll that passed request N to h2 has
320
+ // ended; while the connection is up, a request that found
321
+ // no stream slot is then parked. Later returns at N say
322
+ // nothing more (a closing dispatcher also returns pending
323
+ // while it drains).
324
+ self.holds
325
+ .block(&format!("dispatch:returned:{}", wire.taken()));
326
+ }
327
+ }
328
+ std::task::ready!(polled);
329
+ }
330
+ self.connection = None;
331
+ Poll::Ready(())
332
+ }
333
+ }
334
+
335
+ impl Drop for Dispatcher {
336
+ fn drop(&mut self) {
337
+ // Explicitly first: `closed` must not fire while hyper still holds
338
+ // requests it has yet to answer.
339
+ drop(self.connection.take());
340
+ self.closed.fire();
341
+ // Spec hold point: armed with a zero bound, it counts the fired
342
+ // signals.
343
+ self.holds.block("dispatcher:closed");
344
+ }
345
+ }
346
+
347
+ pub struct Connected {
348
+ pub handshake: Handshake,
349
+ pub local_port: u16,
350
+ /// Never filled on a cleartext connection.
351
+ pub fault: Arc<TlsFault>,
352
+ }
353
+
354
+ async fn resolve(host: &str, port: u16) -> Result<Vec<SocketAddr>, Failure> {
355
+ if let Ok(ip) = host.parse::<IpAddr>() {
356
+ return Ok(vec![SocketAddr::new(ip, port)]);
357
+ }
358
+ let addresses: Vec<SocketAddr> = tokio::net::lookup_host((host, port))
359
+ .await
360
+ .map_err(|e| Failure::io("dns", &e))?
361
+ .collect();
362
+ if addresses.is_empty() {
363
+ return Err(Failure::new("dns", "no addresses"));
364
+ }
365
+ Ok(addresses)
366
+ }
367
+
368
+ fn connect_failure(error: &io::Error) -> Failure {
369
+ let kind = match error.kind() {
370
+ io::ErrorKind::ConnectionRefused => "refused",
371
+ io::ErrorKind::HostUnreachable | io::ErrorKind::NetworkUnreachable => "unreachable",
372
+ _ => "connect",
373
+ };
374
+ Failure::io(kind, error)
375
+ }
376
+
377
+ /// Go's partialDeadline: an equal share of the setup budget left for each
378
+ /// remaining address, at least MIN_ATTEMPT (or all that is left).
379
+ fn attempt_budget(deadline: Instant, remaining_addresses: usize) -> Duration {
380
+ let left = deadline.saturating_duration_since(Instant::now());
381
+ let share = left / u32::try_from(remaining_addresses.max(1)).unwrap_or(u32::MAX);
382
+ if share < MIN_ATTEMPT {
383
+ left.min(MIN_ATTEMPT)
384
+ } else {
385
+ share
386
+ }
387
+ }
388
+
389
+ /// Tries each address in turn, each within its share of the setup budget, so
390
+ /// a blackholed address does not consume all of it; returns the first error
391
+ /// if all fail.
392
+ async fn dial_serial(addresses: &[SocketAddr], deadline: Instant) -> Result<TcpStream, Failure> {
393
+ let mut first = None;
394
+ for (index, address) in addresses.iter().enumerate() {
395
+ let budget = attempt_budget(deadline, addresses.len() - index);
396
+ let result = match tokio::time::timeout(budget, TcpStream::connect(address)).await {
397
+ Ok(result) => result,
398
+ Err(_) => {
399
+ first.get_or_insert_with(|| {
400
+ Failure::new("connect_timeout", "connection attempt timed out")
401
+ });
402
+ continue;
403
+ }
404
+ };
405
+ match result {
406
+ Ok(stream) => return Ok(stream),
407
+ Err(e) => {
408
+ first.get_or_insert_with(|| connect_failure(&e));
409
+ }
410
+ }
411
+ }
412
+ Err(first.unwrap_or_else(|| Failure::new("connect", "no addresses")))
413
+ }
414
+
415
+ /// RFC 6555 as Go dials: the first address's family is primary; the other
416
+ /// family starts after FALLBACK_DELAY, or at once if the primary fails, and
417
+ /// the first connection wins. The primary's error is reported if both fail.
418
+ async fn dial(host: &str, port: u16, deadline: Instant) -> Result<TcpStream, Failure> {
419
+ let addresses = resolve(host, port).await?;
420
+ let primary_v4 = addresses[0].is_ipv4();
421
+ let (primaries, fallbacks): (Vec<SocketAddr>, Vec<SocketAddr>) = addresses
422
+ .into_iter()
423
+ .partition(|a| a.is_ipv4() == primary_v4);
424
+ if fallbacks.is_empty() {
425
+ return dial_serial(&primaries, deadline).await;
426
+ }
427
+ let primary = dial_serial(&primaries, deadline);
428
+ tokio::pin!(primary);
429
+ let delay = tokio::time::sleep(FALLBACK_DELAY);
430
+ tokio::pin!(delay);
431
+ let mut primary_failure = None;
432
+ tokio::select! {
433
+ result = &mut primary => match result {
434
+ Ok(stream) => return Ok(stream),
435
+ Err(failure) => primary_failure = Some(failure),
436
+ },
437
+ _ = &mut delay => {}
438
+ }
439
+ let fallback = dial_serial(&fallbacks, deadline);
440
+ tokio::pin!(fallback);
441
+ if let Some(failure) = primary_failure {
442
+ return fallback.await.map_err(|_| failure);
443
+ }
444
+ let mut fallback_failure = None;
445
+ loop {
446
+ tokio::select! {
447
+ result = &mut primary, if primary_failure.is_none() => match result {
448
+ Ok(stream) => return Ok(stream),
449
+ Err(failure) => {
450
+ if fallback_failure.is_some() {
451
+ return Err(failure);
452
+ }
453
+ primary_failure = Some(failure);
454
+ }
455
+ },
456
+ result = &mut fallback, if fallback_failure.is_none() => match result {
457
+ Ok(stream) => return Ok(stream),
458
+ Err(failure) => {
459
+ if let Some(primary) = primary_failure {
460
+ return Err(primary);
461
+ }
462
+ fallback_failure = Some(failure);
463
+ }
464
+ },
465
+ }
466
+ }
467
+ }
468
+
469
+ fn tls_failure(error: &io::Error) -> Failure {
470
+ let verify = error
471
+ .get_ref()
472
+ .and_then(|inner| inner.downcast_ref::<rustls::Error>())
473
+ .is_some_and(|e| {
474
+ matches!(
475
+ e,
476
+ rustls::Error::InvalidCertificate(_) | rustls::Error::NoCertificatesPresented
477
+ )
478
+ });
479
+ if verify {
480
+ Failure::new("tls_verify", "certificate verification failed")
481
+ } else if error
482
+ .get_ref()
483
+ .is_some_and(|inner| inner.is::<rustls::Error>())
484
+ {
485
+ Failure::new("tls", "TLS handshake failed")
486
+ } else {
487
+ Failure::io("closed", error)
488
+ }
489
+ }
490
+
491
+ /// Connects and completes the handshake hyper performs (for HTTP/2, the
492
+ /// preface is written; hyper exposes no peer-SETTINGS boundary). `deadline`
493
+ /// ends the setup budget that TCP attempts share; the caller enforces it.
494
+ pub async fn connect(
495
+ settings: &Settings,
496
+ tls: Option<Arc<rustls::ClientConfig>>,
497
+ origin: &Origin,
498
+ tracker: &Arc<Tracker>,
499
+ holds: &Arc<Holds>,
500
+ deadline: Instant,
501
+ ) -> Result<Connected, Failure> {
502
+ let stream = match &origin.proxy {
503
+ Some(route) => dial(&route.host, route.port, deadline).await?,
504
+ None => dial(&origin.host, origin.port, deadline).await?,
505
+ };
506
+ let _ = stream.set_nodelay(true);
507
+ let local_port = stream.local_addr().map(|a| a.port()).unwrap_or(0);
508
+ let mut socket = Socket::new(stream, holds);
509
+ if let Some(route) = origin.proxy.as_ref().filter(|r| r.mode == Mode::Tunnel) {
510
+ // Only an h2c server may send its SETTINGS before the client speaks.
511
+ let strict = origin.https || !settings.http2;
512
+ proxy::tunnel(
513
+ &mut socket,
514
+ &origin.authority(),
515
+ route.authorization.as_ref(),
516
+ settings.tunnel,
517
+ strict,
518
+ )
519
+ .await?;
520
+ }
521
+ let (io, h2, fault): (Box<dyn Io>, bool, Arc<TlsFault>) = match tls {
522
+ Some(config) => {
523
+ // An IP literal becomes ServerName::IpAddress: no SNI (RFC 6066).
524
+ let name = ServerName::try_from(origin.host.clone())
525
+ .map_err(|_| Failure::new("tls", "invalid server name"))?;
526
+ let stream = tokio_rustls::TlsConnector::from(config)
527
+ .connect(name, socket)
528
+ .await
529
+ .map_err(|e| tls_failure(&e))?;
530
+ let h2 = stream.get_ref().1.alpn_protocol() == Some(b"h2");
531
+ let fault = Arc::new(TlsFault::new(h2));
532
+ let stream = Recorded {
533
+ inner: stream,
534
+ fault: fault.clone(),
535
+ };
536
+ (Box::new(stream), h2, fault)
537
+ }
538
+ // Cleartext HTTP/2 is prior knowledge (h2c), as gRPC clients use.
539
+ None => (Box::new(socket), settings.http2, Arc::default()),
540
+ };
541
+ let exec = TrackedExec(tracker.clone());
542
+ if h2 {
543
+ let wire = Wire::new(holds.clone());
544
+ let io = TokioIo::new(Tap::new(io, wire.clone()));
545
+ let mut builder = http2::Builder::new(exec);
546
+ builder
547
+ .timer(TokioTimer::new())
548
+ .adaptive_window(true)
549
+ .max_header_list_size(MAX_HEADER_LIST_SIZE)
550
+ .max_send_buf_size(MAX_SEND_BUF_SIZE);
551
+ if let Some((interval, timeout, while_idle)) = settings.keepalive {
552
+ builder
553
+ .keep_alive_interval(interval)
554
+ .keep_alive_timeout(timeout)
555
+ .keep_alive_while_idle(while_idle);
556
+ }
557
+ let (sender, connection) = builder
558
+ .handshake(io)
559
+ .await
560
+ .map_err(|e| Failure::from_hyper(&e))?;
561
+ registering(holds);
562
+ let closed = Signal::new();
563
+ spawn_dispatcher(tracker, holds, connection, &closed, Some(wire.clone()));
564
+ Ok(Connected {
565
+ handshake: Handshake::H2 {
566
+ sender,
567
+ closed,
568
+ wire,
569
+ },
570
+ local_port,
571
+ fault,
572
+ })
573
+ } else {
574
+ let io = TokioIo::new(io);
575
+ let (sender, connection) = http1::Builder::new()
576
+ .max_buf_size(MAX_H1_HEAD)
577
+ .max_header_size(MAX_H1_HEAD)
578
+ .max_headers(MAX_H1_HEADERS)
579
+ .handshake(io)
580
+ .await
581
+ .map_err(|e| Failure::from_hyper(&e))?;
582
+ registering(holds);
583
+ let closed = Signal::new();
584
+ let task = spawn_dispatcher(tracker, holds, connection, &closed, None);
585
+ Ok(Connected {
586
+ handshake: Handshake::H1 {
587
+ sender,
588
+ task,
589
+ closed,
590
+ },
591
+ local_port,
592
+ fault,
593
+ })
594
+ }
595
+ }
596
+
597
+ /// Runs hyper's connection future as a tracked task that fires `closed` once
598
+ /// the future is gone, however the task ends.
599
+ fn spawn_dispatcher<E>(
600
+ tracker: &Arc<Tracker>,
601
+ holds: &Arc<Holds>,
602
+ connection: impl Future<Output = Result<(), E>> + Send + 'static,
603
+ closed: &Arc<Signal>,
604
+ wire: Option<Arc<Wire>>,
605
+ ) -> Task {
606
+ let dispatcher = Dispatcher {
607
+ connection: Some(Box::pin(async move {
608
+ let _ = connection.await;
609
+ })),
610
+ closed: closed.clone(),
611
+ holds: holds.clone(),
612
+ wire,
613
+ };
614
+ let holds = holds.clone();
615
+ tracker.spawn(async move {
616
+ holds.reach("dispatcher").await;
617
+ dispatcher.await;
618
+ })
619
+ }
620
+
621
+ /// Spec hold point between the handshake and the dispatcher's registration,
622
+ /// inside the poll that finished the handshake: parking the thread, not the
623
+ /// task, keeps forced teardown from winning the caller's wait first.
624
+ fn registering(holds: &Holds) {
625
+ holds.block("connect:handshaken");
626
+ }
627
+
628
+ /// HTTP proxy routes. Ruby resolves the proxy (core's ConnectRPC::Proxy) and
629
+ /// passes only the endpoint; nothing here reads proxy environment variables.
630
+ /// A CONNECT exchange has Go net/http's bounds: the response head is capped,
631
+ /// the exchange is capped in time even without a call deadline, and the status
632
+ /// must be exactly 200. Only fixed phrases leave this module, so proxy reply
633
+ /// bytes never reach errors.
634
+ pub mod proxy {
635
+ use std::fmt;
636
+ use std::time::{Duration, Instant};
637
+
638
+ use tokio::io::AsyncWriteExt;
639
+
640
+ use super::Socket;
641
+ use crate::failure::Failure;
642
+
643
+ /// How a request reaches its origin through a proxy.
644
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
645
+ pub enum Mode {
646
+ /// A CONNECT tunnel; the origin's protocol runs inside it.
647
+ Tunnel,
648
+ /// Absolute-form HTTP/1.1 requests with Proxy-Authorization.
649
+ Forward,
650
+ }
651
+
652
+ /// The only place that chooses the mode. TLS and h2c targets tunnel, as
653
+ /// grpc-go does; plaintext HTTP/1.1 is forwarded in absolute form, as Go
654
+ /// net/http and core NetHTTP do.
655
+ pub fn mode(https: bool, http2: bool) -> Mode {
656
+ if https || http2 {
657
+ Mode::Tunnel
658
+ } else {
659
+ Mode::Forward
660
+ }
661
+ }
662
+
663
+ /// A resolved proxy endpoint. Part of the pool key, so direct connections,
664
+ /// different proxies and different credentials never share a connection.
665
+ #[derive(Clone, PartialEq, Eq, Hash)]
666
+ pub struct Route {
667
+ pub host: String,
668
+ pub port: u16,
669
+ /// The Proxy-Authorization value (Basic), marked sensitive.
670
+ pub authorization: Option<http::HeaderValue>,
671
+ pub mode: Mode,
672
+ }
673
+
674
+ impl fmt::Debug for Route {
675
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
676
+ f.write_str("Route(proxy)")
677
+ }
678
+ }
679
+
680
+ /// Bounds for one CONNECT exchange.
681
+ #[derive(Clone, Copy)]
682
+ pub struct Limits {
683
+ pub timeout: Duration,
684
+ pub max_head: usize,
685
+ }
686
+
687
+ fn failed() -> Failure {
688
+ Failure::new("proxy_failed", "proxy tunnel failed")
689
+ }
690
+
691
+ /// Opens a tunnel to `authority` over a connected proxy socket. Nothing past
692
+ /// the response head is consumed. `strict` rejects bytes that arrive with the
693
+ /// head: only an h2c server may speak first (its SETTINGS preface).
694
+ pub async fn tunnel(
695
+ socket: &mut Socket,
696
+ authority: &str,
697
+ authorization: Option<&http::HeaderValue>,
698
+ limits: Limits,
699
+ strict: bool,
700
+ ) -> Result<(), Failure> {
701
+ let started = Instant::now();
702
+ let mut request =
703
+ format!("CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n").into_bytes();
704
+ if let Some(value) = authorization {
705
+ request.extend_from_slice(b"Proxy-Authorization: ");
706
+ request.extend_from_slice(value.as_bytes());
707
+ request.extend_from_slice(b"\r\n");
708
+ }
709
+ request.extend_from_slice(b"\r\n");
710
+ let exchange = async {
711
+ socket
712
+ .write_all(&request)
713
+ .await
714
+ .map_err(|e| Failure::io("closed", &e))?;
715
+ read_head(socket, limits.max_head).await
716
+ };
717
+ let timed_out = || Failure::new("proxy_timeout", "proxy tunnel timed out");
718
+ let (head, extra) = tokio::time::timeout(limits.timeout, exchange)
719
+ .await
720
+ .map_err(|_| timed_out())??;
721
+ // A reply read after the cap passed is never accepted.
722
+ if started.elapsed() >= limits.timeout {
723
+ return Err(timed_out());
724
+ }
725
+ check_status(&head)?;
726
+ if strict && extra {
727
+ return Err(failed());
728
+ }
729
+ Ok(())
730
+ }
731
+
732
+ /// The end of the head at `index`: `\r?\n\r?\n`, returning the index after it.
733
+ fn head_end_at(bytes: &[u8], index: usize) -> Option<usize> {
734
+ let mut at = index;
735
+ if bytes.get(at) == Some(&b'\r') {
736
+ at += 1;
737
+ }
738
+ if bytes.get(at) != Some(&b'\n') {
739
+ return None;
740
+ }
741
+ at += 1;
742
+ match (bytes.get(at), bytes.get(at + 1)) {
743
+ (Some(b'\r'), Some(b'\n')) => Some(at + 2),
744
+ (Some(b'\n'), _) => Some(at + 1),
745
+ _ => None,
746
+ }
747
+ }
748
+
749
+ /// Reads the head without its terminator, peeking so that no byte after it is
750
+ /// consumed, and reports whether more bytes were already buffered.
751
+ async fn read_head(socket: &mut Socket, max: usize) -> Result<(Vec<u8>, bool), Failure> {
752
+ let mut head = Vec::new();
753
+ let mut buffer = vec![0u8; 16_384];
754
+ loop {
755
+ let room = max.saturating_sub(head.len());
756
+ if room == 0 {
757
+ return Err(failed());
758
+ }
759
+ let window = room.min(buffer.len());
760
+ let peeked = socket
761
+ .peek(&mut buffer[..window])
762
+ .await
763
+ .map_err(|e| Failure::io("closed", &e))?;
764
+ if peeked == 0 {
765
+ return Err(failed());
766
+ }
767
+ // A terminator may start in the last three bytes already read.
768
+ let carried = head.len().min(3);
769
+ let mut scan = head[head.len() - carried..].to_vec();
770
+ scan.extend_from_slice(&buffer[..peeked]);
771
+ let found =
772
+ (0..scan.len()).find_map(|index| head_end_at(&scan, index).map(|end| (index, end)));
773
+ let take = match found {
774
+ Some((_, end)) => end - carried,
775
+ None => peeked,
776
+ };
777
+ socket
778
+ .consume(&mut buffer[..take])
779
+ .await
780
+ .map_err(|e| Failure::io("closed", &e))?;
781
+ head.extend_from_slice(&buffer[..take]);
782
+ if let Some((start, end)) = found {
783
+ let head_len = head.len() - (end - start);
784
+ head.truncate(head_len);
785
+ return Ok((head, peeked > take));
786
+ }
787
+ }
788
+ }
789
+
790
+ fn token(byte: u8) -> bool {
791
+ byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte)
792
+ }
793
+
794
+ /// Core NetHTTP's status and field checks: `HTTP/1.[01] NNN[ reason]` and
795
+ /// `token:` fields; 407 and any other non-200 status have fixed phrases.
796
+ fn check_status(head: &[u8]) -> Result<(), Failure> {
797
+ let mut lines = head
798
+ .split(|&byte| byte == b'\n')
799
+ .map(|line| line.strip_suffix(b"\r").unwrap_or(line));
800
+ let status = lines.next().unwrap_or_default();
801
+ let code = status
802
+ .strip_prefix(b"HTTP/1.")
803
+ .filter(|rest| rest.len() >= 5 && matches!(rest[0], b'0' | b'1') && rest[1] == b' ')
804
+ .map(|rest| &rest[2..])
805
+ .filter(|rest| rest[..3].iter().all(u8::is_ascii_digit))
806
+ .filter(|rest| {
807
+ let reason = &rest[3..];
808
+ reason.is_empty()
809
+ || (reason[0] == b' ' && !reason.iter().any(|&b| b == b'\r' || b == b'\n'))
810
+ })
811
+ .map(|rest| &rest[..3]);
812
+ let fields = lines.all(|line| {
813
+ let name = line.iter().take_while(|&&byte| token(byte)).count();
814
+ name > 0 && line.get(name) == Some(&b':')
815
+ });
816
+ let (Some(code), true) = (code, fields) else {
817
+ return Err(failed());
818
+ };
819
+ match code {
820
+ b"200" => Ok(()),
821
+ b"407" => Err(Failure::new("proxy_auth", "proxy authentication failed")),
822
+ _ => Err(Failure::new("proxy_refused", "proxy tunnel refused")),
823
+ }
824
+ }
825
+ }