GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — IoUring:重构写操作的生命周期管理 by dreamlike-ocean · Pull Request #13 · dreamlike-ocean/netty

Conversation

@dreamlike-ocean

@dreamlike-ocean dreamlike-ocean commented Sep 29, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Owner

Motivation

#17238 修复了 shutdownOutput() 提前释放在途写内存的问题:写 promise 失败、outbound 被清空时,内核仍可能访问此前提交的 buffer。该修复引入 WriteOperationTracker,在各类写入路径记录资源引用,并在关闭写端时 retain,直到对应完成事件到达后再释放。

这套机制使普通写在每次提交和完成时都需要维护引用数组,批量写还涉及引用收集、复制和清空。即使 slot 和数组已经复用、没有逐次分配,这些操作仍有 CPU 和 GC 引用写屏障成本,也让生命周期管理分散在各个写入实现中。

本 PR 移除通用 WriteOperationTracker:普通写只记录少量原始类型元数据,在 outbound 即将释放时才恢复并保活在途资源;SEND_ZC / SENDMSG_ZC 等待 notification 所必需的引用则独立管理。同时补齐 TFO、UDS fd 传递和直接失败 flushed 消息时的生命周期处理。

Modification

1. 使用 WriteOpsSnapshot,在释放 outbound 前恢复在途资源

新增每 Channel 复用的 WriteOpsSnapshot。统一的 submitWrite() 在提交成功后,只复制资源恢复所需的 opcode、len、union3 和 userData。快照仅保存原始类型字段,不持有 IoUringIoOps,使 ops 仍可被逃逸分析消除。

在 Channel.Unsafe 新增默认空实现的 prepareToDiscardOutboundMessages(ChannelOutboundBuffer),由 ChannelOutboundBuffer.failFlushed() 在重入保护生效后、失败并释放消息前调用。io_uring 在 AbstractUringUnsafe 中覆写该方法,根据快照和已有 Channel 状态,只 retain 当前在途写需要的资源,待完成事件到达后释放。

回调直接接收待清理的队列,因此即使 shutdownOutput() 已将 unsafe.outboundBuffer() 置空,仍可访问原队列来恢复在途资源。其他 transport 继承默认空实现,原有消息释放顺序保持不变;AbstractChannel 无需新增扩展点,ChannelOutboundBuffer 仍持有 Channel 类型的引用。

WRITEV 按实际提交的 iov 数量恢复涉及的 ByteBuf;UDP 按 sendmsgHdrs 的 slot 识别仍在途的数据报,并按 CQE 索引逐个释放,支持乱序完成。

回调放在 failFlushed(),也覆盖未经过 shutdownOutput() 的失败路径,例如 UDP disconnect 后的 inactive flush,而不只处理显式关闭写端。进入延迟关闭后,写完成路径也不再新增 POLLOUT,避免在取消已有操作后又调度重试。

2. 将 TFO SENDMSG 纳入写生命周期

TFO 实际提交的是引用 outbound 数据的 SENDMSG(MSG_FASTOPEN)。将其纳入写计数并设置 WRITE_SCHEDULED,使 close 等待实际写完成,shutdownOutput 则通过统一回调保活初始数据,避免仅提交 cancel 后就释放 buffer。

完成入口同时检查 connect 状态、SENDMSG opcode 和 MSG_FASTOPEN,避免把与 UDP connect 同时在途的普通发送误判为 TFO。TFO 需要回退到普通 connect 时,也仅在连接请求仍有效的情况下重新提交。

3. 按在途 connect ID 决定取消

CONNECT/TFO 的 primary CQE 到达后,在通知 connect promise 的 listener 之前清零 connectId,避免 listener 内 close 时额外取消已经完成的操作。关闭时以 connectId != 0 识别在途请求,也覆盖 promise 已被取消并清空、实际请求尚未完成的情况。

4. 用独立 fd 副本管理 UDS sendfd 生命周期

