Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 35 additions & 27 deletions src/runtime/socket/socket_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -903,6 +903,27 @@ impl<const SSL: bool> NewSocket<SSL> {
called
}

/// Fails the write with `internal_flush`'s fatal errno, then closes. Caller holds the scope.
#[cfg(not(windows))]
fn fail_fatal_flush(
&self,
handlers: &Handlers,
this_value: JSValue,
fatal_send_errno: i32,
) -> JsResult<()> {
let global = handlers.global_object;
let err_value = <sys::Error as jsc::SysErrorJsc>::to_js(
&sys::Error::from_code_int(fatal_send_errno, sys::Tag::write),
&global,
);
handlers.call_error_handler(this_value, &[this_value, err_value])?;
Comment thread
robobun marked this conversation as resolved.
Resolved
// Close unless the error handler already detached; on_close then reports 'close' to JS.
if !self.socket.get().is_detached() {
self.socket.get().close(uws::CloseCode::Normal);
}
Ok(())
}

/// Takes `ThisPtr<Self>`, not `&mut self`: `callback.call(...)` re-enters
/// JS which can call `socket.write()`/`end()`/`reload()` on this same
/// wrapper via the JS object's `m_ptr`, re-deriving a borrow and mutating
Expand Down Expand Up @@ -946,35 +967,14 @@ impl<const SSL: bool> NewSocket<SSL> {
// Windows, keep the legacy contract there (the close path still fails
// the pending write callback when the socket is torn down).
let fatal_send_errno = this.internal_flush();
// On POSIX the fatal signal is trustworthy: us_socket_write_check_error
// only reports an errno that is either known peer-gone or persisted
// across its bounded unclassified-errno retry window. internal_flush
// already dropped the undeliverable buffer and the writable poll is no
// longer re-armed, so this dispatch is the last place the errno is
// visible - swallowing it here acknowledged the bytes to JS, sent a
// clean FIN, and the peer saw a silently truncated stream. Deliver it
// like a failed write (syscall "write", same shape as net.ts
// failWrite) and close the socket so 'error' is followed by 'close'.
#[cfg(not(windows))]
if fatal_send_errno != 0 {
let global = handlers.global_object;
let _scope = ScopeExit {
socket: this,
scope: Some(handlers.enter()),
};
let this_value = this.get_this_value(&global);
let err_value = <sys::Error as jsc::SysErrorJsc>::to_js(
&sys::Error::from_code_int(fatal_send_errno, sys::Tag::write),
&global,
);
handlers.call_error_handler(this_value, &[this_value, err_value])?;
// The error handler can destroy the socket itself; only close a
// still-attached socket. Close without detaching so on_close runs
// and JS observes 'close' (mirrors h2's dead-transport close).
if !this.socket.get().is_detached() {
this.socket.get().close(uws::CloseCode::Normal);
}
return Ok(());
let this_value = this.get_this_value(&handlers.global_object);
return this.fail_fatal_flush(&handlers, this_value, fatal_send_errno);
}
#[cfg(windows)]
let _ = fatal_send_errno;
Expand Down Expand Up @@ -1620,7 +1620,14 @@ impl<const SSL: bool> NewSocket<SSL> {
// pending JS write the same way on_writable's tail does, otherwise
// the do_socket_write backpressure arms the normal writable
// subscription.
let _ = this.internal_flush();
let fatal_send_errno = this.internal_flush();
// A fatal flush empties the buffer too, so the drain below would report success.
#[cfg(not(windows))]
if fatal_send_errno != 0 {
return this.fail_fatal_flush(&handlers, this_value, fatal_send_errno);
}
#[cfg(windows)]
let _ = fatal_send_errno;
if this.buffered_data_for_node_net.get().len() == 0 {
let drain_callback = handlers.on_writable();
if !drain_callback.is_empty() {
Expand Down Expand Up @@ -2146,7 +2153,7 @@ impl<const SSL: bool> NewSocket<SSL> {
}

// Reached by a nested dispatch (a close from on_open's error branch,
// on_writable's fatal close, a rejected handshake) while the handler
// fail_fatal_flush's close, a rejected handshake) while the handler
// above is unwinding with a termination pending: it belongs to that
// frame, so this dispatch neither enters JS over it nor claims it.
if handlers.global_object.has_exception() {
Expand Down Expand Up @@ -2980,7 +2987,8 @@ impl<const SSL: bool> NewSocket<SSL> {
log!("writeOrEnd {}", bytes.len());
let wrote = self.write_maybe_corked(bytes);
let uwrote: usize = usize::try_from(wrote.max(0)).expect("int cast");
if buffer_unwritten_data {
// JS fails a fatal send (`wrote < -1`): do not queue its bytes.
if buffer_unwritten_data && wrote >= -1 {
let remaining = &bytes[uwrote..];
if !remaining.is_empty() {
let _ = self
Expand Down Expand Up @@ -3020,7 +3028,7 @@ impl<const SSL: bool> NewSocket<SSL> {

/// Flushes the node:net buffered tail. Returns 0, or the positive errno of
/// a fatal send error (buffer dropped, writable not re-armed).
/// On POSIX, `on_writable` consumes the errno: it dispatches the error
/// On POSIX, `fail_fatal_flush` consumes the errno: it dispatches the error
/// handler and closes the socket. On Windows the errno is still ignored
/// (the drain callback is dispatched regardless) - skipping the drain on
/// fatal made Windows servers reset FIN-terminated responses (see
Expand Down
105 changes: 105 additions & 0 deletions test/js/node/net/net-syscall-fault.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,111 @@ describe.skipIf(skip)("node:net under injected syscall faults", () => {
);
}

// Calls `write` on one side from inside its 'connection' (server) or
// 'connect' (client) listener, so under the native open dispatch. Resolves
// once both sockets are closed.
async function writeInsideOpenDispatch(
side: "client" | "server",
write: (s: net.Socket, fd: number, headWritten: (err?: Error | null) => void) => void,
) {
let headError: NodeJS.ErrnoException | null | undefined;
let socketError: NodeJS.ErrnoException | undefined;
let received = Buffer.alloc(0);
const sockets: net.Socket[] = [];
const closed: Promise<void>[] = [];
function track(s: net.Socket) {
sockets.push(s);
closed.push(new Promise<void>(resolve => s.once("close", () => resolve())));
}
function writer(s: net.Socket) {
s.on("error", err => (socketError = err));
const fd = (s as any)._handle.fd as number;
// An fd-less rule would match every socket in the process.
expect(fd).toBeGreaterThanOrEqual(0);
write(s, fd, err => (headError = err ?? null));
}
function reader(s: net.Socket) {
s.on("error", () => {});
s.on("data", c => (received = Buffer.concat([received, c])));
}

const server = net.createServer(s => {
track(s);
if (side === "server") writer(s);
else reader(s);
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
const client = net.connect({ port: (server.address() as net.AddressInfo).port, host: "127.0.0.1" });
track(client);
if (side === "client") client.once("connect", () => writer(client));
else reader(client);

try {
await Promise.all([once(client, "connect"), once(server, "connection")]);
await Promise.all(closed);
} finally {
for (const s of sockets) s.destroy();
server.close();
}

const shape = (err: NodeJS.ErrnoException | null | undefined) => err && { code: err.code, syscall: err.syscall };
return { headError: shape(headError), socketError: shape(socketError), received };
}

for (const side of ["client", "server"] as const) {
// The remainder of a short send made under the open dispatch is flushed
// when that dispatch ends, not by a writable event. A fatal errno from
// that flush must fail the write and destroy the socket. Reporting it as
// drained let the next write go out on the same connection with the
// dropped bytes missing from the middle of the stream.
test.each(["EPIPE", "ECONNRESET"] as const)(
`send → %s on the flush that ends the open dispatch fails the write (${side} writer)`,
async errno => {
const head = Buffer.from(Array.from({ length: 200 }, (_, i) => i & 0xff));
const body = Buffer.alloc(4096, 0xee);
const { received, ...errors } = await writeInsideOpenDispatch(side, (s, fd, headWritten) => {
// send #0: 1 byte accepted, the other 199 stay in
// buffered_data_for_node_net.
fault.set({ syscall: "send", action: "short", bytes: 1, repeat: 1, fd });
s.write(head, headWritten);
// send #1: the flush of that remainder once the listener returns.
fault.set({ syscall: "send", action: "errno", errno, repeat: 1, fd });
s.write(body);
s.end();
});

// The peer may only see bytes from before the failed send: head[0].
const stream = Buffer.concat([head, body]);
expect({
...errors,
received: { length: received.length, isPrefixOfStream: received.equals(stream.subarray(0, received.length)) },
}).toEqual({
headError: { code: errno, syscall: "write" },
socketError: { code: errno, syscall: "write" },
received: { length: 1, isPrefixOfStream: true },
});
},
);

// A send the kernel rejects outright fails the write in JS. Its bytes must
// not stay queued: that flush sent them again, so the peer could receive
// a write that JS had been told failed.
test(`send → ECONNRESET on a write under the open dispatch is not sent again (${side} writer)`, async () => {
const { received, ...errors } = await writeInsideOpenDispatch(side, (s, fd, headWritten) => {
// One shot: a second send of the same bytes would succeed.
fault.set({ syscall: "send", action: "errno", errno: "ECONNRESET", repeat: 1, fd });
s.write(Buffer.alloc(200, "h"), headWritten);
});

expect({ ...errors, received: received.length }).toEqual({
headError: { code: "ECONNRESET", syscall: "write" },
socketError: { code: "ECONNRESET", syscall: "write" },
received: 0,
});
});
}

// us_socket_write_check_error gives send() errnos that are neither
// would-block/transient nor known peer-gone (EPROTOTYPE: macOS returns it
// racily from send() on healthy sockets) a bounded retry through the
Expand Down
75 changes: 73 additions & 2 deletions test/js/node/net/node-net-server.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { realpathSync } from "fs";
import { bunEnv, bunExe, tempDir } from "harness";
import { existsSync, realpathSync } from "fs";
import { bunEnv, bunExe, isWindows, tempDir } from "harness";
import { AddressInfo, createServer, Server, Socket } from "net";
import { createTest } from "node-harness";
import { once } from "node:events";
Expand Down Expand Up @@ -577,6 +577,77 @@ describe("net.createServer events", () => {
});
});

// The 'connection' listener runs under the native open dispatch. A short send
// made there is flushed when that dispatch ends. When the peer reset the
// connection in between, that flush gets ECONNRESET/EPIPE from send() and the
// write must fail. It was reported as drained instead: the write callback
// succeeded and 'finish' fired for a response the peer never received.
// Windows keeps the legacy drain contract for fatal flushes (see on_writable).
it.skipIf(isWindows)(
"fails a write whose flush at the end of the 'connection' listener hits a peer reset",
async () => {
using dir = tempDir("net-open-flush-reset", {
"client.js": `
const net = require("node:net");
const fs = require("node:fs");
const s = net.connect(Number(process.env.RESET_PORT), "127.0.0.1");
s.on("error", () => {});
s.once("data", () => {
// The server's first send happened and its listener is still running.
s.resetAndDestroy();
fs.writeFileSync(process.env.RESET_MARKER, "");
});
`,
});
const marker = join(String(dir), "reset");

let sawReset = false;
let writeFailed: boolean | undefined;
let finished = false;
const socketErrors: NodeJS.ErrnoException[] = [];
const closed = Promise.withResolvers<boolean>();
const server = createServer(c => {
c.on("error", err => socketErrors.push(err));
c.on("finish", () => (finished = true));
c.on("close", hadError => closed.resolve(hadError));
// More than the socket send buffer takes: a real short send.
c.write(Buffer.alloc(16 * 1024 * 1024, "x"), err => (writeFailed = err != null));
c.end();
// Stay in the listener until the peer has reset the connection.
const deadline = performance.now() + 10_000;
while (!(sawReset = existsSync(marker)) && performance.now() < deadline) {}
});
server.listen(0, "127.0.0.1");
await once(server, "listening");

try {
await using client = Bun.spawn({
cmd: [bunExe(), join(String(dir), "client.js")],
env: { ...bunEnv, RESET_PORT: String((server.address() as AddressInfo).port), RESET_MARKER: marker },
stdio: ["ignore", "inherit", "inherit"],
});

expect({
closeHadError: await closed.promise,
sawReset,
writeFailed,
finished,
errors: socketErrors.length,
}).toEqual({
closeHadError: true,
sawReset: true,
writeFailed: true,
finished: false,
errors: 1,
});
expect(["ECONNRESET", "EPIPE"]).toContain(socketErrors[0].code);
expect(await client.exited).toBe(0);
} finally {
server.close();
}
},
);

it("#8374", async () => {
const server = createServer();
const socketPath = join(tmpdir(), "test-unix-socket");
Expand Down
Loading