fix(dispatcher): bound an outbound's handshake

The dial to an outbound was bounded by OUTBOUND_DIAL_TIMEOUT, and nothing
after it was. A server that accepted and then never answered -- a TLS
ClientHello with no ServerHello, a WebSocket upgrade with no reply -- held
the session, and every plugin instance in its chain, for as long as the
server stayed up. The client could not end it: leaf does not read from
the client until the handshake is done, so it never saw the client leave.

OUTBOUND_HANDSHAKE_TIMEOUT, thirty seconds by default and 0 for none, now
bounds the protocol handshake of stream and datagram outbounds.

A failover is the exception. It already gives each actor its own
failTimeout, and one limit around all of them would cut it off before
its later actors and its last resort. The dispatcher leaves it unbounded
as a whole, and the failover puts the limit around its last resort,
which had none. A select passes on whether its chosen actor is one.
This commit is contained in:
eric committed 2026-12-04 09:55:40 +08:00
1 parent f67087f2f5
commit 752d34ddfd
7 files changed
+117 -33

No files matched your search

+1
View File
@@ -782,6 +782,7 @@ loopback.
|---|---|---|
| `INBOUND_ACCEPT_TIMEOUT` | Seconds a `chain` inbound handshake may take | `60` |
| `OUTBOUND_DIAL_TIMEOUT` | Seconds to connect | `8` |
| `OUTBOUND_HANDSHAKE_TIMEOUT` | Seconds an outbound's protocol handshake may take once connected -- TLS, WebSocket, the proxy request, every stage of a chain. A failover is not bounded as a whole: each actor has its `failTimeout`, and its last resort this limit. `0` for no limit | `30` |
| `OUTBOUND_DIAL_ORDER` | Order to try a name's addresses: `ordered`, `random`, `partial-random` | `ordered` |
| `OUTBOUND_DIAL_CONCURRENCY` | Addresses tried at once | `1` |
| `ENDPOINT_TCP_CONCURRENCY` | Proxy connections at once | `1024` (iOS `45`) |
+18 -3
View File
@@ -85,6 +85,19 @@ impl OutboundDatagram for HealthcheckUdpDatagram {
}
}
/// Runs an outbound's handshake, bounded by `OUTBOUND_HANDSHAKE_TIMEOUT`
/// unless the handler bounds its own attempts.
async fn handshake<T>(
bounds_own: bool,
handshake: impl std::future::Future<Output = io::Result<T>>,
) -> io::Result<T> {
if bounds_own {
handshake.await
} else {
crate::proxy::bounded_handshake(handshake).await
}
}
#[inline]
fn log_request(sess: &Session, outbound_tag: &str, handshake_time: Option<u128>) {
let hs = handshake_time.map_or("failed".to_string(), |hs| format!("{}ms", hs));
@@ -325,7 +338,7 @@ impl Dispatcher {
return;
}
};
match th.handle(&sess, Some(&mut lhs), stream).await {
match handshake(th.bounds_own_handshake(), th.handle(&sess, Some(&mut lhs), stream)).await {
Ok(mut rhs) => {
let elapsed = tokio::time::Instant::now().duration_since(handshake_start);
@@ -390,7 +403,8 @@ impl Dispatcher {
let stream =
crate::proxy::connect_stream_outbound(&sess, self.dns_client.clone(), &h).await?;
h.stream()?.handle(&sess, None, stream).await
let th = h.stream()?;
handshake(th.bounds_own_handshake(), th.handle(&sess, None, stream)).await
}
#[async_recursion]
@@ -473,7 +487,8 @@ impl Dispatcher {
}
};
match h.datagram()?.handle(&sess, transport).await {
let dh = h.datagram()?;
match handshake(dh.bounds_own_handshake(), dh.handle(&sess, transport)).await {
Ok(mut d) => {
let elapsed = tokio::time::Instant::now().duration_since(handshake_start);
+8
View File
@@ -287,6 +287,14 @@ lazy_static! {
get_env_var_or("OUTBOUND_DIAL_TIMEOUT", 8)
};
/// Seconds an outbound's protocol handshake may take once its connection
/// is up, `0` for no limit. Without one, a server that accepts and never
/// answers holds the session, and every plugin instance in its chain, for
/// as long as the server stays up.
pub static ref OUTBOUND_HANDSHAKE_TIMEOUT: u64 = {
get_env_var_or("OUTBOUND_HANDSHAKE_TIMEOUT", 30)
};
pub static ref OUTBOUND_DIAL_ORDER: crate::proxy::DialOrder = {
match get_env_var_or("OUTBOUND_DIAL_ORDER", "ordered".to_string()).as_str() {
"random" => crate::proxy::DialOrder::Random,
+23 -14
View File
@@ -108,6 +108,11 @@ impl OutboundDatagramHandler for Handler {
OutboundConnect::Unknown
}
// Each actor has fail_timeout; the last resort is bounded below.
fn bounds_own_handshake(&self) -> bool {
true
}
fn transport_type(&self) -> DatagramTransportType {
DatagramTransportType::Unknown
}
@@ -143,13 +148,15 @@ impl OutboundDatagramHandler for Handler {
sess.destination,
a.tag()
);
return a
.datagram()?
.handle(
sess,
connect_datagram_outbound(sess, self.dns_client.clone(), a).await?,
)
.await;
return crate::proxy::bounded_handshake(async {
a.datagram()?
.handle(
sess,
connect_datagram_outbound(sess, self.dns_client.clone(), a).await?,
)
.await
})
.await;
}
for i in schedule {
@@ -211,13 +218,15 @@ impl OutboundDatagramHandler for Handler {
sess.destination,
a.tag()
);
return a
.datagram()?
.handle(
sess,
connect_datagram_outbound(sess, self.dns_client.clone(), a).await?,
)
.await;
return crate::proxy::bounded_handshake(async {
a.datagram()?
.handle(
sess,
connect_datagram_outbound(sess, self.dns_client.clone(), a).await?,
)
.await
})
.await;
}
Err(io::Error::other("all outbound attempts failed"))
+25 -16
View File
@@ -125,6 +125,11 @@ impl OutboundStreamHandler for Handler {
OutboundConnect::Unknown
}
// Each actor has fail_timeout; the last resort is bounded below.
fn bounds_own_handshake(&self) -> bool {
true
}
async fn handle<'a>(
&'a self,
sess: &'a Session,
@@ -183,14 +188,16 @@ impl OutboundStreamHandler for Handler {
sess.destination,
a.tag()
);
return a
.stream()?
.handle(
sess,
None,
connect_stream_outbound(sess, self.dns_client.clone(), a).await?,
)
.await;
return crate::proxy::bounded_handshake(async {
a.stream()?
.handle(
sess,
None,
connect_stream_outbound(sess, self.dns_client.clone(), a).await?,
)
.await
})
.await;
}
for (sche_idx, actor_idx) in schedule.into_iter().enumerate() {
@@ -261,14 +268,16 @@ impl OutboundStreamHandler for Handler {
sess.destination,
a.tag()
);
return a
.stream()?
.handle(
sess,
None,
connect_stream_outbound(sess, self.dns_client.clone(), a).await?,
)
.await;
return crate::proxy::bounded_handshake(async {
a.stream()?
.handle(
sess,
None,
connect_stream_outbound(sess, self.dns_client.clone(), a).await?,
)
.await
})
.await;
}
Err(io::Error::other("all outbound attempts failed"))
+37
View File
@@ -582,6 +582,15 @@ pub trait OutboundStreamHandler: Send + Sync + Unpin {
/// communicate with.
fn connect_addr(&self) -> OutboundConnect;
/// Whether this handler bounds each attempt of its handshake itself, so
/// that the dispatcher should not put `OUTBOUND_HANDSHAKE_TIMEOUT` around
/// the whole of it. A failover does: it gives each actor its own time, and
/// one overall limit would cut it off before its later actors and its last
/// resort.
fn bounds_own_handshake(&self) -> bool {
false
}
/// Handles a session with the given stream. On success, returns a
/// stream wraps the incoming stream.
async fn handle<'a>(
@@ -633,6 +642,11 @@ pub trait OutboundDatagramHandler: Send + Sync + Unpin {
/// communicate with.
fn connect_addr(&self) -> OutboundConnect;
/// As for [`OutboundStreamHandler::bounds_own_handshake`].
fn bounds_own_handshake(&self) -> bool {
false
}
/// Returns the transport type of this handler.
fn transport_type(&self) -> DatagramTransportType;
@@ -814,3 +828,26 @@ mod tests {
assert!(!*option::TCP_INBOUND_ABORT_ON_CLOSE);
}
}
/// Bounds an outbound's protocol handshake by `OUTBOUND_HANDSHAKE_TIMEOUT`.
///
/// The dial is already bounded; what follows it is not, and a server that
/// accepts and then says nothing would otherwise hold the session forever.
/// The client cannot end it either: leaf does not read from the client until
/// the handshake is done, so it never sees the client leave.
pub async fn bounded_handshake<T>(
handshake: impl std::future::Future<Output = io::Result<T>>,
) -> io::Result<T> {
let limit = *crate::option::OUTBOUND_HANDSHAKE_TIMEOUT;
if limit == 0 {
return handshake.await;
}
timeout(Duration::from_secs(limit), handshake)
.await
.unwrap_or_else(|_| {
Err(io::Error::new(
io::ErrorKind::TimedOut,
format!("outbound handshake took longer than {}s", limit),
))
})
}
+5
View File
@@ -24,6 +24,11 @@ impl OutboundStreamHandler for Handler {
OutboundConnect::Unknown
}
fn bounds_own_handshake(&self) -> bool {
let a = &self.actors[self.selected.load(Ordering::Relaxed)];
a.stream().map(|h| h.bounds_own_handshake()).unwrap_or(false)
}
async fn handle<'a>(
&'a self,
sess: &'a Session,