Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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
15 changes: 12 additions & 3 deletions packages/bun-uws/src/HttpContext.h
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ struct HttpContext {
((AsyncSocket<SSL> *) s)->cork();

/* Mark that we are inside the parser now */
httpContextData->flags.isParsingHttp = true;
httpResponseData->isParsingHttp = true;
httpResponseData->isIdle = false;

/* node:http compat: maintain the headers/request timeout window (see
Expand Down Expand Up @@ -548,8 +548,6 @@ struct HttpContext {

auto httpErrorStatusCode = result.httpErrorStatusCode();

/* Mark that we are no longer parsing Http */
httpContextData->flags.isParsingHttp = false;
/* If we got fullptr that means the parser wants us to close the socket from error (same as calling the errorHandler) */
if (httpErrorStatusCode) {
/* node:http compat: parse errors surface as the server's 'clientError'
Expand All @@ -559,6 +557,8 @@ struct HttpContext {
* parsing further requests on this connection. */
if (IsNodeHttp && httpContextData->onClientError) {
httpResponseData->state |= HttpResponseData<SSL>::HTTP_NODE_PARSING_STOPPED;
/* Cleared before onClientError, which may close the socket. */
httpResponseData->isParsingHttp = false;
httpContextData->onClientError(SSL, s, result.parserError, data, length);
if (!us_socket_is_closed(s)) {
/* Balance the parsing ref taken at the top of onData (the
Expand All @@ -583,6 +583,9 @@ struct HttpContext {
auto returnedData = result.returnedData;
/* We need to uncork in all cases, except for nullptr (closed socket, or upgraded socket) */
if (returnedData != nullptr) {
/* Mark that we are no longer parsing Http (inside the same liveness
* guard every other httpResponseData deref below already sits in). */
httpResponseData->isParsingHttp = false;
Comment thread
robobun marked this conversation as resolved.
Resolved
/* We don't want open sockets to keep the event loop alive between HTTP requests */
us_socket_unref((us_socket_t *) returnedData);

Expand Down Expand Up @@ -644,6 +647,12 @@ struct HttpContext {
return (us_socket_t *) asyncSocket;
}

/* returnedData was nullptr without close or upgrade (the lambdas'
* HTTP_NODE_PARSING_STOPPED / us_socket_is_shut_down early-returns). */
if (!us_socket_is_closed(s)) {
httpResponseData->isParsingHttp = false;
}

/* It is okay to uncork a closed socket and we need to */
((AsyncSocket<SSL> *) s)->uncork();

Expand Down
1 change: 0 additions & 1 deletion packages/bun-uws/src/HttpContextData.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ template<bool> struct HttpResponse;
struct HttpRequest;

struct HttpFlags {
bool isParsingHttp: 1 = false;
bool rejectUnauthorized: 1 = false;
bool usingCustomExpectHandler: 1 = false;
bool requireHostHeader: 1 = true;
Expand Down
78 changes: 41 additions & 37 deletions packages/bun-uws/src/HttpResponse.h
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,37 @@ struct HttpResponse : public AsyncSocket<SSL> {
getHttpResponseData()->state |= HttpResponseData<SSL>::HTTP_WROTE_DATE_HEADER;
}

/* Uncorks a corked end, then closes if the response is done and flagged
* close; returns true when the socket was closed. While the parser is
* running on THIS socket, the close defers to onData's tail so the body
* is still consumed and validated. */
bool uncorkAndCloseIfNeeded(HttpResponseData<SSL> *httpResponseData, bool keepCorked) {
if (Super::isCorked()) {
if (keepCorked) {
return false;
}
this->uncork();
}

if (httpResponseData->isParsingHttp) {
return false;
}

if (httpResponseData->shouldCloseConnection()) {
if ((httpResponseData->state & HttpResponseData<SSL>::HTTP_RESPONSE_PENDING) == 0) {
if (((AsyncSocket<SSL> *) this)->hasFullyDrained()) {
((AsyncSocket<SSL> *) this)->shutdown();
/* We need to force close after sending FIN since we want to hinder
* clients from keeping to send their huge data */
((AsyncSocket<SSL> *) this)->close();
return true;
}
}
}

return false;
}

/* Returns true on success, indicating that it might be feasible to write more data.
* Will start timeout if stream reaches totalSize or write failure.
* keepCorked: if true, skip the trailing uncork so the caller can batch
Expand Down Expand Up @@ -126,12 +157,9 @@ struct HttpResponse : public AsyncSocket<SSL> {
/* We can only write the header once */
if (!(httpResponseData->state & (HttpResponseData<SSL>::HTTP_END_CALLED))) {

/* HTTP 1.1 must send this back unless the client already sent it to us.
* It is a connection close when either of the two parties say so but the
* one party must tell the other one so.
*
* This check also serves to limit writing the header only once. */
if ((httpResponseData->state & HttpResponseData<SSL>::HTTP_CONNECTION_CLOSE) == 0 && !(httpResponseData->state & (HttpResponseData<SSL>::HTTP_WRITE_CALLED))) {
/* RFC 9112 9.6: echo the close option unless the body started
* or the application already wrote a Connection header. */
if (!(httpResponseData->state & (HttpResponseData<SSL>::HTTP_WRITE_CALLED | HttpResponseData<SSL>::HTTP_WROTE_CONNECTION_HEADER))) {
writeHeader("Connection", "close");
Comment thread
robobun marked this conversation as resolved.
Resolved
}

Expand Down Expand Up @@ -187,21 +215,8 @@ struct HttpResponse : public AsyncSocket<SSL> {
}
httpResponseData->markDone(this);

/* We need to check if we should close this socket here now */
if (!Super::isCorked()) {
if (httpResponseData->shouldCloseConnection()) {
if ((httpResponseData->state & HttpResponseData<SSL>::HTTP_RESPONSE_PENDING) == 0) {
if (((AsyncSocket<SSL> *) this)->hasFullyDrained()) {
((AsyncSocket<SSL> *) this)->shutdown();
/* We need to force close after sending FIN since we want to hinder
* clients from keeping to send their huge data */
((AsyncSocket<SSL> *) this)->close();
return true;
}
}
}
} else if (!keepCorked) {
this->uncork();
if (uncorkAndCloseIfNeeded(httpResponseData, keepCorked)) {
return true;
}

/* tryEnd can never fail when in chunked mode, since we do not have tryWrite (yet), only write */
Expand Down Expand Up @@ -252,21 +267,8 @@ struct HttpResponse : public AsyncSocket<SSL> {
/* Remove onAborted function if we reach the end */
if (httpResponseData->offset == totalSize) {
httpResponseData->markDone(this);

/* We need to check if we should close this socket here now */
if (!Super::isCorked()) {
if (httpResponseData->shouldCloseConnection()) {
if ((httpResponseData->state & HttpResponseData<SSL>::HTTP_RESPONSE_PENDING) == 0) {
if (((AsyncSocket<SSL> *) this)->hasFullyDrained()) {
((AsyncSocket<SSL> *) this)->shutdown();
/* We need to force close after sending FIN since we want to hinder
* clients from keeping to send their huge data */
((AsyncSocket<SSL> *) this)->close();
}
}
}
} else if (!keepCorked) {
this->uncork();
if (uncorkAndCloseIfNeeded(httpResponseData, keepCorked)) {
return true;
}
}
Comment thread
robobun marked this conversation as resolved.
Resolved

Expand Down Expand Up @@ -372,6 +374,8 @@ struct HttpResponse : public AsyncSocket<SSL> {
BackPressure backpressure(std::move(((AsyncSocketData<SSL> *) responseData)->buffer));

auto* socketData = responseData->socketData;
/* Captured before ~HttpResponseData and adopt (both invalidate it). */
bool isParsingHttp = responseData->isParsingHttp;
HttpContextData<SSL> *httpContextData = httpContext->getSocketContextData();

/* Destroy HttpResponseData (the IsNodeHttp=true type on node:http
Expand Down Expand Up @@ -412,7 +416,7 @@ struct HttpResponse : public AsyncSocket<SSL> {
}

/* We should only mark this if inside the parser; if upgrading "async" we cannot set this */
if (httpContextData->flags.isParsingHttp) {
if (isParsingHttp) {
/* We need to tell the Http parser that we changed socket */
httpContextData->upgradedWebSocket = webSocket;
}
Expand Down
8 changes: 8 additions & 0 deletions packages/bun-uws/src/HttpResponseData.h
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ struct HttpResponseData : AsyncSocketData<SSL>, HttpParser {
* into the shared word so the shared response-end path (internalEnd) never
* has to touch the node-only field. */
HTTP_NODE_HAS_RESPONSE_TRAILERS = 1 << 16,
/* The application already wrote a Connection header (Bun.serve's
* Response headers, or node:http's _storeHeader which always writes
* one); suppresses the automatic one in internalEnd. */
HTTP_WROTE_CONNECTION_HEADER = 1 << 17,

/* Bits that describe the connection rather than the response in flight.
* There is one HttpResponseData per socket, reused by every request on a
Expand Down Expand Up @@ -197,6 +201,10 @@ struct HttpResponseData : AsyncSocketData<SSL>, HttpParser {
/* The parser writes this through a bool& (getHeaders / consumePostPadded),
* so it cannot live in `state`. */
bool isConnectRequest = false;
/* Brackets one onData call on THIS socket (can span several pipelined
* requests). Not a `state` bit: resetResponseState would clear it
* mid-parse. */
bool isParsingHttp = false;

/* Chunk-extension bytes consumed on the current chunk-size line, reset per
* chunk (llhttp's on_chunk_header); capped at MAX_CHUNK_EXTENSION_SIZE for
Expand Down
21 changes: 11 additions & 10 deletions src/jsc/bindings/NodeHTTP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -830,12 +830,12 @@ static void writeFetchHeadersToUWSResponse(WebCore::FetchHeaders& headers, uWS::
data->state |= uWS::HttpResponseData<isSSL>::HTTP_WROTE_TRANSFER_ENCODING_HEADER;
}

// RFC 9112 §9.6: a server that sends the "close" connection option MUST
// close the connection after the response. Mark the uWS state so
// end()/tryEnd() shut the socket down instead of returning it to the
// keep-alive pool.
if (header.key == WebCore::HTTPHeaderName::Connection && connectionValueHasClose(value)) {
data->state |= uWS::HttpResponseData<isSSL>::HTTP_CONNECTION_CLOSE;
// Prevent automatic Connection: close insertion when user provides one
if (header.key == WebCore::HTTPHeaderName::Connection) {
data->state |= uWS::HttpResponseData<isSSL>::HTTP_WROTE_CONNECTION_HEADER;
if (connectionValueHasClose(value)) {
data->state |= uWS::HttpResponseData<isSSL>::HTTP_CONNECTION_CLOSE;
}
}
writeResponseHeader<isSSL>(res, name, value);
}
Expand Down Expand Up @@ -939,10 +939,11 @@ static bool NodeHTTPServer__writeHead(
}
response->writeStatus(std::string_view(statusMessage, statusMessageLength));

// node:http's ServerResponse owns the Date header entirely (it honors
// res.sendDate / removeHeader("date") in JS), so never let uWS write its
// own Date header for these responses.
response->getHttpResponseData()->state |= uWS::HttpResponseData<isSSL>::HTTP_WROTE_DATE_HEADER;
// node:http's ServerResponse owns the Date and Connection headers entirely
// (it honors res.sendDate / removeHeader in JS, and _storeHeader always
// writes a Connection line), so never let uWS write its own.
Comment thread
robobun marked this conversation as resolved.
Resolved
response->getHttpResponseData()->state |= uWS::HttpResponseData<isSSL>::HTTP_WROTE_DATE_HEADER
| uWS::HttpResponseData<isSSL>::HTTP_WROTE_CONNECTION_HEADER;

// 204/304 responses must not carry any body framing, even when the user
// explicitly set a Transfer-Encoding header (Node.js suppresses the
Expand Down
24 changes: 18 additions & 6 deletions src/uws_sys/libuwsockets.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1326,7 +1326,10 @@ extern "C"
data->offset = offset;
data->state |= uWS::HttpResponseData<true>::HTTP_END_CALLED;
data->markDone(uwsRes);
uwsRes->resetTimeout();
if (!uwsRes->uncorkAndCloseIfNeeded(data, /* keepCorked: caller owns uncork */ true))
{
uwsRes->resetTimeout();
}
}
else
{
Expand All @@ -1335,7 +1338,10 @@ extern "C"
data->offset = offset;
data->state |= uWS::HttpResponseData<false>::HTTP_END_CALLED;
data->markDone(uwsRes);
uwsRes->resetTimeout();
if (!uwsRes->uncorkAndCloseIfNeeded(data, /* keepCorked: caller owns uncork */ true))
{
uwsRes->resetTimeout();
}
}
}
void uws_res_reset_timeout(int ssl, uws_res_r res) {
Expand Down Expand Up @@ -1365,7 +1371,7 @@ extern "C"
auto *data = uwsRes->getHttpResponseData();
if (close_connection)
{
if (!(data->state & uWS::HttpResponseData<true>::HTTP_CONNECTION_CLOSE))
if (!(data->state & (uWS::HttpResponseData<true>::HTTP_WRITE_CALLED | uWS::HttpResponseData<true>::HTTP_WROTE_CONNECTION_HEADER)))
{
uwsRes->writeHeader("Connection", "close");
}
Expand All @@ -1377,15 +1383,18 @@ extern "C"
}
data->state |= uWS::HttpResponseData<true>::HTTP_END_CALLED;
data->markDone(uwsRes);
uwsRes->resetTimeout();
if (!uwsRes->uncorkAndCloseIfNeeded(data, /* keepCorked: caller owns uncork */ true))
{
uwsRes->resetTimeout();
}
}
else
{
uWS::HttpResponse<false> *uwsRes = (uWS::HttpResponse<false> *)res;
auto *data = uwsRes->getHttpResponseData();
if (close_connection)
{
if (!(data->state & uWS::HttpResponseData<false>::HTTP_CONNECTION_CLOSE))
if (!(data->state & (uWS::HttpResponseData<false>::HTTP_WRITE_CALLED | uWS::HttpResponseData<false>::HTTP_WROTE_CONNECTION_HEADER)))
{
uwsRes->writeHeader("Connection", "close");
}
Expand All @@ -1399,7 +1408,10 @@ extern "C"
}
data->state |= uWS::HttpResponseData<false>::HTTP_END_CALLED;
data->markDone(uwsRes);
uwsRes->resetTimeout();
if (!uwsRes->uncorkAndCloseIfNeeded(data, /* keepCorked: caller owns uncork */ true))
{
uwsRes->resetTimeout();
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}

Expand Down
Loading
Loading