Skip to content

An open-source remote desktop application designed for self-hosting, as an alternative to TeamViewer.

fix(port-forward): keep the KCP handle alive and send a close reason (#16880)

RustDesk7b5540bd6119
diff --git a/src/port_forward.rs b/src/port_forward.rs
index 26f8cbc07..356ea4aaf 100644
--- a/src/port_forward.rs
+++ b/src/port_forward.rs
@@ -121,9 +121,10 @@ pub async fn listen(
let mut forward = Framed::new(forward, BytesCodec::new());
let mut close_port_forward = false;
match connect_and_login(&id, &password, &mut ui_receiver, interface.clone(), &mut forward, key, token, is_rdp, &mut close_port_forward, &remote_host, remote_port).await {
- Ok(Some(stream)) => {
+ Ok(Some((stream, kcp))) => {
let interface = interface.clone();
tokio::spawn(async move {
+ let _kcp = kcp;
if let Err(err) = run_forward(forward, stream).await {
interface.msgbox("error", "Error", &err.to_string(), "");
}
@@ -168,13 +169,13 @@ async fn connect_and_login(
close_port_forward: &mut bool,
remote_host: &str,
remote_port: i32,
-) -> ResultType<Option<Stream>> {
+) -> ResultType<Option<(Stream, Option<crate::kcp_stream::KcpStream>)>> {
let conn_type = if is_rdp {
ConnType::RDP
} else {
ConnType::PORT_FORWARD
};
- let ((mut stream, direct, pk, _kcp, _stream_type), (feedback, rendezvous_server)) =
+ let ((mut stream, direct, pk, kcp, _stream_type), (feedback, rendezvous_server)) =
Client::start(id, key, token, conn_type, interface.clone()).await?;
let mut trust = crate::trusted_devices::client::Session::new(
&interface.get_lch().read().unwrap(), stream.is_secured(), pk.as_deref())?;
@@ -242,6 +243,12 @@ async fn connect_and_login(
Some(hash) => login_from_ui(&interface, hash, login, remote_host, remote_port, false, &mut trust, &mut stream).await,
None => pending_login = Some(login),
},
+ // The Close is the listener's, which never sees it once the login has
+ // taken it: end the login and have the listener stop.
+ Some(Data::Close) => {
+ *close_port_forward = true;
+ return Ok(None);
+ }
Some(Data::Message(msg)) => {
let msg = trust.outgoing(msg);
allow_err!(stream.send(&msg).await);
@@ -262,7 +269,7 @@ async fn connect_and_login(
if !buffer.is_empty() {
allow_err!(stream.send_bytes(buffer.into()).await);
}
- Ok(Some(stream))
+ Ok(Some((stream, kcp)))
}
@@ -368,7 +375,7 @@ async fn establish_tunnel(
let mut close_port_forward = false;
match connect_and_login_mux(id, password, ui_receiver, interface.clone(), &mut forward, key, token, is_rdp, &mut close_port_forward, remote_host, remote_port).await {
Ok(Some(outcome)) if outcome.mux => {
- let handle = tunnel.set_muxed(outcome.stream, interface.clone());
+ let handle = tunnel.set_muxed(outcome.stream, outcome.kcp, interface.clone());
if !outcome.local_eof {
let (socket, prebuf) = take_socket(forward, outcome.prebuf);
if let Err(e) = handle.open(remote_host, remote_port, socket, prebuf) {
@@ -421,7 +428,7 @@ async fn connect_and_login_mux(
} else {
ConnType::PORT_FORWARD
};
- let ((mut stream, direct, pk, _kcp, _stream_type), (feedback, rendezvous_server)) =
+ let ((mut stream, direct, pk, kcp, _stream_type), (feedback, rendezvous_server)) =
Client::start(id, key, token, conn_type, interface.clone()).await?;
let mut trust = crate::trusted_devices::client::Session::new(
&interface.get_lch().read().unwrap(), stream.is_secured(), pk.as_deref())?;
@@ -492,6 +499,12 @@ async fn connect_and_login_mux(
Some(hash) => login_from_ui(&interface, hash, login, remote_host, remote_port, true, &mut trust, &mut stream).await,
None => pending_login = Some(login),
},
+ // The Close is the listener's, which never sees it once the login has
+ // taken it: end the login and have the listener stop.
+ Some(Data::Close) => {
+ *close_port_forward = true;
+ return Ok(None);
+ }
Some(Data::Message(msg)) => {
let msg = trust.outgoing(msg);
allow_err!(stream.send(&msg).await);
@@ -513,6 +526,7 @@ async fn connect_and_login_mux(
}
Ok(Some(LoginOutcome {
stream,
+ kcp,
mux,
prebuf: buffer,
local_eof,
@@ -528,7 +542,9 @@ fn run_legacy(
) {
let mut stream = outcome.stream;
let prebuf = outcome.prebuf;
+ let kcp = outcome.kcp;
tokio::spawn(async move {
+ let _kcp = kcp;
stream.set_raw();
if !prebuf.is_empty() {
allow_err!(stream.send_bytes(prebuf.into()).await);
@@ -542,6 +558,8 @@ fn run_legacy(
struct LoginOutcome {
stream: Stream,
+ // Drives a KCP stream's UDP I/O; dropping it kills the stream.
+ kcp: Option<crate::kcp_stream::KcpStream>,
mux: bool,
prebuf: Vec<u8>,
local_eof: bool,
@@ -568,6 +586,25 @@ pub fn mux_enabled() -> bool {
)
}
+/// The port-forward window's last step, called right before its io_loop
+/// returns (`ui_session_interface.rs`).
+///
+/// Why wait 100ms: that io_loop runs on a current_thread runtime that is
+/// dropped the moment it returns, and every task still on it (the mappings,
+/// their tunnels) is dropped with it, never polled again. A KCP tunnel tells
+/// its peer it is closing from its own task,
+/// `port_forward_mux::send_kcp_close_reason`: a send bounded by 30ms, then a
+/// 30ms flush, because KCP only queues the message and its FIN dies with the
+/// KCP handle. Without this wait that never runs, and the peer holds the
+/// connection until its own timeout. 100ms is those 60ms plus room for the
+/// listeners to act on the Close; it is a bound, not a measurement, and
+/// missing it is no worse than not waiting. Which mappings ran over KCP is
+/// not known there, so every port-forward window waits; waiting on the tasks
+/// themselves instead would mean keeping all their handles.
+pub async fn wait_for_tunnel_close_reasons() {
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+}
+
async fn run_forward(forward: Framed<TcpStream, BytesCodec>, stream: Stream) -> ResultType<()> {
log::info!("new port forwarding connection started");
let mut forward = forward;
diff --git a/src/port_forward_mux.rs b/src/port_forward_mux.rs
index 1c9989499..0197db594 100644
--- a/src/port_forward_mux.rs
+++ b/src/port_forward_mux.rs
@@ -474,7 +474,7 @@ mod tunnel {
}
}
- pub fn set_muxed(&self, mut stream: Stream, interface: impl Interface) -> Arc<TunnelHandle> {
+ pub fn set_muxed(&self, mut stream: Stream, kcp: Option<crate::kcp_stream::KcpStream>, interface: impl Interface) -> Arc<TunnelHandle> {
cap_packet_size(&mut stream);
let (data_tx, data_rx) = mpsc::channel(DATA_QUEUE_FRAMES);
let (control_tx, control_rx) = mpsc::unbounded_channel();
@@ -492,6 +492,7 @@ mod tunnel {
self.state.send_replace(TunnelState::Muxed(handle.clone()));
tokio::spawn(tunnel_loop(
stream,
+ kcp,
handle.clone(),
data_rx,
control_rx,
@@ -696,6 +697,8 @@ mod tunnel {
/// the control queue carries `window_update` alone.
async fn tunnel_loop(
mut stream: Stream,
+ // Drives a KCP stream's UDP I/O; dropping it kills the stream.
+ kcp: Option<crate::kcp_stream::KcpStream>,
handle: Arc<TunnelHandle>,
mut data_rx: mpsc::Receiver<Message>,
mut control_rx: mpsc::UnboundedReceiver<Message>,
@@ -738,13 +741,49 @@ mod tunnel {
break format!("send failed: {}", e);
}
}
- _ = lifetime.changed() => break "window closed".to_owned(),
+ _ = lifetime.changed() => {
+ if kcp.is_some() {
+ send_kcp_close_reason(&mut stream).await;
+ }
+ break "window closed".to_owned()
+ }
}
};
log::info!("port forward tunnel ended: {}", err);
handle.close_all();
state.send_replace(TunnelState::Unset);
}
+
+ /// The same flush wait the remote session gives its close reason
+ /// (`io_loop.rs`), reused as the bound on sending it.
+ const KCP_CLOSE_REASON_FLUSH_DELAY: Duration = Duration::from_millis(30);
+
+ /// Tells the peer that this side is closing a KCP tunnel. Without it the
+ /// peer only finds out when its own timeout fires: TCP has the kernel send
+ /// the FIN after we drop the socket, and WebRTC hands its close to a
+ /// process-wide runtime, but KCP's FIN is sent by the tasks of the KCP
+ /// handle, and they stop as soon as the handle is dropped along with the
+ /// stream. KCP only queues the message, so the handle has to stay up a
+ /// moment for it to go out.
+ ///
+ /// The send is bounded too: KCP's stream has no send timeout, so on a dead
+ /// link with a full window it would hold the teardown until KCP itself gave
+ /// up. Bounded, this part of the close fits inside the wait the window
+ /// gives it (`port_forward::wait_for_tunnel_close_reasons`); a data send
+ /// already in flight in another arm is not bounded here, and holds this
+ /// arm until it returns.
+ async fn send_kcp_close_reason(stream: &mut Stream) {
+ let mut misc = Misc::new();
+ misc.set_close_reason("kcp".to_owned());
+ let mut msg = Message::new();
+ msg.set_misc(misc);
+ match tokio::time::timeout(KCP_CLOSE_REASON_FLUSH_DELAY, stream.send(&msg)).await {
+ Ok(Ok(())) => {}
+ Ok(Err(e)) => log::debug!("port forward close reason not sent: {}", e),
+ Err(_) => log::debug!("port forward close reason not sent: send timed out"),
+ }
+ tokio::time::sleep(KCP_CLOSE_REASON_FLUSH_DELAY).await;
+ }
}
#[cfg(test)]
@@ -983,7 +1022,7 @@ mod tests {
let addr = ours.peer_addr().unwrap();
let t = Tunnel::new();
t.claim();
- let _h = t.set_muxed(Stream::Tcp(FramedStream::from(ours, addr)), NoUi::default());
+ let _h = t.set_muxed(Stream::Tcp(FramedStream::from(ours, addr)), None, NoUi::default());
assert!(matches!(t.claim(), Claim::Muxed(_)));
// The codec's three-byte header form, declaring one byte more
// than the cap, and nothing behind it: an uncapped codec waits
@@ -1004,7 +1043,7 @@ mod tests {
let (ours, mut peer) = stream_pair().await;
let t = Tunnel::new();
assert!(matches!(t.claim(), Claim::Claimed));
- let h = t.set_muxed(ours, NoUi::default());
+ let h = t.set_muxed(ours, None, NoUi::default());
let (mut app, sock) = local_pair().await;
h.open("localhost", 80, sock, b"GET / HTTP/1.0\r\n\r\n".to_vec()).unwrap();
let open = recv_frame(&mut peer).await;
@@ -1036,7 +1075,7 @@ mod tests {
let (ours, mut peer) = stream_pair().await;
let t = Tunnel::new();
assert!(matches!(t.claim(), Claim::Claimed));
- let h = t.set_muxed(ours, NoUi::default());
+ let h = t.set_muxed(ours, None, NoUi::default());
let (app, sock) = local_pair().await;
h.open("localhost", 80, sock, Vec::new()).unwrap();
let id = match recv_frame(&mut peer).await.union {
@@ -1065,7 +1104,7 @@ mod tests {
let t = Tunnel::new();
assert!(matches!(t.claim(), Claim::Claimed));
let ui = NoUi::default();
- let h = t.set_muxed(ours, ui.clone());
+ let h = t.set_muxed(ours, None, ui.clone());
for reason in ["unreachable", "unreachable", "no permission"] {
let (mut app, sock) = local_pair().await;
h.open("localhost", 1, sock, vec![]).unwrap();
@@ -1092,7 +1131,7 @@ mod tests {
let (ours, mut peer) = stream_pair().await;
let t = Tunnel::new();
t.claim();
- let h = t.set_muxed(ours, NoUi::default());
+ let h = t.set_muxed(ours, None, NoUi::default());
let (_app, sock) = local_pair().await;
h.open("localhost", 1, sock, vec![]).unwrap();
let id = match recv_frame(&mut peer).await.union {
@@ -1120,7 +1159,7 @@ mod tests {
let (ours, peer) = stream_pair().await;
let t = Tunnel::new();
t.claim();
- let h = t.set_muxed(ours, NoUi::default());
+ let h = t.set_muxed(ours, None, NoUi::default());
let (mut app_a, sock_a) = local_pair().await;
let (mut app_b, sock_b) = local_pair().await;
h.open("localhost", 1, sock_a, vec![]).unwrap();
@@ -1135,7 +1174,7 @@ mod tests {
// The next accept establishes again on the same `Tunnel`.
assert!(matches!(t.claim(), Claim::Claimed));
let (ours, mut peer) = stream_pair().await;
- let h = t.set_muxed(ours, NoUi::default());
+ let h = t.set_muxed(ours, None, NoUi::default());
let (_app_c, sock_c) = local_pair().await;
h.open("localhost", 1, sock_c, vec![]).unwrap();
assert!(matches!(
@@ -1145,6 +1184,49 @@ mod tests {
});
}
+ // A KCP stream dies with the handle that drives its UDP I/O, which is
+ // how a mapping over a UDP punch ended right after login. Closing the
+ // mapping must then reach the peer as a close reason, since KCP gives
+ // it no FIN once the handle is gone.
+ #[test]
+ fn a_tunnel_over_kcp_carries_frames_and_reports_its_close() {
+ rt().block_on(async {
+ use crate::kcp_stream::KcpStream;
+ use hbb_common::tokio::net::UdpSocket;
+ use std::time::Duration;
+ let a = UdpSocket::bind("127.0.0.1:0").await.unwrap();
+ let b = UdpSocket::bind("127.0.0.1:0").await.unwrap();
+ a.connect(b.local_addr().unwrap()).await.unwrap();
+ b.connect(a.local_addr().unwrap()).await.unwrap();
+ let (theirs, ours) = tokio::join!(
+ KcpStream::accept(Arc::new(b), Duration::from_secs(5), None),
+ KcpStream::connect(Arc::new(a), Duration::from_secs(5))
+ );
+ let (_their_kcp, mut peer) = theirs.unwrap();
+ let (kcp, ours) = ours.unwrap();
+ let t = Tunnel::new();
+ t.claim();
+ let h = t.set_muxed(ours, Some(kcp), NoUi::default());
+ let (_app, sock) = local_pair().await;
+ h.open("localhost", 22, sock, vec![]).unwrap();
+ let frame = tokio::time::timeout(Duration::from_secs(5), recv_frame(&mut peer))
+ .await
+ .expect("the open never reached the peer");
+ assert!(matches!(frame.union, Some(port_forward_channel::Union::Open(_))));
+ drop(t);
+ let bytes = tokio::time::timeout(Duration::from_secs(5), peer.next())
+ .await
+ .expect("the close reason never reached the peer")
+ .expect("the link ended without a close reason")
+ .unwrap();
+ let msg = Message::parse_from_bytes(&bytes).unwrap();
+ assert!(matches!(
+ msg.union,
+ Some(message::Union::Misc(m)) if matches!(m.union, Some(misc::Union::CloseReason(_)))
+ ));
+ });
+ }
+
/// An `Interface` that records the dialogs it was asked to show. The
/// tunnel needs it for `handle_test_delay` and for refusal messages.
#[derive(Clone, Default)]
@@ -1244,7 +1326,7 @@ mod tests {
fake_controlled(theirs, format!("127.0.0.1:{}", port));
let t = Tunnel::new();
t.claim();
- let h = t.set_muxed(ours, NoUi::default());
+ let h = t.set_muxed(ours, None, NoUi::default());
(t, h, port)
}
diff --git a/src/ui_session_interface.rs b/src/ui_session_interface.rs
index f317a2134..d9146f2d4 100644
--- a/src/ui_session_interface.rs
+++ b/src/ui_session_interface.rs
@@ -2033,6 +2033,12 @@ pub async fn io_loop<T: InvokeUiSession>(handler: Session<T>, round: u32) {
}
}
Some(Data::Close) => {
+ // Pass the close on before leaving: breaking alone drops the mappings
+ // with this runtime before they ever see it, so no KCP tunnel could
+ // tell its peer it is closing (see the wait below).
+ for s in queues.values() {
+ s.send(Data::Close).ok();
+ }
break;
}
Some(d) => {
@@ -2064,6 +2070,8 @@ pub async fn io_loop<T: InvokeUiSession>(handler: Session<T>, round: u32) {
)
.await;
}
+ // Lets KCP tunnels tell their peers they are closing before this runtime is dropped.
+ crate::port_forward::wait_for_tunnel_close_reasons().await;
return;
}
let mut remote = Remote::new(handler, receiver, sender);