GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — IoUring:重构写操作的生命周期管理 by dreamlike-ocean · Pull Request #13 · dreamlike-ocean/netty Conversation
|
| 场景 | 基线吞吐 MiB/s | 本 PR 吞吐 MiB/s | 吞吐变化 | 基线发送端平均堆分配 B/轮 | 本 PR 发送端平均堆分配 B/轮 | 平均分配差值 B/轮 | 基线 GC 次/ms | 本 PR GC 次/ms |
|---|---|---|---|---|---|---|---|---|
| writeSingle | 3304.1 | 3278.5 | -0.77% | 0.00 | 0.00 | ≈0 | 0/0 | 0/0 |
| writev | 3127.6 | 3161.3 | +1.08% | 24.00 | 24.00 | ≈0 | 0/0 | 0/0 |
| sendzc | 2753.5 | 2754.8 | +0.05% | 0.00 | 0.00 | ≈0 | 0/0 | 0/0 |
| sendmsgzc | 2532.7 | 2554.0 | +0.84% | 0.01 | 0 | ≈0 | 0/0 | 0/0 |
注:结果受 JIT 内联与逃逸分析影响,多轮测试未观察到稳定的吞吐回退。SENDMSG_ZC 多出的 24 B/轮对应两版共有、可被逃逸分析消除的匿名
MessageProcessor;表中保留实测分配值。
下表为默认配置、未注册 Channel 及其专属 Java 对象的常驻堆占用,排除共享 allocator/EventLoop、业务 handler、payload 和堆外内存。使用同一 JDK,开启压缩指针、8 B 对齐,关闭 compact object headers。
| 类型与状态 | 基线常驻堆 B/Channel | 本 PR 常驻堆 B/Channel | 差值 B/Channel |
|---|---|---|---|
| TCP,刚创建 | 864 | 832 | -32 |
| TCP,writeSingle 使用后 | 888 | 832 | -56 |
| TCP,8-buffer WRITEV 使用后 | 912 | 832 | -80 |
| TCP,SEND_ZC,一个 slot 回收后 | 984 | 976 | -8 |
| TCP,8-buffer SENDMSG_ZC,一个 slot 回收后 | 1008 | 1536 | +528 |
| UDP,刚创建 | 172264 | 172216 | -48 |
TCP 8-buffer SENDMSG_ZC 的 +528 B 主要来自 per-channel MsgHdrMemory 缓存及其关联对象,slot 回收后继续保留供后续发送复用。 未使用 SENDMSG_ZC 的普通 TCP Channel 不承担这笔缓存开销。
另外,移除共享的 MsgHdrMemoryArray 和 IovArrayReferenceCollector 后,每个 IoUringIoHandler 减少约 332.3 KiB 常驻堆占用。这笔节省按 handler 计算;总内存变化取决于 handler 数及实际使用 SENDMSG_ZC 的 Channel 数。
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…e registration (netty#17656) Motivation: If the server side `LocalChannel` of a connection is closed before it is registered, the client's `connect()` never completes (the local transport has no connect timeout). This happens when: - the `LocalServerChannel` is closed while the connection is still queued (auto-read off, or `server.close()` right after `connect()`), - the accepted channel cannot be registered (for example the child group is shut down). Related problems on the same path: - A connection that reaches the server after the server channel was closed is still accepted, and `connect()` succeeds against a closed server. - If the client closes while its connection is still queued, `client.close()` fails with `IllegalStateException: channel not registered to an event loop`. When the server accepts the connection later, the client is reopened (`isOpen()` is true again) and the accepted channel becomes active with a closed peer. The same `IllegalStateException` happens for `server.close(); client.close();` issued back to back while the connection is queued. Modification: - `LocalServerChannel`: close queued connections on close, and close connections that arrive after the channel was closed. - The client no longer touches an accepted channel that has not completed the connection. When the accepted channel is registered, it moves the client from `BOUND` to `CONNECTED` with a CAS. The client's `doClose()` uses `getAndSet(CLOSED)`, so exactly one side wins. If the client was closed first, the accepted channel closes itself on its own event loop. - `LocalChannel.tryClose(false)`: if a connect is still pending, the accepted channel was closed before the connection was established. Fail the connect with `ConnectException` (as when nothing is bound to the address) and close the client. A client that closes itself still fails its connect with `ClosedChannelException`. - `registered()` reads `peer` once instead of checking it and reading it again. - Add five tests to `LocalChannelTest`. Result: `connect()` fails with `ConnectException` instead of hanging when the server side goes away, a connection to an already closed server fails, and `client.close()` succeeds in the orderings above. The five new tests fail on 4.2 without the change and pass with it. `LocalChannelTest` (32 tests), the transport module (407 tests), the handler, handler-proxy, codec-haproxy and codec-http2 tests that use the local transport, and checkstyle pass. I also ran a stress test (not included): client, server and accepted channels on three event loops, and the client closes 0 to 100 µs after `connect()`. On 4.2, 20,000 iterations gave 499 `close()` failures with `IllegalStateException`, 2,024 clients open again after `close()`, and 1,523 accepted channels left open and active. With this change, 100,000 iterations with `-ea` had none of these, and every accepted channel was closed and deregistered. Known limitations: - A client that closes while its connection is queued is still accepted later: the child handler's `initChannel` runs and `channelRegistered` fires, then the accepted channel is closed without `channelActive`. - Queued connections that the server closes (on close, or when they arrive after close) were never registered. They are closed with `closeForcibly()`, so their `closeFuture` does not complete. Only code that overrides `newLocalChannel` can see these channels. - Not changed by this PR: if the client closes after the accepted channel completed the connection but before the client's event loop runs the connect success task, the client's pipeline gets `channelInactive` without `channelActive`. 4.2 does the same.
…on (netty#17609) Motivation: `FixedChannelPool.release(...)` does not give back the acquired slot if the release failed with an `IllegalArgumentException`: ```java // Check if the exception was not because of we passed the Channel to the wrong pool. if (!(cause instanceof IllegalArgumentException)) { decrementAndRunTaskQueue(); } ``` `SimpleChannelPool` uses `IllegalArgumentException` for "Channel ... was not acquired from this ChannelPool", and this check has been there since the pools were added. But the release also fails with any exception thrown by user code, for example `ChannelPoolHandler.channelReleased()`, `ChannelHealthChecker.isHealthy()` when the release health check is enabled, or an overridden `offerChannel()`. All of these go through `closeAndFail(...)`. If that exception is an `IllegalArgumentException`, the channel is closed but still counted as acquired. The slot is lost forever: with `maxConnections = 1` every later `acquire()` waits forever or times out. Modification: - `SimpleChannelPool` fails the release of a channel that was not acquired from the pool with a new package-private `ChannelNotAcquiredFromPoolException` (with a `serialVersionUID`). It extends `IllegalArgumentException` and keeps the message and the stack trace, so users who catch or assert `IllegalArgumentException` are not affected. The only visible difference is the class name: `toString()` and logged stack traces now show `io.netty.channel.pool.SimpleChannelPool$ChannelNotAcquiredFromPoolException: Channel ... was not acquired from this ChannelPool` instead of `java.lang.IllegalArgumentException: ...`. - `FixedChannelPool` only skips the decrement for that exception. - Add `FixedChannelPoolTest.testReleaseFailsWithIllegalArgumentExceptionFromHandler`: `maxConnections = 1` with a handler whose `channelReleased()` throws an `IllegalArgumentException`. The release must fail with that exception, the acquired count must drop to 0, and the next `acquire()` must succeed. - `testReleaseDifferentPool` still expects an `IllegalArgumentException`, and now also asserts `pool2.acquiredChannelCount() == 0` after the failed release, so the wrong-pool release still does not give back a slot of the pool it was released to. Result: A release that fails for any reason other than "not acquired from this pool" always gives back its slot, so a buggy handler or health checker can no longer shrink a `FixedChannelPool` for good.
…etty#17663) Motivation: `ChunkedWriteHandler` has no `handlerRemoved()`. Its queue is only drained by `flush()`, `resumeTransfer()`, `channelWritabilityChanged()` and `channelInactive()`, and after `pipeline.remove(handler)` none of these reach it. If the handler is removed while writes are queued (for example, a `ChunkedInput` waiting for `resumeTransfer()`, or any write while the channel is not writable), then: - the write promises never complete, not even after the channel is closed; - the `ChunkedInput` is never closed, so a `ChunkedFile` keeps its file open; - queued `ByteBuf`s leak. A related case: when the user cancels the promise of a queued write, `doFlush()` drops the entry in the `promise.isDone()` branch without closing the `ChunkedInput` or releasing the message. The comment there assumes that whoever completed the promise already closed the input. That is true for the handler's own failure path (netty#8700), but not for a user `cancel()`. A cancelled write on the channel itself is released (`ChannelOutboundBuffer`). Modification: - Add `handlerRemoved()`, which fails the queued writes with `ChannelException("Pending write on removal of ChunkedWriteHandler")`. The messages are closed and released as in `channelInactive()` (`discard(...)`). `SslHandler` does the same for its pending writes. - In the `promise.isDone()` branch, close the `ChunkedInput` or release the message when the promise was cancelled. The handler never cancels promises itself, so this only affects user cancellation. - New tests in `ChunkedWriteHandlerTest`: - `testPendingWritesFailedWhenHandlerRemoved` - `testCancelledWritesAreClosedAndReleased` Result: Queued writes are always completed, and their inputs and buffers are released, when the handler is removed or a queued write is cancelled.
|
Automated review findings ( Correctness: introduced by this PR
Correctness: pre-existing, in code this PR touched
Test coverage
Design
Performance
|
Sorry, something went wrong.
There was an error while loading. Please reload this page.
…Buf) (netty#17682) Motivation: `ByteBufUtil.indexOf(ByteBuf needle, ByteBuf haystack)` searches for the readable bytes of `needle`. Since the Two-Way implementation (netty#11367, 4.1.66) it can miss a match when `needle.readerIndex()` is not 0: ```java ByteBuf needle = Unpooled.copiedBuffer("abc123", CharsetUtil.US_ASCII); needle.readerIndex(3); // "123" ByteBufUtil.indexOf(needle, Unpooled.copiedBuffer("ab1123", CharsetUtil.US_ASCII)); // -1, expected 3 ``` The search loops read the needle relative to its reader index (`needle.getByte(i + aStartIndex)`), but `maxSuf(...)`, which computes the critical factorization, mixes indexes: `j` starts at the reader index (absolute) while `ms` starts at -1 and the loop bound `m` is relative. So the factorization is computed from the wrong bytes, including bytes before the reader index, or not at all when the reader index is at least `m - 1`. The search then skips real occurrences. The haystack half of this regression was reported in netty#11963 and fixed in netty#11970. The existing test with a non-zero needle reader index uses a needle with all bytes distinct, where the wrong factorization happens to work. No caller in Netty passes such a needle (`DelimiterBasedFrameDecoder` slices its delimiters), so this only affects users of the public method. Modification: - In `maxSuf(...)`, keep `j`, `k`, `ms` and `p` relative to the needle's reader index and add it when reading bytes, like the search loops do. With reader index 0 the computation is unchanged, and the search loops are not touched. - New tests in `ByteBufUtilTest`: - `testIndexOfNeedleWithReaderIndex`: two needles with a non-zero reader index. - `testIndexOfMatchesNaiveSearch`, for needle reader index 0 to 3: 10,000 random needles and haystacks over a three-byte alphabet each, compared with a naive search. Result: `ByteBufUtil.indexOf(needle, haystack)` finds the readable bytes of `needle` whatever its reader index, as it did before netty#11367.
…ty#17679) Motivation: A child channel opened with `Http2StreamChannelBootstrap.open()` gets a `DefaultHttp2FrameStream` without an id. The stream becomes known to the `Http2Connection` only when the first HEADERS frame is written. When the parent channel becomes inactive before that, `Http2ConnectionHandler` closes the streams the connection knows. `Http2MultiplexHandler` closes child channels only from the stream's `CLOSED` state event, and it has no `channelInactive()`. So an outbound child channel without HEADERS is never closed: - it stays open and registered; - `channelInactive()` is not fired; - its `closeFuture()` never completes. The child only closes when the user later writes to it and the write fails. This affects clients that open a stream and send HEADERS later (for example after an asynchronous step), and code that waits on the child's `closeFuture()`. In a test with a real NIO h2c client that calls `open()` from a user thread and then closes the parent, 200 of 200 opened children were never closed. Modification: - `Http2MultiplexHandler` keeps the outbound child channels it creates in `newOutboundStream()` until their `closeFuture()` completes. `newOutboundStream()` and the listener run on the parent's event loop. - A new `channelInactive()` closes the child channels whose stream is still `IDLE`. - Child channels that have a stream are left to the existing stream-closed path. That path delivers queued inbound frames before it closes the channel. - `Http2MultiplexCodec` is deprecated and is not changed. - The root `pom.xml` gets a revapi ignore entry for `Http2MultiplexHandler.channelInactive()`: overriding it drops the inherited `@Skip` annotation (`java.annotation.removed`), as for the other handlers listed there. - New tests: - `Http2MultiplexHandlerTest.idleOutboundStreamClosedWhenParentCloses` - `Http2MultiplexTest.allQueuedFramesDeliveredToOutboundStreamAfterParentIsClosed`. It runs for both the codec and the handler. It checks that an outbound stream with HEADERS written and unread inbound frames still delivers them after the parent closes, like the existing test for inbound streams. Result: Every child channel is closed when its parent closes, and child channels with queued inbound frames still deliver them first.
…#17692) Motivation: Since netty#17370 (and netty#17392 for `JZlibDecoder`), the zlib decoders ask `ZlibDecoder.prepareDecompressBuffer(...)` for at least 512 bytes (`MIN_OUTPUT_BUFFER_SIZE`) whenever an `inflate` call did not finish the stream. `prepareDecompressBuffer` throws as soon as `ensureWritable(preferredSize, true)` returns 1, that is, when the buffer is already at `maxAllocation` and has fewer writable bytes than requested. It does not check whether the buffer still has room. So with a `maxAllocation` of 512 or less, the decoder throws `DecompressionException: Decompression buffer has reached maximum size` for every stream that arrives in more than one read, even when the buffer is empty. For example, a ZLIB stream of 36 bytes of output with `maxAllocation = 375`, split into two reads, is rejected. With a larger `maxAllocation` the same happens once the buffer holds more than `maxAllocation - 512` bytes and the stream continues, although the remaining space would be used by the next `inflate` call. Measured with 2,000 random streams per row and wrapper (ZLIB, GZIP, NONE), split into two reads, whose whole output fits into `maxAllocation`: | `maxAllocation` | `JdkZlibDecoder` 4.2.18 | before netty#17370 | with this change | |---|---|---|---| | 1-512 | 73-100% fail | 0 | 0 (1) | | 513-1100 | about 8% fail | 0 | 0 | | 4096-70000 | 2 of 6,000 fail | 0 | 0 | (1) except when one read produces exactly `maxAllocation` bytes and the stream continues; see below. `JZlibDecoder` also requests `max(2 * remaining input, 512)` bytes before its first `inflate`. When `2 * input > maxAllocation`, an input whose output fits is rejected before any byte is decompressed: a single read that holds a ZLIB stream of 600 random bytes fails with `maxAllocation = 1024`. That part predates netty#17392. netty#17364 was merged into 4.1 as well, so 4.1.138.Final has the same behaviour for `JdkZlibDecoder`. The javadoc of `prepareDecompressBuffer` already says that it calls `decompressionBufferExhausted(...)` "if the buffer is full and cannot be expanded further". Modification: - In `ZlibDecoder.prepareDecompressBuffer(...)`, only give up when the buffer could not be expanded and has no writable byte left. Until then the decoder keeps inflating into the space that is left, and a stream whose output exceeds `maxAllocation` still fails as before. - New tests in `ZlibTest`, so they run for both `JdkZlibDecoder` and `JZlibDecoder`: - `@ParameterizedTest` over ZLIB, GZIP and NONE with `maxAllocation` 2, 64 and 512: an output smaller than `maxAllocation`, decoded in one read, in two reads and byte by byte; - `@ParameterizedTest` over 600, 1000 and 1024 incompressible bytes with `maxAllocation = 1024` in one read. - a guard, `@ParameterizedTest` over ZLIB, GZIP and NONE with `maxAllocation` 64, and ZLIB with 512: 64 KiB of zeros (about 100 bytes compressed) in one read is still rejected with "Decompression buffer has reached maximum size", so the limit keeps protecting against small inputs with a large output. Result: `maxAllocation` limits the output of a read again, without rejecting streams whose output fits.
Motivation: `ProxyHandler` queues the writes that arrive before the connection to the destination is established, and writes them once the proxy handshake succeeds. `connectFuture()` is documented to be notified "when the connection to the destination has been established or the connection attempt has failed". The queued writes and `connectFuture()` are only completed by the handshake itself, by `channelInactive()` and by `exceptionCaught()`. If the connection to the proxy server itself can not be established (connection refused, connect timeout, proxy down), the channel is closed without ever becoming active, so `channelInactive()` is never called and nothing else reaches the handler. Then: - the promises of the queued writes never complete; - the queued messages are never released; - `connectFuture()` never completes, so code that waits for the tunnel (for example on `connectFuture()` instead of the bootstrap's connect future) waits forever. With a real NIO client whose proxy port is closed, writing right after `connect()` returned: the connect future fails with `ConnectException`, but the queued write is never completed, its buffer stays at `refCnt=1`, and `connectFuture()` never completes. This is the same for `HttpProxyHandler`, `Socks4ProxyHandler` and `Socks5ProxyHandler`. Without a proxy handler, the same write fails at once with `NotYetConnectedException` and is released. The same happens when the handler is removed before the handshake finished. Modification: - Add `handlerRemoved(...)`. If the handshake did not finish yet, it cancels the connect timeout and fails the queued writes and `connectFuture()` with a `ProxyConnectException`. When the channel is closed, the pipeline removes its handlers, so this also covers a channel that never became active. `SslHandler` does the same for its pending writes and its handshake promise. - If the handshake already finished, `handlerRemoved(...)` does nothing. The handler can be removed from a `ProxyConnectionEvent` listener while `setConnectSuccess()` runs, and the queued writes must still be written then. - The method is not `final`, unlike the other event methods of `ProxyHandler`, because subclasses may already override `handlerRemoved(...)`. - New tests: - `ProxyHandlerTest.testPendingWritesFailedWhenConnectionToProxyFails`, for HTTP, SOCKS4 and SOCKS5: a `LocalChannel` that writes and then connects to an address where nothing is bound. - `ProxyHandlerTest.testPendingWritesFailedWhenHandlerRemoved`, for HTTP, SOCKS4 and SOCKS5. - `HttpProxyHandlerTest.testRemoveOnProxyConnectionEventWritesPendingWrites`: the handler is removed when the `ProxyConnectionEvent` is fired, and the queued write is still written and `connectFuture()` succeeds. Result: The writes queued by a `ProxyHandler` and its `connectFuture()` always complete, and the queued messages are released, also when the connection to the proxy server fails. --------- Co-authored-by: Norman Maurer <[email protected]>
… in codec-http2 (netty#17697) Motivation: Http2MultiplexTransportTest failed on CI in the LeakPresenceExtension afterAll check ("Possible memory leak detected for resource scope") although every test in the class passed. The check waits up to 5 seconds for resources to be released, so something stayed open for good rather than just shutting down slowly. Several tests run LocalChannel / LocalServerChannel on a DefaultEventLoop and then call shutdownGracefully() without waiting. Unlike LocalIoHandler (and NioIoHandler for the other tests in the class), DefaultEventLoop does not close the channels registered with it when it shuts down. A server-side child channel is therefore only closed if the peer-close task still runs before the loop terminates. If it does not, the channel and whatever it still holds (for example the large wrapped payloads written by the auto-read tests added in netty#17617) is never released, which the leak presence detector reports. Modification: - Use `new MultiThreadIoEventLoopGroup(1, LocalIoHandler.newFactory())` instead of `new DefaultEventLoop()` in the LocalChannel based tests of Http2MultiplexTransportTest, Http2MultiplexCodecBuilderTest and Http2StreamChannelBootstrapTest. LocalIoHandler closes all registered channels when the group shuts down. A single thread is kept so server and client still share one event loop as before. Result: Channels of the LocalChannel tests are always closed when their event loop group shuts down, which removes one possible source of the flaky leak report.
…17574) Motivation: WebSocketServerProtocolHandler.decode() writes the CLOSE echo directly via WebSocketServerHandshaker.close(), bypassing this handler's own write()/close() overrides where forceCloseTimeoutMillis was armed. If the peer stops draining its socket, the echo write never completes and the channel, its file descriptor and buffers are pinned forever. Modifications: Arm the timeout explicitly after the echo write is issued, and also from a new flush() override so a bare write(CloseWebSocketFrame) not followed by close() gets the same protection. The timeout is applied after the write/flush attempt, not before, so a write that completes synchronously never races the deadline. Result: Awalys close the channel even when the remote peer stops reading
…tty#17664) Motivation: `StompSubframeDecoder` is a `ReplayingDecoder`. When the header block of a frame is not complete, the next read parses the command and all headers again from the checkpoint. The counter that enforces `maxNumHeaders` (`HeaderParser.numHeaders`, added in netty#17063) is only reset by the empty line that ends the headers. So every replay adds the headers that were already counted. As a result, whether a valid frame is rejected with "maximum number of headers exceeded" depends on how it is split into reads. After the rejection, the decoder stays in `BAD_FRAME`. With the default limit of 128: | Frame | Reads | Result | |---|---|---| | 15 headers | sent byte by byte, or one line at a time from a terminal | rejected | | 40 headers | 32-byte reads | rejected | | 128 headers | 2 reads | rejected | | 90 headers | one read | accepted | Modification: - Reset the counter at the start of `readHeaders()`. Each attempt parses all headers of the frame again, so it counts from zero. - New tests in `StompSubframeDecoderTest`, each with `maxNumHeaders = 10` and read sizes of 1, 7, about half the frame and the whole frame: - `testMaxNumHeadersNotExceededWhenHeadersSplitAcrossReads`: a frame with 10 headers is accepted. - `testMaxNumHeadersEnforcedWhenHeadersSplitAcrossReads`: a frame with 11 headers is rejected. Result: `maxNumHeaders` limits the headers of a frame, however the frame is split into reads. The limit itself is unchanged: each attempt still counts every header of the frame. - `StompSubframeDecoderTest`: 28 tests pass. Without the change to `StompSubframeDecoder`, `testMaxNumHeadersNotExceededWhenHeadersSplitAcrossReads` fails: `read size 1: failure(io.netty.handler.codec.TooLongFrameException: maximum number of headers exceeded: 10)`. - `codec-stomp` tests: 67, 0 failures. Checkstyle passes. The problem was found by modelling the replay behaviour of the decoder in Lean 4 and reproducing it with the real class. The change was prepared with Claude Code (Claude Opus 5.5), and the commit has a `Co-Authored-By` trailer. _Prepared with Claude Code on behalf of allthingssecurity._ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Norman Maurer <[email protected]>
…17711) Motivation: We often need to check if an user has already signed an icla. Let's add a script to do so. Modifications: Add script that can be used to check if an user has signed the icla Result: Less manual lookups during validations
…ream (netty#17683) Motivation: When `close()` is called on a channel with an `Http2ConnectionHandler` while streams are active, the handler sends a GOAWAY and stores a listener that closes the channel (and completes the `close()` promise) once no stream is active, or when `gracefulShutdownTimeoutMillis` elapses. The listener is only checked from `doCloseStream(...)`, that is when a stream is closed through `closeStream(...)`, `closeStreamLocal(...)` or `closeStreamRemote(...)`. The connection also closes streams itself, and those closes are not checked: - A GOAWAY is received: `DefaultHttp2Connection.goAwayReceived(...)` closes the local streams above the last-stream-id. This happens when our request raced the peer's shutdown. - The channel becomes inactive: `channelInactive` calls `connection().close(...)`, which closes every stream. This happens when the peer or a proxy drops the connection while we wait. In both cases the graceful close has nothing left to wait for, but: - the `close()` future completes only when the timeout fires (30 seconds by default), so `channel.close().sync()` blocks for 30 seconds; - after a GOAWAY, the idle connection also stays open for 30 seconds; - with `gracefulShutdownTimeoutMillis(-1)` the `close()` future never completes, and after a GOAWAY the connection is never closed. With a real NIO client whose server closes the TCP connection after reading our GOAWAY, `close()` completed 10 seconds (the configured timeout) after the channel was already closed, in 10 of 10 runs. Modification: - In `handlerAdded(...)`, add an `Http2Connection` listener whose `onStreamClosed(...)` calls the existing `checkCloseConnection(...)`. It runs for every stream close, whatever the reason, after the listeners that were added when the handler was built (flow controllers, `Http2FrameCodec`), like the check in `doCloseStream(...)`. `checkCloseConnection(...)` clears the stored listener before calling it, so the channel is still closed only once, and `doCloseStream(...)`'s own check becomes a no-op in that case. - New tests in `Http2ConnectionHandlerTest`, each run with a timeout of 30000 ms and with -1, with a client and a server `Http2ConnectionHandler` on two `EmbeddedChannel`s and the client's time frozen: - `gracefulShutdownCompletesWhenGoAwayClosesLastStream`: the client calls `close()` with stream 3 open, and the server answers with a GOAWAY with last-stream-id 0. - `gracefulShutdownCompletesWhenChannelBecomesInactive`: the client calls `close()` with stream 3 open, then the connection is lost. Result: A graceful close completes as soon as the last active stream is closed, also when the connection closed it.
…17689) Motivation: When a peer handshake included ed25519 in its supported algorithm list, it wasn't being included in the SSL session. Modification: - update `SignatureAlgorithmConverter#toJavaName` - add tests Result: The Java name, “Ed25519”, is included in the peer algorithm list when `X509ExtendedKeyManager#chooseEngineServerAlias` is called. Fixes netty#17688 --------- Co-authored-by: Norman Maurer <[email protected]>
…es payload bytes as properties (netty#17714) Motivation: MqttDecoder.decodeProperties() only checked the loop condition (numberOfBytesConsumed < totalPropertiesLength) before starting to decode a property. Once a property (e.g. a Content Type string) began, nothing verified that its typed value stayed within the declared Property Length, so a truncated Property Length could let the string-length prefix and body read bytes from the following packet section (e.g. the PUBLISH payload). Modifications: - Throw exception in cause of invalid property sections. - Add unit test Result: Correctly validate property sections
) Fixes netty#17655 ## Motivation `SystemTicker` captures `System.nanoTime()` in a static field. If GraalVM initializes the class while building a native image, running that image after a reboot can produce a negative ticker value and cause scheduled timeouts to fire immediately. ## Changes Add `SystemTicker` to Netty common's native-image runtime initialization list and add a regression test that checks the configuration entry. ## Verification The focused Maven test and the `common` reactor validation passed. A GraalVM native-image build was not run because `native-image` is not installed in this environment. Signed-off-by: Stochastic <[email protected]>
…channel writable (netty#17702) Motivation: `ChannelOutboundBuffer.addFlush()` marks all unflushed writes as flushed. For each write whose promise was cancelled, it releases the message and decrements the pending bytes right away, with `invokeLater = false`. If that brings the channel below the low water mark, `channelWritabilityChanged(...)` is fired inline, while `addFlush()` is still in its loop. At that point the `flushed` counter only covers the entries seen so far, and `unflushedEntry` still points at the first entry. Handlers often write and flush, or close, when the channel becomes writable again; `ChunkedWriteHandler` does this too. Such a handler re-enters the buffer while it is inconsistent: - **Write and flush:** the nested `addFlush()` starts again from `unflushedEntry` and counts the same entries a second time. After the writes, `flushed` stays above zero with no entry left, so `isEmpty()` returns `false` and `current()` returns `null`. `NioSocketChannel.doWrite()` then loops forever without writing anything: the event loop spins at 100% CPU and runs no other task. With `EmbeddedChannel`, a later `close()` throws `IllegalStateException("close() must be invoked after all flushed writes are handled.")` and `channelInactive()` is never fired. `tailEntry` is also left pointing at a recycled entry. - **Close:** `failFlushed(...)` fails only the entries counted so far. `ChannelOutboundBuffer.close(...)` then walks from the stale `unflushedEntry` into a recycled entry and throws a `NullPointerException` (`safeFail` of a `null` promise). The remaining writes are never failed, and their messages leak. All it takes is a write future that is cancelled before the flush while the channel is not writable, and a handler that reacts to writability. Notifying later (`invokeLater = true`) is not an option: netty#5028 did that and was reverted in abce89d, because a deferred notification can be missed. Modification: - `addFlush()` sums the bytes of the cancelled writes in its loop and decrements them once, after `unflushedEntry` is reset. The event is still fired synchronously, but now the buffer is consistent when it fires. The decrement is a no-op when nothing was cancelled. - Two tests in `ChannelOutboundBufferTest`. In both, a 512-byte write makes an `EmbeddedChannel` with water marks 256/512 unwritable, the write is cancelled, and the channel is flushed: - `testWriteAndFlushFromWritabilityChangedCausedByCancelledWrite`: the handler writes and flushes another message when the channel becomes writable. Both remaining writes succeed in order, and the buffer is empty afterwards. - `testCloseFromWritabilityChangedCausedByCancelledWrite`: the handler closes the channel. The two other writes fail with `ClosedChannelException`, their buffers are released, and `channelInactive()` is fired once. Result: A handler can write, flush or close from `channelWritabilityChanged(...)` when a cancelled write makes the channel writable again. --------- Co-authored-by: Norman Maurer <[email protected]>
… requested (netty#17727) Motivation: `ChunkedNioFile` takes its end offset from the constructor arguments, or from `FileChannel.size()` when it is created. If the file is shorter when it is read, for example because another process truncated it in the meantime (or the given length was too large), the positional `FileChannel.read(...)` returns `-1`. `readChunk(...)` then breaks out of its loop and returns an empty buffer without advancing `offset`, and `isEndOfInput()` keeps returning `false` because `offset` never reaches `endOffset`. `ChunkedWriteHandler.doFlush0(...)` loops `while (channel.isWritable())`: it reads the next chunk, writes it, and continues. Empty buffers never make the channel unwritable, so the loop never ends and the event loop spins at 100% CPU (with `EmbeddedChannel`, the outbound queue grows until `OutOfMemoryError`). `ChunkedFile` fails with an `EOFException` from `RandomAccessFile.readFully(...)` in the same situation, and `DefaultFileRegion` was fixed for exactly this problem in netty#8885 (netty#8868, "DefaultFileRegion.transferTo with invalid count may cause busy-spin"). `ChunkedNioFile` is the remaining one; it is what users pick for the SSL path of a static file server (the example uses `ChunkedFile` there). Modification: - In `ChunkedNioFile.readChunk(...)`, throw an `EOFException` when the file ends before the requested region does, instead of returning what was read so far. `ChunkedWriteHandler` already fails the write promise and closes the input when `readChunk(...)` throws. - Add `ChunkedWriteHandlerTest.testChunkedFileFailsWhenFileWasTruncated`, a `@ParameterizedTest` for `ChunkedFile` and `ChunkedNioFile` that truncates the file after the input was created. An outbound handler stops the test after 100 writes, so it fails instead of hanging without the fix. Result: A `ChunkedNioFile` whose file is shorter than requested fails the write with an `EOFException`, like `ChunkedFile`, instead of keeping the event loop busy forever. Files that are at least as long as the requested region are read exactly as before.
Motivation: Netty's bzip2 decoder decodes each Huffman-table selector as a zero-terminated unary code (`while (reader.readBoolean()) index++;`) but never validated the resulting index against the declared number of Huffman tables (2-6) before using it to index into `Bzip2MoveToFrontTable` and, later, the per-table code-limit array sized by that same table count. A crafted stream could drive the index out of range and trigger an `ArrayIndexOutOfBoundsException` instead of a clean `DecompressionException`, closing the connection. This affected both `Bzip2Decoder.decode()` and `Bzip2Decompressor.processInput()`, which duplicate this parsing logic. Modifications: * `Bzip2Decoder.decode()` / `Bzip2Decompressor.processInput()`: in the `RECEIVE_SELECTORS` state, reject the decoded index as soon as it reaches `totalTables`, throwing `DecompressionException` instead of letting the unary loop keep counting past the valid range. Result: A malformed bzip2 stream with an out-of-range selector index is now rejected with a `DecompressionException` instead of crashing with an `ArrayIndexOutOfBoundsException`.
…netty#17681) Motivation: With `server_no_context_takeover` or `client_no_context_takeover` negotiated (`noContext`), every message must be compressed on its own, because the peer may decompress each message with an empty sliding window (RFC 7692, 7.2.2). Netty's own `DeflateDecoder` resets its inflater on every final fragment. `DeflateEncoder` resets its compressor at the end of a message only when the final fragment has content (in `compressContent(...)`). A message can also end with an empty final fragment, the case of data of unknown size (RFC 7692, 7.2.3.6). The encoder has a branch for that (added in netty#9512) which sends `EMPTY_DEFLATE_BLOCK`, but it does not reset the compressor. The next message is then compressed against the window of the previous one. For example, with `PerMessageDeflateEncoder(6, 15, true)`: - message 1: `Text(fin=false, "Hello world, hello world, hello world!")`, then `Continuation(fin=true, empty)`; - message 2: `Text(fin=true, "Hello world, hello world, hello world!")` is sent as `f2 20 4a 15 00`, a back-reference into message 1. A fresh `java.util.zip.Inflater` fails on message 2 with `invalid distance too far back`, and `PerMessageDeflateDecoder(noContext = true)` fails with `DecompressionException`, so the connection fails, also between two Netty peers. With context takeover the same frames decode fine. Modification: - In the empty final fragment branch of `DeflateEncoder.encode(...)`, reset the compressor when `noContext` is set, as `compressContent(...)` already does for a final fragment with content. `PerFrameDeflateEncoder` never sees empty frames, so only permessage-deflate is affected. - New tests in `PerMessageDeflateEncoderTest`: - `testNoContextNextMessageAfterEmptyFinalFragmentIsSelfContained`: with `noContext`, the message after an empty final fragment decompresses on its own. - `testRoundTripWithEmptyFinalFragment`, for `noContext` true and false: encoder to `PerMessageDeflateDecoder` round trip of both messages. Result: With no context takeover, every message is compressed independently, whether its final fragment has content or not.
…7736) Motivation: Every job of the PR validation builds and tests all modules, no matter what a PR changes. A change in a single codec module therefore keeps around a dozen jobs busy for a long time, which slows down the feedback loop and ties up a lot of CI resources. An earlier attempt (netty#11464) was reverted and left an unused `build_affected_only.sh` behind. It diffed the working tree instead of the merge-base and treated every top-level directory as a module, so a change to `.github/` or `docker/` would have produced an invalid `-pl`. Modification: - Add `.github/scripts/detect_affected_modules.sh`. It diffs against the merge-base and prints `ALL`, `NONE` or a comma separated list of modules. Changes that can't be mapped to a single module (root pom, `.github/`, `docker/`, `dev-tools`, unknown directories) result in `ALL`, docs-only changes in `NONE`. - Add `.github/scripts/mvn_affected.sh`, a wrapper around `./mvnw` that reads `NETTY_AFFECTED_MODULES`. Unset or `ALL` behaves exactly like `./mvnw`. For a list of modules it first builds and installs them and what they depend on (`-am`) without tests, and then runs the tests of the affected modules only. Add `affected_includes.sh` so the `testsuite-shading` step only runs when that module is affected. - Add `*-affected-only` variants of the `build`, `build-with-oio-testsuite`, `build-leak-pooled` and `build-boringssl-static-jdk8-tests` docker compose services, including the image entries in the per-JDK compose files. The existing services are not changed, so the post-merge and release workflows still build everything. - Add a `detect-affected` job to `ci-pr.yml` and use the affected-only services for all Linux legs and the Windows leg (which now uses `install` instead of `package`, as modules outside of the affected set are resolved from the local repository). Only `linux-x86_64-java11-boringssl` keeps building everything, with leak detection, so leaks in modules depending on a changed one are still found. - Remove the unused `build_affected_only.sh`. Result: PR validation only builds and tests the modules a PR touches on all but one job, and still does one full build with leak detection per PR. Modules that depend on a changed module are only tested by that full build.
netty#17737) Motivation: testNegativeTtl failed sporadically on CI with "expected: <10000> but was: <160>". The helper thread that resolves the non-existent domain in a loop died with an exception after a few iterations, so the test saw fewer results than expected. resolveNonExistentDomain(...) inspects the DnsQueryLifecycleObserver of the queries that were not answered from the cache. Until the negative answer of the AAAA query is cached, every iteration still sends such a query, and its events are recorded on the EventLoop into an ArrayDeque while the test thread polls it. The check also assumed a fixed event sequence: it cast the event following QueryWrittenEvent to QueryFailedEvent (ClassCastException when the query was cancelled instead), failed on a null event when none had been recorded yet, and asserted that the queue was empty although more events could still arrive. Modification: - Use a ConcurrentLinkedQueue for TestDnsQueryLifecycleObserver.events as it is written and read by different threads. - Drain all pending observers in resolveNonExistentDomain(...) and only verify that no unexpected event was recorded, without assuming a particular order or that the observer has seen all of its events. Result: testNegativeTtl no longer depends on the timing of the asynchronous completion of the observed queries.
Motivation:
`ByteBuf.retainedSlice()` is specified as identical to
`slice(readerIndex(), readableBytes())`, except that it retains the
result. `duplicate()` and `slice()` of a pooled derived buffer, such as
a pooled buffer's `retainedDuplicate()` or `retainedSlice()`, return
non-retained derived buffers. Their `retainedSlice()` uses the capacity
as the length:
| Class | `retainedSlice()` returned | Effect |
|---|---|---|
| `PooledNonRetainedDuplicateByteBuf` | `retainedSlice(readerIndex(),
capacity())` | With a reader index of 0, it includes the bytes after the
writer index; otherwise `IndexOutOfBoundsException` |
| `PooledNonRetainedSlicedByteBuf` | `retainedSlice(0, capacity())` | It
ignores the reader and writer indexes |
```java
ByteBuf root = PooledByteBufAllocator.DEFAULT.directBuffer(16).writeBytes("pooled-data".getBytes(CharsetUtil.US_ASCII));
ByteBuf retainedDuplicate = root.retainedDuplicate();
ByteBuf duplicate = retainedDuplicate.duplicate(); // a PooledNonRetainedDuplicateByteBuf
ByteBuf slice = duplicate.retainedSlice(); // 16 readable bytes instead of 11
slice.release();
duplicate.readByte();
duplicate.retainedSlice(); // IndexOutOfBoundsException
retainedDuplicate.release();
root.release();
```
The overrides came with netty#6024 (4bba752, a fix for
netty#5999). Before it, `slice()` and `duplicate()` of a pooled
derived buffer delegated to the root buffer's `slice()`, whose
`retainedSlice()` respected the indexes. The `length == capacity()`
comment was copied from `PooledSlicedByteBuf.duplicate()`, where it's
correct, but it doesn't hold for `retainedSlice()`.
This was found in Apache Pulsar, where a `retainedSlice()` of such a
duplicate returned bytes beyond the writer index.
Modification:
- Both overrides now return `retainedSlice(readerIndex(),
readableBytes())`.
-
`AbstractByteBufTest.testRetainedSliceOfNonRetainedDerivedBufferCoversTheReadableBytes`
checks `retainedSlice()` of duplicates and slices (also nested) of a
retained duplicate and a retained slice. It runs with reader index 0 and
1, a writer index below the capacity, and before and after a read.
Without the fix, it fails in the 5 pooled buffer test classes.
Result:
`retainedSlice()` of a non-retained pooled derived buffer covers exactly
its readable bytes.
Motivation: The 'bash' shell we were using on Windows was supplied by the Git installation. This included `link.exe` which is corresponding to the `ln` and `link` unix command line programs. They confused the cargo build process which was expecting `link.exe` to be the MSVC linker. Modification: Port the `mvn_affected.sh` script to powershell, and use that on Windows PR builds, instead of relying on `bash` to run the unix script. Result: The Windows PR builds now run in the correct environment.
…imiters Motivation: When configured with a non-line delimiter (e.g. Delimiters.nulDelimiter() or any custom delimiter), DelimiterBasedFrameDecoder.decode() called ByteBufUtil.indexOf for every delimiter on every decode() call, scanning the whole accumulated buffer from the reader index. Unlike LineBasedFrameDecoder, which persists a scan offset and resumes from there, the generic-delimiter branch kept no such offset. A remote peer that streams delimiter-free bytes one per TCP segment therefore forces a full buffer rescan on every byte, producing O(n^2) CPU work bounded only by maxFrameLength, which can pin an event-loop thread with just a few trickle connections. Modification: Add a scanOffset field to DelimiterBasedFrameDecoder, mirroring the offset already used by LineBasedFrameDecoder. Each decode() call now only scans from readerIndex + scanOffset onward. When no delimiter is found and the buffer is still under maxFrameLength, scanOffset advances to readableBytes - maxDelimiterLength + 1 (clamped to 0), the earliest position that could still contain the start of an unconfirmed match for any configured delimiter. scanOffset resets to 0 whenever the buffer is consumed, either because a delimiter was found or because too-long-frame content was discarded. maxDelimiterLength is precomputed once in the constructor from the configured delimiters' readableBytes(). Result: The non-line delimiter branch now does linear work overall instead of quadratic, at parity with LineBasedFrameDecoder. Added testMultiByteDelimiterFoundAcrossResumedScanBoundary to verify a multi-byte delimiter split across dripped bytes is still found even when it spans the resumed-scan boundary, and testDripFeedWithoutDelimiterDoesNotScaleQuadratically to guard against the quadratic behavior regressing.
A non-final SYN_STREAM buffers a request while its body/trailers arrive in later frames. Each subsequent non-final HEADERS frame was appended to the buffered message with no cumulative limit, only the DATA path was bounded by maxContentLength. A remote peer could keep a single stream open and send an unbounded number of HEADERS frames to exhaust the heap. Add a dedicated maxHeaderSize bound (mirroring HttpObjectDecoder's default of 8192) and reject a stream once the accumulated header size exceeds it, releasing the buffered message and throwing TooLongHttpHeaderException.
…v2 length, allowing downstream TLV injection/desync Motivation: HaProxyMessageDecoder exposes direct child TLVs of PP2_TYPE_SSL as both encapsulated children and flattened entries in HAProxyMessage.tlvs(). HAProxyMessageEncoder then recursively encodes SSL TLV children while also iterating the flattened list as top-level wire TLVs. For a decoded PROXY v2 header containing nested SSL TLVs, decode-to-encode forwarding emits a PROXY v2 frame whose length field is larger than the actual bytes written. A downstream PROXY v2 decoder consumes bytes from the following application stream to satisfy the advertised PROXY header length. The supplied PoV shows those bytes being exposed as a downstream PP2_TYPE_ALPN TLV while the remaining application payload continues to the backend. This affects the intended multi-layer proxy forwarding use case for HAProxyMessageEncoder: a Netty hop decodes a PROXY v2 frame, then relays connection metadata to another proxy/backend by re-encoding the decoded HAProxyMessage. Modifications: - HAProxyMessage.tlvNumBytes(): skip flattened SSL-child entries when summing, mirroring the existing skip logic already used in releaseTlvs(). - HAProxyMessageEncoder: split TLV encoding into encodeTlvs() (top-level, skips flattened SSL children) and encodeChildTlvs() (genuine recursive tree encoding for a SSL TLV's actual children); replaced the mutating readSlice() with a non-mutating writeBytes(value, value.readerIndex(), readableBytes) so encoding never corrupts shared buffers. - Added unit test Result: Correctly re-encode in all cases
Motivation: A stream abandoned while blocked on dynamic table updates kept its blocked stream slot. Modification: - Release the slot in `QpackDecoder.streamAbandoned` and when `Http3FrameCodec` is removed while blocked. - Add junit tests Result: Abandoned streams no longer count towards the blocked stream limit.
Motivation: `Content-Type` is a bit special. It's both an HTTP header, and a multipart part-header, though these are specified by different RFCs, 9110 HTTP Semantics and 2045 MIME, respectively. On the receiving side, this means syntactically invalid Content-Type values are replaced with a default value. On the sending side, we refuse to create parts that have malformed Content-Type values. Modifications: - Add `FileUploadUtil.validateContentTypeForMultiPart` and `FileUploadUtil.isContentTypeForMultiPartValid` methods for validating sending and receiving side, respectively. - The validate method throws, and is called from the content type setters in `DiskFileUpload` and `MemoryFileUpload` - The predicate method is called from `HttpPostMultipartRequestDecoder`, which replaces the content type value with a default if validation fails. - Add checks that the HTTP-level content type must be present and not empty, to the `HttpPostMultipartRequestDecoder` constructor. - Add tests for various grammar cases. Result: We no longer emit malformed Content-Type header values when encoding multpart, which prevents CRLF injection through `FileUpload.setContentType`. Breaking change: callers that passed a non-media-type string to `setContentType`, such as `"foo"`, now get an `IllegalArgumentException`.
…, Charset) (netty#17971) Motivation: When the `CharSequence` passed to `Unpooled.copiedBuffer(CharSequence, int offset, int length, Charset)` is a `CharBuffer` without an accessible array, for example one returned by `CharBuffer.wrap(CharSequence)` or `asReadOnlyBuffer()`, the method sets the limit of the slice to `length` instead of `offset + length`. The result is truncated for any `offset > 0`, or `IllegalArgumentException` is thrown if `offset > length`. The array-backed `CharBuffer` and `String` paths copy the requested region. Modification: - Set the limit of the slice to `offset + length`. - Add `UnpooledTest.testCopiedBufferCharBufferRegion`, which covers array-backed and non array-backed `CharBuffer`s, with position 0 and a non-zero position. Result: `copiedBuffer(CharSequence, int, int, Charset)` copies the requested region for every `CharBuffer`.
netty#17991) …elConfig (netty#17969) Motivation: `NioDatagramChannelConfig` maps `setLoopbackModeDisabled(boolean)` and `isLoopbackModeDisabled()` directly to `StandardSocketOptions.IP_MULTICAST_LOOP`, but that option is `true` when loopback is *enabled*. So `setOption(ChannelOption.IP_MULTICAST_LOOP_DISABLED, true)` enables loopback on the NIO transport, and `isLoopbackModeDisabled()` returns `true` for a new socket that has loopback enabled. The other transports handle the option as documented: epoll and io_uring call `setIpMulticastLoop(fd, ipv6, loopbackModeDisabled ? 0 : 1)`, and OIO uses `MulticastSocket.setLoopbackMode(boolean disable)`. Modification: - Negate the value in `setLoopbackModeDisabled(...)` and `isLoopbackModeDisabled()`. - Add `NioDatagramChannelTest.testLoopbackModeDisabled`, which checks the option on the underlying `java.nio.channels.DatagramChannel`. Result: `IP_MULTICAST_LOOP_DISABLED` has the same meaning on the NIO transport as on the other transports. (cherry picked from commit dd5a7e6) Co-authored-by: Martin Mirchev <[email protected]>
…etty#17868) Motivation: A DATA frame on a stream in the RESERVED_REMOTE state (on a client that received a PUSH_PROMISE) or RESERVED_LOCAL state (on a server that sent one) caused an UnsupportedOperationException from DefaultHttp2LocalFlowController. Reserved streams are not active yet, so they still use the reduced flow control state, but receiveFlowControlledFrame and consumeBytes only skipped stream-level flow control for closed streams. DefaultHttp2ConnectionDecoder applies flow control before throwing the error for the unexpected stream state, so the connection was closed with an INTERNAL_ERROR GOAWAY and the UnsupportedOperationException was passed to exceptionCaught. Even without that, the decoder would only have raised a stream error, while RFC 9113, section 5.1 requires a connection error of type PROTOCOL_ERROR for DATA frames on idle or reserved streams. Modification: - Only apply stream-level flow control in DefaultHttp2LocalFlowController for active (OPEN or HALF_CLOSED_*) streams. For other streams the bytes are consumed for the connection window right away, as for closed streams, and returning them later is ignored. - Raise a connection error of type PROTOCOL_ERROR in DefaultHttp2ConnectionDecoder for DATA frames on IDLE or RESERVED_* streams. - Add tests. Result: DATA frames on reserved streams cause a PROTOCOL_ERROR GOAWAY, and the connection flow control window stays correct. Discovered by fuzzing. --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Norman Maurer <[email protected]>
0334122 to
249fccb
Compare
…_SIZE (netty#17779) Motivation: RFC 9113 Section 4.2 applies SETTINGS_MAX_FRAME_SIZE to the payload of every frame. The typed writers in DefaultHttp2FrameWriter honour the limit advertised by the remote peer: writeData splits large payloads into multiple DATA frames and writeHeaders uses CONTINUATION. The generic writeFrame(...) path does not check the limit and writes the full payload length into a single frame header, so it can emit a frame that a compliant peer must reject with FRAME_SIZE_ERROR. Modification: - Verify the payload length against maxFrameSize in writeFrame before allocating the frame header. A generic frame has unknown semantics and cannot be split, so the write fails instead: the payload is released and the promise is failed with an IllegalArgumentException, consistent with the other verify* checks in this class. - Add tests for a payload of maxFrameSize + 1 (rejected, nothing written, payload released) and of exactly maxFrameSize (written). The first fails without the change and passes with it. Result: Generic frames can no longer exceed the frame size negotiated with the remote peer. codec-http2 tests: 1633, 0 failures. Fixes netty#17426 --------- Co-authored-by: Netty Project Bot <[email protected]> Co-authored-by: Norman Maurer <[email protected]> Co-authored-by: Bryce Anderson <[email protected]>
…tty#17973) Motivation: `AbstractDiskHttpData.readFrom(File)`, which `get()`, `getByteBuf()` and `getString()` use, allocates an array of `File.length()` bytes and then runs `read += fileChannel.read(byteBuffer)` until `read` reaches that length. If the file has fewer bytes than `File.length()` reported, for example because it was truncated in between or because it is a procfs/sysfs file, `read(...)` returns `-1` at end of file. The loop adds `-1` and never ends, so the calling thread, often an event loop, spins forever. `getChunk(int)` already checks for `-1`. Modification: - Throw an `EOFException` when `read(...)` returns `-1` before the array is full. - Add `AbstractDiskHttpDataTest.testGetWhenFileIsShorterThanItsLength`, which uses a `File` whose `length()` is larger than its content. Result: `get()`, `getByteBuf()` and `getString()` fail with an `EOFException` instead of spinning forever when the file is shorter than its length.
Motivation: `JdkZlibDecoder` reads both gzip magic bytes (ID1 = 0x1f, ID2 = 0x8b, RFC 1952 section 2.3.1) but only checks ID1, so a stream with a wrong ID2 is decoded as gzip. `java.util.zip.GZIPInputStream` and netty's own `JdkZlibDecompressor` (`magic0 != 31 || magic1 != 139`) reject such a stream. Modification: - Read both bytes unsigned and check ID2, as `JdkZlibDecompressor` does. - Add `JdkZlibTest.testGzipInvalidSecondMagicByteThrows`. Result: `JdkZlibDecoder` rejects input whose gzip header has a wrong ID2. Co-authored-by: Norman Maurer <[email protected]>
…etty#17970) Motivation: `SmtpResponseDecoder.parseCode(...)` adds up the results of `Character.digit(...)` without checking for `-1`. A reply code with a non-digit character is therefore decoded as a different code: `5x0` becomes 490, `2:0` becomes 190 and `4?1` becomes 391. Only results outside 100..599 are rejected, by `DefaultSmtpResponse`. A permanent 5xx failure can thus reach the client as a transient 4xx reply. Modification: - Return `-1` from `parseCode(...)` if one of the three bytes is not a digit, and reject the line with the same `DecoderException` that is used for other invalid lines. - Add `SmtpResponseDecoderTest.testDecodeCodeWithNonDigit`. Result: Reply codes with non-digit characters are rejected instead of being decoded as another code. --------- Co-authored-by: Norman Maurer <[email protected]>
…etty#17967) Motivation: `HttpHeaders.getInt(name)` and `getShort(name)`, and the typed getters of `Headers`, are documented to return `null`, and the overloads with a default value the default value, when the header value can't be converted. `DefaultHeaders` catches conversion failures since netty#7710, but `ReadOnlyHttpHeaders.getInt(...)` and `getShort(...)`, and `ReadOnlyHttp2Headers.getByte(...)`, `getChar(...)`, `getShort(...)`, `getInt(...)`, `getLong(...)`, `getFloat(...)` and `getDouble(...)` let the `NumberFormatException`, or the `IndexOutOfBoundsException` of `getChar(...)` for an empty value, escape to the caller. For example, `HttpToHttp2ConnectionHandler` reads `x-http2-stream-weight` with `getShort(name, defaultValue)`. A request with `x-http2-stream-weight: high` is written with the default weight when it uses `DefaultHttpHeaders`, but with `ReadOnlyHttpHeaders` the write fails with a `NumberFormatException` and the handler sends GOAWAY. Modification: Catch `RuntimeException` around the conversion in these getters, like `DefaultHeaders` does. `getTimeMillis(...)` is covered by netty#17965. Add tests for values that can't be converted. Result: The getters of `ReadOnlyHttpHeaders` and `ReadOnlyHttp2Headers` return `null` or the default value for a value that can't be converted, like `DefaultHttpHeaders` and `DefaultHttp2Headers`. Headers `x-count: abc` and `x-empty:` (empty value); `DefaultHttpHeaders` and `DefaultHttp2Headers` return `null` or `-1` for all of these. Then a request with `x-http2-stream-weight: high` written through `HttpToHttp2ConnectionHandler`: Before: ``` ReadOnlyHttpHeaders.getInt(x-count, -1) threw java.lang.NumberFormatException: For input string: "abc" ReadOnlyHttpHeaders.getShort(x-count) threw java.lang.NumberFormatException: For input string: "abc" ReadOnlyHttp2Headers.getChar(x-empty) threw java.lang.IndexOutOfBoundsException: index: 0 must be in the range [0,0) ReadOnlyHttp2Headers.getLong(x-count) threw java.lang.NumberFormatException: abc ReadOnlyHttp2Headers.getDouble(x-count, -1) threw java.lang.NumberFormatException: For input string: "abc" HttpToHttp2ConnectionHandler write with DefaultHttpHeaders: success=true, first outbound frame type=1 (HEADERS) HttpToHttp2ConnectionHandler write with ReadOnlyHttpHeaders: success=false cause=java.lang.NumberFormatException: For input string: "high", first outbound frame type=7 (GOAWAY) ``` After: ``` ReadOnlyHttpHeaders.getInt(x-count, -1) = -1 ReadOnlyHttpHeaders.getShort(x-count) = null ReadOnlyHttp2Headers.getChar(x-empty) = null ReadOnlyHttp2Headers.getLong(x-count) = null ReadOnlyHttp2Headers.getDouble(x-count, -1) = -1.0 HttpToHttp2ConnectionHandler write with DefaultHttpHeaders: success=true, first outbound frame type=1 (HEADERS) HttpToHttp2ConnectionHandler write with ReadOnlyHttpHeaders: success=true, first outbound frame type=1 (HEADERS) ``` The new tests fail before the change. `codec-http` and `codec-http2` tests pass. --------- Co-authored-by: Norman Maurer <[email protected]>
…ty#17984) Motivation: The MQTT remaining length, the properties length and the Subscription Identifier property are Variable Byte Integers which use at most four bytes and so can not be larger than 268,435,455. MqttEncoder never checked this. getVariableLengthInt() reported four bytes for every value above 2,097,151 while writeVariableLengthInt() wrote as many bytes as the value needed. For a larger value the output buffer was sized too small and a fifth length byte was written, so the packet was not framed correctly. A computed size that overflowed int was handled as a negative value and encoded the same way. Modifications: - Throw an EncoderException from getVariableLengthInt() and writeVariableLengthInt() if the value is negative or larger than 268,435,455. - Compute the CONNACK fixed header size via getVariableLengthInt() so the check also runs before the output buffer is allocated. - Add unit tests. Result: MqttEncoder no longer produces packets with an invalid Variable Byte Integer.
…already done" (netty#17983) Motivation: Since netty#17574, `WebSocketProtocolHandler.closeSent(promise)` cascades the outcome of an already recorded close promise onto the new one. When the server initiates the close handshake by writing a `CloseWebSocketFrame` and the peer responds with its own close frame, `WebSocketServerProtocolHandler.decode()` creates a new promise, passes it to `closeSent()` and then to `WebSocketServerHandshaker.close()`. As our own close frame was already written, the new promise is completed immediately, so the write in `close()` fails with `IllegalArgumentException: promise already done` and the close handshake fails. Modification: If a close frame was already sent (or is still being sent) when a close frame is received, don't echo another close frame (as required by RFC 6455) but close the connection once our own close frame was written. The force-close timeout still applies. Add tests for a server-initiated close handshake, including the reproducer from the issue, and adjust the simultaneous close test as no second close frame is written anymore. Result: Fixes netty#17776. A server-initiated WebSocket close handshake completes correctly again.
…18019) Motivation: `Snappy.encode(in, out, length)` starts at `in.readerIndex()` and works with absolute buffer indices, but compares them with `length` as if the input started at index 0. If the reader index is not 0, the encoder stops early. The compressed block declares `length` bytes in its preamble but contains fewer bytes, or none at all. `SnappyFrameEncoder` is not affected because it always passes a slice from `readSlice(...)`. Code that calls the public `Snappy.encode(...)` method directly is affected. Modification: - Compute the end of the input as `readerIndex + length` and use it instead of `length` for all bounds checks in `Snappy.encode(...)`. - Add a test that encodes the same data with a non-zero reader index, checks the output is identical to the output for reader index 0, and checks that it decodes correctly. Result: `Snappy.encode(...)` produces the same output whatever the reader index of the input buffer.
…llback (netty#18009) Motivation: On Java versions before 10, `PlatformDependent.splittableRandomNextBytes(SplittableRandom, byte[])` fills the array itself instead of calling `SplittableRandom.nextBytes`. The loop for the bytes after the last full 8-byte block increments `i` both in its body (`data[i++] = ...`) and in its update, so every other remaining byte is skipped and stays `0`. For a 7-byte array, bytes 1, 3 and 5 are never written; for any length that is not a multiple of 8, up to 3 bytes stay zero. On Java 10+ `SplittableRandom.nextBytes` is used and every byte is filled, so the two paths disagree for the same seed. Modification: - Increment `i` only in the loop update. - Move the fallback into a package-private `splittableRandomNextBytesFallback` so it can be tested on any Java version, and add `PlatformDependentTest.testSplittableRandomNextBytesFallbackFillsEveryByte`, which compares it with the layout of `SplittableRandom.nextBytes` (one `nextLong()` per 8 bytes, low byte first, one more for the rest) for lengths 0 to 64. Result: The fallback fills every byte and produces the same bytes as `SplittableRandom.nextBytes` for the same seed. In the netty repository the method is used to generate random payloads in tests and the testsuite, which on Java 8 had zero bytes in their tails.
) Motivation: netty#17518 added a workflow that cancels the runs of a PR once it is merged, but it does not free up the runners in all cases. It only looks at runs that are `in_progress`, so runs that are still waiting for a runner are never cancelled. It is triggered by `pull_request`, where the `GITHUB_TOKEN` is read-only for PRs from forks, so cancelling fails for them with a 403, and it does not request `actions: write`. It also does not paginate, a single failed cancel (for example a 409 for a run that just completed) aborts the remaining ones, and it could cancel the runs of another PR that uses the same head commit. Cancelling "Build PR" also triggers "PR Reports" through `workflow_run`, which then runs on a merged PR only to find cancelled runs. Modification: - Cancel every run of the head commit that has not completed yet (`queued`, `in_progress`, `waiting`, `pending` and `requested`). - Use `pull_request_target` and request `actions: write`. The workflow does not check out or run any code of the PR, it only uses the event payload. As the workflow file is taken from the base branch it needs to exist on every branch we merge PRs into. - Paginate, ignore failures to cancel a single run, only consider runs triggered by `pull_request` and skip runs that are attached to a different PR. - Skip the "PR Reports" job if the "Build PR" run was cancelled. Result: Runners are freed up as soon as a PR is merged, also for queued runs and for PRs from forks, and no report job is started for the cancelled runs.
…netty#18008) Motivation: When the initial data of a `TCP_FASTOPEN_CONNECT` is sent as part of the connect, epoll, kqueue and io_uring remove the written bytes from the `ChannelOutboundBuffer` before the connect promise is fulfilled. The write promise of the initial data is therefore notified while the channel is not active yet. A listener that writes and flushes fails with a `NotYetConnectedException`, and a listener that closes the channel fails the connect although it succeeded. kqueue even notifies the write promise when `connectx(...)` only started the connect, before it is known if the connect succeeds. Modification: - epoll and kqueue: remember the bytes that were sent by `TCP_FASTOPEN_CONNECT` and only remove them once the connect promise was fulfilled, or before the outbound buffer is written, closed or shut down. If the connect fails they are not removed, so the write fails. - io_uring: call `connectComplete(...)` before `removeBytes(...)`, and set `WRITE_SCHEDULED` until the bytes were removed so a flush that is triggered by `channelActive()` does not send the initial data a second time. - Write what is left of the initial data once the connect is complete. - Add `SocketConnectTest.testWriteFromFastOpenInitialDataListener`, which runs for all transports that support TCP fast open. Result: Listeners of the initial write see an active channel when the initial data was sent as part of the connect.
…#17980) Motivation: `bindDomainSocket` unconditionally called `unlink(2)` on the bind path before `bind(2)`, and the epoll, kqueue and io_uring server domain socket channels called `File.delete()` on the path when closing. An application that derives the path from external input could therefore have any file it can delete removed by binding or closing a channel. Only a stale socket left by a previous run should be cleaned up. `FileDescriptor.from(...)` opens the file with `O_CREAT | O_TRUNC` and mode `0666`, but its javadoc did not say so. Modification: - In `bindDomainSocket`, `lstat(2)` the path and only `unlink(2)` it if it is a socket. Anything else is left alone and `bind(2)` fails with `EADDRINUSE`. - Add `UnixChannelUtil.deleteDomainSocketFile(String)`, which deletes a path only if it is not a regular file, directory or symbolic link and never follows symbolic links, and use it in the server domain socket channels of all three transports. - Document that `FileDescriptor.from(...)` truncates or creates the file. - Add tests to `SocketTest` for binding over a regular file, binding over a stale socket and `deleteDomainSocketFile`. Result: Binding to or closing a server domain socket channel no longer removes regular files, directories or symbolic links.
249fccb to
e05943b
Compare
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.