对于 writeAndFlush(fd).addListener(f -> fd.close()),写 promise 失败不代表在途 SENDMSG 已结束。内核 poll/retry 时仍可能按 SCM_RIGHTS 中的 fd 数字查找文件,不能仅凭 promise 完成就释放内核使用的 fd。正常完成的 shutdown(SHUT_WR) 会阻止后续发送;但 shutdown 本身失败时,Netty 仍会失败并清空 outbound,因此不能以 shutdown 成功作为资源安全的前提。内核 SENDMSG 重试路径、SCM_RIGHTS 的 fd 查找。

在实际提交 sendfd 前通过 F_DUPFD_CLOEXEC 创建副本,由 Unsafe 单独持有,直到对应 SENDMSG CQE 到达后关闭;未成功提交则立即关闭。每个 Channel 同时只有一个在途写批次,因此一个字段即可管理,无需引用计数包装或替换 outbound 中的消息。排队阶段不创建副本,原始 fd 仍由调用方管理,并需保持有效直到对应写完成。该路径增加一次 dup 和对应的副本关闭,不影响普通 ByteBuf 发送;dup 失败走已有写错误处理,失败相关 promise 并关闭写端。

同时,UDS sendfd 的完成路径在 outbound 已清空时直接返回,避免 shutdownOutput 之后的迟到写错误触发 autoClose,意外关闭仍应保留的读端。

5. 使用 PendingZeroCopyWrites 管理 zero-copy notification 的引用

新增惰性创建的 PendingZeroCopyWrites,按 userData 保留引用直到对应 NOTIF,支持跨请求的乱序 notification。primary CQE 带 MORE 时收集引用;如果 shutdown 已提前 retain,则直接转交。PendingWrite 和引用数组可复用,ID 通过 freeIdStack 回收,耗尽时由 overflow map 承接。

6. 将 SENDMSG_ZC 的 MsgHdrMemory 改为 per-channel 缓存

移除 IoUringIoHandler 中为 SENDMSG_ZC 无条件预分配的 1024 个 MsgHdrMemory,改为 Channel 首次使用时分配并复用一个,减少未使用该路径时的堆内、堆外占用。

每个 TCP Channel 同时只有一个等待 primary CQE 的写批次,per-channel MsgHdrMemory 可保持当前批次的 iovLength。结合 WriteOpsSnapshot 即可恢复待 retain 的 ByteBuf,无需在提交热路径额外解析或保存 iov 信息。

Result

普通写热路径不再收集、复制和清空 tracker 的引用数组;保活逻辑集中在 outbound 释放前,由 PendingZeroCopyWrites 独立管理 zero-copy notification。当前测量中,四种 TCP 场景的吞吐中位数变化均在约 1% 内;普通写的 Channel 常驻堆占用减少,但没有测到普遍的每轮分配下降。

性能与分配

运行环境:Intel Core i5-13600KF,14 核 / 20 线程,系统可见内存约 62.6 GiB;Linux 实机 loopback,CPU affinity 为 8,10。Oracle GraalVM JDK 25.0.2,通过 -XX:-UseJVMCICompiler 使用 C2,固定 1 GiB 堆、G1。

Linux dreamlike-MS-7E01 7.3.0-6-generic #6-Ubuntu SMP PREEMPT_DYNAMIC Mon Sep 21 16:58:57 UTC 2026 x86_64 GNU/Linux

以下对比上游 4.2 基线 059591de569a253117d153f8b5e543788ad1f0f8 与本 PR 分支。

每版每场景运行 3 个独立 JVM,两版交替执行。预热 15 s,持续发送约 15 s 后由外部 SIGINT 触发断开。每轮发送 32 KiB,等待接收端 1 B ACK 后发送下一轮;writeSingle / SEND_ZC 使用一个 buffer,WRITEV / SENDMSG_ZC 使用 8 × 4 KiB。下表取中位数,变化按未舍入的中位数计算。

  • 吞吐:接收确认的 payload / 从开始计量到两端连接关闭的耗时,包含断开收尾。
  • 发送端每轮平均堆分配:client EventLoop 在测量窗口内的堆分配增量 / 完成轮次。每轮发送 32 KiB 并收到 ACK,统计包含发送、CQE 处理和 ACK 接收等该线程上的分配,排除预热和关闭收尾;不包含接收端线程及堆外内存。这不是单次 write 调用或单个 SQE 的独立分配量。
  • 主测不启用 JFR;另开诊断 JVM,在预热后同时启动 hot/all 两份录制,分别于 SIGINT 前和连接关闭后停止,用于分配归因。
