Skip to content
48 changes: 48 additions & 0 deletions src/http_jsc/websocket_client/CppWebSocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ bun_opaque::opaque_ffi! {
pub struct CppWebSocket;
}

/// Matches `WebCore::WebSocket::HandshakeRawHeader` (WebSocket.h).
#[repr(C)]
pub struct RawHeader {
pub name_ptr: *const u8,
pub name_len: usize,
pub value_ptr: *const u8,
pub value_len: usize,
}

// FFI surface for `WebCore::WebSocket` (src/jsc/bindings/webcore/WebSocket.cpp).
// Kept private to this module — the safe wrappers below are the only callers.
//
Expand All @@ -45,6 +54,16 @@ unsafe extern "C" {
deflate_params: *const websocket_deflate::Params,
);
safe fn WebSocket__didAbruptClose(websocket_context: &CppWebSocket, reason: ErrorCode);
fn WebSocket__didReceiveHandshakeResponse(
websocket_context: &CppWebSocket,
status_code: u16,
status_message: *const u8,
status_message_len: usize,
headers: *const RawHeader,
headers_len: usize,
body: *const u8,
body_len: usize,
);
fn WebSocket__didClose(websocket_context: &CppWebSocket, code: u16, reason: *const BunString);
fn WebSocket__didReceiveText(
websocket_context: &CppWebSocket,
Expand Down Expand Up @@ -78,6 +97,35 @@ impl CppWebSocket {
event_loop.exit();
}

/// Dispatch the native `'handshake'` event; C++ copies all slices synchronously.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn did_receive_handshake_response(
&self,
status_code: u16,
status_message: &[u8],
headers: &[RawHeader],
body: &[u8],
) {
// SAFETY: VirtualMachine::get() returns the live current-thread VM;
// event_loop() yields its raw event-loop pointer (live for VM lifetime).
let event_loop = VirtualMachine::get().event_loop_mut();
event_loop.enter();
// SAFETY: self is a valid C++ WebCore::WebSocket; the slices outlive the call.
unsafe {
WebSocket__didReceiveHandshakeResponse(
self,
status_code,
status_message.as_ptr(),
status_message.len(),
headers.as_ptr(),
headers.len(),
body.as_ptr(),
body.len(),
)
};
event_loop.exit();
}

pub(crate) fn did_close(&self, code: u16, reason: &mut BunString) {
// SAFETY: VirtualMachine::get() returns the live current-thread VM;
// event_loop() yields its raw event-loop pointer (live for VM lifetime).
Expand Down
105 changes: 60 additions & 45 deletions src/http_jsc/websocket_client/WebSocketUpgradeClient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -929,19 +929,8 @@ impl<const SSL: bool> HTTPClient<SSL> {
body = &me.body;
}

let is_first = me.body.is_empty();
const HTTP_101: &[u8] = b"HTTP/1.1 101 ";
if is_first && body.len() > HTTP_101.len() {
// fail early if we receive a non-101 status code
if !body.starts_with(HTTP_101) {
// SAFETY: `me`'s last use is above; no `&mut Self` spans this call.
unsafe { Self::terminate(this.as_ptr(), ErrorCode::Expected101StatusCode) };
return;
}
}

let response = match picohttp::Response::parse(body, &mut me.headers_buf) {
Ok(r) => r,
match picohttp::Response::parse(body, &mut me.headers_buf) {
Ok(_) => {}
Err(picohttp::ParseResponseError::MalformedHttpResponse) => {
// SAFETY: `me`'s last use is above; no `&mut Self` spans this call.
unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) };
Expand All @@ -963,15 +952,57 @@ impl<const SSL: bool> HTTPClient<SSL> {
}
};

let bytes_read = usize::try_from(response.bytes_read).expect("int cast");
// Reshaped for borrowck — copy remain_buf out before mutating self.
let remain_buf: Vec<u8> = body[bytes_read..].to_vec();
// SAFETY: `me`'s last use is the `body` slice above (now copied out);
// no `&mut Self` spans this call.
unsafe { Self::process_response(this.as_ptr(), response, &remain_buf) };
let full = body.to_vec();
Self::process_websocket_upgrade_response(this, &full);
// `_guard` drops here, balancing the ref above. May free `this`.
}

/// Forward the handshake response to C++ as a `'handshake'` event.
fn dispatch_handshake(ws: *mut CppWebSocket, response: &picohttp::Response, body: &[u8]) {
let raw_headers: Vec<super::cpp_websocket::RawHeader> = response
.headers
.list
.iter()
.map(|h| super::cpp_websocket::RawHeader {
name_ptr: h.name().as_ptr(),
name_len: h.name().len(),
value_ptr: h.value().as_ptr(),
value_len: h.value().len(),
})
.collect();
CppWebSocket::opaque_ref(ws).did_receive_handshake_response(
u16::try_from(response.status_code).unwrap_or(0),
response.status,
&raw_headers,
body,
);
}

