diff --git a/packages/common/src/prelude.rs b/packages/common/src/prelude.rs index 366c70e..0c00194 100644 --- a/packages/common/src/prelude.rs +++ b/packages/common/src/prelude.rs @@ -55,7 +55,6 @@ pub const PRELUDE: &str = r#" this.protocol = ''; this.extensions = ''; this.readyState = 0; - this.bufferedAmount = 0; this.binaryType = 'arraybuffer'; this.onopen = null; this.onmessage = null; @@ -65,6 +64,7 @@ pub const PRELUDE: &str = r#" var self = this; this._id = g.__nsWebSocketOpen(href, list, function (type, a, b, c) { if (type === 'open') { + if (self.readyState !== 0) { return; } self.readyState = 1; self.protocol = a || ''; self._emit({ type: 'open', target: self }); @@ -73,6 +73,7 @@ pub const PRELUDE: &str = r#" } else if (type === 'error') { self._emit({ type: 'error', message: a, target: self }); } else if (type === 'close') { + self._bufferedFinal = self.bufferedAmount; self.readyState = 3; self._emit({ type: 'close', code: a, reason: b || '', wasClean: !!c, target: self }); } @@ -82,6 +83,15 @@ pub const PRELUDE: &str = r#" WebSocket.OPEN = WebSocket.prototype.OPEN = 1; WebSocket.CLOSING = WebSocket.prototype.CLOSING = 2; WebSocket.CLOSED = WebSocket.prototype.CLOSED = 3; + // Bytes queued by send() and not yet written; kept after the close event. + Object.defineProperty(WebSocket.prototype, 'bufferedAmount', { + configurable: true, + enumerable: true, + get: function () { + if (this._bufferedFinal !== undefined) { return this._bufferedFinal; } + return typeof g.__nsWebSocketBufferedAmount === 'function' ? g.__nsWebSocketBufferedAmount(this._id) : 0; + } + }); WebSocket.prototype._emit = function (event) { var handler = this['on' + event.type]; if (typeof handler === 'function') { handler.call(this, event); } diff --git a/runtime/src/esm_http_test.rs b/runtime/src/esm_http_test.rs index 2a99554..87b8a0c 100644 --- a/runtime/src/esm_http_test.rs +++ b/runtime/src/esm_http_test.rs @@ -72,47 +72,89 @@ fn serve(stream: TcpStream, routes: &Routes, requests: &Arc>>) ); } -fn websocket_echo(mut stream: TcpStream, mut reader: BufReader, key: &str) { +fn websocket_accept(stream: &mut TcpStream, key: &str) { let accept = base64(&sha1(format!("{key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11").as_bytes())); let _ = write!( stream, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {accept}\r\n\r\n" ); - loop { - let mut head = [0u8; 2]; - if reader.read_exact(&mut head).is_err() { - return; - } - let opcode = head[0] & 0x0f; - let mut len = (head[1] & 0x7f) as usize; - if len == 126 { - let mut b = [0u8; 2]; - reader.read_exact(&mut b).unwrap(); - len = u16::from_be_bytes(b) as usize; - } - let mut mask = [0u8; 4]; - reader.read_exact(&mut mask).unwrap(); - let mut payload = vec![0u8; len]; - reader.read_exact(&mut payload).unwrap(); - for (i, b) in payload.iter_mut().enumerate() { - *b ^= mask[i % 4]; - } +} + +/// One masked client frame: (opcode, unmasked payload). None at EOF. +fn read_frame(reader: &mut BufReader) -> Option<(u8, Vec)> { + let mut head = [0u8; 2]; + reader.read_exact(&mut head).ok()?; + let opcode = head[0] & 0x0f; + let mut len = (head[1] & 0x7f) as usize; + if len == 126 { + let mut b = [0u8; 2]; + reader.read_exact(&mut b).ok()?; + len = u16::from_be_bytes(b) as usize; + } else if len == 127 { + let mut b = [0u8; 8]; + reader.read_exact(&mut b).ok()?; + len = u64::from_be_bytes(b) as usize; + } + let mut mask = [0u8; 4]; + reader.read_exact(&mut mask).ok()?; + let mut payload = vec![0u8; len]; + reader.read_exact(&mut payload).ok()?; + for (i, b) in payload.iter_mut().enumerate() { + *b ^= mask[i % 4]; + } + Some((opcode, payload)) +} + +/// An unmasked server frame. +fn server_frame(opcode: u8, payload: &[u8]) -> Vec { + let mut frame = vec![0x80 | opcode]; + if payload.len() < 126 { + frame.push(payload.len() as u8); + } else { + frame.push(126); + frame.extend_from_slice(&(payload.len() as u16).to_be_bytes()); + } + frame.extend_from_slice(payload); + frame +} + +fn websocket_echo(mut stream: TcpStream, mut reader: BufReader, key: &str) { + websocket_accept(&mut stream, key); + while let Some((opcode, payload)) = read_frame(&mut reader) { let reply = if opcode == 1 { [b"echo:".as_slice(), &payload].concat() } else { payload }; - let mut frame = vec![0x80 | opcode]; - if reply.len() < 126 { - frame.push(reply.len() as u8); - } else { - frame.push(126); - frame.extend_from_slice(&(reply.len() as u16).to_be_bytes()); - } - frame.extend_from_slice(&reply); - let _ = stream.write_all(&frame); + let _ = stream.write_all(&server_frame(opcode, &reply)); if opcode == 8 { return; } } } +/// A WebSocket server for one connection: accepts the upgrade, then hands the socket to `run`. +/// Returns its ws:// URL. +fn websocket_server(run: impl FnOnce(TcpStream, BufReader) + Send + 'static) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("ws://127.0.0.1:{}/ws", listener.local_addr().unwrap().port()); + std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut key = String::new(); + loop { + let mut h = String::new(); + if reader.read_line(&mut h).is_err() || h == "\r\n" || h.is_empty() { + break; + } + if let Some((k, v)) = h.split_once(':') { + if k.trim().eq_ignore_ascii_case("sec-websocket-key") { + key = v.trim().to_string(); + } + } + } + websocket_accept(&mut stream, &key); + run(stream, reader); + }); + url +} + fn sha1(data: &[u8]) -> [u8; 20] { let mut h: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]; let mut msg = data.to_vec(); @@ -295,6 +337,129 @@ fn native_websocket_round_trip() { assert_eq!(refused, "ok:1006:false"); } +/// The server never reads: `send` returns at once, reads keep arriving, and the server's FIN +/// surfaces as an error and one close (1006). +#[test] +fn native_websocket_reads_while_writes_stall() { + let url = websocket_server(|mut stream, _reader| { + for i in 0..20 { + if stream.write_all(&server_frame(1, format!("tick {i}").as_bytes())).is_err() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + // FIN without a close frame; keep the socket so no RST unblocks the client's writes + let _ = stream.shutdown(std::net::Shutdown::Write); + std::thread::sleep(std::time::Duration::from_secs(30)); + }); + let mut runtime = Runtime::new("."); + runtime.register_delegate_isolate_ptr(); + let got = await_js( + &mut runtime, + &format!( + "new Promise((resolve, reject) => {{ + const s = new WebSocket('{url}'); + let got = 0, stalled = 0, sendMs = -1, closes = 0, errors = 0; + s.onopen = () => {{ + const t0 = Date.now(); + s.send('hi'); + // far more than the socket buffers take while the server isn't reading + const big = new Uint8Array(1 << 20); + for (let i = 0; i < 48; i++) s.send(big); + sendMs = Date.now() - t0; + }}; + s.onmessage = () => {{ got++; if (s.bufferedAmount > 0) stalled++; }}; + s.onerror = () => errors++; + s.onclose = (e) => {{ + closes++; + s.send('after close'); + __ns__setTimeout(() => resolve([got, stalled, sendMs >= 0 && sendMs < 1000, e.code, e.wasClean, errors, closes, s.bufferedAmount > 0, s.readyState].join(':')), 300); + }}; + __ns__setTimeout(() => reject(new Error('timeout ' + got)), 4500); + }})" + ), + ); + assert_eq!(got, "ok:20:20:true:1006:false:1:1:true:3"); +} + +/// close() the server never answers: one close (1006) after the timeout, no messages after it. +#[test] +fn native_websocket_close_timeout_and_no_messages_after_close() { + let url = websocket_server(|mut stream, _reader| { + // keeps sending and never reads (so never sees, or answers, the close frame) + for i in 0..200 { + if stream.write_all(&server_frame(1, format!("tick {i}").as_bytes())).is_err() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + }); + let mut runtime = Runtime::new("."); + runtime.register_delegate_isolate_ptr(); + let got = await_js( + &mut runtime, + &format!( + "new Promise((resolve, reject) => {{ + const s = new WebSocket('{url}'); + let closedAt = 0, closeCallMs = -1, after = 0, closes = 0; + s.onmessage = () => {{ + if (closedAt) {{ after++; return; }} + closedAt = Date.now(); + s.close(1000, 'bye'); + closeCallMs = Date.now() - closedAt; + s.send('ignored'); + }}; + s.onclose = (e) => {{ + closes++; + const waited = Date.now() - closedAt; + __ns__setTimeout(() => resolve([after, e.code, e.wasClean, closes, closeCallMs < 100, waited >= 1500 && waited < 4000].join(':')), 300); + }}; + __ns__setTimeout(() => reject(new Error('timeout')), 4500); + }})" + ), + ); + assert_eq!(got, "ok:0:1006:false:1:true:true"); +} + +#[link(name = "ws2_32")] +extern "system" { + fn getpeername(socket: usize, name: *mut u8, len: *mut i32) -> i32; + fn getsockopt(socket: usize, level: i32, name: i32, value: *mut u8, len: *mut i32) -> i32; +} + +/// WinHTTP has no TCP_NODELAY option but sets it itself: finds the client socket among the +/// process's handles (by its peer port) and checks. +#[test] +fn native_websocket_uses_tcp_nodelay() { + let (port_tx, port_rx) = std::sync::mpsc::channel(); + let url = websocket_server(move |stream, _reader| { + let _ = port_tx.send(stream.local_addr().unwrap().port()); + std::thread::sleep(std::time::Duration::from_secs(3)); + }); + let mut runtime = Runtime::new("."); + runtime.register_delegate_isolate_ptr(); + let got = await_js( + &mut runtime, + &format!("new Promise((resolve) => {{ const s = new WebSocket('{url}'); s.onopen = () => resolve('open'); }})"), + ); + assert_eq!(got, "ok:open"); + let port = port_rx.recv().unwrap(); + let mut nodelay = Vec::new(); + for handle in (4usize..0x10000).step_by(4) { + let mut addr = [0u8; 128]; + let mut len = addr.len() as i32; + // fails (WSAENOTSOCK) for handles that aren't sockets + if unsafe { getpeername(handle, addr.as_mut_ptr(), &mut len) } != 0 || u16::from_be_bytes([addr[2], addr[3]]) != port { + continue; + } + let mut value = [0u8; 4]; + let mut len = 4i32; + let ok = unsafe { getsockopt(handle, 6 /* IPPROTO_TCP */, 1 /* TCP_NODELAY */, value.as_mut_ptr(), &mut len) } == 0; + nodelay.push(ok && value[0] != 0); + } + assert_eq!(nodelay, [true]); +} + #[test] fn legacy_dynamic_import_uses_the_module_loader() { let server = TestServer::start(); diff --git a/runtime/src/global_fns.rs b/runtime/src/global_fns.rs index 779b85c..b002137 100644 --- a/runtime/src/global_fns.rs +++ b/runtime/src/global_fns.rs @@ -1368,7 +1368,6 @@ const HELPER_SOURCE: &str = concat!(r#" this.protocol = ''; this.extensions = ''; this.readyState = 0; - this.bufferedAmount = 0; this.binaryType = 'arraybuffer'; this.onopen = null; this.onmessage = null; @@ -1378,6 +1377,7 @@ const HELPER_SOURCE: &str = concat!(r#" var self = this; this._id = globalThis.__nsWebSocketOpen(href, list, function (type, a, b, c) { if (type === 'open') { + if (self.readyState !== 0) return; self.readyState = 1; self.protocol = a || ''; self._emit({ type: 'open', target: self }); @@ -1386,6 +1386,7 @@ const HELPER_SOURCE: &str = concat!(r#" } else if (type === 'error') { self._emit({ type: 'error', message: a, target: self }); } else if (type === 'close') { + self._bufferedFinal = self.bufferedAmount; self.readyState = 3; self._emit({ type: 'close', code: a, reason: b || '', wasClean: !!c, target: self }); } @@ -1395,6 +1396,15 @@ const HELPER_SOURCE: &str = concat!(r#" WebSocket.OPEN = WebSocket.prototype.OPEN = 1; WebSocket.CLOSING = WebSocket.prototype.CLOSING = 2; WebSocket.CLOSED = WebSocket.prototype.CLOSED = 3; + // Bytes queued by send() and not yet written; kept after the close event. + Object.defineProperty(WebSocket.prototype, 'bufferedAmount', { + configurable: true, + enumerable: true, + get: function () { + if (this._bufferedFinal !== undefined) return this._bufferedFinal; + return typeof globalThis.__nsWebSocketBufferedAmount === 'function' ? globalThis.__nsWebSocketBufferedAmount(this._id) : 0; + } + }); WebSocket.prototype._emit = function (event) { var handler = this['on' + event.type]; if (typeof handler === 'function') handler.call(this, event); @@ -4445,6 +4455,7 @@ pub(crate) fn init_async_helpers( register!("__nsWebSocketOpen", crate::websocket::handle_open); register!("__nsWebSocketSend", crate::websocket::handle_send); register!("__nsWebSocketClose", crate::websocket::handle_close); + register!("__nsWebSocketBufferedAmount", crate::websocket::handle_buffered_amount); register!("__nsModuleConfigureLoader", crate::handle_ns_module_configure_loader); register!("__nsModuleInvalidate", crate::handle_ns_module_invalidate); register!("__nsModuleLoadedUrls", crate::handle_ns_module_loaded_urls); diff --git a/runtime/src/napi_engine/websocket.rs b/runtime/src/napi_engine/websocket.rs index 6390b43..56b3545 100644 --- a/runtime/src/napi_engine/websocket.rs +++ b/runtime/src/napi_engine/websocket.rs @@ -1,8 +1,9 @@ //! Node-API bindings for the native WebSocket (`crate::websocket`, shared with the classic -//! runtime): `__nsWebSocketOpen` / `__nsWebSocketSend` / `__nsWebSocketClose`, plus `pump`, which -//! the event loop runs each turn to deliver socket events on the JS thread. The WHATWG `WebSocket` -//! class over these natives lives in the shared JS prelude. The Vite HMR client needs it, and -//! `@valor/nativescript-websockets` has no Windows implementation. +//! runtime): `__nsWebSocketOpen` / `__nsWebSocketSend` / `__nsWebSocketClose` / +//! `__nsWebSocketBufferedAmount`, plus `pump`, which the event loop runs each turn to deliver +//! socket events on the JS thread. The WHATWG `WebSocket` class over these natives lives in the +//! shared JS prelude. The Vite HMR client needs it, and `@valor/nativescript-websockets` has no +//! Windows implementation. //! //! Install-if-missing: a host that already has `WebSocket` (Node 22+, Bun, Deno) keeps its own. @@ -132,8 +133,8 @@ pub fn install_websocket(env: &Env) -> napi::Result<()> { _ => None, }; let sent = match binary { - Some(bytes) => socket::send(id, &bytes, true), - None => socket::send(id, arg_string(&ctx, 1)?.as_bytes(), false), + Some(bytes) => socket::send(id, bytes, true), + None => socket::send(id, arg_string(&ctx, 1)?.into_bytes(), false), }; ctx.env.get_boolean(sent) })?; @@ -152,6 +153,13 @@ pub fn install_websocket(env: &Env) -> napi::Result<()> { ctx.env.get_undefined() })?; global.set_named_property("__nsWebSocketClose", close)?; + + // `__nsWebSocketBufferedAmount(id)`: bytes queued by send and not yet written. + let buffered = env.create_function_from_closure("__nsWebSocketBufferedAmount", |ctx: CallContext| { + let id = ctx.get::(0)?.coerce_to_number()?.get_int32()?; + ctx.env.create_double(socket::buffered_amount(id) as f64) + })?; + global.set_named_property("__nsWebSocketBufferedAmount", buffered)?; Ok(()) } @@ -162,13 +170,17 @@ pub fn pump(env: &Env) { return; } for (id, event) in events { + let closing = matches!(event, Event::Close { .. }); let Some((cb_env, callback_ref)) = CALLBACKS.with(|c| c.borrow().get(&id).copied()) else { + if closing { + socket::forget(id); + } continue; }; - let closing = matches!(event, Event::Close { .. }); unsafe { deliver(env, callback_ref, event) }; if closing { CALLBACKS.with(|c| c.borrow_mut().remove(&id)); + socket::forget(id); unsafe { let _ = sys::napi_delete_reference(cb_env, callback_ref); } diff --git a/runtime/src/websocket.rs b/runtime/src/websocket.rs index 19b2581..b8e597c 100644 --- a/runtime/src/websocket.rs +++ b/runtime/src/websocket.rs @@ -2,29 +2,36 @@ //! theirs from `@valor/nativescript-websockets`, which has no Windows implementation; the Vite HMR //! client needs one to receive updates. //! -//! Each socket runs its WinHTTP handshake and blocking receive loop on its own thread. Events go -//! onto the owning JS thread's channel and are delivered by `pump()`, which runs with the timer -//! pump (the host drives it from its render/heartbeat loop), so JS is only ever called on the JS -//! thread. `send` runs on the JS thread; `close` sends the close frame without waiting, and the -//! receive loop reports the resulting close. +//! Each socket's thread drives WinHTTP in async mode: the handshake, one pending receive, and one +//! send at a time from a queue. `send` and `close` only queue, so JS never waits on the network, +//! and closing a stuck socket's handles cancels its operations. Events go onto the owning JS +//! thread's channel and are delivered by `pump()`, which runs with the timer pump (the host drives +//! it from its render/heartbeat loop), so JS is only ever called on the JS thread. //! //! The socket threads and event channel (`connect` / `send` / `shutdown` / `take_events`) are //! engine-neutral; the napi engines bind the same natives in `napi_engine::websocket`. #[cfg(feature = "classic")] use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; -use std::sync::atomic::{AtomicI32, Ordering}; +use std::sync::atomic::{AtomicI32, AtomicU64, Ordering}; use std::sync::mpsc::{self, Receiver, Sender}; use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Duration, Instant}; use windows::Win32::Networking::WinHttp::{ - WinHttpWebSocketQueryCloseStatus, WinHttpWebSocketReceive, WinHttpWebSocketSend, - WinHttpWebSocketShutdown, WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE, + WinHttpReceiveResponse, WinHttpSendRequest, WinHttpSetOption, WinHttpSetStatusCallback, + WinHttpWebSocketCompleteUpgrade, WinHttpWebSocketQueryCloseStatus, WinHttpWebSocketReceive, + WinHttpWebSocketSend, WinHttpWebSocketShutdown, WINHTTP_ASYNC_RESULT, + WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING, + WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE, WINHTTP_CALLBACK_STATUS_READ_COMPLETE, + WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE, + WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE, WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE, + WINHTTP_FLAG_ASYNC, WINHTTP_OPTION_CONTEXT_VALUE, WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE, WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE, WINHTTP_WEB_SOCKET_BUFFER_TYPE, - WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE, WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE, - WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE, + WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE, WINHTTP_WEB_SOCKET_STATUS, + WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE, WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE, }; use crate::winhttp::Handle; @@ -39,13 +46,45 @@ pub(crate) enum Event { Close { code: u16, reason: String, clean: bool }, } -struct Socket { - ws: Handle, - _connect: Handle, +/// How long close() waits for the server's close frame before closing with 1006. +const CLOSE_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(2) } else { Duration::from_secs(20) }; + +/// After the close event, how long queued frames (our close reply) get to go out. +const LINGER: Duration = Duration::from_secs(1); + +/// How long a closed handle gets to report HANDLE_CLOSING; past that its buffers are leaked. +const HANDLE_CLOSE_WAIT: Duration = Duration::from_secs(5); + +/// Largest message a socket buffers (the `ws` package's default `maxPayload`). +const MAX_MESSAGE_BYTES: usize = 100 * 1024 * 1024; + +const ERROR_IO_PENDING: u32 = 997; + +/// What a socket's thread waits for: commands from JS and WinHTTP notifications, on one channel. +enum Msg { + Send(Vec, bool), + Close(u16, String), + /// The JS side is gone: close (1001) with no one to tell. + Detach, + SendRequestComplete, + HeadersAvailable, + ReadComplete(u32, WINHTTP_WEB_SOCKET_BUFFER_TYPE), + WriteComplete, + ShutdownComplete, + /// REQUEST_ERROR: an async operation failed (Win32 error code). + Failed(u32), + /// The last notification for a handle. + HandleClosing(usize), +} + +struct Entry { + commands: Sender, + /// Bytes queued by `send` that WinHTTP hasn't written yet. + buffered: Arc, } -fn sockets() -> &'static Mutex>> { - static SOCKETS: OnceLock>>> = OnceLock::new(); +fn sockets() -> &'static Mutex> { + static SOCKETS: OnceLock>> = OnceLock::new(); SOCKETS.get_or_init(|| Mutex::new(HashMap::new())) } @@ -69,10 +108,8 @@ pub(crate) fn clear_thread_sockets() { pub(crate) fn drop_sockets(ids: &[i32]) { if let Ok(mut map) = sockets().lock() { for id in ids { - if let Some(s) = map.remove(id) { - unsafe { - let _ = WinHttpWebSocketShutdown(s.ws.raw(), 1001, None, 0); - } + if let Some(entry) = map.remove(id) { + let _ = entry.commands.send(Msg::Detach); } } } @@ -82,127 +119,513 @@ pub(crate) fn drop_sockets(ids: &[i32]) { /// through `take_events` on this (the JS) thread. pub(crate) fn connect(url: String, protocols: Vec) -> i32 { let id = NEXT_ID.fetch_add(1, Ordering::Relaxed); - let tx = CHANNEL.with(|(tx, _)| tx.clone()); - std::thread::Builder::new() + let events = CHANNEL.with(|(tx, _)| tx.clone()); + let (commands, rx) = mpsc::channel(); + let buffered = Arc::new(AtomicU64::new(0)); + let context = Arc::new(Context { tx: commands.clone() }); + if let Ok(mut map) = sockets().lock() { + map.insert(id, Entry { commands, buffered: buffered.clone() }); + } + let thread_events = events.clone(); + let spawned = std::thread::Builder::new() .name(format!("ns-websocket-{id}")) - .spawn(move || run_socket(id, url, protocols, tx)) - .ok(); + .spawn(move || run_socket(id, url, protocols, rx, context, buffered, thread_events)); + if let Err(e) = spawned { + let _ = events.send((id, Event::Error(format!("WebSocket: {e}")))); + let _ = events.send((id, Event::Close { code: 1006, reason: String::new(), clean: false })); + } id } -/// Send one text or binary message. False when the socket isn't open. -pub(crate) fn send(id: i32, bytes: &[u8], binary: bool) -> bool { - let Some(socket) = sockets().lock().ok().and_then(|m| m.get(&id).cloned()) else { +/// Queues a message; false for an unknown socket. Dropped once the socket's thread has finished. +pub(crate) fn send(id: i32, bytes: Vec, binary: bool) -> bool { + let Ok(map) = sockets().lock() else { return false; }; - let kind = if binary { - WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE - } else { - WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE + let Some(entry) = map.get(&id) else { + return false; }; - unsafe { WinHttpWebSocketSend(socket.ws.raw(), kind, Some(bytes)) == 0 } + entry.buffered.fetch_add(bytes.len() as u64, Ordering::Relaxed); + let _ = entry.commands.send(Msg::Send(bytes, binary)); + true } -/// Send the close frame without waiting; the receive loop reports the resulting close. +/// Queues the close frame; the close is 1006 if the server doesn't answer within `CLOSE_TIMEOUT`. pub(crate) fn shutdown(id: i32, code: u16, reason: &str) { - let reason = &reason.as_bytes()[..reason.len().min(123)]; - if let Some(socket) = sockets().lock().ok().and_then(|m| m.get(&id).cloned()) { - unsafe { - let _ = WinHttpWebSocketShutdown( - socket.ws.raw(), - code, - if reason.is_empty() { None } else { Some(reason.as_ptr() as *const c_void) }, - reason.len() as u32, - ); + if let Ok(map) = sockets().lock() { + if let Some(entry) = map.get(&id) { + let _ = entry.commands.send(Msg::Close(code, reason.to_string())); } } } +/// `bufferedAmount`: bytes queued by `send` that haven't been written to the network. +pub(crate) fn buffered_amount(id: i32) -> u64 { + sockets() + .lock() + .ok() + .and_then(|m| m.get(&id).map(|e| e.buffered.load(Ordering::Relaxed))) + .unwrap_or(0) +} + +/// Drop the JS side of a socket once its close event was delivered. +pub(crate) fn forget(id: i32) { + if let Ok(mut map) = sockets().lock() { + map.remove(&id); + } +} + /// Socket events queued since the last call, in arrival order. pub(crate) fn take_events() -> Vec<(i32, Event)> { CHANNEL.with(|(_, rx)| rx.try_iter().collect()) } -/// Largest message a socket buffers, the `ws` package's default `maxPayload`: a server streaming -/// one endless message must not exhaust memory. -const MAX_MESSAGE_BYTES: usize = 100 * 1024 * 1024; +/// WinHTTP's callback context: one strong count per handle that carries it, released by that +/// handle's HANDLE_CLOSING, the last notification for it. +struct Context { + tx: Sender, +} + +fn context_value(context: &Arc) -> usize { + Arc::into_raw(context.clone()) as usize +} -fn run_socket(id: i32, url: String, protocols: Vec, tx: Sender<(i32, Event)>) { - let (ws, connect) = match crate::winhttp::websocket_connect(&url, &protocols) { - Ok(pair) => pair, - Err(e) => { - let _ = tx.send((id, Event::Error(e))); - let _ = tx.send((id, Event::Close { code: 1006, reason: String::new(), clean: false })); +unsafe fn release_context(value: usize) { + drop(Arc::from_raw(value as *const Context)); +} + +/// WinHTTP status callback (any thread, possibly inside the call that started the operation): +/// forwards completions to the socket's thread. +unsafe extern "system" fn on_status( + handle: *mut c_void, + context: usize, + status: u32, + info: *mut c_void, + _info_len: u32, +) { + if context == 0 { + return; + } + let ctx = &*(context as *const Context); + let msg = match status { + WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE => Msg::SendRequestComplete, + WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE => Msg::HeadersAvailable, + WINHTTP_CALLBACK_STATUS_READ_COMPLETE if !info.is_null() => { + let s = *(info as *const WINHTTP_WEB_SOCKET_STATUS); + Msg::ReadComplete(s.dwBytesTransferred, s.eBufferType) + } + WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE => Msg::WriteComplete, + WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE => Msg::ShutdownComplete, + // A WINHTTP_WEB_SOCKET_ASYNC_RESULT for socket operations; it starts with this. + WINHTTP_CALLBACK_STATUS_REQUEST_ERROR if !info.is_null() => { + Msg::Failed((*(info as *const WINHTTP_ASYNC_RESULT)).dwError) + } + WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING => { + let _ = ctx.tx.send(Msg::HandleClosing(handle as usize)); + release_context(context); return; } + _ => return, }; - let socket = Arc::new(Socket { ws, _connect: connect }); - if let Ok(mut map) = sockets().lock() { - map.insert(id, socket.clone()); + let _ = ctx.tx.send(msg); +} + +/// The async session all sockets share. +fn session() -> Result<&'static Handle, String> { + static SESSION: OnceLock> = OnceLock::new(); + SESSION + .get_or_init(|| { + let session = crate::winhttp::new_session(WINHTTP_FLAG_ASYNC)?; + unsafe { + WinHttpSetStatusCallback( + session.raw(), + Some(on_status), + WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, + 0, + ); + } + Ok(session) + }) + .as_ref() + .map_err(|e| e.clone()) +} + +fn error_text(err: u32) -> String { + let known = match err { + 12002 => "The operation timed out", + 12007 => "The server name could not be resolved", + 12017 => "The operation was cancelled", + 12029 => "A connection with the server could not be established", + 12030 => "The connection with the server was terminated abnormally", + 12152 => "The server returned an invalid or unrecognized response", + 12175 => "A security error occurred", + _ => "", + }; + if !known.is_empty() { + return known.to_string(); + } + let message = windows::core::Error::from_hresult(windows::core::HRESULT::from_win32(err)).message(); + if message.is_empty() { + format!("WebSocket error {err}") + } else { + message } - let _ = tx.send((id, Event::Open(protocols.first().cloned().unwrap_or_default()))); +} - let mut message: Vec = Vec::new(); - let mut buf = vec![0u8; 64 * 1024]; - let close = loop { - let mut read = 0u32; - let mut kind = WINHTTP_WEB_SOCKET_BUFFER_TYPE(0); +/// Reports a socket's events to JS: exactly one close event, even if the thread ends early. +struct Report { + id: i32, + events: Sender<(i32, Event)>, + done: bool, +} + +impl Report { + fn send(&self, event: Event) { + let _ = self.events.send((self.id, event)); + } + + /// The close event, after an error event when `error` is set. Only the first call counts. + fn close(&mut self, error: Option, code: u16, reason: String, clean: bool) { + if std::mem::replace(&mut self.done, true) { + return; + } + if let Some(error) = error { + self.send(Event::Error(error)); + } + self.send(Event::Close { code, reason, clean }); + } +} + +impl Drop for Report { + fn drop(&mut self) { + self.close(Some("WebSocket connection failed".into()), 1006, String::new(), false); + } +} + +/// An outgoing frame, queued until WinHTTP has finished the one before it. +enum Out { + Frame(Vec, bool), + Shutdown(u16, String), +} + +/// One connection's WinHTTP state, owned by its thread. Buffers WinHTTP may still read or write +/// live here until the handles using them report HANDLE_CLOSING. +struct Conn { + rx: Receiver, + context: Arc, + connect: Option, + request: Option, + ws: Option, + /// Handles carrying our context that haven't reported HANDLE_CLOSING. + live: Vec, + headers: Vec, + recv: Vec, + /// The frame WinHTTP is sending. + sending: Option>, + shutting_down: bool, + reason: Vec, +} + +impl Conn { + /// The next command or notification; None once `deadline` passes. + fn next(&mut self, deadline: Option) -> Option { + loop { + let msg = match deadline { + Some(d) => self.rx.recv_timeout(d.saturating_duration_since(Instant::now())).ok()?, + // never disconnected: `context` holds a sender + None => self.rx.recv().ok()?, + }; + if let Msg::HandleClosing(h) = msg { + self.live.retain(|x| *x != h); + continue; + } + return Some(msg); + } + } + + fn ws(&self) -> *mut c_void { + self.ws.as_ref().map_or(std::ptr::null_mut(), |h| h.raw()) + } + + /// Waits for `want` during the handshake. Err(None): close() or detach came first. + fn wait(&mut self, want: fn(&Msg) -> bool) -> Result<(), Option> { + loop { + match self.next(None) { + Some(m) if want(&m) => return Ok(()), + Some(Msg::Failed(e)) => return Err(Some(error_text(e))), + Some(Msg::Close(..)) => { + return Err(Some("WebSocket is closed before the connection is established.".into())) + } + Some(Msg::Detach) | None => return Err(None), + Some(_) => {} + } + } + } + + /// Upgrade handshake; returns the subprotocol the server selected. + fn handshake(&mut self, url: &str, protocols: &[String]) -> Result> { + let (connect, request, headers) = + crate::winhttp::websocket_request(session().map_err(Some)?, url, protocols).map_err(Some)?; + self.connect = Some(connect); + self.headers = headers; + let value = context_value(&self.context); + let set = unsafe { + WinHttpSetOption(Some(request.raw()), WINHTTP_OPTION_CONTEXT_VALUE, Some(&value.to_ne_bytes())) + }; + if let Err(e) = set { + unsafe { release_context(value) }; + return Err(Some(format!("WebSocket: {}", e.message()))); + } + let raw = request.raw(); + self.live.push(raw as usize); + self.request = Some(request); + let headers = if self.headers.is_empty() { None } else { Some(self.headers.as_slice()) }; + unsafe { WinHttpSendRequest(raw, headers, None, 0, 0, value) } + .map_err(|e| Some(format!("WebSocket connection failed: {}", e.message())))?; + self.wait(|m| matches!(m, Msg::SendRequestComplete))?; + unsafe { WinHttpReceiveResponse(raw, std::ptr::null_mut()) } + .map_err(|e| Some(format!("WebSocket connection failed: {}", e.message())))?; + self.wait(|m| matches!(m, Msg::HeadersAvailable))?; + let (status, protocol) = crate::winhttp::websocket_response(self.request.as_ref().unwrap()); + if status != 101 { + return Err(Some(format!("WebSocket handshake failed: HTTP {status}"))); + } + let value = context_value(&self.context); + let ws = unsafe { WinHttpWebSocketCompleteUpgrade(raw, Some(value)) }; + if ws.is_null() { + let e = windows::core::Error::from_thread().message(); + unsafe { release_context(value) }; + return Err(Some(format!("WinHttpWebSocketCompleteUpgrade failed: {e}"))); + } + self.live.push(ws as usize); + self.ws = Some(Handle::new(ws, "WinHttpWebSocketCompleteUpgrade").map_err(Some)?); + self.request = None; + Ok(protocol) + } + + fn receive(&mut self) -> Result<(), String> { let err = unsafe { WinHttpWebSocketReceive( - socket.ws.raw(), - buf.as_mut_ptr() as *mut c_void, - buf.len() as u32, - &mut read, - &mut kind, + self.ws(), + self.recv.as_mut_ptr() as *mut c_void, + self.recv.len() as u32, + std::ptr::null_mut(), + std::ptr::null_mut(), ) }; - if err != 0 { - let reason = windows::core::Error::from_hresult(windows::core::HRESULT::from_win32(err)).message(); - let _ = tx.send((id, Event::Error(reason))); - break Event::Close { code: 1006, reason: String::new(), clean: false }; + if err == 0 { + Ok(()) + } else { + Err(error_text(err)) } - if message.len() + read as usize > MAX_MESSAGE_BYTES { - unsafe { - let _ = WinHttpWebSocketShutdown(socket.ws.raw(), 1009, None, 0); + } + + /// Start the next queued send if none is in flight. + fn flush(&mut self, out: &mut VecDeque) -> Result<(), String> { + while self.sending.is_none() && !self.shutting_down { + let Some(next) = out.pop_front() else { + return Ok(()); + }; + let ws = self.ws(); + let err = match next { + Out::Frame(bytes, binary) => { + let kind = if binary { + WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE + } else { + WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE + }; + let bytes = self.sending.insert(bytes); + unsafe { WinHttpWebSocketSend(ws, kind, Some(bytes.as_slice())) } + } + Out::Shutdown(code, reason) => { + self.reason = reason.into_bytes(); + self.reason.truncate(123); + let reason = if self.reason.is_empty() { None } else { Some(self.reason.as_ptr() as *const c_void) }; + match unsafe { WinHttpWebSocketShutdown(ws, code, reason, self.reason.len() as u32) } { + ERROR_IO_PENDING => { + self.shutting_down = true; + 0 + } + err => err, + } + } + }; + if err != 0 { + return Err(error_text(err)); } - let _ = tx.send((id, Event::Error("WebSocket message exceeds 100 MiB".to_string()))); - break Event::Close { code: 1009, reason: String::new(), clean: false }; } - message.extend_from_slice(&buf[..read as usize]); - match kind { - WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE | WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE => {} - WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE => { - let text = String::from_utf8_lossy(&std::mem::take(&mut message)).into_owned(); - let _ = tx.send((id, Event::Text(text))); + Ok(()) + } +} + +impl Drop for Conn { + fn drop(&mut self) { + // Closing the handles cancels their pending operations. + self.ws = None; + self.request = None; + let deadline = Instant::now() + HANDLE_CLOSE_WAIT; + while !self.live.is_empty() { + match self.rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + Ok(Msg::HandleClosing(h)) => self.live.retain(|x| *x != h), + Ok(_) => {} + Err(_) => { + std::mem::forget(std::mem::take(&mut self.recv)); + std::mem::forget(self.sending.take()); + std::mem::forget(std::mem::take(&mut self.headers)); + std::mem::forget(std::mem::take(&mut self.reason)); + break; + } } - WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE => { - let _ = tx.send((id, Event::Binary(std::mem::take(&mut message)))); + } + // `connect` closes after its children. + } +} + +fn run_socket( + id: i32, + url: String, + protocols: Vec, + rx: Receiver, + context: Arc, + buffered: Arc, + events: Sender<(i32, Event)>, +) { + let mut report = Report { id, events, done: false }; + let mut conn = Conn { + rx, + context, + connect: None, + request: None, + ws: None, + live: Vec::new(), + headers: Vec::new(), + recv: vec![0u8; 64 * 1024], + sending: None, + shutting_down: false, + reason: Vec::new(), + }; + match conn.handshake(&url, &protocols) { + Ok(protocol) => report.send(Event::Open(protocol)), + Err(error) => { + report.close(error, 1006, String::new(), false); + return; + } + } + serve(&mut conn, &mut report, &buffered); +} + +/// Runs an open socket until its close event is reported (and our close frame had a moment to +/// go out). +fn serve(conn: &mut Conn, report: &mut Report, buffered: &AtomicU64) { + let mut out: VecDeque = VecDeque::new(); + let mut message: Vec = Vec::new(); + // our close frame is queued or sent: nothing more goes out after it + let mut close_queued = false; + // close() timeout, then (after the close event) the linger time + let mut deadline: Option = None; + if let Err(e) = conn.receive() { + report.close(Some(e), 1006, String::new(), false); + return; + } + loop { + if let Err(e) = conn.flush(&mut out) { + report.close(Some(e), 1006, String::new(), false); + return; + } + if report.done && conn.sending.is_none() && !conn.shutting_down && out.is_empty() { + return; + } + let Some(msg) = conn.next(deadline) else { + // close() unanswered (a no-op once the close event was reported) + report.close(None, 1006, String::new(), false); + return; + }; + match msg { + Msg::Send(bytes, binary) => { + if !close_queued { + out.push_back(Out::Frame(bytes, binary)); + } + } + Msg::Close(..) | Msg::Detach if close_queued => {} + Msg::Close(code, reason) => { + close_queued = true; + out.push_back(Out::Shutdown(code, reason)); + deadline = Some(Instant::now() + CLOSE_TIMEOUT); + } + Msg::Detach => { + close_queued = true; + out.push_back(Out::Shutdown(1001, String::new())); + deadline = Some(Instant::now() + CLOSE_TIMEOUT); + } + Msg::ReadComplete(read, kind) => { + if report.done { + continue; + } + if message.len() + read as usize > MAX_MESSAGE_BYTES { + report.close(Some("WebSocket message exceeds 100 MiB".into()), 1009, String::new(), false); + out.retain(|o| matches!(o, Out::Shutdown(..))); + if !close_queued { + close_queued = true; + out.push_back(Out::Shutdown(1009, String::new())); + } + deadline = Some(Instant::now() + LINGER); + continue; + } + message.extend_from_slice(&conn.recv[..read as usize]); + match kind { + WINHTTP_WEB_SOCKET_UTF8_FRAGMENT_BUFFER_TYPE | WINHTTP_WEB_SOCKET_BINARY_FRAGMENT_BUFFER_TYPE => {} + WINHTTP_WEB_SOCKET_UTF8_MESSAGE_BUFFER_TYPE => { + let text = String::from_utf8_lossy(&std::mem::take(&mut message)).into_owned(); + report.send(Event::Text(text)); + } + WINHTTP_WEB_SOCKET_BINARY_MESSAGE_BUFFER_TYPE => { + report.send(Event::Binary(std::mem::take(&mut message))); + } + WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE => { + let mut code = 1005u16; + let mut reason = [0u8; 123]; + let mut reason_len = 0u32; + unsafe { + let _ = WinHttpWebSocketQueryCloseStatus( + conn.ws(), + &mut code, + Some(reason.as_mut_ptr() as *mut c_void), + reason.len() as u32, + &mut reason_len, + ); + } + let reason = String::from_utf8_lossy(&reason[..reason_len as usize]).into_owned(); + // The server is closing: drop unsent frames, answer with its code (unless + // our close frame is already queued or sent), and give that a moment. + out.retain(|o| matches!(o, Out::Shutdown(..))); + if !close_queued { + close_queued = true; + out.push_back(Out::Shutdown(code, String::new())); + } + report.close(None, code, reason, true); + deadline = Some(Instant::now() + LINGER); + continue; + } + _ => {} + } + if let Err(e) = conn.receive() { + report.close(Some(e), 1006, String::new(), false); + return; + } } - WINHTTP_WEB_SOCKET_CLOSE_BUFFER_TYPE => { - let mut code = 1005u16; - let mut reason = [0u8; 123]; - let mut reason_len = 0u32; - unsafe { - let _ = WinHttpWebSocketQueryCloseStatus( - socket.ws.raw(), - &mut code, - Some(reason.as_mut_ptr() as *mut c_void), - reason.len() as u32, - &mut reason_len, - ); - // Complete the closing handshake if we didn't start it. - let _ = WinHttpWebSocketShutdown(socket.ws.raw(), code, None, 0); + Msg::WriteComplete => { + if let Some(sent) = conn.sending.take() { + buffered.fetch_sub(sent.len() as u64, Ordering::Relaxed); } - let reason = String::from_utf8_lossy(&reason[..reason_len as usize]).into_owned(); - break Event::Close { code, reason, clean: true }; } - _ => {} + Msg::ShutdownComplete => conn.shutting_down = false, + Msg::Failed(err) => { + report.close(Some(error_text(err)), 1006, String::new(), false); + return; + } + Msg::SendRequestComplete | Msg::HeadersAvailable | Msg::HandleClosing(_) => {} } - }; - if let Ok(mut map) = sockets().lock() { - map.remove(&id); } - let _ = tx.send((id, close)); } /// `__nsWebSocketOpen(url, protocols, onEvent) → id`. `onEvent(type, a, b, c)` receives @@ -258,7 +681,18 @@ pub(crate) fn handle_send( } else { (data.to_rust_string_lossy(scope).into_bytes(), false) }; - rv.set(v8::Boolean::new(scope, send(id, &bytes, binary)).into()); + rv.set(v8::Boolean::new(scope, send(id, bytes, binary)).into()); +} + +/// `__nsWebSocketBufferedAmount(id)`: bytes queued by `send` and not yet written. +#[cfg(feature = "classic")] +pub(crate) fn handle_buffered_amount( + scope: &mut v8::PinScope<'_, '_>, + args: v8::FunctionCallbackArguments, + mut rv: v8::ReturnValue, +) { + let id = args.get(0).int32_value(scope).unwrap_or(0); + rv.set(v8::Number::new(scope, buffered_amount(id) as f64).into()); } /// `__nsWebSocketClose(id, code, reason)`. @@ -302,11 +736,14 @@ pub(crate) fn pump() { let scope = &mut v8::ContextScope::new(scope, context); v8::tc_scope!(tc, scope); for (id, event) in events { + let closing = matches!(event, Event::Close { .. }); let Some(callback) = CALLBACKS.with(|c| c.borrow().get(&id).cloned()) else { + if closing { + forget(id); + } continue; }; let callback = v8::Local::new(tc, &callback); - let closing = matches!(event, Event::Close { .. }); let argv: Vec> = match event { Event::Open(protocol) => vec![str_val(tc, "open"), str_val(tc, &protocol)], Event::Text(text) => vec![str_val(tc, "message"), str_val(tc, &text)], @@ -334,6 +771,7 @@ pub(crate) fn pump() { } if closing { CALLBACKS.with(|c| c.borrow_mut().remove(&id)); + forget(id); } } if !crate::defer_microtask_drain() { diff --git a/runtime/src/winhttp.rs b/runtime/src/winhttp.rs index 2c6a3c8..cf1b604 100644 --- a/runtime/src/winhttp.rs +++ b/runtime/src/winhttp.rs @@ -1,19 +1,20 @@ -//! Minimal WinHTTP client: blocking GETs for the HTTP ES-module loader and the upgrade handshake -//! behind the native `WebSocket`. WinHTTP rather than a Rust HTTP stack so https dev servers use -//! the system TLS/certificate store with no extra dependencies. +//! Minimal WinHTTP client: blocking GETs for the HTTP ES-module loader and the upgrade request +//! behind the native `WebSocket` (which `websocket.rs` drives in async mode). WinHTTP rather than +//! a Rust HTTP stack so https dev servers use the system TLS/certificate store with no extra +//! dependencies. use std::ffi::c_void; use std::sync::OnceLock; -use windows::core::{HSTRING, PCWSTR}; +use windows::core::{w, HSTRING, PCWSTR}; use windows::Win32::Networking::WinHttp::{ WinHttpCloseHandle, WinHttpConnect, WinHttpOpen, WinHttpOpenRequest, WinHttpQueryDataAvailable, WinHttpQueryHeaders, WinHttpQueryOption, WinHttpReadData, WinHttpReceiveResponse, - WinHttpSendRequest, WinHttpSetOption, WinHttpSetTimeouts, WinHttpWebSocketCompleteUpgrade, + WinHttpSendRequest, WinHttpSetOption, WinHttpSetTimeouts, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_DISABLE_COOKIES, WINHTTP_FLAG_REFRESH, WINHTTP_FLAG_SECURE, WINHTTP_OPEN_REQUEST_FLAGS, WINHTTP_OPTION_DISABLE_FEATURE, - WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, WINHTTP_OPTION_URL, WINHTTP_QUERY_CONTENT_TYPE, WINHTTP_QUERY_FLAG_NUMBER, - WINHTTP_QUERY_STATUS_CODE, + WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, WINHTTP_OPTION_URL, WINHTTP_QUERY_CONTENT_TYPE, WINHTTP_QUERY_CUSTOM, + WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_QUERY_STATUS_CODE, }; /// A WinHTTP handle, closed on drop. @@ -28,7 +29,7 @@ impl Handle { pub(crate) fn raw(&self) -> *mut c_void { self.0 } - fn new(raw: *mut c_void, what: &str) -> Result { + pub(crate) fn new(raw: *mut c_void, what: &str) -> Result { if raw.is_null() { Err(format!("{what} failed: {}", windows::core::Error::from_thread().message())) } else { @@ -45,29 +46,29 @@ impl Drop for Handle { } } +/// A WinHTTP session (`flags`: 0 or `WINHTTP_FLAG_ASYNC`). +pub(crate) fn new_session(flags: u32) -> Result { + let raw = unsafe { + WinHttpOpen( + &HSTRING::from("NativeScript-Windows"), + WINHTTP_ACCESS_TYPE_NO_PROXY, + PCWSTR::null(), + PCWSTR::null(), + flags, + ) + }; + let h = Handle::new(raw, "WinHttpOpen")?; + // Connect/send/receive timeouts: a dev server that stops answering must surface as an + // import error, not a UI thread blocked forever. + unsafe { + let _ = WinHttpSetTimeouts(h.raw(), 5_000, 5_000, 15_000, 30_000); + } + Ok(h) +} + fn session() -> Result<&'static Handle, String> { static SESSION: OnceLock> = OnceLock::new(); - SESSION - .get_or_init(|| { - let raw = unsafe { - WinHttpOpen( - &HSTRING::from("NativeScript-Windows"), - WINHTTP_ACCESS_TYPE_NO_PROXY, - PCWSTR::null(), - PCWSTR::null(), - 0, - ) - }; - let h = Handle::new(raw, "WinHttpOpen")?; - // Connect/send/receive timeouts: a dev server that stops answering must surface as an - // import error, not a UI thread blocked forever. - unsafe { - let _ = WinHttpSetTimeouts(h.raw(), 5_000, 5_000, 15_000, 30_000); - } - Ok(h) - }) - .as_ref() - .map_err(|e| e.clone()) + SESSION.get_or_init(|| new_session(0)).as_ref().map_err(|e| e.clone()) } pub(crate) struct Response { @@ -78,8 +79,8 @@ pub(crate) struct Response { pub final_url: String, } -/// Open a GET request (connected, not yet sent) for `url` with `extra_headers` (CRLF-separated). -fn open_get(url: &str) -> Result<(Handle, Handle), String> { +/// Open a GET request (connected, not yet sent) for `url` on `session`. +fn open_get(session: &Handle, url: &str) -> Result<(Handle, Handle), String> { let parsed = url::Url::parse(url).map_err(|e| format!("invalid URL '{url}': {e}"))?; let secure = match parsed.scheme() { "http" | "ws" => false, @@ -94,7 +95,7 @@ fn open_get(url: &str) -> Result<(Handle, Handle), String> { object.push_str(q); } let connect = Handle::new( - unsafe { WinHttpConnect(session()?.raw(), &HSTRING::from(host), port, 0) }, + unsafe { WinHttpConnect(session.raw(), &HSTRING::from(host), port, 0) }, "WinHttpConnect", )?; let flags = WINHTTP_OPEN_REQUEST_FLAGS( @@ -156,14 +157,20 @@ fn status_code(request: &Handle) -> u32 { } fn content_type(request: &Handle) -> String { + query_header(request, WINHTTP_QUERY_CONTENT_TYPE, PCWSTR::null()) +} + +/// A response header (`info`: a `WINHTTP_QUERY_*` level, or `WINHTTP_QUERY_CUSTOM` with `name`); +/// empty when absent. +fn query_header(request: &Handle, info: u32, name: PCWSTR) -> String { let mut buf = [0u16; 256]; let mut len = std::mem::size_of_val(&buf) as u32; let mut index = 0u32; let ok = unsafe { WinHttpQueryHeaders( request.raw(), - WINHTTP_QUERY_CONTENT_TYPE, - PCWSTR::null(), + info, + name, Some(buf.as_mut_ptr() as *mut c_void), &mut len, &mut index, @@ -204,7 +211,7 @@ fn final_url(request: &Handle) -> String { /// Blocking GET. `headers` are extra request headers, CRLF-separated. pub(crate) fn get(url: &str, headers: &str) -> Result { - let (_connect, request) = open_get(url)?; + let (_connect, request) = open_get(session()?, url)?; send_and_receive(&request, headers)?; let status = status_code(&request); let content_type = content_type(&request); @@ -243,14 +250,19 @@ pub(crate) fn is_http_token(s: &str) -> bool { && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) } -/// Perform the WebSocket upgrade handshake for a `ws://`/`wss://` URL and return the socket -/// handle (plus the connection handle, which must outlive it). -pub(crate) fn websocket_connect(url: &str, protocols: &[String]) -> Result<(Handle, Handle), String> { +/// Open the upgrade request for a `ws://`/`wss://` URL on `session` (not yet sent): returns the +/// connection handle (which must outlive the socket), the request, and the extra request headers +/// to send with it. +pub(crate) fn websocket_request( + session: &Handle, + url: &str, + protocols: &[String], +) -> Result<(Handle, Handle, Vec), String> { // Subprotocols go into a request header, so anything but an HTTP token could inject headers. if let Some(bad) = protocols.iter().find(|p| !is_http_token(p)) { return Err(format!("invalid WebSocket subprotocol {bad:?}")); } - let (connect, request) = open_get(url)?; + let (connect, request) = open_get(session, url)?; unsafe { WinHttpSetOption(Some(request.raw()), WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, None) } .map_err(|e| format!("WebSocket upgrade option failed: {}", e.message()))?; let headers = if protocols.is_empty() { @@ -258,15 +270,11 @@ pub(crate) fn websocket_connect(url: &str, protocols: &[String]) -> Result<(Hand } else { format!("Sec-WebSocket-Protocol: {}\r\n", protocols.join(", ")) }; - send_and_receive(&request, &headers)?; - let status = status_code(&request); - if status != 101 { - return Err(format!("WebSocket handshake failed: HTTP {status}")); - } - let socket = Handle::new( - unsafe { WinHttpWebSocketCompleteUpgrade(request.raw(), None) }, - "WinHttpWebSocketCompleteUpgrade", - )?; - drop(request); - Ok((socket, connect)) + Ok((connect, request, headers.encode_utf16().collect())) +} + +/// The upgrade response's status code and the subprotocol the server selected. +pub(crate) fn websocket_response(request: &Handle) -> (u32, String) { + let protocol = query_header(request, WINHTTP_QUERY_CUSTOM, w!("Sec-WebSocket-Protocol")); + (status_code(request), protocol.trim().to_string()) }