场景 基线吞吐 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 常驻堆占用

下表为默认配置、未注册 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.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@allthingssecurity
LocalChannel: complete connect() when the accepted channel dies befor…
6155c4b
…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.
@dreamlike-ocean dreamlike-ocean changed the title Trace write ops IoUring:重构写操作的生命周期管理 Sep 29, 2026
allthingssecurity added 2 commits September 29, 2026 11:55
@allthingssecurity
Don't leak FixedChannelPool slots on unrelated IllegalArgumentExcepti…
430fdff
…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.
@allthingssecurity
Don't leak queued writes in ChunkedWriteHandler on removal or cancel (n…
9d19e3c
…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.
@QRWells

QRWells commented Sep 30, 2026

Copy link
Copy Markdown

Automated review findings (/code-review) plus performance notes from reading the code. None of this has been manually verified or benchmarked yet. Line numbers refer to 4b60770.

Correctness: introduced by this PR

  1. AbstractIoUringChannel.java:1083: If flush() is called while a TCP Fast Open connect is in progress, flush0 sees !isActive() and calls failFlushed(NotYetConnectedException, true). That fails the in-flight TFO initial data along with every other flushed message. When the SENDMSG|MSG_FASTOPEN CQE later returns res > 0, completeFastOpenWrite skips removeBytes and reports the connect as successful. The peer may have received some or all of the data the application was told failed, and later writes follow it on the same stream, which corrupts framing. The code comment ("an inactive flush may already have failed this batch") treats this as intended.

  2. IoUringDomainSocketChannel.java:141: Native.duplicateFd throws ChannelException, not IOException. When fcntl(F_DUPFD_CLOEXEC) fails (EMFILE, or EBADF if the user already closed the descriptor), handleWriteError shuts down output instead of closing the channel, even with autoClose=true. The channel is left half-closed and the promise fails with ChannelOutputShutdownException. The catch (Throwable) also routes Errors down the write-error path.

  3. ChannelOutboundBuffer.java:689: failFlushed calls prepareToDiscardOutboundMessages without a guard. The io_uring retainWriteBuffers implementations cast messages to ByteBuf and wrap forEachFlushedMessage exceptions in IllegalStateException. If either throws during close or shutdownOutput(), the exception escapes from AbstractUnsafe.close / closeOutboundBufferForShutdown. Flushed promises are never notified, the buffer.close() that follows in the callers is skipped (unflushed messages leak), and channelInactive / ChannelOutputShutdownEvent may not fire.

  4. AbstractIoUringStreamChannel.java:748: Stream and zero-copy completions detect a discarded batch via outboundBuffer() == null, while the datagram path checks retainedWriteBuffers != null. A discard that leaves the outbound buffer attached therefore still consumes the queue. If failFlushed runs through the inactive-flush path while a stream write is in flight, writeComplete0 / handleWriteCompleteZeroCopy (IoUringSocketChannel.java:261) calls removeBytes(res) on messages queued after the failed batch, which drops those bytes and succeeds promises for data that was never written. Today only TFO reaches this path, and it is special-cased.

  5. IoUringDatagramChannel.java:559: The outboundBuffer == null guard was replaced by retainedWriteBuffers != null. A final batch completion with a null outbound buffer and no retained list (any path that nulls outboundBuffer without going through failFlushed while WRITE_SCHEDULED is set) reaches removeFromOutboundBuffer(null, ...). That throws NullPointerException in the completion handler, and numOutstandingWrites / WRITE_SCHEDULED are never reset.

  6. AbstractIoUringChannel.java:569: unregistered() replaced writeTracker.releaseAll() with assert retainedWriteBuffers == null, and nothing drains PendingZeroCopyWrites. With assertions disabled, if the registration is removed while retainedWriteBuffers is non-null or zero-copy writes still hold references, those buffers leak silently. The previous code released them explicitly.

