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
239 changes: 215 additions & 24 deletions packages/bun-usockets/src/crypto/openssl.c

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion packages/bun-usockets/src/internal/internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,9 @@ extern struct us_socket_t *us_dispatch_end(us_socket_r s);
extern struct us_socket_t *us_dispatch_connect_error(us_socket_r s, int code);
extern struct us_connecting_socket_t *us_dispatch_connecting_error(struct us_connecting_socket_t *c, int code);
extern void us_dispatch_handshake(us_socket_r s, int success, struct us_bun_verify_error_t err);
extern void us_dispatch_session(us_socket_r s, const unsigned char *data, int length);
extern void us_dispatch_session(us_socket_r s, const unsigned char *data, int length, int id_length);
extern void us_dispatch_keylog(us_socket_r s, const unsigned char *data, int length);
extern void us_dispatch_resume_session(us_socket_r s, const unsigned char *id, int id_length);
extern struct us_socket_t *us_dispatch_ssl_raw_tap(us_socket_r s, char *data, int length);

extern int Bun__addrinfo_get(struct us_loop_t* loop, const char* host, uint16_t port, struct addrinfo_request** ptr);
Expand Down
12 changes: 10 additions & 2 deletions packages/bun-usockets/src/libusockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,12 @@ void us_listen_socket_on_server_name(struct us_listen_socket_t *ls,
* call consumes the reference. `error` != 0 aborts the handshake. Safe to call
* after the socket closed (no-op). */
void us_socket_sni_resolve(us_socket_r s, struct ssl_ctx_st *ctx, int error);
/* Resume a handshake suspended by the server session-id lookup (node:tls
* 'resumeSession'): get_session_cb returned the magic pending pointer and the
* JS handler was dispatched. `data`/`length` is the serialized SSL_SESSION
* from the external cache, or NULL/0 for a miss. Safe to call after the
* socket closed, and a no-op when nothing is awaiting a resolution. */
void us_socket_session_resolve(us_socket_r s, const unsigned char *data, int length);
void *us_socket_server_name_userdata(us_socket_r s);

/* ── Connect ──────────────────────────────────────────────────────────────
Expand Down Expand Up @@ -474,9 +480,11 @@ int us_ssl_ctx_add_ca_cert(struct ssl_ctx_st *ctx, const char *content);
* the parked new-session/keylog queues, then drain them with the pop calls
* after each SSL_read/SSL_do_handshake stack unwinds. Pop returns the entry
* length (0 = queue empty); entries are capped at 64 KB (sessions) and
* 4 KB+1 (keylog lines). */
* 4 KB+1 (keylog lines). A popped session entry is
* `[*out_id_len bytes: SSL_SESSION_get_id][rest: i2d_SSL_SESSION blob]`;
* `out_id_len` may be NULL if the caller does not need the id. */
void us_ssl_enable_pending_events(struct ssl_st *ssl);
int us_ssl_pop_pending_session(struct ssl_st *ssl, unsigned char *out, int out_cap);
int us_ssl_pop_pending_session(struct ssl_st *ssl, unsigned char *out, int out_cap, int *out_id_len);
int us_ssl_pop_pending_keylog(struct ssl_st *ssl, unsigned char *out, int out_cap);

/* Public interfaces for loops */
Expand Down
21 changes: 11 additions & 10 deletions scripts/build/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,17 @@
*
* Several scripts emit MORE files than they report:
* - bindgen.ts emits Generated<Name>.h per namespace (only .cpp declared)
* - bindgenv2 emits Generated<Type>.h per type (list-outputs skips .h)
* - generate-node-errors.ts emits ErrorCode.d.ts (not declared)
* - bundle-modules.ts emits eval/ subdir, BunBuiltinNames+extras.h, etc.
*
* It WORKS because:
* 1. The declared .cpp outputs guarantee the step runs before compile
* 2. Compilation emits .d depfiles that track the .h files for NEXT build
* 3. PCH order-depends on ALL codegen outputs; every cxx() waits on PCH
* → all codegen completes before any compile, undeclared .h exist
* Ordering is still correct: PCH order-depends on ALL codegen outputs and every
* cxx() waits on PCH, so codegen completes before any compile.
*
* Fixing properly (declaring all outputs) would require patching the
* src/codegen/ scripts to report everything — changing contract with
* existing tooling.
* Staleness is NOT. An undeclared header is a plain source file to ninja, so a
* build that rewrites it cannot dirty the .cpp files that include it but were
* themselves unchanged (restat prunes them). Those objects keep the previous
* layout and the link silently mixes two ABIs; the depfile only catches it on
* the NEXT build. bindgenv2 declares its headers for exactly this reason.
*/

import { spawnSync } from "node:child_process";
Expand Down Expand Up @@ -837,8 +835,11 @@ function emitBindgenV2({ n, cfg, sources, o, dirStamp }: Ctx): void {

assert(allOutputs.length > 0, "bindgenv2 list-outputs returned no files");

// Headers are declared outputs too, so that a type whose layout changed
// dirties every .cpp that embeds it, not just the .cpp regenerated alongside
// it. Only the .cpp files get compiled.
const cppOutputs = allOutputs.filter(p => p.endsWith(".cpp"));
const other = allOutputs.filter(p => !p.endsWith(".cpp"));
const other = allOutputs.filter(p => !p.endsWith(".cpp") && !p.endsWith(".h"));
assert(other.length === 0, `bindgenv2 emitted unexpected output type: ${other.join(", ")}`);

n.build({
Expand Down
4 changes: 4 additions & 0 deletions src/codegen/bindgenv2/script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ function toZigNamespace(name: string): string {
function listOutputs(): void {
const outputs: string[] = [];
for (const type of getNamedExports()) {
// Headers are declared too: a type whose layout changes rewrites only its
// own header, and ninja needs that edge to dirty the .cpp files that embed
// the type but were not themselves regenerated.
if (type.hasCppHeader) outputs.push(cppHeaderPath(type));
if (type.hasCppSource) outputs.push(cppSourcePath(type));
}
process.stdout.write(outputs.join(";"));
Expand Down
180 changes: 138 additions & 42 deletions src/js/node/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ const khandlers = Symbol("khandlers");
const kclosed = Symbol("closed");
const kended = Symbol("ended");
const kpendingSession = Symbol("pendingSession");
// A server handshake completion deferred until the 'newSession' listener's
// done callback runs (Node holds secureConnection for the external session
// store). Holds the verifyError it needs; `undefined` = nothing deferred.
const kdeferredSecure = Symbol("deferredSecure");
const kSNIError = Symbol("kSNIError");
const kALPNError = Symbol("kALPNError");
const kPerfHooksNetConnectContext = Symbol("kPerfHooksNetConnectContext");
Expand Down Expand Up @@ -597,6 +601,60 @@ function onSNIResolution(state, err, context) {
}
}

// The success tail of the server handshake: client-cert authorization, then
// secureConnection/secure/secureConnect. Split out so a pending 'newSession'
// can defer it until its done callback runs (Node's _newSessionPending).
function completeServerHandshake(self, verifyError) {
// Cleared here, not at the top of the handshake callback, so a 'newSession'
// listener that never invokes its done callback is still bounded by
// handshakeTimeout. The failure branch clears it separately.
if (self[khandshakeTimer]) {
clearTimeout(self[khandshakeTimer]);
self[khandshakeTimer] = undefined;
}
const handle = self._handle;
const server = self.server;
self._securePending = false;
self.secureConnecting = false;
self._secureEstablished = true;
self.servername = handle.getServername();
self.alpnProtocol = handle.alpnProtocol;
// The native verifier reports a non-OK code when there is no peer certificate,
// which is the normal case for plain TLS servers.
if (self._requestCert) {
if (verifyError) {
self.authorized = false;
self.authorizationError = verifyError.code || verifyError.message;
server?.emit("tlsClientError", verifyError, self);
if (self._rejectUnauthorized) {
// if we reject we still need to emit secure
self.emit("secure", self);
// No error argument: the socket has no 'error' listener yet, so destroy(err)
// would surface as an uncaught exception.
self.destroy();
return;
}
} else {
self.authorized = true;
}
}
if (server) {
const connectionListener = server[bunSocketServerOptions]?.connectionListener;
if (typeof connectionListener === "function") {
server.prependOnceListener("secureConnection", connectionListener);
}
server.emit("secureConnection", self);
}
// after secureConnection event we emmit secure and secureConnect
self.emit("secure", self);
self.emit("secureConnect", verifyError);
if (server?.pauseOnConnect) {
self.pause();
} else {
self.resume();
}
}

const ServerHandlers: SocketHandler<NetSocket> = {
data(socket, buffer) {
const { data: self } = socket;
Expand Down Expand Up @@ -734,20 +792,88 @@ const ServerHandlers: SocketHandler<NetSocket> = {
handle.onconnection(0, socket);
}
},
// A resumable session was minted for an accepted connection (TLS <= 1.2;
// BoringSSL's TLS 1.3 server is stateless). Emit 'newSession' on the Server;
// 'secureConnection' is HELD until `done` so the external store is populated.
session(socket, sessionData, sessionId) {
const self = socket.data;
if (!self) return;
const server = self.server;
if (!server || server.listenerCount("newSession") === 0) return;
self._newSessionPending = true;
let once = false;
const done = () => {
if (once) return;
once = true;
self._newSessionPending = false;
// The native handshake callback arrived while 'newSession' was still
// pending and was deferred; deliver secureConnection now. The socket
// may have been torn down while the listener's store was in flight.
const deferred = self[kdeferredSecure];
if (deferred === undefined) return;
self[kdeferredSecure] = undefined;
if (self.destroyed || !self._handle) return;
completeServerHandshake(self, deferred.verifyError);
};
// A throwing listener must not leave secureConnection deferred forever:
// complete the handshake, then surface the throw as an uncaughtException
// the way Node does for a 'newSession' listener that throws.
try {
server.emit("newSession", sessionId, sessionData, done);
} catch (err) {
done();
process.nextTick(() => reportError(err));
}
},
Comment thread
robobun marked this conversation as resolved.
Resolved
// A TLS <= 1.2 client offered a session_id: the handshake is suspended on
// the external-cache lookup until the 'resumeSession' callback replies. With
// no listener, resolve immediately as a miss so the handshake never stalls.
resumeSession(socket, sessionId) {
const self = socket.data;
const server = self?.server;
if (!server || server.listenerCount("resumeSession") === 0) {
socket.resolveSession(null);
return;
}
let once = false;
const onresume = (err, sessionData) => {
if (once) return;
once = true;
// Node destroys the socket when the lookup errors; an invalid or
// missing sessionData falls through to a full handshake.
if (err) {
socket.resolveSession(null);
if (!self.destroyed) self.destroy(err);
return;
}
// Node's loadSession treats a non-Buffer sessionData as a miss (full
// handshake) rather than throwing; resolveSession requires a Buffer.
socket.resolveSession(Buffer.isBuffer(sessionData) ? sessionData : null);
};
// A throwing listener must not leave the handshake suspended: resolve as
// a miss, then surface the throw as an uncaughtException the way Node
// does (same as the 'newSession' handler above).
try {
server.emit("resumeSession", sessionId, onresume);
} catch (err) {
onresume(null, null);
process.nextTick(() => reportError(err));
}
},
handshake(socket, success, verifyError) {
const self = socket.data;
// `server` is null for a standalone `new tls.TLSSocket(socket, { isServer: true })`
// (no listening server owns it) — guard every server.emit / server option read.
const server = self.server;
if (self[khandshakeTimer]) {
clearTimeout(self[khandshakeTimer]);
self[khandshakeTimer] = undefined;
}
// On the server side the second argument is the raw handshake result
// (client-certificate verification is reported separately through
// `verifyError` and handled below), so !success always means the TLS
// session was never established.
if (!success) {
if (self[khandshakeTimer]) {
clearTimeout(self[khandshakeTimer]);
self[khandshakeTimer] = undefined;
}
// The handshake never completed: there is no TLS session, so there is
// no secureConnection. Report the failure through tlsClientError the
// way Node does and tear the connection down. A connection that was
Expand Down Expand Up @@ -785,45 +911,15 @@ const ServerHandlers: SocketHandler<NetSocket> = {
self.destroy();
return;
}
self._securePending = false;
self.secureConnecting = false;
self._secureEstablished = !!success;
self.servername = socket.getServername();
self.alpnProtocol = socket.alpnProtocol;
// The native verifier reports a non-OK code when there is no peer certificate,
// which is the normal case for plain TLS servers.
if (self._requestCert) {
if (verifyError) {
self.authorized = false;
self.authorizationError = verifyError.code || verifyError.message;
server?.emit("tlsClientError", verifyError, self);
if (self._rejectUnauthorized) {
// if we reject we still need to emit secure
self.emit("secure", self);
// No error argument: the socket has no 'error' listener yet, so destroy(err)
// would surface as an uncaught exception.
self.destroy();
return;
}
} else {
self.authorized = true;
}
}
if (server) {
const connectionListener = server[bunSocketServerOptions]?.connectionListener;
if (typeof connectionListener === "function") {
server.prependOnceListener("secureConnection", connectionListener);
}
server.emit("secureConnection", self);
}
// after secureConnection event we emmit secure and secureConnect
self.emit("secure", self);
self.emit("secureConnect", verifyError);
if (server?.pauseOnConnect) {
self.pause();
} else {
self.resume();
// The native session callback (delivered just before this) emitted
// 'newSession' and its `done` has not run yet: hold secureConnection
// until it does, the way Node's _newSessionPending defers _finishInit.
if (self._newSessionPending) {
self._securePending = true;
self[kdeferredSecure] = { verifyError };
return;
}
completeServerHandshake(self, verifyError);
},
error(socket, error) {
const data = this.data;
Expand Down
7 changes: 4 additions & 3 deletions src/jsc/bindings/JSSocketHandlers.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ using namespace JSC;
// callbacks live exactly as long as something that can still invoke them.
// Replaces manual gcProtect/gcUnprotect of raw JSValues, and lets `reload` swap
// callbacks in place for live sockets.
class JSSocketHandlers final : public JSC::JSInternalFieldObjectImpl<14> {
class JSSocketHandlers final : public JSC::JSInternalFieldObjectImpl<15> {
public:
using Base = JSC::JSInternalFieldObjectImpl<14>;
using Base = JSC::JSInternalFieldObjectImpl<15>;

// Field order is ABI shared with src/runtime/socket/Handlers.rs.
// Field order is ABI shared with src/runtime/socket/JSSocketHandlers.rs.
enum class Field : uint32_t {
Open = 0,
Close,
Expand All @@ -32,6 +32,7 @@ class JSSocketHandlers final : public JSC::JSInternalFieldObjectImpl<14> {
Error,
Handshake,
Session,
ResumeSession,
Keylog,
ServerName,
ALPNCallback,
Expand Down
3 changes: 3 additions & 0 deletions src/jsc/generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ pub struct SocketConfigHandlers {
pub on_error: JSValue,
pub on_handshake: JSValue,
pub on_session: JSValue,
pub on_resume_session: JSValue,
pub on_keylog: JSValue,
pub on_server_name: JSValue,
pub on_alpn_callback: JSValue,
Expand All @@ -217,6 +218,7 @@ struct ExternSocketConfigHandlers {
onConnectError: JSValue,
onTimeout: JSValue,
onSession: JSValue,
onResumeSession: JSValue,
onKeylog: JSValue,
onServerName: JSValue,
onALPNCallback: JSValue,
Expand Down Expand Up @@ -248,6 +250,7 @@ impl SocketConfigHandlers {
on_connect_error: ext.onConnectError,
on_timeout: ext.onTimeout,
on_session: ext.onSession,
on_resume_session: ext.onResumeSession,
on_keylog: ext.onKeylog,
on_server_name: ext.onServerName,
on_alpn_callback: ext.onALPNCallback,
Expand Down
5 changes: 5 additions & 0 deletions src/runtime/socket/Handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,9 @@ impl Handlers {
pub fn on_session(&self) -> JSValue {
self.cell.on_session()
}
pub fn on_resume_session(&self) -> JSValue {
self.cell.on_resume_session()
}
pub fn on_keylog(&self) -> JSValue {
self.cell.on_keylog()
}
Expand Down Expand Up @@ -365,6 +368,7 @@ impl Handlers {
let on_error = validated_callback!(on_error, "onError");
let on_handshake = validated_callback!(on_handshake, "onHandshake");
let on_session = validated_callback!(on_session, "onSession");
let on_resume_session = validated_callback!(on_resume_session, "onResumeSession");
let on_keylog = validated_callback!(on_keylog, "onKeylog");
let on_server_name = validated_callback!(on_server_name, "onServerName");
let on_alpn_callback = validated_callback!(on_alpn_callback, "onALPNCallback");
Expand All @@ -386,6 +390,7 @@ impl Handlers {
on_error,
on_handshake,
on_session,
on_resume_session,
on_keylog,
on_server_name,
on_alpn_callback,
Expand Down
Loading
Loading