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
44 changes: 34 additions & 10 deletions packages/bun-uws/src/HttpParser.h
Original file line number Diff line number Diff line change
Expand Up @@ -1429,7 +1429,13 @@ struct HttpResponseData;
* to break here as we either have upgraded to
* WebSockets or otherwise closed the socket. */
/* Store any remaining data as head for Node.js compat (connect/upgrade events) */
req->head = std::span<const char>(data, length);
if constexpr (ConsumeMinimally && IsNodeHttp) {
/* consumePostPadded set head to the part of the read that is not in this buffer. The bytes behind
* the request head here are copies of the bytes of the read right in front of that part. */
req->head = std::span<const char>(req->head.data() - length, req->head.size() + length);
Comment thread
robobun marked this conversation as resolved.
Resolved
} else {
req->head = std::span<const char>(data, length);
}
/* Same verdict that selects chunked framing below, so the handler's
* has-body decision cannot disagree with how the body is consumed. */
req->hasTransferEncoding = transferEncoding.has;
Expand Down Expand Up @@ -1661,15 +1667,26 @@ struct HttpResponseData;

size_t maxCopyDistance = std::min<size_t>(maxFallbackSize - fallback.length(), (size_t) length);

/* We don't want fallback to be short string optimized, since we want to move it */
fallback.reserve(fallback.length() + maxCopyDistance + std::max<unsigned int>(MINIMUM_HTTP_POST_PADDING, sizeof(std::string)));
fallback.append(data, maxCopyDistance);
/* This frame owns the bytes for the dispatch: the handler can destroy this parser while the request
* views them, and a parser that lives on must not keep a head that was dispatched. */
std::string reassembled = std::move(fallback);
fallback.clear();

/* The parser reads and writes behind the bytes it is given: the block has room for that padding. */
reassembled.reserve(reassembled.length() + maxCopyDistance + std::max<unsigned int>(MINIMUM_HTTP_POST_PADDING, sizeof(std::string)));
reassembled.append(data, maxCopyDistance);

if constexpr (IsNodeHttp) {
/* The part of this read that is not in the buffer. The dispatch extends it to the whole rest of the read. */
req.head = std::span<const char>(data + maxCopyDistance, length - maxCopyDistance);
}