Correctness: pre-existing, in code this PR touched

  1. IoUringSocketChannel.java:145: iovArray.maxCount(MAX_SKB_FRAGS) is applied to the event loop's shared IovArray, but IovArray.add only stops when count == maxCount, and count already includes other channels' entries (offset). With offset < 17 this SENDMSG_ZC gets only 17 - offset iovs. With offset == 17 it gets 0 (an empty sendmsg_zc). With offset > 17 there is no cap, so more than MAX_SKB_FRAGS iovs are submitted. The limit also stays set until the next clear(), so other channels that write later in the same pass are capped too and can get 0 iovs.

  2. AbstractIoUringChannel.java:1084: On a successful TFO, write listeners run inside removeBytes() before connectComplete sets active = true, and flushed data that TFO did not send is not rescheduled. A listener that calls writeAndFlush sees !isActive() and gets NotYetConnectedException, which also fails the rest of the flushed queue. Without such a listener, the remaining flushed bytes stay in the outbound buffer until the next flush.

  3. IoUringDomainSocketChannel.java:188: Errors.ioResult returns 0 for EAGAIN/EWOULDBLOCK, and the SENDMSG completion treats >= 0 as success. A sendfd SENDMSG that completes with -EAGAIN removes the FileDescriptor message and succeeds its promise although nothing was sent, so the peer never receives the fd.

Test coverage

  1. The channel-level tracker tests (shutdown retention, deregistration release) were deleted, and the new tests cover only PendingZeroCopyWrites and IovBufferCollector. These paths have no tests: the prepareToDiscardOutboundMessages hook in ChannelOutboundBuffer.failFlushed, TFO write counting and retention, per-index datagram release, domain-socket fd duplication, and the delayedClose POLLOUT guard.

Design

  1. Channel.java:468: This adds a public Channel.Unsafe method and a call in core ChannelOutboundBuffer that only io_uring uses. The hook rebuilds the iov-to-buffer mapping from the outbound queue at discard time, which is correct only if readable ranges have not changed since submission. That rule is documented only on IovBufferCollector, and every future discard path has to remember to call the hook.

  2. PendingZeroCopyWrites.java:122: PendingWrite.retain / processMessage duplicate IovBufferCollector.collect / processMessage: the same single-message and single-iov shortcut, the same traversal and the same remainingIovs counting. Both must stay in sync with IovArray.add. If they drift apart, zero-copy notification retention and discard retention disagree, which risks a use-after-free or a leak.

  3. IoUringSocketChannel.java:244: retainedWriteBuffers acts as a three-state flag (null / emptyList() / list), and takeSendZCBuffers overwrites it with emptyList() to signal that ownership moved. Correctness depends on subtle ordering: writeCompleteAndReleaseBuffers re-reads the field after writeComplete0, the field is reset at numOutstandingWrites == 0, and the datagram path calls set(index, null) on a mutable list. The datagram writeComplete0 also reads outboundBuffer() before the retained check, which is wasted work on that branch.

