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..9aa65034 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,201 @@ 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, + 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 + /// 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 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) => { + 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; + } + + if !disable_syn_retransmissions(raw) { + unsafe { closesocket(raw) }; + return None; + } + + 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)) + } + + /// 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, + }; + 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, + ) == 0 + } + } + + 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 +916,28 @@ 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"); + let address = listener.local_addr().expect("listener address"); + drop(listener); + + let started = Instant::now(); + 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(500), + "a closed loopback port must be refused well inside the default probe budget: {elapsed:?}" + ); + } + #[test] fn restart_endpoint_probe_does_not_treat_resolution_errors_as_available() { let error = confirm_backend_endpoint_available_with_resolver(