Repository navigation
Keep file bodies at the length they announce - #2404
Merged
hyperxpro merged 6 commits intoNov 25, 2026
Merged
Conversation
A FilePart takes its file's length when the request is built, and the Content-Length announces it. If the file changed before or while it was sent, the part did not keep to that length: - A file that grew was sent whole, so its extra bytes went out after the end of the body, where the server reads them as the start of the next request. - A file that got shorter ended the part early on the copying path, and stalled the zero-copy path: FileChannel.transferTo returns 0, not -1, at the end of the file. Either way, the server waited for the rest. Both paths of FileMultipartPart now read at most the length taken, and fail with an IOException when the file ends before it. On the zero-copy path, a transfer of 0 bytes is only the end of the file if the open file is no longer than what was sent: a target that takes nothing returns 0 too. Over HTTP/2, a File body read at most its length already, but ended the body early when the file got shorter, leaving it to the server to notice the content-length. It now fails the same way. Claude Code on behalf of Matthias Kurz Co-Authored-By: Claude Opus 5.5 <[email protected]>
On a pooled connection, WriteListener lets a failed write be retried when any exception in its causes has "Connection reset" in its message, taking it for a connection that died. The error of a file part that ended early has the part's name in its message, so a part named "Connection reset" was retried. The retry took the shorter file's length and succeeded. A file body that ends before its length now fails with an EOFException, as Netty's ChunkedNioFile does for the same case, and WriteListener never leaves a write that failed with one in its causes to the retry. A genuine connection error is still retried as before. The tests now count the attempts of each request. Claude Code on behalf of Matthias Kurz Co-Authored-By: Claude Opus 5.5 <[email protected]>
AsyncHttpClient#2401 added imports to Http2StreamingBodyFlowControlTest next to the ones this branch added. Kept both sets. Claude Code on behalf of Matthias Kurz Co-Authored-By: Claude Opus 5.5 <[email protected]>
hyperxpro
requested changes
Nov 24, 2026
A stream body or stream part that ends before its declared length failed with a plain IOException. On a pooled connection, WriteListener leaves a failed write to the retry when its error has "Connection reset" in its message, and a stream part's error has the part's name in it, so such a part was retried. They now fail with an EOFException, as a file that got shorter does, which WriteListener never retries. Its comment now says which bodies fail that way, and that Netty's DefaultFileRegion reports a shorter file with a plain IOException whose message has no caller text. Claude Code on behalf of Matthias Kurz Co-Authored-By: Claude Opus 5.5 <[email protected]>
On the zero-copy path, FileChannel.transferTo returns 0 at the end of the file and when the target takes nothing. The part compared the file's size with its position to tell the two apart, but a file can report a size it does not have: a sysfs file reports 4096 bytes or more and holds fewer. The part then kept returning 0, and the event loop kept calling it until the request timed out. It now reads one byte at its position when transferTo returns 0, and takes -1 for the end of the file. Claude Code on behalf of Matthias Kurz Co-Authored-By: Claude Opus 5.5 <[email protected]>
The change runs in onRequestSend, which only logs an exception, so a change that failed left the grow tests passing. The HTTP/2 tests now apply the change first and record that it ran, and the announced length. They check that it ran, and the FilePart grow test checks the announced length too. The HTTP/1.1 grow test checks the file's new size. Since main, Http2BodyWriter fails the request with its body's error, so the HTTP/2 shrink tests now check the file's EOFException and its message, with a client that replays a request after an IOException. Claude Code on behalf of Matthias Kurz Co-Authored-By: Claude Opus 5.5 <[email protected]>
hyperxpro
approved these changes
Nov 25, 2026
11 tasks done
hyperxpro
added a commit
that referenced
this pull request
Nov 25, 2026
## Summary - **A `Content-Length` header that the caller sets goes on the wire as it is.** `NettyRequestFactory` only sets its own when there is none (`if (!headers.contains(CONTENT_LENGTH))`), as #1440 asked. The body is then written in full, whatever the header says. - **What happens with a wrong header,** shown on `main` `8b81226fa` with a raw socket server and `Content-Length: 49`: - **A body of 84 bytes** (`byte[]`, `String`, `InputStream` or `File`, with and without zero-copy) sends 35 bytes after the declared body. The server parses them as the next request on the connection, here `GET /smuggled HTTP/1.1`, and the request itself gets a 200. - **A body of 20 bytes** leaves the server waiting for the rest until its timeout. - **What is checked already:** - **#2401** checks the header for stream bodies. - **#2402,** with hyperxpro's commit, stops a body that a `BodyGenerator` hands out at the header, and fails it if it ends before. - **What this adds:** a request whose body has a length AHC knows up front is rejected, and not sent. - **For comparison,** Java's `HttpClient` refuses a `Content-Length` header by default ("restricted header name"). ## Change **For every request but a `CONNECT`, a caller's `Content-Length` header:** - **must be a length,** with the parsing that #2401 added: one field, ASCII digits, no sign, trailing whitespace allowed; - **must equal the body's length where AHC knows it.** Otherwise the request fails with an `IllegalArgumentException`, for example `Content-Length header 49 does not match the body's length 84`, or `Content-Length header [+17] is not a length`. The header is never overwritten, so #1440's precedence stays. **Two places check it:** | Where | Bodies | |---|---| | `NettyRequestSender.sendRequest`, before a pooled connection is taken, replacing #2401's `checkStreamBodyLength` | `byte[]`, a list of `byte[]`, `String` (its length in bytes, in the request's charset), `ByteBuffer`, `ByteBuf`, form parameters, `File`, `FileBodyGenerator`, and no body at all (length 0). Stream bodies as in #2401. | | `NettyRequestFactory.newNettyRequest`, once the body is built | Everything, against the built body's length. This is the only check for multipart bodies, whose length depends on a boundary that AHC may only pick when it builds the body, and for other `BodyGenerator`s, whose length is the created body's. A `BodyGenerator`'s body is closed when the check fails. | **Through an HTTP proxy to an `https` URL,** `newNettyRequest` runs once the tunnel's TLS handshake is done, inside a listener of the handshake future. Netty logs and discards what that listener throws, so a failed check left the request waiting for its timeout while it held the tunnel's connection. The third commit aborts the request there, as the listener already did for a failed HTTP/2 upgrade, which fails the future and closes the connection. **Unchanged:** - **A file that isn't there** still fails with its own error ("is not a file or doesn't exist"), not with a length mismatch. - **Redirects:** a redirect that drops the body, or rebuilds one of known length, already removes the caller's header (`Redirect30xInterceptor`). A test covers a 302 after a POST. **This is a behaviour change.** A request with a wrong header used to go out and might even get a 200. It now fails, and is not sent. The same goes for a `Content-Length` above 0 on a request without a body, and for an invalid header on a body that isn't a stream. ### One `Content-Length` parser The second commit moves the parsing of a `Content-Length` header into a new public method, `HttpUtils.parseContentLength(HttpHeaders)`. - **What it is:** AHC's strict reading of the header for the requests it sends, not a general HTTP parser. - **What it rejects:** a list of identical values such as `16, 16`. RFC 9110 section 8.6 lets a recipient accept and normalise such a list, but a sender must not send it. - **API:** this adds public API. Revapi passes, but that shows compatibility only, not that the method belongs there. - **What used it before:** - **`NettyRequestFactory`,** for a caller's header, from #2401; - **`NettyBodyBody`,** for the header on the wire, from #2402. - **One set of messages:** - `Content-Length header [x] is not a length`; - `Content-Length header [x] is longer than AHC supports`, past `Long.MAX_VALUE`. - **What changes:** - an overflowing header in `NettyBodyBody` said "not a length" before; - #2401's stream messages no longer add "for an InputStream body". #2401 is not released yet. ## Tests | Test | What it checks | |---|---| | `HttpUtilsTest` | `parseContentLength`: no header, lengths with and without trailing whitespace up to `Long.MAX_VALUE`, nine values that are not lengths, two fields, and one past `Long.MAX_VALUE`, each with its message. | | `CallerContentLengthTest` (new) | **Against a raw socket server, for `byte[]`, a list of `byte[]`, `String` (non-ASCII), `ByteBuffer`, `ByteBuf`, form, `File`, a `FileBodyGenerator` region and no body:**<ul><li>with its length in the header, the server gets exactly the body, and the next request on the connection is read as `GET /next HTTP/1.1`;</li><li>with a header 5 bytes longer or shorter, the request fails with the message above. It fails before it takes the pooled connection: with `maxConnections` 1, the next request still gets it, and the server sees only the two GETs;</li><li>an invalid header (`17, 17`, `+17`, `-0`, Arabic-Indic digits) fails as not a length.</li></ul>**Multipart and a `BodyGenerator`:** a wrong header fails, and the request is not sent. A multipart body with its boundary in `Content-Type` and its length in the header goes out whole. The generator's body is closed.<br>**On a pooled connection,** with `maxConnections` 1: a `BodyGenerator` body with a wrong header fails, after it took the connection, and is closed. The next request opens a new connection and succeeds.<br>**Through an HTTP proxy to an `https` URL,** with `maxConnections` 1: a multipart body with a wrong header fails with the message above once the tunnel is up, instead of waiting for its timeout. The next request through the proxy opens a new connection and succeeds.<br>**`ByteBuf` bodies** stay the caller's: each test releases its buffer afterwards and checks that this was the last reference.<br>**A 302 after a POST with a header:** the GET that follows has no body. | **Each part reverted, on `main` `76f24a4b0`:** | Reverted | Result | |---|---| | All of it, i.e. `main` | All 23 rejection tests fail. The request goes out: with a header too short, it gets its 200, and with one too long, the server waits for the rest until the client gives up. | | The check in `newNettyRequest` | Only the multipart and `BodyGenerator` tests fail. | | The check in `sendRequest` | The 21 early tests fail. The request is still refused, but only after it took the pooled connection, which #2403 then closes, so the next request has to open a new connection. | | #2403's close of the polled connection | The pooled `BodyGenerator` test fails: the next request gets `TooManyConnectionsException: Too many connections: 1`. | ## Relation to #2401, #2402 and #2403 - **#2401:** this builds on its header parsing and on its check before a pooled connection is taken, which it generalizes. #2401's tests pass. The second commit changes two of their message assertions, as above. - **#2402** stops a wrapped body at the header when it is written. That includes a `BodyGenerator` body or a multipart body of unknown length, and one that ends before the header fails. This PR rejects a known length that contradicts the header, and the request is not sent. - **Together,** a mismatch is caught before sending where the length is known, and enforced while writing where it is not. - **With this PR,** an invalid caller header no longer reaches #2402's parsing at write time. - **#2403:** a multipart or `BodyGenerator` body is checked once it is built, and on a pooled connection that is after the connection was taken. - **#2403 closes that connection** when building the request fails. - **`bodyGeneratorFailingTheCheckOnAPooledConnectionLeavesTheLimitFree`:** with `maxConnections` 1, the next request opens a new connection and succeeds. Before #2403, it got `TooManyConnectionsException`. - **Merge:** #2402 and #2404 are on `main` now, and the branch is rebased onto it without conflicts. ## Not covered - **A body of unknown length:** here only the header's syntax is checked. That is a `BodyGenerator` without a length, or a multipart body with an `InputStreamPart` without one. Its length is enforced while it is written: by #2401 for stream bodies, and by #2402 for the others. - **A `Transfer-Encoding` header that the caller sets.** - **HTTP/2 is not tested separately.** Both checks run before the protocol matters, and the HTTP/2 request is built from the same headers. ## AI disclosure Claude Code on behalf of Matthias Kurz. The first two commits include `Co-Authored-By` per `AGENTS.md`. ## Test plan **The third commit** (`2da74380a`): - [x] `CallerContentLengthTest`, `StreamBodyDeclaredLengthTest` and `BasicHttpProxyToHttpsTest` on JDK 11: 60 tests, 0 failures. - [x] **Reverted:** `multipartBodyFailsTheLateCheckThroughAProxyTunnel` fails with a `TimeoutException`, the request still waiting after 10 seconds. **The final tree** (`846bd2b70` on `main` `322666a10`, byte-identical to a local build of `main` `76f24a4b0` merged with the earlier branch, #2404 and #2405): - [x] `./mvnw -B -ntp -Dgpg.skip=true clean install` on JDK 11: 2,393 tests, 0 failures, 22 skipped; Revapi passed. Docker was not running, so the 22 skipped include the Testcontainers proxy tests. - [x] Before #2405 was merged, the same two commits on `main` `672321768` (`7e88a169f`): `clean verify` on JDK 11, 2,393 tests, 0 failures, 22 skipped; Revapi passed ("API checks completed without failures", against 3.0.14). This machine's `/etc/resolv.conf` had no `search .` then, so `AddressResolverGroupTest` passed without #2405. **Earlier local revisions (not pushed), before the rebase. Both commits** (`53d68f01e` on #2402; `53d68f01e` differs from the verified `0238963d0` only in the javadoc of `parseContentLength`): - [x] **Merged with #2405 and #2404:** `./mvnw -B -ntp -Dgpg.skip=true clean verify` on JDK 11: 2,393 tests, 0 failures, 22 skipped; Revapi passed, with the new public `HttpUtils.parseContentLength`. Docker was not running, so the 22 skipped include the Testcontainers proxy tests. - [x] **Focused tests:** the classes below plus `HttpUtilsTest`, `InputStreamBodyGeneratorTest` and `BodyChunkedInputTest`: 361 tests, 0 failures, 2 skipped (both in `AuthTimeoutTest`). - **Where:** on JDK 11 and JDK 25, and on JDK 11 with NIO selected explicitly. - **With io_uring,** only the four short-stream tests of `StreamBodyDeclaredLengthTest` from #2401 fail, as they do on `main`. **Earlier local revisions, the first commit alone** (`119a6fcad` on `main` `76f24a4b0`): - [x] `./mvnw -B -ntp -Dgpg.skip=true clean verify` on JDK 11, with the DNS test fix (#2405) merged in: 2,353 tests, 0 failures, 22 skipped; Revapi passed. Docker was not running, so the 22 skipped include the Testcontainers proxy tests. Without that fix, `AddressResolverGroupTest.unknownHostWithDnsResolverGroupFails` fails on a machine with `search .` in `/etc/resolv.conf`, as it does on `main`. - [x] **Each part reverted:** as described above. - [x] **Focused tests:** `CallerContentLengthTest`, `StreamBodyDeclaredLengthTest`, `AuthTimeoutTest`, `BasicHttpTest`, `BodyDeferringAsyncHandlerTest`, `RedirectBodyTest`, `PostRedirectGetTest`, `PostWithQueryStringTest`, `ParamEncodingTest`, `RedirectConnectionUsageTest`, `Http2ConformanceRegressionTest`, `ConnectionPoolTest`, `MultipartBodyTest`, `MultipartUploadTest`, `PutFileTest`, `ZeroCopyFileTest`, `Expect100ContinueTest`, `Http2StreamingBodyFlowControlTest`, `BasicHttp2Test` and `RetryRequestTest`: 304 tests, 0 failures, 2 skipped (both in `AuthTimeoutTest`), on JDK 11. - **The version before the pooled test, `96496a76f`:** 303 tests, 0 failures, 2 skipped (the same two), on JDK 11, 17, 21 and 25, and on JDK 11 with NIO selected explicitly. - **With io_uring,** only the four short-stream tests of `StreamBodyDeclaredLengthTest` from #2401 fail, as they do on `main`. - [x] **Repeats:** `CallerContentLengthTest` (35 tests) 5 runs with the default transport and 5 with io_uring, 0 failures. - [x] **Merged with #2402 (`43771d0fc`) and #2404 (`58f462845`):** - those focused tests plus `InputStreamBodyGeneratorTest`, `BodyChunkedInputTest` and `FilePartChangeTest`: 344 tests, 0 failures, 2 skipped (the same two); - `clean verify` with `-Dmaven.test.failure.ignore=true`, without #2405: 2,387 tests, 1 failure, the `AddressResolverGroupTest` one above. Not a green build. --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Aayush Atharva <[email protected]>
30 of 31 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
FileParttakes its file's length when the request is built, inFileMultipartPart, and the multipartContent-Lengthincludes it. If the file changes before or while it is sent, the part did not keep to that length.FileChannel.transferToreturns 0, not -1, at the end of the file. Either way, the server waited for the rest until a timeout.NettyFileBodyreads aFilebody in chunks (FileChunkSource). It already stopped at the length, but ended the body early when the file got shorter, so only a server that checks thecontent-lengthnoticed.setBody(File)keeps to its length in the same cases. It does:DefaultFileRegion: it sends exactly the length, and fails on a shorter file.ChunkedNioFile: with the Netty version onmain, it does the same.Change
FileMultipartPartnow read at most the length taken when the request was built. Bytes the file gained are not sent.EOFException: Multipart file part 'file' ended after 5000 of its 20000 bytes.FileChunkSource(HTTP/2) now fails the same way:EOFException: File body ended after 1000 of its 65536 bytes.EOFExceptiontoo, with the same messages.WriteListenernever retries these errors. They are allEOFExceptions, the type Netty'sChunkedNioFileuses for the same case.WriteListenerleaves a failed write to the retry when any of its causes has "Connection reset" in its message, taking it for a connection that died.EOFExceptionin its causes is aborted instead. A genuine connection error is still retried.DefaultFileRegion, which sends a file body with zero-copy, reports a shorter file with a plainIOException. Its message has no caller text, so it is not retried either.Tests
MultipartBodyTest/sys/devices/system/cpu/online) fails with that message instead of making no progress. Skipped where the file is missing or holds its size.FilePartChangeTest(new)onRequestSend, after the length is taken and before the body is written.GET /next HTTP/1.1.EOFExceptionin its causes. Over zero-copy, Netty reports a failedFileRegionwrite as "Channel output shutdown", caused by it. The request is sent once.onRequestSendis only logged.StreamBodyDeclaredLengthTestEOFException, andonRetryis never called. The other short-stream tests check for anEOFException.Http2StreamingBodyFlowControlTestFilebody and aFilePartthat grow send exactly the announced length.IOExceptionFilterreplays a request, the request fails with the file'sEOFException, and the client does not end the stream withEND_STREAMas if the body were complete. A frame logger on the test server counts that, ahead of the server's own content-length check, which resets such a stream.FilePartgrowth test also checks the announced length.Filegrowth test guards whatNettyFileBodyalready did: it passes without this PR.Without the
WriteListenerrule: both pooled tests are retried, and the request succeeds.Before this PR (checked on
main8b81226fa, before #2401):MultipartBodyTest: the growth and shrinkage tests fail.FilePartChangeTest:END_STREAM, and the growingFilePartis reset by the server.FileMultipartPartchange: the HTTP/2Fileshrinkage test still fails.Each later change, reverted alone:
IOExceptionfor a stream part: the pooled stream-part tests fail: the request is retried, and fails with "already consumed and cannot be sent again".Relation to #2401 and #2402
They change how a failing body fails the request:
Http2BodyWriterin #2401, andBodyChunkedInputin #2402.File body ended after 1000 of its 65536 bytesorMultipart file part 'file' ended after 1000 of its 65536 bytes.IOExceptiondoesn't get to send the shorter file again. The HTTP/2 tests check that with such a filter.BodyChunkedInputalso fails the request with the body's error before theWriteListenerrule applies. The zero-copy path,BodyFileRegion, relies on the rule.Not covered
setBody(File)over HTTP/1.1 uses Netty'sDefaultFileRegionorChunkedNioFile, which this PR doesn't change. With a sysfs file that holds less than its size,ChunkedNioFilefails at once with anEOFException, whileDefaultFileRegion(zero-copy) waits until the request timeout.Content-Lengthheader set by the caller that contradicts a body's length. Stop stream bodies at their declared length #2401 checks it for stream bodies, and other bodies are a separate change.AI disclosure
Claude Code on behalf of Matthias Kurz. The commits include
Co-Authored-ByperAGENTS.md.Test plan
./mvnw -B -ntp -Dgpg.skip=true -Dmaven.test.failure.ignore=true clean verifyon JDK 11: 2,332 tests, 1 failure, 22 skipped; Revapi passed. The flag lets the build go on to Revapi past the failure below, so this is not a green build. Docker was not running, so the 22 skipped include the Testcontainers proxy tests.AddressResolverGroupTest.unknownHostWithDnsResolverGroupFails. It comes from this machine's resolver configuration:search .in/etc/resolv.confmakes Netty's DNS resolver build a name with an empty label. It fails the same way onmain.StreamBodyDeclaredLengthTest,MultipartBodyTest,FilePartChangeTest,Http2StreamingBodyFlowControlTest,RetryRequestTest,NettyRequestSenderConsumedBodyRetryTest,ConnectionPoolTest,MultipartUploadTest,FilePartLargeFileTest,PutFileTest,ZeroCopyFileTest,RedirectBodyTest,MultipartBasicAuthTest,MultipartStreamPartReplayTest,Http2MultipartStreamPartReplayTest,InputStreamPartLargeFileTest,BodyChunkTest,ChunkingTest,BasicHttpTestandExpect100ContinueTest: 219 tests, 0 failures.StreamBodyDeclaredLengthTestfrom Stop stream bodies at their declared length #2401 fail, as they do onmain. The new pooled stream-part test passes there.FilePartfails at once withMultipart file part 'file' ended after 4 of its 16384 bytes, with and without zero-copy.