Skip to content
Closed
9 changes: 9 additions & 0 deletions docs/runtime/networking/tcp.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,15 @@ socket.reload({

`socket.end(data)` accepts the whole chunk. Bun queues the part that the socket did not accept. Bun sends the queued part when the socket is writable again, then closes the socket.

When the connection closes while a part of the chunk is still queued, that part is lost. The report depends on how the connection closed:

- A read error closed the connection, for example the other end reset it. The `close` handler gets that error (`syscall: "read"`) as its second argument. Bun does not call the `error` handler.
- The connection closed with no read error. Bun reports a write error (`syscall: "write"`). The `error` handler gets it. Without an `error` handler, the `close` handler gets it as its second argument.

Only a `close` handler learns of every lost part. `socket.terminate()`, `socket.close()` and `listener.stop(true)` discard the queued part and report nothing. A TLS handshake that fails is reported to the `handshake` handler only, and a Windows named pipe reports nothing.

The report covers only the part that Bun has queued. The operating system and the TLS layer can lose data that they already accepted, so a `close` without an error does not prove that the other end received everything.

Performance-sensitive code should buffer writes itself. For example, this:

```ts
Expand Down
33 changes: 33 additions & 0 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6728,6 +6728,12 @@ declare module "bun" {
* Bun sends the queued data when the socket is writable again. Bun closes the socket after the
* last byte, so the TCP FIN packet follows the data.
*
* When the connection closes while a part of the chunk is still queued, that part is lost. A
* connection that a read error closes gives that error to the `close` handler, and to no other
* handler. A connection that closes with no read error gives a write error to the `error`
* handler: see {@link SocketHandler.error}. `terminate()`, `close()` and `listener.stop(true)`
* discard the queued part and report nothing.
*
* After `end()`, the socket accepts no more data: `write()` and `end()` return `-1`.
*
* `end()` returns a negative number when the socket accepts nothing. The number is `-1` if the
Expand Down Expand Up @@ -7214,7 +7220,34 @@ declare module "bun" {
* handler, this is called only after the handshake completes.
*/
open?(socket: Socket<Data>): void | Promise<void>;
/**
* Called when the socket closes.
*
* A `close` without an error does not prove that the other end received everything: the operating
* system and the TLS layer can lose data that they already accepted.
*
* @param error A read error that closed the connection, for example `ECONNRESET`. Data that
* {@link Socket.end | end(data)} queued is lost then, and the `error` handler is not called.
* Without an `error` handler, a write error also arrives here: see {@link SocketHandler.error}.
*/
close?(socket: Socket<Data>, error?: Error): void | Promise<void>;
/**
* Called when a handler throws an error, and for a write error.
*
* A write error means that Bun did not send all of the data that {@link Socket.end | end(data)}
* queued: the system rejected a send of the queued part, or the connection closed with no read
* error while a part was still queued. The error has `syscall: "write"`. Its `code` is the code
* of the rejected send, or `EPIPE` when the connection closed first.
*
* A connection that a read error closes (for example a reset by the other end) does not call
* this handler, also when queued data is lost. The `close` handler gets the read error: see
* {@link SocketHandler.close}.
*
* The report covers only the part in the queue. It does not cover data that the operating
* system or the TLS layer already accepted: see {@link SocketHandler.close}. A TLS handshake
* that fails is reported to the `handshake` handler only, and a Windows named pipe reports
* nothing.
*/
error?(socket: Socket<Data>, error: Error): void | Promise<void>;
data?(socket: Socket<Data>, data: BinaryTypeList[DataBinaryType]): void | Promise<void>;
drain?(socket: Socket<Data>): void | Promise<void>;
Expand Down
6 changes: 6 additions & 0 deletions packages/bun-usockets/src/context.c
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ void us_socket_group_deinit(struct us_socket_group_t *group) {
* closes it in finalize(), so closing+freeing it here turns that into a UAF
* (the original LSAN was only the *accepted* sockets, not the listener). */
void us_socket_group_close_all_ex(struct us_socket_group_t *group, int also_listeners) {
/* A close handler can call this again for the same group: the outer call keeps the mark. */
unsigned char was_closing_all = group->closing_all;
group->closing_all = 1;

if (also_listeners) {
/* Listeners first — stops new sockets from being accepted into
* head_sockets while we're draining it. */
Expand Down Expand Up @@ -156,6 +160,8 @@ void us_socket_group_close_all_ex(struct us_socket_group_t *group, int also_list
}
US_ASSERT(group->low_prio_count == 0);
}

group->closing_all = was_closing_all;
}

void us_socket_group_close_all(struct us_socket_group_t *group) {
Expand Down
3 changes: 3 additions & 0 deletions packages/bun-usockets/src/libusockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,9 @@ struct us_socket_group_t {
unsigned char timestamp;
unsigned char long_timestamp;
unsigned char linked;
/* Set while us_socket_group_close_all_ex runs: on_close can tell the owner's
* close of every socket from a close that the loop or the peer started. */
unsigned char closing_all;
};

/* Initialise an embedded group. Does NOT link into the loop — that happens
Expand Down
73 changes: 55 additions & 18 deletions src/runtime/socket/socket_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,20 +81,36 @@ fn read_error_from_close_code(code: c_int) -> sys::Error {
}
}

fn write_error_to_js(errno: i32, global: &JSGlobalObject) -> JSValue {
<sys::Error as jsc::SysErrorJsc>::to_js(
&sys::Error::from_code_int(errno, sys::Tag::write),
global,
)
}

/// What the `close` handler gets: a read error for a `close_code` above 2, else the errno of a failed write.
fn close_error_to_js(close_code: c_int, write_errno: u16, global: &JSGlobalObject) -> JSValue {
if close_code > 2 {
<sys::Error as jsc::SysErrorJsc>::to_js(&read_error_from_close_code(close_code), global)
} else if write_errno != 0 {
<sys::Error as jsc::SysErrorJsc>::to_js(
&sys::Error::from_code_int(i32::from(write_errno), sys::Tag::write),
global,
)
write_error_to_js(i32::from(write_errno), global)
} else {
JSValue::UNDEFINED
}
}

/// The one rule for a write error: the `error` handler gets it. False when none is registered
/// (`call_error_handler` raises an uncaught exception then): the caller gives the error to
/// the `close` handler. The caller holds a `Handlers::enter` scope.
fn report_write_error(handlers: &Handlers, this_value: JSValue, errno: i32) -> JsResult<bool> {
if handlers.on_error().is_empty() {
return Ok(false);
}
let err_value = write_error_to_js(errno, &handlers.global_object);
handlers.call_error_handler(this_value, &[this_value, err_value])?;
Ok(true)
}

/// `read_error_from_close_code` for C++: the `closeError` getter of `JSNodeHTTPServerSocket`.
#[unsafe(no_mangle)]
pub(crate) extern "C" fn Bun__socketReadErrorFromCloseCode(
Expand Down Expand Up @@ -946,17 +962,10 @@ impl<const SSL: bool> NewSocket<SSL> {
socket: this,
scope: Some(handlers.enter()),
};
if handlers.on_error().is_empty() {
let this_value = this.get_this_value(&handlers.global_object);
if !report_write_error(handlers, this_value, errno)? {
this.write_errno
.set(u16::try_from(errno).unwrap_or(u16::MAX));
} else {
let global = handlers.global_object;
let this_value = this.get_this_value(&global);
let err_value = <sys::Error as jsc::SysErrorJsc>::to_js(
&sys::Error::from_code_int(errno, sys::Tag::write),
&global,
);
handlers.call_error_handler(this_value, &[this_value, err_value])?;
}
// Closed without detaching: `on_close` runs, so JS observes `close`.
if !this.socket.get().is_detached() {
Expand Down Expand Up @@ -2218,6 +2227,22 @@ impl<const SSL: bool> NewSocket<SSL> {
Ok(())
}

/// True when this close loses data that `end()` accepted. A close that the application
/// starts gets here without a tail (`close_and_detach`, `detach_for_reconnect`), with
/// another code (`close()`), or with its group marked (`SocketGroup::close_all`).
fn loses_end_tail(&self, socket: SocketHandler<SSL>, code: c_int) -> bool {
let flags = self.flags.get();
code == uws::CloseCode::Normal as c_int
// A named pipe and an upgraded duplex close with code 0 for every origin.
&& self.is_usockets_backed()
// node:net fails the pending write of a `$write` queue itself.
&& flags.contains(Flags::END_AFTER_FLUSH)
// The `handshake` handler reports a failed handshake.
&& !flags.contains(Flags::REJECTED)
&& self.buffered_data_for_node_net.get().len() > 0
Comment thread
robobun marked this conversation as resolved.
Resolved
&& !socket.is_group_closing_all()
}

/// Takes `ThisPtr<Self>` for the same re-entrancy reason as `on_writable`.
pub(crate) fn on_close(
this: bun_ptr::ThisPtr<Self>,
Expand All @@ -2227,7 +2252,11 @@ impl<const SSL: bool> NewSocket<SSL> {
) -> JsResult<()> {
jsc::mark_binding!();
this.set_latest_session(ptr::null_mut());
let write_errno = this.write_errno.replace(0);
// An errno that a send returned wins over the one for a tail that no send reported.
let write_errno = match this.write_errno.replace(0) {
0 if this.loses_end_tail(socket, err) => sys::SystemErrno::EPIPE as u16,
errno => errno,
};
// A late close on a socket that already released its Handlers through
// a path that did not route back through this dispatch - e.g. a
// JS-side destroy on a TLS socket driven by an upgraded duplex. There
Expand Down Expand Up @@ -2281,9 +2310,8 @@ impl<const SSL: bool> NewSocket<SSL> {

this.poll_ref.with_mut(|p| p.unref(js_loop_ctx()));

let callback = handlers.on_close();

if callback.is_empty() {
// The `error` handler gets a write error without a `close` handler too.
if handlers.on_close().is_empty() && (write_errno == 0 || handlers.on_error().is_empty()) {
return Ok(());
}

Expand Down Expand Up @@ -2313,8 +2341,17 @@ impl<const SSL: bool> NewSocket<SSL> {
// values >2 are real read errors and 0/1/2 are self-initiated closes
// that must not surface as a JS read error (matching Node's
// onStreamRead, which only sees errors that came from uv_read_cb).
let js_error = close_error_to_js(err, write_errno, &global);
// A write error goes to the `error` handler when there is one: `close` then gets none.
let reported = err <= 2
&& write_errno != 0
&& report_write_error(&handlers, this_value, i32::from(write_errno))?;
let js_error = close_error_to_js(err, if reported { 0 } else { write_errno }, &global);

// Read after the `error` handler ran: it can `reload()` the handlers.
let callback = handlers.on_close();
if callback.is_empty() {
return Ok(());
}
if let Err(e) = callback.call(&global, this_value, &[this_value, js_error]) {
handlers.call_error_handler(this_value, &[this_value, global.take_error(e)])?;
}
Expand Down
4 changes: 3 additions & 1 deletion src/uws_sys/SocketGroup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ pub struct SocketGroup {
pub timestamp: u8,
pub long_timestamp: u8,
pub linked: u8,
/// Nonzero while `close_all` runs: the owner closes the sockets, not the loop or the peer.
pub closing_all: u8,
}

#[repr(C)]
Expand All @@ -59,7 +61,7 @@ pub struct VTable {
}

// Must match `struct us_socket_group_t` in libusockets.h.
// 9 ptrs + u32 + u16 + 3×u8, padded to 8-byte alignment.
// 9 ptrs + u32 + u16 + 4×u8, padded to 8-byte alignment.
const _: () = assert!(
core::mem::size_of::<SocketGroup>() == 9 * core::mem::size_of::<*mut c_void>() + 16,
"SocketGroup layout drifted from us_socket_group_t"
Expand Down
8 changes: 8 additions & 0 deletions src/uws_sys/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,14 @@ impl<const IS_SSL: bool> NewSocketHandler<IS_SSL> {
)
}

/// True while the owner of this socket's group closes every socket of it (`SocketGroup::close_all`).
pub fn is_group_closing_all(&self) -> bool {
match self.socket {
InternalSocket::Connected(s) => sock(s).group().closing_all != 0,
_ => false,
}
}

/// Raw `getaddrinfo(3)` return code for a pending connect whose name
/// lookup failed; 0 otherwise (a connect failure past name resolution, or
/// any non-connecting handle). A different namespace from
Expand Down
Loading
Loading