diff --git a/docs/configuration.md b/docs/configuration.md index a2aff8f..b918ffe 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -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`) | diff --git a/leaf/src/app/dispatcher.rs b/leaf/src/app/dispatcher.rs index 04e4d58..1980c28 100644 --- a/leaf/src/app/dispatcher.rs +++ b/leaf/src/app/dispatcher.rs @@ -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( + bounds_own: bool, + handshake: impl std::future::Future>, +) -> io::Result { + if bounds_own { + handshake.await + } else { + crate::proxy::bounded_handshake(handshake).await + } +} + #[inline] fn log_request(sess: &Session, outbound_tag: &str, handshake_time: Option) { 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); diff --git a/leaf/src/option/mod.rs b/leaf/src/option/mod.rs index c7b4fa9..d8e7663 100644 --- a/leaf/src/option/mod.rs +++ b/leaf/src/option/mod.rs @@ -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, diff --git a/leaf/src/proxy/failover/datagram.rs b/leaf/src/proxy/failover/datagram.rs index c3b7da2..722f685 100644 --- a/leaf/src/proxy/failover/datagram.rs +++ b/leaf/src/proxy/failover/datagram.rs @@ -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")) diff --git a/leaf/src/proxy/failover/stream.rs b/leaf/src/proxy/failover/stream.rs index 265ddcf..c8518a2 100644 --- a/leaf/src/proxy/failover/stream.rs +++ b/leaf/src/proxy/failover/stream.rs @@ -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")) diff --git a/leaf/src/proxy/mod.rs b/leaf/src/proxy/mod.rs index 8baf7da..56d35be 100644 --- a/leaf/src/proxy/mod.rs +++ b/leaf/src/proxy/mod.rs @@ -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( + handshake: impl std::future::Future>, +) -> io::Result { + 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), + )) + }) +} diff --git a/leaf/src/proxy/select/stream.rs b/leaf/src/proxy/select/stream.rs index 0b8f527..27d5ad6 100644 --- a/leaf/src/proxy/select/stream.rs +++ b/leaf/src/proxy/select/stream.rs @@ -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,