// break here on break
HttpParserResult consumed = fenceAndConsumePostPadded<true, IsNodeHttp>(maxHeaderSize, maxHeadersCount, isConnectRequest, requireHostHeader, useStrictMethodValidation, useInsecureHTTPParser, useLenientTransferEncoding, nodeHttpRequestTrailers, chunkedExtensionsByteCount, fallback.data(), (unsigned int) fallback.length(), user, &req, requestHandler, dataHandler);
/* Return data will be different than user if we are upgraded to WebSocket or have an error */
HttpParserResult consumed = fenceAndConsumePostPadded<true, IsNodeHttp>(maxHeaderSize, maxHeadersCount, isConnectRequest, requireHostHeader, useStrictMethodValidation, useInsecureHTTPParser, useLenientTransferEncoding, nodeHttpRequestTrailers, chunkedExtensionsByteCount, reassembled.data(), (unsigned int) reassembled.length(), user, &req, requestHandler, dataHandler);
/* Return data will be different than user if we are upgraded to WebSocket or have an error.
* The parser can be gone by then: no member is touched before this return. */
if (consumed.returnedData != user) {
/* The count is in fallback bytes, and the first `had` of them came from
/* The count is in bytes of the buffer, and the first `had` of them came from
* earlier reads. The head ends past them: those reads did not complete it. */
if (!consumed.isError() && consumed.errorStatusCodeOrConsumedBytes != HttpParserResult::WHOLE_READ) {
consumed.errorStatusCodeOrConsumedBytes -= had;
Expand All @@ -1680,10 +1697,12 @@ struct HttpResponseData;
auto consumedBytes = consumed.consumedBytes();
if (consumedBytes) {

/* This logic assumes that we consumed everything in fallback buffer.
/* This logic assumes that we consumed everything in the buffer.
* This is critically important, as we will get an integer overflow in case
* of "had" being larger than what we consumed, and that we would drop data */
fallback.clear();
/* The answer was user, so the parser is alive: it gets the block back for the next head that takes several reads. */
reassembled.clear();
fallback = std::move(reassembled);
data += consumedBytes - had;
length -= consumedBytes - had;

Expand All @@ -1695,7 +1714,10 @@ struct HttpResponseData;
return HttpParserResult::success(0, user);
} else if (remainingStreamingBytes) {
if(isConnectRequest) {
dataHandler(user, std::string_view(data, length), false);
/* node:http got the whole rest of this read as the head of the request. */
if constexpr (!IsNodeHttp) {
dataHandler(user, std::string_view(data, length), false);
}
return HttpParserResult::success(0, user);
} else if (isParsingChunkedEncoding(remainingStreamingBytes)) {
/* It's either chunked or with a content-length */
Expand Down Expand Up @@ -1753,6 +1775,8 @@ struct HttpResponseData;
}

} else {
/* The head is not complete: nothing was dispatched, and the parser keeps what it has of it. */
fallback = std::move(reassembled);
if (fallback.length() == maxFallbackSize) {
return HttpParserResult::error(HTTP_ERROR_431_REQUEST_HEADER_FIELDS_TOO_LARGE, HTTP_PARSER_ERROR_REQUEST_HEADER_FIELDS_TOO_LARGE);
}
Expand Down
6 changes: 1 addition & 5 deletions src/runtime/server/NodeHTTPResponse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -635,11 +635,7 @@ impl NodeHTTPResponse {
);
}

// The sec-websocket-* headers were already copied into
// raw_response.upgrade(); the underlying HttpParser::fallback buffer is
// freed when uWS adopts the socket above, so set_on_aborted_handler
// (which would call preserve_web_socket_headers_if_needed) must not run
// post-upgrade — it would read freed header views.
// The request's header views end with its dispatch: this context must not read them later.
self.upgrade_context.with_mut(|c| c.reset());

// Last step: a reader that waits for the body gets its 'end', like Node 25 and older.
Expand Down
40 changes: 39 additions & 1 deletion test/js/bun/http/serve-pending-promise-abort-leak.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe } from "harness";
import { bunEnv, bunExe, bunRun } from "harness";
import { connect } from "node:net";
import { join } from "node:path";

Expand All @@ -12,6 +12,10 @@ async function stopAndAssertDrained(server: ReturnType<typeof Bun.serve>) {
expect(server.pendingRequests).toBe(0);
}

// symbolize=0 so an unfixed build's ASAN abort exits promptly instead of
// spending seconds in llvm-symbolizer.
const asanOptionsWithoutSymbolizer = [bunEnv.ASAN_OPTIONS, "symbolize=0"].filter(Boolean).join(":");

test.each([false, true])(
"RequestContext is freed when client aborts before Promise<Response> settles (http2: %p)",
async http2 => {
Expand Down Expand Up @@ -737,6 +741,40 @@ test.each(stoppedRequests)("server.stop(true) inside the handler of %s aborts it
await stopped!;
});

// A request head that arrives split over two reads is parsed out of the HTTP
// parser's per-socket fallback buffer, and the uWS request the dispatch holds
// views into that buffer. server.stop(true) inside the handler closes the
// request's own socket right there, and the close destructed the parser with
// its buffer. Everything that materialises the headers after that read freed
// memory: `req.headers` inside the handler, and the snapshot the server takes
// itself when an async handler ends the dispatch. Under a sanitizer it is a
// heap-use-after-free; without one the headers come back as the bytes of
// whatever allocation took the block over.
test.concurrent.each(["lazy", "async"])(
"a request head split over two reads survives server.stop(true) in the handler (%s headers)",
async mode => {
expect(
await bunRun(join(import.meta.dir, "serve-split-head-stop-fixture.ts"), {
SPLIT_HEAD_MODE: mode,
ASAN_OPTIONS: asanOptionsWithoutSymbolizer,
}),
).toSpawn(`${Buffer.alloc(40, 0x4d).toString()}|300|host,x-mark,x-pad`);
},
);

// The same buffer, reached by the client alone: no server API call and no
// nested event loop. The head is split, the request declares a body it never
// sends, and `Connection: close` makes the completed response close the socket
// inside the dispatch. The pending `req.text()` then rejects, and its handler
// reads a url and headers that the close already freed.
test.concurrent("a split request head survives a Connection: close response on an unfinished body", async () => {
expect(
await bunRun(join(import.meta.dir, "serve-split-head-close-fixture.ts"), {
ASAN_OPTIONS: asanOptionsWithoutSymbolizer,
}),
).toSpawn(`AbortError|"http://x/a"|300|connection,content-length,host,x-pad`);
});

// A Response the server will never render still owns a body stream that
// somebody produces into. The server has to cancel it, like a client abort
// after the stream was attached does, or the producer waits for a pull that
Expand Down
56 changes: 56 additions & 0 deletions test/js/bun/http/serve-split-head-close-fixture.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

77 changes: 77 additions & 0 deletions test/js/bun/http/serve-split-head-stop-fixture.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading