Skip to content
Merged
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
18 changes: 16 additions & 2 deletions packages/bun-uws/src/HttpContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ struct HttpContext {
}

template <bool IsNodeHttp>
static us_socket_t *onClose(us_socket_t *s, int /*code*/, void * /*reason*/) {
static us_socket_t *onClose(us_socket_t *s, int code, void * /*reason*/) {
((AsyncSocket<SSL> *)s)->uncorkWithoutSending();

/* Get socket ext */
Expand Down Expand Up @@ -273,7 +273,15 @@ struct HttpContext {
}

if (httpResponseData->socketData && httpContextData->onSocketClosed) {
httpContextData->onSocketClosed(httpResponseData->socketData, SSL, s);
int readError = 0;
bool peerEnded = false;
/* A tunnel reports its EOF through onSocketData above. */
if (!httpResponseData->isConnectRequest && !nodeHttpTunnelAfterBody) {
/* Above FAST_SHUTDOWN the code is the error of the failed read (a peer RST). */
readError = code > LIBUS_SOCKET_CLOSE_CODE_FAST_SHUTDOWN ? code : 0;
peerEnded = (httpResponseData->state & HttpResponseData<SSL>::HTTP_NODE_PEER_ENDED) != 0;
Comment thread
robobun marked this conversation as resolved.
Resolved
}
httpContextData->onSocketClosed(httpResponseData->socketData, SSL, s, readError, peerEnded);
}
/* Signal broken HTTP request only if we have a pending request */
if (httpResponseData->onAborted != nullptr && httpResponseData->userData != nullptr) {
Expand Down Expand Up @@ -929,6 +937,12 @@ struct HttpContext {
return s;
}

/* Before onClientError, whose listener can destroy the socket. Not once this side
* shut down: TLS delivers the peer's answer to our close_notify here as an EOF. */
if (!us_socket_is_shut_down(s)) {
httpResponseData->state |= HttpResponseData<SSL>::HTTP_NODE_PEER_ENDED;
}

if (httpContextData->onClientError && !(httpResponseData->state & HttpResponseData<SSL>::HTTP_NODE_PARSING_STOPPED)
&& (httpResponseData->hasBufferedPartialRequestHeaders()
|| httpResponseData->hasIncompleteRequestBody())) {
Expand Down
3 changes: 2 additions & 1 deletion packages/bun-uws/src/HttpContextData.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ struct alignas(16) HttpContextData {
using OnSocketDrainCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket);
using OnSocketUpgradedCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket);
using OnClientErrorCallback = MoveOnlyFunction<void(int is_ssl, struct us_socket_t *rawSocket, uWS::HttpParserError errorCode, char *rawPacket, int rawPacketLength)>;
using OnSocketClosedCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket);
/* readError: 0, or the error of the failed read (a peer RST). peerEnded: the peer sent its FIN first. */
using OnSocketClosedCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket, int readError, bool peerEnded);

MoveOnlyFunction<void(const char *hostname)> missingServerNameHandler;

Expand Down
6 changes: 5 additions & 1 deletion packages/bun-uws/src/HttpResponseData.h
Original file line number Diff line number Diff line change
Expand Up @@ -155,13 +155,17 @@ struct HttpResponseData : AsyncSocketData<SSL>, HttpParser {
* that runs after it (microtasks, the request body callback) can block,
* reset the connection or end the process. */
HTTP_SEND_WHEN_COMPLETE = 1 << 18,
/* node:http: the peer sent its FIN first (HTTP_NODE_RECEIVED_FIN only covers a
* deferred close). onSocketClosed reports it so the JS socket emits 'end'. */
HTTP_NODE_PEER_ENDED = 1 << 19,

/* Bits that describe the connection rather than the response in flight.
* There is one HttpResponseData per socket, reused by every request on a
* keep-alive connection, so starting a new response clears the rest of the
* word (resetResponseState) - these have to survive that. */
HTTP_CONNECTION_SCOPED = HTTP_NODE_PARSING_STOPPED | HTTP_NODE_READS_PAUSED
| HTTP_NODE_TUNNEL_AFTER_BODY | HTTP_NODE_RECEIVED_FIN | HTTP_CLOSE_WHEN_IDLE,
| HTTP_NODE_TUNNEL_AFTER_BODY | HTTP_NODE_RECEIVED_FIN | HTTP_CLOSE_WHEN_IDLE
| HTTP_NODE_PEER_ENDED,
};

/* Begin a new response on this connection. Clearing the word in one go is
Expand Down
2 changes: 1 addition & 1 deletion packages/bun-uws/src/WebSocketContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ struct WebSocketContext {
/* For whatever reason, if we already have emitted close event, do not emit it again */
WebSocketData *webSocketData = (WebSocketData *) (us_socket_ext(s));
if (webSocketData->socketData && webSocketData->onSocketClosed) {
webSocketData->onSocketClosed(webSocketData->socketData, SSL, (us_socket_t *) s);
webSocketData->onSocketClosed(webSocketData->socketData, SSL, (us_socket_t *) s, 0, false);
}
if (!webSocketData->isShuttingDown) {
/* Emit close event */
Expand Down
2 changes: 1 addition & 1 deletion packages/bun-uws/src/WebSocketData.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ struct WebSocketData : AsyncSocketData<false>, WebSocketState<true> {
/* We could be a subscriber */
Subscriber *subscriber = nullptr;
public:
using OnSocketClosedCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket);
using OnSocketClosedCallback = void (*)(void* userData, int is_ssl, struct us_socket_t *rawSocket, int readError, bool peerEnded);
void *socketData = nullptr;
/* node http compatibility callbacks */
OnSocketClosedCallback onSocketClosed = nullptr;
Expand Down
28 changes: 22 additions & 6 deletions src/js/node/_http_server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const {
} = require("internal/validators");
const {
ConnResetException,
ErrnoException,
hasObserver,
startPerf,
stopPerf,
Expand Down Expand Up @@ -1517,6 +1518,7 @@ function getNodeHTTPServerSocket() {
_paused = false;
#pendingCallback = null;
#pendingAbortMessage;
#closeError: Error | undefined = undefined;
declare encrypted: boolean;
declare _writableState: { emitClose: boolean; decodeStrings: boolean };
declare _readableState: { emitClose: boolean };
Expand Down Expand Up @@ -1631,14 +1633,28 @@ function getNodeHTTPServerSocket() {
// is deferred to #onClose so the dispatch promise resolves only after the
// native on_abort has released the pending-request ref.
this.#pendingAbortMessage = this._httpMessage;
handle.onclose = this.#onCloseForDestroy.bind(this, callback, err);
handle.onclose = this.#onCloseForDestroy.bind(this, callback, err, handle);
handle.close();
}
#onClose() {
#onClose(closedHandle = this[kHandle]) {
// freeParser equivalent: runs before 'close' listeners so they observe the
// released parser (free() invoked, kOnTimeout nulled).
releaseServerParserShim(this);
this[kHandle] = null;
if (closedHandle) {
// Peer FIN: 'end' before 'close', like Node's net.Socket. read(0) emits it when nothing reads the socket.
if (closedHandle.peerEnded) {
this.push(null);
this.read(0);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
// With no 'error' listener (a socket handed to 'upgrade') the read error would be an uncaught exception.
const closeError = this.listenerCount("error") > 0 ? closedHandle.closeError : undefined;
if (closeError) {
// Node's errnoException(nread, 'read'): "read ECONNRESET".
const er = new ErrnoException(closeError.errno, "read");
this.#closeError = er.code === closeError.code ? er : closeError;
}
}
this.server?.[kTrackedConnections]?.delete(this);
const timer = this[kSocketTimeoutTimer];
if (timer) {
Expand Down Expand Up @@ -1703,11 +1719,11 @@ function getNodeHTTPServerSocket() {
// tunneled/upgraded sockets, main's kIsTunnel case); reaching here from a
// native close without a JS-initiated destroy must still surface it.
if (!this.destroyed) {
this.destroy();
this.destroy(this.#closeError);
}
}
#onCloseForDestroy(closeCallback, err?: Error) {
this.#onClose();
#onCloseForDestroy(closeCallback, err: Error | undefined, handle) {
this.#onClose(handle);
// Thread the destroy error through to the streams machinery (like
// Node.js's net.Socket._destroy passing the exception to its callback),
// so socket.destroy(err) emits 'error' before 'close'.
Expand Down Expand Up @@ -1758,7 +1774,7 @@ function getNodeHTTPServerSocket() {
if ($isCallable(onclose)) {
onclose.$call(handle);
}
if ($isCallable(callback)) callback(err);
if ($isCallable(callback)) callback(err ?? this.#closeError);
Comment thread
robobun marked this conversation as resolved.
Resolved
return;
}

Expand Down
4 changes: 2 additions & 2 deletions src/jsc/bindings/NodeHTTP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,10 @@ template<bool isSSL>
static void assignOnNodeJSCompat(uWS::TemplatedApp<isSSL>* app)
{
app->enableNodeHttpCompat();
app->setOnSocketClosed([](void* socketData, int is_ssl, struct us_socket_t* rawSocket) -> void {
app->setOnSocketClosed([](void* socketData, int is_ssl, struct us_socket_t* rawSocket, int readError, bool peerEnded) -> void {
auto* socket = reinterpret_cast<JSNodeHTTPServerSocket*>(socketData);
ASSERT(rawSocket == socket->socket || socket->socket == nullptr);
socket->onClose();
socket->onClose(readError, peerEnded);
});
app->setOnSocketDrain([](void* socketData, int is_ssl, struct us_socket_t* rawSocket) -> void {
auto* socket = reinterpret_cast<JSNodeHTTPServerSocket*>(socketData);
Expand Down
4 changes: 3 additions & 1 deletion src/jsc/bindings/node/JSNodeHTTPServerSocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -646,10 +646,12 @@ static void notifyResponsesOnClose(JSNodeHTTPServerSocket* socket)
}
}

void JSNodeHTTPServerSocket::onClose()
void JSNodeHTTPServerSocket::onClose(int readError, bool peerEnded)
{
syncPeerCertificateVerification();
this->socket = nullptr;
this->closeReadError = readError;
this->peer_ended = peerEnded;
if (auto* res = this->currentResponseObject.get(); res != nullptr && res->m_ctx != nullptr) {
Bun__NodeHTTPResponse_setClosed(res->m_ctx);
}
Expand Down
5 changes: 4 additions & 1 deletion src/jsc/bindings/node/JSNodeHTTPServerSocket.h
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ class JSNodeHTTPServerSocket : public JSC::JSDestructibleObject {
unsigned ended : 1 = 0;
unsigned upgraded : 1 = 0;
unsigned peer_cert_verified : 1 = 0;
/* Set by onClose() for the peerEnded / closeError getters: the peer's FIN, the error of a failed read. */
unsigned peer_ended : 1 = 0;
int closeReadError = 0;
const char* peerCertVerifyErrorCode = nullptr;
JSC::Strong<JSNodeHTTPServerSocket> strongThis = {};

Expand Down Expand Up @@ -156,7 +159,7 @@ class JSNodeHTTPServerSocket : public JSC::JSDestructibleObject {

void detach();
void syncPeerCertificateVerification();
void onClose();
void onClose(int readError, bool peerEnded);
void onDrain();
void onData(const char* data, int length, bool last);

Expand Down
24 changes: 24 additions & 0 deletions src/jsc/bindings/node/JSNodeHTTPServerSocketPrototype.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ extern "C" uint64_t uws_res_get_remote_address_info(void* res, const char** dest
extern "C" uint64_t uws_res_get_local_address_info(void* res, const char** dest, int* port, bool* is_ipv6);
extern "C" void us_socket_resume(us_socket_t*);
extern "C" void us_socket_pause(us_socket_t*);
extern "C" JSC::EncodedJSValue Bun__socketReadErrorFromCloseCode(JSC::JSGlobalObject* globalObject, int code);

namespace Bun {

Expand Down Expand Up @@ -56,6 +57,8 @@ JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterIsSecureEstablished);
JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterServername);
JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterAuthorizationError);
JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterPeerCertVerified);
JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterCloseError);
JSC_DECLARE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterPeerEnded);

JSC_DEFINE_CUSTOM_SETTER(noOpSetter, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue value, JSC::PropertyName propertyName))
{
Expand Down Expand Up @@ -87,6 +90,8 @@ static const JSC::HashTableValue JSNodeHTTPServerSocketPrototypeTableValues[] =
{ "servername"_s, static_cast<unsigned>(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterServername, noOpSetter } },
{ "authorizationError"_s, static_cast<unsigned>(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterAuthorizationError, noOpSetter } },
{ "peerCertVerified"_s, static_cast<unsigned>(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterPeerCertVerified, noOpSetter } },
{ "closeError"_s, static_cast<unsigned>(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterCloseError, noOpSetter } },
{ "peerEnded"_s, static_cast<unsigned>(JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::ReadOnly), JSC::NoIntrinsic, { JSC::HashTableValue::GetterSetterType, jsNodeHttpServerSocketGetterPeerEnded, noOpSetter } },
};

void JSNodeHTTPServerSocketPrototype::finishCreation(JSC::VM& vm)
Expand Down Expand Up @@ -300,6 +305,25 @@ JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterPeerCertVerified, (JSC::JSG
return JSValue::encode(JSC::jsBoolean(thisObject->isPeerCertificateVerified()));
}

// The error of the read that closed the connection (`read ECONNRESET` for a peer RST), or undefined.
JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterCloseError, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName))
{
auto* thisObject = dynamicDowncast<JSNodeHTTPServerSocket>(JSC::JSValue::decode(thisValue));
if (!thisObject || !thisObject->closeReadError) {
return JSValue::encode(JSC::jsUndefined());
}
return Bun__socketReadErrorFromCloseCode(globalObject, thisObject->closeReadError);
}

JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterPeerEnded, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName))
{
auto* thisObject = dynamicDowncast<JSNodeHTTPServerSocket>(JSC::JSValue::decode(thisValue));
if (!thisObject) [[unlikely]] {
return JSValue::encode(JSC::jsUndefined());
}
return JSValue::encode(JSC::jsBoolean(thisObject->peer_ended));
}

JSC_DEFINE_CUSTOM_GETTER(jsNodeHttpServerSocketGetterDuplex, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName))
{
auto* thisObject = dynamicDowncast<JSNodeHTTPServerSocket>(JSC::JSValue::decode(thisValue));
Expand Down
9 changes: 9 additions & 0 deletions src/runtime/socket/socket_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ fn read_error_from_close_code(code: c_int) -> sys::Error {
}
}

/// `read_error_from_close_code` for C++: the `closeError` getter of `JSNodeHTTPServerSocket`.
#[unsafe(no_mangle)]
pub(crate) extern "C" fn Bun__socketReadErrorFromCloseCode(
global: &JSGlobalObject,
code: c_int,
) -> JSValue {
<sys::Error as jsc::SysErrorJsc>::to_js(&read_error_from_close_code(code), global)
Comment thread
robobun marked this conversation as resolved.
Resolved
}

// ──────────────────────────────────────────────────────────────────────────
// Re-exports
// ──────────────────────────────────────────────────────────────────────────
Expand Down
Loading
Loading