Performance

  1. IoUringSocketChannel.java:186: On kernels with SENDMSG_ZC support, filterWriteMultiple allocates a new wrapper MessageProcessor for every writev (unless escape analysis removes it) and calls shouldWriteZeroCopy for every message, which reads the volatile writeZeroCopyThreshold. This also happens when zero-copy is disabled (the default, -1), where the wrapper never changes the result. This is the default write path for io_uring TCP sockets. (Pre-existing; this PR changed the method's signature.)

  2. IoUringSocketChannel.java:231: Multi-buffer zero-copy writes walk the flushed messages twice: once in IovArray.add at submission, and again at the primary CQE in takeSendZCBuffers → PendingWrite.retain (PendingZeroCopyWrites.java:122) → remainingIovs (AbstractIoUringStreamChannel.java:298) to map iovs back to messages. For composite buffers, both walks call nioBuffers(...), so each such write allocates the NIO buffer arrays twice. This only applies when zero-copy is enabled.

  3. AbstractIoUringChannel.java:296: Each IoUringSocketChannel that uses SENDMSG_ZC now allocates its own direct MsgHdrMemoryArray(1) and keeps it until unregistration. That is a few hundred bytes of direct memory for the msghdr, sockaddr_storage, iovec and cmsg space, plus slice objects and a cmsghdrData JNI call. Previously one 1024-entry array was shared per event loop. TFO frees the array and the next zero-copy write reallocates it. The header only has to outlive submission so that iovLength() can be read at completion; the base branch already relied on the kernel copying the msghdr at submission.

  4. IoUringDomainSocketChannel.java:141: Every FileDescriptor write now costs an extra fcntl(F_DUPFD_CLOEXEC) and close(), and holds a second fd while the send is in flight. Workloads that pass many fds therefore reach EMFILE sooner, which then triggers item 2.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

allthingssecurity and others added 25 commits September 30, 2026 15:22
@allthingssecurity
Honour the needle's reader index in ByteBufUtil.indexOf(ByteBuf, Byte…
e66ce34
…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.
@allthingssecurity
Close idle outbound HTTP/2 child channels when the parent closes (net…
4198bde
…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.
@allthingssecurity
Only fail in ZlibDecoder when the decompression buffer is full (netty…
e6fc471
…#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.
@allthingssecurity @normanmaurer
Fail pending writes of ProxyHandler when it is removed (netty#17691)
44586c5
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]>
@normanmaurer
Use LocalIoHandler instead of DefaultEventLoop for LocalChannel tests…
d3817ad
… 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.
@normanmaurer
Arm force-close timeout when an inbound CLOSE frame is echoed (netty#…
1330f40
…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
@allthingssecurity @claude @normanmaurer
Don't count STOMP headers again when the header block is replayed (ne…
f364155
…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]>
@normanmaurer
Add script that allows to check if a user has signed the icla (netty#…
363d248
…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
@allthingssecurity
Complete HTTP/2 graceful close when the connection closes the last st…
9c77622
…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.
@eager-signal @normanmaurer
Handle ed25519 and ed448 names in SignatureAlgorithmConverter (netty#…
9afb126
…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]>
@normanmaurer
MqttDecoder accepts malformed MQTT 5 property sections and reclassifi…
e7e943d
…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
@Asthenia0412
common: initialize SystemTicker at runtime in native images (netty#17677
658b570
)

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]>
@allthingssecurity @normanmaurer
Don't corrupt ChannelOutboundBuffer when a cancelled write makes the …
594e01c
…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]>
@allthingssecurity
Fail ChunkedNioFile instead of spinning when the file is shorter than…
cfed06a
… 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.
@normanmaurer
Validate bzip2 Huffman table selector index before use (netty#17705)
439c831
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`.
@allthingssecurity
Reset the permessage-deflate compressor after an empty final fragment (…
70f3035
…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.
@normanmaurer
Only build and test the affected modules when validating PRs (netty#1…
6e1f5f1
…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.
@normanmaurer
Fix racy DnsNameResolverTest.testNegativeTtl lifecycle observer checks (
006a2f1
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.
@lhotari
Fix retainedSlice() of non-retained pooled derived buffers (netty#17759)
d84dc6b
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.
@chrisvest
Build using powershell on Windows (netty#17766)
2e28f31
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.
@normanmaurer
Fix quadratic scanning in DelimiterBasedFrameDecoder for non-line del…
85498e0
…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.
@normanmaurer
SpdyHttpDecoder: bound cumulative HEADERS frame size per stream
57b80fc
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.
@normanmaurer
Decoded nested HAProxy SSL TLVs re-encode with an inconsistent PROXY …
9b41ea7
…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
@violetagg @normanmaurer
Release QPACK blocked stream slot when a blocked stream is abandoned
da4c183
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.
@chrisvest @normanmaurer
HTTP1: Stricter multipart per-part Content-Type validation
faec63c
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`.
Marti2203 and others added 3 commits October 21, 2026 20:27
@Marti2203
Fix the region copied by Unpooled.copiedBuffer(CharSequence, int, int…
19e950b
…, 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`.
@normanmaurer @Marti2203
Port 4.1: Don't invert IP_MULTICAST_LOOP_DISABLED in NioDatagramChann… (
192d06e
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]>
@yawkat @claude @normanmaurer
Treat DATA frames on reserved HTTP/2 streams as a connection error (n…
1bf1ac3
…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]>
@dreamlike-ocean
dreamlike-ocean force-pushed the trace_write_ops branch from 0334122 to 249fccb Compare October 22, 2026 08:48
AbhishekShukla1289 and others added 23 commits October 22, 2026 11:37
@AbhishekShukla1289 @netty-project-bot
@normanmaurer @bryce-anderson
Http2: reject generic frames whose payload exceeds SETTINGS_MAX_FRAME…
dc5655e
…_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]>
@Marti2203
Don't loop forever in AbstractDiskHttpData when the file is short (ne…
66dc5e6
…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.
@Marti2203 @normanmaurer
Check the second gzip magic byte in JdkZlibDecoder (netty#17972)
f69f14a
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]>
@Marti2203 @normanmaurer
Reject reply codes with non-digit characters in SmtpResponseDecoder (n…
3073066
…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]>
@CCCLL @normanmaurer
Return null or the default from read-only headers for invalid values (n…
5f89d65
…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]>
@normanmaurer
MqttEncoder: Reject Variable Byte Integers larger than 268435455 (net…
bd41b40
…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.
@normanmaurer
Fix server-initiated WebSocket close handshake failing with "promise …
7a6f630
…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.
@Marti2203
Fix Snappy.encode(...) for input with a non-zero reader index (netty#…
e0f2db4
…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.
@Marti2203
Fill every remaining byte in the Java 8 SplittableRandom.nextBytes fa…
14d1d84
…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.
@normanmaurer
Cancel queued runs and runs of fork PRs when a PR is merged (netty#18026
12c5eb7
)

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.
@normanmaurer
Complete the TCP fast open connect before notifying the initial write (…
7999377
…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.
@normanmaurer
Only delete socket files when binding and closing UDS channels (netty…
6ee2740
…#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.
@dreamlike-ocean
io_uring: simplify write tracking
01deb17
@dreamlike-ocean
fix revapi
59bb6bc
@dreamlike-ocean
record WriteOpsSnapshot to reduce allocation
2df6164
@dreamlike-ocean
refactor PendingZeroCopyWrites to reduce allocation
0ee96be
@dreamlike-ocean
optimize code
4e771a3
@dreamlike-ocean
clean up
2e002a8
@dreamlike-ocean
Reduce WriteOpsSnapshot to fields needed for resource recovery
6625587
@dreamlike-ocean
Move outbound discard hook to Channel.Unsafe
a287d57
@dreamlike-ocean
add ut
36fd8d7
@dreamlike-ocean
Defer io_uring sendfd duplication until submission
6e8abea
@dreamlike-ocean
fix io_uring write tracking after rebasing onto 4.2
e05943b
@dreamlike-ocean
dreamlike-ocean force-pushed the trace_write_ops branch from 249fccb to e05943b Compare October 23, 2026 07:16
dreamlike-ocean added 2 commits October 23, 2026 18:39
@dreamlike-ocean
keep io_uring discard handling out of core
e7fbbbc
@dreamlike-ocean
Report io_uring sendfd dup failures as IOException
187e8db
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

No reviews

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

20 participants

@dreamlike-ocean @QRWells @allthingssecurity @normanmaurer @eager-signal @Asthenia0412 @lhotari @chrisvest @violetagg @ejona86 @netty-project-bot @akilegaspi @yawkat @bryce-anderson @gavinbunney @vpelikh @watson-ryan @arnabnandy7 @Raghuvardhan-Reddy78 @manish-9245
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.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.