From a17cb057c3655548a683ead0fed5e0bc6ed0c3c7 Mon Sep 17 00:00:00 2001 From: Ylang <1643392077@qq.com> Date: Wed, 2 Dec 2026 22:16:48 +0800 Subject: [PATCH 1/2] fix(backend): report a closed loopback port immediately on Windows The managed-backend preflight added in #191 only accepts a refused connection as proof that the endpoint is free. On Windows a refused connection to a closed loopback port is reported only after the SYN retransmission budget expires, which takes about two seconds, and that is longer than the 800 ms default probe timeout. Every managed start was therefore refused with "connection timed out", so Desktop 4.30.0 could not start the backend at all on Windows (#203). Probe loopback targets on a raw Winsock socket with SIO_TCP_INITIAL_RTO / TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS, the same opt-out that Chromium, curl and libuv use. A closed port now reports WSAECONNREFUSED in about 10 ms instead of about 2 s. The behaviour around it is unchanged: an endpoint that answers still blocks a respawn, an inconclusive probe still refuses to start another backend, non-loopback addresses keep using TcpStream::connect_timeout, and every failure to prepare the raw socket falls back to that path. On Windows 11 the nine endpoint-probe tests that fail on main pass with this change: the three probes in backend::http, backend::restart::tests::failed_endpoint_confirmation_retains_the_pid_for_a_retry and the five bridge::commands::tests::run_native_update_install_* cases. --- src-tauri/Cargo.toml | 2 + src-tauri/src/backend/http.rs | 197 +++++++++++++++++++++++++++++++++- 2 files changed, 198 insertions(+), 1 deletion(-) diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 1c725811..cb149366 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -35,7 +35,9 @@ url = "2.5" [target.'cfg(windows)'.dependencies] windows-sys = { version = "0.59", features = [ "Win32_Foundation", + "Win32_Networking_WinSock", "Win32_System_Diagnostics_ToolHelp", + "Win32_System_IO", "Win32_System_Threading", "Win32_UI_Controls", "Win32_UI_WindowsAndMessaging", diff --git a/src-tauri/src/backend/http.rs b/src-tauri/src/backend/http.rs index e2b85a5a..935e8962 100644 --- a/src-tauri/src/backend/http.rs +++ b/src-tauri/src/backend/http.rs @@ -99,7 +99,7 @@ where .checked_duration_since(Instant::now()) .filter(|remaining| !remaining.is_zero()) .ok_or_else(|| inconclusive("probe timed out"))?; - match TcpStream::connect_timeout(&address, remaining) { + match connect_probe(address, remaining) { Ok(_) => { return Err(format!( "Backend endpoint {display_url} is already answering. Stop the existing backend before starting another." @@ -116,6 +116,183 @@ where Ok(()) } +/// Probe one backend address, keeping [`TcpStream::connect_timeout`] semantics. +/// +/// Windows answers a refused connection to a closed loopback port only after +/// its SYN retransmission budget expires, which takes about two seconds. The +/// endpoint check above only needs to tell a refused connection apart from an +/// answering one, so loopback probes on Windows disable those retransmissions +/// for the probe socket, the same way Chromium, curl and libuv do it. +fn connect_probe(address: SocketAddr, timeout: Duration) -> std::io::Result { + #[cfg(windows)] + if is_loopback_socket_address(&address) { + if let Some(result) = windows_loopback_probe::probe(address, timeout) { + return result; + } + } + TcpStream::connect_timeout(&address, timeout) +} + +#[cfg(windows)] +mod windows_loopback_probe { + use std::{ + io::{self, ErrorKind}, + mem::size_of, + net::{SocketAddr, TcpStream}, + os::windows::io::{FromRawSocket, RawSocket}, + ptr::null_mut, + time::Duration, + }; + + use windows_sys::Win32::Networking::WinSock::{ + closesocket, connect, getsockopt, ioctlsocket, select, socket, WSAGetLastError, WSAIoctl, + AF_INET, AF_INET6, FD_SET, FIONBIO, IN6_ADDR, IN6_ADDR_0, INVALID_SOCKET, IN_ADDR, + IN_ADDR_0, IPPROTO_TCP, SOCKADDR, SOCKADDR_IN, SOCKADDR_IN6, SOCKET, SOCKET_ERROR, + SOCK_STREAM, SOL_SOCKET, SO_ERROR, TIMEVAL, WSAEINPROGRESS, WSAEWOULDBLOCK, + }; + + /// `SIO_TCP_INITIAL_RTO` is `_WSAIOW(IOC_VENDOR, 17)`, which windows-sys + /// does not export. The payload is `TCP_INITIAL_RTO_PARAMETERS`. + const SIO_TCP_INITIAL_RTO: u32 = 0x9800_0011; + const TCP_INITIAL_RTO_UNSPECIFIED: u16 = 0xFFFF; + const TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS: u16 = 0xFFFE; + + #[repr(C)] + struct TcpInitialRtoParameters { + rtt: u16, + max_syn_retransmissions: u16, + } + + #[repr(C)] + union SockAddrStorage { + v4: SOCKADDR_IN, + v6: SOCKADDR_IN6, + } + + /// Connect to a loopback address with SYN retransmissions disabled. + /// + /// Returns `None` when the raw socket cannot be prepared, so the caller can + /// fall back to the standard connect path instead of failing the probe. + pub(super) fn probe(address: SocketAddr, timeout: Duration) -> Option> { + let mut storage: SockAddrStorage = unsafe { std::mem::zeroed() }; + let (family, length) = match address { + SocketAddr::V4(v4) => { + let mut ipv4: IN_ADDR = unsafe { std::mem::zeroed() }; + ipv4.S_un = IN_ADDR_0 { + S_addr: u32::from_ne_bytes(v4.ip().octets()), + }; + storage.v4.sin_family = AF_INET; + storage.v4.sin_port = v4.port().to_be(); + storage.v4.sin_addr = ipv4; + (AF_INET as i32, size_of::() as i32) + } + SocketAddr::V6(v6) => { + let mut ipv6: IN6_ADDR = unsafe { std::mem::zeroed() }; + ipv6.u = IN6_ADDR_0 { + Byte: v6.ip().octets(), + }; + storage.v6.sin6_family = AF_INET6; + storage.v6.sin6_port = v6.port().to_be(); + storage.v6.sin6_addr = ipv6; + (AF_INET6 as i32, size_of::() as i32) + } + }; + + let raw = unsafe { socket(family, SOCK_STREAM, IPPROTO_TCP) }; + if raw == INVALID_SOCKET { + return None; + } + + disable_syn_retransmissions(raw); + + let mut nonblocking: u32 = 1; + if unsafe { ioctlsocket(raw, FIONBIO, &mut nonblocking) } == SOCKET_ERROR { + unsafe { closesocket(raw) }; + return None; + } + + let sockaddr = (&storage as *const SockAddrStorage).cast::(); + if unsafe { connect(raw, sockaddr, length) } == SOCKET_ERROR { + let error = unsafe { WSAGetLastError() }; + if error != WSAEWOULDBLOCK && error != WSAEINPROGRESS { + unsafe { closesocket(raw) }; + return Some(Err(io::Error::from_raw_os_error(error))); + } + if let Err(error) = wait_writable(raw, timeout) { + unsafe { closesocket(raw) }; + return Some(Err(error)); + } + } + + let stream = unsafe { TcpStream::from_raw_socket(raw as RawSocket) }; + let _ = stream.set_nonblocking(false); + Some(Ok(stream)) + } + + fn disable_syn_retransmissions(socket: usize) { + let parameters = TcpInitialRtoParameters { + rtt: TCP_INITIAL_RTO_UNSPECIFIED, + max_syn_retransmissions: TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS, + }; + let mut returned = 0u32; + unsafe { + WSAIoctl( + socket, + SIO_TCP_INITIAL_RTO, + (¶meters as *const TcpInitialRtoParameters).cast(), + size_of::() as u32, + null_mut(), + 0, + &mut returned, + null_mut(), + None, + ); + } + } + + fn wait_writable(socket: SOCKET, timeout: Duration) -> io::Result<()> { + let mut write_set: FD_SET = unsafe { std::mem::zeroed() }; + write_set.fd_count = 1; + write_set.fd_array[0] = socket; + // Winsock reports a failed non-blocking connect in the exception set, + // not in the write set, so both have to be watched. + let mut except_set: FD_SET = unsafe { std::mem::zeroed() }; + except_set.fd_count = 1; + except_set.fd_array[0] = socket; + let timeout = TIMEVAL { + tv_sec: timeout.as_secs().min(i32::MAX as u64) as i32, + tv_usec: timeout.subsec_micros() as i32, + }; + + match unsafe { select(0, null_mut(), &mut write_set, &mut except_set, &timeout) } { + 0 => return Err(io::Error::from(ErrorKind::TimedOut)), + SOCKET_ERROR => { + return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() })); + } + _ => {} + } + + let mut socket_error: i32 = 0; + let mut length = size_of::() as i32; + if unsafe { + getsockopt( + socket, + SOL_SOCKET, + SO_ERROR, + (&mut socket_error as *mut i32).cast(), + &mut length, + ) + } == SOCKET_ERROR + { + return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() })); + } + if socket_error != 0 { + return Err(io::Error::from_raw_os_error(socket_error)); + } + Ok(()) + } +} + trait ResponseReader: Read { fn set_response_read_timeout(&self, timeout: Duration) -> std::io::Result<()>; } @@ -721,6 +898,24 @@ mod tests { ); } + #[test] + fn loopback_probe_reports_a_closed_port_without_waiting_for_syn_retransmissions() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind listener"); + let address = listener.local_addr().expect("listener address"); + drop(listener); + + let started = Instant::now(); + let error = connect_probe(address, Duration::from_millis(5_000)) + .expect_err("a closed loopback port must be reported as refused"); + let elapsed = started.elapsed(); + + assert_eq!(error.kind(), ErrorKind::ConnectionRefused, "{error}"); + assert!( + elapsed < Duration::from_millis(1_000), + "a closed loopback port must not wait for the SYN retransmission budget: {elapsed:?}" + ); + } + #[test] fn restart_endpoint_probe_does_not_treat_resolution_errors_as_available() { let error = confirm_backend_endpoint_available_with_resolver( From bc108398f9f85b86c3daa38f5765bb2cb34838a7 Mon Sep 17 00:00:00 2001 From: Ylang <1643392077@qq.com> Date: Wed, 2 Dec 2026 22:49:35 +0800 Subject: [PATCH 2/2] fix(backend): initialise Winsock before the raw loopback probe Address the review on #205: - Call WSAStartup once before the first raw socket. A probe can be the process's first Winsock user, and socket() would then fail with WSANOTINITIALISED and drop the preflight back to the slow path. - Treat a rejected SIO_TCP_INITIAL_RTO as "raw probe unavailable" and fall back to TcpStream::connect_timeout, instead of waiting for a refusal that the default SYN retransmissions will not deliver inside the budget. - Run the regression test on Windows only: the Linux connect path always refuses at once, so it cannot regress there. The test now uses the normal 800 ms probe budget and asserts the refusal arrives well inside it. --- src-tauri/src/backend/http.rs | 44 ++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/src-tauri/src/backend/http.rs b/src-tauri/src/backend/http.rs index 935e8962..9aa65034 100644 --- a/src-tauri/src/backend/http.rs +++ b/src-tauri/src/backend/http.rs @@ -146,9 +146,9 @@ mod windows_loopback_probe { use windows_sys::Win32::Networking::WinSock::{ closesocket, connect, getsockopt, ioctlsocket, select, socket, WSAGetLastError, WSAIoctl, - AF_INET, AF_INET6, FD_SET, FIONBIO, IN6_ADDR, IN6_ADDR_0, INVALID_SOCKET, IN_ADDR, - IN_ADDR_0, IPPROTO_TCP, SOCKADDR, SOCKADDR_IN, SOCKADDR_IN6, SOCKET, SOCKET_ERROR, - SOCK_STREAM, SOL_SOCKET, SO_ERROR, TIMEVAL, WSAEINPROGRESS, WSAEWOULDBLOCK, + WSAStartup, AF_INET, AF_INET6, FD_SET, FIONBIO, IN6_ADDR, IN6_ADDR_0, INVALID_SOCKET, + IN_ADDR, IN_ADDR_0, IPPROTO_TCP, SOCKADDR, SOCKADDR_IN, SOCKADDR_IN6, SOCKET, SOCKET_ERROR, + SOCK_STREAM, SOL_SOCKET, SO_ERROR, TIMEVAL, WSADATA, WSAEINPROGRESS, WSAEWOULDBLOCK, }; /// `SIO_TCP_INITIAL_RTO` is `_WSAIOW(IOC_VENDOR, 17)`, which windows-sys @@ -171,9 +171,14 @@ mod windows_loopback_probe { /// Connect to a loopback address with SYN retransmissions disabled. /// - /// Returns `None` when the raw socket cannot be prepared, so the caller can - /// fall back to the standard connect path instead of failing the probe. + /// Returns `None` when the raw socket cannot be prepared or the provider + /// rejects the RTO option, so the caller falls back to the standard connect + /// path instead of probing with retransmissions still enabled. pub(super) fn probe(address: SocketAddr, timeout: Duration) -> Option> { + if !winsock_ready() { + return None; + } + let mut storage: SockAddrStorage = unsafe { std::mem::zeroed() }; let (family, length) = match address { SocketAddr::V4(v4) => { @@ -203,7 +208,10 @@ mod windows_loopback_probe { return None; } - disable_syn_retransmissions(raw); + if !disable_syn_retransmissions(raw) { + unsafe { closesocket(raw) }; + return None; + } let mut nonblocking: u32 = 1; if unsafe { ioctlsocket(raw, FIONBIO, &mut nonblocking) } == SOCKET_ERROR { @@ -229,7 +237,17 @@ mod windows_loopback_probe { Some(Ok(stream)) } - fn disable_syn_retransmissions(socket: usize) { + /// Winsock has to be initialised before the first socket call, and a probe + /// can be the first Winsock user in the process. + fn winsock_ready() -> bool { + static READY: std::sync::OnceLock = std::sync::OnceLock::new(); + *READY.get_or_init(|| { + let mut data: WSADATA = unsafe { std::mem::zeroed() }; + unsafe { WSAStartup(0x0202, &mut data) == 0 } + }) + } + + fn disable_syn_retransmissions(socket: SOCKET) -> bool { let parameters = TcpInitialRtoParameters { rtt: TCP_INITIAL_RTO_UNSPECIFIED, max_syn_retransmissions: TCP_INITIAL_RTO_NO_SYN_RETRANSMISSIONS, @@ -246,7 +264,7 @@ mod windows_loopback_probe { &mut returned, null_mut(), None, - ); + ) == 0 } } @@ -898,6 +916,10 @@ mod tests { ); } + /// Windows only: the Linux connect path always refuses a closed loopback + /// port at once, so only Windows can regress to the SYN retransmission + /// budget here. + #[cfg(windows)] #[test] fn loopback_probe_reports_a_closed_port_without_waiting_for_syn_retransmissions() { let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind listener"); @@ -905,14 +927,14 @@ mod tests { drop(listener); let started = Instant::now(); - let error = connect_probe(address, Duration::from_millis(5_000)) + let error = connect_probe(address, Duration::from_millis(800)) .expect_err("a closed loopback port must be reported as refused"); let elapsed = started.elapsed(); assert_eq!(error.kind(), ErrorKind::ConnectionRefused, "{error}"); assert!( - elapsed < Duration::from_millis(1_000), - "a closed loopback port must not wait for the SYN retransmission budget: {elapsed:?}" + elapsed < Duration::from_millis(500), + "a closed loopback port must be refused well inside the default probe budget: {elapsed:?}" ); }