/// Surface `'handshake'` to the `ws` shim, then [`Self::process_response`].
/// Caller holds a `ref_guard` and owns `full` (it must not borrow `self`).
Comment thread
robobun marked this conversation as resolved.
Resolved
fn process_websocket_upgrade_response(this: ThisPtr<Self>, full: &[u8]) {
let mut scratch = [picohttp::Header::ZERO; 128];
let Ok(response) = picohttp::Response::parse(full, &mut scratch) else {
// SAFETY: forwards to the existing teardown path.
return unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) };
};
let head_len = usize::try_from(response.bytes_read).expect("int cast");
let is_101 = response.status_code == 101;

// 101: one scope across 'upgrade'+'open' so microtasks drain after open.
let _scope = is_101
.then(|| bun_jsc::virtual_machine::VirtualMachine::get().enter_event_loop_scope());

if let Some(ws) = this.outgoing_websocket {
Self::dispatch_handshake(ws, &response, if is_101 { &[] } else { &full[head_len..] });
if this.outgoing_websocket.is_none() {
return;
}
}
// SAFETY: forwards to the existing handoff path.
unsafe { Self::process_response(this.as_ptr(), response, &full[head_len..]) };
}

/// Takes `ThisPtr<Self>` because `terminate`/`handle_data` may free `this`.
fn handle_proxy_response(this: ThisPtr<Self>, socket: Socket<SSL>, data: &[u8]) {
log!("handleProxyResponse");
Expand Down Expand Up @@ -1217,10 +1248,13 @@ impl<const SSL: bool> HTTPClient<SSL> {
/// `terminate`/`process_response` may free `this`; see `fail`.
pub unsafe fn handle_decrypted_data(this: *mut Self, data: &[u8]) {
log!("handleDecryptedData: {} bytes", data.len());
// SAFETY: caller (proxy tunnel) holds a live ref on `this`.
let this = unsafe { ThisPtr::new(this) };
let _guard = this.ref_guard();

// SAFETY: short-lived `&mut` for body buffering; no reentrant calls in
// this region until `terminate`/`process_response` below.
let me = unsafe { &mut *this };
let me = unsafe { &mut *this.as_ptr() };

// Process as if it came directly from the socket
let mut body = data;
Expand All @@ -1229,46 +1263,27 @@ impl<const SSL: bool> HTTPClient<SSL> {
body = &me.body;
}

let is_first = me.body.is_empty();
const HTTP_101: &[u8] = b"HTTP/1.1 101 ";
if is_first && body.len() > HTTP_101.len() {
// fail early if we receive a non-101 status code
if !body.starts_with(HTTP_101) {
// SAFETY: `me`'s last use is above; no `&mut Self` spans this call.
unsafe { Self::terminate(this, ErrorCode::Expected101StatusCode) };
return;
}
}

let response = match picohttp::Response::parse(body, &mut me.headers_buf) {
Ok(r) => r,
match picohttp::Response::parse(body, &mut me.headers_buf) {
Ok(_) => {}
Err(picohttp::ParseResponseError::MalformedHttpResponse) => {
// SAFETY: `me`'s last use is above; no `&mut Self` spans this call.
unsafe { Self::terminate(this, ErrorCode::InvalidResponse) };
unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) };
return;
}
Err(picohttp::ParseResponseError::ShortRead) => {
if me.body.is_empty() {
me.body.extend_from_slice(data);
}
// ShortRead means no \r\n\r\n was found, so every byte in
// `body` is part of an incomplete header — cap that, not
// total bytes received (which may include pipelined
// WebSocket frames once the header does complete).
if me.body.len() > bun_http::max_http_header_size() {
// SAFETY: `me`'s last use is above; no `&mut Self` spans this call.
unsafe { Self::terminate(this, ErrorCode::InvalidResponse) };
unsafe { Self::terminate(this.as_ptr(), ErrorCode::InvalidResponse) };
Comment thread
robobun marked this conversation as resolved.
Resolved
}
return;
}
};

let bytes_read = usize::try_from(response.bytes_read).expect("int cast");
// Reshaped for borrowck — copy remain_buf out before mutating self.
let remain_buf: Vec<u8> = body[bytes_read..].to_vec();
// SAFETY: `me`'s last use is the `body` slice above (now copied out);
// no `&mut Self` spans this call.
unsafe { Self::process_response(this, response, &remain_buf) };
let full = body.to_vec();
Self::process_websocket_upgrade_response(this, &full);
}

/// Takes `ThisPtr<Self>` because `terminate` may free `this`; see `fail`.
Expand Down
3 changes: 3 additions & 0 deletions src/js/builtins/BunBuiltinNames.h
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ using namespace JSC;
macro(processBindingConstants) \
macro(props) \
macro(pull) \
macro(rawHeaders) \
macro(read) \
macro(readable) \
macro(readableType) \
Expand All @@ -182,6 +183,8 @@ using namespace JSC;
macro(started) \
macro(state) \
macro(status) \
macro(statusCode) \
macro(statusMessage) \
macro(statusText) \
macro(stream) \
macro(structuredCloneForStream) \
Expand Down
Loading
Loading